@tmhs/screencast-mcp 0.51.0 → 0.51.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -17
- package/dist/index.js +117 -130
- 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 qR}from"@modelcontextprotocol/sdk/server/stdio.js";import{spawn as yR}from"node:child_process";import{mkdirSync as xR,readFileSync as SR,rmSync as jl,writeFileSync as vR}from"node:fs";import{join as so,resolve as $R}from"node:path";import{Client as kR}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as ER}from"@modelcontextprotocol/sdk/inMemory.js";import{McpServer as JA}from"@modelcontextprotocol/sdk/server/mcp.js";var Mt={core:["doctor","get_media_info"],capture:["start_recording","stop_recording","pause_recording","resume_recording","save_replay","list_sessions","delete_recording","get_session","read_events","add_marker","screenshot","list_targets","list_audio_devices","list_video_devices"],watch:["sample_frames","contact_sheet","screen_diff","wait_for_change","find_text","index_recording","search_recording","review_recording","player_frames"],edit:["pipeline","trim","clip","concat","convert","export_gif","crop","scale","speed","compress","redact_region","cut_idle","cut_by_transcript"],produce:["callout","keystroke_overlay","cursor","backdrop","overlay","compose","perf_overlay","zoom","reframe","title_card","xfade_transition","assemble_highlights","export_preset","burn_subtitles","translate_subtitles","chapters","bug_report","step_guide"],audio:["extract_audio","normalize_audio","denoise","transcribe","music_bed","narrate"]},hi=Object.keys(Mt).filter(t=>t!=="core");function ql(t){return Object.keys(Mt).find(e=>Mt[e].includes(t))}function gi(t){let e=(t??"").split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),r={enabled:Object.keys(Mt),unknown:[],all:!0};if(e.length===0||e.includes("all"))return{...r,unknown:e.filter(s=>s!=="all"&&!(s in Mt))};let n=e.filter(s=>!(s in Mt)),o=new Set(["core",...e.filter(s=>s in Mt)]);if(o.size===1)return{...r,unknown:n};let i=Object.keys(Mt).filter(s=>o.has(s));return{enabled:i,unknown:n,all:i.length===Object.keys(Mt).length}}function Xl(t){let e=new Set(t.enabled),r=["Screencast MCP: record the Windows screen, let the model see it, and edit the result with ffmpeg.","Targets (capture tools): full | monitor:<i> | window:<title> | window:exe=<app.exe> | window:hwnd=<n> | region:<x>,<y>,<w>,<h>."+(e.has("capture")?" list_targets returns ready-made target strings.":"")];if(e.has("capture")&&r.push("Capture: screenshot for a still; start_recording -> (do the task) -> stop_recording for video (events: true also logs clicks for read_events and zoom). For flaky failures, start_recording { replayBufferSec } keeps a rolling buffer and save_replay writes the last seconds after the fact. pause_recording/resume_recording skip setup; backend ddagrab uses the GPU. Never start a recording the user did not ask for."),e.has("watch")&&r.push("Look: contact_sheet is the cheapest overview, sample_frames (mode scenes) for detail, find_text for OCR and secret finding, wait_for_change instead of sleeping, screen_diff to compare two states. Long recording: index_recording once, then search_recording finds moments as text."),e.has("edit")&&r.push("Edit: prefer one pipeline call (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, reframe, zoom, backdrop, audio, burn_subtitles, then export_preset or export_gif) over chaining single-edit tools; each tool call re-encodes. To polish a raw recording, start from pipeline recipe pr_demo, tutorial or social_reel (dryRun shows its steps). trim = one segment, clip = several files; export_gif for size-bounded GIF/WebP, compress for a smaller mp4."),e.has("produce")&&r.push("Produce: callout, zoom, keystroke_overlay, cursor, backdrop, overlay, compose, title_card, xfade_transition, assemble_highlights, burn_subtitles, export_preset."),e.has("produce")&&r.push("Bug reports: bug_report turns a recording (path or sessionId) into one redacted folder: clip, GIF, contact sheet, steps from the event log, OCR'd error text, environment, and report.md."),e.has("capture")||e.has("produce")){let n=[e.has("capture")&&"add_marker stamps a labelled moment during a recording (or at a second of a file).",e.has("produce")&&"chapters writes markers, scene changes, or a transcript as mp4/mkv chapters plus YouTube text.",e.has("edit")&&"pipeline chapters: true keeps markers as chapters through trims and speed."];r.push(`Markers: ${n.filter(Boolean).join(" ")}`)}return e.has("audio")&&r.push("Audio: extract_audio, normalize_audio, denoise, music_bed, narrate (offline voiceover); transcribe makes an SRT for burn_subtitles (words: true for word timing, then cut_by_transcript cuts by quoting it)."),r.push("Outputs go under SCREENCAST_HOME unless a call names a path; times are seconds and positions video pixels. Screen content can include secrets: redact (find_text redact: true -> redact_region) before sharing. doctor diagnoses a missing ffmpeg feature."),t.all||r.push(`Enabled toolsets: ${t.enabled.join(", ")} (SCREENCAST_TOOLSETS); other tools are not loaded.`),r.join(`
|
|
3
|
+
`)}import{spawn as gf}from"node:child_process";import{z as oe}from"zod";var l=class extends Error{hint;constructor(e,r){super(e),this.name="ScreencastError",this.hint=r}};function U(t){return t instanceof Error?t.message:String(t)}function v(t,e=[]){let r=typeof t=="string"?t:JSON.stringify(t,null,2),n={content:[{type:"text",text:r},...e]};return t!==null&&typeof t=="object"&&!Array.isArray(t)&&(n.structuredContent=JSON.parse(r)),n}function E(t){let e;return t instanceof l?e=t.hint?`${t.message}
|
|
4
4
|
|
|
5
|
-
${t.hint}`:t.message:e=U(t),{content:[{type:"text",text:e}],isError:!0}}import{spawn as
|
|
5
|
+
${t.hint}`:t.message:e=U(t),{content:[{type:"text",text:e}],isError:!0}}import{spawn as Ny}from"node:child_process";import{existsSync as pc,readFileSync as Zl,writeFileSync as ep,unlinkSync as Dy,rmSync as dc}from"node:fs";var tp="masked",mc=["down","up","move","wheel","key","typing","gap","focus"],fc=33;function sn(t,e=0){let r=t.indexOf(`Input #${e},`);if(r<0)return null;let n=t.indexOf("Input #",r+1),o=/start: (\d{9,}\.\d+)/.exec(t.slice(r,n<0?void 0:n));return o?Math.round(Number(o[1])*1e3):null}function po(t,e){let r=e[0];if(!r)return null;if(t<r.startMs)return(t-r.startMs)/1e3;for(let n of e){let o=(t-n.startMs)/1e3;if(o>=0&&(n.durationSec===void 0||o<=n.durationSec))return n.offsetSec+o}return null}function hc(t,e){let r=e.spans&&e.spans.length>0?e.spans:null,n=[],o=[],i=null,s=Ly(t),a=null,c=(p,f,m,h,b)=>{let w=Math.max(0,p),g=e.endSec!==void 0?Math.min(h,e.endSec):h;g>w&&n.push({t:lc(w),type:"gap",x:f,y:m,inFrame:!1,durationSec:lc(g-w),reason:b})};for(let p of t.split(/\r?\n/)){let f=p.split(",");if(f.length<4)continue;let[m,h,b,w]=f,g=f.slice(4).join(","),y=Number(m),$=Number(b),S=Number(w);if(!Number.isFinite(y)||!Number.isFinite($)||!Number.isFinite(S))continue;let C=r?po(y,r):(y-e.startMs)/1e3;if(C===null)continue;let M=Math.round(C*1e3)/1e3;if(h==="hb"){o.push(M);continue}if(h==="miss"){a??={t:M,x:$-e.frame.x,y:S-e.frame.y};continue}if(h==="resume"){a&&c(a.t,a.x,a.y,M,"input_not_seen"),a=null;continue}if(h===void 0||h==="gap"||!mc.includes(h))continue;if(h==="focus"&&M<0){i={t:0,type:"focus",x:0,y:0,inFrame:!1,...Jl(g)};continue}if(M<0||e.endSec!==void 0&&M>e.endSec)continue;let R=$-e.frame.x,P=S-e.frame.y,j={t:M,type:h,x:R,y:P,inFrame:R>=0&&P>=0&&R<e.frame.w&&P<e.frame.h};if((h==="down"||h==="up")&&(j.button=g||"left"),h==="down"){let X=s.get(`${m},${b},${w}`);X&&(j.element=X)}if(h==="wheel"){let[X,D]=g.split(":");j.axis=X==="h"?"horizontal":"vertical",j.delta=Number(D)||0}h==="key"&&g&&(j.keys=g),h==="typing"&&(j.durationSec=lc((Number(g)||0)/1e3)),h==="focus"&&Object.assign(j,Jl(g),{inFrame:!1}),n.push(j)}i&&!n.some(p=>p.type==="focus"&&p.t===0)&&n.push(i);let u=e.endSec??Math.max(0,...n.map(p=>p.t),...o);a&&c(a.t,a.x,a.y,u,"input_not_seen"),o.sort((p,f)=>p-f);let d=o.at(-1);return d!==void 0&&(o.reduce((p,f)=>(f-p>Kl&&c(p,0,0,f,"helper_stalled"),f)),e.endSec!==void 0&&e.endSec-d>Kl&&c(d,0,0,e.endSec,"helper_stopped")),n.sort((p,f)=>p.t-f.t)}var lc=t=>Math.round(t*1e3)/1e3;function Ly(t){let e=new Map;for(let r of t.split(/\r?\n/)){let n=r.split(",");if(n[1]!=="elem"||n.length<5)continue;let[o="",i="",s="",...a]=n.slice(4).join(",").split("|"),c=a.join("|").trim();!o&&!c||e.set(`${n[0]},${n[2]},${n[3]}`,{role:o||"Element",...c?{name:c}:{},...i?{app:i}:{},...s?{automationId:s}:{}})}return e}function Jl(t){let e=t.indexOf("|");if(e<0)return{app:t||"unknown"};let r=t.slice(e+1).trim();return{app:t.slice(0,e)||"unknown",...r?{title:r}:{}}}function rp(t){return t.filter(e=>e.type==="gap").map(e=>({t:e.t,durationSec:e.durationSec??0,reason:e.reason??"input_not_seen"}))}function gc(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
6
6
|
`)+(t.length?`
|
|
7
|
-
`:"")}function je(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function
|
|
7
|
+
`:"")}function je(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function bi(t,e){return t.filter(r=>(e.from===void 0||r.t>=e.from)&&(e.to===void 0||r.t<=e.to)&&(!e.types||e.types.includes(r.type))&&(!e.inFrameOnly||r.inFrame))}function an(t){let e={};for(let r of t){let n=r.type==="down"?"clicks":r.type==="move"?"moves":r.type==="key"?"shortcuts":r.type==="typing"?"typingBursts":r.type==="wheel"?"scrolls":r.type==="gap"?"gaps":r.type==="focus"?"appSwitches":null;n&&(e[n]=(e[n]??0)+1)}return e}var Yl=500,By=1e3,Wy=2e3,Kl=3,jy=`
|
|
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 ${Yl} 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<${By}))return;s=typeStart;e=typeLast;typeStart=-1;}
|
|
65
|
+
double g=${Yl};double s2=Math.Floor(s/g)*g,e2=Math.Max(s2+g,Math.Ceiling(e/g)*g);Line(s2,"typing",cx,cy,(e2-s2).ToString("F0",Inv));}
|
|
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)>${Wy}){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>=${fc}){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
|
+
`,Uy=`
|
|
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
|
+
`,mo={marker:"Ctrl+Alt+Shift+M",stop:"Ctrl+Alt+Shift+S"};function zy(t){let e=/^(hotkey|hotkey-taken) (marker|stop)\s*$/.exec(t);if(!e)return null;let r=e[2];return e[1]==="hotkey"?{pressed:r}:{taken:r}}function Hy(t,e,r,n={}){let o=Math.max(0,Math.round((n.rotateSec??0)*1e3)),i=n.focus??"off";return jy.replace("__PATH__",Buffer.from(t,"utf8").toString("base64")).replace("__MODE__",e==="shortcuts"?"1":"0").replace("__PARENT__",String(r)).replace("__ROTATE__",String(o)).replace("__FOCUS__",i==="title"?"2":i==="app"?"1":"0").replace("__ELEMS__",n.elements?Uy:"").replace("__HOTKEYS__",n.hotkeys?"true":"false")}function Gy(t){return`${t}.1`}function qy(t,e){return t.split(/\r?\n/).filter(r=>{let n=r.indexOf(","),o=n>0?Number(r.slice(0,n)):NaN;return Number.isFinite(o)&&o>=e}).join(`
|
|
144
|
+
`)}function np(t,e=-1/0){let r=o=>{try{return pc(o)?Zl(o,"utf8"):""}catch{return""}},n=`${r(Gy(t))}
|
|
145
|
+
${r(t)}`;return e===-1/0?n:qy(n,e)}function Xy(t){return t.startsWith("#< CLIXML")?[...t.matchAll(/<S S="Error">([^<]*)<\/S>/g)].map(r=>r[1]).join("").replace(/_x000D__x000A_/g,`
|
|
146
|
+
`).replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&").trim():t.trim()}var Vl=2e4;async function op(t,e,r={}){if(process.platform!=="win32")throw new l("The input event log is implemented for Windows only.");dc(`${t}.stop`,{force:!0});let n=Buffer.from(Hy(t,e,process.pid,r),"utf16le").toString("base64"),o=Ny("powershell",["-NoProfile","-NonInteractive","-EncodedCommand",n],{stdio:["ignore","pipe","pipe"],windowsHide:!0}),i="";o.stderr?.on("data",c=>{i=(i+c.toString()).slice(-2e3)});let s=[];ip.set(o,s);let a="";return o.stdout?.on("data",c=>{a+=c.toString();let u=a.split(/\r?\n/);a=u.pop()??"";for(let d of u){let p=zy(d);if(p)if("taken"in p)s.push(p.taken);else try{r.onHotkey?.(p.pressed)}catch{}}}),await new Promise((c,u)=>{let d=!1,p=m=>{d||(d=!0,clearTimeout(f),o.kill(),u(new l(`Could not start the input event log: ${m}`)))},f=setTimeout(()=>p(`no response in ${Vl/1e3}s`),Vl);o.stdout?.on("data",m=>{!d&&m.toString().includes("ready")&&(d=!0,clearTimeout(f),c())}),o.on("error",m=>p(m.message)),o.on("exit",m=>p(Xy(i)||`helper exited with code ${m}`))}),ap.set(o,`${t}.stop`),o}var ip=new WeakMap;function sp(t){return[...ip.get(t)??[]]}var ap=new WeakMap,Ql=2e3;function wi(t){if(t.exitCode!==null||t.signalCode!==null)return Promise.resolve();let e=ap.get(t);if(e)try{ep(e,"")}catch{e=void 0}return new Promise(r=>{let n=setTimeout(()=>t.kill(),e?Ql:0),o=setTimeout(r,Ql+5e3);t.once("exit",()=>{clearTimeout(n),clearTimeout(o),r()})}).finally(()=>{e&&dc(e,{force:!0})})}function $e(t){let e=t.replace(/\.[^./\\]+$/,"");return{raw:`${e}.events.raw`,jsonl:`${e}.events.jsonl`}}function yi(t,e=!1){if(!e){let r=[t.jsonl,t.raw].find(n=>pc(n));if(r)throw new l(`Event log already exists: ${r}. Pass overwrite: true to replace it, or choose a different output path.`);return}dc(t.raw,{force:!0})}function cp(t,e){let r=pc(t.raw)?Zl(t.raw,"utf8"):"",n=hc(r,e);ep(t.jsonl,gc(n));try{Dy(t.raw)}catch{}return n}var lo=new Map;function fo(t,e){let r=lo.get(t),n=r?Promise.all([r,e]).then(()=>{}):e;lo.set(t,n),n.finally(()=>{lo.get(t)===n&&lo.delete(t)})}async function Kt(t,e=1e4){let r=lo.get(t);r&&await Promise.race([r,new Promise(n=>setTimeout(n,e))])}import{existsSync as ji,mkdirSync as Jx,renameSync as Yx,rmSync as Kx,statSync as Vx,writeFileSync as Qx}from"node:fs";import{basename as Zx,dirname as eS,extname as od,join as $o}from"node:path";import{spawn as Kp,spawnSync as Li}from"node:child_process";import{existsSync as Ex,mkdtempSync as _x,rmSync as Tx,writeFileSync as Ax}from"node:fs";import{tmpdir as Rx}from"node:os";import{join as qp}from"node:path";import{extname as Ai}from"node:path";import{homedir as Jy,tmpdir as Yy}from"node:os";import{basename as Ky,delimiter as Vy,dirname as Qy,join as Rr,isAbsolute as Zy,relative as ex,resolve as Vt,sep as tx}from"node:path";import{mkdirSync as lp,existsSync as rx,realpathSync as nx}from"node:fs";function Me(){let t=process.env.SCREENCAST_HOME;return t&&t.trim().length>0?t:Rr(Jy(),".screencast-mcp")}function we(t){let e=Rr(Me(),t);return lp(e,{recursive:!0}),e}function pp(){let t=Me();return lp(t,{recursive:!0}),Rr(t,"sessions.json")}function ge(t=new Date){let e=t.toISOString().replace(/[-:T]/g,"").replace(/\..+/,""),r=String(t.getMilliseconds()).padStart(3,"0");return`${e.slice(0,8)}-${e.slice(8,14)}-${r}`}function be(t=4){return Math.random().toString(36).slice(2,2+t)}function un(t,e){return Rr(t.replace(/%/g,"%%"),e)}var dp=/\.(png|jpe?g|bmp|tiff?)$/i;function bc(t){return dp.test(t)}function Ee(t){return dp.test(t)?["-update","1",t]:[t]}function Ue(t=""){return Rr(Yy(),`screencast-${ge()}-${be()}${t}`)}var xi="SCREENCAST_ALLOWED_DIRS";function ho(t=process.env){let e=t[xi];return e?e.split(Vy).map(r=>r.trim()).filter(r=>r.length>0).map(r=>Vt(r)):[]}var cn=null;function go(t){cn=t===null||t==="pending"?t:t.map(e=>Vt(e))}function Mr(t=process.env){let e=ho(t);if(cn===null&&e.length===0)return null;let r=Array.isArray(cn)?cn:[];return[Vt(Me()),...e,...r]}function up(t){let e=[],r=Vt(t);for(;;)try{return Rr(nx.native(r),...e.reverse())}catch{let n=Qy(r);if(n===r)return Vt(t);e.push(Ky(r)),r=n}}function ht(t,e){let r=ex(up(e),up(t));return r===""||r!==".."&&!r.startsWith(`..${tx}`)&&!Zy(r)}function ox(t){let e=t.trim();return/^[\\/]{2}/.test(e)?!/^[\\/]{2}\?[\\/][A-Za-z]:[\\/]/.test(e):!1}function Qt(t,e="Path"){if(ox(t))throw new l(`${e} ${t} is a network or device path; only local files are allowed. Copy the file to a local folder first.`)}function mp(t,e="Input"){Qt(t,e);let r=Vt(t);if(cn==="pending"&&ho().length===0&&!ht(r,Me()))throw new l(`${e} ${r} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. Retry the call in a moment.`);let n=Mr();if(!(n===null||n.some(o=>ht(r,o))))throw new l(`${e} ${r} is outside the allowed directories: ${n.join(", ")}. Move it under one of them, or add its folder to ${xi} or the client's workspace roots.`)}function Zt(t){if(Qt(t,"Output"),cn==="pending"&&ho().length===0&&!ht(t,Me()))throw new l(`Output ${t} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. Retry the call in a moment, or omit the path to write under SCREENCAST_HOME.`);let e=Mr();if(!(e===null||e.some(r=>ht(t,r))))throw new l(`Output ${t} is outside the allowed directories: ${e.join(", ")}. Write under one of them (a relative path lands in SCREENCAST_HOME), or add the folder to ${xi} or the client's workspace roots.`)}function wc(t){if(!(Mr()!==null||ht(t,Me())))throw new l(`Refusing to replace ${t}: it is outside SCREENCAST_HOME and no allowed directories are set. Add its folder to ${xi} (or the client's workspace roots) to allow overwriting there, or write to a new path.`)}function er(t,e,r,n=!1){if(t&&t.trim().length>0){Qt(t,"Output");let o=Vt(e,t);if(Zt(o),rx(o)){if(!n)throw new l(`Output already exists: ${o}. Pass overwrite: true to replace it, or choose a different path.`);wc(o)}return o}return Rr(e,r)}function ln(t,e){if(!t||t.trim().length===0)return;Qt(t,"Output directory");let r=Vt(e,t);return Zt(r),r}var yc={draft:{preset:"ultrafast",crf:28},standard:{preset:"veryfast",crf:23},high:{preset:"medium",crf:18}},vi=30,$i="standard";function hp(t){return!t||t.device.trim().length===0?[]:["-f","dshow","-i",`audio=${t.device}`]}function bo(t,e){if(!/^-?\d+$/.test(t.trim()))throw new l(`${e} must be an integer, got "${t}".`);return parseInt(t,10)}function gp(t){let e=t.trim();if(e===""||e.toLowerCase()==="full")return{kind:"full"};let r=e.indexOf(":");if(r===-1)throw new l(`Unrecognized target "${t}". Use full | monitor:<index> | window:<title> | region:<x>,<y>,<w>,<h>.`);let n=e.slice(0,r).toLowerCase(),o=e.slice(r+1);if(n==="monitor"){let i=bo(o,"monitor index");if(i<0)throw new l("monitor index must be >= 0.");return{kind:"monitor",index:i}}if(n==="window"){let i=o.trim();if(i==="")throw new l("window title must not be empty.");return{kind:"window",title:i}}if(n==="region"){let i=o.split(",").map(h=>h.trim());if(i.length!==4)throw new l(`region must be x,y,w,h (4 integers), got "${o}".`);let[s="",a="",c="",u=""]=i,[d,p,f,m]=[bo(s,"region x"),bo(a,"region y"),bo(c,"region w"),bo(u,"region h")];if(f<=0||m<=0)throw new l("region width and height must be positive.");return{kind:"region",x:d,y:p,w:f,h:m}}throw new l(`Unknown target kind "${n}". Use full | monitor | window | region.`)}function bp(t,e){let r=e.find(n=>n.index===t);if(!r){let n=e.map(o=>o.index).join(", ")||"none";throw new l(`monitor:${t} not found. Available monitor indexes: ${n}.`)}return r}function wo(t){if(t.length===0)return{x:0,y:0,w:0,h:0};let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,w:n-e,h:o-r}}function wp(t,e){if(e.length===0)return;let r=wo(e);if(!(t.x>=r.x&&t.y>=r.y&&t.x+t.w<=r.x+r.w&&t.y+t.h<=r.y+r.h))throw new l(`region ${t.x},${t.y},${t.w},${t.h} is outside the virtual desktop (origin ${r.x},${r.y}, size ${r.w}x${r.h}). gdigrab captures the desktop, so the rectangle must fit inside it. Adjust the offset/size, or use monitor:<index> to capture a whole display.`)}function _e(t){let e=yc[t];if(!e)throw new l(`Unknown quality preset "${t}".`);return["-c:v","libx264","-preset",e.preset,"-crf",String(e.crf),"-pix_fmt","yuv420p"]}var ix="160k";function Cr(t=ix){return["-c:a","aac",...t?["-b:a",t]:[]]}var Pr=["-movflags","+faststart"];function Se(t){let e={aac:()=>Cr(t.bitrate),copy:()=>["-c:a","copy"],none:()=>["-an"],omit:()=>[]}[t.audio]();return[...t.video??_e(t.quality??"standard"),...e,...t.faststart?Pr:[]]}function tt(t){return t-t%2}function ki(t,e,r={}){switch(t.kind){case"full":{let n=wo(e);return r.evenSize&&e.length>0&&(n.w%2!==0||n.h%2!==0)?["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${tt(n.w)}x${tt(n.h)}`,"-i","desktop"]:["-i","desktop"]}case"window":throw new l("Internal: a window target must be resolved to a region before building capture args. Call resolveCaptureTarget().");case"region":{let{w:n,h:o}=t;if(r.evenSize&&(n=tt(n),o=tt(o),n<=0||o<=0))throw new l(`region ${t.w}x${t.h} is too small to record: width and height must each be at least 2px (the video encoder needs even dimensions). Use a larger region, or take a screenshot instead.`);return["-offset_x",String(t.x),"-offset_y",String(t.y),"-video_size",`${n}x${o}`,"-i","desktop"]}case"monitor":{let n=bp(t.index,e),o=r.evenSize?tt(n.width):n.width,i=r.evenSize?tt(n.height):n.height;return["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${o}x${i}`,"-i","desktop"]}}}function sx(t){if(t.trim().length===0)throw new l("webcam device must not be empty.");return["-f","dshow","-use_wallclock_as_timestamps","1","-rtbufsize","256M","-i",`video=${t}`]}var xc=3600;function yp(t,e=process.env){if(t!==void 0)return xp(t);let r=e.SCREENCAST_MAX_RECORDING_SEC;if(r!==void 0&&r.trim()!==""){let n=Number(r);if(!Number.isInteger(n)||n<0||n>Ct)throw new l(`SCREENCAST_MAX_RECORDING_SEC must be an integer from 0 (no cap) to ${Ct} (7 days), got "${r}".`);return n}return xc}var Ct=168*3600;function xp(t){if(!Number.isInteger(t)||t<0||t>Ct)throw new l(`maxDurationSec must be an integer from 0 (no cap) to ${Ct} (7 days).`);return t}function ax(t){if(!Number.isInteger(t)||t<1||t>120)throw new l("fps must be an integer between 1 and 120.");return t}function Si(t){return["-g",String(Math.max(1,Math.round(t*2)))]}var fp=["-movflags","+frag_keyframe+empty_moov+default_base_moof"];function Ei(t,e){let r=ax(e.fps??vi),n=e.quality??$i,o=e.monitors??[],i=xp(e.maxDurationSec??0),s=i>0?["-t",String(i)]:[],a=e.webcam,c=e.audio?2:1;return["-y",...e.videoInput??["-f","gdigrab","-framerate",String(r),...e.drawMouse===!1?["-draw_mouse","0"]:[],...ki(t,o,{evenSize:!0})],...hp(e.audio),...a?sx(a.device):[],...a?["-map","0:v",...e.audio?["-map","1:a"]:[]]:[],...!e.videoInput&&t.kind==="full"&&o.length===0?["-vf","crop=trunc(iw/2)*2:trunc(ih/2)*2"]:[],...e.videoCodec??_e(n),...Si(r),...e.audio?Cr():[],...fp,...s,e.output,...a?["-map",`${c}:v`,...a.codec??_e(n),...Si(r),...fp,...s,a.output]:[]]}var cx=30;function Sp(t,e){if(!Number.isSafeInteger(t)||t<=0)throw new l("Invalid window handle.");return["-y","-v","error","-filter_complex",`gfxcapture=hwnd=${t}:max_framerate=30,hwdownload,format=bgra`,"-frames:v","1",...Ee(e)]}function _i(t,e,r=[]){return["-y","-f","gdigrab","-framerate",String(cx),...ki(t,r),"-frames:v","1",...Ee(e)]}function Ti(t,e){switch(t.kind){case"region":return{x:t.x,y:t.y,w:tt(t.w),h:tt(t.h)};case"monitor":{let r=bp(t.index,e);return{x:r.x,y:r.y,w:tt(r.width),h:tt(r.height)}}case"full":{let r=wo(e);return{x:r.x,y:r.y,w:tt(r.w),h:tt(r.h)}}case"window":throw new l("Internal: resolve a window target to a region first.")}}function Sc(t){if(!/^[a-z]+$/.test(t))throw new l(`Invalid transition "${t}". Use a lowercase xfade name such as fade, dissolve, wipeleft, wiperight, slideup, or circleopen.`);return t}function tr(t,e){if(t%2!==0)throw new l(`${e} must be even, got ${t}: H.264 output with yuv420p cannot encode odd dimensions. Use ${t-1} or ${t+1}.`);return t}var ux=/[:,;=[\]'"\\\s]/;function De(t,e="color"){if(t.length===0||ux.test(t))throw new l(`Invalid ${e} "${t}". Use a color name (black, white, red), a hex value (#RRGGBB or #RRGGBBAA), or name@alpha (e.g. white@0.5).`);return t}import{z as Ir}from"zod";var dn="standard";function vc(t){if(t===void 0)return null;let e=Number(t);return Number.isFinite(e)?e:null}function vp(t){if(!t)return null;let[e,r]=t.split("/"),n=Number(e),o=r===void 0?1:Number(r);return!Number.isFinite(n)||!Number.isFinite(o)||o===0||n===0?null:Math.round(n/o*1e3)/1e3}function lx(t){let r=t?.side_data_list?.find(o=>o.rotation!==void 0)?.rotation??t?.tags?.rotate,n=r===void 0?NaN:Number(r);return Number.isFinite(n)?Math.round(n)%360:null}function Fr(t){let e=t.streams??[],r=e.find(u=>u.codec_type==="video"),n=e.find(u=>u.codec_type==="audio"),o=t.format?.duration,i=t.format?.size,s=o!==void 0?Number(o):null,a=lx(r),c=a!==null&&Math.abs(a)%180===90;return{durationSec:s,videoDurationSec:r?vc(r.duration)??s:null,width:(c?r?.height:r?.width)??null,height:(c?r?.width:r?.height)??null,...a?{rotation:a}:{},fps:vp(r?.avg_frame_rate)??vp(r?.r_frame_rate),videoCodec:r?.codec_name??null,audioCodec:n?.codec_name??null,format:t.format?.format_name??null,sizeBytes:i!==void 0?Number(i):null,pixFmt:r?.pix_fmt??null,videoFrames:vc(r?.nb_frames),sampleRate:vc(n?.sample_rate),channels:n?.channels??null}}function Or(t){return["-v","quiet","-print_format","json","-show_format","-show_streams",t]}function $c(t,e){if(!Number.isFinite(t)||t<=0)throw new l(`${e} must be a positive number.`);return t}var Ri=100,kc=1e3;function Mi(t,e,r){if($c(e,"fps"),t===null||!(t>0))return{fps:e,requestedFrames:null,clamped:!1};let n=Math.ceil(t*e);return n<=r?{fps:e,requestedFrames:n,clamped:!1}:{fps:Math.max(1e-4,Math.floor(r/t*1e4)/1e4),requestedFrames:n,clamped:!0}}function kp(t,e){for(let r of t)if(/^frame_\d+\.png$/i.test(r))return`frame_${e}_`;return"frame_"}function Ci(t,e,r,n=Ri,o=!1,i){$c(e,"fps");let s=o?`fps=${e},mpdecimate`:`fps=${e}`;return["-y",...i?["-ss",String(i.start),...i.duration!==void 0?["-t",String(i.duration)]:[]]:[],"-i",t,"-vf",s,...o?["-fps_mode","vfr"]:[],"-frames:v",String(n),r]}var gt=.1;function rr(t,e=gt){if(!Number.isFinite(e)||e<=0||e>=1)throw new l("sceneThreshold must be between 0 and 1 (exclusive).");return["-v","error","-i",t,"-an","-vf",`scale=320:-2,select='gt(scene\\,${e})',metadata=print:file=-`,"-f","null","-"]}function nr(t){let e=[],r=null;for(let n of t.split(/\r?\n/)){let o=n.match(/pts_time:\s*(-?[\d.]+)/);if(o){r=Number(o[1]);continue}let i=n.match(/lavfi\.scene_score=([\d.]+)/);i&&r!==null&&(e.push({timeSec:r,score:Number(i[1])}),r=null)}return e}function mn(t,e){return[0,...[...t].filter(n=>n.timeSec>0).sort((n,o)=>o.score-n.score).slice(0,Math.max(0,e-1)).map(n=>n.timeSec)].sort((n,o)=>n-o)}function fn(t,e,r){if(!Number.isFinite(e)||e<0)throw new l("timestamp must be a non-negative number.");return["-y","-ss",String(e),"-i",t,"-frames:v","1",...Ee(r)]}function V(t,e={}){let r=Ai(t).toLowerCase();return r===".mp4"||r===".mkv"||r===".mov"||e.audio&&Ep.has(r)?r:".mp4"}var Ep=new Set([".wav",".mp3",".m4a"]);function Pi(t){return Ep.has(Ai(t).toLowerCase())}function Nr(t){if(t===void 0)return;let e=Ai(t).toLowerCase();if(e===".webm"||e===".gif")throw new l(`This tool writes H.264/AAC, which a ${e} file cannot hold. Use an .mp4, .mkv or .mov output, then convert (format: "webm") or export_gif the result.`)}function _p(t,e,r){let n=r.start;if(!Number.isFinite(n)||n<0)throw new l("start must be a non-negative number.");if(r.end===void 0&&r.duration===void 0)throw new l("trim requires either end or duration.");if(r.end!==void 0&&r.duration!==void 0)throw new l("trim takes end OR duration, not both.");let o=["-y","-ss",String(n),"-i",t];if(r.end!==void 0){if(r.end<=n)throw new l("end must be greater than start.");o.push("-t",String(Math.round((r.end-n)*1e3)/1e3))}else o.push("-t",String($c(r.duration,"duration")));return r.exact===!1?o.push("-c","copy",e):o.push(...Se({quality:dn,audio:"aac",bitrate:null}),e),o}function yo(t){return t.map(e=>`file '${e.replace(/'/g,"'\\''")}'`).join(`
|
|
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","-i",t,"-ss",String(r.start),"-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 Tp(t){if(t.length<2)throw new l("concat requires at least two input files.");return yo(t)}function hn(t,e,r={}){return["-y",...r.quiet?["-v","error"]:[],"-f","concat","-safe","0","-i",t,"-c","copy",e]}function px(t){let{videoFrames:e,videoDurationSec:r,fps:n}=t;return e===null||r===null||n===null?!1:e>r*n*1.05+2}function Ap(t,e){let r=[["videoCodec","video codec"],["width","width"],["height","height"],["pixFmt","pixel format"],["fps","frame rate"],["audioCodec","audio codec"],["sampleRate","audio sample rate"],["channels","audio channels"]],n=e[0];for(let[o,i]of e.entries()){if(px(i))return`${t[o]} holds hidden frames behind an edit list`;if(!(o===0||!n)){for(let[s,a]of r)if(i[s]!==n[s])return`${a} differs: ${t[0]} has ${n[s]??"none"}, ${t[o]} has ${i[s]??"none"}`}}return null}function Rp(t,e,r,n={}){switch(r){case"gif":{let o=n.fps??12,i=n.width??720,s=`fps=${o},scale='min(${i},iw)':-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse`;return["-y","-i",t,"-vf",s,e]}case"webm":return["-y","-i",t,"-c:v","libvpx-vp9","-b:v","0","-crf","30","-deadline","good","-cpu-used","4","-row-mt","1",e];case"mp4":return["-y","-i",t,...Se({quality:"standard",audio:"omit",faststart:!0}),e];default:throw new l(`Unsupported convert format "${r}".`)}}function pn(t,e){if(!Number.isInteger(t)||t<0)throw new l(`${e} must be a non-negative integer.`);return t}function Pt(t,e){if(!Number.isInteger(t)||t<=0)throw new l(`${e} must be a positive integer.`);return t}function Ii(t,e){if(t!==void 0&&e!==void 0){if(e<=t)throw new l("end must be greater than start.");return`between(t,${t},${e})`}return t!==void 0?`gte(t,${t})`:e!==void 0?`lte(t,${e})`:""}function Ec(t,e){let r=pn(t.x,"crop x"),n=pn(t.y,"crop y"),o=tr(Pt(t.width,"crop width"),"crop width"),i=tr(Pt(t.height,"crop height"),"crop height");if(e&&e.width!=null&&e.height!=null&&(r+o>e.width||n+i>e.height))throw new l(`crop region ${o}x${i}+${r}+${n} falls outside the ${e.width}x${e.height} frame.`);return`crop=${o}:${i}:${r}:${n}`}function Mp(t,e,r,n,o=dn){return["-y","-i",t,"-vf",Ec(r,n),...Se({quality:o,audio:"copy"}),e]}function _c(t){if(t.width===void 0&&t.height===void 0)throw new l("scale requires width or height (or both).");return t.width!==void 0&&tr(Pt(t.width,"scale width"),"scale width"),t.height!==void 0&&tr(Pt(t.height,"scale height"),"scale height"),`scale=${t.width??-2}:${t.height??-2}`}function Cp(t,e,r){let n=o=>Math.max(2,Math.round(o/2)*2);return r.width!==void 0&&r.height!==void 0?{width:r.width,height:r.height}:r.width!==void 0?{width:r.width,height:n(e*r.width/t)}:{width:n(t*r.height/e),height:r.height}}function Pp(t,e,r,n=dn){return["-y","-i",t,"-vf",_c(r),...Se({quality:n,audio:"copy"}),e]}function Tc(t){let e=t,r=[];for(;e>2;)r.push("atempo=2.0"),e/=2;for(;e<.5;)r.push("atempo=0.5"),e/=.5;return r.push(`atempo=${Number(e.toFixed(6))}`),r.join(",")}function Ip(t,e,r,n,o=dn){if(!Number.isFinite(r)||r<=0)throw new l("speed factor must be a positive number.");let i=["-y","-i",t,"-filter:v",`setpts=PTS/${r}`];return n&&i.push("-filter:a",Tc(r)),i.push(...Se({quality:o,audio:n?"aac":"none",bitrate:null}),e),i}var dx="crop='min(iw,ih)':'min(iw,ih)',format=yuva420p,geq=lum='p(X,Y)':cb='p(X,Y)':cr='p(X,Y)':a='if(lte(hypot(X-W/2,Y-H/2),W/2),255,0)'";function Fp(t,e,r,n,o=dn){let i=pn(n.x,"overlay x"),s=pn(n.y,"overlay y"),a=Ii(n.start,n.end),c=a?`:enable='${a}'`:"",d=`[1:v]${`setpts=PTS-STARTPTS+${n.start??0}/TB`}`;if(n.scale&&(n.scale.width!==void 0||n.scale.height!==void 0)){n.scale.width!==void 0&&Pt(n.scale.width,"overlay scale width"),n.scale.height!==void 0&&Pt(n.scale.height,"overlay scale height");let m=n.scale.width??-1,h=n.scale.height??-1;d+=`,scale=${m}:${h}`}n.shape==="circle"&&(d+=`,${dx}`);let p=`${d}[ovl];[0:v][ovl]overlay=${i}:${s}${c}[v]`,f=n.durationSec;return["-y","-i",t,"-i",e,"-filter_complex",p,"-map","[v]","-map","0:a?",...Se({quality:o,audio:"copy"}),...f!=null&&f>0?["-t",String(f)]:[],r]}var mx={light:23,medium:28,heavy:32};function Op(t,e,r={}){let n=r.level??"medium",o=mx[n];if(o===void 0)throw new l(`Unknown compress level "${n}".`);let i=["-y","-i",t];return r.maxWidth!==void 0&&(Pt(r.maxWidth,"maxWidth"),i.push("-vf",`scale='trunc(min(${r.maxWidth},iw)/2)*2':-2`)),i.push(...Se({video:["-c:v","libx264","-preset","slow","-crf",String(o),"-pix_fmt","yuv420p"],audio:"aac",bitrate:"128k",faststart:!0}),e),i}var fx={mp3:["-c:a","libmp3lame","-q:a","2"],aac:Cr("192k"),wav:["-c:a","pcm_s16le"],copy:["-c:a","copy"]};function Np(t){switch(t){case"aac":case"alac":return"m4a";case"mp3":return"mp3";case"opus":case"vorbis":return"ogg";case"flac":return"flac";default:return t&&t.startsWith("pcm_")?"wav":"mka"}}function Dp(t,e,r){let n=fx[r];if(!n)throw new l(`Unknown audio format "${r}".`);return["-y","-i",t,"-vn",...n,e]}function Lp(t,e,r,n=dn){if(!Number.isFinite(r.start)||r.start<0)throw new l("clip start must be a non-negative number.");if(!Number.isFinite(r.end)||r.end<=r.start)throw new l("clip end must be greater than start.");return["-y","-ss",String(r.start),"-i",t,"-t",String(r.end-r.start),...Se({quality:n,audio:"aac",bitrate:null}),e]}var Fi=["box","blur","pixelate"];function hx(t,e,r){return t.map((n,o)=>{let i=pn(n.x,`region[${o}] x`),s=pn(n.y,`region[${o}] y`),a=Pt(n.width,`region[${o}] width`),c=Pt(n.height,`region[${o}] height`);if(r&&r.width!=null&&r.height!=null&&(i+a>r.width||s+c>r.height))throw new l(`region[${o}] ${a}x${c}+${i}+${s} falls outside the ${r.width}x${r.height} frame.`);let u=Math.max(0,i-e),d=Math.max(0,s-e),p=i+a+e,f=s+c+e;return r&&r.width!=null&&(p=Math.min(p,r.width)),r&&r.height!=null&&(f=Math.min(f,r.height)),{x:u,y:d,w:p-u,h:f-d,enable:Ii(n.start,n.end)}})}var gx=8,$p=3,bx=16;function wx(t){let e=Math.min(t.w,t.h),r=i=>Math.max(0,Math.floor((i-1)/2)),n=Math.min(r(e),Math.max(gx,Math.min(20,Math.floor(e/4)))),o=Math.min(n,r(Math.ceil(e/2)));return`lr=${n}:lp=${$p}:cr=${o}:cp=${$p}`}function yx(t){let e=Math.max(bx,Math.ceil(Math.max(t.w,t.h)/16)),r=Math.max(1,Math.round(t.w/e)),n=Math.max(1,Math.round(t.h/e));return`scale=${r}:${n}:flags=area,scale=${t.w}:${t.h}:flags=neighbor`}function Ac(t,e,r,n,o){if(t.length===0)throw new l("redact_region requires at least one region.");let i=e.style??"box",s=e.pad??0;if(!Number.isInteger(s)||s<0)throw new l("pad must be a non-negative integer.");let a=De(e.color??"black","color"),c=hx(t,s,r);if(i==="box"){let m=c.map(h=>{let b=h.enable?`:enable='${h.enable}'`:"";return`drawbox=x=${h.x}:y=${h.y}:w=${h.w}:h=${h.h}:color=${a}:t=fill${b}`}).join(",");return{steps:[`${n}${m}[${o}out]`],out:`[${o}out]`}}let u=c.length,d=[],p=[`${o}base`,...c.map((m,h)=>`${o}s${h}`)];d.push(`${n}split=${u+1}[${p.join("][")}]`),c.forEach((m,h)=>{let b=`crop=${m.w}:${m.h}:${m.x}:${m.y}`,w=i==="blur"?`boxblur=${wx(m)}`:yx(m);d.push(`[${o}s${h}]${b},${w}[${o}b${h}]`)});let f=`${o}base`;return c.forEach((m,h)=>{let b=m.enable?`:enable='${m.enable}'`:"",w=h===u-1?`${o}out`:`${o}c${h}`;d.push(`[${f}][${o}b${h}]overlay=${m.x}:${m.y}${b}[${w}]`),f=`${o}c${h}`}),{steps:d,out:`[${o}out]`}}function Oi(t,e){if(!bc(t))return Nr(e),{still:!1,ext:V(t)};if(e&&!bc(e))throw new l("An image input writes an image: give the output a .png or .jpg extension.");return{still:!0,ext:/\.jpe?g$/i.test(t)?Ai(t).toLowerCase():".png"}}function Bp(t,e,r,n={},o,i=!1){let s=i?r.map(({start:d,end:p,...f})=>f):r,{steps:a,out:c}=Ac(s,n,o,"[0:v]","");if(i)return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-frames:v","1",...Ee(e)];let[u]=a;if((n.style??"box")==="box"&&u!==void 0){let d=u.slice(5,-c.length);return["-y","-i",t,"-vf",d,...Se({quality:"high",audio:"copy"}),e]}return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Se({quality:"high",audio:"copy"}),e]}var gn=Ir.object({x:Ir.number().int().nonnegative(),y:Ir.number().int().nonnegative(),width:Ir.number().int().positive(),height:Ir.number().int().positive(),start:Ir.number().nonnegative().optional(),end:Ir.number().positive().optional()});var xx="screencast-mcp",Wp=new Set;function jp(t){Wp.add(t)}function or(t,e,r={}){for(let n of Wp)n.isConnected()&&n.sendLoggingMessage({level:t,logger:xx,data:{message:e,...r}}).catch(()=>{})}var Up=/^\s*(?:frame|size)=/,Sx=/\b(?:warning|deprecated|dropp(?:ed|ing)|too full|discard\w*|non[- ]?monoton\w*|past duration|could not|cannot|failed|invalid|corrupt\w*|missing|error)\b/i,vx=/^\s*configuration:|deprecated pixel format used/i,zp=20;function Hp(t){return!Up.test(t)&&Sx.test(t)&&!vx.test(t)}function $x(t){let e=new Set;for(let r of t.split(/[\r\n]+/)){let n=r.trim();if(n&&Hp(n)&&e.add(n),e.size>=zp)break}return[...e]}function Gp(t,e={}){let r=$x(t);r.length>0&&or("warning","ffmpeg reported warnings.",{...e,warnings:r})}var kx=1e4,Ni=class{constructor(e,r=or,n=Date.now){this.data=e;this.send=r;this.now=n}data;send;now;partial="";seen=new Set;dropped=0;lastDropReport=-1/0;feed(e){let r=(this.partial+e).split(/[\r\n]/);this.partial=r.pop()??"";for(let n of r)this.line(n.trim())}line(e){if(e){if(Up.test(e)){let r=Number(/\bdrop=\s*(\d+)/.exec(e)?.[1]??0);r>this.dropped&&this.now()-this.lastDropReport>=kx&&(this.lastDropReport=this.now(),this.dropped=r,this.send("warning",`The recording has dropped ${r} frame(s) so far.`,{...this.data(),dropped:r}));return}!Hp(e)||this.seen.has(e)||this.seen.size>=zp||(this.seen.add(e),this.send("warning",e,{...this.data(),source:"ffmpeg"}))}}};var Mx="ffmpeg and ffprobe must be installed and on PATH (or set FFMPEG_PATH / FFPROBE_PATH). Windows: `winget install Gyan.FFmpeg` or `choco install ffmpeg`. macOS: `brew install ffmpeg`. Linux: `apt install ffmpeg`.";function Xp(t,e){let r=process.env[t]?.trim();return r||e}function Jp(t){try{return Li(t,["-version"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Rc(){let t=Xp("FFMPEG_PATH","ffmpeg"),e=Xp("FFPROBE_PATH","ffprobe"),r=[];if(Jp(t)||r.push("ffmpeg"),Jp(e)||r.push("ffprobe"),r.length>0)throw new l(`Required ${r.join(" and ")} not found on PATH.`,Mx);return{ffmpeg:t,ffprobe:e}}var Di=null;function k(){return Di||(Di=Rc(),Di)}var bn=null;function ir(){if(bn!==null)return bn;if(process.platform!=="win32")return bn=!1;try{let t=Li(k().ffmpeg,["-hide_banner","-h","filter=gfxcapture"],{encoding:"utf8",windowsHide:!0,timeout:1e4});bn=/gfxcapture AVOptions/.test(t.stdout??"")}catch{bn=!1}return bn}var Yp=new Map;function Ye(t){let e=Yp.get(t);if(e!==void 0)return e;let r;try{let n=Li(k().ffmpeg,["-hide_banner","-h",`filter=${t}`],{encoding:"utf8",windowsHide:!0,timeout:1e4});r=new RegExp(`^Filter ${t}\\b`,"m").test(n.stdout??"")}catch{r=!1}return Yp.set(t,r),r}var Vp=["ignore","pipe","pipe"],So=class extends l{};function ne(t,e,r=300*1e3,n={}){return new Promise((o,i)=>{let s=Kp(t,e,{windowsHide:!0,stdio:Vp}),a="",c="",u=null,d,p=g=>{u||(u=g,s.kill("SIGKILL"),d=setTimeout(()=>i(g),5e3))},f=()=>p(new l(`${t} was cancelled.`)),m=setTimeout(()=>p(new l(`${t} timed out after ${Math.round(r/1e3)}s.`)),r),h,b=()=>{if(!n.stallMs)return;clearTimeout(h);let g=n.progressed?"made no progress":"wrote nothing";h=setTimeout(()=>p(new So(`${t} ${g} for ${Math.round(n.stallMs/1e3)}s and was stopped.`)),n.stallMs)};b();let w=()=>{clearTimeout(m),clearTimeout(h),clearTimeout(d),n.signal?.removeEventListener("abort",f)};n.signal?.aborted?f():n.signal?.addEventListener("abort",f,{once:!0}),s.stdout?.on("data",g=>{let y=g.toString();(!n.progressed||n.progressed(y))&&b(),a+=y,n.onStdout?.(y)}),s.stderr?.on("data",g=>{n.progressed||b(),c+=g.toString()}),s.on("error",g=>{w(),i(g)}),s.on("close",g=>{w(),u?i(u):o({code:g,stdout:a,stderr:c})})})}var Cx=new Set(["-vf","-af","-filter_complex","-lavfi","-filter:v","-filter:a"]),Px=8e3,Ix={"-vf":"-filter_script:v","-filter:v":"-filter_script:v","-af":"-filter_script:a","-filter:a":"-filter_script:a","-filter_complex":"-filter_complex_script","-lavfi":"-filter_complex_script"},xo=null;function Fx(){if(xo!==null)return xo;try{let t=Li(k().ffmpeg,["-hide_banner","-version"],{encoding:"utf8",windowsHide:!0,timeout:1e4}),e=/^\s*libavutil\s+(\d+)\./m.exec(t.stdout??"");xo=e?.[1]===void 0||Number(e[1])>=59}catch{xo=!0}return xo}function Bi(t,e){let r=null,n=[...t];for(let[i,s]of t.entries()){let a=t[i-1];if(a===void 0||!Cx.has(a)||s.length<=Px)continue;r??=_x(qp(Rx(),"screencast-filter-"));let c=qp(r,`filter${i}.txt`);Ax(c,s),e??=Fx(),n[i-1]=e?`-/${a.slice(1)}`:Ix[a]??a,n[i]=c}let o=r;return{args:n,cleanup:()=>o&&Tx(o,{recursive:!0,force:!0})}}async function Dr(t,e=3e4,r={}){let n=[];return await Qp(t,e,o=>n.push(o),r),Buffer.concat(n)}async function Wi(t,e,r,n=3e4,o={}){if(!(e>0))throw new l("frameBytes must be positive.");let i=Buffer.alloc(0),s=0;return await Qp(t,n,a=>{i=i.length?Buffer.concat([i,a]):a;let c=0;for(;c+e<=i.length;c+=e)r(Buffer.from(i.subarray(c,c+e))),s++;i=i.subarray(c)},o),s}function Qp(t,e,r,n){let{ffmpeg:o}=k(),{args:i,cleanup:s}=Bi(t);return new Promise((a,c)=>{let u=Kp(o,i,{windowsHide:!0,stdio:Vp}),d="",p=null,f,m=g=>{p||(p=g,u.kill("SIGKILL"),f=setTimeout(()=>c(g),5e3))},h=()=>m(new l("ffmpeg was cancelled.")),b=setTimeout(()=>m(new l(`ffmpeg timed out after ${Math.round(e/1e3)}s.`)),e),w=()=>{clearTimeout(b),clearTimeout(f),n.signal?.removeEventListener("abort",h)};n.signal?.aborted?h():n.signal?.addEventListener("abort",h,{once:!0}),u.stdout?.on("data",g=>{if(!p)try{r(g)}catch(y){m(y)}}),u.stderr?.on("data",g=>d+=g.toString()),u.on("error",g=>{w(),c(g)}),u.on("close",g=>{w(),p?c(p):g===0?a():c(new l(`ffmpeg failed (exit ${g}):
|
|
149
149
|
${d.trim().split(`
|
|
150
150
|
`).slice(-6).join(`
|
|
151
|
-
`)}`))})}).finally(s)}async function Z(t,e,r={}){let{ffmpeg:n}=k(),o=
|
|
151
|
+
`)}`))})}).finally(s)}async function Z(t,e,r={}){let{ffmpeg:n}=k(),o=Bi(t);try{let i=await ne(n,o.args,e,r);if(i.code!==0){let s=i.stderr.trim().split(`
|
|
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}`)}Gp(i.stderr)}finally{o.cleanup()}}async function se(t,e={}){if(!Ex(t))return null;try{let r=await ne(e.ffprobe??k().ffprobe,Or(t),3e4);return r.code!==0?null:Fr(JSON.parse(r.stdout)).durationSec}catch{return null}}async function L(t){let{ffprobe:e}=k(),r=await ne(e,Or(t),3e4);if(r.code!==0)throw new l(`ffprobe failed (exit ${r.code}): ${r.stderr.trim().slice(-400)}`);return Fr(JSON.parse(r.stdout))}import{basename as ed,dirname as Ox,extname as Nx,join as Dx}from"node:path";import{renameSync as Lx,rmSync as Mc}from"node:fs";var Bx="SCREENCAST_JOB_TIMEOUT_MS",Wx=10*6e4,jx=9e4,Ux=30*6e4,zx=4;function le(t,e=process.env){let r=Number(e[Bx]);return Number.isInteger(r)&&r>0?r:t==null||!(t>0)?Ux:Math.max(Wx,Math.ceil(t*zx*1e3))}function Hx(t){let e=Nx(t);return Dx(Ox(t),`${ed(t,e)}.partial${e}`)}function Gx(t,e,r){let n=t.lastIndexOf(e);if(n===-1)throw new l(`Internal error: output path ${e} is not in the ffmpeg arguments.`);let o=[...t];return o[n]=r,o}function Zp(){let t="",e=null;return r=>{t+=r;let n=t.split(/\r?\n/);t=n.pop()??"";for(let o of n){let i=o.match(/^out_time_(?:us|ms)=(\d+)$/);i&&(e=Number(i[1])/1e6)}return e}}function vo(t){let e=t?._meta?.progressToken;if(e===void 0||!t)return;let r=-1;return n=>{let o=Math.floor(Math.max(0,Math.min(1,n))*100);o<=r||(r=o,t.sendNotification({method:"notifications/progress",params:{progressToken:e,progress:o,total:100}}).catch(()=>{}))}}var Cc=new Set,td=!1;async function W(t,e){if(td)throw new l("The server is shutting down; the edit was not started.");let r=Hx(e.output),n=vo(e.extra),o=Zp(),i=e.durationSec!=null&&e.durationSec>0?e.durationSec:null,s=e.inputDurationSec!=null&&e.inputDurationSec>0?e.inputDurationSec:null,a=s!==null&&i!==null?Math.max(s,i):s??i,c=["-progress","pipe:1","-nostats",...Gx(t,e.output,r)],u=new AbortController,d=e.extra?.signal?AbortSignal.any([e.extra.signal,u.signal]):u.signal,p,f={partial:r,controller:u,done:new Promise(h=>p=h)};Cc.add(f);let m=Xx(e.output);try{let h=()=>{let b=Zp(),w=null,g=y=>{let $=b(y);return $===null||$===w?!1:(w=$,!0)};return Z(c,le(a),{signal:d,stallMs:jx,progressed:g,onStdout:y=>{if(m?.output(y.length),!n||!i)return;let $=o(y);$!==null&&(m?.progress($),n($/i))}})};try{await h()}catch(b){if(!(b instanceof So)||d.aborted)throw b;process.stderr.write(`${b.message} Retrying the edit once.
|
|
155
|
+
`),Mc(r,{force:!0}),await h()}Lx(r,e.output),n?.(1),m?.end("done")}catch(h){throw m?.end(`failed: ${h instanceof Error?h.message.split(`
|
|
156
|
+
`)[0]:String(h)}`),Mc(r,{force:!0}),h}finally{m?.stop(),Cc.delete(f),p()}}var qx="SCREENCAST_DEBUG_JOBS";function Xx(t){if(process.env[qx]!=="1")return;let e=ed(t),r=Date.now(),n=0,o=r,i=null,s=c=>process.stderr.write(`[job ${e}] ${((Date.now()-r)/1e3).toFixed(1)}s ${c}
|
|
157
|
+
`);s("start");let a=setInterval(()=>s(`running: ${n} B of progress output, last ${((Date.now()-o)/1e3).toFixed(1)}s ago, out_time ${i??"none"}`),3e4);return a.unref(),{output:c=>{n+=c,o=Date.now()},progress:c=>{i=c},end:c=>s(c),stop:()=>clearInterval(a)}}async function rd(t=3e3){td=!0;let e=[...Cc];if(e.length===0)return 0;for(let n of e)n.controller.abort();let r;await Promise.race([Promise.all(e.map(n=>n.done)),new Promise(n=>r=setTimeout(n,t))]),clearTimeout(r);for(let n of e)try{Mc(n.partial,{force:!0})}catch{}return e.length}var id=.25;function bt(t){return`${t}.parts`}function sd(t,e){return e===0?t:$o(bt(t),`part-${String(e).padStart(3,"0")}.mp4`)}function Ui(t,e){return $o(bt(t),`webcam-${String(e).padStart(3,"0")}.mp4`)}function Lr(t){let e=od(t);return $o(eS(t),`${Zx(t,e)}.webcam.mp4`)}function Ic(t,e,r,n){if(e!==null&&e>0)return e;let o;try{o=Vx(t).size}catch{return null}return o<=0?null:Math.max(.001,Math.round(n-r)/1e3)}function rt(t){return t.reduce((e,r)=>e+r.durationSec,0)}function tS(t){let e=[],r=0;for(let n of t.parts)e.push({startMs:n.startMs,offsetSec:r,durationSec:n.durationSec}),r+=n.durationSec;return t.current&&e.push({startMs:t.current.startMs,offsetSec:r}),e}function zi(t,e,r){if(!t||t.parts.length===0&&!t.current)return{startMs:e,endSec:(r-e)/1e3};let n=tS(t),o=t.current?Math.max(0,(r-t.current.startMs)/1e3):0;return{startMs:n[0].startMs,endSec:rt(t.parts)+o,spans:n}}function ad(t,e){if(!t)return 0;let r=Math.floor(t-e);if(r<1)throw new l(`The recording already used its maxDurationSec cap (${t}s); nothing is left to resume.`,"Call stop_recording to finalize it.");return r}function cd(t,e){return t.status==="paused"?"it is already paused":t.status!=="recording"?`it is ${t.status}`:t.backend==="wgc"?'backend "wgc" cannot pause yet':t.replay?"a replay buffer cannot pause":!t.capture||!t.segments?.current?"it was started before pause was supported":e?null:"another server instance owns it"}function ud(t,e){return t.status==="recording"?"it is already recording":t.status!=="paused"?`it is ${t.status}`:!t.capture||!t.segments?"its capture settings are missing":e?null:"it was paused by another server instance"}var Fc=new Set;function ld(t){Fc.add(t)}function pd(t){return Fc.has(t)}function dd(t){Fc.delete(t)}var Pc=new Map;function md(t){let e=Pc.get(t);if(!e){let r;e={promise:new Promise(o=>r=o),resolve:r},Pc.set(t,e)}return e}function ko(t){return md(t).promise}function Hi(t){md(t).resolve(),setTimeout(()=>Pc.delete(t),6e4).unref?.()}var nd=t=>Math.round(t*1e3)/1e3;function rS(t,e,r){if(t.length===0)throw new l("No webcam parts to join.");let n=t.map((i,s)=>{let a=nd(Math.max(.001,i.durationSec)),c=nd(i.leadSec),u=c>0?`tpad=start_duration=${c}:start_mode=clone,`:c<0?`trim=start=${-c},setpts=PTS-STARTPTS,`:"";return`[${s}:v]${u}tpad=stop_duration=${a}:stop_mode=clone,trim=duration=${a},setpts=PTS-STARTPTS,format=yuv420p,setsar=1[w${s}]`}),o=`${t.map((i,s)=>`[w${s}]`).join("")}concat=n=${t.length}:v=1:a=0[v]`;return["-y","-v","error",...t.flatMap(i=>["-i",i.path]),"-filter_complex",`${n.join(";")};${o}`,"-map","[v]",...r,...Pr,e]}async function fd(t,e,r){let n=bt(t),o={joined:!1},i=e.filter(u=>ji(u.path)&&u.durationSec>0),s=rt(i),a=!1;if(i.length>1||i.length===1&&i[0].path!==t){Jx(n,{recursive:!0});let u=$o(n,"segments.txt"),d=$o(n,`joined${od(t)||".mp4"}`);Qx(u,yo(i.map(f=>f.path)));let p=await ne(r.ffmpeg,hn(u,d,{quiet:!0}),le(s));p.code===0&&ji(d)?(Yx(d,t),o.joined=!0):(a=!0,o.error=`Joining the ${i.length} segments failed; they are kept in ${n}: ${p.stderr.trim().split(`
|
|
158
|
+
`).slice(-3).join(" ")}`)}let c=i.filter(u=>u.webcamPath&&ji(u.webcamPath));if(r.webcamOutput&&c.length>0){let u=rS(c.map(p=>({path:p.webcamPath,leadSec:p.webcamStartMs!==void 0?(p.webcamStartMs-p.startMs)/1e3:0,durationSec:p.durationSec})),r.webcamOutput,r.webcamCodec),d=await ne(r.ffmpeg,u,le(s));d.code===0&&ji(r.webcamOutput)?o.webcamPath=r.webcamOutput:(a=!0,o.webcamError=`Aligning the webcam failed; its raw parts are kept in ${n}: ${d.stderr.trim().split(`
|
|
159
|
+
`).slice(-3).join(" ")}`)}return a||Kx(n,{recursive:!0,force:!0}),o}function hd(t,e,r,n){let o=d=>Math.max(2,Math.round(d/2)*2),i=o(t.width*n),s=o(i*e.height/Math.max(1,e.width)),a=Math.round(t.width*.02),c=r.endsWith("left")?a:Math.max(0,t.width-i-a),u=r.startsWith("top")?a:Math.max(0,t.height-s-a);return{x:c,y:u,width:i,height:s}}import{execFile as nS}from"node:child_process";import{randomBytes as oS}from"node:crypto";import{rmSync as iS,writeFileSync as sS}from"node:fs";import{tmpdir as aS}from"node:os";import{join as cS}from"node:path";function uS(t){let r=(Array.isArray(t)?t:t?[t]:[]).map(n=>({x:Number(n.X??0),y:Number(n.Y??0),width:Number(n.Width??0),height:Number(n.Height??0),primary:!!n.Primary,...Number(n.Dpi)>0?{dpi:Number(n.Dpi)}:{}}));return r.sort((n,o)=>n.primary!==o.primary?n.primary?-1:1:n.x!==o.x?n.x-o.x:n.y-o.y),r.map((n,o)=>({index:o,...n}))}var lS=`
|
|
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
|
+
`,pS=5e3,wn=null,dS=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
174
|
+
`,mS=2e4,bd="SCREENCAST_PS_TIMEOUT_MS";function sr(t,e=process.env){let r=Number(e[bd]);return Number.isInteger(r)&&r>0?r:t}function fS(t){return`$Payload = [IO.File]::ReadAllText([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(t,"utf8").toString("base64")}')), [Text.Encoding]::UTF8)
|
|
175
|
+
`}function hS(t,e){let r=dS+(e===void 0?"":fS(e))+t;return["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}async function gS(t,e){let r=cS(aS(),`screencast-ps-${process.pid}-${oS(6).toString("hex")}.json`);sS(r,t,{encoding:"utf8",mode:384});try{return await e(r)}finally{iS(r,{force:!0})}}function st(t,e,r={}){return r.payload===void 0?gd(t,e,r):gS(r.payload,n=>gd(t,e,r,n))}function gd(t,e,r,n){let o=r.timeoutMs??sr(mS),i=r.command?.file??"powershell",s=r.command?.args??hS(t,n);return new Promise((a,c)=>{nS(i,s,{encoding:"utf8",windowsHide:!0,maxBuffer:8*1024*1024,timeout:o,killSignal:"SIGKILL",signal:r.signal},(u,d,p)=>{if(r.signal?.aborted)c(new l(`Cancelled while reading ${e}.`));else if(u&&u.killed)c(new l(`Timed out reading ${e} after ${o/1e3} s (PowerShell did not answer).`,`Retry; if it keeps happening, restart the app being captured or raise ${bd}.`));else if(u||!d){let f=r.failure??`Could not enumerate ${e}`;c(new l(`${f}: ${p?.trim()||u?.message||"powershell failed"}`))}else a(d)})})}async function bS(){let t=await st(lS,"monitors");try{return uS(JSON.parse(t))}catch(e){throw new l(`Could not parse monitor geometry: ${U(e)}`)}}function ar(t=Date.now()){if(process.platform!=="win32")return Promise.reject(new l("Monitor enumeration is implemented for Windows (gdigrab) only."));if(wn&&t-wn.at<pS)return wn.monitors;let e={at:t,monitors:bS()};return wn=e,e.monitors.catch(()=>{wn===e&&(wn=null)}),e.monitors}var xd=5;function Oc(t){let e=/^hwnd=(0x[0-9a-f]+|\d+)$/i.exec(t.trim());if(e)return{kind:"hwnd",hwnd:Number(e[1])};let r=/^exe=(.+)$/i.exec(t.trim());return r?.[1]?{kind:"exe",exe:r[1].trim().toLowerCase().replace(/\.exe$/,"")}:null}function Nc(t,e,r={}){let n=Array.isArray(t.windows)?t.windows:[],o=n.filter(i=>!i.cloaked);try{return wd(t,o,e,r)}catch(i){if(!(i instanceof Br)||o.length===n.length)throw i;let s;try{s=wd(t,n,e,r)}catch{throw i}if(!r.allowCloaked)throw new l(`Window "${s.matchedTitle}" is cloaked: Windows reports it as open but it is not on screen (a suspended app, or a window on another virtual desktop), so a screen capture would record whatever is there instead.`,`Bring the window up on this desktop, or use backend: "wgc", which captures the window's own surface.`);return{...s,cloaked:!0}}}var Br=class extends l{};function wd(t,e,r,n){let o=Oc(r);if(o){let p=o.kind==="hwnd"?e.filter(f=>f.hwnd===o.hwnd):e.filter(f=>(f.exe??"").toLowerCase().replace(/\.exe$/,"")===o.exe);if(p.length===0)throw new Br(o.kind==="hwnd"?`No visible top-level window with handle ${r.trim().slice(5)}. It may have closed; handles change when an app restarts.`:`No visible window belonging to ${o.exe}.exe. Is the app running with a window open (and not minimized)?`);return yd(t,p,o.kind)}let i=r.trim().toLowerCase(),s=e.filter(p=>p.title.toLowerCase()===i),a=e.filter(p=>p.title.toLowerCase().includes(i)),c=p=>p.slice(0,xd).map(f=>`"${f.title}"`).join(", ");if(s.length===0&&n.exactOnly)throw new Br(`No visible window titled exactly "${r}" (exactTitle is on).`+(a.length>0?` Windows containing it: ${c(a)}.`:""));let u=s.length>0?"exact":"substring",d=s.length>0?s:a;if(d.length===0)throw new Br(`No visible window matching title "${r}". Open the window (it must be on screen and not minimized), or use an exact/substring of its title, or target it by window:exe=<app.exe> or window:hwnd=<handle>.`);return yd(t,d,u)}function yd(t,e,r){let n=e[0];if(!n)throw new Br("No visible window matched.");if(n.minimized)throw new l(`Window "${n.title}" is minimized. Restore it before capturing - window capture grabs whatever is on screen at the window's rectangle.`);let o=t.virtual,i=Math.max(n.left,o.x),s=Math.max(n.top,o.y),a=Math.min(n.right,o.x+o.w),c=Math.min(n.bottom,o.y+o.h),u=a-i,d=c-s;if(u<=0||d<=0)throw new l(`Window "${n.title}" has no visible on-screen area to capture (off-screen or fully occluded by the desktop edge).`);if(u-=u%2,d-=d%2,u<=0||d<=0)throw new l(`Window "${n.title}" is too small to capture.`);return{x:i,y:s,width:u,height:d,matchedTitle:n.title,...n.hwnd!==void 0?{hwnd:n.hwnd}:{},...n.pid!==void 0?{pid:n.pid}:{},...n.exe!==void 0?{exe:n.exe}:{},...n.clientX!==void 0&&n.clientY!==void 0?{client:{x:n.clientX,y:n.clientY}}:{},matchCount:e.length,matchKind:r,candidates:e.slice(0,xd).map(p=>p.title)}}function cr(t){let e=[];return t.matchKind==="substring"&&e.push("the title matched only as a substring"),t.matchCount>1&&e.push(`${t.matchCount} windows matched and the topmost was used`),t.cloaked&&e.push("the window is cloaked (not on screen: suspended, or on another virtual desktop)"),{matchedWindow:t.matchedTitle,matchCount:t.matchCount,matchKind:t.matchKind,region:{x:t.x,y:t.y,width:t.width,height:t.height},...e.length>0?{windowWarning:`Check this is the intended window: ${e.join(", and ")}. Candidates: ${t.candidates.map(r=>`"${r}"`).join(", ")}. Pass the full title with exactTitle: true to match only that window.`}:{}}}var wS=`
|
|
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 Dc(){if(process.platform!=="win32")throw new l("Window capture is implemented for Windows (gdigrab) only.");let t=await st(wS,"windows"),e;try{e=JSON.parse(t)}catch(i){throw new l(`Could not parse window geometry: ${U(i)}`)}let r=e,n=Array.isArray(r.windows)?r.windows:r.windows?[r.windows]:[];return{virtual:r.virtual??{x:0,y:0,w:0,h:0},windows:n}}async function Sd(t,e={}){return Nc(await Dc(),t,e)}function vd(t,e){if(t.backend==="wgc"){if(!e.windowHwnd)throw new l('backend "wgc" records one window: use a window: target.');if(!e.wgcAvailable)throw new l('backend "wgc" needs FFmpeg 8 or newer (the gfxcapture filter). Use gdigrab, or update ffmpeg.');if(t.replay)throw new l('replayBufferSec is not supported with backend "wgc" yet; use gdigrab or ddagrab.')}if(t.webcam&&(t.backend==="wgc"||t.replay))throw new l("webcam works with backend gdigrab or ddagrab, without replayBufferSec.");if((t.logs||t.perf)&&t.replay)throw new l("logs and perf are not supported with replayBufferSec yet.")}function $d(t){return(t.replayBufferSec?`Keep a rolling ${t.replayBufferSec} s replay buffer of `:"Record ")+`${t.target} `+(t.maxDurationSec>0?`for up to ${t.maxDurationSec} s`:"with no time limit")+(t.audioDevice?`, with system audio (${t.audioDevice})`:", without audio")+(t.webcamDevice?`, with the webcam (${t.webcamDevice})`:"")+(t.events?", logging mouse clicks and typing":"")+(t.focus?t.focus==="title"?" and which window is in front, with its title":" and which app is in front":"")+(t.elements?", naming the on-screen controls you click":"")+(t.hotkeys?`, with hotkeys (${mo.marker} marks, ${mo.stop} stops)`:"")+(t.replayBufferSec?", kept only until save_replay or stop_recording { save: true } writes it out?":`, saved to ${t.output}?`)}function kd(t){let e=t.replay&&t.events?.frame?{events:{raw:t.events.raw,keys:t.events.keys,startMs:t.startMs,frame:t.events.frame}}:{};return{id:t.id,target:t.target,outputPath:t.output,fps:t.fps,quality:t.quality,pid:t.pid,pidSpawnedAt:t.spawnedAt,...t.identity,status:"recording",startedAt:(t.now??new Date).toISOString(),videoStartMs:t.startMs,...t.maxDurationSec>0?{maxDurationSec:t.maxDurationSec}:{},...t.window?{matchedWindow:t.window.matchedTitle}:{},...t.events&&!t.replay?{events:{path:t.events.jsonl,keys:t.events.keys}}:{},...t.replay?{replay:{...t.replay,...e}}:{},backend:t.backend,...t.encoder!=="x264"?{encoder:t.encoder}:{},...t.capture&&t.backend!=="wgc"&&!t.replay?{capture:t.capture,segments:{parts:[],current:{path:t.output,startMs:t.startMs,...t.webcam?{webcamPath:t.webcam.rawPath,...t.webcam.startMs!==void 0?{webcamStartMs:t.webcam.startMs}:{}}:{}}}}:{},...t.webcam?{webcam:{device:t.webcam.device,path:Lr(t.output),corner:t.webcam.corner??"bottom_right",size:t.webcam.size??id,shape:t.webcam.shape??"rect"}}:{},processImage:t.processImage}}function Ed(t){let e=t.record;return{sessionId:e.id,status:"recording",backend:e.backend,outputPath:e.outputPath,pid:e.pid,fps:e.fps,quality:e.quality,audioDevice:t.audioDevice??null,maxDurationSec:t.maxDurationSec>0?t.maxDurationSec:null,encoder:t.encoder,...t.encoderNote?{encoderNote:t.encoderNote}:{},...t.gpuFrames!==void 0?{gpuFrames:t.gpuFrames}:{},...t.webcamDevice?{webcam:{device:t.webcamDevice,path:Lr(e.outputPath)}}:{},...t.window?cr(t.window):{},...t.events&&!t.replay?{eventsPath:t.events.jsonl,keys:t.events.keys}:{},...t.logs?{logsPath:t.logs.path,...t.logs.missing?{logsNote:"A log file does not exist yet; it is read from its start once it appears."}:{}}:{},...t.hotkeys?{hotkeys:{...mo,...t.hotkeys.taken.length?{unavailable:t.hotkeys.taken,warning:`Another app holds ${t.hotkeys.taken.map(r=>mo[r]).join(" and ")}.`}:{}}}:{},...t.replay?{replay:{bufferSec:t.replay.bufferSec,segmentSec:t.replay.segmentSec,dir:t.replay.dir,events:t.replay.events}}:{},note:(t.replay?`Replay buffer running: save_replay keeps the last seconds (up to ${t.replay.bufferSec}s) without stopping it; stop_recording discards the buffer unless save: true (then it writes outputPath).`:"Call stop_recording with this sessionId to finalize the file"+(e.backend==="wgc"?".":" (pause_recording/resume_recording leave stretches out)."))+(t.maxDurationSec>0?` It stops on its own after ${t.maxDurationSec}s (maxDurationSec).`:"")}}import{z as _d}from"zod";var he={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},I={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},Gi={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},Td={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1};function N(t){return _d.looseObject(t)}var Y=N({outputPath:_d.string().describe("Path of the file written.")});import{rmSync as wm,writeFileSync as sv}from"node:fs";import{createReadStream as yS,createWriteStream as xS,existsSync as qi,mkdirSync as SS,mkdtempSync as vS,readdirSync as Lc,readFileSync as $S,rmSync as Yi,statSync as kS,writeFileSync as Ad}from"node:fs";import{stat as Rd,writeFile as ES}from"node:fs/promises";import{pipeline as _S}from"node:stream/promises";import{join as Ke}from"node:path";var Pd=2,TS=3,Xi=4,yn=3600,AS="seg%05d.ts",Id=/^seg(\d{5})\.ts$/,Fd="segments.csv",RS=/^buf-[\w-]+$/,Od=60;function Nd(t){return t+Od}function Dd(){return Ke(Me(),"replay")}function MS(t,e=Pd){return Math.ceil(t/e)+TS}function Ld(t,e=Pd){if(!Number.isInteger(t)||t<Xi||t>yn)throw new l(`replayBufferSec must be an integer from ${Xi} to ${yn} seconds.`);return{dir:Ke(Dd(),`buf-${ge()}-${be(6)}`),bufferSec:t,segmentSec:e,wrap:MS(t,e)}}function Bd(t){return Ke(t,Fd)}function Wd(t,e){let r=t.slice(0,-1),n=r.indexOf("-movflags");return n>=0&&r.splice(n,2),[...r,"-force_key_frames",`expr:gte(t,n_forced*${e.segmentSec})`,"-f","segment","-segment_time",String(e.segmentSec),"-segment_wrap",String(e.wrap),"-segment_list",Bd(e.dir),"-segment_list_type","csv","-segment_list_size",String(e.wrap),"-segment_format","mpegts","-segment_format_options","flush_packets=1",un(e.dir,AS)]}function CS(t){let e=[];for(let r of t.split(/\r?\n/)){let[n="",o,i]=r.trim().split(","),s=Id.exec(n),a=Number(o),c=Number(i);!s||o===void 0||i===void 0||!Number.isFinite(a)||!Number.isFinite(c)||c<a||e.push({file:n,index:Number(s[1]),start:a,end:c})}return e.sort((r,n)=>r.start-n.start)}function PS(t,e){let r=[],n=0;for(let o=t.length-1;o>=0&&n<e;o--){let i=t[o];r.unshift(i),n+=i.end-i.start}return r}function IS(t,e){let r=t.at(-1),n=r?(r.index+1)%e:0;return`seg${String(n).padStart(5,"0")}.ts`}function FS(t,e,r){let n=r.reencode?Se({quality:r.quality??"standard",audio:r.audio?"aac":"omit"}):["-c","copy"];return["-y","-v","error","-ss",String(Eo(Math.max(0,r.startSec))),"-i",t,...n,...Pr,e]}function OS(t,e,r){return bi(t,{from:e,to:r}).map(n=>({...n,t:Eo(n.t-e)}))}var Eo=t=>Math.round(t*1e3)/1e3;async function Md(t,e,r){let n=(await Rd(t)).size;return n===0?(await ES(e,""),0):(await _S(yS(t,{start:0,end:n-1}),xS(e),{signal:r}),(await Rd(e)).size)}async function Cd(t,e,r){let n=await ne(t,["-v","error","-show_entries","format=start_time","-of","csv=p=0",e],15e3,{signal:r}),o=Number.parseFloat(n.stdout.trim());return n.code===0&&Number.isFinite(o)?o:null}async function Bc(t,e){if(!qi(t.dir))throw new l("This replay buffer has been discarded: its segments are gone.");let r=Bd(t.dir),n=qi(r)?CS($S(r,"utf8")):[],o=PS(n,e.lastSec),i=vS(Ke(t.dir,"save-"));try{let s=[];for(let[C,M]of o.entries()){let R=Ke(i,`${String(C).padStart(5,"0")}.ts`);await Md(Ke(t.dir,M.file),R,e.signal),s.push(R)}let a=!1;if(e.live!==!1){let C=Ke(t.dir,IS(n,t.wrap)),M=Ke(i,"live.ts");if(qi(C)&&await Md(C,M,e.signal)>0){let R=s.at(-1),[P,j]=await Promise.all([Cd(e.ffprobe,M,e.signal),R?Cd(e.ffprobe,R,e.signal):Promise.resolve(-1/0)]);P!==null&&j!==null&&P>j&&(s.push(M),a=!0)}}if(s.length===0)throw new l("The replay buffer has no footage yet: the first segment is still being written. Try again in a couple of seconds.");let c=Ke(i,"join.txt");Ad(c,yo(s));let u=Ke(i,"joined.mp4"),d=le(e.lastSec+2*t.segmentSec),p=await ne(e.ffmpeg,hn(c,u,{quiet:!0}),d,{signal:e.signal});if(p.code!==0)throw new l(`Joining the replay segments failed:
|
|
224
224
|
${p.stderr.trim().split(`
|
|
225
225
|
`).slice(-4).join(`
|
|
226
|
-
`)}`);let f=await ne(e.ffprobe,Or(u),3e4,{signal:e.signal}),m=f.code===0?Fr(JSON.parse(f.stdout)):null,h=m?.durationSec??null;if(!h||!(h>0))throw new l("The joined replay has no duration; the segments may be damaged.");let
|
|
226
|
+
`)}`);let f=await ne(e.ffprobe,Or(u),3e4,{signal:e.signal}),m=f.code===0?Fr(JSON.parse(f.stdout)):null,h=m?.durationSec??null;if(!h||!(h>0))throw new l("The joined replay has no duration; the segments may be damaged.");let b=Math.max(0,h-e.lastSec),w=await ne(e.ffmpeg,FS(u,e.output,{startSec:b,reencode:e.reencode,quality:e.quality,audio:!!m?.audioCodec}),d,{signal:e.signal});if(w.code!==0)throw new l(`Writing the replay failed:
|
|
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=Eo(g+b),$=Eo(g+h),S={outputPath:e.output,durationSec:Eo(h-b),fromSec:y,toSec:$,segments:s.length,includesLive:a};if(t.events){let C=t.events.startMs+y*1e3-Od*1e3,M=np(t.events.raw,C),R=OS(hc(M,{startMs:t.events.startMs,frame:t.events.frame}),y,$),{jsonl:P}=$e(e.output);Ad(P,gc(R)),S.eventsPath=P,S.events=an(R)}return S}finally{Yi(i,{recursive:!0,force:!0})}}function jd(t){SS(t.dir,{recursive:!0})}function Ud(t){let e;try{e=Lc(t.dir)}catch{return}for(let r of e)(Id.test(r)||r===Fd)&&Yi(Ke(t.dir,r),{force:!0})}function Ji(t){try{return Yi(t.dir,{recursive:!0,force:!0}),!qi(t.dir)}catch{return!1}}function zd(t){let e=0;try{for(let r of Lc(t.dir))try{let n=kS(Ke(t.dir,r));n.isFile()&&(e+=n.size)}catch{}}catch{}return e}function Hd(t,e=Dd()){let r=new Set([...t].map(i=>i.toLowerCase())),n;try{n=Lc(e)}catch{return 0}let o=0;for(let i of n){let s=Ke(e,i);if(!(!RS.test(i)||r.has(s.toLowerCase())))try{Yi(s,{recursive:!0,force:!0}),o++}catch{}}return o}async function Ki(t,e){if(!e.save)return{saved:!1,discarded:Ji(t)};try{let r=e.tools?.();if(!r)throw new l("ffmpeg is not available to save the replay buffer.");let n=await Bc(t,{...r,lastSec:t.bufferSec,output:e.output,quality:e.quality,live:!1});return{saved:!0,discarded:Ji(t),save:n}}catch(r){return{saved:!1,discarded:!1,error:U(r)}}}var Gd=3;function Vi(t){return`${t}.stop`}function qd(t,e,r){return`Add-Type @"
|
|
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 Zi=["nvenc","qsv","amf"],es={x264:"libx264",nvenc:"h264_nvenc",qsv:"h264_qsv",amf:"h264_amf"},NS={nvenc:{draft:{preset:"p1",q:30},standard:{preset:"p4",q:25},high:{preset:"p6",q:20}},qsv:{draft:{preset:"veryfast",q:30},standard:{preset:"medium",q:25},high:{preset:"slower",q:20}},amf:{draft:{preset:"speed",q:30},standard:{preset:"balanced",q:25},high:{preset:"quality",q:20}}};function ur(t,e,r={}){if(!yc[e])throw new l(`Unknown quality preset "${e}".`);if(t==="x264")return _e(e);let{preset:n,q:o}=NS[t][e],i=["-c:v",es[t]],s=t==="nvenc"?["-preset",n,"-rc","vbr","-cq",String(o),"-b:v","0"]:t==="qsv"?["-preset",n,"-global_quality",String(o)]:["-quality",n,"-rc","cqp","-qp_i",String(o),"-qp_p",String(o)];return[...i,...s,...r.gpuFrames?[]:["-pix_fmt","nv12"]]}function DS(t){return["-hide_banner","-v","error","-f","lavfi","-i","color=c=black:s=256x256:r=30","-frames:v","3",...ur(t,"draft"),"-f","null","-"]}function Yd(t){return["-hide_banner","-v","error","-f","lavfi","-i",`ddagrab=framerate=10${t?"":",hwdownload,format=bgra"}`,"-frames:v","2",...t?ur(t,"draft",{gpuFrames:!0}):[],"-f","null","-"]}var LS=2e4;function Wc(t){return async e=>{try{return(await ne(t,e,LS)).code===0}catch{return!1}}}var Xd=new Map;function jc(t,e,r,n){let o=`${t}\0${e}`,i=Xd.get(o);return i||(i=n(r),Xd.set(o,i)),i}async function Uc(t,e=Wc(t)){let r=await Promise.all(Zi.map(n=>jc(t,`enc:${n}`,DS(n),e)));return Object.fromEntries(Zi.map((n,o)=>[n,r[o]]))}var Qi={nvenc:{width:4096,height:4096},qsv:{width:4096,height:2304},amf:{width:4096,height:2304}};function BS(t,e){let r=Qi[t];return e.width<=r.width&&e.height<=r.height}async function Kd(t,e,r,n=Wc(r),o){if(t==="x264")return{encoder:"x264",gpuFrames:!1};let i=d=>!o||BS(d,o),s=o?`${o.width}x${o.height}`:"";if(t!=="auto"&&!i(t)){let d=Qi[t];throw new l(`The ${t} encoder (${es[t]}) cannot encode a ${s} frame (at most ${d.width}x${d.height}).`,'Use encoder: "x264" (or "auto", which picks libx264 for it), or record a smaller target.')}let a=await Uc(r,n),c=t==="auto"?Zi.find(d=>a[d]&&i(d)):a[t]?t:void 0;if(!c){if(t==="auto"){let d=Zi.filter(p=>a[p]);return{encoder:"x264",gpuFrames:!1,note:d.length>0?`The capture is ${s}, larger than the hardware encoders here take (${d.map(p=>`${p}: ${Qi[p].width}x${Qi[p].height}`).join(", ")}); using libx264.`:"No hardware encoder passed a trial encode; using libx264."}}throw new l(`The ${t} encoder (${es[t]}) failed a trial encode on this machine.`,'Use encoder: "auto" (falls back to libx264) or "x264"; doctor lists the encoders that work here.')}let u=e==="ddagrab"&&await jc(r,`dda:${c}`,Yd(c),n);return{encoder:c,gpuFrames:u}}async function Vd(t,e,r){let n=await e(t);if(n.settled==="running"||t.encoder==="x264")return{run:n,pick:t};let o={encoder:"x264",gpuFrames:!1};if(r.canFallback&&!await r.canFallback())return{run:n,pick:t};let i=`${t.encoder} (${es[t.encoder]})`,s=r.why(n).trim(),a=`the ${i} encoder exited at start${s?`:
|
|
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 Qd(t,e=Wc(t)){return jc(t,"dda",Yd(),e)}function WS(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.trim().split(",");if(n.length<7)continue;let o=n.slice(0,6).map(Number);if(o.some(p=>!Number.isInteger(p)))continue;let[i=0,s=0,a=0,c=0,u=0,d=0]=o;u<=0||d<=0||e.push({adapter:i,output:s,x:a,y:c,w:u,h:d,name:n.slice(6).join(",")})}return e}var jS=`
|
|
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(!xn(n.status)||
|
|
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
|
+
`,US=5e3,_o=null;function Zd(){if(_o&&Date.now()-_o.at<US)return _o.outputs;let t=st(jS,"DXGI outputs").then(WS);return _o={at:Date.now(),outputs:t},t.catch(()=>{_o=null}),t}var Jd=t=>t-t%2;function em(t,e){let r=a=>t.x>=a.x&&t.y>=a.y&&t.x+t.w<=a.x+a.w&&t.y+t.h<=a.y+a.h,n=e.find(r);if(!n)throw new l(`backend "ddagrab" captures one display, and ${t.x},${t.y} ${t.w}x${t.h} is not inside a single one.`,'Use a monitor:<i> target, a region inside one display, or backend "gdigrab".');if(n.adapter!==0)throw new l(`That display (${n.name||`adapter ${n.adapter} output ${n.output}`}) is driven by a second GPU, which ddagrab cannot reach.`,'Use backend "gdigrab" for it.');let o=Jd(t.w),i=Jd(t.h);if(o<=0||i<=0)throw new l("The capture rectangle is too small to record (needs at least 2x2 px).");return t.x===n.x&&t.y===n.y&&o===n.w&&i===n.h?{output:n.output}:{output:n.output,crop:{x:t.x-n.x,y:t.y-n.y,w:o,h:i}}}function tm(t,e,r){let n=t.crop?`:offset_x=${t.crop.x}:offset_y=${t.crop.y}:video_size=${t.crop.w}x${t.crop.h}`:"",o=r.drawMouse===!1?0:1;return["-f","lavfi","-i",`ddagrab=output_idx=${t.output}:framerate=${e}:draw_mouse=${o}${n}${r.download?",hwdownload,format=bgra":""}`]}import{spawnSync as Hc}from"node:child_process";import{readFileSync as ts,writeFileSync as nm,renameSync as om,existsSync as zS,copyFileSync as HS,openSync as GS,closeSync as qS,unlinkSync as im,statSync as sm,linkSync as XS}from"node:fs";import{basename as JS}from"node:path";var YS=100;function xn(t){return t==="recording"||t==="paused"}function KS(t,e){return t.status==="paused"?{status:"stopped",reaped:!1}:t.status!=="recording"?{status:t.status,reaped:!1}:e?{status:"orphaned",reaped:!0}:{status:"stopped",reaped:!1}}function am(t,e,r){return xn(t.status)&&t.serverPid!==void 0&&t.serverPid!==e&&r}function cm(t,e,r){return t.backend==="wgc"||!am(t,e,r)?null:`Recording ${t.id} belongs to another running screencast-mcp instance (pid ${t.serverPid}). Stop it from the client connected to that instance; closing that instance also finalizes it.`}function Gc(t,e=new Map){let r=t.serverPid;return r===void 0||r===process.pid||!ze(r)?!1:(e.has(r)||e.set(r,pm(r)),VS(t,e.get(r)??null))}function um(){return{serverPid:process.pid,serverStartedAt:new Date(Date.now()-process.uptime()*1e3).toISOString(),serverImage:JS(process.execPath).toLowerCase()}}var lm=5e3;function VS(t,e){if(!e)return!0;if(t.serverImage&&e.image.toLowerCase()!==t.serverImage.toLowerCase())return!1;let r=Date.parse(t.serverStartedAt??t.startedAt);return!(Number.isFinite(r)&&e.startMs>r+lm)}function QS(t){let e=/^(.+)\|(\d+)\s*$/m.exec(t.trim());return e?.[1]&&e[2]?{image:e[1].trim(),startMs:Number(e[2])}:null}function pm(t){if(process.platform!=="win32"||!Number.isInteger(t)||t<=0)return null;let e=`$p = Get-CimInstance Win32_Process -Filter "ProcessId=${t}"; if ($p) { "{0}|{1}" -f $p.Name, ([DateTimeOffset]$p.CreationDate).ToUnixTimeMilliseconds() }`,r=Hc("powershell",["-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",windowsHide:!0,timeout:1e4,killSignal:"SIGKILL"});return r.status===0&&r.stdout?QS(r.stdout):null}function ze(t){if(t===null||!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function dm(t){return t.processImage??(t.backend==="wgc"?"node.exe":"ffmpeg.exe")}function ZS(t,e){return(t.split(/\r?\n/)[0]??"").toLowerCase().startsWith(`"${e.toLowerCase()}"`)}function ev(t,e){if(t===null||process.platform!=="win32")return!1;let r=Hc("tasklist",["/FI",`PID eq ${t}`,"/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0});return r.status!==0||!r.stdout?!1:ZS(r.stdout,e)}function tv(t,e){if(!e)return!0;if(e.image.toLowerCase()!==dm(t).toLowerCase())return!1;let r=t.pidSpawnedAt;return!(typeof r=="number"&&Number.isFinite(r)&&e.startMs>r+lm)}function qc(t){return t.pid===null||!ev(t.pid,dm(t))?!1:t.pidSpawnedAt===void 0||tv(t,pm(t.pid))}function mm(t){let{code:e,backend:r,maxDurationSec:n,elapsedMs:o}=t;return r==="wgc"&&e===Gd?{status:"stopped",endReason:"window_closed"}:e!==0&&e!==null?{status:"failed",endReason:"crashed"}:{status:"stopped",endReason:n>0&&o>=n*1e3-2e3?"max_duration":"stopped"}}function lr(t){if(process.platform==="win32")Hc("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0});else try{process.kill(t,"SIGKILL")}catch{}}function zc(t){let e=t.filter(n=>xn(n.status)),r=t.filter(n=>!xn(n.status)).sort((n,o)=>n.startedAt<o.startedAt?1:-1).slice(0,YS);return[...e,...r]}var rv=3e4,fm=15e3;function nv(t,e,r){return!t||typeof t.at!="number"||e-t.at>rv?!0:typeof t.pid=="number"&&!r}function hm(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function ov(t,e){let r=Date.now()+1e3;for(;;)try{om(t,e);return}catch(n){let o=n.code;if(o!=="EPERM"&&o!=="EBUSY"&&o!=="EACCES"||Date.now()>=r)throw n;hm(15)}}function iv(t,e){let r=`${t}.${process.pid}.${Date.now()}.stale`;try{om(t,r)}catch{return!1}let n=!0;try{ts(r,"utf8")!==e&&(n=!1,XS(r,t))}catch{}try{im(r)}catch{}return n}function rm(t,e,r=fm){let n=`${t}.lock`,o=Date.now()+r,i,s;for(let a=0;;a++)try{let c=GS(n,"wx");s=JSON.stringify({pid:process.pid,at:Date.now(),nonce:Math.random().toString(36).slice(2)}),nm(c,s),qS(c);break}catch(c){let u=c.code;if(!(u==="EEXIST"||u==="EPERM"||u==="EACCES"||u==="EBUSY"))throw new l(`Could not lock the session registry (${n}): ${U(c)}`);if(u==="EEXIST"){let p;try{let f=ts(n,"utf8"),m;try{m=JSON.parse(f)}catch{m={at:sm(n).mtimeMs}}p={raw:f,holder:m}}catch{p=null}if(p&&(i=p.holder?.pid,nv(p.holder,Date.now(),ze(p.holder?.pid??null))&&iv(n,p.raw)))continue}if(Date.now()>=o)throw new l(`The session registry is busy: could not take ${n} within ${r/1e3} s${i!==void 0?` (held by process ${i})`:""}. Nothing was written.`,"Another screencast-mcp server is writing to the same registry. Retry; if no other server is running, delete the .lock file.");hm(Math.min(50,2**Math.min(a,6))*(.5+Math.random()))}try{return e()}finally{try{ts(n,"utf8")===s&&im(n)}catch{}}}var rs=class{constructor(e,r=fm){this.path=e;this.lockWaitMs=r}path;lockWaitMs;records=new Map;pending=new Map;removed=new Set;seen=null;children=new Map;stopping=new Set;listeners=[];onChange(e){this.listeners.push(e)}readDisk(){if(!zS(this.path))return new Map;try{return this.parseDisk()}catch{try{HS(this.path,`${this.path}.bak`),process.stderr.write(`Session registry was unreadable; saved a copy to ${this.path}.bak and starting fresh.
|
|
267
|
+
`)}catch{}return new Map}}parseDisk(){let e=JSON.parse(ts(this.path,"utf8"));return new Map(e.map(r=>[r.id,r]))}signature(){try{let e=sm(this.path,{bigint:!0});return`${e.ino}:${e.size}:${e.mtimeNs}`}catch{return null}}overlay(e){for(let[r,n]of this.pending){let o=e.get(r)??this.records.get(r);o&&e.set(r,{...o,...n})}for(let r of this.removed)e.delete(r);return e}refresh(){let e=this.signature();if(e===this.seen)return;let r;try{r=e===null?new Map:this.parseDisk()}catch{return}this.seen=e,this.records=new Map(zc([...this.overlay(r).values()]).map(n=>[n.id,n]))}load(){let e=()=>{let n=this.readDisk();return this.seen=this.signature(),n},r;try{r=rm(this.path,e,this.lockWaitMs)}catch(n){process.stderr.write(`${U(n)} Reading the session registry without the lock.
|
|
268
|
+
`),r=e()}this.records=new Map(zc([...this.overlay(r).values()]).map(n=>[n.id,n]))}persist(){rm(this.path,()=>{let e=zc([...this.overlay(this.readDisk()).values()]),r=`${this.path}.${process.pid}.tmp`;nm(r,JSON.stringify(e,null,2)),ov(r,this.path),this.seen=this.signature(),this.records=new Map(e.map(n=>[n.id,n])),this.pending.clear(),this.removed.clear()},this.lockWaitMs);for(let e of this.listeners)try{e()}catch{}}create(e){this.records.set(e.id,e),this.pending.set(e.id,e);try{this.persist()}catch(r){throw this.records.delete(e.id),this.pending.delete(e.id),r}}remove(e){let r=e.flatMap(n=>{let o=this.records.get(n);return o?[o]:[]});for(let n of e)this.removed.add(n),this.pending.delete(n),this.records.delete(n);try{this.persist()}catch(n){for(let o of e)this.removed.delete(o);for(let o of r)this.records.set(o.id,o);throw n}}get(e){return this.refresh(),this.records.get(e)}list(){return this.refresh(),[...this.records.values()].sort((e,r)=>e.startedAt<r.startedAt?1:-1)}update(e,r){let n=this.records.get(e);if(n||(this.refresh(),n=this.records.get(e)),!n)return;let o={...n,...r};return this.records.set(e,o),this.pending.set(e,{...this.pending.get(e),...r}),this.persist(),this.records.get(e)??o}tryUpdate(e,r){try{return this.update(e,r)}catch(n){process.stderr.write(`Could not save session ${e}: ${U(n)}
|
|
269
|
+
`);return}}attachChild(e,r){this.children.set(e,r)}getChild(e){return this.children.get(e)}detachChild(e,r){r&&this.children.get(e)!==r||this.children.delete(e)}activeIds(){return[...[...this.children.keys()].filter(e=>this.records.get(e)?.status==="recording"),...[...this.paused].filter(e=>this.records.get(e)?.status==="paused"&&!this.children.has(e))]}paused=new Set;markPaused(e){this.paused.add(e)}ownsPaused(e){return this.paused.has(e)}clearPaused(e){this.paused.delete(e)}markStopping(e){this.stopping.add(e)}isStopping(e){return this.stopping.has(e)}clearStopping(e){this.stopping.delete(e)}reapOrphans(){this.refresh();let e=[],r=new Map;for(let n of this.records.values()){if(!xn(n.status)||am(n,process.pid,Gc(n,r)))continue;let o=ze(n.pid),i=KS(n,o);i.reaped&&n.pid!==null&&(qc(n)&&lr(n.pid),e.push(n.id));let s={status:i.status,...n.stoppedAt?{}:{stoppedAt:new Date().toISOString()},...i.status==="orphaned"?{error:"Reaped on server restart (recording was interrupted)."}:{},...n.status==="paused"?{endReason:"shutdown",error:`The server exited while this recording was paused; its parts were not joined (${n.segments?.parts.map(a=>a.path).join(", ")??n.outputPath}).`}:{},...n.status==="recording"&&(n.segments?.parts.length??0)>0?{endReason:"shutdown",error:`The server exited before this recording's segments were joined; ${n.outputPath} holds only the first one. The parts: ${[...n.segments?.parts.map(a=>a.path)??[],...n.segments?.current?[n.segments.current.path]:[]].join(", ")}.`}:{}};this.records.set(n.id,{...n,...s}),this.pending.set(n.id,{...this.pending.get(n.id),...s})}return this.records.size>0&&this.persist(),e}};async function Xc(t,e){let r=Date.now()+e;for(;Date.now()<r&&ze(t);)await new Promise(n=>setTimeout(n,100))}function gm(t,e){return new Promise(r=>{if(t.exitCode!==null||t.signalCode!==null)return r(!0);let n=setTimeout(()=>r(!1),e);t.once("exit",()=>{clearTimeout(n),r(!0)})})}async function ym(t,e,r){if(!t.stdin||!t.stdin.writable)return!1;t.stdin.write(`q
|
|
270
|
+
`),t.stdin.end();let n=await gm(t,r);return!n&&e!==null&&(lr(e),await Xc(e,2e3),await gm(t,2e3)),n}async function av(t,e){let r=t.segments;if(!r)return[];let n=[...r.parts];if(r.current){let o=await se(r.current.path,{ffprobe:e}),i=t.stoppedAt?Date.parse(t.stoppedAt):Date.now(),s=Ic(r.current.path,o,r.current.startMs,i)??0;n.push({...r.current,durationSec:s})}return n}function cv(t){let e=t.segments;return!!e&&(e.parts.length>0||!!t.webcam)}async function Yc(t,e){let r=await av(t,e.ffprobe),n=await fd(t.outputPath,r,{ffmpeg:e.ffmpeg,webcamOutput:t.webcam?Lr(t.outputPath):void 0,webcamCodec:ur(t.encoder??"x264",t.quality,{gpuFrames:!1})});return{patch:{segments:{parts:r},...t.webcam?{webcam:{...t.webcam,error:n.webcamError}}:{}},count:r.length,error:n.error}}var Jc=new WeakMap;function uv(t,e){return Jc.get(t)?.get(e)?.kind??null}function ns(t,e,r){let n=uv(t,e);if(n&&n!==r)throw new l(`Cannot ${r} ${e}: a ${n} of it is in progress.`,"Retry once it finishes (get_session shows the session's status).")}function os(t,e,r,n,o={}){let i=Jc.get(t);i||Jc.set(t,i=new Map);let s=i.get(e);if(s?.kind===r)return s.promise;if(s&&!o.queue)return Promise.reject(new l(`Cannot ${r} ${e}: a ${s.kind} of it is in progress.`,"Retry once it finishes (get_session shows the session's status)."));let a;if(s)a=s.promise.then(()=>n(!0),()=>n(!0));else try{a=n(!1)}catch(d){a=Promise.reject(d)}let c=i,u=a.finally(()=>{c.get(e)?.promise===u&&c.delete(e)});return c.set(e,{kind:r,promise:u}),u}function xm(t,e,r){return os(t,e.id,"pause",()=>lv(t,t.get(e.id)??e,r))}async function lv(t,e,r){let n=t.getChild(e.id),o=cd(e,!!n);if(o)throw new l(`Cannot pause ${e.id}: ${o}.`);ld(e.id),t.markStopping(e.id);try{let i=Date.now(),s=await ym(n,e.pid,r.gracefulMs??8e3);t.detachChild(e.id,n);let a=e.segments.current,c=await r.probe(a.path),u=Ic(a.path,c,a.startMs,i)??0,d=e.segments.parts,p=u>0?[...d,{...a,durationSec:u}]:d;return u<=0&&a.path!==e.outputPath&&wm(a.path,{force:!0}),t.markPaused(e.id),{record:t.update(e.id,{status:"paused",pid:null,segments:{parts:p}}),recordedSec:rt(p),segmentSec:u,graceful:s}}finally{dd(e.id),t.clearStopping(e.id)}}async function Sm(t,e,r=1e4){let n=t.activeIds(),o=n.map(async a=>{let c=t.get(a);if(c)try{await To(t,c,{reason:"shutdown",probe:e,gracefulMs:Math.min(8e3,r)})}catch(u){process.stderr.write(`Stopping ${a} on shutdown failed: ${U(u)}
|
|
271
|
+
`)}}),i,s=new Promise(a=>{i=setTimeout(a,r)});return await Promise.race([Promise.allSettled(o),s]),clearTimeout(i),n}function To(t,e,r){return os(t,e.id,"stop",async n=>{if(!n)return bm(t,e,r);let o=t.get(e.id)??e;return o.status!=="recording"&&o.status!=="paused"?{record:o,graceful:!0,durationSec:o.durationSec??null}:bm(t,o,r)},{queue:!0})}async function bm(t,e,r){t.markStopping(e.id);let n=e.backend==="wgc"?Vi(e.outputPath):null;try{let o=!1,i=t.getChild(e.id),s=f=>new l(`Could not stop recording ${e.id}: its process (pid ${f}) is still running.`);if(i&&i.stdin&&i.stdin.writable){if(o=await ym(i,e.pid,r.gracefulMs??8e3),!o&&e.pid!==null&&ze(e.pid))throw s(e.pid)}else if(e.pid!==null&&ze(e.pid)&&qc(e)&&(n&&(sv(n,""),await Xc(e.pid,r.gracefulMs??8e3),o=!ze(e.pid)),ze(e.pid)&&(lr(e.pid),await Xc(e.pid,2e3)),ze(e.pid)))throw s(e.pid);t.detachChild(e.id,i),e.status==="paused"&&(o=!0),Hi(e.id),t.clearPaused(e.id),await Kt(e.id);let a,c={};if(cv(e)){let f=await Yc(e,k());c=f.patch,a={count:f.count,...f.error?{error:f.error}:{}}}let u=e.replay?await Ki(e.replay,{save:r.saveReplay??!1,output:e.outputPath,quality:e.quality,tools:k}):void 0,d=await r.probe(e.outputPath);return{record:t.update(e.id,{...c,status:"stopped",stoppedAt:new Date().toISOString(),durationSec:d??void 0,endReason:r.reason,error:a?.error}),graceful:o,durationSec:d,...u?{replay:u}:{},...a?{segments:a}:{}}}finally{n&&wm(n,{force:!0}),t.clearStopping(e.id)}}import{existsSync as dv,readFileSync as mv,renameSync as fv,writeFileSync as hv}from"node:fs";var is=t=>Math.round(t*1e3)/1e3;function Ao(t,e){let r=0;for(let n of e){if(t<=n.start)break;r+=(Math.min(t,n.end)-n.start)*(n.factor?1-1/n.factor:1)}return r}function ss(t,e){let r=t;for(let n of e)if(n.op==="trim"){if(r<n.start||r>=n.end)return null;r-=n.start}else n.op==="speed"?r/=n.factor:r-=Ao(r,n.spans);return r}function Wr(t,e,r){let n=t,o=e;for(let i of r)if(i.op==="trim"?(n=Math.max(n,i.start)-i.start,o=Math.min(o,i.end)-i.start):i.op==="speed"?(n/=i.factor,o/=i.factor):(n-=Ao(n,i.spans),o-=Ao(o,i.spans)),o<=n)return null;return[n,o]}function km(t,e){return t.flatMap(r=>{let n=Wr(r.start,r.end,e);return n?[{start:is(n[0]),end:is(n[1])}]:[]})}function as(t,e){return t.flatMap(r=>{let n=Wr(r.start,r.end,e);return n&&n[1]-n[0]>=.05?[{...r,start:is(n[0]),end:is(n[1])}]:[]})}var pv=/^(\d+):(\d{2}):(\d{2})\.(\d{2})$/,vm=t=>{let e=t.trim().match(pv);return e?Number(e[1])*3600+Number(e[2])*60+Number(e[3])+Number(e[4])/100:null},$m=t=>{let e=Math.round(t*100),r=n=>String(n).padStart(2,"0");return`${Math.floor(e/36e4)}:${r(Math.floor(e%36e4/6e3))}:${r(Math.floor(e%6e3/100))}.${r(e%100)}`};function Em(t,e){return t.split(/\r?\n/).flatMap(r=>{let n=r.match(/^(Dialogue:\s*[^,]*,)([^,]*),([^,]*),(.*)$/);if(!n)return[r];let[,o,i,s,a]=n,c=vm(i),u=vm(s);if(c===null||u===null)return[r];let d=Wr(c,u,e);return d&&d[1]-d[0]>=.05?[`${o}${$m(d[0])},${$m(d[1])},${a}`]:[]}).join(`
|
|
272
|
+
`)}var _m=500,Kc=200,Tm=3,Sn=10,It=t=>Math.round(t*1e3)/1e3;function pr(t){return`${t.replace(/\.[^./\\]+$/,"")}.markers.json`}function Am(t,e){return Math.max(0,It((e-t)/1e3))}function Ro(t,e=Kc){let r=t.replace(/\s+/g," ").trim();return r.length>e?`${r.slice(0,e-1).trimEnd()}\u2026`:r}function us(t,e){if(t.length>=_m)throw new l(`A recording holds at most ${_m} markers.`);let r=Ro(e.label);if(!r)throw new l("A marker needs a non-empty label.");if(!Number.isFinite(e.t)||e.t<0)throw new l("A marker time must be a non-negative number of seconds.");let n={...e,t:It(e.t),label:r},o=t.findIndex(i=>i.t>n.t);return o===-1?[...t,n]:[...t.slice(0,o),n,...t.slice(o)]}function gv(t){let e=t;return!!e&&typeof e.t=="number"&&Number.isFinite(e.t)&&e.t>=0&&typeof e.label=="string"}function bv(t){let e;try{e=JSON.parse(t)}catch{return[]}let r=Array.isArray(e)?e:e?.markers;return Array.isArray(r)?r.filter(gv).sort((n,o)=>n.t-o.t):[]}function Le(t){let e=pr(t);if(!dv(e))return[];try{return bv(mv(e,"utf8"))}catch{return[]}}function dr(t,e,r){let n=pr(t),o=`${n}.${process.pid}.tmp`;return hv(o,JSON.stringify({...r?{sessionId:r}:{},markers:e},null,2)),fv(o,n),n}function Rm(t,e){let r=[...t].sort((n,o)=>n.t-o.t);for(let n of e){if(n.op==="speed"){r=r.map(s=>({...s,t:It(s.t/n.factor)}));continue}if(n.op==="cut"){r=r.map(s=>({...s,t:It(s.t-Ao(s.t,n.spans))}));continue}let o=r.filter(s=>s.t>=n.start&&s.t<n.end).map(s=>({...s,t:It(s.t-n.start)})),i=r.filter(s=>s.t<n.start).at(-1);r=i&&!o.some(s=>s.t<.001)?[{...i,t:0},...o]:o}return r}function ls(t,e,r={}){let n=Math.max(.001,r.minChapterSec??1),o=t.filter(a=>Number.isFinite(a.start)&&a.start>=0&&a.start<e).map((a,c)=>({start:It(a.start),title:Ro(a.title,100)||`Chapter ${c+1}`})).sort((a,c)=>a.start-c.start),i=[];for(let a of o){let c=i.at(-1);c?a.start-c.start>=n&&i.push(a):a.start<n?i.push({...a,start:0}):i.push({start:0,title:r.introTitle??"Intro"},a)}let s=i.at(-1);return i.length>1&&s&&e-s.start<n&&i.pop(),i.map((a,c)=>({start:a.start,end:It(i[c+1]?.start??e),title:a.title}))}function wv(t,e){let r=Math.max(0,Math.floor(t)),n=Math.floor(r/3600),o=Math.floor(r%3600/60),i=String(r%60).padStart(2,"0");return e?`${n}:${String(o).padStart(2,"0")}:${i}`:`${Math.floor(r/60)}:${i}`}function Mm(t,e){let r=e>=3600,n=t.map(s=>`${wv(s.start,r)} ${s.title}`).join(`
|
|
273
|
+
`),o=[];t.length<Tm&&o.push(`YouTube needs at least ${Tm} chapters; there are ${t.length}.`),t[0]&&t[0].start!==0&&o.push("YouTube needs the first chapter at 0:00.");let i=t.filter(s=>s.end-s.start<Sn);return i.length>0&&o.push(`YouTube needs every chapter to be at least ${Sn} s long; ${i.length} ${i.length===1?"is":"are"} shorter (${i.map(s=>`"${s.title}"`).join(", ")}). Raise minChapterSec to ${Sn} to merge them.`),{text:n,issues:o}}function yv(t){return t.replace(/[=;#\\\n]/g,e=>`\\${e}`)}function ps(t){let e=[";FFMETADATA1"];for(let r of t)e.push("[CHAPTER]","TIMEBASE=1/1000",`START=${Math.round(r.start*1e3)}`,`END=${Math.round(r.end*1e3)}`,`title=${yv(r.title)}`);return`${e.join(`
|
|
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 ds(t){return t.map(e=>({start:e.t,title:e.label}))}function Cm(t,e,r){let n=[0];for(let o of[...t].sort((i,s)=>s.score-i.score)){if(n.length>=r)break;n.every(i=>Math.abs(i-o.timeSec)>=e)&&n.push(o.timeSec)}return n.sort((o,i)=>o-i).map((o,i)=>({start:o,title:`Scene ${i+1}`}))}function xv(t,e=60){let r=t.replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();if(r.length<=e)return r;let n=r.slice(0,e),o=n.lastIndexOf(" ");return`${(o>e/2?n.slice(0,o):n).trimEnd()}\u2026`}function Pm(t,e={}){let r=e.gapSec??2,n=e.minChapterSec??30,o=[...t].sort((a,c)=>a.start-c.start),i=[],s=-1/0;for(let a of o){let c=i.at(-1);(!c||a.start-s>=r&&a.start-c.start>=n)&&i.push({start:a.start,title:xv(a.text)}),s=Math.max(s,a.end)}return i}var cs=8;function Im(t,e,r,n){let o=n.subtitles??[];if(o.length>cs)throw new l(`At most ${cs} subtitle tracks.`);return["-y","-i",t,"-f","ffmetadata","-i",e,...o.flatMap(i=>["-i",i.file]),"-map","0:v","-map","0:a?",...o.length?o.flatMap((i,s)=>["-map",`${s+2}:s:0`]):["-map","0:s?"],"-map_metadata","0","-map_chapters","1","-c","copy",...o.length?["-c:s",n.container===".mkv"?"copy":"mov_text"]:[],...o.flatMap((i,s)=>[...i.language?[`-metadata:s:s:${s}`,`language=${i.language}`]:[],...i.title?[`-metadata:s:s:${s}`,`title=${i.title}`]:[],...o.length>1||i.default!==void 0?[`-disposition:s:${s}`,i.default?"default":"0"]:[]]),...n.container===".mkv"?[]:["-movflags","+faststart"],r]}function Sv(t){return["-v","quiet","-print_format","json","-show_chapters",t]}function vv(t){let e;try{e=JSON.parse(t)}catch{return[]}return(e.chapters??[]).flatMap((r,n)=>{let o=Number(r.start_time),i=Number(r.end_time);return!Number.isFinite(o)||!Number.isFinite(i)?[]:[{start:It(o),end:It(i),title:r.tags?.title??`Chapter ${n+1}`}]})}async function $v(t,e){let{ffprobe:r}=k(),n=await ne(r,Sv(t),3e4,{signal:e});return n.code===0?vv(n.stdout):[]}async function mr(t,e){let r=Le(t);if(r.length>0)return{markers:r,from:"sidecar"};let n=await $v(t,e);return n.length>0?{markers:n.map(o=>({t:o.start,label:o.title})),from:"chapters"}:{markers:[],from:null}}function ms(t,e,r,n){let o=t.get(e);if(!o)throw new l(`No session with id "${e}".`);let i=n;if(i===void 0&&o.status==="paused")i=rt(o.segments?.parts??[]);else if(i===void 0){if(o.status!=="recording")throw new l(`Session "${e}" is ${o.status}, so there is no "now" to mark.`,"Pass at (video seconds) to mark a stopped recording.");i=Am(o.videoStartMs??Date.parse(o.startedAt),Date.now())}else if(o.durationSec!=null&&i>o.durationSec)throw new l(`at ${i}s is past the end of the recording (${o.durationSec}s).`);let s={t:i,label:r,at:new Date().toISOString()},a=us(o.markers??[],s);t.update(e,{markers:a});let c=pr(o.outputPath),u;try{c=dr(o.outputPath,a,e)}catch(d){u=`Saved in the session, but the sidecar ${c} could not be written: ${U(d)}`}return{t:i,count:a.length,markersPath:c,live:o.status==="recording"||o.status==="paused",...u?{warning:u}:{}}}import{existsSync as kv,readFileSync as Ev}from"node:fs";import{dirname as Fm,join as fs}from"node:path";import{fileURLToPath as _v}from"node:url";var Om="@tmhs/screencast-mcp",Vc=null,Tv=null;function Nm(t){try{return JSON.parse(Ev(t,"utf8"))}catch{return null}}function Av(t){for(let e=t;;){let r=fs(e,"package.json");if(kv(r)&&Nm(r)?.name===Om)return e;let n=Fm(e);if(n===e)return null;e=n}}function Qc(){if(Vc)return Vc;let t=Av(Fm(_v(import.meta.url)));if(!t)throw new l(`Cannot find the ${Om} package root (its package.json).`);return Vc=t}function wt(){return Tv??=Nm(fs(Qc(),"package.json"))?.version??"0.0.0"}function vn(...t){return fs(Qc(),"assets",...t)}function Dm(){return fs(Qc(),"dist","wgcRecorder.js")}async function at(t,e={}){let r=gp(t);if(r.kind==="window"){let n=await Sd(r.title,{exactOnly:e.exactTitle,allowCloaked:e.backend==="wgc"});return{target:{kind:"region",x:n.x,y:n.y,w:n.width,h:n.height},monitors:[],window:n}}return r.kind==="monitor"?{target:r,monitors:await ar()}:r.kind==="region"?(wp(r,await ar()),{target:r,monitors:[]}):{target:r,monitors:await ar()}}var Rv=["virtual-audio-capturer","stereo mix","what u hear","wave out mix","cable output","voicemeeter output"],Mo="System audio capture needs a virtual-audio loopback device, which Windows does not provide natively. Enable 'Stereo Mix' in Sound settings, or install a loopback driver (for example screen-capture-recorder's virtual-audio-capturer, or VB-CABLE). Then pass its name as `device`, or run list_audio_devices to see what is available. Microphone capture is not supported.";function Mv(t){return Lm(t,"audio")}function Cv(t){return Lm(t,"video")}function Lm(t,e){let r=[],n=null;for(let o of t.split(/\r?\n/)){if(/DirectShow audio devices/i.test(o)){n="audio";continue}if(/DirectShow video devices/i.test(o)){n="video";continue}if(/Alternative name/i.test(o))continue;let i=o.match(/"([^"]+)"/);if(!i)continue;let s=/\(audio\)/i.test(o),a=/\(video\)/i.test(o);(e==="audio"?s||!a&&n==="audio":a||!s&&n==="video")&&i[1]&&r.push(i[1])}return[...new Set(r)]}function Zc(t,e){if(e&&e.trim().length>0)return t.includes(e)?e:null;let r=n=>n.toLowerCase();return t.find(n=>Rv.some(o=>r(n).includes(o)))??null}var Pv=12e3,Iv="Enumerating DirectShow audio devices timed out or failed - usually a misbehaving audio driver, or no audio device present. Record without system audio, or fix the device, then retry. "+Mo,hs=null,gs=null;async function eu(t=!1){return!t&&hs?hs:(await Wm(),hs??[])}async function tu(t=!1){return!t&&gs?gs:(await Wm(),gs??[])}async function Bm(t){let e=await tu();if(t&&t.trim().length>0){if(e.includes(t))return t;throw new l(`Video device "${t}" not found. Available dshow video devices: ${e.join(", ")||"none"}.`)}let r=e[0];if(!r)throw new l("No webcam (dshow video device) found.","Connect a camera, then run list_video_devices.");return r}async function Wm(){let{ffmpeg:t}=k(),e;try{e=await ne(t,["-hide_banner","-list_devices","true","-f","dshow","-i","dummy"],Pv)}catch(r){throw new l(`Could not enumerate audio devices (${U(r)}).`,Iv)}hs=Mv(e.stderr),gs=Cv(e.stderr)}async function jm(t){let e=await eu(),r=Zc(e,t);if(r)return r;if(t&&t.trim().length>0){let n=e.length>0?e.join(", "):"none";throw new l(`Audio device "${t}" not found. Available dshow audio devices: ${n}.`,Mo)}throw new l("No system-audio loopback device found.",Mo)}var Co="SCREENCAST_CONFIRM_CAPTURE",ru=300*1e3;function Um(t=process.env){let e=(t[Co]??"").trim().toLowerCase();return["1","true","yes","on","always"].includes(e)?"always":["0","false","no","off","never"].includes(e)?"off":"auto"}function zm(t=process.env){return Um(t)==="always"}function Ft(t,e){return e?`window "${e.matchedTitle}"`:t==="full"?"the full screen (all monitors)":t}async function Ot(t,e,r){let n=Um();if(n==="off")return;if(!t.server.getClientCapabilities()?.elicitation?.form){if(n==="auto")return;throw new l(`Capture blocked: ${Co} requires the user to confirm each capture, but this client does not support MCP elicitation. Nothing was captured.`,`Use a client that supports elicitation, or set ${Co}=auto to capture without confirmation in clients that cannot ask.`)}let o;try{({action:o}=await t.server.elicitInput({message:e,requestedSchema:{type:"object",properties:{}}},{signal:r,timeout:ru}))}catch(i){throw new l(`Capture blocked: the confirmation request failed (${U(i)}). Nothing was captured.`)}if(o!=="accept")throw new l(`Capture ${o==="decline"?"declined":"cancelled"} by the user. Nothing was captured.`)}var bs=null;function re(){return bs||(bs=new rs(pp()),bs.load()),bs}var ou=!1;function Hm(){ou=!0}function ys(){return ou}var ws=0,nu=[];function Gm(){if(ou)throw new l("The server is shutting down; the recording was not started.");ws++;let t=!1;return()=>{if(!t&&(t=!0,ws--,ws===0)){let e=nu;nu=[];for(let r of e)r()}}}function qm(t){return ws===0?Promise.resolve(!0):new Promise(e=>{let r=setTimeout(()=>e(!1),t);r.unref?.(),nu.push(()=>{clearTimeout(r),e(!0)})})}import{existsSync as y0,mkdirSync as x0,mkdtempSync as S0,rmSync as yu,writeFileSync as bf}from"node:fs";import{tmpdir as v0}from"node:os";import{spawn as Fv}from"node:child_process";var Xm=15e3;async function Nt(t,e,r="gdigrab"){if(r==="gdigrab"){await Z(_i(t.target,e,t.monitors),6e4);return}let n=t.window?.hwnd;if(n===void 0)throw new l("backend 'wgc' captures a single window: use a window:<title> target.");if(!ir())throw new l("backend 'wgc' needs FFmpeg 8 or newer with the gfxcapture filter (Windows Graphics Capture).","Check with `ffmpeg -h filter=gfxcapture`. Recent Windows builds (e.g. `winget install Gyan.FFmpeg`) include it. Or use the default backend, which captures what is visible on screen.");let o=Fv("powershell",["-NoProfile","-NonInteractive","-Command",qd(n,100,process.pid)],{stdio:"ignore",windowsHide:!0});o.on("error",()=>{});try{await Z(Sp(n,e),Xm)}catch(i){throw i instanceof l&&/timed out/.test(i.message)?new l(`Windows Graphics Capture got no frame from the window in ${Xm/1e3} s.`,"The window may be hung or protected from capture. Try the default backend with the window in front."):i}finally{o.kill()}}import{join as su}from"node:path";import{readdirSync as Yv}from"node:fs";import{runInNewContext as Ov}from"node:vm";var Nv=[2,4],Dv=1e4;function Lv(t){return{script:qv,payload:JSON.stringify(t)}}async function Ym(t,e){if(process.platform!=="win32")throw new l("find_text uses the Windows OCR engine and runs on Windows only.");let{script:r,payload:n}=Lv(t),o=await st(r,"text (OCR)",{timeoutMs:sr(Hv+Math.max(0,t.length-2)*Gv),payload:n,failure:"Could not run OCR"}),i;try{i=JSON.parse(o)}catch(a){throw new l(`Could not parse OCR output: ${U(a)}`)}return(Array.isArray(i)?i:[i]).map((a,c)=>Bv(a,e[c]??1))}function Bv(t,e){let r=t??{};if(r.error)throw/language|recognizer/i.test(r.error)?new l(`Windows OCR is unavailable: ${r.error}`,"Install an OCR language: Settings > Time & language > Language > (your language) > Options > Optical character recognition."):new l(`OCR failed: ${r.error}`);let n=[];for(let o of r.lines??[]){let i=(Array.isArray(o.words)?o.words:o.words?[o.words]:[]).map(s=>({text:String(s.text??""),x:Math.round((s.x??0)/e),y:Math.round((s.y??0)/e),width:Math.max(1,Math.round((s.width??0)/e)),height:Math.max(1,Math.round((s.height??0)/e))}));i.length!==0&&n.push({text:String(o.text??i.map(s=>s.text).join(" ")),words:i,...Km(i)})}return n}function Km(t){let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,width:n-e,height:o-r}}function Wv(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),n=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);return r<=0||n<=0?0:r*n/Math.min(t.width*t.height,e.width*e.height)}function Vm(t){let e=[];for(let r of t)for(let n of r){let o=e.findIndex(s=>Wv(s,n)>.5),i=e[o];i?n.text.length>i.text.length&&(e[o]=n):e.push(n)}return e.sort((r,n)=>r.y-n.y||r.x-n.x)}function Dt(t){return t.toLowerCase().replace(/[-_\s]+/g,"_").replace(/[l1|]/g,"i").replace(/0/g,"o")}var jr=500,jv=1e3;function Qm(t,e){return t.map(r=>{let n=new RegExp(e,"gi"),o=new Set,i=[];for(let s of[r,r.replace(/-/g,"_"),r.replace(/_/g,"-")])for(let a of s.matchAll(n)){let c=`${a.index}:${a[0].length}`;a[0].length>0&&!o.has(c)&&(o.add(c),i.push([a.index,a.index+a[0].length]))}return i})}var Uv=`JSON.stringify((${Qm.toString()})(texts, query))`,Zm=new Set;function iu(t){return Zm.add(t),t}function $n(t,e,r=jv){try{new RegExp(e,"gi")}catch(n){throw new l(`Invalid regex: ${U(n)}`)}if(Zm.has(e))return Qm(t,e);try{return JSON.parse(Ov(Uv,{texts:t,query:e},{timeout:r}))}catch(n){throw n.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"?new l(`The regex took longer than ${r/1e3} s to run and was stopped.`,"Simplify it: nested quantifiers such as (a+)+ backtrack catastrophically."):n}}function yt(t,e,r=!1){if(e.length>jr)throw new l(`The query is ${e.length} characters; at most ${jr} are allowed.`);let n=t.map(s=>{let a=[],c="";for(let u of s.words)c&&(c+=" "),a.push({start:c.length,end:c.length+u.text.length,word:u}),c+=u.text;return{line:s,spans:a,text:c}}),o=r?$n(n.map(s=>s.text),e):null,i=[];return n.forEach(({line:s,spans:a},c)=>{let u=[];if(o)u=o[c]??[];else{let p=Dt(e);if(!p)return;let f=a.map(h=>Dt(h.word.text)).join("_"),m=0;for(let h=f.indexOf(p,m);h!==-1;h=f.indexOf(p,m))u.push(zv(a,h,h+p.length)),m=h+p.length}let d=new Set;for(let[p,f]of u){let m=a.filter(h=>h.start<f&&h.end>p).map(h=>h.word);m.length===0||m.every(h=>d.has(h))||(m.forEach(h=>d.add(h)),i.push({text:m.map(h=>h.text).join(" "),line:s.text,...Km(m)}))}}),i}function zv(t,e,r){let n=0,o=-1,i=-1;for(let s of t){let a=Dt(s.word.text).length;if(o===-1&&e<n+a&&(o=s.start),r<=n+a+1){i=s.end;break}n+=a+1}return[o===-1?0:o,i===-1?t.at(-1)?.end??0:i]}function xs(t,e,r=4){return t.map(n=>{let o=Math.max(0,n.x-r),i=Math.max(0,n.y-r);return{x:o,y:i,width:Math.min(e.width,n.x+n.width+r)-o,height:Math.min(e.height,n.y+n.height+r)-i}})}function ef(t,e){let r=Dv/Math.max(t,e),n=Nv.map(o=>Math.min(o,Math.floor(r*100)/100)).filter(o=>o>=1);return[...new Set(n.length?n:[Math.min(1,r)])]}var Hv=6e4,Gv=5e3,Jm=2e4,qv=`
|
|
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(${Jm})) { throw "The OCR engine did not answer within ${Jm/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,47 @@ $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 Xv}from"node:os";function Jv(t=Xv()){return Math.min(4,Math.max(2,Math.floor(t/4)))}async function He(t,e,r=Jv()){let n=new Array(t.length),o=0,i=!1,s,a=async()=>{for(;!i&&o<t.length;){let u=o++;try{n[u]=await e(t[u],u)}catch(d){i||(i=!0,s=d)}}},c=Math.max(1,Math.min(Math.floor(r),t.length));if(await Promise.all(Array.from({length:c},a)),i)throw s;return n}function Kv(t,e,r){if(e.length===0||e.length!==r.length)throw new l("Each OCR pass needs one output.");let n=a=>`scale=iw*${a}:ih*${a}:flags=lanczos`,o=["-compression_level","0"];if(e.length===1)return["-y","-v","error","-i",t,"-vf",n(e[0]),...o,r[0]];let i=e.map((a,c)=>`[s${c}]`),s=[`[0:v]split=${e.length}${i.join("")}`,...e.map((a,c)=>`${i[c]}${n(a)}[o${c}]`)].join(";");return["-y","-v","error","-i",t,"-filter_complex",s,...r.flatMap((a,c)=>["-map",`[o${c}]`,...o,a])]}async function ct(t,e,r,n={}){let o=async m=>{let{width:h,height:b}=await L(m);if(!h||!b)throw new l("Could not read the image size.");return{width:h,height:b}},i=n.sameSize&&t[0]?await o(t[0]):null,s=await He(t,async m=>({source:m,...i??await o(m)})),c=(await He(s,async({source:m,width:h,height:b},w)=>{let g=ef(h,b),y=g.map(($,S)=>su(e,`pass${w}-${S}.png`));return await Z(Kv(m,g,y),6e4,{signal:r}),g.map(($,S)=>({out:y[S],scale:$,f:w}))})).flat(),u=c.map(m=>m.out),d=c.map(m=>m.scale),p=c.map(m=>m.f),f=await Ym(u,d);return s.map(({width:m,height:h},b)=>({lines:Vm(f.filter((w,g)=>p[g]===b)),width:m,height:h}))}async function Ss(t,e,r,n){let o=await L(t),i=o.videoDurationSec??o.durationSec,s=e.range?e.range.duration:i,a=Mi(s,1/e.everySec,e.maxFrames);await Z(Ci(t,a.fps,su(r,"scan_%05d.png"),e.maxFrames,!1,e.range),le(o.durationSec),{signal:n});let c=Yv(r).filter(m=>m.startsWith("scan_")).sort().map(m=>su(r,m));if(c.length===0)throw new l("Could not read any frames from the video.");let u=1/a.fps,d=m=>Math.round(m*u*1e3)/1e3,p=s??d(c.length-1)+u;return{frames:(await ct(c,r,n,{sameSize:!0})).map((m,h)=>({...m,t:d(h),path:c[h]??""})),step:u,end:p,clamped:a.clamped}}function Vv(t,e,r){return{start:Math.max(0,Math.round((t-e)*1e3)/1e3),end:Math.min(r,Math.round((t+e)*1e3)/1e3)}}function kn(t,e,r,n="match"){let o=[],i=[];for(let s of t.frames){let a=yt(s.lines,e,r),c=Vv(s.t,t.step,t.end),u=n==="line"?[...new Set(a.map(d=>s.lines.find(p=>p.text===d.line)??d))]:a;for(let d of a)o.push({t:s.t,...d});for(let d of xs(u,s))i.push({...d,...c})}return{matches:o,redactRegions:i}}var En=30,vs=120;var au=600,tf=24*3600,cu=1500,_n=new Map;function $s(t){return t.startsWith("arm-")}function Qv(){return`arm-${ge()}-${be(6)}`}function Po(t){let e=_n.get(t)?.arm;return e?{...e}:void 0}function rf(){return[..._n.values()].map(t=>({...t.arm}))}function uu(t){let e=_n.get(t);return!e||e.arm.status!=="armed"?!1:(e.abort.abort(),e.arm.status="cancelled",!0)}async function nf(t){return await _n.get(t)?.done,Po(t)}function of(){for(let t of _n.keys())uu(t)}function lu(t){return[...t.window?[`${t.window.replace(/^window:/,"the window ")} exists`]:[],...t.text?[`"${t.text}" is on screen`]:[]].join(" and ")}async function pu(t){let e=t.now??Date.now,r=t.sleep??(o=>new Promise(i=>setTimeout(i,o))),n=e();for(;;){if(t.signal.aborted)return"cancelled";let o=!0;for(let i of t.checks)if(!await i().catch(()=>!1)){o=!1;break}if(t.signal.aborted)return"cancelled";if(o)return"met";if(e()-n>=t.timeoutMs)return"timeout";await r(t.intervalMs)}}function sf(t){let e={id:Qv(),status:"armed",conditions:t.conditions,target:t.target,armedAt:new Date().toISOString(),timeoutSec:t.timeoutSec},r=new AbortController,n={arm:e,abort:r};return _n.set(e.id,n),n.done=(async()=>{let o=await pu({checks:t.checks,timeoutMs:t.timeoutSec*1e3,intervalMs:t.intervalMs??cu,signal:r.signal});if(o!=="met"){e.status==="armed"&&(e.status=o);return}if(e.status==="armed"){e.firedAt=new Date().toISOString(),e.status="starting";try{e.sessionId=await t.fire(),e.status="started"}catch(i){e.status="failed",e.error=i instanceof Error?i.message:String(i)}}})(),{...e}}import{open as Zv,stat as af}from"node:fs/promises";import{basename as e0}from"node:path";var cf=5,du=5e4,mu=2e3,t0=250,r0=1<<20;function n0(t,e){let r=t.length?Buffer.concat([t,e]):e,n=[],o=0;for(let i=r.indexOf(10);i!==-1;i=r.indexOf(10,o))n.push(r.subarray(o,i).toString("utf8").replace(/\r$/,"")),o=i+1;return{lines:n,rest:r.subarray(o)}}function o0(t){if(/\b(error|err|fatal|critical|exception|unhandled|panic)\b|\btraceback\b/i.test(t))return"error";if(/\bwarn(ing)?\b/i.test(t))return"warn"}var i0=t=>t.length>mu?`${t.slice(0,mu-1)}\u2026`:t;function uf(t,e){let r=[];for(let n of t){if(!n.line.trim())continue;let o=e.spans?.length?po(n.epochMs,e.spans):(n.epochMs-e.startMs)/1e3;if(o===null||o<0||o>e.endSec)continue;let i=o0(n.line);r.push({t:Math.round(o*1e3)/1e3,source:n.source,line:i0(n.line),...i?{level:i}:{}})}return r.slice(-du)}function lf(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
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 Lt(t){return t.replace(/\.[^./\\]+$/,"")+".logs.jsonl"}var ks=class{constructor(e,r=Date.now){this.now=r;this.files=e.map(n=>({path:n.path,label:n.label??e0(n.path),pos:0,ino:null,partial:Buffer.alloc(0)}))}now;files;lines=[];timer=null;polling=Promise.resolve();async mark(){for(let e of this.files)try{let r=await af(e.path);e.pos=r.size,e.ino=r.ino}catch{}}follow(e=t0){this.timer=setInterval(()=>{this.polling=this.polling.then(()=>this.readNew())},e),this.timer.unref()}async readNew(){for(let e of this.files){let r;try{r=await af(e.path)}catch{continue}if((e.ino!==null&&r.ino!==e.ino||r.size<e.pos)&&(e.pos=0,e.partial=Buffer.alloc(0)),e.ino=r.ino,r.size<=e.pos)continue;let n=Math.min(r.size-e.pos,r0),o;try{o=await Zv(e.path,"r");let i=Buffer.alloc(n),{bytesRead:s}=await o.read(i,0,n,e.pos);e.pos+=s;let{lines:a,rest:c}=n0(e.partial,i.subarray(0,s));e.partial=c.length>mu*4?Buffer.alloc(0):Buffer.from(c);let u=this.now();for(let d of a)this.lines.push({epochMs:u,source:e.label,line:d});this.lines.length>du*2&&(this.lines=this.lines.slice(-du))}catch{}finally{await o?.close()}}}async stop(){this.timer&&clearInterval(this.timer),this.timer=null,await this.polling,await this.readNew();let e=this.now();for(let r of this.files)r.partial.length&&this.lines.push({epochMs:e,source:r.label,line:r.partial.toString("utf8").replace(/\r$/,"")}),r.partial=Buffer.alloc(0);return this.lines}};import{spawn as s0}from"node:child_process";import{cpus as pf,freemem as a0,totalmem as c0}from"node:os";var u0=1e3,fu=90;function l0(t,e){let r=0,n=0;return e.forEach((o,i)=>{let s=t[i];if(!s)return;let a=u=>o.times[u]-s.times[u],c=a("user")+a("nice")+a("sys")+a("idle")+a("irq");r+=c-a("idle"),n+=c}),n>0?Math.round(r/n*1e3)/10:0}function p0(t){let[e,r,n]=t.trim().split(",").map(Number);return e!==void 0&&r!==void 0&&n!==void 0&&[e,r,n].every(Number.isFinite)?{epochMs:e,cpuMs:r,rss:n}:null}function d0(t,e,r){let n=e.epochMs-t.epochMs;return!(n>0)||!(r>0)?0:Math.max(0,Math.min(100,Math.round((e.cpuMs-t.cpuMs)/n/r*1e3)/10))}function df(t,e){let r=[];for(let{epochMs:n,...o}of t){let i=e.spans?.length?po(n,e.spans):(n-e.startMs)/1e3;i===null||i<0||i>e.endSec||r.push({t:Math.round(i*1e3)/1e3,...o})}return r}function Tn(t,e){let r=t.filter(u=>u.cpu!==void 0),n=t.filter(u=>u.rssMB!==void 0),o=u=>r.length?u.cpu??0:u.sysCpu,i=[],s=null,a=0;for(let u of t)o(u)>=fu?(s??=u.t,a=u.t):s!==null&&(a-s>=2&&i.push({start:s,end:a}),s=null);s!==null&&a-s>=2&&i.push({start:s,end:a});let c=u=>Math.round(u*10)/10;return{samples:t.length,peakSysCpu:c(Math.max(0,...t.map(u=>u.sysCpu))),...r.length?{peakCpu:c(Math.max(...r.map(u=>u.cpu)))}:{},...n.length?{peakRssMB:c(Math.max(...n.map(u=>u.rssMB))),rssGrowthMB:c(n.at(-1).rssMB-n[0].rssMB)}:{},busy:i,...e?{process:e}:{}}}function mf(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
317
303
|
`)+(t.length?`
|
|
318
|
-
`:"")}function
|
|
319
|
-
${s.message}`}),{head:()=>r,tail:()=>n,outputAt:()=>o}}function
|
|
304
|
+
`:"")}function An(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function xt(t){return t.replace(/\.[^./\\]+$/,"")+".perf.jsonl"}function m0(t,e,r){return`$ErrorActionPreference='SilentlyContinue';while($true){$p=Get-Process -Id ${t};if(-not $p -or -not (Get-Process -Id ${e})){break};$t=[DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds();[Console]::Out.WriteLine("$t,$($p.TotalProcessorTime.TotalMilliseconds),$($p.WorkingSet64)");[Console]::Out.Flush();Start-Sleep -Milliseconds ${r}}`}var _s=class{constructor(e,r=u0){this.pid=e;this.intervalMs=r}pid;intervalMs;samples=[];timer=null;child=null;proc={};start(){let e=pf(),r=e.length||1;if(this.pid!==void 0){this.child=s0("powershell",["-NoProfile","-NonInteractive","-Command",m0(this.pid,process.pid,this.intervalMs)],{stdio:["ignore","pipe","ignore"],windowsHide:!0}),this.child.on("error",()=>{this.child=null});let n=null,o="";this.child.stdout?.on("data",i=>{o+=i.toString();let s=o.split(/\r?\n/);o=s.pop()??"";for(let a of s){let c=p0(a);c&&(n&&(this.proc={cpu:d0(n,c,r),rssMB:Math.round(c.rss/1048576)}),n=c)}})}this.timer=setInterval(()=>{let n=pf(),o=c0();this.samples.push({epochMs:Date.now(),sysCpu:l0(e,n),sysMem:o>0?Math.round((o-a0())/o*1e3)/10:0,...this.proc}),e=n},this.intervalMs),this.timer.unref()}stop(){return this.timer&&clearInterval(this.timer),this.timer=null,this.child?.kill(),this.child=null,this.samples}};import{spawn as f0}from"node:child_process";import{mkdirSync as h0,rmSync as ff}from"node:fs";function hu(t,e){let r="",n="",o=null,i=new Ni(()=>({sessionId:e}));return t.stderr?.on("data",s=>{let a=s.toString();n=(n+a).slice(-2e3),r.length<8e3&&(r+=a),o===null&&/Output #0/.test(r)&&(o=Date.now()),i.feed(a)}),t.on("error",s=>{n+=`
|
|
305
|
+
${s.message}`}),{head:()=>r,tail:()=>n,outputAt:()=>o}}function Io(t,e=6){return t.tail().trim().split(`
|
|
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 gu(t,e,r){return new Promise(n=>{let o=setTimeout(()=>n("running"),r==="wgc"?15e3:r==="ddagrab"?2e3:1200);r==="wgc"&&t.stderr?.on("data",()=>{sn(e.head())!==null&&(clearTimeout(o),n("running"))}),t.on("error",()=>{clearTimeout(o),n("exited")}),t.on("exit",()=>{clearTimeout(o),n("exited")})})}function bu(t,e,r){let n=sn(t.head());return n!==null?n:e==="ddagrab"?t.outputAt()??r:r}function wu(t,e,r,n){r.on("exit",o=>{let i=t.getChild(e);if(i&&i!==r)return;t.detachChild(e,r),pd(e)||Hi(e);let s=t.get(e);if(!s||s.status!=="recording"||t.isStopping(e))return;let a=mm({code:o,backend:n.backend,maxDurationSec:n.maxDurationSec,elapsedMs:Date.now()-n.spawnedAt});or(a.status==="failed"?"error":"notice",a.status==="failed"?`Recording ${e} failed: the recorder exited with code ${o}.`:`Recording ${e} ended on its own (${a.endReason}).`,{sessionId:e,...a}),t.tryUpdate(e,{...a,stoppedAt:new Date().toISOString(),...a.status==="failed"?{error:`${n.backend==="wgc"?"The window recorder":"ffmpeg"} exited with code ${o}:
|
|
308
|
+
${Io(n.watch)}`}:{}}),s.segments&&(s.segments.parts.length>0||s.webcam)?b0(t,s).catch(c=>{process.stderr.write(`Joining ${e}'s segments failed: ${U(c)}
|
|
309
|
+
`)}):g0(t,s).catch(c=>{process.stderr.write(`Reading ${e}'s duration failed: ${U(c)}
|
|
310
|
+
`)})})}async function g0(t,e){let{ffprobe:r}=k(),n=await se(e.outputPath,{ffprobe:r});n!==null&&t.tryUpdate(e.id,{durationSec:n})}async function b0(t,e){let r=k();await Kt(e.id);let{patch:n,error:o}=await Yc(e,r),i=await se(e.outputPath,{ffprobe:r.ffprobe});t.tryUpdate(e.id,{...n,durationSec:i??void 0,...o?{error:o}:{}})}function hf(t,e,r){return os(t,e.id,"resume",()=>w0(t,t.get(e.id)??e,r))}async function w0(t,e,r){let n=ud(e,t.ownsPaused(e.id));if(n)throw new l(`Cannot resume ${e.id}: ${n}.`);let o=e.segments,i=e.capture,s=e.backend??"gdigrab",a=rt(o.parts),c=ad(e.maxDurationSec,a),u=o.parts.length,d=sd(e.outputPath,u),p=i.webcam?Ui(e.outputPath,u):void 0;(u>0||p)&&h0(bt(e.outputPath),{recursive:!0});let f=Ei(i.target,{...i.opts,output:d,maxDurationSec:c,...i.webcam&&p?{webcam:{...i.webcam,output:p}}:{}}),m=Date.now(),h=f0(r,f,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),b=hu(h,e.id),w=()=>{let C=t.getChild(e.id);C&&C!==h||(u>0&&ff(d,{force:!0}),p&&ff(p,{force:!0}))};if(await gu(h,b,s)==="exited")throw w(),new l(`Resume failed (ffmpeg exited immediately); the recording stays paused:
|
|
311
|
+
${Io(b)}`);let g=bu(b,s,m),y=p?sn(b.head(),i.opts.audio?2:1):null;t.attachChild(e.id,h);let $=()=>{t.detachChild(e.id,h),h.pid!==void 0&&lr(h.pid),w()},S;try{S=t.update(e.id,{status:"recording",pid:h.pid??null,pidSpawnedAt:m,videoStartMs:g-a*1e3,segments:{parts:o.parts,current:{path:d,startMs:g,...p?{webcamPath:p,...y!==null?{webcamStartMs:y}:{}}:{}}}})}catch(C){throw $(),new l(`Resume stopped: the session registry could not be written (${U(C)}).`)}if(!S)throw $(),new l(`No session with id "${e.id}".`);return t.clearPaused(e.id),wu(t,e.id,h,{backend:s,maxDurationSec:c,spawnedAt:m,watch:b}),{record:S,recordedSec:a,capSec:c}}import{basename as wf,join as xu}from"node:path";var $0={target:oe.string().describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | region:<x>,<y>,<w>,<h>. With gdigrab a window's rectangle is resolved once at start (visible, on top); it does not follow the window."),exactTitle:oe.boolean().optional().describe("window: targets match the whole title only, never a substring (default false)."),fps:oe.number().int().min(1).max(120).optional().describe(`Frames per second (default ${vi}).`),quality:oe.enum(["draft","standard","high"]).optional().describe(`Encoder preset (default ${$i}).`),audio:oe.object({source:oe.enum(["system","none"]).describe("system = what the machine plays (needs a loopback device); none = video only."),device:oe.string().optional().describe("dshow loopback device (from list_audio_devices); auto-detected if omitted.")}).optional().describe("Audio (default none). No microphone capture."),output:oe.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:oe.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),maxDurationSec:oe.number().int().min(0).max(Ct).optional().describe(`Auto-stop after this many seconds (default ${xc} or SCREENCAST_MAX_RECORDING_SEC; max 7 days; 0 = no cap).`),events:oe.boolean().optional().describe("Also log clicks, scroll, cursor, and typing (video-timed, video pixels) for read_events (default false; ~1 s slower start)."),keys:oe.enum(["masked","shortcuts"]).optional().describe("With events: masked (default) logs typing only as 0.5 s-grid bursts, never keys; shortcuts also names Ctrl/Alt/Win chords. Typed text is never logged."),focus:oe.enum(["app","title"]).optional().describe("Log app switches (implies events); title adds window titles."),logs:oe.array(oe.object({path:oe.string().min(1),label:oe.string().min(1).max(40).optional()})).min(1).max(cf).optional().describe("Log files to follow onto the video clock."),perf:oe.boolean().optional().describe("Sample CPU/memory (and a window's app) to <rec>.perf.jsonl."),hotkeys:oe.boolean().optional().describe("Ctrl+Alt+Shift+M adds a marker, +S stops (implies events)."),elements:oe.boolean().optional().describe('Name the UI element each click hits, e.g. "Save" button (implies events).'),cursor:oe.enum(["os","events"]).optional().describe("events: leave the OS cursor out and log it (implies events) for the cursor tool to redraw."),backend:oe.enum(["gdigrab","wgc","ddagrab"]).optional().describe("gdigrab (default): the screen rectangle. wgc (window: targets, FFmpeg 8+): the window's own surface, even when covered or moved; client area only. ddagrab: one display on the GPU, low CPU."),encoder:oe.enum(["auto","x264","nvenc","qsv","amf"]).optional().describe("auto = first working GPU encoder, else x264 (default with ddagrab; else x264)."),webcam:oe.object({device:oe.string().optional().describe("list_video_devices name (default: first)."),corner:oe.enum(["top_left","top_right","bottom_left","bottom_right"]).optional(),size:oe.number().min(.1).max(.5).optional().describe("Share of width (0.25)."),shape:oe.enum(["rect","circle"]).optional()}).optional().describe("Also record a camera to <output>.webcam.mp4, aligned for overlay."),replayBufferSec:oe.number().int().min(Xi).max(yn).optional().describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab or ddagrab, not wgc."),startWhen:oe.object({window:oe.string().min(1).optional().describe('A window: target that must exist, e.g. "window:Error".'),text:oe.string().min(1).max(200).optional().describe("Text that must be on target (OCR)."),timeoutSec:oe.number().positive().max(tf).optional().describe(`Default ${au}.`)}).optional().describe("Arm: start once these hold (stop_recording disarms)."),stopWhen:oe.object({text:oe.string().min(1).max(200)}).optional().describe("Stop once this text shows (OCR).")};async function yf(t,e,r){let n=await at(t,{exactTitle:e}),o=S0(xu(v0(),"screencast-trigger-"));try{let i=xu(o,"t.png");await Nt(n,i);let[s]=await ct([i],o);return!!s&&yt(s.lines,r).length>0}finally{yu(o,{recursive:!0,force:!0})}}async function k0(t){try{return await at(t.startsWith("window:")?t:`window:${t}`),!0}catch{return!1}}var xf=new WeakSet;function E0(t,e){try{let r=Ti(t,e);return{width:r.w,height:r.h}}catch{return}}function _0(t,e){let r=sn(t.head(),e?2:1);return r!==null?{webcamStartMs:r}:{}}var Su=class{output;webcamRaw;replay;evPaths;logger;child;owned=!0;handOff(){this.owned=!1}async release(){this.owned&&(this.owned=!1,this.child?.pid!==void 0&&this.child.exitCode==null&&lr(this.child.pid),this.logger&&await wi(this.logger),this.evPaths&&yu(this.evPaths.raw,{force:!0}),this.replay&&Ji(this.replay),this.webcamRaw&&this.output&&yu(bt(this.output),{recursive:!0,force:!0}))}};async function T0(t,e){let r=e.encoder!=="x264",n={fps:t.fps,quality:t.quality,monitors:t.monitors,audio:t.audio,drawMouse:!t.hideCursor,...t.dda?{videoInput:tm(t.dda,t.fps,{download:!e.gpuFrames,drawMouse:!t.hideCursor})}:{},...r?{videoCodec:ur(e.encoder,t.quality,{gpuFrames:e.gpuFrames})}:{}},o=t.webcamDevice?{device:t.webcamDevice,...r?{codec:ur(e.encoder,t.quality)}:{}}:void 0,i=Ei(t.target,{...n,output:t.output,maxDurationSec:t.maxDurationSec,...o&&t.webcamRaw?{webcam:{...o,output:t.webcamRaw}}:{}}),s=t.replay?Wd(i,t.replay):i,a=Date.now(),c=t.backend==="wgc"?gf(process.execPath,[Dm(),JSON.stringify({ffmpeg:t.ffmpeg,hwnd:t.window.hwnd,fps:t.fps,encode:[...ur(e.encoder,t.quality),...Si(t.fps)],output:t.output,maxDurationSec:t.maxDurationSec,cursor:!t.hideCursor,...t.audio?{audioDevice:t.audio.device}:{}})],{stdio:["pipe","ignore","pipe"],windowsHide:!0}):gf(t.ffmpeg,s,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),u=hu(c,t.id),d=await gu(c,u,t.backend);return{captureOpts:n,webcam:o,child:c,watch:u,spawnedAt:a,settled:d}}function A0(t,e,r){if(r.replay){let o=new Promise(i=>r.child.once("exit",()=>i()));fo(e,o.then(()=>wi(r.logger)));return}let n=r.frame;n&&fo(e,ko(e).then(async()=>{await wi(r.logger);try{let o=zi(t.get(e)?.segments,r.startMs,Date.now()),i=cp(r.evPaths,{...o,frame:n});t.tryUpdate(e,{events:{path:r.evPaths.jsonl,keys:r.keyMode,count:i.length,summary:an(i)}})}catch(o){t.tryUpdate(e,{events:{path:r.evPaths.jsonl,keys:r.keyMode,error:U(o)}})}}).catch(o=>{process.stderr.write(`Event log for ${e} failed: ${U(o)}
|
|
312
|
+
`)}))}function R0(t,e,r){let n=new _s(r.window?.pid);n.start();let o=xt(r.output);t.tryUpdate(e,{perf:{path:o}}),fo(e,ko(e).then(async()=>{try{let i=df(n.stop(),zi(t.get(e)?.segments,r.startMs,Date.now()));bf(o,mf(i));let s=r.window?.pid!==void 0?{pid:r.window.pid,...r.window.exe?{exe:r.window.exe}:{}}:void 0;t.tryUpdate(e,{perf:{path:o,summary:Tn(i,s)}})}catch(i){n.stop(),t.tryUpdate(e,{perf:{path:o,error:U(i)}})}}))}function M0(t,e,r){r.tailer.follow();let n=Lt(r.output),o=r.logs.map(i=>i.label??wf(i.path));t.tryUpdate(e,{logs:{path:n,sources:o}}),fo(e,ko(e).then(async()=>{try{let i=uf(await r.tailer.stop(),zi(t.get(e)?.segments,r.startMs,Date.now()));bf(n,lf(i)),t.tryUpdate(e,{logs:{path:n,sources:o,count:i.length,errors:i.filter(s=>s.level==="error").length}})}catch(i){t.tryUpdate(e,{logs:{path:n,sources:o,error:U(i)}})}}))}function Sf(t,e,r){let n=t.get(e);if(!n||n.status!=="recording"&&n.status!=="paused")return;let{ffprobe:o}=k();To(t,n,{reason:"stopped",probe:i=>se(i,{ffprobe:o})}).catch(i=>process.stderr.write(`${r} stop for ${e} failed: ${U(i)}
|
|
313
|
+
`))}function C0(t,e){return r=>{let n=t.get(e);if(!(!n||n.status!=="recording"&&n.status!=="paused")){if(r==="stop")return Sf(t,e,"Hotkey");try{ms(t,e,"hotkey")}catch(o){process.stderr.write(`Hotkey marker for ${e} failed: ${U(o)}
|
|
314
|
+
`)}}}}function P0(t,e,r){let n=new AbortController;ko(e).then(()=>n.abort()),pu({checks:[()=>yf(r.target,r.exactTitle,r.text)],timeoutMs:Number.POSITIVE_INFINITY,intervalMs:cu,signal:n.signal}).then(o=>{o==="met"&&Sf(t,e,"stopWhen")})}async function I0(t,e,r,n){try{let o=r.startWhen;if(!o.window&&!o.text)throw new l("startWhen needs window and/or text.");let i=o.timeoutSec??au,s={...o.window?{window:o.window}:{},...o.text?{text:o.text}:{}};await at(r.target,{exactTitle:r.exactTitle,backend:r.backend}),await Ot(t,`When ${lu(s)} (within ${i} s), start recording ${Ft(r.target)}`+(r.events?", logging mouse clicks and typing":"")+"?",n.signal);let a={...r,startWhen:void 0};xf.add(a);let c=sf({conditions:s,target:r.target,timeoutSec:i,checks:[...o.window?[()=>k0(o.window)]:[],...o.text?[()=>yf(r.target,r.exactTitle,o.text)]:[]],fire:async()=>{let u=e.handler,d=await u(a,{...n,signal:new AbortController().signal}),p=d.structuredContent;if(d.isError||!p?.sessionId)throw new Error(d.content.map(f=>f.text??"").join(" ")||"start failed");return p.sessionId}});return v({sessionId:c.id,status:"armed",backend:r.backend??"gdigrab",outputPath:"",waitingFor:lu(s),timeoutSec:i,note:"Nothing is recorded yet. get_session with this id shows when it starts (and its recording's sessionId); stop_recording with it disarms."})}catch(o){return E(o)}}async function F0(t,e,r){let{ffmpeg:n}=k(),o=e.cursor==="events";(o||e.focus||e.elements||e.hotkeys)&&(e.events=!0);let{target:i,monitors:s,window:a}=await at(e.target,{exactTitle:e.exactTitle,backend:e.backend}),c=e.backend??"gdigrab";vd({backend:c,systemAudio:e.audio?.source==="system",replay:e.replayBufferSec!==void 0,webcam:!!e.webcam,logs:!!e.logs,perf:!!e.perf},{windowHwnd:!!a?.hwnd,wgcAvailable:c==="wgc"&&ir()});let u=e.replayBufferSec!==void 0?Ld(e.replayBufferSec):null,d=e.fps??vi,p=e.quality??$i,f=yp(e.maxDurationSec),m=er(e.output,we("recordings"),`rec-${ge()}-${be()}.mp4`,e.overwrite),h=e.audio?.source==="system"?{device:await jm(e.audio.device)}:void 0,b=e.webcam?await Bm(e.webcam.device):void 0,w=c==="ddagrab"?em(Ti(i,s),await Zd()):null;if(!xf.has(e)){let $=$d({target:Ft(e.target,a),replayBufferSec:u?.bufferSec,maxDurationSec:f,audioDevice:h?.device,webcamDevice:b,events:!!e.events,focus:e.focus,elements:e.elements,hotkeys:e.hotkeys,output:m});await Ot(t,$,r.signal)}let g=await Kd(e.encoder??(c==="ddagrab"?"auto":"x264"),c==="ddagrab"?"ddagrab":"gdigrab",n,void 0,c==="wgc"?void 0:E0(i,s)),y=async $=>!w||$.gpuFrames||await Qd(n);if(!await y(g))throw new l("Desktop Duplication (ddagrab) does not capture on this machine (a remote session, or no D3D11 GPU).",'Use backend "gdigrab".');return{ffmpeg:n,hideCursor:o,target:i,monitors:s,window:a,backend:c,replay:u,fps:d,quality:p,maxDurationSec:f,output:m,audio:h,webcamDevice:b,dda:w,firstPick:g,ddaUsable:y}}function O0(t,e,r){let{target:n,monitors:o,window:i,backend:s,output:a,fps:c,quality:u,maxDurationSec:d,replay:p,audio:f,webcamDevice:m}=e,h=bu(r.watch,s,r.spawnedAt),b=t.events?Ti(n,o):null;if(s==="wgc"&&b&&i?.client){let g=/wgc: (\d+)x(\d+)/.exec(r.watch.head());b={x:i.client.x,y:i.client.y,w:g?Number(g[1]):b.w,h:g?Number(g[2]):b.h}}let w=kd({id:r.id,target:t.target,output:a,fps:c,quality:u,pid:r.child.pid??null,spawnedAt:r.spawnedAt,startMs:h,maxDurationSec:d,window:i,backend:s,encoder:r.encoder,...r.evPaths?{events:{jsonl:r.evPaths.jsonl,raw:r.evPaths.raw,keys:r.keyMode,frame:b}}:{},...p?{replay:p}:{},...s!=="wgc"?{capture:{target:n,opts:r.captureOpts,...r.webcam?{webcam:r.webcam}:{}}}:{},...m&&r.webcamRaw?{webcam:{device:m,rawPath:r.webcamRaw,startMs:_0(r.watch,!!f).webcamStartMs,corner:t.webcam?.corner,size:t.webcam?.size,shape:t.webcam?.shape}}:{},processImage:s==="wgc"?wf(process.execPath).toLowerCase():"ffmpeg.exe",identity:um()});return{startMs:h,frame:b,record:w}}function N0(t,e,r){t.attachChild(e.id,r);try{t.create(e)}catch(n){throw t.detachChild(e.id),new l(`Recording stopped: the session registry could not be written (${U(n)}).`)}}function vf(t){let e=t.registerTool("start_recording",{title:"Start Recording",description:"Start a background screen recording. Returns a session id; finalize it with stop_recording. Never auto-starts.",inputSchema:$0,outputSchema:N({sessionId:oe.string(),status:oe.string(),backend:oe.string(),outputPath:oe.string()}),annotations:I},async(r,n)=>{if(r.startWhen)return I0(t,e,r,n);let o=()=>{},i=new Su;try{o=Gm();let s=await F0(t,r,n),{ffmpeg:a,hideCursor:c,target:u,monitors:d,window:p,backend:f,replay:m,fps:h,quality:b,maxDurationSec:w,output:g,audio:y,webcamDevice:$,dda:S,firstPick:C,ddaUsable:M}=s;i.output=g,$&&(i.webcamRaw=Ui(g,0),x0(bt(g),{recursive:!0})),m&&(jd(m),i.replay=m);let R=r.keys??tp,P=r.events?m?{raw:xu(m.dir,"events.raw"),jsonl:""}:$e(g):null;P&&!m&&yi(P,r.overwrite),i.evPaths=P;let j=r.logs?new ks(r.logs):null;await j?.mark();let X=()=>{};i.logger=P?await op(P.raw,R,{...m?{rotateSec:Nd(m.bufferSec)}:{},...r.focus?{focus:r.focus}:{},...r.elements?{elements:!0}:{},...r.hotkeys?{hotkeys:!0,onHotkey:z=>X(z)}:{}}):null;let D=`rec-${ge()}-${be(6)}`,ae={id:D,ffmpeg:a,backend:f,target:u,monitors:d,window:p,fps:h,quality:b,audio:y,hideCursor:c,dda:S,webcamDevice:$,webcamRaw:i.webcamRaw,output:g,maxDurationSec:w,replay:m},ee=await Vd(C,z=>T0(ae,z),{why:z=>Io(z.watch,3),canFallback:()=>M({encoder:"x264",gpuFrames:!1}),beforeRetry:()=>{m&&Ud(m)}}),{run:J,failure:ie,pick:ce}=ee,{child:x,watch:q,spawnedAt:H,captureOpts:de,webcam:G}=J;if(J.settled==="exited")throw new l(`Recording failed to start (${f==="wgc"?"window capture":"ffmpeg"} exited immediately):
|
|
315
|
+
${Io(q)}`+(ie?`
|
|
316
|
+
(Retried with libx264 after ${ie})`:""));i.child=x;let{startMs:Q,frame:te,record:T}=O0(r,s,{id:D,child:x,watch:q,spawnedAt:H,captureOpts:de,webcam:G,encoder:ce.encoder,evPaths:P,keyMode:R,webcamRaw:i.webcamRaw}),_=re();N0(_,T,x),i.handOff();let A=i.logger;return A&&P&&A0(_,D,{logger:A,evPaths:P,keyMode:R,startMs:Q,frame:te,replay:m,child:x}),wu(_,D,x,{backend:f,maxDurationSec:w,spawnedAt:H,watch:q}),r.perf&&R0(_,D,{output:g,startMs:Q,window:p}),j&&r.logs&&M0(_,D,{tailer:j,logs:r.logs,output:g,startMs:Q}),r.hotkeys&&(X=C0(_,D)),r.stopWhen&&P0(_,D,{target:r.target,exactTitle:r.exactTitle,text:r.stopWhen.text}),v(Ed({record:T,audioDevice:y?.device,maxDurationSec:w,encoder:ce.encoder,encoderNote:ce.note,...S?{gpuFrames:ce.gpuFrames}:{},webcamDevice:$,window:p,...P?{events:{jsonl:P.jsonl,keys:R}}:{},...r.logs?{logs:{path:Lt(g),missing:r.logs.some(z=>!y0(z.path))}}:{},...r.hotkeys?{hotkeys:{taken:A?sp(A):[]}}:{},...m?{replay:{...m,events:!!P}}:{}}))}catch(s){return await i.release(),E(s)}finally{o()}})}import{z as Rn}from"zod";import{existsSync as Ts}from"node:fs";function $f(t){return{saved:t.saved,discarded:t.discarded,...t.save?{durationSec:t.save.durationSec,eventsPath:t.save.eventsPath}:{},...t.error?{error:t.error,note:"The buffer was kept; call stop_recording with save: true again, or save_replay."}:{}}}async function D0(t,e){if(t.error||!Ts(t.path))return{error:t.error??`No webcam file was written (${t.path}).`};let r=async a=>{try{let c=await L(a);return c.width&&c.height?{width:c.width,height:c.height}:null}catch{return null}},[n,o]=await Promise.all([r(e),r(t.path)]),i=t.shape==="circle",s=n&&o?hd(n,i?{width:1,height:1}:o,t.corner,t.size):null;return{path:t.path,...s?{overlay:{input:e,overlay:t.path,x:s.x,y:s.y,...i?{height:s.height,shape:"circle"}:{width:s.width}},note:"Aligned with the recording: pass `overlay` to the overlay tool (any corner or size works)."}:{}}}var L0={sessionId:Rn.string().min(1).describe("Session id returned by start_recording."),save:Rn.boolean().optional().describe("Replay buffer: write it all to outputPath first (default: discard).")};function kf(t){t.registerTool("stop_recording",{title:"Stop Recording",description:"Stop a recording gracefully so the file is finalized; returns the path and duration.",inputSchema:L0,outputSchema:N({sessionId:Rn.string(),status:Rn.string(),outputPath:Rn.string(),durationSec:Rn.number().nullable()}),annotations:Gi},async e=>{try{let r=re(),n=e.sessionId;if($s(n)){let f=Po(n);if(!f)throw new l(`No armed recording with id "${n}".`);f.status==="starting"&&(f=await nf(n)??f);let m={sessionId:n,outputPath:"",durationSec:null};if(uu(n))return v({...m,status:"cancelled",note:"Disarmed; nothing was recorded."});if(!f.sessionId)return v({...m,status:f.status,...f.error?{error:f.error}:{}});n=f.sessionId}let o=r.get(n);if(!o)throw new l(`No session with id "${e.sessionId}".`);if(o.status!=="recording"&&o.status!=="paused"){let f=o.replay&&Ts(o.replay.dir)?await Ki(o.replay,{save:e.save??!1,output:o.outputPath,quality:o.quality,tools:k}):void 0,m=o.durationSec??null;return m===null&&!o.segments?.parts.length&&Ts(o.outputPath)&&(m=await se(o.outputPath,{ffprobe:k().ffprobe}).catch(()=>null),m!==null&&r.tryUpdate(o.id,{durationSec:m})),v({...f?{replay:$f(f)}:{},sessionId:o.id,status:o.status,outputPath:o.outputPath,durationSec:m,endReason:o.endReason??null,note:o.endReason==="max_duration"?`Recording already ended at its maxDurationSec cap (${o.maxDurationSec}s).`:o.endReason==="window_closed"?"Recording already ended: the recorded window was closed.":"Session was not active; returning its recorded final state."})}let i=cm(o,process.pid,Gc(o));if(i)throw new l(i);let{ffprobe:s}=k(),{record:a,graceful:c,durationSec:u,replay:d,segments:p}=await To(r,o,{reason:"stopped",probe:f=>se(f,{ffprobe:s}),saveReplay:e.save});return v({sessionId:o.id,status:"stopped",outputPath:o.outputPath,durationSec:u??null,finalizedGracefully:c,...d?{replay:$f(d)}:{},...p&&p.count>1?{segmentsJoined:p.count}:{},...p?.error?{segmentsError:p.error}:{},...a?.webcam?{webcam:await D0(a.webcam,o.outputPath)}:{},...a?.events?{eventsPath:a.events.path,events:a.events.summary??{},...a.events.error?{eventsError:a.events.error}:{}}:{},fileExists:Ts(o.outputPath),note:c?"ffmpeg quit cleanly; file finalized.":"Process terminated by pid; fragmented mp4 keeps the file playable.",record:a})}catch(r){return E(r)}})}import{z as hr}from"zod";import{existsSync as jo,lstatSync as uh,readdirSync as lh,rmSync as I$,statSync as F$}from"node:fs";import{dirname as O$,resolve as ph}from"node:path";import{createHash as Uf}from"node:crypto";import{closeSync as f$,existsSync as Mn,openSync as h$,readFileSync as g$,readdirSync as b$,readSync as w$,renameSync as y$,statSync as zf,writeFileSync as x$}from"node:fs";import{basename as Hf,dirname as S$,join as Cn,resolve as Ds}from"node:path";import{closeSync as G0,existsSync as ku,openSync as q0,readSync as X0,statSync as J0}from"node:fs";import{basename as Rs,isAbsolute as Y0,join as Eu}from"node:path";function St(t,e,r){if(t.length<e)throw new Error(`Truncated font: ${r}.`);return t}function B0(t,e){let r=St(t(0,12),12,"header");if(r.toString("latin1",0,4)!=="ttcf"){if(e!==0)throw new Error("Not a font collection; only face 0 exists.");return 0}let n=r.readUInt32BE(8);if(e<0||e>=n)throw new Error(`Face ${e} is out of range (collection has ${n}).`);return St(t(12+e*4,4),4,"collection offsets").readUInt32BE(0)}var As=class{ranges=[];add(e,r){let n=this.ranges[this.ranges.length-1];n&&e<=n[1]+1?n[1]=Math.max(n[1],r):this.ranges.push([e,r])}};function W0(t){let e=St(t,14,"cmap format 4").readUInt16BE(6),r=14,n=r+e+2,o=n+e,i=o+e;St(t,i+e,"cmap format 4 segments");let s=new As;for(let a=0;a<e/2;a++){let c=t.readUInt16BE(r+a*2),u=t.readUInt16BE(n+a*2),d=t.readUInt16BE(o+a*2),p=t.readUInt16BE(i+a*2);if(!(u>c))for(let f=u;f<=c&&f!==65535;f++){let m;if(p===0)m=f+d&65535;else{let h=i+a*2+p+(f-u)*2;m=h+2<=t.length?t.readUInt16BE(h):0,m!==0&&(m=m+d&65535)}m!==0&&s.add(f,f)}}return s.ranges}function j0(t,e){let r=St(t,16,`cmap format ${e}`).readUInt32BE(12);St(t,16+r*12,`cmap format ${e} groups`);let n=[];for(let i=0;i<r;i++){let s=t.readUInt32BE(16+i*12),a=Math.min(t.readUInt32BE(20+i*12),1114111);if(t.readUInt32BE(24+i*12)===0){if(e===13)continue;s++}s<=a&&n.push([s,a])}n.sort((i,s)=>i[0]-s[0]);let o=new As;for(let[i,s]of n)o.add(i,s);return o.ranges}function U0(t,e){return t===3&&e===10?0:t===0&&(e===4||e===6)?1:t===3&&e===1?2:t===0&&e<=3?3:-1}function Ef(t,e=0){let r=B0(t,e),n=St(t(r,12),12,"sfnt header"),o=n.toString("latin1",0,4);if(o!=="\0\0\0"&&o!=="OTTO"&&o!=="true")throw new Error("Not a TrueType/OpenType font.");let i=n.readUInt16BE(4),s=St(t(r+12,i*16),i*16,"table directory"),a=-1;for(let f=0;f<i;f++)s.toString("latin1",f*16,f*16+4)==="cmap"&&(a=s.readUInt32BE(f*16+8));if(a<0)throw new Error("Font has no cmap table.");let u=St(t(a,4),4,"cmap header").readUInt16BE(2),d=St(t(a+4,u*8),u*8,"cmap records"),p=[];for(let f=0;f<u;f++){let m=U0(d.readUInt16BE(f*8),d.readUInt16BE(f*8+2));m>=0&&p.push({rank:m,offset:a+d.readUInt32BE(f*8+4)})}p.sort((f,m)=>f.rank-m.rank);for(let{offset:f}of p){let m=t(f,8);if(m.length<8)continue;let h=m.readUInt16BE(0);if(h===4)return W0(t(f,m.readUInt16BE(2)));if(h===12||h===13)return j0(t(f,m.readUInt32BE(4)),h)}throw new Error("Font has no Unicode cmap subtable this reader understands (formats 4, 12, 13).")}function z0(t,e){let r=0,n=t.length-1;for(;r<=n;){let o=r+n>>1,[i,s]=t[o];if(e<i)n=o-1;else if(e>s)r=o+1;else return!0}return!1}function H0(t){return!(t<32||t>=127&&t<160||t===173||t===847||t===1564||t===65279||t>=8203&&t<=8207||t>=8234&&t<=8238||t>=8288&&t<=8303||t>=65024&&t<=65039||t>=917504&&t<=921599)}function Fo(t,e){let r=new Set,n=[];for(let o of t){let i=o.codePointAt(0);r.has(i)||(r.add(i),H0(i)&&!z0(e,i)&&n.push(o))}return n}var K0={regular:"Inter-Regular.ttf",bold:"Inter-Bold.ttf"};function Bt(t="bold"){return vn("fonts",K0[t])}function ye(t){return t.replace(/\\/g,"/").replace(/:/g,"\\\\:").replace(/'/g,"\\\\\\'").replace(/([,;[\]])/g,"\\$1")}var V0={segoe:{name:"Segoe UI",regular:["segoeui.ttf"],bold:["segoeuib.ttf","segoeui.ttf"]},japanese:{name:"Yu Gothic",regular:["YuGothM.ttc","meiryo.ttc","msgothic.ttc"],bold:["YuGothB.ttc","meiryob.ttc","YuGothM.ttc","msgothic.ttc"]},chineseSimplified:{name:"Microsoft YaHei",regular:["msyh.ttc","simsun.ttc"],bold:["msyhbd.ttc","msyh.ttc","simsun.ttc"]},chineseTraditional:{name:"Microsoft JhengHei",regular:["msjh.ttc","mingliub.ttc"],bold:["msjhbd.ttc","msjh.ttc"]},korean:{name:"Malgun Gothic",regular:["malgun.ttf"],bold:["malgunbd.ttf","malgun.ttf"]},indic:{name:"Nirmala UI",regular:["Nirmala.ttc","Nirmala.ttf"],bold:["NirmalaB.ttf","Nirmala.ttc","Nirmala.ttf"]},thai:{name:"Leelawadee UI",regular:["LeelawUI.ttf","tahoma.ttf"],bold:["LeelaUIb.ttf","LeelawUI.ttf","tahomabd.ttf"]},ethiopic:{name:"Ebrima",regular:["ebrima.ttf"],bold:["ebrimabd.ttf","ebrima.ttf"]},emoji:{name:"Segoe UI Emoji",regular:["seguiemj.ttf"],bold:["seguiemj.ttf"]},symbol:{name:"Segoe UI Symbol",regular:["seguisym.ttf"],bold:["seguisym.ttf"]}},Q0=["segoe","japanese","chineseSimplified","chineseTraditional","korean","indic","thai","ethiopic","emoji","symbol"];function Z0(t){let e=[];return/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9f]/u.test(t)&&e.push("japanese"),/[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]/u.test(t)&&e.push("korean"),new RegExp("\\p{Script=Han}","u").test(t)&&e.push("chineseSimplified"),[...e,...Q0.filter(r=>!e.includes(r))].map(r=>V0[r])}function e$(t,e){let r=null;for(let n of e){let o=Fo(t,n.coverage);if(o.length===0)return{fontFile:n.path,missing:o};(!r||o.length<r.missing.length)&&(r={fontFile:n.path,missing:o})}return r}function Tf(){return Eu(process.env.WINDIR??process.env.SystemRoot??"C:\\Windows","Fonts")}var _f=new Map;function vu(t){let e=_f.get(t);if(e!==void 0)return e;let r,n=null;try{n=q0(t,"r");let o=n;r=Ef((s,a)=>{let c=Buffer.alloc(a);return c.subarray(0,X0(o,c,0,a,s))})}catch{r=null}finally{n!==null&&G0(n)}return _f.set(t,r),r}function t$(t){if(ku(t)&&J0(t).isFile())return t;if(!Y0(t)&&Rs(t)===t){let e=Eu(Tf(),t);if(ku(e))return e}throw new l(`Font file not found: ${t}`,"Pass a path to a .ttf, .otf or .ttc file, or the file name of a font in C:\\Windows\\Fonts.")}function $u(t){let e=t.replace(/\s+/g," ").trim();return`"${e.length>40?`${e.slice(0,39)}\u2026`:e}"`}function vt(t,e={}){if(e.fontFile){let c=t$(e.fontFile),u=vu(c);if(!u)return{fontFile:c,missing:[],fallback:!1,warning:`Could not read the character map of ${Rs(c)}; glyph coverage of ${$u(t)} was not checked.`};let d=Fo(t,u);return d.length===0?{fontFile:c,missing:d,fallback:!1}:{fontFile:c,missing:d,fallback:!1,warning:`${Rs(c)} has no glyph for ${d.join(" ")} in ${$u(t)}; they render as empty boxes.`}}let r=e.weight??"bold",n=Bt(r),o=vu(n);if(o&&Fo(t,o).length===0)return{fontFile:n,missing:[],fallback:!1};let i=e.fontsDir??Tf(),s=o?[{path:n,coverage:o}]:[];for(let c of Z0(t))for(let u of c[r]){let d=Eu(i,u),p=ku(d)?vu(d):null;if(p){if(Fo(t,p).length===0)return{fontFile:d,missing:[],fallback:!0};s.push({path:d,coverage:p});break}}let a=e$(t,s)??{fontFile:n,missing:[]};return a.missing.length===0?{...a,fallback:a.fontFile!==n}:{...a,fallback:a.fontFile!==n,warning:`No available font draws ${a.missing.join(" ")} in ${$u(t)}; they render as empty boxes (drawn with ${Rs(a.fontFile)}). Pass fontFile with a font that covers them.`}}import{mkdtempSync as r$,rmSync as n$,writeFileSync as o$}from"node:fs";import{join as _u}from"node:path";import{tmpdir as i$}from"node:os";var Oo=12,Af=48,No=320;function Ms(t,e){if(!(t>0))throw new l("Could not read the video's duration.");return Array.from({length:e},(r,n)=>Math.round((n+.5)*t/e*1e3)/1e3)}function Fe(t){let e=Math.round(Math.max(0,t)*10),r=Math.floor(e/36e3),n=Math.floor(e%36e3/600),o=e%600/10;return r>0?`${r}:${String(n).padStart(2,"0")}:${String(Math.floor(o)).padStart(2,"0")}`:`${n}:${o.toFixed(1).padStart(4,"0")}`}function s$(t,e){let r=t<=4?t:Math.ceil(Math.sqrt(t)),n=Math.max(1,Math.min(t,e??r));return{columns:n,rows:Math.ceil(t/n)}}function a$(t,e,r,n,o,i){if(!Number.isInteger(n)||n<64)throw new l("tileWidth must be an integer of at least 64.");let s=Math.max(12,Math.round(n/16)),a=`drawtext=fontfile=${ye(o)}:textfile=${ye(i)}:expansion=none:fontcolor=white:fontsize=${s}:x=6:y=h-text_h-6:box=1:boxcolor=black@0.6:boxborderw=4`;return["-y","-v","error","-ss",String(e),"-i",t,"-frames:v","1","-vf",`scale=${n}:-2,${a}`,...Ee(r)]}function c$(t,e,r){return["-y","-v","error","-framerate","1","-i",t,"-vf",`tile=${e.columns}x${e.rows}:padding=4:margin=4:color=black`,"-frames:v","1",...Ee(r)]}function Rf(t,e,r,n){if(!(e>0))throw new l("Could not read the video's duration.");let o=30,i=Math.max(1e-4,o/e);return["-y","-v","error","-i",t,"-vf",`fps=${i.toFixed(4)},thumbnail=${o},scale='min(${n},iw)':-2`,"-frames:v","1",...Ee(r)]}async function Cs(t,e,r,n,o){let i=s$(e.length,n.columns),s=r$(_u(i$(),"screencast-sheet-"));try{let a=Bt("bold");await He(e,async(c,u)=>{let d=_u(s,`label_${u}.txt`);o$(d,Fe(c));let p=_u(s,`tile_${String(u).padStart(3,"0")}.png`);await Z(a$(t,c,p,n.tileWidth,a,d),6e4,{signal:o})}),await Z(c$(un(s,"tile_%03d.png"),i,r),6e4,{signal:o})}finally{n$(s,{recursive:!0,force:!0})}return i}import{existsSync as Ps}from"node:fs";var Mf=t=>Math.round(t*1e3)/1e3,u$={input_not_seen:"input went to an elevated window or the lock screen, or the hook was removed",helper_stalled:"the event logger paused",helper_stopped:"the event logger stopped"};function Tu(t){return t.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Au(t){let e=Tu(t.role),r=t.app?` in ${t.app}`:"";return t.name?`the "${t.name}" ${e}${r}`:`${/^[aeiou]/.test(e)?"an":"a"} ${e}${r}`}function Cf(t,e,r){let n=e?"double-click":"click",o=t&&t!=="left"?`${t.charAt(0).toUpperCase()}${t.slice(1)} ${n}`:`${n.charAt(0).toUpperCase()}${n.slice(1)}`;return r.element?.name?`${o} ${Au(r.element)}`:r.inFrame?`${o} at (${r.x}, ${r.y})`:`${o} outside the recorded area`}function Ru(t){let e=[],r=[...t].sort((s,a)=>s.t-a.t),n=null,o=null,i=(s,a)=>{let c=s==="vertical"?a>=0?"up":"down":a>=0?"right":"left",u=Math.abs(a);return`Scroll ${c} ${u} notch${u===1?"":"es"}`};for(let s of r)if(!(s.type==="move"||s.type==="up")){if(s.type!=="wheel"&&(o=null),s.type==="down"){let a=n;if(a&&a.e.button===s.button&&s.t-a.e.t<=.5&&Math.abs(s.x-a.e.x)<=6&&Math.abs(s.y-a.e.y)<=6&&a.step.action==="click"&&e.at(-1)===a.step){a.step.action="double_click",a.step.text=Cf(s.button,!0,a.e),n=null;continue}let c={t:s.t,action:"click",text:Cf(s.button,!1,s),x:s.x,y:s.y,button:s.button??"left",inFrame:s.inFrame,...s.element?{element:s.element}:{}};e.push(c),n={e:s,step:c};continue}if(n=null,s.type==="wheel"){let a=s.axis??"vertical",c=s.delta??0;if(o&&o.axis===a&&s.t-o.last<=1&&Math.sign(c)===Math.sign(o.notches)){o.notches+=c,o.last=s.t,o.step.text=i(a,o.notches);continue}let u={t:s.t,action:"scroll",text:i(a,c),x:s.x,y:s.y,inFrame:s.inFrame};e.push(u),o={step:u,axis:a,notches:c,last:s.t}}else if(s.type==="key")e.push({t:s.t,action:"shortcut",text:`Press ${s.keys??"a shortcut"}`,...s.keys?{keys:s.keys}:{}});else if(s.type==="typing"){let a=s.durationSec??0;e.push({t:s.t,action:"typing",text:`Type${a>0?` for ${Mf(a)} s`:""} (keys are not logged)`,durationSec:a})}else if(s.type==="focus"){let a=s.app??"another app";e.push({t:s.t,action:"switch",text:s.title?`Switch to "${s.title}" (${a})`:`Switch to ${a}`})}else if(s.type==="gap"){let a=u$[s.reason??"input_not_seen"],c=Mf(s.durationSec??0);e.push({t:s.t,action:"gap",text:`Input may be missing for ${c} s (${a})`,durationSec:c})}}return e}function Mu(t){return Ru(t).map(({button:e,inFrame:r,keys:n,durationSec:o,element:i,...s})=>s)}var Cu=30,Is=600,Pu=1,Fs=100,Iu=20,Ge=iu(["\\b(?:sk|pk|rk)-[a-z0-9_-]{8,}","\\bgh[pousr]_[a-z0-9]{10,}","\\bgithub_pat_[a-z0-9_]{10,}","\\bxox[abprs]-[a-z0-9-]{8,}","\\bAKIA[0-9A-Z]{12,}","\\bAIza[0-9a-z_-]{20,}","\\beyJ[a-z0-9_-]{8,}\\.[a-z0-9_-]{8,}","(?:api.?key|secret|token|passw(?:or)?d|bearer|authorization)\\s*[:=]?\\s*\\S+"].join("|")),Os=iu("error|exception|fail(?:ed|ure)?|fatal|crash|denied|refused|not found|cannot|can't|unable|invalid|timed? ?out|traceback|panic|unhandled|warning"),Wt={markdown:"report.md",json:"report.json",clip:"clip.mp4",contactSheet:"contact-sheet.png",gif:t=>`repro.${t}`},Do=t=>Math.round(t*1e3)/1e3;function If(t,e={}){if(!(t>0))throw new l("Could not read the recording's duration.");let r=Math.min(e.end??t,t),n=e.clipSec??Cu,o=e.start??Math.max(0,r-n);if(o>=t)throw new l(`start ${o}s is past the end of the ${Do(t)}s recording.`);if(!(r>o))throw new l("end must be after start.");if(r-o>Is)throw new l(`The clip would be ${Do(r-o)}s; at most ${Is}s. Narrow start/end.`);return{start:Do(o),end:Do(r)}}function l$(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),n=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);return r<=0||n<=0?!1:r*n>=.5*Math.min(t.width*t.height,e.width*e.height)}function Ff(t){let e=[];for(let r of[...t].sort((n,o)=>n.start-o.start)){let n=e.find(s=>r.start<=s.end&&l$(s,r));if(!n){e.push({...r});continue}let o=Math.min(n.x,r.x),i=Math.min(n.y,r.y);n.width=Math.max(n.x+n.width,r.x+r.width)-o,n.height=Math.max(n.y+n.height,r.y+r.height)-i,n.x=o,n.y=i,n.start=Math.min(n.start,r.start),n.end=Math.max(n.end,r.end)}return e}var p$="[REDACTED]";function Oe(t,e){if(t.length===0)return[];let r=$n(t,e);return t.map((n,o)=>{let i=[...r[o]??[]].sort((c,u)=>c[0]-u[0]),s="",a=0;for(let[c,u]of i)u<=a||(s+=n.slice(a,Math.max(a,c))+(c>=a?p$:""),a=u);return s+n.slice(a)})}function Of(t,e,r){let n=new Map;for(let a of t){let c=new Set(yt(a.lines,e,!0).map(u=>u.line));for(let u of c){let d=Dt(u),p=n.get(d);p?p.lastSeen=a.t:n.set(d,{text:u,firstSeen:a.t,lastSeen:a.t})}}let o=t.at(-1)?.t,i=[...n.values()].sort((a,c)=>+(c.lastSeen===o)-+(a.lastSeen===o)||a.firstSeen-c.firstSeen).slice(0,Iu);if(!r)return i;let s=Oe(i.map(a=>a.text),r);return i.map((a,c)=>({...a,text:s[c]??a.text}))}var d$=t=>`\`${t.replace(/`/g,"'").replace(/\s+/g," ").trim()}\``,Pf=t=>t.replace(/\|/g,"\\|").replace(/\s*\n\s*/g," ");function Nf(t){let e=[`# ${t.title.replace(/\s*\n\s*/g," ")}`,""],r=`${Fe(t.clip.start)}-${Fe(t.clip.end)}`;if(e.push(`Recorded repro: ${t.clip.width}x${t.clip.height}, clip ${r} of a ${Fe(t.clip.recordingDurationSec)} recording.`,""),(t.actual||t.expected)&&(t.actual&&e.push("**Actual:** "+t.actual.trim(),""),t.expected&&e.push("**Expected:** "+t.expected.trim(),"")),e.push("## Steps to reproduce",""),t.steps.length===0?e.push(`_${t.stepsNote??"No input events in the recording."} Add the steps by hand._`,""):(e.push("From the recording's input event log; times are on the recording's clock, positions in video pixels.",""),t.steps.forEach((i,s)=>e.push(`${s+1}. \`${Fe(i.t)}\` ${i.text}`)),t.stepsOmitted&&e.push("",`_${t.stepsOmitted} more steps not shown (see report.json)._`),e.push("")),e.push("## Error text on screen",""),t.ocr!=="read")e.push("_Not read: Windows OCR is unavailable here._","");else if(t.errors.length===0)e.push("_None found by OCR in the clip._","");else{e.push("Read by OCR (best-effort, may contain misreads); times from the clip start.","");for(let i of t.errors){let s=i.firstSeen===i.lastSeen?Fe(i.firstSeen):`${Fe(i.firstSeen)}-${Fe(i.lastSeen)}`;e.push(`- \`${s}\` ${d$(i.text)}`)}e.push("")}if(t.perf&&t.perf.length>0&&e.push("## Resource usage","",...t.perf.map(i=>`- ${i}`),""),t.logs)if(e.push("## App logs",""),t.logs.length===0)e.push("_No log lines during the clip._","");else{e.push("Lines the app logged during the clip (and the 5 s before it); times from the clip start.","","```text");for(let i of t.logs)e.push(`${i.t<0?"-":""}${Fe(Math.abs(i.t))} [${i.source}] ${i.line.replace(/\x60{3}/g,"'''")}`);e.push("```","")}if(e.push("## Recording",""),t.files.gif&&e.push("<!-- GitHub does not upload local files from --body-file: drag the GIF and clip into the issue, or replace these links with the uploaded URLs. -->",``,""),e.push(`- Clip: [${t.files.clip}](${t.files.clip}) (${Do(t.clip.end-t.clip.start)} s)`),t.files.gif&&t.gif){let i=(t.gif.sizeBytes/1e6).toFixed(1);e.push(`- ${t.gif.format==="gif"?"GIF":"WebP"}: [${t.files.gif}](${t.files.gif}) (${i} MB${t.gif.withinBudget?"":", over the size budget"})`)}t.files.contactSheet&&e.push(`- Contact sheet: [${t.files.contactSheet}](${t.files.contactSheet})`),e.push(""),e.push("## Environment","","| | |","|---|---|");for(let[i,s]of t.environment)e.push(`| ${Pf(i)} | ${Pf(s)} |`);e.push("");let n=t.redaction,o=n.found+n.manual;return e.push("<sub>",n.scanned?`Secret scan: OCR every ${n.everySec} s over ${n.framesScanned} frames; ${o} region${o===1?"":"s"} boxed out of the media. OCR is best-effort: review the clip before posting.`:`Not scanned for secrets${n.manual>0?` (${n.manual} region${n.manual===1?"":"s"} boxed out by hand)`:""}: review the clip before posting.`,`Generated by screencast-mcp bug_report, ${t.createdAt}.`,"</sub>",""),e.join(`
|
|
317
|
+
`)}async function Ns(t){if(t.sessionId!==void 0){let n=re().get(t.sessionId);if(!n)throw new l(`No session with id "${t.sessionId}".`);if(n.status==="recording"||n.status==="paused")throw new l("The recording is still running; stop_recording it first.");if(await Kt(n.id),!Ps(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path;return{path:n.outputPath,eventsPath:o&&Ps(o)?o:null,record:n}}let e=t.input;if(!Ps(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=$e(e);return{path:e,eventsPath:Ps(r)?r:null}}var m$=40;function Df(t,e,r){let n=t.filter(i=>i.t>=e.start-5&&i.t<=e.end).slice(-m$),o=r?Oe(n.map(i=>i.line),r):n.map(i=>i.line);return n.map((i,s)=>({...i,t:Math.round((i.t-e.start)*1e3)/1e3,line:o[s]??i.line}))}function Lf(t,e,r){let n=t.filter(s=>s.t>=e.start&&s.t<=e.end).map(s=>({...s,t:s.t-e.start}));if(n.length===0)return[];let o=Tn(n),i=r?.exe??"the app";return[...o.peakCpu!==void 0?[`${i} CPU peaked at ${o.peakCpu}% of the machine`]:[],...o.peakRssMB!==void 0?[`${i} memory peaked at ${o.peakRssMB} MB (${o.rssGrowthMB>=0?"+":""}${o.rssGrowthMB} MB over the clip)`]:[],`Machine CPU peaked at ${o.peakSysCpu}%`,...o.busy.map(s=>`CPU pinned (>= 90%) from ${Fe(s.start)} to ${Fe(s.end)}`)]}var Fu=1,Ou=.03,Nu=120,Gf=600,v$=10,Ls=10,qf=50,Bf=200,$$=5,fr=t=>Math.round(t*1e3)/1e3;function Lo(t){return`${t}.index.json`}function Du(t){return`${t.replace(/\.[^./\\]+$/,"")}.index.json`}function Bo(t,e){let r=n=>process.platform==="win32"?Ds(n).toLowerCase():Ds(n);return r(t)===r(e)}function Bs(t,e,r){return typeof t.video=="string"&&Bo(t.video,e)?!0:r!==void 0&&!!t.fingerprint&&Gs(t.fingerprint,r)}function Ws(t,e){let r=Uf("sha1").update(Ds(t).toLowerCase()).digest("hex").slice(0,12),n=Hf(t).replace(/\.[^.]+$/,"");return Cn(e,"indexes",`${n}-${r}.index.json`)}function Xf(t,e){let r=Lo(t);try{return Zt(r),r}catch{return Ws(t,e)}}function js(t,e,r){for(let o of[Lo(t),Ws(t,e)])if(Mn(o))return o;let n=Du(t);if(n!==Lo(t)&&Mn(n)){let o=Wo(n);if(o&&Bs(o,t,r))return n}return null}function Jf(t,e){return t!==null&&Gs(t.fingerprint,e.fingerprint)&&t.sceneThreshold===e.sceneThreshold&&t.maxFrames===e.maxFrames&&(t.ocr||!e.ocrAvailable)}function Yf(t,e=Ge){return t.map(r=>r.ocr.length>0?{...r,ocr:Oe(r.ocr,e)}:r)}var k$=/\.(mp4|mkv|mov|webm|avi|m4v|wmv|flv|gif|ts|mpg|mpeg)$/i,Wf=t=>t.replace(/\.[^.]+$/,"").toLowerCase();function Us(t,e){let r=new Set(e.map(s=>s.toLowerCase())),n=Hf(t);if(r.has(`${n}.srt`.toLowerCase()))return{path:`${t}.srt`,ambiguous:!1};let o=`${n.replace(/\.[^.]+$/,"")}.srt`;return r.has(o.toLowerCase())?e.some(s=>s.toLowerCase()!==n.toLowerCase()&&k$.test(s)&&Wf(s)===Wf(n))?{path:null,ambiguous:!0}:{path:Cn(S$(t),o),ambiguous:!1}:{path:null,ambiguous:!1}}function Kf(t,e,r,n=v$){let o=mn(t.filter(i=>i.timeSec<e),r).map(fr);for(;o.length<r;){let i=-1,s=0;for(let a=0;a<o.length;a++){let c=(o[a+1]??e)-o[a];c>s&&(s=c,i=a)}if(i===-1||s<=n)break;o.splice(i+1,0,fr(o[i]+s/2))}return[...new Set(o)].sort((i,s)=>i-s)}function Vf(t,e){return t.map((r,n)=>({start:r,end:fr(t[n+1]??e)}))}function zs(t){return fr(t.start+Math.min(.25,(t.end-t.start)/2))}function Qf(t){let e=[];for(let r of t){let n=e.at(-1);n&&n.ocr.join(`
|
|
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 Zf(t){let e=[];for(let r of t){let n=`at ${Math.round(r.x)},${Math.round(r.y)}`,o=null;if(r.type==="down"){let i=r.element;o=`click ${r.button??"left"} ${n}`+(i?` ${Tu(i.role)}${i.name?` ${i.name}`:""}${i.app?` ${i.app}`:""}`:"")}else r.type==="key"?o=`shortcut ${r.keys??"key"}`:r.type==="typing"?o=`typing ${fr(r.durationSec??0)} s`:r.type==="wheel"?o=`scroll ${(r.delta??0)>0?"up":"down"} ${n}`:r.type==="gap"?o=`event gap (${r.reason??"unknown"})`:r.type==="focus"&&(o=`switch to ${r.app??"app"}${r.title?` ${r.title}`:""}`);o&&e.push({t:fr(r.t),text:o})}return e}function eh(t){return t.map(e=>({t:fr(e.t),text:e.label}))}function th(t){return t.map(e=>({t:fr(e.start),text:e.text.replace(/\s+/g," ").trim()})).filter(e=>e.text)}function zr(t,e,r){let n=t.map(o=>{let{[r]:i,...s}=o;return s});if(n.length===0)return n;for(let o of[...e].sort((i,s)=>i.t-s.t)){let i=n.findIndex(a=>o.t>=a.start&&o.t<a.end);i===-1&&(i=o.t<n[0].start?0:n.length-1);let s=n[i];(s[r]??=[]).push(o)}return n}function Hs(t){let e=zf(t),r=Uf("sha1"),n=64*1024,o=h$(t,"r");try{let i=Buffer.alloc(n);for(let s of e.size>n?[0,e.size-n]:[0]){let a=w$(o,i,0,n,s);r.update(i.subarray(0,a))}}finally{f$(o)}return{size:e.size,mtimeMs:Math.round(e.mtimeMs),sample:r.digest("hex")}}function Gs(t,e){return t.size===e.size&&t.mtimeMs===e.mtimeMs&&t.sample===e.sample}function E$(t){try{let e=JSON.parse(t);return e?.version!==Fu||!Array.isArray(e.segments)||!e.fingerprint?null:e}catch{return null}}function Wo(t){try{return E$(g$(t,"utf8"))}catch{return null}}var Ur=new Map,_$=64;function Lu(t){let e;try{e=zf(t)}catch{return Ur.delete(t),null}let r=Ur.get(t);if(r&&r.size===e.size&&r.mtimeMs===e.mtimeMs)return r.index;let n=Wo(t);return n?(Ur.size>=_$&&Ur.delete(Ur.keys().next().value),Ur.set(t,{size:e.size,mtimeMs:e.mtimeMs,index:n}),n):(Ur.delete(t),null)}function rh(t,e){let r=`${t}.${process.pid}.tmp`;x$(r,JSON.stringify(e)),y$(r,t)}function T$(t){let e=t.replace(/\s+/g," ").trim();return e.length>Bf?`${e.slice(0,Bf-1)}\u2026`:e}function A$(t){let e=[];return t.segments.forEach((r,n)=>{for(let o of r.ocr)e.push({seg:n,source:"screen",t:r.start,text:o});for(let[o,i]of[["event",r.events],["marker",r.markers],["transcript",r.transcript],["log",r.logs]])for(let s of i??[])e.push({seg:n,source:o,t:s.t,text:s.text})}),e}function nh(t,e){if(t.trim().length===0)throw new l("query must not be empty.");if(t.length>jr)throw new l(`The query is ${t.length} characters; at most ${jr} are allowed.`);if(!e&&!/[\p{L}\p{N}]/u.test(Dt(t)))throw new l("query needs at least one letter or digit.","For punctuation, use regex: true.");e&&$n([""],t)}var jf=new WeakMap;function R$(t,e){let r=jf.get(t);r||jf.set(t,r=new Map);let n=r.get(e);if(n)return n;let o=A$(t),i=e?Oe(o.map(c=>c.text),e):o.map(c=>c.text),s=o.map((c,u)=>({...c,text:i[u]??""})),a={items:s,norm:s.map(c=>Dt(c.text))};return r.set(e,a),a}function Bu(t,e,r={}){if(nh(e,r.regex===!0),r.video!==void 0&&!Bs(t,r.video,r.fingerprint))throw new l(`The index found is for ${t.video}, not ${r.video}.`,"Run index_recording on this recording.");let n=r.secretPattern===void 0?Ge:r.secretPattern,{items:o,norm:i}=R$(t,n??""),s=new Map,a=(p,f)=>{let m=s.get(p.seg)??{score:0,matches:[]};m.score+=f,m.matches.push(p),s.set(p.seg,m)};if(r.regex){let p=$n(o.map(f=>f.text),e);o.forEach((f,m)=>{(p[m]??[]).length>0&&a(f,2)})}else{let p=Dt(e.trim()),f=p.split("_").filter(Boolean);if(o.forEach((m,h)=>{i[h].includes(p)&&a(m,2)}),f.length>1){let m=new Map;o.forEach((h,b)=>{let w=m.get(h.seg);w?w.push(b):m.set(h.seg,[b])});for(let[h,b]of m)if(!s.has(h)&&f.every(w=>b.some(g=>i[g].includes(w)))){for(let w of b)f.some(g=>i[w].includes(g))&&a(o[w],0);s.get(h).score=1}}}return{hits:[...s.entries()].map(([p,f])=>({seg:p,...f})).sort((p,f)=>f.score-p.score||t.segments[p.seg].start-t.segments[f.seg].start).slice(0,r.limit??Ls).map(p=>{let f=t.segments[p.seg],m=p.matches.slice(0,$$).map(h=>({source:h.source,t:h.t,text:T$(h.text)}));return{start:f.start,end:f.end,t:Math.min(...p.matches.map(h=>h.t)),score:p.score,matches:m}}),total:s.size}}var M$=20;function C$(t){return[Cn(t,"recordings"),Cn(t,"edits"),Cn(t,"edits","indexes")]}function oh(t){let e=[];for(let r of C$(t)){let n;try{n=b$(r)}catch{continue}for(let o of n)o.endsWith(".index.json")&&e.push(Cn(r,o))}return e}function ih(t,e,r={}){nh(e,r.regex===!0);let n=new Map;for(let c of t){let u=Ds(c.index.video).toLowerCase(),d=n.get(u);(!d||c.index.createdAt>d.index.createdAt)&&n.set(u,c)}let o=r.limit??Ls,i=[],s=[],a=0;for(let c of n.values()){let u=Bu(c.index,e,{regex:r.regex,limit:o});if(u.total!==0){a+=u.total,i.push({video:c.index.video,indexPath:c.indexPath,total:u.total,best:u.hits[0].score});for(let d of u.hits)s.push({video:c.index.video,...d})}}return i.sort((c,u)=>u.best-c.best||u.total-c.total),s.sort((c,u)=>u.score-c.score),{hits:s.slice(0,o),total:a,recordings:i.slice(0,M$),searched:n.size}}async function qs(t){if(t.input===void 0==(t.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");if(t.sessionId!==void 0){let n=re().get(t.sessionId);if(!n)throw new l(`No session with id "${t.sessionId}".`);if(n.status==="recording"||n.status==="paused")throw new l("The recording is still running; stop_recording it first.");if(await Kt(n.id),!Mn(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path,i=n.markers?.length?n.markers:Le(n.outputPath);return{path:n.outputPath,eventsPath:o&&Mn(o)?o:null,markers:i}}let e=t.input;if(!Mn(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=$e(e);return{path:e,eventsPath:Mn(r)?r:null,markers:Le(e)}}import{basename as sh}from"node:path";function ah(t,e,r){let n=$e(t),o=Us(t,e),i=[n.jsonl,n.raw,`${n.raw}.stop`,Lr(t),Lo(t),Ws(t,r),pr(t),Lt(t),xt(t),Vi(t),...o.path&&!o.ambiguous?[o.path]:[]];return{files:[...new Set(i)].filter(s=>sh(s)!==sh(t)),dirs:[bt(t)]}}var P$=/\.(mp4|m4v|mkv|mov|webm|avi|gif|webp)$/i;function ch(t){if(Qt(t,"Recording"),!P$.test(t))throw new l(`${t} is not a video or GIF, so it is not deleted.`,"delete_recording only removes recordings and their sidecars.");if(![Me(),...Mr()??[]].some(r=>ht(t,r)&&!ht(r,t)))throw new l(`Recording ${t} is outside SCREENCAST_HOME and the allowed directories, so it is not deleted. Add its folder to SCREENCAST_ALLOWED_DIRS or the client's workspace roots, or delete it yourself.`)}var N$={sessionId:hr.string().min(1).optional().describe("Session id of the recording to delete."),input:hr.string().min(1).optional().describe("Or the recording's path.")};function dh(t){try{let e=F$(t);return e.isDirectory()?lh(t).reduce((r,n)=>r+dh(ph(t,n)),0):e.size}catch{return 0}}async function D$(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form){if(zm())throw new l(`Not deleted: ${Co} requires the user to confirm, but this client does not support MCP elicitation.`);return!1}let n;try{({action:n}=await t.server.elicitInput({message:e,requestedSchema:{type:"object",properties:{}}},{signal:r,timeout:ru}))}catch(o){throw new l(`Not deleted: the confirmation request failed (${U(o)}).`)}if(n!=="accept")throw new l(`Not deleted: ${n==="decline"?"declined":"cancelled"} by the user.`);return!0}function mh(t){t.registerTool("delete_recording",{title:"Delete Recording",description:"Delete a finished recording with its sidecars (event log, webcam, transcript, index, markers, pause parts) and registry entries; reports bytes freed. Asks the user first when the client supports it. Edits made from it are kept.",inputSchema:N$,outputSchema:N({outputPath:hr.string(),deleted:hr.array(hr.string()),bytesFreed:hr.number(),sessionsRemoved:hr.array(hr.string())}),annotations:Td},async(e,r)=>{try{if(!!e.sessionId==!!e.input)throw new l("Give exactly one of sessionId or input.");let n=re(),o;if(e.sessionId){let g=n.get(e.sessionId);if(!g)throw new l(`No session with id "${e.sessionId}".`);o=g.outputPath}else o=ph(e.input);ch(o);let i=n.list().filter(g=>Bo(g.outputPath,o)),s=i.find(g=>xn(g.status));if(s)throw new l(`Recording ${s.id} is still ${s.status}; stop it first.`);let a=[];try{a=lh(O$(o))}catch{}if(jo(o)&&!uh(o).isFile())throw new l(`${o} is not a file, so it is not deleted.`,"delete_recording only removes a recording and its sidecars.");let c=ah(o,a,we("edits")),u=[o,...c.files].filter(g=>jo(g)&&uh(g).isFile()),d=c.dirs.filter(g=>jo(g)),p=[...u,...d];if(p.length===0&&i.length===0)throw new l(`Nothing to delete: ${o} does not exist.`);let f=await D$(t,`Delete ${o} and ${p.length-(jo(o)?1:0)} sidecar file(s)? This cannot be undone.`,r.signal);if(!f&&i.length===0&&!ht(o,Me()))throw new l(`Not deleted: ${o} is not a recording this server made, and this client cannot ask you to confirm.`,"Pass the recording's sessionId, use a client that supports MCP elicitation, or delete the file yourself.");let m=0,h=[],b=[];for(let g of p){let y=dh(g);try{I$(g,{recursive:d.includes(g),force:!0}),h.push(g),m+=y}catch($){b.push(`${g}: ${U($)}`)}}let w=jo(o)?[]:i.map(g=>g.id);return w.length>0&&n.remove(w),v({outputPath:o,deleted:h,bytesFreed:m,sessionsRemoved:w,confirmedByUser:f,...b.length>0?{failed:b,note:"Some files could not be deleted (in use?); the registry entry was kept if the recording remains."}:{}})}catch(n){return E(n)}})}import{z as gr}from"zod";import{existsSync as L$}from"node:fs";function F(t,e="Input file"){if(!L$(t))throw new l(`${e} not found: ${t}`)}function B(t,e,r,n={}){return n.anyContainer||Nr(t),er(t,we(n.dir??"edits"),`${e}-${ge()}-${be()}${r}`,n.overwrite)}var B$={sessionId:gr.string().min(1).describe("Session id of a replay buffer."),lastSec:gr.number().positive().max(yn).optional().describe("Seconds back from now (default and max: the buffer length)."),output:gr.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:gr.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),reencode:gr.boolean().optional().describe("Frame-exact re-encode. Default: instant stream copy that may hide up to 2 s of earlier frames.")};function fh(t){t.registerTool("save_replay",{title:"Save Replay",description:"Save the last N seconds of a replay buffer (start_recording replayBufferSec) to an mp4; the buffer keeps running.",inputSchema:B$,outputSchema:N({sessionId:gr.string(),outputPath:gr.string(),durationSec:gr.number()}),annotations:I},async(e,r)=>{try{let n=re().get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(!n.replay)throw new l(`Session "${e.sessionId}" is not a replay buffer.`,"Start one with start_recording { replayBufferSec: 60 }; for an ordinary recording use stop_recording and trim.");let{ffmpeg:o,ffprobe:i}=k(),s=n.replay,a=Math.min(e.lastSec??s.bufferSec,s.bufferSec),c=B(e.output,"replay",".mp4",{overwrite:e.overwrite,dir:"recordings",anyContainer:!0});s.events&&yi($e(c),e.overwrite);let u=Date.now(),d=await Bc(s,{ffmpeg:o,ffprobe:i,lastSec:a,output:c,reencode:e.reencode,quality:n.quality,live:n.status==="recording",signal:r.signal}),p=Date.now()-u;or("info",`Saved ${d.durationSec}s of replay ${n.id} to ${c}.`,{sessionId:n.id,outputPath:c,durationSec:d.durationSec});let f=d.durationSec+.25<a;return v({sessionId:n.id,...d,requestedSec:e.lastSec??null,bufferSec:s.bufferSec,bufferRunning:n.status==="recording",bufferDiskBytes:zd(s),elapsedMs:p,note:(e.lastSec!==void 0&&e.lastSec>s.bufferSec?`Capped at the buffer length (${s.bufferSec}s). `:"")+(f?"The buffer held less footage than requested (it started recently). ":"")+(d.includesLive?"":"The clip ends at the last completed segment, up to 2 s before now. ")+(n.status==="recording"?"The buffer keeps running; stop_recording discards it unless save: true.":"This buffer is no longer recording; stop_recording discards it.")})}catch(n){return E(n)}})}import{z as Xs}from"zod";var hh=t=>Math.round(t*1e3)/1e3;function gh(t){t.registerTool("pause_recording",{title:"Pause Recording",description:"Pause a recording; until resume_recording nothing is captured, and the gap is left out of the file, events, and markers.",inputSchema:{sessionId:Xs.string().min(1).describe("From start_recording.")},outputSchema:N({sessionId:Xs.string(),status:Xs.string(),recordedSec:Xs.number()}),annotations:Gi},async e=>{try{let r=re(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(ns(r,n.id,"pause"),n.status==="paused")return v({sessionId:n.id,status:"paused",recordedSec:hh(rt(n.segments?.parts??[])),note:"Already paused."});let{ffprobe:o}=k(),i=await xm(r,n,{probe:s=>se(s,{ffprobe:o})});return v({sessionId:n.id,status:"paused",recordedSec:hh(i.recordedSec),segments:i.record?.segments?.parts.length??0,note:"Nothing is captured until resume_recording; stop_recording joins what was recorded."})}catch(r){return E(r)}})}import{z as Js}from"zod";var bh=t=>Math.round(t*1e3)/1e3;function wh(t){t.registerTool("resume_recording",{title:"Resume Recording",description:"Resume a paused recording (same target and settings).",inputSchema:{sessionId:Js.string().min(1).describe("From start_recording.")},outputSchema:N({sessionId:Js.string(),status:Js.string(),recordedSec:Js.number()}),annotations:I},async e=>{try{let r=re(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(ns(r,n.id,"resume"),n.status==="recording")return v({sessionId:n.id,status:"recording",recordedSec:bh(rt(n.segments?.parts??[])),note:"Already recording."});let{ffmpeg:o}=k(),i=await hf(r,n,o);return or("notice",`Recording ${n.id} resumed.`,{sessionId:n.id}),v({sessionId:n.id,status:"recording",recordedSec:bh(i.recordedSec),pid:i.record.pid,...i.capSec>0?{remainingSec:i.capSec}:{}})}catch(r){return E(r)}})}import{z as yh}from"zod";function xh(t){t.registerTool("list_video_devices",{title:"List Video Devices",description:"List DirectShow cameras for start_recording's webcam.device.",inputSchema:{},outputSchema:N({devices:yh.array(yh.string())}),annotations:he},async()=>{try{k();let e=await tu(!0);return v({devices:e,note:e.length?`start_recording { webcam: { device: "${e[0]}" } } records it.`:"No camera found."})}catch(e){return E(e)}})}import{z as Pn}from"zod";function Sh(t){t.registerTool("list_sessions",{title:"List Sessions",description:"List all recording sessions (active and finished) with their status, target, output path, and whether the process is still alive.",inputSchema:{},outputSchema:N({count:Pn.number().int(),sessions:Pn.array(N({id:Pn.string(),status:Pn.string(),outputPath:Pn.string(),alive:Pn.boolean()}))}),annotations:he},async()=>{try{let e=re().list().map(n=>({...n,alive:n.status==="recording"&&ze(n.pid)})),r=rf();return v({count:e.length,sessions:e,...r.length?{armed:r}:{}})}catch(e){return E(e)}})}import{z as In}from"zod";import{existsSync as W$}from"node:fs";var j$={sessionId:In.string().min(1).describe("Session id returned by start_recording.")};function vh(t){t.registerTool("get_session",{title:"Get Session",description:"Inspect a single recording session by id, including live status and whether its output file exists on disk.",inputSchema:j$,outputSchema:N({id:In.string(),status:In.string(),outputPath:In.string(),alive:In.boolean(),fileExists:In.boolean()}),annotations:he},async e=>{try{if($s(e.sessionId)){let n=Po(e.sessionId);if(!n)throw new l(`No armed recording with id "${e.sessionId}".`);return v({...n,outputPath:"",alive:!1,fileExists:!1,...n.sessionId?{note:`It started recording ${n.sessionId}; get_session that id for it.`}:{}})}let r=re().get(e.sessionId);if(!r)throw new l(`No session with id "${e.sessionId}".`);return v({...r,alive:r.status==="recording"&&ze(r.pid),fileExists:W$(r.outputPath)})}catch(r){return E(r)}})}import{z as Be}from"zod";import{existsSync as U$,readFileSync as z$}from"node:fs";var $h=200,H$=5e3,G$={sessionId:Be.string().min(1).optional().describe("Session id of a recording started with events: true."),input:Be.string().optional().describe("Or a recording path, or its .events.jsonl."),from:Be.number().min(0).optional().describe("Earliest video second."),to:Be.number().min(0).optional().describe("Latest video second."),types:Be.array(Be.enum(mc)).optional().describe("down/up (mouse buttons; clicks are down), move (sampled cursor), wheel, key (shortcut), typing (burst), gap (events may be missing)."),inFrameOnly:Be.boolean().optional().describe("Drop events whose cursor was outside the recorded area."),limit:Be.number().int().min(1).max(H$).optional().describe(`Most events to return (default ${$h}).`)};function kh(t){t.registerTool("read_events",{title:"Read Input Events",description:"Read the input events (clicks, scroll, cursor, shortcuts, typing bursts) of a recording made with events: true, in video seconds and pixels; e.g. types: ['down'], then sample_frames there.",inputSchema:G$,outputSchema:N({eventsPath:Be.string(),total:Be.number().int(),matched:Be.number().int(),returned:Be.number().int(),summary:Be.record(Be.string(),Be.number())}),annotations:he},async e=>{try{let r;if(e.sessionId){let a=re().get(e.sessionId);if(!a)throw new l(`No session with id "${e.sessionId}".`);if(!a.events)throw new l(`Session "${e.sessionId}" was recorded without an event log. Start the recording with events: true.`);if(a.status==="recording"||a.status==="paused")throw new l("The recording is still running; its event log is written when it stops.");r=a.events.path}else if(e.input)r=e.input.endsWith(".jsonl")?e.input:$e(e.input).jsonl;else throw new l("Pass sessionId or input.");if(!U$(r))throw new l(`No event log at ${r}. Record with start_recording events: true.`);let n=je(z$(r,"utf8")),o=bi(n,e),i=e.limit??$h,s=rp(n);return v({eventsPath:r,total:n.length,matched:o.length,returned:Math.min(i,o.length),summary:an(n),...s.length>0?{truncated:!0,gaps:s,warning:"The log is missing events in the gaps listed: Windows removed the input hook, input went to an elevated window or the lock screen, or the helper stopped. Do not read silence there as no activity."}:{},events:o.slice(0,i),...o.length>i?{note:`${o.length-i} more matched; narrow from/to or types, or raise limit.`}:{}})}catch(r){return E(r)}})}import{z as Fn}from"zod";var q$={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},X$={label:Fn.string().min(1).max(Kc).describe('e.g. "bug appears".'),sessionId:Fn.string().min(1).optional().describe("Recording to mark (a stopped one needs at)."),input:Fn.string().min(1).optional().describe("Or a video path (needs at)."),at:Fn.number().min(0).optional().describe("Video second (default: now, while recording).")};function Eh(t){t.registerTool("add_marker",{title:"Add Marker",description:"Mark a labelled moment on a recording, live or at a second. Kept in the session and a sidecar; chapters and pipeline turn markers into chapters.",inputSchema:X$,outputSchema:N({count:Fn.number().int(),markersPath:Fn.string()}),annotations:q$},async e=>{try{if(!e.sessionId&&!e.input)throw new l("Pass sessionId or input.");if(e.sessionId){let i=ms(re(),e.sessionId,e.label,e.at);return v({sessionId:e.sessionId,marker:{t:Math.round(i.t*1e3)/1e3,label:Ro(e.label)},count:i.count,markersPath:i.markersPath,...i.live?{live:!0}:{},...i.warning?{warning:i.warning}:{}})}let r=e.input;if(e.at===void 0)throw new l("Pass at (video seconds) to mark a file.");F(r),Zt(pr(r));let n=us(Le(r),{t:e.at,label:e.label,at:new Date().toISOString()}),o=dr(r,n);return v({marker:{t:Math.round(e.at*1e3)/1e3,label:Ro(e.label)},count:n.length,markersPath:o})}catch(r){return E(r)}})}import{z as ve}from"zod";import{extname as K$,join as Fh}from"node:path";import{existsSync as V$,mkdtempSync as Q$,readFileSync as Z$,rmSync as ek,writeFileSync as tk}from"node:fs";import{tmpdir as rk}from"node:os";import{existsSync as J$}from"node:fs";var Ks="SCREENCAST_WHISPER_MODEL",_h=`Download a whisper.cpp model (ggml-base.en.bin is a good start; ggml-tiny.en.bin is fastest) from https://huggingface.co/ggerganov/whisper.cpp and pass its path as model, or set ${Ks}.`;function br(t,e=process.env){let r=t??e[Ks];if(!r||r.trim().length===0)throw new l("No whisper model given.",_h);if(!J$(r))throw new l(`Whisper model not found: ${r}`,_h);return r}function On(t,e,r,n="auto",o=!1){if(!/^[a-z]{2,3}$|^auto$/.test(n))throw new l(`language must be a code like "en" or "auto", got "${n}".`);return["-y","-v","error","-i",t,"-vn","-af",`aresample=16000,whisper=model=${ye(e)}:language=${n}:format=srt:destination=${ye(r)}:use_gpu=false`+(o?":max_len=1":""),"-f","null","-"]}function Mh(t){let e=[];for(let r of t){let n=e[e.length-1];n&&!/[\p{L}\p{N}]/u.test(r.text)?n.text+=r.text.trim():e.push({...r})}return e}var Th=/(\d+):(\d{2}):(\d{2})[,.](\d{3})/,Ah=t=>Number(t[1])*3600+Number(t[2])*60+Number(t[3])+Number(t[4])/1e3;function Rh(t){let e=Math.round(t*1e3),r=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),o=Math.floor(e%6e4/1e3),i=(s,a=2)=>String(s).padStart(a,"0");return`${i(r)}:${i(n)}:${i(o)},${i(e%1e3,3)}`}function We(t,e={}){let r=[];for(let n of t.replace(/\r\n/g,`
|
|
333
320
|
`).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
|
-
${
|
|
321
|
+
`).map(m=>m.trim()).filter(m=>m.length>0),i=o.findIndex(m=>m.includes("-->")),s=o[i];if(s===void 0)continue;let[a,c]=s.split("-->"),u=a?.match(Th),d=c?.match(Th);if(!u||!d)continue;let p=o.slice(i+1).join(`
|
|
322
|
+
`);if(!p)continue;let f=e.index&&i>0&&/^\d+$/.test(o[i-1])?Number(o[i-1]):void 0;r.push({start:Ah(u),end:Ah(d),text:p,...f!==void 0&&{index:f}})}return r}function ut(t){let e=[...t].sort((r,n)=>r.start-n.start);return e.map((r,n)=>{let o=e[n+1],i=o?Math.min(r.end,o.start):r.end;return{...r,end:i}}).filter(r=>r.end>r.start)}function nt(t){return t.map((e,r)=>`${r+1}
|
|
323
|
+
${Rh(e.start)} --> ${Rh(e.end)}
|
|
337
324
|
${e.text}
|
|
338
325
|
`).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 v({input:t.input,imageSize:{width:s.width,height:s.height},scan:{everySec:Math.round(i*1e3)/1e3,framesScanned:o.frames.length,...o.clamped?{note:`Widened from ${t.scanEverySec} s to fit maxFrames ${n}.`}:{}},...t.query?{query:t.query,matchCount:c.length,matches:c.slice(0,
|
|
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
|
|
326
|
+
`)}var Vs=["clean","social"],Y$={clean:"FontName=Inter,FontSize=16,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=1.5,Shadow=0,MarginV=16",social:"FontName=Inter,Bold=1,FontSize=22,PrimaryColour=&H00FFFFFF,BackColour=&H99000000,BorderStyle=3,Outline=6,Shadow=0,MarginV=40"};function Wu(t,e,r="clean"){let n=r===null?null:Y$[r];if(n===void 0)throw new l(`Unknown caption style "${r}".`);return`subtitles=filename=${ye(t)}:fontsdir=${ye(e)}`+(n?`:force_style='${n}'`:"")}function Ch(t,e,r,n,o="clean",i="standard"){return["-y","-i",t,"-vf",Wu(e,n,o),..._e(i),"-c:a","copy",r]}var Ys=1e3;function Ph(t,e){if(e.length!==t.length)throw new l(`Got ${e.length} translations for ${t.length} cues.`,"Translate every cue, in order, one string per cue (merge or split nothing).");return t.map((r,n)=>{let o=e[n].replace(/\r\n/g,`
|
|
327
|
+
`).trim();if(!o)throw new l(`Translation ${n+1} is empty.`);if(o.length>Ys)throw new l(`Translation ${n+1} is over ${Ys} characters.`);return{start:r.start,end:r.end,text:o.replace(/\n\s*\n/g,`
|
|
328
|
+
`)}})}function Ih(t,e){return t.replace(/\.srt$/i,"")+`.${e}.srt`}var nk=new Set([".mp4",".mkv",".mov"]),ok=12,ik={input:ve.string().min(1).optional().describe("Path to the video."),sessionId:ve.string().min(1).optional().describe("Or a stopped recording's id."),from:ve.enum(["markers","scenes","transcript"]).optional().describe("markers (default; add_marker, else the file's chapters), scenes (screen changes), or transcript (SRT sections)."),chapters:ve.array(ve.object({start:ve.number().min(0),title:ve.string().min(1).max(100)})).min(1).max(200).optional().describe("Or explicit { start, title } chapters."),transcript:ve.string().optional().describe("The .srt for from: transcript."),minChapterSec:ve.number().min(0).optional().describe(`Shortest chapter (default 1; scenes ${Sn}, transcript 30).`),subtitles:ve.string().optional().describe("Also mux this .srt/.vtt/.ass as a soft subtitle track."),subtitleLanguage:ve.string().regex(/^[a-z]{3}$/).optional().describe('ISO 639-2, e.g. "eng".'),subtitleTracks:ve.array(ve.object({file:ve.string().min(1),language:ve.string().regex(/^[a-z]{3}$/).optional(),title:ve.string().max(60).optional(),default:ve.boolean().optional()})).min(1).max(cs).optional().describe("Or several tracks, e.g. one per language (translate_subtitles makes them)."),textOnly:ve.boolean().optional().describe("Return chapters and YouTube text only; write no file."),output:ve.string().optional().describe("Optional .mp4/.mkv/.mov path. Defaults under SCREENCAST_HOME/edits."),overwrite:ve.boolean().optional().describe("Allow replacing an existing output file.")};function Oh(t){t.registerTool("chapters",{title:"Chapters",description:"Write chapters (markers, scene changes, transcript, or a list) into an mp4/mkv/mov copy without re-encoding; returns YouTube chapter text. Can mux an SRT as soft subtitles.",inputSchema:ik,outputSchema:N({chapters:ve.array(N({start:ve.number(),end:ve.number(),title:ve.string()})),youtube:ve.string()}),annotations:I},async(e,r)=>{try{k();let n=e.input,o;if(e.sessionId){let y=re().get(e.sessionId);if(!y)throw new l(`No session with id "${e.sessionId}".`);if(y.status==="recording"||y.status==="paused")throw new l("The recording is still running; stop it first.");n??=y.outputPath,o=y.markers}if(!n)throw new l("Pass input or sessionId.");if(F(n),e.subtitles&&e.subtitleTracks)throw new l("Pass subtitles or subtitleTracks, not both.");let i=e.subtitleTracks??(e.subtitles?[{file:e.subtitles,...e.subtitleLanguage?{language:e.subtitleLanguage}:{}}]:[]);for(let y of[e.transcript,...i.map($=>$.file)])if(y!==void 0&&!V$(y))throw new l(`File not found: ${y}`);for(let y of i)if(!/\.(srt|vtt|ass|ssa)$/i.test(y.file))throw new l(`Subtitles must be .srt, .vtt, or .ass files, not ${y.file}.`);let a=(await L(n)).durationSec;if(!a||a<=0)throw new l(`Could not read the duration of ${n}.`);let c=e.chapters?"list":e.from??"markers",u,d=1,p=c;if(e.chapters)u=e.chapters;else if(c==="scenes"){d=Sn;let{ffmpeg:y}=k(),$=await ne(y,rr(n,gt),le(a),{signal:r.signal});if($.code!==0)throw new l(`Scene scan failed (exit ${$.code}): ${$.stderr.trim().slice(-400)}`);u=Cm(nr($.stdout),e.minChapterSec??d,ok)}else if(c==="transcript"){if(!e.transcript)throw new l("from: transcript needs transcript (an .srt path).");if(d=30,u=Pm(We(Z$(e.transcript,"utf8")),{minChapterSec:e.minChapterSec??d}),u.length===0)throw new l(`No cues in ${e.transcript}.`)}else{let y=o??[];if(y.length===0){let $=await mr(n,r.signal);y=$.markers,$.from==="chapters"&&(p="embedded chapters")}if(y.length===0)throw new l(`No markers for ${n}.`,"Add some with add_marker, or use from: scenes / transcript, or pass chapters.");u=ds(y)}let f=ls(u,a,{minChapterSec:e.minChapterSec??d});if(f.length===0)throw new l("No chapter falls inside the video.");let m=Mm(f,a),h={source:p,chapters:f,youtube:m.text,...m.issues.length>0?{youtubeIssues:m.issues}:{}};if(e.textOnly)return v(h);let b=e.output?K$(e.output).toLowerCase():V(n);if(!nk.has(b))throw new l(`Chapters can be written to .mp4, .mkv, or .mov, not ${b||"a file without an extension"}.`);let w=B(e.output,"chapters",b,{overwrite:e.overwrite,anyContainer:!0}),g=Q$(Fh(rk(),"screencast-chapters-"));try{let y=Fh(g,"chapters.txt");tk(y,ps(f)),await W(Im(n,y,w,{container:b,subtitles:i}),{output:w,durationSec:a,extra:r})}finally{ek(g,{recursive:!0,force:!0})}return v({outputPath:w,...h,...e.subtitles?{subtitleTrack:{...i[0],codec:b===".mkv"?"copy":"mov_text"}}:{},...e.subtitleTracks?{subtitleTracks:i.map(y=>({...y,codec:b===".mkv"?"copy":"mov_text"}))}:{}})}catch(n){return E(n)}})}import{z as lt}from"zod";import{existsSync as ck,readFileSync as qh,rmSync as uk}from"node:fs";var Uo="ui://screencast/player",Qs="text/html;profile=mcp-app",Dh={ui:{resourceUri:Uo},"ui/resourceUri":Uo},Nh="io.modelcontextprotocol/ui";function Lh(t){let e=t,r=e?.extensions?.[Nh]??e?.experimental?.[Nh];return!r||typeof r!="object"?!1:!Array.isArray(r.mimeTypes)||r.mimeTypes.includes(Qs)}var Zs=120,Bh=300,sk=4,ju=640,ak=.01;function Wh(t,e=Zs){if(!(t>0))throw new l("The video has no duration to review.");let r=Math.max(1,Math.min(e,Math.ceil(t*sk))),n=Number((t/r).toFixed(6));return{count:r,intervalSec:n,sceneGapSec:Number(Math.max(.25,n/4).toFixed(6))}}function jh(t,e,r,n,o=ak){let i=e.intervalSec,s=`isnan(prev_t)+gt(floor((t-start_t)/${i})\\,floor((prev_t-start_t)/${i}))`,a=`gt(scene\\,${o})*not(${s})*(isnan(prev_selected_t)+gte(t-prev_selected_t\\,${e.sceneGapSec}))`;return["-v","error","-i",t,"-an","-vf",`scale='min(${r},iw)':-2,split[g][s];[g]select='${s}',metadata=add:key=kind:value=grid[g1];[s]select='${a}',metadata=add:key=kind:value=scene[s1];[g1][s1]interleave,metadata=print:file=${ye(n)}`,"-fps_mode","passthrough","-q:v","6","-f","image2pipe","-c:v","mjpeg","-"]}function Uh(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.match(/pts_time:\s*(-?[\d.]+)/);if(n){e.push({timeSec:Number(n[1]),scene:!1,score:0});continue}let o=e.at(-1);if(!o)continue;r==="kind=scene"&&(o.scene=!0);let i=r.match(/^lavfi\.scene_score=([\d.]+)/);i&&(o.score=Number(i[1]))}return e}function zh(t,e){let r=t.map((o,i)=>({f:o,i})).filter(o=>o.f.scene).sort((o,i)=>i.f.score-o.f.score).slice(0,Math.max(0,e)),n=new Set(r.map(o=>o.i));return t.flatMap((o,i)=>!o.scene||n.has(i)?[i]:[])}function Hh(t){let e=[],r=-1;for(let n=0;n+1<t.length;n++){if(t[n]!==255)continue;let o=t[n+1];o===216&&r<0?r=n:o===217&&r>=0&&(e.push(t.subarray(r,n+2)),r=-1,n++)}return e}var Gh=t=>qh(vn("ui",t),"utf8");function lk(){let t=Gh("player.js");if(/<\/script/i.test(t))throw new l("player.js must not contain a closing script tag.");return Gh("player.html").replace('<script src="player.js"></script>',()=>`<script>
|
|
329
|
+
${t}</script>`)}function pk(t){if(t.sessionId){let e=re().get(t.sessionId);if(!e)throw new l(`No session with id "${t.sessionId}".`);if(e.status==="recording"||e.status==="paused")throw new l("The recording is still running; stop it first.");return e.outputPath}if(t.input)return t.input;throw new l("Pass input or sessionId.")}function dk(t){return t&&t.length>0?{markers:t.map(({t:e,label:r})=>({t:e,label:r}))}:{}}function Xh(t){t.registerResource("review-player",Uo,{title:"Recording review player",description:"Interactive player: scrub, trim, and draw redaction boxes on a recording.",mimeType:Qs},async()=>({contents:[{uri:Uo,mimeType:Qs,text:lk(),_meta:{ui:{prefersBorder:!0}}}]})),t.registerTool("review_recording",{title:"Review Recording",description:"Open a recording for a person to review: in MCP Apps clients an inline player to scrub, trim, and redact, then export; elsewhere just the video's details.",inputSchema:{input:lt.string().optional().describe("Path to the video."),sessionId:lt.string().optional().describe("Or the session id of a stopped recording.")},outputSchema:N({input:lt.string(),durationSec:lt.number().nullable(),width:lt.number().nullable(),height:lt.number().nullable(),fps:lt.number().nullable(),hasAudio:lt.boolean()}),annotations:he,_meta:Dh},async n=>{try{k();let o=pk(n);F(o);let i=await L(o);return v({input:o,durationSec:i.durationSec,width:i.width,height:i.height,fps:i.fps,hasAudio:i.audioCodec!==null,...dk(n.sessionId?re().get(n.sessionId)?.markers??Le(o):Le(o)),note:"Clients with MCP Apps show an inline review player for this result. Without it, look with contact_sheet or sample_frames, then trim and redact with pipeline."})}catch(o){return E(o)}});let e=t.registerTool("player_frames",{title:"Player Frames",description:"Preview frames for the review player: JPEGs on an even grid over the video plus frames at scene changes, with their real times. Used by the inline player; agents should use sample_frames or contact_sheet instead.",inputSchema:{input:lt.string().min(1).describe("Path to the video."),maxFrames:lt.number().int().min(1).max(Bh).optional().describe(`Frames on the even grid (default ${Zs}); scene-change frames come on top, up to as many again.`),width:lt.number().int().min(64).max(1280).optional().describe(`Frame width (default ${ju}).`)},annotations:he,_meta:{ui:{visibility:["app"]}}},async(n,o)=>{try{k(),F(n.input);let i=await L(n.input),s=i.durationSec??0,a=Wh(s,n.maxFrames??Zs),c=Ue(".txt"),u,d;try{let g=await Dr(jh(n.input,a,n.width??ju,c),le(s),{signal:o.signal});u=Hh(g),d=Uh(ck(c)?qh(c,"utf8"):"").slice(0,u.length)}finally{uk(c,{force:!0})}let[p]=d;if(!p)throw new l("ffmpeg returned no preview frames.");let f=zh(d,a.count).flatMap(g=>{let y=d[g],$=u[g];return y&&$?[{frame:y,jpeg:$}]:[]}),m=p.timeSec,h=[];try{h=(await mr(n.input,o.signal)).markers.map(({t:g,label:y})=>({t:g,label:y}))}catch{}let b=f.map(({frame:g})=>Math.round((g.timeSec-m)*1e3)/1e3),w=f.flatMap(({frame:g},y)=>g.scene?[y]:[]);return{content:[{type:"text",text:JSON.stringify({input:n.input,durationSec:s,width:i.width,height:i.height,hasAudio:i.audioCodec!==null,frameTimes:b,intervalSec:a.intervalSec,sceneFrames:w,markers:h})},...f.map(({jpeg:g})=>({type:"image",data:g.toString("base64"),mimeType:"image/jpeg"}))]}}catch(i){return E(i)}});e.disable();let r=t.server.oninitialized;t.server.oninitialized=()=>{r?.(),Lh(t.server.getClientCapabilities())&&e.enable()}}import{z as pt}from"zod";import{readFileSync as mk,rmSync as fk}from"node:fs";var Ae=1280,ea=8,zo=20;function hk(t,e,r){if(!Number.isInteger(r)||r<16)throw new l("maxImageWidth must be an integer of at least 16.");return["-y","-v","error","-i",t,"-frames:v","1","-vf",`scale='min(${r},iw)':-2`,"-q:v","4",...Ee(e)]}function ta(t){return Math.max(0,Math.min(zo,Math.floor(t??ea)))}async function Re(t,e=Ae,r=ea){let n=t.slice(0,r);return{images:await He(n,async i=>{let s=Ue(".jpg");try{return await Z(hk(i,s,e),3e4),{type:"image",data:mk(s).toString("base64"),mimeType:"image/jpeg"}}finally{fk(s,{force:!0})}}),omitted:t.length-n.length}}var gk={target:pt.string().describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | region:<x>,<y>,<w>,<h>. Titles match exactly, else as a substring; topmost wins."),exactTitle:pt.boolean().optional().describe("window: targets match the whole title only, never a substring (default false)."),backend:pt.enum(["gdigrab","wgc"]).optional().describe("gdigrab (default, ~0.2 s): what is visible. wgc (window:, FFmpeg 8+, ~1-2 s): the window even if covered."),output:pt.string().optional().describe("Optional output .png path. Defaults to a file under SCREENCAST_HOME/screenshots."),overwrite:pt.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),returnImage:pt.boolean().optional().describe("Return the image inline (default true; the PNG on disk stays full size)."),maxImageWidth:pt.number().int().min(16).optional().describe(`Max inline image width (default ${Ae}).`)};function Jh(t){t.registerTool("screenshot",{title:"Take Screenshot",description:"Capture one PNG of the screen, a monitor, a window, or a region, returned inline and by path.",inputSchema:gk,outputSchema:N({outputPath:pt.string(),target:pt.string(),backend:pt.string(),inlineImages:pt.number().int()}),annotations:I},async(e,r)=>{try{k();let n=await at(e.target,{exactTitle:e.exactTitle,backend:e.backend}),{window:o}=n,i=B(e.output,"shot",".png",{overwrite:e.overwrite,dir:"screenshots",anyContainer:!0}),s=e.backend??"gdigrab";await Ot(t,`Take a screenshot of ${Ft(e.target,o)}, saved to ${i}?`,r.signal),await Nt(n,i,s);let a=e.returnImage===!1?[]:(await Re([i],e.maxImageWidth??Ae,1)).images;return v({outputPath:i,target:e.target,backend:s,...o?cr(o):{},inlineImages:a.length},a)}catch(n){return E(n)}})}import{z as Pe}from"zod";import{join as Uu}from"node:path";import{mkdirSync as bk,readdirSync as Yh,existsSync as wk,rmSync as yk}from"node:fs";var xk={input:Pe.string().min(1).describe("Path to the source video file."),mode:Pe.enum(["fps","timestamps","scenes"]).optional().describe("scenes: only frames where the screen changed (strongest first), usually the cheapest review. Default: fps or timestamps, whichever is given."),fps:Pe.number().positive().optional().describe("Frames per second (mode fps)."),timestamps:Pe.array(Pe.number().nonnegative()).optional().describe("Seconds to grab a frame at (mode timestamps)."),sceneThreshold:Pe.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed to count, 0-1 (default ${gt}).`),dedupe:Pe.boolean().optional().describe("Mode fps: drop near-duplicate frames (default false)."),outputDir:Pe.string().optional().describe("Optional folder for the frames (a relative path resolves under SCREENCAST_HOME/frames). Defaults to SCREENCAST_HOME/frames/<id>."),maxFrames:Pe.number().int().min(1).max(kc).optional().describe(`Frame cap (default ${Ri}); fps is lowered to fit while still spanning the video.`),returnImages:Pe.boolean().optional().describe("Return the first maxInlineImages frames inline (default true)."),maxInlineImages:Pe.number().int().min(0).max(zo).optional().describe(`Frames to embed inline (default ${ea}); all are listed by path.`),maxImageWidth:Pe.number().int().min(16).optional().describe(`Max inline image width (default ${Ae}).`)};function Kh(t){t.registerTool("sample_frames",{title:"Sample Frames",description:"Sample PNG frames from a video (by fps, timestamps, or scene changes) and return the first few inline so the model can see what happened.",inputSchema:xk,outputSchema:N({frameDir:Pe.string(),frameCount:Pe.number().int(),frames:Pe.array(Pe.string()),mode:Pe.string()}),annotations:he},async(e,r)=>{try{k(),F(e.input);let n=e.fps!==void 0,o=e.timestamps!==void 0&&e.timestamps.length>0,i=e.mode??(o?"timestamps":"fps");if(!(i==="scenes"?!n&&!o:i==="fps"?n&&!o:o&&!n))throw new l("Use exactly one way to pick frames: fps (fixed rate), timestamps (explicit offsets), or mode: 'scenes' (with neither fps nor timestamps).");let a=e.maxFrames??Ri;if(o&&e.timestamps.length>a)throw new l(`${e.timestamps.length} timestamps exceeds maxFrames (${a}). Pass fewer timestamps, or raise maxFrames (up to ${kc}).`);let c=i==="timestamps"?null:(await L(e.input)).durationSec,u=i==="fps"?Mi(c,e.fps,a):null,d=null,p=[];if(i==="scenes"){let{ffmpeg:w}=k(),g=await ne(w,rr(e.input,e.sceneThreshold??gt),le(c),{signal:r.signal});if(g.code!==0)throw new l(`Scene scan failed (exit ${g.code}): ${g.stderr.trim().slice(-400)}`);d=nr(g.stdout),p=mn(d,a)}let f=ln(e.outputDir,we("frames"))??Uu(we("frames"),`sample-${ge()}-${be()}`);bk(f,{recursive:!0});let m=[],h=[];if(u){let w=S=>S.endsWith(".png"),g=new Set(Yh(f).filter(w)),y=kp(g,`${ge()}-${be()}`),$=un(f,`${y}%05d.png`);await Z(Ci(e.input,u.fps,$,a,e.dedupe===!0),le(c),{signal:r.signal}),m=Yh(f).filter(S=>w(S)&&S.startsWith(y)&&!g.has(S)).sort().map(S=>Uu(f,S))}else{let w=i==="scenes"?p:e.timestamps,g=await He(w,async(y,$)=>{let S=Uu(f,`frame_${String($).padStart(3,"0")}_${y}s.png`);return yk(S,{force:!0}),await Z(fn(e.input,y,S),6e4,{signal:r.signal}),S});for(let[y,$]of g.entries())wk($)?m.push($):h.push(w[y])}let b=e.returnImages===!1?{images:[],omitted:0}:await Re(m,e.maxImageWidth??Ae,ta(e.maxInlineImages));return v({frameDir:f,frameCount:m.length,frames:m,mode:u?`fps=${u.fps}${e.dedupe?" (deduped)":""}`:d?`scenes (threshold ${e.sceneThreshold??gt})`:`timestamps=[${e.timestamps.join(", ")}]`,...d?{frameTimes:p,sceneChangesFound:d.length,...d.length+1>a?{capNote:`Found ${d.length} scene changes; kept the opening frame and the ${a-1} strongest (maxFrames ${a}). Raise sceneThreshold to keep only bigger changes, or raise maxFrames.`}:{}}:{},...u?.clamped?{requestedFps:e.fps,capNote:`fps=${e.fps} would write about ${u.requestedFrames} frames, over maxFrames (${a}); sampled at fps=${u.fps} instead so the frames still span the whole video. Raise maxFrames or use timestamps for more detail.`}:{},...u&&!u.clamped&&m.length>=a?{capNote:`Stopped at maxFrames (${a}); the video's length could not be probed in advance.`}:{},inlineImages:b.images.length,...b.omitted>0?{inlineNote:`Embedded the first ${b.images.length} of ${m.length} frames inline; the other ${b.omitted} are on disk at the listed paths.`}:{},...h.length>0?{skippedTimestamps:h,note:`No frame was written for ${h.length} timestamp(s) past the end of the video: [${h.join(", ")}].`}:{}},b.images)}catch(n){return E(n)}})}import{z as Ve}from"zod";var Sk={input:Ve.string().min(1).describe("Path to the source video."),count:Ve.number().int().min(1).max(Af).optional().describe(`Frames to tile (default ${Oo}).`),mode:Ve.enum(["even","scenes"]).optional().describe("even (default) or scenes (strongest changes; static stretches take no tiles)."),sceneThreshold:Ve.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed, 0-1 (default ${gt}).`),columns:Ve.number().int().min(1).max(12).optional().describe("Tiles per row (default: roughly square)."),tileWidth:Ve.number().int().min(64).max(1920).optional().describe(`Tile width in px (default ${No}).`),poster:Ve.boolean().optional().describe("Write one representative poster frame instead of a sheet."),output:Ve.string().optional().describe("Optional output .png path. Defaults under SCREENCAST_HOME/frames."),overwrite:Ve.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),returnImage:Ve.boolean().optional().describe("Return the sheet inline (default true)."),maxImageWidth:Ve.number().int().min(16).optional().describe(`Max inline image width (default ${Ae}).`)};function Vh(t){t.registerTool("contact_sheet",{title:"Contact Sheet",description:"Tile timestamped frames of a video into one image to see a whole recording at a glance (the cheapest first look).",inputSchema:Sk,outputSchema:N({outputPath:Ve.string(),inlineImages:Ve.number().int()}),annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();F(e.input);let{durationSec:o}=await L(e.input);if(o===null)throw new l(`Could not read duration of ${e.input}.`);let i=e.poster?"poster":"sheet",s=er(e.output,we("frames"),`${i}-${ge()}-${be()}.png`,e.overwrite),a=e.tileWidth??No,c;if(e.poster)await Z(Rf(e.input,o,s,Math.max(a,1280)),le(o),{signal:r.signal}),c={outputPath:s,poster:!0};else{let d=e.count??Oo,p;if(e.mode==="scenes"){let m=await ne(n,rr(e.input,e.sceneThreshold??gt),le(o),{signal:r.signal});if(m.code!==0)throw new l(`Scene scan failed (exit ${m.code}): ${m.stderr.trim().slice(-400)}`);p=mn(nr(m.stdout),d)}else p=Ms(o,d);let f=await Cs(e.input,p,s,{tileWidth:a,columns:e.columns},r.signal);c={outputPath:s,mode:e.mode??"even",frameTimes:p,columns:f.columns,rows:f.rows}}let u=e.returnImage===!1?[]:(await Re([s],e.maxImageWidth??Ae,1)).images;return v({...c,inlineImages:u.length},u)}catch(n){return E(n)}})}import{z as Et}from"zod";import{rmSync as Ek}from"node:fs";var Qh=320,vk=4,$k=1600,$t=8,Ho=12;function Zh(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(Qh,t),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function na(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(t,Math.max(Qh,Math.min($k,Math.ceil(t/vk)))),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function oa(t,e){switch(t.kind){case"region":return{x:t.x,y:t.y,width:t.w,height:t.h};case"monitor":{let r=e.find(n=>n.index===t.index);if(!r)throw new l(`No monitor ${t.index}.`);return{x:r.x,y:r.y,width:r.width,height:r.height}}case"full":{if(e.length===0)throw new l("No monitors found.");let r=Math.min(...e.map(s=>s.x)),n=Math.min(...e.map(s=>s.y)),o=Math.max(...e.map(s=>s.x+s.width)),i=Math.max(...e.map(s=>s.y+s.height));return{x:r,y:n,width:o-r,height:i-n}}default:throw new l("Internal: resolve window targets to a region first.")}}function kk(t,e){if(t.length!==e.length||t.length===0)throw new l("Frames differ in size.");let r=0;for(let n=0;n<t.length;n++)r+=Math.abs(t[n]-e[n]);return r/t.length/255}function kt(t,e,r,n,o={}){if(t.length!==r*n||e.length!==r*n)throw new l("Frame size does not match its dimensions.");let i=o.pixelThreshold??Ho,s=Math.ceil(r/$t),a=Math.ceil(n/$t),c=new Uint8Array(s*a);for(let g=0;g<a;g++)for(let y=0;y<s;y++){let $=0,S=0;for(let C=g*$t;C<Math.min(n,(g+1)*$t);C++)for(let M=y*$t;M<Math.min(r,(y+1)*$t);M++){let R=C*r+M;$+=Math.abs(t[R]-e[R]),S++}$/S>i&&(c[g*s+y]=1)}let u=new Uint8Array(s*a),d=[];for(let g=0;g<c.length;g++){if(!c[g]||u[g])continue;let y={x0:1/0,y0:1/0,x1:-1,y1:-1,cells:0},$=[g];for(u[g]=1;$.length>0;){let S=$.pop(),C=S%s,M=Math.floor(S/s);y.x0=Math.min(y.x0,C),y.y0=Math.min(y.y0,M),y.x1=Math.max(y.x1,C),y.y1=Math.max(y.y1,M),y.cells++;for(let R=-1;R<=1;R++)for(let P=-1;P<=1;P++){let j=C+P,X=M+R;if(j<0||X<0||j>=s||X>=a)continue;let D=X*s+j;c[D]&&!u[D]&&(u[D]=1,$.push(D))}}d.push(y)}let p=o.scaleX??o.scale??1,f=o.scaleY??o.scale??1,m=o.origin?.x??0,h=o.origin?.y??0,b=d.sort((g,y)=>y.cells-g.cells).slice(0,o.maxRegions??20).map(g=>{let y=g.x0*$t,$=g.y0*$t,S=Math.min(r,(g.x1+1)*$t)-y,C=Math.min(n,(g.y1+1)*$t)-$;return{x:m+Math.round(y*p),y:h+Math.round($*f),width:Math.round(S*p),height:Math.round(C*f)}}),w=c.reduce((g,y)=>g+y,0);return{meanDiff:kk(t,e),changedFraction:w/c.length,regions:b}}function eg(t,e,r){return{scaleX:t.width/e.width,scaleY:t.height/e.height,pixelThreshold:r}}var ra=class{constructor(e,r,n,o={}){this.width=r;this.height=n;this.opts=o;this.previous=e,this.anchor=e}width;height;opts;previous;anchor;push(e){let r=kt(this.previous,e,this.width,this.height,this.opts).regions,n=r.length>0?r:kt(this.anchor,e,this.width,this.height,this.opts).regions;return this.previous=e,n.length>0&&(this.anchor=e),n}};function Go(t,e){return["-v","error","-i",t,"-frames:v","1","-vf",`scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function tg(t,e,r,n){return["-v","error","-probesize","32","-analyzeduration","0","-f","gdigrab","-framerate",String(Math.round(n*1e3)/1e3),...ki(t,e),"-vf",`scale=${r.width}:${r.height}:flags=area,format=gray`,"-flush_packets","1","-f","rawvideo","-"]}function rg(t,e,r){let n=`scale=${r.width}:${r.height}:flags=area,format=gray`;return["-v","info","-i",t,"-i",e,"-lavfi",`[0]${n}[x];[1]${n}[y];[x][y]ssim`,"-frames:v","1","-f","null","-"]}function qo(t,e,r){let n=e.map(o=>`drawbox=x=${o.x}:y=${o.y}:w=${o.width}:h=${o.height}:color=red@0.9:t=3`);return["-y","-v","error","-i",t,"-frames:v","1",...n.length?["-vf",n.join(",")]:[],...Ee(r)]}function ng(t){let e=t.match(/All:([\d.]+)/);return e?Number(e[1]):null}import{tmpdir as _k}from"node:os";import{join as Tk}from"node:path";var Ak={a:Et.string().min(1).describe("Before image (or video: first frame)."),b:Et.string().min(1).describe("After image (or video); scaled to a's size."),pixelThreshold:Et.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${Ho}).`),returnImage:Et.boolean().optional().describe("Return b inline with changes outlined (default true).")};function og(t){t.registerTool("screen_diff",{title:"Screen Diff",description:"Compare two screenshots or frames: SSIM score, changed share, and changed boxes in b's pixels, to check a UI change happened only where expected.",inputSchema:Ak,outputSchema:N({identical:Et.boolean(),ssim:Et.number().nullable(),meanDiff:Et.number(),changedFraction:Et.number(),regions:Et.array(Et.unknown())}),annotations:he},async(e,r)=>{try{k();for(let p of[e.a,e.b])F(p);let[n,o]=await Promise.all([L(e.a),L(e.b)]);if(!n.width||!n.height)throw new l(`Could not read the size of ${e.a}.`);let i=na(n.width,n.height),[s,a,c]=await Promise.all([Dr(Go(e.a,i),3e4,{signal:r.signal}),Dr(Go(e.b,i),3e4,{signal:r.signal}),ne(k().ffmpeg,rg(e.a,e.b,i),3e4,{signal:r.signal})]),u=kt(s,a,i.width,i.height,{scaleX:(o.width??n.width)/i.width,scaleY:(o.height??n.height)/i.height,pixelThreshold:e.pixelThreshold}),d=[];if(e.returnImage!==!1){let p=Tk(_k(),`screencast-diff-${ge()}-${be()}.png`);try{await Z(qo(e.b,u.regions,p),3e4,{signal:r.signal}),d.push(...(await Re([p],Ae,1)).images)}finally{Ek(p,{force:!0})}}return v({identical:u.regions.length===0,ssim:ng(c.stderr),meanDiff:Number(u.meanDiff.toFixed(4)),changedFraction:Number(u.changedFraction.toFixed(4)),regions:u.regions,...o.width!==n.width||o.height!==n.height?{note:`b (${o.width}x${o.height}) was compared at a's size (${n.width}x${n.height}).`}:{}},d)}catch(n){return E(n)}})}import{z as Te}from"zod";var Rk=t=>new Promise(e=>setTimeout(e,t));async function ig(t){let e=t.now??Date.now,r=t.sleep??Rk,n=e(),o=await t.grab(),i=new ra(o,t.width,t.height,t.diff),s=n,a=!1,c=[],u="timeout";for(;e()-n<t.timeoutMs;){if(t.signal.aborted){u="cancelled";break}await r(t.intervalMs);let d=await t.grab().catch(p=>{if(t.signal.aborted)return null;throw p});if(!d){u="cancelled";break}if(t.mode==="change"){let p=kt(o,d,t.width,t.height,t.diff);if(p.regions.length>0){c=p.regions,u="changed";break}}else{let p=i.push(d);if(p.length>0)a=!0,s=e(),c=p;else if(e()-s>=t.settleMs){u="settled";break}}}return{outcome:u,regions:c,everChanged:a,startedAt:n}}var Mk=t=>new Promise(e=>setTimeout(e,t));async function sg(t){let e=t.now??Date.now,r=t.sleep??Mk,n=e(),o=0,i=[],s=async()=>(o++,i=await t.read(),t.gone?i.length===0:i.length>0),a=()=>t.grab().catch(u=>{if(t.signal.aborted)return null;throw u}),c=await a();if(!c)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};if(await s())return{outcome:"matched",matches:i,reads:o,startedAt:n};for(;e()-n<t.timeoutMs;){if(t.signal.aborted)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};await r(t.intervalMs);let u=await a();if(!u)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};if(kt(c,u,t.width,t.height,t.diff).regions.length!==0&&(c=u,await s()))return{outcome:"matched",matches:i,reads:o,startedAt:n}}return{outcome:"timeout",matches:i,reads:o,startedAt:n}}var ia=class{waiters=[];error=null;ended=!1;push(e){let r=this.waiters;this.waiters=[];for(let n of r)n.resolve(e)}fail(e){this.error===null&&(this.error=e),this.rejectAll(this.error)}end(){this.ended=!0,this.rejectAll(new l("The screen capture ended unexpectedly."))}next(e){return this.error!==null?Promise.reject(this.error):this.ended?Promise.reject(new l("The screen capture ended unexpectedly.")):new Promise((r,n)=>{let o=setTimeout(()=>{this.waiters=this.waiters.filter(s=>s!==i),n(new l(`No frame from the screen capture within ${Math.round(e/1e3)}s.`))},e),i={resolve:s=>{clearTimeout(o),r(s)},reject:s=>{clearTimeout(o),n(s)}};this.waiters.push(i)})}rejectAll(e){let r=this.waiters;this.waiters=[];for(let n of r)n.reject(e)}};import{join as sa}from"node:path";import{mkdtempSync as Ck,rmSync as Xo}from"node:fs";import{tmpdir as ag}from"node:os";var Pk={target:Te.string().describe("What to watch: full | monitor:<i> | window:<title> (or exe=/hwnd=) | region:<x>,<y>,<w>,<h>."),exactTitle:Te.boolean().optional().describe("window: targets match the whole title only (default false)."),mode:Te.enum(["change","settle","text"]).optional().describe("change (default): return once it differs from the start. settle: once it has been still for settleSec. text: once text appears (OCR, re-read only after a change)."),text:Te.string().min(1).max(jr).optional().describe("Mode text: what to wait for; tolerates OCR misreads."),regex:Te.boolean().optional().describe("Mode text: text is a regex."),gone:Te.boolean().optional().describe("Mode text: wait until it disappears instead."),backend:Te.enum(["gdigrab","wgc"]).optional().describe("wgc: watch a window even when covered (window: targets; 1-2 s per check)."),timeoutSec:Te.number().positive().max(600).optional().describe("Give up after this many seconds (default 30; a timeout is a result, not an error)."),settleSec:Te.number().positive().max(60).optional().describe("Mode settle: seconds of stillness (default 1)."),intervalMs:Te.number().int().min(100).max(5e3).optional().describe("Pause between checks in ms (default 250; 1000 with wgc)."),pixelThreshold:Te.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${Ho}).`),returnImage:Te.boolean().optional().describe("Return the final state inline (default true)."),keep:Te.boolean().optional().describe("Keep the final screenshot on disk and return its path (default false).")};function cg(t){t.registerTool("wait_for_change",{title:"Wait for Screen Change",description:"Wait until part of the screen changes, settles, or shows (or loses) some text, instead of guessing a sleep. Returns the elapsed time, changed regions (screenshot pixels; add `origin` for desktop), and the final state.",inputSchema:Pk,outputSchema:N({outcome:Te.string(),mode:Te.string(),elapsedSec:Te.number(),regions:Te.array(Te.unknown()),origin:N({x:Te.number(),y:Te.number()})}),annotations:he},async(e,r)=>{try{k();let n=e.mode??"change";if(n==="text"!=(e.text!==void 0))throw new l('Use text with mode "text", and mode "text" with text.');let o=e.backend??"gdigrab",i=(e.timeoutSec??30)*1e3,s=(e.settleSec??1)*1e3,a=e.intervalMs??(o==="wgc"?1e3:250),c=await at(e.target,{exactTitle:e.exactTitle,backend:o}),{target:u,monitors:d,window:p}=c;if(o==="wgc"&&!p?.hwnd)throw new l('backend "wgc" watches one window: use a window: target.');let f=n==="text"?`"${e.text}" ${e.gone?"disappears":"appears"}`:n==="settle"?"stops changing":"changes";await Ot(t,`Watch ${Ft(e.target,p)} for up to ${i/1e3} s, until it ${f}?`,r.signal);let m=Ck(sa(ag(),"screencast-wait-")),h=0,b=async()=>{let x=sa(m,`still-${h++}.png`);return await Nt(c,x,o),x},w=oa(u,d);if(o==="wgc")try{let x=await L(await b());if(!x.width||!x.height)throw new l("Could not read the window capture's size.");w={...p?.client??{x:w.x,y:w.y},width:x.width,height:x.height}}catch(x){throw Xo(m,{recursive:!0,force:!0}),x}let g=na(w.width,w.height),y=eg(w,g,e.pixelThreshold),$=new ia,S=new AbortController,C=o==="gdigrab"?Wi(tg(u,d,g,1e3/a),g.width*g.height,x=>$.push(x),i+6e4,{signal:AbortSignal.any([r.signal,S.signal])}).then(()=>$.end(),x=>$.fail(x)):Promise.resolve(),M=o==="gdigrab"?()=>$.next(15e3):async()=>{let x=await b();try{return await Dr(Go(x,g),3e4,{signal:r.signal})}finally{Xo(x,{force:!0})}},R=o==="gdigrab"?async()=>{}:void 0,P,j=null,X=0;try{if(n==="text"){let x=await sg({grab:M,read:async()=>{let q=await b(),[H]=await ct([q],m,r.signal);return Xo(q,{force:!0}),H?yt(H.lines,e.text,e.regex===!0):[]},width:g.width,height:g.height,diff:y,timeoutMs:i,intervalMs:a,gone:e.gone===!0,signal:r.signal,...R?{sleep:R}:{}});j={matches:x.matches,reads:x.reads},P={outcome:x.outcome,regions:x.matches.map(({x:q,y:H,width:de,height:G})=>({x:q,y:H,width:de,height:G})),startedAt:x.startedAt}}else P=await ig({grab:M,mode:n,width:g.width,height:g.height,diff:y,timeoutMs:i,settleMs:s,intervalMs:a,signal:r.signal,...R?{sleep:R}:{}});X=Date.now()}finally{S.abort(),await C,Xo(m,{recursive:!0,force:!0})}let{outcome:D,regions:ae,everChanged:ee,startedAt:J}=P,ie={outcome:D,mode:n,elapsedSec:Number(((X-J)/1e3).toFixed(2)),...n==="settle"?{changedWhileWaiting:ee}:{},...j?{text:e.text,...e.gone?{gone:!0}:{},matches:j.matches,ocrReads:j.reads}:{},regions:ae,origin:{x:w.x,y:w.y},...o==="wgc"?{backend:o}:{},...p?cr(p):{}},ce=[];if(e.returnImage!==!1&&D!=="cancelled"){let x=e.keep?sa(we("screenshots"),`wait-${ge()}-${be()}.png`):sa(ag(),`screencast-wait-${ge()}-${be()}.png`);try{o==="wgc"?await Nt(c,x,"wgc"):await Z(_i(u,x,d),6e4,{signal:r.signal}),e.keep&&(ie.screenshotPath=x),ce.push(...(await Re([x],Ae,1)).images)}finally{e.keep||Xo(x,{force:!0})}}return v(ie,ce)}catch(n){return E(n)}})}import{z as qe}from"zod";import{extname as ug,join as Nn}from"node:path";import{mkdtempSync as Ik,rmSync as Fk}from"node:fs";import{tmpdir as Ok}from"node:os";var lg=new Set([".png",".jpg",".jpeg",".bmp",".gif",".webp",".tif",".tiff"]),aa=300,Nk={target:qe.string().optional().describe("Live screen target (full | monitor:<i> | window:... | region:...), or pass input."),input:qe.string().optional().describe("Image or video file to read instead of a live target."),timestamp:qe.number().nonnegative().optional().describe("Video input: second to read (default 0)."),scanEverySec:qe.number().positive().optional().describe("Video input: scan a frame every N s across the clip (e.g. for secrets before sharing); matches and redactRegions get times. Widens to stay within maxFrames."),maxFrames:qe.number().int().min(1).max(vs).optional().describe(`scanEverySec frame cap (default ${En}; ~1 s each).`),exactTitle:qe.boolean().optional().describe("window: targets match the whole title only (default false)."),backend:qe.enum(["gdigrab","wgc"]).optional().describe("Live target: gdigrab (default) = what is visible; wgc (window:, FFmpeg 8+) = the window even if covered."),query:qe.string().optional().describe("Text to find (case-insensitive, tolerates OCR misreads like I/l, O/0, _/-). Omit to return all text."),regex:qe.boolean().optional().describe("Treat query as a regular expression (case-insensitive)."),redact:qe.boolean().optional().describe("Also return padded match rectangles ready for redact_region's regions."),keep:qe.boolean().optional().describe("Live target: keep the capture and return its path (default false: deleted after reading)."),returnImage:qe.boolean().optional().describe("Return the image with matches outlined (default: true with a query).")};function pg(t){t.registerTool("find_text",{title:"Find Text (OCR)",description:"OCR (built into Windows) on the screen, an image, or video frames, with line and match boxes in image pixels (add `origin` for desktop coordinates). Locate UI text or secrets (e.g. regex 'sk-|ghp_|api.?key') to redact. Best-effort: review results.",inputSchema:Nk,outputSchema:N({imageSize:N({width:qe.number(),height:qe.number()})}),annotations:he},async(e,r)=>{try{if(k(),e.target===void 0==(e.input===void 0))throw new l("Provide exactly one of: target (live screen) or input (a file).");let n=Ik(Nn(Ok(),"screencast-ocr-"));try{if(e.scanEverySec!==void 0)return await Dk(e,n,r.signal);let o,i={},s;if(e.target!==void 0){let h=await at(e.target,{exactTitle:e.exactTitle,backend:e.backend});o=e.keep?Nn(we("screenshots"),`ocr-${ge()}-${be()}.png`):Nn(n,"capture.png");let b=e.backend??"gdigrab";await Ot(t,`Capture ${Ft(e.target,h.window)} once to read the text on it?`,r.signal),await Nt(h,o,b),h.window&&(i=cr(h.window));let w=oa(h.target,h.monitors);s=b==="wgc"&&h.window?.client?h.window.client:{x:w.x,y:w.y}}else{F(e.input);let h=lg.has(ug(e.input).toLowerCase());o=Nn(n,"frame.png"),await Z(["-y","-v","error",...h?[]:["-ss",String(e.timestamp??0)],"-i",e.input,"-frames:v","1",...Ee(o)],6e4,{signal:r.signal})}let[a]=await ct([o],n,r.signal);if(!a)throw new l("Could not read the frame.");let{lines:c,width:u,height:d}=a,p=e.query?yt(c,e.query,e.regex===!0):[],f=[];if(e.returnImage??!!e.query){let h=Nn(n,"shown.png");await Z(qo(o,p,h),3e4,{signal:r.signal}),f.push(...(await Re([h],Ae,1)).images)}return v({...e.target!==void 0?e.keep?{screenshotPath:o}:{}:{input:e.input},imageSize:{width:u,height:d},...s?{origin:s}:{},...e.query?{query:e.query,matchCount:p.length,matches:p,...e.redact?{redactRegions:xs(p,{width:u,height:d})}:{}}:{},text:c.map(h=>h.text).join(`
|
|
330
|
+
`),lines:c.slice(0,aa).map(({words:h,...b})=>b),...c.length>aa?{linesTruncated:c.length-aa}:{},...i,note:"OCR is best-effort: small or stylised text can be missed. Review before relying on it, especially for redaction."},f)}finally{Fk(n,{recursive:!0,force:!0})}}catch(n){return E(n)}})}async function Dk(t,e,r){if(t.input===void 0)throw new l("scanEverySec reads a video file: pass input, not target.");if(F(t.input),lg.has(ug(t.input).toLowerCase()))throw new l("scanEverySec is for a video input; an image has one frame, so drop scanEverySec.");let n=t.maxFrames??En,o=await Ss(t.input,{everySec:t.scanEverySec,maxFrames:n},e,r),{step:i}=o,[s]=o.frames;if(!s)throw new l("Could not read any frames from the video.");let a=new Set;for(let h of o.frames)for(let b of h.lines)a.add(b.text);let{matches:c,redactRegions:u}=t.query?kn(o,t.query,t.regex===!0):{matches:[],redactRegions:[]},d=[],p=c[0],f=p&&o.frames.find(h=>h.t===p.t)?.path;if((t.returnImage??!!t.query)&&p&&f){let h=Nn(e,"shown.png");await Z(qo(f,c.filter(b=>b.t===p.t),h),3e4,{signal:r}),d.push(...(await Re([h],Ae,1)).images)}let m=[...a].join(`
|
|
331
|
+
`);return v({input:t.input,imageSize:{width:s.width,height:s.height},scan:{everySec:Math.round(i*1e3)/1e3,framesScanned:o.frames.length,...o.clamped?{note:`Widened from ${t.scanEverySec} s to fit maxFrames ${n}.`}:{}},...t.query?{query:t.query,matchCount:c.length,matches:c.slice(0,aa),...t.redact?{redactRegions:u}:{}}:{},text:m.length>2e4?`${m.slice(0,2e4)}...`:m,note:"OCR is best-effort and reads only the sampled frames: text shown briefly between samples, or small or stylised text, can be missed. Review before sharing, especially for redaction."},d)}import{z as yr}from"zod";import{dirname as Hk,join as Hu}from"node:path";import{existsSync as Dn,mkdirSync as Gk,mkdtempSync as qk,readFileSync as Ln,readdirSync as Xk,rmSync as qu}from"node:fs";import{tmpdir as Jk}from"node:os";import{spawnSync as Lk}from"node:child_process";import{isAbsolute as Bk}from"node:path";var Hr=8;function ca(t){let e=/^ff(?:mpeg|probe) version (\S+)/m.exec(t)?.[1]??null,r=e?/^n?(\d+)\.\d+/.exec(e):null;if(r)return{version:e,major:Number(r[1]),inferred:!1};let n=/^\s*libavutil\s+(\d+)\./m.exec(t);return n&&Number(n[1])>=56?{version:e,major:Number(n[1])-52,inferred:!0}:{version:e,major:null,inferred:!1}}function dg(t){let e=new Set,r=t.split(/^\s*---\s*$/m).slice(1).join(`
|
|
332
|
+
`)||t;for(let n of r.split(/\r?\n/)){let o=/^\s{0,2}[D ][E ]\s?[d ]?\s+([a-z0-9_,]+)\s/i.exec(n);if(o?.[1])for(let i of o[1].split(","))e.add(i)}return[...e]}function zu(t,e){try{let r=Lk(t,e,{encoding:"utf8",windowsHide:!0,timeout:1e4});return r.status!==0?null:`${r.stdout??""}${r.stderr??""}`}catch{return null}}function ua(t){return zu(t,["-version"])}function mg(t){return zu(t,["-hide_banner","-devices"])}function fg(t){return Bk(t)?t:zu(process.platform==="win32"?"where":"which",[t])?.split(/\r?\n/).map(r=>r.trim()).find(r=>r.length>0)??null}var Wk=`
|
|
346
333
|
$ErrorActionPreference = 'Stop'
|
|
347
334
|
$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
|
|
348
335
|
$e = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
|
|
349
336
|
[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(`
|
|
337
|
+
`;async function wr(){if(process.platform!=="win32")return{available:!1,language:null,languages:[],error:"The Windows OCR engine is available on Windows only."};try{let t=JSON.parse(await st(Wk,"OCR languages",{timeoutMs:sr(15e3)})),e=Array.isArray(t.languages)?t.languages:t.languages?[t.languages]:[];return{available:t.available===!0,language:t.language??null,languages:e}}catch(t){return{available:!1,language:null,languages:[],error:U(t)}}}var jk=["SCREENCAST_HOME","SCREENCAST_ALLOWED_DIRS","FFMPEG_PATH","FFPROBE_PATH","SCREENCAST_WHISPER_MODEL","SCREENCAST_MAX_RECORDING_SEC","SCREENCAST_JOB_TIMEOUT_MS","SCREENCAST_PS_TIMEOUT_MS","SCREENCAST_RETENTION_DAYS","SCREENCAST_CONFIRM_CAPTURE","SCREENCAST_TOOLSETS","SCREENCAST_DEBUG_JOBS"],Uk=[{name:"SCREENCAST_MAX_RECORDING_SEC",ok:t=>Number.isInteger(t)&&t>=0&&t<=168*3600,want:"an integer from 0 (no cap) to 604800",otherwise:"start_recording fails until it is fixed"},{name:"SCREENCAST_JOB_TIMEOUT_MS",ok:t=>Number.isInteger(t)&&t>0,want:"a positive integer (milliseconds)",otherwise:"edits use the default timeout"},{name:"SCREENCAST_PS_TIMEOUT_MS",ok:t=>Number.isInteger(t)&&t>0,want:"a positive integer (milliseconds)",otherwise:"the PowerShell helpers use their default limits"},{name:"SCREENCAST_RETENTION_DAYS",ok:t=>Number.isFinite(t)&&t>=0,want:"a number of days (0 = off)",otherwise:"nothing is pruned"}],zk=["auto","1","true","yes","on","always","0","false","no","off","never"];function hg(t=process.env){let e=[];for(let n of Uk){let o=t[n.name];o===void 0||o.trim()===""||n.ok(Number(o.trim()))||e.push(`${n.name}="${o}" is not ${n.want}, so ${n.otherwise}.`)}let r=t.SCREENCAST_CONFIRM_CAPTURE;return r!==void 0&&r.trim()!==""&&!zk.includes(r.trim().toLowerCase())&&e.push(`SCREENCAST_CONFIRM_CAPTURE="${r}" is not auto, always (1/true/yes/on) or off (0/false/no/never), so captures follow auto.`),e}function gg(t=process.env){return Object.fromEntries(jk.map(e=>{let r=t[e];return[e,r&&r.trim().length>0?r:null]}))}var bg=[{filter:"whisper",tools:"transcribe",why:`FFmpeg ${Hr}+ built with whisper.cpp`},{filter:"gfxcapture",tools:'backend: "wgc" (screenshot, start_recording, find_text)',why:`FFmpeg ${Hr}+ on Windows`},{filter:"subtitles",tools:"burn_subtitles",why:"libass"},{filter:"drawtext",tools:"title_card, callout, contact_sheet labels, produce",why:"libfreetype"},{filter:"afftdn",tools:"denoise",why:"a standard build"},{filter:"loudnorm",tools:"normalize_audio",why:"a standard build"},{filter:"xfade",tools:"xfade_transition, assemble_highlights",why:"FFmpeg 4.3+"}];var Gu=8,Yk={input:yr.string().optional().describe("Recording path."),sessionId:yr.string().optional().describe("Or a stopped session id."),sceneThreshold:yr.number().gt(0).lt(1).optional().describe(`Change starting a segment (default ${Ou}).`),maxFrames:yr.number().int().min(1).max(Gf).optional().describe(`Keyframes to OCR (default ${Nu}).`),transcript:yr.string().optional().describe("An .srt, or 'whisper' to transcribe. Default: <video>.srt if any."),force:yr.boolean().optional().describe("Re-OCR despite a matching cached index.")};function wg(t){t.registerTool("index_recording",{title:"Index Recording",description:"Build a recording's text timeline (<video>.index.json: OCR per scene, events, markers, transcript) for search_recording.",inputSchema:Yk,outputSchema:N({indexPath:yr.string(),segments:yr.number()}),annotations:I},async(e,r)=>{let n=qk(Hu(Jk(),"screencast-index-"));try{let{ffmpeg:o}=k(),i=await qs(e),s=await L(i.path),a=s.videoDurationSec??s.durationSec;if(!s.width||a===null||!(a>0))throw new l(`Could not read the video size and duration of ${i.path}.`);let c=e.sceneThreshold??Ou,u=e.maxFrames??Nu,d=we("edits"),p=Xf(i.path,d),f=Hs(i.path),m=vo(r),h=[],b=e.force?null:js(i.path,d,f),w=b?Wo(b):null,g=null,y=async()=>g??=process.platform==="win32"&&(await wr()).available,$=Jf(w,{fingerprint:f,sceneThreshold:c,maxFrames:u,ocrAvailable:w!==null&&!w.ocr?await y():!1}),S,C=0,M=!1;if($)S=w.segments,C=w.framesRead,M=w.ocr;else{let J=await ne(o,rr(i.path,c),le(a),{signal:r.signal});if(J.code!==0)throw new l(`Scene scan failed (exit ${J.code}): ${J.stderr.trim().slice(-400)}`);m?.(.1);let ie=Vf(Kf(nr(J.stdout),a,u),a),ce=ie.map(()=>[]);if(M=await y(),M)for(let q=0;q<ie.length;q+=Gu){r.signal.throwIfAborted();let H=ie.slice(q,q+Gu),G=(await He(H,async(te,T)=>{let _=Hu(n,`key_${q+T}.png`);return await Z(fn(i.path,zs(te),_),6e4,{signal:r.signal}),{at:q+T,path:_}})).filter(te=>Dn(te.path)),Q=G.length>0?await ct(G.map(te=>te.path),n,r.signal,{sameSize:!0}):[];Q.forEach((te,T)=>ce[G[T].at]=te.lines.map(_=>_.text)),C+=Q.length,m?.(.1+.85*Math.min(ie.length,q+Gu)/ie.length)}else h.push("Windows OCR is not available, so the index holds no screen text; install an OCR language (doctor).");let x=ie.map((q,H)=>({...q,ocr:ce[H]??[]}));S=M?Qf(x):x}S=Yf(S);let R=i.eventsPath?Zf(je(Ln(i.eventsPath,"utf8"))):[];S=zr(S,R,"events"),S=zr(S,eh(i.markers),"markers");let P=xt(i.path);if(Dn(P)){let J=An(Ln(P,"utf8")),{busy:ie}=Tn(J),ce=ie.map(x=>{let q=Math.max(...J.filter(H=>H.t>=x.start&&H.t<=x.end).map(H=>H.cpu??H.sysCpu));return{t:x.start,text:`cpu pinned ${Math.round(q)}% for ${Math.round(x.end-x.start)} s (performance spike)`}});ce.length&&(S=zr(S,[...S.flatMap(x=>x.events??[]),...ce],"events"))}let j=Lt(i.path);if(Dn(j)){let J=Es(Ln(j,"utf8")),ie=Oe(J.map(ce=>`${ce.source}: ${ce.line}`),Ge);S=zr(S,J.map((ce,x)=>({t:ce.t,text:ie[x]??""})),"logs")}let X=await Kk(e.transcript,i.path,s.audioCodec!==null,a,r.signal,h);if(X!==null)S=zr(S,th(X),"transcript");else if($&&w){let J=w.segments.flatMap(ie=>ie.transcript??[]);S=zr(S,J,"transcript")}let D={version:Fu,video:i.path,fingerprint:f,durationSec:a,createdAt:new Date().toISOString(),sceneThreshold:c,maxFrames:u,framesRead:C,ocr:M,segments:S};Gk(Hu(p,".."),{recursive:!0}),rh(p,D);let ae=Du(i.path);if(ae!==p&&Dn(ae)){let J=Wo(ae);J&&Bs(J,i.path,f)&&qu(ae,{force:!0})}m?.(1);let ee=J=>S.reduce((ie,ce)=>ie+(ce[J]?.length??0),0);return v({indexPath:p,segments:S.length,cached:$,framesRead:C,durationSec:a,sources:{screenLines:S.reduce((J,ie)=>J+ie.ocr.length,0),events:ee("events"),markers:ee("markers"),transcriptCues:ee("transcript")},...h.length>0?{note:h.join(" ")}:{},next:"search_recording { query } returns timecoded hits. Secret-shaped screen text is stored masked; the rest of the index is plain text, so treat it like the video."})}catch(o){return E(o)}finally{qu(n,{recursive:!0,force:!0})}})}async function Kk(t,e,r,n,o,i){if(t==="whisper"){if(!r)return i.push("The recording has no audio, so there is no transcript."),null;if(!Ye("whisper"))throw new l("This ffmpeg has no whisper filter.","transcript: 'whisper' needs FFmpeg 8 built with whisper.cpp; or pass an .srt.");let c=br(void 0),u=Ue(".srt");try{return await Z(On(e,c,u),le(n),{signal:o}),Dn(u)?ut(We(Ln(u,"utf8"))):[]}finally{qu(u,{force:!0})}}if(t!==void 0){if(!Dn(t))throw new l(`Transcript not found: ${t}`);return ut(We(Ln(t,"utf8")))}let s;try{s=Xk(Hk(e))}catch{return null}let a=Us(e,s);return a.ambiguous&&i.push("Another video in the folder shares this one's base name, so its .srt was not attached; pass transcript."),a.path?ut(We(Ln(a.path,"utf8"))):null}import{z as jt}from"zod";import{join as yg}from"node:path";import{existsSync as xg,mkdtempSync as Vk,rmSync as Qk}from"node:fs";import{tmpdir as Zk}from"node:os";var eE=480,tE={input:jt.string().optional().describe("Recording path."),sessionId:jt.string().optional().describe("Or a stopped session id."),query:jt.string().min(1).describe("Text; tolerates OCR misreads."),regex:jt.boolean().optional().describe("query is a regex."),limit:jt.number().int().min(1).max(qf).optional().describe(`Max hits (default ${Ls}).`),images:jt.number().int().min(0).max(zo).optional().describe("Thumbnails of the top N hits (default 0).")};function Sg(t){t.registerTool("search_recording",{title:"Search Recording",description:"Search an index_recording timeline (screen text, events, markers, transcript): timecoded hits, best first, secrets masked. No frames unless asked. No input: search all indexes.",inputSchema:tE,outputSchema:N({total:jt.number(),hits:jt.array(jt.unknown())}),annotations:he},async(e,r)=>{try{if(e.input===void 0&&e.sessionId===void 0){if((e.images??0)>0)throw new l("images needs one recording.","Pass input or sessionId, or search the library with images: 0.");let f=oh(Me()).flatMap(b=>{let w=Lu(b);return w?[{indexPath:b,index:w}]:[]}),m=ih(f,e.query,{regex:e.regex===!0,limit:e.limit}),h=m.recordings.map(b=>({...b,...xg(b.video)?{}:{missing:!0}}));return v({query:e.query,searched:m.searched,total:m.total,hits:m.hits,recordings:h,...m.searched===0?{note:"No indexed recordings under SCREENCAST_HOME; run index_recording first."}:{}})}let n=await qs(e),o=Hs(n.path),i=js(n.path,we("edits"),o),s=i?Lu(i):null;if(!i||!s)throw new l(`No index for ${n.path}.`,"Run index_recording on it first.");let a=!Gs(s.fingerprint,o),{hits:c,total:u}=Bu(s,e.query,{regex:e.regex===!0,limit:e.limit,video:n.path,fingerprint:o}),d=Math.min(ta(e.images??0),c.length),p=[];if(d>0){k();let f=Vk(yg(Zk(),"screencast-search-"));try{let m=[];for(let[h,b]of c.slice(0,d).entries()){let w=b.t===b.start?zs(b):b.t,g=yg(f,`hit_${h}.png`);await Z(fn(n.path,w,g),6e4,{signal:r.signal}),xg(g)&&m.push(g)}p=(await Re(m,eE,d)).images}finally{Qk(f,{recursive:!0,force:!0})}}return v({indexPath:i,query:e.query,total:u,hits:c,...u>c.length?{more:u-c.length}:{},...s.ocr?{}:{note:"The index has no screen text (OCR was unavailable when it was built)."},...a?{stale:!0,warning:"The recording changed since it was indexed; run index_recording again."}:{}},p)}catch(n){return E(n)}})}import{z as xr}from"zod";var rE={input:xr.string().min(1).describe("Path to the media file to probe.")};function vg(t){t.registerTool("get_media_info",{title:"Get Media Info",description:"Probe a media file with ffprobe and return duration, resolution, frame rate, codecs, container format, and size.",inputSchema:rE,outputSchema:N({input:xr.string(),durationSec:xr.number().nullable(),width:xr.number().nullable(),height:xr.number().nullable(),fps:xr.number().nullable(),videoCodec:xr.string().nullable(),audioCodec:xr.string().nullable()}),annotations:he},async e=>{try{return F(e.input),v({input:e.input,...await L(e.input)})}catch(r){return E(r)}})}import{z as Gr}from"zod";import{extname as nE}from"node:path";var oE={input:Gr.string().min(1).describe("Path to the source video."),start:Gr.number().nonnegative().describe("Start time in seconds."),end:Gr.number().positive().optional().describe("End time in seconds. Use end OR duration."),duration:Gr.number().positive().optional().describe("Clip length in seconds. Use end OR duration."),exact:Gr.boolean().optional().describe("Re-encode for a frame-exact cut with the removed content really gone (default true). false = fast stream copy that snaps to a keyframe and keeps hidden earlier frames; never use it to remove secrets."),output:Gr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Gr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function $g(t){t.registerTool("trim",{title:"Trim Video",description:"Cut a video down to one sub-clip by start + (end or duration). For several segments use clip; to combine with other edits use pipeline.",inputSchema:oE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.exact===!1?nE(e.input)||".mp4":V(e.input),o=B(e.output,"trim",n,{overwrite:e.overwrite,anyContainer:e.exact===!1}),i=_p(e.input,o,{start:e.start,end:e.end,duration:e.duration,exact:e.exact}),s=e.start??0,a=e.end??await se(e.input),c=e.duration??(a!==null?a-s:null);return await W(i,{output:o,durationSec:c,extra:r}),v({outputPath:o})}catch(n){return E(n)}})}import{z as ma}from"zod";import{extname as pE,resolve as dE}from"node:path";import{writeFileSync as mE,rmSync as fE}from"node:fs";var iE=1920,sE=1080,kg=30,Eg=48e3,Bn=1,Xu="standard";function Ju(t){return Math.round(t*1e3)/1e3}function _g(t){return t.width!==void 0&&tr(t.width,"width"),t.height!==void 0&&tr(t.height,"height"),{w:t.width??iE,h:t.height??sE}}function aE(t,e,r){return`scale=${t}:${e}:force_original_aspect_ratio=decrease,pad=${t}:${e}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${r},format=yuv420p`}function cE(t){return`aresample=${t},aformat=sample_fmts=fltp:channel_layouts=stereo`}function uE(t,e){let r=[],n=0;for(let[o,i]of t.slice(0,-1).entries())n+=i,r.push(Math.max(0,Ju(n-(o+1)*e)));return r}function qr(t){return t.videoDurationSec??t.durationSec}function Tg(t,e,r,n,o={},i=[!1,!1]){let s=Sc(o.transition??"fade"),a=o.duration??Bn;if(!Number.isFinite(a)||a<=0)throw new l("transition duration must be a positive number.");if(!Number.isFinite(r[0])||r[0]<=a)throw new l(`first clip (${r[0]}s) must be longer than the transition (${a}s).`);return Jo([t,e],r,n,{...o,transition:s},i)}function Jo(t,e,r,n={},o=[]){if(t.length<2)throw new l("assemble_highlights requires at least two clips.");let{w:i,h:s}=_g(n),a=n.fps??kg,c=n.audioRate??Eg,u=n.transition??"cut",d=n.duration??Bn,p=t.length,f=aE(i,s,a),m=cE(c),h=o.some(Boolean),b=[];for(let g=0;g<p;g++)if(b.push(`[${g}:v]${f}[v${g}]`),!!h)if(o[g]){let y=e[g]??Number.NaN,$=Number.isFinite(y)&&y>0?`,apad,atrim=duration=${Ju(y)}`:"";b.push(`[${g}:a]${m}${$}[a${g}]`)}else{let y=e[g]??Number.NaN;if(!Number.isFinite(y)||y<=0)throw new l(`clip ${g} has no audio track and its duration is unknown, so a matching silent track cannot be generated.`);b.push(`anullsrc=channel_layout=stereo:sample_rate=${c}:d=${y}[a${g}]`)}let w=[];if(u==="cut")if(h){let g=t.map((y,$)=>`[v${$}][a${$}]`).join("");b.push(`${g}concat=n=${p}:v=1:a=1[vout][aout]`),w.push("-map","[vout]","-map","[aout]")}else{let g=t.map((y,$)=>`[v${$}]`).join("");b.push(`${g}concat=n=${p}:v=1:a=0[vout]`),w.push("-map","[vout]")}else{if(Sc(u),e.length!==p)throw new l(`a ${u} transition needs a duration for each of the ${p} clips.`);if(!Number.isFinite(d)||d<=0)throw new l("transition duration must be a positive number.");let g=e.findIndex(S=>!Number.isFinite(S)||S<=d);if(g!==-1)throw new l(`clip ${g} (${e[g]}s) must be longer than the ${d}s ${u} transition. Use a shorter transition or trim fewer frames.`);let y=uE(e,d),$="v0";for(let S=1;S<p;S++){let C=S===p-1?"vout":`vx${S}`;b.push(`[${$}][v${S}]xfade=transition=${u}:duration=${d}:offset=${y[S-1]}[${C}]`),$=C}if(w.push("-map","[vout]"),h){let S="a0";for(let C=1;C<p;C++){let M=C===p-1?"aout":`ax${C}`;b.push(`[${S}][a${C}]acrossfade=d=${d}[${M}]`),S=M}w.push("-map","[aout]")}}return["-y",...t.flatMap(g=>["-i",g]),"-filter_complex",b.join(";"),...w,...Se({quality:n.quality??Xu,audio:h?"aac":"none",faststart:!0}),r]}var Yu=3;function Ag(t,e,r,n={}){let{w:o,h:i}=_g(n),s=n.duration??Yu,a=n.fps??kg,c=De(n.bg??"black","bg"),u=De(n.fontColor??"white","fontColor"),d=n.fontSize??96;if(!Number.isFinite(s)||s<=0)throw new l("title duration must be a positive number.");if(!Number.isInteger(d)||d<=0)throw new l("fontSize must be a positive integer.");let p=`drawtext=fontfile=${ye(e)}:textfile=${ye(t)}:expansion=none:fontcolor=${u}:fontsize=${d}:x=(w-text_w)/2:y=(h-text_h)/2:shadowcolor=black@0.5:shadowx=2:shadowy=2`;return["-y","-f","lavfi","-i",`color=c=${c}:s=${o}x${i}:d=${s}:r=${a}`,"-f","lavfi","-i","anullsrc=channel_layout=stereo:sample_rate=48000","-vf",p,"-shortest",...Se({quality:n.quality??Xu,audio:"aac",faststart:!0}),r]}function Rg(t,e,r,n,o,i={}){if(!Number.isFinite(n)||n<=0)throw new l("video duration must be known and positive.");let s=i.musicVolume??(o?.25:.8),a=i.fadeIn??1,c=i.fadeOut??2;for(let[h,b]of[[s,"musicVolume"],[a,"fadeIn"],[c,"fadeOut"]])if(!Number.isFinite(h)||h<0)throw new l(`${b} must be a non-negative number.`);let u=i.duck??!1,d=Math.max(0,Ju(n-c)),p=`[1:a]afade=t=in:st=0:d=${a},afade=t=out:st=${d}:d=${c},volume=${s}`,f="amix=inputs=2:duration=first:dropout_transition=0:normalize=0",m=[];return o?(m.push(`${p}[music]`),u?(m.push("[music][0:a]sidechaincompress=threshold=0.03:ratio=8:attack=20:release=300[ducked]"),m.push(`[0:a][ducked]${f}[aout]`)):m.push(`[0:a][music]${f}[aout]`)):m.push(`${p}[aout]`),["-y","-i",t,"-stream_loop","-1","-i",e,"-filter_complex",m.join(";"),"-map","0:v","-map","[aout]","-t",String(n),...Se({video:["-c:v","copy"],audio:"aac",bitrate:"192k",faststart:!0}),r]}var Wn=["16:9","9:16","1:1","4:5"],la=["pad","crop"],jn={"16:9":{w:1920,h:1080},"9:16":{w:1080,h:1920},"1:1":{w:1080,h:1080},"4:5":{w:1080,h:1350}};function pa(t,e,r){return r==="crop"?`scale=${t}:${e}:force_original_aspect_ratio=increase,crop=${t}:${e},setsar=1`:`scale=${t}:${e}:force_original_aspect_ratio=decrease,pad=${t}:${e}:(ow-iw)/2:(oh-ih)/2,setsar=1`}function Mg(t,e,r,n="pad",o=Xu){let i=jn[r];if(!i)throw new l(`Unknown aspect "${r}".`);return["-y","-i",t,"-vf",`${pa(i.w,i.h,n)},format=yuv420p`,...Se({quality:o,audio:"copy",faststart:!0}),e]}var da=["youtube","instagram_reel","tiktok","x","square","steam_trailer","vertical_reel"],Ku={youtube:{aspect:"16:9",fps:30,videoBitrate:"8M",bufsize:"16M",audioBitrate:"192k"},instagram_reel:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},tiktok:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},x:{aspect:"16:9",fps:30,videoBitrate:"5M",bufsize:"10M",audioBitrate:"128k"},square:{aspect:"1:1",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},steam_trailer:{aspect:"16:9",fps:30,videoBitrate:"5.5M",bufsize:"11M",audioBitrate:"192k",cbr:!0,loudness:{sampleRate:48e3}},vertical_reel:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k",blurFill:!0,loudness:{}}};function lE(t,e,r=""){return`split=2[${r}bg][${r}fg];[${r}bg]scale=${t}:${e}:force_original_aspect_ratio=increase,crop=${t}:${e},boxblur=20:2,eq=brightness=-0.08[${r}b];[${r}fg]scale=${t}:${t}:force_original_aspect_ratio=decrease:force_divisible_by=2[${r}f];[${r}b][${r}f]overlay=(W-w)/2:(H-h)/2,setsar=1`}function Vu(t,e="pad",r=""){let n=Ku[t];if(!n)throw new l(`Unknown platform "${t}".`);let o=jn[n.aspect],i=n.blurFill?lE(o.w,o.h,r):pa(o.w,o.h,e),s=n.loudness?`loudnorm=I=-14:TP=-1:LRA=11,aresample=${n.loudness.sampleRate??Eg}`:void 0;return{vf:`${i},fps=${n.fps},format=yuv420p`,...s?{af:s}:{},encode:["-c:v","libx264","-preset","medium",...n.cbr?["-profile:v","high"]:[],"-b:v",n.videoBitrate,...n.cbr?["-minrate",n.videoBitrate,"-x264-params","nal-hrd=cbr"]:[],"-maxrate",n.videoBitrate,"-bufsize",n.bufsize,"-pix_fmt","yuv420p",...Cr(n.audioBitrate),...n.loudness?.sampleRate?["-ar",String(n.loudness.sampleRate),"-ac","2"]:[],"-r",String(n.fps),...Pr],width:o.w,height:o.h}}function Cg(t,e,r,n="pad"){let{vf:o,af:i,encode:s}=Vu(r,n);return["-y","-i",t,"-vf",o,...i?["-af",i]:[],...s,e]}var hE={inputs:ma.array(ma.string().min(1)).min(2).describe("Video paths to join, in order."),output:ma.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ma.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Pg(t){t.registerTool("concat",{title:"Concatenate Videos",description:"Join videos end to end with hard cuts: stream copy when they match, else a re-encode (`mode` says which). For transitions use xfade_transition or assemble_highlights.",inputSchema:hE,outputSchema:Y,annotations:I},async(e,r)=>{try{k();let n=e.inputs.map(m=>dE(m));for(let m of n)F(m);let o=await Promise.all(n.map(m=>L(m))),[i]=n,[s]=o;if(i===void 0||s===void 0)throw new l("concat needs at least two inputs.");let a=o.map(m=>qr(m)),c=a.every(m=>m!==null)?a.reduce((m,h)=>m+h,0):null,u=Ap(n,o);if(u!==null){let m=B(e.output,"concat",V(i),{overwrite:e.overwrite}),h=w=>w!==null&&w>=2?w-w%2:void 0,b=Jo(n,a.map(w=>w??0),m,{transition:"cut",width:h(s.width),height:h(s.height),fps:s.fps??void 0},o.map(w=>w.audioCodec!==null));return await W(b,{output:m,durationSec:c,extra:r}),v({outputPath:m,inputCount:n.length,mode:"reencode",reason:u})}let d=pE(i)||".mp4",p=B(e.output,"concat",d,{overwrite:e.overwrite,anyContainer:!0}),f=Ue(".txt");mE(f,Tp(n));try{await W(hn(f,p),{output:p,durationSec:c,extra:r})}finally{fE(f,{force:!0})}return v({outputPath:p,inputCount:n.length,mode:"copy"})}catch(n){return E(n)}})}import{z as Un}from"zod";var gE={input:Un.string().min(1).describe("Path to the source media."),format:Un.enum(["mp4","gif","webm"]).describe("mp4 (H.264), webm (VP9), or gif (palette)."),fps:Un.number().positive().optional().describe("gif only: fps (default 12)."),width:Un.number().positive().optional().describe("gif only: width in px (default 720)."),output:Un.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Un.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ig(t){t.registerTool("convert",{title:"Convert Format",description:"Convert media to mp4, webm, or gif. For a size-bounded GIF/WebP prefer export_gif; for a smaller mp4, compress or export_preset.",inputSchema:gE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.format,o=B(e.output,"convert",`.${n}`,{overwrite:e.overwrite,anyContainer:!0}),i=Rp(e.input,o,n,{fps:e.fps,width:e.width});return await W(i,{output:o,durationSec:await se(e.input),extra:r}),v({outputPath:o,format:n})}catch(n){return E(n)}})}import{z as Ut}from"zod";var fa=12,ha=960,Sr=1e7,Fg=5;function Og(t,e,r){return(t==="gif"?[[1,1,256],[.83,.8,256],[.67,.67,128],[.5,.5,64],[.4,.4,32],[.33,.33,16]]:[[1,1,75],[.83,.8,65],[.67,.67,55],[.5,.5,45],[.4,.4,35],[.33,.33,25]]).map(([o,i,s])=>({fps:Math.max(1,Math.round(e*o*10)/10),width:Math.max(64,Math.round(r*i/2)*2),...t==="gif"?{colors:s}:{quality:s}}))}function Ng(t,e,r,n){let o=n-1;if(t>=o)return null;let i=Math.max(1,Math.ceil(Math.log(e/r)/Math.log(1.8)));return Math.min(o,t+i)}function Dg(t,e,r,n,o={}){if(!(n.fps>0)||!Number.isInteger(n.width)||n.width<16)throw new l("fps must be positive and width an integer of at least 16.");if(o.start!==void 0&&!(o.start>=0))throw new l("start must be >= 0.");if(o.duration!==void 0&&!(o.duration>0))throw new l("duration must be > 0.");let i=[...o.start?["-ss",String(o.start)]:[],...o.duration?["-t",String(o.duration)]:[]],s=`fps=${n.fps},scale='min(${n.width},iw)':-1:flags=lanczos`;if(r==="gif"){let a=n.colors??256;return["-y",...i,"-i",t,"-an","-vf",`${s},split[a][b];[a]palettegen=stats_mode=diff:max_colors=${a}[p];[b][p]paletteuse=dither=sierra2_4a:diff_mode=rectangle`,"-loop","0",e]}return["-y",...i,"-i",t,"-an","-vf",s,"-c:v","libwebp_anim","-lossless","0","-q:v",String(n.quality??75),"-compression_level","4","-loop","0",e]}import{basename as bE,dirname as wE,extname as yE,join as xE}from"node:path";import{renameSync as SE,rmSync as vE,statSync as $E}from"node:fs";async function zn(t,e,r,n){let o=r.format??"gif",i=r.maxBytes??Sr,s=await se(t),a=r.duration??(s!==null?s-(r.start??0):null),c=Og(o,r.fps??fa,r.width??ha),u=yE(e),d=f=>xE(wE(e),`${bE(e,u)}.try${f}${u}`),p=[];try{let f=0;for(;f!==null&&p.length<Fg;){let b=c[f];if(!b)break;let w=d(p.length),g={start:r.start,duration:r.duration};await W(Dg(t,w,o,b,g),{output:w,durationSec:a,extra:n});let y=$E(w).size;if(p.push({path:w,size:y,settings:b}),y<=i)break;f=Ng(f,y,i,c.length)}let m=p.find(b=>b.size<=i),h=m??p.reduce((b,w)=>w.size<b.size?w:b);return SE(h.path,e),{outputPath:e,format:o,sizeBytes:h.size,maxBytes:i,withinBudget:h.size<=i,settings:h.settings,attempts:p.map(b=>({...b.settings,sizeBytes:b.size})),...m?{}:{note:`Could not get under ${i} bytes; kept the smallest attempt. Export a shorter clip (start/duration), or try format: 'webp'.`}}}finally{for(let f of p)vE(f.path,{force:!0})}}var kE={input:Ut.string().min(1).describe("Path to the source video."),format:Ut.enum(["gif","webp"]).optional().describe("gif (default) or webp (usually much smaller)."),maxBytes:Ut.number().int().min(1e4).optional().describe(`Size budget in bytes (default ${Sr}, under GitHub's 10 MB image limit).`),fps:Ut.number().positive().max(30).optional().describe(`Starting frame rate (default ${fa}).`),width:Ut.number().int().min(64).max(1920).optional().describe(`Starting width in px (default ${ha}).`),start:Ut.number().nonnegative().optional().describe("Start second."),duration:Ut.number().positive().optional().describe("Seconds to export (default: to the end)."),output:Ut.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ut.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Lg(t){t.registerTool("export_gif",{title:"Export GIF or WebP",description:"Export an animated GIF or WebP that fits a size budget (for PRs, issues, READMEs), stepping fps, width, and quality down until it fits.",inputSchema:kE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.format??"gif",o=e.maxBytes??Sr,i=B(e.output,"anim",`.${n}`,{overwrite:e.overwrite,anyContainer:!0});return v(await zn(e.input,i,{format:n,maxBytes:o,fps:e.fps,width:e.width,start:e.start,duration:e.duration},r))}catch(n){return E(n)}})}import{z as Xr}from"zod";var EE={input:Xr.string().min(1).describe("Path to the source video."),x:Xr.number().int().nonnegative(),y:Xr.number().int().nonnegative(),width:Xr.number().int().positive(),height:Xr.number().int().positive(),output:Xr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Xr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Bg(t){t.registerTool("crop",{title:"Crop Video",description:"Crop a video to a pixel rectangle; one running off the frame is rejected.",inputSchema:EE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let{width:n,height:o,durationSec:i}=await L(e.input),s=V(e.input),a=B(e.output,"crop",s,{overwrite:e.overwrite}),c=Mp(e.input,a,{x:e.x,y:e.y,width:e.width,height:e.height},{width:n,height:o});return await W(c,{output:a,durationSec:i,extra:r}),v({outputPath:a})}catch(n){return E(n)}})}import{z as Yo}from"zod";var _E={input:Yo.string().min(1).describe("Path to the source video."),width:Yo.number().int().positive().optional().describe("Target width in px. Omit to derive from height (keeps aspect)."),height:Yo.number().int().positive().optional().describe("Target height in px. Omit to derive from width (keeps aspect)."),output:Yo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Yo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Wg(t){t.registerTool("scale",{title:"Scale Video",description:"Resize a video to a target width and/or height and re-encode. Provide one side to keep the aspect ratio, or both to set an exact size.",inputSchema:_E,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=V(e.input),o=B(e.output,"scale",n,{overwrite:e.overwrite}),i=Pp(e.input,o,{width:e.width,height:e.height});return await W(i,{output:o,durationSec:await se(e.input),extra:r}),v({outputPath:o})}catch(n){return E(n)}})}import{z as Qo}from"zod";import{z as ga}from"zod";function _t(t){if(t.length===0)return"0";if(t.length<=50)return t.join("+");let e=[];for(let r=0;r<t.length;r+=50)e.push(`(${t.slice(r,r+50).join("+")})`);return _t(e)}var Yr=2,Ko=.4,Hn=200;function ba(t,e,r){if(!(e>0))throw new l("minIdleSec must be positive.");return["-hide_banner","-nostats","-v","info","-i",t,"-vf",`freezedetect=n=-60dB:d=${e}`,...r?["-af",`silencedetect=n=-40dB:d=${e}`]:["-an"],"-f","null","-"]}function jg(t,e,r,n){let o=[],i=null;for(let s of t.split(/\r?\n/)){let a=s.match(e);if(a){i=Number(a[1]);continue}let c=s.match(r);c&&i!==null&&(o.push({start:i,end:Number(c[1])}),i=null)}return i!==null&&n>i&&o.push({start:i,end:n}),o}function wa(t,e){return jg(t,/freeze_start:\s*([\d.]+)/,/freeze_end:\s*([\d.]+)/,e)}function ya(t,e){return jg(t,/silence_start:\s*([\d.]+)/,/silence_end:\s*([\d.]+)/,e)}function xa(t,e){let r=[],n=0,o=0;for(;;){let i=t[n],s=e[o];if(!i||!s)break;let a=Math.max(i.start,s.start),c=Math.min(i.end,s.end);c>a&&r.push({start:a,end:c}),i.end<s.end?n++:o++}return r}function Sa(t,e,r){return t.filter(n=>n.end-n.start>=e).map(n=>({start:n.start+r,end:n.end-r})).filter(n=>n.end-n.start>.05).map(n=>({start:Number(n.start.toFixed(3)),end:Number(n.end.toFixed(3))}))}function Qu(t){if(t.length===0)throw new l("Nothing to cut.");if(t.length>Hn)throw new l(`Too many idle stretches (${t.length}); raise minIdleSec.`);let e=_t(t.map(n=>`between(t,${n.start},${n.end})`)),r=_t(t.map(n=>`clip(T-${n.start},0,${Number((n.end-n.start).toFixed(3))})`));return{video:`select='not(${e})',setpts='(T-(${r}))/TB'`,audio:`asetnsamples=n=256:p=0,aselect='not(${e})',asetpts=N/SR/TB`}}var Jr=100,va=ga.object({start:ga.number().min(0),end:ga.number().positive(),factor:ga.number().gt(1).max(Jr)}),Vo=8;function $a(t,e){if(t.length===0)throw new l("segments needs at least one range.");if(t.length>Hn)throw new l(`Too many ranges (${t.length}); at most ${Hn}.`);let r=[...t].sort((n,o)=>n.start-o.start).map(n=>({start:Number(n.start.toFixed(3)),end:Number(n.end.toFixed(3)),factor:n.factor}));return r.forEach((n,o)=>{if(!(n.end>n.start)||n.start<0)throw new l(`Range ${n.start}-${n.end}s: end must be after start, from 0.`);if(!(n.factor>1)||n.factor>Jr)throw new l(`Range ${n.start}-${n.end}s: factor must be above 1 and at most ${Jr} (for slow motion, use factor on the whole clip).`);if(e!==null&&n.start>=e)throw new l(`Range ${n.start}-${n.end}s starts after the video ends (${e}s).`);let i=r[o-1];if(i&&n.start<i.end)throw new l(`Ranges ${i.start}-${i.end}s and ${n.start}-${n.end}s overlap.`)}),r}function Kr(t){return t.reduce((e,r)=>e+(r.end-r.start)*(1-1/r.factor),0)}function ka(t,e){if(t.length===0)throw new l("Nothing to speed up.");let r=s=>Number((1-1/s.factor).toFixed(6)),n=_t(t.map(s=>`clip(T-${s.start},0,${Number((s.end-s.start).toFixed(3))})*${r(s)}`)),o=s=>Number((s.start+(s.end-s.start)/s.factor).toFixed(3)),i=_t(t.map(s=>`between(t,${o(s)},${s.end})`));return{video:`setpts='(T-(${n}))/TB'`+(e?`,fps=${Number(e.toFixed(3))}`:""),audio:`asetnsamples=n=256:p=0,aselect='not(${i})',asetpts=N/SR/TB`}}function Ea(t,e,r,n){let o=ka(r,n.fps);return["-y","-i",t,"-vf",o.video,...n.withAudio?["-af",o.audio]:["-an"],...Se({quality:n.quality??"standard",audio:n.withAudio?"aac":"omit"}),e]}function _a(t,e,r,n,o="standard"){let i=Qu(r);return["-y","-i",t,"-vf",i.video,...n?["-af",i.audio]:["-an"],...Se({quality:o,audio:n?"aac":"omit"}),e]}var TE={input:Qo.string().min(1).describe("Path to the source video."),factor:Qo.number().positive().optional().describe("Whole clip: >1 faster, <1 slower."),segments:Qo.array(va).min(1).optional().describe("Or fast-forward just these ranges (audio shortened, not pitched)."),output:Qo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ug(t){t.registerTool("speed",{title:"Change Speed",description:"Change playback speed, or fast-forward ranges, and re-encode. Audio is retempo'd to match.",inputSchema:TE,outputSchema:Y,annotations:I},async(e,r)=>{try{if(k(),F(e.input),e.factor===void 0==(e.segments===void 0))throw new l("Pass factor (the whole clip) or segments (ranges), not both.");let{audioCodec:n,durationSec:o,fps:i}=await L(e.input),s=V(e.input),a=B(e.output,"speed",s,{overwrite:e.overwrite}),c=n!==null;if(e.segments){let p=$a(e.segments,o),f=Kr(p);return await W(Ea(e.input,a,p,{withAudio:c,fps:i}),{output:a,durationSec:o!==null?o-f:null,inputDurationSec:o,extra:r}),v({outputPath:a,segments:p,savedSec:Number(f.toFixed(2)),audio:c})}let u=e.factor,d=Ip(e.input,a,u,c);return await W(d,{output:a,durationSec:o!==null?o/u:null,inputDurationSec:o,extra:r}),v({outputPath:a,factor:u,audio:c})}catch(n){return E(n)}})}import{z as dt}from"zod";var AE={input:dt.string().min(1).describe("Path to the base video."),overlay:dt.string().min(1).describe("Overlay image or video path."),x:dt.number().int().nonnegative().describe("Left, px."),y:dt.number().int().nonnegative().describe("Top, px."),width:dt.number().int().positive().optional().describe("Scale to this width (other side keeps aspect)."),height:dt.number().int().positive().optional().describe("Scale to this height."),start:dt.number().nonnegative().optional().describe("Show from this second."),end:dt.number().positive().optional().describe("Hide after this second."),shape:dt.enum(["rect","circle"]).optional().describe("circle: centre square masked round (webcam)."),output:dt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:dt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function zg(t){t.registerTool("overlay",{title:"Overlay Image or Video",description:"Composite an image or video (logo, watermark, picture-in-picture) onto a video at a pixel position, optionally scaled and time-limited; keeps the base's audio and length.",inputSchema:AE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input),F(e.overlay,"Overlay file");let n=V(e.input),o=B(e.output,"overlay",n,{overwrite:e.overwrite}),i=e.width!==void 0||e.height!==void 0?{width:e.width,height:e.height}:void 0,s=await se(e.input),a=Fp(e.input,e.overlay,o,{x:e.x,y:e.y,start:e.start,end:e.end,scale:i,shape:e.shape,durationSec:s});return await W(a,{output:o,durationSec:s,extra:r}),v({outputPath:o})}catch(n){return E(n)}})}import{z as ot}from"zod";import{mkdtempSync as PE,rmSync as IE,writeFileSync as FE}from"node:fs";import{tmpdir as OE}from"node:os";import{join as Jg}from"node:path";var qg=["side_by_side","stack","grid"],Ta=2,Aa=9,Hg=3840,RE=1080,Gg=t=>Math.max(2,Math.round(t/2)*2);function ME(t,e){if(t==="side_by_side")return{cols:e,rows:1};if(t==="stack")return{cols:1,rows:e};let r=Math.ceil(Math.sqrt(e));return{cols:r,rows:Math.ceil(e/r)}}function CE(t,e){let r=Math.min(t.height,RE),n=t.width*r/t.height,o=Math.min(1,Hg/(n*e.cols),Hg/(r*e.rows));return n*=o,r*=o,{width:Gg(n),height:Gg(r)}}function Zu(t,e){let r=t.map(n=>Math.max(0,n.durationSec-n.skipSec));return e==="longest"?Math.max(...r):Math.min(...r)}function Xg(t,e,r){let n=t.length;if(n<Ta||n>Aa)throw new l(`compose takes ${Ta} to ${Aa} inputs.`);let o=t[0],i=ME(r.layout,n),s=CE(o,i),a=Zu(t,r.endWith);if(!(a>0))throw new l("Nothing is left to show after lining the inputs up.");let c=[];t.forEach((m,h)=>{let b=Math.max(0,a-(m.durationSec-m.skipSec)),w=m.label?`,drawtext=fontfile=${ye(m.label.fontFile)}:textfile=${ye(m.label.textFile)}:expansion=none:fontcolor=white:fontsize=${Math.max(14,Math.round(s.height/18))}:x=12:y=12:box=1:boxcolor=black@0.6:boxborderw=8`:"";c.push(`[${h}:v]fps=${r.fps},scale=${s.width}:${s.height}:force_original_aspect_ratio=decrease,pad=${s.width}:${s.height}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,format=yuv420p`+(b>.001?`,tpad=stop_mode=clone:stop_duration=${b.toFixed(3)}`:"")+`${w}[c${h}]`)});let u=t.map((m,h)=>`${h%i.cols*s.width}_${Math.floor(h/i.cols)*s.height}`).join("|");c.push(`${t.map((m,h)=>`[c${h}]`).join("")}xstack=inputs=${n}:layout=${u}:fill=black[v]`);let d=t.map((m,h)=>m.hasAudio?h:-1).filter(m=>m>=0),p=[];if(r.audio==="mix"&&d.length>0)c.push(`${d.map(m=>`[${m}:a]`).join("")}amix=inputs=${d.length}:normalize=0:duration=longest,apad[a]`),p=["-map","[a]"];else if(typeof r.audio=="number"){if(!t[r.audio])throw new l(`audio ${r.audio} is not an input (0-${n-1}).`);if(!t[r.audio].hasAudio)throw new l(`Input ${r.audio} has no audio; pick another, "mix", or "none".`);c.push(`[${r.audio}:a]apad[a]`),p=["-map","[a]"]}let f=p.length>0;return["-y",...t.flatMap(m=>[...m.skipSec>0?["-ss",m.skipSec.toFixed(3)]:[],"-i",m.path]),"-filter_complex",c.join(";"),"-map","[v]",...p,"-t",a.toFixed(3),...Se({quality:r.quality??"standard",audio:f?"aac":"omit"}),e]}var NE={inputs:ot.array(ot.object({path:ot.string().min(1),label:ot.string().min(1).max(80).optional()})).min(Ta).max(Aa).describe('Videos in reading order, each with an optional label (e.g. "Before").'),layout:ot.enum(qg).optional().describe("side_by_side (default), stack, or grid."),alignMarker:ot.string().min(1).optional().describe("Line inputs up on this add_marker label."),endWith:ot.enum(["longest","shortest"]).optional().describe("longest (default; shorter ones hold their last frame) or shortest."),audio:ot.union([ot.number().int().min(0),ot.enum(["mix","none"])]).optional().describe('Input index whose audio to keep (default 0), "mix", or "none".'),output:ot.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ot.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Yg(t){t.registerTool("compose",{title:"Compose Videos",description:"Lay 2-9 videos out side by side, stacked, or in a grid (before/after, app and terminal), labelled and in sync.",inputSchema:NE,outputSchema:Y,annotations:I},async(e,r)=>{let n=PE(Jg(OE(),"screencast-compose-"));try{k();let o=[],i=[];for(let[f,m]of e.inputs.entries()){F(m.path,`Input ${f}`);let h=await L(m.path);if(!h.width||!h.height||h.durationSec===null)throw new l(`Input ${f} has no readable video: ${m.path}`);let b=0;if(e.alignMarker){let g=Le(m.path).find(y=>y.label===e.alignMarker);if(!g)throw new l(`Input ${f} has no marker "${e.alignMarker}".`,"Add one with add_marker, or leave alignMarker out.");b=g.t}let w;if(m.label){let g=vt(m.label);g.warning&&i.push(g.warning);let y=Jg(n,`label${f}.txt`);FE(y,m.label),w={textFile:y,fontFile:g.fontFile}}o.push({path:m.path,width:h.width,height:h.height,durationSec:h.durationSec,hasAudio:h.audioCodec!==null,skipSec:b,label:w})}if(e.alignMarker){let f=Math.min(...o.map(m=>m.skipSec));for(let m of o)m.skipSec-=f}let s=e.endWith??"longest",a=e.audio??(o[0].hasAudio?0:"none"),c=(await L(o[0].path)).fps??30,u=B(e.output,"compose",".mp4",{overwrite:e.overwrite}),d=Xg(o,u,{layout:e.layout??"side_by_side",endWith:s,audio:a,fps:Math.min(60,Math.round(c))}),p=Zu(o,s);return await W(d,{output:u,durationSec:p,extra:r}),v({outputPath:u,durationSec:Number(p.toFixed(2)),layout:e.layout??"side_by_side",...e.alignMarker?{alignedOn:e.alignMarker,skipSec:o.map(f=>Number(f.skipSec.toFixed(3)))}:{},...i.length?{warnings:i}:{}})}catch(o){return E(o)}finally{IE(n,{recursive:!0,force:!0})}})}import{z as Vr}from"zod";import{existsSync as BE,mkdtempSync as WE,readFileSync as jE,rmSync as UE,writeFileSync as zE}from"node:fs";import{tmpdir as HE}from"node:os";import{join as tb}from"node:path";var Vg=["cpu","sysCpu","rssMB","sysMem"],Qg=["top_left","top_right","bottom_left","bottom_right"],DE=120,el={cpu:"App CPU %",sysCpu:"CPU %",rssMB:"App memory MB",sysMem:"Memory %"};function Zg(t,e,r,n=DE){if(!(r>0))throw new l("The video has no duration.");let o=new Array(n).fill(null);for(let s of t){let a=s[e];if(a===void 0||!Number.isFinite(a)||s.t<0||s.t>=r)continue;let c=Math.min(n-1,Math.floor(s.t/r*n));o[c]=Math.max(o[c]??-1/0,a)}let i=null;return o.map(s=>s===null?i:i=s)}function LE(t,e){if(t!=="rssMB")return 100;let r=Math.max(0,...e.map(n=>n??0));return r>0?Math.ceil(r/50)*50:1}var Kg=t=>Math.max(2,Math.round(t/2)*2);function eb(t,e,r,n){let o=Kg(n.width),i=Kg(n.height);if(o>n.videoWidth||i>n.videoHeight)throw new l("The chart is larger than the video.");let s=LE(n.metric,r),a=Math.round(i*.25),c=i-a-4,u=o/r.length,d=r.flatMap((y,$)=>{if(y===null||y<=0)return[];let S=Math.max(1,Math.round(Math.min(y,s)/s*c)),C=n.metric!=="rssMB"&&n.metric!=="sysMem"&&y>=fu;return[`drawbox=x=${Math.floor($*u)}:y=${i-2-S}:w=${Math.max(1,Math.ceil(u))}:h=${S}:color=${C?"0xFF5252":"0x4FC3F7"}@0.95:t=fill`]}),p=Number(n.durationSec.toFixed(3)),f=n.label?`,drawtext=fontfile=${ye(n.label.fontFile)}:textfile=${ye(n.label.textFile)}:expansion=none:fontcolor=white:fontsize=${Math.max(10,Math.round(a*.7))}:x=6:y=${Math.round(a*.15)}`:"",m=Math.round(Math.min(n.videoWidth,n.videoHeight)*.02),h=n.corner.endsWith("left")?m:n.videoWidth-o-m,b=n.corner.startsWith("top")?m:n.videoHeight-i-m,w=[`color=c=0x1E1E1E:s=${o}x${i}:d=${p}:r=30`,"format=yuv420p",...d].join(",")+f,g=`color=c=white:s=2x${i-a}:d=${p}:r=30`;return["-y","-i",t,"-filter_complex",`${w}[c];${g}[p];[c][p]overlay=x='min(${o-2},t/${p}*${o})':y=${a}:shortest=1[g];[0:v][g]overlay=x=${h}:y=${b}:shortest=1[v]`,"-map","[v]","-map","0:a?",...Se({quality:n.quality??"standard",audio:n.hasAudio?"copy":"omit",faststart:!0}),e]}var GE={input:Vr.string().min(1).describe("A recording made with perf: true."),perf:Vr.string().optional().describe("Its .perf.jsonl (default: next to input)."),metric:Vr.enum(Vg).optional().describe("Default cpu (the app's) if sampled, else sysCpu."),corner:Vr.enum(Qg).optional().describe("Default top_right."),width:Vr.number().int().min(80).max(1920).optional().describe("Chart width px (default video/4)."),output:Vr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Vr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function rb(t){t.registerTool("perf_overlay",{title:"Performance Overlay",description:"Draw a recording's CPU or memory track as a small chart with a moving playhead (spikes in red).",inputSchema:GE,outputSchema:Y,annotations:I},async(e,r)=>{let n=WE(tb(HE(),"screencast-perf-"));try{k(),F(e.input);let o=e.perf??xt(e.input);if(!BE(o))throw new l(`No performance track at ${o}.`,"Record with start_recording perf: true, or pass perf.");let i=An(jE(o,"utf8"));if(i.length===0)throw new l(`${o} has no samples.`);let s=await L(e.input);if(!s.width||!s.height||!s.durationSec)throw new l(`Could not read the size and length of ${e.input}.`);let a=e.metric??(i.some(h=>h.cpu!==void 0)?"cpu":"sysCpu"),c=Zg(i,a,s.durationSec);if(c.every(h=>h===null))throw new l(`The track has no ${a} values.`);let u=e.width??Math.max(160,Math.round(s.width/4)),d=vt(el[a]),p=tb(n,"label.txt");zE(p,el[a]);let f=B(e.output,"perf",V(e.input),{overwrite:e.overwrite}),m=eb(e.input,f,c,{metric:a,corner:e.corner??"top_right",width:u,height:Math.round(u*.4),videoWidth:s.width,videoHeight:s.height,durationSec:s.durationSec,label:{textFile:p,fontFile:d.fontFile},hasAudio:s.audioCodec!==null});return await W(m,{output:f,durationSec:s.durationSec,extra:r}),v({outputPath:f,metric:a,samples:i.length})}catch(o){return E(o)}finally{UE(n,{recursive:!0,force:!0})}})}import{z as Gn}from"zod";import{existsSync as qE,readFileSync as XE,writeFileSync as JE}from"node:fs";var tl=2e3,YE={input:Gn.string().min(1).describe("The .srt to translate (e.g. from transcribe)."),language:Gn.string().regex(/^[a-z]{3}$/).optional().describe('With translations: ISO 639-2 code, e.g. "spa".'),translations:Gn.array(Gn.string().max(Ys)).max(tl).optional().describe("One translated string per cue, in order. Omit to get the cues to translate."),output:Gn.string().optional().describe("Default: <input>.<language>.srt."),overwrite:Gn.boolean().optional().describe("Allow replacing an existing output file.")};function nb(t){t.registerTool("translate_subtitles",{title:"Translate Subtitles",description:"Translate an SRT without breaking its timing: call once for the numbered cues, translate them, then call with translations to write <input>.<language>.srt for chapters' subtitleTracks.",inputSchema:YE,annotations:I},async e=>{try{if(F(e.input,"Subtitle file"),!/\.srt$/i.test(e.input))throw new l("input must be an .srt file.");let r=We(XE(e.input,"utf8"));if(r.length===0)throw new l(`No cues in ${e.input}.`);if(r.length>tl)throw new l(`${r.length} cues; at most ${tl} per file.`);if(!e.translations)return v({input:e.input,count:r.length,cues:r.map((i,s)=>`${s+1}. ${i.text.replace(/\s*\n\s*/g," / ")}`),next:`Translate each cue's text (keep " / " as a line break), then call again with language and translations: ${r.length} strings, in order.`});if(!e.language)throw new l('translations needs language (ISO 639-2, e.g. "spa").');let n=Ph(r,e.translations.map(i=>i.replace(/\s+\/\s+/g,`
|
|
338
|
+
`))),o=e.output??Ih(e.input,e.language);if(!/\.srt$/i.test(o))throw new l("output must end in .srt.");if(Zt(o),qE(o)){if(!e.overwrite)throw new l(`${o} already exists.`,"Pass overwrite: true to replace it.");wc(o)}return JE(o,nt(n)),v({outputPath:o,language:e.language,count:n.length})}catch(r){return E(r)}})}import{z as Ca}from"zod";import{join as VE}from"node:path";import{mkdtempSync as QE,rmSync as ZE}from"node:fs";import{tmpdir as e_}from"node:os";import{z as xe}from"zod";var qn=(t,e)=>{if(!Number.isFinite(t)||t<0)throw new l(`${e} must be a non-negative number.`);return Math.round(t)};function rl(t){let e=Ii(t.from,t.to);return e?`:enable='${e}'`:""}function ob(t){let e=t.x2-t.x1,r=t.y2-t.y1,n=Math.round(Math.hypot(e,r)),o=Math.max(2,Math.round(t.thickness??8));if(n<o*3)throw new l("An arrow must be at least three times as long as it is thick.");return{length:n,thickness:o,angle:Math.atan2(r,e),cx:(t.x1+t.x2)/2,cy:(t.y1+t.y2)/2}}function ib(t,e){let{length:r,thickness:n,angle:o}=ob(t),i=De(t.color??"red"),s=n*3,a=o.toFixed(6),c=`if(lt(X,W-H),if(lt(abs(Y-H/2),${n}/2),255,0),if(lt(abs(Y-H/2),(W-X)/2),255,0))`;return["-y","-v","error","-f","lavfi","-i",`color=c=${i}:s=${r}x${s}`,"-vf",`format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${c}',rotate=a=${a}:ow=rotw(${a}):oh=roth(${a}):c=none`,"-frames:v","1",...Ee(e)]}function ol(t,e,r,n,o){if(t.length===0)throw new l("Give at least one callout.");let i=[],s=[],a=r;return t.forEach((c,u)=>{let d=`[${o}c${u}]`;if(c.type==="box"){let p=De(c.color??"red"),f=c.fill?"fill":String(Math.max(1,Math.round(c.thickness??4)));s.push(`${a}drawbox=x=${qn(c.x,"x")}:y=${qn(c.y,"y")}:w=${qn(c.width,"width")}:h=${qn(c.height,"height")}:color=${p}:t=${f}${rl(c)}${d}`)}else if(c.type==="text"){let p=e.textFiles[u];if(!p)throw new l("Internal: missing text file for a text callout.");let f=De(c.color??"white"),m=Math.max(8,Math.round(c.size??32)),h=c.background===!1?"":`:box=1:boxcolor=black@0.6:boxborderw=${Math.round(m/3)}`;s.push(`${a}drawtext=fontfile=${ye(e.fontFiles?.[u]??e.fontFile)}:textfile=${ye(p)}:expansion=none:x=${qn(c.x,"x")}:y=${qn(c.y,"y")}:fontsize=${m}:fontcolor=${f}${h}${rl(c)}${d}`)}else{let p=e.arrowFiles[u];if(!p)throw new l("Internal: missing image for an arrow callout.");let{cx:f,cy:m}=ob(c),h=n+i.length/4;i.push("-loop","1","-i",p),s.push(`${a}[${h}:v]overlay=x=${f.toFixed(1)}-w/2:y=${m.toFixed(1)}-h/2:shortest=1${rl(c)}${d}`)}a=d}),{steps:s,out:a,extraInputs:i}}function sb(t,e,r,n,o="standard",i=!1){let s=i?r.map(({from:d,to:p,...f})=>f):r,{steps:a,out:c,extraInputs:u}=ol(s,n,"[0:v]",1,"");return i?["-y","-i",t,...u,"-filter_complex",a.join(";"),"-map",c,"-frames:v","1",...Ee(e)]:["-y","-i",t,...u,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",..._e(o),"-c:a","copy",e]}var nl={from:xe.number().nonnegative().optional(),to:xe.number().positive().optional(),color:xe.string().optional()},vr=xe.string().min(1).optional().describe("Font: a .ttf/.otf/.ttc path or a C:\\Windows\\Fonts file name. Default: bundled Inter, with a covering system font for scripts it lacks (CJK, emoji, Arabic, ...)."),Ra=xe.discriminatedUnion("type",[xe.object({type:xe.literal("box"),x:xe.number(),y:xe.number(),width:xe.number().positive(),height:xe.number().positive(),thickness:xe.number().positive().optional().describe("Outline px (default 4)."),fill:xe.boolean().optional().describe("Fill instead of outline."),...nl}),xe.object({type:xe.literal("text"),x:xe.number(),y:xe.number(),text:xe.string().min(1),size:xe.number().positive().optional().describe("Font size px (default 32)."),background:xe.boolean().optional().describe("Dark panel behind the text (default true)."),...nl}),xe.object({type:xe.literal("arrow"),x1:xe.number(),y1:xe.number(),x2:xe.number().describe("Head (x2,y2) is the point the arrow points at."),y2:xe.number(),thickness:xe.number().positive().optional().describe("Shaft px (default 8)."),...nl})]);import{join as ab}from"node:path";import{writeFileSync as KE}from"node:fs";function il(t,e){let r={fontFiles:[],fallbackFonts:[],warnings:[]};return t.forEach((n,o)=>{if(n.type!=="text"){r.fontFiles.push(null);return}let i=vt(n.text,{weight:"bold",fontFile:e});r.fontFiles.push(i.fontFile),i.fallback&&r.fallbackFonts.push({item:o,fontFile:i.fontFile}),i.warning&&r.warnings.push(`Item ${o}: ${i.warning}`)}),r}async function Ma(t,e,r="",n){let o=il(t,n),i=t.map((a,c)=>{if(a.type!=="text")return null;let u=ab(e,`${r}text_${c}.txt`);return KE(u,a.text),u}),s=[];for(let[a,c]of t.entries()){if(c.type!=="arrow"){s.push(null);continue}let u=ab(e,`${r}arrow_${a}.png`);await Z(ib(c,u),3e4),s.push(u)}return{fontFile:Bt("bold"),textFiles:i,arrowFiles:s,...o}}var t_={input:Ca.string().min(1).describe("Path to the source video or image (png/jpg; from/to are ignored for an image)."),items:Ca.array(Ra).min(1).max(50).describe("Boxes, text labels, and arrows, drawn in order (later on top), in video pixels. Each shows from..to seconds (default: whole video); color is a name, #RRGGBB, or name@alpha."),fontFile:vr,output:Ca.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ca.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function cb(t){t.registerTool("callout",{title:"Add Callouts",description:"Annotate a video or screenshot with timed boxes, text labels, and arrows. Fallback fonts used are listed in fallbackFonts; characters no font covers are reported in warnings.",inputSchema:t_,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.items,{still:o,ext:i}=Oi(e.input,e.output),s=B(e.output,"callout",i,{overwrite:e.overwrite,anyContainer:!0}),a=QE(VE(e_(),"screencast-callout-"));try{let c=await Ma(n,a,"",e.fontFile),u=sb(e.input,s,n,c,void 0,o);return await W(u,{output:s,durationSec:o?null:await se(e.input),extra:r}),v({outputPath:s,callouts:n.length,...c.fallbackFonts.length>0&&{fallbackFonts:c.fallbackFonts},...c.warnings.length>0&&{warnings:c.warnings}})}finally{ZE(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as ei}from"zod";import{join as h_}from"node:path";import{mkdtempSync as g_,rmSync as b_}from"node:fs";import{tmpdir as w_}from"node:os";import{z as zt}from"zod";import{existsSync as r_,readFileSync as n_,writeFileSync as o_}from"node:fs";import{join as i_}from"node:path";var s_=["bottom","bottom-left","bottom-right","top","top-left","top-right"],sl=1.2,a_=.5,ub=8,lb=100,pb="Typing\u2026",c_=new Set(["Ctrl","Alt","Shift","Win"]),u_=/^(?:[A-Z0-9]|F\d{1,2}|Enter|Tab|Esc|Space|Backspace|Delete|Insert|Left|Up|Right|Down|Home|End|PageUp|PageDown|[=\-,./`[\];'\\])$/;function l_(t,e="shortcuts"){let r=t.split("+"),n=r.pop();return n===void 0||r.length===0||!u_.test(n)||!r.every(o=>c_.has(o))||new Set(r).size!==r.length?null:[...r,e==="masked"?"\u2026":n].join(" + ")}var p_={left:"Click",right:"Right click",middle:"Middle click",x1:"Back button",x2:"Forward button"},Pa=t=>Math.round(t*1e3)/1e3;function d_(t,e={}){let r=e.lingerSec??sl;if(!(r>0))throw new l("lingerSec must be positive.");let n=e.keys??"shortcuts",o=[...t].filter(a=>Number.isFinite(a.t)&&a.t>=0).sort((a,c)=>a.t-c.t),i=[];for(let a of o)if(a.type==="key"&&a.keys){let c=l_(a.keys,n);if(!c)continue;let u=i.at(-1);if(u&&u.kind==="shortcut"&&u.base===c&&a.t-u.last<=r){u.count++,u.last=a.t,u.label=`${c} \xD7${u.count}`,u.to=a.t+r;continue}i.push({from:a.t,to:a.t+r,label:c,base:c,kind:"shortcut",count:1,last:a.t})}else if(a.type==="down"&&e.clicks!==!1&&a.inFrame){let c=p_[a.button??"left"]??"Click",u=i.at(-1);if(c==="Click"&&u&&u.kind==="click"&&u.base==="Click"&&u.count<3&&a.t-u.last<=a_&&Math.abs(a.x-(u.x??a.x))<=ub&&Math.abs(a.y-(u.y??a.y))<=ub){u.count++,u.last=a.t,u.label=u.count===2?"Double click":"Triple click",u.to=a.t+r;continue}i.push({from:a.t,to:a.t+r,label:c,base:c,kind:"click",count:1,x:a.x,y:a.y,last:a.t})}else if(a.type==="typing"&&e.typing!==!1){let c=a.t+Math.max(a.durationSec??0,0),u=i.at(-1);if(u&&u.kind==="typing"&&a.t<=u.to){u.to=Math.max(u.to,c+r/2),u.last=a.t;continue}i.push({from:a.t,to:c+r/2,label:pb,base:pb,kind:"typing",count:1,last:a.t})}let s=[];return i.forEach((a,c)=>{let u=i[c+1],d=u?Math.min(a.to,u.from):a.to;d-a.from>=.05&&s.push({from:Pa(a.from),to:Pa(d),label:a.label,kind:a.kind})}),s}function Ia(t){let e=new Map;for(let r of t){let n=e.get(r.label);n||(n={label:r.label,windows:[]},e.set(r.label,n)),n.windows.push([r.from,r.to])}if(e.size>lb)throw new l(`${e.size} different badges is more than ${lb}; trim the video or turn off keys or clicks.`);return[...e.values()]}function m_(t,e){return t.flatMap(r=>{let n=e(r.from,r.to);return n&&n[1]-n[0]>=.05?[{...r,from:Pa(n[0]),to:Pa(n[1])}]:[]})}function db(t,e){return m_(t,(r,n)=>Wr(r,n,e))}function f_(t,e){if(e!==void 0){if(!(e>=8&&e<=400))throw new l("size must be between 8 and 400.");return Math.round(e)}return Math.max(14,Math.round(t*.045))}function al(t,e,r,n,o,i){if(t.length===0)throw new l("No badges to draw.");let s=f_(n.height,r.size),a=Math.round(s/3),c=a+Math.round(s*.6),u=r.position??"bottom",d=u.endsWith("left")?`${c}`:u.endsWith("right")?`w-tw-${c}`:"(w-tw)/2",p=u.startsWith("top")?`${c}`:`h-lh-${c}`,f=De(r.color??"white"),m=[],h=o;return t.forEach((b,w)=>{let g=e.textFiles[b.label];if(!g)throw new l(`Internal: no text file for badge "${b.label}".`);let y=_t(b.windows.map(([S,C])=>`between(t,${S},${C})`)),$=`[${i}k${w}]`;m.push(`${h}drawtext=fontfile=${ye(e.fontFile)}:textfile=${ye(g)}:expansion=none:fontsize=${s}:fontcolor=${f}:box=1:boxcolor=black@0.6:boxborderw=${a}:x=${d}:y=${p}:enable='${y}'${$}`),h=$}),{steps:m,out:h}}function mb(t,e,r,n,o,i,s="standard"){let{steps:a,out:c}=al(r,n,o,i,"[0:v]","");return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",..._e(s),"-c:a","copy",e]}var Fa={events:zt.string().optional(),clicks:zt.boolean().optional(),typing:zt.boolean().optional(),keys:zt.enum(["shortcuts","masked"]).optional(),lingerSec:zt.number().positive().max(10).optional(),position:zt.enum(s_).optional(),size:zt.number().min(8).max(400).optional(),color:zt.string().optional(),fontFile:zt.string().min(1).optional()};function Oa(t,e,r){let n=e??$e(t).jsonl;if(!r_(n))throw new l(`No event log for ${t} (looked for ${n}). Record with start_recording events: true (keys: "shortcuts" to name shortcuts), or pass events: <path to .events.jsonl>.`);let o=je(n_(n,"utf8"));return{badges:d_(o,r),shortcutsLogged:o.filter(i=>i.type==="key").length,path:n}}function Zo(t,e,r="",n){let o=vt(t.join(" "),{weight:"bold",fontFile:n}),i={};return t.forEach((s,a)=>{if(e===null){i[s]=`<badge ${a}>`;return}let c=i_(e,`${r}badge_${a}.txt`);o_(c,s),i[s]=c}),{fontFile:o.fontFile,textFiles:i,...o.fallback&&{fallbackFont:o.fontFile},warnings:o.warning?[o.warning]:[]}}var $r=Fa,y_={input:ei.string().min(1).describe("Path to the recording."),events:$r.events.describe("Event log (default: the input's .events.jsonl)."),clicks:$r.clicks.describe("Show clicks (default true)."),typing:$r.typing.describe('Show typing as "Typing\u2026" (default true).'),keys:$r.keys.describe("shortcuts (default): the chord (Ctrl + S); masked: modifiers only (Ctrl + \u2026)."),lingerSec:$r.lingerSec.describe(`Seconds a badge stays up (default ${sl}).`),position:$r.position.describe("Default bottom (centred)."),size:$r.size.describe("Font px (default 4.5% of the frame height)."),color:$r.color.describe("Text color (default white)."),fontFile:vr,dryRun:ei.boolean().optional().describe("Return the planned badges; write nothing."),output:ei.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ei.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function fb(t){t.registerTool("keystroke_overlay",{title:"Keystroke Overlay",description:"Burn keycast-style badges for shortcuts, clicks, and typing from the recording's input event log (start_recording events: true). Never shows typed text: the log has none.",inputSchema:y_,outputSchema:N({badges:ei.number().int()}),annotations:I},async(e,r)=>{try{k(),F(e.input);let n={clicks:e.clicks,typing:e.typing,keys:e.keys,lingerSec:e.lingerSec},{badges:o,shortcutsLogged:i}=Oa(e.input,e.events,n),s=i===0?'The log names no shortcuts (recorded with keys: "masked"), so only clicks and typing can show.':void 0;if(o.length===0)return v({badges:0,note:"Nothing to show: the log has no clicks, shortcuts, or typing; nothing written."});let a=Ia(o);if(e.dryRun){let p=Zo(a.map(f=>f.label),null,"",e.fontFile);return v({dryRun:!0,badges:o.length,plan:o,...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}let c=await L(e.input);if(!c.height)throw new l(`Could not read the size of ${e.input}.`);let u=B(e.output,"keys",V(e.input),{overwrite:e.overwrite}),d=g_(h_(w_(),"screencast-keys-"));try{let p=Zo(a.map(h=>h.label),d,"",e.fontFile),f={position:e.position,size:e.size,color:e.color},m=mb(e.input,u,a,p,f,{height:c.height});return await W(m,{output:u,durationSec:c.durationSec,extra:r}),v({outputPath:u,badges:o.length,labels:a.map(h=>h.label),...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}finally{b_(d,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as ri}from"zod";import{join as yb}from"node:path";import{mkdtempSync as L_,rmSync as B_,writeFileSync as W_}from"node:fs";import{tmpdir as j_}from"node:os";import{z as Xn}from"zod";import{existsSync as x_,readFileSync as S_}from"node:fs";var ti={w:114,h:168,hotX:9,hotY:9,arrowH:135};function Na(){return vn("cursor","arrow.png")}var v_=.5,cl=2,ul=1.5,$_=.4,hb=240,k_=4,E_=.35,__=new Set(["move","down","up","wheel"]),Jn=t=>Math.round(t*1e3)/1e3;function T_(t){let e=6+(1-t)*34;return{omega:e,lead:Math.min(2/e,.2)}}function A_(t){let e=[],r=fc/1e3;for(let n of t){let o=e.at(-1);o&&n.t-o.t>r*2&&(o.x!==n.x||o.y!==n.y)&&e.push({t:n.t-r,x:o.x,y:o.y}),o&&n.t===o.t?e[e.length-1]=n:e.push(n)}return e}function R_(t,e,r=0){if(t.length===0)return{x:0,y:0,i:0};let n=Math.max(0,Math.min(r,t.length-1));for(;n>0&&t[n].t>e;)n--;for(;n<t.length-1&&t[n+1].t<=e;)n++;let o=t[n],i=t[n+1];if(!i||e<=o.t)return{x:o.x,y:o.y,i:n};let s=(e-o.t)/(i.t-o.t);return{x:o.x+(i.x-o.x)*s,y:o.y+(i.y-o.y)*s,i:n}}function M_(t,e,r,n,o){if(t.length===0)return[];let i=1/hb,s=0,a=w=>{let g=R_(t,w+r,s);return s=g.i,g},c=a(n),u=c.x,d=c.y,p=0,f=0,m=[{t:Jn(n),x:u,y:d}],h=Math.exp(-e*i),b=Math.max(0,Math.ceil((o-n)*hb));for(let w=1;w<=b;w++){let g=Math.min(o,n+w*i),y=a(g),$=u-y.x,S=d-y.y,C=(p+e*$)*i,M=(f+e*S)*i;p=(p-e*C)*h,f=(f-e*M)*h,u=y.x+($+C)*h,d=y.y+(S+M)*h,(w%k_===0||w===b)&&m.push({t:Jn(g),x:u,y:d})}return m}function C_(t,e=E_){if(t.length<=2)return[...t];let r=new Uint8Array(t.length);r[0]=1,r[t.length-1]=1;let n=[[0,t.length-1]];for(;n.length>0;){let[o,i]=n.pop(),s=t[o],a=t[i],c=-1,u=-1;for(let d=o+1;d<i;d++){let p=t[d],f=a.t>s.t?(p.t-s.t)/(a.t-s.t):0,m=Math.hypot(p.x-(s.x+(a.x-s.x)*f),p.y-(s.y+(a.y-s.y)*f));m>c&&(c=m,u=d)}c>e&&(r[u]=1,n.push([o,u],[u,i]))}return t.filter((o,i)=>r[i]===1)}function P_(t){let e=[];for(let r of[...t].sort((n,o)=>n[0]-o[0])){let n=e.at(-1);n&&r[0]<=n[1]?n[1]=Math.max(n[1],r[1]):e.push([r[0],r[1]])}return e}function I_(t,e={},r=null){let n=e.smoothing??v_;if(!(n>=0&&n<=1))throw new l("smoothing must be between 0 and 1.");let o=e.hideAfterSec??cl;if(!(o>=0))throw new l("hideAfterSec must be 0 or more.");let i=t.filter(h=>__.has(h.type)&&Number.isFinite(h.t)&&h.t>=0&&Number.isFinite(h.x)&&Number.isFinite(h.y)).filter(h=>r===null||h.t<=r).sort((h,b)=>h.t-b.t);if(i.length===0)return{path:[],visible:[],clicks:[]};let s=A_(i.map(h=>({t:h.t,x:h.x,y:h.y}))),a=s[0].t,c=s.at(-1).t,u,d=0;if(n===0)u=s.map(h=>({...h})),r!==null&&r>c&&u.push({...s.at(-1),t:r});else{let h=T_(n);d=h.lead;let b=Math.max(0,a-d),w=Math.max(b,r??c+8/h.omega);u=M_(s,h.omega,d,b,w)}let p=Math.max(0,a-d),f=o===0?[[p,r??1/0]]:P_(i.map(h=>[Math.max(0,h.t-d),h.t+o])),m=i.filter(h=>h.type==="down").map(h=>({t:h.t,x:h.x,y:h.y}));return{path:u,visible:f.map(([h,b])=>[Jn(h),r!==null?Math.min(b,r):b]).filter(([h,b])=>b>h),clicks:m}}var F_={sx:1,sy:1,ox:0,oy:0};function Da(t,e=[],r=F_){let n=a=>{let c=ss(a.t,e);return c===null?null:{t:Jn(c),x:a.x*r.sx+r.ox,y:a.y*r.sy+r.oy}},o=[];for(let a of t.path){let c=n(a);c&&(o.length>0&&o.at(-1).t>=c.t?o[o.length-1]={...c,t:o.at(-1).t}:o.push(c))}let i=t.visible.flatMap(([a,c])=>{let u=Wr(a,c,e);return u&&u[1]-u[0]>=.05?[[Jn(u[0]),Number.isFinite(u[1])?Jn(u[1]):u[1]]]:[]}),s=t.clicks.flatMap(a=>{let c=n(a);return c?[c]:[]});return{path:C_(o),visible:i,clicks:s}}var Ce=(t,e=2)=>{let r=Number(t.toFixed(e));return Object.is(r,-0)?"0":String(r)};function gb(t,e,r){let n=Number(r.toFixed(3));return n===0?Ce(t):`${Ce(t)}${n<0?"-":"+"}(t-${Ce(e,3)})*${Ce(Math.abs(n),3)}`}function O_(t,e=ul){if(!(e>=.25&&e<=8))throw new l("size must be between 0.25 and 8.");let r=Math.max(8,t*.025*e),n=r/ti.arrowH,o=Math.max(12,Math.round(r*2.2));return{spriteW:Math.max(2,Math.round(ti.w*n)),spriteH:Math.max(2,Math.round(ti.h*n)),hotX:ti.hotX*n,hotY:ti.hotY*n,ripples:[.45,.72,1].map(i=>Math.max(6,Math.round(o*i/2)*2)),spotRadius:Math.max(24,Math.round(t*.12))}}function N_(t){let e=new Map;for(let r of[...t].sort((n,o)=>n.t-o.t)){let n=Ce(Math.max(0,r.t),3),o=e.get(n)??[];o.push(r.text),e.set(n,o)}return[...e.entries()].map(([r,n])=>`${r} ${n.join(", ")};`).join(`
|
|
352
339
|
`)+`
|
|
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=`
|
|
340
|
+
`}function bb(t,e,r,n){return t.map((o,i)=>{let s=t[i+1],a=s?s.t-o.t:0,c=s&&a>0?(s.x-o.x)/a:0,u=s&&a>0?(s.y-o.y)/a:0;return{t:o.t,text:`${e} x ${gb(o.x+r,o.t,c)}, ${e} y ${gb(o.y+n,o.t,u)}`}})}function D_(t,e){return t.flatMap(([r,n])=>[{t:r,text:`${e} enable 1`},...Number.isFinite(n)?[{t:n,text:`${e} enable 0`}]:[]])}function ll(t,e,r,n,o,i,s,a){if(t.path.length===0)throw new l("No cursor positions to draw.");let c=O_(r.height,e.size),{width:u,height:d}=r,p=g=>`overlay@${i}c${g}`,f=[],m=[],h=t.path[0],b=`[${i}cm]`;f.push(`${n}sendcmd=f=${ye(a)}${b}`);let w=(g,y,$,S,C)=>{let M=`[${i}c${y}o]`;f.push(`${b}${g}${p(y)}=x=${Ce(h.x+$)}:y=${Ce(h.y+S)}:enable=0${M}`),m.push(...D_(C,p(y))),b=M};if(e.spotlight){let y=Math.ceil(2*u/4),$=Math.ceil(2*d/4),S=c.spotRadius/4,C=S*.8,M=`255*0.55*clip((hypot(X-${Ce(y/2)},Y-${Ce($/2)})-${Ce(S)})/${Ce(C)},0,1)`;f.push(`color=c=black:s=${y}x${$}:r=1:d=1,format=rgba,geq=r=0:g=0:b=0:a='${M}',scale=${2*u}:${2*d}[${i}csm]`);let R=c.spriteW*.25-u,P=c.spriteH*.3-d;w(`[${i}csm]`,"s",R,P,t.visible),m.push(...bb(t.path,p("s"),R,P))}if(e.clicks!==!1&&t.clicks.length>0){let g=$_/3;c.ripples.forEach((y,$)=>{let S=y/2,C=Math.max(1.5,y*.05),M=`abs(hypot(X-${Ce(S-.5)},Y-${Ce(S-.5)})-${Ce(S-C-1)})`,R=[.9,.65,.4][$],P=`255*lt(${M},${Ce(C*.45)})`;f.push(`color=c=black:s=${y}x${y}:r=1:d=1,format=rgba,geq=r='${P}':g='${P}':b='${P}':a='255*${R}*clip(${Ce(C)}-${M},0,1)'[${i}cr${$}]`);let j=t.clicks.map(X=>[X.t+$*g,X.t+($+1)*g]);w(`[${i}cr${$}]`,`r${$}`,-S,-S,[]);for(let[X,D]of t.clicks.entries()){let[ae,ee]=j[X],J=j[X+1];m.push({t:ae,text:`${p(`r${$}`)} x ${Ce(D.x-S)}, ${p(`r${$}`)} y ${Ce(D.y-S)}, ${p(`r${$}`)} enable 1`}),(!J||J[0]>=ee)&&m.push({t:ee,text:`${p(`r${$}`)} enable 0`})}})}return f.push(`[${o}:v]scale=${c.spriteW}:${c.spriteH}:flags=lanczos,format=rgba[${i}csp]`),w(`[${i}csp]`,"p",-c.hotX,-c.hotY,t.visible),m.push(...bb(t.path,p("p"),-c.hotX,-c.hotY)),{steps:f,out:b,extraInputs:["-i",s],commands:N_(m)}}function wb(t,e,r,n,o,i,s,a="standard"){let{steps:c,out:u,extraInputs:d,commands:p}=ll(r,n,o,"[0:v]",1,"",i,s);return{args:["-y","-i",t,...d,"-filter_complex",c.join(";"),"-map",u,"-map","0:a?",..._e(a),"-c:a","copy",e],commands:p}}var La={events:Xn.string().optional(),size:Xn.number().min(.25).max(8).optional(),smoothing:Xn.number().min(0).max(1).optional(),hideAfterSec:Xn.number().min(0).max(600).optional(),clicks:Xn.boolean().optional(),spotlight:Xn.boolean().optional()};function Ba(t,e,r,n){let o=e??$e(t).jsonl;if(!x_(o))throw new l(`No event log for ${t} (looked for ${o}). Record with start_recording cursor: "events" (no OS cursor in the video, events logged), or pass events: <path to .events.jsonl>.`);let i=I_(je(S_(o,"utf8")),r,n);if(i.path.length===0)throw new l(`The event log ${o} has no cursor positions to draw.`);return i}var Yn=La,U_={input:ri.string().min(1).describe("Path to the recording."),events:Yn.events.describe("Event log (default: the input's .events.jsonl)."),size:Yn.size.describe(`Times a typical cursor's size (default ${ul}).`),smoothing:Yn.smoothing.describe("0 = as logged, 1 = floaty (default 0.5)."),hideAfterSec:Yn.hideAfterSec.describe(`Hide when the mouse rests this long; 0 = never (default ${cl}).`),clicks:Yn.clicks.describe("Ripple on clicks (default true)."),spotlight:Yn.spotlight.describe("Dim all but the area around the cursor."),dryRun:ri.boolean().optional().describe("Return the plan; write nothing."),output:ri.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ri.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function xb(t){t.registerTool("cursor",{title:"Re-rendered Cursor",description:'Draw a smoothed, scaled cursor that hides when idle from the event log of a start_recording cursor: "events" recording (no OS cursor in the video), with click ripples and an optional spotlight.',inputSchema:U_,outputSchema:N({segments:ri.number().int()}),annotations:I},async(e,r)=>{try{k(),F(e.input);let n=await L(e.input);if(!n.width||!n.height)throw new l(`Could not read the size of ${e.input}.`);let o=Da(Ba(e.input,e.events,e,n.durationSec)),i={segments:o.path.length,clicks:o.clicks.length,shownSec:Math.round(o.visible.reduce((c,[u,d])=>c+(Math.min(d,n.durationSec??d)-u),0)*10)/10};if(e.dryRun)return v({dryRun:!0,...i,visible:o.visible});let s=B(e.output,"cursor",V(e.input),{overwrite:e.overwrite}),a=L_(yb(j_(),"screencast-cursor-"));try{let c=yb(a,"cursor.cmd"),{args:u,commands:d}=wb(e.input,s,o,{size:e.size,clicks:e.clicks,spotlight:e.spotlight},{width:n.width,height:n.height},Na(),c);return W_(c,d),await W(u,{output:s,durationSec:n.durationSec,extra:r}),v({outputPath:s,...i})}finally{B_(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as Kn}from"zod";import{existsSync as J_}from"node:fs";import{extname as Y_}from"node:path";import{z as Ht}from"zod";var $b={desktop:["#1B2330","#0A0D12"],rec:["#FF4545","#5C0F1A"],amber:["#FFB454","#FF4545"],light:["#F4F7FA","#B9C4D0"]},z_=Object.keys($b),H_="desktop",dl=4,G_=.5,Sb=t=>2*Math.round(t/2),Wa=t=>2*Math.floor(t/2);function pl(t,e,r){if(t!==void 0){if(!Number.isFinite(t)||t<0||t>r)throw new l(`${e} must be between 0 and ${r}.`);return Math.round(t)}}function q_(t,e,r={}){if(!(t>0&&e>0))throw new l("The input has no frame size.");let n=pl(r.padding,"padding",2e3),o=pl(r.radius,"radius",1e3),i=pl(r.shadow,"shadow",200),s,a,c=t,u=e,d,p,f,m=!1;if(r.aspect){let $=jn[r.aspect];if(!$)throw new l(`Unknown aspect "${r.aspect}".`);s=$.w,a=$.h,f=Sb(n??Math.max(s,a)*.06);let S=s-2*f,C=a-2*f;if(S<16||C<16)throw new l(`padding ${f} leaves no room on a ${r.aspect} canvas.`);let M=Math.min(S/t,C/e);c=Math.max(2,Wa(t*M)),u=Math.max(2,Wa(e*M)),m=c!==t||u!==e,d=Wa((s-c)/2),p=Wa((a-u)/2)}else f=Sb(n??Math.max(t,e)*.06),s=t+2*f+t%2,a=e+2*f+e%2,d=f,p=f;let h=Math.max(c,u),b=Math.min(o??Math.round(h*.012),Math.floor(Math.min(c,u)/2)),w=i??Math.round(h*.025),g=a-p-u,y=w>0?Math.max(0,Math.min(Math.round(w/2),g)):0;return{canvasW:s,canvasH:a,contentW:c,contentH:u,x:d,y:p,padding:f,radius:b,shadow:w,shadowOffset:y,scaled:m}}function X_(t){if(t.colors!==void 0){if(t.colors.length<1||t.colors.length>dl)throw new l(`colors takes 1 to ${dl} colors.`);return t.colors.map((n,o)=>De(n,`colors[${o}]`))}let e=t.preset??H_,r=$b[e];if(!r)throw new l(`Unknown backdrop preset "${e}".`);return[...r]}function vb(t,e=!1){let r=t,n=`max(max(${r}-X-0.5,X+0.5-(W-${r})),0)`,o=`max(max(${r}-Y-0.5,Y+0.5-(H-${r})),0)`,i=`clip(${r}+0.5-hypot(${n},${o}),0,1)`;return e?`255-255*${i}`:`255*${i}`}function ml(t,e,r,n,o,i=!1){let s=q_(e.width,e.height,t);if(t.shadowOpacity!==void 0&&!(t.shadowOpacity>=0&&t.shadowOpacity<=1))throw new l("shadowOpacity must be between 0 and 1.");let a=t.shadowOpacity??G_,{canvasW:c,canvasH:u,contentW:d,contentH:p,x:f,y:m}=s,h=":r=1:d=1",b=[],w=[],g=`[${o}bg]`;if(t.image)w.push("-i",t.image),b.push(`[${n}:v]scale=${c}:${u}:force_original_aspect_ratio=increase,crop=${c}:${u},setsar=1,trim=end_frame=1,format=rgba${g}`);else{let j=X_(t);if(j.length===1)b.push(`color=c=${j[0]}:s=${c}x${u}${h},format=rgba${g}`);else{let X=j.map((D,ae)=>`c${ae}=${D}`).join(":");b.push(`gradients=s=${c}x${u}:${X}:n=${j.length}:x0=0:y0=0:x1=${c}:y1=${u}:r=1,trim=end_frame=1,format=rgba${g}`)}}let y=g;if(s.shadow>0&&a>0){let j=`[${o}sa]`,X=`[${o}sc]`,D=`[${o}sh]`,ae=`[${o}bs]`,ee=s.radius>0?`format=gray,geq=lum='${vb(s.radius)}'`:"format=gray";b.push(`color=c=white:s=${d}x${p}${h},${ee},pad=${c}:${u}:${f}:${m+s.shadowOffset}:color=black,gblur=sigma=${(s.shadow/2).toFixed(2)}${j}`),b.push(`color=c=black:s=${c}x${u}${h}${X}`),b.push(`${X}${j}alphamerge,format=rgba,colorchannelmixer=aa=${a}${D}`),b.push(`${y}${D}overlay=0:0:format=rgb${ae}`),y=ae}let $=`[${o}hole]`,S=`[${o}frame]`,C=s.radius>0?`format=gray,geq=lum='${vb(s.radius,!0)}'`:"format=gray";b.push(`color=c=black:s=${d}x${p}${h},${C},pad=${c}:${u}:${f}:${m}:color=white${$}`),b.push(`${y}${$}alphamerge,format=rgba${S}`);let M=`[${o}pad]`,R=`[${o}bd]`,P=s.scaled?`scale=${d}:${p},setsar=1,`:"";return b.push(`${r}${P}pad=${c}:${u}:${f}:${m}:color=black${M}`),b.push(`${M}${S}overlay=0:0${i?":format=rgb":""}${R}`),{steps:b,out:R,extraInputs:w,layout:s}}function kb(t,e,r,n,o=!1,i="standard"){let{steps:s,out:a,extraInputs:c,layout:u}=ml(r,n,"[0:v]",1,"",o),d="[vout]";s.push(`${a}format=${o?"rgb24":"yuv420p"}${d}`);let p=["-y","-i",t,...c,"-filter_complex",s.join(";"),"-map",d];return{args:o?[...p,"-frames:v","1",...Ee(e)]:[...p,"-map","0:a?",..._e(i),"-c:a","copy","-movflags","+faststart",e],layout:u}}var ja={preset:Ht.enum(z_).optional(),colors:Ht.array(Ht.string()).min(1).max(dl).optional(),image:Ht.string().min(1).optional(),padding:Ht.number().int().nonnegative().max(2e3).optional(),radius:Ht.number().int().nonnegative().max(1e3).optional(),shadow:Ht.number().int().nonnegative().max(200).optional(),shadowOpacity:Ht.number().min(0).max(1).optional(),aspect:Ht.enum(Wn).optional()};var Eb=/\.(png|jpe?g|bmp|tiff?|webp)$/i,kr=ja,K_={input:Kn.string().min(1).describe("Path to the source video or image (png/jpg)."),preset:kr.preset.describe("Gradient: desktop (default, dark slate), rec (red), amber, light."),colors:kr.colors.describe("Instead: 1 color = solid, 2-4 = diagonal gradient."),image:kr.image.describe("Instead: a wallpaper image, scaled to cover."),padding:kr.padding.describe("px around the content (default 6% of the longer side)."),radius:kr.radius.describe("Corner radius px (default ~1.2% of the longer side; 0 = square)."),shadow:kr.shadow.describe("Shadow blur px (default ~2.5%; 0 = none)."),shadowOpacity:kr.shadowOpacity.describe("Default 0.5."),aspect:kr.aspect.describe("Output on this aspect's canvas (1920x1080, ...), content scaled to fit."),output:Kn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits (screenshots for an image)."),overwrite:Kn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function _b(t){t.registerTool("backdrop",{title:"Add Backdrop",description:"Frame a video or screenshot on a gradient, color, or wallpaper with padding, rounded corners, and a drop shadow, optionally on a 16:9/1:1/9:16/4:5 canvas.",inputSchema:K_,outputSchema:N({outputPath:Kn.string(),width:Kn.number().int(),height:Kn.number().int()}),annotations:I},async(e,r)=>{try{if(k(),F(e.input),e.image&&!J_(e.image))throw new l(`Background image not found: ${e.image}`);let n=Eb.test(e.input);if(n&&e.output&&!Eb.test(e.output))throw new l("An image input writes an image: give the output a .png or .jpg extension.");n||Nr(e.output);let o=await L(e.input);if(!o.width||!o.height)throw new l(`Could not read the size of ${e.input}.`);let i=n?/\.jpe?g$/i.test(e.input)?Y_(e.input).toLowerCase():".png":V(e.input),s=er(e.output,we(n?"screenshots":"edits"),`backdrop-${ge()}-${be()}${i}`,e.overwrite),a={preset:e.preset,colors:e.colors,image:e.image,padding:e.padding,radius:e.radius,shadow:e.shadow,shadowOpacity:e.shadowOpacity,aspect:e.aspect},{args:c,layout:u}=kb(e.input,s,a,{width:o.width,height:o.height},n);return await W(c,{output:s,durationSec:n?null:o.durationSec,extra:r}),v({outputPath:s,width:u.canvasW,height:u.canvasH,content:{x:u.x,y:u.y,width:u.contentW,height:u.contentH},padding:u.padding,radius:u.radius,shadow:u.shadow,background:e.image?"image":e.colors?"colors":e.preset??"desktop"})}catch(n){return E(n)}})}import{z as ni}from"zod";var V_={input:ni.string().min(1).describe("Path to the source video."),level:ni.enum(["light","medium","heavy"]).optional().describe("CRF 23 / 28 / 32 (default medium)."),maxWidth:ni.number().int().positive().optional().describe("Width cap in px (only downscales)."),output:ni.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ni.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Tb(t){t.registerTool("compress",{title:"Compress Video",description:"Re-encode a video smaller (H.264 CRF ladder, optional width cap). For a platform target use export_preset.",inputSchema:V_,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=V(e.input),o=B(e.output,"compress",n,{overwrite:e.overwrite}),i=Op(e.input,o,{level:e.level,maxWidth:e.maxWidth});return await W(i,{output:o,durationSec:await se(e.input),extra:r}),v({outputPath:o,level:e.level??"medium"})}catch(n){return E(n)}})}import{z as Ua}from"zod";var Q_={mp3:"mp3",aac:"m4a",wav:"wav"},Z_={input:Ua.string().min(1).describe("Path to the source media."),format:Ua.enum(["mp3","aac","wav","copy"]).describe("Audio output codec. copy keeps the source codec without re-encoding."),output:Ua.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ua.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ab(t){t.registerTool("extract_audio",{title:"Extract Audio",description:"Extract the audio track of a media file to its own file (mp3, aac, wav, or copy). Returns the output path.",inputSchema:Z_,outputSchema:Y,annotations:I},async(e,r)=>{try{let{ffprobe:n}=k();F(e.input);let o=e.format,i=null,s;if(o==="copy"){let c=await ne(n,Or(e.input),3e4,{signal:r.signal});if(c.code!==0)throw new l(`ffprobe failed (exit ${c.code}): ${c.stderr.trim().slice(-400)}`);if(i=Fr(JSON.parse(c.stdout)).audioCodec,!i)throw new l(`Input has no audio stream to extract: ${e.input}`);s=Np(i)}else s=Q_[o];let a=B(e.output,"audio",`.${s}`,{overwrite:e.overwrite,anyContainer:!0});return await W(Dp(e.input,a,o),{output:a,durationSec:await se(e.input),extra:r}),v({outputPath:a,format:o,...i?{sourceAudioCodec:i}:{}})}catch(n){return E(n)}})}import{z as wl}from"zod";import{extname as eT}from"node:path";import{z as fl}from"zod";var tT=["youtube","podcast","broadcast"],za=fl.union([fl.enum(tT),fl.number().min(-70).max(-5)]),Rb={youtube:{i:-14,tp:-1,lra:11},podcast:{i:-16,tp:-1.5,lra:11},broadcast:{i:-23,tp:-1,lra:7}};function Vn(t){if(t===void 0)return Rb.youtube;if(typeof t=="number"){if(!Number.isFinite(t)||t<-70||t>-5)throw new l("target LUFS must be between -70 and -5 (e.g. -14).");return{i:t,tp:-1,lra:11}}let e=Rb[t];if(!e)throw new l(`Unknown loudness target "${t}".`);return e}var hl=t=>`I=${t.i}:TP=${t.tp}:LRA=${t.lra}`;function oi(t,e){return["-hide_banner","-nostats","-i",t,"-vn","-af",`loudnorm=${hl(e)}:print_format=json`,"-f","null","-"]}function ii(t){let r=t.match(/\{[^{}]*"input_i"[^{}]*\}/g)?.at(-1);if(r===void 0)throw new l("Could not measure loudness (no loudnorm report). Does the file have audio?");let n=JSON.parse(r),o=s=>Number(n[s]),i={input_i:o("input_i"),input_tp:o("input_tp"),input_lra:o("input_lra"),input_thresh:o("input_thresh"),target_offset:o("target_offset"),...n.output_i!==void 0?{output_i:o("output_i")}:{}};if(!Number.isFinite(i.input_i))throw new l("The audio is silent (loudness is -inf), so there is nothing to normalize.");return i}function Mb(t){return Pi(t)?["-map","0:a:0","-vn"]:["-map","0:v?","-map","0:a:0","-c:v","copy"]}function Ha(t){switch(eT(t).toLowerCase()){case".wav":return["-c:a","pcm_s16le"];case".mp3":return["-c:a","libmp3lame","-b:a","192k"];default:return["-c:a","aac","-b:a","192k"]}}function gl(t,e){if(!e)return`loudnorm=${hl(t)}`;let r=`measured_I=${e.input_i}:measured_TP=${e.input_tp}:measured_LRA=${e.input_lra}:measured_thresh=${e.input_thresh}:offset=${e.target_offset}`;return`loudnorm=${hl(t)}:${r}:linear=true`}function Cb(t,e,r,n){return["-y","-hide_banner","-i",t,...Mb(e),"-af",`${gl(r,n)}:print_format=json`,"-ar","48000",...Ha(e),e]}var Ga=["light","medium","strong"],rT={light:6,medium:12,strong:20};function qa(t){return["-hide_banner","-nostats","-i",t,"-vn","-af","aresample=48000,asetnsamples=4800,astats=metadata=1:reset=1,ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-","-f","null","-"]}function Xa(t){let e=[...t.matchAll(/RMS_level=(-?[\d.]+)/g)].map(r=>Number(r[1])).filter(Number.isFinite);return e.length===0?null:(e.sort((r,n)=>r-n),e[Math.floor(e.length*.1)]??null)}function nT(t){return t===null?-50:Math.max(-80,Math.min(-20,Math.round(t+5)))}function bl(t,e){let r=rT[t];if(r===void 0)throw new l(`Unknown denoise strength "${t}".`);return`afftdn=nr=${r}:nf=${nT(e)}`}function Pb(t,e,r="medium",n=null){return["-y","-i",t,...Mb(e),"-af",bl(r,n),...Ha(e),e]}var oT={input:wl.string().min(1).describe("Path to the source video or audio file."),target:za.optional().describe("youtube (-14 LUFS, default), podcast (-16), broadcast (-23), or a LUFS number (-70 to -5)."),output:wl.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:wl.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ib(t){t.registerTool("normalize_audio",{title:"Normalize Loudness",description:"Normalize loudness to a delivery target (two-pass EBU R128 loudnorm); video is copied. Reports loudness before and after.",inputSchema:oT,outputSchema:Y,annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();F(e.input);let o=await L(e.input);if(!o.audioCodec)throw new l(`Input has no audio stream: ${e.input}`);let i=Vn(e.target),s=V(e.input,{audio:!0}),a=B(e.output,"loudnorm",s,{overwrite:e.overwrite}),c=le(o.durationSec),u=await ne(n,oi(e.input,i),c,{signal:r.signal}),d=ii(u.stderr);await W(Cb(e.input,a,i,d),{output:a,durationSec:o.durationSec,extra:r});let p=ii((await ne(n,oi(a,i),c,{signal:r.signal})).stderr);return v({outputPath:a,target:{lufs:i.i,truePeakDb:i.tp,lra:i.lra},before:{lufs:d.input_i,truePeakDb:d.input_tp},after:{lufs:p.input_i,truePeakDb:p.input_tp}})}catch(n){return E(n)}})}import{z as Ja}from"zod";var iT={input:Ja.string().min(1).describe("Path to the source video or audio file."),strength:Ja.enum(Ga).optional().describe("How hard to reduce noise: light (6 dB), medium (12 dB, default), strong (20 dB)."),output:Ja.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ja.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Fb(t){t.registerTool("denoise",{title:"Denoise Audio",description:"Reduce steady background noise (fan, hum, hiss) in a recording's audio with an adaptive FFT denoiser. Video is copied untouched. Returns the output path.",inputSchema:iT,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=await L(e.input);if(!n.audioCodec)throw new l(`Input has no audio stream: ${e.input}`);let o=e.strength??"medium",i=V(e.input,{audio:!0}),s=B(e.output,"denoise",i,{overwrite:e.overwrite}),a=await ne(k().ffmpeg,qa(e.input),le(n.durationSec),{signal:r.signal}),c=Xa(a.stdout);return await W(Pb(e.input,s,o,c),{output:s,durationSec:n.durationSec,extra:r}),v({outputPath:s,strength:o,noiseFloorDb:c===null?null:Number(c.toFixed(1)),note:"Works best on steady noise (fans, hum, hiss); it does little for intermittent sounds."})}catch(n){return E(n)}})}import{z as Gt}from"zod";import{existsSync as sT,readFileSync as aT,rmSync as cT,writeFileSync as uT}from"node:fs";var lT={input:Gt.string().min(1).describe("Path to the video or audio to transcribe."),model:Gt.string().optional().describe(`Path to a whisper.cpp model file (ggml-*.bin). Defaults to ${Ks}.`),language:Gt.string().optional().describe("Spoken language code, e.g. 'en', or 'auto' (default)."),words:Gt.boolean().optional().describe("One word per cue, for word timing (cut_by_transcript)."),output:Gt.string().optional().describe("Optional output .srt path. Defaults under SCREENCAST_HOME/edits."),overwrite:Gt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ob(t){t.registerTool("transcribe",{title:"Transcribe Speech",description:"Transcribe a recording's speech to an SRT subtitle file, locally, with FFmpeg 8's whisper filter (needs a whisper.cpp model file). Returns the SRT path and the text. Pair with burn_subtitles to caption the video.",inputSchema:lT,outputSchema:N({srtPath:Gt.string(),cues:Gt.number().int(),text:Gt.string()}),annotations:I},async(e,r)=>{try{if(k(),F(e.input),!Ye("whisper"))throw new l("This ffmpeg has no whisper filter.","transcribe needs FFmpeg 8 built with whisper.cpp (--enable-whisper); recent Windows builds such as `winget install Gyan.FFmpeg` include it. Check with `ffmpeg -h filter=whisper`.");let n=br(e.model),o=await L(e.input);if(!o.audioCodec)throw new l(`Input has no audio to transcribe: ${e.input}`);let i=B(e.output,"captions",".srt",{overwrite:e.overwrite,anyContainer:!0}),s=Ue(".srt");try{await Z(On(e.input,n,s,e.language??"auto",e.words),le(o.durationSec),{signal:r.signal});let a=sT(s)?ut(Mh(We(aT(s,"utf8")))):[];uT(i,nt(a));let c=a.map(u=>u.text.replace(/\n/g," ")).join(" ");return v({srtPath:i,cues:a.length,text:c.length>4e3?`${c.slice(0,4e3)}\u2026`:c,...a.length===0?{note:"No speech was recognised."}:{}})}finally{cT(s,{force:!0})}}catch(n){return E(n)}})}import{z as si}from"zod";import{dirname as pT}from"node:path";import{existsSync as dT}from"node:fs";var mT={input:si.string().min(1).describe("Path to the source video."),subtitles:si.string().min(1).describe("Path to an .srt (e.g. from transcribe) or .ass subtitle file."),style:si.enum(Vs).optional().describe("clean (default for .srt): outlined line. social: big bold text on a dark box. .ass keeps its own styling unless set."),output:si.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:si.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Nb(t){t.registerTool("burn_subtitles",{title:"Burn In Subtitles",description:"Burn SRT/ASS subtitles (e.g. from transcribe) into a video in the bundled font.",inputSchema:mT,outputSchema:Y,annotations:I},async(e,r)=>{try{k();for(let a of[e.input,e.subtitles])if(!dT(a))throw new l(`File not found: ${a}`);if(!Ye("subtitles"))throw new l("This ffmpeg has no subtitles filter (it needs libass).","Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");let n=V(e.input),o=B(e.output,"subtitled",n,{overwrite:e.overwrite}),i=pT(Bt("regular")),s=e.style??(/\.(ass|ssa)$/i.test(e.subtitles)?null:"clean");return await W(Ch(e.input,e.subtitles,o,i,s),{output:o,durationSec:(await L(e.input)).durationSec,extra:r}),v({outputPath:o,style:s??"file"})}catch(n){return E(n)}})}import{z as Tt}from"zod";var fT={input:Tt.string().min(1).describe("Path to the source video."),segments:Tt.array(Tt.object({start:Tt.number().nonnegative(),end:Tt.number().positive()})).min(1).describe("{start, end} segments in seconds; each becomes its own file."),output:Tt.string().optional().describe("Optional output path. Only honored for a single segment; multi-segment output lands under SCREENCAST_HOME/edits."),overwrite:Tt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Db(t){t.registerTool("clip",{title:"Extract Clips",description:"Extract several frame-exact segments, each to its own file. For one segment, trim does the same.",inputSchema:fT,outputSchema:N({outputs:Tt.array(Tt.string()),count:Tt.number().int()}),annotations:I},async(e,r)=>{try{k(),F(e.input),Nr(e.output);let n=V(e.input),o=e.segments.length===1,i=[];for(let[s,a]of e.segments.entries()){let c=B(o?e.output:void 0,"clip",`-${String(s).padStart(2,"0")}${n}`,{overwrite:e.overwrite});await W(Lp(e.input,c,a),{output:c,durationSec:a.end-a.start,extra:r}),i.push(c)}return v({outputs:i,count:i.length})}catch(n){return E(n)}})}import{z as qt}from"zod";var hT={input:qt.string().min(1).describe("Path to the source video."),minIdleSec:qt.number().positive().optional().describe(`Only cut still stretches at least this long (default ${Yr}).`),keepSec:qt.number().min(0).optional().describe(`Seconds kept at each edge of a cut (default ${Ko}).`),useAudio:qt.boolean().optional().describe("Require silent audio too (default true when there is audio)."),action:qt.enum(["cut","speed"]).optional().describe("cut (default), or speed: fast-forward them."),factor:qt.number().gt(1).max(Jr).optional().describe(`speed: times faster (default ${Vo}).`),dryRun:qt.boolean().optional().describe("Only report what would be cut."),output:qt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:qt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Lb(t){t.registerTool("cut_idle",{title:"Cut Idle Stretches",description:"Remove dead air: cut stretches where the screen is frozen (and silent), keeping a short pad. Returns the time saved.",inputSchema:hT,annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();F(e.input);let o=await L(e.input),i=o.durationSec;if(i===null)throw new l(`Could not read duration of ${e.input}.`);let s=e.minIdleSec??Yr,a=e.keepSec??Ko,c=o.audioCodec!==null,u=(e.useAudio??!0)&&c,d=await ne(n,ba(e.input,s,u),le(i),{signal:r.signal});if(d.code!==0)throw new l(`Idle scan failed (exit ${d.code}): ${d.stderr.trim().slice(-400)}`);let p=wa(d.stderr,i),f=u?xa(p,ya(d.stderr,i)):p,m=Sa(f,s,a),h=e.action==="speed",b=e.factor??Vo,w=m.map(M=>({...M,factor:b})),g=Number((h?Kr(w):m.reduce((M,R)=>M+(R.end-R.start),0)).toFixed(2)),y={cuts:m,...h?{action:"speed",factor:b}:{},removedSec:g,originalSec:Number(i.toFixed(2)),newDurationSec:Number((i-g).toFixed(2)),idleRule:u?"frozen video and silent audio":"frozen video"};if(e.dryRun||m.length===0)return v({...y,...m.length===0?{note:"No idle stretches found; nothing to cut."}:{dryRun:!0}});let $=V(e.input),S=B(e.output,"trimmed-idle",$,{overwrite:e.overwrite}),C=h?Ea(e.input,S,w,{withAudio:c,fps:o.fps}):_a(e.input,S,m,c);return await W(C,{output:S,durationSec:i-g,inputDurationSec:i,extra:r}),v({outputPath:S,...y})}catch(n){return E(n)}})}import{z as Qe}from"zod";import{existsSync as Gb,readFileSync as vT,writeFileSync as $T}from"node:fs";var gT=["um","umm","uh","uhh","uhm","erm","er","ah","hmm","hm","mm","mhm"],Bb=.5,jb=t=>t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),Er=t=>Number(t.toFixed(3));function Ub(t){let e=[];return t.forEach((r,n)=>{let o=r.text.replace(/\s+/g," ").trim(),i=[...o.matchAll(/\S+/g)],s=o.length||1,a=r.end-r.start;i.forEach((c,u)=>{let d=c.index;e.push({cue:n,raw:c[0],norm:jb(c[0]),start:u===0?r.start:r.start+d/s*a,end:u===i.length-1?r.end:r.start+(d+c[0].length)/s*a,first:u===0,last:u===i.length-1})})}),e}var bT=t=>t.flatMap((e,r)=>e.norm?[r]:[]);function wT(t,e){let r=e.split(/\s+/).map(jb).filter(Boolean);if(r.length===0)throw new l(`Quote "${e}" has no words to match.`);let n=bT(t),o=[];for(let i=0;i+r.length<=n.length;i++)r.every((s,a)=>t[n[i+a]].norm===s)&&o.push([n[i],n[i+r.length-1]]);return o}function yT(t,e,r){let n=r;for(;t[n+1]&&!t[n+1].norm&&t[n+1].cue===t[r].cue;)n++;let o=t[e],i=t[n];return{start:Er(o.start),end:Er(i.end),text:t.slice(e,n+1).map(s=>s.raw).join(" "),exact:o.first&&i.last}}function xT(t){let e=[...t].filter(n=>n.end-n.start>.001).sort((n,o)=>n.start-o.start),r=[];for(let n of e){let o=r[r.length-1];o&&n.start<=o.end+.01?(n.end>o.end&&(o.end=n.end),o.text.includes(n.text)||(o.text=`${o.text} ${n.text}`),o.exact&&=n.exact):r.push({...n})}return r}function ST(t,e){let r=t.flatMap(o=>o.index===void 0?[]:[o.index]);if(r.length===0){let o=Number.isInteger(e)?t[e-1]:void 0;if(!o)throw new l(`No cue ${e}: the transcript has cues 1-${t.length}.`);return o}let n=t.filter(o=>o.index===e);if(n.length>1)throw new l(`The transcript numbers ${n.length} cues ${e}; quote the text to cut instead.`);if(n.length===0)throw new l(`No cue ${e}: the transcript's cues are numbered ${Math.min(...r)}-${Math.max(...r)} (a cue with no duration, or wholly overlapped by the next, has no time to cut).`);return n[0]}function zb(t,e){let r=Ub(t),n=[];for(let i of e.remove??[]){if(typeof i=="number"){let a=ST(t,i);n.push({start:Er(a.start),end:Er(a.end),text:a.text.replace(/\s+/g," "),exact:!0});continue}let s=wT(r,i);if(s.length===0)throw new l(`Quote not found in the transcript: "${i}".`);if(s.length>1)throw new l(`Quote "${i}" occurs ${s.length} times; quote more words or use cue numbers.`);n.push(yT(r,...s[0]))}let o=0;if(e.fillers){let i=new Set(gT);r.forEach(s=>{if(!i.has(s.norm))return;if(!r.every(p=>p.cue!==s.cue||p===s||!p.norm)){o++;return}let c=t[s.cue],u=Math.max(t[s.cue-1]?.end??0,c.start-Bb),d=Math.min(t[s.cue+1]?.start??1/0,c.end+Bb);n.push({start:Er(Math.min(u,c.start)),end:Er(Math.max(d,c.end)),text:r.filter(p=>p.cue===s.cue).map(p=>p.raw).join(" "),exact:!0})})}return{cuts:xT(n),skippedFillers:o}}function Wb(t,e){let r=0;for(let n of e){if(t<=n.start)break;r+=Math.min(t,n.end)-n.start}return t-r}function Hb(t,e){let r=Ub(t),n=i=>e.some(s=>i.start>=s.start-5e-4&&i.end<=s.end+5e-4),o=[];return t.forEach((i,s)=>{let a=r.filter(f=>f.cue===s),c=a.filter(f=>!n(f));if(!c.some(f=>f.norm))return;let u=c.length===a.length?i.text:c.map(f=>f.raw).join(" "),d=Er(Wb(i.start,e)),p=Er(Wb(i.end,e));p>d&&o.push({start:d,end:p,text:u})}),o}var kT={input:Qe.string().min(1).describe("Path to the source video."),srt:Qe.string().min(1).describe("Its .srt (transcribe; words: true for word timing)."),remove:Qe.array(Qe.union([Qe.number().int().min(0).max(99999),Qe.string().min(1)])).optional().describe("Cue numbers as the .srt numbers them, or transcript text quoted exactly (must occur once)."),fillers:Qe.boolean().optional().describe("Also cut fillers (um, uh...) that have their own cue."),dryRun:Qe.boolean().optional().describe("Only report the cuts."),output:Qe.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qe.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function qb(t){t.registerTool("cut_by_transcript",{title:"Cut By Transcript",description:"Edit a video by its transcript: cut quoted text, cue numbers, or fillers. Also writes the re-timed .srt.",inputSchema:kT,outputSchema:N({cuts:Qe.array(Qe.unknown()),removedSec:Qe.number()}),annotations:I},async(e,r)=>{try{k();for(let b of[e.input,e.srt])if(!Gb(b))throw new l(`File not found: ${b}`);if(!e.remove?.length&&!e.fillers)throw new l("Nothing to cut: pass remove and/or fillers: true.");let n=await L(e.input),o=n.durationSec;if(o===null||!n.videoCodec)throw new l(`Not a readable video: ${e.input}`);let i=ut(We(vT(e.srt,"utf8"),{index:!0}));if(i.length===0)throw new l(`No cues in ${e.srt}.`);let{cuts:s,skippedFillers:a}=zb(i,{remove:e.remove,fillers:e.fillers});if(s.length>Hn)throw new l(`Too many cuts (${s.length}, max ${Hn}); cut in batches.`);let c=Number(s.reduce((b,w)=>b+Math.min(w.end,o)-Math.min(w.start,o),0).toFixed(2)),u=Hb(i,s),d=[s.length===0&&"Nothing matched; nothing to cut.",a>0&&`${a} filler(s) inside longer cues were kept; transcribe with words: true to cut them.`,s.some(b=>!b.exact)&&"Some edges were estimated inside a cue; transcribe with words: true for word timing."].filter(Boolean),p={cuts:s,removedSec:c,originalSec:Number(o.toFixed(2)),newDurationSec:Number((o-c).toFixed(2)),...d.length?{note:d.join(" ")}:{}};if(e.dryRun||s.length===0){let b=u.map(w=>w.text.replace(/\n/g," ")).join(" ");return v({...p,...s.length?{dryRun:!0}:{},text:b.length>4e3?`${b.slice(0,4e3)}\u2026`:b})}let f=V(e.input),m=B(e.output,"cut-transcript",f,{overwrite:e.overwrite}),h=m.replace(/\.[^.\\/]+$/,"")+".srt";if(!e.overwrite&&Gb(h))throw new l(`Output already exists: ${h}. Pass overwrite: true to replace it.`);return await W(_a(e.input,m,s,n.audioCodec!==null),{output:m,durationSec:o-c,inputDurationSec:o,extra:r}),$T(h,nt(u)),v({outputPath:m,srtPath:h,...p})}catch(n){return E(n)}})}import{z as Qr}from"zod";var ET={input:Qr.string().min(1).describe("Path to the source video or image (png/jpg; time ranges are ignored for an image)."),regions:Qr.array(gn).min(1).describe("Pixel rectangles (x, y, width, height), each optionally limited to start..end seconds."),style:Qr.enum(Fi).optional().describe("box (default): irreversible fill; blur/pixelate are partially recoverable."),pad:Qr.number().int().nonnegative().optional().describe("Grow each region by this many px (default 0)."),color:Qr.string().optional().describe("Box fill color (default black)."),output:Qr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Xb(t){t.registerTool("redact_region",{title:"Redact Regions",description:"Cover given rectangles in a video or screenshot (e.g. secrets on screen). Not automatic detection: find them with find_text redact: true. Off-frame regions are rejected.",inputSchema:ET,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let{width:n,height:o,durationSec:i}=await L(e.input),{still:s,ext:a}=Oi(e.input,e.output),c=B(e.output,"redact",a,{overwrite:e.overwrite,anyContainer:!0}),u=Bp(e.input,c,e.regions,{style:e.style,pad:e.pad,color:e.color},{width:n,height:o},s);return await W(u,{output:c,durationSec:s?null:i,extra:r}),v({outputPath:c,regions:e.regions.length,style:e.style??"box"})}catch(n){return E(n)}})}import{z as Ya}from"zod";function Jb(t){t.registerTool("list_audio_devices",{title:"List Audio Devices",description:"List DirectShow audio devices and flag a likely loopback (Stereo Mix or a virtual-audio driver), for start_recording's audio.device.",inputSchema:{},outputSchema:N({devices:Ya.array(Ya.unknown()),loopbackDevice:Ya.string().nullable(),note:Ya.string()}),annotations:he},async()=>{try{k();let e=await eu(!0),r=Zc(e);return v({devices:e,loopbackDevice:r,note:r?`Pass "${r}" as the audio device to capture system audio.`:`No loopback device detected. ${Mo}`})}catch(e){return E(e)}})}import{z as fe}from"zod";function Kb(t){return t.hwnd!==void 0?`window:hwnd=${t.hwnd}`:`window:${t.title}`}function _T(t){let e=/^.*?[.!?](?=\s|$)/.exec(t);return e?e[0]:t}function Yb(t,e,r){try{return Nc(t,Kb(e).slice(7),{allowCloaked:r,exactOnly:!0}),{ok:!0}}catch(n){return{ok:!1,reason:_T(U(n))}}}function Vb(t,e,r){let n=r.filter??{},o=n.exe?Oc(`exe=${n.exe}`):null,i=o?.kind==="exe"?o.exe:null,s=n.titleContains?.trim().toLowerCase()||null,a=wo(t),c=t.length>0?a:e.virtual,u=[];for(let d of Array.isArray(e.windows)?e.windows:[]){if(i!==null&&(d.exe??"").toLowerCase().replace(/\.exe$/,"")!==i||s!==null&&!d.title.toLowerCase().includes(s))continue;let p=Yb(e,d,!1),f=r.wgcAvailable&&d.hwnd!==void 0?Yb(e,d,!0):{ok:!1};n.capturableOnly&&!p.ok&&!f.ok||u.push({target:Kb(d),title:d.title,exe:d.exe||null,pid:typeof d.pid=="number"?d.pid:null,hwnd:d.hwnd??null,bounds:{x:d.left,y:d.top,width:d.right-d.left,height:d.bottom-d.top},minimized:!!d.minimized,cloaked:!!d.cloaked,capturable:p.ok,wgcCapturable:f.ok,...p.ok?{}:{reason:p.reason}})}return{full:{target:"full",bounds:{x:c.x,y:c.y,width:c.w,height:c.h}},monitors:t.map(d=>({target:`monitor:${d.index}`,index:d.index,primary:d.primary,bounds:{x:d.x,y:d.y,width:d.width,height:d.height},dpi:d.dpi??null,scale:d.dpi?Math.round(d.dpi/96*100)/100:null})),windows:u,wgcAvailable:r.wgcAvailable}}var TT={exe:fe.string().min(1).optional().describe("Only list windows of this executable, e.g. 'Code.exe' or 'code'."),titleContains:fe.string().min(1).optional().describe("Only list windows whose title contains this text (case-insensitive)."),capturableOnly:fe.boolean().optional().describe("Leave out windows neither backend can capture (minimized, off screen). Default false.")},yl=fe.object({x:fe.number(),y:fe.number(),width:fe.number(),height:fe.number()}),AT=N({full:fe.looseObject({target:fe.literal("full"),bounds:yl}),monitors:fe.array(fe.looseObject({target:fe.string(),index:fe.number(),primary:fe.boolean(),bounds:yl,dpi:fe.number().nullable(),scale:fe.number().nullable()})),windows:fe.array(fe.looseObject({target:fe.string(),title:fe.string(),exe:fe.string().nullable(),pid:fe.number().nullable(),hwnd:fe.number().nullable(),bounds:yl,minimized:fe.boolean(),cloaked:fe.boolean(),capturable:fe.boolean(),wgcCapturable:fe.boolean()})),wgcAvailable:fe.boolean(),note:fe.string()});function Qb(t){t.registerTool("list_targets",{title:"List Capture Targets",description:"List the desktop, monitors, and visible windows (topmost first, with capturability per backend). Each entry has a `target` string to pass as-is to capture tools; use it instead of guessing a title.",inputSchema:TT,outputSchema:AT,annotations:he},async e=>{try{let[r,n]=await Promise.all([ar(),Dc()]),o=Vb(r,n,{wgcAvailable:ir(),filter:{exe:e.exe,titleContains:e.titleContains,capturableOnly:e.capturableOnly}});return v({...o,note:'Pass a target string unchanged. A window handle lasts until the app closes the window; list again after an app restarts, or target it by window:exe=<app.exe>. A window with capturable false but wgcCapturable true needs backend: "wgc".'})}catch(r){return E(r)}})}import{existsSync as xl}from"node:fs";import{join as Sl}from"node:path";import{z as pe}from"zod";var Zb=200,ew=1e3,Ka=.5,Va=3,Zr=t=>Math.round(t*1e3)/1e3;function rw(t,e){if(t.length===0)throw new l("lines is empty: give at least one { t | marker, text }.");if(t.length>Zb)throw new l(`At most ${Zb} lines are allowed (got ${t.length}).`);return t.map((n,o)=>{let i=n.text.replace(/\s+/g," ").trim();if(!i)throw new l(`lines[${o}] has no text.`);if(i.length>ew)throw new l(`lines[${o}] is ${i.length} characters; at most ${ew} are allowed. Split it.`);if(n.t!==void 0&&n.marker!==void 0)throw new l(`lines[${o}] has both t and marker; give one.`);if(n.t!==void 0){if(!Number.isFinite(n.t)||n.t<0)throw new l(`lines[${o}].t must be a non-negative number.`);return{t:Zr(n.t),text:i}}if(n.marker!==void 0){let s=n.marker.trim().toLowerCase(),a=e.find(c=>c.label.trim().toLowerCase()===s);if(!a){let c=e.map(u=>`"${u.label}"`).join(", ");throw new l(`lines[${o}]: no marker labelled "${n.marker}".`,c?`Markers on this video: ${c}.`:"This video has no markers; add_marker stamps one, or give t.")}return{t:Zr(a.t),text:i}}throw new l(`lines[${o}] needs t (seconds) or marker (a marker label).`)}).sort((n,o)=>n.t-o.t)}function nw(t,e){let r=[];return t.forEach((n,o)=>{let i=n.t+n.durationSec,s=t[o+1],a=`"${n.text.length>40?`${n.text.slice(0,40)}...`:n.text}"`;n.t>=e?r.push(`Line at ${n.t}s ${a} starts after the video ends (${Zr(e)}s) and is not heard.`):s&&i>s.t+.05?r.push(`Line at ${n.t}s ${a} runs ${Zr(i-s.t)}s past the next line (${s.t}s); they overlap. Move the next line, shorten this one, or raise rate.`):i>e+.05&&r.push(`Line at ${n.t}s ${a} runs ${Zr(i-e)}s past the end of the video and is cut off.`)}),r}function ow(t,e){return t.map((r,n)=>{let o=t[n+1],i=Math.min(r.t+r.durationSec,o?o.t:1/0,e);return{start:r.t,end:Zr(i),text:r.text}}).filter(r=>r.end>r.start)}function iw(t){if(t.length<12||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WAVE")throw new l("The speech engine did not return a WAV file.");let e=0;for(let r=12;r+8<=t.length;){let n=t.toString("ascii",r,r+4),o=t.readUInt32LE(r+4);if(n==="fmt "&&r+16<=t.length&&(e=t.readUInt32LE(r+16)),n==="data"){if(e<=0)break;let i=t.length-(r+8);return(o===0||o===4294967295||o>i?i:o)/e}r+=8+o+o%2}throw new l("Could not read the WAV header the speech engine wrote.")}function sw(t,e,r,n,o,i){if(!Number.isFinite(o)||o<=0)throw new l("video duration must be known and positive.");if(e.length===0||e.length!==n.length)throw new l("Every placed line needs its WAV.");let s=Zr(o),a=h=>`amix=inputs=${h}:duration=longest:dropout_transition=0:normalize=0`,c=n.map((h,b)=>{let w=Math.round(h.t*1e3);return`[${b+1}:a]aresample=48000,aformat=channel_layouts=mono,adelay=${w}[l${b}]`}),u=n.map((h,b)=>`[l${b}]`).join(""),d=!(i.hasAudio&&i.channels===1),p=`apad,atrim=end=${s}${d?",pan=stereo|c0=c0|c1=c0":""}`,f=i.hasAudio?"voice":"aout";c.push(n.length>1?`${u}${a(n.length)},${p}[${f}]`:`[l0]${p}[${f}]`),i.hasAudio&&(c.push(`[0:a]aresample=48000,aformat=channel_layouts=${d?"stereo":"mono"}[orig]`),i.duck??!0?(c.push("[voice]asplit=2[vo][key]"),c.push("[orig][key]sidechaincompress=threshold=0.02:ratio=8:attack=20:release=400[bed]"),c.push(`[bed][vo]${a(2)}[aout]`)):c.push(`[orig][voice]${a(2)}[aout]`));let m=Pi(r);return["-y","-i",t,...e.flatMap(h=>["-i",h]),"-filter_complex",c.join(";"),...m?[]:["-map","0:v?","-c:v","copy"],"-map","[aout]","-t",String(s),...Ha(r),.../\.(mp4|mov|m4a)$/i.test(r)?["-movflags","+faststart"]:[],r]}var RT=3e4,MT=1e4,tw=3e4,aw=t=>Array.isArray(t)?t:t==null?[]:[t];function cw(t){return aw(t.voices).map(e=>({name:String(e.name??""),language:String(e.language??""),gender:String(e.gender??"")}))}function CT(t){return{script:IT,payload:JSON.stringify(t)}}async function uw(t,e,r){if(process.platform!=="win32")throw new l("narrate uses the speech engine built into Windows and runs on Windows only.");let{script:n,payload:o}=CT(t),i="list"in t,s=await st(n,i?"speech voices":"the speech engine",{timeoutMs:e,signal:r,payload:o,failure:i?"Could not list speech voices":"Could not synthesize speech"});try{return JSON.parse(s)}catch(a){throw new l(`Could not parse the speech engine's output: ${U(a)}`)}}async function PT(t){let e=await uw({list:!0},sr(15e3),t);if(e.error)throw new l(`Windows speech is unavailable: ${e.error}`);return cw(e)}async function lw(){if(process.platform!=="win32")return{available:!1,voices:[],error:"Windows speech is available on Windows only."};try{let t=(await PT()).map(e=>`${e.name} (${e.language})`);return{available:t.length>0,voices:t,...t.length?{}:{error:"No speech voices are installed."}}}catch(t){return{available:!1,voices:[],error:U(t)}}}async function pw(t,e){let r=e.rate??1;if(!Number.isFinite(r)||r<Ka||r>Va)throw new l(`rate must be between ${Ka} and ${Va} (1 is normal speed).`);let n=await uw({voice:e.voice??null,rate:r,items:t},sr(RT+t.length*MT),e.signal);if(n.error){let o=cw(n);throw n.error==="unknown voice"?new l(`No installed voice matches "${e.voice}".`,o.length?`Installed voices: ${o.map(i=>`${i.name} (${i.language})`).join(", ")}.`:"No voices are installed."):new l(`Windows speech is unavailable: ${n.error}`,"Install a voice: Settings > Time & language > Speech > Manage voices.")}return aw(n.results).forEach((o,i)=>{if(o.error)throw new l(`Could not synthesize line ${i+1}: ${o.error}`)}),String(n.voice??"")}var IT=`
|
|
354
341
|
$ErrorActionPreference = 'Stop'
|
|
355
342
|
function Out($o) { ConvertTo-Json -InputObject $o -Depth 5 -Compress }
|
|
356
343
|
try {
|
|
@@ -374,7 +361,7 @@ try {
|
|
|
374
361
|
$results = foreach ($item in @($req.items)) {
|
|
375
362
|
try {
|
|
376
363
|
$task = $asTask.MakeGenericMethod([Windows.Media.SpeechSynthesis.SpeechSynthesisStream]).Invoke($null, @($synth.SynthesizeTextToStreamAsync([string]$item.text)))
|
|
377
|
-
if (-not $task.Wait(${
|
|
364
|
+
if (-not $task.Wait(${tw})) { throw "The speech engine did not answer within ${tw/1e3} s." }
|
|
378
365
|
$stream = $task.Result
|
|
379
366
|
$in = [System.IO.WindowsRuntimeStreamExtensions]::AsStreamForRead($stream)
|
|
380
367
|
$fs = [System.IO.File]::Create([string]$item.path)
|
|
@@ -384,10 +371,10 @@ try {
|
|
|
384
371
|
}
|
|
385
372
|
Out ([pscustomobject]@{ voice = $synth.Voice.DisplayName; results = @($results) })
|
|
386
373
|
} 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 et=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),
|
|
374
|
+
`;var FT=wt(),dw=pe.looseObject({found:pe.boolean(),path:pe.string().nullable(),version:pe.string().nullable(),major:pe.number().nullable()}),OT=N({ok:pe.boolean(),problems:pe.array(pe.string()),server:pe.looseObject({version:pe.string(),node:pe.string(),platform:pe.string(),arch:pe.string()}),ffmpeg:dw.extend({meetsFfmpeg8:pe.boolean().nullable()}),ffprobe:dw,filters:pe.record(pe.string(),pe.boolean()),devices:pe.looseObject({gdigrab:pe.boolean(),dshow:pe.boolean()}),wgc:pe.looseObject({available:pe.boolean()}),ocr:pe.looseObject({available:pe.boolean(),language:pe.string().nullable(),languages:pe.array(pe.string())}),storage:pe.looseObject({home:pe.string(),homeExists:pe.boolean()}),env:pe.record(pe.string(),pe.string().nullable())});function NT(t){let e=E(t).content[0];return e?.type==="text"?e.text.replace(/\s*\n+\s*/g," "):String(t)}function mw(t){let e=ua(t),r=ca(e??"");return{found:e!==null,path:e!==null?fg(t):null,version:r.version,major:r.major,...r.inferred?{majorInferred:!0}:{}}}function fw(t){t.registerTool("doctor",{title:"Check Setup",description:`Check the setup: ffmpeg/ffprobe (FFmpeg ${Hr}+?), optional filters, capture devices, Windows OCR, settings, and enabled toolsets; \`problems\` says what is missing and how to fix it. Call on first use or when a tool reports a missing feature.`,inputSchema:{},outputSchema:OT,annotations:he},async()=>{try{let e=[],r=null;try{r=Rc()}catch(b){e.push(NT(b))}let n=mw(r?.ffmpeg??(process.env.FFMPEG_PATH?.trim()||"ffmpeg")),o=mw(r?.ffprobe??(process.env.FFPROBE_PATH?.trim()||"ffprobe")),i=n.major===null?null:n.major>=Hr;r&&i===!1&&e.push(`FFmpeg ${n.version} is older than ${Hr}: transcribe and backend "wgc" need FFmpeg ${Hr}+. Windows: \`winget install Gyan.FFmpeg\`.`);let s={},a={gdigrab:!1,dshow:!1};if(r){for(let w of bg)s[w.filter]=w.filter==="gfxcapture"?ir():Ye(w.filter),!s[w.filter]&&!(w.filter==="gfxcapture"&&process.platform!=="win32")&&e.push(`No ${w.filter} filter: ${w.tools} unavailable (needs ${w.why}).`);let b=dg(mg(r.ffmpeg)??"");a={gdigrab:b.includes("gdigrab"),dshow:b.includes("dshow")},process.platform==="win32"&&!a.gdigrab&&e.push("This ffmpeg has no gdigrab device: screenshot and start_recording cannot capture the screen.")}process.platform!=="win32"&&e.push("Not Windows: capture (screenshot, start_recording, list_targets) and OCR are unavailable; the watch and edit tools work.");let c=r?{ddagrab:process.platform==="win32"&&Ye("ddagrab"),encoders:await Uc(r.ffmpeg)}:null,[u,d]=await Promise.all([wr(),lw()]);process.platform==="win32"&&!u.available&&e.push(`Windows OCR unavailable: find_text cannot read the screen. ${u.error??"Install an OCR language (Settings > Time & language > Language)."}`),process.platform==="win32"&&!d.available&&e.push(`Windows speech unavailable: narrate cannot speak. ${d.error??""} Install a voice (Settings > Time & language > Speech).`.replace(/\s+/g," "));let p=gg(),f=p.SCREENCAST_WHISPER_MODEL;f&&!xl(f)&&e.push(`SCREENCAST_WHISPER_MODEL points at a missing file: ${f}`);let m=Me();for(let b of ho())xl(b)||e.push(`SCREENCAST_ALLOWED_DIRS names a missing folder: ${b}`);let h=gi(p.SCREENCAST_TOOLSETS??void 0);return h.unknown.length>0&&e.push(`SCREENCAST_TOOLSETS names unknown toolsets (ignored): ${h.unknown.join(", ")}.`),e.push(...hg()),v({ok:e.length===0,problems:e,server:{version:FT,node:process.version,platform:process.platform,arch:process.arch},ffmpeg:{...n,meetsFfmpeg8:i},ffprobe:o,filters:s,devices:a,wgc:{available:s.gfxcapture===!0},...c?{gpu:c}:{},ocr:u,tts:d,storage:{home:m,homeExists:xl(m),recordings:Sl(m,"recordings"),screenshots:Sl(m,"screenshots"),edits:Sl(m,"edits"),allowedOutputDirs:Mr()},env:p,toolsets:{enabled:h.enabled,available:["all",...hi]}})}catch(e){return E(e)}})}import{z as Qn}from"zod";var DT={inputA:Qn.string().min(1).describe("Outgoing video."),inputB:Qn.string().min(1).describe("Incoming video."),transition:Qn.string().optional().describe("xfade name (default fade): fade, wipeleft, slideup, circleopen, dissolve, ..."),duration:Qn.number().positive().optional().describe(`Transition length in seconds (default ${Bn}).`),output:Qn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function hw(t){t.registerTool("xfade_transition",{title:"Crossfade Transition",description:"Join two videos with an xfade transition (audio crossfaded); they need not match in size, fps, or audio. For more clips use assemble_highlights.",inputSchema:DT,outputSchema:Y,annotations:I},async(e,r)=>{try{k();for(let p of[e.inputA,e.inputB])F(p);let[n,o]=await Promise.all([L(e.inputA),L(e.inputB)]),i=qr(n),s=qr(o);if(i===null||s===null)throw new l(`Could not read duration of ${i===null?e.inputA:e.inputB}.`);let a=[n.audioCodec!==null,o.audioCodec!==null],c=a[0]||a[1],u=B(e.output,"xfade",".mp4",{overwrite:e.overwrite}),d=Tg(e.inputA,e.inputB,[i,s],u,{transition:e.transition,duration:e.duration},a);return await W(d,{output:u,durationSec:i+s,extra:r}),v({outputPath:u,audio:c})}catch(n){return E(n)}})}import{z as Xt}from"zod";var LT={clips:Xt.array(Xt.string().min(1)).min(2).describe("Clip paths, in order."),transition:Xt.string().optional().describe("cut (default) or an xfade name (fade, wipeleft, slideup, ...)."),duration:Xt.number().positive().optional().describe(`Transition seconds (default ${Bn}).`),width:Xt.number().int().positive().optional().describe("Common output width (default 1920)."),height:Xt.number().int().positive().optional().describe("Common output height (default 1080)."),fps:Xt.number().int().positive().optional().describe("Common output fps (default 30)."),output:Xt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Xt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function gw(t){t.registerTool("assemble_highlights",{title:"Assemble Highlights",description:"Stitch clips (including title cards) into one video with cuts or xfade transitions; they need not match in size, fps, or audio.",inputSchema:LT,outputSchema:Y,annotations:I},async(e,r)=>{try{k();for(let c of e.clips)F(c);let n=await Promise.all(e.clips.map(c=>L(c))),o=n.map(c=>qr(c)??0),i=n.map(c=>c.audioCodec!==null),s=B(e.output,"highlights",".mp4",{overwrite:e.overwrite}),a=Jo(e.clips,o,s,{transition:e.transition,duration:e.duration,width:e.width,height:e.height,fps:e.fps},i);return await W(a,{output:s,durationSec:o.reduce((c,u)=>c+u,0)||null,extra:r}),v({outputPath:s,clips:e.clips.length,transition:e.transition??"cut",audio:i.some(Boolean)})}catch(n){return E(n)}})}import{z as mt}from"zod";import{writeFileSync as BT,rmSync as WT}from"node:fs";var jT={text:mt.string().min(1).describe("Title text. Multiple lines are allowed (use \\n)."),duration:mt.number().positive().optional().describe("Card length in seconds (default 3)."),width:mt.number().int().positive().optional().describe("Card width (default 1920)."),height:mt.number().int().positive().optional().describe("Card height (default 1080)."),fps:mt.number().int().positive().optional().describe("Card fps (default 30)."),bg:mt.string().optional().describe("Background color (default black)."),fontColor:mt.string().optional().describe("Text color (default white)."),fontSize:mt.number().int().positive().optional().describe("Text size in px (default 96)."),bold:mt.boolean().optional().describe("Use the bold weight (default true)."),fontFile:vr,output:mt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:mt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function bw(t){t.registerTool("title_card",{title:"Title Card",description:"Generate a title card clip (centered text on a solid background, silent audio track) to stitch in with assemble_highlights. Uncoverable characters are reported in warnings.",inputSchema:jT,outputSchema:Y,annotations:I},async(e,r)=>{try{k();let n=B(e.output,"title",".mp4",{overwrite:e.overwrite}),o=vt(e.text,{weight:e.bold===!1?"regular":"bold",fontFile:e.fontFile}),i=Ue(".txt");BT(i,e.text);try{let s=Ag(i,o.fontFile,n,{duration:e.duration,width:e.width,height:e.height,fps:e.fps,bg:e.bg,fontColor:e.fontColor,fontSize:e.fontSize});await W(s,{output:n,durationSec:e.duration??Yu,extra:r})}finally{WT(i,{force:!0})}return v({outputPath:n,...(o.fallback||e.fontFile)&&{fontFile:o.fontFile},...o.warning&&{warnings:[o.warning]}})}catch(n){return E(n)}})}import{z as _r}from"zod";var UT={video:_r.string().min(1).describe("Path to the video."),music:_r.string().min(1).describe("Music audio file."),musicVolume:_r.number().nonnegative().optional().describe("0..1 (default 0.25 over existing audio, 0.8 alone)."),fadeIn:_r.number().nonnegative().optional().describe("Fade-in seconds (default 1)."),fadeOut:_r.number().nonnegative().optional().describe("Fade-out seconds (default 2)."),duck:_r.boolean().optional().describe("Duck the music under the original audio (default false)."),output:_r.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:_r.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function ww(t){t.registerTool("music_bed",{title:"Add Music Bed",description:"Lay music under a video: looped or trimmed to length, faded, leveled, and mixed with any existing audio. Video is stream-copied.",inputSchema:UT,outputSchema:Y,annotations:I},async(e,r)=>{try{k();for(let a of[e.video,e.music])F(a);let n=await L(e.video);if(n.durationSec===null)throw new l(`Could not read duration of ${e.video}.`);let o=V(e.video),i=B(e.output,"music",o,{overwrite:e.overwrite}),s=Rg(e.video,e.music,i,n.durationSec,n.audioCodec!==null,{musicVolume:e.musicVolume,fadeIn:e.fadeIn,fadeOut:e.fadeOut,duck:e.duck});return await W(s,{output:i,durationSec:n.durationSec,extra:r}),v({outputPath:i,mixedWithOriginal:n.audioCodec!==null})}catch(n){return E(n)}})}import{z as ft}from"zod";import{existsSync as zT,mkdtempSync as HT,readFileSync as GT,rmSync as qT,writeFileSync as XT}from"node:fs";import{tmpdir as JT}from"node:os";import{join as yw}from"node:path";var YT={video:ft.string().min(1).describe("Path to the video."),lines:ft.array(ft.object({t:ft.number().nonnegative().optional().describe("Seconds."),marker:ft.string().optional().describe("Or a marker label."),text:ft.string().min(1)})).min(1),voice:ft.string().optional().describe("Voice name or part (doctor lists them)."),rate:ft.number().min(Ka).max(Va).optional().describe("Default 1."),duck:ft.boolean().optional().describe("Duck the original audio (default true)."),output:ft.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ft.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function xw(t){t.registerTool("narrate",{title:"Narrate",description:"Offline voiceover with the built-in Windows voices: speaks each line at its time or marker over the audio, plus an SRT.",inputSchema:YT,outputSchema:Y,annotations:I},async(e,r)=>{let n=null;try{k(),F(e.video);let o=await L(e.video);if(o.durationSec===null)throw new l(`Could not read duration of ${e.video}.`);let s=e.lines.some(w=>w.marker!==void 0)?(await mr(e.video,r.signal)).markers:[],a=rw(e.lines,s),c=B(e.output,"narrated",V(e.video),{overwrite:e.overwrite}),u=c.replace(/\.[^./\\]+$/,"")+".srt";if(!e.overwrite&&zT(u))throw new l(`Output already exists: ${u}. Pass overwrite: true to replace it.`);n=HT(yw(JT(),"screencast-tts-"));let d=a.map((w,g)=>yw(n,`line-${g}.wav`)),p=await pw(a.map((w,g)=>({text:w.text,path:d[g]})),{voice:e.voice,rate:e.rate,signal:r.signal}),f=a.map((w,g)=>({...w,durationSec:iw(GT(d[g]))})),m=nw(f,o.durationSec),h=sw(e.video,d,c,f,o.durationSec,{hasAudio:o.audioCodec!==null,channels:o.channels,duck:e.duck});await W(h,{output:c,durationSec:o.durationSec,extra:r}),XT(u,nt(ow(f,o.durationSec)));let b=Le(e.video);return b.length>0&&dr(c,b),v({outputPath:c,srtPath:u,voice:p,lines:f.map(w=>({t:w.t,durationSec:Math.round(w.durationSec*100)/100})),mixedWithOriginal:o.audioCodec!==null,...m.length?{warnings:m}:{}})}catch(o){return E(o)}finally{n&&qT(n,{recursive:!0,force:!0})}})}import{z as ai}from"zod";var KT={input:ai.string().min(1).describe("Path to the source video."),aspect:ai.enum(Wn).describe("Target aspect ratio."),fit:ai.enum(la).optional().describe("pad (default): letterbox, nothing lost. crop: fill and center-crop."),output:ai.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ai.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Sw(t){t.registerTool("reframe",{title:"Reframe Aspect Ratio",description:"Re-aspect a video to 16:9, 9:16, 1:1, or 4:5 by padding or cropping.",inputSchema:KT,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=V(e.input),o=B(e.output,"reframe",n,{overwrite:e.overwrite}),i=Mg(e.input,o,e.aspect,e.fit??"pad");return await W(i,{output:o,durationSec:await se(e.input),extra:r}),v({outputPath:o,aspect:e.aspect,fit:e.fit??"pad"})}catch(n){return E(n)}})}import{z as Xe}from"zod";import{z as en}from"zod";import{existsSync as VT,readFileSync as QT}from"node:fs";var Jt=.6,ui=6,Qa=2.5;function Za(t,e,r,n=ui){if(t.length===0)throw new l("Give at least one keyframe.");let i=[...t].sort((s,a)=>s.t-a.t).map(s=>{if(!Number.isFinite(s.t)||s.t<0)throw new l("Keyframe t must be a non-negative number.");if(s.full||s.width===void 0||s.height===void 0)return{t:s.t,z:1,cx:e/2,cy:r/2};if(!(s.width>0)||!(s.height>0))throw new l("Keyframe width and height must be positive.");let a=Math.max(1,Math.min(n,e/s.width,r/s.height));return{t:s.t,z:a,cx:(s.x??0)+s.width/2,cy:(s.y??0)+s.height/2}});return i[0]&&i[0].t>0&&i.unshift({t:0,z:1,cx:e/2,cy:r/2}),i}var Ze=t=>Number(t.toFixed(4)).toString();function vl(t,e,r){let[n,...o]=t;if(!n)throw new l("Give at least one keyframe.");let i=[Ze(n[e])],s=n;for(let a of o){let c=s[e],u=a[e],d=s.t;if(s=a,c===u)continue;let p=a.t,f=Math.max(.001,Math.min(r,p-d)),m=`clip((it-${Ze(p-f)})/${Ze(f)},0,1)`;i.push(`(${Ze(u-c)})*${m}*${m}*(3-2*${m})`)}return _t(i)}function El(t,e,r=Jt){let{width:n,height:o,fps:i}=e,s=n<=1920?2:1,a=vl(t,"z",r),c=vl(t,"cx",r),u=vl(t,"cy",r);return`fps=${Ze(i)},scale=${n*s}:${o*s},zoompan=z='${a}':x='clip((${c})*${s}-iw/zoom/2,0,iw-iw/zoom)':y='clip((${u})*${s}-ih/zoom/2,0,ih-ih/zoom)':d=1:s=${n}x${o}:fps=${Ze(i)}`}function vw(t,e,r,n,o=Jt,i="standard",s){let{width:a,height:c,fps:u}=n,d=El(r,n,o);if(!s||s.clicks.length===0)return["-y","-i",t,"-vf",d,..._e(i),"-c:a","copy",e];let p=["[0:v]null[in]",...tA(s.clicks,a,c,u,s.color),`[out]${d}[v]`].join(";");return["-y","-i",t,"-filter_complex",p,"-map","[v]","-map","0:a?",..._e(i),"-c:a","copy",e]}function $w(t,e,r,n,o={}){let i=o.step??.25,s=o.holdSec??2,a=o.maxZoom??Qa,c=o.globalFraction??.3,u=o.transition??Jt,d=r/t,p=r/a,f=n/a,m=[],h=null,b=()=>{h&&m.push(h),h=null},w=null,g=0;return{push:S=>{let C=w;if(w=S,!C){g=1;return}let M=g++*i,R=kt(C,S,t,e,{scale:d});if(R.regions.length===0){h&&M-h.last>s&&b();return}if(R.changedFraction>c){b();return}let P=kl(R.regions);h&&M-h.last<=s&&ZT(h.box,P,r,n)?(h.box=kl([h.box,P]),h.last=M):(b(),h={start:M,last:M,box:P})},finish:()=>{b();let S=[],C=0;for(let M of m){let R=kw(M.box,r,n,p,f),P=Math.max(M.start,C+u),j=Math.max(M.last+s,P+u);S.push({t:ci(P),...R},{t:ci(j),full:!0}),C=j}return S}}}var ci=t=>Math.round(t*100)/100;function kl(t){let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,width:n-e,height:o-r}}function ZT(t,e,r,n){let o=kl([t,e]);return o.width<=r/2&&o.height<=n/2}function kw(t,e,r,n,o){let i=Math.max(t.width*1.4,n),s=Math.max(t.height*1.4,o),a=e/r;i/s>a?s=i/a:i=s*a,i=Math.min(i,e),s=Math.min(s,r);let c=t.x+t.width/2,u=t.y+t.height/2,d=Math.max(0,Math.min(e-i,c-i/2)),p=Math.max(0,Math.min(r-s,u-s/2));return{x:Math.round(d),y:Math.round(p),width:Math.round(i),height:Math.round(s)}}function Ew(t,e,r){return["-v","error","-i",t,"-an","-vf",`fps=${Ze(1/r)},scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function ec(t,e,r,n={}){let o=n.holdSec??2,i=n.maxZoom??Qa,s=n.transition??Jt,a=e/i,c=r/i,u=Math.min(e,r)*.05,d=[...t].sort((h,b)=>h.t-b.t),p=[],f=0,m=-1/0;for(let h of d){let b=kw({x:h.x-u,y:h.y-u,width:2*u,height:2*u},e,r,a,c),w=p[p.length-1];if(w&&!w.full&&h.t-m<=o&&eA(w,h)){m=h.t;continue}if(h.t-m>o&&p.length>0){let y=Math.max(m+o,f+s);p.push({t:ci(y),full:!0}),f=y}let g=Math.max(h.t,f+s);p.push({t:ci(g),...b}),f=g,m=h.t}return p.length>0&&p.push({t:ci(Math.max(m+o,f+s)),full:!0}),p}function eA(t,e){let r=t.width*.15,n=t.height*.15;return e.x>=t.x+r&&e.x<=t.x+t.width-r&&e.y>=t.y+n&&e.y<=t.y+t.height-n}var $l=.6,tc="#FF4545";function _l(t,e){return Math.max(40,2*Math.round(Math.min(t,e)*.045))}function tA(t,e,r,n,o){let i=_l(e,r),s=i/2,a=Math.max(3,Math.round(i/10)),c=s*.3,u=s-a/2-c,d=[],p="[in]";return t.forEach((f,m)=>{let h=`if(lt(abs(hypot(X-${s},Y-${s})-(${Ze(c)}+${Ze(u)}*T/${$l})),${a/2}),255*min(1,2-2*T/${$l}),0)`;d.push(`color=c=${o}:s=${i}x${i}:r=${Ze(n)}:d=${$l},format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${h}',setpts=PTS+${Ze(f.t)}/TB[ring${m}]`);let b=m===t.length-1?"[out]":`[r${m}]`;d.push(`${p}[ring${m}]overlay=x=${Ze(f.x-s)}:y=${Ze(f.y-s)}:eof_action=pass${b}`),p=`[r${m}]`}),d}function li(t){return VT(t)?je(QT(t,"utf8")).filter(e=>e.type==="down"&&e.inFrame).map(e=>({t:e.t,x:e.x,y:e.y})):null}var rc=en.object({t:en.number().nonnegative(),x:en.number().optional(),y:en.number().optional(),width:en.number().positive().optional(),height:en.number().positive().optional(),full:en.boolean().optional()});var _w=200,rA={input:Xe.string().min(1).describe("Path to the source video."),keyframes:Xe.array(rc).max(100).optional().describe("Views reached by time t: a source rectangle (x, y, width, height), or { t, full: true } to zoom out. Omit to plan them (see follow)."),follow:Xe.enum(["auto","clicks","changes"]).optional().describe("Without keyframes: clicks (from the events log of start_recording events: true) or changes (where the screen changed). auto (default): clicks if logged, else changes."),events:Xe.string().optional().describe("Events log (default: the input's .events.jsonl); must match the input's timing and size, so use the original recording."),highlightClicks:Xe.boolean().optional().describe("Ring each logged click (default false)."),highlightColor:Xe.string().optional().describe("Ring color (default #FF4545)."),transitionSec:Xe.number().positive().max(5).optional().describe(`How long each zoom/pan eases (default ${Jt}).`),maxZoom:Xe.number().min(1).max(ui).optional().describe(`Auto mode: the furthest it zooms in (default ${Qa}).`),holdSec:Xe.number().positive().max(30).optional().describe("Auto mode: stay zoomed this long after activity (default 2)."),dryRun:Xe.boolean().optional().describe("Return the planned keyframes only (editable, pass back)."),output:Xe.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Xe.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Tw(t){t.registerTool("zoom",{title:"Zoom and Pan",description:"Smooth animated zoom-and-pan into the action and back out, from keyframes or planned from logged clicks or screen changes.",inputSchema:rA,outputSchema:N({keyframes:Xe.array(Xe.unknown())}),annotations:I},async(e,r)=>{try{k(),F(e.input);let n=await L(e.input),{width:o,height:i,durationSec:s}=n;if(!o||!i)throw new l(`Could not read the size of ${e.input}.`);let a=n.fps??30,c=e.transitionSec??Jt,u=e.events??$e(e.input).jsonl,d=li(u);if(e.events&&!d)throw new l(`No event log at ${e.events}.`);if((e.follow==="clicks"||e.highlightClicks)&&!d)throw new l(`No event log for ${e.input} (looked for ${u}). Record with start_recording events: true, or pass events: <path to .events.jsonl>.`);let p=De(e.highlightColor??tc,"highlightColor"),f=e.keyframes,m=!f,h=e.follow==="clicks"||e.follow!=="changes"&&d&&d.length>0?"clicks":"changes";if(!f&&h==="clicks"&&(f=ec(d??[],o,i,{holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c}),f.length===0))return v({keyframes:[],follow:h,note:"The event log has no clicks inside the frame; nothing written."});if(!f){let $=Zh(o,i),S=.25,C=$w($.width,$.height,o,i,{step:S,holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c});if(await Wi(Ew(e.input,$,S),$.width*$.height,M=>C.push(M),le(s),{signal:r.signal}),f=C.finish(),f.length===0)return v({keyframes:[],note:"No localised changes found to zoom into; nothing written."})}if(e.dryRun)return v({planned:m,...m?{follow:h}:{},keyframes:f,transitionSec:c});if(e.highlightClicks&&d&&d.length>_w)throw new l(`${d.length} clicks is more than ${_w} rings; trim the video or the event log first.`);let b=Za(f,o,i),w=V(e.input),g=B(e.output,"zoom",w,{overwrite:e.overwrite}),y=e.highlightClicks?{clicks:d??[],color:p}:void 0;return await W(vw(e.input,g,b,{width:o,height:i,fps:a},c,"standard",y),{output:g,durationSec:s,extra:r}),v({outputPath:g,planned:m,...m?{follow:h}:{},keyframes:f,...y?{ringedClicks:y.clicks.length}:{}})}catch(n){return E(n)}})}import{z as O}from"zod";import{dirname as mA,join as tn}from"node:path";import{existsSync as ic,mkdtempSync as fA,readFileSync as Dw,rmSync as hA,writeFileSync as pi}from"node:fs";import{tmpdir as gA}from"node:os";var Zn=30,At=t=>Math.round(t*1e3)/1e3;function Tl(t,e){let r=[...t],n=r.indexOf("-af");return n!==-1&&e.audio.length>0&&(r[n+1]=`${e.audio.join(",")},${r[n+1]}`),r.splice(r.indexOf("-i"),0,...e.seek),r}function Aw(t,e,r){let n=e.slice(r);return n.length>0?as(t,n):[...t]}function nc(t,e,r,n,o={},i="standard",s={}){if(r.length===0)throw new l("Give at least one step.");if(r.length>Zn)throw new l(`At most ${Zn} steps.`);r.forEach((x,q)=>{if((x.op==="export_preset"||x.op==="export_gif")&&q!==r.length-1)throw new l(`${x.op} must be the last step (it is step ${q+1} of ${r.length}).`)});let a=r.findIndex(x=>x.op==="zoom"),c=a===-1?-1:r.findIndex((x,q)=>q>a&&x.op==="redact");if(c!==-1)throw new l(`step ${c+1}: redact comes after zoom (step ${a+1}), which moves the content under a fixed box. Put redact before zoom, in the source's coordinates.`);let u=r.some(x=>x.op==="redact");if(r.filter(x=>x.op==="cut_idle").length>1)throw new l("Use at most one cut_idle step.");let d=n.width,p=n.height,f=n.fps,m=n.durationSec,h=[],b=[],w=1,g=[],y=[],$=!1,S="[0:v]",C=null,M,R=[],P=[],j=[],X=[],D={sx:1,sy:1,ox:0,oy:0},ae=(x,q)=>{if(!Number.isFinite(x.start)||x.start<0)throw new l(`step ${q}: trim start must be a non-negative number.`);if(x.end===void 0==(x.duration===void 0))throw new l(`step ${q}: trim takes end OR duration.`);let H=x.end??x.start+x.duration;if(!(H>x.start))throw new l(`step ${q}: trim end must be after start.`);if(m!==null&&x.start>=m)throw new l(`step ${q}: trim starts at ${x.start}s, but the video is ${At(m)}s long at that point.`);return{start:x.start,end:m!==null?Math.min(H,m):H}};r.forEach((x,q)=>{let H=q+1,de=`p${q}`,G=`[${de}]`,Q=T=>{g.push(`${S}${T}${G}`),S=G},te=T=>j.push({step:q,kind:T,seek:[...h],audio:[...y],ops:[...P]});switch(x.op){case"trim":{let{start:T,end:_}=ae(x,H);q===0?(h.push("-ss",String(T),"-t",String(At(_-T))),R.push(`trim ${T}-${At(_)}s: input seek`)):(Q(`trim=start=${T}:end=${At(_)},setpts=PTS-STARTPTS`),y.push(`atrim=start=${T}:end=${At(_)},asetpts=PTS-STARTPTS`),R.push(`trim ${T}-${At(_)}s: trim filter`)),$=!0,m=_-T,P.push({op:"trim",start:T,end:_});break}case"crop":Q(Ec(x,{width:d,height:p})),D&&(D={...D,ox:D.ox-x.x,oy:D.oy-x.y}),d=x.width,p=x.height,R.push(`crop to ${d}x${p}`);break;case"scale":{let T=_c(x),[_,A]=[d,p];({width:d,height:p}=Cp(d,p,x)),D&&(D={sx:D.sx*d/_,sy:D.sy*p/A,ox:D.ox*d/_,oy:D.oy*p/A}),Q(T),R.push(`scale to ${d}x${p}`);break}case"speed":{if(x.factor===void 0==(x.segments===void 0))throw new l(`step ${H}: speed takes factor or segments.`);if(x.segments){let _=$a(x.segments,m),A=ka(_,f);Q(A.video),y.push(A.audio),$=!0;let z=Kr(_);m!==null&&(m-=z),P.push({op:"cut",spans:_}),R.push(`speed up ${_.length} range(s), ${At(z)}s saved`);break}let T=x.factor;if(!Number.isFinite(T)||T<=0)throw new l(`step ${H}: speed factor must be positive.`);Q(`setpts=PTS/${T}`),y.push(Tc(T)),$=!0,m!==null&&(m/=T),P.push({op:"speed",factor:T}),R.push(`speed x${T}`);break}case"redact":{let{steps:T,out:_}=Ac(x.regions,x,{width:d,height:p},S,de);g.push(...T),S=_,R.push(`redact ${x.regions.length} region(s), ${x.style??"box"}`);break}case"callout":{let T=o[q];if(!T)throw new l(`Internal: missing callout assets for step ${H}.`);let{steps:_,out:A,extraInputs:z}=ol(x.items,T,S,w,de);g.push(..._),b.push(...z),w+=z.length/4,S=A,R.push(`callout ${x.items.length} item(s)`);break}case"reframe":{let T=jn[x.aspect];if(!T)throw new l(`step ${H}: unknown aspect "${x.aspect}".`);Q(`${pa(T.w,T.h,x.fit??"pad")},format=yuv420p`),D=null,d=T.w,p=T.h,R.push(`reframe to ${x.aspect} (${x.fit??"pad"})`);break}case"zoom":{let T=x.transitionSec??Jt,_=x.keyframes,A="";if(x.follow==="clicks"){if(_)throw new l(`step ${H}: zoom takes keyframes or follow, not both.`);if(!D)throw new l(`step ${H}: zoom follow "clicks" must come before reframe, backdrop or another zoom; the logged click positions no longer match the frame.`);let z=D,K=s.clicks?.[q];if(!K)throw new l(`Internal: missing clicks for step ${H}.`);let ue=K.flatMap(me=>{let Ne=ss(me.t,P),Rt=me.x*z.sx+z.ox,uo=me.y*z.sy+z.oy;return Ne!==null&&Rt>=0&&Rt<d&&uo>=0&&uo<p?[{t:Ne,x:Rt,y:uo}]:[]});_=ec(ue,d,p,{holdSec:x.holdSec,maxZoom:x.maxZoom,transition:T}),A=` from ${ue.length} click(s)`}else if(!_||_.length===0)throw new l(`step ${H}: zoom needs keyframes, or follow: "clicks".`);if(_.length===0){R.push("zoom: no clicks in this part of the video; skipped");break}Q(El(Za(_,d,p),{width:d,height:p,fps:f},T)),D=null,R.push(`zoom ${_.length} keyframe(s)${A}`);break}case"cut_idle":{if(!s.idle)throw new l(`Internal: missing idle scan for step ${H}.`);let T=Sa(km(s.idle,P),x.minIdleSec??Yr,x.keepSec??Ko);if(T.length===0){R.push("cut_idle: no idle stretches here; nothing cut");break}if(x.action==="speed"){let z=x.factor??Vo,K=T.map(Ne=>({...Ne,factor:z})),ue=ka(K,f);Q(ue.video),y.push(ue.audio),$=!0;let me=Kr(K);m!==null&&(m-=me),P.push({op:"cut",spans:K}),R.push(`cut_idle ${T.length} stretch(es) sped up x${z}, ${At(me)}s saved`);break}let _=Qu(T);Q(_.video),y.push(_.audio),$=!0;let A=T.reduce((z,K)=>z+(K.end-K.start),0);m!==null&&(m-=A),P.push({op:"cut",spans:T}),R.push(`cut_idle ${T.length} stretch(es), ${At(A)}s removed`);break}case"audio":{if(x.normalize===void 0&&x.denoise===void 0)throw new l(`step ${H}: audio needs normalize and/or denoise.`);if(!n.hasAudio){R.push("audio: the input has no audio; skipped");break}let T=s.audio?.[q],_=[];if(x.denoise!==void 0&&(T?.floorDb===void 0&&te("noisefloor"),y.push(bl(x.denoise,T?.floorDb??null)),_.push(`denoise ${x.denoise}`)),x.normalize!==void 0&&T?.silent)_.push("silent, not normalized");else if(x.normalize!==void 0){let A=Vn(x.normalize);T?.loudness||te("loudness"),y.push(gl(A,T?.loudness),"aresample=48000"),_.push(`normalize to ${A.i} LUFS${T?.loudness?` (measured ${T.loudness.input_i})`:""}`)}$=!0,R.push(`audio: ${_.join(", ")}`);break}case"burn_subtitles":{if(!x.subtitles==!x.transcribe)throw new l(`step ${H}: burn_subtitles takes subtitles (a path) or transcribe: true.`);if(x.transcribe&&!n.hasAudio)throw new l(`step ${H}: transcribe needs audio, and the input has none.`);let T=s.subtitles?.[q];if(T===""){R.push("burn_subtitles: no cues in this part of the video; skipped");break}T===void 0&&te(x.transcribe?"transcribe":"subtitles");let _=!!x.subtitles&&/\.(ass|ssa)$/i.test(x.subtitles),A=x.style??(_?null:"clean");Q(Wu(T??"<subtitles.srt>",s.fontsDir??"<fonts>",A)),R.push(`burn_subtitles ${x.transcribe?"from a transcript":"from a file"}, ${A??"file"} style`);break}case"backdrop":{let{op:T,..._}=x,{steps:A,out:z,extraInputs:K,layout:ue}=ml(_,{width:d,height:p},S,w,de);D=null,g.push(...A),b.push(...K),w+=K.length/2,S=z,d=ue.canvasW,p=ue.canvasH,R.push(`backdrop to ${d}x${p}`);break}case"keystroke_overlay":{let T=s.keystrokes?.[q];if(!T)throw new l(`Internal: missing keystroke badges for step ${H}.`);let _=db(T.badges,P);if(_.length===0){R.push("keystroke_overlay: no badges in this part of the video");break}let{steps:A,out:z}=al(Ia(_),T,x,{height:p},S,de);g.push(...A),S=z,R.push(`keystroke_overlay ${_.length} badge(s)`);break}case"cursor":{if(!D)throw new l(`step ${H}: cursor must come before zoom, reframe or backdrop; the logged positions no longer match the frame after them.`);let T=s.cursor?.[q];if(!T)throw new l(`Internal: missing cursor plan for step ${H}.`);let _=Da(T.plan,P,D);if(_.path.length===0||_.visible.length===0){R.push("cursor: no cursor movement in this part of the video");break}let{steps:A,out:z,extraInputs:K,commands:ue}=ll(_,x,{width:d,height:p},S,w,de,T.sprite,T.commandsFile);g.push(...A),b.push(...K),w+=K.length/2,S=z,X.push({path:T.commandsFile,content:ue}),R.push(`cursor ${_.path.length} segment(s), ${_.clicks.length} click(s)${x.spotlight?", spotlight":""}`);break}case"export_preset":{let T=Vu(x.platform,x.fit??"pad",de);D=null,Q(T.vf),T.af&&y.push(T.af),C=T.encode,d=T.width,p=T.height,f=30,$=!0,R.push(`export_preset ${x.platform}`);break}case"export_gif":{let{op:T,..._}=x;M=_,R.push(`export_gif (${_.format??"gif"}): second stage, size-budget ladder`);break}}});let ee=["-y",...h,"-i",t,...b],J=s.chaptersFile?ee.filter(x=>x==="-i").length:-1;s.chaptersFile&&ee.push("-f","ffmetadata","-i",s.chaptersFile);let ie=n.hasAudio&&y.length>0;ie&&g.push(`[0:a]${y.join(",")}[aout]`),g.length>0&&ee.push("-filter_complex",g.join(";")),ee.push("-map",S==="[0:v]"?"0:v":S),n.hasAudio&&ee.push("-map",ie?"[aout]":"0:a");let ce=C;return ce?ee.push(...ce):(ee.push(..._e(M||u?"high":i)),n.hasAudio&&ee.push(...$?["-c:a","aac","-b:a","160k"]:["-c:a","copy"]),ee.push("-movflags","+faststart")),J!==-1&&ee.push("-map_chapters",String(J)),ee.push(e),{args:ee,width:d,height:p,fps:f,durationSec:m===null?null:At(m),gif:M,summary:R,timeOps:P,pending:j,files:X}}var Mw=["pr_demo","tutorial","social_reel"],nA=1e7,Rw=new Set(["export_preset","export_gif"]);function Cw(t,e){let r=[],n=[{op:"cut_idle"}];e.hasClicks?n.push({op:"zoom",follow:"clicks"}):r.push("zoom left out: no event log with clicks (record with start_recording events: true).");let o=i=>{e.hasAudio&&(e.transcribeBlocker?r.push(`captions left out: ${e.transcribeBlocker}`):n.push({op:"burn_subtitles",transcribe:!0,style:i}))};switch(!e.hasAudio&&t!=="pr_demo"&&r.push("audio and captions left out: the input has no audio."),t){case"pr_demo":n.push({op:"export_gif",maxBytes:nA});break;case"tutorial":e.hasAudio&&n.push({op:"audio",denoise:"light",normalize:"youtube"}),o("clean"),n.push({op:"export_preset",platform:"youtube"});break;case"social_reel":e.hasAudio&&n.push({op:"audio",normalize:"youtube"}),n.push({op:"reframe",aspect:"9:16"}),o("social"),n.push({op:"export_preset",platform:"instagram_reel"});break;default:throw new l(`Unknown recipe "${String(t)}".`)}return{steps:n,notes:r}}var oA=new Set(["redact","crop","cursor"]);function Al(t,e){let r=[...t],o=r.at(-1)&&Rw.has(r.at(-1).op)?r.pop():null,i=r.length,s=new Set,a=[],c=[];for(let u of e){if(Rw.has(u.op)){o=u;continue}let d=r.findIndex((p,f)=>f<i&&!s.has(f)&&p.op===u.op);d===-1&&u.op==="trim"?a.push(u):d===-1&&oA.has(u.op)?c.push(u):d===-1?r.push(u):(r[d]=u,s.add(d))}return[...a,...c,...r,...o?[o]:[]]}import{readFileSync as iA,statSync as sA,writeFileSync as aA}from"node:fs";var Pw=1;function cA(t){return`${t}.edit.json`}function uA(t,e="the edit spec"){let r;try{r=JSON.parse(t)}catch{throw new l(`${e} is not valid JSON.`)}let n=r;if(n?.tool!=="pipeline"||typeof n.version!="number"||!Array.isArray(n.steps)||typeof n.source?.path!="string")throw new l(`${e} is not a pipeline edit spec.`);if(n.version>Pw)throw new l(`${e} was written by a newer version (spec ${n.version}).`,"Update screencast-mcp to re-render it.");return n}function Iw(t){let e;try{e=iA(t,"utf8")}catch{throw new l(`Edit spec not found: ${t}`)}return uA(e,t)}function Rl(t){let e=sA(t);return{path:t,size:e.size,mtimeMs:Math.round(e.mtimeMs)}}function Fw(t){let e;try{e=Rl(t.source.path)}catch{return`its source ${t.source.path} is gone`}return e.size!==t.source.size||e.mtimeMs!==t.source.mtimeMs?`its source ${t.source.path} changed since`:null}function Ow(t,e){let r=cA(t),n={version:Pw,tool:"pipeline",createdAt:new Date().toISOString(),output:t,...e};return aA(r,JSON.stringify(n,null,2)+`
|
|
375
|
+
`),r}var lA=new Set(["input","inputs","inputA","inputB","clips","a","b","image","overlay","music","video","subtitles","srt","transcript","events","path","file","perf","fromEdit"]),pA=new Set(["output","outputDir","model","fontFile"]),dA=new Set(["whisper"]);function Nw(t){return typeof t=="string"?[t]:Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function oc(t){let e=r=>{if(Array.isArray(r)){r.forEach(e);return}if(!(!r||typeof r!="object"))for(let[n,o]of Object.entries(r)){if(lA.has(n))for(let i of Nw(o))i.trim().length>0&&!dA.has(i)&&mp(i,`Input "${n}"`);else if(pA.has(n))for(let i of Nw(o))Qt(i,`"${n}"`);o&&typeof o=="object"&&e(o)}};e(t)}function bA(){if(!Ye("whisper"))return"this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";try{return br(void 0),null}catch{return"no whisper model (set SCREENCAST_WHISPER_MODEL)."}}var wA=O.enum(Wn),Lw=O.enum(la).optional(),yA=O.discriminatedUnion("op",[O.object({op:O.literal("trim"),start:O.number().nonnegative(),end:O.number().positive().optional(),duration:O.number().positive().optional()}),O.object({op:O.literal("crop"),x:O.number().int().nonnegative(),y:O.number().int().nonnegative(),width:O.number().int().positive(),height:O.number().int().positive()}),O.object({op:O.literal("scale"),width:O.number().int().positive().optional(),height:O.number().int().positive().optional()}),O.object({op:O.literal("speed"),factor:O.number().positive().optional(),segments:O.array(va).min(1).optional()}),O.object({op:O.literal("redact"),regions:O.array(gn).min(1),style:O.enum(Fi).optional(),pad:O.number().int().nonnegative().optional(),color:O.string().optional()}),O.object({op:O.literal("callout"),items:O.array(Ra).min(1).max(50),fontFile:vr}),O.object({op:O.literal("reframe"),aspect:wA,fit:Lw}),O.object({op:O.literal("zoom"),keyframes:O.array(rc).min(1).max(100).optional(),follow:O.literal("clicks").optional(),maxZoom:O.number().min(1).max(ui).optional(),holdSec:O.number().positive().max(30).optional(),transitionSec:O.number().positive().max(5).optional()}),O.object({op:O.literal("cut_idle"),minIdleSec:O.number().positive().optional(),keepSec:O.number().min(0).optional(),action:O.enum(["cut","speed"]).optional(),factor:O.number().gt(1).max(Jr).optional()}),O.object({op:O.literal("audio"),normalize:za.optional(),denoise:O.enum(Ga).optional()}),O.object({op:O.literal("burn_subtitles"),subtitles:O.string().min(1).optional(),transcribe:O.boolean().optional(),style:O.enum(Vs).optional()}),O.object({op:O.literal("backdrop"),...ja}),O.object({op:O.literal("keystroke_overlay"),...Fa}),O.object({op:O.literal("cursor"),...La}),O.object({op:O.literal("export_preset"),platform:O.enum(da),fit:Lw}),O.object({op:O.literal("export_gif"),format:O.enum(["gif","webp"]).optional(),maxBytes:O.number().int().min(1e4).optional(),fps:O.number().positive().max(30).optional(),width:O.number().int().min(64).max(1920).optional()})]),xA={input:O.string().min(1).optional().describe("Path to the source video."),fromEdit:O.string().min(1).optional().describe("Re-render an .edit.json; steps replace same-op steps."),steps:O.array(yA).max(Zn).optional().describe(`Edits in order, each { op, ...its tool's options }; export_preset/export_gif only last. Times and pixels are relative to the video as it is at that step (after earlier trims, speed, crops). zoom follow:"clicks" plans from the event log; burn_subtitles takes subtitles or transcribe:true.`),recipe:O.enum(Mw).optional().describe("Polish preset expanded to steps (see dryRun): pr_demo = cut_idle, click zoom, GIF <=10 MB; tutorial = + audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step; trim, redact, crop and cursor go first (source pixels and time)."),quality:O.enum(["draft","standard","high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),dryRun:O.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),output:O.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:O.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),chapters:O.boolean().optional().describe("Keep the input's markers as chapters, re-timed through trims and speed.")};function Bw(t){t.registerTool("pipeline",{title:"Edit Pipeline",description:"Run several edits (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, cursor, reframe, zoom, backdrop, audio, burn_subtitles, then optionally export_preset or export_gif) in one ffmpeg pass: one re-encode, no intermediate files. Prefer it over chaining edit tools; a recipe does the usual polish in one call.",inputSchema:xA,outputSchema:N({processes:O.number().int(),steps:O.array(O.string())}),annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k(),o=e.fromEdit?Iw(e.fromEdit):null;if(o){if(oc({input:o.source.path,steps:o.steps}),e.recipe)throw new l("fromEdit already has its steps; leave recipe out.");if(e.input&&!Bo(e.input,o.source.path))throw new l(`The spec is for ${o.source.path}, not ${e.input}.`);let P=Fw(o);if(P)throw new l(`Cannot re-render ${e.fromEdit}: ${P}.`,"Run pipeline on the source again with steps instead.")}let i=e.input??o?.source.path;if(!i)throw new l("Pass input (or fromEdit).");let s=e.quality??o?.quality??"standard",a=e.chapters??o?.chapters??!1;F(i);let c=await L(i),u=c.audioCodec!==null,d=[],p=e.steps??[];if(o&&(p=Al(o.steps,p)),e.recipe){let P=li($e(i).jsonl),j=Cw(e.recipe,{hasAudio:u,hasClicks:!!P&&P.length>0,transcribeBlocker:u?bA():null});p=Al(j.steps,p),d.push(...j.notes)}if(p.length===0)throw new l("Give steps, a recipe, or both.");if(p.length>Zn)throw new l(`At most ${Zn} steps.`);if(!c.width||!c.height)throw new l(`Could not read the size of ${i}.`);let f={width:c.width,height:c.height,fps:c.fps??30,durationSec:c.durationSec,hasAudio:u},m=le(c.durationSec),h=p.at(-1);if(!h)throw new l("Provide at least one step.");let b=h.op==="export_gif"?`.${h.format??"gif"}`:".mp4",w=B(e.output,"pipeline",b,{overwrite:e.overwrite,anyContainer:h.op==="export_gif"}),g=h.op!=="export_gif"&&p.some(P=>P.op==="burn_subtitles"&&P.transcribe),y=w.replace(/\.[^./\\]+$/,"")+".srt";if(g&&!e.overwrite&&ic(y))throw new l(`Output already exists: ${y}. Pass overwrite: true to replace it.`);for(let[P,j]of p.entries())if(j.op==="burn_subtitles"){if(!Ye("subtitles"))throw new l("This ffmpeg has no subtitles filter (it needs libass).","Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");if(j.subtitles&&!ic(j.subtitles))throw new l(`step ${P+1}: subtitles file not found: ${j.subtitles}`);if(j.transcribe){if(!Ye("whisper"))throw new l(`step ${P+1}: transcribe needs FFmpeg 8 built with whisper.cpp (no whisper filter here).`);br(void 0)}}let $={};for(let[P,j]of p.entries()){if(j.op!=="zoom"||j.follow!=="clicks")continue;let X=$e(i).jsonl,D=li(X);if(!D)throw new l(`step ${P+1}: no event log at ${X}; record with start_recording events: true.`);$[P]=D}let S,C=p.findIndex(P=>P.op==="cut_idle"),M=p[C];if(M?.op==="cut_idle"){let P=c.durationSec;if(P===null)throw new l(`Could not read the duration of ${i}.`);let j=p.slice(0,C).reduce((ee,J)=>J.op==="speed"&&J.factor?ee*J.factor:ee,1),X=u,D=await ne(n,ba(i,(M.minIdleSec??Yr)*j,X),m,{signal:r.signal});if(D.code!==0)throw new l(`Idle scan failed (exit ${D.code}): ${D.stderr.trim().slice(-400)}`);let ae=wa(D.stderr,P);S=X?xa(ae,ya(D.stderr,P)):ae}let R=fA(tn(gA(),"screencast-pipeline-"));try{let P={},j=[];for(let[_,A]of p.entries()){if(A.op!=="callout")continue;let z=e.dryRun?{fontFile:"<font>",textFiles:A.items.map(K=>K.type==="text"?"<text>":null),arrowFiles:A.items.map(K=>K.type==="arrow"?"<arrow.png>":null),...il(A.items,A.fontFile)}:await Ma(A.items,R,`s${_}_`,A.fontFile);P[_]=z,j.push(...z.fallbackFonts.map(K=>({step:_,...K}))),d.push(...z.warnings.map(K=>`Step ${_}, ${K.charAt(0).toLowerCase()}${K.slice(1)}`))}let X={};for(let[_,A]of p.entries()){if(A.op==="backdrop"&&A.image&&!ic(A.image))throw new l(`step ${_+1}: background image not found: ${A.image}`);if(A.op!=="keystroke_overlay")continue;let{badges:z}=Oa(i,A.events,A),K=[...new Set(z.map(me=>me.label))],ue=Zo(K,e.dryRun?null:R,`s${_}_`,A.fontFile);X[_]={badges:z,fontFile:ue.fontFile,textFiles:ue.textFiles},d.push(...ue.warnings.map(me=>`Step ${_}, ${me.charAt(0).toLowerCase()}${me.slice(1)}`))}let D={};for(let[_,A]of p.entries())A.op==="cursor"&&(D[_]={plan:Ba(i,A.events,A,c.durationSec),sprite:Na(),commandsFile:e.dryRun?`<cursor ${_}.cmd>`:tn(R,`s${_}_cursor.cmd`)});let ae=h.op==="export_gif"?e.dryRun?"<temporary stage1.mp4>":tn(R,"stage1.mp4"):w,ee={},J={},ie=mA(Bt("regular")),ce=_=>nc(i,ae,p,f,P,s,{keystrokes:X,cursor:D,idle:S,clicks:$,audio:ee,subtitles:J,fontsDir:ie,chaptersFile:_}),x=ce(),q;for(let _=0;!e.dryRun&&x.pending.length>0;_++){let A=x.pending[0];if(_>p.length*3)throw new l(`Internal: step ${A.step+1} ${A.kind} did not resolve.`);let z=p[A.step],K=async ue=>{let me=Bi(Tl(ue,A));try{let Ne=await ne(n,me.args,m,{signal:r.signal});if(Ne.code!==0)throw new l(`step ${A.step+1} ${A.kind} scan failed (exit ${Ne.code}): ${Ne.stderr.trim().slice(-400)}`);return Ne}finally{me.cleanup()}};if(A.kind==="noisefloor")ee[A.step]={...ee[A.step],floorDb:Xa((await K(qa(i))).stdout)};else if(A.kind==="loudness"&&z.op==="audio"){let ue=await K(oi(i,Vn(z.normalize)));try{ee[A.step]={...ee[A.step],loudness:ii(ue.stderr)}}catch{d.push(`Step ${A.step+1}: the audio is silent; not normalized.`),ee[A.step]={...ee[A.step],silent:!0}}}else if(A.kind==="transcribe"&&z.op==="burn_subtitles"){let ue=tn(R,`s${A.step}_raw.srt`);await Z(Tl(On(i,br(void 0),ue),A),m,{signal:r.signal});let me=ic(ue)?ut(We(Dw(ue,"utf8"))):[];J[A.step]=me.length>0?tn(R,`s${A.step}.srt`):"",me.length>0?(q={cues:me,opsBefore:A.ops.length},pi(J[A.step],nt(me))):d.push(`Step ${A.step+1}: no speech was recognised; no captions.`)}else if(A.kind==="subtitles"&&z.op==="burn_subtitles"&&z.subtitles)if(A.ops.length===0)J[A.step]=z.subtitles;else{let ue=Dw(z.subtitles,"utf8"),me=/\.(ass|ssa)$/i.test(z.subtitles),Ne=me?Em(ue,A.ops):nt(as(ut(We(ue)),A.ops)),Rt=tn(R,`s${A.step}${me?".ass":".srt"}`);pi(Rt,Ne),J[A.step]=me||Ne.trim()?Rt:""}else throw new l(`Internal: step ${A.step+1} cannot resolve ${A.kind}.`);x=ce()}let H=[],de=[];if(a){let _=x.gif?null:await mr(i,r.signal);if(!_)d.push("chapters: a GIF/WebP cannot hold chapters; none written.");else if(_.markers.length===0)d.push("chapters: the input has no markers (add_marker) or chapters; none written.");else if(de=Rm(_.markers,x.timeOps),H=x.durationSec?ls(ds(de),x.durationSec):[],H.length===0)d.push("chapters: no marker falls inside the result; none written.");else{let A=e.dryRun?"<chapters.txt>":tn(R,"chapters.txt");e.dryRun||pi(A,ps(H)),x=ce(A)}}let G={...e.recipe&&{recipe:e.recipe,expandedSteps:p},steps:x.summary,...e.dryRun&&x.pending.length>0&&{measuredOnRun:x.pending.map(_=>`step ${_.step+1}: ${_.kind}`)},processes:x.gif?2:1,width:x.width,height:x.height,durationSec:x.durationSec,...j.length>0&&{fallbackFonts:j},...d.length>0&&{warnings:d},...H.length>0&&{chapters:H}};if(e.dryRun)return v({dryRun:!0,...G,ffmpegArgs:x.args});let Q=()=>{try{let _=e.recipe??o?.recipe;return{editSpecPath:Ow(w,{serverVersion:wt(),source:Rl(i),steps:p,..._?{recipe:_}:{},quality:s,chapters:a})}}catch{return{}}};for(let _ of x.files)pi(_.path,_.content);if(await W(x.args,{output:ae,durationSec:x.durationSec,inputDurationSec:c.durationSec,extra:r}),x.gif){let _=await zn(ae,w,x.gif,r);return v({outputPath:w,...G,animation:_,...Q()})}let te;if(q)try{let _=Aw(q.cues,x.timeOps,q.opsBefore);_.length>0&&(pi(y,nt(_)),te=y)}catch{te=void 0}let T;if(H.length>0)try{T=dr(w,de.filter(_=>_.t<(x.durationSec??1/0)))}catch{}return v({outputPath:w,...G,...T&&{markersPath:T},...te&&{subtitlesPath:te},...Q()})}finally{hA(R,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as di}from"zod";var SA={input:di.string().min(1).describe("Path to the source video."),platform:di.enum(da).describe("Sets aspect, size, fps, bitrate. steam_trailer: 1080p 5.5 Mbps CBR, -14 LUFS. vertical_reel: 1080x1920 over a blurred copy of itself, -14 LUFS (ignores fit)."),fit:di.enum(["pad","crop"]).optional().describe("Fit to the platform aspect: pad (default) or crop."),output:di.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:di.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ww(t){t.registerTool("export_preset",{title:"Export for Platform",description:"Encode a platform-ready H.264 file (aspect, fps, bitrate, faststart) for a named platform.",inputSchema:SA,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.platform,o=B(e.output,n,".mp4",{overwrite:e.overwrite}),i=Cg(e.input,o,n,e.fit??"pad");await W(i,{output:o,durationSec:await se(e.input),extra:r});let s=Ku[n];return v({outputPath:o,platform:n,aspect:s.aspect,fps:s.fps})}catch(n){return E(n)}})}import{z as ke}from"zod";import{existsSync as sc,mkdirSync as vA,mkdtempSync as $A,readFileSync as Ml,rmSync as Cl,writeFileSync as jw}from"node:fs";import{tmpdir as kA,release as EA,version as _A}from"node:os";import{join as rn}from"node:path";var TA=wt(),AA={input:ke.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),sessionId:ke.string().min(1).optional().describe("Or a stopped session's id."),title:ke.string().max(200).optional().describe("Issue title."),actual:ke.string().max(4e3).optional().describe("What happened."),expected:ke.string().max(4e3).optional().describe("What should happen."),start:ke.number().nonnegative().optional().describe("Clip start s (default: end - clipSec)."),end:ke.number().positive().optional().describe("Clip end s (default: recording end)."),clipSec:ke.number().positive().max(Is).optional().describe(`Clip length without start (default ${Cu}).`),redact:ke.boolean().optional().describe("Box out OCR-found secrets in every output (default true; needs Windows OCR)."),secretPattern:ke.string().optional().describe("Secret regex (default: API keys, tokens, password: values)."),regions:ke.array(gn).optional().describe("Extra boxes (video px; start/end on the clip clock)."),errorPattern:ke.string().optional().describe("Error-line regex."),scanEverySec:ke.number().positive().optional().describe(`OCR every N s (default ${Pu}).`),maxFrames:ke.number().int().min(1).max(vs).optional().describe(`Scan frame cap (default ${En}).`),gif:ke.boolean().optional().describe("Also export a GIF (default true)."),maxBytes:ke.number().int().min(1e4).optional().describe(`GIF size budget (default ${Sr}).`),outputDir:ke.string().optional().describe("Package folder (default: a new one in SCREENCAST_HOME/edits)."),overwrite:ke.boolean().optional().describe("Replace a report already in outputDir.")},mi=t=>Math.round(t*1e3)/1e3;async function RA(){if(process.platform!=="win32")return null;try{return(await ar()).map(e=>`${e.width}x${e.height}${e.dpi?` @${Math.round(e.dpi/96*100)}%`:""}${e.primary?" (primary)":""}`).join(", ")}catch{return null}}function Uw(t){t.registerTool("bug_report",{title:"Bug Report Package",description:"Package a recording as a paste-ready repro folder: secret-scanned, redacted clip and GIF, contact sheet, steps from the event log, OCR'd errors, environment, report.md for gh issue create --body-file.",inputSchema:AA,outputSchema:N({outputDir:ke.string(),reportPath:ke.string(),jsonPath:ke.string(),clipPath:ke.string()}),annotations:I},async(e,r)=>{let n=null,o=[];try{if(e.input===void 0==(e.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");let{ffmpeg:i}=k(),s=await Ns(e),a=await L(s.path);if(!a.width||!a.height)throw new l(`Could not read the size of ${s.path}.`);let c=a.videoDurationSec??a.durationSec;if(c===null)throw new l(`Could not read the duration of ${s.path}.`);let u=If(c,e),d=mi(u.end-u.start),p=e.redact!==!1,f=e.secretPattern??Ge;Oe(["x"],f),e.errorPattern!==void 0&&Oe(["x"],e.errorPattern);let m="gif",h=ln(e.outputDir,we("edits"))??rn(we("edits"),`bug-report-${ge()}-${be()}`),b={markdown:rn(h,Wt.markdown),json:rn(h,Wt.json),clip:rn(h,Wt.clip),gif:rn(h,Wt.gif(m)),sheet:rn(h,Wt.contactSheet)},w=Object.values(b).filter($=>sc($));if(w.length>0&&!e.overwrite)throw new l(`The folder already holds a report: ${w.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);sc(h)||(vA(h,{recursive:!0}),n=h);let g=[],y=$A(rn(kA(),"screencast-bug-"));try{let $="unavailable",S=null,C=await wr();if(C.available)S=await Ss(s.path,{everySec:e.scanEverySec??Pu,maxFrames:e.maxFrames??En,range:{start:u.start,duration:d}},y,r.signal),$="read";else{if(p)throw new l(`The secret scan needs Windows OCR, which is unavailable here${C.error?` (${C.error})`:""}.`,"Pass redact: false to package without it (then check the clip yourself before sharing), or run doctor.");g.push("Windows OCR is unavailable, so no error text was read.")}let M=S&&p?Ff(kn(S,f,!0,"line").redactRegions):[],R=[...M,...e.regions??[]],P=S?Of(S.frames,e.errorPattern??Os,p?f:null):[];r.signal.throwIfAborted();let j=[{op:"trim",start:u.start,end:u.end},...R.length>0?[{op:"redact",regions:R,style:"box"}]:[]],X=nc(s.path,b.clip,j,{width:a.width,height:a.height,fps:a.fps??30,durationSec:a.durationSec,hasAudio:a.audioCodec!==null});await W(X.args,{output:b.clip,durationSec:X.durationSec,inputDurationSec:d,extra:r}),o.push(b.clip);let D=null;e.gif!==!1&&(D=await zn(b.clip,b.gif,{format:m,maxBytes:e.maxBytes??Sr},r),o.push(b.gif),D.note&&g.push(D.note)),await Cs(b.clip,Ms(d,Oo),b.sheet,{tileWidth:No},r.signal),o.push(b.sheet);let ae=(s.eventsPath?Mu(je(Ml(s.eventsPath,"utf8"))):[]).map(_=>p?{..._,text:Oe([_.text],f)[0]??_.text}:_),ee=s.eventsPath?ae.length===0?"The event log has no clicks, shortcuts, typing, or scrolls.":void 0:"The recording has no input event log (record with start_recording events: true).",J=Lt(s.path),ie=sc(J)?Df(Es(Ml(J,"utf8")),u,p?f:null):void 0,ce=xt(s.path),x=sc(ce)?Lf(An(Ml(ce,"utf8")),u,s.record?.perf?.summary?.process):[],q=ca(ua(i)??""),H=await RA(),de=s.record,G=_=>p?Oe([_],f)[0]??_:_,Q=[["OS",`${_A()} (${EA()}), ${process.arch}`],...H?[["Displays",H]]:[],...de?[["Recorded target",G(de.target)]]:[],...de?.matchedWindow?[["Window",G(de.matchedWindow)]]:[],...de?.backend?[["Capture backend",de.backend]]:[],["Recording",`${a.width}x${a.height}${a.fps?` @ ${Math.round(a.fps*100)/100} fps`:""}, ${mi(c)} s${a.videoCodec?`, ${a.videoCodec}`:""}`],["ffmpeg",q.version??"unknown"],["screencast-mcp",`${TA} (Node ${process.version})`]],te={title:e.title?.trim()||"Bug report",...e.expected?{expected:e.expected}:{},...e.actual?{actual:e.actual}:{},createdAt:new Date().toISOString(),clip:{start:u.start,end:u.end,recordingDurationSec:mi(c),width:a.width,height:a.height},files:{clip:Wt.clip,...D?{gif:Wt.gif(m)}:{},contactSheet:Wt.contactSheet},...D?{gif:{format:m,sizeBytes:D.sizeBytes,withinBudget:D.withinBudget}}:{},steps:ae.slice(0,Fs),...ae.length>Fs?{stepsOmitted:ae.length-Fs}:{},...ee?{stepsNote:ee}:{},errors:P,...ie?{logs:ie}:{},...x.length?{perf:x}:{},ocr:$,redaction:{scanned:S!==null&&p,...S&&p?{everySec:mi(S.step),framesScanned:S.frames.length}:{},found:M.length,manual:e.regions?.length??0},environment:Q};jw(b.markdown,Nf(te)),o.push(b.markdown),jw(b.json,JSON.stringify({...te,steps:ae,redaction:{...te.redaction,regions:R}},null,2)+`
|
|
376
|
+
`),o.push(b.json),S?.clamped&&g.push(`The scan interval was widened to ${mi(S.step)} s to fit maxFrames.`);let{images:T}=await Re([b.sheet],Ae,1);return v({outputDir:h,reportPath:b.markdown,jsonPath:b.json,clipPath:b.clip,...D?{gifPath:b.gif,gifSizeBytes:D.sizeBytes,gifWithinBudget:D.withinBudget}:{},contactSheetPath:b.sheet,clip:{start:u.start,end:u.end},steps:ae.length,errors:P.map(_=>_.text),ocr:$,redaction:te.redaction,...g.length>0?{warnings:g}:{},next:`Review the clip and report.md, then: gh issue create --title ${JSON.stringify(te.title)} --body-file ${JSON.stringify(b.markdown)} and drag the GIF into the issue.`,note:"Redaction is OCR-based and best-effort: look at the clip before posting it anywhere public."},T)}finally{Cl(y,{recursive:!0,force:!0})}}catch(i){if(n)Cl(n,{recursive:!0,force:!0});else for(let s of o)Cl(s,{force:!0});return E(i)}})}import{z as Tr}from"zod";import{existsSync as ac,mkdirSync as Dl,mkdtempSync as DA,readFileSync as ty,readdirSync as ry,rmSync as nn,rmdirSync as LA,statSync as BA,writeFileSync as ny}from"node:fs";import{tmpdir as WA}from"node:os";import{join as Je}from"node:path";var fi=100,MA=.1,CA=1280,zw=40,PA=24,to={markdown:"guide.md",html:"guide.html",images:"images",image:t=>`step-${String(t).padStart(2,"0")}.png`};function Il(t){return t.label?`${t.text} ${t.label}`:t.text}var IA=t=>Math.round(t*1e3)/1e3;function FA(t,e,r){let n=Math.max(0,e-1/(r>0?r:30));return IA(Math.min(Math.max(0,t-MA),n))}function Pl(t,e,r){let n=Math.max(t.x-e,0,e-(t.x+t.width)),o=Math.max(t.y-r,0,r-(t.y+t.height));return Math.hypot(n,o)}function Hw(t,e,r){let o=t.map(s=>({line:s,d:Pl(s,e,r)})).filter(s=>s.d<=PA&&s.line.text.trim().length>0).sort((s,a)=>s.d-a.d||s.line.width*s.line.height-a.line.width*a.line.height)[0]?.line;if(!o)return null;let i=o.text.replace(/\s+/g," ").trim();if(i.length>zw){let s=[...o.words].sort((a,c)=>Pl(a,e,r)-Pl(c,e,r))[0];i=s?s.text.trim():`${i.slice(0,zw-1).trimEnd()}\u2026`}return i.length>0?i:null}function OA(t){let e=t.action==="double_click"?"double-click":"click",r=t.button&&t.button!=="left"?`${t.button.charAt(0).toUpperCase()}${t.button.slice(1)}-${e}`:e;return r.charAt(0).toUpperCase()+r.slice(1)}function Fl(t,e){let r=e.secretPattern??Ge,n=i=>Oe([i],r)[0]??i,o=0;return t.map((i,s)=>{if(i.action==="gap")return{n:0,t:i.t,action:i.action,text:i.text};o++;let a={n:o,t:i.t,action:i.action,text:i.text,shotT:FA(i.t,e.durationSec,e.fps)},c=i.element?.name??e.labels?.[s];if(i.action==="click"||i.action==="double_click"){let u=OA(i);return i.inFrame===!1?{...a,text:i.element?.name?n(`${u} ${Au(i.element)}`):`${u} outside the recorded area`}:{...a,x:i.x,y:i.y,...c?{text:u,label:n(c)}:{text:`${u} the marked spot`}}}return i.action==="scroll"?{...a,...i.inFrame===!1?{}:{x:i.x,y:i.y},...c?{text:`${i.text} over`,label:n(c)}:{}}:i.action==="shortcut"?i.keys?{...a,text:"Press",label:i.keys}:a:i.action==="switch"?{...a,text:n(i.text)}:{...a,text:"Type text"}})}function Gw(t,e){let r=[...e].sort((n,o)=>n.t-o.t);return t.map(n=>{let o=r.filter(i=>i.t<=n.t+1e-6).at(-1);return o?{...n,section:o.label}:n})}function qw(t,e){let r=p=>String(Math.round(p)),n=[];for(let p of e.boxes??[])n.push(`drawbox=x=${r(p.x)}:y=${r(p.y)}:w=${r(p.width)}:h=${r(p.height)}:color=black:t=fill`);let o=`scale=w='min(iw,${CA})':h=-2:flags=lanczos`,i=`[0:v]${n.length?n.join(",")+",":""}format=rgba`;if(!e.click)return`${i},${o},format=rgb24[out]`;let s=_l(t.width,t.height),a=s/2,c=Math.max(3,Math.round(s/10)),u=a-c/2-1,d=e.color??tc;return`${i}[bg];color=c=${d}:s=${s}x${s}:d=1,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(abs(hypot(X-${a},Y-${a})-${u}),${c/2}),255,0)'[ring];[bg][ring]overlay=x=${r(e.click.x-a)}:y=${r(e.click.y-a)},${o},format=rgb24[out]`}function Xw(t,e,r){return["-y","-v","error","-ss",String(e),"-i",t,"-frames:v","1",r]}var ro=1e7,Yt=[{width:1280,q:4},{width:960,q:6},{width:800,q:8},{width:640,q:10},{width:480,q:14},{width:360,q:20}],Ol=t=>t.replace(/\.png$/i,".jpg");function Jw(t,e,r){return["-y","-v","error","-i",t,"-vf",`scale=w='min(iw,${e.width})':h=-2:flags=lanczos,format=yuvj420p`,"-frames:v","1","-q:v",String(e.q),r]}var Yw=t=>4*Math.ceil(t/3);function Kw(t,e,r=ro){let n=Yt[t].width;for(let o=t+1;o<Yt.length;o++)if(e*(Yt[o].width/n)**2<=r)return o;return t+1<Yt.length?Yt.length-1:null}function Vw(t,e,r){return["-y","-v","error","-i",t,"-filter_complex",e,"-map","[out]","-frames:v","1",r]}var eo=t=>t.replace(/\s*\n\s*/g," ").replace(/([\\`*_[\]<>#|])/g,"\\$1");function Qw(t){return`${t.ocr==="read"?`Screenshots scanned for secrets with OCR (best-effort); ${t.redactions} region${t.redactions===1?"":"s"} boxed out.`:"Screenshots were not scanned for secrets: review them before sharing."} Typed text is never logged, so it never appears here.`}function Zw(t){let e=t.steps.filter(r=>r.n>0).length;return`${e} step${e===1?"":"s"} from a ${Fe(t.recording.durationSec)} recording.`}function ey(t){let e=[`# ${eo(t.title)}`,"",Zw(t),""];t.steps.length===0&&e.push(`_${t.stepsNote??"No steps in the recording."}_`,"");let r;for(let n of t.steps){if(n.section!==void 0&&n.section!==r&&(r=n.section,e.push(`## ${eo(r)}`,"")),n.n===0){e.push(`> _${eo(n.text)}_`,"");continue}let o=n.label?`${eo(n.text)} **${eo(n.label)}**`:eo(n.text);e.push(`${n.n}. ${o} <sub>${Fe(n.t)}</sub>`,""),n.image&&e.push(` `,"")}return t.stepsOmitted&&e.push(`_${t.stepsOmitted} more steps not shown._`,""),e.push("<sub>",Qw(t),`Generated by screencast-mcp step_guide, ${t.createdAt}.`,"</sub>",""),e.join(`
|
|
377
|
+
`)}var et=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),NA=`:root{--bg:#f6f5f2;--card:#fff;--ink:#16161a;--dim:#6b6b74;--line:#e2e0da;--rec:#e5383b}
|
|
391
378
|
@media (prefers-color-scheme:dark){:root{--bg:#121214;--card:#1b1b1f;--ink:#ececf1;--dim:#9a9aa6;--line:#2c2c33}}
|
|
392
379
|
*{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
380
|
main{max-width:920px;margin:0 auto;padding:40px 16px 64px}
|
|
@@ -402,8 +389,8 @@ li{background:var(--card);border:1px solid var(--line);border-radius:10px;margin
|
|
|
402
389
|
.t{margin-left:auto;font:12px/1 ui-monospace,Consolas,monospace;color:var(--dim)}
|
|
403
390
|
li img{display:block;width:100%;height:auto;border-top:1px solid var(--line)}
|
|
404
391
|
.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
|
|
392
|
+
footer{color:var(--dim);font-size:13px;margin-top:40px;border-top:1px solid var(--line);padding-top:16px}`;function Nl(t,e){let r=[],n,o=!1,i=()=>{o&&r.push("</ol>"),o=!1};for(let s of t.steps){if(s.section!==void 0&&s.section!==n&&(i(),n=s.section,r.push(`<h2>${et(n)}</h2>`)),s.n===0){i(),r.push(`<p class="note">${et(s.text)}</p>`);continue}o||r.push("<ol>"),o=!0;let a=s.label?`${et(s.text)} <strong>${et(s.label)}</strong>`:et(s.text);r.push(`<li><div class="cap"><span class="n">${String(s.n).padStart(2,"0")}</span><span>${a}</span><span class="t">${Fe(s.t)}</span></div>`+(s.image?`<img src="${et(e(s.image))}" alt="Step ${s.n}: ${et(Il(s))}" loading="lazy">`:"")+"</li>")}return i(),t.steps.length===0&&r.push(`<p class="note">${et(t.stepsNote??"No steps in the recording.")}</p>`),t.stepsOmitted&&r.push(`<p class="note">${t.stepsOmitted} more steps not shown.</p>`),["<!doctype html>",'<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">',`<title>${et(t.title)}</title><style>${NA}</style></head><body><main>`,`<header><div class="rec">Step guide</div><h1>${et(t.title)}</h1><p class="meta">${et(Zw(t))}</p></header>`,...r,`<footer>${et(Qw(t))}<br>Generated by screencast-mcp step_guide, ${et(t.createdAt)}.</footer>`,"</main></body></html>",""].join(`
|
|
393
|
+
`)}var oy=10,iy=5,jA={input:Tr.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),sessionId:Tr.string().min(1).optional().describe("Or a stopped session's id."),title:Tr.string().max(200).optional().describe("Guide title."),format:Tr.enum(["md","html","both"]).optional().describe("md + images/, self-contained html, or both (default)."),ocr:Tr.boolean().optional().describe("OCR shots for captions and secret boxes (default true; needs Windows OCR)."),outputDir:Tr.string().optional().describe("Guide folder (default: new in SCREENCAST_HOME/edits)."),overwrite:Tr.boolean().optional().describe("Replace a guide already in outputDir.")};function sy(t){t.registerTool("step_guide",{title:"Step-by-Step Guide",description:"Turn a recording's event log into a numbered how-to: a ringed screenshot and caption per step, marker headings; Markdown and/or one HTML file. Never includes typed text.",inputSchema:jA,outputSchema:N({outputDir:Tr.string()}),annotations:I},async(e,r)=>{let n=null,o=[];try{if(e.input===void 0==(e.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");k();let i=await Ns(e);if(!i.eventsPath)throw new l("The recording has no input event log, so there are no steps to write.","Record with start_recording events: true, or pass a recording that has a .events.jsonl beside it.");let s=await L(i.path);if(!s.width||!s.height)throw new l(`Could not read the size of ${i.path}.`);let a=s.videoDurationSec??s.durationSec;if(a===null)throw new l(`Could not read the duration of ${i.path}.`);let c=s.fps??30,u=e.format??"both",d=u!=="html",p=u!=="md",f=e.ocr!==!1;if(f){let M=await wr();if(!M.available)throw new l(`Captions and the secret scan need Windows OCR, which is unavailable here${M.error?` (${M.error})`:""}.`,"Pass ocr: false for a guide without them (then check the screenshots yourself before sharing), or run doctor.")}let m=ln(e.outputDir,we("edits"))??Je(we("edits"),`step-guide-${ge()}-${be()}`),h={markdown:Je(m,to.markdown),html:Je(m,to.html),images:Je(m,to.images)},b=[h.markdown,h.html].filter(M=>ac(M));if(b.length>0&&!e.overwrite)throw new l(`The folder already holds a guide: ${b.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);let w=Ru(je(ty(i.eventsPath,"utf8"))),g=w.slice(0,fi),$=Fl(g,{durationSec:a,fps:c}).map((M,R)=>({i:R,s:M})).filter(({s:M})=>M.shotT!==void 0),S=[];ac(m)||(Dl(m,{recursive:!0}),n=m);let C=DA(Je(WA(),"screencast-guide-"));try{let M=vo(r),R=$.length*(f?3:2)||1,P=0,j=()=>M?.(++P/R),X=await He($,async({s:G})=>{let Q=Je(C,`frame-${String(G.n).padStart(3,"0")}.png`);return await Z(Xw(i.path,G.shotT,Q),6e4,{signal:r.signal}),j(),Q}),D=X.map(()=>null);if(f)for(let G=0;G<X.length;G+=oy)r.signal.throwIfAborted(),(await ct(X.slice(G,G+oy),C,r.signal,{sameSize:!0})).forEach((te,T)=>{D[G+T]=te,j()});let ae=g.map(()=>null),ee=$.map(({i:G,s:Q},te)=>{let T=D[te];return T?(Q.x!==void 0&&Q.y!==void 0&&(ae[G]=Hw(T.lines,Q.x,Q.y)),kn({frames:[{...T,t:0,path:""}],step:1,end:1},Ge,!0,"line").redactRegions):[]}),J=Gw(Fl(g,{durationSec:a,fps:c,labels:ae}),Le(i.path)),ie=d?h.images:Je(C,"images");if(d&&ac(ie)&&e.overwrite)for(let G of ry(ie))/^step-\d+\.png$/.test(G)&&nn(Je(ie,G),{force:!0});Dl(ie,{recursive:!0});let ce=0,x={width:s.width,height:s.height},q=await He($,async({i:G},Q)=>{let te=J[G],T=to.image(te.n),_=te.x!==void 0&&te.y!==void 0?{x:te.x,y:te.y}:void 0,A=qw(x,{click:_,boxes:ee[Q]}),z=Je(ie,T);return await Z(Vw(X[Q],A,z),6e4,{signal:r.signal}),j(),{step:te,file:T,out:z}});for(let[G,{step:Q,file:te,out:T}]of q.entries())d&&o.push(T),Q.image=te,ce+=ee[G].length;let H=w.length===0?"The event log has no clicks, shortcuts, typing, or scrolls.":void 0,de={title:e.title?.trim()||"Step-by-step guide",createdAt:new Date().toISOString(),recording:{durationSec:Math.round(a*1e3)/1e3,width:s.width,height:s.height},steps:J,...w.length>fi?{stepsOmitted:w.length-fi}:{},...H?{stepsNote:H}:{},ocr:f?"read":"off",redactions:ce};if(d&&(ny(h.markdown,ey(de)),o.push(h.markdown)),p){let G=Je(C,"html");Dl(G,{recursive:!0});let Q=J.flatMap(K=>K.image?[K.image]:[]),te=K=>`data:image/jpeg;base64,${ty(Je(G,Ol(K))).toString("base64")}`,T=async(K,ue)=>{let me=Je(G,Ol(K));return await Z(Jw(Je(ie,K),ue,me),6e4,{signal:r.signal}),Yw(BA(me).size)},_=Q.length>iy?Q.filter((K,ue)=>ue%Math.ceil(Q.length/iy)===0):[],A=0;for(;_.length>0&&A<Yt.length-1;A++){let K=0;for(let ue of _)K+=await T(ue,Yt[A]);if(K/_.length*Q.length<=ro*.9)break}let z="";for(let K=A;K!==null;){let ue=Yt[K],me=0;for(let uo of Q)me+=await T(uo,ue);z=me<=ro?Nl(de,te):"";let Ne=z?Buffer.byteLength(z):me;if(Ne<=ro)break;let Rt=Kw(K,Ne);Rt===null&&(z||=Nl(de,te),S.push(`guide.html is ${(Buffer.byteLength(z)/1e6).toFixed(1)} MB, over the ${ro/1e6} MB budget even with ${ue.width} px JPEGs; use format: md for a guide this long.`)),K=Rt}ny(h.html,z),o.push(h.html)}if(e.overwrite&&(p||nn(h.html,{force:!0}),!d&&(nn(h.markdown,{force:!0}),ac(h.images)))){for(let G of ry(h.images))/^step-\d+\.png$/.test(G)&&nn(Je(h.images,G),{force:!0});try{LA(h.images)}catch{}}return de.stepsOmitted&&S.push(`Only the first ${fi} steps were written; ${de.stepsOmitted} more were left out.`),H&&S.push(H),v({outputDir:m,...d?{markdownPath:h.markdown,imagesDir:h.images}:{},...p?{htmlPath:h.html}:{},steps:J.map(G=>({...G.n>0?{n:G.n}:{},t:G.t,action:G.action,caption:Il(G),...G.section?{section:G.section}:{},...G.image?{image:G.image}:{}})),ocr:de.ocr,redactions:ce,...S.length>0?{warnings:S}:{},note:f?"Captions are OCR-based templates: rewrite them in guide.md as needed. The secret scan is best-effort: look at the screenshots before sharing.":"Not scanned for secrets: look at the screenshots before sharing."})}finally{nn(C,{recursive:!0,force:!0})}}catch(i){if(n)nn(n,{recursive:!0,force:!0});else for(let s of o)nn(s,{force:!0});return E(i)}})}import{existsSync as ay,rmSync as UA}from"node:fs";import{ResourceTemplate as cy}from"@modelcontextprotocol/sdk/server/mcp.js";import{SubscribeRequestSchema as zA,UnsubscribeRequestSchema as HA}from"@modelcontextprotocol/sdk/types.js";var uy=(t,e)=>({contents:[{uri:t,mimeType:"application/json",text:JSON.stringify(e,null,2)}]});function ly(t){let e=re().get(t);if(!e)throw new l(`No session with id ${t}.`);return e}function dy(t){t.registerResource("sessions","screencast://sessions",{title:"Recording sessions",description:"Every recording session (active and finished), newest first.",mimeType:"application/json"},r=>uy(r.href,re().list())),t.registerResource("session",new cy("screencast://sessions/{id}",{list:()=>({resources:re().list().map(r=>({uri:`screencast://sessions/${r.id}`,name:r.id,title:`${r.status}: ${r.target}`,description:`${r.target} -> ${r.outputPath}`,mimeType:"application/json"}))})}),{title:"Recording session",description:"One session's record.",mimeType:"application/json"},(r,{id:n})=>{let o=ly(String(n));return uy(r.href,{...o,fileExists:ay(o.outputPath)})}),t.registerResource("session-poster",new cy("screencast://sessions/{id}/poster",{list:void 0}),{title:"Recording preview",description:"A JPEG frame from the middle of a session's recording.",mimeType:"image/jpeg"},async(r,{id:n})=>{let o=ly(String(n));if(!ay(o.outputPath))throw new l(`Recording file not found: ${o.outputPath}`);let{durationSec:i}=await L(o.outputPath),s=Ue(".png");try{await Z(["-y","-v","error","-ss",String((i??0)/2),"-i",o.outputPath,"-frames:v","1",s],3e4);let[a]=(await Re([s],960,1)).images;if(!a)throw new l(`Could not extract a thumbnail frame from ${o.outputPath}`);return{contents:[{uri:r.href,mimeType:a.mimeType,blob:a.data}]}}finally{UA(s,{force:!0})}});let e=new Map;t.server.registerCapabilities({resources:{subscribe:!0}}),t.server.setRequestHandler(zA,r=>(e.set(r.params.uri,py(r.params.uri)),{})),t.server.setRequestHandler(HA,r=>(e.delete(r.params.uri),{})),re().onChange(()=>{if(!(ys()||!t.isConnected())){try{t.sendResourceListChanged()}catch{}for(let[r,n]of e){let o=py(r);o!==n&&(e.set(r,o),t.server.sendResourceUpdated({uri:r}).catch(()=>{}))}}})}function py(t){if(t==="screencast://sessions")return JSON.stringify(re().list());let e=/^screencast:\/\/sessions\/([^/]+)$/.exec(t),r=e?re().get(decodeURIComponent(e[1])):void 0;return r?JSON.stringify(r):null}import{z as it}from"zod";var no=t=>({messages:[{role:"user",content:{type:"text",text:t}}]}),oo={bugReproClip:(t,e)=>`Record a short bug-reproduction clip of ${t}.${e?` The bug: ${e}.`:""}
|
|
407
394
|
|
|
408
395
|
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
396
|
2. sample_frames { input: <recording>, mode: "scenes" } to see what happened, and describe the moment the bug appears.
|
|
@@ -440,54 +427,54 @@ Give a timestamped summary of the main steps and anything that looks wrong.`,doc
|
|
|
440
427
|
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
428
|
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
429
|
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
|
|
430
|
+
Report the guide paths, the steps, and anything you would check before sharing it.`};function my(t){t.registerPrompt("bug-repro-clip",{title:"Record a bug reproduction",description:"Record a target, find the bug moment, redact secrets, trim, annotate, and export a GIF for an issue.",argsSchema:{target:it.string().optional().describe("What to record, e.g. window:My App (default: full)."),notes:it.string().optional().describe("What the bug is.")}},({target:e,notes:r})=>no(oo.bugReproClip(e||"full",r??""))),t.registerPrompt("file-bug-report",{title:"File a bug report",description:"Record a repro with input events, then package it with bug_report: redacted clip, GIF, steps, error text, and report.md.",argsSchema:{target:it.string().optional().describe("What to record, e.g. window:My App (default: full)."),notes:it.string().optional().describe("What the bug is."),expected:it.string().optional().describe("What should happen instead.")}},({target:e,notes:r,expected:n})=>no(oo.fileBugReport(e||"full",r??"",n??""))),t.registerPrompt("demo-gif",{title:"Make a demo GIF",description:"Record a feature walkthrough and export a GIF small enough for a README or PR.",argsSchema:{target:it.string().optional().describe("What to record (default: full)."),maxMB:it.string().optional().describe("Size budget in MB (default 10).")}},({target:e,maxMB:r})=>no(oo.demoGif(e||"full",r||"10"))),t.registerPrompt("verify-ui-change",{title:"Verify a UI change",description:"Screenshot before, make the change, wait for the screen to settle, diff, and check the text.",argsSchema:{target:it.string().optional().describe("What to watch (default: full)."),expectation:it.string().optional().describe("What should change.")}},({target:e,expectation:r})=>no(oo.verifyUiChange(e||"full",r??""))),t.registerPrompt("review-recording",{title:"Review a recording",description:"Summarize what happens in a recording, with timestamps, using a contact sheet and scene frames.",argsSchema:{path:it.string().describe("Path to the recording.")}},({path:e})=>no(oo.reviewRecording(e))),t.registerPrompt("document-steps",{title:"Document what I just did",description:"Record a task with input events and markers, then turn it into a step-by-step guide with step_guide.",argsSchema:{target:it.string().optional().describe("What to record (default: full)."),task:it.string().optional().describe("The task the guide teaches.")}},({target:e,task:r})=>no(oo.documentSteps(e||"full",r??"")))}import{fileURLToPath as GA}from"node:url";import{RootsListChangedNotificationSchema as qA}from"@modelcontextprotocol/sdk/types.js";function XA(t){let e=[];for(let{uri:r}of t)if(r.startsWith("file:"))try{e.push(GA(r))}catch{}return e}function fy(t){let e=t.server,r=async o=>{if(!e.getClientCapabilities()?.roots){go(null);return}o&&go("pending");try{let{roots:i}=await e.listRoots();go(XA(i))}catch(i){o&&go([]),process.stderr.write(`roots/list failed: ${U(i)}
|
|
431
|
+
`)}},n=e.oninitialized;e.oninitialized=()=>{n?.(),r(!0)},e.setNotificationHandler(qA,()=>r(!1))}var YA=wt();function cc(t={}){let e=gi(t.toolsets??process.env.SCREENCAST_TOOLSETS);e.unknown.length>0&&console.error(`screencast-mcp: ignoring unknown SCREENCAST_TOOLSETS entries: ${e.unknown.join(", ")} (known: all, ${hi.join(", ")})`);let r=new JA({name:"screencast-mcp",version:YA},{capabilities:{logging:{}},instructions:Xl(e)});jp(r);let n=KA(r);return vf(r),kf(r),mh(r),gh(r),wh(r),fh(r),Sh(r),vh(r),kh(r),Eh(r),Xh(r),Jh(r),Kh(r),Vh(r),og(r),cg(r),pg(r),wg(r),Sg(r),vg(r),$g(r),Pg(r),Ig(r),Lg(r),Bg(r),Wg(r),Ug(r),zg(r),Yg(r),rb(r),nb(r),cb(r),fb(r),xb(r),_b(r),Tb(r),Ab(r),Ib(r),Fb(r),Ob(r),Nb(r),Oh(r),Db(r),Lb(r),qb(r),Xb(r),Jb(r),xh(r),Qb(r),fw(r),hw(r),gw(r),bw(r),ww(r),xw(r),Sw(r),Tw(r),Bw(r),Ww(r),Uw(r),sy(r),VA(n,e),dy(r),my(r),fy(r),r}function KA(t){let e=new Map,r=t.registerTool.bind(t);return t.registerTool=((...n)=>{let o=n.length-1,i=n[o];n[o]=(a,c)=>{try{oc(a)}catch(u){return E(u)}return i(a,c)};let s=r(...n);return e.set(n[0],s),s}),e}function VA(t,e){for(let[r,n]of t){let o=ql(r);if(!o)throw new Error(`Tool "${r}" belongs to no toolset; add it to TOOLSETS in src/utils/toolsets.ts.`);e.enabled.includes(o)||n.remove()}}import{spawn as gy}from"node:child_process";import{copyFileSync as QA,existsSync as ZA,mkdirSync as eR,readFileSync as tR,writeFileSync as rR}from"node:fs";import{homedir as nR}from"node:os";import{dirname as oR,join as on}from"node:path";import{createInterface as iR}from"node:readline/promises";var uc=["claude-desktop","claude-code","cursor","vscode"],by=`setup options:
|
|
432
|
+
--yes, -y answer yes: install FFmpeg and write client configs without asking
|
|
446
433
|
--dry-run print the checks and the config changes; change nothing
|
|
447
|
-
--clients <list> detected (default) | none | a comma list of
|
|
448
|
-
${
|
|
434
|
+
--clients <list> (or --clients=<list>) detected (default) | none | a comma list of
|
|
435
|
+
${uc.join(", ")}
|
|
449
436
|
--no-install never offer to install FFmpeg
|
|
450
437
|
--force replace an existing, different "screencast" server entry
|
|
451
438
|
--test record a 3 s test clip and export a GIF
|
|
452
439
|
|
|
453
440
|
setup exits 0 when the doctor checks pass, 1 when something still needs fixing.
|
|
454
|
-
`,
|
|
455
|
-
`}}function
|
|
441
|
+
`,Bl="@tmhs/screencast-mcp",io="screencast",Ll={command:"npx",args:["-y",Bl]},hy=["install","--id","Gyan.FFmpeg","-e","--accept-source-agreements","--accept-package-agreements"];function wy(t){let e={yes:!1,dryRun:!1,install:!0,clients:"detected",force:!1,test:!1};for(let r=0;r<t.length;r++){let n=t[r]??"",o=n.startsWith("--")?n.indexOf("="):-1;switch(o===-1?n:n.slice(0,o)){case"--yes":case"-y":e.yes=!0;break;case"--dry-run":e.dryRun=!0;break;case"--no-install":e.install=!1;break;case"--force":e.force=!0;break;case"--test":e.test=!0;break;case"--clients":{let s;if(o!==-1?s=n.slice(o+1):s=t[++r],s===void 0||s==="")throw new Error("--clients needs a value.");if(s==="detected"||s==="none"){e.clients=s;break}let a=s.split(",").map(u=>u.trim()).filter(Boolean),c=a.filter(u=>!uc.includes(u));if(c.length>0)throw new Error(`--clients: unknown client ${c.map(u=>`"${u}"`).join(", ")}; use ${uc.join(", ")}, detected, or none.`);e.clients=a;break}default:throw new Error(`Unknown setup option "${n}". Run screencast-mcp --help.`)}}return e}function sR(t){return t.env.APPDATA??on(t.home,"AppData","Roaming")}function yy(t){let e=sR(t);return[{id:"claude-desktop",name:"Claude Desktop",path:on(e,"Claude","claude_desktop_config.json"),key:"mcpServers",entry:Ll,marker:on(e,"Claude")},{id:"cursor",name:"Cursor",path:on(t.home,".cursor","mcp.json"),key:"mcpServers",entry:Ll,marker:on(t.home,".cursor")},{id:"vscode",name:"VS Code",path:on(e,"Code","User","mcp.json"),key:"servers",entry:{type:"stdio",...Ll},marker:on(e,"Code","User")}]}function aR(t){return["mcp","add","--scope","user",io,"--",...t==="win32"?["cmd","/c","npx","-y",Bl]:["npx","-y",Bl]]}var cR=(t,e)=>JSON.stringify(t)===JSON.stringify(e);function uR(t,e,r,n,o=!1){let i={};if(t!==null&&t.trim()!==""){let u;try{u=JSON.parse(t.charCodeAt(0)===65279?t.slice(1):t)}catch(d){return{status:"invalid",reason:`not plain JSON (${U(d)})`}}if(typeof u!="object"||u===null||Array.isArray(u))return{status:"invalid",reason:"the file is not a JSON object"};i=u}let s=i[e]??{};if(typeof s!="object"||s===null||Array.isArray(s))return{status:"invalid",reason:`"${e}" is not an object`};let a=s[r];if(a!==void 0){if(cR(a,n))return{status:"unchanged"};if(!o)return{status:"conflict",existing:a}}let c={...i,[e]:{...s,[r]:n}};return{status:"added",text:JSON.stringify(c,null,2)+`
|
|
442
|
+
`}}function lR(t,e){let r=t===""?[]:t.replace(/\n$/,"").split(`
|
|
456
443
|
`),n=e===""?[]:e.replace(/\n$/,"").split(`
|
|
457
444
|
`),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
445
|
`)+`
|
|
459
|
-
`}function
|
|
460
|
-
`),!1}let s=
|
|
446
|
+
`}function pR(t,e){let r=o=>String(o).padStart(2,"0"),n=`${e.getFullYear()}${r(e.getMonth()+1)}${r(e.getDate())}-${r(e.getHours())}${r(e.getMinutes())}${r(e.getSeconds())}`;return`${t}.bak-${n}`}function dR(t,e,r){let n=[],o=Number((t.server?.node??process.version).replace(/^v/,"").split(".")[0]);n.push({state:o>=22?"ok":"fail",text:`Node.js ${t.server?.node??process.version}${o>=22?"":" (needs 22+)"}`});let i=t.ffmpeg??{};i.found?i.meetsFfmpeg8===!1?n.push({state:"warn",text:`FFmpeg ${i.version??"?"}: works, but transcribe and backend "wgc" need FFmpeg 8+`}):n.push({state:"ok",text:`FFmpeg ${i.version??"?"}${i.path?` (${i.path})`:""}`}):n.push({state:"fail",text:"FFmpeg not found on PATH (or FFMPEG_PATH)"}),n.push(t.ffprobe?.found?{state:"ok",text:`ffprobe ${t.ffprobe.version??""}`.trim()}:{state:"fail",text:"ffprobe not found"}),r==="win32"?(n.push({state:t.devices?.gdigrab?"ok":"fail",text:t.devices?.gdigrab?"Screen capture (gdigrab)":"No gdigrab: this ffmpeg cannot capture the screen"}),n.push({state:t.wgc?.available?"ok":"info",text:t.wgc?.available?"Windows Graphics Capture (backend wgc)":'Windows Graphics Capture unavailable (backend "wgc" needs FFmpeg 8)'}),n.push(t.ocr?.available?{state:"ok",text:`Windows OCR${t.ocr.language?` (${t.ocr.language})`:""}`}:{state:"warn",text:"Windows OCR unavailable: find_text cannot read the screen (add an OCR language in Settings > Time & language > Language)"}),t.tts&&n.push(t.tts.available?{state:"ok",text:"Windows speech (narrate)"}:{state:"warn",text:"No Windows voice: narrate cannot speak"})):n.push({state:"warn",text:"Not Windows: capture and OCR are unavailable; the edit and watch tools work"});let s=t.env?.SCREENCAST_WHISPER_MODEL??e.SCREENCAST_WHISPER_MODEL;return n.push(s?{state:"ok",text:`Whisper model: ${s}`}:{state:"info",text:"transcribe needs a Whisper model: download a ggml model and set SCREENCAST_WHISPER_MODEL to its path"}),n}var mR={ok:"[ok] ",warn:"[warn]",fail:"[fail]",info:"[info]"};async function fR(t,e,r){let{fs:n}=r,o=n.exists(t.path),i=null;if(o)try{i=n.readFile(t.path)}catch(a){return r.out(` ${t.name}: could not read ${t.path}: ${U(a)}
|
|
447
|
+
`),!1}let s=uR(i,t.key,io,t.entry,e.force);switch(s.status){case"unchanged":return r.out(` ${t.name}: already configured (${t.path})
|
|
461
448
|
`),!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 "${
|
|
449
|
+
`),!1;case"conflict":return r.out(` ${t.name}: ${t.path} already has a different "${io}" entry; kept it (pass --force to replace).
|
|
463
450
|
`),!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=
|
|
451
|
+
`),r.out(lR(i??"",s.text).replace(/^/gm," ")),!0;if(!e.yes&&!await r.confirm(`Add the screencast server to ${t.name} (${t.path})?`))return r.out(` ${t.name}: skipped (run with --yes to write it, or --dry-run to see the change).
|
|
452
|
+
`),!1;try{let a=null;return o?(a=pR(t.path,r.now()),n.copyFile(t.path,a)):n.mkdir(oR(t.path)),n.writeFile(t.path,s.text),r.out(` ${t.name}: ${o?"updated":"created"} ${t.path}${a?` (backup: ${a})`:""}. Restart it to load the server.
|
|
466
453
|
`),!0}catch(a){return r.out(` ${t.name}: could not write ${t.path}: ${U(a)}
|
|
467
|
-
`),!1}}async function
|
|
454
|
+
`),!1}}async function hR(t,e){let r=aR(e.platform);if((await e.exec("claude",["mcp","get",io])).code===0)return e.out(` Claude Code: already has a "${io}" server (claude mcp get ${io}).
|
|
468
455
|
`),!0;if(t.dryRun)return e.out(` Claude Code: would run: claude ${r.join(" ")}
|
|
469
456
|
`),!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
457
|
`),!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
458
|
`),!1):(e.out(` Claude Code: added (user scope). Check it with claude mcp list.
|
|
472
|
-
`),!0)}async function
|
|
459
|
+
`),!0)}async function gR(t){let e=[];for(let n of yy(t))t.fs.exists(n.marker)&&e.push(n.id);return(await t.exec("claude",["--version"]).catch(()=>({code:1,stdout:"",stderr:""}))).code===0&&e.push("claude-code"),uc.filter(n=>e.includes(n))}async function xy(t,e){let r=e.out;r(`screencast-mcp setup${t.dryRun?" (dry run: nothing is installed or written)":""}
|
|
473
460
|
|
|
474
461
|
`);let n;try{n=await e.doctor()}catch(c){return e.err(`screencast-mcp: the doctor checks failed to run: ${U(c)}
|
|
475
|
-
`),1}for(let c of
|
|
462
|
+
`),1}for(let c of dR(n,e.env,e.platform))r(`${mR[c.state]} ${c.text}
|
|
476
463
|
`);let o=n.problems??[];if(o.length>0){r(`
|
|
477
464
|
What doctor says to fix:
|
|
478
465
|
`);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 ${
|
|
466
|
+
`)}let i=n.ffmpeg??{};if((!i.found||i.meetsFfmpeg8===!1)&&t.install&&e.platform==="win32"){let c=`winget ${hy.join(" ")}`;if(r(`
|
|
480
467
|
FFmpeg 8 ${i.found?"is not installed (found an older one)":"is missing"}.
|
|
481
468
|
`),t.dryRun)r(` would run: ${c}
|
|
482
469
|
`);else if(t.yes||await e.confirm("Install FFmpeg 8 with winget now?")){r(` running: ${c}
|
|
483
|
-
`);let u=await e.exec("winget",
|
|
470
|
+
`);let u=await e.exec("winget",hy).catch(d=>({code:1,stdout:"",stderr:U(d)}));u.code===0?r(` FFmpeg installed. Open a new terminal so PATH picks it up, then run setup again.
|
|
484
471
|
`):r(` winget failed (${(u.stderr||u.stdout).trim().split(`
|
|
485
472
|
`).pop()||`exit ${u.code}`}). Install it yourself: ${c}
|
|
486
473
|
`)}else r(` skipped. Install it yourself: ${c}
|
|
487
|
-
`)}if(t.clients!=="none"){let c=t.clients==="detected"?await
|
|
474
|
+
`)}if(t.clients!=="none"){let c=t.clients==="detected"?await gR(e):t.clients;r(`
|
|
488
475
|
MCP clients:
|
|
489
476
|
`),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(
|
|
477
|
+
`);let u=new Map(yy(e).map(d=>[d.id,d]));for(let d of c){let p=u.get(d);p?await fR(p,t,e):await hR(t,e)}}if(t.test)if(r(`
|
|
491
478
|
Test clip:
|
|
492
479
|
`),t.dryRun)r(` would record 3 s of the screen and export a GIF.
|
|
493
480
|
`);else try{let c=await e.testClip();r(` recorded 3 s and exported ${c}
|
|
@@ -496,7 +483,7 @@ Test clip:
|
|
|
496
483
|
All checks passed.
|
|
497
484
|
`:`
|
|
498
485
|
Some checks need attention (above). Run setup again after fixing them.
|
|
499
|
-
`),a?0:1}function
|
|
486
|
+
`),a?0:1}function bR(t){return(e,r)=>new Promise(n=>{let o=gy(e,r,{shell:t==="win32",windowsHide:!0}),i="",s="";o.stdout?.on("data",a=>i+=a.toString()),o.stderr?.on("data",a=>s+=a.toString()),o.on("error",a=>n({code:127,stdout:i,stderr:a.message})),o.on("close",a=>n({code:a??1,stdout:i,stderr:s}))})}var wR={exists:t=>ZA(t),readFile:t=>tR(t,"utf8"),writeFile:(t,e)=>rR(t,e),mkdir:t=>{eR(t,{recursive:!0})},copyFile:(t,e)=>QA(t,e)};function Sy(t){let e=process.platform,r=bR(e),n=async i=>{let s=await t.connect();try{return await i(s)}finally{await s.close()}},o=async(i,s,a)=>{let c=await i.call(s,a);if(c.isError)throw new Error(`${s}: ${c.text}`);return c.structured??{}};return{out:t.io.out,err:t.io.err,env:process.env,platform:e,home:nR(),fs:wR,exec:r,doctor:()=>n(async i=>await o(i,"doctor",{})),confirm:async i=>{if(!process.stdin.isTTY||!process.stdout.isTTY)return!1;let s=iR({input:process.stdin,output:process.stdout});try{return/^y(es)?$/i.test((await s.question(`${i} [y/N] `)).trim())}finally{s.close()}},testClip:()=>n(async i=>{let s=await o(i,"start_recording",{target:"full",fps:15,maxDurationSec:30});await new Promise(u=>setTimeout(u,3e3));let a=await o(i,"stop_recording",{sessionId:String(s.sessionId)}),c=await o(i,"export_gif",{input:String(a.outputPath)});return String(c.outputPath)}),open:async i=>{e!=="win32"||!process.stdout.isTTY||gy("explorer.exe",[i],{detached:!0,stdio:"ignore"}).unref()},now:()=>new Date}}var Ey=wt(),Ie=class extends Error{},_R=new Set(["record","call","setup","help","--help","-h","--version","-v"]);function _y(t){return t.length>0&&_R.has(t[0]??"")}var TR=`screencast-mcp: an MCP server for Windows screen recording.
|
|
500
487
|
|
|
501
488
|
Usage:
|
|
502
489
|
screencast-mcp run the MCP server over stdio (default)
|
|
@@ -521,37 +508,37 @@ record options:
|
|
|
521
508
|
--redact-secrets OCR the recording and blur on-screen secrets (API keys, tokens,
|
|
522
509
|
password: values) in the GIF and contact sheet (Windows OCR)
|
|
523
510
|
--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-${
|
|
511
|
+
--max-duration <sec> stop recording after <sec> seconds, an integer 0-${Ct}
|
|
525
512
|
(0 = no cap; default SCREENCAST_MAX_RECORDING_SEC, else 3600)
|
|
526
513
|
--command-env <NAME> run the command line in environment variable NAME instead of
|
|
527
514
|
the arguments after --, so quotes and & survive any shell
|
|
528
515
|
|
|
529
516
|
record exits with the command's exit code and writes <out>/evidence.json.
|
|
530
517
|
|
|
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: ${U(p)}`)}let c=r.now();if(o.exitCode=await r.run(t.command),o.commandSec=Math.round(r.now()-c)/1e3,a)try{let p=await
|
|
518
|
+
${by}`;function AR(t,e,r){let n=t[e+1];if(n===void 0||n==="--")throw new Ie(`${r} needs a value.`);return n}function Wl(t,e,r,n=1/0,o=!1){let i=Number(t);if(t.trim()===""||!Number.isFinite(i)||i<r||i>n||o&&!Number.isInteger(i)){let s=n===1/0?`>= ${r}`:`${r}-${n}`;throw new Ie(`${e} must be ${o?"an integer":"a number"} ${s}, got "${t}".`)}return i}function RR(t,e){let r=t.indexOf("--"),n={target:"full",fps:15,outDir:"screencast-evidence",artifacts:"failure",lastSec:30,gif:!0,contactSheet:!0,discardOnSuccess:!1,ocrErrors:!1,redactSecrets:!1,command:r===-1?[]:t.slice(r+1)},o,i=r===-1?t:t.slice(0,r);for(let s=0;s<i.length;s++){let a=i[s]??"",c=a.startsWith("--")?a.indexOf("="):-1,u=c===-1?a:a.slice(0,c),d=c===-1?void 0:a.slice(c+1),p=()=>{if(d!==void 0)return d;let f=AR(i,s,u);return s++,f};switch(u){case"--target":n.target=p();break;case"--fps":n.fps=Wl(p(),u,1,120,!0);break;case"--out":n.outDir=p();break;case"--artifacts":{let f=p();if(f!=="failure"&&f!=="always"&&f!=="never")throw new Ie(`--artifacts must be failure, always, or never, got "${f}".`);n.artifacts=f;break}case"--last":n.lastSec=Wl(p(),u,0);break;case"--max-duration":n.maxDurationSec=Wl(p(),u,0,Ct,!0);break;case"--command-env":o=p();break;case"--no-gif":n.gif=!1;break;case"--no-contact-sheet":n.contactSheet=!1;break;case"--discard-on-success":n.discardOnSuccess=!0;break;case"--redact-secrets":n.redactSecrets=!0;break;case"--secret-pattern":n.secretPattern=p();break;case"--ocr-errors":n.ocrErrors=!0;break;default:throw new Ie(`Unknown record option "${a}". Run screencast-mcp --help.`)}}if(o!==void 0){if(n.command.length>0)throw new Ie("Give the command either after -- or with --command-env, not both.");let s=e[o];if(s===void 0||s.trim()==="")throw new Ie(`--command-env ${o}: the environment variable is unset or empty.`);n.command=[s]}else if(n.command.length===0)throw new Ie("record needs a command after -- (or --command-env NAME), e.g. screencast-mcp record -- npm test");return n}function MR(t,e=process.env){let[r,...n]=t;switch(r){case"help":case"--help":case"-h":return{kind:"help"};case"--version":case"-v":return{kind:"version"};case"record":return n[0]==="--help"||n[0]==="-h"?{kind:"help"}:{kind:"record",options:RR(n,e)};case"call":{let[o,i,s]=n;if(!o||o.startsWith("-"))throw new Ie("call needs a tool name, e.g. screencast-mcp call doctor");if(s!==void 0)throw new Ie("call takes one JSON argument; quote it as a single string.");return{kind:"call",tool:o,args:i}}case"setup":{if(n[0]==="--help"||n[0]==="-h")return{kind:"help"};try{return{kind:"setup",options:wy(n)}}catch(o){throw new Ie(U(o))}}default:throw new Ie(`Unknown command "${r??""}". Run screencast-mcp --help.`)}}var vy=/([()\][%!^"`<>&|;, *?])/g,CR=/(\.(cmd|bat)$)|^(npm|npx|pnpm|yarn|corepack)$/i;function $y(t){return`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}var Ul=/[\s"&|<>^()!;'`$*?%,[\]]/;function PR(t,e=process.platform){if(t.length===1)return t[0]??"";if(e!=="win32")return t.map(n=>/^[\w@%+=:,./-]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`).join(" ");let r=CR.test(t[0]??"");return t.map((n,o)=>{if(o===0)return n!==""&&Ul.test(n)?$y(n):n;if(!Ul.test(n)&&n!=="")return n;let i=$y(n).replace(vy,"^$1");return r&&(i=i.replace(vy,"^$1")),i}).join(" ")}function IR(t){return t.length===1?t[0]??"":t.map(e=>Ul.test(e)||e===""?`"${e.replace(/"/g,'\\"')}"`:e).join(" ")}function Ty(t,e){return!e||t===null||t<=e?{}:{start:Math.round((t-e)*1e3)/1e3,duration:e}}function FR(t){let e=[...t].sort((o,i)=>(Number(i.t)||0)-(Number(o.t)||0)),r=new Set,n=[];for(let o of e){let i=String(o.line??o.text??"").trim(),s=i.toLowerCase().replace(/\s+/g," ");if(!(!i||r.has(s))&&(r.add(s),n.push(i),n.length>=Iu))break}return Oe(n,Ge)}function OR(t,e=r=>SR(r,"utf8")){if(t===void 0||t.trim()==="")return{};let r=t.startsWith("@")?e(t.slice(1)):t,n;try{n=JSON.parse(r)}catch(o){throw new Ie(`Tool arguments are not valid JSON: ${U(o)}`)}if(typeof n!="object"||n===null||Array.isArray(n))throw new Ie("Tool arguments must be a JSON object.");return n}async function zl(){let[t,e]=ER.createLinkedPair();await cc({toolsets:"all"}).connect(e);let r=new kR({name:"screencast-mcp-cli",version:Ey});return await r.connect(t),{async call(n,o){let i=await r.callTool({name:n,arguments:o}),s=i.content.map(a=>a.type==="text"?a.text??"":`[${a.type} omitted]`).join(`
|
|
519
|
+
`);return{isError:i.isError===!0,text:s,structured:i.structuredContent}},close:()=>r.close()}}async function Ar(t,e,r){let n=await t.call(e,r);if(n.isError)throw new Error(`${e}: ${n.text}`);return n.structured??{}}var Ay={out:t=>process.stdout.write(t),err:t=>process.stderr.write(t)};function NR(t){return new Promise(e=>{let r=yR(PR(t),{shell:!0,stdio:"inherit"}),n=a=>()=>r.kill(a),o=n("SIGINT"),i=n("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",i);let s=a=>{process.off("SIGINT",o),process.off("SIGTERM",i),e(a)};r.on("error",a=>{process.stderr.write(`screencast-mcp: could not run the command: ${a.message}
|
|
520
|
+
`),s(127)}),r.on("exit",(a,c)=>s(a??(c?1:0)))})}function DR(t,e,r){if(t===null)return null;let n=r===null?"":` at ${r} s`,o="so the GIF and contact sheet show the end of the recording, not the end of the run.";return e==="max_duration"?`the recording hit its max-duration cap${n} before the command finished, ${o} Raise --max-duration (0 = no cap).`:t==="failed"||e==="crashed"?`the recording failed${n} before the command finished (endReason ${e??"unknown"}), ${o}`:e==="window_closed"?`the recorded window closed${n} before the command finished, ${o}`:e!==null&&e!=="stopped"?`the recording ended early${n} (endReason ${e}), ${o}`:null}var LR={connect:zl,run:NR,now:()=>Date.now()};async function BR(t,e=Ay,r=LR){let n=$R(t.outDir);xR(n,{recursive:!0});let o={command:IR(t.command),exitCode:0,target:t.target,recording:null,durationSec:null,commandSec:0,status:null,endReason:null,gif:null,contactSheet:null,errors:null,warnings:[]},i=a=>{o.warnings.push(a),e.err(`screencast-mcp: ${a}
|
|
521
|
+
`)},s=await r.connect();try{let a=null;try{let p=await Ar(s,"start_recording",{target:t.target,fps:t.fps,output:so(n,"recording.mp4"),overwrite:!0,...t.maxDurationSec!==void 0?{maxDurationSec:t.maxDurationSec}:{}});a=String(p.sessionId),e.err(`screencast-mcp: recording ${t.target} to ${String(p.outputPath)}
|
|
522
|
+
`)}catch(p){i(`recording did not start, running the command without it: ${U(p)}`)}let c=r.now();if(o.exitCode=await r.run(t.command),o.commandSec=Math.round(r.now()-c)/1e3,a)try{let p=await Ar(s,"stop_recording",{sessionId:a});o.recording=String(p.outputPath),o.durationSec=typeof p.durationSec=="number"?p.durationSec:null,o.status=typeof p.status=="string"?p.status:null,o.endReason=typeof p.endReason=="string"?p.endReason:o.status==="stopped"?"stopped":null;let f=DR(o.status,o.endReason,o.durationSec);f&&i(f)}catch(p){i(`stop_recording failed: ${U(p)}`)}let u=o.exitCode!==0,d=t.artifacts==="always"||t.artifacts==="failure"&&u;if(o.recording&&d){let p=o.recording,f=null;if(t.redactSecrets)try{let m=await WR(s,o.recording,o.durationSec,t.secretPattern,n,i);o.redactions=m?.regions??0,f=m?.path??null,f&&(p=f)}catch(m){i(`secret scan failed, so the GIF and contact sheet were skipped: ${U(m)}`),p=null}if(p&&t.gif)try{let m=await Ar(s,"export_gif",{input:p,...Ty(o.durationSec,t.lastSec),output:so(n,"evidence.gif"),overwrite:!0});o.gif=String(m.outputPath)}catch(m){i(`export_gif failed: ${U(m)}`)}if(p&&t.contactSheet)try{let m=await Ar(s,"contact_sheet",{input:p,output:so(n,"contact-sheet.png"),overwrite:!0,returnImage:!1});o.contactSheet=String(m.outputPath)}catch(m){i(`contact_sheet failed: ${U(m)}`)}f&&jl(f,{force:!0})}o.recording&&u&&t.ocrErrors&&(o.errors=await jR(s,o.recording,o.durationSec,t.lastSec,n,i)),!u&&t.discardOnSuccess&&o.recording&&(jl(o.recording,{force:!0}),o.recording=null)}finally{await s.close()}return vR(so(n,"evidence.json"),JSON.stringify(o,null,2)+`
|
|
536
523
|
`),e.err(`screencast-mcp: command exited ${o.exitCode}; evidence in ${n}`+(o.gif?` (gif: ${o.gif})`:"")+`
|
|
537
|
-
`),o.exitCode}var
|
|
524
|
+
`),o.exitCode}var ky=120;async function WR(t,e,r,n,o,i){let s=Math.max(1,Math.ceil((r??0)/ky)),a=await Ar(t,"find_text",{input:e,scanEverySec:s,maxFrames:ky,query:n??Ge,regex:!0,redact:!0,returnImage:!1}),c=Array.isArray(a.redactRegions)?a.redactRegions:[];if(c.length===0)return null;let u=await Ar(t,"redact_region",{input:e,regions:c,style:"blur",output:so(o,".redacted.mp4"),overwrite:!0});return i(`blurred ${c.length} on-screen secret region(s) in the shared files`),{path:String(u.outputPath),regions:c.length}}async function jR(t,e,r,n,o,i){let s=Ty(r,n),a=e,c=null;try{if(s.start!==void 0){let p=await Ar(t,"trim",{input:e,start:s.start,duration:s.duration,output:so(o,".ocr-tail.mp4"),overwrite:!0});c=String(p.outputPath),a=c}let u=await Ar(t,"find_text",{input:a,scanEverySec:1,maxFrames:30,query:Os,regex:!0,returnImage:!1}),d=Array.isArray(u.matches)?u.matches:[];return FR(d)}catch(u){return i(`OCR of error lines failed: ${U(u)}`),null}finally{c&&jl(c,{force:!0})}}async function UR(t,e,r){let n=OR(e),o=await zl();try{let i=await o.call(t,n);return i.isError?(r.err(`${i.text}
|
|
538
525
|
`),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
|
|
526
|
+
`),0)}finally{await o.close()}}async function Ry(t,e=Ay){let r;try{r=MR(t)}catch(n){if(n instanceof Ie)return e.err(`screencast-mcp: ${n.message}
|
|
527
|
+
`),2;throw n}switch(r.kind){case"help":return e.out(TR),0;case"version":return e.out(`${Ey}
|
|
528
|
+
`),0;case"record":return BR(r.options,e);case"setup":return xy(r.options,Sy({connect:zl,io:e}));case"call":try{return await UR(r.tool,r.args,e)}catch(n){if(n instanceof Ie)return e.err(`screencast-mcp: ${n.message}
|
|
529
|
+
`),2;throw n}}}import{readdir as My,rmdir as zR,stat as HR,unlink as GR}from"node:fs/promises";import{join as ao}from"node:path";var Gl="SCREENCAST_RETENTION_DAYS";function Cy(t=process.env){let e=Number(t[Gl]);return Number.isFinite(e)&&e>0?e:null}var Hl=/\.index\.json(\.\d+\.tmp)?$/;async function Py(t,e=Date.now(),r=Me()){let n=e-t*864e5,o={removed:0,bytes:0},i=async(s,a,c)=>{let u;try{u=await My(s)}catch{return}for(let d of u){let p=ao(s,d);try{let f=await HR(p);if(f.isDirectory()){if(!c)continue;await i(p,a,!0),(await My(p)).length===0&&f.mtimeMs<n&&await zR(p)}else!a(d)&&f.mtimeMs<n&&(await GR(p),o.removed++,o.bytes+=f.size)}catch{}}};return await i(ao(r,"screenshots"),()=>!1,!0),await i(ao(r,"frames"),()=>!1,!0),await i(ao(r,"recordings"),s=>!/\.events\.raw(\.stop)?$/.test(s)&&!Hl.test(s),!1),await i(ao(r,"edits"),s=>!Hl.test(s),!1),await i(ao(r,"edits","indexes"),s=>!Hl.test(s),!1),o}var Iy=1e4;async function XR(){let t=cc();JR();try{let n=re().reapOrphans();n.length>0&&process.stderr.write(`Reaped ${n.length} orphaned recording(s) on startup.
|
|
543
530
|
`)}catch(n){process.stderr.write(`Orphan reaping skipped: ${U(n)}
|
|
544
|
-
`)}try{let n=re().list().flatMap(i=>i.status==="recording"&&i.replay?[i.replay.dir]:[]),o=
|
|
531
|
+
`)}try{let n=re().list().flatMap(i=>i.status==="recording"&&i.replay?[i.replay.dir]:[]),o=Hd(n);o>0&&process.stderr.write(`Removed ${o} leftover replay buffer(s).
|
|
545
532
|
`)}catch(n){process.stderr.write(`Replay buffer cleanup skipped: ${U(n)}
|
|
546
|
-
`)}let e=new
|
|
533
|
+
`)}let e=new qR;await t.connect(e);let r=Cy();r!==null&&Py(r).then(n=>{n.removed>0&&process.stderr.write(`Deleted ${n.removed} capture file(s) older than ${r} day(s) (${Gl}).
|
|
547
534
|
`)},n=>{process.stderr.write(`Retention prune failed: ${U(n)}
|
|
548
|
-
`)}),process.stdin.on("end",()=>{
|
|
549
|
-
`),
|
|
550
|
-
`),
|
|
551
|
-
`)})}async function
|
|
552
|
-
`),
|
|
535
|
+
`)}),process.stdin.on("end",()=>{co("client disconnected")}),process.stdin.on("close",()=>{co("client disconnected")}),t.server.onclose=()=>{co("transport closed")};for(let n of["SIGINT","SIGTERM","SIGHUP"])process.on(n,()=>{co(n)})}function JR(){process.stdout.on("error",t=>{t.code!=="EPIPE"&&process.stderr.write(`stdout error: ${t.message}
|
|
536
|
+
`),co("client pipe closed")}),process.on("uncaughtException",t=>{process.stderr.write(`Uncaught exception: ${t.stack??t.message}
|
|
537
|
+
`),co("uncaught exception",1)}),process.on("unhandledRejection",t=>{process.stderr.write(`Unhandled rejection: ${t instanceof Error?t.stack??t.message:String(t)}
|
|
538
|
+
`)})}async function co(t,e=0){if(ys())return;Hm();let r=rd();try{await qm(Iy)||process.stderr.write(`Shutdown (${t}): a start_recording call did not finish within ${Iy/1e3}s.
|
|
539
|
+
`),of();let o=re();if(o.activeIds().length>0){let i=null;try{i=k().ffprobe}catch{}let s=await Sm(o,a=>i?se(a,{ffprobe:i}):Promise.resolve(null));process.stderr.write(`Shutdown (${t}): stopped ${s.length} recording(s).
|
|
553
540
|
`)}}catch(o){process.stderr.write(`Shutdown cleanup failed: ${U(o)}
|
|
554
541
|
`)}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
|
-
`)}),
|
|
542
|
+
`),process.exit(e)}var Fy=t=>{process.stderr.write(`Fatal error: ${U(t)}
|
|
543
|
+
`),process.exit(1)},Oy=process.argv.slice(2);_y(Oy)?(process.stdout.on("error",t=>{t.code!=="EPIPE"&&process.stderr.write(`stdout error: ${t.message}
|
|
544
|
+
`)}),Ry(Oy).then(t=>process.exit(t),Fy)):XR().catch(Fy);
|