@tmhs/screencast-mcp 0.52.0 → 0.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +127 -123
- 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 NA}from"@modelcontextprotocol/sdk/server/stdio.js";import{spawn as uA}from"node:child_process";import{mkdirSync as lA,readFileSync as pA,rmSync as Yl,writeFileSync as dA}from"node:fs";import{join as Dr,resolve as mA}from"node:path";import{Client as fA}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as hA}from"@modelcontextprotocol/sdk/inMemory.js";import{McpServer as LM}from"@modelcontextprotocol/sdk/server/mcp.js";var Nt={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"]},_i=Object.keys(Nt).filter(t=>t!=="core");function tp(t){return Object.keys(Nt).find(e=>Nt[e].includes(t))}function Ri(t){let e=(t??"").split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),r={enabled:Object.keys(Nt),unknown:[],all:!0};if(e.length===0||e.includes("all"))return{...r,unknown:e.filter(s=>s!=="all"&&!(s in Nt))};let n=e.filter(s=>!(s in Nt)),o=new Set(["core",...e.filter(s=>s in Nt)]);if(o.size===1)return{...r,unknown:n};let i=Object.keys(Nt).filter(s=>o.has(s));return{enabled:i,unknown:n,all:i.length===Object.keys(Nt).length}}function rp(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 Ff}from"node:child_process";import{z as Q}from"zod";var l=class extends Error{hint;constructor(e,r){super(e),this.name="ScreencastError",this.hint=r}};function j(t){return t instanceof Error?t.message:String(t)}function S(t,e=[]){let r=typeof t=="string"?t:JSON.stringify(t,null,2),n={content:[{type:"text",text:r},...e]};return t!==null&&typeof t=="object"&&!Array.isArray(t)&&(n.structuredContent=JSON.parse(r)),n}function E(t){let e;return t instanceof l?e=t.hint?`${t.message}
|
|
4
4
|
|
|
5
|
-
${t.hint}`:t.message:e=
|
|
5
|
+
${t.hint}`:t.message:e=j(t),{content:[{type:"text",text:e}],isError:!0}}import{spawn as px}from"node:child_process";import{existsSync as yc,readFileSync as cp,writeFileSync as up,unlinkSync as dx,rmSync as xc}from"node:fs";var lp="masked",Sc=["down","up","move","wheel","key","typing","gap","focus"],vc=33;function gn(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 wo(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 $c(t,e){let r=e.spans&&e.spans.length>0?e.spans:null,n=[],o=[],i=null,s=mx(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:wc(w),type:"gap",x:f,y:m,inFrame:!1,durationSec:wc(g-w),reason:b})};for(let p of t.split(/\r?\n/)){let f=p.split(",");if(f.length<4)continue;let[m,h,b,w]=f,g=f.slice(4).join(","),y=Number(m),v=Number(b),x=Number(w);if(!Number.isFinite(y)||!Number.isFinite(v)||!Number.isFinite(x))continue;let T=r?wo(y,r):(y-e.startMs)/1e3;if(T===null)continue;let R=Math.round(T*1e3)/1e3;if(h==="hb"){o.push(R);continue}if(h==="miss"){a??={t:R,x:v-e.frame.x,y:x-e.frame.y};continue}if(h==="resume"){a&&c(a.t,a.x,a.y,R,"input_not_seen"),a=null;continue}if(h===void 0||h==="gap"||!Sc.includes(h))continue;if(h==="focus"&&R<0){i={t:0,type:"focus",x:0,y:0,inFrame:!1,...np(g)};continue}if(R<0||e.endSec!==void 0&&R>e.endSec)continue;let P=v-e.frame.x,z=x-e.frame.y,H={t:R,type:h,x:P,y:z,inFrame:P>=0&&z>=0&&P<e.frame.w&&z<e.frame.h};if((h==="down"||h==="up")&&(H.button=g||"left"),h==="down"){let D=s.get(`${m},${b},${w}`);D&&(H.element=D)}if(h==="wheel"){let[D,M]=g.split(":");H.axis=D==="h"?"horizontal":"vertical",H.delta=Number(M)||0}h==="key"&&g&&(H.keys=g),h==="typing"&&(H.durationSec=wc((Number(g)||0)/1e3)),h==="focus"&&Object.assign(H,np(g),{inFrame:!1}),n.push(H)}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>ip&&c(p,0,0,f,"helper_stalled"),f)),e.endSec!==void 0&&e.endSec-d>ip&&c(d,0,0,e.endSec,"helper_stopped")),n.sort((p,f)=>p.t-f.t)}var wc=t=>Math.round(t*1e3)/1e3;function mx(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 np(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 pp(t){return t.filter(e=>e.type==="gap").map(e=>({t:e.t,durationSec:e.durationSec??0,reason:e.reason??"input_not_seen"}))}function yo(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
6
6
|
`)+(t.length?`
|
|
7
|
-
`:"")}function
|
|
7
|
+
`:"")}function Ie(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function Ti(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 bn(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 op=500,fx=1e3,hx=2e3,ip=3,gx=`
|
|
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 ${op} 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<${fx}))return;s=typeStart;e=typeLast;typeStart=-1;}
|
|
65
|
+
double g=${op};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)>${hx}){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>=${vc}){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
|
+
`,bx=`
|
|
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 Zl=2e4;async function sp(t,e,r={}){if(process.platform!=="win32")throw new l("The input event log is implemented for Windows only.");mc(`${t}.stop`,{force:!0});let n=Buffer.from(tx(t,e,process.pid,r),"utf16le").toString("base64"),o=Xy("powershell",["-NoProfile","-NonInteractive","-EncodedCommand",n],{stdio:["ignore","pipe","pipe"],windowsHide:!0}),i="";o.stderr?.on("data",c=>{i=(i+c.toString()).slice(-2e3)});let s=[];ap.set(o,s);let a="";return o.stdout?.on("data",c=>{a+=c.toString();let u=a.split(/\r?\n/);a=u.pop()??"";for(let d of u){let p=ex(d);if(p)if("taken"in p)s.push(p.taken);else try{r.onHotkey?.(p.pressed)}catch{}}}),await new Promise((c,u)=>{let d=!1,p=m=>{d||(d=!0,clearTimeout(f),o.kill(),u(new l(`Could not start the input event log: ${m}`)))},f=setTimeout(()=>p(`no response in ${Zl/1e3}s`),Zl);o.stdout?.on("data",m=>{!d&&m.toString().includes("ready")&&(d=!0,clearTimeout(f),c())}),o.on("error",m=>p(m.message)),o.on("exit",m=>p(ox(i)||`helper exited with code ${m}`))}),up.set(o,`${t}.stop`),o}var ap=new WeakMap;function cp(t){return[...ap.get(t)??[]]}var up=new WeakMap,ep=2e3;function yi(t){if(t.exitCode!==null||t.signalCode!==null)return Promise.resolve();let e=up.get(t);if(e)try{rp(e,"")}catch{e=void 0}return new Promise(r=>{let n=setTimeout(()=>t.kill(),e?ep:0),o=setTimeout(r,ep+5e3);t.once("exit",()=>{clearTimeout(n),clearTimeout(o),r()})}).finally(()=>{e&&mc(e,{force:!0})})}function ke(t){let e=t.replace(/\.[^./\\]+$/,"");return{raw:`${e}.events.raw`,jsonl:`${e}.events.jsonl`}}function xi(t,e=!1){if(!e){let r=[t.jsonl,t.raw].find(n=>dc(n));if(r)throw new l(`Event log already exists: ${r}. Pass overwrite: true to replace it, or choose a different output path.`);return}mc(t.raw,{force:!0})}function lp(t,e){let r=dc(t.raw)?tp(t.raw,"utf8"):"",n=gc(r,e);rp(t.jsonl,bc(n));try{Jy(t.raw)}catch{}return n}var po=new Map;function ho(t,e){let r=po.get(t),n=r?Promise.all([r,e]).then(()=>{}):e;po.set(t,n),n.finally(()=>{po.get(t)===n&&po.delete(t)})}async function Zt(t,e=1e4){let r=po.get(t);r&&await Promise.race([r,new Promise(n=>setTimeout(n,e))])}import{existsSync as Ui,mkdirSync as iS,renameSync as sS,rmSync as aS,statSync as cS,writeFileSync as uS}from"node:fs";import{basename as lS,dirname as pS,extname as sd,join as ko}from"node:path";import{spawn as Qp,spawnSync as Bi}from"node:child_process";import{existsSync as Nx,mkdtempSync as Dx,rmSync as Lx,writeFileSync as Bx}from"node:fs";import{tmpdir as Wx}from"node:os";import{join as Jp}from"node:path";import{extname as Ai}from"node:path";import{homedir as ix,tmpdir as sx}from"node:os";import{basename as ax,delimiter as cx,dirname as ux,join as Fr,isAbsolute as lx,relative as px,resolve as er,sep as dx}from"node:path";import{mkdirSync as dp,existsSync as mx,realpathSync as fx}from"node:fs";function Pe(){let t=process.env.SCREENCAST_HOME;return t&&t.trim().length>0?t:Fr(ix(),".screencast-mcp")}function we(t){let e=Fr(Pe(),t);return dp(e,{recursive:!0}),e}function mp(){let t=Pe();return dp(t,{recursive:!0}),Fr(t,"sessions.json")}function he(t=new Date){let e=t.toISOString().replace(/[-:T]/g,"").replace(/\..+/,""),r=String(t.getMilliseconds()).padStart(3,"0");return`${e.slice(0,8)}-${e.slice(8,14)}-${r}`}function ge(t=4){return Math.random().toString(36).slice(2,2+t)}function mn(t,e){return Fr(t.replace(/%/g,"%%"),e)}var fp=/\.(png|jpe?g|bmp|tiff?)$/i;function wc(t){return fp.test(t)}function Te(t){return fp.test(t)?["-update","1",t]:[t]}function He(t=""){return Fr(sx(),`screencast-${he()}-${ge()}${t}`)}var Si="SCREENCAST_ALLOWED_DIRS";function go(t=process.env){let e=t[Si];return e?e.split(cx).map(r=>r.trim()).filter(r=>r.length>0).map(r=>er(r)):[]}var dn=null;function bo(t){dn=t===null||t==="pending"?t:t.map(e=>er(e))}function Or(t=process.env){let e=go(t);if(dn===null&&e.length===0)return null;let r=Array.isArray(dn)?dn:[];return[er(Pe()),...e,...r]}function pp(t){let e=[],r=er(t);for(;;)try{return Fr(fx.native(r),...e.reverse())}catch{let n=ux(r);if(n===r)return er(t);e.push(ax(r)),r=n}}function bt(t,e){let r=px(pp(e),pp(t));return r===""||r!==".."&&!r.startsWith(`..${dx}`)&&!lx(r)}function hx(t){let e=t.trim();return/^[\\/]{2}/.test(e)?!/^[\\/]{2}\?[\\/][A-Za-z]:[\\/]/.test(e):!1}function tr(t,e="Path"){if(hx(t))throw new l(`${e} ${t} is a network or device path; only local files are allowed. Copy the file to a local folder first.`)}function hp(t,e="Input"){tr(t,e);let r=er(t);if(dn==="pending"&&go().length===0&&!bt(r,Pe()))throw new l(`${e} ${r} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. Retry the call in a moment.`);let n=Or();if(!(n===null||n.some(o=>bt(r,o))))throw new l(`${e} ${r} is outside the allowed directories: ${n.join(", ")}. Move it under one of them, or add its folder to ${Si} or the client's workspace roots.`)}function rr(t){if(tr(t,"Output"),dn==="pending"&&go().length===0&&!bt(t,Pe()))throw new l(`Output ${t} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. Retry the call in a moment, or omit the path to write under SCREENCAST_HOME.`);let e=Or();if(!(e===null||e.some(r=>bt(t,r))))throw new l(`Output ${t} is outside the allowed directories: ${e.join(", ")}. Write under one of them (a relative path lands in SCREENCAST_HOME), or add the folder to ${Si} or the client's workspace roots.`)}function yc(t){if(!(Or()!==null||bt(t,Pe())))throw new l(`Refusing to replace ${t}: it is outside SCREENCAST_HOME and no allowed directories are set. Add its folder to ${Si} (or the client's workspace roots) to allow overwriting there, or write to a new path.`)}function nr(t,e,r,n=!1){if(t&&t.trim().length>0){tr(t,"Output");let o=er(e,t);if(rr(o),mx(o)){if(!n)throw new l(`Output already exists: ${o}. Pass overwrite: true to replace it, or choose a different path.`);yc(o)}return o}return Fr(e,r)}function fn(t,e){if(!t||t.trim().length===0)return;tr(t,"Output directory");let r=er(e,t);return rr(r),r}var xc={draft:{preset:"ultrafast",crf:28},standard:{preset:"veryfast",crf:23},high:{preset:"medium",crf:18}},$i=30,ki="standard";function bp(t){return!t||t.device.trim().length===0?[]:["-f","dshow","-i",`audio=${t.device}`]}function wo(t,e){if(!/^-?\d+$/.test(t.trim()))throw new l(`${e} must be an integer, got "${t}".`);return parseInt(t,10)}function wp(t){let e=t.trim();if(e===""||e.toLowerCase()==="full")return{kind:"full"};let r=e.indexOf(":");if(r===-1)throw new l(`Unrecognized target "${t}". Use full | monitor:<index> | window:<title> | region:<x>,<y>,<w>,<h>.`);let n=e.slice(0,r).toLowerCase(),o=e.slice(r+1);if(n==="monitor"){let i=wo(o,"monitor index");if(i<0)throw new l("monitor index must be >= 0.");return{kind:"monitor",index:i}}if(n==="window"){let i=o.trim();if(i==="")throw new l("window title must not be empty.");return{kind:"window",title:i}}if(n==="region"){let i=o.split(",").map(h=>h.trim());if(i.length!==4)throw new l(`region must be x,y,w,h (4 integers), got "${o}".`);let[s="",a="",c="",u=""]=i,[d,p,f,m]=[wo(s,"region x"),wo(a,"region y"),wo(c,"region w"),wo(u,"region h")];if(f<=0||m<=0)throw new l("region width and height must be positive.");return{kind:"region",x:d,y:p,w:f,h:m}}throw new l(`Unknown target kind "${n}". Use full | monitor | window | region.`)}function yp(t,e){let r=e.find(n=>n.index===t);if(!r){let n=e.map(o=>o.index).join(", ")||"none";throw new l(`monitor:${t} not found. Available monitor indexes: ${n}.`)}return r}function yo(t){if(t.length===0)return{x:0,y:0,w:0,h:0};let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,w:n-e,h:o-r}}function xp(t,e){if(e.length===0)return;let r=yo(e);if(!(t.x>=r.x&&t.y>=r.y&&t.x+t.w<=r.x+r.w&&t.y+t.h<=r.y+r.h))throw new l(`region ${t.x},${t.y},${t.w},${t.h} is outside the virtual desktop (origin ${r.x},${r.y}, size ${r.w}x${r.h}). gdigrab captures the desktop, so the rectangle must fit inside it. Adjust the offset/size, or use monitor:<index> to capture a whole display.`)}function Re(t){let e=xc[t];if(!e)throw new l(`Unknown quality preset "${t}".`);return["-c:v","libx264","-preset",e.preset,"-crf",String(e.crf),"-pix_fmt","yuv420p"]}var gx="160k";function Nr(t=gx){return["-c:a","aac",...t?["-b:a",t]:[]]}var Dr=["-movflags","+faststart"];function Se(t){let e={aac:()=>Nr(t.bitrate),copy:()=>["-c:a","copy"],none:()=>["-an"],omit:()=>[]}[t.audio]();return[...t.video??Re(t.quality??"standard"),...e,...t.faststart?Dr:[]]}function nt(t){return t-t%2}function Ei(t,e,r={}){switch(t.kind){case"full":{let n=yo(e);return r.evenSize&&e.length>0&&(n.w%2!==0||n.h%2!==0)?["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${nt(n.w)}x${nt(n.h)}`,"-i","desktop"]:["-i","desktop"]}case"window":throw new l("Internal: a window target must be resolved to a region before building capture args. Call resolveCaptureTarget().");case"region":{let{w:n,h:o}=t;if(r.evenSize&&(n=nt(n),o=nt(o),n<=0||o<=0))throw new l(`region ${t.w}x${t.h} is too small to record: width and height must each be at least 2px (the video encoder needs even dimensions). Use a larger region, or take a screenshot instead.`);return["-offset_x",String(t.x),"-offset_y",String(t.y),"-video_size",`${n}x${o}`,"-i","desktop"]}case"monitor":{let n=yp(t.index,e),o=r.evenSize?nt(n.width):n.width,i=r.evenSize?nt(n.height):n.height;return["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${o}x${i}`,"-i","desktop"]}}}function bx(t){if(t.trim().length===0)throw new l("webcam device must not be empty.");return["-f","dshow","-use_wallclock_as_timestamps","1","-rtbufsize","256M","-i",`video=${t}`]}var Sc=3600;function Sp(t,e=process.env){if(t!==void 0)return vp(t);let r=e.SCREENCAST_MAX_RECORDING_SEC;if(r!==void 0&&r.trim()!==""){let n=Number(r);if(!Number.isInteger(n)||n<0||n>It)throw new l(`SCREENCAST_MAX_RECORDING_SEC must be an integer from 0 (no cap) to ${It} (7 days), got "${r}".`);return n}return Sc}var It=168*3600;function vp(t){if(!Number.isInteger(t)||t<0||t>It)throw new l(`maxDurationSec must be an integer from 0 (no cap) to ${It} (7 days).`);return t}function wx(t){if(!Number.isInteger(t)||t<1||t>120)throw new l("fps must be an integer between 1 and 120.");return t}function vi(t){return["-g",String(Math.max(1,Math.round(t*2)))]}var gp=["-movflags","+frag_keyframe+empty_moov+default_base_moof"];function _i(t,e){let r=wx(e.fps??$i),n=e.quality??ki,o=e.monitors??[],i=vp(e.maxDurationSec??0),s=i>0?["-t",String(i)]:[],a=e.webcam,c=e.audio?2:1;return["-y",...e.videoInput??["-f","gdigrab","-framerate",String(r),...e.drawMouse===!1?["-draw_mouse","0"]:[],...Ei(t,o,{evenSize:!0})],...bp(e.audio),...a?bx(a.device):[],...a?["-map","0:v",...e.audio?["-map","1:a"]:[]]:[],...!e.videoInput&&t.kind==="full"&&o.length===0?["-vf","crop=trunc(iw/2)*2:trunc(ih/2)*2"]:[],...e.videoCodec??Re(n),...vi(r),...e.audio?Nr():[],...gp,...s,e.output,...a?["-map",`${c}:v`,...a.codec??Re(n),...vi(r),...gp,...s,a.output]:[]]}var yx=30;function $p(t,e){if(!Number.isSafeInteger(t)||t<=0)throw new l("Invalid window handle.");return["-y","-v","error","-filter_complex",`gfxcapture=hwnd=${t}:max_framerate=30,hwdownload,format=bgra`,"-frames:v","1",...Te(e)]}function Ti(t,e,r=[]){return["-y","-f","gdigrab","-framerate",String(yx),...Ei(t,r),"-frames:v","1",...Te(e)]}function Ri(t,e){switch(t.kind){case"region":return{x:t.x,y:t.y,w:nt(t.w),h:nt(t.h)};case"monitor":{let r=yp(t.index,e);return{x:r.x,y:r.y,w:nt(r.width),h:nt(r.height)}}case"full":{let r=yo(e);return{x:r.x,y:r.y,w:nt(r.w),h:nt(r.h)}}case"window":throw new l("Internal: resolve a window target to a region first.")}}function vc(t){if(!/^[a-z]+$/.test(t))throw new l(`Invalid transition "${t}". Use a lowercase xfade name such as fade, dissolve, wipeleft, wiperight, slideup, or circleopen.`);return t}function or(t,e){if(t%2!==0)throw new l(`${e} must be even, got ${t}: H.264 output with yuv420p cannot encode odd dimensions. Use ${t-1} or ${t+1}.`);return t}var xx=/[:,;=[\]'"\\\s]/;function Be(t,e="color"){if(t.length===0||xx.test(t))throw new l(`Invalid ${e} "${t}". Use a color name (black, white, red), a hex value (#RRGGBB or #RRGGBBAA), or name@alpha (e.g. white@0.5).`);return t}import{z as Lr}from"zod";var gn="standard";function $c(t){if(t===void 0)return null;let e=Number(t);return Number.isFinite(e)?e:null}function kp(t){if(!t)return null;let[e,r]=t.split("/"),n=Number(e),o=r===void 0?1:Number(r);return!Number.isFinite(n)||!Number.isFinite(o)||o===0||n===0?null:Math.round(n/o*1e3)/1e3}function Sx(t){let r=t?.side_data_list?.find(o=>o.rotation!==void 0)?.rotation??t?.tags?.rotate,n=r===void 0?NaN:Number(r);return Number.isFinite(n)?Math.round(n)%360:null}function Br(t){let e=t.streams??[],r=e.find(u=>u.codec_type==="video"),n=e.find(u=>u.codec_type==="audio"),o=t.format?.duration,i=t.format?.size,s=o!==void 0?Number(o):null,a=Sx(r),c=a!==null&&Math.abs(a)%180===90;return{durationSec:s,videoDurationSec:r?$c(r.duration)??s:null,width:(c?r?.height:r?.width)??null,height:(c?r?.width:r?.height)??null,...a?{rotation:a}:{},fps:kp(r?.avg_frame_rate)??kp(r?.r_frame_rate),videoCodec:r?.codec_name??null,audioCodec:n?.codec_name??null,format:t.format?.format_name??null,sizeBytes:i!==void 0?Number(i):null,pixFmt:r?.pix_fmt??null,videoFrames:$c(r?.nb_frames),sampleRate:$c(n?.sample_rate),channels:n?.channels??null}}function Wr(t){return["-v","quiet","-print_format","json","-show_format","-show_streams",t]}function kc(t,e){if(!Number.isFinite(t)||t<=0)throw new l(`${e} must be a positive number.`);return t}var Mi=100,Ec=1e3;function Ci(t,e,r){if(kc(e,"fps"),t===null||!(t>0))return{fps:e,requestedFrames:null,clamped:!1};let n=Math.ceil(t*e);return n<=r?{fps:e,requestedFrames:n,clamped:!1}:{fps:Math.max(1e-4,Math.floor(r/t*1e4)/1e4),requestedFrames:n,clamped:!0}}function _p(t,e){for(let r of t)if(/^frame_\d+\.png$/i.test(r))return`frame_${e}_`;return"frame_"}function Pi(t,e,r,n=Mi,o=!1,i){kc(e,"fps");let s=o?`fps=${e},mpdecimate`:`fps=${e}`;return["-y",...i?["-ss",String(i.start),...i.duration!==void 0?["-t",String(i.duration)]:[]]:[],"-i",t,"-vf",s,...o?["-fps_mode","vfr"]:[],"-frames:v",String(n),r]}var wt=.1;function ir(t,e=wt){if(!Number.isFinite(e)||e<=0||e>=1)throw new l("sceneThreshold must be between 0 and 1 (exclusive).");return["-v","error","-i",t,"-an","-vf",`scale=320:-2,select='gt(scene\\,${e})',metadata=print:file=-`,"-f","null","-"]}function sr(t){let e=[],r=null;for(let n of t.split(/\r?\n/)){let o=n.match(/pts_time:\s*(-?[\d.]+)/);if(o){r=Number(o[1]);continue}let i=n.match(/lavfi\.scene_score=([\d.]+)/);i&&r!==null&&(e.push({timeSec:r,score:Number(i[1])}),r=null)}return e}function bn(t,e){return[0,...[...t].filter(n=>n.timeSec>0).sort((n,o)=>o.score-n.score).slice(0,Math.max(0,e-1)).map(n=>n.timeSec)].sort((n,o)=>n-o)}function wn(t,e,r){if(!Number.isFinite(e)||e<0)throw new l("timestamp must be a non-negative number.");return["-y","-ss",String(e),"-i",t,"-frames:v","1",...Te(r)]}function Z(t,e={}){let r=Ai(t).toLowerCase();return r===".mp4"||r===".mkv"||r===".mov"||e.audio&&Tp.has(r)?r:".mp4"}var Tp=new Set([".wav",".mp3",".m4a"]);function Ii(t){return Tp.has(Ai(t).toLowerCase())}function jr(t){if(t===void 0)return;let e=Ai(t).toLowerCase();if(e===".webm"||e===".gif")throw new l(`This tool writes H.264/AAC, which a ${e} file cannot hold. Use an .mp4, .mkv or .mov output, then convert (format: "webm") or export_gif the result.`)}function Rp(t,e,r){let n=r.start;if(!Number.isFinite(n)||n<0)throw new l("start must be a non-negative number.");if(r.end===void 0&&r.duration===void 0)throw new l("trim requires either end or duration.");if(r.end!==void 0&&r.duration!==void 0)throw new l("trim takes end OR duration, not both.");let o=["-y","-ss",String(n),"-i",t];if(r.end!==void 0){if(r.end<=n)throw new l("end must be greater than start.");o.push("-t",String(Math.round((r.end-n)*1e3)/1e3))}else o.push("-t",String(kc(r.duration,"duration")));return r.exact===!1?o.push("-c","copy",e):o.push(...Se({quality:gn,audio:"aac",bitrate:null}),e),o}function xo(t){return t.map(e=>`file '${e.replace(/'/g,"'\\''")}'`).join(`
|
|
143
|
+
`,xo={marker:"Ctrl+Alt+Shift+M",stop:"Ctrl+Alt+Shift+S"};function wx(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 yx(t,e,r,n={}){let o=Math.max(0,Math.round((n.rotateSec??0)*1e3)),i=n.focus??"off";return gx.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?bx:"").replace("__HOTKEYS__",n.hotkeys?"true":"false")}function xx(t){return`${t}.1`}function Sx(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 dp(t,e=-1/0){let r=o=>{try{return yc(o)?cp(o,"utf8"):""}catch{return""}},n=`${r(xx(t))}
|
|
145
|
+
${r(t)}`;return e===-1/0?n:Sx(n,e)}function vx(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 sp=2e4;async function mp(t,e,r={}){if(process.platform!=="win32")throw new l("The input event log is implemented for Windows only.");xc(`${t}.stop`,{force:!0});let n=Buffer.from(yx(t,e,process.pid,r),"utf16le").toString("base64"),o=px("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=[];fp.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=wx(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 ${sp/1e3}s`),sp);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(vx(i)||`helper exited with code ${m}`))}),gp.set(o,`${t}.stop`),o}var fp=new WeakMap;function hp(t){return[...fp.get(t)??[]]}var gp=new WeakMap,ap=2e3;function Mi(t){if(t.exitCode!==null||t.signalCode!==null)return Promise.resolve();let e=gp.get(t);if(e)try{up(e,"")}catch{e=void 0}return new Promise(r=>{let n=setTimeout(()=>t.kill(),e?ap:0),o=setTimeout(r,ap+5e3);t.once("exit",()=>{clearTimeout(n),clearTimeout(o),r()})}).finally(()=>{e&&xc(e,{force:!0})})}function he(t){let e=t.replace(/\.[^./\\]+$/,"");return{raw:`${e}.events.raw`,jsonl:`${e}.events.jsonl`}}function So(t,e=!1){if(!e){let r=[t.jsonl,t.raw].find(n=>yc(n));if(r)throw new l(`Event log already exists: ${r}. Pass overwrite: true to replace it, or choose a different output path.`);return}xc(t.raw,{force:!0})}function bp(t,e){let r=yc(t.raw)?cp(t.raw,"utf8"):"",n=$c(r,e);up(t.jsonl,yo(n));try{dx(t.raw)}catch{}return n}var bo=new Map;function vo(t,e){let r=bo.get(t),n=r?Promise.all([r,e]).then(()=>{}):e;bo.set(t,n),n.finally(()=>{bo.get(t)===n&&bo.delete(t)})}async function nr(t,e=1e4){let r=bo.get(t);r&&await Promise.race([r,new Promise(n=>setTimeout(n,e))])}import{existsSync as Vi,mkdirSync as $S,renameSync as kS,rmSync as ES,statSync as _S,writeFileSync as RS}from"node:fs";import{basename as TS,dirname as MS,extname as md,join as Co}from"node:path";import{spawn as id,spawnSync as Ji}from"node:child_process";import{existsSync as eS,mkdtempSync as tS,rmSync as rS,writeFileSync as nS}from"node:fs";import{tmpdir as oS}from"node:os";import{join as td}from"node:path";import{extname as Li}from"node:path";import{homedir as $x,tmpdir as kx}from"node:os";import{basename as Ex,delimiter as _x,dirname as Rx,join as Br,isAbsolute as Tx,relative as Mx,resolve as or,sep as Ax}from"node:path";import{mkdirSync as yp,existsSync as Cx,realpathSync as Px}from"node:fs";function Fe(){let t=process.env.SCREENCAST_HOME;return t&&t.trim().length>0?t:Br($x(),".screencast-mcp")}function ye(t){let e=Br(Fe(),t);return yp(e,{recursive:!0}),e}function xp(){let t=Fe();return yp(t,{recursive:!0}),Br(t,"sessions.json")}function be(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 we(t=4){return Math.random().toString(36).slice(2,2+t)}function yn(t,e){return Br(t.replace(/%/g,"%%"),e)}var Sp=/\.(png|jpe?g|bmp|tiff?)$/i;function kc(t){return Sp.test(t)}function _e(t){return Sp.test(t)?["-update","1",t]:[t]}function Xe(t=""){return Br(kx(),`screencast-${be()}-${we()}${t}`)}var Ai="SCREENCAST_ALLOWED_DIRS";function $o(t=process.env){let e=t[Ai];return e?e.split(_x).map(r=>r.trim()).filter(r=>r.length>0).map(r=>or(r)):[]}var wn=null;function ko(t){wn=t===null||t==="pending"?t:t.map(e=>or(e))}function Wr(t=process.env){let e=$o(t);if(wn===null&&e.length===0)return null;let r=Array.isArray(wn)?wn:[];return[or(Fe()),...e,...r]}function wp(t){let e=[],r=or(t);for(;;)try{return Br(Px.native(r),...e.reverse())}catch{let n=Rx(r);if(n===r)return or(t);e.push(Ex(r)),r=n}}function vt(t,e){let r=Mx(wp(e),wp(t));return r===""||r!==".."&&!r.startsWith(`..${Ax}`)&&!Tx(r)}function Ix(t){let e=t.trim();return/^[\\/]{2}/.test(e)?!/^[\\/]{2}\?[\\/][A-Za-z]:[\\/]/.test(e):!1}function ir(t,e="Path"){if(Ix(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 vp(t,e="Input"){ir(t,e);let r=or(t);if(wn==="pending"&&$o().length===0&&!vt(r,Fe()))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=Wr();if(!(n===null||n.some(o=>vt(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 ${Ai} or the client's workspace roots.`)}function sr(t){if(ir(t,"Output"),wn==="pending"&&$o().length===0&&!vt(t,Fe()))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=Wr();if(!(e===null||e.some(r=>vt(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 ${Ai} or the client's workspace roots.`)}function Ec(t){if(!(Wr()!==null||vt(t,Fe())))throw new l(`Refusing to replace ${t}: it is outside SCREENCAST_HOME and no allowed directories are set. Add its folder to ${Ai} (or the client's workspace roots) to allow overwriting there, or write to a new path.`)}function ar(t,e,r,n=!1){if(t&&t.trim().length>0){ir(t,"Output");let o=or(e,t);if(sr(o),Cx(o)){if(!n)throw new l(`Output already exists: ${o}. Pass overwrite: true to replace it, or choose a different path.`);Ec(o)}return o}return Br(e,r)}function xn(t,e){if(!t||t.trim().length===0)return;ir(t,"Output directory");let r=or(e,t);return sr(r),r}var _c={draft:{preset:"ultrafast",crf:28},standard:{preset:"veryfast",crf:23},high:{preset:"medium",crf:18}},Pi=30,Ii="standard";function kp(t){return!t||t.device.trim().length===0?[]:["-f","dshow","-i",`audio=${t.device}`]}function Eo(t,e){if(!/^-?\d+$/.test(t.trim()))throw new l(`${e} must be an integer, got "${t}".`);return parseInt(t,10)}function Ep(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=Eo(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]=[Eo(s,"region x"),Eo(a,"region y"),Eo(c,"region w"),Eo(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 _p(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 _o(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 Rp(t,e){if(e.length===0)return;let r=_o(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 Me(t){let e=_c[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 Fx="160k";function jr(t=Fx){return["-c:a","aac",...t?["-b:a",t]:[]]}var Ur=["-movflags","+faststart"];function ve(t){let e={aac:()=>jr(t.bitrate),copy:()=>["-c:a","copy"],none:()=>["-an"],omit:()=>[]}[t.audio]();return[...t.video??Me(t.quality??"standard"),...e,...t.faststart?Ur:[]]}function ot(t){return t-t%2}function Fi(t,e,r={}){switch(t.kind){case"full":{let n=_o(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",`${ot(n.w)}x${ot(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=ot(n),o=ot(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=_p(t.index,e),o=r.evenSize?ot(n.width):n.width,i=r.evenSize?ot(n.height):n.height;return["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${o}x${i}`,"-i","desktop"]}}}function Ox(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 Rc=3600;function Tp(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>Dt)throw new l(`SCREENCAST_MAX_RECORDING_SEC must be an integer from 0 (no cap) to ${Dt} (7 days), got "${r}".`);return n}return Rc}var Dt=168*3600;function Mp(t){if(!Number.isInteger(t)||t<0||t>Dt)throw new l(`maxDurationSec must be an integer from 0 (no cap) to ${Dt} (7 days).`);return t}function Nx(t){if(!Number.isInteger(t)||t<1||t>120)throw new l("fps must be an integer between 1 and 120.");return t}function Ci(t){return["-g",String(Math.max(1,Math.round(t*2)))]}var $p=["-movflags","+frag_keyframe+empty_moov+default_base_moof"];function Oi(t,e){let r=Nx(e.fps??Pi),n=e.quality??Ii,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"]:[],...Fi(t,o,{evenSize:!0})],...kp(e.audio),...a?Ox(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??Me(n),...Ci(r),...e.audio?jr():[],...$p,...s,e.output,...a?["-map",`${c}:v`,...a.codec??Me(n),...Ci(r),...$p,...s,a.output]:[]]}var Dx=30;function Ap(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",..._e(e)]}function Ni(t,e,r=[]){return["-y","-f","gdigrab","-framerate",String(Dx),...Fi(t,r),"-frames:v","1",..._e(e)]}function Di(t,e){switch(t.kind){case"region":return{x:t.x,y:t.y,w:ot(t.w),h:ot(t.h)};case"monitor":{let r=_p(t.index,e);return{x:r.x,y:r.y,w:ot(r.width),h:ot(r.height)}}case"full":{let r=_o(e);return{x:r.x,y:r.y,w:ot(r.w),h:ot(r.h)}}case"window":throw new l("Internal: resolve a window target to a region first.")}}function Tc(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 cr(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 Lx=/[:,;=[\]'"\\\s]/;function Ue(t,e="color"){if(t.length===0||Lx.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 zr}from"zod";var vn="standard";function Mc(t){if(t===void 0)return null;let e=Number(t);return Number.isFinite(e)?e:null}function Cp(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 Bx(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 Hr(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=Bx(r),c=a!==null&&Math.abs(a)%180===90;return{durationSec:s,videoDurationSec:r?Mc(r.duration)??s:null,width:(c?r?.height:r?.width)??null,height:(c?r?.width:r?.height)??null,...a?{rotation:a}:{},fps:Cp(r?.avg_frame_rate)??Cp(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:Mc(r?.nb_frames),sampleRate:Mc(n?.sample_rate),channels:n?.channels??null}}function Gr(t){return["-v","quiet","-print_format","json","-show_format","-show_streams",t]}function Ac(t,e){if(!Number.isFinite(t)||t<=0)throw new l(`${e} must be a positive number.`);return t}var Bi=100,Cc=1e3;function Wi(t,e,r){if(Ac(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 Ip(t,e){for(let r of t)if(/^frame_\d+\.png$/i.test(r))return`frame_${e}_`;return"frame_"}function ji(t,e,r,n=Bi,o=!1,i){Ac(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 $t=.1;function ur(t,e=$t){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 lr(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 $n(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 kn(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",..._e(r)]}function V(t,e={}){let r=Li(t).toLowerCase();return r===".mp4"||r===".mkv"||r===".mov"||e.audio&&Fp.has(r)?r:".mp4"}var Fp=new Set([".wav",".mp3",".m4a"]);function Ui(t){return Fp.has(Li(t).toLowerCase())}function qr(t){if(t===void 0)return;let e=Li(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 Op(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(Ac(r.duration,"duration")));return r.exact===!1?o.push("-c","copy",e):o.push(...ve({quality:vn,audio:"aac",bitrate:null}),e),o}function Ro(t){return t.map(e=>`file '${e.replace(/'/g,"'\\''")}'`).join(`
|
|
147
147
|
`)+`
|
|
148
|
-
`}function Ap(t){if(t.length<2)throw new l("concat requires at least two input files.");return xo(t)}function yn(t,e,r={}){return["-y",...r.quiet?["-v","error"]:[],"-f","concat","-safe","0","-i",t,"-c","copy",e]}function vx(t){let{videoFrames:e,videoDurationSec:r,fps:n}=t;return e===null||r===null||n===null?!1:e>r*n*1.05+2}function Mp(t,e){let r=[["videoCodec","video codec"],["width","width"],["height","height"],["pixFmt","pixel format"],["fps","frame rate"],["audioCodec","audio codec"],["sampleRate","audio sample rate"],["channels","audio channels"]],n=e[0];for(let[o,i]of e.entries()){if(vx(i))return`${t[o]} holds hidden frames behind an edit list`;if(!(o===0||!n)){for(let[s,a]of r)if(i[s]!==n[s])return`${a} differs: ${t[0]} has ${n[s]??"none"}, ${t[o]} has ${i[s]??"none"}`}}return null}function Cp(t,e,r,n={}){switch(r){case"gif":{let o=n.fps??12,i=n.width??720,s=`fps=${o},scale='min(${i},iw)':-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse`;return["-y","-i",t,"-vf",s,e]}case"webm":return["-y","-i",t,"-c:v","libvpx-vp9","-b:v","0","-crf","30","-deadline","good","-cpu-used","4","-row-mt","1",e];case"mp4":return["-y","-i",t,...Se({quality:"standard",audio:"omit",faststart:!0}),e];default:throw new l(`Unsupported convert format "${r}".`)}}function hn(t,e){if(!Number.isInteger(t)||t<0)throw new l(`${e} must be a non-negative integer.`);return t}function Ft(t,e){if(!Number.isInteger(t)||t<=0)throw new l(`${e} must be a positive integer.`);return t}function Fi(t,e){if(t!==void 0&&e!==void 0){if(e<=t)throw new l("end must be greater than start.");return`between(t,${t},${e})`}return t!==void 0?`gte(t,${t})`:e!==void 0?`lte(t,${e})`:""}function _c(t,e){let r=hn(t.x,"crop x"),n=hn(t.y,"crop y"),o=or(Ft(t.width,"crop width"),"crop width"),i=or(Ft(t.height,"crop height"),"crop height");if(e&&e.width!=null&&e.height!=null&&(r+o>e.width||n+i>e.height))throw new l(`crop region ${o}x${i}+${r}+${n} falls outside the ${e.width}x${e.height} frame.`);return`crop=${o}:${i}:${r}:${n}`}function Pp(t,e,r,n,o=gn){return["-y","-i",t,"-vf",_c(r,n),...Se({quality:o,audio:"copy"}),e]}function Tc(t){if(t.width===void 0&&t.height===void 0)throw new l("scale requires width or height (or both).");return t.width!==void 0&&or(Ft(t.width,"scale width"),"scale width"),t.height!==void 0&&or(Ft(t.height,"scale height"),"scale height"),`scale=${t.width??-2}:${t.height??-2}`}function Ip(t,e,r){let n=o=>Math.max(2,Math.round(o/2)*2);return r.width!==void 0&&r.height!==void 0?{width:r.width,height:r.height}:r.width!==void 0?{width:r.width,height:n(e*r.width/t)}:{width:n(t*r.height/e),height:r.height}}function Fp(t,e,r,n=gn){return["-y","-i",t,"-vf",Tc(r),...Se({quality:n,audio:"copy"}),e]}function Rc(t){let e=t,r=[];for(;e>2;)r.push("atempo=2.0"),e/=2;for(;e<.5;)r.push("atempo=0.5"),e/=.5;return r.push(`atempo=${Number(e.toFixed(6))}`),r.join(",")}function Op(t,e,r,n,o=gn){if(!Number.isFinite(r)||r<=0)throw new l("speed factor must be a positive number.");let i=["-y","-i",t,"-filter:v",`setpts=PTS/${r}`];return n&&i.push("-filter:a",Rc(r)),i.push(...Se({quality:o,audio:n?"aac":"none",bitrate:null}),e),i}var $x="crop='min(iw,ih)':'min(iw,ih)',format=yuva420p,geq=lum='p(X,Y)':cb='p(X,Y)':cr='p(X,Y)':a='if(lte(hypot(X-W/2,Y-H/2),W/2),255,0)'";function Np(t,e,r,n,o=gn){let i=hn(n.x,"overlay x"),s=hn(n.y,"overlay y"),a=Fi(n.start,n.end),c=a?`:enable='${a}'`:"",d=`[1:v]${`setpts=PTS-STARTPTS+${n.start??0}/TB`}`;if(n.scale&&(n.scale.width!==void 0||n.scale.height!==void 0)){n.scale.width!==void 0&&Ft(n.scale.width,"overlay scale width"),n.scale.height!==void 0&&Ft(n.scale.height,"overlay scale height");let m=n.scale.width??-1,h=n.scale.height??-1;d+=`,scale=${m}:${h}`}n.shape==="circle"&&(d+=`,${$x}`);let p=`${d}[ovl];[0:v][ovl]overlay=${i}:${s}${c}[v]`,f=n.durationSec;return["-y","-i",t,"-i",e,"-filter_complex",p,"-map","[v]","-map","0:a?",...Se({quality:o,audio:"copy"}),...f!=null&&f>0?["-t",String(f)]:[],r]}var kx={light:23,medium:28,heavy:32};function Dp(t,e,r={}){let n=r.level??"medium",o=kx[n];if(o===void 0)throw new l(`Unknown compress level "${n}".`);let i=["-y","-i",t];return r.maxWidth!==void 0&&(Ft(r.maxWidth,"maxWidth"),i.push("-vf",`scale='trunc(min(${r.maxWidth},iw)/2)*2':-2`)),i.push(...Se({video:["-c:v","libx264","-preset","slow","-crf",String(o),"-pix_fmt","yuv420p"],audio:"aac",bitrate:"128k",faststart:!0}),e),i}var Ex={mp3:["-c:a","libmp3lame","-q:a","2"],aac:Nr("192k"),wav:["-c:a","pcm_s16le"],copy:["-c:a","copy"]};function Lp(t){switch(t){case"aac":case"alac":return"m4a";case"mp3":return"mp3";case"opus":case"vorbis":return"ogg";case"flac":return"flac";default:return t&&t.startsWith("pcm_")?"wav":"mka"}}function Bp(t,e,r){let n=Ex[r];if(!n)throw new l(`Unknown audio format "${r}".`);return["-y","-i",t,"-vn",...n,e]}function Wp(t,e,r,n=gn){if(!Number.isFinite(r.start)||r.start<0)throw new l("clip start must be a non-negative number.");if(!Number.isFinite(r.end)||r.end<=r.start)throw new l("clip end must be greater than start.");return["-y","-ss",String(r.start),"-i",t,"-t",String(r.end-r.start),...Se({quality:n,audio:"aac",bitrate:null}),e]}var Oi=["box","blur","pixelate"];function _x(t,e,r){return t.map((n,o)=>{let i=hn(n.x,`region[${o}] x`),s=hn(n.y,`region[${o}] y`),a=Ft(n.width,`region[${o}] width`),c=Ft(n.height,`region[${o}] height`);if(r&&r.width!=null&&r.height!=null&&(i+a>r.width||s+c>r.height))throw new l(`region[${o}] ${a}x${c}+${i}+${s} falls outside the ${r.width}x${r.height} frame.`);let u=Math.max(0,i-e),d=Math.max(0,s-e),p=i+a+e,f=s+c+e;return r&&r.width!=null&&(p=Math.min(p,r.width)),r&&r.height!=null&&(f=Math.min(f,r.height)),{x:u,y:d,w:p-u,h:f-d,enable:Fi(n.start,n.end)}})}var Tx=8,Ep=3,Rx=16;function Ax(t){let e=Math.min(t.w,t.h),r=i=>Math.max(0,Math.floor((i-1)/2)),n=Math.min(r(e),Math.max(Tx,Math.min(20,Math.floor(e/4)))),o=Math.min(n,r(Math.ceil(e/2)));return`lr=${n}:lp=${Ep}:cr=${o}:cp=${Ep}`}function Mx(t){let e=Math.max(Rx,Math.ceil(Math.max(t.w,t.h)/16)),r=Math.max(1,Math.round(t.w/e)),n=Math.max(1,Math.round(t.h/e));return`scale=${r}:${n}:flags=area,scale=${t.w}:${t.h}:flags=neighbor`}function Ac(t,e,r,n,o){if(t.length===0)throw new l("redact_region requires at least one region.");let i=e.style??"box",s=e.pad??0;if(!Number.isInteger(s)||s<0)throw new l("pad must be a non-negative integer.");let a=Be(e.color??"black","color"),c=_x(t,s,r);if(i==="box"){let m=c.map(h=>{let b=h.enable?`:enable='${h.enable}'`:"";return`drawbox=x=${h.x}:y=${h.y}:w=${h.w}:h=${h.h}:color=${a}:t=fill${b}`}).join(",");return{steps:[`${n}${m}[${o}out]`],out:`[${o}out]`}}let u=c.length,d=[],p=[`${o}base`,...c.map((m,h)=>`${o}s${h}`)];d.push(`${n}split=${u+1}[${p.join("][")}]`),c.forEach((m,h)=>{let b=`crop=${m.w}:${m.h}:${m.x}:${m.y}`,w=i==="blur"?`boxblur=${Ax(m)}`:Mx(m);d.push(`[${o}s${h}]${b},${w}[${o}b${h}]`)});let f=`${o}base`;return c.forEach((m,h)=>{let b=m.enable?`:enable='${m.enable}'`:"",w=h===u-1?`${o}out`:`${o}c${h}`;d.push(`[${f}][${o}b${h}]overlay=${m.x}:${m.y}${b}[${w}]`),f=`${o}c${h}`}),{steps:d,out:`[${o}out]`}}function Ni(t,e){if(!wc(t))return jr(e),{still:!1,ext:Z(t)};if(e&&!wc(e))throw new l("An image input writes an image: give the output a .png or .jpg extension.");return{still:!0,ext:/\.jpe?g$/i.test(t)?Ai(t).toLowerCase():".png"}}function jp(t,e,r,n={},o,i=!1){let s=i?r.map(({start:d,end:p,...f})=>f):r,{steps:a,out:c}=Ac(s,n,o,"[0:v]","");if(i)return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-frames:v","1",...Te(e)];let[u]=a;if((n.style??"box")==="box"&&u!==void 0){let d=u.slice(5,-c.length);return["-y","-i",t,"-vf",d,...Se({quality:"high",audio:"copy"}),e]}return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Se({quality:"high",audio:"copy"}),e]}var xn=Lr.object({x:Lr.number().int().nonnegative(),y:Lr.number().int().nonnegative(),width:Lr.number().int().positive(),height:Lr.number().int().positive(),start:Lr.number().nonnegative().optional(),end:Lr.number().positive().optional()});var Cx="screencast-mcp",Up=new Set;function zp(t){Up.add(t)}function ar(t,e,r={}){for(let n of Up)n.isConnected()&&n.sendLoggingMessage({level:t,logger:Cx,data:{message:e,...r}}).catch(()=>{})}var Hp=/^\s*(?:frame|size)=/,Px=/\b(?:warning|deprecated|dropp(?:ed|ing)|too full|discard\w*|non[- ]?monoton\w*|past duration|could not|cannot|failed|invalid|corrupt\w*|missing|error)\b/i,Ix=/^\s*configuration:|deprecated pixel format used/i,Gp=20;function qp(t){return!Hp.test(t)&&Px.test(t)&&!Ix.test(t)}function Fx(t){let e=new Set;for(let r of t.split(/[\r\n]+/)){let n=r.trim();if(n&&qp(n)&&e.add(n),e.size>=Gp)break}return[...e]}function Xp(t,e={}){let r=Fx(t);r.length>0&&ar("warning","ffmpeg reported warnings.",{...e,warnings:r})}var Ox=1e4,Di=class{constructor(e,r=ar,n=Date.now){this.data=e;this.send=r;this.now=n}data;send;now;partial="";seen=new Set;dropped=0;lastDropReport=-1/0;feed(e){let r=(this.partial+e).split(/[\r\n]/);this.partial=r.pop()??"";for(let n of r)this.line(n.trim())}line(e){if(e){if(Hp.test(e)){let r=Number(/\bdrop=\s*(\d+)/.exec(e)?.[1]??0);r>this.dropped&&this.now()-this.lastDropReport>=Ox&&(this.lastDropReport=this.now(),this.dropped=r,this.send("warning",`The recording has dropped ${r} frame(s) so far.`,{...this.data(),dropped:r}));return}!qp(e)||this.seen.has(e)||this.seen.size>=Gp||(this.seen.add(e),this.send("warning",e,{...this.data(),source:"ffmpeg"}))}}};var jx="ffmpeg and ffprobe must be installed and on PATH (or set FFMPEG_PATH / FFPROBE_PATH). Windows: `winget install Gyan.FFmpeg` or `choco install ffmpeg`. macOS: `brew install ffmpeg`. Linux: `apt install ffmpeg`.";function Yp(t,e){let r=process.env[t]?.trim();return r||e}function Kp(t){try{return Bi(t,["-version"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Mc(){let t=Yp("FFMPEG_PATH","ffmpeg"),e=Yp("FFPROBE_PATH","ffprobe"),r=[];if(Kp(t)||r.push("ffmpeg"),Kp(e)||r.push("ffprobe"),r.length>0)throw new l(`Required ${r.join(" and ")} not found on PATH.`,jx);return{ffmpeg:t,ffprobe:e}}var Li=null;function k(){return Li||(Li=Mc(),Li)}var Sn=null;function cr(){if(Sn!==null)return Sn;if(process.platform!=="win32")return Sn=!1;try{let t=Bi(k().ffmpeg,["-hide_banner","-h","filter=gfxcapture"],{encoding:"utf8",windowsHide:!0,timeout:1e4});Sn=/gfxcapture AVOptions/.test(t.stdout??"")}catch{Sn=!1}return Sn}var Vp=new Map;function Ve(t){let e=Vp.get(t);if(e!==void 0)return e;let r;try{let n=Bi(k().ffmpeg,["-hide_banner","-h",`filter=${t}`],{encoding:"utf8",windowsHide:!0,timeout:1e4});r=new RegExp(`^Filter ${t}\\b`,"m").test(n.stdout??"")}catch{r=!1}return Vp.set(t,r),r}var Zp=["ignore","pipe","pipe"],vo=class extends l{};function se(t,e,r=300*1e3,n={}){return new Promise((o,i)=>{let s=Qp(t,e,{windowsHide:!0,stdio:Zp}),a="",c="",u=null,d,p=g=>{u||(u=g,s.kill("SIGKILL"),d=setTimeout(()=>i(g),5e3))},f=()=>p(new l(`${t} was cancelled.`)),m=setTimeout(()=>p(new l(`${t} timed out after ${Math.round(r/1e3)}s.`)),r),h,b=()=>{if(!n.stallMs)return;clearTimeout(h);let g=n.progressed?"made no progress":"wrote nothing";h=setTimeout(()=>p(new vo(`${t} ${g} for ${Math.round(n.stallMs/1e3)}s and was stopped.`)),n.stallMs)};b();let w=()=>{clearTimeout(m),clearTimeout(h),clearTimeout(d),n.signal?.removeEventListener("abort",f)};n.signal?.aborted?f():n.signal?.addEventListener("abort",f,{once:!0}),s.stdout?.on("data",g=>{let y=g.toString();(!n.progressed||n.progressed(y))&&b(),a+=y,n.onStdout?.(y)}),s.stderr?.on("data",g=>{n.progressed||b(),c+=g.toString()}),s.on("error",g=>{w(),i(g)}),s.on("close",g=>{w(),u?i(u):o({code:g,stdout:a,stderr:c})})})}var Ux=new Set(["-vf","-af","-filter_complex","-lavfi","-filter:v","-filter:a"]),zx=8e3,Hx={"-vf":"-filter_script:v","-filter:v":"-filter_script:v","-af":"-filter_script:a","-filter:a":"-filter_script:a","-filter_complex":"-filter_complex_script","-lavfi":"-filter_complex_script"},So=null;function Gx(){if(So!==null)return So;try{let t=Bi(k().ffmpeg,["-hide_banner","-version"],{encoding:"utf8",windowsHide:!0,timeout:1e4}),e=/^\s*libavutil\s+(\d+)\./m.exec(t.stdout??"");So=e?.[1]===void 0||Number(e[1])>=59}catch{So=!0}return So}function Wi(t,e){let r=null,n=[...t];for(let[i,s]of t.entries()){let a=t[i-1];if(a===void 0||!Ux.has(a)||s.length<=zx)continue;r??=Dx(Jp(Wx(),"screencast-filter-"));let c=Jp(r,`filter${i}.txt`);Bx(c,s),e??=Gx(),n[i-1]=e?`-/${a.slice(1)}`:Hx[a]??a,n[i]=c}let o=r;return{args:n,cleanup:()=>o&&Lx(o,{recursive:!0,force:!0})}}async function Ur(t,e=3e4,r={}){let n=[];return await ed(t,e,o=>n.push(o),r),Buffer.concat(n)}async function ji(t,e,r,n=3e4,o={}){if(!(e>0))throw new l("frameBytes must be positive.");let i=Buffer.alloc(0),s=0;return await ed(t,n,a=>{i=i.length?Buffer.concat([i,a]):a;let c=0;for(;c+e<=i.length;c+=e)r(Buffer.from(i.subarray(c,c+e))),s++;i=i.subarray(c)},o),s}function ed(t,e,r,n){let{ffmpeg:o}=k(),{args:i,cleanup:s}=Wi(t);return new Promise((a,c)=>{let u=Qp(o,i,{windowsHide:!0,stdio:Zp}),d="",p=null,f,m=g=>{p||(p=g,u.kill("SIGKILL"),f=setTimeout(()=>c(g),5e3))},h=()=>m(new l("ffmpeg was cancelled.")),b=setTimeout(()=>m(new l(`ffmpeg timed out after ${Math.round(e/1e3)}s.`)),e),w=()=>{clearTimeout(b),clearTimeout(f),n.signal?.removeEventListener("abort",h)};n.signal?.aborted?h():n.signal?.addEventListener("abort",h,{once:!0}),u.stdout?.on("data",g=>{if(!p)try{r(g)}catch(y){m(y)}}),u.stderr?.on("data",g=>d+=g.toString()),u.on("error",g=>{w(),c(g)}),u.on("close",g=>{w(),p?c(p):g===0?a():c(new l(`ffmpeg failed (exit ${g}):
|
|
148
|
+
`}function Np(t){if(t.length<2)throw new l("concat requires at least two input files.");return Ro(t)}function En(t,e,r={}){return["-y",...r.quiet?["-v","error"]:[],"-f","concat","-safe","0","-i",t,"-c","copy",e]}function Wx(t){let{videoFrames:e,videoDurationSec:r,fps:n}=t;return e===null||r===null||n===null?!1:e>r*n*1.05+2}function Dp(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(Wx(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 Lp(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,...ve({quality:"standard",audio:"omit",faststart:!0}),e];default:throw new l(`Unsupported convert format "${r}".`)}}function Sn(t,e){if(!Number.isInteger(t)||t<0)throw new l(`${e} must be a non-negative integer.`);return t}function Lt(t,e){if(!Number.isInteger(t)||t<=0)throw new l(`${e} must be a positive integer.`);return t}function zi(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 Pc(t,e){let r=Sn(t.x,"crop x"),n=Sn(t.y,"crop y"),o=cr(Lt(t.width,"crop width"),"crop width"),i=cr(Lt(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 Bp(t,e,r,n,o=vn){return["-y","-i",t,"-vf",Pc(r,n),...ve({quality:o,audio:"copy"}),e]}function Ic(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&&cr(Lt(t.width,"scale width"),"scale width"),t.height!==void 0&&cr(Lt(t.height,"scale height"),"scale height"),`scale=${t.width??-2}:${t.height??-2}`}function Wp(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 jp(t,e,r,n=vn){return["-y","-i",t,"-vf",Ic(r),...ve({quality:n,audio:"copy"}),e]}function Fc(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 Up(t,e,r,n,o=vn){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",Fc(r)),i.push(...ve({quality:o,audio:n?"aac":"none",bitrate:null}),e),i}var jx="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 zp(t,e,r,n,o=vn){let i=Sn(n.x,"overlay x"),s=Sn(n.y,"overlay y"),a=zi(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&&Lt(n.scale.width,"overlay scale width"),n.scale.height!==void 0&&Lt(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+=`,${jx}`);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?",...ve({quality:o,audio:"copy"}),...f!=null&&f>0?["-t",String(f)]:[],r]}var Ux={light:23,medium:28,heavy:32};function Hp(t,e,r={}){let n=r.level??"medium",o=Ux[n];if(o===void 0)throw new l(`Unknown compress level "${n}".`);let i=["-y","-i",t];return r.maxWidth!==void 0&&(Lt(r.maxWidth,"maxWidth"),i.push("-vf",`scale='trunc(min(${r.maxWidth},iw)/2)*2':-2`)),i.push(...ve({video:["-c:v","libx264","-preset","slow","-crf",String(o),"-pix_fmt","yuv420p"],audio:"aac",bitrate:"128k",faststart:!0}),e),i}var zx={mp3:["-c:a","libmp3lame","-q:a","2"],aac:jr("192k"),wav:["-c:a","pcm_s16le"],copy:["-c:a","copy"]};function Gp(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 qp(t,e,r){let n=zx[r];if(!n)throw new l(`Unknown audio format "${r}".`);return["-y","-i",t,"-vn",...n,e]}function Xp(t,e,r,n=vn){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),...ve({quality:n,audio:"aac",bitrate:null}),e]}var Hi=["box","blur","pixelate"];function Hx(t,e,r){return t.map((n,o)=>{let i=Sn(n.x,`region[${o}] x`),s=Sn(n.y,`region[${o}] y`),a=Lt(n.width,`region[${o}] width`),c=Lt(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:zi(n.start,n.end)}})}var Gx=8,Pp=3,qx=16;function Xx(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=${Pp}:cr=${o}:cp=${Pp}`}function Jx(t){let e=Math.max(qx,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 Oc(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=Ue(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=${Xx(m)}`:Jx(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 Gi(t,e){if(!kc(t))return qr(e),{still:!1,ext:V(t)};if(e&&!kc(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)?Li(t).toLowerCase():".png"}}function Jp(t,e,r,n={},o,i=!1){let s=i?r.map(({start:d,end:p,...f})=>f):r,{steps:a,out:c}=Oc(s,n,o,"[0:v]","");if(i)return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-frames:v","1",..._e(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,...ve({quality:"high",audio:"copy"}),e]}return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...ve({quality:"high",audio:"copy"}),e]}var _n=zr.object({x:zr.number().int().nonnegative(),y:zr.number().int().nonnegative(),width:zr.number().int().positive(),height:zr.number().int().positive(),start:zr.number().nonnegative().optional(),end:zr.number().positive().optional()});var Yx="screencast-mcp",Yp=new Set;function Kp(t){Yp.add(t)}function kt(t,e,r={}){for(let n of Yp)n.isConnected()&&n.sendLoggingMessage({level:t,logger:Yx,data:{message:e,...r}}).catch(()=>{})}var Vp=/^\s*(?:frame|size)=/,Kx=/\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,Qp=20;function Zp(t){return!Vp.test(t)&&Kx.test(t)&&!Vx.test(t)}function Qx(t){let e=new Set;for(let r of t.split(/[\r\n]+/)){let n=r.trim();if(n&&Zp(n)&&e.add(n),e.size>=Qp)break}return[...e]}function ed(t,e={}){let r=Qx(t);r.length>0&&kt("warning","ffmpeg reported warnings.",{...e,warnings:r})}var Zx=1e4,qi=class{constructor(e,r=kt,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(Vp.test(e)){let r=Number(/\bdrop=\s*(\d+)/.exec(e)?.[1]??0);r>this.dropped&&this.now()-this.lastDropReport>=Zx&&(this.lastDropReport=this.now(),this.dropped=r,this.send("warning",`The recording has dropped ${r} frame(s) so far.`,{...this.data(),dropped:r}));return}!Zp(e)||this.seen.has(e)||this.seen.size>=Qp||(this.seen.add(e),this.send("warning",e,{...this.data(),source:"ffmpeg"}))}}};var iS="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 rd(t,e){let r=process.env[t]?.trim();return r||e}function nd(t){try{return Ji(t,["-version"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Nc(){let t=rd("FFMPEG_PATH","ffmpeg"),e=rd("FFPROBE_PATH","ffprobe"),r=[];if(nd(t)||r.push("ffmpeg"),nd(e)||r.push("ffprobe"),r.length>0)throw new l(`Required ${r.join(" and ")} not found on PATH.`,iS);return{ffmpeg:t,ffprobe:e}}var Xi=null;function k(){return Xi||(Xi=Nc(),Xi)}var Rn=null;function pr(){if(Rn!==null)return Rn;if(process.platform!=="win32")return Rn=!1;try{let t=Ji(k().ffmpeg,["-hide_banner","-h","filter=gfxcapture"],{encoding:"utf8",windowsHide:!0,timeout:1e4});Rn=/gfxcapture AVOptions/.test(t.stdout??"")}catch{Rn=!1}return Rn}var od=new Map;function Qe(t){let e=od.get(t);if(e!==void 0)return e;let r;try{let n=Ji(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 od.set(t,r),r}var sd=["ignore","pipe","pipe"],Mo=class extends l{};function ce(t,e,r=300*1e3,n={}){return new Promise((o,i)=>{let s=id(t,e,{windowsHide:!0,stdio:sd}),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 Mo(`${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 sS=new Set(["-vf","-af","-filter_complex","-lavfi","-filter:v","-filter:a"]),aS=8e3,cS={"-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"},To=null;function uS(){if(To!==null)return To;try{let t=Ji(k().ffmpeg,["-hide_banner","-version"],{encoding:"utf8",windowsHide:!0,timeout:1e4}),e=/^\s*libavutil\s+(\d+)\./m.exec(t.stdout??"");To=e?.[1]===void 0||Number(e[1])>=59}catch{To=!0}return To}function Yi(t,e){let r=null,n=[...t];for(let[i,s]of t.entries()){let a=t[i-1];if(a===void 0||!sS.has(a)||s.length<=aS)continue;r??=tS(td(oS(),"screencast-filter-"));let c=td(r,`filter${i}.txt`);nS(c,s),e??=uS(),n[i-1]=e?`-/${a.slice(1)}`:cS[a]??a,n[i]=c}let o=r;return{args:n,cleanup:()=>o&&rS(o,{recursive:!0,force:!0})}}async function Xr(t,e=3e4,r={}){let n=[];return await ad(t,e,o=>n.push(o),r),Buffer.concat(n)}async function Ki(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 ad(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 ad(t,e,r,n){let{ffmpeg:o}=k(),{args:i,cleanup:s}=Yi(t);return new Promise((a,c)=>{let u=id(o,i,{windowsHide:!0,stdio:sd}),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 te(t,e,r={}){let{ffmpeg:n}=k(),o=
|
|
151
|
+
`)}`))})}).finally(s)}async function te(t,e,r={}){let{ffmpeg:n}=k(),o=Yi(t);try{let i=await ce(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}`)}ed(i.stderr)}finally{o.cleanup()}}async function ue(t,e={}){if(!eS(t))return null;try{let r=await ce(e.ffprobe??k().ffprobe,Gr(t),3e4);return r.code!==0?null:Hr(JSON.parse(r.stdout)).durationSec}catch{return null}}async function L(t){let{ffprobe:e}=k(),r=await ce(e,Gr(t),3e4);if(r.code!==0)throw new l(`ffprobe failed (exit ${r.code}): ${r.stderr.trim().slice(-400)}`);return Hr(JSON.parse(r.stdout))}import{basename as ud,dirname as lS,extname as pS,join as dS}from"node:path";import{renameSync as mS,rmSync as Dc}from"node:fs";var fS="SCREENCAST_JOB_TIMEOUT_MS",hS=10*6e4,gS=9e4,bS=30*6e4,wS=4;function de(t,e=process.env){let r=Number(e[fS]);return Number.isInteger(r)&&r>0?r:t==null||!(t>0)?bS:Math.max(hS,Math.ceil(t*wS*1e3))}function yS(t){let e=pS(t);return dS(lS(t),`${ud(t,e)}.partial${e}`)}function xS(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 cd(){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 Ao(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 Lc=new Set,ld=!1;async function U(t,e){if(ld)throw new l("The server is shutting down; the edit was not started.");let r=yS(e.output),n=Ao(e.extra),o=cd(),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",...xS(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)};Lc.add(f);let m=vS(e.output);try{let h=()=>{let b=cd(),w=null,g=y=>{let v=b(y);return v===null||v===w?!1:(w=v,!0)};return te(c,de(a),{signal:d,stallMs:gS,progressed:g,onStdout:y=>{if(m?.output(y.length),!n||!i)return;let v=o(y);v!==null&&(m?.progress(v),n(v/i))}})};try{await h()}catch(b){if(!(b instanceof Mo)||d.aborted)throw b;process.stderr.write(`${b.message} Retrying the edit once.
|
|
155
|
+
`),Dc(r,{force:!0}),await h()}mS(r,e.output),n?.(1),m?.end("done")}catch(h){throw m?.end(`failed: ${h instanceof Error?h.message.split(`
|
|
156
|
+
`)[0]:String(h)}`),Dc(r,{force:!0}),h}finally{m?.stop(),Lc.delete(f),p()}}var SS="SCREENCAST_DEBUG_JOBS";function vS(t){if(process.env[SS]!=="1")return;let e=ud(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 pd(t=3e3){ld=!0;let e=[...Lc];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{Dc(n.partial,{force:!0})}catch{}return e.length}var fd=.25;function Et(t){return`${t}.parts`}function hd(t,e){return e===0?t:Co(Et(t),`part-${String(e).padStart(3,"0")}.mp4`)}function Qi(t,e){return Co(Et(t),`webcam-${String(e).padStart(3,"0")}.mp4`)}function Jr(t){let e=md(t);return Co(MS(t),`${TS(t,e)}.webcam.mp4`)}function Wc(t,e,r,n){if(e!==null&&e>0)return e;let o;try{o=_S(t).size}catch{return null}return o<=0?null:Math.max(.001,Math.round(n-r)/1e3)}function it(t){return t.reduce((e,r)=>e+r.durationSec,0)}function AS(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=AS(t),o=t.current?Math.max(0,(r-t.current.startMs)/1e3):0;return{startMs:n[0].startMs,endSec:it(t.parts)+o,spans:n}}function gd(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 bd(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 wd(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 jc=new Set;function yd(t){jc.add(t)}function xd(t){return jc.has(t)}function Sd(t){jc.delete(t)}var Bc=new Map;function vd(t){let e=Bc.get(t);if(!e){let r;e={promise:new Promise(o=>r=o),resolve:r},Bc.set(t,e)}return e}function Tn(t){return vd(t).promise}function es(t){vd(t).resolve(),setTimeout(()=>Bc.delete(t),6e4).unref?.()}var dd=t=>Math.round(t*1e3)/1e3;function CS(t,e,r){if(t.length===0)throw new l("No webcam parts to join.");let n=t.map((i,s)=>{let a=dd(Math.max(.001,i.durationSec)),c=dd(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,...Ur,e]}async function $d(t,e,r){let n=Et(t),o={joined:!1},i=e.filter(u=>Vi(u.path)&&u.durationSec>0),s=it(i),a=!1;if(i.length>1||i.length===1&&i[0].path!==t){$S(n,{recursive:!0});let u=Co(n,"segments.txt"),d=Co(n,`joined${md(t)||".mp4"}`);RS(u,Ro(i.map(f=>f.path)));let p=await ce(r.ffmpeg,En(u,d,{quiet:!0}),de(s));p.code===0&&Vi(d)?(kS(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&&Vi(u.webcamPath));if(r.webcamOutput&&c.length>0){let u=CS(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 ce(r.ffmpeg,u,de(s));d.code===0&&Vi(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||ES(n,{recursive:!0,force:!0}),o}function kd(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 PS}from"node:child_process";import{randomBytes as IS}from"node:crypto";import{rmSync as FS,writeFileSync as OS}from"node:fs";import{tmpdir as NS}from"node:os";import{join as DS}from"node:path";function LS(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 BS=`
|
|
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
|
+
`,WS=5e3,Mn=null,jS=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
174
|
+
`,US=2e4,_d="SCREENCAST_PS_TIMEOUT_MS";function dr(t,e=process.env){let r=Number(e[_d]);return Number.isInteger(r)&&r>0?r:t}function zS(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=jS+(e===void 0?"":zS(e))+t;return["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}async function GS(t,e){let r=DS(NS(),`screencast-ps-${process.pid}-${IS(6).toString("hex")}.json`);OS(r,t,{encoding:"utf8",mode:384});try{return await e(r)}finally{FS(r,{force:!0})}}function pt(t,e,r={}){return r.payload===void 0?Ed(t,e,r):GS(r.payload,n=>Ed(t,e,r,n))}function Ed(t,e,r,n){let o=r.timeoutMs??dr(US),i=r.command?.file??"powershell",s=r.command?.args??HS(t,n);return new Promise((a,c)=>{PS(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 ${_d}.`));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 qS(){let t=await pt(BS,"monitors");try{return LS(JSON.parse(t))}catch(e){throw new l(`Could not parse monitor geometry: ${j(e)}`)}}function mr(t=Date.now()){if(process.platform!=="win32")return Promise.reject(new l("Monitor enumeration is implemented for Windows (gdigrab) only."));if(Mn&&t-Mn.at<WS)return Mn.monitors;let e={at:t,monitors:qS()};return Mn=e,e.monitors.catch(()=>{Mn===e&&(Mn=null)}),e.monitors}var Md=5;function Uc(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 zc(t,e,r={}){let n=Array.isArray(t.windows)?t.windows:[],o=n.filter(i=>!i.cloaked);try{return Rd(t,o,e,r)}catch(i){if(!(i instanceof Yr)||o.length===n.length)throw i;let s;try{s=Rd(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 Yr=class extends l{};function Rd(t,e,r,n){let o=Uc(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 Yr(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 Td(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,Md).map(f=>`"${f.title}"`).join(", ");if(s.length===0&&n.exactOnly)throw new Yr(`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 Yr(`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 Td(t,d,u)}function Td(t,e,r){let n=e[0];if(!n)throw new Yr("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,Md).map(p=>p.title)}}function fr(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 XS=`
|
|
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 Hc(){if(process.platform!=="win32")throw new l("Window capture is implemented for Windows (gdigrab) only.");let t=await pt(XS,"windows"),e;try{e=JSON.parse(t)}catch(i){throw new l(`Could not parse window geometry: ${j(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 Ad(t,e={}){return zc(await Hc(),t,e)}function Cd(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.saveWhen&&!t.replay)throw new l("saveWhen saves from a replay buffer: add replayBufferSec.");if((t.logs||t.perf)&&t.replay)throw new l("logs and perf are not supported with replayBufferSec yet.")}function Pd(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 (${xo.marker} marks, ${xo.stop} stops)`:"")+(t.replayBufferSec?", kept only until save_replay or stop_recording { save: true } writes it out?":`, saved to ${t.output}?`)}function Id(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,...t.label?{label:t.label}:{},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:Jr(t.output),corner:t.webcam.corner??"bottom_right",size:t.webcam.size??fd,shape:t.webcam.shape??"rect"}}:{},processImage:t.processImage}}function Fd(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.diskNote?{diskNote:t.diskNote}:{},...t.gpuFrames!==void 0?{gpuFrames:t.gpuFrames}:{},...t.webcamDevice?{webcam:{device:t.webcamDevice,path:Jr(e.outputPath)}}:{},...t.window?fr(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:{...xo,...t.hotkeys.taken.length?{unavailable:t.hotkeys.taken,warning:`Another app holds ${t.hotkeys.taken.map(r=>xo[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 Od}from"zod";var ge={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},C={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},ts={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},Nd={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1};function N(t){return Od.looseObject(t)}var Y=N({outputPath:Od.string().describe("Path of the file written.")});import{rmSync as Rm,writeFileSync as Ov}from"node:fs";import{createReadStream as JS,createWriteStream as YS,existsSync as rs,mkdirSync as KS,mkdtempSync as VS,readdirSync as Gc,readFileSync as QS,rmSync as is,statSync as ZS,writeFileSync as Dd}from"node:fs";import{stat as Ld,writeFile as ev}from"node:fs/promises";import{pipeline as tv}from"node:stream/promises";import{join as Ze}from"node:path";var jd=2,rv=3,ns=4,Kr=3600,nv="seg%05d.ts",Ud=/^seg(\d{5})\.ts$/,zd="segments.csv",ov=/^buf-[\w-]+$/,Hd=60;function Gd(t){return t+Hd}function qd(){return Ze(Fe(),"replay")}function iv(t,e=jd){return Math.ceil(t/e)+rv}function Xd(t,e=jd){if(!Number.isInteger(t)||t<ns||t>Kr)throw new l(`replayBufferSec must be an integer from ${ns} to ${Kr} seconds.`);return{dir:Ze(qd(),`buf-${be()}-${we(6)}`),bufferSec:t,segmentSec:e,wrap:iv(t,e)}}function Jd(t){return Ze(t,zd)}function Yd(t,e){let r=t.slice(0,-1),n=r.indexOf("-movflags");return n>=0&&r.splice(n,2),[...r,"-force_key_frames",`expr:gte(t,n_forced*${e.segmentSec})`,"-f","segment","-segment_time",String(e.segmentSec),"-segment_wrap",String(e.wrap),"-segment_list",Jd(e.dir),"-segment_list_type","csv","-segment_list_size",String(e.wrap),"-segment_format","mpegts","-segment_format_options","flush_packets=1",yn(e.dir,nv)]}function sv(t){let e=[];for(let r of t.split(/\r?\n/)){let[n="",o,i]=r.trim().split(","),s=Ud.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 av(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 cv(t,e){let r=t.at(-1),n=r?(r.index+1)%e:0;return`seg${String(n).padStart(5,"0")}.ts`}function uv(t,e,r){let n=r.reencode?ve({quality:r.quality??"standard",audio:r.audio?"aac":"omit"}):["-c","copy"];return["-y","-v","error","-ss",String(Po(Math.max(0,r.startSec))),"-i",t,...n,...Ur,e]}function lv(t,e,r){return Ti(t,{from:e,to:r}).map(n=>({...n,t:Po(n.t-e)}))}var Po=t=>Math.round(t*1e3)/1e3;async function Bd(t,e,r){let n=(await Ld(t)).size;return n===0?(await ev(e,""),0):(await tv(JS(t,{start:0,end:n-1}),YS(e),{signal:r}),(await Ld(e)).size)}async function Wd(t,e,r){let n=await ce(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 Io(t,e){if(!rs(t.dir))throw new l("This replay buffer has been discarded: its segments are gone.");let r=Jd(t.dir),n=rs(r)?sv(QS(r,"utf8")):[],o=av(n,e.lastSec),i=VS(Ze(t.dir,"save-"));try{let s=[];for(let[T,R]of o.entries()){let P=Ze(i,`${String(T).padStart(5,"0")}.ts`);await Bd(Ze(t.dir,R.file),P,e.signal),s.push(P)}let a=!1;if(e.live!==!1){let T=Ze(t.dir,cv(n,t.wrap)),R=Ze(i,"live.ts");if(rs(T)&&await Bd(T,R,e.signal)>0){let P=s.at(-1),[z,H]=await Promise.all([Wd(e.ffprobe,R,e.signal),P?Wd(e.ffprobe,P,e.signal):Promise.resolve(-1/0)]);z!==null&&H!==null&&z>H&&(s.push(R),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=Ze(i,"join.txt");Dd(c,Ro(s));let u=Ze(i,"joined.mp4"),d=de(e.lastSec+2*t.segmentSec),p=await ce(e.ffmpeg,En(c,u,{quiet:!0}),d,{signal:e.signal});if(p.code!==0)throw new l(`Joining the replay segments failed:
|
|
224
224
|
${p.stderr.trim().split(`
|
|
225
225
|
`).slice(-4).join(`
|
|
226
|
-
`)}`);let f=await
|
|
226
|
+
`)}`);let f=await ce(e.ffprobe,Gr(u),3e4,{signal:e.signal}),m=f.code===0?Hr(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 ce(e.ffmpeg,uv(u,e.output,{startSec:b,reencode:e.reencode,quality:e.quality,audio:!!m?.audioCodec}),d,{signal:e.signal});if(w.code!==0)throw new l(`Writing the replay failed:
|
|
227
227
|
${w.stderr.trim().split(`
|
|
228
228
|
`).slice(-4).join(`
|
|
229
|
-
`)}`);let g=o[0]?.start??n.at(-1)?.end??0,y=
|
|
229
|
+
`)}`);let g=o[0]?.start??n.at(-1)?.end??0,y=Po(g+b),v=Po(g+h),x={outputPath:e.output,durationSec:Po(h-b),fromSec:y,toSec:v,segments:s.length,includesLive:a};if(t.events){let T=t.events.startMs+y*1e3-Hd*1e3,R=dp(t.events.raw,T),P=lv($c(R,{startMs:t.events.startMs,frame:t.events.frame}),y,v),{jsonl:z}=he(e.output);Dd(z,yo(P)),x.eventsPath=z,x.events=bn(P)}return x}finally{is(i,{recursive:!0,force:!0})}}function Kd(t){KS(t.dir,{recursive:!0})}function Vd(t){let e;try{e=Gc(t.dir)}catch{return}for(let r of e)(Ud.test(r)||r===zd)&&is(Ze(t.dir,r),{force:!0})}function os(t){try{return is(t.dir,{recursive:!0,force:!0}),!rs(t.dir)}catch{return!1}}function Qd(t){let e=0;try{for(let r of Gc(t.dir))try{let n=ZS(Ze(t.dir,r));n.isFile()&&(e+=n.size)}catch{}}catch{}return e}function Zd(t,e=qd()){let r=new Set([...t].map(i=>i.toLowerCase())),n;try{n=Gc(e)}catch{return 0}let o=0;for(let i of n){let s=Ze(e,i);if(!(!ov.test(i)||r.has(s.toLowerCase())))try{is(s,{recursive:!0,force:!0}),o++}catch{}}return o}async function ss(t,e){if(!e.save)return{saved:!1,discarded:os(t)};try{let r=e.tools?.();if(!r)throw new l("ffmpeg is not available to save the replay buffer.");let n=await Io(t,{...r,lastSec:t.bufferSec,output:e.output,quality:e.quality,live:!1});return{saved:!0,discarded:os(t),save:n}}catch(r){return{saved:!1,discarded:!1,error:j(r)}}}var em=3;function as(t){return`${t}.stop`}function tm(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 us=["nvenc","qsv","amf"],ls={x264:"libx264",nvenc:"h264_nvenc",qsv:"h264_qsv",amf:"h264_amf"},pv={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 hr(t,e,r={}){if(!_c[e])throw new l(`Unknown quality preset "${e}".`);if(t==="x264")return Me(e);let{preset:n,q:o}=pv[t][e],i=["-c:v",ls[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 dv(t){return["-hide_banner","-v","error","-f","lavfi","-i","color=c=black:s=256x256:r=30","-frames:v","3",...hr(t,"draft"),"-f","null","-"]}function om(t){return["-hide_banner","-v","error","-f","lavfi","-i",`ddagrab=framerate=10${t?"":",hwdownload,format=bgra"}`,"-frames:v","2",...t?hr(t,"draft",{gpuFrames:!0}):[],"-f","null","-"]}var mv=2e4;function qc(t){return async e=>{try{return(await ce(t,e,mv)).code===0}catch{return!1}}}var rm=new Map;function Xc(t,e,r,n){let o=`${t}\0${e}`,i=rm.get(o);return i||(i=n(r),rm.set(o,i)),i}async function Jc(t,e=qc(t)){let r=await Promise.all(us.map(n=>Xc(t,`enc:${n}`,dv(n),e)));return Object.fromEntries(us.map((n,o)=>[n,r[o]]))}var cs={nvenc:{width:4096,height:4096},qsv:{width:4096,height:2304},amf:{width:4096,height:2304}};function fv(t,e){let r=cs[t];return e.width<=r.width&&e.height<=r.height}async function im(t,e,r,n=qc(r),o){if(t==="x264")return{encoder:"x264",gpuFrames:!1};let i=d=>!o||fv(d,o),s=o?`${o.width}x${o.height}`:"";if(t!=="auto"&&!i(t)){let d=cs[t];throw new l(`The ${t} encoder (${ls[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 Jc(r,n),c=t==="auto"?us.find(d=>a[d]&&i(d)):a[t]?t:void 0;if(!c){if(t==="auto"){let d=us.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}: ${cs[p].width}x${cs[p].height}`).join(", ")}); using libx264.`:"No hardware encoder passed a trial encode; using libx264."}}throw new l(`The ${t} encoder (${ls[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 Xc(r,`dda:${c}`,om(c),n);return{encoder:c,gpuFrames:u}}async function sm(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} (${ls[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 am(t,e=qc(t)){return Xc(t,"dda",om(),e)}function hv(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 gv=`
|
|
242
242
|
Add-Type -TypeDefinition @"
|
|
243
243
|
using System; using System.Runtime.InteropServices; using System.Text;
|
|
244
244
|
public static class ScDxgi {
|
|
@@ -263,23 +263,23 @@ public static class ScDxgi {
|
|
|
263
263
|
return sb.ToString(); } }
|
|
264
264
|
"@
|
|
265
265
|
[ScDxgi]::List()
|
|
266
|
-
`,
|
|
267
|
-
`)}catch{}return new Map}}parseDisk(){let e=JSON.parse(
|
|
268
|
-
`),r=e()}this.records=new Map(
|
|
269
|
-
`);return}}attachChild(e,r){this.children.set(e,r)}getChild(e){return this.children.get(e)}detachChild(e,r){r&&this.children.get(e)!==r||this.children.delete(e)}activeIds(){return[...[...this.children.keys()].filter(e=>this.records.get(e)?.status==="recording"),...[...this.paused].filter(e=>this.records.get(e)?.status==="paused"&&!this.children.has(e))]}paused=new Set;markPaused(e){this.paused.add(e)}ownsPaused(e){return this.paused.has(e)}clearPaused(e){this.paused.delete(e)}markStopping(e){this.stopping.add(e)}isStopping(e){return this.stopping.has(e)}clearStopping(e){this.stopping.delete(e)}reapOrphans(){this.refresh();let e=[],r=new Map;for(let n of this.records.values()){if(!
|
|
270
|
-
`),t.stdin.end();let n=await
|
|
271
|
-
`)}}),i,s=new Promise(a=>{i=setTimeout(a,r)});return await Promise.race([Promise.allSettled(o),s]),clearTimeout(i),n}function
|
|
272
|
-
`)}var
|
|
273
|
-
`),o=[];t.length<
|
|
266
|
+
`,bv=5e3,Fo=null;function cm(){if(Fo&&Date.now()-Fo.at<bv)return Fo.outputs;let t=pt(gv,"DXGI outputs").then(hv);return Fo={at:Date.now(),outputs:t},t.catch(()=>{Fo=null}),t}var nm=t=>t-t%2;function um(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=nm(t.w),i=nm(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 lm(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 Kc}from"node:child_process";import{readFileSync as ps,writeFileSync as dm,renameSync as mm,existsSync as wv,copyFileSync as yv,openSync as xv,closeSync as Sv,unlinkSync as fm,statSync as hm,linkSync as vv}from"node:fs";import{basename as $v}from"node:path";var kv=100;function An(t){return t==="recording"||t==="paused"}function Ev(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 gm(t,e,r){return An(t.status)&&t.serverPid!==void 0&&t.serverPid!==e&&r}function bm(t,e,r){return t.backend==="wgc"||!gm(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 Vc(t,e=new Map){let r=t.serverPid;return r===void 0||r===process.pid||!ze(r)?!1:(e.has(r)||e.set(r,xm(r)),_v(t,e.get(r)??null))}function wm(){return{serverPid:process.pid,serverStartedAt:new Date(Date.now()-process.uptime()*1e3).toISOString(),serverImage:$v(process.execPath).toLowerCase()}}var ym=5e3;function _v(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+ym)}function Rv(t){let e=/^(.+)\|(\d+)\s*$/m.exec(t.trim());return e?.[1]&&e[2]?{image:e[1].trim(),startMs:Number(e[2])}:null}function xm(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=Kc("powershell",["-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",windowsHide:!0,timeout:1e4,killSignal:"SIGKILL"});return r.status===0&&r.stdout?Rv(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 Sm(t){return t.processImage??(t.backend==="wgc"?"node.exe":"ffmpeg.exe")}function Tv(t,e){return(t.split(/\r?\n/)[0]??"").toLowerCase().startsWith(`"${e.toLowerCase()}"`)}function Mv(t,e){if(t===null||process.platform!=="win32")return!1;let r=Kc("tasklist",["/FI",`PID eq ${t}`,"/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0});return r.status!==0||!r.stdout?!1:Tv(r.stdout,e)}function Av(t,e){if(!e)return!0;if(e.image.toLowerCase()!==Sm(t).toLowerCase())return!1;let r=t.pidSpawnedAt;return!(typeof r=="number"&&Number.isFinite(r)&&e.startMs>r+ym)}function Qc(t){return t.pid===null||!Mv(t.pid,Sm(t))?!1:t.pidSpawnedAt===void 0||Av(t,xm(t.pid))}function vm(t){let{code:e,backend:r,maxDurationSec:n,elapsedMs:o}=t;return r==="wgc"&&e===em?{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 gr(t){if(process.platform==="win32")Kc("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0});else try{process.kill(t,"SIGKILL")}catch{}}function Yc(t){let e=t.filter(n=>An(n.status)),r=t.filter(n=>!An(n.status)).sort((n,o)=>n.startedAt<o.startedAt?1:-1).slice(0,kv);return[...e,...r]}var Cv=3e4,$m=15e3;function Pv(t,e,r){return!t||typeof t.at!="number"||e-t.at>Cv?!0:typeof t.pid=="number"&&!r}function km(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Iv(t,e){let r=Date.now()+1e3;for(;;)try{mm(t,e);return}catch(n){let o=n.code;if(o!=="EPERM"&&o!=="EBUSY"&&o!=="EACCES"||Date.now()>=r)throw n;km(15)}}function Fv(t,e){let r=`${t}.${process.pid}.${Date.now()}.stale`;try{mm(t,r)}catch{return!1}let n=!0;try{ps(r,"utf8")!==e&&(n=!1,vv(r,t))}catch{}try{fm(r)}catch{}return n}function pm(t,e,r=$m){let n=`${t}.lock`,o=Date.now()+r,i,s;for(let a=0;;a++)try{let c=xv(n,"wx");s=JSON.stringify({pid:process.pid,at:Date.now(),nonce:Math.random().toString(36).slice(2)}),dm(c,s),Sv(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}): ${j(c)}`);if(u==="EEXIST"){let p;try{let f=ps(n,"utf8"),m;try{m=JSON.parse(f)}catch{m={at:hm(n).mtimeMs}}p={raw:f,holder:m}}catch{p=null}if(p&&(i=p.holder?.pid,Pv(p.holder,Date.now(),ze(p.holder?.pid??null))&&Fv(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.");km(Math.min(50,2**Math.min(a,6))*(.5+Math.random()))}try{return e()}finally{try{ps(n,"utf8")===s&&fm(n)}catch{}}}var ds=class{constructor(e,r=$m){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(!wv(this.path))return new Map;try{return this.parseDisk()}catch{try{yv(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(ps(this.path,"utf8"));return new Map(e.map(r=>[r.id,r]))}signature(){try{let e=hm(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(Yc([...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=pm(this.path,e,this.lockWaitMs)}catch(n){process.stderr.write(`${j(n)} Reading the session registry without the lock.
|
|
268
|
+
`),r=e()}this.records=new Map(Yc([...this.overlay(r).values()]).map(n=>[n.id,n]))}persist(){pm(this.path,()=>{let e=Yc([...this.overlay(this.readDisk()).values()]),r=`${this.path}.${process.pid}.tmp`;dm(r,JSON.stringify(e,null,2)),Iv(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}: ${j(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(!An(n.status)||gm(n,process.pid,Vc(n,r)))continue;let o=ze(n.pid),i=Ev(n,o);i.reaped&&n.pid!==null&&(Qc(n)&&gr(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 Zc(t,e){let r=Date.now()+e;for(;Date.now()<r&&ze(t);)await new Promise(n=>setTimeout(n,100))}function Em(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 Tm(t,e,r){if(!t.stdin||!t.stdin.writable)return!1;t.stdin.write(`q
|
|
270
|
+
`),t.stdin.end();let n=await Em(t,r);return!n&&e!==null&&(gr(e),await Zc(e,2e3),await Em(t,2e3)),n}async function Nv(t,e){let r=t.segments;if(!r)return[];let n=[...r.parts];if(r.current){let o=await ue(r.current.path,{ffprobe:e}),i=t.stoppedAt?Date.parse(t.stoppedAt):Date.now(),s=Wc(r.current.path,o,r.current.startMs,i)??0;n.push({...r.current,durationSec:s})}return n}function Dv(t){let e=t.segments;return!!e&&(e.parts.length>0||!!t.webcam)}async function tu(t,e){let r=await Nv(t,e.ffprobe),n=await $d(t.outputPath,r,{ffmpeg:e.ffmpeg,webcamOutput:t.webcam?Jr(t.outputPath):void 0,webcamCodec:hr(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 eu=new WeakMap;function Lv(t,e){return eu.get(t)?.get(e)?.kind??null}function ms(t,e,r){let n=Lv(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 fs(t,e,r,n,o={}){let i=eu.get(t);i||eu.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 Mm(t,e,r){return fs(t,e.id,"pause",()=>Bv(t,t.get(e.id)??e,r))}async function Bv(t,e,r){let n=t.getChild(e.id),o=bd(e,!!n);if(o)throw new l(`Cannot pause ${e.id}: ${o}.`);yd(e.id),t.markStopping(e.id);try{let i=Date.now(),s=await Tm(n,e.pid,r.gracefulMs??8e3);t.detachChild(e.id,n);let a=e.segments.current,c=await r.probe(a.path),u=Wc(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&&Rm(a.path,{force:!0}),t.markPaused(e.id),{record:t.update(e.id,{status:"paused",pid:null,segments:{parts:p}}),recordedSec:it(p),segmentSec:u,graceful:s}}finally{Sd(e.id),t.clearStopping(e.id)}}async function Am(t,e,r=1e4){let n=t.activeIds(),o=n.map(async a=>{let c=t.get(a);if(c)try{await Oo(t,c,{reason:"shutdown",probe:e,gracefulMs:Math.min(8e3,r)})}catch(u){process.stderr.write(`Stopping ${a} on shutdown failed: ${j(u)}
|
|
271
|
+
`)}}),i,s=new Promise(a=>{i=setTimeout(a,r)});return await Promise.race([Promise.allSettled(o),s]),clearTimeout(i),n}function Oo(t,e,r){return fs(t,e.id,"stop",async n=>{if(!n)return _m(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}:_m(t,o,r)},{queue:!0})}async function _m(t,e,r){t.markStopping(e.id);let n=e.backend==="wgc"?as(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 Tm(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&&(Ov(n,""),await Zc(e.pid,r.gracefulMs??8e3),o=!ze(e.pid)),ze(e.pid)&&(gr(e.pid),await Zc(e.pid,2e3)),ze(e.pid)))throw s(e.pid);t.detachChild(e.id,i),e.status==="paused"&&(o=!0),es(e.id),t.clearPaused(e.id),await nr(e.id);let a,c={};if(Dv(e)){let f=await tu(e,k());c=f.patch,a={count:f.count,...f.error?{error:f.error}:{}}}let u=e.replay?await ss(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&&Rm(n,{force:!0}),t.clearStopping(e.id)}}import{existsSync as jv,readFileSync as Uv,renameSync as zv,writeFileSync as Hv}from"node:fs";var hs=t=>Math.round(t*1e3)/1e3;function No(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 br(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-=No(r,n.spans);return r}function Vr(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-=No(n,i.spans),o-=No(o,i.spans)),o<=n)return null;return[n,o]}function Im(t,e){return t.flatMap(r=>{let n=Vr(r.start,r.end,e);return n?[{start:hs(n[0]),end:hs(n[1])}]:[]})}function gs(t,e){return t.flatMap(r=>{let n=Vr(r.start,r.end,e);return n&&n[1]-n[0]>=.05?[{...r,start:hs(n[0]),end:hs(n[1])}]:[]})}var Wv=/^(\d+):(\d{2}):(\d{2})\.(\d{2})$/,Cm=t=>{let e=t.trim().match(Wv);return e?Number(e[1])*3600+Number(e[2])*60+Number(e[3])+Number(e[4])/100:null},Pm=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 Fm(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=Cm(i),u=Cm(s);if(c===null||u===null)return[r];let d=Vr(c,u,e);return d&&d[1]-d[0]>=.05?[`${o}${Pm(d[0])},${Pm(d[1])},${a}`]:[]}).join(`
|
|
272
|
+
`)}var Om=500,Do=200,Nm=3,Cn=10,Bt=t=>Math.round(t*1e3)/1e3;function wr(t){return`${t.replace(/\.[^./\\]+$/,"")}.markers.json`}function Dm(t,e){return Math.max(0,Bt((e-t)/1e3))}function Lo(t,e=Do){let r=t.replace(/\s+/g," ").trim();return r.length>e?`${r.slice(0,e-1).trimEnd()}\u2026`:r}function ws(t,e){if(t.length>=Om)throw new l(`A recording holds at most ${Om} markers.`);let r=Lo(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:Bt(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 qv(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 He(t){let e=wr(t);if(!jv(e))return[];try{return qv(Uv(e,"utf8"))}catch{return[]}}function yr(t,e,r){let n=wr(t),o=`${n}.${process.pid}.tmp`;return Hv(o,JSON.stringify({...r?{sessionId:r}:{},markers:e},null,2)),zv(o,n),n}function Lm(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:Bt(s.t/n.factor)}));continue}if(n.op==="cut"){r=r.map(s=>({...s,t:Bt(s.t-No(s.t,n.spans))}));continue}let o=r.filter(s=>s.t>=n.start&&s.t<n.end).map(s=>({...s,t:Bt(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 ys(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:Bt(a.start),title:Lo(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:Bt(i[c+1]?.start??e),title:a.title}))}function Xv(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 Bm(t,e){let r=e>=3600,n=t.map(s=>`${Xv(s.start,r)} ${s.title}`).join(`
|
|
273
|
+
`),o=[];t.length<Nm&&o.push(`YouTube needs at least ${Nm} 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<Cn);return i.length>0&&o.push(`YouTube needs every chapter to be at least ${Cn} s long; ${i.length} ${i.length===1?"is":"are"} shorter (${i.map(s=>`"${s.title}"`).join(", ")}). Raise minChapterSec to ${Cn} to merge them.`),{text:n,issues:o}}function Jv(t){return t.replace(/[=;#\\\n]/g,e=>`\\${e}`)}function xs(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=${Jv(r.title)}`);return`${e.join(`
|
|
274
274
|
`)}
|
|
275
|
-
`}function ms(t){return t.map(e=>({start:e.t,title:e.label}))}function Im(t,e,r){let n=[0];for(let o of[...t].sort((i,s)=>s.score-i.score)){if(n.length>=r)break;n.every(i=>Math.abs(i-o.timeSec)>=e)&&n.push(o.timeSec)}return n.sort((o,i)=>o-i).map((o,i)=>({start:o,title:`Scene ${i+1}`}))}function Cv(t,e=60){let r=t.replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();if(r.length<=e)return r;let n=r.slice(0,e),o=n.lastIndexOf(" ");return`${(o>e/2?n.slice(0,o):n).trimEnd()}\u2026`}function Fm(t,e={}){let r=e.gapSec??2,n=e.minChapterSec??30,o=[...t].sort((a,c)=>a.start-c.start),i=[],s=-1/0;for(let a of o){let c=i.at(-1);(!c||a.start-s>=r&&a.start-c.start>=n)&&i.push({start:a.start,title:Cv(a.text)}),s=Math.max(s,a.end)}return i}var us=8;function Om(t,e,r,n){let o=n.subtitles??[];if(o.length>us)throw new l(`At most ${us} subtitle tracks.`);return["-y","-i",t,"-f","ffmetadata","-i",e,...o.flatMap(i=>["-i",i.file]),"-map","0:v","-map","0:a?",...o.length?o.flatMap((i,s)=>["-map",`${s+2}:s:0`]):["-map","0:s?"],"-map_metadata","0","-map_chapters","1","-c","copy",...o.length?["-c:s",n.container===".mkv"?"copy":"mov_text"]:[],...o.flatMap((i,s)=>[...i.language?[`-metadata:s:s:${s}`,`language=${i.language}`]:[],...i.title?[`-metadata:s:s:${s}`,`title=${i.title}`]:[],...o.length>1||i.default!==void 0?[`-disposition:s:${s}`,i.default?"default":"0"]:[]]),...n.container===".mkv"?[]:["-movflags","+faststart"],r]}function Pv(t){return["-v","quiet","-print_format","json","-show_chapters",t]}function Iv(t){let e;try{e=JSON.parse(t)}catch{return[]}return(e.chapters??[]).flatMap((r,n)=>{let o=Number(r.start_time),i=Number(r.end_time);return!Number.isFinite(o)||!Number.isFinite(i)?[]:[{start:Ot(o),end:Ot(i),title:r.tags?.title??`Chapter ${n+1}`}]})}async function Fv(t,e){let{ffprobe:r}=k(),n=await se(r,Pv(t),3e4,{signal:e});return n.code===0?Iv(n.stdout):[]}async function gr(t,e){let r=We(t);if(r.length>0)return{markers:r,from:"sidecar"};let n=await Fv(t,e);return n.length>0?{markers:n.map(o=>({t:o.start,label:o.title})),from:"chapters"}:{markers:[],from:null}}function fs(t,e,r,n){let o=t.get(e);if(!o)throw new l(`No session with id "${e}".`);let i=n;if(i===void 0&&o.status==="paused")i=ot(o.segments?.parts??[]);else if(i===void 0){if(o.status!=="recording")throw new l(`Session "${e}" is ${o.status}, so there is no "now" to mark.`,"Pass at (video seconds) to mark a stopped recording.");i=Mm(o.videoStartMs??Date.parse(o.startedAt),Date.now())}else if(o.durationSec!=null&&i>o.durationSec)throw new l(`at ${i}s is past the end of the recording (${o.durationSec}s).`);let s={t:i,label:r,at:new Date().toISOString()},a=ls(o.markers??[],s);t.update(e,{markers:a});let c=fr(o.outputPath),u;try{c=hr(o.outputPath,a,e)}catch(d){u=`Saved in the session, but the sidecar ${c} could not be written: ${z(d)}`}return{t:i,count:a.length,markersPath:c,live:o.status==="recording"||o.status==="paused",...u?{warning:u}:{}}}import{existsSync as Ov,readFileSync as Nv}from"node:fs";import{dirname as Nm,join as hs}from"node:path";import{fileURLToPath as Dv}from"node:url";var Dm="@tmhs/screencast-mcp",Qc=null,Lv=null;function Lm(t){try{return JSON.parse(Nv(t,"utf8"))}catch{return null}}function Bv(t){for(let e=t;;){let r=hs(e,"package.json");if(Ov(r)&&Lm(r)?.name===Dm)return e;let n=Nm(e);if(n===e)return null;e=n}}function Zc(){if(Qc)return Qc;let t=Bv(Nm(Dv(import.meta.url)));if(!t)throw new l(`Cannot find the ${Dm} package root (its package.json).`);return Qc=t}function xt(){return Lv??=Lm(hs(Zc(),"package.json"))?.version??"0.0.0"}function _n(...t){return hs(Zc(),"assets",...t)}function Bm(){return hs(Zc(),"dist","wgcRecorder.js")}async function ut(t,e={}){let r=wp(t);if(r.kind==="window"){let n=await $d(r.title,{exactOnly:e.exactTitle,allowCloaked:e.backend==="wgc"});return{target:{kind:"region",x:n.x,y:n.y,w:n.width,h:n.height},monitors:[],window:n}}return r.kind==="monitor"?{target:r,monitors:await lr()}:r.kind==="region"?(xp(r,await lr()),{target:r,monitors:[]}):{target:r,monitors:await lr()}}var Wv=["virtual-audio-capturer","stereo mix","what u hear","wave out mix","cable output","voicemeeter output"],Co="System audio capture needs a virtual-audio loopback device, which Windows does not provide natively. Enable 'Stereo Mix' in Sound settings, or install a loopback driver (for example screen-capture-recorder's virtual-audio-capturer, or VB-CABLE). Then pass its name as `device`, or run list_audio_devices to see what is available. Microphone capture is not supported.";function jv(t){return Wm(t,"audio")}function Uv(t){return Wm(t,"video")}function Wm(t,e){let r=[],n=null;for(let o of t.split(/\r?\n/)){if(/DirectShow audio devices/i.test(o)){n="audio";continue}if(/DirectShow video devices/i.test(o)){n="video";continue}if(/Alternative name/i.test(o))continue;let i=o.match(/"([^"]+)"/);if(!i)continue;let s=/\(audio\)/i.test(o),a=/\(video\)/i.test(o);(e==="audio"?s||!a&&n==="audio":a||!s&&n==="video")&&i[1]&&r.push(i[1])}return[...new Set(r)]}function eu(t,e){if(e&&e.trim().length>0)return t.includes(e)?e:null;let r=n=>n.toLowerCase();return t.find(n=>Wv.some(o=>r(n).includes(o)))??null}var zv=12e3,Hv="Enumerating DirectShow audio devices timed out or failed - usually a misbehaving audio driver, or no audio device present. Record without system audio, or fix the device, then retry. "+Co,gs=null,bs=null;async function tu(t=!1){return!t&&gs?gs:(await Um(),gs??[])}async function ru(t=!1){return!t&&bs?bs:(await Um(),bs??[])}async function jm(t){let e=await ru();if(t&&t.trim().length>0){if(e.includes(t))return t;throw new l(`Video device "${t}" not found. Available dshow video devices: ${e.join(", ")||"none"}.`)}let r=e[0];if(!r)throw new l("No webcam (dshow video device) found.","Connect a camera, then run list_video_devices.");return r}async function Um(){let{ffmpeg:t}=k(),e;try{e=await se(t,["-hide_banner","-list_devices","true","-f","dshow","-i","dummy"],zv)}catch(r){throw new l(`Could not enumerate audio devices (${z(r)}).`,Hv)}gs=jv(e.stderr),bs=Uv(e.stderr)}async function zm(t){let e=await tu(),r=eu(e,t);if(r)return r;if(t&&t.trim().length>0){let n=e.length>0?e.join(", "):"none";throw new l(`Audio device "${t}" not found. Available dshow audio devices: ${n}.`,Co)}throw new l("No system-audio loopback device found.",Co)}var Po="SCREENCAST_CONFIRM_CAPTURE",nu=300*1e3;function Hm(t=process.env){let e=(t[Po]??"").trim().toLowerCase();return["1","true","yes","on","always"].includes(e)?"always":["0","false","no","off","never"].includes(e)?"off":"auto"}function Gm(t=process.env){return Hm(t)==="always"}function Nt(t,e){return e?`window "${e.matchedTitle}"`:t==="full"?"the full screen (all monitors)":t}async function Dt(t,e,r){let n=Hm();if(n==="off")return;if(!t.server.getClientCapabilities()?.elicitation?.form){if(n==="auto")return;throw new l(`Capture blocked: ${Po} requires the user to confirm each capture, but this client does not support MCP elicitation. Nothing was captured.`,`Use a client that supports elicitation, or set ${Po}=auto to capture without confirmation in clients that cannot ask.`)}let o;try{({action:o}=await t.server.elicitInput({message:e,requestedSchema:{type:"object",properties:{}}},{signal:r,timeout:nu}))}catch(i){throw new l(`Capture blocked: the confirmation request failed (${z(i)}). Nothing was captured.`)}if(o!=="accept")throw new l(`Capture ${o==="decline"?"declined":"cancelled"} by the user. Nothing was captured.`)}var ws=null;function oe(){return ws||(ws=new ns(mp()),ws.load()),ws}var iu=!1;function qm(){iu=!0}function xs(){return iu}var ys=0,ou=[];function Xm(){if(iu)throw new l("The server is shutting down; the recording was not started.");ys++;let t=!1;return()=>{if(!t&&(t=!0,ys--,ys===0)){let e=ou;ou=[];for(let r of e)r()}}}function Jm(t){return ys===0?Promise.resolve(!0):new Promise(e=>{let r=setTimeout(()=>e(!1),t);r.unref?.(),ou.push(()=>{clearTimeout(r),e(!0)})})}import{existsSync as M0,mkdirSync as C0,mkdtempSync as P0,rmSync as xu,writeFileSync as yf}from"node:fs";import{tmpdir as I0}from"node:os";import{spawn as Gv}from"node:child_process";var Ym=15e3;async function Lt(t,e,r="gdigrab"){if(r==="gdigrab"){await te(Ti(t.target,e,t.monitors),6e4);return}let n=t.window?.hwnd;if(n===void 0)throw new l("backend 'wgc' captures a single window: use a window:<title> target.");if(!cr())throw new l("backend 'wgc' needs FFmpeg 8 or newer with the gfxcapture filter (Windows Graphics Capture).","Check with `ffmpeg -h filter=gfxcapture`. Recent Windows builds (e.g. `winget install Gyan.FFmpeg`) include it. Or use the default backend, which captures what is visible on screen.");let o=Gv("powershell",["-NoProfile","-NonInteractive","-Command",Jd(n,100,process.pid)],{stdio:"ignore",windowsHide:!0});o.on("error",()=>{});try{await te($p(n,e),Ym)}catch(i){throw i instanceof l&&/timed out/.test(i.message)?new l(`Windows Graphics Capture got no frame from the window in ${Ym/1e3} s.`,"The window may be hung or protected from capture. Try the default backend with the window in front."):i}finally{o.kill()}}import{join as au}from"node:path";import{readdirSync as s0}from"node:fs";import{runInNewContext as qv}from"node:vm";var Xv=[2,4],Jv=1e4;function Yv(t){return{script:n0,payload:JSON.stringify(t)}}async function Vm(t,e){if(process.platform!=="win32")throw new l("find_text uses the Windows OCR engine and runs on Windows only.");let{script:r,payload:n}=Yv(t),o=await ct(r,"text (OCR)",{timeoutMs:ur(t0+Math.max(0,t.length-2)*r0),payload:n,failure:"Could not run OCR"}),i;try{i=JSON.parse(o)}catch(a){throw new l(`Could not parse OCR output: ${z(a)}`)}return(Array.isArray(i)?i:[i]).map((a,c)=>Kv(a,e[c]??1))}function Kv(t,e){let r=t??{};if(r.error)throw/language|recognizer/i.test(r.error)?new l(`Windows OCR is unavailable: ${r.error}`,"Install an OCR language: Settings > Time & language > Language > (your language) > Options > Optical character recognition."):new l(`OCR failed: ${r.error}`);let n=[];for(let o of r.lines??[]){let i=(Array.isArray(o.words)?o.words:o.words?[o.words]:[]).map(s=>({text:String(s.text??""),x:Math.round((s.x??0)/e),y:Math.round((s.y??0)/e),width:Math.max(1,Math.round((s.width??0)/e)),height:Math.max(1,Math.round((s.height??0)/e))}));i.length!==0&&n.push({text:String(o.text??i.map(s=>s.text).join(" ")),words:i,...Qm(i)})}return n}function Qm(t){let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,width:n-e,height:o-r}}function Vv(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),n=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);return r<=0||n<=0?0:r*n/Math.min(t.width*t.height,e.width*e.height)}function Zm(t){let e=[];for(let r of t)for(let n of r){let o=e.findIndex(s=>Vv(s,n)>.5),i=e[o];i?n.text.length>i.text.length&&(e[o]=n):e.push(n)}return e.sort((r,n)=>r.y-n.y||r.x-n.x)}function Bt(t){return t.toLowerCase().replace(/[-_\s]+/g,"_").replace(/[l1|]/g,"i").replace(/0/g,"o")}var qr=500,Qv=1e3;function ef(t,e){return t.map(r=>{let n=new RegExp(e,"gi"),o=new Set,i=[];for(let s of[r,r.replace(/-/g,"_"),r.replace(/_/g,"-")])for(let a of s.matchAll(n)){let c=`${a.index}:${a[0].length}`;a[0].length>0&&!o.has(c)&&(o.add(c),i.push([a.index,a.index+a[0].length]))}return i})}var Zv=`JSON.stringify((${ef.toString()})(texts, query))`,tf=new Set;function su(t){return tf.add(t),t}function Tn(t,e,r=Qv){try{new RegExp(e,"gi")}catch(n){throw new l(`Invalid regex: ${z(n)}`)}if(tf.has(e))return ef(t,e);try{return JSON.parse(qv(Zv,{texts:t,query:e},{timeout:r}))}catch(n){throw n.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"?new l(`The regex took longer than ${r/1e3} s to run and was stopped.`,"Simplify it: nested quantifiers such as (a+)+ backtrack catastrophically."):n}}function St(t,e,r=!1){if(e.length>qr)throw new l(`The query is ${e.length} characters; at most ${qr} are allowed.`);let n=t.map(s=>{let a=[],c="";for(let u of s.words)c&&(c+=" "),a.push({start:c.length,end:c.length+u.text.length,word:u}),c+=u.text;return{line:s,spans:a,text:c}}),o=r?Tn(n.map(s=>s.text),e):null,i=[];return n.forEach(({line:s,spans:a},c)=>{let u=[];if(o)u=o[c]??[];else{let p=Bt(e);if(!p)return;let f=a.map(h=>Bt(h.word.text)).join("_"),m=0;for(let h=f.indexOf(p,m);h!==-1;h=f.indexOf(p,m))u.push(e0(a,h,h+p.length)),m=h+p.length}let d=new Set;for(let[p,f]of u){let m=a.filter(h=>h.start<f&&h.end>p).map(h=>h.word);m.length===0||m.every(h=>d.has(h))||(m.forEach(h=>d.add(h)),i.push({text:m.map(h=>h.text).join(" "),line:s.text,...Qm(m)}))}}),i}function e0(t,e,r){let n=0,o=-1,i=-1;for(let s of t){let a=Bt(s.word.text).length;if(o===-1&&e<n+a&&(o=s.start),r<=n+a+1){i=s.end;break}n+=a+1}return[o===-1?0:o,i===-1?t.at(-1)?.end??0:i]}function Ss(t,e,r=4){return t.map(n=>{let o=Math.max(0,n.x-r),i=Math.max(0,n.y-r);return{x:o,y:i,width:Math.min(e.width,n.x+n.width+r)-o,height:Math.min(e.height,n.y+n.height+r)-i}})}function rf(t,e){let r=Jv/Math.max(t,e),n=Xv.map(o=>Math.min(o,Math.floor(r*100)/100)).filter(o=>o>=1);return[...new Set(n.length?n:[Math.min(1,r)])]}var t0=6e4,r0=5e3,Km=2e4,n0=`
|
|
275
|
+
`}function Ss(t){return t.map(e=>({start:e.t,title:e.label}))}function Wm(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 Yv(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 jm(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:Yv(a.text)}),s=Math.max(s,a.end)}return i}var bs=8;function Um(t,e,r,n){let o=n.subtitles??[];if(o.length>bs)throw new l(`At most ${bs} 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 Kv(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:Bt(o),end:Bt(i),title:r.tags?.title??`Chapter ${n+1}`}]})}async function Qv(t,e){let{ffprobe:r}=k(),n=await ce(r,Kv(t),3e4,{signal:e});return n.code===0?Vv(n.stdout):[]}async function xr(t,e){let r=He(t);if(r.length>0)return{markers:r,from:"sidecar"};let n=await Qv(t,e);return n.length>0?{markers:n.map(o=>({t:o.start,label:o.title})),from:"chapters"}:{markers:[],from:null}}function Bo(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=it(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=Dm(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=ws(o.markers??[],s);t.update(e,{markers:a});let c=wr(o.outputPath),u;try{c=yr(o.outputPath,a,e)}catch(d){u=`Saved in the session, but the sidecar ${c} could not be written: ${j(d)}`}return{t:i,count:a.length,markersPath:c,live:o.status==="recording"||o.status==="paused",...u?{warning:u}:{}}}import{existsSync as Zv,readFileSync as e0}from"node:fs";import{dirname as zm,join as vs}from"node:path";import{fileURLToPath as t0}from"node:url";var Hm="@tmhs/screencast-mcp",ru=null,r0=null;function Gm(t){try{return JSON.parse(e0(t,"utf8"))}catch{return null}}function n0(t){for(let e=t;;){let r=vs(e,"package.json");if(Zv(r)&&Gm(r)?.name===Hm)return e;let n=zm(e);if(n===e)return null;e=n}}function nu(){if(ru)return ru;let t=n0(zm(t0(import.meta.url)));if(!t)throw new l(`Cannot find the ${Hm} package root (its package.json).`);return ru=t}function _t(){return r0??=Gm(vs(nu(),"package.json"))?.version??"0.0.0"}function Pn(...t){return vs(nu(),"assets",...t)}function qm(){return vs(nu(),"dist","wgcRecorder.js")}async function dt(t,e={}){let r=Ep(t);if(r.kind==="window"){let n=await Ad(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 mr()}:r.kind==="region"?(Rp(r,await mr()),{target:r,monitors:[]}):{target:r,monitors:await mr()}}var o0=["virtual-audio-capturer","stereo mix","what u hear","wave out mix","cable output","voicemeeter output"],Wo="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 i0(t){return Xm(t,"audio")}function s0(t){return Xm(t,"video")}function Xm(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 ou(t,e){if(e&&e.trim().length>0)return t.includes(e)?e:null;let r=n=>n.toLowerCase();return t.find(n=>o0.some(o=>r(n).includes(o)))??null}var a0=12e3,c0="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. "+Wo,$s=null,ks=null;async function iu(t=!1){return!t&&$s?$s:(await Ym(),$s??[])}async function su(t=!1){return!t&&ks?ks:(await Ym(),ks??[])}async function Jm(t){let e=await su();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 Ym(){let{ffmpeg:t}=k(),e;try{e=await ce(t,["-hide_banner","-list_devices","true","-f","dshow","-i","dummy"],a0)}catch(r){throw new l(`Could not enumerate audio devices (${j(r)}).`,c0)}$s=i0(e.stderr),ks=s0(e.stderr)}async function Km(t){let e=await iu(),r=ou(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}.`,Wo)}throw new l("No system-audio loopback device found.",Wo)}var jo="SCREENCAST_CONFIRM_CAPTURE",au=300*1e3;function Vm(t=process.env){let e=(t[jo]??"").trim().toLowerCase();return["1","true","yes","on","always"].includes(e)?"always":["0","false","no","off","never"].includes(e)?"off":"auto"}function Qm(t=process.env){return Vm(t)==="always"}function Wt(t,e){return e?`window "${e.matchedTitle}"`:t==="full"?"the full screen (all monitors)":t}async function jt(t,e,r){let n=Vm();if(n==="off")return;if(!t.server.getClientCapabilities()?.elicitation?.form){if(n==="auto")return;throw new l(`Capture blocked: ${jo} 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 ${jo}=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:au}))}catch(i){throw new l(`Capture blocked: the confirmation request failed (${j(i)}). Nothing was captured.`)}if(o!=="accept")throw new l(`Capture ${o==="decline"?"declined":"cancelled"} by the user. Nothing was captured.`)}var Es=null;function se(){return Es||(Es=new ds(xp()),Es.load()),Es}var uu=!1;function Zm(){uu=!0}function Rs(){return uu}var _s=0,cu=[];function ef(){if(uu)throw new l("The server is shutting down; the recording was not started.");_s++;let t=!1;return()=>{if(!t&&(t=!0,_s--,_s===0)){let e=cu;cu=[];for(let r of e)r()}}}function tf(t){return _s===0?Promise.resolve(!0):new Promise(e=>{let r=setTimeout(()=>e(!1),t);r.unref?.(),cu.push(()=>{clearTimeout(r),e(!0)})})}import{existsSync as e$,mkdirSync as t$,mkdtempSync as r$,rmSync as Eu,writeFileSync as Of}from"node:fs";import{tmpdir as n$}from"node:os";import{spawn as u0}from"node:child_process";var rf=15e3;async function Ut(t,e,r="gdigrab"){if(r==="gdigrab"){await te(Ni(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(!pr())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=u0("powershell",["-NoProfile","-NonInteractive","-Command",tm(n,100,process.pid)],{stdio:"ignore",windowsHide:!0});o.on("error",()=>{});try{await te(Ap(n,e),rf)}catch(i){throw i instanceof l&&/timed out/.test(i.message)?new l(`Windows Graphics Capture got no frame from the window in ${rf/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 pu}from"node:path";import{readdirSync as k0}from"node:fs";import{runInNewContext as l0}from"node:vm";var p0=[2,4],d0=1e4;function m0(t){return{script:S0,payload:JSON.stringify(t)}}async function of(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}=m0(t),o=await pt(r,"text (OCR)",{timeoutMs:dr(y0+Math.max(0,t.length-2)*x0),payload:n,failure:"Could not run OCR"}),i;try{i=JSON.parse(o)}catch(a){throw new l(`Could not parse OCR output: ${j(a)}`)}return(Array.isArray(i)?i:[i]).map((a,c)=>f0(a,e[c]??1))}function f0(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,...sf(i)})}return n}function sf(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 h0(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 af(t){let e=[];for(let r of t)for(let n of r){let o=e.findIndex(s=>h0(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 zt(t){return t.toLowerCase().replace(/[-_\s]+/g,"_").replace(/[l1|]/g,"i").replace(/0/g,"o")}var Qr=500,g0=1e3;function cf(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 b0=`JSON.stringify((${cf.toString()})(texts, query))`,uf=new Set;function lu(t){return uf.add(t),t}function In(t,e,r=g0){try{new RegExp(e,"gi")}catch(n){throw new l(`Invalid regex: ${j(n)}`)}if(uf.has(e))return cf(t,e);try{return JSON.parse(l0(b0,{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 Rt(t,e,r=!1){if(e.length>Qr)throw new l(`The query is ${e.length} characters; at most ${Qr} are allowed.`);let n=t.map(s=>{let a=[],c="";for(let u of s.words)c&&(c+=" "),a.push({start:c.length,end:c.length+u.text.length,word:u}),c+=u.text;return{line:s,spans:a,text:c}}),o=r?In(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=zt(e);if(!p)return;let f=a.map(h=>zt(h.word.text)).join("_"),m=0;for(let h=f.indexOf(p,m);h!==-1;h=f.indexOf(p,m))u.push(w0(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,...sf(m)}))}}),i}function w0(t,e,r){let n=0,o=-1,i=-1;for(let s of t){let a=zt(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 Ts(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 lf(t,e){let r=d0/Math.max(t,e),n=p0.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 y0=6e4,x0=5e3,nf=2e4,S0=`
|
|
276
276
|
$ErrorActionPreference = 'Stop'
|
|
277
277
|
Add-Type -AssemblyName System.Runtime.WindowsRuntime
|
|
278
278
|
$null = [Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime]
|
|
279
279
|
$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
|
|
280
280
|
$null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime]
|
|
281
281
|
$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
|
|
282
|
-
function Await($op, [Type]$t) { $task = $asTask.MakeGenericMethod($t).Invoke($null, @($op)); if (-not $task.Wait(${
|
|
282
|
+
function Await($op, [Type]$t) { $task = $asTask.MakeGenericMethod($t).Invoke($null, @($op)); if (-not $task.Wait(${nf})) { throw "The OCR engine did not answer within ${nf/1e3} s." }; $task.Result }
|
|
283
283
|
$paths = $Payload | ConvertFrom-Json
|
|
284
284
|
$engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
|
|
285
285
|
$out = foreach ($p in $paths) {
|
|
@@ -297,48 +297,48 @@ $out = foreach ($p in $paths) {
|
|
|
297
297
|
} catch { [pscustomobject]@{ error = $_.Exception.Message } }
|
|
298
298
|
}
|
|
299
299
|
ConvertTo-Json -InputObject @($out) -Depth 6 -Compress
|
|
300
|
-
`;import{availableParallelism as
|
|
300
|
+
`;import{availableParallelism as v0}from"node:os";function $0(t=v0()){return Math.min(4,Math.max(2,Math.floor(t/4)))}async function Je(t,e,r=$0()){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 E0(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 mt(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 Je(t,async m=>({source:m,...i??await o(m)})),c=(await Je(s,async({source:m,width:h,height:b},w)=>{let g=lf(h,b),y=g.map((v,x)=>pu(e,`pass${w}-${x}.png`));return await te(E0(m,g,y),6e4,{signal:r}),g.map((v,x)=>({out:y[x],scale:v,f:w}))})).flat(),u=c.map(m=>m.out),d=c.map(m=>m.scale),p=c.map(m=>m.f),f=await of(u,d);return s.map(({width:m,height:h},b)=>({lines:af(f.filter((w,g)=>p[g]===b)),width:m,height:h}))}async function Fn(t,e,r,n){let o=await L(t),i=o.videoDurationSec??o.durationSec,s=e.range?e.range.duration:i,a=Wi(s,1/e.everySec,e.maxFrames);await te(ji(t,a.fps,pu(r,"scan_%05d.png"),e.maxFrames,!1,e.range),de(o.durationSec),{signal:n});let c=k0(r).filter(m=>m.startsWith("scan_")).sort().map(m=>pu(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 mt(c,r,n,{sameSize:!0})).map((m,h)=>({...m,t:d(h),path:c[h]??""})),step:u,end:p,clamped:a.clamped}}function _0(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 Sr(t,e,r,n="match"){let o=[],i=[];for(let s of t.frames){let a=Rt(s.lines,e,r),c=_0(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 Ts(u,s))i.push({...d,...c})}return{matches:o,redactRegions:i}}var Ht=30,Ms=120;var du=600,pf=24*3600,As=1500,mu=3,df=30,fu=5,mf=50,On=new Map;function Cs(t){return t.startsWith("arm-")}function R0(){return`arm-${be()}-${we(6)}`}function Uo(t){let e=On.get(t)?.arm;return e?{...e}:void 0}function ff(){return[...On.values()].map(t=>({...t.arm}))}function hu(t){let e=On.get(t);return!e||e.arm.status!=="armed"?!1:(e.abort.abort(),e.arm.status="cancelled",!0)}async function hf(t){return await On.get(t)?.done,Uo(t)}function gf(){for(let t of On.keys())hu(t)}function gu(t){return[...t.window?[`${t.window.replace(/^window:/,"the window ")} exists`]:[],...t.text?[`"${t.text}" is on screen`]:[]].join(" and ")}async function Ps(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)}}async function bf(t){let e=t.sleep??(o=>new Promise(i=>setTimeout(i,o))),r=o=>Ps({checks:[o],timeoutMs:Number.POSITIVE_INFINITY,intervalMs:t.intervalMs,signal:t.signal,sleep:e}),n=0;for(;n<t.max&&!(await r(t.seen)!=="met"||(await e(t.postRollMs),t.signal.aborted)||(n++,!await t.act())||n<t.max&&await r(async()=>!await t.seen().catch(()=>!1))!=="met"););return n}function wf(t){let e={id:R0(),status:"armed",conditions:t.conditions,target:t.target,armedAt:new Date().toISOString(),timeoutSec:t.timeoutSec},r=new AbortController,n={arm:e,abort:r};return On.set(e.id,n),n.done=(async()=>{let o=await Ps({checks:t.checks,timeoutMs:t.timeoutSec*1e3,intervalMs:t.intervalMs??As,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 T0,stat as yf}from"node:fs/promises";import{basename as M0}from"node:path";var xf=5,bu=5e4,wu=2e3,A0=250,C0=1<<20;function P0(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 I0(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 F0=t=>t.length>wu?`${t.slice(0,wu-1)}\u2026`:t;function Sf(t,e){let r=[];for(let n of t){if(!n.line.trim())continue;let o=e.spans?.length?wo(n.epochMs,e.spans):(n.epochMs-e.startMs)/1e3;if(o===null||o<0||o>e.endSec)continue;let i=I0(n.line);r.push({t:Math.round(o*1e3)/1e3,source:n.source,line:F0(n.line),...i?{level:i}:{}})}return r.slice(-bu)}function vf(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
301
301
|
`)+(t.length?`
|
|
302
|
-
`:"")}function
|
|
302
|
+
`:"")}function Fs(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function ft(t){return t.replace(/\.[^./\\]+$/,"")+".logs.jsonl"}var Is=class{constructor(e,r=Date.now){this.now=r;this.files=e.map(n=>({path:n.path,label:n.label??M0(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 yf(e.path);e.pos=r.size,e.ino=r.ino}catch{}}follow(e=A0){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 yf(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,C0),o;try{o=await T0(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}=P0(e.partial,i.subarray(0,s));e.partial=c.length>wu*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>bu*2&&(this.lines=this.lines.slice(-bu))}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 O0}from"node:child_process";import{cpus as $f,freemem as N0,totalmem as D0}from"node:os";var L0=1e3,yu=90;function B0(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 W0(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 j0(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 kf(t,e){let r=[];for(let{epochMs:n,...o}of t){let i=e.spans?.length?wo(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 Nn(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)>=yu?(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 Ef(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
303
303
|
`)+(t.length?`
|
|
304
|
-
`:"")}function
|
|
305
|
-
${s.message}`}),{head:()=>r,tail:()=>n,outputAt:()=>o}}function
|
|
304
|
+
`:"")}function Dn(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function st(t){return t.replace(/\.[^./\\]+$/,"")+".perf.jsonl"}function U0(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 Os=class{constructor(e,r=L0){this.pid=e;this.intervalMs=r}pid;intervalMs;samples=[];timer=null;child=null;proc={};start(){let e=$f(),r=e.length||1;if(this.pid!==void 0){this.child=O0("powershell",["-NoProfile","-NonInteractive","-Command",U0(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=W0(a);c&&(n&&(this.proc={cpu:j0(n,c,r),rssMB:Math.round(c.rss/1048576)}),n=c)}})}this.timer=setInterval(()=>{let n=$f(),o=D0();this.samples.push({epochMs:Date.now(),sysCpu:B0(e,n),sysMem:o>0?Math.round((o-N0())/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 z0}from"node:child_process";import{mkdirSync as H0,rmSync as _f}from"node:fs";function xu(t,e){let r="",n="",o=null,i=new qi(()=>({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 zo(t,e=6){return t.tail().trim().split(`
|
|
306
306
|
`).slice(-e).join(`
|
|
307
|
-
`)}function
|
|
308
|
-
${
|
|
309
|
-
`)}):
|
|
310
|
-
`)})})}async function
|
|
311
|
-
${
|
|
312
|
-
`)}))}function
|
|
313
|
-
`))}function
|
|
314
|
-
`)}}}}function
|
|
315
|
-
${
|
|
316
|
-
(Retried with libx264 after ${q})`:""));i.child=$;let{startMs:ee,frame:ie,record:_}=q0(r,s,{id:C,child:$,watch:J,spawnedAt:N,captureOpts:le,webcam:X,encoder:Q.encoder,evPaths:H,keyMode:M,webcamRaw:i.webcamRaw}),P=oe();X0(P,_,$),i.handOff();let re=i.logger;return re&&H&&B0(P,C,{logger:re,evPaths:H,keyMode:M,startMs:ee,frame:ie,replay:m,child:$}),yu(P,C,$,{backend:f,maxDurationSec:w,spawnedAt:N,watch:J}),r.perf&&W0(P,C,{output:g,startMs:ee,window:p}),G&&r.logs&&j0(P,C,{tailer:G,logs:r.logs,output:g,startMs:ee}),r.hotkeys&&(L=U0(P,C)),r.stopWhen&&z0(P,C,{target:r.target,exactTitle:r.exactTitle,text:r.stopWhen.text}),S(Td({record:_,audioDevice:y?.device,maxDurationSec:w,encoder:Q.encoder,encoderNote:Q.note,...x?{gpuFrames:Q.gpuFrames}:{},webcamDevice:v,window:p,...H?{events:{jsonl:H.jsonl,keys:M}}:{},...r.logs?{logs:{path:jt(g),missing:r.logs.some(D=>!M0(D.path))}}:{},...r.hotkeys?{hotkeys:{taken:re?cp(re):[]}}:{},...m?{replay:{...m,events:!!H}}:{}}))}catch(s){return await i.release(),E(s)}finally{o()}})}import{z as Pn}from"zod";import{existsSync as Ts}from"node:fs";function Ef(t){return{saved:t.saved,discarded:t.discarded,...t.save?{durationSec:t.save.durationSec,eventsPath:t.save.eventsPath}:{},...t.error?{error:t.error,note:"The buffer was kept; call stop_recording with save: true again, or save_replay."}:{}}}async function J0(t,e){if(t.error||!Ts(t.path))return{error:t.error??`No webcam file was written (${t.path}).`};let r=async a=>{try{let c=await W(a);return c.width&&c.height?{width:c.width,height:c.height}:null}catch{return null}},[n,o]=await Promise.all([r(e),r(t.path)]),i=t.shape==="circle",s=n&&o?bd(n,i?{width:1,height:1}:o,t.corner,t.size):null;return{path:t.path,...s?{overlay:{input:e,overlay:t.path,x:s.x,y:s.y,...i?{height:s.height,shape:"circle"}:{width:s.width}},note:"Aligned with the recording: pass `overlay` to the overlay tool (any corner or size works)."}:{}}}var Y0={sessionId:Pn.string().min(1).describe("Session id returned by start_recording."),save:Pn.boolean().optional().describe("Replay buffer: write it all to outputPath first (default: discard).")};function _f(t){t.registerTool("stop_recording",{title:"Stop Recording",description:"Stop a recording gracefully so the file is finalized; returns the path and duration.",inputSchema:Y0,outputSchema:B({sessionId:Pn.string(),status:Pn.string(),outputPath:Pn.string(),durationSec:Pn.number().nullable()}),annotations:qi},async e=>{try{let r=oe(),n=e.sessionId;if($s(n)){let f=Io(n);if(!f)throw new l(`No armed recording with id "${n}".`);f.status==="starting"&&(f=await sf(n)??f);let m={sessionId:n,outputPath:"",durationSec:null};if(lu(n))return S({...m,status:"cancelled",note:"Disarmed; nothing was recorded."});if(!f.sessionId)return S({...m,status:f.status,...f.error?{error:f.error}:{}});n=f.sessionId}let o=r.get(n);if(!o)throw new l(`No session with id "${e.sessionId}".`);if(o.status!=="recording"&&o.status!=="paused"){let f=o.replay&&Ts(o.replay.dir)?await Vi(o.replay,{save:e.save??!1,output:o.outputPath,quality:o.quality,tools:k}):void 0,m=o.durationSec??null;return m===null&&!o.segments?.parts.length&&Ts(o.outputPath)&&(m=await ue(o.outputPath,{ffprobe:k().ffprobe}).catch(()=>null),m!==null&&r.tryUpdate(o.id,{durationSec:m})),S({...f?{replay:Ef(f)}:{},sessionId:o.id,status:o.status,outputPath:o.outputPath,durationSec:m,endReason:o.endReason??null,note:o.endReason==="max_duration"?`Recording already ended at its maxDurationSec cap (${o.maxDurationSec}s).`:o.endReason==="window_closed"?"Recording already ended: the recorded window was closed.":"Session was not active; returning its recorded final state."})}let i=lm(o,process.pid,qc(o));if(i)throw new l(i);let{ffprobe:s}=k(),{record:a,graceful:c,durationSec:u,replay:d,segments:p}=await Ro(r,o,{reason:"stopped",probe:f=>ue(f,{ffprobe:s}),saveReplay:e.save});return S({sessionId:o.id,status:"stopped",outputPath:o.outputPath,durationSec:u??null,finalizedGracefully:c,...d?{replay:Ef(d)}:{},...p&&p.count>1?{segmentsJoined:p.count}:{},...p?.error?{segmentsError:p.error}:{},...a?.webcam?{webcam:await J0(a.webcam,o.outputPath)}:{},...a?.events?{eventsPath:a.events.path,events:a.events.summary??{},...a.events.error?{eventsError:a.events.error}:{}}:{},fileExists:Ts(o.outputPath),note:c?"ffmpeg quit cleanly; file finalized.":"Process terminated by pid; fragmented mp4 keeps the file playable.",record:a})}catch(r){return E(r)}})}import{z as yr}from"zod";import{existsSync as Uo,lstatSync as ph,readdirSync as dh,rmSync as H$,statSync as G$}from"node:fs";import{dirname as q$,resolve as mh}from"node:path";import{createHash as Hf}from"node:crypto";import{closeSync as E$,existsSync as In,openSync as _$,readFileSync as T$,readdirSync as R$,readSync as A$,renameSync as M$,statSync as Gf,writeFileSync as C$}from"node:fs";import{basename as qf,dirname as P$,join as Fn,resolve as Ds}from"node:path";import{closeSync as r$,existsSync as Eu,openSync as n$,readSync as o$,statSync as i$}from"node:fs";import{basename as As,isAbsolute as s$,join as _u}from"node:path";function $t(t,e,r){if(t.length<e)throw new Error(`Truncated font: ${r}.`);return t}function K0(t,e){let r=$t(t(0,12),12,"header");if(r.toString("latin1",0,4)!=="ttcf"){if(e!==0)throw new Error("Not a font collection; only face 0 exists.");return 0}let n=r.readUInt32BE(8);if(e<0||e>=n)throw new Error(`Face ${e} is out of range (collection has ${n}).`);return $t(t(12+e*4,4),4,"collection offsets").readUInt32BE(0)}var Rs=class{ranges=[];add(e,r){let n=this.ranges[this.ranges.length-1];n&&e<=n[1]+1?n[1]=Math.max(n[1],r):this.ranges.push([e,r])}};function V0(t){let e=$t(t,14,"cmap format 4").readUInt16BE(6),r=14,n=r+e+2,o=n+e,i=o+e;$t(t,i+e,"cmap format 4 segments");let s=new Rs;for(let a=0;a<e/2;a++){let c=t.readUInt16BE(r+a*2),u=t.readUInt16BE(n+a*2),d=t.readUInt16BE(o+a*2),p=t.readUInt16BE(i+a*2);if(!(u>c))for(let f=u;f<=c&&f!==65535;f++){let m;if(p===0)m=f+d&65535;else{let h=i+a*2+p+(f-u)*2;m=h+2<=t.length?t.readUInt16BE(h):0,m!==0&&(m=m+d&65535)}m!==0&&s.add(f,f)}}return s.ranges}function Q0(t,e){let r=$t(t,16,`cmap format ${e}`).readUInt32BE(12);$t(t,16+r*12,`cmap format ${e} groups`);let n=[];for(let i=0;i<r;i++){let s=t.readUInt32BE(16+i*12),a=Math.min(t.readUInt32BE(20+i*12),1114111);if(t.readUInt32BE(24+i*12)===0){if(e===13)continue;s++}s<=a&&n.push([s,a])}n.sort((i,s)=>i[0]-s[0]);let o=new Rs;for(let[i,s]of n)o.add(i,s);return o.ranges}function Z0(t,e){return t===3&&e===10?0:t===0&&(e===4||e===6)?1:t===3&&e===1?2:t===0&&e<=3?3:-1}function Tf(t,e=0){let r=K0(t,e),n=$t(t(r,12),12,"sfnt header"),o=n.toString("latin1",0,4);if(o!=="\0\0\0"&&o!=="OTTO"&&o!=="true")throw new Error("Not a TrueType/OpenType font.");let i=n.readUInt16BE(4),s=$t(t(r+12,i*16),i*16,"table directory"),a=-1;for(let f=0;f<i;f++)s.toString("latin1",f*16,f*16+4)==="cmap"&&(a=s.readUInt32BE(f*16+8));if(a<0)throw new Error("Font has no cmap table.");let u=$t(t(a,4),4,"cmap header").readUInt16BE(2),d=$t(t(a+4,u*8),u*8,"cmap records"),p=[];for(let f=0;f<u;f++){let m=Z0(d.readUInt16BE(f*8),d.readUInt16BE(f*8+2));m>=0&&p.push({rank:m,offset:a+d.readUInt32BE(f*8+4)})}p.sort((f,m)=>f.rank-m.rank);for(let{offset:f}of p){let m=t(f,8);if(m.length<8)continue;let h=m.readUInt16BE(0);if(h===4)return V0(t(f,m.readUInt16BE(2)));if(h===12||h===13)return Q0(t(f,m.readUInt32BE(4)),h)}throw new Error("Font has no Unicode cmap subtable this reader understands (formats 4, 12, 13).")}function e$(t,e){let r=0,n=t.length-1;for(;r<=n;){let o=r+n>>1,[i,s]=t[o];if(e<i)n=o-1;else if(e>s)r=o+1;else return!0}return!1}function t$(t){return!(t<32||t>=127&&t<160||t===173||t===847||t===1564||t===65279||t>=8203&&t<=8207||t>=8234&&t<=8238||t>=8288&&t<=8303||t>=65024&&t<=65039||t>=917504&&t<=921599)}function Oo(t,e){let r=new Set,n=[];for(let o of t){let i=o.codePointAt(0);r.has(i)||(r.add(i),t$(i)&&!e$(e,i)&&n.push(o))}return n}var a$={regular:"Inter-Regular.ttf",bold:"Inter-Bold.ttf"};function Ut(t="bold"){return _n("fonts",a$[t])}function ye(t){return t.replace(/\\/g,"/").replace(/:/g,"\\\\:").replace(/'/g,"\\\\\\'").replace(/([,;[\]])/g,"\\$1")}var c$={segoe:{name:"Segoe UI",regular:["segoeui.ttf"],bold:["segoeuib.ttf","segoeui.ttf"]},japanese:{name:"Yu Gothic",regular:["YuGothM.ttc","meiryo.ttc","msgothic.ttc"],bold:["YuGothB.ttc","meiryob.ttc","YuGothM.ttc","msgothic.ttc"]},chineseSimplified:{name:"Microsoft YaHei",regular:["msyh.ttc","simsun.ttc"],bold:["msyhbd.ttc","msyh.ttc","simsun.ttc"]},chineseTraditional:{name:"Microsoft JhengHei",regular:["msjh.ttc","mingliub.ttc"],bold:["msjhbd.ttc","msjh.ttc"]},korean:{name:"Malgun Gothic",regular:["malgun.ttf"],bold:["malgunbd.ttf","malgun.ttf"]},indic:{name:"Nirmala UI",regular:["Nirmala.ttc","Nirmala.ttf"],bold:["NirmalaB.ttf","Nirmala.ttc","Nirmala.ttf"]},thai:{name:"Leelawadee UI",regular:["LeelawUI.ttf","tahoma.ttf"],bold:["LeelaUIb.ttf","LeelawUI.ttf","tahomabd.ttf"]},ethiopic:{name:"Ebrima",regular:["ebrima.ttf"],bold:["ebrimabd.ttf","ebrima.ttf"]},emoji:{name:"Segoe UI Emoji",regular:["seguiemj.ttf"],bold:["seguiemj.ttf"]},symbol:{name:"Segoe UI Symbol",regular:["seguisym.ttf"],bold:["seguisym.ttf"]}},u$=["segoe","japanese","chineseSimplified","chineseTraditional","korean","indic","thai","ethiopic","emoji","symbol"];function l$(t){let e=[];return/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9f]/u.test(t)&&e.push("japanese"),/[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]/u.test(t)&&e.push("korean"),new RegExp("\\p{Script=Han}","u").test(t)&&e.push("chineseSimplified"),[...e,...u$.filter(r=>!e.includes(r))].map(r=>c$[r])}function p$(t,e){let r=null;for(let n of e){let o=Oo(t,n.coverage);if(o.length===0)return{fontFile:n.path,missing:o};(!r||o.length<r.missing.length)&&(r={fontFile:n.path,missing:o})}return r}function Af(){return _u(process.env.WINDIR??process.env.SystemRoot??"C:\\Windows","Fonts")}var Rf=new Map;function $u(t){let e=Rf.get(t);if(e!==void 0)return e;let r,n=null;try{n=n$(t,"r");let o=n;r=Tf((s,a)=>{let c=Buffer.alloc(a);return c.subarray(0,o$(o,c,0,a,s))})}catch{r=null}finally{n!==null&&r$(n)}return Rf.set(t,r),r}function d$(t){if(Eu(t)&&i$(t).isFile())return t;if(!s$(t)&&As(t)===t){let e=_u(Af(),t);if(Eu(e))return e}throw new l(`Font file not found: ${t}`,"Pass a path to a .ttf, .otf or .ttc file, or the file name of a font in C:\\Windows\\Fonts.")}function ku(t){let e=t.replace(/\s+/g," ").trim();return`"${e.length>40?`${e.slice(0,39)}\u2026`:e}"`}function kt(t,e={}){if(e.fontFile){let c=d$(e.fontFile),u=$u(c);if(!u)return{fontFile:c,missing:[],fallback:!1,warning:`Could not read the character map of ${As(c)}; glyph coverage of ${ku(t)} was not checked.`};let d=Oo(t,u);return d.length===0?{fontFile:c,missing:d,fallback:!1}:{fontFile:c,missing:d,fallback:!1,warning:`${As(c)} has no glyph for ${d.join(" ")} in ${ku(t)}; they render as empty boxes.`}}let r=e.weight??"bold",n=Ut(r),o=$u(n);if(o&&Oo(t,o).length===0)return{fontFile:n,missing:[],fallback:!1};let i=e.fontsDir??Af(),s=o?[{path:n,coverage:o}]:[];for(let c of l$(t))for(let u of c[r]){let d=_u(i,u),p=Eu(d)?$u(d):null;if(p){if(Oo(t,p).length===0)return{fontFile:d,missing:[],fallback:!0};s.push({path:d,coverage:p});break}}let a=p$(t,s)??{fontFile:n,missing:[]};return a.missing.length===0?{...a,fallback:a.fontFile!==n}:{...a,fallback:a.fontFile!==n,warning:`No available font draws ${a.missing.join(" ")} in ${ku(t)}; they render as empty boxes (drawn with ${As(a.fontFile)}). Pass fontFile with a font that covers them.`}}import{mkdtempSync as m$,rmSync as f$,writeFileSync as h$}from"node:fs";import{join as Tu}from"node:path";import{tmpdir as g$}from"node:os";var No=12,Mf=48,Do=320;function Ms(t,e){if(!(t>0))throw new l("Could not read the video's duration.");return Array.from({length:e},(r,n)=>Math.round((n+.5)*t/e*1e3)/1e3)}function Ne(t){let e=Math.round(Math.max(0,t)*10),r=Math.floor(e/36e3),n=Math.floor(e%36e3/600),o=e%600/10;return r>0?`${r}:${String(n).padStart(2,"0")}:${String(Math.floor(o)).padStart(2,"0")}`:`${n}:${o.toFixed(1).padStart(4,"0")}`}function b$(t,e){let r=t<=4?t:Math.ceil(Math.sqrt(t)),n=Math.max(1,Math.min(t,e??r));return{columns:n,rows:Math.ceil(t/n)}}function w$(t,e,r,n,o,i){if(!Number.isInteger(n)||n<64)throw new l("tileWidth must be an integer of at least 64.");let s=Math.max(12,Math.round(n/16)),a=`drawtext=fontfile=${ye(o)}:textfile=${ye(i)}:expansion=none:fontcolor=white:fontsize=${s}:x=6:y=h-text_h-6:box=1:boxcolor=black@0.6:boxborderw=4`;return["-y","-v","error","-ss",String(e),"-i",t,"-frames:v","1","-vf",`scale=${n}:-2,${a}`,...Te(r)]}function y$(t,e,r){return["-y","-v","error","-framerate","1","-i",t,"-vf",`tile=${e.columns}x${e.rows}:padding=4:margin=4:color=black`,"-frames:v","1",...Te(r)]}function Cf(t,e,r,n){if(!(e>0))throw new l("Could not read the video's duration.");let o=30,i=Math.max(1e-4,o/e);return["-y","-v","error","-i",t,"-vf",`fps=${i.toFixed(4)},thumbnail=${o},scale='min(${n},iw)':-2`,"-frames:v","1",...Te(r)]}async function Cs(t,e,r,n,o){let i=b$(e.length,n.columns),s=m$(Tu(g$(),"screencast-sheet-"));try{let a=Ut("bold");await qe(e,async(c,u)=>{let d=Tu(s,`label_${u}.txt`);h$(d,Ne(c));let p=Tu(s,`tile_${String(u).padStart(3,"0")}.png`);await te(w$(t,c,p,n.tileWidth,a,d),6e4,{signal:o})}),await te(y$(mn(s,"tile_%03d.png"),i,r),6e4,{signal:o})}finally{f$(s,{recursive:!0,force:!0})}return i}import{existsSync as Ps}from"node:fs";var Pf=t=>Math.round(t*1e3)/1e3,x$={input_not_seen:"input went to an elevated window or the lock screen, or the hook was removed",helper_stalled:"the event logger paused",helper_stopped:"the event logger stopped"};function Ru(t){return t.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Au(t){let e=Ru(t.role),r=t.app?` in ${t.app}`:"";return t.name?`the "${t.name}" ${e}${r}`:`${/^[aeiou]/.test(e)?"an":"a"} ${e}${r}`}function If(t,e,r){let n=e?"double-click":"click",o=t&&t!=="left"?`${t.charAt(0).toUpperCase()}${t.slice(1)} ${n}`:`${n.charAt(0).toUpperCase()}${n.slice(1)}`;return r.element?.name?`${o} ${Au(r.element)}`:r.inFrame?`${o} at (${r.x}, ${r.y})`:`${o} outside the recorded area`}function Mu(t){let e=[],r=[...t].sort((s,a)=>s.t-a.t),n=null,o=null,i=(s,a)=>{let c=s==="vertical"?a>=0?"up":"down":a>=0?"right":"left",u=Math.abs(a);return`Scroll ${c} ${u} notch${u===1?"":"es"}`};for(let s of r)if(!(s.type==="move"||s.type==="up")){if(s.type!=="wheel"&&(o=null),s.type==="down"){let a=n;if(a&&a.e.button===s.button&&s.t-a.e.t<=.5&&Math.abs(s.x-a.e.x)<=6&&Math.abs(s.y-a.e.y)<=6&&a.step.action==="click"&&e.at(-1)===a.step){a.step.action="double_click",a.step.text=If(s.button,!0,a.e),n=null;continue}let c={t:s.t,action:"click",text:If(s.button,!1,s),x:s.x,y:s.y,button:s.button??"left",inFrame:s.inFrame,...s.element?{element:s.element}:{}};e.push(c),n={e:s,step:c};continue}if(n=null,s.type==="wheel"){let a=s.axis??"vertical",c=s.delta??0;if(o&&o.axis===a&&s.t-o.last<=1&&Math.sign(c)===Math.sign(o.notches)){o.notches+=c,o.last=s.t,o.step.text=i(a,o.notches);continue}let u={t:s.t,action:"scroll",text:i(a,c),x:s.x,y:s.y,inFrame:s.inFrame};e.push(u),o={step:u,axis:a,notches:c,last:s.t}}else if(s.type==="key")e.push({t:s.t,action:"shortcut",text:`Press ${s.keys??"a shortcut"}`,...s.keys?{keys:s.keys}:{}});else if(s.type==="typing"){let a=s.durationSec??0;e.push({t:s.t,action:"typing",text:`Type${a>0?` for ${Pf(a)} s`:""} (keys are not logged)`,durationSec:a})}else if(s.type==="focus"){let a=s.app??"another app";e.push({t:s.t,action:"switch",text:s.title?`Switch to "${s.title}" (${a})`:`Switch to ${a}`})}else if(s.type==="gap"){let a=x$[s.reason??"input_not_seen"],c=Pf(s.durationSec??0);e.push({t:s.t,action:"gap",text:`Input may be missing for ${c} s (${a})`,durationSec:c})}}return e}function Cu(t){return Mu(t).map(({button:e,inFrame:r,keys:n,durationSec:o,element:i,...s})=>s)}var Pu=30,Is=600,Iu=1,Fs=100,Fu=20,De=su(["\\b(?:sk|pk|rk)-[a-z0-9_-]{8,}","\\bgh[pousr]_[a-z0-9]{10,}","\\bgithub_pat_[a-z0-9_]{10,}","\\bxox[abprs]-[a-z0-9-]{8,}","\\bAKIA[0-9A-Z]{12,}","\\bAIza[0-9a-z_-]{20,}","\\beyJ[a-z0-9_-]{8,}\\.[a-z0-9_-]{8,}","(?:api.?key|secret|token|passw(?:or)?d|bearer|authorization)\\s*[:=]?\\s*\\S+"].join("|")),Os=su("error|exception|fail(?:ed|ure)?|fatal|crash|denied|refused|not found|cannot|can't|unable|invalid|timed? ?out|traceback|panic|unhandled|warning"),zt={markdown:"report.md",json:"report.json",clip:"clip.mp4",contactSheet:"contact-sheet.png",gif:t=>`repro.${t}`},Lo=t=>Math.round(t*1e3)/1e3;function Of(t,e={}){if(!(t>0))throw new l("Could not read the recording's duration.");let r=Math.min(e.end??t,t),n=e.clipSec??Pu,o=e.start??Math.max(0,r-n);if(o>=t)throw new l(`start ${o}s is past the end of the ${Lo(t)}s recording.`);if(!(r>o))throw new l("end must be after start.");if(r-o>Is)throw new l(`The clip would be ${Lo(r-o)}s; at most ${Is}s. Narrow start/end.`);return{start:Lo(o),end:Lo(r)}}function S$(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),n=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);return r<=0||n<=0?!1:r*n>=.5*Math.min(t.width*t.height,e.width*e.height)}function Nf(t){let e=[];for(let r of[...t].sort((n,o)=>n.start-o.start)){let n=e.find(s=>r.start<=s.end&&S$(s,r));if(!n){e.push({...r});continue}let o=Math.min(n.x,r.x),i=Math.min(n.y,r.y);n.width=Math.max(n.x+n.width,r.x+r.width)-o,n.height=Math.max(n.y+n.height,r.y+r.height)-i,n.x=o,n.y=i,n.start=Math.min(n.start,r.start),n.end=Math.max(n.end,r.end)}return e}var v$="[REDACTED]";function Le(t,e){if(t.length===0)return[];let r=Tn(t,e);return t.map((n,o)=>{let i=[...r[o]??[]].sort((c,u)=>c[0]-u[0]),s="",a=0;for(let[c,u]of i)u<=a||(s+=n.slice(a,Math.max(a,c))+(c>=a?v$:""),a=u);return s+n.slice(a)})}function Df(t,e,r){let n=new Map;for(let a of t){let c=new Set(St(a.lines,e,!0).map(u=>u.line));for(let u of c){let d=Bt(u),p=n.get(d);p?p.lastSeen=a.t:n.set(d,{text:u,firstSeen:a.t,lastSeen:a.t})}}let o=t.at(-1)?.t,i=[...n.values()].sort((a,c)=>+(c.lastSeen===o)-+(a.lastSeen===o)||a.firstSeen-c.firstSeen).slice(0,Fu);if(!r)return i;let s=Le(i.map(a=>a.text),r);return i.map((a,c)=>({...a,text:s[c]??a.text}))}var $$=t=>`\`${t.replace(/`/g,"'").replace(/\s+/g," ").trim()}\``,Ff=t=>t.replace(/\|/g,"\\|").replace(/\s*\n\s*/g," ");function Lf(t){let e=[`# ${t.title.replace(/\s*\n\s*/g," ")}`,""],r=`${Ne(t.clip.start)}-${Ne(t.clip.end)}`;if(e.push(`Recorded repro: ${t.clip.width}x${t.clip.height}, clip ${r} of a ${Ne(t.clip.recordingDurationSec)} recording.`,""),(t.actual||t.expected)&&(t.actual&&e.push("**Actual:** "+t.actual.trim(),""),t.expected&&e.push("**Expected:** "+t.expected.trim(),"")),e.push("## Steps to reproduce",""),t.steps.length===0?e.push(`_${t.stepsNote??"No input events in the recording."} Add the steps by hand._`,""):(e.push("From the recording's input event log; times are on the recording's clock, positions in video pixels.",""),t.steps.forEach((i,s)=>e.push(`${s+1}. \`${Ne(i.t)}\` ${i.text}`)),t.stepsOmitted&&e.push("",`_${t.stepsOmitted} more steps not shown (see report.json)._`),e.push("")),e.push("## Error text on screen",""),t.ocr!=="read")e.push("_Not read: Windows OCR is unavailable here._","");else if(t.errors.length===0)e.push("_None found by OCR in the clip._","");else{e.push("Read by OCR (best-effort, may contain misreads); times from the clip start.","");for(let i of t.errors){let s=i.firstSeen===i.lastSeen?Ne(i.firstSeen):`${Ne(i.firstSeen)}-${Ne(i.lastSeen)}`;e.push(`- \`${s}\` ${$$(i.text)}`)}e.push("")}if(t.perf&&t.perf.length>0&&e.push("## Resource usage","",...t.perf.map(i=>`- ${i}`),""),t.logs)if(e.push("## App logs",""),t.logs.length===0)e.push("_No log lines during the clip._","");else{e.push("Lines the app logged during the clip (and the 5 s before it); times from the clip start.","","```text");for(let i of t.logs)e.push(`${i.t<0?"-":""}${Ne(Math.abs(i.t))} [${i.source}] ${i.line.replace(/\x60{3}/g,"'''")}`);e.push("```","")}if(e.push("## Recording",""),t.files.gif&&e.push("<!-- GitHub does not upload local files from --body-file: drag the GIF and clip into the issue, or replace these links with the uploaded URLs. -->",``,""),e.push(`- Clip: [${t.files.clip}](${t.files.clip}) (${Lo(t.clip.end-t.clip.start)} s)`),t.files.gif&&t.gif){let i=(t.gif.sizeBytes/1e6).toFixed(1);e.push(`- ${t.gif.format==="gif"?"GIF":"WebP"}: [${t.files.gif}](${t.files.gif}) (${i} MB${t.gif.withinBudget?"":", over the size budget"})`)}t.files.contactSheet&&e.push(`- Contact sheet: [${t.files.contactSheet}](${t.files.contactSheet})`),e.push(""),e.push("## Environment","","| | |","|---|---|");for(let[i,s]of t.environment)e.push(`| ${Ff(i)} | ${Ff(s)} |`);e.push("");let n=t.redaction,o=n.found+n.manual;return e.push("<sub>",n.scanned?`Secret scan: OCR every ${n.everySec} s over ${n.framesScanned} frames; ${o} region${o===1?"":"s"} boxed out of the media. OCR is best-effort: review the clip before posting.`:`Not scanned for secrets${n.manual>0?` (${n.manual} region${n.manual===1?"":"s"} boxed out by hand)`:""}: review the clip before posting.`,`Generated by screencast-mcp bug_report, ${t.createdAt}.`,"</sub>",""),e.join(`
|
|
317
|
-
`)}async function
|
|
307
|
+
`)}function Su(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",()=>{gn(e.head())!==null&&(clearTimeout(o),n("running"))}),t.on("error",()=>{clearTimeout(o),n("exited")}),t.on("exit",()=>{clearTimeout(o),n("exited")})})}function vu(t,e,r){let n=gn(t.head());return n!==null?n:e==="ddagrab"?t.outputAt()??r:r}function $u(t,e,r,n){r.on("exit",o=>{let i=t.getChild(e);if(i&&i!==r)return;t.detachChild(e,r),xd(e)||es(e);let s=t.get(e);if(!s||s.status!=="recording"||t.isStopping(e))return;let a=vm({code:o,backend:n.backend,maxDurationSec:n.maxDurationSec,elapsedMs:Date.now()-n.spawnedAt});kt(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
|
+
${zo(n.watch)}`}:{}}),s.segments&&(s.segments.parts.length>0||s.webcam)?q0(t,s).catch(c=>{process.stderr.write(`Joining ${e}'s segments failed: ${j(c)}
|
|
309
|
+
`)}):G0(t,s).catch(c=>{process.stderr.write(`Reading ${e}'s duration failed: ${j(c)}
|
|
310
|
+
`)})})}async function G0(t,e){let{ffprobe:r}=k(),n=await ue(e.outputPath,{ffprobe:r});n!==null&&t.tryUpdate(e.id,{durationSec:n})}async function q0(t,e){let r=k();await nr(e.id);let{patch:n,error:o}=await tu(e,r),i=await ue(e.outputPath,{ffprobe:r.ffprobe});t.tryUpdate(e.id,{...n,durationSec:i??void 0,...o?{error:o}:{}})}function Rf(t,e,r){return fs(t,e.id,"resume",()=>X0(t,t.get(e.id)??e,r))}async function X0(t,e,r){let n=wd(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=it(o.parts),c=gd(e.maxDurationSec,a),u=o.parts.length,d=hd(e.outputPath,u),p=i.webcam?Qi(e.outputPath,u):void 0;(u>0||p)&&H0(Et(e.outputPath),{recursive:!0});let f=Oi(i.target,{...i.opts,output:d,maxDurationSec:c,...i.webcam&&p?{webcam:{...i.webcam,output:p}}:{}}),m=Date.now(),h=z0(r,f,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),b=xu(h,e.id),w=()=>{let T=t.getChild(e.id);T&&T!==h||(u>0&&_f(d,{force:!0}),p&&_f(p,{force:!0}))};if(await Su(h,b,s)==="exited")throw w(),new l(`Resume failed (ffmpeg exited immediately); the recording stays paused:
|
|
311
|
+
${zo(b)}`);let g=vu(b,s,m),y=p?gn(b.head(),i.opts.audio?2:1):null;t.attachChild(e.id,h);let v=()=>{t.detachChild(e.id,h),h.pid!==void 0&&gr(h.pid),w()},x;try{x=t.update(e.id,{status:"recording",pid:h.pid??null,pidSpawnedAt:m,videoStartMs:g-a*1e3,segments:{parts:o.parts,current:{path:d,startMs:g,...p?{webcamPath:p,...y!==null?{webcamStartMs:y}:{}}:{}}}})}catch(T){throw v(),new l(`Resume stopped: the session registry could not be written (${j(T)}).`)}if(!x)throw v(),new l(`No session with id "${e.id}".`);return t.clearPaused(e.id),$u(t,e.id,h,{backend:s,maxDurationSec:c,spawnedAt:m,watch:b}),{record:x,recordedSec:a,capSec:c}}import{basename as Nf,dirname as o$,join as _u}from"node:path";import{readdir as J0,stat as Y0,statfs as K0}from"node:fs/promises";import{dirname as V0,join as Mf}from"node:path";var ku=2*1024**3,Tf=["recordings","edits","screenshots","frames"];async function Af(t){let e;try{e=await J0(t,{withFileTypes:!0})}catch{return 0}let r=0;for(let n of e){let o=Mf(t,n.name);n.isDirectory()?r+=await Af(o):n.isFile()&&(r+=await Y0(o).then(i=>i.size,()=>0))}return r}async function Ds(t){try{let e=await K0(t);return Number(e.bavail)*Number(e.bsize)}catch{return null}}var Q0=500*1024**2;async function Cf(t){let e=t;for(;;){let r=await Ds(e);if(r!==null)return r;let n=V0(e);if(n===e)return null;e=n}}function Pf(t){return t===null?{}:t<Q0?{refuse:`Only ${Ns(t)} free on the output drive.`}:t<ku?{note:`Only ${Ns(t)} free on the output drive; a long recording may run out of space.`}:{}}async function If(t){let[e,...r]=await Promise.all([Ds(t),...Tf.map(o=>Af(Mf(t,o)))]),n=Object.fromEntries(Tf.map((o,i)=>[o,r[i]??0]));return{freeBytes:e??null,bytes:n}}function Ns(t){let e=["B","KB","MB","GB","TB"],r=t,n=0;for(;r>=1024&&n<e.length-1;)r/=1024,n++;return`${n===0?r:r.toFixed(1)} ${e[n]}`}import{existsSync as Z0}from"node:fs";function F(t,e="Input file"){if(!Z0(t))throw new l(`${e} not found: ${t}`)}function B(t,e,r,n={}){return n.anyContainer||qr(t),ar(t,ye(n.dir??"edits"),`${e}-${be()}-${we()}${r}`,n.overwrite)}var i$={target:Q.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:Q.boolean().optional().describe("window: targets match the whole title only, never a substring (default false)."),fps:Q.number().int().min(1).max(120).optional().describe(`Frames per second (default ${Pi}).`),quality:Q.enum(["draft","standard","high"]).optional().describe(`Encoder preset (default ${Ii}).`),audio:Q.object({source:Q.enum(["system","none"]).describe("system = what the machine plays (needs a loopback device); none = video only."),device:Q.string().optional().describe("dshow loopback device (from list_audio_devices); auto-detected if omitted.")}).optional().describe("Audio (default none). No microphone capture."),output:Q.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:Q.boolean().optional().describe("Replace an existing output (default false)."),label:Q.string().min(1).max(80).optional().describe("Name for list_sessions query."),maxDurationSec:Q.number().int().min(0).max(Dt).optional().describe(`Auto-stop after this many seconds (default ${Rc} or SCREENCAST_MAX_RECORDING_SEC; max 7 days; 0 = no cap).`),events:Q.boolean().optional().describe("Also log clicks, scroll, cursor, and typing (video-timed, video pixels) for read_events (default false; ~1 s slower start)."),keys:Q.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:Q.enum(["app","title"]).optional().describe("Log app switches (implies events); title adds window titles."),logs:Q.array(Q.object({path:Q.string().min(1),label:Q.string().min(1).max(40).optional()})).min(1).max(xf).optional().describe("Log files to follow onto the video clock."),perf:Q.boolean().optional().describe("Sample CPU/memory (and a window's app) to <rec>.perf.jsonl."),hotkeys:Q.boolean().optional().describe("Ctrl+Alt+Shift+M adds a marker, +S stops (implies events)."),elements:Q.boolean().optional().describe('Name the UI element each click hits, e.g. "Save" button (implies events).'),cursor:Q.enum(["os","events"]).optional().describe("events: leave the OS cursor out and log it (implies events) for the cursor tool to redraw."),backend:Q.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:Q.enum(["auto","x264","nvenc","qsv","amf"]).optional().describe("auto = first working GPU encoder, else x264 (default with ddagrab; else x264)."),webcam:Q.object({device:Q.string().optional().describe("list_video_devices name (default: first)."),corner:Q.enum(["top_left","top_right","bottom_left","bottom_right"]).optional(),size:Q.number().min(.1).max(.5).optional().describe("Share of width (0.25)."),shape:Q.enum(["rect","circle"]).optional()}).optional().describe("Also record a camera to <output>.webcam.mp4, aligned for overlay."),replayBufferSec:Q.number().int().min(ns).max(Kr).optional().describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab or ddagrab, not wgc."),startWhen:Q.object({window:Q.string().min(1).optional().describe('A window: target that must exist, e.g. "window:Error".'),text:Q.string().min(1).max(200).optional().describe("Text that must be on target (OCR)."),timeoutSec:Q.number().positive().max(pf).optional().describe(`Default ${du}.`)}).optional().describe("Arm: start once these hold (stop_recording disarms)."),stopWhen:Q.object({text:Q.string().min(1).max(200)}).optional().describe("Stop once this text shows (OCR)."),saveWhen:Q.object({text:Q.string().min(1).max(200),lastSec:Q.number().positive().max(Kr).optional(),postRollSec:Q.number().min(0).max(df).optional(),maxSaves:Q.number().int().min(1).max(mf).optional()}).optional().describe(`Replay buffer: save_replay when text shows (OCR), postRollSec (${mu}) later; re-arms once it goes (maxSaves ${fu}).`)};async function Tu(t,e,r){let n=await dt(t,{exactTitle:e}),o=r$(_u(n$(),"screencast-trigger-"));try{let i=_u(o,"t.png");await Ut(n,i);let[s]=await mt([i],o);return!!s&&Rt(s.lines,r).length>0}finally{Eu(o,{recursive:!0,force:!0})}}async function s$(t){try{return await dt(t.startsWith("window:")?t:`window:${t}`),!0}catch{return!1}}var Df=new WeakSet;function a$(t,e){try{let r=Di(t,e);return{width:r.w,height:r.h}}catch{return}}function c$(t,e){let r=gn(t.head(),e?2:1);return r!==null?{webcamStartMs:r}:{}}var Ru=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&&gr(this.child.pid),this.logger&&await Mi(this.logger),this.evPaths&&Eu(this.evPaths.raw,{force:!0}),this.replay&&os(this.replay),this.webcamRaw&&this.output&&Eu(Et(this.output),{recursive:!0,force:!0}))}};async function u$(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:lm(t.dda,t.fps,{download:!e.gpuFrames,drawMouse:!t.hideCursor})}:{},...r?{videoCodec:hr(e.encoder,t.quality,{gpuFrames:e.gpuFrames})}:{}},o=t.webcamDevice?{device:t.webcamDevice,...r?{codec:hr(e.encoder,t.quality)}:{}}:void 0,i=Oi(t.target,{...n,output:t.output,maxDurationSec:t.maxDurationSec,...o&&t.webcamRaw?{webcam:{...o,output:t.webcamRaw}}:{}}),s=t.replay?Yd(i,t.replay):i,a=Date.now(),c=t.backend==="wgc"?Ff(process.execPath,[qm(),JSON.stringify({ffmpeg:t.ffmpeg,hwnd:t.window.hwnd,fps:t.fps,encode:[...hr(e.encoder,t.quality),...Ci(t.fps)],output:t.output,maxDurationSec:t.maxDurationSec,cursor:!t.hideCursor,...t.audio?{audioDevice:t.audio.device}:{}})],{stdio:["pipe","ignore","pipe"],windowsHide:!0}):Ff(t.ffmpeg,s,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),u=xu(c,t.id),d=await Su(c,u,t.backend);return{captureOpts:n,webcam:o,child:c,watch:u,spawnedAt:a,settled:d}}function l$(t,e,r){if(r.replay){let o=new Promise(i=>r.child.once("exit",()=>i()));vo(e,o.then(()=>Mi(r.logger)));return}let n=r.frame;n&&vo(e,Tn(e).then(async()=>{await Mi(r.logger);try{let o=Zi(t.get(e)?.segments,r.startMs,Date.now()),i=bp(r.evPaths,{...o,frame:n});t.tryUpdate(e,{events:{path:r.evPaths.jsonl,keys:r.keyMode,count:i.length,summary:bn(i)}})}catch(o){t.tryUpdate(e,{events:{path:r.evPaths.jsonl,keys:r.keyMode,error:j(o)}})}}).catch(o=>{process.stderr.write(`Event log for ${e} failed: ${j(o)}
|
|
312
|
+
`)}))}function p$(t,e,r){let n=new Os(r.window?.pid);n.start();let o=st(r.output);t.tryUpdate(e,{perf:{path:o}}),vo(e,Tn(e).then(async()=>{try{let i=kf(n.stop(),Zi(t.get(e)?.segments,r.startMs,Date.now()));Of(o,Ef(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:Nn(i,s)}})}catch(i){n.stop(),t.tryUpdate(e,{perf:{path:o,error:j(i)}})}}))}function d$(t,e,r){r.tailer.follow();let n=ft(r.output),o=r.logs.map(i=>i.label??Nf(i.path));t.tryUpdate(e,{logs:{path:n,sources:o}}),vo(e,Tn(e).then(async()=>{try{let i=Sf(await r.tailer.stop(),Zi(t.get(e)?.segments,r.startMs,Date.now()));Of(n,vf(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:j(i)}})}}))}function Lf(t,e,r){let n=t.get(e);if(!n||n.status!=="recording"&&n.status!=="paused")return;let{ffprobe:o}=k();Oo(t,n,{reason:"stopped",probe:i=>ue(i,{ffprobe:o})}).catch(i=>process.stderr.write(`${r} stop for ${e} failed: ${j(i)}
|
|
313
|
+
`))}function m$(t,e){return r=>{let n=t.get(e);if(!(!n||n.status!=="recording"&&n.status!=="paused")){if(r==="stop")return Lf(t,e,"Hotkey");try{Bo(t,e,"hotkey")}catch(o){process.stderr.write(`Hotkey marker for ${e} failed: ${j(o)}
|
|
314
|
+
`)}}}}function f$(t,e,r){let n=new AbortController;Tn(e).then(()=>n.abort()),Ps({checks:[()=>Tu(r.target,r.exactTitle,r.text)],timeoutMs:Number.POSITIVE_INFINITY,intervalMs:As,signal:n.signal}).then(o=>{o==="met"&&Lf(t,e,"stopWhen")})}function h$(t,e,r){let n=new AbortController;Tn(e).then(()=>n.abort()),bf({seen:()=>Tu(r.target,r.exactTitle,r.when.text),act:async()=>{let i=t.get(e);if(!i?.replay||i.status!=="recording")return!1;let s=new Date().toISOString();try{let{ffmpeg:a,ffprobe:c}=k(),u=B(void 0,"replay",".mp4",{dir:"recordings",anyContainer:!0});i.replay.events&&So(he(u));let d=Math.min(r.when.lastSec??i.replay.bufferSec,i.replay.bufferSec),p=await Io(i.replay,{ffmpeg:a,ffprobe:c,lastSec:d,output:u,quality:i.quality,live:!0,signal:n.signal});Bo(t,e,`saveWhen: ${r.when.text}`.slice(0,Do)),t.tryUpdate(e,{autoSaves:[...t.get(e)?.autoSaves??[],{at:s,outputPath:u,durationSec:p.durationSec}]}),kt("info",`saveWhen saved ${p.durationSec}s of replay ${e} to ${u}.`,{sessionId:e,outputPath:u})}catch(a){if(n.signal.aborted)return!1;t.tryUpdate(e,{autoSaves:[...t.get(e)?.autoSaves??[],{at:s,error:j(a)}]})}return!0},max:r.when.maxSaves??fu,postRollMs:(r.when.postRollSec??mu)*1e3,intervalMs:As,signal:n.signal})}async function g$(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??du,s={...o.window?{window:o.window}:{},...o.text?{text:o.text}:{}};await dt(r.target,{exactTitle:r.exactTitle,backend:r.backend}),await jt(t,`When ${gu(s)} (within ${i} s), start recording ${Wt(r.target)}`+(r.events?", logging mouse clicks and typing":"")+"?",n.signal);let a={...r,startWhen:void 0};Df.add(a);let c=wf({conditions:s,target:r.target,timeoutSec:i,checks:[...o.window?[()=>s$(o.window)]:[],...o.text?[()=>Tu(r.target,r.exactTitle,o.text)]:[]],fire:async()=>{let u=e.handler,d=await u(a,{...n,signal:new AbortController().signal}),p=d.structuredContent;if(d.isError||!p?.sessionId)throw new Error(d.content.map(f=>f.text??"").join(" ")||"start failed");return p.sessionId}});return S({sessionId:c.id,status:"armed",backend:r.backend??"gdigrab",outputPath:"",waitingFor:gu(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 b$(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 dt(e.target,{exactTitle:e.exactTitle,backend:e.backend}),c=e.backend??"gdigrab";Cd({backend:c,systemAudio:e.audio?.source==="system",replay:e.replayBufferSec!==void 0,webcam:!!e.webcam,logs:!!e.logs,perf:!!e.perf,saveWhen:!!e.saveWhen},{windowHwnd:!!a?.hwnd,wgcAvailable:c==="wgc"&&pr()});let u=e.replayBufferSec!==void 0?Xd(e.replayBufferSec):null,d=e.fps??Pi,p=e.quality??Ii,f=Tp(e.maxDurationSec),m=ar(e.output,ye("recordings"),`rec-${be()}-${we()}.mp4`,e.overwrite),h=Pf(await Cf(o$(m)));if(h.refuse)throw new l(h.refuse,"Free some space (delete_recording removes old recordings), or record to another drive with output.");let b=e.audio?.source==="system"?{device:await Km(e.audio.device)}:void 0,w=e.webcam?await Jm(e.webcam.device):void 0,g=c==="ddagrab"?um(Di(i,s),await cm()):null;if(!Df.has(e)){let x=Pd({target:Wt(e.target,a),replayBufferSec:u?.bufferSec,maxDurationSec:f,audioDevice:b?.device,webcamDevice:w,events:!!e.events,focus:e.focus,elements:e.elements,hotkeys:e.hotkeys,output:m});await jt(t,x,r.signal)}let y=await im(e.encoder??(c==="ddagrab"?"auto":"x264"),c==="ddagrab"?"ddagrab":"gdigrab",n,void 0,c==="wgc"?void 0:a$(i,s)),v=async x=>!g||x.gpuFrames||await am(n);if(!await v(y))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:b,webcamDevice:w,dda:g,firstPick:y,ddaUsable:v,diskNote:h.note}}function w$(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=vu(r.watch,s,r.spawnedAt),b=t.events?Di(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=Id({id:r.id,target:t.target,label:t.label,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:c$(r.watch,!!f).webcamStartMs,corner:t.webcam?.corner,size:t.webcam?.size,shape:t.webcam?.shape}}:{},processImage:s==="wgc"?Nf(process.execPath).toLowerCase():"ffmpeg.exe",identity:wm()});return{startMs:h,frame:b,record:w}}function y$(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 (${j(n)}).`)}}function Bf(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:i$,outputSchema:N({sessionId:Q.string(),status:Q.string(),backend:Q.string(),outputPath:Q.string()}),annotations:C},async(r,n)=>{if(r.startWhen)return g$(t,e,r,n);let o=()=>{},i=new Ru;try{o=ef();let s=await b$(t,r,n),{ffmpeg:a,hideCursor:c,target:u,monitors:d,window:p,backend:f,replay:m,fps:h,quality:b,maxDurationSec:w,output:g,audio:y,webcamDevice:v,dda:x,firstPick:T,ddaUsable:R}=s;i.output=g,v&&(i.webcamRaw=Qi(g,0),t$(Et(g),{recursive:!0})),m&&(Kd(m),i.replay=m);let P=r.keys??lp,z=r.events?m?{raw:_u(m.dir,"events.raw"),jsonl:""}:he(g):null;z&&!m&&So(z,r.overwrite),i.evPaths=z;let H=r.logs?new Is(r.logs):null;await H?.mark();let D=()=>{};i.logger=z?await mp(z.raw,P,{...m?{rotateSec:Gd(m.bufferSec)}:{},...r.focus?{focus:r.focus}:{},...r.elements?{elements:!0}:{},...r.hotkeys?{hotkeys:!0,onHotkey:re=>D(re)}:{}}):null;let M=`rec-${be()}-${we(6)}`,ie={id:M,ffmpeg:a,backend:f,target:u,monitors:d,window:p,fps:h,quality:b,audio:y,hideCursor:c,dda:x,webcamDevice:v,webcamRaw:i.webcamRaw,output:g,maxDurationSec:w,replay:m},Z=await sm(T,re=>u$(ie,re),{why:re=>zo(re.watch,3),canFallback:()=>R({encoder:"x264",gpuFrames:!1}),beforeRetry:()=>{m&&Vd(m)}}),{run:K,failure:X,pick:ne}=Z,{child:$,watch:J,spawnedAt:O,captureOpts:pe,webcam:q}=K;if(K.settled==="exited")throw new l(`Recording failed to start (${f==="wgc"?"window capture":"ffmpeg"} exited immediately):
|
|
315
|
+
${zo(J)}`+(X?`
|
|
316
|
+
(Retried with libx264 after ${X})`:""));i.child=$;let{startMs:ee,frame:ae,record:_}=w$(r,s,{id:M,child:$,watch:J,spawnedAt:O,captureOpts:pe,webcam:q,encoder:ne.encoder,evPaths:z,keyMode:P,webcamRaw:i.webcamRaw}),A=se();y$(A,_,$),i.handOff();let oe=i.logger;return oe&&z&&l$(A,M,{logger:oe,evPaths:z,keyMode:P,startMs:ee,frame:ae,replay:m,child:$}),$u(A,M,$,{backend:f,maxDurationSec:w,spawnedAt:O,watch:J}),r.perf&&p$(A,M,{output:g,startMs:ee,window:p}),H&&r.logs&&d$(A,M,{tailer:H,logs:r.logs,output:g,startMs:ee}),r.hotkeys&&(D=m$(A,M)),r.stopWhen&&f$(A,M,{target:r.target,exactTitle:r.exactTitle,text:r.stopWhen.text}),r.saveWhen&&h$(A,M,{target:r.target,exactTitle:r.exactTitle,when:r.saveWhen}),S(Fd({record:_,audioDevice:y?.device,maxDurationSec:w,encoder:ne.encoder,encoderNote:ne.note,diskNote:s.diskNote,...x?{gpuFrames:ne.gpuFrames}:{},webcamDevice:v,window:p,...z?{events:{jsonl:z.jsonl,keys:P}}:{},...r.logs?{logs:{path:ft(g),missing:r.logs.some(re=>!e$(re.path))}}:{},...r.hotkeys?{hotkeys:{taken:oe?hp(oe):[]}}:{},...m?{replay:{...m,events:!!z}}:{}}))}catch(s){return await i.release(),E(s)}finally{o()}})}import{z as Ln}from"zod";import{existsSync as Ls}from"node:fs";function Wf(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 x$(t,e){if(t.error||!Ls(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?kd(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 S$={sessionId:Ln.string().min(1).describe("Session id returned by start_recording."),save:Ln.boolean().optional().describe("Replay buffer: write it all to outputPath first (default: discard).")};function jf(t){t.registerTool("stop_recording",{title:"Stop Recording",description:"Stop a recording gracefully so the file is finalized; returns the path and duration.",inputSchema:S$,outputSchema:N({sessionId:Ln.string(),status:Ln.string(),outputPath:Ln.string(),durationSec:Ln.number().nullable()}),annotations:ts},async e=>{try{let r=se(),n=e.sessionId;if(Cs(n)){let f=Uo(n);if(!f)throw new l(`No armed recording with id "${n}".`);f.status==="starting"&&(f=await hf(n)??f);let m={sessionId:n,outputPath:"",durationSec:null};if(hu(n))return S({...m,status:"cancelled",note:"Disarmed; nothing was recorded."});if(!f.sessionId)return S({...m,status:f.status,...f.error?{error:f.error}:{}});n=f.sessionId}let o=r.get(n);if(!o)throw new l(`No session with id "${e.sessionId}".`);if(o.status!=="recording"&&o.status!=="paused"){let f=o.replay&&Ls(o.replay.dir)?await ss(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&&Ls(o.outputPath)&&(m=await ue(o.outputPath,{ffprobe:k().ffprobe}).catch(()=>null),m!==null&&r.tryUpdate(o.id,{durationSec:m})),S({...f?{replay:Wf(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=bm(o,process.pid,Vc(o));if(i)throw new l(i);let{ffprobe:s}=k(),{record:a,graceful:c,durationSec:u,replay:d,segments:p}=await Oo(r,o,{reason:"stopped",probe:f=>ue(f,{ffprobe:s}),saveReplay:e.save});return S({sessionId:o.id,status:"stopped",outputPath:o.outputPath,durationSec:u??null,finalizedGracefully:c,...d?{replay:Wf(d)}:{},...p&&p.count>1?{segmentsJoined:p.count}:{},...p?.error?{segmentsError:p.error}:{},...a?.webcam?{webcam:await x$(a.webcam,o.outputPath)}:{},...a?.events?{eventsPath:a.events.path,events:a.events.summary??{},...a.events.error?{eventsError:a.events.error}:{}}:{},fileExists:Ls(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 $r}from"zod";import{existsSync as Vo,lstatSync as _h,readdirSync as Rh,rmSync as gk,statSync as bk}from"node:fs";import{dirname as wk,resolve as Th}from"node:path";import{createHash as ih}from"node:crypto";import{closeSync as V$,existsSync as Bn,openSync as Q$,readFileSync as Z$,readdirSync as ek,readSync as tk,renameSync as rk,statSync as sh,writeFileSync as nk}from"node:fs";import{basename as ah,dirname as ok,join as Wn,resolve as Js}from"node:path";import{closeSync as T$,existsSync as Cu,openSync as M$,readSync as A$,statSync as C$}from"node:fs";import{basename as Ws,isAbsolute as P$,join as Pu}from"node:path";function Tt(t,e,r){if(t.length<e)throw new Error(`Truncated font: ${r}.`);return t}function v$(t,e){let r=Tt(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 Tt(t(12+e*4,4),4,"collection offsets").readUInt32BE(0)}var Bs=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 $$(t){let e=Tt(t,14,"cmap format 4").readUInt16BE(6),r=14,n=r+e+2,o=n+e,i=o+e;Tt(t,i+e,"cmap format 4 segments");let s=new Bs;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 k$(t,e){let r=Tt(t,16,`cmap format ${e}`).readUInt32BE(12);Tt(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 Bs;for(let[i,s]of n)o.add(i,s);return o.ranges}function E$(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 Uf(t,e=0){let r=v$(t,e),n=Tt(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=Tt(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=Tt(t(a,4),4,"cmap header").readUInt16BE(2),d=Tt(t(a+4,u*8),u*8,"cmap records"),p=[];for(let f=0;f<u;f++){let m=E$(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 $$(t(f,m.readUInt16BE(2)));if(h===12||h===13)return k$(t(f,m.readUInt32BE(4)),h)}throw new Error("Font has no Unicode cmap subtable this reader understands (formats 4, 12, 13).")}function _$(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 R$(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 Ho(t,e){let r=new Set,n=[];for(let o of t){let i=o.codePointAt(0);r.has(i)||(r.add(i),R$(i)&&!_$(e,i)&&n.push(o))}return n}var I$={regular:"Inter-Regular.ttf",bold:"Inter-Bold.ttf"};function Gt(t="bold"){return Pn("fonts",I$[t])}function xe(t){return t.replace(/\\/g,"/").replace(/:/g,"\\\\:").replace(/'/g,"\\\\\\'").replace(/([,;[\]])/g,"\\$1")}var F$={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"]}},O$=["segoe","japanese","chineseSimplified","chineseTraditional","korean","indic","thai","ethiopic","emoji","symbol"];function N$(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,...O$.filter(r=>!e.includes(r))].map(r=>F$[r])}function D$(t,e){let r=null;for(let n of e){let o=Ho(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 Hf(){return Pu(process.env.WINDIR??process.env.SystemRoot??"C:\\Windows","Fonts")}var zf=new Map;function Mu(t){let e=zf.get(t);if(e!==void 0)return e;let r,n=null;try{n=M$(t,"r");let o=n;r=Uf((s,a)=>{let c=Buffer.alloc(a);return c.subarray(0,A$(o,c,0,a,s))})}catch{r=null}finally{n!==null&&T$(n)}return zf.set(t,r),r}function L$(t){if(Cu(t)&&C$(t).isFile())return t;if(!P$(t)&&Ws(t)===t){let e=Pu(Hf(),t);if(Cu(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 Au(t){let e=t.replace(/\s+/g," ").trim();return`"${e.length>40?`${e.slice(0,39)}\u2026`:e}"`}function Mt(t,e={}){if(e.fontFile){let c=L$(e.fontFile),u=Mu(c);if(!u)return{fontFile:c,missing:[],fallback:!1,warning:`Could not read the character map of ${Ws(c)}; glyph coverage of ${Au(t)} was not checked.`};let d=Ho(t,u);return d.length===0?{fontFile:c,missing:d,fallback:!1}:{fontFile:c,missing:d,fallback:!1,warning:`${Ws(c)} has no glyph for ${d.join(" ")} in ${Au(t)}; they render as empty boxes.`}}let r=e.weight??"bold",n=Gt(r),o=Mu(n);if(o&&Ho(t,o).length===0)return{fontFile:n,missing:[],fallback:!1};let i=e.fontsDir??Hf(),s=o?[{path:n,coverage:o}]:[];for(let c of N$(t))for(let u of c[r]){let d=Pu(i,u),p=Cu(d)?Mu(d):null;if(p){if(Ho(t,p).length===0)return{fontFile:d,missing:[],fallback:!0};s.push({path:d,coverage:p});break}}let a=D$(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 ${Au(t)}; they render as empty boxes (drawn with ${Ws(a.fontFile)}). Pass fontFile with a font that covers them.`}}import{mkdtempSync as B$,rmSync as W$,writeFileSync as j$}from"node:fs";import{join as Iu}from"node:path";import{tmpdir as U$}from"node:os";var Go=12,Gf=48,qo=320;function js(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 Be(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 z$(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 H$(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=${xe(o)}:textfile=${xe(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}`,..._e(r)]}function G$(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",..._e(r)]}function qf(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",..._e(r)]}async function Us(t,e,r,n,o){let i=z$(e.length,n.columns),s=B$(Iu(U$(),"screencast-sheet-"));try{let a=Gt("bold");await Je(e,async(c,u)=>{let d=Iu(s,`label_${u}.txt`);j$(d,Be(c));let p=Iu(s,`tile_${String(u).padStart(3,"0")}.png`);await te(H$(t,c,p,n.tileWidth,a,d),6e4,{signal:o})}),await te(G$(yn(s,"tile_%03d.png"),i,r),6e4,{signal:o})}finally{W$(s,{recursive:!0,force:!0})}return i}import{existsSync as zs}from"node:fs";var Xf=t=>Math.round(t*1e3)/1e3,q$={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 Fu(t){return t.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Ou(t){let e=Fu(t.role),r=t.app?` in ${t.app}`:"";return t.name?`the "${t.name}" ${e}${r}`:`${/^[aeiou]/.test(e)?"an":"a"} ${e}${r}`}function Jf(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} ${Ou(r.element)}`:r.inFrame?`${o} at (${r.x}, ${r.y})`:`${o} outside the recorded area`}function Nu(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=Jf(s.button,!0,a.e),n=null;continue}let c={t:s.t,action:"click",text:Jf(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=q$[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 Du(t){return Nu(t).map(({button:e,inFrame:r,keys:n,durationSec:o,element:i,...s})=>s)}var Lu=30,Hs=600,Bu=1,Gs=100,Wu=20,We=lu(["\\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("|")),qs=lu("error|exception|fail(?:ed|ure)?|fatal|crash|denied|refused|not found|cannot|can't|unable|invalid|timed? ?out|traceback|panic|unhandled|warning"),qt={markdown:"report.md",json:"report.json",clip:"clip.mp4",contactSheet:"contact-sheet.png",gif:t=>`repro.${t}`},Xo=t=>Math.round(t*1e3)/1e3;function Kf(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??Lu,o=e.start??Math.max(0,r-n);if(o>=t)throw new l(`start ${o}s is past the end of the ${Xo(t)}s recording.`);if(!(r>o))throw new l("end must be after start.");if(r-o>Hs)throw new l(`The clip would be ${Xo(r-o)}s; at most ${Hs}s. Narrow start/end.`);return{start:Xo(o),end:Xo(r)}}function X$(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 Vf(t){let e=[];for(let r of[...t].sort((n,o)=>n.start-o.start)){let n=e.find(s=>r.start<=s.end&&X$(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 J$="[REDACTED]";function je(t,e){if(t.length===0)return[];let r=In(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?J$:""),a=u);return s+n.slice(a)})}function Qf(t,e,r){let n=new Map;for(let a of t){let c=new Set(Rt(a.lines,e,!0).map(u=>u.line));for(let u of c){let d=zt(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,Wu);if(!r)return i;let s=je(i.map(a=>a.text),r);return i.map((a,c)=>({...a,text:s[c]??a.text}))}var Y$=t=>`\`${t.replace(/`/g,"'").replace(/\s+/g," ").trim()}\``,Yf=t=>t.replace(/\|/g,"\\|").replace(/\s*\n\s*/g," ");function Zf(t){let e=[`# ${t.title.replace(/\s*\n\s*/g," ")}`,""],r=`${Be(t.clip.start)}-${Be(t.clip.end)}`;if(e.push(`Recorded repro: ${t.clip.width}x${t.clip.height}, clip ${r} of a ${Be(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}. \`${Be(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?Be(i.firstSeen):`${Be(i.firstSeen)}-${Be(i.lastSeen)}`;e.push(`- \`${s}\` ${Y$(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?"-":""}${Be(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}) (${Xo(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(`| ${Yf(i)} | ${Yf(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 Xs(t){if(t.sessionId!==void 0){let n=se().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 nr(n.id),!zs(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path;return{path:n.outputPath,eventsPath:o&&zs(o)?o:null,record:n}}let e=t.input;if(!zs(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=he(e);return{path:e,eventsPath:zs(r)?r:null}}var K$=40;function eh(t,e,r){let n=t.filter(i=>i.t>=e.start-5&&i.t<=e.end).slice(-K$),o=r?je(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 th(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=Nn(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 ${Be(s.start)} to ${Be(s.end)}`)]}var ju=1,Uu=.03,zu=120,ch=600,ik=10,Ys=10,uh=50,rh=200,sk=5,vr=t=>Math.round(t*1e3)/1e3;function Jo(t){return`${t}.index.json`}function Hu(t){return`${t.replace(/\.[^./\\]+$/,"")}.index.json`}function Yo(t,e){let r=n=>process.platform==="win32"?Js(n).toLowerCase():Js(n);return r(t)===r(e)}function Ks(t,e,r){return typeof t.video=="string"&&Yo(t.video,e)?!0:r!==void 0&&!!t.fingerprint&&ra(t.fingerprint,r)}function Vs(t,e){let r=ih("sha1").update(Js(t).toLowerCase()).digest("hex").slice(0,12),n=ah(t).replace(/\.[^.]+$/,"");return Wn(e,"indexes",`${n}-${r}.index.json`)}function lh(t,e){let r=Jo(t);try{return sr(r),r}catch{return Vs(t,e)}}function Qs(t,e,r){for(let o of[Jo(t),Vs(t,e)])if(Bn(o))return o;let n=Hu(t);if(n!==Jo(t)&&Bn(n)){let o=Ko(n);if(o&&Ks(o,t,r))return n}return null}function ph(t,e){return t!==null&&ra(t.fingerprint,e.fingerprint)&&t.sceneThreshold===e.sceneThreshold&&t.maxFrames===e.maxFrames&&(t.ocr||!e.ocrAvailable)}function dh(t,e=We){return t.map(r=>r.ocr.length>0?{...r,ocr:je(r.ocr,e)}:r)}var ak=/\.(mp4|mkv|mov|webm|avi|m4v|wmv|flv|gif|ts|mpg|mpeg)$/i,nh=t=>t.replace(/\.[^.]+$/,"").toLowerCase();function Zs(t,e){let r=new Set(e.map(s=>s.toLowerCase())),n=ah(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()&&ak.test(s)&&nh(s)===nh(n))?{path:null,ambiguous:!0}:{path:Wn(ok(t),o),ambiguous:!1}:{path:null,ambiguous:!1}}function mh(t,e,r,n=ik){let o=$n(t.filter(i=>i.timeSec<e),r).map(vr);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,vr(o[i]+s/2))}return[...new Set(o)].sort((i,s)=>i-s)}function fh(t,e){return t.map((r,n)=>({start:r,end:vr(t[n+1]??e)}))}function ea(t){return vr(t.start+Math.min(.25,(t.end-t.start)/2))}function hh(t){let e=[];for(let r of t){let n=e.at(-1);n&&n.ocr.join(`
|
|
318
318
|
`)===r.ocr.join(`
|
|
319
|
-
`)&&!r.events&&!r.markers&&!r.transcript?n.end=r.end:e.push({...r,ocr:[...r.ocr]})}return e}function th(t){let e=[];for(let r of t){let n=`at ${Math.round(r.x)},${Math.round(r.y)}`,o=null;if(r.type==="down"){let i=r.element;o=`click ${r.button??"left"} ${n}`+(i?` ${Ru(i.role)}${i.name?` ${i.name}`:""}${i.app?` ${i.app}`:""}`:"")}else r.type==="key"?o=`shortcut ${r.keys??"key"}`:r.type==="typing"?o=`typing ${wr(r.durationSec??0)} s`:r.type==="wheel"?o=`scroll ${(r.delta??0)>0?"up":"down"} ${n}`:r.type==="gap"?o=`event gap (${r.reason??"unknown"})`:r.type==="focus"&&(o=`switch to ${r.app??"app"}${r.title?` ${r.title}`:""}`);o&&e.push({t:wr(r.t),text:o})}return e}function rh(t){return t.map(e=>({t:wr(e.t),text:e.label}))}function nh(t){return t.map(e=>({t:wr(e.start),text:e.text.replace(/\s+/g," ").trim()})).filter(e=>e.text)}function Jr(t,e,r){let n=t.map(i=>{let{[r]:s,...a}=i;return a});if(n.length===0)return n;let o=i=>{let s=0,a=n.length-1,c=-1;for(;s<=a;){let u=s+a>>1;n[u].start<=i?(c=u,s=u+1):a=u-1}return c!==-1&&i<n[c].end?c:-1};for(let i of[...e].sort((s,a)=>s.t-a.t)){let s=o(i.t);s===-1&&(s=i.t<n[0].start?0:n.length-1);let a=n[s];(a[r]??=[]).push(i)}return n}function Hs(t){let e=Gf(t),r=Hf("sha1"),n=64*1024,o=_$(t,"r");try{let i=Buffer.alloc(n);for(let s of e.size>n?[0,e.size-n]:[0]){let a=A$(o,i,0,n,s);r.update(i.subarray(0,a))}}finally{E$(o)}return{size:e.size,mtimeMs:Math.round(e.mtimeMs),sample:r.digest("hex")}}function Gs(t,e){return t.size===e.size&&t.mtimeMs===e.mtimeMs&&t.sample===e.sample}function N$(t){try{let e=JSON.parse(t);return e?.version!==Ou||!Array.isArray(e.segments)||!e.fingerprint?null:e}catch{return null}}function jo(t){try{return N$(T$(t,"utf8"))}catch{return null}}var Xr=new Map,D$=64;function Bu(t){let e;try{e=Gf(t)}catch{return Xr.delete(t),null}let r=Xr.get(t);if(r&&r.size===e.size&&r.mtimeMs===e.mtimeMs)return r.index;let n=jo(t);return n?(Xr.size>=D$&&Xr.delete(Xr.keys().next().value),Xr.set(t,{size:e.size,mtimeMs:e.mtimeMs,index:n}),n):(Xr.delete(t),null)}function oh(t,e){let r=`${t}.${process.pid}.tmp`;C$(r,JSON.stringify(e)),M$(r,t)}function L$(t){let e=t.replace(/\s+/g," ").trim();return e.length>jf?`${e.slice(0,jf-1)}\u2026`:e}function B$(t){let e=[];return t.segments.forEach((r,n)=>{for(let o of r.ocr)e.push({seg:n,source:"screen",t:r.start,text:o});for(let[o,i]of[["event",r.events],["marker",r.markers],["transcript",r.transcript],["log",r.logs]])for(let s of i??[])e.push({seg:n,source:o,t:s.t,text:s.text})}),e}function ih(t,e){if(t.trim().length===0)throw new l("query must not be empty.");if(t.length>qr)throw new l(`The query is ${t.length} characters; at most ${qr} are allowed.`);if(!e&&!/[\p{L}\p{N}]/u.test(Bt(t)))throw new l("query needs at least one letter or digit.","For punctuation, use regex: true.");e&&Tn([""],t)}var zf=new WeakMap;function W$(t,e){let r=zf.get(t);r||zf.set(t,r=new Map);let n=r.get(e);if(n)return n;let o=B$(t),i=e?Le(o.map(c=>c.text),e):o.map(c=>c.text),s=o.map((c,u)=>({...c,text:i[u]??""})),a={items:s,norm:s.map(c=>Bt(c.text))};return r.set(e,a),a}function Wu(t,e,r={}){if(ih(e,r.regex===!0),r.video!==void 0&&!Bs(t,r.video,r.fingerprint))throw new l(`The index found is for ${t.video}, not ${r.video}.`,"Run index_recording on this recording.");let n=r.secretPattern===void 0?De:r.secretPattern,{items:o,norm:i}=W$(t,n??""),s=new Map,a=(p,f)=>{let m=s.get(p.seg)??{score:0,matches:[]};m.score+=f,m.matches.push(p),s.set(p.seg,m)};if(r.regex){let p=Tn(o.map(f=>f.text),e);o.forEach((f,m)=>{(p[m]??[]).length>0&&a(f,2)})}else{let p=Bt(e.trim()),f=p.split("_").filter(Boolean);if(o.forEach((m,h)=>{i[h].includes(p)&&a(m,2)}),f.length>1){let m=new Map;o.forEach((h,b)=>{let w=m.get(h.seg);w?w.push(b):m.set(h.seg,[b])});for(let[h,b]of m)if(!s.has(h)&&f.every(w=>b.some(g=>i[g].includes(w)))){for(let w of b)f.some(g=>i[w].includes(g))&&a(o[w],0);s.get(h).score=1}}}return{hits:[...s.entries()].map(([p,f])=>({seg:p,...f})).sort((p,f)=>f.score-p.score||t.segments[p.seg].start-t.segments[f.seg].start).slice(0,r.limit??Ls).map(p=>{let f=t.segments[p.seg],m=p.matches.slice(0,F$).map(h=>({source:h.source,t:h.t,text:L$(h.text)}));return{start:f.start,end:f.end,t:Math.min(...p.matches.map(h=>h.t)),score:p.score,matches:m}}),total:s.size}}var j$=20;function U$(t){return[Fn(t,"recordings"),Fn(t,"edits"),Fn(t,"edits","indexes")]}function sh(t){let e=[];for(let r of U$(t)){let n;try{n=R$(r)}catch{continue}for(let o of n)o.endsWith(".index.json")&&e.push(Fn(r,o))}return e}function ah(t,e,r={}){ih(e,r.regex===!0);let n=new Map;for(let c of t){let u=Ds(c.index.video).toLowerCase(),d=n.get(u);(!d||c.index.createdAt>d.index.createdAt)&&n.set(u,c)}let o=r.limit??Ls,i=[],s=[],a=0;for(let c of n.values()){let u=Wu(c.index,e,{regex:r.regex,limit:o});if(u.total!==0){a+=u.total,i.push({video:c.index.video,indexPath:c.indexPath,total:u.total,best:u.hits[0].score});for(let d of u.hits)s.push({video:c.index.video,...d})}}return i.sort((c,u)=>u.best-c.best||u.total-c.total),s.sort((c,u)=>u.score-c.score),{hits:s.slice(0,o),total:a,recordings:i.slice(0,j$),searched:n.size}}async function qs(t){if(t.input===void 0==(t.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");if(t.sessionId!==void 0){let n=oe().get(t.sessionId);if(!n)throw new l(`No session with id "${t.sessionId}".`);if(n.status==="recording"||n.status==="paused")throw new l("The recording is still running; stop_recording it first.");if(await Zt(n.id),!In(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path,i=n.markers?.length?n.markers:We(n.outputPath);return{path:n.outputPath,eventsPath:o&&In(o)?o:null,markers:i}}let e=t.input;if(!In(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=ke(e);return{path:e,eventsPath:In(r)?r:null,markers:We(e)}}import{basename as ch}from"node:path";function uh(t,e,r){let n=ke(t),o=Us(t,e),i=[n.jsonl,n.raw,`${n.raw}.stop`,zr(t),Bo(t),Ws(t,r),fr(t),jt(t),vt(t),Qi(t),...o.path&&!o.ambiguous?[o.path]:[]];return{files:[...new Set(i)].filter(s=>ch(s)!==ch(t)),dirs:[yt(t)]}}var z$=/\.(mp4|m4v|mkv|mov|webm|avi|gif|webp)$/i;function lh(t){if(tr(t,"Recording"),!z$.test(t))throw new l(`${t} is not a video or GIF, so it is not deleted.`,"delete_recording only removes recordings and their sidecars.");if(![Pe(),...Or()??[]].some(r=>bt(t,r)&&!bt(r,t)))throw new l(`Recording ${t} is outside SCREENCAST_HOME and the allowed directories, so it is not deleted. Add its folder to SCREENCAST_ALLOWED_DIRS or the client's workspace roots, or delete it yourself.`)}var X$={sessionId:yr.string().min(1).optional().describe("Session id of the recording to delete."),input:yr.string().min(1).optional().describe("Or the recording's path.")};function fh(t){try{let e=G$(t);return e.isDirectory()?dh(t).reduce((r,n)=>r+fh(mh(t,n)),0):e.size}catch{return 0}}async function J$(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form){if(Gm())throw new l(`Not deleted: ${Po} requires the user to confirm, but this client does not support MCP elicitation.`);return!1}let n;try{({action:n}=await t.server.elicitInput({message:e,requestedSchema:{type:"object",properties:{}}},{signal:r,timeout:nu}))}catch(o){throw new l(`Not deleted: the confirmation request failed (${z(o)}).`)}if(n!=="accept")throw new l(`Not deleted: ${n==="decline"?"declined":"cancelled"} by the user.`);return!0}function hh(t){t.registerTool("delete_recording",{title:"Delete Recording",description:"Delete a finished recording with its sidecars (event log, webcam, transcript, index, markers, pause parts) and registry entries; reports bytes freed. Asks the user first when the client supports it. Edits made from it are kept.",inputSchema:X$,outputSchema:B({outputPath:yr.string(),deleted:yr.array(yr.string()),bytesFreed:yr.number(),sessionsRemoved:yr.array(yr.string())}),annotations:Ad},async(e,r)=>{try{if(!!e.sessionId==!!e.input)throw new l("Give exactly one of sessionId or input.");let n=oe(),o;if(e.sessionId){let g=n.get(e.sessionId);if(!g)throw new l(`No session with id "${e.sessionId}".`);o=g.outputPath}else o=mh(e.input);lh(o);let i=n.list().filter(g=>Wo(g.outputPath,o)),s=i.find(g=>kn(g.status));if(s)throw new l(`Recording ${s.id} is still ${s.status}; stop it first.`);let a=[];try{a=dh(q$(o))}catch{}if(Uo(o)&&!ph(o).isFile())throw new l(`${o} is not a file, so it is not deleted.`,"delete_recording only removes a recording and its sidecars.");let c=uh(o,a,we("edits")),u=[o,...c.files].filter(g=>Uo(g)&&ph(g).isFile()),d=c.dirs.filter(g=>Uo(g)),p=[...u,...d];if(p.length===0&&i.length===0)throw new l(`Nothing to delete: ${o} does not exist.`);let f=await J$(t,`Delete ${o} and ${p.length-(Uo(o)?1:0)} sidecar file(s)? This cannot be undone.`,r.signal);if(!f&&i.length===0&&!bt(o,Pe()))throw new l(`Not deleted: ${o} is not a recording this server made, and this client cannot ask you to confirm.`,"Pass the recording's sessionId, use a client that supports MCP elicitation, or delete the file yourself.");let m=0,h=[],b=[];for(let g of p){let y=fh(g);try{H$(g,{recursive:d.includes(g),force:!0}),h.push(g),m+=y}catch(v){b.push(`${g}: ${z(v)}`)}}let w=Uo(o)?[]:i.map(g=>g.id);return w.length>0&&n.remove(w),S({outputPath:o,deleted:h,bytesFreed:m,sessionsRemoved:w,confirmedByUser:f,...b.length>0?{failed:b,note:"Some files could not be deleted (in use?); the registry entry was kept if the recording remains."}:{}})}catch(n){return E(n)}})}import{z as xr}from"zod";import{existsSync as Y$}from"node:fs";function O(t,e="Input file"){if(!Y$(t))throw new l(`${e} not found: ${t}`)}function j(t,e,r,n={}){return n.anyContainer||jr(t),nr(t,we(n.dir??"edits"),`${e}-${he()}-${ge()}${r}`,n.overwrite)}var K$={sessionId:xr.string().min(1).describe("Session id of a replay buffer."),lastSec:xr.number().positive().max($n).optional().describe("Seconds back from now (default and max: the buffer length)."),output:xr.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:xr.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),reencode:xr.boolean().optional().describe("Frame-exact re-encode. Default: instant stream copy that may hide up to 2 s of earlier frames.")};function gh(t){t.registerTool("save_replay",{title:"Save Replay",description:"Save the last N seconds of a replay buffer (start_recording replayBufferSec) to an mp4; the buffer keeps running.",inputSchema:K$,outputSchema:B({sessionId:xr.string(),outputPath:xr.string(),durationSec:xr.number()}),annotations:I},async(e,r)=>{try{let n=oe().get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(!n.replay)throw new l(`Session "${e.sessionId}" is not a replay buffer.`,"Start one with start_recording { replayBufferSec: 60 }; for an ordinary recording use stop_recording and trim.");let{ffmpeg:o,ffprobe:i}=k(),s=n.replay,a=Math.min(e.lastSec??s.bufferSec,s.bufferSec),c=j(e.output,"replay",".mp4",{overwrite:e.overwrite,dir:"recordings",anyContainer:!0});s.events&&xi(ke(c),e.overwrite);let u=Date.now(),d=await Wc(s,{ffmpeg:o,ffprobe:i,lastSec:a,output:c,reencode:e.reencode,quality:n.quality,live:n.status==="recording",signal:r.signal}),p=Date.now()-u;ar("info",`Saved ${d.durationSec}s of replay ${n.id} to ${c}.`,{sessionId:n.id,outputPath:c,durationSec:d.durationSec});let f=d.durationSec+.25<a;return S({sessionId:n.id,...d,requestedSec:e.lastSec??null,bufferSec:s.bufferSec,bufferRunning:n.status==="recording",bufferDiskBytes:Gd(s),elapsedMs:p,note:(e.lastSec!==void 0&&e.lastSec>s.bufferSec?`Capped at the buffer length (${s.bufferSec}s). `:"")+(f?"The buffer held less footage than requested (it started recently). ":"")+(d.includesLive?"":"The clip ends at the last completed segment, up to 2 s before now. ")+(n.status==="recording"?"The buffer keeps running; stop_recording discards it unless save: true.":"This buffer is no longer recording; stop_recording discards it.")})}catch(n){return E(n)}})}import{z as Xs}from"zod";var bh=t=>Math.round(t*1e3)/1e3;function wh(t){t.registerTool("pause_recording",{title:"Pause Recording",description:"Pause a recording; until resume_recording nothing is captured, and the gap is left out of the file, events, and markers.",inputSchema:{sessionId:Xs.string().min(1).describe("From start_recording.")},outputSchema:B({sessionId:Xs.string(),status:Xs.string(),recordedSec:Xs.number()}),annotations:qi},async e=>{try{let r=oe(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(os(r,n.id,"pause"),n.status==="paused")return S({sessionId:n.id,status:"paused",recordedSec:bh(ot(n.segments?.parts??[])),note:"Already paused."});let{ffprobe:o}=k(),i=await vm(r,n,{probe:s=>ue(s,{ffprobe:o})});return S({sessionId:n.id,status:"paused",recordedSec:bh(i.recordedSec),segments:i.record?.segments?.parts.length??0,note:"Nothing is captured until resume_recording; stop_recording joins what was recorded."})}catch(r){return E(r)}})}import{z as Js}from"zod";var yh=t=>Math.round(t*1e3)/1e3;function xh(t){t.registerTool("resume_recording",{title:"Resume Recording",description:"Resume a paused recording (same target and settings).",inputSchema:{sessionId:Js.string().min(1).describe("From start_recording.")},outputSchema:B({sessionId:Js.string(),status:Js.string(),recordedSec:Js.number()}),annotations:I},async e=>{try{let r=oe(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(os(r,n.id,"resume"),n.status==="recording")return S({sessionId:n.id,status:"recording",recordedSec:yh(ot(n.segments?.parts??[])),note:"Already recording."});let{ffmpeg:o}=k(),i=await bf(r,n,o);return ar("notice",`Recording ${n.id} resumed.`,{sessionId:n.id}),S({sessionId:n.id,status:"recording",recordedSec:yh(i.recordedSec),pid:i.record.pid,...i.capSec>0?{remainingSec:i.capSec}:{}})}catch(r){return E(r)}})}import{z as Sh}from"zod";function vh(t){t.registerTool("list_video_devices",{title:"List Video Devices",description:"List DirectShow cameras for start_recording's webcam.device.",inputSchema:{},outputSchema:B({devices:Sh.array(Sh.string())}),annotations:fe},async()=>{try{k();let e=await ru(!0);return S({devices:e,note:e.length?`start_recording { webcam: { device: "${e[0]}" } } records it.`:"No camera found."})}catch(e){return E(e)}})}import{z as Et}from"zod";function $h(t){t.registerTool("list_sessions",{title:"List Sessions",description:"List recording sessions, newest first: id, status, target, output path, duration, and whether the recorder is alive. A summary each unless full; get_session gives one in full.",inputSchema:{status:Et.array(Et.enum(["recording","paused","stopped","failed","orphaned"])).min(1).optional().describe("Only these."),limit:Et.number().int().min(1).max(100).optional().describe("At most this many (default all)."),full:Et.boolean().optional().describe("Whole records.")},outputSchema:B({count:Et.number().int(),sessions:Et.array(B({id:Et.string(),status:Et.string(),outputPath:Et.string(),alive:Et.boolean()}))}),annotations:fe},async e=>{try{let r=oe().list(),o=r.filter(s=>!e.status||e.status.includes(s.status)).sort((s,a)=>a.startedAt.localeCompare(s.startedAt)).slice(0,e.limit??1/0).map(s=>{let a=s.status==="recording"&&Ge(s.pid);return e.full?{...s,alive:a}:{id:s.id,status:s.status,target:s.target,outputPath:s.outputPath,startedAt:s.startedAt,...s.stoppedAt?{stoppedAt:s.stoppedAt}:{},durationSec:s.durationSec??null,...s.endReason?{endReason:s.endReason}:{},...s.error?{error:s.error.split(`
|
|
320
|
-
`)[0]}:{},alive:
|
|
319
|
+
`)&&!r.events&&!r.markers&&!r.transcript?n.end=r.end:e.push({...r,ocr:[...r.ocr]})}return e}function gh(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?` ${Fu(i.role)}${i.name?` ${i.name}`:""}${i.app?` ${i.app}`:""}`:"")}else r.type==="key"?o=`shortcut ${r.keys??"key"}`:r.type==="typing"?o=`typing ${vr(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:vr(r.t),text:o})}return e}function bh(t){return t.map(e=>({t:vr(e.t),text:e.label}))}function wh(t){return t.map(e=>({t:vr(e.start),text:e.text.replace(/\s+/g," ").trim()})).filter(e=>e.text)}function en(t,e,r){let n=t.map(i=>{let{[r]:s,...a}=i;return a});if(n.length===0)return n;let o=i=>{let s=0,a=n.length-1,c=-1;for(;s<=a;){let u=s+a>>1;n[u].start<=i?(c=u,s=u+1):a=u-1}return c!==-1&&i<n[c].end?c:-1};for(let i of[...e].sort((s,a)=>s.t-a.t)){let s=o(i.t);s===-1&&(s=i.t<n[0].start?0:n.length-1);let a=n[s];(a[r]??=[]).push(i)}return n}function ta(t){let e=sh(t),r=ih("sha1"),n=64*1024,o=Q$(t,"r");try{let i=Buffer.alloc(n);for(let s of e.size>n?[0,e.size-n]:[0]){let a=tk(o,i,0,n,s);r.update(i.subarray(0,a))}}finally{V$(o)}return{size:e.size,mtimeMs:Math.round(e.mtimeMs),sample:r.digest("hex")}}function ra(t,e){return t.size===e.size&&t.mtimeMs===e.mtimeMs&&t.sample===e.sample}function ck(t){try{let e=JSON.parse(t);return e?.version!==ju||!Array.isArray(e.segments)||!e.fingerprint?null:e}catch{return null}}function Ko(t){try{return ck(Z$(t,"utf8"))}catch{return null}}var Zr=new Map,uk=64;function Gu(t){let e;try{e=sh(t)}catch{return Zr.delete(t),null}let r=Zr.get(t);if(r&&r.size===e.size&&r.mtimeMs===e.mtimeMs)return r.index;let n=Ko(t);return n?(Zr.size>=uk&&Zr.delete(Zr.keys().next().value),Zr.set(t,{size:e.size,mtimeMs:e.mtimeMs,index:n}),n):(Zr.delete(t),null)}function yh(t,e){let r=`${t}.${process.pid}.tmp`;nk(r,JSON.stringify(e)),rk(r,t)}function lk(t){let e=t.replace(/\s+/g," ").trim();return e.length>rh?`${e.slice(0,rh-1)}\u2026`:e}function pk(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 xh(t,e){if(t.trim().length===0)throw new l("query must not be empty.");if(t.length>Qr)throw new l(`The query is ${t.length} characters; at most ${Qr} are allowed.`);if(!e&&!/[\p{L}\p{N}]/u.test(zt(t)))throw new l("query needs at least one letter or digit.","For punctuation, use regex: true.");e&&In([""],t)}var oh=new WeakMap;function dk(t,e){let r=oh.get(t);r||oh.set(t,r=new Map);let n=r.get(e);if(n)return n;let o=pk(t),i=e?je(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=>zt(c.text))};return r.set(e,a),a}function qu(t,e,r={}){if(xh(e,r.regex===!0),r.video!==void 0&&!Ks(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?We:r.secretPattern,{items:o,norm:i}=dk(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=In(o.map(f=>f.text),e);o.forEach((f,m)=>{(p[m]??[]).length>0&&a(f,2)})}else{let p=zt(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??Ys).map(p=>{let f=t.segments[p.seg],m=p.matches.slice(0,sk).map(h=>({source:h.source,t:h.t,text:lk(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 mk=20;function fk(t){return[Wn(t,"recordings"),Wn(t,"edits"),Wn(t,"edits","indexes")]}function Sh(t){let e=[];for(let r of fk(t)){let n;try{n=ek(r)}catch{continue}for(let o of n)o.endsWith(".index.json")&&e.push(Wn(r,o))}return e}function vh(t,e,r={}){xh(e,r.regex===!0);let n=new Map;for(let c of t){let u=Js(c.index.video).toLowerCase(),d=n.get(u);(!d||c.index.createdAt>d.index.createdAt)&&n.set(u,c)}let o=r.limit??Ys,i=[],s=[],a=0;for(let c of n.values()){let u=qu(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,mk),searched:n.size}}async function na(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=se().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 nr(n.id),!Bn(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path,i=n.markers?.length?n.markers:He(n.outputPath);return{path:n.outputPath,eventsPath:o&&Bn(o)?o:null,markers:i}}let e=t.input;if(!Bn(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=he(e);return{path:e,eventsPath:Bn(r)?r:null,markers:He(e)}}import{basename as $h}from"node:path";function kh(t,e,r){let n=he(t),o=Zs(t,e),i=[n.jsonl,n.raw,`${n.raw}.stop`,Jr(t),Jo(t),Vs(t,r),wr(t),ft(t),st(t),as(t),...o.path&&!o.ambiguous?[o.path]:[]];return{files:[...new Set(i)].filter(s=>$h(s)!==$h(t)),dirs:[Et(t)]}}var hk=/\.(mp4|m4v|mkv|mov|webm|avi|gif|webp)$/i;function Eh(t){if(ir(t,"Recording"),!hk.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(![Fe(),...Wr()??[]].some(r=>vt(t,r)&&!vt(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 yk={sessionId:$r.string().min(1).optional().describe("Session id of the recording to delete."),input:$r.string().min(1).optional().describe("Or the recording's path.")};function Mh(t){try{let e=bk(t);return e.isDirectory()?Rh(t).reduce((r,n)=>r+Mh(Th(t,n)),0):e.size}catch{return 0}}async function xk(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form){if(Qm())throw new l(`Not deleted: ${jo} 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:au}))}catch(o){throw new l(`Not deleted: the confirmation request failed (${j(o)}).`)}if(n!=="accept")throw new l(`Not deleted: ${n==="decline"?"declined":"cancelled"} by the user.`);return!0}function Ah(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:yk,outputSchema:N({outputPath:$r.string(),deleted:$r.array($r.string()),bytesFreed:$r.number(),sessionsRemoved:$r.array($r.string())}),annotations:Nd},async(e,r)=>{try{if(!!e.sessionId==!!e.input)throw new l("Give exactly one of sessionId or input.");let n=se(),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=Th(e.input);Eh(o);let i=n.list().filter(g=>Yo(g.outputPath,o)),s=i.find(g=>An(g.status));if(s)throw new l(`Recording ${s.id} is still ${s.status}; stop it first.`);let a=[];try{a=Rh(wk(o))}catch{}if(Vo(o)&&!_h(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=kh(o,a,ye("edits")),u=[o,...c.files].filter(g=>Vo(g)&&_h(g).isFile()),d=c.dirs.filter(g=>Vo(g)),p=[...u,...d];if(p.length===0&&i.length===0)throw new l(`Nothing to delete: ${o} does not exist.`);let f=await xk(t,`Delete ${o} and ${p.length-(Vo(o)?1:0)} sidecar file(s)? This cannot be undone.`,r.signal);if(!f&&i.length===0&&!vt(o,Fe()))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=Mh(g);try{gk(g,{recursive:d.includes(g),force:!0}),h.push(g),m+=y}catch(v){b.push(`${g}: ${j(v)}`)}}let w=Vo(o)?[]:i.map(g=>g.id);return w.length>0&&n.remove(w),S({outputPath:o,deleted:h,bytesFreed:m,sessionsRemoved:w,confirmedByUser:f,...b.length>0?{failed:b,note:"Some files could not be deleted (in use?); the registry entry was kept if the recording remains."}:{}})}catch(n){return E(n)}})}import{z as kr}from"zod";var Sk={sessionId:kr.string().min(1).describe("Session id of a replay buffer."),lastSec:kr.number().positive().max(Kr).optional().describe("Seconds back from now (default and max: the buffer length)."),output:kr.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:kr.boolean().optional().describe("Replace an existing output (default false)."),reencode:kr.boolean().optional().describe("Frame-exact re-encode. Default: instant stream copy that may hide up to 2 s of earlier frames.")};function Ch(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:Sk,outputSchema:N({sessionId:kr.string(),outputPath:kr.string(),durationSec:kr.number()}),annotations:C},async(e,r)=>{try{let n=se().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&&So(he(c),e.overwrite);let u=Date.now(),d=await Io(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;kt("info",`Saved ${d.durationSec}s of replay ${n.id} to ${c}.`,{sessionId:n.id,outputPath:c,durationSec:d.durationSec});let f=d.durationSec+.25<a;return S({sessionId:n.id,...d,requestedSec:e.lastSec??null,bufferSec:s.bufferSec,bufferRunning:n.status==="recording",bufferDiskBytes:Qd(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 oa}from"zod";var Ph=t=>Math.round(t*1e3)/1e3;function Ih(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:oa.string().min(1).describe("From start_recording.")},outputSchema:N({sessionId:oa.string(),status:oa.string(),recordedSec:oa.number()}),annotations:ts},async e=>{try{let r=se(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(ms(r,n.id,"pause"),n.status==="paused")return S({sessionId:n.id,status:"paused",recordedSec:Ph(it(n.segments?.parts??[])),note:"Already paused."});let{ffprobe:o}=k(),i=await Mm(r,n,{probe:s=>ue(s,{ffprobe:o})});return S({sessionId:n.id,status:"paused",recordedSec:Ph(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 ia}from"zod";var Fh=t=>Math.round(t*1e3)/1e3;function Oh(t){t.registerTool("resume_recording",{title:"Resume Recording",description:"Resume a paused recording (same target and settings).",inputSchema:{sessionId:ia.string().min(1).describe("From start_recording.")},outputSchema:N({sessionId:ia.string(),status:ia.string(),recordedSec:ia.number()}),annotations:C},async e=>{try{let r=se(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(ms(r,n.id,"resume"),n.status==="recording")return S({sessionId:n.id,status:"recording",recordedSec:Fh(it(n.segments?.parts??[])),note:"Already recording."});let{ffmpeg:o}=k(),i=await Rf(r,n,o);return kt("notice",`Recording ${n.id} resumed.`,{sessionId:n.id}),S({sessionId:n.id,status:"recording",recordedSec:Fh(i.recordedSec),pid:i.record.pid,...i.capSec>0?{remainingSec:i.capSec}:{}})}catch(r){return E(r)}})}import{z as Nh}from"zod";function Dh(t){t.registerTool("list_video_devices",{title:"List Video Devices",description:"List DirectShow cameras for start_recording's webcam.device.",inputSchema:{},outputSchema:N({devices:Nh.array(Nh.string())}),annotations:ge},async()=>{try{k();let e=await su(!0);return S({devices:e,note:e.length?`start_recording { webcam: { device: "${e[0]}" } } records it.`:"No camera found."})}catch(e){return E(e)}})}import{z as ht}from"zod";function Lh(t){t.registerTool("list_sessions",{title:"List Sessions",description:"List recording sessions, newest first: id, status, target, output path, duration, and whether the recorder is alive. A summary each unless full; get_session gives one in full.",inputSchema:{status:ht.array(ht.enum(["recording","paused","stopped","failed","orphaned"])).min(1).optional().describe("Only these."),limit:ht.number().int().min(1).max(100).optional().describe("At most this many (default all)."),query:ht.string().min(1).max(80).optional().describe("In label, id, target or output."),full:ht.boolean().optional().describe("Whole records.")},outputSchema:N({count:ht.number().int(),sessions:ht.array(N({id:ht.string(),status:ht.string(),outputPath:ht.string(),alive:ht.boolean()}))}),annotations:ge},async e=>{try{let r=se().list(),n=e.query?.toLowerCase(),i=r.filter(a=>!e.status||e.status.includes(a.status)).filter(a=>!n||[a.label,a.id,a.target,a.outputPath].some(c=>c?.toLowerCase().includes(n))).sort((a,c)=>c.startedAt.localeCompare(a.startedAt)).slice(0,e.limit??1/0).map(a=>{let c=a.status==="recording"?ze(a.pid):a.status==="paused"?ze(a.serverPid??null):!1;return e.full?{...a,alive:c}:{id:a.id,...a.label?{label:a.label}:{},status:a.status,target:a.target,outputPath:a.outputPath,startedAt:a.startedAt,...a.stoppedAt?{stoppedAt:a.stoppedAt}:{},durationSec:a.durationSec??null,...a.endReason?{endReason:a.endReason}:{},...a.error?{error:a.error.split(`
|
|
320
|
+
`)[0]}:{},alive:c}}),s=ff();return S({count:i.length,...i.length<r.length?{total:r.length}:{},sessions:i,...s.length?{armed:s}:{}})}catch(r){return E(r)}})}import{z as jn}from"zod";import{existsSync as vk}from"node:fs";var $k={sessionId:jn.string().min(1).describe("Session id returned by start_recording.")};function Bh(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:$k,outputSchema:N({id:jn.string(),status:jn.string(),outputPath:jn.string(),alive:jn.boolean(),fileExists:jn.boolean()}),annotations:ge},async e=>{try{if(Cs(e.sessionId)){let n=Uo(e.sessionId);if(!n)throw new l(`No armed recording with id "${e.sessionId}".`);return S({...n,outputPath:"",alive:!1,fileExists:!1,...n.sessionId?{note:`It started recording ${n.sessionId}; get_session that id for it.`}:{}})}let r=se().get(e.sessionId);if(!r)throw new l(`No session with id "${e.sessionId}".`);return S({...r,alive:r.status==="recording"&&ze(r.pid),fileExists:vk(r.outputPath)})}catch(r){return E(r)}})}import{z as Ge}from"zod";import{existsSync as kk,readFileSync as Ek}from"node:fs";var Wh=200,_k=5e3,Rk={sessionId:Ge.string().min(1).optional().describe("Session id of a recording started with events: true."),input:Ge.string().optional().describe("Or a recording path, or its .events.jsonl."),from:Ge.number().min(0).optional().describe("Earliest video second."),to:Ge.number().min(0).optional().describe("Latest video second."),types:Ge.array(Ge.enum(Sc)).optional().describe("down/up (mouse buttons; clicks are down), move (sampled cursor), wheel, key (shortcut), typing (burst), gap (events may be missing)."),inFrameOnly:Ge.boolean().optional().describe("Drop events whose cursor was outside the recorded area."),limit:Ge.number().int().min(1).max(_k).optional().describe(`Most events to return (default ${Wh}).`)};function jh(t){t.registerTool("read_events",{title:"Read Input Events",description:"Read the input events (clicks, scroll, cursor, shortcuts, typing bursts) of a recording made with events: true, in video seconds and pixels; e.g. types: ['down'], then sample_frames there.",inputSchema:Rk,outputSchema:N({eventsPath:Ge.string(),total:Ge.number().int(),matched:Ge.number().int(),returned:Ge.number().int(),summary:Ge.record(Ge.string(),Ge.number())}),annotations:ge},async e=>{try{let r;if(e.sessionId){let a=se().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:he(e.input).jsonl;else throw new l("Pass sessionId or input.");if(!kk(r))throw new l(`No event log at ${r}. Record with start_recording events: true.`);let n=Ie(Ek(r,"utf8")),o=Ti(n,e),i=e.limit??Wh,s=pp(n);return S({eventsPath:r,total:n.length,matched:o.length,returned:Math.min(i,o.length),summary:bn(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 Un}from"zod";var Tk={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},Mk={label:Un.string().min(1).max(Do).describe('e.g. "bug appears".'),sessionId:Un.string().min(1).optional().describe("Recording to mark (a stopped one needs at)."),input:Un.string().min(1).optional().describe("Or a video path (needs at)."),at:Un.number().min(0).optional().describe("Video second (default: now, while recording).")};function Uh(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:Mk,outputSchema:N({count:Un.number().int(),markersPath:Un.string()}),annotations:Tk},async e=>{try{if(!e.sessionId&&!e.input)throw new l("Pass sessionId or input.");if(e.sessionId){let i=Bo(se(),e.sessionId,e.label,e.at);return S({sessionId:e.sessionId,marker:{t:Math.round(i.t*1e3)/1e3,label:Lo(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),sr(wr(r));let n=ws(He(r),{t:e.at,label:e.label,at:new Date().toISOString()}),o=yr(r,n);return S({marker:{t:Math.round(e.at*1e3)/1e3,label:Lo(e.label)},count:n.length,markersPath:o})}catch(r){return E(r)}})}import{z as $e}from"zod";import{extname as Pk,join as Vh}from"node:path";import{existsSync as Ik,mkdtempSync as Fk,readFileSync as Ok,rmSync as Nk,writeFileSync as Dk}from"node:fs";import{tmpdir as Lk}from"node:os";import{existsSync as Ak}from"node:fs";var aa="SCREENCAST_WHISPER_MODEL",zh=`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 ${aa}.`;function Er(t,e=process.env){let r=t??e[aa];if(!r||r.trim().length===0)throw new l("No whisper model given.",zh);if(!Ak(r))throw new l(`Whisper model not found: ${r}`,zh);return r}function zn(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=${xe(e)}:language=${n}:format=srt:destination=${xe(r)}:use_gpu=false`+(o?":max_len=1":""),"-f","null","-"]}function Xh(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 Hh=/(\d+):(\d{2}):(\d{2})[,.](\d{3})/,Gh=t=>Number(t[1])*3600+Number(t[2])*60+Number(t[3])+Number(t[4])/1e3;function qh(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 qe(t,e={}){let r=[];for(let n of t.replace(/\r\n/g,`
|
|
321
321
|
`).split(/\n\s*\n/)){let o=n.split(`
|
|
322
|
-
`).map(m=>m.trim()).filter(m=>m.length>0),i=o.findIndex(m=>m.includes("-->")),s=o[i];if(s===void 0)continue;let[a,c]=s.split("-->"),u=a?.match(
|
|
323
|
-
`);if(!p)continue;let f=e.index&&i>0&&/^\d+$/.test(o[i-1])?Number(o[i-1]):void 0;r.push({start:
|
|
324
|
-
${
|
|
322
|
+
`).map(m=>m.trim()).filter(m=>m.length>0),i=o.findIndex(m=>m.includes("-->")),s=o[i];if(s===void 0)continue;let[a,c]=s.split("-->"),u=a?.match(Hh),d=c?.match(Hh);if(!u||!d)continue;let p=o.slice(i+1).join(`
|
|
323
|
+
`);if(!p)continue;let f=e.index&&i>0&&/^\d+$/.test(o[i-1])?Number(o[i-1]):void 0;r.push({start:Gh(u),end:Gh(d),text:p,...f!==void 0&&{index:f}})}return r}function gt(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 at(t){return t.map((e,r)=>`${r+1}
|
|
324
|
+
${qh(e.start)} --> ${qh(e.end)}
|
|
325
325
|
${e.text}
|
|
326
326
|
`).join(`
|
|
327
|
-
`)}var
|
|
328
|
-
`).trim();if(!o)throw new l(`Translation ${n+1} is empty.`);if(o.length>
|
|
329
|
-
`)}})}function
|
|
330
|
-
${t}</script>`)}function vk(t){if(t.sessionId){let e=oe().get(t.sessionId);if(!e)throw new l(`No session with id "${t.sessionId}".`);if(e.status==="recording"||e.status==="paused")throw new l("The recording is still running; stop it first.");return e.outputPath}if(t.input)return t.input;throw new l("Pass input or sessionId.")}function $k(t){return t&&t.length>0?{markers:t.map(({t:e,label:r})=>({t:e,label:r}))}:{}}function Yh(t){t.registerResource("review-player",zo,{title:"Recording review player",description:"Interactive player: scrub, trim, and draw redaction boxes on a recording.",mimeType:Qs},async()=>({contents:[{uri:zo,mimeType:Qs,text:Sk(),_meta:{ui:{prefersBorder:!0}}}]})),t.registerTool("review_recording",{title:"Review Recording",description:"Open a recording for a person to review: in MCP Apps clients an inline player to scrub, trim, and redact, then export; elsewhere just the video's details.",inputSchema:{input:dt.string().optional().describe("Path to the video."),sessionId:dt.string().optional().describe("Or the session id of a stopped recording.")},outputSchema:B({input:dt.string(),durationSec:dt.number().nullable(),width:dt.number().nullable(),height:dt.number().nullable(),fps:dt.number().nullable(),hasAudio:dt.boolean()}),annotations:fe,_meta:Bh},async n=>{try{k();let o=vk(n);O(o);let i=await W(o);return S({input:o,durationSec:i.durationSec,width:i.width,height:i.height,fps:i.fps,hasAudio:i.audioCodec!==null,...$k(n.sessionId?oe().get(n.sessionId)?.markers??We(o):We(o)),note:"Clients with MCP Apps show an inline review player for this result. Without it, look with contact_sheet or sample_frames, then trim and redact with pipeline."})}catch(o){return E(o)}});let e=t.registerTool("player_frames",{title:"Player Frames",description:"Preview frames for the review player: JPEGs on an even grid over the video plus frames at scene changes, with their real times. Used by the inline player; agents should use sample_frames or contact_sheet instead.",inputSchema:{input:dt.string().min(1).describe("Path to the video."),maxFrames:dt.number().int().min(1).max(jh).optional().describe(`Frames on the even grid (default ${Zs}); scene-change frames come on top, up to as many again.`),width:dt.number().int().min(64).max(1280).optional().describe(`Frame width (default ${Uu}).`)},annotations:fe,_meta:{ui:{visibility:["app"]}}},async(n,o)=>{try{k(),O(n.input);let i=await W(n.input),s=i.durationSec??0,a=Uh(s,n.maxFrames??Zs),c=He(".txt"),u,d;try{let g=await Ur(zh(n.input,a,n.width??Uu,c),pe(s),{signal:o.signal});u=qh(g),d=Hh(yk(c)?Jh(c,"utf8"):"").slice(0,u.length)}finally{xk(c,{force:!0})}let[p]=d;if(!p)throw new l("ffmpeg returned no preview frames.");let f=Gh(d,a.count).flatMap(g=>{let y=d[g],v=u[g];return y&&v?[{frame:y,jpeg:v}]:[]}),m=p.timeSec,h=[];try{h=(await gr(n.input,o.signal)).markers.map(({t:g,label:y})=>({t:g,label:y}))}catch{}let b=f.map(({frame:g})=>Math.round((g.timeSec-m)*1e3)/1e3),w=f.flatMap(({frame:g},y)=>g.scene?[y]:[]);return{content:[{type:"text",text:JSON.stringify({input:n.input,durationSec:s,width:i.width,height:i.height,hasAudio:i.audioCodec!==null,frameTimes:b,intervalSec:a.intervalSec,sceneFrames:w,markers:h})},...f.map(({jpeg:g})=>({type:"image",data:g.toString("base64"),mimeType:"image/jpeg"}))]}}catch(i){return E(i)}});e.disable();let r=t.server.oninitialized;t.server.oninitialized=()=>{r?.(),Wh(t.server.getClientCapabilities())&&e.enable()}}import{z as mt}from"zod";import{readFileSync as kk,rmSync as Ek}from"node:fs";var Me=1280,ea=8,Ho=20;function _k(t,e,r){if(!Number.isInteger(r)||r<16)throw new l("maxImageWidth must be an integer of at least 16.");return["-y","-v","error","-i",t,"-frames:v","1","-vf",`scale='min(${r},iw)':-2`,"-q:v","4",...Te(e)]}function ta(t){return Math.max(0,Math.min(Ho,Math.floor(t??ea)))}async function Ce(t,e=Me,r=ea){let n=t.slice(0,r);return{images:await qe(n,async i=>{let s=He(".jpg");try{return await te(_k(i,s,e),3e4),{type:"image",data:kk(s).toString("base64"),mimeType:"image/jpeg"}}finally{Ek(s,{force:!0})}}),omitted:t.length-n.length}}var Tk={target:mt.string().describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | region:<x>,<y>,<w>,<h>. Titles match exactly, else as a substring; topmost wins."),exactTitle:mt.boolean().optional().describe("window: targets match the whole title only, never a substring (default false)."),backend:mt.enum(["gdigrab","wgc"]).optional().describe("gdigrab (default, ~0.2 s): what is visible. wgc (window:, FFmpeg 8+, ~1-2 s): the window even if covered."),output:mt.string().optional().describe("Optional output .png path. Defaults to a file under SCREENCAST_HOME/screenshots."),overwrite:mt.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),returnImage:mt.boolean().optional().describe("Return the image inline (default true; the PNG on disk stays full size)."),maxImageWidth:mt.number().int().min(16).optional().describe(`Max inline image width (default ${Me}).`)};function Kh(t){t.registerTool("screenshot",{title:"Take Screenshot",description:"Capture one PNG of the screen, a monitor, a window, or a region, returned inline and by path.",inputSchema:Tk,outputSchema:B({outputPath:mt.string(),target:mt.string(),backend:mt.string(),inlineImages:mt.number().int()}),annotations:I},async(e,r)=>{try{k();let n=await ut(e.target,{exactTitle:e.exactTitle,backend:e.backend}),{window:o}=n,i=j(e.output,"shot",".png",{overwrite:e.overwrite,dir:"screenshots",anyContainer:!0}),s=e.backend??"gdigrab";await Dt(t,`Take a screenshot of ${Nt(e.target,o)}, saved to ${i}?`,r.signal),await Lt(n,i,s);let a=e.returnImage===!1?[]:(await Ce([i],e.maxImageWidth??Me,1)).images;return S({outputPath:i,target:e.target,backend:s,...o?pr(o):{},inlineImages:a.length},a)}catch(n){return E(n)}})}import{z as Fe}from"zod";import{join as zu}from"node:path";import{mkdirSync as Rk,readdirSync as Vh,existsSync as Ak,rmSync as Mk}from"node:fs";var Ck={input:Fe.string().min(1).describe("Path to the source video file."),mode:Fe.enum(["fps","timestamps","scenes"]).optional().describe("scenes: only frames where the screen changed (strongest first), usually the cheapest review. Default: fps or timestamps, whichever is given."),fps:Fe.number().positive().optional().describe("Frames per second (mode fps)."),timestamps:Fe.array(Fe.number().nonnegative()).optional().describe("Seconds to grab a frame at (mode timestamps)."),sceneThreshold:Fe.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed to count, 0-1 (default ${wt}).`),dedupe:Fe.boolean().optional().describe("Mode fps: drop near-duplicate frames (default false)."),outputDir:Fe.string().optional().describe("Optional folder for the frames (a relative path resolves under SCREENCAST_HOME/frames). Defaults to SCREENCAST_HOME/frames/<id>."),maxFrames:Fe.number().int().min(1).max(Ec).optional().describe(`Frame cap (default ${Mi}); fps is lowered to fit while still spanning the video.`),returnImages:Fe.boolean().optional().describe("Return the first maxInlineImages frames inline (default true)."),maxInlineImages:Fe.number().int().min(0).max(Ho).optional().describe(`Frames to embed inline (default ${ea}); all are listed by path.`),maxImageWidth:Fe.number().int().min(16).optional().describe(`Max inline image width (default ${Me}).`)};function Qh(t){t.registerTool("sample_frames",{title:"Sample Frames",description:"Sample PNG frames from a video (by fps, timestamps, or scene changes) and return the first few inline so the model can see what happened.",inputSchema:Ck,outputSchema:B({frameDir:Fe.string(),frameCount:Fe.number().int(),frames:Fe.array(Fe.string()),mode:Fe.string()}),annotations:fe},async(e,r)=>{try{k(),O(e.input);let n=e.fps!==void 0,o=e.timestamps!==void 0&&e.timestamps.length>0,i=e.mode??(o?"timestamps":"fps");if(!(i==="scenes"?!n&&!o:i==="fps"?n&&!o:o&&!n))throw new l("Use exactly one way to pick frames: fps (fixed rate), timestamps (explicit offsets), or mode: 'scenes' (with neither fps nor timestamps).");let a=e.maxFrames??Mi;if(o&&e.timestamps.length>a)throw new l(`${e.timestamps.length} timestamps exceeds maxFrames (${a}). Pass fewer timestamps, or raise maxFrames (up to ${Ec}).`);let c=i==="timestamps"?null:(await W(e.input)).durationSec,u=i==="fps"?Ci(c,e.fps,a):null,d=null,p=[];if(i==="scenes"){let{ffmpeg:w}=k(),g=await se(w,ir(e.input,e.sceneThreshold??wt),pe(c),{signal:r.signal});if(g.code!==0)throw new l(`Scene scan failed (exit ${g.code}): ${g.stderr.trim().slice(-400)}`);d=sr(g.stdout),p=bn(d,a)}let f=fn(e.outputDir,we("frames"))??zu(we("frames"),`sample-${he()}-${ge()}`);Rk(f,{recursive:!0});let m=[],h=[];if(u){let w=x=>x.endsWith(".png"),g=new Set(Vh(f).filter(w)),y=_p(g,`${he()}-${ge()}`),v=mn(f,`${y}%05d.png`);await te(Pi(e.input,u.fps,v,a,e.dedupe===!0),pe(c),{signal:r.signal}),m=Vh(f).filter(x=>w(x)&&x.startsWith(y)&&!g.has(x)).sort().map(x=>zu(f,x))}else{let w=i==="scenes"?p:e.timestamps,g=await qe(w,async(y,v)=>{let x=zu(f,`frame_${String(v).padStart(3,"0")}_${y}s.png`);return Mk(x,{force:!0}),await te(wn(e.input,y,x),6e4,{signal:r.signal}),x});for(let[y,v]of g.entries())Ak(v)?m.push(v):h.push(w[y])}let b=e.returnImages===!1?{images:[],omitted:0}:await Ce(m,e.maxImageWidth??Me,ta(e.maxInlineImages));return S({frameDir:f,frameCount:m.length,frames:m,mode:u?`fps=${u.fps}${e.dedupe?" (deduped)":""}`:d?`scenes (threshold ${e.sceneThreshold??wt})`:`timestamps=[${e.timestamps.join(", ")}]`,...d?{frameTimes:p,sceneChangesFound:d.length,...d.length+1>a?{capNote:`Found ${d.length} scene changes; kept the opening frame and the ${a-1} strongest (maxFrames ${a}). Raise sceneThreshold to keep only bigger changes, or raise maxFrames.`}:{}}:{},...u?.clamped?{requestedFps:e.fps,capNote:`fps=${e.fps} would write about ${u.requestedFrames} frames, over maxFrames (${a}); sampled at fps=${u.fps} instead so the frames still span the whole video. Raise maxFrames or use timestamps for more detail.`}:{},...u&&!u.clamped&&m.length>=a?{capNote:`Stopped at maxFrames (${a}); the video's length could not be probed in advance.`}:{},inlineImages:b.images.length,...b.omitted>0?{inlineNote:`Embedded the first ${b.images.length} of ${m.length} frames inline; the other ${b.omitted} are on disk at the listed paths.`}:{},...h.length>0?{skippedTimestamps:h,note:`No frame was written for ${h.length} timestamp(s) past the end of the video: [${h.join(", ")}].`}:{}},b.images)}catch(n){return E(n)}})}import{z as Ze}from"zod";var Pk={input:Ze.string().min(1).describe("Path to the source video."),count:Ze.number().int().min(1).max(Mf).optional().describe(`Frames to tile (default ${No}).`),mode:Ze.enum(["even","scenes"]).optional().describe("even (default) or scenes (strongest changes; static stretches take no tiles)."),sceneThreshold:Ze.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed, 0-1 (default ${wt}).`),columns:Ze.number().int().min(1).max(12).optional().describe("Tiles per row (default: roughly square)."),tileWidth:Ze.number().int().min(64).max(1920).optional().describe(`Tile width in px (default ${Do}).`),poster:Ze.boolean().optional().describe("Write one representative poster frame instead of a sheet."),output:Ze.string().optional().describe("Optional output .png path. Defaults under SCREENCAST_HOME/frames."),overwrite:Ze.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),returnImage:Ze.boolean().optional().describe("Return the sheet inline (default true)."),maxImageWidth:Ze.number().int().min(16).optional().describe(`Max inline image width (default ${Me}).`)};function Zh(t){t.registerTool("contact_sheet",{title:"Contact Sheet",description:"Tile timestamped frames of a video into one image to see a whole recording at a glance (the cheapest first look).",inputSchema:Pk,outputSchema:B({outputPath:Ze.string(),inlineImages:Ze.number().int()}),annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();O(e.input);let{durationSec:o}=await W(e.input);if(o===null)throw new l(`Could not read duration of ${e.input}.`);let i=e.poster?"poster":"sheet",s=nr(e.output,we("frames"),`${i}-${he()}-${ge()}.png`,e.overwrite),a=e.tileWidth??Do,c;if(e.poster)await te(Cf(e.input,o,s,Math.max(a,1280)),pe(o),{signal:r.signal}),c={outputPath:s,poster:!0};else{let d=e.count??No,p;if(e.mode==="scenes"){let m=await se(n,ir(e.input,e.sceneThreshold??wt),pe(o),{signal:r.signal});if(m.code!==0)throw new l(`Scene scan failed (exit ${m.code}): ${m.stderr.trim().slice(-400)}`);p=bn(sr(m.stdout),d)}else p=Ms(o,d);let f=await Cs(e.input,p,s,{tileWidth:a,columns:e.columns},r.signal);c={outputPath:s,mode:e.mode??"even",frameTimes:p,columns:f.columns,rows:f.rows}}let u=e.returnImage===!1?[]:(await Ce([s],e.maxImageWidth??Me,1)).images;return S({...c,inlineImages:u.length},u)}catch(n){return E(n)}})}import{z as Rt}from"zod";import{rmSync as Nk}from"node:fs";var eg=320,Ik=4,Fk=1600,_t=8,Go=12;function tg(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(eg,t),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function na(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(t,Math.max(eg,Math.min(Fk,Math.ceil(t/Ik)))),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function oa(t,e){switch(t.kind){case"region":return{x:t.x,y:t.y,width:t.w,height:t.h};case"monitor":{let r=e.find(n=>n.index===t.index);if(!r)throw new l(`No monitor ${t.index}.`);return{x:r.x,y:r.y,width:r.width,height:r.height}}case"full":{if(e.length===0)throw new l("No monitors found.");let r=Math.min(...e.map(s=>s.x)),n=Math.min(...e.map(s=>s.y)),o=Math.max(...e.map(s=>s.x+s.width)),i=Math.max(...e.map(s=>s.y+s.height));return{x:r,y:n,width:o-r,height:i-n}}default:throw new l("Internal: resolve window targets to a region first.")}}function Ok(t,e){if(t.length!==e.length||t.length===0)throw new l("Frames differ in size.");let r=0;for(let n=0;n<t.length;n++)r+=Math.abs(t[n]-e[n]);return r/t.length/255}function Tt(t,e,r,n,o={}){if(t.length!==r*n||e.length!==r*n)throw new l("Frame size does not match its dimensions.");let i=o.pixelThreshold??Go,s=Math.ceil(r/_t),a=Math.ceil(n/_t),c=new Uint8Array(s*a);for(let g=0;g<a;g++)for(let y=0;y<s;y++){let v=0,x=0;for(let R=g*_t;R<Math.min(n,(g+1)*_t);R++)for(let T=y*_t;T<Math.min(r,(y+1)*_t);T++){let M=R*r+T;v+=Math.abs(t[M]-e[M]),x++}v/x>i&&(c[g*s+y]=1)}let u=new Uint8Array(s*a),d=[];for(let g=0;g<c.length;g++){if(!c[g]||u[g])continue;let y={x0:1/0,y0:1/0,x1:-1,y1:-1,cells:0},v=[g];for(u[g]=1;v.length>0;){let x=v.pop(),R=x%s,T=Math.floor(x/s);y.x0=Math.min(y.x0,R),y.y0=Math.min(y.y0,T),y.x1=Math.max(y.x1,R),y.y1=Math.max(y.y1,T),y.cells++;for(let M=-1;M<=1;M++)for(let H=-1;H<=1;H++){let G=R+H,L=T+M;if(G<0||L<0||G>=s||L>=a)continue;let C=L*s+G;c[C]&&!u[C]&&(u[C]=1,v.push(C))}}d.push(y)}let p=o.scaleX??o.scale??1,f=o.scaleY??o.scale??1,m=o.origin?.x??0,h=o.origin?.y??0,b=d.sort((g,y)=>y.cells-g.cells).slice(0,o.maxRegions??20).map(g=>{let y=g.x0*_t,v=g.y0*_t,x=Math.min(r,(g.x1+1)*_t)-y,R=Math.min(n,(g.y1+1)*_t)-v;return{x:m+Math.round(y*p),y:h+Math.round(v*f),width:Math.round(x*p),height:Math.round(R*f)}}),w=c.reduce((g,y)=>g+y,0);return{meanDiff:Ok(t,e),changedFraction:w/c.length,regions:b}}function rg(t,e,r){return{scaleX:t.width/e.width,scaleY:t.height/e.height,pixelThreshold:r}}var ra=class{constructor(e,r,n,o={}){this.width=r;this.height=n;this.opts=o;this.previous=e,this.anchor=e}width;height;opts;previous;anchor;push(e){let r=Tt(this.previous,e,this.width,this.height,this.opts).regions,n=r.length>0?r:Tt(this.anchor,e,this.width,this.height,this.opts).regions;return this.previous=e,n.length>0&&(this.anchor=e),n}};function qo(t,e){return["-v","error","-i",t,"-frames:v","1","-vf",`scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function ng(t,e,r,n){return["-v","error","-probesize","32","-analyzeduration","0","-f","gdigrab","-framerate",String(Math.round(n*1e3)/1e3),...Ei(t,e),"-vf",`scale=${r.width}:${r.height}:flags=area,format=gray`,"-flush_packets","1","-f","rawvideo","-"]}function og(t,e,r){let n=`scale=${r.width}:${r.height}:flags=area,format=gray`;return["-v","info","-i",t,"-i",e,"-lavfi",`[0]${n}[x];[1]${n}[y];[x][y]ssim`,"-frames:v","1","-f","null","-"]}function Xo(t,e,r){let n=e.map(o=>`drawbox=x=${o.x}:y=${o.y}:w=${o.width}:h=${o.height}:color=red@0.9:t=3`);return["-y","-v","error","-i",t,"-frames:v","1",...n.length?["-vf",n.join(",")]:[],...Te(r)]}function ig(t){let e=t.match(/All:([\d.]+)/);return e?Number(e[1]):null}import{tmpdir as Dk}from"node:os";import{join as Lk}from"node:path";var Bk={a:Rt.string().min(1).describe("Before image (or video: first frame)."),b:Rt.string().min(1).describe("After image (or video); scaled to a's size."),pixelThreshold:Rt.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${Go}).`),returnImage:Rt.boolean().optional().describe("Return b inline with changes outlined (default true).")};function sg(t){t.registerTool("screen_diff",{title:"Screen Diff",description:"Compare two screenshots or frames: SSIM score, changed share, and changed boxes in b's pixels, to check a UI change happened only where expected.",inputSchema:Bk,outputSchema:B({identical:Rt.boolean(),ssim:Rt.number().nullable(),meanDiff:Rt.number(),changedFraction:Rt.number(),regions:Rt.array(Rt.unknown())}),annotations:fe},async(e,r)=>{try{k();for(let p of[e.a,e.b])O(p);let[n,o]=await Promise.all([W(e.a),W(e.b)]);if(!n.width||!n.height)throw new l(`Could not read the size of ${e.a}.`);let i=na(n.width,n.height),[s,a,c]=await Promise.all([Ur(qo(e.a,i),3e4,{signal:r.signal}),Ur(qo(e.b,i),3e4,{signal:r.signal}),se(k().ffmpeg,og(e.a,e.b,i),3e4,{signal:r.signal})]),u=Tt(s,a,i.width,i.height,{scaleX:(o.width??n.width)/i.width,scaleY:(o.height??n.height)/i.height,pixelThreshold:e.pixelThreshold}),d=[];if(e.returnImage!==!1){let p=Lk(Dk(),`screencast-diff-${he()}-${ge()}.png`);try{await te(Xo(e.b,u.regions,p),3e4,{signal:r.signal}),d.push(...(await Ce([p],Me,1)).images)}finally{Nk(p,{force:!0})}}return S({identical:u.regions.length===0,ssim:ig(c.stderr),meanDiff:Number(u.meanDiff.toFixed(4)),changedFraction:Number(u.changedFraction.toFixed(4)),regions:u.regions,...o.width!==n.width||o.height!==n.height?{note:`b (${o.width}x${o.height}) was compared at a's size (${n.width}x${n.height}).`}:{}},d)}catch(n){return E(n)}})}import{z as Ae}from"zod";var Wk=t=>new Promise(e=>setTimeout(e,t));async function ag(t){let e=t.now??Date.now,r=t.sleep??Wk,n=e(),o=await t.grab(),i=new ra(o,t.width,t.height,t.diff),s=n,a=!1,c=[],u="timeout";for(;e()-n<t.timeoutMs;){if(t.signal.aborted){u="cancelled";break}await r(t.intervalMs);let d=await t.grab().catch(p=>{if(t.signal.aborted)return null;throw p});if(!d){u="cancelled";break}if(t.mode==="change"){let p=Tt(o,d,t.width,t.height,t.diff);if(p.regions.length>0){c=p.regions,u="changed";break}}else{let p=i.push(d);if(p.length>0)a=!0,s=e(),c=p;else if(e()-s>=t.settleMs){u="settled";break}}}return{outcome:u,regions:c,everChanged:a,startedAt:n}}var jk=t=>new Promise(e=>setTimeout(e,t));async function cg(t){let e=t.now??Date.now,r=t.sleep??jk,n=e(),o=0,i=[],s=async()=>(o++,i=await t.read(),t.gone?i.length===0:i.length>0),a=()=>t.grab().catch(u=>{if(t.signal.aborted)return null;throw u}),c=await a();if(!c)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};if(await s())return{outcome:"matched",matches:i,reads:o,startedAt:n};for(;e()-n<t.timeoutMs;){if(t.signal.aborted)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};await r(t.intervalMs);let u=await a();if(!u)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};if(Tt(c,u,t.width,t.height,t.diff).regions.length!==0&&(c=u,await s()))return{outcome:"matched",matches:i,reads:o,startedAt:n}}return{outcome:"timeout",matches:i,reads:o,startedAt:n}}var ia=class{waiters=[];error=null;ended=!1;push(e){let r=this.waiters;this.waiters=[];for(let n of r)n.resolve(e)}fail(e){this.error===null&&(this.error=e),this.rejectAll(this.error)}end(){this.ended=!0,this.rejectAll(new l("The screen capture ended unexpectedly."))}next(e){return this.error!==null?Promise.reject(this.error):this.ended?Promise.reject(new l("The screen capture ended unexpectedly.")):new Promise((r,n)=>{let o=setTimeout(()=>{this.waiters=this.waiters.filter(s=>s!==i),n(new l(`No frame from the screen capture within ${Math.round(e/1e3)}s.`))},e),i={resolve:s=>{clearTimeout(o),r(s)},reject:s=>{clearTimeout(o),n(s)}};this.waiters.push(i)})}rejectAll(e){let r=this.waiters;this.waiters=[];for(let n of r)n.reject(e)}};import{join as sa}from"node:path";import{mkdtempSync as Uk,rmSync as Jo}from"node:fs";import{tmpdir as ug}from"node:os";var zk={target:Ae.string().describe("What to watch: full | monitor:<i> | window:<title> (or exe=/hwnd=) | region:<x>,<y>,<w>,<h>."),exactTitle:Ae.boolean().optional().describe("window: targets match the whole title only (default false)."),mode:Ae.enum(["change","settle","text"]).optional().describe("change (default): return once it differs from the start. settle: once it has been still for settleSec. text: once text appears (OCR, re-read only after a change)."),text:Ae.string().min(1).max(qr).optional().describe("Mode text: what to wait for; tolerates OCR misreads."),regex:Ae.boolean().optional().describe("Mode text: text is a regex."),gone:Ae.boolean().optional().describe("Mode text: wait until it disappears instead."),backend:Ae.enum(["gdigrab","wgc"]).optional().describe("wgc: watch a window even when covered (window: targets; 1-2 s per check)."),timeoutSec:Ae.number().positive().max(600).optional().describe("Give up after this many seconds (default 30; a timeout is a result, not an error)."),settleSec:Ae.number().positive().max(60).optional().describe("Mode settle: seconds of stillness (default 1)."),intervalMs:Ae.number().int().min(100).max(5e3).optional().describe("Pause between checks in ms (default 250; 1000 with wgc)."),pixelThreshold:Ae.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${Go}).`),returnImage:Ae.boolean().optional().describe("Return the final state inline (default true)."),keep:Ae.boolean().optional().describe("Keep the final screenshot on disk and return its path (default false).")};function lg(t){t.registerTool("wait_for_change",{title:"Wait for Screen Change",description:"Wait until part of the screen changes, settles, or shows (or loses) some text, instead of guessing a sleep. Returns the elapsed time, changed regions (screenshot pixels; add `origin` for desktop), and the final state.",inputSchema:zk,outputSchema:B({outcome:Ae.string(),mode:Ae.string(),elapsedSec:Ae.number(),regions:Ae.array(Ae.unknown()),origin:B({x:Ae.number(),y:Ae.number()})}),annotations:fe},async(e,r)=>{try{k();let n=e.mode??"change";if(n==="text"!=(e.text!==void 0))throw new l('Use text with mode "text", and mode "text" with text.');let o=e.backend??"gdigrab",i=(e.timeoutSec??30)*1e3,s=(e.settleSec??1)*1e3,a=e.intervalMs??(o==="wgc"?1e3:250),c=await ut(e.target,{exactTitle:e.exactTitle,backend:o}),{target:u,monitors:d,window:p}=c;if(o==="wgc"&&!p?.hwnd)throw new l('backend "wgc" watches one window: use a window: target.');let f=n==="text"?`"${e.text}" ${e.gone?"disappears":"appears"}`:n==="settle"?"stops changing":"changes";await Dt(t,`Watch ${Nt(e.target,p)} for up to ${i/1e3} s, until it ${f}?`,r.signal);let m=Uk(sa(ug(),"screencast-wait-")),h=0,b=async()=>{let $=sa(m,`still-${h++}.png`);return await Lt(c,$,o),$},w=oa(u,d);if(o==="wgc")try{let $=await W(await b());if(!$.width||!$.height)throw new l("Could not read the window capture's size.");w={...p?.client??{x:w.x,y:w.y},width:$.width,height:$.height}}catch($){throw Jo(m,{recursive:!0,force:!0}),$}let g=na(w.width,w.height),y=rg(w,g,e.pixelThreshold),v=new ia,x=new AbortController,R=o==="gdigrab"?ji(ng(u,d,g,1e3/a),g.width*g.height,$=>v.push($),i+6e4,{signal:AbortSignal.any([r.signal,x.signal])}).then(()=>v.end(),$=>v.fail($)):Promise.resolve(),T=o==="gdigrab"?()=>v.next(15e3):async()=>{let $=await b();try{return await Ur(qo($,g),3e4,{signal:r.signal})}finally{Jo($,{force:!0})}},M=o==="gdigrab"?async()=>{}:void 0,H,G=null,L=0;try{if(n==="text"){let $=await cg({grab:T,read:async()=>{let J=await b(),[N]=await lt([J],m,r.signal);return Jo(J,{force:!0}),N?St(N.lines,e.text,e.regex===!0):[]},width:g.width,height:g.height,diff:y,timeoutMs:i,intervalMs:a,gone:e.gone===!0,signal:r.signal,...M?{sleep:M}:{}});G={matches:$.matches,reads:$.reads},H={outcome:$.outcome,regions:$.matches.map(({x:J,y:N,width:le,height:X})=>({x:J,y:N,width:le,height:X})),startedAt:$.startedAt}}else H=await ag({grab:T,mode:n,width:g.width,height:g.height,diff:y,timeoutMs:i,settleMs:s,intervalMs:a,signal:r.signal,...M?{sleep:M}:{}});L=Date.now()}finally{x.abort(),await R,Jo(m,{recursive:!0,force:!0})}let{outcome:C,regions:ne,everChanged:V,startedAt:Y}=H,q={outcome:C,mode:n,elapsedSec:Number(((L-Y)/1e3).toFixed(2)),...n==="settle"?{changedWhileWaiting:V}:{},...G?{text:e.text,...e.gone?{gone:!0}:{},matches:G.matches,ocrReads:G.reads}:{},regions:ne,origin:{x:w.x,y:w.y},...o==="wgc"?{backend:o}:{},...p?pr(p):{}},Q=[];if(e.returnImage!==!1&&C!=="cancelled"){let $=e.keep?sa(we("screenshots"),`wait-${he()}-${ge()}.png`):sa(ug(),`screencast-wait-${he()}-${ge()}.png`);try{o==="wgc"?await Lt(c,$,"wgc"):await te(Ti(u,$,d),6e4,{signal:r.signal}),e.keep&&(q.screenshotPath=$),Q.push(...(await Ce([$],Me,1)).images)}finally{e.keep||Jo($,{force:!0})}}return S(q,Q)}catch(n){return E(n)}})}import{z as Xe}from"zod";import{extname as pg,join as Ln}from"node:path";import{mkdtempSync as Hk,rmSync as Gk}from"node:fs";import{tmpdir as qk}from"node:os";var dg=new Set([".png",".jpg",".jpeg",".bmp",".gif",".webp",".tif",".tiff"]),aa=300,Xk={target:Xe.string().optional().describe("Live screen target (full | monitor:<i> | window:... | region:...), or pass input."),input:Xe.string().optional().describe("Image or video file to read instead of a live target."),timestamp:Xe.number().nonnegative().optional().describe("Video input: second to read (default 0)."),scanEverySec:Xe.number().positive().optional().describe("Video input: scan a frame every N s across the clip (e.g. for secrets before sharing); matches and redactRegions get times. Widens to stay within maxFrames."),maxFrames:Xe.number().int().min(1).max(vs).optional().describe(`scanEverySec frame cap (default ${Wt}; ~1 s each).`),exactTitle:Xe.boolean().optional().describe("window: targets match the whole title only (default false)."),backend:Xe.enum(["gdigrab","wgc"]).optional().describe("Live target: gdigrab (default) = what is visible; wgc (window:, FFmpeg 8+) = the window even if covered."),query:Xe.string().optional().describe("Text to find (case-insensitive, tolerates OCR misreads like I/l, O/0, _/-). Omit to return all text."),regex:Xe.boolean().optional().describe("Treat query as a regular expression (case-insensitive)."),redact:Xe.boolean().optional().describe("Also return padded match rectangles ready for redact_region's regions."),keep:Xe.boolean().optional().describe("Live target: keep the capture and return its path (default false: deleted after reading)."),returnImage:Xe.boolean().optional().describe("Return the image with matches outlined (default: true with a query).")};function mg(t){t.registerTool("find_text",{title:"Find Text (OCR)",description:"OCR (built into Windows) on the screen, an image, or video frames, with line and match boxes in image pixels (add `origin` for desktop coordinates). Locate UI text or secrets (e.g. regex 'sk-|ghp_|api.?key') to redact. Best-effort: review results.",inputSchema:Xk,outputSchema:B({imageSize:B({width:Xe.number(),height:Xe.number()})}),annotations:fe},async(e,r)=>{try{if(k(),e.target===void 0==(e.input===void 0))throw new l("Provide exactly one of: target (live screen) or input (a file).");let n=Hk(Ln(qk(),"screencast-ocr-"));try{if(e.scanEverySec!==void 0)return await Jk(e,n,r.signal);let o,i={},s;if(e.target!==void 0){let h=await ut(e.target,{exactTitle:e.exactTitle,backend:e.backend});o=e.keep?Ln(we("screenshots"),`ocr-${he()}-${ge()}.png`):Ln(n,"capture.png");let b=e.backend??"gdigrab";await Dt(t,`Capture ${Nt(e.target,h.window)} once to read the text on it?`,r.signal),await Lt(h,o,b),h.window&&(i=pr(h.window));let w=oa(h.target,h.monitors);s=b==="wgc"&&h.window?.client?h.window.client:{x:w.x,y:w.y}}else{O(e.input);let h=dg.has(pg(e.input).toLowerCase());o=Ln(n,"frame.png"),await te(["-y","-v","error",...h?[]:["-ss",String(e.timestamp??0)],"-i",e.input,"-frames:v","1",...Te(o)],6e4,{signal:r.signal})}let[a]=await lt([o],n,r.signal);if(!a)throw new l("Could not read the frame.");let{lines:c,width:u,height:d}=a,p=e.query?St(c,e.query,e.regex===!0):[],f=[];if(e.returnImage??!!e.query){let h=Ln(n,"shown.png");await te(Xo(o,p,h),3e4,{signal:r.signal}),f.push(...(await Ce([h],Me,1)).images)}return S({...e.target!==void 0?e.keep?{screenshotPath:o}:{}:{input:e.input},imageSize:{width:u,height:d},...s?{origin:s}:{},...e.query?{query:e.query,matchCount:p.length,matches:p,...e.redact?{redactRegions:Ss(p,{width:u,height:d})}:{}}:{},text:c.map(h=>h.text).join(`
|
|
331
|
-
`),lines:c.slice(0,
|
|
332
|
-
`);return S({input:t.input,imageSize:{width:s.width,height:s.height},scan:{everySec:Math.round(i*1e3)/1e3,framesScanned:o.frames.length,...o.clamped?{note:`Widened from ${t.scanEverySec} s to fit maxFrames ${n}.`}:{}},...t.query?{query:t.query,matchCount:c.length,matches:c.slice(0,
|
|
333
|
-
`)||t;for(let n of r.split(/\r?\n/)){let o=/^\s{0,2}[D ][E ]\s?[d ]?\s+([a-z0-9_,]+)\s/i.exec(n);if(o?.[1])for(let i of o[1].split(","))e.add(i)}return[...e]}function
|
|
327
|
+
`)}var ca=["clean","social"],Ck={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 Xu(t,e,r="clean"){let n=r===null?null:Ck[r];if(n===void 0)throw new l(`Unknown caption style "${r}".`);return`subtitles=filename=${xe(t)}:fontsdir=${xe(e)}`+(n?`:force_style='${n}'`:"")}function Jh(t,e,r,n,o="clean",i="standard"){return["-y","-i",t,"-vf",Xu(e,n,o),...Me(i),"-c:a","copy",r]}var sa=1e3;function Yh(t,e){if(e.length!==t.length)throw new l(`Got ${e.length} translations for ${t.length} cues.`,"Translate every cue, in order, one string per cue (merge or split nothing).");return t.map((r,n)=>{let o=e[n].replace(/\r\n/g,`
|
|
328
|
+
`).trim();if(!o)throw new l(`Translation ${n+1} is empty.`);if(o.length>sa)throw new l(`Translation ${n+1} is over ${sa} characters.`);return{start:r.start,end:r.end,text:o.replace(/\n\s*\n/g,`
|
|
329
|
+
`)}})}function Kh(t,e){return t.replace(/\.srt$/i,"")+`.${e}.srt`}var Bk=new Set([".mp4",".mkv",".mov"]),Wk=12,jk={input:$e.string().min(1).optional().describe("Path to the video."),sessionId:$e.string().min(1).optional().describe("Or a stopped recording's id."),from:$e.enum(["markers","scenes","transcript"]).optional().describe("markers (default; add_marker, else the file's chapters), scenes (screen changes), or transcript (SRT sections)."),chapters:$e.array($e.object({start:$e.number().min(0),title:$e.string().min(1).max(100)})).min(1).max(200).optional().describe("Or explicit { start, title } chapters."),transcript:$e.string().optional().describe("The .srt for from: transcript."),minChapterSec:$e.number().min(0).optional().describe(`Shortest chapter (default 1; scenes ${Cn}, transcript 30).`),subtitles:$e.string().optional().describe("Also mux this .srt/.vtt/.ass as a soft subtitle track."),subtitleLanguage:$e.string().regex(/^[a-z]{3}$/).optional().describe('ISO 639-2, e.g. "eng".'),subtitleTracks:$e.array($e.object({file:$e.string().min(1),language:$e.string().regex(/^[a-z]{3}$/).optional(),title:$e.string().max(60).optional(),default:$e.boolean().optional()})).min(1).max(bs).optional().describe("Or several tracks, e.g. one per language (translate_subtitles makes them)."),textOnly:$e.boolean().optional().describe("Return chapters and YouTube text only; write no file."),output:$e.string().optional().describe("Optional .mp4/.mkv/.mov path. Defaults under SCREENCAST_HOME/edits."),overwrite:$e.boolean().optional().describe("Allow replacing an existing output file.")};function Qh(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:jk,outputSchema:N({chapters:$e.array(N({start:$e.number(),end:$e.number(),title:$e.string()})),youtube:$e.string()}),annotations:C},async(e,r)=>{try{k();let n=e.input,o;if(e.sessionId){let y=se().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(v=>v.file)])if(y!==void 0&&!Ik(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=Cn;let{ffmpeg:y}=k(),v=await ce(y,ur(n,$t),de(a),{signal:r.signal});if(v.code!==0)throw new l(`Scene scan failed (exit ${v.code}): ${v.stderr.trim().slice(-400)}`);u=Wm(lr(v.stdout),e.minChapterSec??d,Wk)}else if(c==="transcript"){if(!e.transcript)throw new l("from: transcript needs transcript (an .srt path).");if(d=30,u=jm(qe(Ok(e.transcript,"utf8")),{minChapterSec:e.minChapterSec??d}),u.length===0)throw new l(`No cues in ${e.transcript}.`)}else{let y=o??[];if(y.length===0){let v=await xr(n,r.signal);y=v.markers,v.from==="chapters"&&(p="embedded chapters")}if(y.length===0)throw new l(`No markers for ${n}.`,"Add some with add_marker, or use from: scenes / transcript, or pass chapters.");u=Ss(y)}let f=ys(u,a,{minChapterSec:e.minChapterSec??d});if(f.length===0)throw new l("No chapter falls inside the video.");let m=Bm(f,a),h={source:p,chapters:f,youtube:m.text,...m.issues.length>0?{youtubeIssues:m.issues}:{}};if(e.textOnly)return S(h);let b=e.output?Pk(e.output).toLowerCase():V(n);if(!Bk.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=Fk(Vh(Lk(),"screencast-chapters-"));try{let y=Vh(g,"chapters.txt");Dk(y,xs(f)),await U(Um(n,y,w,{container:b,subtitles:i}),{output:w,durationSec:a,extra:r})}finally{Nk(g,{recursive:!0,force:!0})}return S({outputPath:w,...h,...e.subtitles?{subtitleTrack:{...i[0],codec:b===".mkv"?"copy":"mov_text"}}:{},...e.subtitleTracks?{subtitleTracks:i.map(y=>({...y,codec:b===".mkv"?"copy":"mov_text"}))}:{}})}catch(n){return E(n)}})}import{z as bt}from"zod";import{existsSync as Hk,readFileSync as ug,rmSync as Gk}from"node:fs";var Qo="ui://screencast/player",ua="text/html;profile=mcp-app",eg={ui:{resourceUri:Qo},"ui/resourceUri":Qo},Zh="io.modelcontextprotocol/ui";function tg(t){let e=t,r=e?.extensions?.[Zh]??e?.experimental?.[Zh];return!r||typeof r!="object"?!1:!Array.isArray(r.mimeTypes)||r.mimeTypes.includes(ua)}var la=120,rg=300,Uk=4,Ju=640,zk=.01;function ng(t,e=la){if(!(t>0))throw new l("The video has no duration to review.");let r=Math.max(1,Math.min(e,Math.ceil(t*Uk))),n=Number((t/r).toFixed(6));return{count:r,intervalSec:n,sceneGapSec:Number(Math.max(.25,n/4).toFixed(6))}}function og(t,e,r,n,o=zk){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=${xe(n)}`,"-fps_mode","passthrough","-q:v","6","-f","image2pipe","-c:v","mjpeg","-"]}function ig(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 sg(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 ag(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 cg=t=>ug(Pn("ui",t),"utf8");function qk(){let t=cg("player.js");if(/<\/script/i.test(t))throw new l("player.js must not contain a closing script tag.");return cg("player.html").replace('<script src="player.js"></script>',()=>`<script>
|
|
330
|
+
${t}</script>`)}function Xk(t){if(t.sessionId){let e=se().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 Jk(t){return t&&t.length>0?{markers:t.map(({t:e,label:r})=>({t:e,label:r}))}:{}}function lg(t){t.registerResource("review-player",Qo,{title:"Recording review player",description:"Interactive player: scrub, trim, and draw redaction boxes on a recording.",mimeType:ua},async()=>({contents:[{uri:Qo,mimeType:ua,text:qk(),_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:bt.string().optional().describe("Path to the video."),sessionId:bt.string().optional().describe("Or the session id of a stopped recording.")},outputSchema:N({input:bt.string(),durationSec:bt.number().nullable(),width:bt.number().nullable(),height:bt.number().nullable(),fps:bt.number().nullable(),hasAudio:bt.boolean()}),annotations:ge,_meta:eg},async n=>{try{k();let o=Xk(n);F(o);let i=await L(o);return S({input:o,durationSec:i.durationSec,width:i.width,height:i.height,fps:i.fps,hasAudio:i.audioCodec!==null,...Jk(n.sessionId?se().get(n.sessionId)?.markers??He(o):He(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:bt.string().min(1).describe("Path to the video."),maxFrames:bt.number().int().min(1).max(rg).optional().describe(`Frames on the even grid (default ${la}); scene-change frames come on top, up to as many again.`),width:bt.number().int().min(64).max(1280).optional().describe(`Frame width (default ${Ju}).`)},annotations:ge,_meta:{ui:{visibility:["app"]}}},async(n,o)=>{try{k(),F(n.input);let i=await L(n.input),s=i.durationSec??0,a=ng(s,n.maxFrames??la),c=Xe(".txt"),u,d;try{let g=await Xr(og(n.input,a,n.width??Ju,c),de(s),{signal:o.signal});u=ag(g),d=ig(Hk(c)?ug(c,"utf8"):"").slice(0,u.length)}finally{Gk(c,{force:!0})}let[p]=d;if(!p)throw new l("ffmpeg returned no preview frames.");let f=sg(d,a.count).flatMap(g=>{let y=d[g],v=u[g];return y&&v?[{frame:y,jpeg:v}]:[]}),m=p.timeSec,h=[];try{h=(await xr(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?.(),tg(t.server.getClientCapabilities())&&e.enable()}}import{z as wt}from"zod";import{readFileSync as Yk,rmSync as Kk}from"node:fs";var Ce=1280,pa=8,Zo=20;function Vk(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",..._e(e)]}function da(t){return Math.max(0,Math.min(Zo,Math.floor(t??pa)))}async function Pe(t,e=Ce,r=pa){let n=t.slice(0,r);return{images:await Je(n,async i=>{let s=Xe(".jpg");try{return await te(Vk(i,s,e),3e4),{type:"image",data:Yk(s).toString("base64"),mimeType:"image/jpeg"}}finally{Kk(s,{force:!0})}}),omitted:t.length-n.length}}var Qk={target:wt.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:wt.boolean().optional().describe("window: targets match the whole title only, never a substring (default false)."),backend:wt.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:wt.string().optional().describe("Optional output .png path. Defaults to a file under SCREENCAST_HOME/screenshots."),overwrite:wt.boolean().optional().describe("Replace an existing output (default false)."),returnImage:wt.boolean().optional().describe("Return the image inline (default true; the PNG on disk stays full size)."),maxImageWidth:wt.number().int().min(16).optional().describe(`Max inline image width (default ${Ce}).`)};function pg(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:Qk,outputSchema:N({outputPath:wt.string(),target:wt.string(),backend:wt.string(),inlineImages:wt.number().int()}),annotations:C},async(e,r)=>{try{k();let n=await dt(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 jt(t,`Take a screenshot of ${Wt(e.target,o)}, saved to ${i}?`,r.signal),await Ut(n,i,s);let a=e.returnImage===!1?[]:(await Pe([i],e.maxImageWidth??Ce,1)).images;return S({outputPath:i,target:e.target,backend:s,...o?fr(o):{},inlineImages:a.length},a)}catch(n){return E(n)}})}import{z as Ne}from"zod";import{join as Yu}from"node:path";import{mkdirSync as Zk,readdirSync as dg,existsSync as eE,rmSync as tE}from"node:fs";var rE={input:Ne.string().min(1).describe("Path to the source video file."),mode:Ne.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:Ne.number().positive().optional().describe("Frames per second (mode fps)."),timestamps:Ne.array(Ne.number().nonnegative()).optional().describe("Seconds to grab a frame at (mode timestamps)."),sceneThreshold:Ne.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed to count, 0-1 (default ${$t}).`),dedupe:Ne.boolean().optional().describe("Mode fps: drop near-duplicate frames (default false)."),outputDir:Ne.string().optional().describe("Optional folder for the frames (a relative path resolves under SCREENCAST_HOME/frames). Defaults to SCREENCAST_HOME/frames/<id>."),maxFrames:Ne.number().int().min(1).max(Cc).optional().describe(`Frame cap (default ${Bi}); fps is lowered to fit while still spanning the video.`),returnImages:Ne.boolean().optional().describe("Return the first maxInlineImages frames inline (default true)."),maxInlineImages:Ne.number().int().min(0).max(Zo).optional().describe(`Frames to embed inline (default ${pa}); all are listed by path.`),maxImageWidth:Ne.number().int().min(16).optional().describe(`Max inline image width (default ${Ce}).`)};function mg(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:rE,outputSchema:N({frameDir:Ne.string(),frameCount:Ne.number().int(),frames:Ne.array(Ne.string()),mode:Ne.string()}),annotations:ge},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??Bi;if(o&&e.timestamps.length>a)throw new l(`${e.timestamps.length} timestamps exceeds maxFrames (${a}). Pass fewer timestamps, or raise maxFrames (up to ${Cc}).`);let c=i==="timestamps"?null:(await L(e.input)).durationSec,u=i==="fps"?Wi(c,e.fps,a):null,d=null,p=[];if(i==="scenes"){let{ffmpeg:w}=k(),g=await ce(w,ur(e.input,e.sceneThreshold??$t),de(c),{signal:r.signal});if(g.code!==0)throw new l(`Scene scan failed (exit ${g.code}): ${g.stderr.trim().slice(-400)}`);d=lr(g.stdout),p=$n(d,a)}let f=xn(e.outputDir,ye("frames"))??Yu(ye("frames"),`sample-${be()}-${we()}`);Zk(f,{recursive:!0});let m=[],h=[];if(u){let w=x=>x.endsWith(".png"),g=new Set(dg(f).filter(w)),y=Ip(g,`${be()}-${we()}`),v=yn(f,`${y}%05d.png`);await te(ji(e.input,u.fps,v,a,e.dedupe===!0),de(c),{signal:r.signal}),m=dg(f).filter(x=>w(x)&&x.startsWith(y)&&!g.has(x)).sort().map(x=>Yu(f,x))}else{let w=i==="scenes"?p:e.timestamps,g=await Je(w,async(y,v)=>{let x=Yu(f,`frame_${String(v).padStart(3,"0")}_${y}s.png`);return tE(x,{force:!0}),await te(kn(e.input,y,x),6e4,{signal:r.signal}),x});for(let[y,v]of g.entries())eE(v)?m.push(v):h.push(w[y])}let b=e.returnImages===!1?{images:[],omitted:0}:await Pe(m,e.maxImageWidth??Ce,da(e.maxInlineImages));return S({frameDir:f,frameCount:m.length,frames:m,mode:u?`fps=${u.fps}${e.dedupe?" (deduped)":""}`:d?`scenes (threshold ${e.sceneThreshold??$t})`:`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 et}from"zod";var nE={input:et.string().min(1).describe("Source video path."),count:et.number().int().min(1).max(Gf).optional().describe(`Frames to tile (default ${Go}).`),mode:et.enum(["even","scenes"]).optional().describe("even (default) or scenes (strongest changes; static stretches take no tiles)."),sceneThreshold:et.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed, 0-1 (default ${$t}).`),columns:et.number().int().min(1).max(12).optional().describe("Tiles per row (default: roughly square)."),tileWidth:et.number().int().min(64).max(1920).optional().describe(`Tile width in px (default ${qo}).`),poster:et.boolean().optional().describe("Write one representative poster frame instead of a sheet."),output:et.string().optional().describe("Optional output .png path. Defaults under SCREENCAST_HOME/frames."),overwrite:et.boolean().optional().describe("Replace an existing output (default false)."),returnImage:et.boolean().optional().describe("Return the sheet inline (default true)."),maxImageWidth:et.number().int().min(16).optional().describe(`Max inline image width (default ${Ce}).`)};function fg(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:nE,outputSchema:N({outputPath:et.string(),inlineImages:et.number().int()}),annotations:C},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=ar(e.output,ye("frames"),`${i}-${be()}-${we()}.png`,e.overwrite),a=e.tileWidth??qo,c;if(e.poster)await te(qf(e.input,o,s,Math.max(a,1280)),de(o),{signal:r.signal}),c={outputPath:s,poster:!0};else{let d=e.count??Go,p;if(e.mode==="scenes"){let m=await ce(n,ur(e.input,e.sceneThreshold??$t),de(o),{signal:r.signal});if(m.code!==0)throw new l(`Scene scan failed (exit ${m.code}): ${m.stderr.trim().slice(-400)}`);p=$n(lr(m.stdout),d)}else p=js(o,d);let f=await Us(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 Pe([s],e.maxImageWidth??Ce,1)).images;return S({...c,inlineImages:u.length},u)}catch(n){return E(n)}})}import{z as Pt}from"zod";import{rmSync as aE}from"node:fs";var hg=320,oE=4,iE=1600,At=8,ei=12;function gg(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(hg,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 fa(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(t,Math.max(hg,Math.min(iE,Math.ceil(t/oE)))),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function ha(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 sE(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 Ct(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??ei,s=Math.ceil(r/At),a=Math.ceil(n/At),c=new Uint8Array(s*a);for(let g=0;g<a;g++)for(let y=0;y<s;y++){let v=0,x=0;for(let T=g*At;T<Math.min(n,(g+1)*At);T++)for(let R=y*At;R<Math.min(r,(y+1)*At);R++){let P=T*r+R;v+=Math.abs(t[P]-e[P]),x++}v/x>i&&(c[g*s+y]=1)}let u=new Uint8Array(s*a),d=[];for(let g=0;g<c.length;g++){if(!c[g]||u[g])continue;let y={x0:1/0,y0:1/0,x1:-1,y1:-1,cells:0},v=[g];for(u[g]=1;v.length>0;){let x=v.pop(),T=x%s,R=Math.floor(x/s);y.x0=Math.min(y.x0,T),y.y0=Math.min(y.y0,R),y.x1=Math.max(y.x1,T),y.y1=Math.max(y.y1,R),y.cells++;for(let P=-1;P<=1;P++)for(let z=-1;z<=1;z++){let H=T+z,D=R+P;if(H<0||D<0||H>=s||D>=a)continue;let M=D*s+H;c[M]&&!u[M]&&(u[M]=1,v.push(M))}}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*At,v=g.y0*At,x=Math.min(r,(g.x1+1)*At)-y,T=Math.min(n,(g.y1+1)*At)-v;return{x:m+Math.round(y*p),y:h+Math.round(v*f),width:Math.round(x*p),height:Math.round(T*f)}}),w=c.reduce((g,y)=>g+y,0);return{meanDiff:sE(t,e),changedFraction:w/c.length,regions:b}}function bg(t,e,r){return{scaleX:t.width/e.width,scaleY:t.height/e.height,pixelThreshold:r}}var ma=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=Ct(this.previous,e,this.width,this.height,this.opts).regions,n=r.length>0?r:Ct(this.anchor,e,this.width,this.height,this.opts).regions;return this.previous=e,n.length>0&&(this.anchor=e),n}};function ti(t,e){return["-v","error","-i",t,"-frames:v","1","-vf",`scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function wg(t,e,r,n){return["-v","error","-probesize","32","-analyzeduration","0","-f","gdigrab","-framerate",String(Math.round(n*1e3)/1e3),...Fi(t,e),"-vf",`scale=${r.width}:${r.height}:flags=area,format=gray`,"-flush_packets","1","-f","rawvideo","-"]}function yg(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 ri(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(",")]:[],..._e(r)]}function xg(t){let e=t.match(/All:([\d.]+)/);return e?Number(e[1]):null}import{tmpdir as cE}from"node:os";import{join as uE}from"node:path";var lE={a:Pt.string().min(1).describe("Before image (or video: first frame)."),b:Pt.string().min(1).describe("After image (or video); scaled to a's size."),pixelThreshold:Pt.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${ei}).`),returnImage:Pt.boolean().optional().describe("Return b inline with changes outlined (default true).")};function Sg(t){t.registerTool("screen_diff",{title:"Screen Diff",description:"Compare two screenshots or frames: SSIM score, changed share, and changed boxes in b's pixels, to check a UI change happened only where expected.",inputSchema:lE,outputSchema:N({identical:Pt.boolean(),ssim:Pt.number().nullable(),meanDiff:Pt.number(),changedFraction:Pt.number(),regions:Pt.array(Pt.unknown())}),annotations:ge},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=fa(n.width,n.height),[s,a,c]=await Promise.all([Xr(ti(e.a,i),3e4,{signal:r.signal}),Xr(ti(e.b,i),3e4,{signal:r.signal}),ce(k().ffmpeg,yg(e.a,e.b,i),3e4,{signal:r.signal})]),u=Ct(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=uE(cE(),`screencast-diff-${be()}-${we()}.png`);try{await te(ri(e.b,u.regions,p),3e4,{signal:r.signal}),d.push(...(await Pe([p],Ce,1)).images)}finally{aE(p,{force:!0})}}return S({identical:u.regions.length===0,ssim:xg(c.stderr),meanDiff:Number(u.meanDiff.toFixed(4)),changedFraction:Number(u.changedFraction.toFixed(4)),regions:u.regions,...o.width!==n.width||o.height!==n.height?{note:`b (${o.width}x${o.height}) was compared at a's size (${n.width}x${n.height}).`}:{}},d)}catch(n){return E(n)}})}import{z as Ae}from"zod";var pE=t=>new Promise(e=>setTimeout(e,t));async function vg(t){let e=t.now??Date.now,r=t.sleep??pE,n=e(),o=await t.grab(),i=new ma(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=Ct(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 dE=t=>new Promise(e=>setTimeout(e,t));async function $g(t){let e=t.now??Date.now,r=t.sleep??dE,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(Ct(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 ga=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 ba}from"node:path";import{mkdtempSync as mE,rmSync as ni}from"node:fs";import{tmpdir as kg}from"node:os";var fE={target:Ae.string().describe("What to watch: full | monitor:<i> | window:<title> (or exe=/hwnd=) | region:<x>,<y>,<w>,<h>."),exactTitle:Ae.boolean().optional().describe("window: targets match the whole title only (default false)."),mode:Ae.enum(["change","settle","text"]).optional().describe("change (default): return once it differs from the start. settle: once it has been still for settleSec. text: once text appears (OCR, re-read only after a change)."),text:Ae.string().min(1).max(Qr).optional().describe("Mode text: what to wait for; tolerates OCR misreads."),regex:Ae.boolean().optional().describe("Mode text: text is a regex."),gone:Ae.boolean().optional().describe("Mode text: wait until it disappears instead."),backend:Ae.enum(["gdigrab","wgc"]).optional().describe("wgc: watch a window even when covered (window: targets; 1-2 s per check)."),timeoutSec:Ae.number().positive().max(600).optional().describe("Give up after this many seconds (default 30; a timeout is a result, not an error)."),settleSec:Ae.number().positive().max(60).optional().describe("Mode settle: seconds of stillness (default 1)."),intervalMs:Ae.number().int().min(100).max(5e3).optional().describe("Pause between checks in ms (default 250; 1000 with wgc)."),pixelThreshold:Ae.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${ei}).`),returnImage:Ae.boolean().optional().describe("Return the final state inline (default true)."),keep:Ae.boolean().optional().describe("Keep the final screenshot on disk and return its path (default false).")};function Eg(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:fE,outputSchema:N({outcome:Ae.string(),mode:Ae.string(),elapsedSec:Ae.number(),regions:Ae.array(Ae.unknown()),origin:N({x:Ae.number(),y:Ae.number()})}),annotations:ge},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 dt(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 jt(t,`Watch ${Wt(e.target,p)} for up to ${i/1e3} s, until it ${f}?`,r.signal);let m=mE(ba(kg(),"screencast-wait-")),h=0,b=async()=>{let $=ba(m,`still-${h++}.png`);return await Ut(c,$,o),$},w=ha(u,d);if(o==="wgc")try{let $=await L(await b());if(!$.width||!$.height)throw new l("Could not read the window capture's size.");w={...p?.client??{x:w.x,y:w.y},width:$.width,height:$.height}}catch($){throw ni(m,{recursive:!0,force:!0}),$}let g=fa(w.width,w.height),y=bg(w,g,e.pixelThreshold),v=new ga,x=new AbortController,T=o==="gdigrab"?Ki(wg(u,d,g,1e3/a),g.width*g.height,$=>v.push($),i+6e4,{signal:AbortSignal.any([r.signal,x.signal])}).then(()=>v.end(),$=>v.fail($)):Promise.resolve(),R=o==="gdigrab"?()=>v.next(15e3):async()=>{let $=await b();try{return await Xr(ti($,g),3e4,{signal:r.signal})}finally{ni($,{force:!0})}},P=o==="gdigrab"?async()=>{}:void 0,z,H=null,D=0;try{if(n==="text"){let $=await $g({grab:R,read:async()=>{let J=await b(),[O]=await mt([J],m,r.signal);return ni(J,{force:!0}),O?Rt(O.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,...P?{sleep:P}:{}});H={matches:$.matches,reads:$.reads},z={outcome:$.outcome,regions:$.matches.map(({x:J,y:O,width:pe,height:q})=>({x:J,y:O,width:pe,height:q})),startedAt:$.startedAt}}else z=await vg({grab:R,mode:n,width:g.width,height:g.height,diff:y,timeoutMs:i,settleMs:s,intervalMs:a,signal:r.signal,...P?{sleep:P}:{}});D=Date.now()}finally{x.abort(),await T,ni(m,{recursive:!0,force:!0})}let{outcome:M,regions:ie,everChanged:Z,startedAt:K}=z,X={outcome:M,mode:n,elapsedSec:Number(((D-K)/1e3).toFixed(2)),...n==="settle"?{changedWhileWaiting:Z}:{},...H?{text:e.text,...e.gone?{gone:!0}:{},matches:H.matches,ocrReads:H.reads}:{},regions:ie,origin:{x:w.x,y:w.y},...o==="wgc"?{backend:o}:{},...p?fr(p):{}},ne=[];if(e.returnImage!==!1&&M!=="cancelled"){let $=e.keep?ba(ye("screenshots"),`wait-${be()}-${we()}.png`):ba(kg(),`screencast-wait-${be()}-${we()}.png`);try{o==="wgc"?await Ut(c,$,"wgc"):await te(Ni(u,$,d),6e4,{signal:r.signal}),e.keep&&(X.screenshotPath=$),ne.push(...(await Pe([$],Ce,1)).images)}finally{e.keep||ni($,{force:!0})}}return S(X,ne)}catch(n){return E(n)}})}import{z as Ye}from"zod";import{extname as _g,join as Hn}from"node:path";import{mkdtempSync as hE,rmSync as gE}from"node:fs";import{tmpdir as bE}from"node:os";var Rg=new Set([".png",".jpg",".jpeg",".bmp",".gif",".webp",".tif",".tiff"]),wa=300,wE={target:Ye.string().optional().describe("Live screen target (full | monitor:<i> | window:... | region:...), or pass input."),input:Ye.string().optional().describe("Image or video file to read instead of a live target."),timestamp:Ye.number().nonnegative().optional().describe("Video input: second to read (default 0)."),scanEverySec:Ye.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:Ye.number().int().min(1).max(Ms).optional().describe(`scanEverySec frame cap (default ${Ht}; ~1 s each).`),exactTitle:Ye.boolean().optional().describe("window: targets match the whole title only (default false)."),backend:Ye.enum(["gdigrab","wgc"]).optional().describe("Live target: gdigrab (default) = what is visible; wgc (window:, FFmpeg 8+) = the window even if covered."),query:Ye.string().optional().describe("Text to find (case-insensitive, tolerates OCR misreads like I/l, O/0, _/-). Omit to return all text."),regex:Ye.boolean().optional().describe("Treat query as a regular expression (case-insensitive)."),redact:Ye.boolean().optional().describe("Also return padded match rectangles ready for redact_region's regions."),keep:Ye.boolean().optional().describe("Live target: keep the capture and return its path (default false: deleted after reading)."),returnImage:Ye.boolean().optional().describe("Return the image with matches outlined (default: true with a query).")};function Tg(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:wE,outputSchema:N({imageSize:N({width:Ye.number(),height:Ye.number()})}),annotations:ge},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=hE(Hn(bE(),"screencast-ocr-"));try{if(e.scanEverySec!==void 0)return await yE(e,n,r.signal);let o,i={},s;if(e.target!==void 0){let h=await dt(e.target,{exactTitle:e.exactTitle,backend:e.backend});o=e.keep?Hn(ye("screenshots"),`ocr-${be()}-${we()}.png`):Hn(n,"capture.png");let b=e.backend??"gdigrab";await jt(t,`Capture ${Wt(e.target,h.window)} once to read the text on it?`,r.signal),await Ut(h,o,b),h.window&&(i=fr(h.window));let w=ha(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=Rg.has(_g(e.input).toLowerCase());o=Hn(n,"frame.png"),await te(["-y","-v","error",...h?[]:["-ss",String(e.timestamp??0)],"-i",e.input,"-frames:v","1",..._e(o)],6e4,{signal:r.signal})}let[a]=await mt([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?Rt(c,e.query,e.regex===!0):[],f=[];if(e.returnImage??!!e.query){let h=Hn(n,"shown.png");await te(ri(o,p,h),3e4,{signal:r.signal}),f.push(...(await Pe([h],Ce,1)).images)}return S({...e.target!==void 0?e.keep?{screenshotPath:o}:{}:{input:e.input},imageSize:{width:u,height:d},...s?{origin:s}:{},...e.query?{query:e.query,matchCount:p.length,matches:p,...e.redact?{redactRegions:Ts(p,{width:u,height:d})}:{}}:{},text:c.map(h=>h.text).join(`
|
|
331
|
+
`),lines:c.slice(0,wa).map(({words:h,...b})=>b),...c.length>wa?{linesTruncated:c.length-wa}:{},...i,note:"OCR is best-effort: small or stylised text can be missed. Review before relying on it, especially for redaction."},f)}finally{gE(n,{recursive:!0,force:!0})}}catch(n){return E(n)}})}async function yE(t,e,r){if(t.input===void 0)throw new l("scanEverySec reads a video file: pass input, not target.");if(F(t.input),Rg.has(_g(t.input).toLowerCase()))throw new l("scanEverySec is for a video input; an image has one frame, so drop scanEverySec.");let n=t.maxFrames??Ht,o=await Fn(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?Sr(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=Hn(e,"shown.png");await te(ri(f,c.filter(b=>b.t===p.t),h),3e4,{signal:r}),d.push(...(await Pe([h],Ce,1)).images)}let m=[...a].join(`
|
|
332
|
+
`);return S({input:t.input,imageSize:{width:s.width,height:s.height},scan:{everySec:Math.round(i*1e3)/1e3,framesScanned:o.frames.length,...o.clamped?{note:`Widened from ${t.scanEverySec} s to fit maxFrames ${n}.`}:{}},...t.query?{query:t.query,matchCount:c.length,matches:c.slice(0,wa),...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 Rr}from"zod";import{dirname as _E,join as Vu}from"node:path";import{existsSync as Gn,mkdirSync as RE,mkdtempSync as TE,readFileSync as qn,readdirSync as ME,rmSync as Zu}from"node:fs";import{tmpdir as AE}from"node:os";import{spawnSync as xE}from"node:child_process";import{isAbsolute as SE}from"node:path";var tn=8;function ya(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 Mg(t){let e=new Set,r=t.split(/^\s*---\s*$/m).slice(1).join(`
|
|
333
|
+
`)||t;for(let n of r.split(/\r?\n/)){let o=/^\s{0,2}[D ][E ]\s?[d ]?\s+([a-z0-9_,]+)\s/i.exec(n);if(o?.[1])for(let i of o[1].split(","))e.add(i)}return[...e]}function Ku(t,e){try{let r=xE(t,e,{encoding:"utf8",windowsHide:!0,timeout:1e4});return r.status!==0?null:`${r.stdout??""}${r.stderr??""}`}catch{return null}}function xa(t){return Ku(t,["-version"])}function Ag(t){return Ku(t,["-hide_banner","-devices"])}function Cg(t){return SE(t)?t:Ku(process.platform==="win32"?"where":"which",[t])?.split(/\r?\n/).map(r=>r.trim()).find(r=>r.length>0)??null}var vE=`
|
|
334
334
|
$ErrorActionPreference = 'Stop'
|
|
335
335
|
$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
|
|
336
336
|
$e = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
|
|
337
337
|
[pscustomobject]@{ available = ($null -ne $e); language = $(if ($e) { $e.RecognizerLanguage.LanguageTag } else { $null }); languages = @([Windows.Media.Ocr.OcrEngine]::AvailableRecognizerLanguages | ForEach-Object { $_.LanguageTag }) } | ConvertTo-Json -Compress
|
|
338
|
-
`;async function vr(){if(process.platform!=="win32")return{available:!1,language:null,languages:[],error:"The Windows OCR engine is available on Windows only."};try{let t=JSON.parse(await ct(Vk,"OCR languages",{timeoutMs:ur(15e3)})),e=Array.isArray(t.languages)?t.languages:t.languages?[t.languages]:[];return{available:t.available===!0,language:t.language??null,languages:e}}catch(t){return{available:!1,language:null,languages:[],error:z(t)}}}var Qk=["SCREENCAST_HOME","SCREENCAST_ALLOWED_DIRS","FFMPEG_PATH","FFPROBE_PATH","SCREENCAST_WHISPER_MODEL","SCREENCAST_MAX_RECORDING_SEC","SCREENCAST_JOB_TIMEOUT_MS","SCREENCAST_PS_TIMEOUT_MS","SCREENCAST_RETENTION_DAYS","SCREENCAST_CONFIRM_CAPTURE","SCREENCAST_TOOLSETS","SCREENCAST_DEBUG_JOBS"],Zk=[{name:"SCREENCAST_MAX_RECORDING_SEC",ok:t=>Number.isInteger(t)&&t>=0&&t<=168*3600,want:"an integer from 0 (no cap) to 604800",otherwise:"start_recording fails until it is fixed"},{name:"SCREENCAST_JOB_TIMEOUT_MS",ok:t=>Number.isInteger(t)&&t>0,want:"a positive integer (milliseconds)",otherwise:"edits use the default timeout"},{name:"SCREENCAST_PS_TIMEOUT_MS",ok:t=>Number.isInteger(t)&&t>0,want:"a positive integer (milliseconds)",otherwise:"the PowerShell helpers use their default limits"},{name:"SCREENCAST_RETENTION_DAYS",ok:t=>Number.isFinite(t)&&t>=0,want:"a number of days (0 = off)",otherwise:"nothing is pruned"}],eE=["auto","1","true","yes","on","always","0","false","no","off","never"];function bg(t=process.env){let e=[];for(let n of Zk){let o=t[n.name];o===void 0||o.trim()===""||n.ok(Number(o.trim()))||e.push(`${n.name}="${o}" is not ${n.want}, so ${n.otherwise}.`)}let r=t.SCREENCAST_CONFIRM_CAPTURE;return r!==void 0&&r.trim()!==""&&!eE.includes(r.trim().toLowerCase())&&e.push(`SCREENCAST_CONFIRM_CAPTURE="${r}" is not auto, always (1/true/yes/on) or off (0/false/no/never), so captures follow auto.`),e}function wg(t=process.env){return Object.fromEntries(Qk.map(e=>{let r=t[e];return[e,r&&r.trim().length>0?r:null]}))}var yg=[{filter:"whisper",tools:"transcribe",why:`FFmpeg ${Yr}+ built with whisper.cpp`},{filter:"gfxcapture",tools:'backend: "wgc" (screenshot, start_recording, find_text)',why:`FFmpeg ${Yr}+ on Windows`},{filter:"subtitles",tools:"burn_subtitles",why:"libass"},{filter:"drawtext",tools:"title_card, callout, contact_sheet labels, produce",why:"libfreetype"},{filter:"afftdn",tools:"denoise",why:"a standard build"},{filter:"loudnorm",tools:"normalize_audio",why:"a standard build"},{filter:"xfade",tools:"xfade_transition, assemble_highlights",why:"FFmpeg 4.3+"}];var qu=8,sE={input:$r.string().optional().describe("Recording path."),sessionId:$r.string().optional().describe("Or a stopped session id."),sceneThreshold:$r.number().gt(0).lt(1).optional().describe(`Change starting a segment (default ${Nu}).`),maxFrames:$r.number().int().min(1).max(Xf).optional().describe(`Keyframes to OCR (default ${Du}).`),transcript:$r.string().optional().describe("An .srt, or 'whisper' to transcribe. Default: <video>.srt if any."),force:$r.boolean().optional().describe("Re-OCR despite a matching cached index.")};function xg(t){t.registerTool("index_recording",{title:"Index Recording",description:"Build a recording's text timeline (<video>.index.json: OCR per scene, events, markers, transcript) for search_recording.",inputSchema:sE,outputSchema:B({indexPath:$r.string(),segments:$r.number()}),annotations:I},async(e,r)=>{let n=nE(Gu(iE(),"screencast-index-"));try{let{ffmpeg:o}=k(),i=await qs(e),s=await W(i.path),a=s.videoDurationSec??s.durationSec;if(!s.width||a===null||!(a>0))throw new l(`Could not read the video size and duration of ${i.path}.`);let c=e.sceneThreshold??Nu,u=e.maxFrames??Du,d=we("edits"),p=Yf(i.path,d),f=Hs(i.path),m=$o(r),h=[],b=e.force?null:js(i.path,d,f),w=b?jo(b):null,g=null,y=async()=>g??=process.platform==="win32"&&(await vr()).available,v=Kf(w,{fingerprint:f,sceneThreshold:c,maxFrames:u,ocrAvailable:w!==null&&!w.ocr?await y():!1}),x,R=0,T=!1;if(v)x=w.segments,R=w.framesRead,T=w.ocr;else{let Y=await se(o,ir(i.path,c),pe(a),{signal:r.signal});if(Y.code!==0)throw new l(`Scene scan failed (exit ${Y.code}): ${Y.stderr.trim().slice(-400)}`);m?.(.1);let q=Zf(Qf(sr(Y.stdout),a,u),a),Q=q.map(()=>[]);if(T=await y(),T)for(let J=0;J<q.length;J+=qu){r.signal.throwIfAborted();let N=q.slice(J,J+qu),X=(await qe(N,async(ie,_)=>{let P=Gu(n,`key_${J+_}.png`);return await te(wn(i.path,zs(ie),P),6e4,{signal:r.signal}),{at:J+_,path:P}})).filter(ie=>Bn(ie.path)),ee=X.length>0?await lt(X.map(ie=>ie.path),n,r.signal,{sameSize:!0}):[];ee.forEach((ie,_)=>Q[X[_].at]=ie.lines.map(P=>P.text)),R+=ee.length,m?.(.1+.85*Math.min(q.length,J+qu)/q.length)}else h.push("Windows OCR is not available, so the index holds no screen text; install an OCR language (doctor).");let $=q.map((J,N)=>({...J,ocr:Q[N]??[]}));x=T?eh($):$}x=Vf(x);let M=i.eventsPath?th(ze(Wn(i.eventsPath,"utf8"))):[];x=Jr(x,M,"events"),x=Jr(x,rh(i.markers),"markers");let H=vt(i.path);if(Bn(H)){let Y=Cn(Wn(H,"utf8")),{busy:q}=Mn(Y),Q=q.map($=>{let J=Math.max(...Y.filter(N=>N.t>=$.start&&N.t<=$.end).map(N=>N.cpu??N.sysCpu));return{t:$.start,text:`cpu pinned ${Math.round(J)}% for ${Math.round($.end-$.start)} s (performance spike)`}});Q.length&&(x=Jr(x,[...x.flatMap($=>$.events??[]),...Q],"events"))}let G=jt(i.path);if(Bn(G)){let Y=Es(Wn(G,"utf8")),q=Le(Y.map(Q=>`${Q.source}: ${Q.line}`),De);x=Jr(x,Y.map((Q,$)=>({t:Q.t,text:q[$]??""})),"logs")}let L=await aE(e.transcript,i.path,s.audioCodec!==null,a,r.signal,h);if(L!==null)x=Jr(x,nh(L),"transcript");else if(v&&w){let Y=w.segments.flatMap(q=>q.transcript??[]);x=Jr(x,Y,"transcript")}let C={version:Ou,video:i.path,fingerprint:f,durationSec:a,createdAt:new Date().toISOString(),sceneThreshold:c,maxFrames:u,framesRead:R,ocr:T,segments:x};rE(Gu(p,".."),{recursive:!0}),oh(p,C);let ne=Lu(i.path);if(ne!==p&&Bn(ne)){let Y=jo(ne);Y&&Bs(Y,i.path,f)&&Xu(ne,{force:!0})}m?.(1);let V=Y=>x.reduce((q,Q)=>q+(Q[Y]?.length??0),0);return S({indexPath:p,segments:x.length,cached:v,framesRead:R,durationSec:a,sources:{screenLines:x.reduce((Y,q)=>Y+q.ocr.length,0),events:V("events"),markers:V("markers"),transcriptCues:V("transcript")},...h.length>0?{note:h.join(" ")}:{},next:"search_recording { query } returns timecoded hits. Secret-shaped screen text is stored masked; the rest of the index is plain text, so treat it like the video."})}catch(o){return E(o)}finally{Xu(n,{recursive:!0,force:!0})}})}async function aE(t,e,r,n,o,i){if(t==="whisper"){if(!r)return i.push("The recording has no audio, so there is no transcript."),null;if(!Ve("whisper"))throw new l("This ffmpeg has no whisper filter.","transcript: 'whisper' needs FFmpeg 8 built with whisper.cpp; or pass an .srt.");let c=Sr(void 0),u=He(".srt");try{return await te(Dn(e,c,u),pe(n),{signal:o}),Bn(u)?pt(Ue(Wn(u,"utf8"))):[]}finally{Xu(u,{force:!0})}}if(t!==void 0){if(!Bn(t))throw new l(`Transcript not found: ${t}`);return pt(Ue(Wn(t,"utf8")))}let s;try{s=oE(tE(e))}catch{return null}let a=Us(e,s);return a.ambiguous&&i.push("Another video in the folder shares this one's base name, so its .srt was not attached; pass transcript."),a.path?pt(Ue(Wn(a.path,"utf8"))):null}import{z as Ht}from"zod";import{join as Sg}from"node:path";import{existsSync as vg,mkdtempSync as cE,rmSync as uE}from"node:fs";import{tmpdir as lE}from"node:os";var pE=480,dE={input:Ht.string().optional().describe("Recording path."),sessionId:Ht.string().optional().describe("Or a stopped session id."),query:Ht.string().min(1).describe("Text; tolerates OCR misreads."),regex:Ht.boolean().optional().describe("query is a regex."),limit:Ht.number().int().min(1).max(Jf).optional().describe(`Max hits (default ${Ls}).`),images:Ht.number().int().min(0).max(Ho).optional().describe("Thumbnails of the top N hits (default 0).")};function $g(t){t.registerTool("search_recording",{title:"Search Recording",description:"Search an index_recording timeline (screen text, events, markers, transcript): timecoded hits, best first, secrets masked. No frames unless asked. No input: search all indexes.",inputSchema:dE,outputSchema:B({total:Ht.number(),hits:Ht.array(Ht.unknown())}),annotations:fe},async(e,r)=>{try{if(e.input===void 0&&e.sessionId===void 0){if((e.images??0)>0)throw new l("images needs one recording.","Pass input or sessionId, or search the library with images: 0.");let f=sh(Pe()).flatMap(b=>{let w=Bu(b);return w?[{indexPath:b,index:w}]:[]}),m=ah(f,e.query,{regex:e.regex===!0,limit:e.limit}),h=m.recordings.map(b=>({...b,...vg(b.video)?{}:{missing:!0}}));return S({query:e.query,searched:m.searched,total:m.total,hits:m.hits,recordings:h,...m.searched===0?{note:"No indexed recordings under SCREENCAST_HOME; run index_recording first."}:{}})}let n=await qs(e),o=Hs(n.path),i=js(n.path,we("edits"),o),s=i?Bu(i):null;if(!i||!s)throw new l(`No index for ${n.path}.`,"Run index_recording on it first.");let a=!Gs(s.fingerprint,o),{hits:c,total:u}=Wu(s,e.query,{regex:e.regex===!0,limit:e.limit,video:n.path,fingerprint:o}),d=Math.min(ta(e.images??0),c.length),p=[];if(d>0){k();let f=cE(Sg(lE(),"screencast-search-"));try{let m=[];for(let[h,b]of c.slice(0,d).entries()){let w=b.t===b.start?zs(b):b.t,g=Sg(f,`hit_${h}.png`);await te(wn(n.path,w,g),6e4,{signal:r.signal}),vg(g)&&m.push(g)}p=(await Ce(m,pE,d)).images}finally{uE(f,{recursive:!0,force:!0})}}return S({indexPath:i,query:e.query,total:u,hits:c,...u>c.length?{more:u-c.length}:{},...s.ocr?{}:{note:"The index has no screen text (OCR was unavailable when it was built)."},...a?{stale:!0,warning:"The recording changed since it was indexed; run index_recording again."}:{}},p)}catch(n){return E(n)}})}import{z as kr}from"zod";var mE={input:kr.string().min(1).describe("Path to the media file to probe.")};function kg(t){t.registerTool("get_media_info",{title:"Get Media Info",description:"Probe a media file with ffprobe and return duration, resolution, frame rate, codecs, container format, and size.",inputSchema:mE,outputSchema:B({input:kr.string(),durationSec:kr.number().nullable(),width:kr.number().nullable(),height:kr.number().nullable(),fps:kr.number().nullable(),videoCodec:kr.string().nullable(),audioCodec:kr.string().nullable()}),annotations:fe},async e=>{try{return O(e.input),S({input:e.input,...await W(e.input)})}catch(r){return E(r)}})}import{z as Kr}from"zod";import{extname as fE}from"node:path";var hE={input:Kr.string().min(1).describe("Path to the source video."),start:Kr.number().nonnegative().describe("Start time in seconds."),end:Kr.number().positive().optional().describe("End time in seconds. Use end OR duration."),duration:Kr.number().positive().optional().describe("Clip length in seconds. Use end OR duration."),exact:Kr.boolean().optional().describe("Re-encode for a frame-exact cut with the removed content really gone (default true). false = fast stream copy that snaps to a keyframe and keeps hidden earlier frames; never use it to remove secrets."),output:Kr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Kr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Eg(t){t.registerTool("trim",{title:"Trim Video",description:"Cut a video down to one sub-clip by start + (end or duration). For several segments use clip; to combine with other edits use pipeline.",inputSchema:hE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=e.exact===!1?fE(e.input)||".mp4":Z(e.input),o=j(e.output,"trim",n,{overwrite:e.overwrite,anyContainer:e.exact===!1}),i=Rp(e.input,o,{start:e.start,end:e.end,duration:e.duration,exact:e.exact}),s=e.start??0,a=e.end??await ue(e.input),c=e.duration??(a!==null?a-s:null);return await U(i,{output:o,durationSec:c,extra:r}),S({outputPath:o})}catch(n){return E(n)}})}import{z as ma}from"zod";import{extname as vE,resolve as $E}from"node:path";import{writeFileSync as kE,rmSync as EE}from"node:fs";var gE=1920,bE=1080,_g=30,Tg=48e3,jn=1,Ju="standard";function Yu(t){return Math.round(t*1e3)/1e3}function Rg(t){return t.width!==void 0&&or(t.width,"width"),t.height!==void 0&&or(t.height,"height"),{w:t.width??gE,h:t.height??bE}}function wE(t,e,r){return`scale=${t}:${e}:force_original_aspect_ratio=decrease,pad=${t}:${e}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${r},format=yuv420p`}function yE(t){return`aresample=${t},aformat=sample_fmts=fltp:channel_layouts=stereo`}function xE(t,e){let r=[],n=0;for(let[o,i]of t.slice(0,-1).entries())n+=i,r.push(Math.max(0,Yu(n-(o+1)*e)));return r}function Vr(t){return t.videoDurationSec??t.durationSec}function Ag(t,e,r,n,o={},i=[!1,!1]){let s=vc(o.transition??"fade"),a=o.duration??jn;if(!Number.isFinite(a)||a<=0)throw new l("transition duration must be a positive number.");if(!Number.isFinite(r[0])||r[0]<=a)throw new l(`first clip (${r[0]}s) must be longer than the transition (${a}s).`);return Yo([t,e],r,n,{...o,transition:s},i)}function Yo(t,e,r,n={},o=[]){if(t.length<2)throw new l("assemble_highlights requires at least two clips.");let{w:i,h:s}=Rg(n),a=n.fps??_g,c=n.audioRate??Tg,u=n.transition??"cut",d=n.duration??jn,p=t.length,f=wE(i,s,a),m=yE(c),h=o.some(Boolean),b=[];for(let g=0;g<p;g++)if(b.push(`[${g}:v]${f}[v${g}]`),!!h)if(o[g]){let y=e[g]??Number.NaN,v=Number.isFinite(y)&&y>0?`,apad,atrim=duration=${Yu(y)}`:"";b.push(`[${g}:a]${m}${v}[a${g}]`)}else{let y=e[g]??Number.NaN;if(!Number.isFinite(y)||y<=0)throw new l(`clip ${g} has no audio track and its duration is unknown, so a matching silent track cannot be generated.`);b.push(`anullsrc=channel_layout=stereo:sample_rate=${c}:d=${y}[a${g}]`)}let w=[];if(u==="cut")if(h){let g=t.map((y,v)=>`[v${v}][a${v}]`).join("");b.push(`${g}concat=n=${p}:v=1:a=1[vout][aout]`),w.push("-map","[vout]","-map","[aout]")}else{let g=t.map((y,v)=>`[v${v}]`).join("");b.push(`${g}concat=n=${p}:v=1:a=0[vout]`),w.push("-map","[vout]")}else{if(vc(u),e.length!==p)throw new l(`a ${u} transition needs a duration for each of the ${p} clips.`);if(!Number.isFinite(d)||d<=0)throw new l("transition duration must be a positive number.");let g=e.findIndex(x=>!Number.isFinite(x)||x<=d);if(g!==-1)throw new l(`clip ${g} (${e[g]}s) must be longer than the ${d}s ${u} transition. Use a shorter transition or trim fewer frames.`);let y=xE(e,d),v="v0";for(let x=1;x<p;x++){let R=x===p-1?"vout":`vx${x}`;b.push(`[${v}][v${x}]xfade=transition=${u}:duration=${d}:offset=${y[x-1]}[${R}]`),v=R}if(w.push("-map","[vout]"),h){let x="a0";for(let R=1;R<p;R++){let T=R===p-1?"aout":`ax${R}`;b.push(`[${x}][a${R}]acrossfade=d=${d}[${T}]`),x=T}w.push("-map","[aout]")}}return["-y",...t.flatMap(g=>["-i",g]),"-filter_complex",b.join(";"),...w,...Se({quality:n.quality??Ju,audio:h?"aac":"none",faststart:!0}),r]}var Ku=3;function Mg(t,e,r,n={}){let{w:o,h:i}=Rg(n),s=n.duration??Ku,a=n.fps??_g,c=Be(n.bg??"black","bg"),u=Be(n.fontColor??"white","fontColor"),d=n.fontSize??96;if(!Number.isFinite(s)||s<=0)throw new l("title duration must be a positive number.");if(!Number.isInteger(d)||d<=0)throw new l("fontSize must be a positive integer.");let p=`drawtext=fontfile=${ye(e)}:textfile=${ye(t)}:expansion=none:fontcolor=${u}:fontsize=${d}:x=(w-text_w)/2:y=(h-text_h)/2:shadowcolor=black@0.5:shadowx=2:shadowy=2`;return["-y","-f","lavfi","-i",`color=c=${c}:s=${o}x${i}:d=${s}:r=${a}`,"-f","lavfi","-i","anullsrc=channel_layout=stereo:sample_rate=48000","-vf",p,"-shortest",...Se({quality:n.quality??Ju,audio:"aac",faststart:!0}),r]}function Cg(t,e,r,n,o,i={}){if(!Number.isFinite(n)||n<=0)throw new l("video duration must be known and positive.");let s=i.musicVolume??(o?.25:.8),a=i.fadeIn??1,c=i.fadeOut??2;for(let[h,b]of[[s,"musicVolume"],[a,"fadeIn"],[c,"fadeOut"]])if(!Number.isFinite(h)||h<0)throw new l(`${b} must be a non-negative number.`);let u=i.duck??!1,d=Math.max(0,Yu(n-c)),p=`[1:a]afade=t=in:st=0:d=${a},afade=t=out:st=${d}:d=${c},volume=${s}`,f="amix=inputs=2:duration=first:dropout_transition=0:normalize=0",m=[];return o?(m.push(`${p}[music]`),u?(m.push("[music][0:a]sidechaincompress=threshold=0.03:ratio=8:attack=20:release=300[ducked]"),m.push(`[0:a][ducked]${f}[aout]`)):m.push(`[0:a][music]${f}[aout]`)):m.push(`${p}[aout]`),["-y","-i",t,"-stream_loop","-1","-i",e,"-filter_complex",m.join(";"),"-map","0:v","-map","[aout]","-t",String(n),...Se({video:["-c:v","copy"],audio:"aac",bitrate:"192k",faststart:!0}),r]}var Un=["16:9","9:16","1:1","4:5"],la=["pad","crop"],zn={"16:9":{w:1920,h:1080},"9:16":{w:1080,h:1920},"1:1":{w:1080,h:1080},"4:5":{w:1080,h:1350}};function pa(t,e,r){return r==="crop"?`scale=${t}:${e}:force_original_aspect_ratio=increase,crop=${t}:${e},setsar=1`:`scale=${t}:${e}:force_original_aspect_ratio=decrease,pad=${t}:${e}:(ow-iw)/2:(oh-ih)/2,setsar=1`}function Pg(t,e,r,n="pad",o=Ju){let i=zn[r];if(!i)throw new l(`Unknown aspect "${r}".`);return["-y","-i",t,"-vf",`${pa(i.w,i.h,n)},format=yuv420p`,...Se({quality:o,audio:"copy",faststart:!0}),e]}var da=["youtube","instagram_reel","tiktok","x","square","steam_trailer","vertical_reel"],Vu={youtube:{aspect:"16:9",fps:30,videoBitrate:"8M",bufsize:"16M",audioBitrate:"192k"},instagram_reel:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},tiktok:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},x:{aspect:"16:9",fps:30,videoBitrate:"5M",bufsize:"10M",audioBitrate:"128k"},square:{aspect:"1:1",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},steam_trailer:{aspect:"16:9",fps:30,videoBitrate:"5.5M",bufsize:"11M",audioBitrate:"192k",cbr:!0,loudness:{sampleRate:48e3}},vertical_reel:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k",blurFill:!0,loudness:{}}};function SE(t,e,r=""){return`split=2[${r}bg][${r}fg];[${r}bg]scale=${t}:${e}:force_original_aspect_ratio=increase,crop=${t}:${e},boxblur=20:2,eq=brightness=-0.08[${r}b];[${r}fg]scale=${t}:${t}:force_original_aspect_ratio=decrease:force_divisible_by=2[${r}f];[${r}b][${r}f]overlay=(W-w)/2:(H-h)/2,setsar=1`}function Qu(t,e="pad",r=""){let n=Vu[t];if(!n)throw new l(`Unknown platform "${t}".`);let o=zn[n.aspect],i=n.blurFill?SE(o.w,o.h,r):pa(o.w,o.h,e),s=n.loudness?`loudnorm=I=-14:TP=-1:LRA=11,aresample=${n.loudness.sampleRate??Tg}`:void 0;return{vf:`${i},fps=${n.fps},format=yuv420p`,...s?{af:s}:{},encode:["-c:v","libx264","-preset","medium",...n.cbr?["-profile:v","high"]:[],"-b:v",n.videoBitrate,...n.cbr?["-minrate",n.videoBitrate,"-x264-params","nal-hrd=cbr"]:[],"-maxrate",n.videoBitrate,"-bufsize",n.bufsize,"-pix_fmt","yuv420p",...Nr(n.audioBitrate),...n.loudness?.sampleRate?["-ar",String(n.loudness.sampleRate),"-ac","2"]:[],"-r",String(n.fps),...Dr],width:o.w,height:o.h}}function Ig(t,e,r,n="pad"){let{vf:o,af:i,encode:s}=Qu(r,n);return["-y","-i",t,"-vf",o,...i?["-af",i]:[],...s,e]}var _E={inputs:ma.array(ma.string().min(1)).min(2).describe("Video paths to join, in order."),output:ma.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ma.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Fg(t){t.registerTool("concat",{title:"Concatenate Videos",description:"Join videos end to end with hard cuts: stream copy when they match, else a re-encode (`mode` says which). For transitions use xfade_transition or assemble_highlights.",inputSchema:_E,outputSchema:K,annotations:I},async(e,r)=>{try{k();let n=e.inputs.map(m=>$E(m));for(let m of n)O(m);let o=await Promise.all(n.map(m=>W(m))),[i]=n,[s]=o;if(i===void 0||s===void 0)throw new l("concat needs at least two inputs.");let a=o.map(m=>Vr(m)),c=a.every(m=>m!==null)?a.reduce((m,h)=>m+h,0):null,u=Mp(n,o);if(u!==null){let m=j(e.output,"concat",Z(i),{overwrite:e.overwrite}),h=w=>w!==null&&w>=2?w-w%2:void 0,b=Yo(n,a.map(w=>w??0),m,{transition:"cut",width:h(s.width),height:h(s.height),fps:s.fps??void 0},o.map(w=>w.audioCodec!==null));return await U(b,{output:m,durationSec:c,extra:r}),S({outputPath:m,inputCount:n.length,mode:"reencode",reason:u})}let d=vE(i)||".mp4",p=j(e.output,"concat",d,{overwrite:e.overwrite,anyContainer:!0}),f=He(".txt");kE(f,Ap(n));try{await U(yn(f,p),{output:p,durationSec:c,extra:r})}finally{EE(f,{force:!0})}return S({outputPath:p,inputCount:n.length,mode:"copy"})}catch(n){return E(n)}})}import{z as Hn}from"zod";var TE={input:Hn.string().min(1).describe("Path to the source media."),format:Hn.enum(["mp4","gif","webm"]).describe("mp4 (H.264), webm (VP9), or gif (palette)."),fps:Hn.number().positive().optional().describe("gif only: fps (default 12)."),width:Hn.number().positive().optional().describe("gif only: width in px (default 720)."),output:Hn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Hn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Og(t){t.registerTool("convert",{title:"Convert Format",description:"Convert media to mp4, webm, or gif. For a size-bounded GIF/WebP prefer export_gif; for a smaller mp4, compress or export_preset.",inputSchema:TE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=e.format,o=j(e.output,"convert",`.${n}`,{overwrite:e.overwrite,anyContainer:!0}),i=Cp(e.input,o,n,{fps:e.fps,width:e.width});return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o,format:n})}catch(n){return E(n)}})}import{z as Gt}from"zod";var fa=12,ha=960,Er=1e7,Ng=5;function Dg(t,e,r){return(t==="gif"?[[1,1,256],[.83,.8,256],[.67,.67,128],[.5,.5,64],[.4,.4,32],[.33,.33,16]]:[[1,1,75],[.83,.8,65],[.67,.67,55],[.5,.5,45],[.4,.4,35],[.33,.33,25]]).map(([o,i,s])=>({fps:Math.max(1,Math.round(e*o*10)/10),width:Math.max(64,Math.round(r*i/2)*2),...t==="gif"?{colors:s}:{quality:s}}))}function Lg(t,e,r,n){let o=n-1;if(t>=o)return null;let i=Math.max(1,Math.ceil(Math.log(e/r)/Math.log(1.8)));return Math.min(o,t+i)}function Bg(t,e,r,n,o={}){if(!(n.fps>0)||!Number.isInteger(n.width)||n.width<16)throw new l("fps must be positive and width an integer of at least 16.");if(o.start!==void 0&&!(o.start>=0))throw new l("start must be >= 0.");if(o.duration!==void 0&&!(o.duration>0))throw new l("duration must be > 0.");let i=[...o.start?["-ss",String(o.start)]:[],...o.duration?["-t",String(o.duration)]:[]],s=`fps=${n.fps},scale='min(${n.width},iw)':-1:flags=lanczos`;if(r==="gif"){let a=n.colors??256;return["-y",...i,"-i",t,"-an","-vf",`${s},split[a][b];[a]palettegen=stats_mode=diff:max_colors=${a}[p];[b][p]paletteuse=dither=sierra2_4a:diff_mode=rectangle`,"-loop","0",e]}return["-y",...i,"-i",t,"-an","-vf",s,"-c:v","libwebp_anim","-lossless","0","-q:v",String(n.quality??75),"-compression_level","4","-loop","0",e]}import{basename as RE,dirname as AE,extname as ME,join as CE}from"node:path";import{renameSync as PE,rmSync as IE,statSync as FE}from"node:fs";async function Gn(t,e,r,n){let o=r.format??"gif",i=r.maxBytes??Er,s=await ue(t),a=r.duration??(s!==null?s-(r.start??0):null),c=Dg(o,r.fps??fa,r.width??ha),u=ME(e),d=f=>CE(AE(e),`${RE(e,u)}.try${f}${u}`),p=[];try{let f=0;for(;f!==null&&p.length<Ng;){let b=c[f];if(!b)break;let w=d(p.length),g={start:r.start,duration:r.duration};await U(Bg(t,w,o,b,g),{output:w,durationSec:a,extra:n});let y=FE(w).size;if(p.push({path:w,size:y,settings:b}),y<=i)break;f=Lg(f,y,i,c.length)}let m=p.find(b=>b.size<=i),h=m??p.reduce((b,w)=>w.size<b.size?w:b);return PE(h.path,e),{outputPath:e,format:o,sizeBytes:h.size,maxBytes:i,withinBudget:h.size<=i,settings:h.settings,attempts:p.map(b=>({...b.settings,sizeBytes:b.size})),...m?{}:{note:`Could not get under ${i} bytes; kept the smallest attempt. Export a shorter clip (start/duration), or try format: 'webp'.`}}}finally{for(let f of p)IE(f.path,{force:!0})}}var OE={input:Gt.string().min(1).describe("Path to the source video."),format:Gt.enum(["gif","webp"]).optional().describe("gif (default) or webp (usually much smaller)."),maxBytes:Gt.number().int().min(1e4).optional().describe(`Size budget in bytes (default ${Er}, under GitHub's 10 MB image limit).`),fps:Gt.number().positive().max(30).optional().describe(`Starting frame rate (default ${fa}).`),width:Gt.number().int().min(64).max(1920).optional().describe(`Starting width in px (default ${ha}).`),start:Gt.number().nonnegative().optional().describe("Start second."),duration:Gt.number().positive().optional().describe("Seconds to export (default: to the end)."),output:Gt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Gt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Wg(t){t.registerTool("export_gif",{title:"Export GIF or WebP",description:"Export an animated GIF or WebP that fits a size budget (for PRs, issues, READMEs), stepping fps, width, and quality down until it fits.",inputSchema:OE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=e.format??"gif",o=e.maxBytes??Er,i=j(e.output,"anim",`.${n}`,{overwrite:e.overwrite,anyContainer:!0});return S(await Gn(e.input,i,{format:n,maxBytes:o,fps:e.fps,width:e.width,start:e.start,duration:e.duration},r))}catch(n){return E(n)}})}import{z as Qr}from"zod";var NE={input:Qr.string().min(1).describe("Path to the source video."),x:Qr.number().int().nonnegative(),y:Qr.number().int().nonnegative(),width:Qr.number().int().positive(),height:Qr.number().int().positive(),output:Qr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function jg(t){t.registerTool("crop",{title:"Crop Video",description:"Crop a video to a pixel rectangle; one running off the frame is rejected.",inputSchema:NE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let{width:n,height:o,durationSec:i}=await W(e.input),s=Z(e.input),a=j(e.output,"crop",s,{overwrite:e.overwrite}),c=Pp(e.input,a,{x:e.x,y:e.y,width:e.width,height:e.height},{width:n,height:o});return await U(c,{output:a,durationSec:i,extra:r}),S({outputPath:a})}catch(n){return E(n)}})}import{z as Ko}from"zod";var DE={input:Ko.string().min(1).describe("Path to the source video."),width:Ko.number().int().positive().optional().describe("Target width in px. Omit to derive from height (keeps aspect)."),height:Ko.number().int().positive().optional().describe("Target height in px. Omit to derive from width (keeps aspect)."),output:Ko.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ko.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ug(t){t.registerTool("scale",{title:"Scale Video",description:"Resize a video to a target width and/or height and re-encode. Provide one side to keep the aspect ratio, or both to set an exact size.",inputSchema:DE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=Z(e.input),o=j(e.output,"scale",n,{overwrite:e.overwrite}),i=Fp(e.input,o,{width:e.width,height:e.height});return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o})}catch(n){return E(n)}})}import{z as Zo}from"zod";import{z as ga}from"zod";function At(t){if(t.length===0)return"0";if(t.length<=50)return t.join("+");let e=[];for(let r=0;r<t.length;r+=50)e.push(`(${t.slice(r,r+50).join("+")})`);return At(e)}var en=2,Vo=.4,qn=200;function ba(t,e,r){if(!(e>0))throw new l("minIdleSec must be positive.");return["-hide_banner","-nostats","-v","info","-i",t,"-vf",`freezedetect=n=-60dB:d=${e}`,...r?["-af",`silencedetect=n=-40dB:d=${e}`]:["-an"],"-f","null","-"]}function zg(t,e,r,n){let o=[],i=null;for(let s of t.split(/\r?\n/)){let a=s.match(e);if(a){i=Number(a[1]);continue}let c=s.match(r);c&&i!==null&&(o.push({start:i,end:Number(c[1])}),i=null)}return i!==null&&n>i&&o.push({start:i,end:n}),o}function wa(t,e){return zg(t,/freeze_start:\s*([\d.]+)/,/freeze_end:\s*([\d.]+)/,e)}function ya(t,e){return zg(t,/silence_start:\s*([\d.]+)/,/silence_end:\s*([\d.]+)/,e)}function xa(t,e){let r=[],n=0,o=0;for(;;){let i=t[n],s=e[o];if(!i||!s)break;let a=Math.max(i.start,s.start),c=Math.min(i.end,s.end);c>a&&r.push({start:a,end:c}),i.end<s.end?n++:o++}return r}function Sa(t,e,r){return t.filter(n=>n.end-n.start>=e).map(n=>({start:n.start+r,end:n.end-r})).filter(n=>n.end-n.start>.05).map(n=>({start:Number(n.start.toFixed(3)),end:Number(n.end.toFixed(3))}))}function Zu(t){if(t.length===0)throw new l("Nothing to cut.");if(t.length>qn)throw new l(`Too many idle stretches (${t.length}); raise minIdleSec.`);let e=At(t.map(n=>`between(t,${n.start},${n.end})`)),r=At(t.map(n=>`clip(T-${n.start},0,${Number((n.end-n.start).toFixed(3))})`));return{video:`select='not(${e})',setpts='(T-(${r}))/TB'`,audio:`asetnsamples=n=256:p=0,aselect='not(${e})',asetpts=N/SR/TB`}}var Zr=100,va=ga.object({start:ga.number().min(0),end:ga.number().positive(),factor:ga.number().gt(1).max(Zr)}),Qo=8;function $a(t,e){if(t.length===0)throw new l("segments needs at least one range.");if(t.length>qn)throw new l(`Too many ranges (${t.length}); at most ${qn}.`);let r=[...t].sort((n,o)=>n.start-o.start).map(n=>({start:Number(n.start.toFixed(3)),end:Number(n.end.toFixed(3)),factor:n.factor}));return r.forEach((n,o)=>{if(!(n.end>n.start)||n.start<0)throw new l(`Range ${n.start}-${n.end}s: end must be after start, from 0.`);if(!(n.factor>1)||n.factor>Zr)throw new l(`Range ${n.start}-${n.end}s: factor must be above 1 and at most ${Zr} (for slow motion, use factor on the whole clip).`);if(e!==null&&n.start>=e)throw new l(`Range ${n.start}-${n.end}s starts after the video ends (${e}s).`);let i=r[o-1];if(i&&n.start<i.end)throw new l(`Ranges ${i.start}-${i.end}s and ${n.start}-${n.end}s overlap.`)}),r}function tn(t){return t.reduce((e,r)=>e+(r.end-r.start)*(1-1/r.factor),0)}function ka(t,e){if(t.length===0)throw new l("Nothing to speed up.");let r=s=>Number((1-1/s.factor).toFixed(6)),n=At(t.map(s=>`clip(T-${s.start},0,${Number((s.end-s.start).toFixed(3))})*${r(s)}`)),o=s=>Number((s.start+(s.end-s.start)/s.factor).toFixed(3)),i=At(t.map(s=>`between(t,${o(s)},${s.end})`));return{video:`setpts='(T-(${n}))/TB'`+(e?`,fps=${Number(e.toFixed(3))}`:""),audio:`asetnsamples=n=256:p=0,aselect='not(${i})',asetpts=N/SR/TB`}}function Ea(t,e,r,n){let o=ka(r,n.fps);return["-y","-i",t,"-vf",o.video,...n.withAudio?["-af",o.audio]:["-an"],...Se({quality:n.quality??"standard",audio:n.withAudio?"aac":"omit"}),e]}function _a(t,e,r,n,o="standard"){let i=Zu(r);return["-y","-i",t,"-vf",i.video,...n?["-af",i.audio]:["-an"],...Se({quality:o,audio:n?"aac":"omit"}),e]}var LE={input:Zo.string().min(1).describe("Path to the source video."),factor:Zo.number().positive().optional().describe("Whole clip: >1 faster, <1 slower."),segments:Zo.array(va).min(1).optional().describe("Or fast-forward just these ranges (audio shortened, not pitched)."),output:Zo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Zo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Hg(t){t.registerTool("speed",{title:"Change Speed",description:"Change playback speed, or fast-forward ranges, and re-encode. Audio is retempo'd to match.",inputSchema:LE,outputSchema:K,annotations:I},async(e,r)=>{try{if(k(),O(e.input),e.factor===void 0==(e.segments===void 0))throw new l("Pass factor (the whole clip) or segments (ranges), not both.");let{audioCodec:n,durationSec:o,fps:i}=await W(e.input),s=Z(e.input),a=j(e.output,"speed",s,{overwrite:e.overwrite}),c=n!==null;if(e.segments){let p=$a(e.segments,o),f=tn(p);return await U(Ea(e.input,a,p,{withAudio:c,fps:i}),{output:a,durationSec:o!==null?o-f:null,inputDurationSec:o,extra:r}),S({outputPath:a,segments:p,savedSec:Number(f.toFixed(2)),audio:c})}let u=e.factor,d=Op(e.input,a,u,c);return await U(d,{output:a,durationSec:o!==null?o/u:null,inputDurationSec:o,extra:r}),S({outputPath:a,factor:u,audio:c})}catch(n){return E(n)}})}import{z as ft}from"zod";var BE={input:ft.string().min(1).describe("Path to the base video."),overlay:ft.string().min(1).describe("Overlay image or video path."),x:ft.number().int().nonnegative().describe("Left, px."),y:ft.number().int().nonnegative().describe("Top, px."),width:ft.number().int().positive().optional().describe("Scale to this width (other side keeps aspect)."),height:ft.number().int().positive().optional().describe("Scale to this height."),start:ft.number().nonnegative().optional().describe("Show from this second."),end:ft.number().positive().optional().describe("Hide after this second."),shape:ft.enum(["rect","circle"]).optional().describe("circle: centre square masked round (webcam)."),output:ft.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ft.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Gg(t){t.registerTool("overlay",{title:"Overlay Image or Video",description:"Composite an image or video (logo, watermark, picture-in-picture) onto a video at a pixel position, optionally scaled and time-limited; keeps the base's audio and length.",inputSchema:BE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input),O(e.overlay,"Overlay file");let n=Z(e.input),o=j(e.output,"overlay",n,{overwrite:e.overwrite}),i=e.width!==void 0||e.height!==void 0?{width:e.width,height:e.height}:void 0,s=await ue(e.input),a=Np(e.input,e.overlay,o,{x:e.x,y:e.y,start:e.start,end:e.end,scale:i,shape:e.shape,durationSec:s});return await U(a,{output:o,durationSec:s,extra:r}),S({outputPath:o})}catch(n){return E(n)}})}import{z as st}from"zod";import{mkdtempSync as zE,rmSync as HE,writeFileSync as GE}from"node:fs";import{tmpdir as qE}from"node:os";import{join as Kg}from"node:path";var Jg=["side_by_side","stack","grid"],Ta=2,Ra=9,qg=3840,WE=1080,Xg=t=>Math.max(2,Math.round(t/2)*2);function jE(t,e){if(t==="side_by_side")return{cols:e,rows:1};if(t==="stack")return{cols:1,rows:e};let r=Math.ceil(Math.sqrt(e));return{cols:r,rows:Math.ceil(e/r)}}function UE(t,e){let r=Math.min(t.height,WE),n=t.width*r/t.height,o=Math.min(1,qg/(n*e.cols),qg/(r*e.rows));return n*=o,r*=o,{width:Xg(n),height:Xg(r)}}function el(t,e){let r=t.map(n=>Math.max(0,n.durationSec-n.skipSec));return e==="longest"?Math.max(...r):Math.min(...r)}function Yg(t,e,r){let n=t.length;if(n<Ta||n>Ra)throw new l(`compose takes ${Ta} to ${Ra} inputs.`);let o=t[0],i=jE(r.layout,n),s=UE(o,i),a=el(t,r.endWith);if(!(a>0))throw new l("Nothing is left to show after lining the inputs up.");let c=[];t.forEach((m,h)=>{let b=Math.max(0,a-(m.durationSec-m.skipSec)),w=m.label?`,drawtext=fontfile=${ye(m.label.fontFile)}:textfile=${ye(m.label.textFile)}:expansion=none:fontcolor=white:fontsize=${Math.max(14,Math.round(s.height/18))}:x=12:y=12:box=1:boxcolor=black@0.6:boxborderw=8`:"";c.push(`[${h}:v]fps=${r.fps},scale=${s.width}:${s.height}:force_original_aspect_ratio=decrease,pad=${s.width}:${s.height}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,format=yuv420p`+(b>.001?`,tpad=stop_mode=clone:stop_duration=${b.toFixed(3)}`:"")+`${w}[c${h}]`)});let u=t.map((m,h)=>`${h%i.cols*s.width}_${Math.floor(h/i.cols)*s.height}`).join("|");c.push(`${t.map((m,h)=>`[c${h}]`).join("")}xstack=inputs=${n}:layout=${u}:fill=black[v]`);let d=t.map((m,h)=>m.hasAudio?h:-1).filter(m=>m>=0),p=[];if(r.audio==="mix"&&d.length>0)c.push(`${d.map(m=>`[${m}:a]`).join("")}amix=inputs=${d.length}:normalize=0:duration=longest,apad[a]`),p=["-map","[a]"];else if(typeof r.audio=="number"){if(!t[r.audio])throw new l(`audio ${r.audio} is not an input (0-${n-1}).`);if(!t[r.audio].hasAudio)throw new l(`Input ${r.audio} has no audio; pick another, "mix", or "none".`);c.push(`[${r.audio}:a]apad[a]`),p=["-map","[a]"]}let f=p.length>0;return["-y",...t.flatMap(m=>[...m.skipSec>0?["-ss",m.skipSec.toFixed(3)]:[],"-i",m.path]),"-filter_complex",c.join(";"),"-map","[v]",...p,"-t",a.toFixed(3),...Se({quality:r.quality??"standard",audio:f?"aac":"omit"}),e]}var XE={inputs:st.array(st.object({path:st.string().min(1),label:st.string().min(1).max(80).optional()})).min(Ta).max(Ra).describe('Videos in reading order, each with an optional label (e.g. "Before").'),layout:st.enum(Jg).optional().describe("side_by_side (default), stack, or grid."),alignMarker:st.string().min(1).optional().describe("Line inputs up on this add_marker label."),endWith:st.enum(["longest","shortest"]).optional().describe("longest (default; shorter ones hold their last frame) or shortest."),audio:st.union([st.number().int().min(0),st.enum(["mix","none"])]).optional().describe('Input index whose audio to keep (default 0), "mix", or "none".'),output:st.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:st.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Vg(t){t.registerTool("compose",{title:"Compose Videos",description:"Lay 2-9 videos out side by side, stacked, or in a grid (before/after, app and terminal), labelled and in sync.",inputSchema:XE,outputSchema:K,annotations:I},async(e,r)=>{let n=zE(Kg(qE(),"screencast-compose-"));try{k();let o=[],i=[];for(let[f,m]of e.inputs.entries()){O(m.path,`Input ${f}`);let h=await W(m.path);if(!h.width||!h.height||h.durationSec===null)throw new l(`Input ${f} has no readable video: ${m.path}`);let b=0;if(e.alignMarker){let g=We(m.path).find(y=>y.label===e.alignMarker);if(!g)throw new l(`Input ${f} has no marker "${e.alignMarker}".`,"Add one with add_marker, or leave alignMarker out.");b=g.t}let w;if(m.label){let g=kt(m.label);g.warning&&i.push(g.warning);let y=Kg(n,`label${f}.txt`);GE(y,m.label),w={textFile:y,fontFile:g.fontFile}}o.push({path:m.path,width:h.width,height:h.height,durationSec:h.durationSec,hasAudio:h.audioCodec!==null,skipSec:b,label:w})}if(e.alignMarker){let f=Math.min(...o.map(m=>m.skipSec));for(let m of o)m.skipSec-=f}let s=e.endWith??"longest",a=e.audio??(o[0].hasAudio?0:"none"),c=(await W(o[0].path)).fps??30,u=j(e.output,"compose",".mp4",{overwrite:e.overwrite}),d=Yg(o,u,{layout:e.layout??"side_by_side",endWith:s,audio:a,fps:Math.min(60,Math.round(c))}),p=el(o,s);return await U(d,{output:u,durationSec:p,extra:r}),S({outputPath:u,durationSec:Number(p.toFixed(2)),layout:e.layout??"side_by_side",...e.alignMarker?{alignedOn:e.alignMarker,skipSec:o.map(f=>Number(f.skipSec.toFixed(3)))}:{},...i.length?{warnings:i}:{}})}catch(o){return E(o)}finally{HE(n,{recursive:!0,force:!0})}})}import{z as rn}from"zod";import{existsSync as KE,mkdtempSync as VE,readFileSync as QE,rmSync as ZE,writeFileSync as e_}from"node:fs";import{tmpdir as t_}from"node:os";import{join as nb}from"node:path";var Zg=["cpu","sysCpu","rssMB","sysMem"],eb=["top_left","top_right","bottom_left","bottom_right"],JE=120,tl={cpu:"App CPU %",sysCpu:"CPU %",rssMB:"App memory MB",sysMem:"Memory %"};function tb(t,e,r,n=JE){if(!(r>0))throw new l("The video has no duration.");let o=new Array(n).fill(null);for(let s of t){let a=s[e];if(a===void 0||!Number.isFinite(a)||s.t<0||s.t>=r)continue;let c=Math.min(n-1,Math.floor(s.t/r*n));o[c]=Math.max(o[c]??-1/0,a)}let i=null;return o.map(s=>s===null?i:i=s)}function YE(t,e){if(t!=="rssMB")return 100;let r=Math.max(0,...e.map(n=>n??0));return r>0?Math.ceil(r/50)*50:1}var Qg=t=>Math.max(2,Math.round(t/2)*2);function rb(t,e,r,n){let o=Qg(n.width),i=Qg(n.height);if(o>n.videoWidth||i>n.videoHeight)throw new l("The chart is larger than the video.");let s=YE(n.metric,r),a=Math.round(i*.25),c=i-a-4,u=o/r.length,d=r.flatMap((y,v)=>{if(y===null||y<=0)return[];let x=Math.max(1,Math.round(Math.min(y,s)/s*c)),R=n.metric!=="rssMB"&&n.metric!=="sysMem"&&y>=hu;return[`drawbox=x=${Math.floor(v*u)}:y=${i-2-x}:w=${Math.max(1,Math.ceil(u))}:h=${x}:color=${R?"0xFF5252":"0x4FC3F7"}@0.95:t=fill`]}),p=Number(n.durationSec.toFixed(3)),f=n.label?`,drawtext=fontfile=${ye(n.label.fontFile)}:textfile=${ye(n.label.textFile)}:expansion=none:fontcolor=white:fontsize=${Math.max(10,Math.round(a*.7))}:x=6:y=${Math.round(a*.15)}`:"",m=Math.round(Math.min(n.videoWidth,n.videoHeight)*.02),h=n.corner.endsWith("left")?m:n.videoWidth-o-m,b=n.corner.startsWith("top")?m:n.videoHeight-i-m,w=[`color=c=0x1E1E1E:s=${o}x${i}:d=${p}:r=30`,"format=yuv420p",...d].join(",")+f,g=`color=c=white:s=2x${i-a}:d=${p}:r=30`;return["-y","-i",t,"-filter_complex",`${w}[c];${g}[p];[c][p]overlay=x='min(${o-2},t/${p}*${o})':y=${a}:shortest=1[g];[0:v][g]overlay=x=${h}:y=${b}:shortest=1[v]`,"-map","[v]","-map","0:a?",...Se({quality:n.quality??"standard",audio:n.hasAudio?"copy":"omit",faststart:!0}),e]}var r_={input:rn.string().min(1).describe("A recording made with perf: true."),perf:rn.string().optional().describe("Its .perf.jsonl (default: next to input)."),metric:rn.enum(Zg).optional().describe("Default cpu (the app's) if sampled, else sysCpu."),corner:rn.enum(eb).optional().describe("Default top_right."),width:rn.number().int().min(80).max(1920).optional().describe("Chart width px (default video/4)."),output:rn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:rn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function ob(t){t.registerTool("perf_overlay",{title:"Performance Overlay",description:"Draw a recording's CPU or memory track as a small chart with a moving playhead (spikes in red).",inputSchema:r_,outputSchema:K,annotations:I},async(e,r)=>{let n=VE(nb(t_(),"screencast-perf-"));try{k(),O(e.input);let o=e.perf??vt(e.input);if(!KE(o))throw new l(`No performance track at ${o}.`,"Record with start_recording perf: true, or pass perf.");let i=Cn(QE(o,"utf8"));if(i.length===0)throw new l(`${o} has no samples.`);let s=await W(e.input);if(!s.width||!s.height||!s.durationSec)throw new l(`Could not read the size and length of ${e.input}.`);let a=e.metric??(i.some(h=>h.cpu!==void 0)?"cpu":"sysCpu"),c=tb(i,a,s.durationSec);if(c.every(h=>h===null))throw new l(`The track has no ${a} values.`);let u=e.width??Math.max(160,Math.round(s.width/4)),d=kt(tl[a]),p=nb(n,"label.txt");e_(p,tl[a]);let f=j(e.output,"perf",Z(e.input),{overwrite:e.overwrite}),m=rb(e.input,f,c,{metric:a,corner:e.corner??"top_right",width:u,height:Math.round(u*.4),videoWidth:s.width,videoHeight:s.height,durationSec:s.durationSec,label:{textFile:p,fontFile:d.fontFile},hasAudio:s.audioCodec!==null});return await U(m,{output:f,durationSec:s.durationSec,extra:r}),S({outputPath:f,metric:a,samples:i.length})}catch(o){return E(o)}finally{ZE(n,{recursive:!0,force:!0})}})}import{z as Xn}from"zod";import{existsSync as n_,readFileSync as o_,writeFileSync as i_}from"node:fs";var rl=2e3,s_={input:Xn.string().min(1).describe("The .srt to translate (e.g. from transcribe)."),language:Xn.string().regex(/^[a-z]{3}$/).optional().describe('With translations: ISO 639-2 code, e.g. "spa".'),translations:Xn.array(Xn.string().max(Ys)).max(rl).optional().describe("One translated string per cue, in order. Omit to get the cues to translate."),output:Xn.string().optional().describe("Default: <input>.<language>.srt."),overwrite:Xn.boolean().optional().describe("Allow replacing an existing output file.")};function ib(t){t.registerTool("translate_subtitles",{title:"Translate Subtitles",description:"Translate an SRT without breaking its timing: call once for the numbered cues, translate them, then call with translations to write <input>.<language>.srt for chapters' subtitleTracks.",inputSchema:s_,annotations:I},async e=>{try{if(O(e.input,"Subtitle file"),!/\.srt$/i.test(e.input))throw new l("input must be an .srt file.");let r=Ue(o_(e.input,"utf8"));if(r.length===0)throw new l(`No cues in ${e.input}.`);if(r.length>rl)throw new l(`${r.length} cues; at most ${rl} per file.`);if(!e.translations)return S({input:e.input,count:r.length,cues:r.map((i,s)=>`${s+1}. ${i.text.replace(/\s*\n\s*/g," / ")}`),next:`Translate each cue's text (keep " / " as a line break), then call again with language and translations: ${r.length} strings, in order.`});if(!e.language)throw new l('translations needs language (ISO 639-2, e.g. "spa").');let n=Fh(r,e.translations.map(i=>i.replace(/\s+\/\s+/g,`
|
|
339
|
-
`))),o=e.output??Oh(e.input,e.language);if(!/\.srt$/i.test(o))throw new l("output must end in .srt.");if(rr(o),n_(o)){if(!e.overwrite)throw new l(`${o} already exists.`,"Pass overwrite: true to replace it.");yc(o)}return i_(o,it(n)),S({outputPath:o,language:e.language,count:n.length})}catch(r){return E(r)}})}import{z as Ca}from"zod";import{join as c_}from"node:path";import{mkdtempSync as u_,rmSync as l_}from"node:fs";import{tmpdir as p_}from"node:os";import{z as xe}from"zod";var Jn=(t,e)=>{if(!Number.isFinite(t)||t<0)throw new l(`${e} must be a non-negative number.`);return Math.round(t)};function nl(t){let e=Fi(t.from,t.to);return e?`:enable='${e}'`:""}function sb(t){let e=t.x2-t.x1,r=t.y2-t.y1,n=Math.round(Math.hypot(e,r)),o=Math.max(2,Math.round(t.thickness??8));if(n<o*3)throw new l("An arrow must be at least three times as long as it is thick.");return{length:n,thickness:o,angle:Math.atan2(r,e),cx:(t.x1+t.x2)/2,cy:(t.y1+t.y2)/2}}function ab(t,e){let{length:r,thickness:n,angle:o}=sb(t),i=Be(t.color??"red"),s=n*3,a=o.toFixed(6),c=`if(lt(X,W-H),if(lt(abs(Y-H/2),${n}/2),255,0),if(lt(abs(Y-H/2),(W-X)/2),255,0))`;return["-y","-v","error","-f","lavfi","-i",`color=c=${i}:s=${r}x${s}`,"-vf",`format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${c}',rotate=a=${a}:ow=rotw(${a}):oh=roth(${a}):c=none`,"-frames:v","1",...Te(e)]}function il(t,e,r,n,o){if(t.length===0)throw new l("Give at least one callout.");let i=[],s=[],a=r;return t.forEach((c,u)=>{let d=`[${o}c${u}]`;if(c.type==="box"){let p=Be(c.color??"red"),f=c.fill?"fill":String(Math.max(1,Math.round(c.thickness??4)));s.push(`${a}drawbox=x=${Jn(c.x,"x")}:y=${Jn(c.y,"y")}:w=${Jn(c.width,"width")}:h=${Jn(c.height,"height")}:color=${p}:t=${f}${nl(c)}${d}`)}else if(c.type==="text"){let p=e.textFiles[u];if(!p)throw new l("Internal: missing text file for a text callout.");let f=Be(c.color??"white"),m=Math.max(8,Math.round(c.size??32)),h=c.background===!1?"":`:box=1:boxcolor=black@0.6:boxborderw=${Math.round(m/3)}`;s.push(`${a}drawtext=fontfile=${ye(e.fontFiles?.[u]??e.fontFile)}:textfile=${ye(p)}:expansion=none:x=${Jn(c.x,"x")}:y=${Jn(c.y,"y")}:fontsize=${m}:fontcolor=${f}${h}${nl(c)}${d}`)}else{let p=e.arrowFiles[u];if(!p)throw new l("Internal: missing image for an arrow callout.");let{cx:f,cy:m}=sb(c),h=n+i.length/4;i.push("-loop","1","-i",p),s.push(`${a}[${h}:v]overlay=x=${f.toFixed(1)}-w/2:y=${m.toFixed(1)}-h/2:shortest=1${nl(c)}${d}`)}a=d}),{steps:s,out:a,extraInputs:i}}function cb(t,e,r,n,o="standard",i=!1){let s=i?r.map(({from:d,to:p,...f})=>f):r,{steps:a,out:c,extraInputs:u}=il(s,n,"[0:v]",1,"");return i?["-y","-i",t,...u,"-filter_complex",a.join(";"),"-map",c,"-frames:v","1",...Te(e)]:["-y","-i",t,...u,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Re(o),"-c:a","copy",e]}var ol={from:xe.number().nonnegative().optional(),to:xe.number().positive().optional(),color:xe.string().optional()},_r=xe.string().min(1).optional().describe("Font: a .ttf/.otf/.ttc path or a C:\\Windows\\Fonts file name. Default: bundled Inter, with a covering system font for scripts it lacks (CJK, emoji, Arabic, ...)."),Aa=xe.discriminatedUnion("type",[xe.object({type:xe.literal("box"),x:xe.number(),y:xe.number(),width:xe.number().positive(),height:xe.number().positive(),thickness:xe.number().positive().optional().describe("Outline px (default 4)."),fill:xe.boolean().optional().describe("Fill instead of outline."),...ol}),xe.object({type:xe.literal("text"),x:xe.number(),y:xe.number(),text:xe.string().min(1),size:xe.number().positive().optional().describe("Font size px (default 32)."),background:xe.boolean().optional().describe("Dark panel behind the text (default true)."),...ol}),xe.object({type:xe.literal("arrow"),x1:xe.number(),y1:xe.number(),x2:xe.number().describe("Head (x2,y2) is the point the arrow points at."),y2:xe.number(),thickness:xe.number().positive().optional().describe("Shaft px (default 8)."),...ol})]);import{join as ub}from"node:path";import{writeFileSync as a_}from"node:fs";function sl(t,e){let r={fontFiles:[],fallbackFonts:[],warnings:[]};return t.forEach((n,o)=>{if(n.type!=="text"){r.fontFiles.push(null);return}let i=kt(n.text,{weight:"bold",fontFile:e});r.fontFiles.push(i.fontFile),i.fallback&&r.fallbackFonts.push({item:o,fontFile:i.fontFile}),i.warning&&r.warnings.push(`Item ${o}: ${i.warning}`)}),r}async function Ma(t,e,r="",n){let o=sl(t,n),i=t.map((a,c)=>{if(a.type!=="text")return null;let u=ub(e,`${r}text_${c}.txt`);return a_(u,a.text),u}),s=[];for(let[a,c]of t.entries()){if(c.type!=="arrow"){s.push(null);continue}let u=ub(e,`${r}arrow_${a}.png`);await te(ab(c,u),3e4),s.push(u)}return{fontFile:Ut("bold"),textFiles:i,arrowFiles:s,...o}}var d_={input:Ca.string().min(1).describe("Path to the source video or image (png/jpg; from/to are ignored for an image)."),items:Ca.array(Aa).min(1).max(50).describe("Boxes, text labels, and arrows, drawn in order (later on top), in video pixels. Each shows from..to seconds (default: whole video); color is a name, #RRGGBB, or name@alpha."),fontFile:_r,output:Ca.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ca.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function lb(t){t.registerTool("callout",{title:"Add Callouts",description:"Annotate a video or screenshot with timed boxes, text labels, and arrows. Fallback fonts used are listed in fallbackFonts; characters no font covers are reported in warnings.",inputSchema:d_,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=e.items,{still:o,ext:i}=Ni(e.input,e.output),s=j(e.output,"callout",i,{overwrite:e.overwrite,anyContainer:!0}),a=u_(c_(p_(),"screencast-callout-"));try{let c=await Ma(n,a,"",e.fontFile),u=cb(e.input,s,n,c,void 0,o);return await U(u,{output:s,durationSec:o?null:await ue(e.input),extra:r}),S({outputPath:s,callouts:n.length,...c.fallbackFonts.length>0&&{fallbackFonts:c.fallbackFonts},...c.warnings.length>0&&{warnings:c.warnings}})}finally{l_(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as ti}from"zod";import{join as __}from"node:path";import{mkdtempSync as T_,rmSync as R_}from"node:fs";import{tmpdir as A_}from"node:os";import{z as qt}from"zod";import{existsSync as m_,readFileSync as f_,writeFileSync as h_}from"node:fs";import{join as g_}from"node:path";var b_=["bottom","bottom-left","bottom-right","top","top-left","top-right"],al=1.2,w_=.5,pb=8,db=100,mb="Typing\u2026",y_=new Set(["Ctrl","Alt","Shift","Win"]),x_=/^(?:[A-Z0-9]|F\d{1,2}|Enter|Tab|Esc|Space|Backspace|Delete|Insert|Left|Up|Right|Down|Home|End|PageUp|PageDown|[=\-,./`[\];'\\])$/;function S_(t,e="shortcuts"){let r=t.split("+"),n=r.pop();return n===void 0||r.length===0||!x_.test(n)||!r.every(o=>y_.has(o))||new Set(r).size!==r.length?null:[...r,e==="masked"?"\u2026":n].join(" + ")}var v_={left:"Click",right:"Right click",middle:"Middle click",x1:"Back button",x2:"Forward button"},Pa=t=>Math.round(t*1e3)/1e3;function $_(t,e={}){let r=e.lingerSec??al;if(!(r>0))throw new l("lingerSec must be positive.");let n=e.keys??"shortcuts",o=[...t].filter(a=>Number.isFinite(a.t)&&a.t>=0).sort((a,c)=>a.t-c.t),i=[];for(let a of o)if(a.type==="key"&&a.keys){let c=S_(a.keys,n);if(!c)continue;let u=i.at(-1);if(u&&u.kind==="shortcut"&&u.base===c&&a.t-u.last<=r){u.count++,u.last=a.t,u.label=`${c} \xD7${u.count}`,u.to=a.t+r;continue}i.push({from:a.t,to:a.t+r,label:c,base:c,kind:"shortcut",count:1,last:a.t})}else if(a.type==="down"&&e.clicks!==!1&&a.inFrame){let c=v_[a.button??"left"]??"Click",u=i.at(-1);if(c==="Click"&&u&&u.kind==="click"&&u.base==="Click"&&u.count<3&&a.t-u.last<=w_&&Math.abs(a.x-(u.x??a.x))<=pb&&Math.abs(a.y-(u.y??a.y))<=pb){u.count++,u.last=a.t,u.label=u.count===2?"Double click":"Triple click",u.to=a.t+r;continue}i.push({from:a.t,to:a.t+r,label:c,base:c,kind:"click",count:1,x:a.x,y:a.y,last:a.t})}else if(a.type==="typing"&&e.typing!==!1){let c=a.t+Math.max(a.durationSec??0,0),u=i.at(-1);if(u&&u.kind==="typing"&&a.t<=u.to){u.to=Math.max(u.to,c+r/2),u.last=a.t;continue}i.push({from:a.t,to:c+r/2,label:mb,base:mb,kind:"typing",count:1,last:a.t})}let s=[];return i.forEach((a,c)=>{let u=i[c+1],d=u?Math.min(a.to,u.from):a.to;d-a.from>=.05&&s.push({from:Pa(a.from),to:Pa(d),label:a.label,kind:a.kind})}),s}function Ia(t){let e=new Map;for(let r of t){let n=e.get(r.label);n||(n={label:r.label,windows:[]},e.set(r.label,n)),n.windows.push([r.from,r.to])}if(e.size>db)throw new l(`${e.size} different badges is more than ${db}; trim the video or turn off keys or clicks.`);return[...e.values()]}function k_(t,e){return t.flatMap(r=>{let n=e(r.from,r.to);return n&&n[1]-n[0]>=.05?[{...r,from:Pa(n[0]),to:Pa(n[1])}]:[]})}function fb(t,e){return k_(t,(r,n)=>Gr(r,n,e))}function E_(t,e){if(e!==void 0){if(!(e>=8&&e<=400))throw new l("size must be between 8 and 400.");return Math.round(e)}return Math.max(14,Math.round(t*.045))}function cl(t,e,r,n,o,i){if(t.length===0)throw new l("No badges to draw.");let s=E_(n.height,r.size),a=Math.round(s/3),c=a+Math.round(s*.6),u=r.position??"bottom",d=u.endsWith("left")?`${c}`:u.endsWith("right")?`w-tw-${c}`:"(w-tw)/2",p=u.startsWith("top")?`${c}`:`h-lh-${c}`,f=Be(r.color??"white"),m=[],h=o;return t.forEach((b,w)=>{let g=e.textFiles[b.label];if(!g)throw new l(`Internal: no text file for badge "${b.label}".`);let y=At(b.windows.map(([x,R])=>`between(t,${x},${R})`)),v=`[${i}k${w}]`;m.push(`${h}drawtext=fontfile=${ye(e.fontFile)}:textfile=${ye(g)}:expansion=none:fontsize=${s}:fontcolor=${f}:box=1:boxcolor=black@0.6:boxborderw=${a}:x=${d}:y=${p}:enable='${y}'${v}`),h=v}),{steps:m,out:h}}function hb(t,e,r,n,o,i,s="standard"){let{steps:a,out:c}=cl(r,n,o,i,"[0:v]","");return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Re(s),"-c:a","copy",e]}var Fa={events:qt.string().optional(),clicks:qt.boolean().optional(),typing:qt.boolean().optional(),keys:qt.enum(["shortcuts","masked"]).optional(),lingerSec:qt.number().positive().max(10).optional(),position:qt.enum(b_).optional(),size:qt.number().min(8).max(400).optional(),color:qt.string().optional(),fontFile:qt.string().min(1).optional()};function Oa(t,e,r){let n=e??ke(t).jsonl;if(!m_(n))throw new l(`No event log for ${t} (looked for ${n}). Record with start_recording events: true (keys: "shortcuts" to name shortcuts), or pass events: <path to .events.jsonl>.`);let o=ze(f_(n,"utf8"));return{badges:$_(o,r),shortcutsLogged:o.filter(i=>i.type==="key").length,path:n}}function ei(t,e,r="",n){let o=kt(t.join(" "),{weight:"bold",fontFile:n}),i={};return t.forEach((s,a)=>{if(e===null){i[s]=`<badge ${a}>`;return}let c=g_(e,`${r}badge_${a}.txt`);h_(c,s),i[s]=c}),{fontFile:o.fontFile,textFiles:i,...o.fallback&&{fallbackFont:o.fontFile},warnings:o.warning?[o.warning]:[]}}var Tr=Fa,M_={input:ti.string().min(1).describe("Path to the recording."),events:Tr.events.describe("Event log (default: the input's .events.jsonl)."),clicks:Tr.clicks.describe("Show clicks (default true)."),typing:Tr.typing.describe('Show typing as "Typing\u2026" (default true).'),keys:Tr.keys.describe("shortcuts (default): the chord (Ctrl + S); masked: modifiers only (Ctrl + \u2026)."),lingerSec:Tr.lingerSec.describe(`Seconds a badge stays up (default ${al}).`),position:Tr.position.describe("Default bottom (centred)."),size:Tr.size.describe("Font px (default 4.5% of the frame height)."),color:Tr.color.describe("Text color (default white)."),fontFile:_r,dryRun:ti.boolean().optional().describe("Return the planned badges; write nothing."),output:ti.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ti.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function gb(t){t.registerTool("keystroke_overlay",{title:"Keystroke Overlay",description:"Burn keycast-style badges for shortcuts, clicks, and typing from the recording's input event log (start_recording events: true). Never shows typed text: the log has none.",inputSchema:M_,outputSchema:B({badges:ti.number().int()}),annotations:I},async(e,r)=>{try{k(),O(e.input);let n={clicks:e.clicks,typing:e.typing,keys:e.keys,lingerSec:e.lingerSec},{badges:o,shortcutsLogged:i}=Oa(e.input,e.events,n),s=i===0?'The log names no shortcuts (recorded with keys: "masked"), so only clicks and typing can show.':void 0;if(o.length===0)return S({badges:0,note:"Nothing to show: the log has no clicks, shortcuts, or typing; nothing written."});let a=Ia(o);if(e.dryRun){let p=ei(a.map(f=>f.label),null,"",e.fontFile);return S({dryRun:!0,badges:o.length,plan:o,...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}let c=await W(e.input);if(!c.height)throw new l(`Could not read the size of ${e.input}.`);let u=j(e.output,"keys",Z(e.input),{overwrite:e.overwrite}),d=T_(__(A_(),"screencast-keys-"));try{let p=ei(a.map(h=>h.label),d,"",e.fontFile),f={position:e.position,size:e.size,color:e.color},m=hb(e.input,u,a,p,f,{height:c.height});return await U(m,{output:u,durationSec:c.durationSec,extra:r}),S({outputPath:u,badges:o.length,labels:a.map(h=>h.label),...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}finally{R_(d,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as ni}from"zod";import{join as Sb}from"node:path";import{mkdtempSync as Y_,rmSync as K_,writeFileSync as V_}from"node:fs";import{tmpdir as Q_}from"node:os";import{z as Yn}from"zod";import{existsSync as C_,readFileSync as P_}from"node:fs";var ri={w:114,h:168,hotX:9,hotY:9,arrowH:135};function Na(){return _n("cursor","arrow.png")}var I_=.5,ul=2,ll=1.5,F_=.4,bb=240,O_=4,N_=.35,D_=new Set(["move","down","up","wheel"]),Kn=t=>Math.round(t*1e3)/1e3;function L_(t){let e=6+(1-t)*34;return{omega:e,lead:Math.min(2/e,.2)}}function B_(t){let e=[],r=hc/1e3;for(let n of t){let o=e.at(-1);o&&n.t-o.t>r*2&&(o.x!==n.x||o.y!==n.y)&&e.push({t:n.t-r,x:o.x,y:o.y}),o&&n.t===o.t?e[e.length-1]=n:e.push(n)}return e}function W_(t,e,r=0){if(t.length===0)return{x:0,y:0,i:0};let n=Math.max(0,Math.min(r,t.length-1));for(;n>0&&t[n].t>e;)n--;for(;n<t.length-1&&t[n+1].t<=e;)n++;let o=t[n],i=t[n+1];if(!i||e<=o.t)return{x:o.x,y:o.y,i:n};let s=(e-o.t)/(i.t-o.t);return{x:o.x+(i.x-o.x)*s,y:o.y+(i.y-o.y)*s,i:n}}function j_(t,e,r,n,o){if(t.length===0)return[];let i=1/bb,s=0,a=w=>{let g=W_(t,w+r,s);return s=g.i,g},c=a(n),u=c.x,d=c.y,p=0,f=0,m=[{t:Kn(n),x:u,y:d}],h=Math.exp(-e*i),b=Math.max(0,Math.ceil((o-n)*bb));for(let w=1;w<=b;w++){let g=Math.min(o,n+w*i),y=a(g),v=u-y.x,x=d-y.y,R=(p+e*v)*i,T=(f+e*x)*i;p=(p-e*R)*h,f=(f-e*T)*h,u=y.x+(v+R)*h,d=y.y+(x+T)*h,(w%O_===0||w===b)&&m.push({t:Kn(g),x:u,y:d})}return m}function U_(t,e=N_){if(t.length<=2)return[...t];let r=new Uint8Array(t.length);r[0]=1,r[t.length-1]=1;let n=[[0,t.length-1]];for(;n.length>0;){let[o,i]=n.pop(),s=t[o],a=t[i],c=-1,u=-1;for(let d=o+1;d<i;d++){let p=t[d],f=a.t>s.t?(p.t-s.t)/(a.t-s.t):0,m=Math.hypot(p.x-(s.x+(a.x-s.x)*f),p.y-(s.y+(a.y-s.y)*f));m>c&&(c=m,u=d)}c>e&&(r[u]=1,n.push([o,u],[u,i]))}return t.filter((o,i)=>r[i]===1)}function z_(t){let e=[];for(let r of[...t].sort((n,o)=>n[0]-o[0])){let n=e.at(-1);n&&r[0]<=n[1]?n[1]=Math.max(n[1],r[1]):e.push([r[0],r[1]])}return e}function H_(t,e={},r=null){let n=e.smoothing??I_;if(!(n>=0&&n<=1))throw new l("smoothing must be between 0 and 1.");let o=e.hideAfterSec??ul;if(!(o>=0))throw new l("hideAfterSec must be 0 or more.");let i=t.filter(h=>D_.has(h.type)&&Number.isFinite(h.t)&&h.t>=0&&Number.isFinite(h.x)&&Number.isFinite(h.y)).filter(h=>r===null||h.t<=r).sort((h,b)=>h.t-b.t);if(i.length===0)return{path:[],visible:[],clicks:[]};let s=B_(i.map(h=>({t:h.t,x:h.x,y:h.y}))),a=s[0].t,c=s.at(-1).t,u,d=0;if(n===0)u=s.map(h=>({...h})),r!==null&&r>c&&u.push({...s.at(-1),t:r});else{let h=L_(n);d=h.lead;let b=Math.max(0,a-d),w=Math.max(b,r??c+8/h.omega);u=j_(s,h.omega,d,b,w)}let p=Math.max(0,a-d),f=o===0?[[p,r??1/0]]:z_(i.map(h=>[Math.max(0,h.t-d),h.t+o])),m=i.filter(h=>h.type==="down").map(h=>({t:h.t,x:h.x,y:h.y}));return{path:u,visible:f.map(([h,b])=>[Kn(h),r!==null?Math.min(b,r):b]).filter(([h,b])=>b>h),clicks:m}}var G_={sx:1,sy:1,ox:0,oy:0};function Da(t,e=[],r=G_){let n=a=>{let c=as(a.t,e);return c===null?null:{t:Kn(c),x:a.x*r.sx+r.ox,y:a.y*r.sy+r.oy}},o=[];for(let a of t.path){let c=n(a);c&&(o.length>0&&o.at(-1).t>=c.t?o[o.length-1]={...c,t:o.at(-1).t}:o.push(c))}let i=t.visible.flatMap(([a,c])=>{let u=Gr(a,c,e);return u&&u[1]-u[0]>=.05?[[Kn(u[0]),Number.isFinite(u[1])?Kn(u[1]):u[1]]]:[]}),s=t.clicks.flatMap(a=>{let c=n(a);return c?[c]:[]});return{path:U_(o),visible:i,clicks:s}}var Ie=(t,e=2)=>{let r=Number(t.toFixed(e));return Object.is(r,-0)?"0":String(r)};function wb(t,e,r){let n=Number(r.toFixed(3));return n===0?Ie(t):`${Ie(t)}${n<0?"-":"+"}(t-${Ie(e,3)})*${Ie(Math.abs(n),3)}`}function q_(t,e=ll){if(!(e>=.25&&e<=8))throw new l("size must be between 0.25 and 8.");let r=Math.max(8,t*.025*e),n=r/ri.arrowH,o=Math.max(12,Math.round(r*2.2));return{spriteW:Math.max(2,Math.round(ri.w*n)),spriteH:Math.max(2,Math.round(ri.h*n)),hotX:ri.hotX*n,hotY:ri.hotY*n,ripples:[.45,.72,1].map(i=>Math.max(6,Math.round(o*i/2)*2)),spotRadius:Math.max(24,Math.round(t*.12))}}function X_(t){let e=new Map;for(let r of[...t].sort((n,o)=>n.t-o.t)){let n=Ie(Math.max(0,r.t),3),o=e.get(n)??[];o.push(r.text),e.set(n,o)}return[...e.entries()].map(([r,n])=>`${r} ${n.join(", ")};`).join(`
|
|
338
|
+
`;async function _r(){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 pt(vE,"OCR languages",{timeoutMs:dr(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:j(t)}}}var $E=["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"],kE=[{name:"SCREENCAST_MAX_RECORDING_SEC",ok:t=>Number.isInteger(t)&&t>=0&&t<=168*3600,want:"an integer from 0 (no cap) to 604800",otherwise:"start_recording fails until it is fixed"},{name:"SCREENCAST_JOB_TIMEOUT_MS",ok:t=>Number.isInteger(t)&&t>0,want:"a positive integer (milliseconds)",otherwise:"edits use the default timeout"},{name:"SCREENCAST_PS_TIMEOUT_MS",ok:t=>Number.isInteger(t)&&t>0,want:"a positive integer (milliseconds)",otherwise:"the PowerShell helpers use their default limits"},{name:"SCREENCAST_RETENTION_DAYS",ok:t=>Number.isFinite(t)&&t>=0,want:"a number of days (0 = off)",otherwise:"nothing is pruned"}],EE=["auto","1","true","yes","on","always","0","false","no","off","never"];function Pg(t=process.env){let e=[];for(let n of kE){let o=t[n.name];o===void 0||o.trim()===""||n.ok(Number(o.trim()))||e.push(`${n.name}="${o}" is not ${n.want}, so ${n.otherwise}.`)}let r=t.SCREENCAST_CONFIRM_CAPTURE;return r!==void 0&&r.trim()!==""&&!EE.includes(r.trim().toLowerCase())&&e.push(`SCREENCAST_CONFIRM_CAPTURE="${r}" is not auto, always (1/true/yes/on) or off (0/false/no/never), so captures follow auto.`),e}function Ig(t=process.env){return Object.fromEntries($E.map(e=>{let r=t[e];return[e,r&&r.trim().length>0?r:null]}))}var Fg=[{filter:"whisper",tools:"transcribe",why:`FFmpeg ${tn}+ built with whisper.cpp`},{filter:"gfxcapture",tools:'backend: "wgc" (screenshot, start_recording, find_text)',why:`FFmpeg ${tn}+ on Windows`},{filter:"subtitles",tools:"burn_subtitles",why:"libass"},{filter:"drawtext",tools:"title_card, callout, contact_sheet labels, produce",why:"libfreetype"},{filter:"afftdn",tools:"denoise",why:"a standard build"},{filter:"loudnorm",tools:"normalize_audio",why:"a standard build"},{filter:"xfade",tools:"xfade_transition, assemble_highlights",why:"FFmpeg 4.3+"}];var Qu=8,CE={input:Rr.string().optional().describe("Recording path."),sessionId:Rr.string().optional().describe("Or a stopped session id."),sceneThreshold:Rr.number().gt(0).lt(1).optional().describe(`Change starting a segment (default ${Uu}).`),maxFrames:Rr.number().int().min(1).max(ch).optional().describe(`Keyframes to OCR (default ${zu}).`),transcript:Rr.string().optional().describe("An .srt, or 'whisper' to transcribe. Default: <video>.srt if any."),force:Rr.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:CE,outputSchema:N({indexPath:Rr.string(),segments:Rr.number()}),annotations:C},async(e,r)=>{let n=TE(Vu(AE(),"screencast-index-"));try{let{ffmpeg:o}=k(),i=await na(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??Uu,u=e.maxFrames??zu,d=ye("edits"),p=lh(i.path,d),f=ta(i.path),m=Ao(r),h=[],b=e.force?null:Qs(i.path,d,f),w=b?Ko(b):null,g=null,y=async()=>g??=process.platform==="win32"&&(await _r()).available,v=ph(w,{fingerprint:f,sceneThreshold:c,maxFrames:u,ocrAvailable:w!==null&&!w.ocr?await y():!1}),x,T=0,R=!1;if(v)x=w.segments,T=w.framesRead,R=w.ocr;else{let K=await ce(o,ur(i.path,c),de(a),{signal:r.signal});if(K.code!==0)throw new l(`Scene scan failed (exit ${K.code}): ${K.stderr.trim().slice(-400)}`);m?.(.1);let X=fh(mh(lr(K.stdout),a,u),a),ne=X.map(()=>[]);if(R=await y(),R)for(let J=0;J<X.length;J+=Qu){r.signal.throwIfAborted();let O=X.slice(J,J+Qu),q=(await Je(O,async(ae,_)=>{let A=Vu(n,`key_${J+_}.png`);return await te(kn(i.path,ea(ae),A),6e4,{signal:r.signal}),{at:J+_,path:A}})).filter(ae=>Gn(ae.path)),ee=q.length>0?await mt(q.map(ae=>ae.path),n,r.signal,{sameSize:!0}):[];ee.forEach((ae,_)=>ne[q[_].at]=ae.lines.map(A=>A.text)),T+=ee.length,m?.(.1+.85*Math.min(X.length,J+Qu)/X.length)}else h.push("Windows OCR is not available, so the index holds no screen text; install an OCR language (doctor).");let $=X.map((J,O)=>({...J,ocr:ne[O]??[]}));x=R?hh($):$}x=dh(x);let P=i.eventsPath?gh(Ie(qn(i.eventsPath,"utf8"))):[];x=en(x,P,"events"),x=en(x,bh(i.markers),"markers");let z=st(i.path);if(Gn(z)){let K=Dn(qn(z,"utf8")),{busy:X}=Nn(K),ne=X.map($=>{let J=Math.max(...K.filter(O=>O.t>=$.start&&O.t<=$.end).map(O=>O.cpu??O.sysCpu));return{t:$.start,text:`cpu pinned ${Math.round(J)}% for ${Math.round($.end-$.start)} s (performance spike)`}});ne.length&&(x=en(x,[...x.flatMap($=>$.events??[]),...ne],"events"))}let H=ft(i.path);if(Gn(H)){let K=Fs(qn(H,"utf8")),X=je(K.map(ne=>`${ne.source}: ${ne.line}`),We);x=en(x,K.map((ne,$)=>({t:ne.t,text:X[$]??""})),"logs")}let D=await PE(e.transcript,i.path,s.audioCodec!==null,a,r.signal,h);if(D!==null)x=en(x,wh(D),"transcript");else if(v&&w){let K=w.segments.flatMap(X=>X.transcript??[]);x=en(x,K,"transcript")}let M={version:ju,video:i.path,fingerprint:f,durationSec:a,createdAt:new Date().toISOString(),sceneThreshold:c,maxFrames:u,framesRead:T,ocr:R,segments:x};RE(Vu(p,".."),{recursive:!0}),yh(p,M);let ie=Hu(i.path);if(ie!==p&&Gn(ie)){let K=Ko(ie);K&&Ks(K,i.path,f)&&Zu(ie,{force:!0})}m?.(1);let Z=K=>x.reduce((X,ne)=>X+(ne[K]?.length??0),0);return S({indexPath:p,segments:x.length,cached:v,framesRead:T,durationSec:a,sources:{screenLines:x.reduce((K,X)=>K+X.ocr.length,0),events:Z("events"),markers:Z("markers"),transcriptCues:Z("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{Zu(n,{recursive:!0,force:!0})}})}async function PE(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(!Qe("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=Er(void 0),u=Xe(".srt");try{return await te(zn(e,c,u),de(n),{signal:o}),Gn(u)?gt(qe(qn(u,"utf8"))):[]}finally{Zu(u,{force:!0})}}if(t!==void 0){if(!Gn(t))throw new l(`Transcript not found: ${t}`);return gt(qe(qn(t,"utf8")))}let s;try{s=ME(_E(e))}catch{return null}let a=Zs(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?gt(qe(qn(a.path,"utf8"))):null}import{z as Xt}from"zod";import{join as Ng}from"node:path";import{existsSync as Dg,mkdtempSync as IE,rmSync as FE}from"node:fs";import{tmpdir as OE}from"node:os";var NE=480,DE={input:Xt.string().optional().describe("Recording path."),sessionId:Xt.string().optional().describe("Or a stopped session id."),query:Xt.string().min(1).describe("Text; tolerates OCR misreads."),regex:Xt.boolean().optional().describe("query is a regex."),limit:Xt.number().int().min(1).max(uh).optional().describe(`Max hits (default ${Ys}).`),images:Xt.number().int().min(0).max(Zo).optional().describe("Thumbnails of the top N hits (default 0).")};function Lg(t){t.registerTool("search_recording",{title:"Search Recording",description:"Search an index_recording timeline (screen text, events, markers, transcript): timecoded hits, best first, secrets masked. No frames unless asked. No input: search all indexes.",inputSchema:DE,outputSchema:N({total:Xt.number(),hits:Xt.array(Xt.unknown())}),annotations:ge},async(e,r)=>{try{if(e.input===void 0&&e.sessionId===void 0){if((e.images??0)>0)throw new l("images needs one recording.","Pass input or sessionId, or search the library with images: 0.");let f=Sh(Fe()).flatMap(b=>{let w=Gu(b);return w?[{indexPath:b,index:w}]:[]}),m=vh(f,e.query,{regex:e.regex===!0,limit:e.limit}),h=m.recordings.map(b=>({...b,...Dg(b.video)?{}:{missing:!0}}));return S({query:e.query,searched:m.searched,total:m.total,hits:m.hits,recordings:h,...m.searched===0?{note:"No indexed recordings under SCREENCAST_HOME; run index_recording first."}:{}})}let n=await na(e),o=ta(n.path),i=Qs(n.path,ye("edits"),o),s=i?Gu(i):null;if(!i||!s)throw new l(`No index for ${n.path}.`,"Run index_recording on it first.");let a=!ra(s.fingerprint,o),{hits:c,total:u}=qu(s,e.query,{regex:e.regex===!0,limit:e.limit,video:n.path,fingerprint:o}),d=Math.min(da(e.images??0),c.length),p=[];if(d>0){k();let f=IE(Ng(OE(),"screencast-search-"));try{let m=[];for(let[h,b]of c.slice(0,d).entries()){let w=b.t===b.start?ea(b):b.t,g=Ng(f,`hit_${h}.png`);await te(kn(n.path,w,g),6e4,{signal:r.signal}),Dg(g)&&m.push(g)}p=(await Pe(m,NE,d)).images}finally{FE(f,{recursive:!0,force:!0})}}return S({indexPath:i,query:e.query,total:u,hits:c,...u>c.length?{more:u-c.length}:{},...s.ocr?{}:{note:"The index has no screen text (OCR was unavailable when it was built)."},...a?{stale:!0,warning:"The recording changed since it was indexed; run index_recording again."}:{}},p)}catch(n){return E(n)}})}import{z as Tr}from"zod";var LE={input:Tr.string().min(1).describe("Path to the media file to probe.")};function Bg(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:LE,outputSchema:N({input:Tr.string(),durationSec:Tr.number().nullable(),width:Tr.number().nullable(),height:Tr.number().nullable(),fps:Tr.number().nullable(),videoCodec:Tr.string().nullable(),audioCodec:Tr.string().nullable()}),annotations:ge},async e=>{try{return F(e.input),S({input:e.input,...await L(e.input)})}catch(r){return E(r)}})}import{z as rn}from"zod";import{extname as BE}from"node:path";var WE={input:rn.string().min(1).describe("Source video path."),start:rn.number().nonnegative().describe("Start time in seconds."),end:rn.number().positive().optional().describe("End time in seconds. Use end OR duration."),duration:rn.number().positive().optional().describe("Clip length in seconds. Use end OR duration."),exact:rn.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:rn.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:rn.boolean().optional().describe("Replace an existing output (default false).")};function Wg(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:WE,outputSchema:Y,annotations:C},async(e,r)=>{try{k(),F(e.input);let n=e.exact===!1?BE(e.input)||".mp4":V(e.input),o=B(e.output,"trim",n,{overwrite:e.overwrite,anyContainer:e.exact===!1}),i=Op(e.input,o,{start:e.start,end:e.end,duration:e.duration,exact:e.exact}),s=e.start??0,a=e.end??await ue(e.input),c=e.duration??(a!==null?a-s:null);return await U(i,{output:o,durationSec:c,extra:r}),S({outputPath:o})}catch(n){return E(n)}})}import{z as ka}from"zod";import{extname as XE,resolve as JE}from"node:path";import{writeFileSync as YE,rmSync as KE}from"node:fs";var jE=1920,UE=1080,jg=30,Ug=48e3,Xn=1,el="standard";function tl(t){return Math.round(t*1e3)/1e3}function zg(t){return t.width!==void 0&&cr(t.width,"width"),t.height!==void 0&&cr(t.height,"height"),{w:t.width??jE,h:t.height??UE}}function zE(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 HE(t){return`aresample=${t},aformat=sample_fmts=fltp:channel_layouts=stereo`}function GE(t,e){let r=[],n=0;for(let[o,i]of t.slice(0,-1).entries())n+=i,r.push(Math.max(0,tl(n-(o+1)*e)));return r}function nn(t){return t.videoDurationSec??t.durationSec}function Hg(t,e,r,n,o={},i=[!1,!1]){let s=Tc(o.transition??"fade"),a=o.duration??Xn;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 oi([t,e],r,n,{...o,transition:s},i)}function oi(t,e,r,n={},o=[]){if(t.length<2)throw new l("assemble_highlights requires at least two clips.");let{w:i,h:s}=zg(n),a=n.fps??jg,c=n.audioRate??Ug,u=n.transition??"cut",d=n.duration??Xn,p=t.length,f=zE(i,s,a),m=HE(c),h=o.some(Boolean),b=[];for(let g=0;g<p;g++)if(b.push(`[${g}:v]${f}[v${g}]`),!!h)if(o[g]){let y=e[g]??Number.NaN,v=Number.isFinite(y)&&y>0?`,apad,atrim=duration=${tl(y)}`:"";b.push(`[${g}:a]${m}${v}[a${g}]`)}else{let y=e[g]??Number.NaN;if(!Number.isFinite(y)||y<=0)throw new l(`clip ${g} has no audio track and its duration is unknown, so a matching silent track cannot be generated.`);b.push(`anullsrc=channel_layout=stereo:sample_rate=${c}:d=${y}[a${g}]`)}let w=[];if(u==="cut")if(h){let g=t.map((y,v)=>`[v${v}][a${v}]`).join("");b.push(`${g}concat=n=${p}:v=1:a=1[vout][aout]`),w.push("-map","[vout]","-map","[aout]")}else{let g=t.map((y,v)=>`[v${v}]`).join("");b.push(`${g}concat=n=${p}:v=1:a=0[vout]`),w.push("-map","[vout]")}else{if(Tc(u),e.length!==p)throw new l(`a ${u} transition needs a duration for each of the ${p} clips.`);if(!Number.isFinite(d)||d<=0)throw new l("transition duration must be a positive number.");let g=e.findIndex(x=>!Number.isFinite(x)||x<=d);if(g!==-1)throw new l(`clip ${g} (${e[g]}s) must be longer than the ${d}s ${u} transition. Use a shorter transition or trim fewer frames.`);let y=GE(e,d),v="v0";for(let x=1;x<p;x++){let T=x===p-1?"vout":`vx${x}`;b.push(`[${v}][v${x}]xfade=transition=${u}:duration=${d}:offset=${y[x-1]}[${T}]`),v=T}if(w.push("-map","[vout]"),h){let x="a0";for(let T=1;T<p;T++){let R=T===p-1?"aout":`ax${T}`;b.push(`[${x}][a${T}]acrossfade=d=${d}[${R}]`),x=R}w.push("-map","[aout]")}}return["-y",...t.flatMap(g=>["-i",g]),"-filter_complex",b.join(";"),...w,...ve({quality:n.quality??el,audio:h?"aac":"none",faststart:!0}),r]}var rl=3;function Gg(t,e,r,n={}){let{w:o,h:i}=zg(n),s=n.duration??rl,a=n.fps??jg,c=Ue(n.bg??"black","bg"),u=Ue(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=${xe(e)}:textfile=${xe(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",...ve({quality:n.quality??el,audio:"aac",faststart:!0}),r]}function qg(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,tl(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),...ve({video:["-c:v","copy"],audio:"aac",bitrate:"192k",faststart:!0}),r]}var Jn=["16:9","9:16","1:1","4:5"],Sa=["pad","crop"],Yn={"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 va(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 Xg(t,e,r,n="pad",o=el){let i=Yn[r];if(!i)throw new l(`Unknown aspect "${r}".`);return["-y","-i",t,"-vf",`${va(i.w,i.h,n)},format=yuv420p`,...ve({quality:o,audio:"copy",faststart:!0}),e]}var $a=["youtube","instagram_reel","tiktok","x","square","steam_trailer","vertical_reel"],nl={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 qE(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 ol(t,e="pad",r=""){let n=nl[t];if(!n)throw new l(`Unknown platform "${t}".`);let o=Yn[n.aspect],i=n.blurFill?qE(o.w,o.h,r):va(o.w,o.h,e),s=n.loudness?`loudnorm=I=-14:TP=-1:LRA=11,aresample=${n.loudness.sampleRate??Ug}`: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",...jr(n.audioBitrate),...n.loudness?.sampleRate?["-ar",String(n.loudness.sampleRate),"-ac","2"]:[],"-r",String(n.fps),...Ur],width:o.w,height:o.h}}function Jg(t,e,r,n="pad"){let{vf:o,af:i,encode:s}=ol(r,n);return["-y","-i",t,"-vf",o,...i?["-af",i]:[],...s,e]}var VE={inputs:ka.array(ka.string().min(1)).min(2).describe("Video paths to join, in order."),output:ka.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:ka.boolean().optional().describe("Replace an existing output (default false).")};function Yg(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:VE,outputSchema:Y,annotations:C},async(e,r)=>{try{k();let n=e.inputs.map(m=>JE(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=>nn(m)),c=a.every(m=>m!==null)?a.reduce((m,h)=>m+h,0):null,u=Dp(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=oi(n,a.map(w=>w??0),m,{transition:"cut",width:h(s.width),height:h(s.height),fps:s.fps??void 0},o.map(w=>w.audioCodec!==null));return await U(b,{output:m,durationSec:c,extra:r}),S({outputPath:m,inputCount:n.length,mode:"reencode",reason:u})}let d=XE(i)||".mp4",p=B(e.output,"concat",d,{overwrite:e.overwrite,anyContainer:!0}),f=Xe(".txt");YE(f,Np(n));try{await U(En(f,p),{output:p,durationSec:c,extra:r})}finally{KE(f,{force:!0})}return S({outputPath:p,inputCount:n.length,mode:"copy"})}catch(n){return E(n)}})}import{z as Kn}from"zod";var QE={input:Kn.string().min(1).describe("Path to the source media."),format:Kn.enum(["mp4","gif","webm"]).describe("mp4 (H.264), webm (VP9), or gif (palette)."),fps:Kn.number().positive().optional().describe("gif only: fps (default 12)."),width:Kn.number().positive().optional().describe("gif only: width in px (default 720)."),output:Kn.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:Kn.boolean().optional().describe("Replace an existing output (default false).")};function Kg(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:QE,outputSchema:Y,annotations:C},async(e,r)=>{try{k(),F(e.input);let n=e.format,o=B(e.output,"convert",`.${n}`,{overwrite:e.overwrite,anyContainer:!0}),i=Lp(e.input,o,n,{fps:e.fps,width:e.width});return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o,format:n})}catch(n){return E(n)}})}import{z as Jt}from"zod";var Ea=12,_a=960,Mr=1e7,Vg=5;function Qg(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 Zg(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 eb(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 ZE,dirname as e_,extname as t_,join as r_}from"node:path";import{renameSync as n_,rmSync as o_,statSync as i_}from"node:fs";async function Vn(t,e,r,n){let o=r.format??"gif",i=r.maxBytes??Mr,s=await ue(t),a=r.duration??(s!==null?s-(r.start??0):null),c=Qg(o,r.fps??Ea,r.width??_a),u=t_(e),d=f=>r_(e_(e),`${ZE(e,u)}.try${f}${u}`),p=[];try{let f=0;for(;f!==null&&p.length<Vg;){let b=c[f];if(!b)break;let w=d(p.length),g={start:r.start,duration:r.duration};await U(eb(t,w,o,b,g),{output:w,durationSec:a,extra:n});let y=i_(w).size;if(p.push({path:w,size:y,settings:b}),y<=i)break;f=Zg(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 n_(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)o_(f.path,{force:!0})}}var s_={input:Jt.string().min(1).describe("Source video path."),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 ${Mr}, under GitHub's 10 MB image limit).`),fps:Jt.number().positive().max(30).optional().describe(`Starting frame rate (default ${Ea}).`),width:Jt.number().int().min(64).max(1920).optional().describe(`Starting width in px (default ${_a}).`),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("Output path; default SCREENCAST_HOME/edits."),overwrite:Jt.boolean().optional().describe("Replace an existing output (default false).")};function tb(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:s_,outputSchema:Y,annotations:C},async(e,r)=>{try{k(),F(e.input);let n=e.format??"gif",o=e.maxBytes??Mr,i=B(e.output,"anim",`.${n}`,{overwrite:e.overwrite,anyContainer:!0});return S(await Vn(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 on}from"zod";var a_={input:on.string().min(1).describe("Source video path."),x:on.number().int().nonnegative(),y:on.number().int().nonnegative(),width:on.number().int().positive(),height:on.number().int().positive(),output:on.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:on.boolean().optional().describe("Replace an existing output (default false).")};function rb(t){t.registerTool("crop",{title:"Crop Video",description:"Crop a video to a pixel rectangle; one running off the frame is rejected.",inputSchema:a_,outputSchema:Y,annotations:C},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=Bp(e.input,a,{x:e.x,y:e.y,width:e.width,height:e.height},{width:n,height:o});return await U(c,{output:a,durationSec:i,extra:r}),S({outputPath:a})}catch(n){return E(n)}})}import{z as ii}from"zod";var c_={input:ii.string().min(1).describe("Source video path."),width:ii.number().int().positive().optional().describe("Target width in px. Omit to derive from height (keeps aspect)."),height:ii.number().int().positive().optional().describe("Target height in px. Omit to derive from width (keeps aspect)."),output:ii.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:ii.boolean().optional().describe("Replace an existing output (default false).")};function nb(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:c_,outputSchema:Y,annotations:C},async(e,r)=>{try{k(),F(e.input);let n=V(e.input),o=B(e.output,"scale",n,{overwrite:e.overwrite}),i=jp(e.input,o,{width:e.width,height:e.height});return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o})}catch(n){return E(n)}})}import{z as ui}from"zod";import{z as ct}from"zod";function It(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 It(e)}var an=2,ai=.4,Qn=200,u_={strict:-60,normal:-50,loose:-40},l_=["screen","events","both"],p_=ct.object({x:ct.number().nonnegative(),y:ct.number().nonnegative(),width:ct.number().positive(),height:ct.number().positive()}),d_=8,si={sensitivity:ct.enum(["strict","normal","loose"]).optional(),ignoreRegions:ct.array(p_).max(d_).optional(),basis:ct.enum(l_).optional()},ob={sensitivity:si.sensitivity.describe("Freeze tolerance: strict (default), normal, loose (a caret or spinner still counts as idle)."),ignoreRegions:si.ignoreRegions.describe("Rectangles (a clock) left out of the freeze check."),basis:si.basis.describe("screen (default), events (no input in .events.jsonl), or both.")};function ib(t,e,r,n={}){if(!(e>0))throw new l("minIdleSec must be positive.");let o=(n.ignoreRegions??[]).map(i=>`drawbox=x=${Math.round(i.x)}:y=${Math.round(i.y)}:w=${Math.round(i.width)}:h=${Math.round(i.height)}:color=black:t=fill`);return["-hide_banner","-nostats","-v","info","-i",t,"-vf",[...o,`freezedetect=n=${u_[n.sensitivity??"strict"]}dB:d=${e}`].join(","),...r?["-af",`silencedetect=n=-40dB:d=${e}`]:["-an"],"-f","null","-"]}function sb(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 ab(t,e){return sb(t,/freeze_start:\s*([\d.]+)/,/freeze_end:\s*([\d.]+)/,e)}function cb(t,e){return sb(t,/silence_start:\s*([\d.]+)/,/silence_end:\s*([\d.]+)/,e)}function ub(t,e,r){let n=t.filter(s=>s.type!=="move"&&s.type!=="focus").map(s=>({start:s.t,end:s.t+(s.durationSec??0)})).sort((s,a)=>s.start-a.start),o=[],i=0;for(let s of[...n,{start:e,end:e}]){let a=Math.min(s.start,e);a-i>=r&&o.push({start:i,end:a}),i=Math.max(i,s.end)}return o}function il(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 Ra(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 sl(t){if(t.length===0)throw new l("Nothing to cut.");if(t.length>Qn)throw new l(`Too many idle stretches (${t.length}); raise minIdleSec.`);let e=It(t.map(n=>`between(t,${n.start},${n.end})`)),r=It(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 sn=100,Ta=ct.object({start:ct.number().min(0),end:ct.number().positive(),factor:ct.number().gt(1).max(sn)}),ci=8;function Ma(t,e){if(t.length===0)throw new l("segments needs at least one range.");if(t.length>Qn)throw new l(`Too many ranges (${t.length}); at most ${Qn}.`);let r=[...t].sort((n,o)=>n.start-o.start).map(n=>({start:Number(n.start.toFixed(3)),end:Number(n.end.toFixed(3)),factor:n.factor}));return r.forEach((n,o)=>{if(!(n.end>n.start)||n.start<0)throw new l(`Range ${n.start}-${n.end}s: end must be after start, from 0.`);if(!(n.factor>1)||n.factor>sn)throw new l(`Range ${n.start}-${n.end}s: factor must be above 1 and at most ${sn} (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 cn(t){return t.reduce((e,r)=>e+(r.end-r.start)*(1-1/r.factor),0)}function Aa(t,e){if(t.length===0)throw new l("Nothing to speed up.");let r=s=>Number((1-1/s.factor).toFixed(6)),n=It(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=It(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 Ca(t,e,r,n){let o=Aa(r,n.fps);return["-y","-i",t,"-vf",o.video,...n.withAudio?["-af",o.audio]:["-an"],...ve({quality:n.quality??"standard",audio:n.withAudio?"aac":"omit"}),e]}function Pa(t,e,r,n,o="standard"){let i=sl(r);return["-y","-i",t,"-vf",i.video,...n?["-af",i.audio]:["-an"],...ve({quality:o,audio:n?"aac":"omit"}),e]}var m_={input:ui.string().min(1).describe("Source video path."),factor:ui.number().positive().optional().describe("Whole clip: >1 faster, <1 slower."),segments:ui.array(Ta).min(1).optional().describe("Or fast-forward just these ranges (audio shortened, not pitched)."),output:ui.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:ui.boolean().optional().describe("Replace an existing output (default false).")};function lb(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:m_,outputSchema:Y,annotations:C},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=Ma(e.segments,o),f=cn(p);return await U(Ca(e.input,a,p,{withAudio:c,fps:i}),{output:a,durationSec:o!==null?o-f:null,inputDurationSec:o,extra:r}),S({outputPath:a,segments:p,savedSec:Number(f.toFixed(2)),audio:c})}let u=e.factor,d=Up(e.input,a,u,c);return await U(d,{output:a,durationSec:o!==null?o/u:null,inputDurationSec:o,extra:r}),S({outputPath:a,factor:u,audio:c})}catch(n){return E(n)}})}import{z as yt}from"zod";var f_={input:yt.string().min(1).describe("Path to the base video."),overlay:yt.string().min(1).describe("Overlay image or video path."),x:yt.number().int().nonnegative().describe("Left, px."),y:yt.number().int().nonnegative().describe("Top, px."),width:yt.number().int().positive().optional().describe("Scale to this width (other side keeps aspect)."),height:yt.number().int().positive().optional().describe("Scale to this height."),start:yt.number().nonnegative().optional().describe("Show from this second."),end:yt.number().positive().optional().describe("Hide after this second."),shape:yt.enum(["rect","circle"]).optional().describe("circle: centre square masked round (webcam)."),output:yt.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:yt.boolean().optional().describe("Replace an existing output (default false).")};function pb(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:f_,outputSchema:Y,annotations:C},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=zp(e.input,e.overlay,o,{x:e.x,y:e.y,start:e.start,end:e.end,scale:i,shape:e.shape,durationSec:s});return await U(a,{output:o,durationSec:s,extra:r}),S({outputPath:o})}catch(n){return E(n)}})}import{z as ut}from"zod";import{mkdtempSync as w_,rmSync as y_,writeFileSync as x_}from"node:fs";import{tmpdir as S_}from"node:os";import{join as gb}from"node:path";var fb=["side_by_side","stack","grid"],Ia=2,Fa=9,db=3840,h_=1080,mb=t=>Math.max(2,Math.round(t/2)*2);function g_(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 b_(t,e){let r=Math.min(t.height,h_),n=t.width*r/t.height,o=Math.min(1,db/(n*e.cols),db/(r*e.rows));return n*=o,r*=o,{width:mb(n),height:mb(r)}}function al(t,e){let r=t.map(n=>Math.max(0,n.durationSec-n.skipSec));return e==="longest"?Math.max(...r):Math.min(...r)}function hb(t,e,r){let n=t.length;if(n<Ia||n>Fa)throw new l(`compose takes ${Ia} to ${Fa} inputs.`);let o=t[0],i=g_(r.layout,n),s=b_(o,i),a=al(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=${xe(m.label.fontFile)}:textfile=${xe(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),...ve({quality:r.quality??"standard",audio:f?"aac":"omit"}),e]}var v_={inputs:ut.array(ut.object({path:ut.string().min(1),label:ut.string().min(1).max(80).optional()})).min(Ia).max(Fa).describe('Videos in reading order, each with an optional label (e.g. "Before").'),layout:ut.enum(fb).optional().describe("side_by_side (default), stack, or grid."),alignMarker:ut.string().min(1).optional().describe("Line inputs up on this add_marker label."),endWith:ut.enum(["longest","shortest"]).optional().describe("longest (default; shorter ones hold their last frame) or shortest."),audio:ut.union([ut.number().int().min(0),ut.enum(["mix","none"])]).optional().describe('Input index whose audio to keep (default 0), "mix", or "none".'),output:ut.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:ut.boolean().optional().describe("Replace an existing output (default false).")};function bb(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:v_,outputSchema:Y,annotations:C},async(e,r)=>{let n=w_(gb(S_(),"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=He(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=Mt(m.label);g.warning&&i.push(g.warning);let y=gb(n,`label${f}.txt`);x_(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=hb(o,u,{layout:e.layout??"side_by_side",endWith:s,audio:a,fps:Math.min(60,Math.round(c))}),p=al(o,s);return await U(d,{output:u,durationSec:p,extra:r}),S({outputPath:u,durationSec:Number(p.toFixed(2)),layout:e.layout??"side_by_side",...e.alignMarker?{alignedOn:e.alignMarker,skipSec:o.map(f=>Number(f.skipSec.toFixed(3)))}:{},...i.length?{warnings:i}:{}})}catch(o){return E(o)}finally{y_(n,{recursive:!0,force:!0})}})}import{z as un}from"zod";import{existsSync as E_,mkdtempSync as __,readFileSync as R_,rmSync as T_,writeFileSync as M_}from"node:fs";import{tmpdir as A_}from"node:os";import{join as $b}from"node:path";var yb=["cpu","sysCpu","rssMB","sysMem"],xb=["top_left","top_right","bottom_left","bottom_right"],$_=120,cl={cpu:"App CPU %",sysCpu:"CPU %",rssMB:"App memory MB",sysMem:"Memory %"};function Sb(t,e,r,n=$_){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 k_(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 wb=t=>Math.max(2,Math.round(t/2)*2);function vb(t,e,r,n){let o=wb(n.width),i=wb(n.height);if(o>n.videoWidth||i>n.videoHeight)throw new l("The chart is larger than the video.");let s=k_(n.metric,r),a=Math.round(i*.25),c=i-a-4,u=o/r.length,d=r.flatMap((y,v)=>{if(y===null||y<=0)return[];let x=Math.max(1,Math.round(Math.min(y,s)/s*c)),T=n.metric!=="rssMB"&&n.metric!=="sysMem"&&y>=yu;return[`drawbox=x=${Math.floor(v*u)}:y=${i-2-x}:w=${Math.max(1,Math.ceil(u))}:h=${x}:color=${T?"0xFF5252":"0x4FC3F7"}@0.95:t=fill`]}),p=Number(n.durationSec.toFixed(3)),f=n.label?`,drawtext=fontfile=${xe(n.label.fontFile)}:textfile=${xe(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?",...ve({quality:n.quality??"standard",audio:n.hasAudio?"copy":"omit",faststart:!0}),e]}var C_={input:un.string().min(1).describe("A recording made with perf: true."),perf:un.string().optional().describe("Its .perf.jsonl (default: next to input)."),metric:un.enum(yb).optional().describe("Default cpu (the app's) if sampled, else sysCpu."),corner:un.enum(xb).optional().describe("Default top_right."),width:un.number().int().min(80).max(1920).optional().describe("Chart width px (default video/4)."),output:un.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:un.boolean().optional().describe("Replace an existing output (default false).")};function kb(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:C_,outputSchema:Y,annotations:C},async(e,r)=>{let n=__($b(A_(),"screencast-perf-"));try{k(),F(e.input);let o=e.perf??st(e.input);if(!E_(o))throw new l(`No performance track at ${o}.`,"Record with start_recording perf: true, or pass perf.");let i=Dn(R_(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=Sb(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=Mt(cl[a]),p=$b(n,"label.txt");M_(p,cl[a]);let f=B(e.output,"perf",V(e.input),{overwrite:e.overwrite}),m=vb(e.input,f,c,{metric:a,corner:e.corner??"top_right",width:u,height:Math.round(u*.4),videoWidth:s.width,videoHeight:s.height,durationSec:s.durationSec,label:{textFile:p,fontFile:d.fontFile},hasAudio:s.audioCodec!==null});return await U(m,{output:f,durationSec:s.durationSec,extra:r}),S({outputPath:f,metric:a,samples:i.length})}catch(o){return E(o)}finally{T_(n,{recursive:!0,force:!0})}})}import{z as Zn}from"zod";import{existsSync as P_,readFileSync as I_,writeFileSync as F_}from"node:fs";var ul=2e3,O_={input:Zn.string().min(1).describe("The .srt to translate (e.g. from transcribe)."),language:Zn.string().regex(/^[a-z]{3}$/).optional().describe('With translations: ISO 639-2 code, e.g. "spa".'),translations:Zn.array(Zn.string().max(sa)).max(ul).optional().describe("One translated string per cue, in order. Omit to get the cues to translate."),output:Zn.string().optional().describe("Default: <input>.<language>.srt."),overwrite:Zn.boolean().optional().describe("Allow replacing an existing output file.")};function Eb(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:O_,annotations:C},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=qe(I_(e.input,"utf8"));if(r.length===0)throw new l(`No cues in ${e.input}.`);if(r.length>ul)throw new l(`${r.length} cues; at most ${ul} per file.`);if(!e.translations)return S({input:e.input,count:r.length,cues:r.map((i,s)=>`${s+1}. ${i.text.replace(/\s*\n\s*/g," / ")}`),next:`Translate each cue's text (keep " / " as a line break), then call again with language and translations: ${r.length} strings, in order.`});if(!e.language)throw new l('translations needs language (ISO 639-2, e.g. "spa").');let n=Yh(r,e.translations.map(i=>i.replace(/\s+\/\s+/g,`
|
|
339
|
+
`))),o=e.output??Kh(e.input,e.language);if(!/\.srt$/i.test(o))throw new l("output must end in .srt.");if(sr(o),P_(o)){if(!e.overwrite)throw new l(`${o} already exists.`,"Pass overwrite: true to replace it.");Ec(o)}return F_(o,at(n)),S({outputPath:o,language:e.language,count:n.length})}catch(r){return E(r)}})}import{z as Da}from"zod";import{join as D_}from"node:path";import{mkdtempSync as L_,rmSync as B_}from"node:fs";import{tmpdir as W_}from"node:os";import{z as Se}from"zod";var eo=(t,e)=>{if(!Number.isFinite(t)||t<0)throw new l(`${e} must be a non-negative number.`);return Math.round(t)};function ll(t){let e=zi(t.from,t.to);return e?`:enable='${e}'`:""}function _b(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 Rb(t,e){let{length:r,thickness:n,angle:o}=_b(t),i=Ue(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",..._e(e)]}function dl(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=Ue(c.color??"red"),f=c.fill?"fill":String(Math.max(1,Math.round(c.thickness??4)));s.push(`${a}drawbox=x=${eo(c.x,"x")}:y=${eo(c.y,"y")}:w=${eo(c.width,"width")}:h=${eo(c.height,"height")}:color=${p}:t=${f}${ll(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=Ue(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=${xe(e.fontFiles?.[u]??e.fontFile)}:textfile=${xe(p)}:expansion=none:x=${eo(c.x,"x")}:y=${eo(c.y,"y")}:fontsize=${m}:fontcolor=${f}${h}${ll(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}=_b(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${ll(c)}${d}`)}a=d}),{steps:s,out:a,extraInputs:i}}function Tb(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}=dl(s,n,"[0:v]",1,"");return i?["-y","-i",t,...u,"-filter_complex",a.join(";"),"-map",c,"-frames:v","1",..._e(e)]:["-y","-i",t,...u,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Me(o),"-c:a","copy",e]}var pl={from:Se.number().nonnegative().optional(),to:Se.number().positive().optional(),color:Se.string().optional()},Ar=Se.string().min(1).optional().describe("Font: .ttf/.otf/.ttc path or C:\\Windows\\Fonts name. Default: bundled Inter, plus a system font for CJK, emoji, Arabic."),Oa=Se.discriminatedUnion("type",[Se.object({type:Se.literal("box"),x:Se.number(),y:Se.number(),width:Se.number().positive(),height:Se.number().positive(),thickness:Se.number().positive().optional().describe("Outline px (default 4)."),fill:Se.boolean().optional().describe("Fill instead of outline."),...pl}),Se.object({type:Se.literal("text"),x:Se.number(),y:Se.number(),text:Se.string().min(1),size:Se.number().positive().optional().describe("Font size px (default 32)."),background:Se.boolean().optional().describe("Dark panel behind the text (default true)."),...pl}),Se.object({type:Se.literal("arrow"),x1:Se.number(),y1:Se.number(),x2:Se.number().describe("Head (x2,y2) is the point the arrow points at."),y2:Se.number(),thickness:Se.number().positive().optional().describe("Shaft px (default 8)."),...pl})]);import{join as Mb}from"node:path";import{writeFileSync as N_}from"node:fs";function ml(t,e){let r={fontFiles:[],fallbackFonts:[],warnings:[]};return t.forEach((n,o)=>{if(n.type!=="text"){r.fontFiles.push(null);return}let i=Mt(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 Na(t,e,r="",n){let o=ml(t,n),i=t.map((a,c)=>{if(a.type!=="text")return null;let u=Mb(e,`${r}text_${c}.txt`);return N_(u,a.text),u}),s=[];for(let[a,c]of t.entries()){if(c.type!=="arrow"){s.push(null);continue}let u=Mb(e,`${r}arrow_${a}.png`);await te(Rb(c,u),3e4),s.push(u)}return{fontFile:Gt("bold"),textFiles:i,arrowFiles:s,...o}}var j_={input:Da.string().min(1).describe("Path to the source video or image (png/jpg; from/to are ignored for an image)."),items:Da.array(Oa).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:Ar,output:Da.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:Da.boolean().optional().describe("Replace an existing output (default false).")};function Ab(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:j_,outputSchema:Y,annotations:C},async(e,r)=>{try{k(),F(e.input);let n=e.items,{still:o,ext:i}=Gi(e.input,e.output),s=B(e.output,"callout",i,{overwrite:e.overwrite,anyContainer:!0}),a=L_(D_(W_(),"screencast-callout-"));try{let c=await Na(n,a,"",e.fontFile),u=Tb(e.input,s,n,c,void 0,o);return await U(u,{output:s,durationSec:o?null:await ue(e.input),extra:r}),S({outputPath:s,callouts:n.length,...c.fallbackFonts.length>0&&{fallbackFonts:c.fallbackFonts},...c.warnings.length>0&&{warnings:c.warnings}})}finally{B_(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as pi}from"zod";import{join as tR}from"node:path";import{mkdtempSync as rR,rmSync as nR}from"node:fs";import{tmpdir as oR}from"node:os";import{z as Yt}from"zod";import{existsSync as U_,readFileSync as z_,writeFileSync as H_}from"node:fs";import{join as G_}from"node:path";var q_=["bottom","bottom-left","bottom-right","top","top-left","top-right"],fl=1.2,X_=.5,Cb=8,Pb=100,Ib="Typing\u2026",J_=new Set(["Ctrl","Alt","Shift","Win"]),Y_=/^(?:[A-Z0-9]|F\d{1,2}|Enter|Tab|Esc|Space|Backspace|Delete|Insert|Left|Up|Right|Down|Home|End|PageUp|PageDown|[=\-,./`[\];'\\])$/;function K_(t,e="shortcuts"){let r=t.split("+"),n=r.pop();return n===void 0||r.length===0||!Y_.test(n)||!r.every(o=>J_.has(o))||new Set(r).size!==r.length?null:[...r,e==="masked"?"\u2026":n].join(" + ")}var V_={left:"Click",right:"Right click",middle:"Middle click",x1:"Back button",x2:"Forward button"},La=t=>Math.round(t*1e3)/1e3;function Q_(t,e={}){let r=e.lingerSec??fl;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=K_(a.keys,n);if(!c)continue;let u=i.at(-1);if(u&&u.kind==="shortcut"&&u.base===c&&a.t-u.last<=r){u.count++,u.last=a.t,u.label=`${c} \xD7${u.count}`,u.to=a.t+r;continue}i.push({from:a.t,to:a.t+r,label:c,base:c,kind:"shortcut",count:1,last:a.t})}else if(a.type==="down"&&e.clicks!==!1&&a.inFrame){let c=V_[a.button??"left"]??"Click",u=i.at(-1);if(c==="Click"&&u&&u.kind==="click"&&u.base==="Click"&&u.count<3&&a.t-u.last<=X_&&Math.abs(a.x-(u.x??a.x))<=Cb&&Math.abs(a.y-(u.y??a.y))<=Cb){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:Ib,base:Ib,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:La(a.from),to:La(d),label:a.label,kind:a.kind})}),s}function Ba(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>Pb)throw new l(`${e.size} different badges is more than ${Pb}; trim the video or turn off keys or clicks.`);return[...e.values()]}function Z_(t,e){return t.flatMap(r=>{let n=e(r.from,r.to);return n&&n[1]-n[0]>=.05?[{...r,from:La(n[0]),to:La(n[1])}]:[]})}function Fb(t,e){return Z_(t,(r,n)=>Vr(r,n,e))}function eR(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 hl(t,e,r,n,o,i){if(t.length===0)throw new l("No badges to draw.");let s=eR(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=Ue(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=It(b.windows.map(([x,T])=>`between(t,${x},${T})`)),v=`[${i}k${w}]`;m.push(`${h}drawtext=fontfile=${xe(e.fontFile)}:textfile=${xe(g)}:expansion=none:fontsize=${s}:fontcolor=${f}:box=1:boxcolor=black@0.6:boxborderw=${a}:x=${d}:y=${p}:enable='${y}'${v}`),h=v}),{steps:m,out:h}}function Ob(t,e,r,n,o,i,s="standard"){let{steps:a,out:c}=hl(r,n,o,i,"[0:v]","");return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Me(s),"-c:a","copy",e]}var Wa={events:Yt.string().optional(),clicks:Yt.boolean().optional(),typing:Yt.boolean().optional(),keys:Yt.enum(["shortcuts","masked"]).optional(),lingerSec:Yt.number().positive().max(10).optional(),position:Yt.enum(q_).optional(),size:Yt.number().min(8).max(400).optional(),color:Yt.string().optional(),fontFile:Yt.string().min(1).optional()};function ja(t,e,r){let n=e??he(t).jsonl;if(!U_(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=Ie(z_(n,"utf8"));return{badges:Q_(o,r),shortcutsLogged:o.filter(i=>i.type==="key").length,path:n}}function li(t,e,r="",n){let o=Mt(t.join(" "),{weight:"bold",fontFile:n}),i={};return t.forEach((s,a)=>{if(e===null){i[s]=`<badge ${a}>`;return}let c=G_(e,`${r}badge_${a}.txt`);H_(c,s),i[s]=c}),{fontFile:o.fontFile,textFiles:i,...o.fallback&&{fallbackFont:o.fontFile},warnings:o.warning?[o.warning]:[]}}var Cr=Wa,iR={input:pi.string().min(1).describe("Path to the recording."),events:Cr.events.describe("Event log (default: the input's .events.jsonl)."),clicks:Cr.clicks.describe("Show clicks (default true)."),typing:Cr.typing.describe('Show typing as "Typing\u2026" (default true).'),keys:Cr.keys.describe("shortcuts (default): the chord (Ctrl + S); masked: modifiers only (Ctrl + \u2026)."),lingerSec:Cr.lingerSec.describe(`Seconds a badge stays up (default ${fl}).`),position:Cr.position.describe("Default bottom (centred)."),size:Cr.size.describe("Font px (default 4.5% of the frame height)."),color:Cr.color.describe("Text color (default white)."),fontFile:Ar,dryRun:pi.boolean().optional().describe("Return the planned badges; write nothing."),output:pi.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:pi.boolean().optional().describe("Replace an existing output (default false).")};function Nb(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:iR,outputSchema:N({badges:pi.number().int()}),annotations:C},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}=ja(e.input,e.events,n),s=i===0?'The log names no shortcuts (recorded with keys: "masked"), so only clicks and typing can show.':void 0;if(o.length===0)return S({badges:0,note:"Nothing to show: the log has no clicks, shortcuts, or typing; nothing written."});let a=Ba(o);if(e.dryRun){let p=li(a.map(f=>f.label),null,"",e.fontFile);return S({dryRun:!0,badges:o.length,plan:o,...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}let c=await 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=rR(tR(oR(),"screencast-keys-"));try{let p=li(a.map(h=>h.label),d,"",e.fontFile),f={position:e.position,size:e.size,color:e.color},m=Ob(e.input,u,a,p,f,{height:c.height});return await U(m,{output:u,durationSec:c.durationSec,extra:r}),S({outputPath:u,badges:o.length,labels:a.map(h=>h.label),...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}finally{nR(d,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as mi}from"zod";import{join as jb}from"node:path";import{mkdtempSync as kR,rmSync as ER,writeFileSync as _R}from"node:fs";import{tmpdir as RR}from"node:os";import{z as to}from"zod";import{existsSync as sR,readFileSync as aR}from"node:fs";var di={w:114,h:168,hotX:9,hotY:9,arrowH:135};function Ua(){return Pn("cursor","arrow.png")}var cR=.5,gl=2,bl=1.5,uR=.4,Db=240,lR=4,pR=.35,dR=new Set(["move","down","up","wheel"]),ro=t=>Math.round(t*1e3)/1e3;function mR(t){let e=6+(1-t)*34;return{omega:e,lead:Math.min(2/e,.2)}}function fR(t){let e=[],r=vc/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 hR(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 gR(t,e,r,n,o){if(t.length===0)return[];let i=1/Db,s=0,a=w=>{let g=hR(t,w+r,s);return s=g.i,g},c=a(n),u=c.x,d=c.y,p=0,f=0,m=[{t:ro(n),x:u,y:d}],h=Math.exp(-e*i),b=Math.max(0,Math.ceil((o-n)*Db));for(let w=1;w<=b;w++){let g=Math.min(o,n+w*i),y=a(g),v=u-y.x,x=d-y.y,T=(p+e*v)*i,R=(f+e*x)*i;p=(p-e*T)*h,f=(f-e*R)*h,u=y.x+(v+T)*h,d=y.y+(x+R)*h,(w%lR===0||w===b)&&m.push({t:ro(g),x:u,y:d})}return m}function bR(t,e=pR){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 wR(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 yR(t,e={},r=null){let n=e.smoothing??cR;if(!(n>=0&&n<=1))throw new l("smoothing must be between 0 and 1.");let o=e.hideAfterSec??gl;if(!(o>=0))throw new l("hideAfterSec must be 0 or more.");let i=t.filter(h=>dR.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=fR(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=mR(n);d=h.lead;let b=Math.max(0,a-d),w=Math.max(b,r??c+8/h.omega);u=gR(s,h.omega,d,b,w)}let p=Math.max(0,a-d),f=o===0?[[p,r??1/0]]:wR(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])=>[ro(h),r!==null?Math.min(b,r):b]).filter(([h,b])=>b>h),clicks:m}}var xR={sx:1,sy:1,ox:0,oy:0};function za(t,e=[],r=xR){let n=a=>{let c=br(a.t,e);return c===null?null:{t:ro(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=Vr(a,c,e);return u&&u[1]-u[0]>=.05?[[ro(u[0]),Number.isFinite(u[1])?ro(u[1]):u[1]]]:[]}),s=t.clicks.flatMap(a=>{let c=n(a);return c?[c]:[]});return{path:bR(o),visible:i,clicks:s}}var Oe=(t,e=2)=>{let r=Number(t.toFixed(e));return Object.is(r,-0)?"0":String(r)};function Lb(t,e,r){let n=Number(r.toFixed(3));return n===0?Oe(t):`${Oe(t)}${n<0?"-":"+"}(t-${Oe(e,3)})*${Oe(Math.abs(n),3)}`}function SR(t,e=bl){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/di.arrowH,o=Math.max(12,Math.round(r*2.2));return{spriteW:Math.max(2,Math.round(di.w*n)),spriteH:Math.max(2,Math.round(di.h*n)),hotX:di.hotX*n,hotY:di.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 vR(t){let e=new Map;for(let r of[...t].sort((n,o)=>n.t-o.t)){let n=Oe(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(`
|
|
340
340
|
`)+`
|
|
341
|
-
`}function yb(t,e,r,n){return t.map((o,i)=>{let s=t[i+1],a=s?s.t-o.t:0,c=s&&a>0?(s.x-o.x)/a:0,u=s&&a>0?(s.y-o.y)/a:0;return{t:o.t,text:`${e} x ${wb(o.x+r,o.t,c)}, ${e} y ${wb(o.y+n,o.t,u)}`}})}function J_(t,e){return t.flatMap(([r,n])=>[{t:r,text:`${e} enable 1`},...Number.isFinite(n)?[{t:n,text:`${e} enable 0`}]:[]])}function pl(t,e,r,n,o,i,s,a){if(t.path.length===0)throw new l("No cursor positions to draw.");let c=q_(r.height,e.size),{width:u,height:d}=r,p=g=>`overlay@${i}c${g}`,f=[],m=[],h=t.path[0],b=`[${i}cm]`;f.push(`${n}sendcmd=f=${ye(a)}${b}`);let w=(g,y,v,x,R)=>{let T=`[${i}c${y}o]`;f.push(`${b}${g}${p(y)}=x=${Ie(h.x+v)}:y=${Ie(h.y+x)}:enable=0${T}`),m.push(...J_(R,p(y))),b=T};if(e.spotlight){let y=Math.ceil(2*u/4),v=Math.ceil(2*d/4),x=c.spotRadius/4,R=x*.8,T=`255*0.55*clip((hypot(X-${Ie(y/2)},Y-${Ie(v/2)})-${Ie(x)})/${Ie(R)},0,1)`;f.push(`color=c=black:s=${y}x${v}:r=1:d=1,format=rgba,geq=r=0:g=0:b=0:a='${T}',scale=${2*u}:${2*d}[${i}csm]`);let M=c.spriteW*.25-u,H=c.spriteH*.3-d;w(`[${i}csm]`,"s",M,H,t.visible),m.push(...yb(t.path,p("s"),M,H))}if(e.clicks!==!1&&t.clicks.length>0){let g=F_/3;c.ripples.forEach((y,v)=>{let x=y/2,R=Math.max(1.5,y*.05),T=`abs(hypot(X-${Ie(x-.5)},Y-${Ie(x-.5)})-${Ie(x-R-1)})`,M=[.9,.65,.4][v],H=`255*lt(${T},${Ie(R*.45)})`;f.push(`color=c=black:s=${y}x${y}:r=1:d=1,format=rgba,geq=r='${H}':g='${H}':b='${H}':a='255*${M}*clip(${Ie(R)}-${T},0,1)'[${i}cr${v}]`);let G=t.clicks.map(L=>[L.t+v*g,L.t+(v+1)*g]);w(`[${i}cr${v}]`,`r${v}`,-x,-x,[]);for(let[L,C]of t.clicks.entries()){let[ne,V]=G[L],Y=G[L+1];m.push({t:ne,text:`${p(`r${v}`)} x ${Ie(C.x-x)}, ${p(`r${v}`)} y ${Ie(C.y-x)}, ${p(`r${v}`)} enable 1`}),(!Y||Y[0]>=V)&&m.push({t:V,text:`${p(`r${v}`)} enable 0`})}})}return f.push(`[${o}:v]scale=${c.spriteW}:${c.spriteH}:flags=lanczos,format=rgba[${i}csp]`),w(`[${i}csp]`,"p",-c.hotX,-c.hotY,t.visible),m.push(...yb(t.path,p("p"),-c.hotX,-c.hotY)),{steps:f,out:b,extraInputs:["-i",s],commands:X_(m)}}function xb(t,e,r,n,o,i,s,a="standard"){let{steps:c,out:u,extraInputs:d,commands:p}=pl(r,n,o,"[0:v]",1,"",i,s);return{args:["-y","-i",t,...d,"-filter_complex",c.join(";"),"-map",u,"-map","0:a?",...Re(a),"-c:a","copy",e],commands:p}}var La={events:Yn.string().optional(),size:Yn.number().min(.25).max(8).optional(),smoothing:Yn.number().min(0).max(1).optional(),hideAfterSec:Yn.number().min(0).max(600).optional(),clicks:Yn.boolean().optional(),spotlight:Yn.boolean().optional()};function Ba(t,e,r,n){let o=e??ke(t).jsonl;if(!C_(o))throw new l(`No event log for ${t} (looked for ${o}). Record with start_recording cursor: "events" (no OS cursor in the video, events logged), or pass events: <path to .events.jsonl>.`);let i=H_(ze(P_(o,"utf8")),r,n);if(i.path.length===0)throw new l(`The event log ${o} has no cursor positions to draw.`);return i}var Vn=La,Z_={input:ni.string().min(1).describe("Path to the recording."),events:Vn.events.describe("Event log (default: the input's .events.jsonl)."),size:Vn.size.describe(`Times a typical cursor's size (default ${ll}).`),smoothing:Vn.smoothing.describe("0 = as logged, 1 = floaty (default 0.5)."),hideAfterSec:Vn.hideAfterSec.describe(`Hide when the mouse rests this long; 0 = never (default ${ul}).`),clicks:Vn.clicks.describe("Ripple on clicks (default true)."),spotlight:Vn.spotlight.describe("Dim all but the area around the cursor."),dryRun:ni.boolean().optional().describe("Return the plan; write nothing."),output:ni.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ni.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function vb(t){t.registerTool("cursor",{title:"Re-rendered Cursor",description:'Draw a smoothed, scaled cursor that hides when idle from the event log of a start_recording cursor: "events" recording (no OS cursor in the video), with click ripples and an optional spotlight.',inputSchema:Z_,outputSchema:B({segments:ni.number().int()}),annotations:I},async(e,r)=>{try{k(),O(e.input);let n=await W(e.input);if(!n.width||!n.height)throw new l(`Could not read the size of ${e.input}.`);let o=Da(Ba(e.input,e.events,e,n.durationSec)),i={segments:o.path.length,clicks:o.clicks.length,shownSec:Math.round(o.visible.reduce((c,[u,d])=>c+(Math.min(d,n.durationSec??d)-u),0)*10)/10};if(e.dryRun)return S({dryRun:!0,...i,visible:o.visible});let s=j(e.output,"cursor",Z(e.input),{overwrite:e.overwrite}),a=Y_(Sb(Q_(),"screencast-cursor-"));try{let c=Sb(a,"cursor.cmd"),{args:u,commands:d}=xb(e.input,s,o,{size:e.size,clicks:e.clicks,spotlight:e.spotlight},{width:n.width,height:n.height},Na(),c);return V_(c,d),await U(u,{output:s,durationSec:n.durationSec,extra:r}),S({outputPath:s,...i})}finally{K_(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as Qn}from"zod";import{existsSync as iT}from"node:fs";import{extname as sT}from"node:path";import{z as Xt}from"zod";var Eb={desktop:["#1B2330","#0A0D12"],rec:["#FF4545","#5C0F1A"],amber:["#FFB454","#FF4545"],light:["#F4F7FA","#B9C4D0"]},eT=Object.keys(Eb),tT="desktop",ml=4,rT=.5,$b=t=>2*Math.round(t/2),Wa=t=>2*Math.floor(t/2);function dl(t,e,r){if(t!==void 0){if(!Number.isFinite(t)||t<0||t>r)throw new l(`${e} must be between 0 and ${r}.`);return Math.round(t)}}function nT(t,e,r={}){if(!(t>0&&e>0))throw new l("The input has no frame size.");let n=dl(r.padding,"padding",2e3),o=dl(r.radius,"radius",1e3),i=dl(r.shadow,"shadow",200),s,a,c=t,u=e,d,p,f,m=!1;if(r.aspect){let v=zn[r.aspect];if(!v)throw new l(`Unknown aspect "${r.aspect}".`);s=v.w,a=v.h,f=$b(n??Math.max(s,a)*.06);let x=s-2*f,R=a-2*f;if(x<16||R<16)throw new l(`padding ${f} leaves no room on a ${r.aspect} canvas.`);let T=Math.min(x/t,R/e);c=Math.max(2,Wa(t*T)),u=Math.max(2,Wa(e*T)),m=c!==t||u!==e,d=Wa((s-c)/2),p=Wa((a-u)/2)}else f=$b(n??Math.max(t,e)*.06),s=t+2*f+t%2,a=e+2*f+e%2,d=f,p=f;let h=Math.max(c,u),b=Math.min(o??Math.round(h*.012),Math.floor(Math.min(c,u)/2)),w=i??Math.round(h*.025),g=a-p-u,y=w>0?Math.max(0,Math.min(Math.round(w/2),g)):0;return{canvasW:s,canvasH:a,contentW:c,contentH:u,x:d,y:p,padding:f,radius:b,shadow:w,shadowOffset:y,scaled:m}}function oT(t){if(t.colors!==void 0){if(t.colors.length<1||t.colors.length>ml)throw new l(`colors takes 1 to ${ml} colors.`);return t.colors.map((n,o)=>Be(n,`colors[${o}]`))}let e=t.preset??tT,r=Eb[e];if(!r)throw new l(`Unknown backdrop preset "${e}".`);return[...r]}function kb(t,e=!1){let r=t,n=`max(max(${r}-X-0.5,X+0.5-(W-${r})),0)`,o=`max(max(${r}-Y-0.5,Y+0.5-(H-${r})),0)`,i=`clip(${r}+0.5-hypot(${n},${o}),0,1)`;return e?`255-255*${i}`:`255*${i}`}function fl(t,e,r,n,o,i=!1){let s=nT(e.width,e.height,t);if(t.shadowOpacity!==void 0&&!(t.shadowOpacity>=0&&t.shadowOpacity<=1))throw new l("shadowOpacity must be between 0 and 1.");let a=t.shadowOpacity??rT,{canvasW:c,canvasH:u,contentW:d,contentH:p,x:f,y:m}=s,h=":r=1:d=1",b=[],w=[],g=`[${o}bg]`;if(t.image)w.push("-i",t.image),b.push(`[${n}:v]scale=${c}:${u}:force_original_aspect_ratio=increase,crop=${c}:${u},setsar=1,trim=end_frame=1,format=rgba${g}`);else{let G=oT(t);if(G.length===1)b.push(`color=c=${G[0]}:s=${c}x${u}${h},format=rgba${g}`);else{let L=G.map((C,ne)=>`c${ne}=${C}`).join(":");b.push(`gradients=s=${c}x${u}:${L}:n=${G.length}:x0=0:y0=0:x1=${c}:y1=${u}:r=1,trim=end_frame=1,format=rgba${g}`)}}let y=g;if(s.shadow>0&&a>0){let G=`[${o}sa]`,L=`[${o}sc]`,C=`[${o}sh]`,ne=`[${o}bs]`,V=s.radius>0?`format=gray,geq=lum='${kb(s.radius)}'`:"format=gray";b.push(`color=c=white:s=${d}x${p}${h},${V},pad=${c}:${u}:${f}:${m+s.shadowOffset}:color=black,gblur=sigma=${(s.shadow/2).toFixed(2)}${G}`),b.push(`color=c=black:s=${c}x${u}${h}${L}`),b.push(`${L}${G}alphamerge,format=rgba,colorchannelmixer=aa=${a}${C}`),b.push(`${y}${C}overlay=0:0:format=rgb${ne}`),y=ne}let v=`[${o}hole]`,x=`[${o}frame]`,R=s.radius>0?`format=gray,geq=lum='${kb(s.radius,!0)}'`:"format=gray";b.push(`color=c=black:s=${d}x${p}${h},${R},pad=${c}:${u}:${f}:${m}:color=white${v}`),b.push(`${y}${v}alphamerge,format=rgba${x}`);let T=`[${o}pad]`,M=`[${o}bd]`,H=s.scaled?`scale=${d}:${p},setsar=1,`:"";return b.push(`${r}${H}pad=${c}:${u}:${f}:${m}:color=black${T}`),b.push(`${T}${x}overlay=0:0${i?":format=rgb":""}${M}`),{steps:b,out:M,extraInputs:w,layout:s}}function _b(t,e,r,n,o=!1,i="standard"){let{steps:s,out:a,extraInputs:c,layout:u}=fl(r,n,"[0:v]",1,"",o),d="[vout]";s.push(`${a}format=${o?"rgb24":"yuv420p"}${d}`);let p=["-y","-i",t,...c,"-filter_complex",s.join(";"),"-map",d];return{args:o?[...p,"-frames:v","1",...Te(e)]:[...p,"-map","0:a?",...Re(i),"-c:a","copy","-movflags","+faststart",e],layout:u}}var ja={preset:Xt.enum(eT).optional(),colors:Xt.array(Xt.string()).min(1).max(ml).optional(),image:Xt.string().min(1).optional(),padding:Xt.number().int().nonnegative().max(2e3).optional(),radius:Xt.number().int().nonnegative().max(1e3).optional(),shadow:Xt.number().int().nonnegative().max(200).optional(),shadowOpacity:Xt.number().min(0).max(1).optional(),aspect:Xt.enum(Un).optional()};var Tb=/\.(png|jpe?g|bmp|tiff?|webp)$/i,Rr=ja,aT={input:Qn.string().min(1).describe("Path to the source video or image (png/jpg)."),preset:Rr.preset.describe("Gradient: desktop (default, dark slate), rec (red), amber, light."),colors:Rr.colors.describe("Instead: 1 color = solid, 2-4 = diagonal gradient."),image:Rr.image.describe("Instead: a wallpaper image, scaled to cover."),padding:Rr.padding.describe("px around the content (default 6% of the longer side)."),radius:Rr.radius.describe("Corner radius px (default ~1.2% of the longer side; 0 = square)."),shadow:Rr.shadow.describe("Shadow blur px (default ~2.5%; 0 = none)."),shadowOpacity:Rr.shadowOpacity.describe("Default 0.5."),aspect:Rr.aspect.describe("Output on this aspect's canvas (1920x1080, ...), content scaled to fit."),output:Qn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits (screenshots for an image)."),overwrite:Qn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Rb(t){t.registerTool("backdrop",{title:"Add Backdrop",description:"Frame a video or screenshot on a gradient, color, or wallpaper with padding, rounded corners, and a drop shadow, optionally on a 16:9/1:1/9:16/4:5 canvas.",inputSchema:aT,outputSchema:B({outputPath:Qn.string(),width:Qn.number().int(),height:Qn.number().int()}),annotations:I},async(e,r)=>{try{if(k(),O(e.input),e.image&&!iT(e.image))throw new l(`Background image not found: ${e.image}`);let n=Tb.test(e.input);if(n&&e.output&&!Tb.test(e.output))throw new l("An image input writes an image: give the output a .png or .jpg extension.");n||jr(e.output);let o=await W(e.input);if(!o.width||!o.height)throw new l(`Could not read the size of ${e.input}.`);let i=n?/\.jpe?g$/i.test(e.input)?sT(e.input).toLowerCase():".png":Z(e.input),s=nr(e.output,we(n?"screenshots":"edits"),`backdrop-${he()}-${ge()}${i}`,e.overwrite),a={preset:e.preset,colors:e.colors,image:e.image,padding:e.padding,radius:e.radius,shadow:e.shadow,shadowOpacity:e.shadowOpacity,aspect:e.aspect},{args:c,layout:u}=_b(e.input,s,a,{width:o.width,height:o.height},n);return await U(c,{output:s,durationSec:n?null:o.durationSec,extra:r}),S({outputPath:s,width:u.canvasW,height:u.canvasH,content:{x:u.x,y:u.y,width:u.contentW,height:u.contentH},padding:u.padding,radius:u.radius,shadow:u.shadow,background:e.image?"image":e.colors?"colors":e.preset??"desktop"})}catch(n){return E(n)}})}import{z as oi}from"zod";var cT={input:oi.string().min(1).describe("Path to the source video."),level:oi.enum(["light","medium","heavy"]).optional().describe("CRF 23 / 28 / 32 (default medium)."),maxWidth:oi.number().int().positive().optional().describe("Width cap in px (only downscales)."),output:oi.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:oi.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ab(t){t.registerTool("compress",{title:"Compress Video",description:"Re-encode a video smaller (H.264 CRF ladder, optional width cap). For a platform target use export_preset.",inputSchema:cT,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=Z(e.input),o=j(e.output,"compress",n,{overwrite:e.overwrite}),i=Dp(e.input,o,{level:e.level,maxWidth:e.maxWidth});return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o,level:e.level??"medium"})}catch(n){return E(n)}})}import{z as Ua}from"zod";var uT={mp3:"mp3",aac:"m4a",wav:"wav"},lT={input:Ua.string().min(1).describe("Path to the source media."),format:Ua.enum(["mp3","aac","wav","copy"]).describe("Audio output codec. copy keeps the source codec without re-encoding."),output:Ua.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ua.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Mb(t){t.registerTool("extract_audio",{title:"Extract Audio",description:"Extract the audio track of a media file to its own file (mp3, aac, wav, or copy). Returns the output path.",inputSchema:lT,outputSchema:K,annotations:I},async(e,r)=>{try{let{ffprobe:n}=k();O(e.input);let o=e.format,i=null,s;if(o==="copy"){let c=await se(n,Wr(e.input),3e4,{signal:r.signal});if(c.code!==0)throw new l(`ffprobe failed (exit ${c.code}): ${c.stderr.trim().slice(-400)}`);if(i=Br(JSON.parse(c.stdout)).audioCodec,!i)throw new l(`Input has no audio stream to extract: ${e.input}`);s=Lp(i)}else s=uT[o];let a=j(e.output,"audio",`.${s}`,{overwrite:e.overwrite,anyContainer:!0});return await U(Bp(e.input,a,o),{output:a,durationSec:await ue(e.input),extra:r}),S({outputPath:a,format:o,...i?{sourceAudioCodec:i}:{}})}catch(n){return E(n)}})}import{z as yl}from"zod";import{extname as pT}from"node:path";import{z as hl}from"zod";var dT=["youtube","podcast","broadcast"],za=hl.union([hl.enum(dT),hl.number().min(-70).max(-5)]),Cb={youtube:{i:-14,tp:-1,lra:11},podcast:{i:-16,tp:-1.5,lra:11},broadcast:{i:-23,tp:-1,lra:7}};function Zn(t){if(t===void 0)return Cb.youtube;if(typeof t=="number"){if(!Number.isFinite(t)||t<-70||t>-5)throw new l("target LUFS must be between -70 and -5 (e.g. -14).");return{i:t,tp:-1,lra:11}}let e=Cb[t];if(!e)throw new l(`Unknown loudness target "${t}".`);return e}var gl=t=>`I=${t.i}:TP=${t.tp}:LRA=${t.lra}`;function ii(t,e){return["-hide_banner","-nostats","-i",t,"-vn","-af",`loudnorm=${gl(e)}:print_format=json`,"-f","null","-"]}function si(t){let r=t.match(/\{[^{}]*"input_i"[^{}]*\}/g)?.at(-1);if(r===void 0)throw new l("Could not measure loudness (no loudnorm report). Does the file have audio?");let n=JSON.parse(r),o=s=>Number(n[s]),i={input_i:o("input_i"),input_tp:o("input_tp"),input_lra:o("input_lra"),input_thresh:o("input_thresh"),target_offset:o("target_offset"),...n.output_i!==void 0?{output_i:o("output_i")}:{}};if(!Number.isFinite(i.input_i))throw new l("The audio is silent (loudness is -inf), so there is nothing to normalize.");return i}function Pb(t){return Ii(t)?["-map","0:a:0","-vn"]:["-map","0:v?","-map","0:a:0","-c:v","copy"]}function Ha(t){switch(pT(t).toLowerCase()){case".wav":return["-c:a","pcm_s16le"];case".mp3":return["-c:a","libmp3lame","-b:a","192k"];default:return["-c:a","aac","-b:a","192k"]}}function bl(t,e){if(!e)return`loudnorm=${gl(t)}`;let r=`measured_I=${e.input_i}:measured_TP=${e.input_tp}:measured_LRA=${e.input_lra}:measured_thresh=${e.input_thresh}:offset=${e.target_offset}`;return`loudnorm=${gl(t)}:${r}:linear=true`}function Ib(t,e,r,n){return["-y","-hide_banner","-i",t,...Pb(e),"-af",`${bl(r,n)}:print_format=json`,"-ar","48000",...Ha(e),e]}var Ga=["light","medium","strong"],mT={light:6,medium:12,strong:20};function qa(t){return["-hide_banner","-nostats","-i",t,"-vn","-af","aresample=48000,asetnsamples=4800,astats=metadata=1:reset=1,ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-","-f","null","-"]}function Xa(t){let e=[...t.matchAll(/RMS_level=(-?[\d.]+)/g)].map(r=>Number(r[1])).filter(Number.isFinite);return e.length===0?null:(e.sort((r,n)=>r-n),e[Math.floor(e.length*.1)]??null)}function fT(t){return t===null?-50:Math.max(-80,Math.min(-20,Math.round(t+5)))}function wl(t,e){let r=mT[t];if(r===void 0)throw new l(`Unknown denoise strength "${t}".`);return`afftdn=nr=${r}:nf=${fT(e)}`}function Fb(t,e,r="medium",n=null){return["-y","-i",t,...Pb(e),"-af",wl(r,n),...Ha(e),e]}var hT={input:yl.string().min(1).describe("Path to the source video or audio file."),target:za.optional().describe("youtube (-14 LUFS, default), podcast (-16), broadcast (-23), or a LUFS number (-70 to -5)."),output:yl.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:yl.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ob(t){t.registerTool("normalize_audio",{title:"Normalize Loudness",description:"Normalize loudness to a delivery target (two-pass EBU R128 loudnorm); video is copied. Reports loudness before and after.",inputSchema:hT,outputSchema:K,annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();O(e.input);let o=await W(e.input);if(!o.audioCodec)throw new l(`Input has no audio stream: ${e.input}`);let i=Zn(e.target),s=Z(e.input,{audio:!0}),a=j(e.output,"loudnorm",s,{overwrite:e.overwrite}),c=pe(o.durationSec),u=await se(n,ii(e.input,i),c,{signal:r.signal}),d=si(u.stderr);await U(Ib(e.input,a,i,d),{output:a,durationSec:o.durationSec,extra:r});let p=si((await se(n,ii(a,i),c,{signal:r.signal})).stderr);return S({outputPath:a,target:{lufs:i.i,truePeakDb:i.tp,lra:i.lra},before:{lufs:d.input_i,truePeakDb:d.input_tp},after:{lufs:p.input_i,truePeakDb:p.input_tp}})}catch(n){return E(n)}})}import{z as Ja}from"zod";var gT={input:Ja.string().min(1).describe("Path to the source video or audio file."),strength:Ja.enum(Ga).optional().describe("How hard to reduce noise: light (6 dB), medium (12 dB, default), strong (20 dB)."),output:Ja.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ja.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Nb(t){t.registerTool("denoise",{title:"Denoise Audio",description:"Reduce steady background noise (fan, hum, hiss) in a recording's audio with an adaptive FFT denoiser. Video is copied untouched. Returns the output path.",inputSchema:gT,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=await W(e.input);if(!n.audioCodec)throw new l(`Input has no audio stream: ${e.input}`);let o=e.strength??"medium",i=Z(e.input,{audio:!0}),s=j(e.output,"denoise",i,{overwrite:e.overwrite}),a=await se(k().ffmpeg,qa(e.input),pe(n.durationSec),{signal:r.signal}),c=Xa(a.stdout);return await U(Fb(e.input,s,o,c),{output:s,durationSec:n.durationSec,extra:r}),S({outputPath:s,strength:o,noiseFloorDb:c===null?null:Number(c.toFixed(1)),note:"Works best on steady noise (fans, hum, hiss); it does little for intermittent sounds."})}catch(n){return E(n)}})}import{z as Jt}from"zod";import{existsSync as bT,readFileSync as wT,rmSync as yT,writeFileSync as xT}from"node:fs";var ST={input:Jt.string().min(1).describe("Path to the video or audio to transcribe."),model:Jt.string().optional().describe(`Path to a whisper.cpp model file (ggml-*.bin). Defaults to ${Ks}.`),language:Jt.string().optional().describe("Spoken language code, e.g. 'en', or 'auto' (default)."),words:Jt.boolean().optional().describe("One word per cue, for word timing (cut_by_transcript)."),output:Jt.string().optional().describe("Optional output .srt path. Defaults under SCREENCAST_HOME/edits."),overwrite:Jt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Db(t){t.registerTool("transcribe",{title:"Transcribe Speech",description:"Transcribe a recording's speech to an SRT subtitle file, locally, with FFmpeg 8's whisper filter (needs a whisper.cpp model file). Returns the SRT path and the text. Pair with burn_subtitles to caption the video.",inputSchema:ST,outputSchema:B({srtPath:Jt.string(),cues:Jt.number().int(),text:Jt.string()}),annotations:I},async(e,r)=>{try{if(k(),O(e.input),!Ve("whisper"))throw new l("This ffmpeg has no whisper filter.","transcribe needs FFmpeg 8 built with whisper.cpp (--enable-whisper); recent Windows builds such as `winget install Gyan.FFmpeg` include it. Check with `ffmpeg -h filter=whisper`.");let n=Sr(e.model),o=await W(e.input);if(!o.audioCodec)throw new l(`Input has no audio to transcribe: ${e.input}`);let i=j(e.output,"captions",".srt",{overwrite:e.overwrite,anyContainer:!0}),s=He(".srt");try{await te(Dn(e.input,n,s,e.language??"auto",e.words),pe(o.durationSec),{signal:r.signal});let a=bT(s)?pt(Ph(Ue(wT(s,"utf8")))):[];xT(i,it(a));let c=a.map(u=>u.text.replace(/\n/g," ")).join(" ");return S({srtPath:i,cues:a.length,text:c.length>4e3?`${c.slice(0,4e3)}\u2026`:c,...a.length===0?{note:"No speech was recognised."}:{}})}finally{yT(s,{force:!0})}}catch(n){return E(n)}})}import{z as ai}from"zod";import{dirname as vT}from"node:path";import{existsSync as $T}from"node:fs";var kT={input:ai.string().min(1).describe("Path to the source video."),subtitles:ai.string().min(1).describe("Path to an .srt (e.g. from transcribe) or .ass subtitle file."),style:ai.enum(Vs).optional().describe("clean (default for .srt): outlined line. social: big bold text on a dark box. .ass keeps its own styling unless set."),output:ai.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ai.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Lb(t){t.registerTool("burn_subtitles",{title:"Burn In Subtitles",description:"Burn SRT/ASS subtitles (e.g. from transcribe) into a video in the bundled font.",inputSchema:kT,outputSchema:K,annotations:I},async(e,r)=>{try{k();for(let a of[e.input,e.subtitles])if(!$T(a))throw new l(`File not found: ${a}`);if(!Ve("subtitles"))throw new l("This ffmpeg has no subtitles filter (it needs libass).","Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");let n=Z(e.input),o=j(e.output,"subtitled",n,{overwrite:e.overwrite}),i=vT(Ut("regular")),s=e.style??(/\.(ass|ssa)$/i.test(e.subtitles)?null:"clean");return await U(Ih(e.input,e.subtitles,o,i,s),{output:o,durationSec:(await W(e.input)).durationSec,extra:r}),S({outputPath:o,style:s??"file"})}catch(n){return E(n)}})}import{z as Mt}from"zod";var ET={input:Mt.string().min(1).describe("Path to the source video."),segments:Mt.array(Mt.object({start:Mt.number().nonnegative(),end:Mt.number().positive()})).min(1).describe("{start, end} segments in seconds; each becomes its own file."),output:Mt.string().optional().describe("Optional output path. Only honored for a single segment; multi-segment output lands under SCREENCAST_HOME/edits."),overwrite:Mt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Bb(t){t.registerTool("clip",{title:"Extract Clips",description:"Extract several frame-exact segments, each to its own file. For one segment, trim does the same.",inputSchema:ET,outputSchema:B({outputs:Mt.array(Mt.string()),count:Mt.number().int()}),annotations:I},async(e,r)=>{try{k(),O(e.input),jr(e.output);let n=Z(e.input),o=e.segments.length===1,i=[];for(let[s,a]of e.segments.entries()){let c=j(o?e.output:void 0,"clip",`-${String(s).padStart(2,"0")}${n}`,{overwrite:e.overwrite});await U(Wp(e.input,c,a),{output:c,durationSec:a.end-a.start,extra:r}),i.push(c)}return S({outputs:i,count:i.length})}catch(n){return E(n)}})}import{z as Yt}from"zod";var _T={input:Yt.string().min(1).describe("Path to the source video."),minIdleSec:Yt.number().positive().optional().describe(`Only cut still stretches at least this long (default ${en}).`),keepSec:Yt.number().min(0).optional().describe(`Seconds kept at each edge of a cut (default ${Vo}).`),useAudio:Yt.boolean().optional().describe("Require silent audio too (default true when there is audio)."),action:Yt.enum(["cut","speed"]).optional().describe("cut (default), or speed: fast-forward them."),factor:Yt.number().gt(1).max(Zr).optional().describe(`speed: times faster (default ${Qo}).`),dryRun:Yt.boolean().optional().describe("Only report what would be cut."),output:Yt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Yt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Wb(t){t.registerTool("cut_idle",{title:"Cut Idle Stretches",description:"Remove dead air: cut stretches where the screen is frozen (and silent), keeping a short pad. Returns the time saved.",inputSchema:_T,annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();O(e.input);let o=await W(e.input),i=o.durationSec;if(i===null)throw new l(`Could not read duration of ${e.input}.`);let s=e.minIdleSec??en,a=e.keepSec??Vo,c=o.audioCodec!==null,u=(e.useAudio??!0)&&c,d=await se(n,ba(e.input,s,u),pe(i),{signal:r.signal});if(d.code!==0)throw new l(`Idle scan failed (exit ${d.code}): ${d.stderr.trim().slice(-400)}`);let p=wa(d.stderr,i),f=u?xa(p,ya(d.stderr,i)):p,m=Sa(f,s,a),h=e.action==="speed",b=e.factor??Qo,w=m.map(T=>({...T,factor:b})),g=Number((h?tn(w):m.reduce((T,M)=>T+(M.end-M.start),0)).toFixed(2)),y={cuts:m,...h?{action:"speed",factor:b}:{},removedSec:g,originalSec:Number(i.toFixed(2)),newDurationSec:Number((i-g).toFixed(2)),idleRule:u?"frozen video and silent audio":"frozen video"};if(e.dryRun||m.length===0)return S({...y,...m.length===0?{note:"No idle stretches found; nothing to cut."}:{dryRun:!0}});let v=Z(e.input),x=j(e.output,"trimmed-idle",v,{overwrite:e.overwrite}),R=h?Ea(e.input,x,w,{withAudio:c,fps:o.fps}):_a(e.input,x,m,c);return await U(R,{output:x,durationSec:i-g,inputDurationSec:i,extra:r}),S({outputPath:x,...y})}catch(n){return E(n)}})}import{z as et}from"zod";import{existsSync as Xb,readFileSync as IT,writeFileSync as FT}from"node:fs";var TT=["um","umm","uh","uhh","uhm","erm","er","ah","hmm","hm","mm","mhm"],jb=.5,zb=t=>t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),Ar=t=>Number(t.toFixed(3));function Hb(t){let e=[];return t.forEach((r,n)=>{let o=r.text.replace(/\s+/g," ").trim(),i=[...o.matchAll(/\S+/g)],s=o.length||1,a=r.end-r.start;i.forEach((c,u)=>{let d=c.index;e.push({cue:n,raw:c[0],norm:zb(c[0]),start:u===0?r.start:r.start+d/s*a,end:u===i.length-1?r.end:r.start+(d+c[0].length)/s*a,first:u===0,last:u===i.length-1})})}),e}var RT=t=>t.flatMap((e,r)=>e.norm?[r]:[]);function AT(t,e){let r=e.split(/\s+/).map(zb).filter(Boolean);if(r.length===0)throw new l(`Quote "${e}" has no words to match.`);let n=RT(t),o=[];for(let i=0;i+r.length<=n.length;i++)r.every((s,a)=>t[n[i+a]].norm===s)&&o.push([n[i],n[i+r.length-1]]);return o}function MT(t,e,r){let n=r;for(;t[n+1]&&!t[n+1].norm&&t[n+1].cue===t[r].cue;)n++;let o=t[e],i=t[n];return{start:Ar(o.start),end:Ar(i.end),text:t.slice(e,n+1).map(s=>s.raw).join(" "),exact:o.first&&i.last}}function CT(t){let e=[...t].filter(n=>n.end-n.start>.001).sort((n,o)=>n.start-o.start),r=[];for(let n of e){let o=r[r.length-1];o&&n.start<=o.end+.01?(n.end>o.end&&(o.end=n.end),o.text.includes(n.text)||(o.text=`${o.text} ${n.text}`),o.exact&&=n.exact):r.push({...n})}return r}function PT(t,e){let r=t.flatMap(o=>o.index===void 0?[]:[o.index]);if(r.length===0){let o=Number.isInteger(e)?t[e-1]:void 0;if(!o)throw new l(`No cue ${e}: the transcript has cues 1-${t.length}.`);return o}let n=t.filter(o=>o.index===e);if(n.length>1)throw new l(`The transcript numbers ${n.length} cues ${e}; quote the text to cut instead.`);if(n.length===0)throw new l(`No cue ${e}: the transcript's cues are numbered ${Math.min(...r)}-${Math.max(...r)} (a cue with no duration, or wholly overlapped by the next, has no time to cut).`);return n[0]}function Gb(t,e){let r=Hb(t),n=[];for(let i of e.remove??[]){if(typeof i=="number"){let a=PT(t,i);n.push({start:Ar(a.start),end:Ar(a.end),text:a.text.replace(/\s+/g," "),exact:!0});continue}let s=AT(r,i);if(s.length===0)throw new l(`Quote not found in the transcript: "${i}".`);if(s.length>1)throw new l(`Quote "${i}" occurs ${s.length} times; quote more words or use cue numbers.`);n.push(MT(r,...s[0]))}let o=0;if(e.fillers){let i=new Set(TT);r.forEach(s=>{if(!i.has(s.norm))return;if(!r.every(p=>p.cue!==s.cue||p===s||!p.norm)){o++;return}let c=t[s.cue],u=Math.max(t[s.cue-1]?.end??0,c.start-jb),d=Math.min(t[s.cue+1]?.start??1/0,c.end+jb);n.push({start:Ar(Math.min(u,c.start)),end:Ar(Math.max(d,c.end)),text:r.filter(p=>p.cue===s.cue).map(p=>p.raw).join(" "),exact:!0})})}return{cuts:CT(n),skippedFillers:o}}function Ub(t,e){let r=0;for(let n of e){if(t<=n.start)break;r+=Math.min(t,n.end)-n.start}return t-r}function qb(t,e){let r=Hb(t),n=i=>e.some(s=>i.start>=s.start-5e-4&&i.end<=s.end+5e-4),o=[];return t.forEach((i,s)=>{let a=r.filter(f=>f.cue===s),c=a.filter(f=>!n(f));if(!c.some(f=>f.norm))return;let u=c.length===a.length?i.text:c.map(f=>f.raw).join(" "),d=Ar(Ub(i.start,e)),p=Ar(Ub(i.end,e));p>d&&o.push({start:d,end:p,text:u})}),o}var OT={input:et.string().min(1).describe("Path to the source video."),srt:et.string().min(1).describe("Its .srt (transcribe; words: true for word timing)."),remove:et.array(et.union([et.number().int().min(0).max(99999),et.string().min(1)])).optional().describe("Cue numbers as the .srt numbers them, or transcript text quoted exactly (must occur once)."),fillers:et.boolean().optional().describe("Also cut fillers (um, uh...) that have their own cue."),dryRun:et.boolean().optional().describe("Only report the cuts."),output:et.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:et.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Jb(t){t.registerTool("cut_by_transcript",{title:"Cut By Transcript",description:"Edit a video by its transcript: cut quoted text, cue numbers, or fillers. Also writes the re-timed .srt.",inputSchema:OT,outputSchema:B({cuts:et.array(et.unknown()),removedSec:et.number()}),annotations:I},async(e,r)=>{try{k();for(let b of[e.input,e.srt])if(!Xb(b))throw new l(`File not found: ${b}`);if(!e.remove?.length&&!e.fillers)throw new l("Nothing to cut: pass remove and/or fillers: true.");let n=await W(e.input),o=n.durationSec;if(o===null||!n.videoCodec)throw new l(`Not a readable video: ${e.input}`);let i=pt(Ue(IT(e.srt,"utf8"),{index:!0}));if(i.length===0)throw new l(`No cues in ${e.srt}.`);let{cuts:s,skippedFillers:a}=Gb(i,{remove:e.remove,fillers:e.fillers});if(s.length>qn)throw new l(`Too many cuts (${s.length}, max ${qn}); cut in batches.`);let c=Number(s.reduce((b,w)=>b+Math.min(w.end,o)-Math.min(w.start,o),0).toFixed(2)),u=qb(i,s),d=[s.length===0&&"Nothing matched; nothing to cut.",a>0&&`${a} filler(s) inside longer cues were kept; transcribe with words: true to cut them.`,s.some(b=>!b.exact)&&"Some edges were estimated inside a cue; transcribe with words: true for word timing."].filter(Boolean),p={cuts:s,removedSec:c,originalSec:Number(o.toFixed(2)),newDurationSec:Number((o-c).toFixed(2)),...d.length?{note:d.join(" ")}:{}};if(e.dryRun||s.length===0){let b=u.map(w=>w.text.replace(/\n/g," ")).join(" ");return S({...p,...s.length?{dryRun:!0}:{},text:b.length>4e3?`${b.slice(0,4e3)}\u2026`:b})}let f=Z(e.input),m=j(e.output,"cut-transcript",f,{overwrite:e.overwrite}),h=m.replace(/\.[^.\\/]+$/,"")+".srt";if(!e.overwrite&&Xb(h))throw new l(`Output already exists: ${h}. Pass overwrite: true to replace it.`);return await U(_a(e.input,m,s,n.audioCodec!==null),{output:m,durationSec:o-c,inputDurationSec:o,extra:r}),FT(h,it(u)),S({outputPath:m,srtPath:h,...p})}catch(n){return E(n)}})}import{z as nn}from"zod";var NT={input:nn.string().min(1).describe("Path to the source video or image (png/jpg; time ranges are ignored for an image)."),regions:nn.array(xn).min(1).describe("Pixel rectangles (x, y, width, height), each optionally limited to start..end seconds."),style:nn.enum(Oi).optional().describe("box (default): irreversible fill; blur/pixelate are partially recoverable."),pad:nn.number().int().nonnegative().optional().describe("Grow each region by this many px (default 0)."),color:nn.string().optional().describe("Box fill color (default black)."),output:nn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:nn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Yb(t){t.registerTool("redact_region",{title:"Redact Regions",description:"Cover given rectangles in a video or screenshot (e.g. secrets on screen). Not automatic detection: find them with find_text redact: true. Off-frame regions are rejected.",inputSchema:NT,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let{width:n,height:o,durationSec:i}=await W(e.input),{still:s,ext:a}=Ni(e.input,e.output),c=j(e.output,"redact",a,{overwrite:e.overwrite,anyContainer:!0}),u=jp(e.input,c,e.regions,{style:e.style,pad:e.pad,color:e.color},{width:n,height:o},s);return await U(u,{output:c,durationSec:s?null:i,extra:r}),S({outputPath:c,regions:e.regions.length,style:e.style??"box"})}catch(n){return E(n)}})}import{z as Ya}from"zod";function Kb(t){t.registerTool("list_audio_devices",{title:"List Audio Devices",description:"List DirectShow audio devices and flag a likely loopback (Stereo Mix or a virtual-audio driver), for start_recording's audio.device.",inputSchema:{},outputSchema:B({devices:Ya.array(Ya.unknown()),loopbackDevice:Ya.string().nullable(),note:Ya.string()}),annotations:fe},async()=>{try{k();let e=await tu(!0),r=eu(e);return S({devices:e,loopbackDevice:r,note:r?`Pass "${r}" as the audio device to capture system audio.`:`No loopback device detected. ${Co}`})}catch(e){return E(e)}})}import{z as me}from"zod";function Qb(t){return t.hwnd!==void 0?`window:hwnd=${t.hwnd}`:`window:${t.title}`}function DT(t){let e=/^.*?[.!?](?=\s|$)/.exec(t);return e?e[0]:t}function Vb(t,e,r){try{return Dc(t,Qb(e).slice(7),{allowCloaked:r,exactOnly:!0}),{ok:!0}}catch(n){return{ok:!1,reason:DT(z(n))}}}function Zb(t,e,r){let n=r.filter??{},o=n.exe?Nc(`exe=${n.exe}`):null,i=o?.kind==="exe"?o.exe:null,s=n.titleContains?.trim().toLowerCase()||null,a=yo(t),c=t.length>0?a:e.virtual,u=[];for(let d of Array.isArray(e.windows)?e.windows:[]){if(i!==null&&(d.exe??"").toLowerCase().replace(/\.exe$/,"")!==i||s!==null&&!d.title.toLowerCase().includes(s))continue;let p=Vb(e,d,!1),f=r.wgcAvailable&&d.hwnd!==void 0?Vb(e,d,!0):{ok:!1};n.capturableOnly&&!p.ok&&!f.ok||u.push({target:Qb(d),title:d.title,exe:d.exe||null,pid:typeof d.pid=="number"?d.pid:null,hwnd:d.hwnd??null,bounds:{x:d.left,y:d.top,width:d.right-d.left,height:d.bottom-d.top},minimized:!!d.minimized,cloaked:!!d.cloaked,capturable:p.ok,wgcCapturable:f.ok,...p.ok?{}:{reason:p.reason}})}return{full:{target:"full",bounds:{x:c.x,y:c.y,width:c.w,height:c.h}},monitors:t.map(d=>({target:`monitor:${d.index}`,index:d.index,primary:d.primary,bounds:{x:d.x,y:d.y,width:d.width,height:d.height},dpi:d.dpi??null,scale:d.dpi?Math.round(d.dpi/96*100)/100:null})),windows:u,wgcAvailable:r.wgcAvailable}}var LT={exe:me.string().min(1).optional().describe("Only list windows of this executable, e.g. 'Code.exe' or 'code'."),titleContains:me.string().min(1).optional().describe("Only list windows whose title contains this text (case-insensitive)."),capturableOnly:me.boolean().optional().describe("Leave out windows neither backend can capture (minimized, off screen). Default false.")},xl=me.object({x:me.number(),y:me.number(),width:me.number(),height:me.number()}),BT=B({full:me.looseObject({target:me.literal("full"),bounds:xl}),monitors:me.array(me.looseObject({target:me.string(),index:me.number(),primary:me.boolean(),bounds:xl,dpi:me.number().nullable(),scale:me.number().nullable()})),windows:me.array(me.looseObject({target:me.string(),title:me.string(),exe:me.string().nullable(),pid:me.number().nullable(),hwnd:me.number().nullable(),bounds:xl,minimized:me.boolean(),cloaked:me.boolean(),capturable:me.boolean(),wgcCapturable:me.boolean()})),wgcAvailable:me.boolean(),note:me.string()});function ew(t){t.registerTool("list_targets",{title:"List Capture Targets",description:"List the desktop, monitors, and visible windows (topmost first, with capturability per backend). Each entry has a `target` string to pass as-is to capture tools; use it instead of guessing a title.",inputSchema:LT,outputSchema:BT,annotations:fe},async e=>{try{let[r,n]=await Promise.all([lr(),Lc()]),o=Zb(r,n,{wgcAvailable:cr(),filter:{exe:e.exe,titleContains:e.titleContains,capturableOnly:e.capturableOnly}});return S({...o,note:'Pass a target string unchanged. A window handle lasts until the app closes the window; list again after an app restarts, or target it by window:exe=<app.exe>. A window with capturable false but wgcCapturable true needs backend: "wgc".'})}catch(r){return E(r)}})}import{existsSync as Qa}from"node:fs";import{dirname as JT,join as vl}from"node:path";import{z as de}from"zod";import{readdir as WT,stat as jT,statfs as UT}from"node:fs/promises";import{join as rw}from"node:path";var nw=2*1024**3,tw=["recordings","edits","screenshots","frames"];async function ow(t){let e;try{e=await WT(t,{withFileTypes:!0})}catch{return 0}let r=0;for(let n of e){let o=rw(t,n.name);n.isDirectory()?r+=await ow(o):n.isFile()&&(r+=await jT(o).then(i=>i.size,()=>0))}return r}async function Sl(t){try{let e=await UT(t);return Number(e.bavail)*Number(e.bsize)}catch{return null}}async function iw(t){let[e,...r]=await Promise.all([Sl(t),...tw.map(o=>ow(rw(t,o)))]),n=Object.fromEntries(tw.map((o,i)=>[o,r[i]??0]));return{freeBytes:e??null,bytes:n}}function sw(t){let e=["B","KB","MB","GB","TB"],r=t,n=0;for(;r>=1024&&n<e.length-1;)r/=1024,n++;return`${n===0?r:r.toFixed(1)} ${e[n]}`}var aw=200,cw=1e3,Ka=.5,Va=3,on=t=>Math.round(t*1e3)/1e3;function lw(t,e){if(t.length===0)throw new l("lines is empty: give at least one { t | marker, text }.");if(t.length>aw)throw new l(`At most ${aw} lines are allowed (got ${t.length}).`);return t.map((n,o)=>{let i=n.text.replace(/\s+/g," ").trim();if(!i)throw new l(`lines[${o}] has no text.`);if(i.length>cw)throw new l(`lines[${o}] is ${i.length} characters; at most ${cw} are allowed. Split it.`);if(n.t!==void 0&&n.marker!==void 0)throw new l(`lines[${o}] has both t and marker; give one.`);if(n.t!==void 0){if(!Number.isFinite(n.t)||n.t<0)throw new l(`lines[${o}].t must be a non-negative number.`);return{t:on(n.t),text:i}}if(n.marker!==void 0){let s=n.marker.trim().toLowerCase(),a=e.find(c=>c.label.trim().toLowerCase()===s);if(!a){let c=e.map(u=>`"${u.label}"`).join(", ");throw new l(`lines[${o}]: no marker labelled "${n.marker}".`,c?`Markers on this video: ${c}.`:"This video has no markers; add_marker stamps one, or give t.")}return{t:on(a.t),text:i}}throw new l(`lines[${o}] needs t (seconds) or marker (a marker label).`)}).sort((n,o)=>n.t-o.t)}function pw(t,e){let r=[];return t.forEach((n,o)=>{let i=n.t+n.durationSec,s=t[o+1],a=`"${n.text.length>40?`${n.text.slice(0,40)}...`:n.text}"`;n.t>=e?r.push(`Line at ${n.t}s ${a} starts after the video ends (${on(e)}s) and is not heard.`):s&&i>s.t+.05?r.push(`Line at ${n.t}s ${a} runs ${on(i-s.t)}s past the next line (${s.t}s); they overlap. Move the next line, shorten this one, or raise rate.`):i>e+.05&&r.push(`Line at ${n.t}s ${a} runs ${on(i-e)}s past the end of the video and is cut off.`)}),r}function dw(t,e){return t.map((r,n)=>{let o=t[n+1],i=Math.min(r.t+r.durationSec,o?o.t:1/0,e);return{start:r.t,end:on(i),text:r.text}}).filter(r=>r.end>r.start)}function mw(t){if(t.length<12||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WAVE")throw new l("The speech engine did not return a WAV file.");let e=0;for(let r=12;r+8<=t.length;){let n=t.toString("ascii",r,r+4),o=t.readUInt32LE(r+4);if(n==="fmt "&&r+16<=t.length&&(e=t.readUInt32LE(r+16)),n==="data"){if(e<=0)break;let i=t.length-(r+8);return(o===0||o===4294967295||o>i?i:o)/e}r+=8+o+o%2}throw new l("Could not read the WAV header the speech engine wrote.")}function fw(t,e,r,n,o,i){if(!Number.isFinite(o)||o<=0)throw new l("video duration must be known and positive.");if(e.length===0||e.length!==n.length)throw new l("Every placed line needs its WAV.");let s=on(o),a=h=>`amix=inputs=${h}:duration=longest:dropout_transition=0:normalize=0`,c=n.map((h,b)=>{let w=Math.round(h.t*1e3);return`[${b+1}:a]aresample=48000,aformat=channel_layouts=mono,adelay=${w}[l${b}]`}),u=n.map((h,b)=>`[l${b}]`).join(""),d=!(i.hasAudio&&i.channels===1),p=`apad,atrim=end=${s}${d?",pan=stereo|c0=c0|c1=c0":""}`,f=i.hasAudio?"voice":"aout";c.push(n.length>1?`${u}${a(n.length)},${p}[${f}]`:`[l0]${p}[${f}]`),i.hasAudio&&(c.push(`[0:a]aresample=48000,aformat=channel_layouts=${d?"stereo":"mono"}[orig]`),i.duck??!0?(c.push("[voice]asplit=2[vo][key]"),c.push("[orig][key]sidechaincompress=threshold=0.02:ratio=8:attack=20:release=400[bed]"),c.push(`[bed][vo]${a(2)}[aout]`)):c.push(`[orig][voice]${a(2)}[aout]`));let m=Ii(r);return["-y","-i",t,...e.flatMap(h=>["-i",h]),"-filter_complex",c.join(";"),...m?[]:["-map","0:v?","-c:v","copy"],"-map","[aout]","-t",String(s),...Ha(r),.../\.(mp4|mov|m4a)$/i.test(r)?["-movflags","+faststart"]:[],r]}var zT=3e4,HT=1e4,uw=3e4,hw=t=>Array.isArray(t)?t:t==null?[]:[t];function gw(t){return hw(t.voices).map(e=>({name:String(e.name??""),language:String(e.language??""),gender:String(e.gender??"")}))}function GT(t){return{script:XT,payload:JSON.stringify(t)}}async function bw(t,e,r){if(process.platform!=="win32")throw new l("narrate uses the speech engine built into Windows and runs on Windows only.");let{script:n,payload:o}=GT(t),i="list"in t,s=await ct(n,i?"speech voices":"the speech engine",{timeoutMs:e,signal:r,payload:o,failure:i?"Could not list speech voices":"Could not synthesize speech"});try{return JSON.parse(s)}catch(a){throw new l(`Could not parse the speech engine's output: ${z(a)}`)}}async function qT(t){let e=await bw({list:!0},ur(15e3),t);if(e.error)throw new l(`Windows speech is unavailable: ${e.error}`);return gw(e)}async function ww(){if(process.platform!=="win32")return{available:!1,voices:[],error:"Windows speech is available on Windows only."};try{let t=(await qT()).map(e=>`${e.name} (${e.language})`);return{available:t.length>0,voices:t,...t.length?{}:{error:"No speech voices are installed."}}}catch(t){return{available:!1,voices:[],error:z(t)}}}async function yw(t,e){let r=e.rate??1;if(!Number.isFinite(r)||r<Ka||r>Va)throw new l(`rate must be between ${Ka} and ${Va} (1 is normal speed).`);let n=await bw({voice:e.voice??null,rate:r,items:t},ur(zT+t.length*HT),e.signal);if(n.error){let o=gw(n);throw n.error==="unknown voice"?new l(`No installed voice matches "${e.voice}".`,o.length?`Installed voices: ${o.map(i=>`${i.name} (${i.language})`).join(", ")}.`:"No voices are installed."):new l(`Windows speech is unavailable: ${n.error}`,"Install a voice: Settings > Time & language > Speech > Manage voices.")}return hw(n.results).forEach((o,i)=>{if(o.error)throw new l(`Could not synthesize line ${i+1}: ${o.error}`)}),String(n.voice??"")}var XT=`
|
|
341
|
+
`}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 ${Lb(o.x+r,o.t,c)}, ${e} y ${Lb(o.y+n,o.t,u)}`}})}function $R(t,e){return t.flatMap(([r,n])=>[{t:r,text:`${e} enable 1`},...Number.isFinite(n)?[{t:n,text:`${e} enable 0`}]:[]])}function wl(t,e,r,n,o,i,s,a){if(t.path.length===0)throw new l("No cursor positions to draw.");let c=SR(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=${xe(a)}${b}`);let w=(g,y,v,x,T)=>{let R=`[${i}c${y}o]`;f.push(`${b}${g}${p(y)}=x=${Oe(h.x+v)}:y=${Oe(h.y+x)}:enable=0${R}`),m.push(...$R(T,p(y))),b=R};if(e.spotlight){let y=Math.ceil(2*u/4),v=Math.ceil(2*d/4),x=c.spotRadius/4,T=x*.8,R=`255*0.55*clip((hypot(X-${Oe(y/2)},Y-${Oe(v/2)})-${Oe(x)})/${Oe(T)},0,1)`;f.push(`color=c=black:s=${y}x${v}:r=1:d=1,format=rgba,geq=r=0:g=0:b=0:a='${R}',scale=${2*u}:${2*d}[${i}csm]`);let P=c.spriteW*.25-u,z=c.spriteH*.3-d;w(`[${i}csm]`,"s",P,z,t.visible),m.push(...Bb(t.path,p("s"),P,z))}if(e.clicks!==!1&&t.clicks.length>0){let g=uR/3;c.ripples.forEach((y,v)=>{let x=y/2,T=Math.max(1.5,y*.05),R=`abs(hypot(X-${Oe(x-.5)},Y-${Oe(x-.5)})-${Oe(x-T-1)})`,P=[.9,.65,.4][v],z=`255*lt(${R},${Oe(T*.45)})`;f.push(`color=c=black:s=${y}x${y}:r=1:d=1,format=rgba,geq=r='${z}':g='${z}':b='${z}':a='255*${P}*clip(${Oe(T)}-${R},0,1)'[${i}cr${v}]`);let H=t.clicks.map(D=>[D.t+v*g,D.t+(v+1)*g]);w(`[${i}cr${v}]`,`r${v}`,-x,-x,[]);for(let[D,M]of t.clicks.entries()){let[ie,Z]=H[D],K=H[D+1];m.push({t:ie,text:`${p(`r${v}`)} x ${Oe(M.x-x)}, ${p(`r${v}`)} y ${Oe(M.y-x)}, ${p(`r${v}`)} enable 1`}),(!K||K[0]>=Z)&&m.push({t:Z,text:`${p(`r${v}`)} enable 0`})}})}return f.push(`[${o}:v]scale=${c.spriteW}:${c.spriteH}:flags=lanczos,format=rgba[${i}csp]`),w(`[${i}csp]`,"p",-c.hotX,-c.hotY,t.visible),m.push(...Bb(t.path,p("p"),-c.hotX,-c.hotY)),{steps:f,out:b,extraInputs:["-i",s],commands:vR(m)}}function Wb(t,e,r,n,o,i,s,a="standard"){let{steps:c,out:u,extraInputs:d,commands:p}=wl(r,n,o,"[0:v]",1,"",i,s);return{args:["-y","-i",t,...d,"-filter_complex",c.join(";"),"-map",u,"-map","0:a?",...Me(a),"-c:a","copy",e],commands:p}}var Ha={events:to.string().optional(),size:to.number().min(.25).max(8).optional(),smoothing:to.number().min(0).max(1).optional(),hideAfterSec:to.number().min(0).max(600).optional(),clicks:to.boolean().optional(),spotlight:to.boolean().optional()};function Ga(t,e,r,n){let o=e??he(t).jsonl;if(!sR(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=yR(Ie(aR(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 no=Ha,TR={input:mi.string().min(1).describe("Path to the recording."),events:no.events.describe("Event log (default: the input's .events.jsonl)."),size:no.size.describe(`Times a typical cursor's size (default ${bl}).`),smoothing:no.smoothing.describe("0 = as logged, 1 = floaty (default 0.5)."),hideAfterSec:no.hideAfterSec.describe(`Hide when the mouse rests this long; 0 = never (default ${gl}).`),clicks:no.clicks.describe("Ripple on clicks (default true)."),spotlight:no.spotlight.describe("Dim all but the area around the cursor."),dryRun:mi.boolean().optional().describe("Return the plan; write nothing."),output:mi.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:mi.boolean().optional().describe("Replace an existing output (default false).")};function Ub(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:TR,outputSchema:N({segments:mi.number().int()}),annotations:C},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=za(Ga(e.input,e.events,e,n.durationSec)),i={segments:o.path.length,clicks:o.clicks.length,shownSec:Math.round(o.visible.reduce((c,[u,d])=>c+(Math.min(d,n.durationSec??d)-u),0)*10)/10};if(e.dryRun)return S({dryRun:!0,...i,visible:o.visible});let s=B(e.output,"cursor",V(e.input),{overwrite:e.overwrite}),a=kR(jb(RR(),"screencast-cursor-"));try{let c=jb(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},Ua(),c);return _R(c,d),await U(u,{output:s,durationSec:n.durationSec,extra:r}),S({outputPath:s,...i})}finally{ER(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as oo}from"zod";import{existsSync as FR}from"node:fs";import{extname as OR}from"node:path";import{z as Kt}from"zod";var Gb={desktop:["#1B2330","#0A0D12"],rec:["#FF4545","#5C0F1A"],amber:["#FFB454","#FF4545"],light:["#F4F7FA","#B9C4D0"]},MR=Object.keys(Gb),AR="desktop",xl=4,CR=.5,zb=t=>2*Math.round(t/2),qa=t=>2*Math.floor(t/2);function yl(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 PR(t,e,r={}){if(!(t>0&&e>0))throw new l("The input has no frame size.");let n=yl(r.padding,"padding",2e3),o=yl(r.radius,"radius",1e3),i=yl(r.shadow,"shadow",200),s,a,c=t,u=e,d,p,f,m=!1;if(r.aspect){let v=Yn[r.aspect];if(!v)throw new l(`Unknown aspect "${r.aspect}".`);s=v.w,a=v.h,f=zb(n??Math.max(s,a)*.06);let x=s-2*f,T=a-2*f;if(x<16||T<16)throw new l(`padding ${f} leaves no room on a ${r.aspect} canvas.`);let R=Math.min(x/t,T/e);c=Math.max(2,qa(t*R)),u=Math.max(2,qa(e*R)),m=c!==t||u!==e,d=qa((s-c)/2),p=qa((a-u)/2)}else f=zb(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 IR(t){if(t.colors!==void 0){if(t.colors.length<1||t.colors.length>xl)throw new l(`colors takes 1 to ${xl} colors.`);return t.colors.map((n,o)=>Ue(n,`colors[${o}]`))}let e=t.preset??AR,r=Gb[e];if(!r)throw new l(`Unknown backdrop preset "${e}".`);return[...r]}function Hb(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 Sl(t,e,r,n,o,i=!1){let s=PR(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??CR,{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 H=IR(t);if(H.length===1)b.push(`color=c=${H[0]}:s=${c}x${u}${h},format=rgba${g}`);else{let D=H.map((M,ie)=>`c${ie}=${M}`).join(":");b.push(`gradients=s=${c}x${u}:${D}:n=${H.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 H=`[${o}sa]`,D=`[${o}sc]`,M=`[${o}sh]`,ie=`[${o}bs]`,Z=s.radius>0?`format=gray,geq=lum='${Hb(s.radius)}'`:"format=gray";b.push(`color=c=white:s=${d}x${p}${h},${Z},pad=${c}:${u}:${f}:${m+s.shadowOffset}:color=black,gblur=sigma=${(s.shadow/2).toFixed(2)}${H}`),b.push(`color=c=black:s=${c}x${u}${h}${D}`),b.push(`${D}${H}alphamerge,format=rgba,colorchannelmixer=aa=${a}${M}`),b.push(`${y}${M}overlay=0:0:format=rgb${ie}`),y=ie}let v=`[${o}hole]`,x=`[${o}frame]`,T=s.radius>0?`format=gray,geq=lum='${Hb(s.radius,!0)}'`:"format=gray";b.push(`color=c=black:s=${d}x${p}${h},${T},pad=${c}:${u}:${f}:${m}:color=white${v}`),b.push(`${y}${v}alphamerge,format=rgba${x}`);let R=`[${o}pad]`,P=`[${o}bd]`,z=s.scaled?`scale=${d}:${p},setsar=1,`:"";return b.push(`${r}${z}pad=${c}:${u}:${f}:${m}:color=black${R}`),b.push(`${R}${x}overlay=0:0${i?":format=rgb":""}${P}`),{steps:b,out:P,extraInputs:w,layout:s}}function qb(t,e,r,n,o=!1,i="standard"){let{steps:s,out:a,extraInputs:c,layout:u}=Sl(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",..._e(e)]:[...p,"-map","0:a?",...Me(i),"-c:a","copy","-movflags","+faststart",e],layout:u}}var Xa={preset:Kt.enum(MR).optional(),colors:Kt.array(Kt.string()).min(1).max(xl).optional(),image:Kt.string().min(1).optional(),padding:Kt.number().int().nonnegative().max(2e3).optional(),radius:Kt.number().int().nonnegative().max(1e3).optional(),shadow:Kt.number().int().nonnegative().max(200).optional(),shadowOpacity:Kt.number().min(0).max(1).optional(),aspect:Kt.enum(Jn).optional()};var Xb=/\.(png|jpe?g|bmp|tiff?|webp)$/i,Pr=Xa,NR={input:oo.string().min(1).describe("Path to the source video or image (png/jpg)."),preset:Pr.preset.describe("Gradient: desktop (default, dark slate), rec (red), amber, light."),colors:Pr.colors.describe("Instead: 1 color = solid, 2-4 = diagonal gradient."),image:Pr.image.describe("Instead: a wallpaper image, scaled to cover."),padding:Pr.padding.describe("px around the content (default 6% of the longer side)."),radius:Pr.radius.describe("Corner radius px (default ~1.2% of the longer side; 0 = square)."),shadow:Pr.shadow.describe("Shadow blur px (default ~2.5%; 0 = none)."),shadowOpacity:Pr.shadowOpacity.describe("Default 0.5."),aspect:Pr.aspect.describe("Output on this aspect's canvas (1920x1080, ...), content scaled to fit."),output:oo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits (screenshots for an image)."),overwrite:oo.boolean().optional().describe("Replace an existing output (default false).")};function Jb(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:NR,outputSchema:N({outputPath:oo.string(),width:oo.number().int(),height:oo.number().int()}),annotations:C},async(e,r)=>{try{if(k(),F(e.input),e.image&&!FR(e.image))throw new l(`Background image not found: ${e.image}`);let n=Xb.test(e.input);if(n&&e.output&&!Xb.test(e.output))throw new l("An image input writes an image: give the output a .png or .jpg extension.");n||qr(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)?OR(e.input).toLowerCase():".png":V(e.input),s=ar(e.output,ye(n?"screenshots":"edits"),`backdrop-${be()}-${we()}${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}=qb(e.input,s,a,{width:o.width,height:o.height},n);return await U(c,{output:s,durationSec:n?null:o.durationSec,extra:r}),S({outputPath:s,width:u.canvasW,height:u.canvasH,content:{x:u.x,y:u.y,width:u.contentW,height:u.contentH},padding:u.padding,radius:u.radius,shadow:u.shadow,background:e.image?"image":e.colors?"colors":e.preset??"desktop"})}catch(n){return E(n)}})}import{z as fi}from"zod";var DR={input:fi.string().min(1).describe("Source video path."),level:fi.enum(["light","medium","heavy"]).optional().describe("CRF 23 / 28 / 32 (default medium)."),maxWidth:fi.number().int().positive().optional().describe("Width cap in px (only downscales)."),output:fi.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:fi.boolean().optional().describe("Replace an existing output (default false).")};function Yb(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:DR,outputSchema:Y,annotations:C},async(e,r)=>{try{k(),F(e.input);let n=V(e.input),o=B(e.output,"compress",n,{overwrite:e.overwrite}),i=Hp(e.input,o,{level:e.level,maxWidth:e.maxWidth});return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o,level:e.level??"medium"})}catch(n){return E(n)}})}import{z as Ja}from"zod";var LR={mp3:"mp3",aac:"m4a",wav:"wav"},BR={input:Ja.string().min(1).describe("Path to the source media."),format:Ja.enum(["mp3","aac","wav","copy"]).describe("Audio output codec. copy keeps the source codec without re-encoding."),output:Ja.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:Ja.boolean().optional().describe("Replace an existing output (default false).")};function Kb(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:BR,outputSchema:Y,annotations:C},async(e,r)=>{try{let{ffprobe:n}=k();F(e.input);let o=e.format,i=null,s;if(o==="copy"){let c=await ce(n,Gr(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=Hr(JSON.parse(c.stdout)).audioCodec,!i)throw new l(`Input has no audio stream to extract: ${e.input}`);s=Gp(i)}else s=LR[o];let a=B(e.output,"audio",`.${s}`,{overwrite:e.overwrite,anyContainer:!0});return await U(qp(e.input,a,o),{output:a,durationSec:await ue(e.input),extra:r}),S({outputPath:a,format:o,...i?{sourceAudioCodec:i}:{}})}catch(n){return E(n)}})}import{z as _l}from"zod";import{extname as WR}from"node:path";import{z as vl}from"zod";var jR=["youtube","podcast","broadcast"],Ya=vl.union([vl.enum(jR),vl.number().min(-70).max(-5)]),Vb={youtube:{i:-14,tp:-1,lra:11},podcast:{i:-16,tp:-1.5,lra:11},broadcast:{i:-23,tp:-1,lra:7}};function io(t){if(t===void 0)return Vb.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=Vb[t];if(!e)throw new l(`Unknown loudness target "${t}".`);return e}var $l=t=>`I=${t.i}:TP=${t.tp}:LRA=${t.lra}`;function hi(t,e){return["-hide_banner","-nostats","-i",t,"-vn","-af",`loudnorm=${$l(e)}:print_format=json`,"-f","null","-"]}function gi(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 Qb(t){return Ui(t)?["-map","0:a:0","-vn"]:["-map","0:v?","-map","0:a:0","-c:v","copy"]}function Ka(t){switch(WR(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 kl(t,e){if(!e)return`loudnorm=${$l(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=${$l(t)}:${r}:linear=true`}function Zb(t,e,r,n){return["-y","-hide_banner","-i",t,...Qb(e),"-af",`${kl(r,n)}:print_format=json`,"-ar","48000",...Ka(e),e]}var Va=["light","medium","strong"],UR={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 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 zR(t){return t===null?-50:Math.max(-80,Math.min(-20,Math.round(t+5)))}function El(t,e){let r=UR[t];if(r===void 0)throw new l(`Unknown denoise strength "${t}".`);return`afftdn=nr=${r}:nf=${zR(e)}`}function ew(t,e,r="medium",n=null){return["-y","-i",t,...Qb(e),"-af",El(r,n),...Ka(e),e]}var HR={input:_l.string().min(1).describe("Path to the source video or audio file."),target:Ya.optional().describe("youtube (-14 LUFS, default), podcast (-16), broadcast (-23), or a LUFS number (-70 to -5)."),output:_l.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:_l.boolean().optional().describe("Replace an existing output (default false).")};function tw(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:HR,outputSchema:Y,annotations:C},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=io(e.target),s=V(e.input,{audio:!0}),a=B(e.output,"loudnorm",s,{overwrite:e.overwrite}),c=de(o.durationSec),u=await ce(n,hi(e.input,i),c,{signal:r.signal}),d=gi(u.stderr);await U(Zb(e.input,a,i,d),{output:a,durationSec:o.durationSec,extra:r});let p=gi((await ce(n,hi(a,i),c,{signal:r.signal})).stderr);return S({outputPath:a,target:{lufs:i.i,truePeakDb:i.tp,lra:i.lra},before:{lufs:d.input_i,truePeakDb:d.input_tp},after:{lufs:p.input_i,truePeakDb:p.input_tp}})}catch(n){return E(n)}})}import{z as ec}from"zod";var GR={input:ec.string().min(1).describe("Path to the source video or audio file."),strength:ec.enum(Va).optional().describe("How hard to reduce noise: light (6 dB), medium (12 dB, default), strong (20 dB)."),output:ec.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:ec.boolean().optional().describe("Replace an existing output (default false).")};function rw(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:GR,outputSchema:Y,annotations:C},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 ce(k().ffmpeg,Qa(e.input),de(n.durationSec),{signal:r.signal}),c=Za(a.stdout);return await U(ew(e.input,s,o,c),{output:s,durationSec:n.durationSec,extra:r}),S({outputPath:s,strength:o,noiseFloorDb:c===null?null:Number(c.toFixed(1)),note:"Works best on steady noise (fans, hum, hiss); it does little for intermittent sounds."})}catch(n){return E(n)}})}import{z as Vt}from"zod";import{existsSync as qR,readFileSync as XR,rmSync as JR,writeFileSync as YR}from"node:fs";var KR={input:Vt.string().min(1).describe("Path to the video or audio to transcribe."),model:Vt.string().optional().describe(`Path to a whisper.cpp model file (ggml-*.bin). Defaults to ${aa}.`),language:Vt.string().optional().describe("Spoken language code, e.g. 'en', or 'auto' (default)."),words:Vt.boolean().optional().describe("One word per cue, for word timing (cut_by_transcript)."),output:Vt.string().optional().describe("Optional output .srt path. Defaults under SCREENCAST_HOME/edits."),overwrite:Vt.boolean().optional().describe("Replace an existing output (default false).")};function nw(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:KR,outputSchema:N({srtPath:Vt.string(),cues:Vt.number().int(),text:Vt.string()}),annotations:C},async(e,r)=>{try{if(k(),F(e.input),!Qe("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=Er(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=Xe(".srt");try{await te(zn(e.input,n,s,e.language??"auto",e.words),de(o.durationSec),{signal:r.signal});let a=qR(s)?gt(Xh(qe(XR(s,"utf8")))):[];YR(i,at(a));let c=a.map(u=>u.text.replace(/\n/g," ")).join(" ");return S({srtPath:i,cues:a.length,text:c.length>4e3?`${c.slice(0,4e3)}\u2026`:c,...a.length===0?{note:"No speech was recognised."}:{}})}finally{JR(s,{force:!0})}}catch(n){return E(n)}})}import{z as bi}from"zod";import{dirname as VR}from"node:path";import{existsSync as QR}from"node:fs";var ZR={input:bi.string().min(1).describe("Source video path."),subtitles:bi.string().min(1).describe("Path to an .srt (e.g. from transcribe) or .ass subtitle file."),style:bi.enum(ca).optional().describe("clean (default for .srt): outlined line. social: big bold text on a dark box. .ass keeps its own styling unless set."),output:bi.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:bi.boolean().optional().describe("Replace an existing output (default false).")};function ow(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:ZR,outputSchema:Y,annotations:C},async(e,r)=>{try{k();for(let a of[e.input,e.subtitles])if(!QR(a))throw new l(`File not found: ${a}`);if(!Qe("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=VR(Gt("regular")),s=e.style??(/\.(ass|ssa)$/i.test(e.subtitles)?null:"clean");return await U(Jh(e.input,e.subtitles,o,i,s),{output:o,durationSec:(await L(e.input)).durationSec,extra:r}),S({outputPath:o,style:s??"file"})}catch(n){return E(n)}})}import{z as Ft}from"zod";var eT={input:Ft.string().min(1).describe("Source video path."),segments:Ft.array(Ft.object({start:Ft.number().nonnegative(),end:Ft.number().positive()})).min(1).describe("{start, end} segments in seconds; each becomes its own file."),output:Ft.string().optional().describe("Optional output path. Only honored for a single segment; multi-segment output lands under SCREENCAST_HOME/edits."),overwrite:Ft.boolean().optional().describe("Replace an existing output (default false).")};function iw(t){t.registerTool("clip",{title:"Extract Clips",description:"Extract several frame-exact segments, each to its own file. For one segment, trim does the same.",inputSchema:eT,outputSchema:N({outputs:Ft.array(Ft.string()),count:Ft.number().int()}),annotations:C},async(e,r)=>{try{k(),F(e.input),qr(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 U(Xp(e.input,c,a),{output:c,durationSec:a.end-a.start,extra:r}),i.push(c)}return S({outputs:i,count:i.length})}catch(n){return E(n)}})}import{z as Qt}from"zod";import{existsSync as tT,readFileSync as rT}from"node:fs";async function tc(t,e,r){let n=r.basis??"screen",o=null;if(n!=="screen"){let u=he(e).jsonl;if(!tT(u))throw new l(`basis "${n}" needs the recording's event log (${u}).`,'Record with start_recording events: true, or use basis "screen".');if(o=ub(Ie(rT(u,"utf8")),r.duration,r.minIdleSec),n==="events")return{idle:o,rule:"no clicks, wheel or typing"}}let i=await ce(t,ib(e,r.minIdleSec,r.useAudio,r),r.timeoutMs,{signal:r.signal});if(i.code!==0)throw new l(`Idle scan failed (exit ${i.code}): ${i.stderr.trim().slice(-400)}`);let s=ab(i.stderr,r.duration),a=r.useAudio?il(s,cb(i.stderr,r.duration)):s,c=r.useAudio?"frozen video and silent audio":"frozen video";return o&&(a=il(a,o),c+=", and no clicks, wheel or typing"),{idle:a,rule:c}}var nT={input:Qt.string().min(1).describe("Source video path."),minIdleSec:Qt.number().positive().optional().describe(`Only cut still stretches at least this long (default ${an}).`),keepSec:Qt.number().min(0).optional().describe(`Seconds kept at each edge of a cut (default ${ai}).`),useAudio:Qt.boolean().optional().describe("Require silent audio too (default true when there is audio)."),...ob,action:Qt.enum(["cut","speed"]).optional().describe("cut (default), or speed: fast-forward them."),factor:Qt.number().gt(1).max(sn).optional().describe(`speed: times faster (default ${ci}).`),dryRun:Qt.boolean().optional().describe("Only report what would be cut."),output:Qt.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:Qt.boolean().optional().describe("Replace an existing output (default false).")};function sw(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:nT,annotations:C},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??an,a=e.keepSec??ai,c=o.audioCodec!==null,u=(e.useAudio??!0)&&c,{idle:d,rule:p}=await tc(n,e.input,{minIdleSec:s,useAudio:u,duration:i,sensitivity:e.sensitivity,ignoreRegions:e.ignoreRegions,basis:e.basis,timeoutMs:de(i),signal:r.signal}),f=Ra(d,s,a),m=e.action==="speed",h=e.factor??ci,b=f.map(T=>({...T,factor:h})),w=Number((m?cn(b):f.reduce((T,R)=>T+(R.end-R.start),0)).toFixed(2)),g={cuts:f,...m?{action:"speed",factor:h}:{},removedSec:w,originalSec:Number(i.toFixed(2)),newDurationSec:Number((i-w).toFixed(2)),idleRule:p};if(e.dryRun||f.length===0)return S({...g,...f.length===0?{note:"No idle stretches found; nothing to cut."}:{dryRun:!0}});let y=V(e.input),v=B(e.output,"trimmed-idle",y,{overwrite:e.overwrite}),x=m?Ca(e.input,v,b,{withAudio:c,fps:o.fps}):Pa(e.input,v,f,c);return await U(x,{output:v,durationSec:i-w,inputDurationSec:i,extra:r}),S({outputPath:v,...g})}catch(n){return E(n)}})}import{z as tt}from"zod";import{existsSync as mw,readFileSync as lT,writeFileSync as pT}from"node:fs";var oT=["um","umm","uh","uhh","uhm","erm","er","ah","hmm","hm","mm","mhm"],aw=.5,uw=t=>t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),Ir=t=>Number(t.toFixed(3));function lw(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:uw(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 iT=t=>t.flatMap((e,r)=>e.norm?[r]:[]);function sT(t,e){let r=e.split(/\s+/).map(uw).filter(Boolean);if(r.length===0)throw new l(`Quote "${e}" has no words to match.`);let n=iT(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 aT(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:Ir(o.start),end:Ir(i.end),text:t.slice(e,n+1).map(s=>s.raw).join(" "),exact:o.first&&i.last}}function cT(t){let e=[...t].filter(n=>n.end-n.start>.001).sort((n,o)=>n.start-o.start),r=[];for(let n of e){let o=r[r.length-1];o&&n.start<=o.end+.01?(n.end>o.end&&(o.end=n.end),o.text.includes(n.text)||(o.text=`${o.text} ${n.text}`),o.exact&&=n.exact):r.push({...n})}return r}function uT(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 pw(t,e){let r=lw(t),n=[];for(let i of e.remove??[]){if(typeof i=="number"){let a=uT(t,i);n.push({start:Ir(a.start),end:Ir(a.end),text:a.text.replace(/\s+/g," "),exact:!0});continue}let s=sT(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(aT(r,...s[0]))}let o=0;if(e.fillers){let i=new Set(oT);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-aw),d=Math.min(t[s.cue+1]?.start??1/0,c.end+aw);n.push({start:Ir(Math.min(u,c.start)),end:Ir(Math.max(d,c.end)),text:r.filter(p=>p.cue===s.cue).map(p=>p.raw).join(" "),exact:!0})})}return{cuts:cT(n),skippedFillers:o}}function cw(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 dw(t,e){let r=lw(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=Ir(cw(i.start,e)),p=Ir(cw(i.end,e));p>d&&o.push({start:d,end:p,text:u})}),o}var dT={input:tt.string().min(1).describe("Source video path."),srt:tt.string().min(1).describe("Its .srt (transcribe; words: true for word timing)."),remove:tt.array(tt.union([tt.number().int().min(0).max(99999),tt.string().min(1)])).optional().describe("Cue numbers as the .srt numbers them, or transcript text quoted exactly (must occur once)."),fillers:tt.boolean().optional().describe("Also cut fillers (um, uh...) that have their own cue."),dryRun:tt.boolean().optional().describe("Only report the cuts."),output:tt.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:tt.boolean().optional().describe("Replace an existing output (default false).")};function fw(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:dT,outputSchema:N({cuts:tt.array(tt.unknown()),removedSec:tt.number()}),annotations:C},async(e,r)=>{try{k();for(let b of[e.input,e.srt])if(!mw(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=gt(qe(lT(e.srt,"utf8"),{index:!0}));if(i.length===0)throw new l(`No cues in ${e.srt}.`);let{cuts:s,skippedFillers:a}=pw(i,{remove:e.remove,fillers:e.fillers});if(s.length>Qn)throw new l(`Too many cuts (${s.length}, max ${Qn}); cut in batches.`);let c=Number(s.reduce((b,w)=>b+Math.min(w.end,o)-Math.min(w.start,o),0).toFixed(2)),u=dw(i,s),d=[s.length===0&&"Nothing matched; nothing to cut.",a>0&&`${a} filler(s) inside longer cues were kept; transcribe with words: true to cut them.`,s.some(b=>!b.exact)&&"Some edges were estimated inside a cue; transcribe with words: true for word timing."].filter(Boolean),p={cuts:s,removedSec:c,originalSec:Number(o.toFixed(2)),newDurationSec:Number((o-c).toFixed(2)),...d.length?{note:d.join(" ")}:{}};if(e.dryRun||s.length===0){let b=u.map(w=>w.text.replace(/\n/g," ")).join(" ");return S({...p,...s.length?{dryRun:!0}:{},text:b.length>4e3?`${b.slice(0,4e3)}\u2026`:b})}let f=V(e.input),m=B(e.output,"cut-transcript",f,{overwrite:e.overwrite}),h=m.replace(/\.[^.\\/]+$/,"")+".srt";if(!e.overwrite&&mw(h))throw new l(`Output already exists: ${h}. Pass overwrite: true to replace it.`);return await U(Pa(e.input,m,s,n.audioCodec!==null),{output:m,durationSec:o-c,inputDurationSec:o,extra:r}),pT(h,at(u)),S({outputPath:m,srtPath:h,...p})}catch(n){return E(n)}})}import{z as ln}from"zod";var mT={input:ln.string().min(1).describe("Path to the source video or image (png/jpg; time ranges are ignored for an image)."),regions:ln.array(_n).min(1).describe("Pixel rectangles (x, y, width, height), each optionally limited to start..end seconds."),style:ln.enum(Hi).optional().describe("box (default): irreversible fill; blur/pixelate are partially recoverable."),pad:ln.number().int().nonnegative().optional().describe("Grow each region by this many px (default 0)."),color:ln.string().optional().describe("Box fill color (default black)."),output:ln.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:ln.boolean().optional().describe("Replace an existing output (default false).")};function hw(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:mT,outputSchema:Y,annotations:C},async(e,r)=>{try{k(),F(e.input);let{width:n,height:o,durationSec:i}=await L(e.input),{still:s,ext:a}=Gi(e.input,e.output),c=B(e.output,"redact",a,{overwrite:e.overwrite,anyContainer:!0}),u=Jp(e.input,c,e.regions,{style:e.style,pad:e.pad,color:e.color},{width:n,height:o},s);return await U(u,{output:c,durationSec:s?null:i,extra:r}),S({outputPath:c,regions:e.regions.length,style:e.style??"box"})}catch(n){return E(n)}})}import{z as rc}from"zod";function gw(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:rc.array(rc.unknown()),loopbackDevice:rc.string().nullable(),note:rc.string()}),annotations:ge},async()=>{try{k();let e=await iu(!0),r=ou(e);return S({devices:e,loopbackDevice:r,note:r?`Pass "${r}" as the audio device to capture system audio.`:`No loopback device detected. ${Wo}`})}catch(e){return E(e)}})}import{z as fe}from"zod";function ww(t){return t.hwnd!==void 0?`window:hwnd=${t.hwnd}`:`window:${t.title}`}function fT(t){let e=/^.*?[.!?](?=\s|$)/.exec(t);return e?e[0]:t}function bw(t,e,r){try{return zc(t,ww(e).slice(7),{allowCloaked:r,exactOnly:!0}),{ok:!0}}catch(n){return{ok:!1,reason:fT(j(n))}}}function yw(t,e,r){let n=r.filter??{},o=n.exe?Uc(`exe=${n.exe}`):null,i=o?.kind==="exe"?o.exe:null,s=n.titleContains?.trim().toLowerCase()||null,a=_o(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=bw(e,d,!1),f=r.wgcAvailable&&d.hwnd!==void 0?bw(e,d,!0):{ok:!1};n.capturableOnly&&!p.ok&&!f.ok||u.push({target:ww(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 hT={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.")},Rl=fe.object({x:fe.number(),y:fe.number(),width:fe.number(),height:fe.number()}),gT=N({full:fe.looseObject({target:fe.literal("full"),bounds:Rl}),monitors:fe.array(fe.looseObject({target:fe.string(),index:fe.number(),primary:fe.boolean(),bounds:Rl,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:Rl,minimized:fe.boolean(),cloaked:fe.boolean(),capturable:fe.boolean(),wgcCapturable:fe.boolean()})),wgcAvailable:fe.boolean(),note:fe.string()});function xw(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:hT,outputSchema:gT,annotations:ge},async e=>{try{let[r,n]=await Promise.all([mr(),Hc()]),o=yw(r,n,{wgcAvailable:pr(),filter:{exe:e.exe,titleContains:e.titleContains,capturableOnly:e.capturableOnly}});return S({...o,note:'Pass a target string unchanged. A window handle lasts until the app closes the window; list again after an app restarts, or target it by window:exe=<app.exe>. A window with capturable false but wgcCapturable true needs backend: "wgc".'})}catch(r){return E(r)}})}import{existsSync as ic}from"node:fs";import{dirname as vT,join as Tl}from"node:path";import{z as me}from"zod";var Sw=200,vw=1e3,nc=.5,oc=3,pn=t=>Math.round(t*1e3)/1e3;function kw(t,e){if(t.length===0)throw new l("lines is empty: give at least one { t | marker, text }.");if(t.length>Sw)throw new l(`At most ${Sw} 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>vw)throw new l(`lines[${o}] is ${i.length} characters; at most ${vw} 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:pn(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:pn(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 Ew(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 (${pn(e)}s) and is not heard.`):s&&i>s.t+.05?r.push(`Line at ${n.t}s ${a} runs ${pn(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 ${pn(i-e)}s past the end of the video and is cut off.`)}),r}function _w(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:pn(i),text:r.text}}).filter(r=>r.end>r.start)}function Rw(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 Tw(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=pn(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=Ui(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),...Ka(r),.../\.(mp4|mov|m4a)$/i.test(r)?["-movflags","+faststart"]:[],r]}var bT=3e4,wT=1e4,$w=3e4,Mw=t=>Array.isArray(t)?t:t==null?[]:[t];function Aw(t){return Mw(t.voices).map(e=>({name:String(e.name??""),language:String(e.language??""),gender:String(e.gender??"")}))}function yT(t){return{script:ST,payload:JSON.stringify(t)}}async function Cw(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}=yT(t),i="list"in t,s=await pt(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: ${j(a)}`)}}async function xT(t){let e=await Cw({list:!0},dr(15e3),t);if(e.error)throw new l(`Windows speech is unavailable: ${e.error}`);return Aw(e)}async function Pw(){if(process.platform!=="win32")return{available:!1,voices:[],error:"Windows speech is available on Windows only."};try{let t=(await xT()).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:j(t)}}}async function Iw(t,e){let r=e.rate??1;if(!Number.isFinite(r)||r<nc||r>oc)throw new l(`rate must be between ${nc} and ${oc} (1 is normal speed).`);let n=await Cw({voice:e.voice??null,rate:r,items:t},dr(bT+t.length*wT),e.signal);if(n.error){let o=Aw(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 Mw(n.results).forEach((o,i)=>{if(o.error)throw new l(`Could not synthesize line ${i+1}: ${o.error}`)}),String(n.voice??"")}var ST=`
|
|
342
342
|
$ErrorActionPreference = 'Stop'
|
|
343
343
|
function Out($o) { ConvertTo-Json -InputObject $o -Depth 5 -Compress }
|
|
344
344
|
try {
|
|
@@ -362,7 +362,7 @@ try {
|
|
|
362
362
|
$results = foreach ($item in @($req.items)) {
|
|
363
363
|
try {
|
|
364
364
|
$task = $asTask.MakeGenericMethod([Windows.Media.SpeechSynthesis.SpeechSynthesisStream]).Invoke($null, @($synth.SynthesizeTextToStreamAsync([string]$item.text)))
|
|
365
|
-
if (-not $task.Wait(${
|
|
365
|
+
if (-not $task.Wait(${$w})) { throw "The speech engine did not answer within ${$w/1e3} s." }
|
|
366
366
|
$stream = $task.Result
|
|
367
367
|
$in = [System.IO.WindowsRuntimeStreamExtensions]::AsStreamForRead($stream)
|
|
368
368
|
$fs = [System.IO.File]::Create([string]$item.path)
|
|
@@ -372,10 +372,12 @@ try {
|
|
|
372
372
|
}
|
|
373
373
|
Out ([pscustomobject]@{ voice = $synth.Voice.DisplayName; results = @($results) })
|
|
374
374
|
} catch { Out ([pscustomobject]@{ error = $_.Exception.Message }) }
|
|
375
|
-
`;var YT=xt(),xw=de.looseObject({found:de.boolean(),path:de.string().nullable(),version:de.string().nullable(),major:de.number().nullable()}),KT=B({ok:de.boolean(),problems:de.array(de.string()),server:de.looseObject({version:de.string(),node:de.string(),platform:de.string(),arch:de.string()}),ffmpeg:xw.extend({meetsFfmpeg8:de.boolean().nullable()}),ffprobe:xw,filters:de.record(de.string(),de.boolean()),devices:de.looseObject({gdigrab:de.boolean(),dshow:de.boolean()}),wgc:de.looseObject({available:de.boolean()}),ocr:de.looseObject({available:de.boolean(),language:de.string().nullable(),languages:de.array(de.string())}),storage:de.looseObject({home:de.string(),homeExists:de.boolean()}),env:de.record(de.string(),de.string().nullable())});function VT(t){let e=E(t).content[0];return e?.type==="text"?e.text.replace(/\s*\n+\s*/g," "):String(t)}function Sw(t){let e=ua(t),r=ca(e??"");return{found:e!==null,path:e!==null?gg(t):null,version:r.version,major:r.major,...r.inferred?{majorInferred:!0}:{}}}function vw(t){t.registerTool("doctor",{title:"Check Setup",description:`Check the setup: ffmpeg/ffprobe (FFmpeg ${Yr}+?), optional filters, capture devices, Windows OCR, settings, and enabled toolsets; \`problems\` says what is missing and how to fix it. Call on first use or when a tool reports a missing feature.`,inputSchema:{},outputSchema:KT,annotations:fe},async()=>{try{let e=[],r=null;try{r=Mc()}catch(w){e.push(VT(w))}let n=Sw(r?.ffmpeg??(process.env.FFMPEG_PATH?.trim()||"ffmpeg")),o=Sw(r?.ffprobe??(process.env.FFPROBE_PATH?.trim()||"ffprobe")),i=n.major===null?null:n.major>=Yr;r&&i===!1&&e.push(`FFmpeg ${n.version} is older than ${Yr}: transcribe and backend "wgc" need FFmpeg ${Yr}+. Windows: \`winget install Gyan.FFmpeg\`.`);let s={},a={gdigrab:!1,dshow:!1};if(r){for(let g of yg)s[g.filter]=g.filter==="gfxcapture"?cr():Ve(g.filter),!s[g.filter]&&!(g.filter==="gfxcapture"&&process.platform!=="win32")&&e.push(`No ${g.filter} filter: ${g.tools} unavailable (needs ${g.why}).`);let w=fg(hg(r.ffmpeg)??"");a={gdigrab:w.includes("gdigrab"),dshow:w.includes("dshow")},process.platform==="win32"&&!a.gdigrab&&e.push("This ffmpeg has no gdigrab device: screenshot and start_recording cannot capture the screen.")}process.platform!=="win32"&&e.push("Not Windows: capture (screenshot, start_recording, list_targets) and OCR are unavailable; the watch and edit tools work.");let c=r?{ddagrab:process.platform==="win32"&&Ve("ddagrab"),encoders:await zc(r.ffmpeg)}:null,[u,d]=await Promise.all([vr(),ww()]);process.platform==="win32"&&!u.available&&e.push(`Windows OCR unavailable: find_text cannot read the screen. ${u.error??"Install an OCR language (Settings > Time & language > Language)."}`),process.platform==="win32"&&!d.available&&e.push(`Windows speech unavailable: narrate cannot speak. ${d.error??""} Install a voice (Settings > Time & language > Speech).`.replace(/\s+/g," "));let p=wg(),f=p.SCREENCAST_WHISPER_MODEL;f&&!Qa(f)&&e.push(`SCREENCAST_WHISPER_MODEL points at a missing file: ${f}`);let m=Pe();for(let w of go())Qa(w)||e.push(`SCREENCAST_ALLOWED_DIRS names a missing folder: ${w}`);let h=bi(p.SCREENCAST_TOOLSETS??void 0);h.unknown.length>0&&e.push(`SCREENCAST_TOOLSETS names unknown toolsets (ignored): ${h.unknown.join(", ")}.`),e.push(...bg());let b=Qa(m)?await iw(m):{freeBytes:await Sl(JT(m)),bytes:null};return b.freeBytes!==null&&b.freeBytes<nw&&e.push(`Only ${sw(b.freeBytes)} free on the drive holding SCREENCAST_HOME: a long recording can fail partway. Delete old recordings (delete_recording) or set SCREENCAST_HOME on a bigger drive.`),S({ok:e.length===0,problems:e,server:{version:YT,node:process.version,platform:process.platform,arch:process.arch},ffmpeg:{...n,meetsFfmpeg8:i},ffprobe:o,filters:s,devices:a,wgc:{available:s.gfxcapture===!0},...c?{gpu:c}:{},ocr:u,tts:d,storage:{home:m,homeExists:Qa(m),freeBytes:b.freeBytes,...b.bytes?{bytes:b.bytes}:{},recordings:vl(m,"recordings"),screenshots:vl(m,"screenshots"),edits:vl(m,"edits"),allowedOutputDirs:Or()},env:p,toolsets:{enabled:h.enabled,available:["all",...gi]}})}catch(e){return E(e)}})}import{z as eo}from"zod";var QT={inputA:eo.string().min(1).describe("Outgoing video."),inputB:eo.string().min(1).describe("Incoming video."),transition:eo.string().optional().describe("xfade name (default fade): fade, wipeleft, slideup, circleopen, dissolve, ..."),duration:eo.number().positive().optional().describe(`Transition length in seconds (default ${jn}).`),output:eo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:eo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function $w(t){t.registerTool("xfade_transition",{title:"Crossfade Transition",description:"Join two videos with an xfade transition (audio crossfaded); they need not match in size, fps, or audio. For more clips use assemble_highlights.",inputSchema:QT,outputSchema:K,annotations:I},async(e,r)=>{try{k();for(let p of[e.inputA,e.inputB])O(p);let[n,o]=await Promise.all([W(e.inputA),W(e.inputB)]),i=Vr(n),s=Vr(o);if(i===null||s===null)throw new l(`Could not read duration of ${i===null?e.inputA:e.inputB}.`);let a=[n.audioCodec!==null,o.audioCodec!==null],c=a[0]||a[1],u=j(e.output,"xfade",".mp4",{overwrite:e.overwrite}),d=Ag(e.inputA,e.inputB,[i,s],u,{transition:e.transition,duration:e.duration},a);return await U(d,{output:u,durationSec:i+s,extra:r}),S({outputPath:u,audio:c})}catch(n){return E(n)}})}import{z as Kt}from"zod";var ZT={clips:Kt.array(Kt.string().min(1)).min(2).describe("Clip paths, in order."),transition:Kt.string().optional().describe("cut (default) or an xfade name (fade, wipeleft, slideup, ...)."),duration:Kt.number().positive().optional().describe(`Transition seconds (default ${jn}).`),width:Kt.number().int().positive().optional().describe("Common output width (default 1920)."),height:Kt.number().int().positive().optional().describe("Common output height (default 1080)."),fps:Kt.number().int().positive().optional().describe("Common output fps (default 30)."),output:Kt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Kt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function kw(t){t.registerTool("assemble_highlights",{title:"Assemble Highlights",description:"Stitch clips (including title cards) into one video with cuts or xfade transitions; they need not match in size, fps, or audio.",inputSchema:ZT,outputSchema:K,annotations:I},async(e,r)=>{try{k();for(let c of e.clips)O(c);let n=await Promise.all(e.clips.map(c=>W(c))),o=n.map(c=>Vr(c)??0),i=n.map(c=>c.audioCodec!==null),s=j(e.output,"highlights",".mp4",{overwrite:e.overwrite}),a=Yo(e.clips,o,s,{transition:e.transition,duration:e.duration,width:e.width,height:e.height,fps:e.fps},i);return await U(a,{output:s,durationSec:o.reduce((c,u)=>c+u,0)||null,extra:r}),S({outputPath:s,clips:e.clips.length,transition:e.transition??"cut",audio:i.some(Boolean)})}catch(n){return E(n)}})}import{z as ht}from"zod";import{writeFileSync as eR,rmSync as tR}from"node:fs";var rR={text:ht.string().min(1).describe("Title text. Multiple lines are allowed (use \\n)."),duration:ht.number().positive().optional().describe("Card length in seconds (default 3)."),width:ht.number().int().positive().optional().describe("Card width (default 1920)."),height:ht.number().int().positive().optional().describe("Card height (default 1080)."),fps:ht.number().int().positive().optional().describe("Card fps (default 30)."),bg:ht.string().optional().describe("Background color (default black)."),fontColor:ht.string().optional().describe("Text color (default white)."),fontSize:ht.number().int().positive().optional().describe("Text size in px (default 96)."),bold:ht.boolean().optional().describe("Use the bold weight (default true)."),fontFile:_r,output:ht.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ht.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ew(t){t.registerTool("title_card",{title:"Title Card",description:"Generate a title card clip (centered text on a solid background, silent audio track) to stitch in with assemble_highlights. Uncoverable characters are reported in warnings.",inputSchema:rR,outputSchema:K,annotations:I},async(e,r)=>{try{k();let n=j(e.output,"title",".mp4",{overwrite:e.overwrite}),o=kt(e.text,{weight:e.bold===!1?"regular":"bold",fontFile:e.fontFile}),i=He(".txt");eR(i,e.text);try{let s=Mg(i,o.fontFile,n,{duration:e.duration,width:e.width,height:e.height,fps:e.fps,bg:e.bg,fontColor:e.fontColor,fontSize:e.fontSize});await U(s,{output:n,durationSec:e.duration??Ku,extra:r})}finally{tR(i,{force:!0})}return S({outputPath:n,...(o.fallback||e.fontFile)&&{fontFile:o.fontFile},...o.warning&&{warnings:[o.warning]}})}catch(n){return E(n)}})}import{z as Mr}from"zod";var nR={video:Mr.string().min(1).describe("Path to the video."),music:Mr.string().min(1).describe("Music audio file."),musicVolume:Mr.number().nonnegative().optional().describe("0..1 (default 0.25 over existing audio, 0.8 alone)."),fadeIn:Mr.number().nonnegative().optional().describe("Fade-in seconds (default 1)."),fadeOut:Mr.number().nonnegative().optional().describe("Fade-out seconds (default 2)."),duck:Mr.boolean().optional().describe("Duck the music under the original audio (default false)."),output:Mr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Mr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function _w(t){t.registerTool("music_bed",{title:"Add Music Bed",description:"Lay music under a video: looped or trimmed to length, faded, leveled, and mixed with any existing audio. Video is stream-copied.",inputSchema:nR,outputSchema:K,annotations:I},async(e,r)=>{try{k();for(let a of[e.video,e.music])O(a);let n=await W(e.video);if(n.durationSec===null)throw new l(`Could not read duration of ${e.video}.`);let o=Z(e.video),i=j(e.output,"music",o,{overwrite:e.overwrite}),s=Cg(e.video,e.music,i,n.durationSec,n.audioCodec!==null,{musicVolume:e.musicVolume,fadeIn:e.fadeIn,fadeOut:e.fadeOut,duck:e.duck});return await U(s,{output:i,durationSec:n.durationSec,extra:r}),S({outputPath:i,mixedWithOriginal:n.audioCodec!==null})}catch(n){return E(n)}})}import{z as gt}from"zod";import{existsSync as oR,mkdtempSync as iR,readFileSync as sR,rmSync as aR,writeFileSync as cR}from"node:fs";import{tmpdir as uR}from"node:os";import{join as Tw}from"node:path";var lR={video:gt.string().min(1).describe("Path to the video."),lines:gt.array(gt.object({t:gt.number().nonnegative().optional().describe("Seconds."),marker:gt.string().optional().describe("Or a marker label."),text:gt.string().min(1)})).min(1),voice:gt.string().optional().describe("Voice name or part (doctor lists them)."),rate:gt.number().min(Ka).max(Va).optional().describe("Default 1."),duck:gt.boolean().optional().describe("Duck the original audio (default true)."),output:gt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:gt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Rw(t){t.registerTool("narrate",{title:"Narrate",description:"Offline voiceover with the built-in Windows voices: speaks each line at its time or marker over the audio, plus an SRT.",inputSchema:lR,outputSchema:K,annotations:I},async(e,r)=>{let n=null;try{k(),O(e.video);let o=await W(e.video);if(o.durationSec===null)throw new l(`Could not read duration of ${e.video}.`);let s=e.lines.some(w=>w.marker!==void 0)?(await gr(e.video,r.signal)).markers:[],a=lw(e.lines,s),c=j(e.output,"narrated",Z(e.video),{overwrite:e.overwrite}),u=c.replace(/\.[^./\\]+$/,"")+".srt";if(!e.overwrite&&oR(u))throw new l(`Output already exists: ${u}. Pass overwrite: true to replace it.`);n=iR(Tw(uR(),"screencast-tts-"));let d=a.map((w,g)=>Tw(n,`line-${g}.wav`)),p=await yw(a.map((w,g)=>({text:w.text,path:d[g]})),{voice:e.voice,rate:e.rate,signal:r.signal}),f=a.map((w,g)=>({...w,durationSec:mw(sR(d[g]))})),m=pw(f,o.durationSec),h=fw(e.video,d,c,f,o.durationSec,{hasAudio:o.audioCodec!==null,channels:o.channels,duck:e.duck});await U(h,{output:c,durationSec:o.durationSec,extra:r}),cR(u,it(dw(f,o.durationSec)));let b=We(e.video);return b.length>0&&hr(c,b),S({outputPath:c,srtPath:u,voice:p,lines:f.map(w=>({t:w.t,durationSec:Math.round(w.durationSec*100)/100})),mixedWithOriginal:o.audioCodec!==null,...m.length?{warnings:m}:{}})}catch(o){return E(o)}finally{n&&aR(n,{recursive:!0,force:!0})}})}import{z as ci}from"zod";var pR={input:ci.string().min(1).describe("Path to the source video."),aspect:ci.enum(Un).describe("Target aspect ratio."),fit:ci.enum(la).optional().describe("pad (default): letterbox, nothing lost. crop: fill and center-crop."),output:ci.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ci.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Aw(t){t.registerTool("reframe",{title:"Reframe Aspect Ratio",description:"Re-aspect a video to 16:9, 9:16, 1:1, or 4:5 by padding or cropping.",inputSchema:pR,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=Z(e.input),o=j(e.output,"reframe",n,{overwrite:e.overwrite}),i=Pg(e.input,o,e.aspect,e.fit??"pad");return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o,aspect:e.aspect,fit:e.fit??"pad"})}catch(n){return E(n)}})}import{z as Je}from"zod";import{z as sn}from"zod";import{existsSync as dR,readFileSync as mR}from"node:fs";var Vt=.6,li=6,Za=2.5;function ec(t,e,r,n=li){if(t.length===0)throw new l("Give at least one keyframe.");let i=[...t].sort((s,a)=>s.t-a.t).map(s=>{if(!Number.isFinite(s.t)||s.t<0)throw new l("Keyframe t must be a non-negative number.");if(s.full||s.width===void 0||s.height===void 0)return{t:s.t,z:1,cx:e/2,cy:r/2};if(!(s.width>0)||!(s.height>0))throw new l("Keyframe width and height must be positive.");let a=Math.max(1,Math.min(n,e/s.width,r/s.height));return{t:s.t,z:a,cx:(s.x??0)+s.width/2,cy:(s.y??0)+s.height/2}});return i[0]&&i[0].t>0&&i.unshift({t:0,z:1,cx:e/2,cy:r/2}),i}var tt=t=>Number(t.toFixed(4)).toString();function $l(t,e,r){let[n,...o]=t;if(!n)throw new l("Give at least one keyframe.");let i=[tt(n[e])],s=n;for(let a of o){let c=s[e],u=a[e],d=s.t;if(s=a,c===u)continue;let p=a.t,f=Math.max(.001,Math.min(r,p-d)),m=`clip((it-${tt(p-f)})/${tt(f)},0,1)`;i.push(`(${tt(u-c)})*${m}*${m}*(3-2*${m})`)}return At(i)}function _l(t,e,r=Vt){let{width:n,height:o,fps:i}=e,s=n<=1920?2:1,a=$l(t,"z",r),c=$l(t,"cx",r),u=$l(t,"cy",r);return`fps=${tt(i)},scale=${n*s}:${o*s},zoompan=z='${a}':x='clip((${c})*${s}-iw/zoom/2,0,iw-iw/zoom)':y='clip((${u})*${s}-ih/zoom/2,0,ih-ih/zoom)':d=1:s=${n}x${o}:fps=${tt(i)}`}function Mw(t,e,r,n,o=Vt,i="standard",s){let{width:a,height:c,fps:u}=n,d=_l(r,n,o);if(!s||s.clicks.length===0)return["-y","-i",t,"-vf",d,...Re(i),"-c:a","copy",e];let p=["[0:v]null[in]",...gR(s.clicks,a,c,u,s.color),`[out]${d}[v]`].join(";");return["-y","-i",t,"-filter_complex",p,"-map","[v]","-map","0:a?",...Re(i),"-c:a","copy",e]}function Cw(t,e,r,n,o={}){let i=o.step??.25,s=o.holdSec??2,a=o.maxZoom??Za,c=o.globalFraction??.3,u=o.transition??Vt,d=r/t,p=r/a,f=n/a,m=[],h=null,b=()=>{h&&m.push(h),h=null},w=null,g=0;return{push:x=>{let R=w;if(w=x,!R){g=1;return}let T=g++*i,M=Tt(R,x,t,e,{scale:d});if(M.regions.length===0){h&&T-h.last>s&&b();return}if(M.changedFraction>c){b();return}let H=El(M.regions);h&&T-h.last<=s&&fR(h.box,H,r,n)?(h.box=El([h.box,H]),h.last=T):(b(),h={start:T,last:T,box:H})},finish:()=>{b();let x=[],R=0;for(let T of m){let M=Pw(T.box,r,n,p,f),H=Math.max(T.start,R+u),G=Math.max(T.last+s,H+u);x.push({t:ui(H),...M},{t:ui(G),full:!0}),R=G}return x}}}var ui=t=>Math.round(t*100)/100;function El(t){let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,width:n-e,height:o-r}}function fR(t,e,r,n){let o=El([t,e]);return o.width<=r/2&&o.height<=n/2}function Pw(t,e,r,n,o){let i=Math.max(t.width*1.4,n),s=Math.max(t.height*1.4,o),a=e/r;i/s>a?s=i/a:i=s*a,i=Math.min(i,e),s=Math.min(s,r);let c=t.x+t.width/2,u=t.y+t.height/2,d=Math.max(0,Math.min(e-i,c-i/2)),p=Math.max(0,Math.min(r-s,u-s/2));return{x:Math.round(d),y:Math.round(p),width:Math.round(i),height:Math.round(s)}}function Iw(t,e,r){return["-v","error","-i",t,"-an","-vf",`fps=${tt(1/r)},scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function tc(t,e,r,n={}){let o=n.holdSec??2,i=n.maxZoom??Za,s=n.transition??Vt,a=e/i,c=r/i,u=Math.min(e,r)*.05,d=[...t].sort((h,b)=>h.t-b.t),p=[],f=0,m=-1/0;for(let h of d){let b=Pw({x:h.x-u,y:h.y-u,width:2*u,height:2*u},e,r,a,c),w=p[p.length-1];if(w&&!w.full&&h.t-m<=o&&hR(w,h)){m=h.t;continue}if(h.t-m>o&&p.length>0){let y=Math.max(m+o,f+s);p.push({t:ui(y),full:!0}),f=y}let g=Math.max(h.t,f+s);p.push({t:ui(g),...b}),f=g,m=h.t}return p.length>0&&p.push({t:ui(Math.max(m+o,f+s)),full:!0}),p}function hR(t,e){let r=t.width*.15,n=t.height*.15;return e.x>=t.x+r&&e.x<=t.x+t.width-r&&e.y>=t.y+n&&e.y<=t.y+t.height-n}var kl=.6,rc="#FF4545";function Tl(t,e){return Math.max(40,2*Math.round(Math.min(t,e)*.045))}function gR(t,e,r,n,o){let i=Tl(e,r),s=i/2,a=Math.max(3,Math.round(i/10)),c=s*.3,u=s-a/2-c,d=[],p="[in]";return t.forEach((f,m)=>{let h=`if(lt(abs(hypot(X-${s},Y-${s})-(${tt(c)}+${tt(u)}*T/${kl})),${a/2}),255*min(1,2-2*T/${kl}),0)`;d.push(`color=c=${o}:s=${i}x${i}:r=${tt(n)}:d=${kl},format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${h}',setpts=PTS+${tt(f.t)}/TB[ring${m}]`);let b=m===t.length-1?"[out]":`[r${m}]`;d.push(`${p}[ring${m}]overlay=x=${tt(f.x-s)}:y=${tt(f.y-s)}:eof_action=pass${b}`),p=`[r${m}]`}),d}function pi(t){return dR(t)?ze(mR(t,"utf8")).filter(e=>e.type==="down"&&e.inFrame).map(e=>({t:e.t,x:e.x,y:e.y})):null}var nc=sn.object({t:sn.number().nonnegative(),x:sn.number().optional(),y:sn.number().optional(),width:sn.number().positive().optional(),height:sn.number().positive().optional(),full:sn.boolean().optional()});var Fw=200,bR={input:Je.string().min(1).describe("Path to the source video."),keyframes:Je.array(nc).max(100).optional().describe("Views reached by time t: a source rectangle (x, y, width, height), or { t, full: true } to zoom out. Omit to plan them (see follow)."),follow:Je.enum(["auto","clicks","changes"]).optional().describe("Without keyframes: clicks (from the events log of start_recording events: true) or changes (where the screen changed). auto (default): clicks if logged, else changes."),events:Je.string().optional().describe("Events log (default: the input's .events.jsonl); must match the input's timing and size, so use the original recording."),highlightClicks:Je.boolean().optional().describe("Ring each logged click (default false)."),highlightColor:Je.string().optional().describe("Ring color (default #FF4545)."),transitionSec:Je.number().positive().max(5).optional().describe(`How long each zoom/pan eases (default ${Vt}).`),maxZoom:Je.number().min(1).max(li).optional().describe(`Auto mode: the furthest it zooms in (default ${Za}).`),holdSec:Je.number().positive().max(30).optional().describe("Auto mode: stay zoomed this long after activity (default 2)."),dryRun:Je.boolean().optional().describe("Return the planned keyframes only (editable, pass back)."),output:Je.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Je.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ow(t){t.registerTool("zoom",{title:"Zoom and Pan",description:"Smooth animated zoom-and-pan into the action and back out, from keyframes or planned from logged clicks or screen changes.",inputSchema:bR,outputSchema:B({keyframes:Je.array(Je.unknown())}),annotations:I},async(e,r)=>{try{k(),O(e.input);let n=await W(e.input),{width:o,height:i,durationSec:s}=n;if(!o||!i)throw new l(`Could not read the size of ${e.input}.`);let a=n.fps??30,c=e.transitionSec??Vt,u=e.events??ke(e.input).jsonl,d=pi(u);if(e.events&&!d)throw new l(`No event log at ${e.events}.`);if((e.follow==="clicks"||e.highlightClicks)&&!d)throw new l(`No event log for ${e.input} (looked for ${u}). Record with start_recording events: true, or pass events: <path to .events.jsonl>.`);let p=Be(e.highlightColor??rc,"highlightColor"),f=e.keyframes,m=!f,h=e.follow==="clicks"||e.follow!=="changes"&&d&&d.length>0?"clicks":"changes";if(!f&&h==="clicks"&&(f=tc(d??[],o,i,{holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c}),f.length===0))return S({keyframes:[],follow:h,note:"The event log has no clicks inside the frame; nothing written."});if(!f){let v=tg(o,i),x=.25,R=Cw(v.width,v.height,o,i,{step:x,holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c});if(await ji(Iw(e.input,v,x),v.width*v.height,T=>R.push(T),pe(s),{signal:r.signal}),f=R.finish(),f.length===0)return S({keyframes:[],note:"No localised changes found to zoom into; nothing written."})}if(e.dryRun)return S({planned:m,...m?{follow:h}:{},keyframes:f,transitionSec:c});if(e.highlightClicks&&d&&d.length>Fw)throw new l(`${d.length} clicks is more than ${Fw} rings; trim the video or the event log first.`);let b=ec(f,o,i),w=Z(e.input),g=j(e.output,"zoom",w,{overwrite:e.overwrite}),y=e.highlightClicks?{clicks:d??[],color:p}:void 0;return await U(Mw(e.input,g,b,{width:o,height:i,fps:a},c,"standard",y),{output:g,durationSec:s,extra:r}),S({outputPath:g,planned:m,...m?{follow:h}:{},keyframes:f,...y?{ringedClicks:y.clicks.length}:{}})}catch(n){return E(n)}})}import{z as F}from"zod";import{dirname as RR,join as Cr}from"node:path";import{existsSync as sc,mkdtempSync as Gw,readFileSync as qw,rmSync as Xw,writeFileSync as di}from"node:fs";import{tmpdir as Jw}from"node:os";var to=30,Ct=t=>Math.round(t*1e3)/1e3;function Rl(t,e){let r=[...t],n=r.indexOf("-af");return n!==-1&&e.audio.length>0&&(r[n+1]=`${e.audio.join(",")},${r[n+1]}`),r.splice(r.indexOf("-i"),0,...e.seek),r}function Nw(t,e,r){let n=e.slice(r);return n.length>0?cs(t,n):[...t]}function oc(t,e,r,n,o={},i="standard",s={}){if(r.length===0)throw new l("Give at least one step.");if(r.length>to)throw new l(`At most ${to} steps.`);r.forEach(($,J)=>{if(($.op==="export_preset"||$.op==="export_gif")&&J!==r.length-1)throw new l(`${$.op} must be the last step (it is step ${J+1} of ${r.length}).`)});let a=r.findIndex($=>$.op==="zoom"),c=a===-1?-1:r.findIndex(($,J)=>J>a&&$.op==="redact");if(c!==-1)throw new l(`step ${c+1}: redact comes after zoom (step ${a+1}), which moves the content under a fixed box. Put redact before zoom, in the source's coordinates.`);let u=r.some($=>$.op==="redact");if(r.filter($=>$.op==="cut_idle").length>1)throw new l("Use at most one cut_idle step.");let d=n.width,p=n.height,f=n.fps,m=n.durationSec,h=[],b=[],w=1,g=[],y=[],v=!1,x="[0:v]",R=null,T,M=[],H=[],G=[],L=[],C={sx:1,sy:1,ox:0,oy:0},ne=($,J)=>{if(!Number.isFinite($.start)||$.start<0)throw new l(`step ${J}: trim start must be a non-negative number.`);if($.end===void 0==($.duration===void 0))throw new l(`step ${J}: trim takes end OR duration.`);let N=$.end??$.start+$.duration;if(!(N>$.start))throw new l(`step ${J}: trim end must be after start.`);if(m!==null&&$.start>=m)throw new l(`step ${J}: trim starts at ${$.start}s, but the video is ${Ct(m)}s long at that point.`);return{start:$.start,end:m!==null?Math.min(N,m):N}};r.forEach(($,J)=>{let N=J+1,le=`p${J}`,X=`[${le}]`,ee=_=>{g.push(`${x}${_}${X}`),x=X},ie=_=>G.push({step:J,kind:_,seek:[...h],audio:[...y],ops:[...H]});switch($.op){case"trim":{let{start:_,end:P}=ne($,N);J===0?(h.push("-ss",String(_),"-t",String(Ct(P-_))),M.push(`trim ${_}-${Ct(P)}s: input seek`)):(ee(`trim=start=${_}:end=${Ct(P)},setpts=PTS-STARTPTS`),y.push(`atrim=start=${_}:end=${Ct(P)},asetpts=PTS-STARTPTS`),M.push(`trim ${_}-${Ct(P)}s: trim filter`)),v=!0,m=P-_,H.push({op:"trim",start:_,end:P});break}case"crop":ee(_c($,{width:d,height:p})),C&&(C={...C,ox:C.ox-$.x,oy:C.oy-$.y}),d=$.width,p=$.height,M.push(`crop to ${d}x${p}`);break;case"scale":{let _=Tc($),[P,re]=[d,p];({width:d,height:p}=Ip(d,p,$)),C&&(C={sx:C.sx*d/P,sy:C.sy*p/re,ox:C.ox*d/P,oy:C.oy*p/re}),ee(_),M.push(`scale to ${d}x${p}`);break}case"speed":{if($.factor===void 0==($.segments===void 0))throw new l(`step ${N}: speed takes factor or segments.`);if($.segments){let P=$a($.segments,m),re=ka(P,f);ee(re.video),y.push(re.audio),v=!0;let D=tn(P);m!==null&&(m-=D),H.push({op:"cut",spans:P}),M.push(`speed up ${P.length} range(s), ${Ct(D)}s saved`);break}let _=$.factor;if(!Number.isFinite(_)||_<=0)throw new l(`step ${N}: speed factor must be positive.`);ee(`setpts=PTS/${_}`),y.push(Rc(_)),v=!0,m!==null&&(m/=_),H.push({op:"speed",factor:_}),M.push(`speed x${_}`);break}case"redact":{let{steps:_,out:P}=Ac($.regions,$,{width:d,height:p},x,le);g.push(..._),x=P,M.push(`redact ${$.regions.length} region(s), ${$.style??"box"}`);break}case"callout":{let _=o[J];if(!_)throw new l(`Internal: missing callout assets for step ${N}.`);let{steps:P,out:re,extraInputs:D}=il($.items,_,x,w,le);g.push(...P),b.push(...D),w+=D.length/4,x=re,M.push(`callout ${$.items.length} item(s)`);break}case"reframe":{let _=zn[$.aspect];if(!_)throw new l(`step ${N}: unknown aspect "${$.aspect}".`);ee(`${pa(_.w,_.h,$.fit??"pad")},format=yuv420p`),C=null,d=_.w,p=_.h,M.push(`reframe to ${$.aspect} (${$.fit??"pad"})`);break}case"zoom":{let _=$.transitionSec??Vt,P=$.keyframes,re="";if($.follow==="clicks"){if(P)throw new l(`step ${N}: zoom takes keyframes or follow, not both.`);if(!C)throw new l(`step ${N}: zoom follow "clicks" must come before reframe, backdrop or another zoom; the logged click positions no longer match the frame.`);let D=C,A=s.clicks?.[J];if(!A)throw new l(`Internal: missing clicks for step ${N}.`);let ce=A.flatMap(be=>{let Ee=as(be.t,H),$e=be.x*D.sx+D.ox,Ke=be.y*D.sy+D.oy;return Ee!==null&&$e>=0&&$e<d&&Ke>=0&&Ke<p?[{t:Ee,x:$e,y:Ke}]:[]});P=tc(ce,d,p,{holdSec:$.holdSec,maxZoom:$.maxZoom,transition:_}),re=` from ${ce.length} click(s)`}else if(!P||P.length===0)throw new l(`step ${N}: zoom needs keyframes, or follow: "clicks".`);if(P.length===0){M.push("zoom: no clicks in this part of the video; skipped");break}ee(_l(ec(P,d,p),{width:d,height:p,fps:f},_)),C=null,M.push(`zoom ${P.length} keyframe(s)${re}`);break}case"cut_idle":{if(!s.idle)throw new l(`Internal: missing idle scan for step ${N}.`);let _=Sa(_m(s.idle,H),$.minIdleSec??en,$.keepSec??Vo);if(_.length===0){M.push("cut_idle: no idle stretches here; nothing cut");break}if($.action==="speed"){let D=$.factor??Qo,A=_.map(Ee=>({...Ee,factor:D})),ce=ka(A,f);ee(ce.video),y.push(ce.audio),v=!0;let be=tn(A);m!==null&&(m-=be),H.push({op:"cut",spans:A}),M.push(`cut_idle ${_.length} stretch(es) sped up x${D}, ${Ct(be)}s saved`);break}let P=Zu(_);ee(P.video),y.push(P.audio),v=!0;let re=_.reduce((D,A)=>D+(A.end-A.start),0);m!==null&&(m-=re),H.push({op:"cut",spans:_}),M.push(`cut_idle ${_.length} stretch(es), ${Ct(re)}s removed`);break}case"audio":{if($.normalize===void 0&&$.denoise===void 0)throw new l(`step ${N}: audio needs normalize and/or denoise.`);if(!n.hasAudio){M.push("audio: the input has no audio; skipped");break}let _=s.audio?.[J],P=[];if($.denoise!==void 0&&(_?.floorDb===void 0&&ie("noisefloor"),y.push(wl($.denoise,_?.floorDb??null)),P.push(`denoise ${$.denoise}`)),$.normalize!==void 0&&_?.silent)P.push("silent, not normalized");else if($.normalize!==void 0){let re=Zn($.normalize);_?.loudness||ie("loudness"),y.push(bl(re,_?.loudness),"aresample=48000"),P.push(`normalize to ${re.i} LUFS${_?.loudness?` (measured ${_.loudness.input_i})`:""}`)}v=!0,M.push(`audio: ${P.join(", ")}`);break}case"burn_subtitles":{if(!$.subtitles==!$.transcribe)throw new l(`step ${N}: burn_subtitles takes subtitles (a path) or transcribe: true.`);if($.transcribe&&!n.hasAudio)throw new l(`step ${N}: transcribe needs audio, and the input has none.`);let _=s.subtitles?.[J];if(_===""){M.push("burn_subtitles: no cues in this part of the video; skipped");break}_===void 0&&ie($.transcribe?"transcribe":"subtitles");let P=!!$.subtitles&&/\.(ass|ssa)$/i.test($.subtitles),re=$.style??(P?null:"clean");ee(ju(_??"<subtitles.srt>",s.fontsDir??"<fonts>",re)),M.push(`burn_subtitles ${$.transcribe?"from a transcript":"from a file"}, ${re??"file"} style`);break}case"backdrop":{let{op:_,...P}=$,{steps:re,out:D,extraInputs:A,layout:ce}=fl(P,{width:d,height:p},x,w,le);C=null,g.push(...re),b.push(...A),w+=A.length/2,x=D,d=ce.canvasW,p=ce.canvasH,M.push(`backdrop to ${d}x${p}`);break}case"keystroke_overlay":{let _=s.keystrokes?.[J];if(!_)throw new l(`Internal: missing keystroke badges for step ${N}.`);let P=fb(_.badges,H);if(P.length===0){M.push("keystroke_overlay: no badges in this part of the video");break}let{steps:re,out:D}=cl(Ia(P),_,$,{height:p},x,le);g.push(...re),x=D,M.push(`keystroke_overlay ${P.length} badge(s)`);break}case"cursor":{if(!C)throw new l(`step ${N}: cursor must come before zoom, reframe or backdrop; the logged positions no longer match the frame after them.`);let _=s.cursor?.[J];if(!_)throw new l(`Internal: missing cursor plan for step ${N}.`);let P=Da(_.plan,H,C);if(P.path.length===0||P.visible.length===0){M.push("cursor: no cursor movement in this part of the video");break}let{steps:re,out:D,extraInputs:A,commands:ce}=pl(P,$,{width:d,height:p},x,w,le,_.sprite,_.commandsFile);g.push(...re),b.push(...A),w+=A.length/2,x=D,L.push({path:_.commandsFile,content:ce}),M.push(`cursor ${P.path.length} segment(s), ${P.clicks.length} click(s)${$.spotlight?", spotlight":""}`);break}case"export_preset":{let _=Qu($.platform,$.fit??"pad",le);C=null,ee(_.vf),_.af&&y.push(_.af),R=_.encode,d=_.width,p=_.height,f=30,v=!0,M.push(`export_preset ${$.platform}`);break}case"export_gif":{let{op:_,...P}=$;T=P,M.push(`export_gif (${P.format??"gif"}): second stage, size-budget ladder`);break}}});let V=["-y",...h,"-i",t,...b],Y=s.chaptersFile?V.filter($=>$==="-i").length:-1;s.chaptersFile&&V.push("-f","ffmetadata","-i",s.chaptersFile);let q=n.hasAudio&&y.length>0;q&&g.push(`[0:a]${y.join(",")}[aout]`),g.length>0&&V.push("-filter_complex",g.join(";")),V.push("-map",x==="[0:v]"?"0:v":x),n.hasAudio&&V.push("-map",q?"[aout]":"0:a");let Q=R;return Q?V.push(...Q):(V.push(...Re(T||u?"high":i)),n.hasAudio&&V.push(...v?["-c:a","aac","-b:a","160k"]:["-c:a","copy"]),V.push("-movflags","+faststart")),Y!==-1&&V.push("-map_chapters",String(Y)),V.push(e),{args:V,width:d,height:p,fps:f,durationSec:m===null?null:Ct(m),gif:T,summary:M,timeOps:H,pending:G,files:L}}var Lw=["pr_demo","tutorial","social_reel"],wR=1e7,Dw=new Set(["export_preset","export_gif"]);function Bw(t,e){let r=[],n=[{op:"cut_idle"}];e.hasClicks?n.push({op:"zoom",follow:"clicks"}):r.push("zoom left out: no event log with clicks (record with start_recording events: true).");let o=i=>{e.hasAudio&&(e.transcribeBlocker?r.push(`captions left out: ${e.transcribeBlocker}`):n.push({op:"burn_subtitles",transcribe:!0,style:i}))};switch(!e.hasAudio&&t!=="pr_demo"&&r.push("audio and captions left out: the input has no audio."),t){case"pr_demo":n.push({op:"export_gif",maxBytes:wR});break;case"tutorial":e.hasAudio&&n.push({op:"audio",denoise:"light",normalize:"youtube"}),o("clean"),n.push({op:"export_preset",platform:"youtube"});break;case"social_reel":e.hasAudio&&n.push({op:"audio",normalize:"youtube"}),n.push({op:"reframe",aspect:"9:16"}),o("social"),n.push({op:"export_preset",platform:"instagram_reel"});break;default:throw new l(`Unknown recipe "${String(t)}".`)}return{steps:n,notes:r}}var yR=new Set(["redact","crop","cursor"]);function Al(t,e){let r=[...t],o=r.at(-1)&&Dw.has(r.at(-1).op)?r.pop():null,i=r.length,s=new Set,a=[],c=[];for(let u of e){if(Dw.has(u.op)){o=u;continue}let d=r.findIndex((p,f)=>f<i&&!s.has(f)&&p.op===u.op);d===-1&&u.op==="trim"?a.push(u):d===-1&&yR.has(u.op)?c.push(u):d===-1?r.push(u):(r[d]=u,s.add(d))}return[...a,...c,...r,...o?[o]:[]]}import{readFileSync as xR,statSync as SR,writeFileSync as vR}from"node:fs";var Ww=1;function $R(t){return`${t}.edit.json`}function kR(t,e="the edit spec"){let r;try{r=JSON.parse(t)}catch{throw new l(`${e} is not valid JSON.`)}let n=r;if(n?.tool!=="pipeline"||typeof n.version!="number"||!Array.isArray(n.steps)||typeof n.source?.path!="string")throw new l(`${e} is not a pipeline edit spec.`);if(n.version>Ww)throw new l(`${e} was written by a newer version (spec ${n.version}).`,"Update screencast-mcp to re-render it.");return n}function jw(t){let e;try{e=xR(t,"utf8")}catch{throw new l(`Edit spec not found: ${t}`)}return kR(e,t)}function Ml(t){let e=SR(t);return{path:t,size:e.size,mtimeMs:Math.round(e.mtimeMs)}}function Uw(t){let e;try{e=Ml(t.source.path)}catch{return`its source ${t.source.path} is gone`}return e.size!==t.source.size||e.mtimeMs!==t.source.mtimeMs?`its source ${t.source.path} changed since`:null}function zw(t,e){let r=$R(t),n={version:Ww,tool:"pipeline",createdAt:new Date().toISOString(),output:t,...e};return vR(r,JSON.stringify(n,null,2)+`
|
|
376
|
-
`),r}var ER=new Set(["input","inputs","inputA","inputB","clips","a","b","image","overlay","music","video","subtitles","srt","transcript","events","path","file","perf","fromEdit"]),_R=new Set(["output","outputDir","model","fontFile"]),TR=new Set(["whisper"]);function Hw(t){return typeof t=="string"?[t]:Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function ic(t){let e=r=>{if(Array.isArray(r)){r.forEach(e);return}if(!(!r||typeof r!="object"))for(let[n,o]of Object.entries(r)){if(ER.has(n))for(let i of Hw(o))i.trim().length>0&&!TR.has(i)&&hp(i,`Input "${n}"`);else if(_R.has(n))for(let i of Hw(o))tr(i,`"${n}"`);o&&typeof o=="object"&&e(o)}};e(t)}function AR(){if(!Ve("whisper"))return"this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";try{return Sr(void 0),null}catch{return"no whisper model (set SCREENCAST_WHISPER_MODEL)."}}var MR=F.enum(Un),Yw=F.enum(la).optional(),CR=F.discriminatedUnion("op",[F.object({op:F.literal("trim"),start:F.number().nonnegative(),end:F.number().positive().optional(),duration:F.number().positive().optional()}),F.object({op:F.literal("crop"),x:F.number().int().nonnegative(),y:F.number().int().nonnegative(),width:F.number().int().positive(),height:F.number().int().positive()}),F.object({op:F.literal("scale"),width:F.number().int().positive().optional(),height:F.number().int().positive().optional()}),F.object({op:F.literal("speed"),factor:F.number().positive().optional(),segments:F.array(va).min(1).optional()}),F.object({op:F.literal("redact"),regions:F.array(xn).min(1).optional(),secrets:F.union([F.boolean(),F.string().min(1).max(500)]).optional().describe("OCR for on-screen secrets: true or a regex."),style:F.enum(Oi).optional(),pad:F.number().int().nonnegative().optional(),color:F.string().optional()}),F.object({op:F.literal("callout"),items:F.array(Aa).min(1).max(50),fontFile:_r}),F.object({op:F.literal("reframe"),aspect:MR,fit:Yw}),F.object({op:F.literal("zoom"),keyframes:F.array(nc).min(1).max(100).optional(),follow:F.literal("clicks").optional(),maxZoom:F.number().min(1).max(li).optional(),holdSec:F.number().positive().max(30).optional(),transitionSec:F.number().positive().max(5).optional()}),F.object({op:F.literal("cut_idle"),minIdleSec:F.number().positive().optional(),keepSec:F.number().min(0).optional(),action:F.enum(["cut","speed"]).optional(),factor:F.number().gt(1).max(Zr).optional()}),F.object({op:F.literal("audio"),normalize:za.optional(),denoise:F.enum(Ga).optional()}),F.object({op:F.literal("burn_subtitles"),subtitles:F.string().min(1).optional(),transcribe:F.boolean().optional(),style:F.enum(Vs).optional()}),F.object({op:F.literal("backdrop"),...ja}),F.object({op:F.literal("keystroke_overlay"),...Fa}),F.object({op:F.literal("cursor"),...La}),F.object({op:F.literal("export_preset"),platform:F.enum(da),fit:Yw}),F.object({op:F.literal("export_gif"),format:F.enum(["gif","webp"]).optional(),maxBytes:F.number().int().min(1e4).optional(),fps:F.number().positive().max(30).optional(),width:F.number().int().min(64).max(1920).optional()})]),PR={input:F.string().min(1).optional().describe("Path to the source video."),fromEdit:F.string().min(1).optional().describe("Re-render an .edit.json; steps replace same-op steps."),steps:F.array(CR).max(to).optional().describe(`Edits in order, each { op, ...its tool's options }; export_preset/export_gif only last. Times and pixels are relative to the video as it is at that step (after earlier trims, speed, crops). zoom follow:"clicks" plans from the event log; burn_subtitles takes subtitles or transcribe:true.`),recipe:F.enum(Lw).optional().describe("Polish preset expanded to steps (see dryRun): pr_demo = cut_idle, click zoom, GIF <=10 MB; tutorial = + audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step; trim, redact, crop and cursor go first (source pixels and time)."),quality:F.enum(["draft","standard","high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),dryRun:F.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),output:F.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:F.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),chapters:F.boolean().optional().describe("Keep the input's markers as chapters, re-timed through trims and speed.")};function Kw(t){t.registerTool("pipeline",{title:"Edit Pipeline",description:"Run several edits (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, cursor, reframe, zoom, backdrop, audio, burn_subtitles, then optionally export_preset or export_gif) in one ffmpeg pass: one re-encode, no intermediate files. Prefer it over chaining edit tools; a recipe does the usual polish in one call.",inputSchema:PR,outputSchema:B({processes:F.number().int(),steps:F.array(F.string())}),annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k(),o=e.fromEdit?jw(e.fromEdit):null;if(o){if(ic({input:o.source.path,steps:o.steps}),e.recipe)throw new l("fromEdit already has its steps; leave recipe out.");if(e.input&&!Wo(e.input,o.source.path))throw new l(`The spec is for ${o.source.path}, not ${e.input}.`);let L=Uw(o);if(L)throw new l(`Cannot re-render ${e.fromEdit}: ${L}.`,"Run pipeline on the source again with steps instead.")}let i=e.input??o?.source.path;if(!i)throw new l("Pass input (or fromEdit).");let s=e.quality??o?.quality??"standard",a=e.chapters??o?.chapters??!1;O(i);let c=await W(i),u=c.audioCodec!==null,d=[],p=e.steps??[];if(o&&(p=Al(o.steps,p)),e.recipe){let L=pi(ke(i).jsonl),C=Bw(e.recipe,{hasAudio:u,hasClicks:!!L&&L.length>0,transcribeBlocker:u?AR():null});p=Al(C.steps,p),d.push(...C.notes)}if(p.length===0)throw new l("Give steps, a recipe, or both.");if(p.length>to)throw new l(`At most ${to} steps.`);if(!c.width||!c.height)throw new l(`Could not read the size of ${i}.`);let f={width:c.width,height:c.height,fps:c.fps??30,durationSec:c.durationSec,hasAudio:u},m=pe(c.durationSec),h=p.at(-1);if(!h)throw new l("Provide at least one step.");let b=h.op==="export_gif"?`.${h.format??"gif"}`:".mp4",w=j(e.output,"pipeline",b,{overwrite:e.overwrite,anyContainer:h.op==="export_gif"}),g=h.op!=="export_gif"&&p.some(L=>L.op==="burn_subtitles"&&L.transcribe),y=w.replace(/\.[^./\\]+$/,"")+".srt";if(g&&!e.overwrite&&sc(y))throw new l(`Output already exists: ${y}. Pass overwrite: true to replace it.`);for(let[L,C]of p.entries())if(C.op==="burn_subtitles"){if(!Ve("subtitles"))throw new l("This ffmpeg has no subtitles filter (it needs libass).","Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");if(C.subtitles&&!sc(C.subtitles))throw new l(`step ${L+1}: subtitles file not found: ${C.subtitles}`);if(C.transcribe){if(!Ve("whisper"))throw new l(`step ${L+1}: transcribe needs FFmpeg 8 built with whisper.cpp (no whisper filter here).`);Sr(void 0)}}let v={};for(let[L,C]of p.entries()){if(C.op!=="zoom"||C.follow!=="clicks")continue;let ne=ke(i).jsonl,V=pi(ne);if(!V)throw new l(`step ${L+1}: no event log at ${ne}; record with start_recording events: true.`);v[L]=V}let x,R=p.findIndex(L=>L.op==="cut_idle"),T=p[R];if(T?.op==="cut_idle"){let L=c.durationSec;if(L===null)throw new l(`Could not read the duration of ${i}.`);let C=p.slice(0,R).reduce((q,Q)=>Q.op==="speed"&&Q.factor?q*Q.factor:q,1),ne=u,V=await se(n,ba(i,(T.minIdleSec??en)*C,ne),m,{signal:r.signal});if(V.code!==0)throw new l(`Idle scan failed (exit ${V.code}): ${V.stderr.trim().slice(-400)}`);let Y=wa(V.stderr,L);x=ne?xa(Y,ya(V.stderr,L)):Y}let M=0,H=p;p=[...p];for(let[L,C]of p.entries()){if(C.op!=="redact")continue;let ne=[...C.regions??[]];if(C.secrets){let V=p.slice(0,L);if(V.some(q=>q.op==="speed"||q.op==="cut_idle"))throw new l(`step ${L+1}: put a redact with secrets before speed and cut_idle; it scans the source's clock.`);let Y=V.reduce((q,Q)=>Q.op==="trim"?q+Q.start:q,0);if(e.dryRun)d.push(`Step ${L+1}: the secret scan runs when rendering, not in a dry run.`);else{let q=Gw(Cr(Jw(),"screencast-secrets-"));try{let Q=c.durationSec??0,$=await Rn(i,{everySec:Math.max(1,Math.ceil(Q/Wt)),maxFrames:Wt},q,r.signal),J=typeof C.secrets=="string"?C.secrets:De;for(let N of br($,J,!0).redactRegions){if(N.end-Y<=0)continue;let le={x:Math.round(N.x),y:Math.round(N.y),width:Math.round(N.width),height:Math.round(N.height)};ne.push({...le,start:Math.max(0,N.start-Y),end:N.end-Y}),M++}}finally{Xw(q,{recursive:!0,force:!0})}}}else if(ne.length===0)throw new l(`step ${L+1}: redact needs regions, or secrets: true to find them.`);p[L]={...C,regions:ne}}if(p.some(L=>L.op==="redact"&&L.secrets)&&!e.dryRun&&d.push(M>0?`Blurred ${M} on-screen secret region(s).`:"No on-screen secrets found."),p=p.filter(L=>L.op!=="redact"||L.regions.length>0),p.length===0)throw new l("Nothing to render: the only step was a redact that found no secrets.");let G=Gw(Cr(Jw(),"screencast-pipeline-"));try{let L={},C=[];for(let[D,A]of p.entries()){if(A.op!=="callout")continue;let ce=e.dryRun?{fontFile:"<font>",textFiles:A.items.map(be=>be.type==="text"?"<text>":null),arrowFiles:A.items.map(be=>be.type==="arrow"?"<arrow.png>":null),...sl(A.items,A.fontFile)}:await Ma(A.items,G,`s${D}_`,A.fontFile);L[D]=ce,C.push(...ce.fallbackFonts.map(be=>({step:D,...be}))),d.push(...ce.warnings.map(be=>`Step ${D}, ${be.charAt(0).toLowerCase()}${be.slice(1)}`))}let ne={};for(let[D,A]of p.entries()){if(A.op==="backdrop"&&A.image&&!sc(A.image))throw new l(`step ${D+1}: background image not found: ${A.image}`);if(A.op!=="keystroke_overlay")continue;let{badges:ce}=Oa(i,A.events,A),be=[...new Set(ce.map($e=>$e.label))],Ee=ei(be,e.dryRun?null:G,`s${D}_`,A.fontFile);ne[D]={badges:ce,fontFile:Ee.fontFile,textFiles:Ee.textFiles},d.push(...Ee.warnings.map($e=>`Step ${D}, ${$e.charAt(0).toLowerCase()}${$e.slice(1)}`))}let V={};for(let[D,A]of p.entries())A.op==="cursor"&&(V[D]={plan:Ba(i,A.events,A,c.durationSec),sprite:Na(),commandsFile:e.dryRun?`<cursor ${D}.cmd>`:Cr(G,`s${D}_cursor.cmd`)});let Y=h.op==="export_gif"?e.dryRun?"<temporary stage1.mp4>":Cr(G,"stage1.mp4"):w,q={},Q={},$=RR(Ut("regular")),J=D=>oc(i,Y,p,f,L,s,{keystrokes:ne,cursor:V,idle:x,clicks:v,audio:q,subtitles:Q,fontsDir:$,chaptersFile:D}),N=J(),le;for(let D=0;!e.dryRun&&N.pending.length>0;D++){let A=N.pending[0];if(D>p.length*3)throw new l(`Internal: step ${A.step+1} ${A.kind} did not resolve.`);let ce=p[A.step],be=async Ee=>{let $e=Wi(Rl(Ee,A));try{let Ke=await se(n,$e.args,m,{signal:r.signal});if(Ke.code!==0)throw new l(`step ${A.step+1} ${A.kind} scan failed (exit ${Ke.code}): ${Ke.stderr.trim().slice(-400)}`);return Ke}finally{$e.cleanup()}};if(A.kind==="noisefloor")q[A.step]={...q[A.step],floorDb:Xa((await be(qa(i))).stdout)};else if(A.kind==="loudness"&&ce.op==="audio"){let Ee=await be(ii(i,Zn(ce.normalize)));try{q[A.step]={...q[A.step],loudness:si(Ee.stderr)}}catch{d.push(`Step ${A.step+1}: the audio is silent; not normalized.`),q[A.step]={...q[A.step],silent:!0}}}else if(A.kind==="transcribe"&&ce.op==="burn_subtitles"){let Ee=Cr(G,`s${A.step}_raw.srt`);await te(Rl(Dn(i,Sr(void 0),Ee),A),m,{signal:r.signal});let $e=sc(Ee)?pt(Ue(qw(Ee,"utf8"))):[];Q[A.step]=$e.length>0?Cr(G,`s${A.step}.srt`):"",$e.length>0?(le={cues:$e,opsBefore:A.ops.length},di(Q[A.step],it($e))):d.push(`Step ${A.step+1}: no speech was recognised; no captions.`)}else if(A.kind==="subtitles"&&ce.op==="burn_subtitles"&&ce.subtitles)if(A.ops.length===0)Q[A.step]=ce.subtitles;else{let Ee=qw(ce.subtitles,"utf8"),$e=/\.(ass|ssa)$/i.test(ce.subtitles),Ke=$e?Tm(Ee,A.ops):it(cs(pt(Ue(Ee)),A.ops)),Xl=Cr(G,`s${A.step}${$e?".ass":".srt"}`);di(Xl,Ke),Q[A.step]=$e||Ke.trim()?Xl:""}else throw new l(`Internal: step ${A.step+1} cannot resolve ${A.kind}.`);N=J()}let X=[],ee=[];if(a){let D=N.gif?null:await gr(i,r.signal);if(!D)d.push("chapters: a GIF/WebP cannot hold chapters; none written.");else if(D.markers.length===0)d.push("chapters: the input has no markers (add_marker) or chapters; none written.");else if(ee=Cm(D.markers,N.timeOps),X=N.durationSec?ps(ms(ee),N.durationSec):[],X.length===0)d.push("chapters: no marker falls inside the result; none written.");else{let A=e.dryRun?"<chapters.txt>":Cr(G,"chapters.txt");e.dryRun||di(A,ds(X)),N=J(A)}}let ie={...e.recipe&&{recipe:e.recipe,expandedSteps:p},steps:N.summary,...e.dryRun&&N.pending.length>0&&{measuredOnRun:N.pending.map(D=>`step ${D.step+1}: ${D.kind}`)},processes:N.gif?2:1,width:N.width,height:N.height,durationSec:N.durationSec,...C.length>0&&{fallbackFonts:C},...d.length>0&&{warnings:d},...X.length>0&&{chapters:X}};if(e.dryRun)return S({dryRun:!0,...ie,ffmpegArgs:N.args});let _=()=>{try{let D=e.recipe??o?.recipe;return{editSpecPath:zw(w,{serverVersion:xt(),source:Ml(i),steps:H,...D?{recipe:D}:{},quality:s,chapters:a})}}catch{return{}}};for(let D of N.files)di(D.path,D.content);if(await U(N.args,{output:Y,durationSec:N.durationSec,inputDurationSec:c.durationSec,extra:r}),N.gif){let D=await Gn(Y,w,N.gif,r);return S({outputPath:w,...ie,animation:D,..._()})}let P;if(le)try{let D=Nw(le.cues,N.timeOps,le.opsBefore);D.length>0&&(di(y,it(D)),P=y)}catch{P=void 0}let re;if(X.length>0)try{re=hr(w,ee.filter(D=>D.t<(N.durationSec??1/0)))}catch{}return S({outputPath:w,...ie,...re&&{markersPath:re},...P&&{subtitlesPath:P},..._()})}finally{Xw(G,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as mi}from"zod";var IR={input:mi.string().min(1).describe("Path to the source video."),platform:mi.enum(da).describe("Sets aspect, size, fps, bitrate. steam_trailer: 1080p 5.5 Mbps CBR, -14 LUFS. vertical_reel: 1080x1920 over a blurred copy of itself, -14 LUFS (ignores fit)."),fit:mi.enum(["pad","crop"]).optional().describe("Fit to the platform aspect: pad (default) or crop."),output:mi.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:mi.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Vw(t){t.registerTool("export_preset",{title:"Export for Platform",description:"Encode a platform-ready H.264 file (aspect, fps, bitrate, faststart) for a named platform.",inputSchema:IR,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=e.platform,o=j(e.output,n,".mp4",{overwrite:e.overwrite}),i=Ig(e.input,o,n,e.fit??"pad");await U(i,{output:o,durationSec:await ue(e.input),extra:r});let s=Vu[n];return S({outputPath:o,platform:n,aspect:s.aspect,fps:s.fps})}catch(n){return E(n)}})}import{z as _e}from"zod";import{existsSync as ac,mkdirSync as FR,mkdtempSync as OR,readFileSync as Cl,rmSync as Pl,writeFileSync as Qw}from"node:fs";import{tmpdir as NR,release as DR,version as LR}from"node:os";import{join as an}from"node:path";var BR=xt(),WR={input:_e.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),sessionId:_e.string().min(1).optional().describe("Or a stopped session's id."),title:_e.string().max(200).optional().describe("Issue title."),actual:_e.string().max(4e3).optional().describe("What happened."),expected:_e.string().max(4e3).optional().describe("What should happen."),start:_e.number().nonnegative().optional().describe("Clip start s (default: end - clipSec)."),end:_e.number().positive().optional().describe("Clip end s (default: recording end)."),clipSec:_e.number().positive().max(Is).optional().describe(`Clip length without start (default ${Pu}).`),redact:_e.boolean().optional().describe("Box out OCR-found secrets in every output (default true; needs Windows OCR)."),secretPattern:_e.string().optional().describe("Secret regex (default: API keys, tokens, password: values)."),regions:_e.array(xn).optional().describe("Extra boxes (video px; start/end on the clip clock)."),errorPattern:_e.string().optional().describe("Error-line regex."),scanEverySec:_e.number().positive().optional().describe(`OCR every N s (default ${Iu}).`),maxFrames:_e.number().int().min(1).max(vs).optional().describe(`Scan frame cap (default ${Wt}).`),gif:_e.boolean().optional().describe("Also export a GIF (default true)."),maxBytes:_e.number().int().min(1e4).optional().describe(`GIF size budget (default ${Er}).`),outputDir:_e.string().optional().describe("Package folder (default: a new one in SCREENCAST_HOME/edits)."),overwrite:_e.boolean().optional().describe("Replace a report already in outputDir.")},fi=t=>Math.round(t*1e3)/1e3;async function jR(){if(process.platform!=="win32")return null;try{return(await lr()).map(e=>`${e.width}x${e.height}${e.dpi?` @${Math.round(e.dpi/96*100)}%`:""}${e.primary?" (primary)":""}`).join(", ")}catch{return null}}function Zw(t){t.registerTool("bug_report",{title:"Bug Report Package",description:"Package a recording as a paste-ready repro folder: secret-scanned, redacted clip and GIF, contact sheet, steps from the event log, OCR'd errors, environment, report.md for gh issue create --body-file.",inputSchema:WR,outputSchema:B({outputDir:_e.string(),reportPath:_e.string(),jsonPath:_e.string(),clipPath:_e.string()}),annotations:I},async(e,r)=>{let n=null,o=[];try{if(e.input===void 0==(e.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");let{ffmpeg:i}=k(),s=await Ns(e),a=await W(s.path);if(!a.width||!a.height)throw new l(`Could not read the size of ${s.path}.`);let c=a.videoDurationSec??a.durationSec;if(c===null)throw new l(`Could not read the duration of ${s.path}.`);let u=Of(c,e),d=fi(u.end-u.start),p=e.redact!==!1,f=e.secretPattern??De;Le(["x"],f),e.errorPattern!==void 0&&Le(["x"],e.errorPattern);let m="gif",h=fn(e.outputDir,we("edits"))??an(we("edits"),`bug-report-${he()}-${ge()}`),b={markdown:an(h,zt.markdown),json:an(h,zt.json),clip:an(h,zt.clip),gif:an(h,zt.gif(m)),sheet:an(h,zt.contactSheet)},w=Object.values(b).filter(v=>ac(v));if(w.length>0&&!e.overwrite)throw new l(`The folder already holds a report: ${w.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);ac(h)||(FR(h,{recursive:!0}),n=h);let g=[],y=OR(an(NR(),"screencast-bug-"));try{let v="unavailable",x=null,R=await vr();if(R.available)x=await Rn(s.path,{everySec:e.scanEverySec??Iu,maxFrames:e.maxFrames??Wt,range:{start:u.start,duration:d}},y,r.signal),v="read";else{if(p)throw new l(`The secret scan needs Windows OCR, which is unavailable here${R.error?` (${R.error})`:""}.`,"Pass redact: false to package without it (then check the clip yourself before sharing), or run doctor.");g.push("Windows OCR is unavailable, so no error text was read.")}let T=x&&p?Nf(br(x,f,!0,"line").redactRegions):[],M=[...T,...e.regions??[]],H=x?Df(x.frames,e.errorPattern??Os,p?f:null):[];r.signal.throwIfAborted();let G=[{op:"trim",start:u.start,end:u.end},...M.length>0?[{op:"redact",regions:M,style:"box"}]:[]],L=oc(s.path,b.clip,G,{width:a.width,height:a.height,fps:a.fps??30,durationSec:a.durationSec,hasAudio:a.audioCodec!==null});await U(L.args,{output:b.clip,durationSec:L.durationSec,inputDurationSec:d,extra:r}),o.push(b.clip);let C=null;e.gif!==!1&&(C=await Gn(b.clip,b.gif,{format:m,maxBytes:e.maxBytes??Er},r),o.push(b.gif),C.note&&g.push(C.note)),await Cs(b.clip,Ms(d,No),b.sheet,{tileWidth:Do},r.signal),o.push(b.sheet);let ne=(s.eventsPath?Cu(ze(Cl(s.eventsPath,"utf8"))):[]).map(P=>p?{...P,text:Le([P.text],f)[0]??P.text}:P),V=s.eventsPath?ne.length===0?"The event log has no clicks, shortcuts, typing, or scrolls.":void 0:"The recording has no input event log (record with start_recording events: true).",Y=jt(s.path),q=ac(Y)?Bf(Es(Cl(Y,"utf8")),u,p?f:null):void 0,Q=vt(s.path),$=ac(Q)?Wf(Cn(Cl(Q,"utf8")),u,s.record?.perf?.summary?.process):[],J=ca(ua(i)??""),N=await jR(),le=s.record,X=P=>p?Le([P],f)[0]??P:P,ee=[["OS",`${LR()} (${DR()}), ${process.arch}`],...N?[["Displays",N]]:[],...le?[["Recorded target",X(le.target)]]:[],...le?.matchedWindow?[["Window",X(le.matchedWindow)]]:[],...le?.backend?[["Capture backend",le.backend]]:[],["Recording",`${a.width}x${a.height}${a.fps?` @ ${Math.round(a.fps*100)/100} fps`:""}, ${fi(c)} s${a.videoCodec?`, ${a.videoCodec}`:""}`],["ffmpeg",J.version??"unknown"],["screencast-mcp",`${BR} (Node ${process.version})`]],ie={title:e.title?.trim()||"Bug report",...e.expected?{expected:e.expected}:{},...e.actual?{actual:e.actual}:{},createdAt:new Date().toISOString(),clip:{start:u.start,end:u.end,recordingDurationSec:fi(c),width:a.width,height:a.height},files:{clip:zt.clip,...C?{gif:zt.gif(m)}:{},contactSheet:zt.contactSheet},...C?{gif:{format:m,sizeBytes:C.sizeBytes,withinBudget:C.withinBudget}}:{},steps:ne.slice(0,Fs),...ne.length>Fs?{stepsOmitted:ne.length-Fs}:{},...V?{stepsNote:V}:{},errors:H,...q?{logs:q}:{},...$.length?{perf:$}:{},ocr:v,redaction:{scanned:x!==null&&p,...x&&p?{everySec:fi(x.step),framesScanned:x.frames.length}:{},found:T.length,manual:e.regions?.length??0},environment:ee};Qw(b.markdown,Lf(ie)),o.push(b.markdown),Qw(b.json,JSON.stringify({...ie,steps:ne,redaction:{...ie.redaction,regions:M}},null,2)+`
|
|
377
|
-
|
|
378
|
-
`)}var rt=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),JR=`:root{--bg:#f6f5f2;--card:#fff;--ink:#16161a;--dim:#6b6b74;--line:#e2e0da;--rec:#e5383b}
|
|
375
|
+
`;var $T=_t(),Fw=me.looseObject({found:me.boolean(),path:me.string().nullable(),version:me.string().nullable(),major:me.number().nullable()}),kT=N({ok:me.boolean(),problems:me.array(me.string()),server:me.looseObject({version:me.string(),node:me.string(),platform:me.string(),arch:me.string()}),ffmpeg:Fw.extend({meetsFfmpeg8:me.boolean().nullable()}),ffprobe:Fw,filters:me.record(me.string(),me.boolean()),devices:me.looseObject({gdigrab:me.boolean(),dshow:me.boolean()}),wgc:me.looseObject({available:me.boolean()}),ocr:me.looseObject({available:me.boolean(),language:me.string().nullable(),languages:me.array(me.string())}),storage:me.looseObject({home:me.string(),homeExists:me.boolean()}),env:me.record(me.string(),me.string().nullable())});function ET(t){let e=E(t).content[0];return e?.type==="text"?e.text.replace(/\s*\n+\s*/g," "):String(t)}function Ow(t){let e=xa(t),r=ya(e??"");return{found:e!==null,path:e!==null?Cg(t):null,version:r.version,major:r.major,...r.inferred?{majorInferred:!0}:{}}}function Nw(t){t.registerTool("doctor",{title:"Check Setup",description:`Check the setup: ffmpeg/ffprobe (FFmpeg ${tn}+?), optional filters, capture devices, Windows OCR, settings, and enabled toolsets; \`problems\` says what is missing and how to fix it. Call on first use or when a tool reports a missing feature.`,inputSchema:{},outputSchema:kT,annotations:ge},async()=>{try{let e=[],r=null;try{r=Nc()}catch(w){e.push(ET(w))}let n=Ow(r?.ffmpeg??(process.env.FFMPEG_PATH?.trim()||"ffmpeg")),o=Ow(r?.ffprobe??(process.env.FFPROBE_PATH?.trim()||"ffprobe")),i=n.major===null?null:n.major>=tn;r&&i===!1&&e.push(`FFmpeg ${n.version} is older than ${tn}: transcribe and backend "wgc" need FFmpeg ${tn}+. Windows: \`winget install Gyan.FFmpeg\`.`);let s={},a={gdigrab:!1,dshow:!1};if(r){for(let g of Fg)s[g.filter]=g.filter==="gfxcapture"?pr():Qe(g.filter),!s[g.filter]&&!(g.filter==="gfxcapture"&&process.platform!=="win32")&&e.push(`No ${g.filter} filter: ${g.tools} unavailable (needs ${g.why}).`);let w=Mg(Ag(r.ffmpeg)??"");a={gdigrab:w.includes("gdigrab"),dshow:w.includes("dshow")},process.platform==="win32"&&!a.gdigrab&&e.push("This ffmpeg has no gdigrab device: screenshot and start_recording cannot capture the screen.")}process.platform!=="win32"&&e.push("Not Windows: capture (screenshot, start_recording, list_targets) and OCR are unavailable; the watch and edit tools work.");let c=r?{ddagrab:process.platform==="win32"&&Qe("ddagrab"),encoders:await Jc(r.ffmpeg)}:null,[u,d]=await Promise.all([_r(),Pw()]);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=Ig(),f=p.SCREENCAST_WHISPER_MODEL;f&&!ic(f)&&e.push(`SCREENCAST_WHISPER_MODEL points at a missing file: ${f}`);let m=Fe();for(let w of $o())ic(w)||e.push(`SCREENCAST_ALLOWED_DIRS names a missing folder: ${w}`);let h=Ri(p.SCREENCAST_TOOLSETS??void 0);h.unknown.length>0&&e.push(`SCREENCAST_TOOLSETS names unknown toolsets (ignored): ${h.unknown.join(", ")}.`),e.push(...Pg());let b=ic(m)?await If(m):{freeBytes:await Ds(vT(m)),bytes:null};return b.freeBytes!==null&&b.freeBytes<ku&&e.push(`Only ${Ns(b.freeBytes)} free on the drive holding SCREENCAST_HOME: a long recording can fail partway. Delete old recordings (delete_recording) or set SCREENCAST_HOME on a bigger drive.`),S({ok:e.length===0,problems:e,server:{version:$T,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:ic(m),freeBytes:b.freeBytes,...b.bytes?{bytes:b.bytes}:{},recordings:Tl(m,"recordings"),screenshots:Tl(m,"screenshots"),edits:Tl(m,"edits"),allowedOutputDirs:Wr()},env:p,toolsets:{enabled:h.enabled,available:["all",..._i]}})}catch(e){return E(e)}})}import{z as so}from"zod";var _T={inputA:so.string().min(1).describe("Outgoing video."),inputB:so.string().min(1).describe("Incoming video."),transition:so.string().optional().describe("xfade name (default fade): fade, wipeleft, slideup, circleopen, dissolve, ..."),duration:so.number().positive().optional().describe(`Transition length in seconds (default ${Xn}).`),output:so.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:so.boolean().optional().describe("Replace an existing output (default false).")};function Dw(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:_T,outputSchema:Y,annotations:C},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=nn(n),s=nn(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=Hg(e.inputA,e.inputB,[i,s],u,{transition:e.transition,duration:e.duration},a);return await U(d,{output:u,durationSec:i+s,extra:r}),S({outputPath:u,audio:c})}catch(n){return E(n)}})}import{z as Zt}from"zod";var RT={clips:Zt.array(Zt.string().min(1)).min(2).describe("Clip paths, in order."),transition:Zt.string().optional().describe("cut (default) or an xfade name (fade, wipeleft, slideup, ...)."),duration:Zt.number().positive().optional().describe(`Transition seconds (default ${Xn}).`),width:Zt.number().int().positive().optional().describe("Common output width (default 1920)."),height:Zt.number().int().positive().optional().describe("Common output height (default 1080)."),fps:Zt.number().int().positive().optional().describe("Common output fps (default 30)."),output:Zt.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:Zt.boolean().optional().describe("Replace an existing output (default false).")};function Lw(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:RT,outputSchema:Y,annotations:C},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=>nn(c)??0),i=n.map(c=>c.audioCodec!==null),s=B(e.output,"highlights",".mp4",{overwrite:e.overwrite}),a=oi(e.clips,o,s,{transition:e.transition,duration:e.duration,width:e.width,height:e.height,fps:e.fps},i);return await U(a,{output:s,durationSec:o.reduce((c,u)=>c+u,0)||null,extra:r}),S({outputPath:s,clips:e.clips.length,transition:e.transition??"cut",audio:i.some(Boolean)})}catch(n){return E(n)}})}import{z as xt}from"zod";import{writeFileSync as TT,rmSync as MT}from"node:fs";var AT={text:xt.string().min(1).describe("Title text. Multiple lines are allowed (use \\n)."),duration:xt.number().positive().optional().describe("Card length in seconds (default 3)."),width:xt.number().int().positive().optional().describe("Card width (default 1920)."),height:xt.number().int().positive().optional().describe("Card height (default 1080)."),fps:xt.number().int().positive().optional().describe("Card fps (default 30)."),bg:xt.string().optional().describe("Background color (default black)."),fontColor:xt.string().optional().describe("Text color (default white)."),fontSize:xt.number().int().positive().optional().describe("Text size in px (default 96)."),bold:xt.boolean().optional().describe("Use the bold weight (default true)."),fontFile:Ar,output:xt.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:xt.boolean().optional().describe("Replace an existing output (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:AT,outputSchema:Y,annotations:C},async(e,r)=>{try{k();let n=B(e.output,"title",".mp4",{overwrite:e.overwrite}),o=Mt(e.text,{weight:e.bold===!1?"regular":"bold",fontFile:e.fontFile}),i=Xe(".txt");TT(i,e.text);try{let s=Gg(i,o.fontFile,n,{duration:e.duration,width:e.width,height:e.height,fps:e.fps,bg:e.bg,fontColor:e.fontColor,fontSize:e.fontSize});await U(s,{output:n,durationSec:e.duration??rl,extra:r})}finally{MT(i,{force:!0})}return S({outputPath:n,...(o.fallback||e.fontFile)&&{fontFile:o.fontFile},...o.warning&&{warnings:[o.warning]}})}catch(n){return E(n)}})}import{z as Fr}from"zod";var CT={video:Fr.string().min(1).describe("Path to the video."),music:Fr.string().min(1).describe("Music audio file."),musicVolume:Fr.number().nonnegative().optional().describe("0..1 (default 0.25 over existing audio, 0.8 alone)."),fadeIn:Fr.number().nonnegative().optional().describe("Fade-in seconds (default 1)."),fadeOut:Fr.number().nonnegative().optional().describe("Fade-out seconds (default 2)."),duck:Fr.boolean().optional().describe("Duck the music under the original audio (default false)."),output:Fr.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:Fr.boolean().optional().describe("Replace an existing output (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:CT,outputSchema:Y,annotations:C},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=qg(e.video,e.music,i,n.durationSec,n.audioCodec!==null,{musicVolume:e.musicVolume,fadeIn:e.fadeIn,fadeOut:e.fadeOut,duck:e.duck});return await U(s,{output:i,durationSec:n.durationSec,extra:r}),S({outputPath:i,mixedWithOriginal:n.audioCodec!==null})}catch(n){return E(n)}})}import{z as St}from"zod";import{existsSync as PT,mkdtempSync as IT,readFileSync as FT,rmSync as OT,writeFileSync as NT}from"node:fs";import{tmpdir as DT}from"node:os";import{join as jw}from"node:path";var LT={video:St.string().min(1).describe("Path to the video."),lines:St.array(St.object({t:St.number().nonnegative().optional().describe("Seconds."),marker:St.string().optional().describe("Or a marker label."),text:St.string().min(1)})).min(1),voice:St.string().optional().describe("Voice name or part (doctor lists them)."),rate:St.number().min(nc).max(oc).optional().describe("Default 1."),duck:St.boolean().optional().describe("Duck the original audio (default true)."),output:St.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:St.boolean().optional().describe("Replace an existing output (default false).")};function Uw(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:LT,outputSchema:Y,annotations:C},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 xr(e.video,r.signal)).markers:[],a=kw(e.lines,s),c=B(e.output,"narrated",V(e.video),{overwrite:e.overwrite}),u=c.replace(/\.[^./\\]+$/,"")+".srt";if(!e.overwrite&&PT(u))throw new l(`Output already exists: ${u}. Pass overwrite: true to replace it.`);n=IT(jw(DT(),"screencast-tts-"));let d=a.map((w,g)=>jw(n,`line-${g}.wav`)),p=await Iw(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:Rw(FT(d[g]))})),m=Ew(f,o.durationSec),h=Tw(e.video,d,c,f,o.durationSec,{hasAudio:o.audioCodec!==null,channels:o.channels,duck:e.duck});await U(h,{output:c,durationSec:o.durationSec,extra:r}),NT(u,at(_w(f,o.durationSec)));let b=He(e.video);return b.length>0&&yr(c,b),S({outputPath:c,srtPath:u,voice:p,lines:f.map(w=>({t:w.t,durationSec:Math.round(w.durationSec*100)/100})),mixedWithOriginal:o.audioCodec!==null,...m.length?{warnings:m}:{}})}catch(o){return E(o)}finally{n&&OT(n,{recursive:!0,force:!0})}})}import{z as wi}from"zod";var BT={input:wi.string().min(1).describe("Source video path."),aspect:wi.enum(Jn).describe("Target aspect ratio."),fit:wi.enum(Sa).optional().describe("pad (default): letterbox, nothing lost. crop: fill and center-crop."),output:wi.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:wi.boolean().optional().describe("Replace an existing output (default false).")};function zw(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:BT,outputSchema:Y,annotations:C},async(e,r)=>{try{k(),F(e.input);let n=V(e.input),o=B(e.output,"reframe",n,{overwrite:e.overwrite}),i=Xg(e.input,o,e.aspect,e.fit??"pad");return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o,aspect:e.aspect,fit:e.fit??"pad"})}catch(n){return E(n)}})}import{z as Ke}from"zod";import{z as dn}from"zod";import{existsSync as WT,readFileSync as jT}from"node:fs";var er=.6,xi=6,sc=2.5;function ac(t,e,r,n=xi){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 rt=t=>Number(t.toFixed(4)).toString();function Ml(t,e,r){let[n,...o]=t;if(!n)throw new l("Give at least one keyframe.");let i=[rt(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-${rt(p-f)})/${rt(f)},0,1)`;i.push(`(${rt(u-c)})*${m}*${m}*(3-2*${m})`)}return It(i)}function Pl(t,e,r=er){let{width:n,height:o,fps:i}=e,s=n<=1920?2:1,a=Ml(t,"z",r),c=Ml(t,"cx",r),u=Ml(t,"cy",r);return`fps=${rt(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=${rt(i)}`}function Hw(t,e,r,n,o=er,i="standard",s){let{width:a,height:c,fps:u}=n,d=Pl(r,n,o);if(!s||s.clicks.length===0)return["-y","-i",t,"-vf",d,...Me(i),"-c:a","copy",e];let p=["[0:v]null[in]",...HT(s.clicks,a,c,u,s.color),`[out]${d}[v]`].join(";");return["-y","-i",t,"-filter_complex",p,"-map","[v]","-map","0:a?",...Me(i),"-c:a","copy",e]}function Gw(t,e,r,n,o={}){let i=o.step??.25,s=o.holdSec??2,a=o.maxZoom??sc,c=o.globalFraction??.3,u=o.transition??er,d=r/t,p=r/a,f=n/a,m=[],h=null,b=()=>{h&&m.push(h),h=null},w=null,g=0;return{push:x=>{let T=w;if(w=x,!T){g=1;return}let R=g++*i,P=Ct(T,x,t,e,{scale:d});if(P.regions.length===0){h&&R-h.last>s&&b();return}if(P.changedFraction>c){b();return}let z=Cl(P.regions);h&&R-h.last<=s&&UT(h.box,z,r,n)?(h.box=Cl([h.box,z]),h.last=R):(b(),h={start:R,last:R,box:z})},finish:()=>{b();let x=[],T=0;for(let R of m){let P=qw(R.box,r,n,p,f),z=Math.max(R.start,T+u),H=Math.max(R.last+s,z+u);x.push({t:yi(z),...P},{t:yi(H),full:!0}),T=H}return x}}}var yi=t=>Math.round(t*100)/100;function Cl(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 UT(t,e,r,n){let o=Cl([t,e]);return o.width<=r/2&&o.height<=n/2}function qw(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 Xw(t,e,r){return["-v","error","-i",t,"-an","-vf",`fps=${rt(1/r)},scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function cc(t,e,r,n={}){let o=n.holdSec??2,i=n.maxZoom??sc,s=n.transition??er,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=qw({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&&zT(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:yi(y),full:!0}),f=y}let g=Math.max(h.t,f+s);p.push({t:yi(g),...b}),f=g,m=h.t}return p.length>0&&p.push({t:yi(Math.max(m+o,f+s)),full:!0}),p}function zT(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 Al=.6,uc="#FF4545";function Il(t,e){return Math.max(40,2*Math.round(Math.min(t,e)*.045))}function HT(t,e,r,n,o){let i=Il(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})-(${rt(c)}+${rt(u)}*T/${Al})),${a/2}),255*min(1,2-2*T/${Al}),0)`;d.push(`color=c=${o}:s=${i}x${i}:r=${rt(n)}:d=${Al},format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${h}',setpts=PTS+${rt(f.t)}/TB[ring${m}]`);let b=m===t.length-1?"[out]":`[r${m}]`;d.push(`${p}[ring${m}]overlay=x=${rt(f.x-s)}:y=${rt(f.y-s)}:eof_action=pass${b}`),p=`[r${m}]`}),d}function Si(t){return WT(t)?Ie(jT(t,"utf8")).filter(e=>e.type==="down"&&e.inFrame).map(e=>({t:e.t,x:e.x,y:e.y})):null}var lc=dn.object({t:dn.number().nonnegative(),x:dn.number().optional(),y:dn.number().optional(),width:dn.number().positive().optional(),height:dn.number().positive().optional(),full:dn.boolean().optional()});var Jw=200,GT={input:Ke.string().min(1).describe("Source video path."),keyframes:Ke.array(lc).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:Ke.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:Ke.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:Ke.boolean().optional().describe("Ring each logged click (default false)."),highlightColor:Ke.string().optional().describe("Ring color (default #FF4545)."),transitionSec:Ke.number().positive().max(5).optional().describe(`How long each zoom/pan eases (default ${er}).`),maxZoom:Ke.number().min(1).max(xi).optional().describe(`Auto mode: the furthest it zooms in (default ${sc}).`),holdSec:Ke.number().positive().max(30).optional().describe("Auto mode: stay zoomed this long after activity (default 2)."),dryRun:Ke.boolean().optional().describe("Return the planned keyframes only (editable, pass back)."),output:Ke.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:Ke.boolean().optional().describe("Replace an existing output (default false).")};function Yw(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:GT,outputSchema:N({keyframes:Ke.array(Ke.unknown())}),annotations:C},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??er,u=e.events??he(e.input).jsonl,d=Si(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=Ue(e.highlightColor??uc,"highlightColor"),f=e.keyframes,m=!f,h=e.follow==="clicks"||e.follow!=="changes"&&d&&d.length>0?"clicks":"changes";if(!f&&h==="clicks"&&(f=cc(d??[],o,i,{holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c}),f.length===0))return S({keyframes:[],follow:h,note:"The event log has no clicks inside the frame; nothing written."});if(!f){let v=gg(o,i),x=.25,T=Gw(v.width,v.height,o,i,{step:x,holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c});if(await Ki(Xw(e.input,v,x),v.width*v.height,R=>T.push(R),de(s),{signal:r.signal}),f=T.finish(),f.length===0)return S({keyframes:[],note:"No localised changes found to zoom into; nothing written."})}if(e.dryRun)return S({planned:m,...m?{follow:h}:{},keyframes:f,transitionSec:c});if(e.highlightClicks&&d&&d.length>Jw)throw new l(`${d.length} clicks is more than ${Jw} rings; trim the video or the event log first.`);let b=ac(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 U(Hw(e.input,g,b,{width:o,height:i,fps:a},c,"standard",y),{output:g,durationSec:s,extra:r}),S({outputPath:g,planned:m,...m?{follow:h}:{},keyframes:f,...y?{ringedClicks:y.clicks.length}:{}})}catch(n){return E(n)}})}import{z as I}from"zod";import{dirname as sM,join as Or}from"node:path";import{existsSync as mc,mkdtempSync as uy,readFileSync as ly,rmSync as py,writeFileSync as vi}from"node:fs";import{tmpdir as dy}from"node:os";var ao=30,Ot=t=>Math.round(t*1e3)/1e3;function Fl(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 Kw(t,e,r){let n=e.slice(r);return n.length>0?gs(t,n):[...t]}function pc(t,e,r,n,o={},i="standard",s={}){if(r.length===0)throw new l("Give at least one step.");if(r.length>ao)throw new l(`At most ${ao} steps.`);r.forEach(($,J)=>{if(($.op==="export_preset"||$.op==="export_gif")&&J!==r.length-1)throw new l(`${$.op} must be the last step (it is step ${J+1} of ${r.length}).`)});let a=r.findIndex($=>$.op==="zoom"),c=a===-1?-1:r.findIndex(($,J)=>J>a&&$.op==="redact");if(c!==-1)throw new l(`step ${c+1}: redact comes after zoom (step ${a+1}), which moves the content under a fixed box. Put redact before zoom, in the source's coordinates.`);let u=r.some($=>$.op==="redact");if(r.filter($=>$.op==="cut_idle").length>1)throw new l("Use at most one cut_idle step.");let d=n.width,p=n.height,f=n.fps,m=n.durationSec,h=[],b=[],w=1,g=[],y=[],v=!1,x="[0:v]",T=null,R,P=[],z=[],H=[],D=[],M={sx:1,sy:1,ox:0,oy:0},ie=($,J)=>{if(!Number.isFinite($.start)||$.start<0)throw new l(`step ${J}: trim start must be a non-negative number.`);if($.end===void 0==($.duration===void 0))throw new l(`step ${J}: trim takes end OR duration.`);let O=$.end??$.start+$.duration;if(!(O>$.start))throw new l(`step ${J}: trim end must be after start.`);if(m!==null&&$.start>=m)throw new l(`step ${J}: trim starts at ${$.start}s, but the video is ${Ot(m)}s long at that point.`);return{start:$.start,end:m!==null?Math.min(O,m):O}};r.forEach(($,J)=>{let O=J+1,pe=`p${J}`,q=`[${pe}]`,ee=_=>{g.push(`${x}${_}${q}`),x=q},ae=_=>H.push({step:J,kind:_,seek:[...h],audio:[...y],ops:[...z]});switch($.op){case"trim":{let{start:_,end:A}=ie($,O);J===0?(h.push("-ss",String(_),"-t",String(Ot(A-_))),P.push(`trim ${_}-${Ot(A)}s: input seek`)):(ee(`trim=start=${_}:end=${Ot(A)},setpts=PTS-STARTPTS`),y.push(`atrim=start=${_}:end=${Ot(A)},asetpts=PTS-STARTPTS`),P.push(`trim ${_}-${Ot(A)}s: trim filter`)),v=!0,m=A-_,z.push({op:"trim",start:_,end:A});break}case"crop":ee(Pc($,{width:d,height:p})),M&&(M={...M,ox:M.ox-$.x,oy:M.oy-$.y}),d=$.width,p=$.height,P.push(`crop to ${d}x${p}`);break;case"scale":{let _=Ic($),[A,oe]=[d,p];({width:d,height:p}=Wp(d,p,$)),M&&(M={sx:M.sx*d/A,sy:M.sy*p/oe,ox:M.ox*d/A,oy:M.oy*p/oe}),ee(_),P.push(`scale to ${d}x${p}`);break}case"speed":{if($.factor===void 0==($.segments===void 0))throw new l(`step ${O}: speed takes factor or segments.`);if($.segments){let A=Ma($.segments,m),oe=Aa(A,f);ee(oe.video),y.push(oe.audio),v=!0;let re=cn(A);m!==null&&(m-=re),z.push({op:"cut",spans:A}),P.push(`speed up ${A.length} range(s), ${Ot(re)}s saved`);break}let _=$.factor;if(!Number.isFinite(_)||_<=0)throw new l(`step ${O}: speed factor must be positive.`);ee(`setpts=PTS/${_}`),y.push(Fc(_)),v=!0,m!==null&&(m/=_),z.push({op:"speed",factor:_}),P.push(`speed x${_}`);break}case"redact":{let{steps:_,out:A}=Oc($.regions,$,{width:d,height:p},x,pe);g.push(..._),x=A,P.push(`redact ${$.regions.length} region(s), ${$.style??"box"}`);break}case"callout":{let _=o[J];if(!_)throw new l(`Internal: missing callout assets for step ${O}.`);let{steps:A,out:oe,extraInputs:re}=dl($.items,_,x,w,pe);g.push(...A),b.push(...re),w+=re.length/4,x=oe,P.push(`callout ${$.items.length} item(s)`);break}case"reframe":{let _=Yn[$.aspect];if(!_)throw new l(`step ${O}: unknown aspect "${$.aspect}".`);ee(`${va(_.w,_.h,$.fit??"pad")},format=yuv420p`),M=null,d=_.w,p=_.h,P.push(`reframe to ${$.aspect} (${$.fit??"pad"})`);break}case"zoom":{let _=$.transitionSec??er,A=$.keyframes,oe="";if($.follow==="clicks"){if(A)throw new l(`step ${O}: zoom takes keyframes or follow, not both.`);if(!M)throw new l(`step ${O}: zoom follow "clicks" must come before reframe, backdrop or another zoom; the logged click positions no longer match the frame.`);let re=M,le=s.clicks?.[J];if(!le)throw new l(`Internal: missing clicks for step ${O}.`);let G=le.flatMap(W=>{let ke=br(W.t,z),Re=W.x*re.sx+re.ox,Te=W.y*re.sy+re.oy;return ke!==null&&Re>=0&&Re<d&&Te>=0&&Te<p?[{t:ke,x:Re,y:Te}]:[]});A=cc(G,d,p,{holdSec:$.holdSec,maxZoom:$.maxZoom,transition:_}),oe=` from ${G.length} click(s)`}else if(!A||A.length===0)throw new l(`step ${O}: zoom needs keyframes, or follow: "clicks".`);if(A.length===0){P.push("zoom: no clicks in this part of the video; skipped");break}ee(Pl(ac(A,d,p),{width:d,height:p,fps:f},_)),M=null,P.push(`zoom ${A.length} keyframe(s)${oe}`);break}case"cut_idle":{if(!s.idle)throw new l(`Internal: missing idle scan for step ${O}.`);let _=Ra(Im(s.idle,z),$.minIdleSec??an,$.keepSec??ai);if(_.length===0){P.push("cut_idle: no idle stretches here; nothing cut");break}if($.action==="speed"){let re=$.factor??ci,le=_.map(ke=>({...ke,factor:re})),G=Aa(le,f);ee(G.video),y.push(G.audio),v=!0;let W=cn(le);m!==null&&(m-=W),z.push({op:"cut",spans:le}),P.push(`cut_idle ${_.length} stretch(es) sped up x${re}, ${Ot(W)}s saved`);break}let A=sl(_);ee(A.video),y.push(A.audio),v=!0;let oe=_.reduce((re,le)=>re+(le.end-le.start),0);m!==null&&(m-=oe),z.push({op:"cut",spans:_}),P.push(`cut_idle ${_.length} stretch(es), ${Ot(oe)}s removed`);break}case"audio":{if($.normalize===void 0&&$.denoise===void 0)throw new l(`step ${O}: audio needs normalize and/or denoise.`);if(!n.hasAudio){P.push("audio: the input has no audio; skipped");break}let _=s.audio?.[J],A=[];if($.denoise!==void 0&&(_?.floorDb===void 0&&ae("noisefloor"),y.push(El($.denoise,_?.floorDb??null)),A.push(`denoise ${$.denoise}`)),$.normalize!==void 0&&_?.silent)A.push("silent, not normalized");else if($.normalize!==void 0){let oe=io($.normalize);_?.loudness||ae("loudness"),y.push(kl(oe,_?.loudness),"aresample=48000"),A.push(`normalize to ${oe.i} LUFS${_?.loudness?` (measured ${_.loudness.input_i})`:""}`)}v=!0,P.push(`audio: ${A.join(", ")}`);break}case"burn_subtitles":{if(!$.subtitles==!$.transcribe)throw new l(`step ${O}: burn_subtitles takes subtitles (a path) or transcribe: true.`);if($.transcribe&&!n.hasAudio)throw new l(`step ${O}: transcribe needs audio, and the input has none.`);let _=s.subtitles?.[J];if(_===""){P.push("burn_subtitles: no cues in this part of the video; skipped");break}_===void 0&&ae($.transcribe?"transcribe":"subtitles");let A=!!$.subtitles&&/\.(ass|ssa)$/i.test($.subtitles),oe=$.style??(A?null:"clean");ee(Xu(_??"<subtitles.srt>",s.fontsDir??"<fonts>",oe)),P.push(`burn_subtitles ${$.transcribe?"from a transcript":"from a file"}, ${oe??"file"} style`);break}case"backdrop":{let{op:_,...A}=$,{steps:oe,out:re,extraInputs:le,layout:G}=Sl(A,{width:d,height:p},x,w,pe);M=null,g.push(...oe),b.push(...le),w+=le.length/2,x=re,d=G.canvasW,p=G.canvasH,P.push(`backdrop to ${d}x${p}`);break}case"keystroke_overlay":{let _=s.keystrokes?.[J];if(!_)throw new l(`Internal: missing keystroke badges for step ${O}.`);let A=Fb(_.badges,z);if(A.length===0){P.push("keystroke_overlay: no badges in this part of the video");break}let{steps:oe,out:re}=hl(Ba(A),_,$,{height:p},x,pe);g.push(...oe),x=re,P.push(`keystroke_overlay ${A.length} badge(s)`);break}case"cursor":{if(!M)throw new l(`step ${O}: cursor must come before zoom, reframe or backdrop; the logged positions no longer match the frame after them.`);let _=s.cursor?.[J];if(!_)throw new l(`Internal: missing cursor plan for step ${O}.`);let A=za(_.plan,z,M);if(A.path.length===0||A.visible.length===0){P.push("cursor: no cursor movement in this part of the video");break}let{steps:oe,out:re,extraInputs:le,commands:G}=wl(A,$,{width:d,height:p},x,w,pe,_.sprite,_.commandsFile);g.push(...oe),b.push(...le),w+=le.length/2,x=re,D.push({path:_.commandsFile,content:G}),P.push(`cursor ${A.path.length} segment(s), ${A.clicks.length} click(s)${$.spotlight?", spotlight":""}`);break}case"export_preset":{let _=ol($.platform,$.fit??"pad",pe);M=null,ee(_.vf),_.af&&y.push(_.af),T=_.encode,d=_.width,p=_.height,f=30,v=!0,P.push(`export_preset ${$.platform}`);break}case"export_gif":{let{op:_,...A}=$;R=A,P.push(`export_gif (${A.format??"gif"}): second stage, size-budget ladder`);break}}});let Z=["-y",...h,"-i",t,...b],K=s.chaptersFile?Z.filter($=>$==="-i").length:-1;s.chaptersFile&&Z.push("-f","ffmetadata","-i",s.chaptersFile);let X=n.hasAudio&&y.length>0;X&&g.push(`[0:a]${y.join(",")}[aout]`),g.length>0&&Z.push("-filter_complex",g.join(";")),Z.push("-map",x==="[0:v]"?"0:v":x),n.hasAudio&&Z.push("-map",X?"[aout]":"0:a");let ne=T;return ne?Z.push(...ne):(Z.push(...Me(R||u?"high":i)),n.hasAudio&&Z.push(...v?["-c:a","aac","-b:a","160k"]:["-c:a","copy"]),Z.push("-movflags","+faststart")),K!==-1&&Z.push("-map_chapters",String(K)),Z.push(e),{args:Z,width:d,height:p,fps:f,durationSec:m===null?null:Ot(m),gif:R,summary:P,timeOps:z,geometry:M,pending:H,files:D}}import{existsSync as Vw,readFileSync as Zw,writeFileSync as Qw}from"node:fs";var Ol=t=>Math.round(t*1e3)/1e3;function qT(t,e,r){return t.flatMap(n=>{let o=br(n.t,e);return o===null||r!==null&&o>r?[]:[{...n,t:Ol(o)}]})}function XT(t,e,r,n){return t.flatMap(o=>{let i=br(o.t,e);if(i===null||n.durationSec!==null&&i>n.durationSec)return[];let s=Math.round(o.x*r.sx+r.ox),a=Math.round(o.y*r.sy+r.oy),c={...o,t:Ol(i),x:s,y:a,inFrame:o.inFrame&&s>=0&&a>=0&&s<n.width&&a<n.height};if(o.durationSec!==void 0){let u=br(o.t+o.durationSec,e)??n.durationSec??i;c.durationSec=Ol(Math.max(0,u-i))}return[c]})}function JT(t){return Zw(t,"utf8").split(/\r?\n/).flatMap(e=>{if(!e.trim())return[];try{return[JSON.parse(e)]}catch{return[]}})}var YT=t=>t.map(e=>JSON.stringify(e)).join(`
|
|
376
|
+
`)+(t.length?`
|
|
377
|
+
`:"");function ey(t,e,r){let n={},o=he(t).jsonl;if(Vw(o))if(!r.geometry)n.note="The input's event log was not carried over: a zoom, reframe or backdrop moved the content, so logged positions no longer match.";else try{let i=XT(Ie(Zw(o,"utf8")),r.timeOps,r.geometry,r),s=he(e).jsonl;Qw(s,yo(i)),n.eventsPath=s}catch{}for(let[i,s]of[["logsPath",ft],["perfPath",st]]){let a=s(t);if(Vw(a))try{let c=s(e);Qw(c,YT(qT(JT(a),r.timeOps,r.durationSec))),n[i]=c}catch{}}return n}var ry=["pr_demo","tutorial","social_reel"],KT=1e7,ty=new Set(["export_preset","export_gif"]);function ny(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:KT});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 VT=new Set(["redact","crop","cursor"]);function Nl(t,e){let r=[...t],o=r.at(-1)&&ty.has(r.at(-1).op)?r.pop():null,i=r.length,s=new Set,a=[],c=[];for(let u of e){if(ty.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&&VT.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 QT,statSync as ZT,writeFileSync as eM}from"node:fs";var oy=1;function tM(t){return`${t}.edit.json`}function rM(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>oy)throw new l(`${e} was written by a newer version (spec ${n.version}).`,"Update screencast-mcp to re-render it.");return n}function iy(t){let e;try{e=QT(t,"utf8")}catch{throw new l(`Edit spec not found: ${t}`)}return rM(e,t)}function Dl(t){let e=ZT(t);return{path:t,size:e.size,mtimeMs:Math.round(e.mtimeMs)}}function sy(t){let e;try{e=Dl(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 ay(t,e){let r=tM(t),n={version:oy,tool:"pipeline",createdAt:new Date().toISOString(),output:t,...e};return eM(r,JSON.stringify(n,null,2)+`
|
|
378
|
+
`),r}var nM=new Set(["input","inputs","inputA","inputB","clips","a","b","image","overlay","music","video","subtitles","srt","transcript","events","path","file","perf","fromEdit"]),oM=new Set(["output","outputDir","model","fontFile"]),iM=new Set(["whisper"]);function cy(t){return typeof t=="string"?[t]:Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function dc(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(nM.has(n))for(let i of cy(o))i.trim().length>0&&!iM.has(i)&&vp(i,`Input "${n}"`);else if(oM.has(n))for(let i of cy(o))ir(i,`"${n}"`);o&&typeof o=="object"&&e(o)}};e(t)}function aM(){if(!Qe("whisper"))return"this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";try{return Er(void 0),null}catch{return"no whisper model (set SCREENCAST_WHISPER_MODEL)."}}var cM=I.enum(Jn),my=I.enum(Sa).optional(),uM=I.discriminatedUnion("op",[I.object({op:I.literal("trim"),start:I.number().nonnegative(),end:I.number().positive().optional(),duration:I.number().positive().optional()}),I.object({op:I.literal("crop"),x:I.number().int().nonnegative(),y:I.number().int().nonnegative(),width:I.number().int().positive(),height:I.number().int().positive()}),I.object({op:I.literal("scale"),width:I.number().int().positive().optional(),height:I.number().int().positive().optional()}),I.object({op:I.literal("speed"),factor:I.number().positive().optional(),segments:I.array(Ta).min(1).optional()}),I.object({op:I.literal("redact"),regions:I.array(_n).min(1).optional(),secrets:I.union([I.boolean(),I.string().min(1).max(500)]).optional().describe("OCR for on-screen secrets: true or a regex."),style:I.enum(Hi).optional(),pad:I.number().int().nonnegative().optional(),color:I.string().optional()}),I.object({op:I.literal("callout"),items:I.array(Oa).min(1).max(50),fontFile:Ar}),I.object({op:I.literal("reframe"),aspect:cM,fit:my}),I.object({op:I.literal("zoom"),keyframes:I.array(lc).min(1).max(100).optional(),follow:I.literal("clicks").optional(),maxZoom:I.number().min(1).max(xi).optional(),holdSec:I.number().positive().max(30).optional(),transitionSec:I.number().positive().max(5).optional()}),I.object({op:I.literal("cut_idle"),minIdleSec:I.number().positive().optional(),keepSec:I.number().min(0).optional(),action:I.enum(["cut","speed"]).optional(),factor:I.number().gt(1).max(sn).optional(),...si}),I.object({op:I.literal("audio"),normalize:Ya.optional(),denoise:I.enum(Va).optional()}),I.object({op:I.literal("burn_subtitles"),subtitles:I.string().min(1).optional(),transcribe:I.boolean().optional(),style:I.enum(ca).optional()}),I.object({op:I.literal("backdrop"),...Xa}),I.object({op:I.literal("keystroke_overlay"),...Wa}),I.object({op:I.literal("cursor"),...Ha}),I.object({op:I.literal("export_preset"),platform:I.enum($a),fit:my}),I.object({op:I.literal("export_gif"),format:I.enum(["gif","webp"]).optional(),maxBytes:I.number().int().min(1e4).optional(),fps:I.number().positive().max(30).optional(),width:I.number().int().min(64).max(1920).optional()})]),lM={input:I.string().min(1).optional().describe("Source video path."),fromEdit:I.string().min(1).optional().describe("Re-render an .edit.json; steps replace same-op steps."),steps:I.array(uM).max(ao).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:I.enum(ry).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:I.enum(["draft","standard","high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),dryRun:I.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),output:I.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:I.boolean().optional().describe("Replace an existing output (default false)."),chapters:I.boolean().optional().describe("Keep the input's markers as chapters, re-timed through trims and speed.")};function fy(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:lM,outputSchema:N({processes:I.number().int(),steps:I.array(I.string())}),annotations:C},async(e,r)=>{try{let{ffmpeg:n}=k(),o=e.fromEdit?iy(e.fromEdit):null;if(o){if(dc({input:o.source.path,steps:o.steps}),e.recipe)throw new l("fromEdit already has its steps; leave recipe out.");if(e.input&&!Yo(e.input,o.source.path))throw new l(`The spec is for ${o.source.path}, not ${e.input}.`);let D=sy(o);if(D)throw new l(`Cannot re-render ${e.fromEdit}: ${D}.`,"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=Nl(o.steps,p)),e.recipe){let D=Si(he(i).jsonl),M=ny(e.recipe,{hasAudio:u,hasClicks:!!D&&D.length>0,transcribeBlocker:u?aM():null});p=Nl(M.steps,p),d.push(...M.notes)}if(p.length===0)throw new l("Give steps, a recipe, or both.");if(p.length>ao)throw new l(`At most ${ao} 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=de(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(D=>D.op==="burn_subtitles"&&D.transcribe),y=w.replace(/\.[^./\\]+$/,"")+".srt";if(g&&!e.overwrite&&mc(y))throw new l(`Output already exists: ${y}. Pass overwrite: true to replace it.`);for(let[D,M]of p.entries())if(M.op==="burn_subtitles"){if(!Qe("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(M.subtitles&&!mc(M.subtitles))throw new l(`step ${D+1}: subtitles file not found: ${M.subtitles}`);if(M.transcribe){if(!Qe("whisper"))throw new l(`step ${D+1}: transcribe needs FFmpeg 8 built with whisper.cpp (no whisper filter here).`);Er(void 0)}}let v={};for(let[D,M]of p.entries()){if(M.op!=="zoom"||M.follow!=="clicks")continue;let ie=he(i).jsonl,Z=Si(ie);if(!Z)throw new l(`step ${D+1}: no event log at ${ie}; record with start_recording events: true.`);v[D]=Z}let x,T=p.findIndex(D=>D.op==="cut_idle"),R=p[T];if(R?.op==="cut_idle"){let D=c.durationSec;if(D===null)throw new l(`Could not read the duration of ${i}.`);let M=p.slice(0,T).reduce((ie,Z)=>Z.op==="speed"&&Z.factor?ie*Z.factor:ie,1);({idle:x}=await tc(n,i,{minIdleSec:(R.minIdleSec??an)*M,useAudio:u,duration:D,sensitivity:R.sensitivity,ignoreRegions:R.ignoreRegions,basis:R.basis,timeoutMs:m,signal:r.signal}))}let P=0,z=p;p=[...p];for(let[D,M]of p.entries()){if(M.op!=="redact")continue;let ie=[...M.regions??[]];if(M.secrets){let Z=p.slice(0,D);if(Z.some(X=>X.op==="speed"||X.op==="cut_idle"))throw new l(`step ${D+1}: put a redact with secrets before speed and cut_idle; it scans the source's clock.`);let K=Z.reduce((X,ne)=>ne.op==="trim"?X+ne.start:X,0);if(e.dryRun)d.push(`Step ${D+1}: the secret scan runs when rendering, not in a dry run.`);else{let X=uy(Or(dy(),"screencast-secrets-"));try{let ne=c.durationSec??0,$=await Fn(i,{everySec:Math.max(1,Math.ceil(ne/Ht)),maxFrames:Ht},X,r.signal),J=typeof M.secrets=="string"?M.secrets:We;for(let O of Sr($,J,!0).redactRegions){if(O.end-K<=0)continue;let pe={x:Math.round(O.x),y:Math.round(O.y),width:Math.round(O.width),height:Math.round(O.height)};ie.push({...pe,start:Math.max(0,O.start-K),end:O.end-K}),P++}}finally{py(X,{recursive:!0,force:!0})}}}else if(ie.length===0)throw new l(`step ${D+1}: redact needs regions, or secrets: true to find them.`);p[D]={...M,regions:ie}}if(p.some(D=>D.op==="redact"&&D.secrets)&&!e.dryRun&&d.push(P>0?`Blurred ${P} on-screen secret region(s).`:"No on-screen secrets found."),p=p.filter(D=>D.op!=="redact"||D.regions.length>0),p.length===0)throw new l("Nothing to render: the only step was a redact that found no secrets.");let H=uy(Or(dy(),"screencast-pipeline-"));try{let D={},M=[];for(let[G,W]of p.entries()){if(W.op!=="callout")continue;let ke=e.dryRun?{fontFile:"<font>",textFiles:W.items.map(Re=>Re.type==="text"?"<text>":null),arrowFiles:W.items.map(Re=>Re.type==="arrow"?"<arrow.png>":null),...ml(W.items,W.fontFile)}:await Na(W.items,H,`s${G}_`,W.fontFile);D[G]=ke,M.push(...ke.fallbackFonts.map(Re=>({step:G,...Re}))),d.push(...ke.warnings.map(Re=>`Step ${G}, ${Re.charAt(0).toLowerCase()}${Re.slice(1)}`))}let ie={};for(let[G,W]of p.entries()){if(W.op==="backdrop"&&W.image&&!mc(W.image))throw new l(`step ${G+1}: background image not found: ${W.image}`);if(W.op!=="keystroke_overlay")continue;let{badges:ke}=ja(i,W.events,W),Re=[...new Set(ke.map(Le=>Le.label))],Te=li(Re,e.dryRun?null:H,`s${G}_`,W.fontFile);ie[G]={badges:ke,fontFile:Te.fontFile,textFiles:Te.textFiles},d.push(...Te.warnings.map(Le=>`Step ${G}, ${Le.charAt(0).toLowerCase()}${Le.slice(1)}`))}let Z={};for(let[G,W]of p.entries())W.op==="cursor"&&(Z[G]={plan:Ga(i,W.events,W,c.durationSec),sprite:Ua(),commandsFile:e.dryRun?`<cursor ${G}.cmd>`:Or(H,`s${G}_cursor.cmd`)});let K=h.op==="export_gif"?e.dryRun?"<temporary stage1.mp4>":Or(H,"stage1.mp4"):w,X={},ne={},$=sM(Gt("regular")),J=G=>pc(i,K,p,f,D,s,{keystrokes:ie,cursor:Z,idle:x,clicks:v,audio:X,subtitles:ne,fontsDir:$,chaptersFile:G}),O=J(),pe;for(let G=0;!e.dryRun&&O.pending.length>0;G++){let W=O.pending[0];if(G>p.length*3)throw new l(`Internal: step ${W.step+1} ${W.kind} did not resolve.`);let ke=p[W.step],Re=async Te=>{let Le=Yi(Fl(Te,W));try{let Lr=await ce(n,Le.args,m,{signal:r.signal});if(Lr.code!==0)throw new l(`step ${W.step+1} ${W.kind} scan failed (exit ${Lr.code}): ${Lr.stderr.trim().slice(-400)}`);return Lr}finally{Le.cleanup()}};if(W.kind==="noisefloor")X[W.step]={...X[W.step],floorDb:Za((await Re(Qa(i))).stdout)};else if(W.kind==="loudness"&&ke.op==="audio"){let Te=await Re(hi(i,io(ke.normalize)));try{X[W.step]={...X[W.step],loudness:gi(Te.stderr)}}catch{d.push(`Step ${W.step+1}: the audio is silent; not normalized.`),X[W.step]={...X[W.step],silent:!0}}}else if(W.kind==="transcribe"&&ke.op==="burn_subtitles"){let Te=Or(H,`s${W.step}_raw.srt`);await te(Fl(zn(i,Er(void 0),Te),W),m,{signal:r.signal});let Le=mc(Te)?gt(qe(ly(Te,"utf8"))):[];ne[W.step]=Le.length>0?Or(H,`s${W.step}.srt`):"",Le.length>0?(pe={cues:Le,opsBefore:W.ops.length},vi(ne[W.step],at(Le))):d.push(`Step ${W.step+1}: no speech was recognised; no captions.`)}else if(W.kind==="subtitles"&&ke.op==="burn_subtitles"&&ke.subtitles)if(W.ops.length===0)ne[W.step]=ke.subtitles;else{let Te=ly(ke.subtitles,"utf8"),Le=/\.(ass|ssa)$/i.test(ke.subtitles),Lr=Le?Fm(Te,W.ops):at(gs(gt(qe(Te)),W.ops)),ep=Or(H,`s${W.step}${Le?".ass":".srt"}`);vi(ep,Lr),ne[W.step]=Le||Lr.trim()?ep:""}else throw new l(`Internal: step ${W.step+1} cannot resolve ${W.kind}.`);O=J()}let q=[],ee=[];if(a){let G=O.gif?null:await xr(i,r.signal);if(!G)d.push("chapters: a GIF/WebP cannot hold chapters; none written.");else if(G.markers.length===0)d.push("chapters: the input has no markers (add_marker) or chapters; none written.");else if(ee=Lm(G.markers,O.timeOps),q=O.durationSec?ys(Ss(ee),O.durationSec):[],q.length===0)d.push("chapters: no marker falls inside the result; none written.");else{let W=e.dryRun?"<chapters.txt>":Or(H,"chapters.txt");e.dryRun||vi(W,xs(q)),O=J(W)}}let ae={...e.recipe&&{recipe:e.recipe,expandedSteps:p},steps:O.summary,...e.dryRun&&O.pending.length>0&&{measuredOnRun:O.pending.map(G=>`step ${G.step+1}: ${G.kind}`)},processes:O.gif?2:1,width:O.width,height:O.height,durationSec:O.durationSec,...M.length>0&&{fallbackFonts:M},...d.length>0&&{warnings:d},...q.length>0&&{chapters:q}};if(e.dryRun)return S({dryRun:!0,...ae,ffmpegArgs:O.args});let _=()=>{try{let G=e.recipe??o?.recipe;return{editSpecPath:ay(w,{serverVersion:_t(),source:Dl(i),steps:z,...G?{recipe:G}:{},quality:s,chapters:a})}}catch{return{}}};for(let G of O.files)vi(G.path,G.content);if(await U(O.args,{output:K,durationSec:O.durationSec,inputDurationSec:c.durationSec,extra:r}),O.gif){let G=await Vn(K,w,O.gif,r);return S({outputPath:w,...ae,animation:G,..._()})}let A;if(pe)try{let G=Kw(pe.cues,O.timeOps,pe.opsBefore);G.length>0&&(vi(y,at(G)),A=y)}catch{A=void 0}let oe;if(q.length>0)try{oe=yr(w,ee.filter(G=>G.t<(O.durationSec??1/0)))}catch{}let{note:re,...le}=ey(i,w,O);return re&&d.push(re),S({outputPath:w,...ae,...d.length>0&&{warnings:d},...oe&&{markersPath:oe},...A&&{subtitlesPath:A},...le,..._()})}finally{py(H,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as $i}from"zod";var pM={input:$i.string().min(1).describe("Source video path."),platform:$i.enum($a).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:$i.enum(["pad","crop"]).optional().describe("Fit to the platform aspect: pad (default) or crop."),output:$i.string().optional().describe("Output path; default SCREENCAST_HOME/edits."),overwrite:$i.boolean().optional().describe("Replace an existing output (default false).")};function hy(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:pM,outputSchema:Y,annotations:C},async(e,r)=>{try{k(),F(e.input);let n=e.platform,o=B(e.output,n,".mp4",{overwrite:e.overwrite}),i=Jg(e.input,o,n,e.fit??"pad");await U(i,{output:o,durationSec:await ue(e.input),extra:r});let s=nl[n];return S({outputPath:o,platform:n,aspect:s.aspect,fps:s.fps})}catch(n){return E(n)}})}import{z as Ee}from"zod";import{existsSync as fc,mkdirSync as dM,mkdtempSync as mM,readFileSync as Ll,rmSync as Bl,writeFileSync as gy}from"node:fs";import{tmpdir as fM,release as hM,version as gM}from"node:os";import{join as mn}from"node:path";var bM=_t(),wM={input:Ee.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),sessionId:Ee.string().min(1).optional().describe("Or a stopped session's id."),title:Ee.string().max(200).optional().describe("Issue title."),actual:Ee.string().max(4e3).optional().describe("What happened."),expected:Ee.string().max(4e3).optional().describe("What should happen."),start:Ee.number().nonnegative().optional().describe("Clip start s (default: end - clipSec)."),end:Ee.number().positive().optional().describe("Clip end s (default: recording end)."),clipSec:Ee.number().positive().max(Hs).optional().describe(`Clip length without start (default ${Lu}).`),redact:Ee.boolean().optional().describe("Box out OCR-found secrets in every output (default true; needs Windows OCR)."),secretPattern:Ee.string().optional().describe("Secret regex (default: API keys, tokens, password: values)."),regions:Ee.array(_n).optional().describe("Extra boxes (video px; start/end on the clip clock)."),errorPattern:Ee.string().optional().describe("Error-line regex."),scanEverySec:Ee.number().positive().optional().describe(`OCR every N s (default ${Bu}).`),maxFrames:Ee.number().int().min(1).max(Ms).optional().describe(`Scan frame cap (default ${Ht}).`),gif:Ee.boolean().optional().describe("Also export a GIF (default true)."),maxBytes:Ee.number().int().min(1e4).optional().describe(`GIF size budget (default ${Mr}).`),outputDir:Ee.string().optional().describe("Package folder (default: a new one in SCREENCAST_HOME/edits)."),overwrite:Ee.boolean().optional().describe("Replace a report already in outputDir.")},ki=t=>Math.round(t*1e3)/1e3;async function yM(){if(process.platform!=="win32")return null;try{return(await mr()).map(e=>`${e.width}x${e.height}${e.dpi?` @${Math.round(e.dpi/96*100)}%`:""}${e.primary?" (primary)":""}`).join(", ")}catch{return null}}function by(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:wM,outputSchema:N({outputDir:Ee.string(),reportPath:Ee.string(),jsonPath:Ee.string(),clipPath:Ee.string()}),annotations:C},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 Xs(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=Kf(c,e),d=ki(u.end-u.start),p=e.redact!==!1,f=e.secretPattern??We;je(["x"],f),e.errorPattern!==void 0&&je(["x"],e.errorPattern);let m="gif",h=xn(e.outputDir,ye("edits"))??mn(ye("edits"),`bug-report-${be()}-${we()}`),b={markdown:mn(h,qt.markdown),json:mn(h,qt.json),clip:mn(h,qt.clip),gif:mn(h,qt.gif(m)),sheet:mn(h,qt.contactSheet)},w=Object.values(b).filter(v=>fc(v));if(w.length>0&&!e.overwrite)throw new l(`The folder already holds a report: ${w.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);fc(h)||(dM(h,{recursive:!0}),n=h);let g=[],y=mM(mn(fM(),"screencast-bug-"));try{let v="unavailable",x=null,T=await _r();if(T.available)x=await Fn(s.path,{everySec:e.scanEverySec??Bu,maxFrames:e.maxFrames??Ht,range:{start:u.start,duration:d}},y,r.signal),v="read";else{if(p)throw new l(`The secret scan needs Windows OCR, which is unavailable here${T.error?` (${T.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 R=x&&p?Vf(Sr(x,f,!0,"line").redactRegions):[],P=[...R,...e.regions??[]],z=x?Qf(x.frames,e.errorPattern??qs,p?f:null):[];r.signal.throwIfAborted();let H=[{op:"trim",start:u.start,end:u.end},...P.length>0?[{op:"redact",regions:P,style:"box"}]:[]],D=pc(s.path,b.clip,H,{width:a.width,height:a.height,fps:a.fps??30,durationSec:a.durationSec,hasAudio:a.audioCodec!==null});await U(D.args,{output:b.clip,durationSec:D.durationSec,inputDurationSec:d,extra:r}),o.push(b.clip);let M=null;e.gif!==!1&&(M=await Vn(b.clip,b.gif,{format:m,maxBytes:e.maxBytes??Mr},r),o.push(b.gif),M.note&&g.push(M.note)),await Us(b.clip,js(d,Go),b.sheet,{tileWidth:qo},r.signal),o.push(b.sheet);let ie=(s.eventsPath?Du(Ie(Ll(s.eventsPath,"utf8"))):[]).map(A=>p?{...A,text:je([A.text],f)[0]??A.text}:A),Z=s.eventsPath?ie.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).",K=ft(s.path),X=fc(K)?eh(Fs(Ll(K,"utf8")),u,p?f:null):void 0,ne=st(s.path),$=fc(ne)?th(Dn(Ll(ne,"utf8")),u,s.record?.perf?.summary?.process):[],J=ya(xa(i)??""),O=await yM(),pe=s.record,q=A=>p?je([A],f)[0]??A:A,ee=[["OS",`${gM()} (${hM()}), ${process.arch}`],...O?[["Displays",O]]:[],...pe?[["Recorded target",q(pe.target)]]:[],...pe?.matchedWindow?[["Window",q(pe.matchedWindow)]]:[],...pe?.backend?[["Capture backend",pe.backend]]:[],["Recording",`${a.width}x${a.height}${a.fps?` @ ${Math.round(a.fps*100)/100} fps`:""}, ${ki(c)} s${a.videoCodec?`, ${a.videoCodec}`:""}`],["ffmpeg",J.version??"unknown"],["screencast-mcp",`${bM} (Node ${process.version})`]],ae={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:ki(c),width:a.width,height:a.height},files:{clip:qt.clip,...M?{gif:qt.gif(m)}:{},contactSheet:qt.contactSheet},...M?{gif:{format:m,sizeBytes:M.sizeBytes,withinBudget:M.withinBudget}}:{},steps:ie.slice(0,Gs),...ie.length>Gs?{stepsOmitted:ie.length-Gs}:{},...Z?{stepsNote:Z}:{},errors:z,...X?{logs:X}:{},...$.length?{perf:$}:{},ocr:v,redaction:{scanned:x!==null&&p,...x&&p?{everySec:ki(x.step),framesScanned:x.frames.length}:{},found:R.length,manual:e.regions?.length??0},environment:ee};gy(b.markdown,Zf(ae)),o.push(b.markdown),gy(b.json,JSON.stringify({...ae,steps:ie,redaction:{...ae.redaction,regions:P}},null,2)+`
|
|
379
|
+
`),o.push(b.json),x?.clamped&&g.push(`The scan interval was widened to ${ki(x.step)} s to fit maxFrames.`);let{images:_}=await Pe([b.sheet],Ce,1);return S({outputDir:h,reportPath:b.markdown,jsonPath:b.json,clipPath:b.clip,...M?{gifPath:b.gif,gifSizeBytes:M.sizeBytes,gifWithinBudget:M.withinBudget}:{},contactSheetPath:b.sheet,clip:{start:u.start,end:u.end},steps:ie.length,errors:z.map(A=>A.text),ocr:v,redaction:ae.redaction,...g.length>0?{warnings:g}:{},next:`Review the clip and report.md, then: gh issue create --title ${JSON.stringify(ae.title)} --body-file ${JSON.stringify(b.markdown)} and drag the GIF into the issue.`,note:"Redaction is OCR-based and best-effort: look at the clip before posting it anywhere public."},_)}finally{Bl(y,{recursive:!0,force:!0})}}catch(i){if(n)Bl(n,{recursive:!0,force:!0});else for(let s of o)Bl(s,{force:!0});return E(i)}})}import{z as Nr}from"zod";import{existsSync as hc,mkdirSync as Gl,mkdtempSync as RM,readFileSync as Ay,readdirSync as Cy,rmSync as fn,rmdirSync as TM,statSync as MM,writeFileSync as Py}from"node:fs";import{tmpdir as AM}from"node:os";import{join as Ve}from"node:path";var Ei=100,xM=.1,SM=1280,wy=40,vM=24,uo={markdown:"guide.md",html:"guide.html",images:"images",image:t=>`step-${String(t).padStart(2,"0")}.png`};function jl(t){return t.label?`${t.text} ${t.label}`:t.text}var $M=t=>Math.round(t*1e3)/1e3;function kM(t,e,r){let n=Math.max(0,e-1/(r>0?r:30));return $M(Math.min(Math.max(0,t-xM),n))}function Wl(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 yy(t,e,r){let o=t.map(s=>({line:s,d:Wl(s,e,r)})).filter(s=>s.d<=vM&&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>wy){let s=[...o.words].sort((a,c)=>Wl(a,e,r)-Wl(c,e,r))[0];i=s?s.text.trim():`${i.slice(0,wy-1).trimEnd()}\u2026`}return i.length>0?i:null}function EM(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 Ul(t,e){let r=e.secretPattern??We,n=i=>je([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:kM(i.t,e.durationSec,e.fps)},c=i.element?.name??e.labels?.[s];if(i.action==="click"||i.action==="double_click"){let u=EM(i);return i.inFrame===!1?{...a,text:i.element?.name?n(`${u} ${Ou(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 xy(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 Sy(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,${SM})':h=-2:flags=lanczos`,i=`[0:v]${n.length?n.join(",")+",":""}format=rgba`;if(!e.click)return`${i},${o},format=rgb24[out]`;let s=Il(t.width,t.height),a=s/2,c=Math.max(3,Math.round(s/10)),u=a-c/2-1,d=e.color??uc;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 vy(t,e,r){return["-y","-v","error","-ss",String(e),"-i",t,"-frames:v","1",r]}var lo=1e7,tr=[{width:1280,q:4},{width:960,q:6},{width:800,q:8},{width:640,q:10},{width:480,q:14},{width:360,q:20}],zl=t=>t.replace(/\.png$/i,".jpg");function $y(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 ky=t=>4*Math.ceil(t/3);function Ey(t,e,r=lo){let n=tr[t].width;for(let o=t+1;o<tr.length;o++)if(e*(tr[o].width/n)**2<=r)return o;return t+1<tr.length?tr.length-1:null}function _y(t,e,r){return["-y","-v","error","-i",t,"-filter_complex",e,"-map","[out]","-frames:v","1",r]}var co=t=>t.replace(/\s*\n\s*/g," ").replace(/([\\`*_[\]<>#|])/g,"\\$1");function Ry(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 Ty(t){let e=t.steps.filter(r=>r.n>0).length;return`${e} step${e===1?"":"s"} from a ${Be(t.recording.durationSec)} recording.`}function My(t){let e=[`# ${co(t.title)}`,"",Ty(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(`## ${co(r)}`,"")),n.n===0){e.push(`> _${co(n.text)}_`,"");continue}let o=n.label?`${co(n.text)} **${co(n.label)}**`:co(n.text);e.push(`${n.n}. ${o} <sub>${Be(n.t)}</sub>`,""),n.image&&e.push(` `,"")}return t.stepsOmitted&&e.push(`_${t.stepsOmitted} more steps not shown._`,""),e.push("<sub>",Ry(t),`Generated by screencast-mcp step_guide, ${t.createdAt}.`,"</sub>",""),e.join(`
|
|
380
|
+
`)}var nt=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),_M=`:root{--bg:#f6f5f2;--card:#fff;--ink:#16161a;--dim:#6b6b74;--line:#e2e0da;--rec:#e5383b}
|
|
379
381
|
@media (prefers-color-scheme:dark){:root{--bg:#121214;--card:#1b1b1f;--ink:#ececf1;--dim:#9a9aa6;--line:#2c2c33}}
|
|
380
382
|
*{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}
|
|
381
383
|
main{max-width:920px;margin:0 auto;padding:40px 16px 64px}
|
|
@@ -390,8 +392,8 @@ li{background:var(--card);border:1px solid var(--line);border-radius:10px;margin
|
|
|
390
392
|
.t{margin-left:auto;font:12px/1 ui-monospace,Consolas,monospace;color:var(--dim)}
|
|
391
393
|
li img{display:block;width:100%;height:auto;border-top:1px solid var(--line)}
|
|
392
394
|
.note{color:var(--dim);font-style:italic;margin:0 0 18px;padding-left:18px;border-left:3px solid var(--line)}
|
|
393
|
-
footer{color:var(--dim);font-size:13px;margin-top:40px;border-top:1px solid var(--line);padding-top:16px}`;function
|
|
394
|
-
`)}var
|
|
395
|
+
footer{color:var(--dim);font-size:13px;margin-top:40px;border-top:1px solid var(--line);padding-top:16px}`;function Hl(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>${nt(n)}</h2>`)),s.n===0){i(),r.push(`<p class="note">${nt(s.text)}</p>`);continue}o||r.push("<ol>"),o=!0;let a=s.label?`${nt(s.text)} <strong>${nt(s.label)}</strong>`:nt(s.text);r.push(`<li><div class="cap"><span class="n">${String(s.n).padStart(2,"0")}</span><span>${a}</span><span class="t">${Be(s.t)}</span></div>`+(s.image?`<img src="${nt(e(s.image))}" alt="Step ${s.n}: ${nt(jl(s))}" loading="lazy">`:"")+"</li>")}return i(),t.steps.length===0&&r.push(`<p class="note">${nt(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>${nt(t.title)}</title><style>${_M}</style></head><body><main>`,`<header><div class="rec">Step guide</div><h1>${nt(t.title)}</h1><p class="meta">${nt(Ty(t))}</p></header>`,...r,`<footer>${nt(Ry(t))}<br>Generated by screencast-mcp step_guide, ${nt(t.createdAt)}.</footer>`,"</main></body></html>",""].join(`
|
|
396
|
+
`)}var Iy=10,Fy=5,CM={input:Nr.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),sessionId:Nr.string().min(1).optional().describe("Or a stopped session's id."),title:Nr.string().max(200).optional().describe("Guide title."),format:Nr.enum(["md","html","both"]).optional().describe("md + images/, self-contained html, or both (default)."),ocr:Nr.boolean().optional().describe("OCR shots for captions and secret boxes (default true; needs Windows OCR)."),outputDir:Nr.string().optional().describe("Guide folder (default: new in SCREENCAST_HOME/edits)."),overwrite:Nr.boolean().optional().describe("Replace a guide already in outputDir.")};function Oy(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:CM,outputSchema:N({outputDir:Nr.string()}),annotations:C},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 Xs(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 R=await _r();if(!R.available)throw new l(`Captions and the secret scan need Windows OCR, which is unavailable here${R.error?` (${R.error})`:""}.`,"Pass ocr: false for a guide without them (then check the screenshots yourself before sharing), or run doctor.")}let m=xn(e.outputDir,ye("edits"))??Ve(ye("edits"),`step-guide-${be()}-${we()}`),h={markdown:Ve(m,uo.markdown),html:Ve(m,uo.html),images:Ve(m,uo.images)},b=[h.markdown,h.html].filter(R=>hc(R));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=Nu(Ie(Ay(i.eventsPath,"utf8"))),g=w.slice(0,Ei),v=Ul(g,{durationSec:a,fps:c}).map((R,P)=>({i:P,s:R})).filter(({s:R})=>R.shotT!==void 0),x=[];hc(m)||(Gl(m,{recursive:!0}),n=m);let T=RM(Ve(AM(),"screencast-guide-"));try{let R=Ao(r),P=v.length*(f?3:2)||1,z=0,H=()=>R?.(++z/P),D=await Je(v,async({s:q})=>{let ee=Ve(T,`frame-${String(q.n).padStart(3,"0")}.png`);return await te(vy(i.path,q.shotT,ee),6e4,{signal:r.signal}),H(),ee}),M=D.map(()=>null);if(f)for(let q=0;q<D.length;q+=Iy)r.signal.throwIfAborted(),(await mt(D.slice(q,q+Iy),T,r.signal,{sameSize:!0})).forEach((ae,_)=>{M[q+_]=ae,H()});let ie=g.map(()=>null),Z=v.map(({i:q,s:ee},ae)=>{let _=M[ae];return _?(ee.x!==void 0&&ee.y!==void 0&&(ie[q]=yy(_.lines,ee.x,ee.y)),Sr({frames:[{..._,t:0,path:""}],step:1,end:1},We,!0,"line").redactRegions):[]}),K=xy(Ul(g,{durationSec:a,fps:c,labels:ie}),He(i.path)),X=d?h.images:Ve(T,"images");if(d&&hc(X)&&e.overwrite)for(let q of Cy(X))/^step-\d+\.png$/.test(q)&&fn(Ve(X,q),{force:!0});Gl(X,{recursive:!0});let ne=0,$={width:s.width,height:s.height},J=await Je(v,async({i:q},ee)=>{let ae=K[q],_=uo.image(ae.n),A=ae.x!==void 0&&ae.y!==void 0?{x:ae.x,y:ae.y}:void 0,oe=Sy($,{click:A,boxes:Z[ee]}),re=Ve(X,_);return await te(_y(D[ee],oe,re),6e4,{signal:r.signal}),H(),{step:ae,file:_,out:re}});for(let[q,{step:ee,file:ae,out:_}]of J.entries())d&&o.push(_),ee.image=ae,ne+=Z[q].length;let O=w.length===0?"The event log has no clicks, shortcuts, typing, or scrolls.":void 0,pe={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:K,...w.length>Ei?{stepsOmitted:w.length-Ei}:{},...O?{stepsNote:O}:{},ocr:f?"read":"off",redactions:ne};if(d&&(Py(h.markdown,My(pe)),o.push(h.markdown)),p){let q=Ve(T,"html");Gl(q,{recursive:!0});let ee=K.flatMap(le=>le.image?[le.image]:[]),ae=le=>`data:image/jpeg;base64,${Ay(Ve(q,zl(le))).toString("base64")}`,_=async(le,G)=>{let W=Ve(q,zl(le));return await te($y(Ve(X,le),G,W),6e4,{signal:r.signal}),ky(MM(W).size)},A=ee.length>Fy?ee.filter((le,G)=>G%Math.ceil(ee.length/Fy)===0):[],oe=0;for(;A.length>0&&oe<tr.length-1;oe++){let le=0;for(let G of A)le+=await _(G,tr[oe]);if(le/A.length*ee.length<=lo*.9)break}let re="";for(let le=oe;le!==null;){let G=tr[le],W=0;for(let Te of ee)W+=await _(Te,G);re=W<=lo?Hl(pe,ae):"";let ke=re?Buffer.byteLength(re):W;if(ke<=lo)break;let Re=Ey(le,ke);Re===null&&(re||=Hl(pe,ae),x.push(`guide.html is ${(Buffer.byteLength(re)/1e6).toFixed(1)} MB, over the ${lo/1e6} MB budget even with ${G.width} px JPEGs; use format: md for a guide this long.`)),le=Re}Py(h.html,re),o.push(h.html)}if(e.overwrite&&(p||fn(h.html,{force:!0}),!d&&(fn(h.markdown,{force:!0}),hc(h.images)))){for(let q of Cy(h.images))/^step-\d+\.png$/.test(q)&&fn(Ve(h.images,q),{force:!0});try{TM(h.images)}catch{}}return pe.stepsOmitted&&x.push(`Only the first ${Ei} steps were written; ${pe.stepsOmitted} more were left out.`),O&&x.push(O),S({outputDir:m,...d?{markdownPath:h.markdown,imagesDir:h.images}:{},...p?{htmlPath:h.html}:{},steps:K.map(q=>({...q.n>0?{n:q.n}:{},t:q.t,action:q.action,caption:jl(q),...q.section?{section:q.section}:{},...q.image?{image:q.image}:{}})),ocr:pe.ocr,redactions:ne,...x.length>0?{warnings:x}:{},note:f?"Captions are OCR-based templates: rewrite them in guide.md as needed. The secret scan is best-effort: look at the screenshots before sharing.":"Not scanned for secrets: look at the screenshots before sharing."})}finally{fn(T,{recursive:!0,force:!0})}}catch(i){if(n)fn(n,{recursive:!0,force:!0});else for(let s of o)fn(s,{force:!0});return E(i)}})}import{existsSync as Ny,rmSync as PM}from"node:fs";import{ResourceTemplate as Dy}from"@modelcontextprotocol/sdk/server/mcp.js";import{SubscribeRequestSchema as IM,UnsubscribeRequestSchema as FM}from"@modelcontextprotocol/sdk/types.js";var Ly=(t,e)=>({contents:[{uri:t,mimeType:"application/json",text:JSON.stringify(e,null,2)}]});function By(t){let e=se().get(t);if(!e)throw new l(`No session with id ${t}.`);return e}function jy(t){t.registerResource("sessions","screencast://sessions",{title:"Recording sessions",description:"Every recording session (active and finished), newest first.",mimeType:"application/json"},r=>Ly(r.href,se().list())),t.registerResource("session",new Dy("screencast://sessions/{id}",{list:()=>({resources:se().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=By(String(n));return Ly(r.href,{...o,fileExists:Ny(o.outputPath)})}),t.registerResource("session-poster",new Dy("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=By(String(n));if(!Ny(o.outputPath))throw new l(`Recording file not found: ${o.outputPath}`);let{durationSec:i}=await L(o.outputPath),s=Xe(".png");try{await te(["-y","-v","error","-ss",String((i??0)/2),"-i",o.outputPath,"-frames:v","1",s],3e4);let[a]=(await Pe([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{PM(s,{force:!0})}});let e=new Map;t.server.registerCapabilities({resources:{subscribe:!0}}),t.server.setRequestHandler(IM,r=>(e.set(r.params.uri,Wy(r.params.uri)),{})),t.server.setRequestHandler(FM,r=>(e.delete(r.params.uri),{})),se().onChange(()=>{if(!(Rs()||!t.isConnected())){try{t.sendResourceListChanged()}catch{}for(let[r,n]of e){let o=Wy(r);o!==n&&(e.set(r,o),t.server.sendResourceUpdated({uri:r}).catch(()=>{}))}}})}function Wy(t){if(t==="screencast://sessions")return JSON.stringify(se().list());let e=/^screencast:\/\/sessions\/([^/]+)$/.exec(t),r=e?se().get(decodeURIComponent(e[1])):void 0;return r?JSON.stringify(r):null}import{z as lt}from"zod";var po=t=>({messages:[{role:"user",content:{type:"text",text:t}}]}),mo={bugReproClip:(t,e)=>`Record a short bug-reproduction clip of ${t}.${e?` The bug: ${e}.`:""}
|
|
395
397
|
|
|
396
398
|
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.
|
|
397
399
|
2. sample_frames { input: <recording>, mode: "scenes" } to see what happened, and describe the moment the bug appears.
|
|
@@ -428,63 +430,63 @@ Give a timestamped summary of the main steps and anything that looks wrong.`,doc
|
|
|
428
430
|
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.
|
|
429
431
|
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.
|
|
430
432
|
3. Read the returned steps and rewrite any vague caption ("Click the marked spot") in guide.md, using the screenshot to name the control.
|
|
431
|
-
Report the guide paths, the steps, and anything you would check before sharing it.`};function
|
|
432
|
-
`)}},n=e.oninitialized;e.oninitialized=()=>{n?.(),r(!0)},e.setNotificationHandler(
|
|
433
|
+
Report the guide paths, the steps, and anything you would check before sharing it.`};function Uy(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:lt.string().optional().describe("What to record, e.g. window:My App (default: full)."),notes:lt.string().optional().describe("What the bug is.")}},({target:e,notes:r})=>po(mo.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:lt.string().optional().describe("What to record, e.g. window:My App (default: full)."),notes:lt.string().optional().describe("What the bug is."),expected:lt.string().optional().describe("What should happen instead.")}},({target:e,notes:r,expected:n})=>po(mo.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:lt.string().optional().describe("What to record (default: full)."),maxMB:lt.string().optional().describe("Size budget in MB (default 10).")}},({target:e,maxMB:r})=>po(mo.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:lt.string().optional().describe("What to watch (default: full)."),expectation:lt.string().optional().describe("What should change.")}},({target:e,expectation:r})=>po(mo.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:lt.string().describe("Path to the recording.")}},({path:e})=>po(mo.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:lt.string().optional().describe("What to record (default: full)."),task:lt.string().optional().describe("The task the guide teaches.")}},({target:e,task:r})=>po(mo.documentSteps(e||"full",r??"")))}import{fileURLToPath as OM}from"node:url";import{RootsListChangedNotificationSchema as NM}from"@modelcontextprotocol/sdk/types.js";function DM(t){let e=[];for(let{uri:r}of t)if(r.startsWith("file:"))try{e.push(OM(r))}catch{}return e}function zy(t){let e=t.server,r=async o=>{if(!e.getClientCapabilities()?.roots){ko(null);return}o&&ko("pending");try{let{roots:i}=await e.listRoots();ko(DM(i))}catch(i){o&&ko([]),process.stderr.write(`roots/list failed: ${j(i)}
|
|
434
|
+
`)}},n=e.oninitialized;e.oninitialized=()=>{n?.(),r(!0)},e.setNotificationHandler(NM,()=>r(!1))}var BM=_t();function gc(t={}){let e=Ri(t.toolsets??process.env.SCREENCAST_TOOLSETS);e.unknown.length>0&&console.error(`screencast-mcp: ignoring unknown SCREENCAST_TOOLSETS entries: ${e.unknown.join(", ")} (known: all, ${_i.join(", ")})`);let r=new LM({name:"screencast-mcp",version:BM},{capabilities:{logging:{}},instructions:rp(e)});Kp(r);let n=WM(r);return Bf(r),jf(r),Ah(r),Ih(r),Oh(r),Ch(r),Lh(r),Bh(r),jh(r),Uh(r),lg(r),pg(r),mg(r),fg(r),Sg(r),Eg(r),Tg(r),Og(r),Lg(r),Bg(r),Wg(r),Yg(r),Kg(r),tb(r),rb(r),nb(r),lb(r),pb(r),bb(r),kb(r),Eb(r),Ab(r),Nb(r),Ub(r),Jb(r),Yb(r),Kb(r),tw(r),rw(r),nw(r),ow(r),Qh(r),iw(r),sw(r),fw(r),hw(r),gw(r),Dh(r),xw(r),Nw(r),Dw(r),Lw(r),Bw(r),Ww(r),Uw(r),zw(r),Yw(r),fy(r),hy(r),by(r),Oy(r),jM(n,e),jy(r),Uy(r),zy(r),r}function WM(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{dc(a)}catch(u){return E(u)}return i(a,c)};let s=r(...n);return e.set(n[0],s),s}),e}function jM(t,e){for(let[r,n]of t){let o=tp(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 UM,existsSync as zM,mkdirSync as HM,readFileSync as GM,writeFileSync as qM}from"node:fs";import{homedir as XM}from"node:os";import{dirname as JM,join as hn}from"node:path";import{createInterface as YM}from"node:readline/promises";var bc=["claude-desktop","claude-code","cursor","vscode"],qy=`setup options:
|
|
433
435
|
--yes, -y answer yes: install FFmpeg and write client configs without asking
|
|
434
436
|
--dry-run print the checks and the config changes; change nothing
|
|
435
437
|
--clients <list> (or --clients=<list>) detected (default) | none | a comma list of
|
|
436
|
-
${
|
|
438
|
+
${bc.join(", ")}
|
|
437
439
|
--no-install never offer to install FFmpeg
|
|
438
440
|
--force replace an existing, different "screencast" server entry
|
|
439
441
|
--test record a 3 s test clip and export a GIF
|
|
440
442
|
|
|
441
443
|
setup exits 0 when the doctor checks pass, 1 when something still needs fixing.
|
|
442
|
-
`,
|
|
443
|
-
`}}function
|
|
444
|
+
`,Xl="@tmhs/screencast-mcp",fo="screencast",ql={command:"npx",args:["-y",Xl]},Hy=["install","--id","Gyan.FFmpeg","-e","--accept-source-agreements","--accept-package-agreements"];function Xy(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=>!bc.includes(u));if(c.length>0)throw new Error(`--clients: unknown client ${c.map(u=>`"${u}"`).join(", ")}; use ${bc.join(", ")}, detected, or none.`);e.clients=a;break}default:throw new Error(`Unknown setup option "${n}". Run screencast-mcp --help.`)}}return e}function KM(t){return t.env.APPDATA??hn(t.home,"AppData","Roaming")}function Jy(t){let e=KM(t);return[{id:"claude-desktop",name:"Claude Desktop",path:hn(e,"Claude","claude_desktop_config.json"),key:"mcpServers",entry:ql,marker:hn(e,"Claude")},{id:"cursor",name:"Cursor",path:hn(t.home,".cursor","mcp.json"),key:"mcpServers",entry:ql,marker:hn(t.home,".cursor")},{id:"vscode",name:"VS Code",path:hn(e,"Code","User","mcp.json"),key:"servers",entry:{type:"stdio",...ql},marker:hn(e,"Code","User")}]}function VM(t){return["mcp","add","--scope","user",fo,"--",...t==="win32"?["cmd","/c","npx","-y",Xl]:["npx","-y",Xl]]}var QM=(t,e)=>JSON.stringify(t)===JSON.stringify(e);function ZM(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 (${j(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(QM(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)+`
|
|
445
|
+
`}}function eA(t,e){let r=t===""?[]:t.replace(/\n$/,"").split(`
|
|
444
446
|
`),n=e===""?[]:e.replace(/\n$/,"").split(`
|
|
445
447
|
`),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(`
|
|
446
448
|
`)+`
|
|
447
|
-
`}function
|
|
448
|
-
`),!1}let s=
|
|
449
|
+
`}function tA(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 rA(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 nA={ok:"[ok] ",warn:"[warn]",fail:"[fail]",info:"[info]"};async function oA(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}: ${j(a)}
|
|
450
|
+
`),!1}let s=ZM(i,t.key,fo,t.entry,e.force);switch(s.status){case"unchanged":return r.out(` ${t.name}: already configured (${t.path})
|
|
449
451
|
`),!0;case"invalid":return r.out(` ${t.name}: left ${t.path} alone: ${s.reason}. Add the server by hand (see docs/connect.html).
|
|
450
|
-
`),!1;case"conflict":return r.out(` ${t.name}: ${t.path} already has a different "${
|
|
452
|
+
`),!1;case"conflict":return r.out(` ${t.name}: ${t.path} already has a different "${fo}" entry; kept it (pass --force to replace).
|
|
451
453
|
`),!1}if(e.dryRun)return r.out(` ${t.name}: would ${o?"update":"create"} ${t.path}:
|
|
452
|
-
`),r.out(
|
|
453
|
-
`),!1;try{let a=null;return o?(a
|
|
454
|
-
`),!0}catch(a){return r.out(` ${t.name}: could not write ${t.path}: ${
|
|
455
|
-
`),!1}}async function
|
|
454
|
+
`),r.out(eA(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).
|
|
455
|
+
`),!1;try{let a=null;return o?(a=tA(t.path,r.now()),n.copyFile(t.path,a)):n.mkdir(JM(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.
|
|
456
|
+
`),!0}catch(a){return r.out(` ${t.name}: could not write ${t.path}: ${j(a)}
|
|
457
|
+
`),!1}}async function iA(t,e){let r=VM(e.platform);if((await e.exec("claude",["mcp","get",fo])).code===0)return e.out(` Claude Code: already has a "${fo}" server (claude mcp get ${fo}).
|
|
456
458
|
`),!0;if(t.dryRun)return e.out(` Claude Code: would run: claude ${r.join(" ")}
|
|
457
459
|
`),!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(" ")}
|
|
458
460
|
`),!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}`}).
|
|
459
461
|
`),!1):(e.out(` Claude Code: added (user scope). Check it with claude mcp list.
|
|
460
|
-
`),!0)}async function
|
|
462
|
+
`),!0)}async function sA(t){let e=[];for(let n of Jy(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"),bc.filter(n=>e.includes(n))}async function Yy(t,e){let r=e.out;r(`screencast-mcp setup${t.dryRun?" (dry run: nothing is installed or written)":""}
|
|
461
463
|
|
|
462
|
-
`);let n;try{n=await e.doctor()}catch(c){return e.err(`screencast-mcp: the doctor checks failed to run: ${
|
|
463
|
-
`),1}for(let c of
|
|
464
|
+
`);let n;try{n=await e.doctor()}catch(c){return e.err(`screencast-mcp: the doctor checks failed to run: ${j(c)}
|
|
465
|
+
`),1}for(let c of rA(n,e.env,e.platform))r(`${nA[c.state]} ${c.text}
|
|
464
466
|
`);let o=n.problems??[];if(o.length>0){r(`
|
|
465
467
|
What doctor says to fix:
|
|
466
468
|
`);for(let c of o)r(` - ${c}
|
|
467
|
-
`)}let i=n.ffmpeg??{};if((!i.found||i.meetsFfmpeg8===!1)&&t.install&&e.platform==="win32"){let c=`winget ${
|
|
469
|
+
`)}let i=n.ffmpeg??{};if((!i.found||i.meetsFfmpeg8===!1)&&t.install&&e.platform==="win32"){let c=`winget ${Hy.join(" ")}`;if(r(`
|
|
468
470
|
FFmpeg 8 ${i.found?"is not installed (found an older one)":"is missing"}.
|
|
469
471
|
`),t.dryRun)r(` would run: ${c}
|
|
470
472
|
`);else if(t.yes||await e.confirm("Install FFmpeg 8 with winget now?")){r(` running: ${c}
|
|
471
|
-
`);let u=await e.exec("winget",
|
|
473
|
+
`);let u=await e.exec("winget",Hy).catch(d=>({code:1,stdout:"",stderr:j(d)}));u.code===0?r(` FFmpeg installed. Open a new terminal so PATH picks it up, then run setup again.
|
|
472
474
|
`):r(` winget failed (${(u.stderr||u.stdout).trim().split(`
|
|
473
475
|
`).pop()||`exit ${u.code}`}). Install it yourself: ${c}
|
|
474
476
|
`)}else r(` skipped. Install it yourself: ${c}
|
|
475
|
-
`)}if(t.clients!=="none"){let c=t.clients==="detected"?await
|
|
477
|
+
`)}if(t.clients!=="none"){let c=t.clients==="detected"?await sA(e):t.clients;r(`
|
|
476
478
|
MCP clients:
|
|
477
479
|
`),c.length===0&&r(` none found (Claude Desktop, Claude Code, Cursor, VS Code). Name one with --clients, or see docs/connect.html.
|
|
478
|
-
`);let u=new Map(
|
|
480
|
+
`);let u=new Map(Jy(e).map(d=>[d.id,d]));for(let d of c){let p=u.get(d);p?await oA(p,t,e):await iA(t,e)}}if(t.test)if(r(`
|
|
479
481
|
Test clip:
|
|
480
482
|
`),t.dryRun)r(` would record 3 s of the screen and export a GIF.
|
|
481
483
|
`);else try{let c=await e.testClip();r(` recorded 3 s and exported ${c}
|
|
482
|
-
`),await e.open(c).catch(()=>{})}catch(c){return r(` the test clip failed: ${
|
|
484
|
+
`),await e.open(c).catch(()=>{})}catch(c){return r(` the test clip failed: ${j(c)}
|
|
483
485
|
`),1}let a=n.ok??o.length===0;return r(a?`
|
|
484
486
|
All checks passed.
|
|
485
487
|
`:`
|
|
486
488
|
Some checks need attention (above). Run setup again after fixing them.
|
|
487
|
-
`),a?0:1}function
|
|
489
|
+
`),a?0:1}function aA(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 cA={exists:t=>zM(t),readFile:t=>GM(t,"utf8"),writeFile:(t,e)=>qM(t,e),mkdir:t=>{HM(t,{recursive:!0})},copyFile:(t,e)=>UM(t,e)};function Ky(t){let e=process.platform,r=aA(e),n=async i=>{let s=await t.connect();try{return await i(s)}finally{await s.close()}},o=async(i,s,a)=>{let c=await i.call(s,a);if(c.isError)throw new Error(`${s}: ${c.text}`);return c.structured??{}};return{out:t.io.out,err:t.io.err,env:process.env,platform:e,home:XM(),fs:cA,exec:r,doctor:()=>n(async i=>await o(i,"doctor",{})),confirm:async i=>{if(!process.stdin.isTTY||!process.stdout.isTTY)return!1;let s=YM({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 ex=_t(),De=class extends Error{},gA=new Set(["record","call","setup","help","--help","-h","--version","-v"]);function tx(t){return t.length>0&&gA.has(t[0]??"")}var bA=`screencast-mcp: an MCP server for Windows screen recording.
|
|
488
490
|
|
|
489
491
|
Usage:
|
|
490
492
|
screencast-mcp run the MCP server over stdio (default)
|
|
@@ -509,40 +511,42 @@ record options:
|
|
|
509
511
|
--redact-secrets OCR the recording and blur on-screen secrets (API keys, tokens,
|
|
510
512
|
password: values) in the GIF and contact sheet (Windows OCR)
|
|
511
513
|
--secret-pattern <re> with --redact-secrets, the regex to blur instead of the default
|
|
512
|
-
--max-duration <sec> stop recording after <sec> seconds, an integer 0-${
|
|
514
|
+
--max-duration <sec> stop recording after <sec> seconds, an integer 0-${Dt}
|
|
513
515
|
(0 = no cap; default SCREENCAST_MAX_RECORDING_SEC, else 3600)
|
|
514
516
|
--events also log clicks, scrolls and typing bursts to recording.events.jsonl
|
|
515
517
|
--perf also sample CPU and memory to recording.perf.jsonl
|
|
516
518
|
--log <path> follow an app log into recording.logs.jsonl (repeatable)
|
|
519
|
+
--bug-report on failure, write a redacted bug_report package (clip, GIF, steps,
|
|
520
|
+
errors, report.md) to <out>/bug-report/
|
|
517
521
|
--command-env <NAME> run the command line in environment variable NAME instead of
|
|
518
522
|
the arguments after --, so quotes and & survive any shell
|
|
519
523
|
|
|
520
524
|
record exits with the command's exit code and writes <out>/evidence.json.
|
|
521
525
|
|
|
522
|
-
${
|
|
523
|
-
`);return{isError:i.isError===!0,text:s,structured:i.structuredContent}},close:()=>r.close()}}async function
|
|
524
|
-
`),s(127)}),r.on("exit",(a,c)=>s(a??(c?1:0)))})}function
|
|
525
|
-
`)},s=await r.connect();try{let a=null;try{let p=await
|
|
526
|
-
`)}catch(p){i(`recording did not start, running the command without it: ${
|
|
526
|
+
${qy}`;function wA(t,e,r){let n=t[e+1];if(n===void 0||n==="--")throw new De(`${r} needs a value.`);return n}function Jl(t,e,r,n=1/0,o=!1){let i=Number(t);if(t.trim()===""||!Number.isFinite(i)||i<r||i>n||o&&!Number.isInteger(i)){let s=n===1/0?`>= ${r}`:`${r}-${n}`;throw new De(`${e} must be ${o?"an integer":"a number"} ${s}, got "${t}".`)}return i}function yA(t,e){let r=t.indexOf("--"),n={target:"full",fps:15,outDir:"screencast-evidence",artifacts:"failure",lastSec:30,gif:!0,contactSheet:!0,discardOnSuccess:!1,ocrErrors:!1,redactSecrets:!1,command:r===-1?[]:t.slice(r+1)},o,i=r===-1?t:t.slice(0,r);for(let s=0;s<i.length;s++){let a=i[s]??"",c=a.startsWith("--")?a.indexOf("="):-1,u=c===-1?a:a.slice(0,c),d=c===-1?void 0:a.slice(c+1),p=()=>{if(d!==void 0)return d;let f=wA(i,s,u);return s++,f};switch(u){case"--target":n.target=p();break;case"--fps":n.fps=Jl(p(),u,1,120,!0);break;case"--out":n.outDir=p();break;case"--artifacts":{let f=p();if(f!=="failure"&&f!=="always"&&f!=="never")throw new De(`--artifacts must be failure, always, or never, got "${f}".`);n.artifacts=f;break}case"--last":n.lastSec=Jl(p(),u,0);break;case"--max-duration":n.maxDurationSec=Jl(p(),u,0,Dt,!0);break;case"--command-env":o=p();break;case"--no-gif":n.gif=!1;break;case"--no-contact-sheet":n.contactSheet=!1;break;case"--discard-on-success":n.discardOnSuccess=!0;break;case"--redact-secrets":n.redactSecrets=!0;break;case"--secret-pattern":n.secretPattern=p();break;case"--ocr-errors":n.ocrErrors=!0;break;case"--events":n.events=!0;break;case"--perf":n.perf=!0;break;case"--log":n.logs=[...n.logs??[],p()];break;case"--bug-report":n.bugReport=!0;break;default:throw new De(`Unknown record option "${a}". Run screencast-mcp --help.`)}}if(o!==void 0){if(n.command.length>0)throw new De("Give the command either after -- or with --command-env, not both.");let s=e[o];if(s===void 0||s.trim()==="")throw new De(`--command-env ${o}: the environment variable is unset or empty.`);n.command=[s]}else if(n.command.length===0)throw new De("record needs a command after -- (or --command-env NAME), e.g. screencast-mcp record -- npm test");return n}function xA(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:yA(n,e)};case"call":{let[o,i,s]=n;if(!o||o.startsWith("-"))throw new De("call needs a tool name, e.g. screencast-mcp call doctor");if(s!==void 0)throw new De("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:Xy(n)}}catch(o){throw new De(j(o))}}default:throw new De(`Unknown command "${r??""}". Run screencast-mcp --help.`)}}var Vy=/([()\][%!^"`<>&|;, *?])/g,SA=/(\.(cmd|bat)$)|^(npm|npx|pnpm|yarn|corepack)$/i;function Qy(t){return`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}var Kl=/[\s"&|<>^()!;'`$*?%,[\]]/;function vA(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=SA.test(t[0]??"");return t.map((n,o)=>{if(o===0)return n!==""&&Kl.test(n)?Qy(n):n;if(!Kl.test(n)&&n!=="")return n;let i=Qy(n).replace(Vy,"^$1");return r&&(i=i.replace(Vy,"^$1")),i}).join(" ")}function $A(t){return t.length===1?t[0]??"":t.map(e=>Kl.test(e)||e===""?`"${e.replace(/"/g,'\\"')}"`:e).join(" ")}function rx(t,e){return!e||t===null||t<=e?{}:{start:Math.round((t-e)*1e3)/1e3,duration:e}}function kA(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>=Wu))break}return je(n,We)}function EA(t,e=r=>pA(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 De(`Tool arguments are not valid JSON: ${j(o)}`)}if(typeof n!="object"||n===null||Array.isArray(n))throw new De("Tool arguments must be a JSON object.");return n}async function Vl(){let[t,e]=hA.createLinkedPair();await gc({toolsets:"all"}).connect(e);let r=new fA({name:"screencast-mcp-cli",version:ex});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(`
|
|
527
|
+
`);return{isError:i.isError===!0,text:s,structured:i.structuredContent}},close:()=>r.close()}}async function rr(t,e,r){let n=await t.call(e,r);if(n.isError)throw new Error(`${e}: ${n.text}`);return n.structured??{}}var nx={out:t=>process.stdout.write(t),err:t=>process.stderr.write(t)};function _A(t){return new Promise(e=>{let r=uA(vA(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}
|
|
528
|
+
`),s(127)}),r.on("exit",(a,c)=>s(a??(c?1:0)))})}function RA(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 TA={connect:Vl,run:_A,now:()=>Date.now()};async function MA(t,e=nx,r=TA){let n=mA(t.outDir);lA(n,{recursive:!0});let o={command:$A(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}
|
|
529
|
+
`)},s=await r.connect();try{let a=null;try{let p=await rr(s,"start_recording",{target:t.target,fps:t.fps,output:Dr(n,"recording.mp4"),overwrite:!0,...t.maxDurationSec!==void 0?{maxDurationSec:t.maxDurationSec}:{},...t.events?{events:!0}:{},...t.perf?{perf:!0}:{},...t.logs?.length?{logs:t.logs.map(f=>({path:f}))}:{}});a=String(p.sessionId),e.err(`screencast-mcp: recording ${t.target} to ${String(p.outputPath)}
|
|
530
|
+
`)}catch(p){i(`recording did not start, running the command without it: ${j(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 rr(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=RA(o.status,o.endReason,o.durationSec);f&&i(f)}catch(p){i(`stop_recording failed: ${j(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 AA(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: ${j(m)}`),p=null}if(p&&t.gif)try{let m=await rr(s,"export_gif",{input:p,...rx(o.durationSec,t.lastSec),output:Dr(n,"evidence.gif"),overwrite:!0});o.gif=String(m.outputPath)}catch(m){i(`export_gif failed: ${j(m)}`)}if(p&&t.contactSheet)try{let m=await rr(s,"contact_sheet",{input:p,output:Dr(n,"contact-sheet.png"),overwrite:!0,returnImage:!1});o.contactSheet=String(m.outputPath)}catch(m){i(`contact_sheet failed: ${j(m)}`)}f&&Yl(f,{force:!0})}if(o.recording&&u&&t.ocrErrors&&(o.errors=await CA(s,o.recording,o.durationSec,t.lastSec,n,i)),o.recording&&u&&t.bugReport){o.bugReport=null;try{let p=await rr(s,"bug_report",{input:o.recording,title:`${o.command} failed`,actual:`Exited with code ${o.exitCode}.`,clipSec:t.lastSec>0?t.lastSec:void 0,outputDir:Dr(n,"bug-report"),overwrite:!0});o.bugReport=Dr(String(p.outputDir),"report.md")}catch(p){i(`bug_report failed: ${j(p)}`)}}!u&&t.discardOnSuccess&&o.recording&&(Yl(o.recording,{force:!0}),o.recording=null)}finally{await s.close()}return dA(Dr(n,"evidence.json"),JSON.stringify(o,null,2)+`
|
|
527
531
|
`),e.err(`screencast-mcp: command exited ${o.exitCode}; evidence in ${n}`+(o.gif?` (gif: ${o.gif})`:"")+`
|
|
528
|
-
`),o.exitCode}var
|
|
532
|
+
`),o.exitCode}var Zy=120;async function AA(t,e,r,n,o,i){let s=Math.max(1,Math.ceil((r??0)/Zy)),a=await rr(t,"find_text",{input:e,scanEverySec:s,maxFrames:Zy,query:n??We,regex:!0,redact:!0,returnImage:!1}),c=Array.isArray(a.redactRegions)?a.redactRegions:[];if(c.length===0)return null;let u=await rr(t,"redact_region",{input:e,regions:c,style:"blur",output:Dr(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 CA(t,e,r,n,o,i){let s=rx(r,n),a=e,c=null;try{if(s.start!==void 0){let p=await rr(t,"trim",{input:e,start:s.start,duration:s.duration,output:Dr(o,".ocr-tail.mp4"),overwrite:!0});c=String(p.outputPath),a=c}let u=await rr(t,"find_text",{input:a,scanEverySec:1,maxFrames:30,query:qs,regex:!0,returnImage:!1}),d=Array.isArray(u.matches)?u.matches:[];return kA(d)}catch(u){return i(`OCR of error lines failed: ${j(u)}`),null}finally{c&&Yl(c,{force:!0})}}async function PA(t,e,r){let n=EA(e),o=await Vl();try{let i=await o.call(t,n);return i.isError?(r.err(`${i.text}
|
|
529
533
|
`),1):(r.out((i.structured?JSON.stringify(i.structured,null,2):i.text)+`
|
|
530
|
-
`),0)}finally{await o.close()}}async function
|
|
531
|
-
`),2;throw n}switch(r.kind){case"help":return e.out(
|
|
532
|
-
`),0;case"record":return
|
|
533
|
-
`),2;throw n}}}import{readdir as
|
|
534
|
-
`)}catch(n){process.stderr.write(`Orphan reaping skipped: ${
|
|
535
|
-
`)}try{let n=
|
|
536
|
-
`)}catch(n){process.stderr.write(`Replay buffer cleanup skipped: ${
|
|
537
|
-
`)}let e=new
|
|
538
|
-
`)},n=>{process.stderr.write(`Retention prune failed: ${
|
|
539
|
-
`)}),process.stdin.on("end",()=>{
|
|
540
|
-
`),
|
|
541
|
-
`),
|
|
542
|
-
`)})}async function
|
|
543
|
-
`),
|
|
544
|
-
`)}}catch(o){process.stderr.write(`Shutdown cleanup failed: ${
|
|
534
|
+
`),0)}finally{await o.close()}}async function ox(t,e=nx){let r;try{r=xA(t)}catch(n){if(n instanceof De)return e.err(`screencast-mcp: ${n.message}
|
|
535
|
+
`),2;throw n}switch(r.kind){case"help":return e.out(bA),0;case"version":return e.out(`${ex}
|
|
536
|
+
`),0;case"record":return MA(r.options,e);case"setup":return Yy(r.options,Ky({connect:Vl,io:e}));case"call":try{return await PA(r.tool,r.args,e)}catch(n){if(n instanceof De)return e.err(`screencast-mcp: ${n.message}
|
|
537
|
+
`),2;throw n}}}import{readdir as ix,rmdir as IA,stat as FA,unlink as OA}from"node:fs/promises";import{join as ho}from"node:path";var Zl="SCREENCAST_RETENTION_DAYS";function sx(t=process.env){let e=Number(t[Zl]);return Number.isFinite(e)&&e>0?e:null}var Ql=/\.index\.json(\.\d+\.tmp)?$/;async function ax(t,e=Date.now(),r=Fe()){let n=e-t*864e5,o={removed:0,bytes:0},i=async(s,a,c)=>{let u;try{u=await ix(s)}catch{return}for(let d of u){let p=ho(s,d);try{let f=await FA(p);if(f.isDirectory()){if(!c)continue;await i(p,a,!0),(await ix(p)).length===0&&f.mtimeMs<n&&await IA(p)}else!a(d)&&f.mtimeMs<n&&(await OA(p),o.removed++,o.bytes+=f.size)}catch{}}};return await i(ho(r,"screenshots"),()=>!1,!0),await i(ho(r,"frames"),()=>!1,!0),await i(ho(r,"recordings"),s=>!/\.events\.raw(\.stop)?$/.test(s)&&!Ql.test(s),!1),await i(ho(r,"edits"),s=>!Ql.test(s),!1),await i(ho(r,"edits","indexes"),s=>!Ql.test(s),!1),o}var cx=1e4;async function DA(){let t=gc();LA();try{let n=se().reapOrphans();n.length>0&&process.stderr.write(`Reaped ${n.length} orphaned recording(s) on startup.
|
|
538
|
+
`)}catch(n){process.stderr.write(`Orphan reaping skipped: ${j(n)}
|
|
539
|
+
`)}try{let n=se().list().flatMap(i=>i.status==="recording"&&i.replay?[i.replay.dir]:[]),o=Zd(n);o>0&&process.stderr.write(`Removed ${o} leftover replay buffer(s).
|
|
540
|
+
`)}catch(n){process.stderr.write(`Replay buffer cleanup skipped: ${j(n)}
|
|
541
|
+
`)}let e=new NA;await t.connect(e);let r=sx();r!==null&&ax(r).then(n=>{n.removed>0&&process.stderr.write(`Deleted ${n.removed} capture file(s) older than ${r} day(s) (${Zl}).
|
|
542
|
+
`)},n=>{process.stderr.write(`Retention prune failed: ${j(n)}
|
|
543
|
+
`)}),process.stdin.on("end",()=>{go("client disconnected")}),process.stdin.on("close",()=>{go("client disconnected")}),t.server.onclose=()=>{go("transport closed")};for(let n of["SIGINT","SIGTERM","SIGHUP"])process.on(n,()=>{go(n)})}function LA(){process.stdout.on("error",t=>{t.code!=="EPIPE"&&process.stderr.write(`stdout error: ${t.message}
|
|
544
|
+
`),go("client pipe closed")}),process.on("uncaughtException",t=>{process.stderr.write(`Uncaught exception: ${t.stack??t.message}
|
|
545
|
+
`),go("uncaught exception",1)}),process.on("unhandledRejection",t=>{process.stderr.write(`Unhandled rejection: ${t instanceof Error?t.stack??t.message:String(t)}
|
|
546
|
+
`)})}async function go(t,e=0){if(Rs())return;Zm();let r=pd();try{await tf(cx)||process.stderr.write(`Shutdown (${t}): a start_recording call did not finish within ${cx/1e3}s.
|
|
547
|
+
`),gf();let o=se();if(o.activeIds().length>0){let i=null;try{i=k().ffprobe}catch{}let s=await Am(o,a=>i?ue(a,{ffprobe:i}):Promise.resolve(null));process.stderr.write(`Shutdown (${t}): stopped ${s.length} recording(s).
|
|
548
|
+
`)}}catch(o){process.stderr.write(`Shutdown cleanup failed: ${j(o)}
|
|
545
549
|
`)}let n=await r;n>0&&process.stderr.write(`Shutdown (${t}): cancelled ${n} edit job(s).
|
|
546
|
-
`),process.exit(e)}var
|
|
547
|
-
`),process.exit(1)},
|
|
548
|
-
`)}),
|
|
550
|
+
`),process.exit(e)}var ux=t=>{process.stderr.write(`Fatal error: ${j(t)}
|
|
551
|
+
`),process.exit(1)},lx=process.argv.slice(2);tx(lx)?(process.stdout.on("error",t=>{t.code!=="EPIPE"&&process.stderr.write(`stdout error: ${t.message}
|
|
552
|
+
`)}),ox(lx).then(t=>process.exit(t),ux)):DA().catch(ux);
|