@tmhs/screencast-mcp 0.49.1 → 0.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -8
- package/dist/index.js +550 -106
- package/dist/wgcRecorder.js +15 -139
- package/package.json +8 -4
- package/assets/.gitkeep +0 -0
- package/assets/icon.png +0 -0
- package/dist/cli.js +0 -516
- package/dist/context.js +0 -50
- package/dist/prompts.js +0 -95
- package/dist/resources.js +0 -93
- package/dist/server.js +0 -174
- package/dist/setup.js +0 -438
- package/dist/tools/addMarker.js +0 -93
- package/dist/tools/assembleHighlights.js +0 -69
- package/dist/tools/backdrop.js +0 -79
- package/dist/tools/bugReport.js +0 -243
- package/dist/tools/burnSubtitles.js +0 -56
- package/dist/tools/callout.js +0 -62
- package/dist/tools/chapters.js +0 -156
- package/dist/tools/clip.js +0 -52
- package/dist/tools/compress.js +0 -51
- package/dist/tools/concat.js +0 -67
- package/dist/tools/contactSheet.js +0 -113
- package/dist/tools/convert.js +0 -46
- package/dist/tools/crop.js +0 -43
- package/dist/tools/cursor.js +0 -67
- package/dist/tools/cutByTranscript.js +0 -86
- package/dist/tools/cutIdle.js +0 -84
- package/dist/tools/deleteRecording.js +0 -119
- package/dist/tools/denoise.js +0 -60
- package/dist/tools/doctor.js +0 -146
- package/dist/tools/exportGif.js +0 -57
- package/dist/tools/exportPreset.js +0 -48
- package/dist/tools/extractAudio.js +0 -65
- package/dist/tools/findText.js +0 -194
- package/dist/tools/getMediaInfo.js +0 -36
- package/dist/tools/getSession.js +0 -40
- package/dist/tools/indexRecording.js +0 -195
- package/dist/tools/keystrokeOverlay.js +0 -90
- package/dist/tools/listAudioDevices.js +0 -35
- package/dist/tools/listSessions.js +0 -28
- package/dist/tools/listTargets.js +0 -76
- package/dist/tools/listVideoDevices.js +0 -26
- package/dist/tools/musicBed.js +0 -55
- package/dist/tools/narrate.js +0 -86
- package/dist/tools/normalizeAudio.js +0 -59
- package/dist/tools/overlay.js +0 -62
- package/dist/tools/pauseRecording.js +0 -44
- package/dist/tools/pipeline.js +0 -397
- package/dist/tools/readEvents.js +0 -98
- package/dist/tools/redactRegion.js +0 -62
- package/dist/tools/reframe.js +0 -46
- package/dist/tools/resumeRecording.js +0 -46
- package/dist/tools/reviewRecording.js +0 -163
- package/dist/tools/sampleFrames.js +0 -200
- package/dist/tools/saveReplay.js +0 -90
- package/dist/tools/scale.js +0 -44
- package/dist/tools/screenDiff.js +0 -86
- package/dist/tools/screenshot.js +0 -76
- package/dist/tools/searchRecording.js +0 -79
- package/dist/tools/speed.js +0 -46
- package/dist/tools/startRecording.js +0 -398
- package/dist/tools/stepGuide.js +0 -249
- package/dist/tools/stopRecording.js +0 -132
- package/dist/tools/titleCard.js +0 -67
- package/dist/tools/transcribe.js +0 -66
- package/dist/tools/trim.js +0 -57
- package/dist/tools/waitForChange.js +0 -142
- package/dist/tools/xfadeTransition.js +0 -58
- package/dist/tools/zoom.js +0 -134
- package/dist/utils/anim.js +0 -54
- package/dist/utils/animExport.js +0 -56
- package/dist/utils/argPaths.js +0 -39
- package/dist/utils/audio.js +0 -117
- package/dist/utils/audioDevices.js +0 -107
- package/dist/utils/backdrop.js +0 -162
- package/dist/utils/bugReport.js +0 -195
- package/dist/utils/callout.js +0 -132
- package/dist/utils/calloutAssets.js +0 -42
- package/dist/utils/capabilities.js +0 -96
- package/dist/utils/captions.js +0 -104
- package/dist/utils/chapters.js +0 -227
- package/dist/utils/consent.js +0 -29
- package/dist/utils/cursor.js +0 -338
- package/dist/utils/diff.js +0 -186
- package/dist/utils/errors.js +0 -29
- package/dist/utils/events.js +0 -403
- package/dist/utils/expr.js +0 -11
- package/dist/utils/ffmpeg.js +0 -285
- package/dist/utils/fontCoverage.js +0 -177
- package/dist/utils/fonts.js +0 -154
- package/dist/utils/frameQueue.js +0 -50
- package/dist/utils/gpu.js +0 -219
- package/dist/utils/idle.js +0 -91
- package/dist/utils/images.js +0 -38
- package/dist/utils/jobs.js +0 -129
- package/dist/utils/keystrokes.js +0 -198
- package/dist/utils/lifecycle.js +0 -233
- package/dist/utils/logging.js +0 -75
- package/dist/utils/media.js +0 -584
- package/dist/utils/monitors.js +0 -124
- package/dist/utils/narrate.js +0 -233
- package/dist/utils/ocr.js +0 -222
- package/dist/utils/ocrScan.js +0 -93
- package/dist/utils/paths.js +0 -155
- package/dist/utils/pause.js +0 -190
- package/dist/utils/pipeline.js +0 -361
- package/dist/utils/player.js +0 -85
- package/dist/utils/pool.js +0 -29
- package/dist/utils/produce.js +0 -300
- package/dist/utils/recipes.js +0 -71
- package/dist/utils/recorder.js +0 -173
- package/dist/utils/recordingFiles.js +0 -32
- package/dist/utils/recordingIndex.js +0 -312
- package/dist/utils/replay.js +0 -283
- package/dist/utils/resolveTarget.js +0 -25
- package/dist/utils/retention.js +0 -48
- package/dist/utils/roots.js +0 -43
- package/dist/utils/sessions.js +0 -499
- package/dist/utils/sheet.js +0 -82
- package/dist/utils/stepGuide.js +0 -231
- package/dist/utils/steps.js +0 -88
- package/dist/utils/still.js +0 -38
- package/dist/utils/targetList.js +0 -64
- package/dist/utils/targets.js +0 -265
- package/dist/utils/timeline.js +0 -85
- package/dist/utils/toolSpec.js +0 -31
- package/dist/utils/toolsets.js +0 -134
- package/dist/utils/transcriptCut.js +0 -149
- package/dist/utils/validate.js +0 -23
- package/dist/utils/waitLoop.js +0 -50
- package/dist/utils/wgc.js +0 -84
- package/dist/utils/windows.js +0 -192
- package/dist/utils/zoom.js +0 -252
package/dist/index.js
CHANGED
|
@@ -1,112 +1,556 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
import { probeDuration, requireFfmpeg } from "./utils/ffmpeg.js";
|
|
6
|
-
|
|
7
|
-
import { stopAll } from "./utils/lifecycle.js";
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
async function
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
2
|
+
import{StdioServerTransport as XA}from"@modelcontextprotocol/sdk/server/stdio.js";import{spawn as xA}from"node:child_process";import{mkdirSync as yA,readFileSync as SA,rmSync as Ml,writeFileSync as vA}from"node:fs";import{join as to,resolve as $A}from"node:path";import{Client as kA}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as EA}from"@modelcontextprotocol/sdk/inMemory.js";import{McpServer as JT}from"@modelcontextprotocol/sdk/server/mcp.js";var Tt={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","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"]},di=Object.keys(Tt).filter(t=>t!=="core");function Fl(t){return Object.keys(Tt).find(e=>Tt[e].includes(t))}function mi(t){let e=(t??"").split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),r={enabled:Object.keys(Tt),unknown:[],all:!0};if(e.length===0||e.includes("all"))return{...r,unknown:e.filter(s=>s!=="all"&&!(s in Tt))};let n=e.filter(s=>!(s in Tt)),o=new Set(["core",...e.filter(s=>s in Tt)]);if(o.size===1)return{...r,unknown:n};let i=Object.keys(Tt).filter(s=>o.has(s));return{enabled:i,unknown:n,all:i.length===Object.keys(Tt).length}}function Ol(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 Ym}from"node:child_process";import{z as ae}from"zod";var l=class extends Error{hint;constructor(e,r){super(e),this.name="ScreencastError",this.hint=r}};function H(t){return t instanceof Error?t.message:String(t)}function v(t,e=[]){let r=typeof t=="string"?t:JSON.stringify(t,null,2),n={content:[{type:"text",text:r},...e]};return t!==null&&typeof t=="object"&&!Array.isArray(t)&&(n.structuredContent=JSON.parse(r)),n}function _(t){let e;return t instanceof l?e=t.hint?`${t.message}
|
|
4
|
+
|
|
5
|
+
${t.hint}`:t.message:e=H(t),{content:[{type:"text",text:e}],isError:!0}}import{z as Nl}from"zod";var fe={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},O={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},fi={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},Dl={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1};function L(t){return Nl.looseObject(t)}var Q=L({outputPath:Nl.string().describe("Path of the file written.")});import{spawn as kp,spawnSync as Ii}from"node:child_process";import{existsSync as Dx,mkdtempSync as Lx,rmSync as Wx,writeFileSync as jx}from"node:fs";import{tmpdir as Bx}from"node:os";import{join as yp}from"node:path";import{extname as $i}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 Ar,isAbsolute as lx,relative as px,resolve as Xt,sep as dx}from"node:path";import{mkdirSync as Wl,existsSync as mx,realpathSync as fx}from"node:fs";function Fe(){let t=process.env.SCREENCAST_HOME;return t&&t.trim().length>0?t:Ar(ix(),".screencast-mcp")}function be(t){let e=Ar(Fe(),t);return Wl(e,{recursive:!0}),e}function jl(){let t=Fe();return Wl(t,{recursive:!0}),Ar(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 rn(t,e){return Ar(t.replace(/%/g,"%%"),e)}var Bl=/\.(png|jpe?g|bmp|tiff?)$/i;function oc(t){return Bl.test(t)}function _e(t){return Bl.test(t)?["-update","1",t]:[t]}function Be(t=""){return Ar(sx(),`screencast-${he()}-${ge()}${t}`)}var hi="SCREENCAST_ALLOWED_DIRS";function io(t=process.env){let e=t[hi];return e?e.split(cx).map(r=>r.trim()).filter(r=>r.length>0).map(r=>Xt(r)):[]}var tn=null;function so(t){tn=t===null||t==="pending"?t:t.map(e=>Xt(e))}function Rr(t=process.env){let e=io(t);if(tn===null&&e.length===0)return null;let r=Array.isArray(tn)?tn:[];return[Xt(Fe()),...e,...r]}function Ll(t){let e=[],r=Xt(t);for(;;)try{return Ar(fx.native(r),...e.reverse())}catch{let n=ux(r);if(n===r)return Xt(t);e.push(ax(r)),r=n}}function Tr(t,e){let r=px(Ll(e),Ll(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 Jt(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 Ul(t,e="Input"){Jt(t,e);let r=Xt(t);if(tn==="pending"&&io().length===0&&!Tr(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=Rr();if(!(n===null||n.some(o=>Tr(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 ${hi} or the client's workspace roots.`)}function Yt(t){if(Jt(t,"Output"),tn==="pending"&&io().length===0&&!Tr(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=Rr();if(!(e===null||e.some(r=>Tr(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 ${hi} or the client's workspace roots.`)}function ic(t){if(!(Rr()!==null||Tr(t,Fe())))throw new l(`Refusing to replace ${t}: it is outside SCREENCAST_HOME and no allowed directories are set. Add its folder to ${hi} (or the client's workspace roots) to allow overwriting there, or write to a new path.`)}function Kt(t,e,r,n=!1){if(t&&t.trim().length>0){Jt(t,"Output");let o=Xt(e,t);if(Yt(o),mx(o)){if(!n)throw new l(`Output already exists: ${o}. Pass overwrite: true to replace it, or choose a different path.`);ic(o)}return o}return Ar(e,r)}function nn(t,e){if(!t||t.trim().length===0)return;Jt(t,"Output directory");let r=Xt(e,t);return Yt(r),r}var sc={draft:{preset:"ultrafast",crf:28},standard:{preset:"veryfast",crf:23},high:{preset:"medium",crf:18}},bi=30,wi="standard";function gx(t){return!t||t.device.trim().length===0?[]:["-f","dshow","-i",`audio=${t.device}`]}function ao(t,e){if(!/^-?\d+$/.test(t.trim()))throw new l(`${e} must be an integer, got "${t}".`);return parseInt(t,10)}function Hl(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=ao(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]=[ao(s,"region x"),ao(a,"region y"),ao(c,"region w"),ao(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 Gl(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 co(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 ql(t,e){if(e.length===0)return;let r=co(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 Te(t){let e=sc[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 bx="160k";function on(t=bx){return["-c:a","aac",...t?["-b:a",t]:[]]}var Mr=["-movflags","+faststart"];function $e(t){let e={aac:()=>on(t.bitrate),copy:()=>["-c:a","copy"],none:()=>["-an"],omit:()=>[]}[t.audio]();return[...t.video??Te(t.quality??"standard"),...e,...t.faststart?Mr:[]]}function tt(t){return t-t%2}function xi(t,e,r={}){switch(t.kind){case"full":{let n=co(e);return r.evenSize&&e.length>0&&(n.w%2!==0||n.h%2!==0)?["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${tt(n.w)}x${tt(n.h)}`,"-i","desktop"]:["-i","desktop"]}case"window":throw new l("Internal: a window target must be resolved to a region before building capture args. Call resolveCaptureTarget().");case"region":{let{w:n,h:o}=t;if(r.evenSize&&(n=tt(n),o=tt(o),n<=0||o<=0))throw new l(`region ${t.w}x${t.h} is too small to record: width and height must each be at least 2px (the video encoder needs even dimensions). Use a larger region, or take a screenshot instead.`);return["-offset_x",String(t.x),"-offset_y",String(t.y),"-video_size",`${n}x${o}`,"-i","desktop"]}case"monitor":{let n=Gl(t.index,e),o=r.evenSize?tt(n.width):n.width,i=r.evenSize?tt(n.height):n.height;return["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${o}x${i}`,"-i","desktop"]}}}function wx(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 ac=3600;function Xl(t,e=process.env){if(t!==void 0)return Jl(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>At)throw new l(`SCREENCAST_MAX_RECORDING_SEC must be an integer from 0 (no cap) to ${At} (7 days), got "${r}".`);return n}return ac}var At=168*3600;function Jl(t){if(!Number.isInteger(t)||t<0||t>At)throw new l(`maxDurationSec must be an integer from 0 (no cap) to ${At} (7 days).`);return t}function xx(t){if(!Number.isInteger(t)||t<1||t>120)throw new l("fps must be an integer between 1 and 120.");return t}function gi(t){return["-g",String(Math.max(1,Math.round(t*2)))]}var zl=["-movflags","+frag_keyframe+empty_moov+default_base_moof"];function yi(t,e){let r=xx(e.fps??bi),n=e.quality??wi,o=e.monitors??[],i=Jl(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"]:[],...xi(t,o,{evenSize:!0})],...gx(e.audio),...a?wx(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??Te(n),...gi(r),...e.audio?on():[],...zl,...s,e.output,...a?["-map",`${c}:v`,...a.codec??Te(n),...gi(r),...zl,...s,a.output]:[]]}var yx=30;function Yl(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 Si(t,e,r=[]){return["-y","-f","gdigrab","-framerate",String(yx),...xi(t,r),"-frames:v","1",..._e(e)]}function vi(t,e){switch(t.kind){case"region":return{x:t.x,y:t.y,w:tt(t.w),h:tt(t.h)};case"monitor":{let r=Gl(t.index,e);return{x:r.x,y:r.y,w:tt(r.width),h:tt(r.height)}}case"full":{let r=co(e);return{x:r.x,y:r.y,w:tt(r.w),h:tt(r.h)}}case"window":throw new l("Internal: resolve a window target to a region first.")}}function cc(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 Vt(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 Sx=/[:,;=[\]'"\\\s]/;function De(t,e="color"){if(t.length===0||Sx.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 Cr}from"zod";var an="standard";function uc(t){if(t===void 0)return null;let e=Number(t);return Number.isFinite(e)?e:null}function Kl(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 vx(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 Pr(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=vx(r),c=a!==null&&Math.abs(a)%180===90;return{durationSec:s,videoDurationSec:r?uc(r.duration)??s:null,width:(c?r?.height:r?.width)??null,height:(c?r?.width:r?.height)??null,...a?{rotation:a}:{},fps:Kl(r?.avg_frame_rate)??Kl(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:uc(r?.nb_frames),sampleRate:uc(n?.sample_rate),channels:n?.channels??null}}function Ir(t){return["-v","quiet","-print_format","json","-show_format","-show_streams",t]}function lc(t,e){if(!Number.isFinite(t)||t<=0)throw new l(`${e} must be a positive number.`);return t}var ki=100,pc=1e3;function Ei(t,e,r){if(lc(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 Ql(t,e){for(let r of t)if(/^frame_\d+\.png$/i.test(r))return`frame_${e}_`;return"frame_"}function _i(t,e,r,n=ki,o=!1,i){lc(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 bt=.1;function Qt(t,e=bt){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 Zt(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 cn(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 un(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 ee(t,e={}){let r=$i(t).toLowerCase();return r===".mp4"||r===".mkv"||r===".mov"||e.audio&&Zl.has(r)?r:".mp4"}var Zl=new Set([".wav",".mp3",".m4a"]);function Ti(t){return Zl.has($i(t).toLowerCase())}function Fr(t){if(t===void 0)return;let e=$i(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 ep(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(lc(r.duration,"duration")));return r.exact===!1?o.push("-c","copy",e):o.push(...$e({quality:an,audio:"aac",bitrate:null}),e),o}function uo(t){return t.map(e=>`file '${e.replace(/'/g,"'\\''")}'`).join(`
|
|
6
|
+
`)+`
|
|
7
|
+
`}function tp(t){if(t.length<2)throw new l("concat requires at least two input files.");return uo(t)}function ln(t,e,r={}){return["-y",...r.quiet?["-v","error"]:[],"-f","concat","-safe","0","-i",t,"-c","copy",e]}function $x(t){let{videoFrames:e,videoDurationSec:r,fps:n}=t;return e===null||r===null||n===null?!1:e>r*n*1.05+2}function rp(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($x(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 np(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,...$e({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 Rt(t,e){if(!Number.isInteger(t)||t<=0)throw new l(`${e} must be a positive integer.`);return t}function Ai(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 dc(t,e){let r=sn(t.x,"crop x"),n=sn(t.y,"crop y"),o=Vt(Rt(t.width,"crop width"),"crop width"),i=Vt(Rt(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 op(t,e,r,n,o=an){return["-y","-i",t,"-vf",dc(r,n),...$e({quality:o,audio:"copy"}),e]}function mc(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&&Vt(Rt(t.width,"scale width"),"scale width"),t.height!==void 0&&Vt(Rt(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 sp(t,e,r,n=an){return["-y","-i",t,"-vf",mc(r),...$e({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 ap(t,e,r,n,o=an){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(...$e({quality:o,audio:n?"aac":"none",bitrate:null}),e),i}var kx="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 cp(t,e,r,n,o=an){let i=sn(n.x,"overlay x"),s=sn(n.y,"overlay y"),a=Ai(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&&Rt(n.scale.width,"overlay scale width"),n.scale.height!==void 0&&Rt(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+=`,${kx}`);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?",...$e({quality:o,audio:"copy"}),...f!=null&&f>0?["-t",String(f)]:[],r]}var Ex={light:23,medium:28,heavy:32};function up(t,e,r={}){let n=r.level??"medium",o=Ex[n];if(o===void 0)throw new l(`Unknown compress level "${n}".`);let i=["-y","-i",t];return r.maxWidth!==void 0&&(Rt(r.maxWidth,"maxWidth"),i.push("-vf",`scale='trunc(min(${r.maxWidth},iw)/2)*2':-2`)),i.push(...$e({video:["-c:v","libx264","-preset","slow","-crf",String(o),"-pix_fmt","yuv420p"],audio:"aac",bitrate:"128k",faststart:!0}),e),i}var _x={mp3:["-c:a","libmp3lame","-q:a","2"],aac:on("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 pp(t,e,r){let n=_x[r];if(!n)throw new l(`Unknown audio format "${r}".`);return["-y","-i",t,"-vn",...n,e]}function dp(t,e,r,n=an){if(!Number.isFinite(r.start)||r.start<0)throw new l("clip start must be a non-negative number.");if(!Number.isFinite(r.end)||r.end<=r.start)throw new l("clip end must be greater than start.");return["-y","-i",t,"-ss",String(r.start),"-t",String(r.end-r.start),...$e({quality:n,audio:"aac",bitrate:null}),e]}var Ri=["box","blur","pixelate"];function Tx(t,e,r){return t.map((n,o)=>{let i=sn(n.x,`region[${o}] x`),s=sn(n.y,`region[${o}] y`),a=Rt(n.width,`region[${o}] width`),c=Rt(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:Ai(n.start,n.end)}})}var Ax=8,Vl=3,Rx=16;function Mx(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(Ax,Math.min(20,Math.floor(e/4)))),o=Math.min(n,r(Math.ceil(e/2)));return`lr=${n}:lp=${Vl}:cr=${o}:cp=${Vl}`}function Cx(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 hc(t,e,r,n,o){if(t.length===0)throw new l("redact_region requires at least one region.");let i=e.style??"box",s=e.pad??0;if(!Number.isInteger(s)||s<0)throw new l("pad must be a non-negative integer.");let a=De(e.color??"black","color"),c=Tx(t,s,r);if(i==="box"){let m=c.map(h=>{let g=h.enable?`:enable='${h.enable}'`:"";return`drawbox=x=${h.x}:y=${h.y}:w=${h.w}:h=${h.h}:color=${a}:t=fill${g}`}).join(",");return{steps:[`${n}${m}[${o}out]`],out:`[${o}out]`}}let u=c.length,d=[],p=[`${o}base`,...c.map((m,h)=>`${o}s${h}`)];d.push(`${n}split=${u+1}[${p.join("][")}]`),c.forEach((m,h)=>{let g=`crop=${m.w}:${m.h}:${m.x}:${m.y}`,w=i==="blur"?`boxblur=${Mx(m)}`:Cx(m);d.push(`[${o}s${h}]${g},${w}[${o}b${h}]`)});let f=`${o}base`;return c.forEach((m,h)=>{let g=m.enable?`:enable='${m.enable}'`:"",w=h===u-1?`${o}out`:`${o}c${h}`;d.push(`[${f}][${o}b${h}]overlay=${m.x}:${m.y}${g}[${w}]`),f=`${o}c${h}`}),{steps:d,out:`[${o}out]`}}function Mi(t,e){if(!oc(t))return Fr(e),{still:!1,ext:ee(t)};if(e&&!oc(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)?$i(t).toLowerCase():".png"}}function mp(t,e,r,n={},o,i=!1){let s=i?r.map(({start:d,end:p,...f})=>f):r,{steps:a,out:c}=hc(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,...$e({quality:"high",audio:"copy"}),e]}return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...$e({quality:"high",audio:"copy"}),e]}var pn=Cr.object({x:Cr.number().int().nonnegative(),y:Cr.number().int().nonnegative(),width:Cr.number().int().positive(),height:Cr.number().int().positive(),start:Cr.number().nonnegative().optional(),end:Cr.number().positive().optional()});var Px="screencast-mcp",fp=new Set;function hp(t){fp.add(t)}function er(t,e,r={}){for(let n of fp)n.isConnected()&&n.sendLoggingMessage({level:t,logger:Px,data:{message:e,...r}}).catch(()=>{})}var gp=/^\s*(?:frame|size)=/,Ix=/\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,Fx=/^\s*configuration:|deprecated pixel format used/i,bp=20;function wp(t){return!gp.test(t)&&Ix.test(t)&&!Fx.test(t)}function Ox(t){let e=new Set;for(let r of t.split(/[\r\n]+/)){let n=r.trim();if(n&&wp(n)&&e.add(n),e.size>=bp)break}return[...e]}function xp(t,e={}){let r=Ox(t);r.length>0&&er("warning","ffmpeg reported warnings.",{...e,warnings:r})}var Nx=1e4,Ci=class{constructor(e,r=er,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(gp.test(e)){let r=Number(/\bdrop=\s*(\d+)/.exec(e)?.[1]??0);r>this.dropped&&this.now()-this.lastDropReport>=Nx&&(this.lastDropReport=this.now(),this.dropped=r,this.send("warning",`The recording has dropped ${r} frame(s) so far.`,{...this.data(),dropped:r}));return}!wp(e)||this.seen.has(e)||this.seen.size>=bp||(this.seen.add(e),this.send("warning",e,{...this.data(),source:"ffmpeg"}))}}};var Ux="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 Sp(t,e){let r=process.env[t];return r&&r.trim().length>0?r:e}function vp(t){try{return Ii(t,["-version"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function gc(){let t=Sp("FFMPEG_PATH","ffmpeg"),e=Sp("FFPROBE_PATH","ffprobe"),r=[];if(vp(t)||r.push("ffmpeg"),vp(e)||r.push("ffprobe"),r.length>0)throw new l(`Required ${r.join(" and ")} not found on PATH.`,Ux);return{ffmpeg:t,ffprobe:e}}var Pi=null;function E(){return Pi||(Pi=gc(),Pi)}var dn=null;function tr(){if(dn!==null)return dn;if(process.platform!=="win32")return dn=!1;try{let t=Ii(E().ffmpeg,["-hide_banner","-h","filter=gfxcapture"],{encoding:"utf8",windowsHide:!0,timeout:1e4});dn=/gfxcapture AVOptions/.test(t.stdout??"")}catch{dn=!1}return dn}var $p=new Map;function Ye(t){let e=$p.get(t);if(e!==void 0)return e;let r;try{let n=Ii(E().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 $p.set(t,r),r}var Ep=["ignore","pipe","pipe"],po=class extends l{};function se(t,e,r=300*1e3,n={}){return new Promise((o,i)=>{let s=kp(t,e,{windowsHide:!0,stdio:Ep}),a="",c="",u=null,d,p=b=>{u||(u=b,s.kill("SIGKILL"),d=setTimeout(()=>i(b),5e3))},f=()=>p(new l(`${t} was cancelled.`)),m=setTimeout(()=>p(new l(`${t} timed out after ${Math.round(r/1e3)}s.`)),r),h,g=()=>{n.stallMs&&(clearTimeout(h),h=setTimeout(()=>p(new po(`${t} wrote nothing for ${Math.round(n.stallMs/1e3)}s and was stopped.`)),n.stallMs))};g();let w=()=>{clearTimeout(m),clearTimeout(h),clearTimeout(d),n.signal?.removeEventListener("abort",f)};n.signal?.aborted?f():n.signal?.addEventListener("abort",f,{once:!0}),s.stdout?.on("data",b=>{g();let x=b.toString();a+=x,n.onStdout?.(x)}),s.stderr?.on("data",b=>{g(),c+=b.toString()}),s.on("error",b=>{w(),i(b)}),s.on("close",b=>{w(),u?i(u):o({code:b,stdout:a,stderr:c})})})}var zx=new Set(["-vf","-af","-filter_complex","-lavfi","-filter:v","-filter:a"]),Hx=8e3,Gx={"-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"},lo=null;function qx(){if(lo!==null)return lo;try{let t=Ii(E().ffmpeg,["-hide_banner","-version"],{encoding:"utf8",windowsHide:!0,timeout:1e4}),e=/^\s*libavutil\s+(\d+)\./m.exec(t.stdout??"");lo=e?.[1]===void 0||Number(e[1])>=59}catch{lo=!0}return lo}function Fi(t,e){let r=null,n=[...t];for(let[i,s]of t.entries()){let a=t[i-1];if(a===void 0||!zx.has(a)||s.length<=Hx)continue;r??=Lx(yp(Bx(),"screencast-filter-"));let c=yp(r,`filter${i}.txt`);jx(c,s),e??=qx(),n[i-1]=e?`-/${a.slice(1)}`:Gx[a]??a,n[i]=c}let o=r;return{args:n,cleanup:()=>o&&Wx(o,{recursive:!0,force:!0})}}async function Or(t,e=3e4,r={}){let n=[];return await _p(t,e,o=>n.push(o),r),Buffer.concat(n)}async function Oi(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 _p(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 _p(t,e,r,n){let{ffmpeg:o}=E(),{args:i,cleanup:s}=Fi(t);return new Promise((a,c)=>{let u=kp(o,i,{windowsHide:!0,stdio:Ep}),d="",p=null,f,m=b=>{p||(p=b,u.kill("SIGKILL"),f=setTimeout(()=>c(b),5e3))},h=()=>m(new l("ffmpeg was cancelled.")),g=setTimeout(()=>m(new l(`ffmpeg timed out after ${Math.round(e/1e3)}s.`)),e),w=()=>{clearTimeout(g),clearTimeout(f),n.signal?.removeEventListener("abort",h)};n.signal?.aborted?h():n.signal?.addEventListener("abort",h,{once:!0}),u.stdout?.on("data",b=>{if(!p)try{r(b)}catch(x){m(x)}}),u.stderr?.on("data",b=>d+=b.toString()),u.on("error",b=>{w(),c(b)}),u.on("close",b=>{w(),p?c(p):b===0?a():c(new l(`ffmpeg failed (exit ${b}):
|
|
8
|
+
${d.trim().split(`
|
|
9
|
+
`).slice(-6).join(`
|
|
10
|
+
`)}`))})}).finally(s)}async function te(t,e,r={}){let{ffmpeg:n}=E(),o=Fi(t);try{let i=await se(n,o.args,e,r);if(i.code!==0){let s=i.stderr.trim().split(`
|
|
11
|
+
`).slice(-6).join(`
|
|
12
|
+
`);throw new l(`ffmpeg failed (exit ${i.code}):
|
|
13
|
+
${s}`)}xp(i.stderr)}finally{o.cleanup()}}async function ue(t,e={}){if(!Dx(t))return null;try{let r=await se(e.ffprobe??E().ffprobe,Ir(t),3e4);return r.code!==0?null:Pr(JSON.parse(r.stdout)).durationSec}catch{return null}}async function B(t){let{ffprobe:e}=E(),r=await se(e,Ir(t),3e4);if(r.code!==0)throw new l(`ffprobe failed (exit ${r.code}): ${r.stderr.trim().slice(-400)}`);return Pr(JSON.parse(r.stdout))}import{rmSync as Kd,writeFileSync as RS}from"node:fs";import{createReadStream as wy,createWriteStream as xy,existsSync as Li,mkdirSync as yy,mkdtempSync as Sy,readdirSync as _c,readFileSync as vy,rmSync as ji,statSync as $y,writeFileSync as Hp}from"node:fs";import{stat as Gp,writeFile as ky}from"node:fs/promises";import{pipeline as Ey}from"node:stream/promises";import{join as Ke}from"node:path";import{basename as Xx,dirname as Jx,extname as Yx,join as Kx}from"node:path";import{renameSync as Vx,rmSync as bc}from"node:fs";var Qx="SCREENCAST_JOB_TIMEOUT_MS",Zx=10*6e4,ey=9e4,ty=30*6e4,ry=4;function le(t,e=process.env){let r=Number(e[Qx]);return Number.isInteger(r)&&r>0?r:t==null||!(t>0)?ty:Math.max(Zx,Math.ceil(t*ry*1e3))}function ny(t){let e=Yx(t);return Kx(Jx(t),`${Xx(t,e)}.partial${e}`)}function oy(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 iy(){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 mo(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 wc=new Set,Tp=!1;async function G(t,e){if(Tp)throw new l("The server is shutting down; the edit was not started.");let r=ny(e.output),n=mo(e.extra),o=iy(),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",...oy(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(m=>p=m)};wc.add(f);try{let m=()=>te(c,le(a),{signal:d,stallMs:ey,onStdout:n&&i?h=>{let g=o(h);g!==null&&n(g/i)}:void 0});try{await m()}catch(h){if(!(h instanceof po)||d.aborted)throw h;process.stderr.write(`${h.message} Retrying the edit once.
|
|
14
|
+
`),bc(r,{force:!0}),await m()}Vx(r,e.output),n?.(1)}catch(m){throw bc(r,{force:!0}),m}finally{wc.delete(f),p()}}async function Ap(t=3e3){Tp=!0;let e=[...wc];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{bc(n.partial,{force:!0})}catch{}return e.length}import{spawn as sy}from"node:child_process";import{existsSync as yc,readFileSync as Fp,writeFileSync as Op,unlinkSync as ay,rmSync as Sc}from"node:fs";var Np="masked",vc=["down","up","move","wheel","key","typing","gap","focus"],$c=33;function mn(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 ho(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 kc(t,e){let r=e.spans&&e.spans.length>0?e.spans:null,n=[],o=[],i=null,s=cy(t),a=null,c=(p,f,m,h,g)=>{let w=Math.max(0,p),b=e.endSec!==void 0?Math.min(h,e.endSec):h;b>w&&n.push({t:xc(w),type:"gap",x:f,y:m,inFrame:!1,durationSec:xc(b-w),reason:g})};for(let p of t.split(/\r?\n/)){let f=p.split(",");if(f.length<4)continue;let[m,h,g,w]=f,b=f.slice(4).join(","),x=Number(m),$=Number(g),S=Number(w);if(!Number.isFinite(x)||!Number.isFinite($)||!Number.isFinite(S))continue;let C=r?ho(x,r):(x-e.startMs)/1e3;if(C===null)continue;let I=Math.round(C*1e3)/1e3;if(h==="hb"){o.push(I);continue}if(h==="miss"){a??={t:I,x:$-e.frame.x,y:S-e.frame.y};continue}if(h==="resume"){a&&c(a.t,a.x,a.y,I,"input_not_seen"),a=null;continue}if(h===void 0||h==="gap"||!vc.includes(h))continue;if(h==="focus"&&I<0){i={t:0,type:"focus",x:0,y:0,inFrame:!1,...Rp(b)};continue}if(I<0||e.endSec!==void 0&&I>e.endSec)continue;let R=$-e.frame.x,A=S-e.frame.y,W={t:I,type:h,x:R,y:A,inFrame:R>=0&&A>=0&&R<e.frame.w&&A<e.frame.h};if((h==="down"||h==="up")&&(W.button=b||"left"),h==="down"){let Y=s.get(`${m},${g},${w}`);Y&&(W.element=Y)}if(h==="wheel"){let[Y,j]=b.split(":");W.axis=Y==="h"?"horizontal":"vertical",W.delta=Number(j)||0}h==="key"&&b&&(W.keys=b),h==="typing"&&(W.durationSec=xc((Number(b)||0)/1e3)),h==="focus"&&Object.assign(W,Rp(b),{inFrame:!1}),n.push(W)}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>Cp&&c(p,0,0,f,"helper_stalled"),f)),e.endSec!==void 0&&e.endSec-d>Cp&&c(d,0,0,e.endSec,"helper_stopped")),n.sort((p,f)=>p.t-f.t)}var xc=t=>Math.round(t*1e3)/1e3;function cy(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 Rp(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 Dp(t){return t.filter(e=>e.type==="gap").map(e=>({t:e.t,durationSec:e.durationSec??0,reason:e.reason??"input_not_seen"}))}function Ec(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
15
|
+
`)+(t.length?`
|
|
16
|
+
`:"")}function Ue(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function Ni(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 fn(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 Mp=500,uy=1e3,ly=2e3,Cp=3,py=`
|
|
17
|
+
$ErrorActionPreference='Stop'
|
|
18
|
+
$ProgressPreference='SilentlyContinue'
|
|
19
|
+
Add-Type @"
|
|
20
|
+
#pragma warning disable 649
|
|
21
|
+
using System;using System.IO;using System.Text;using System.Threading;using System.Diagnostics;using System.Collections.Generic;using System.Runtime.InteropServices;
|
|
22
|
+
public static class ScEvents{
|
|
23
|
+
delegate IntPtr Proc(int n,IntPtr w,IntPtr l);
|
|
24
|
+
[DllImport("user32.dll")] static extern IntPtr SetWindowsHookEx(int id,Proc p,IntPtr mod,uint tid);
|
|
25
|
+
[DllImport("user32.dll")] static extern IntPtr CallNextHookEx(IntPtr h,int n,IntPtr w,IntPtr l);
|
|
26
|
+
[DllImport("user32.dll")] static extern int GetMessage(out MSG m,IntPtr h,uint a,uint b);
|
|
27
|
+
[DllImport("user32.dll")] static extern short GetAsyncKeyState(int vk);
|
|
28
|
+
[DllImport("user32.dll")] static extern IntPtr SetProcessDpiAwarenessContext(IntPtr v);
|
|
29
|
+
[DllImport("kernel32.dll")] static extern IntPtr GetModuleHandle(string n);
|
|
30
|
+
[DllImport("kernel32.dll")] static extern void GetSystemTimePreciseAsFileTime(out long t);
|
|
31
|
+
struct MSG{public IntPtr h;public uint m;public IntPtr w;public IntPtr l;public uint t;public int x;public int y;}
|
|
32
|
+
struct MS{public int x;public int y;public uint data;public uint flags;public uint time;public IntPtr extra;}
|
|
33
|
+
struct KB{public uint vk;public uint scan;public uint flags;public uint time;public IntPtr extra;}
|
|
34
|
+
[DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LII i);
|
|
35
|
+
[DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
|
|
36
|
+
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h,IntPtr p);
|
|
37
|
+
[DllImport("user32.dll")] static extern IntPtr GetKeyboardLayout(uint t);
|
|
38
|
+
[DllImport("user32.dll",EntryPoint="GetWindowThreadProcessId")] static extern uint WindowPid(IntPtr h,out uint pid);
|
|
39
|
+
[DllImport("user32.dll",CharSet=CharSet.Unicode)] static extern int GetWindowText(IntPtr h,StringBuilder s,int n);
|
|
40
|
+
[DllImport("user32.dll")] static extern bool RegisterHotKey(IntPtr h,int id,uint mods,uint vk);
|
|
41
|
+
// Hotkeys (#337): Ctrl+Alt+Shift+M marks, +S stops; told to the server on stdout.
|
|
42
|
+
public static bool Hotkeys;
|
|
43
|
+
static void Say(string s){lock(Console.Out){Console.Out.WriteLine(s);Console.Out.Flush();}}
|
|
44
|
+
[DllImport("user32.dll")] static extern int ToUnicodeEx(uint vk,uint scan,byte[] ks,[Out,MarshalAs(UnmanagedType.LPWStr)] StringBuilder b,int n,uint f,IntPtr hkl);
|
|
45
|
+
struct LII{public uint cb;public uint t;}
|
|
46
|
+
static Proc mp,kp;static StreamWriter w;static bool sc;static double lastMove;static int cx,cy;
|
|
47
|
+
static readonly object wl=new object();static string P;public static int Rot;static int lastRot;
|
|
48
|
+
static HashSet<uint> held=new HashSet<uint>();
|
|
49
|
+
// Focus (#323): 0 off, 1 the foreground app's exe, 2 also its title.
|
|
50
|
+
public static int Focus;static IntPtr lastFg;
|
|
51
|
+
static void CheckFocus(){if(Focus==0)return;IntPtr fg=GetForegroundWindow();if(fg==IntPtr.Zero||fg==lastFg)return;lastFg=fg;
|
|
52
|
+
uint pid;WindowPid(fg,out pid);string exe;try{exe=Process.GetProcessById((int)pid).ProcessName+".exe";}catch{exe="unknown";}
|
|
53
|
+
string d=exe;if(Focus==2){var t=new StringBuilder(512);GetWindowText(fg,t,512);d+="|"+t.ToString().Replace('\\r',' ').Replace('\\n',' ');}
|
|
54
|
+
Put("focus",cx,cy,d);}
|
|
55
|
+
// Elements (#333): each press is queued and described by UI Automation on
|
|
56
|
+
// its own thread. A UIA call into a busy app can take a while, which must
|
|
57
|
+
// never happen inside the hook.
|
|
58
|
+
public static Func<double,double,string> Describer;static readonly Queue<double[]> clicks=new Queue<double[]>();static readonly AutoResetEvent clickEv=new AutoResetEvent(false);
|
|
59
|
+
static void Press(int x,int y,string b){double t=Now();Line(t,"down",x,y,b);if(Describer!=null){lock(clicks){if(clicks.Count<32)clicks.Enqueue(new double[]{t,x,y});}clickEv.Set();}}
|
|
60
|
+
static void Elements(){while(true){clickEv.WaitOne();while(true){double[] c;lock(clicks){if(clicks.Count==0)break;c=clicks.Dequeue();}string d=null;try{d=Describer(c[1],c[2]);}catch{}if(d!=null)Line(c[0],"elem",(int)c[1],(int)c[2],d);}}}
|
|
61
|
+
static readonly object q=new object();static StringBuilder buf=new StringBuilder();
|
|
62
|
+
static double typeStart=-1,typeLast;static int lastHook=Environment.TickCount;static bool missing;
|
|
63
|
+
static readonly IFormatProvider Inv=System.Globalization.CultureInfo.InvariantCulture;
|
|
64
|
+
static double Now(){long t;GetSystemTimePreciseAsFileTime(out t);return (t-116444736000000000L)/10000.0;}
|
|
65
|
+
// The hooks only append to a buffer; the pump thread writes it. Slow file
|
|
66
|
+
// I/O inside a hook makes Windows drop the hook without notice (#210).
|
|
67
|
+
static void Line(double t,string type,int x,int y,string data){lock(q){buf.Append(t.ToString("F1",Inv)).Append(',').Append(type).Append(',').Append(x).Append(',').Append(y).Append(',').Append(data).Append('\\n');}}
|
|
68
|
+
static void Put(string type,int x,int y,string data){Line(Now(),type,x,y,data);}
|
|
69
|
+
static bool Down(int vk){return (GetAsyncKeyState(vk)&0x8000)!=0;}
|
|
70
|
+
static void Seen(){lastHook=Environment.TickCount;if(missing){missing=false;Put("resume",cx,cy,"");}}
|
|
71
|
+
// Typed keys become bursts on a ${Mp} ms grid, so the log holds no per-key timing.
|
|
72
|
+
static void Typed(){double t=Now();lock(q){if(typeStart<0)typeStart=t;typeLast=t;}}
|
|
73
|
+
static void EndTyping(bool force){double s,e;lock(q){if(typeStart<0||(!force&&Now()-typeLast<${uy}))return;s=typeStart;e=typeLast;typeStart=-1;}
|
|
74
|
+
double g=${Mp};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));}
|
|
75
|
+
static void Drain(){lock(wl){string s;lock(q){s=buf.ToString();buf.Clear();}if(s.Length>0){w.Write(s);w.Flush();}}}
|
|
76
|
+
static void Quit(){EndTyping(true);Drain();lock(wl){w.Close();}Process.GetCurrentProcess().Kill();}
|
|
77
|
+
// Replay buffers (#258): every Rot ms the log becomes path.1 (replacing the one before), so it never holds much more than two periods.
|
|
78
|
+
static void Rotate(){lock(wl){w.Close();try{string old=P+".1";if(File.Exists(old))File.Delete(old);File.Move(P,old);}catch{}w=new StreamWriter(P,true,new UTF8Encoding(false));}}
|
|
79
|
+
static void Pump(string stop){int tick=0;CheckFocus();while(true){Thread.Sleep(250);tick++;
|
|
80
|
+
EndTyping(false);CheckFocus();
|
|
81
|
+
lock(held){foreach(uint vk in new List<uint>(held)){if(!Down((int)vk))held.Remove(vk);}}
|
|
82
|
+
LII li=new LII();li.cb=8;if(!missing&&GetLastInputInfo(ref li)&&unchecked((int)li.t-lastHook)>${ly}){missing=true;Put("miss",cx,cy,"");}
|
|
83
|
+
if(tick%4==0)Put("hb",0,0,"");
|
|
84
|
+
if(File.Exists(stop))Quit();
|
|
85
|
+
Drain();
|
|
86
|
+
if(Rot>0&&unchecked(Environment.TickCount-lastRot)>=Rot){lastRot=Environment.TickCount;Rotate();}}}
|
|
87
|
+
static IntPtr Mouse(int n,IntPtr wp,IntPtr lp){
|
|
88
|
+
if(n>=0){Seen();MS s=(MS)Marshal.PtrToStructure(lp,typeof(MS));int m=(int)wp;cx=s.x;cy=s.y;
|
|
89
|
+
if(m==0x200){double t=Now();if(t-lastMove>=${$c}){lastMove=t;Put("move",s.x,s.y,"");}}
|
|
90
|
+
else if(m==0x201)Press(s.x,s.y,"left");else if(m==0x202)Put("up",s.x,s.y,"left");
|
|
91
|
+
else if(m==0x204)Press(s.x,s.y,"right");else if(m==0x205)Put("up",s.x,s.y,"right");
|
|
92
|
+
else if(m==0x207)Press(s.x,s.y,"middle");else if(m==0x208)Put("up",s.x,s.y,"middle");
|
|
93
|
+
else if(m==0x20B||m==0x20C){string b=((s.data>>16)==1)?"x1":"x2";if(m==0x20B)Press(s.x,s.y,b);else Put("up",s.x,s.y,b);}
|
|
94
|
+
else if(m==0x20A||m==0x20E){short d=(short)(s.data>>16);Put("wheel",s.x,s.y,(m==0x20E?"h:":"v:")+(d/120.0).ToString(System.Globalization.CultureInfo.InvariantCulture));}}
|
|
95
|
+
return CallNextHookEx(IntPtr.Zero,n,wp,lp);}
|
|
96
|
+
static string Name(uint vk){
|
|
97
|
+
if(vk>=0x41&&vk<=0x5A)return ((char)vk).ToString();if(vk>=0x30&&vk<=0x39)return ((char)vk).ToString();
|
|
98
|
+
if(vk>=0x70&&vk<=0x87)return "F"+(vk-0x6F);
|
|
99
|
+
switch(vk){case 0x0D:return "Enter";case 0x09:return "Tab";case 0x1B:return "Esc";case 0x20:return "Space";case 0x08:return "Backspace";case 0x2E:return "Delete";case 0x2D:return "Insert";
|
|
100
|
+
case 0x25:return "Left";case 0x26:return "Up";case 0x27:return "Right";case 0x28:return "Down";case 0x24:return "Home";case 0x23:return "End";case 0x21:return "PageUp";case 0x22:return "PageDown";
|
|
101
|
+
case 0xBB:return "=";case 0xBD:return "-";case 0xBC:return ",";case 0xBE:return ".";case 0xBF:return "/";case 0xC0:return "\`";case 0xDB:return "[";case 0xDD:return "]";case 0xBA:return ";";case 0xDE:return "'";case 0xDC:return "\\\\";}
|
|
102
|
+
return null;}
|
|
103
|
+
static bool IsMod(uint vk){return vk==0x10||vk==0x11||vk==0x12||(vk>=0xA0&&vk<=0xA5)||vk==0x5B||vk==0x5C;}
|
|
104
|
+
// Ctrl+Alt+key types a character on AltGr layouts (Polish, German...): that is text, not a chord.
|
|
105
|
+
static bool Types(KB k,bool shift){var ks=new byte[256];ks[0x11]=ks[0xA2]=ks[0x12]=ks[0xA4]=0x80;if(shift)ks[0x10]=ks[0xA0]=0x80;
|
|
106
|
+
var b=new StringBuilder(8);int r=ToUnicodeEx(k.vk,k.scan,ks,b,8,4,GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(),IntPtr.Zero)));
|
|
107
|
+
return r<0||(r>0&&b.Length>0&&!char.IsControl(b[0]));}
|
|
108
|
+
static IntPtr Key(int n,IntPtr wp,IntPtr lp){
|
|
109
|
+
if(n>=0){Seen();KB k=(KB)Marshal.PtrToStructure(lp,typeof(KB));int m=(int)wp;bool fresh;
|
|
110
|
+
if(m==0x101||m==0x105){lock(held){held.Remove(k.vk);}}
|
|
111
|
+
else if(m==0x100||m==0x104){lock(held){fresh=!IsMod(k.vk)&&held.Add(k.vk);}
|
|
112
|
+
if(fresh){string chord="";
|
|
113
|
+
if(sc&&!Down(0xA5)){bool ctl=Down(0x11),alt=Down(0x12),win=Down(0x5B)||Down(0x5C),sh=Down(0x10);string nm=Name(k.vk);
|
|
114
|
+
if((ctl||alt||win)&&nm!=null&&!(ctl&&alt&&!win&&Types(k,sh))){chord=(ctl?"Ctrl+":"")+(alt?"Alt+":"")+(sh?"Shift+":"")+(win?"Win+":"")+nm;}}
|
|
115
|
+
if(chord.Length>0)Put("key",cx,cy,chord);else Typed();}}}
|
|
116
|
+
return CallNextHookEx(IntPtr.Zero,n,wp,lp);}
|
|
117
|
+
public static void Run(string path,bool shortcuts,int parent){
|
|
118
|
+
try{SetProcessDpiAwarenessContext(new IntPtr(-4));}catch{}
|
|
119
|
+
sc=shortcuts;P=path;lastRot=Environment.TickCount;w=new StreamWriter(path,true,new UTF8Encoding(false));
|
|
120
|
+
IntPtr mod=GetModuleHandle(null);mp=Mouse;kp=Key;
|
|
121
|
+
if(SetWindowsHookEx(14,mp,mod,0)==IntPtr.Zero||SetWindowsHookEx(13,kp,mod,0)==IntPtr.Zero)throw new Exception("SetWindowsHookEx failed: "+Marshal.GetLastWin32Error());
|
|
122
|
+
var watch=new Thread(()=>{while(true){Thread.Sleep(500);bool gone;try{gone=Process.GetProcessById(parent).HasExited;}catch{gone=true;}if(gone)Quit();}});
|
|
123
|
+
watch.IsBackground=true;watch.Start();
|
|
124
|
+
var pump=new Thread(()=>Pump(path+".stop"));pump.IsBackground=true;pump.Start();
|
|
125
|
+
if(Describer!=null){var ew=new Thread(Elements);ew.IsBackground=true;ew.Start();}
|
|
126
|
+
if(Hotkeys){if(!RegisterHotKey(IntPtr.Zero,1,0x4007,0x4D))Say("hotkey-taken marker");if(!RegisterHotKey(IntPtr.Zero,2,0x4007,0x53))Say("hotkey-taken stop");}
|
|
127
|
+
Say("ready");
|
|
128
|
+
MSG msg;while(GetMessage(out msg,IntPtr.Zero,0,0)>0){if(msg.m==0x312){string a=msg.w.ToInt64()==1?"marker":"stop";Put("hotkey",cx,cy,a);Say("hotkey "+a);}}
|
|
129
|
+
}
|
|
54
130
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
131
|
+
"@
|
|
132
|
+
[ScEvents]::Rot=__ROTATE__
|
|
133
|
+
[ScEvents]::Focus=__FOCUS__
|
|
134
|
+
[ScEvents]::Hotkeys=$__HOTKEYS__
|
|
135
|
+
__ELEMS__
|
|
136
|
+
[ScEvents]::Run([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATH__')), [bool]__MODE__, __PARENT__)
|
|
137
|
+
`,dy=`
|
|
138
|
+
Add-Type -AssemblyName UIAutomationClient,UIAutomationTypes,WindowsBase
|
|
139
|
+
$refs=@([System.Windows.Automation.AutomationElement].Assembly.Location,[System.Windows.Automation.ControlType].Assembly.Location,[System.Windows.Point].Assembly.Location)
|
|
140
|
+
Add-Type -ReferencedAssemblies $refs @"
|
|
141
|
+
using System;using System.Diagnostics;using System.Windows.Automation;
|
|
142
|
+
public static class ScElems{
|
|
143
|
+
static string Clean(string s){return (s??"").Replace('\\r',' ').Replace('\\n',' ').Trim();}
|
|
144
|
+
public static string At(double x,double y){AutomationElement el=AutomationElement.FromPoint(new System.Windows.Point(x,y));if(el==null)return null;var cur=el.Current;
|
|
145
|
+
string role=cur.ControlType==null?"":cur.ControlType.ProgrammaticName.Replace("ControlType.","");
|
|
146
|
+
string name=cur.IsPassword?"":Clean(cur.Name);if(name.Length>200)name=name.Substring(0,200);
|
|
147
|
+
string exe;try{exe=Process.GetProcessById(cur.ProcessId).ProcessName+".exe";}catch{exe="";}
|
|
148
|
+
return role+"|"+exe+"|"+Clean(cur.AutomationId).Replace('|',' ')+"|"+name;}
|
|
68
149
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
const stopped = await stopAll(store, (path) => ffprobe ? probeDuration(path, { ffprobe }) : Promise.resolve(null));
|
|
87
|
-
process.stderr.write(`Shutdown (${reason}): stopped ${stopped.length} recording(s).\n`);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
catch (err) {
|
|
91
|
-
process.stderr.write(`Shutdown cleanup failed: ${errorMessage(err)}\n`);
|
|
92
|
-
}
|
|
93
|
-
const cancelled = await edits;
|
|
94
|
-
if (cancelled > 0)
|
|
95
|
-
process.stderr.write(`Shutdown (${reason}): cancelled ${cancelled} edit job(s).\n`);
|
|
96
|
-
process.exit(exitCode);
|
|
150
|
+
"@
|
|
151
|
+
[ScEvents]::Describer=[Delegate]::CreateDelegate([Func[double,double,string]],[ScElems].GetMethod('At'))
|
|
152
|
+
`,go={marker:"Ctrl+Alt+Shift+M",stop:"Ctrl+Alt+Shift+S"};function my(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 fy(t,e,r,n={}){let o=Math.max(0,Math.round((n.rotateSec??0)*1e3)),i=n.focus??"off";return py.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?dy:"").replace("__HOTKEYS__",n.hotkeys?"true":"false")}function hy(t){return`${t}.1`}function gy(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(`
|
|
153
|
+
`)}function Lp(t,e=-1/0){let r=o=>{try{return yc(o)?Fp(o,"utf8"):""}catch{return""}},n=`${r(hy(t))}
|
|
154
|
+
${r(t)}`;return e===-1/0?n:gy(n,e)}function by(t){return t.startsWith("#< CLIXML")?[...t.matchAll(/<S S="Error">([^<]*)<\/S>/g)].map(r=>r[1]).join("").replace(/_x000D__x000A_/g,`
|
|
155
|
+
`).replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&").trim():t.trim()}var Pp=2e4;async function Wp(t,e,r={}){if(process.platform!=="win32")throw new l("The input event log is implemented for Windows only.");Sc(`${t}.stop`,{force:!0});let n=Buffer.from(fy(t,e,process.pid,r),"utf16le").toString("base64"),o=sy("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=[];jp.set(o,s);let a="";return o.stdout?.on("data",c=>{a+=c.toString();let u=a.split(/\r?\n/);a=u.pop()??"";for(let d of u){let p=my(d);if(p)if("taken"in p)s.push(p.taken);else try{r.onHotkey?.(p.pressed)}catch{}}}),await new Promise((c,u)=>{let d=!1,p=m=>{d||(d=!0,clearTimeout(f),o.kill(),u(new l(`Could not start the input event log: ${m}`)))},f=setTimeout(()=>p(`no response in ${Pp/1e3}s`),Pp);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(by(i)||`helper exited with code ${m}`))}),Up.set(o,`${t}.stop`),o}var jp=new WeakMap;function Bp(t){return[...jp.get(t)??[]]}var Up=new WeakMap,Ip=2e3;function bo(t){if(t.exitCode!==null||t.signalCode!==null)return Promise.resolve();let e=Up.get(t);if(e)try{Op(e,"")}catch{e=void 0}return new Promise(r=>{let n=setTimeout(()=>t.kill(),e?Ip:0),o=setTimeout(r,Ip+5e3);t.once("exit",()=>{clearTimeout(n),clearTimeout(o),r()})}).finally(()=>{e&&Sc(e,{force:!0})})}function ke(t){let e=t.replace(/\.[^./\\]+$/,"");return{raw:`${e}.events.raw`,jsonl:`${e}.events.jsonl`}}function Di(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}Sc(t.raw,{force:!0})}function zp(t,e){let r=yc(t.raw)?Fp(t.raw,"utf8"):"",n=kc(r,e);Op(t.jsonl,Ec(n));try{ay(t.raw)}catch{}return n}var fo=new Map;function wo(t,e){let r=fo.get(t),n=r?Promise.all([r,e]).then(()=>{}):e;fo.set(t,n),n.finally(()=>{fo.get(t)===n&&fo.delete(t)})}async function rr(t,e=1e4){let r=fo.get(t);r&&await Promise.race([r,new Promise(n=>setTimeout(n,e))])}var Jp=2,_y=3,Wi=4,hn=3600,Ty="seg%05d.ts",Yp=/^seg(\d{5})\.ts$/,Kp="segments.csv",Ay=/^buf-[\w-]+$/,Vp=60;function Qp(t){return t+Vp}function Zp(){return Ke(Fe(),"replay")}function Ry(t,e=Jp){return Math.ceil(t/e)+_y}function ed(t,e=Jp){if(!Number.isInteger(t)||t<Wi||t>hn)throw new l(`replayBufferSec must be an integer from ${Wi} to ${hn} seconds.`);return{dir:Ke(Zp(),`buf-${he()}-${ge(6)}`),bufferSec:t,segmentSec:e,wrap:Ry(t,e)}}function td(t){return Ke(t,Kp)}function rd(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",td(e.dir),"-segment_list_type","csv","-segment_list_size",String(e.wrap),"-segment_format","mpegts","-segment_format_options","flush_packets=1",rn(e.dir,Ty)]}function My(t){let e=[];for(let r of t.split(/\r?\n/)){let[n="",o,i]=r.trim().split(","),s=Yp.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 Cy(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 Py(t,e){let r=t.at(-1),n=r?(r.index+1)%e:0;return`seg${String(n).padStart(5,"0")}.ts`}function Iy(t,e,r){let n=r.reencode?$e({quality:r.quality??"standard",audio:r.audio?"aac":"omit"}):["-c","copy"];return["-y","-v","error","-ss",String(xo(Math.max(0,r.startSec))),"-i",t,...n,...Mr,e]}function Fy(t,e,r){return Ni(t,{from:e,to:r}).map(n=>({...n,t:xo(n.t-e)}))}var xo=t=>Math.round(t*1e3)/1e3;async function qp(t,e,r){let n=(await Gp(t)).size;return n===0?(await ky(e,""),0):(await Ey(wy(t,{start:0,end:n-1}),xy(e),{signal:r}),(await Gp(e)).size)}async function Xp(t,e,r){let n=await se(t,["-v","error","-show_entries","format=start_time","-of","csv=p=0",e],15e3,{signal:r}),o=Number.parseFloat(n.stdout.trim());return n.code===0&&Number.isFinite(o)?o:null}async function Tc(t,e){if(!Li(t.dir))throw new l("This replay buffer has been discarded: its segments are gone.");let r=td(t.dir),n=Li(r)?My(vy(r,"utf8")):[],o=Cy(n,e.lastSec),i=Sy(Ke(t.dir,"save-"));try{let s=[];for(let[C,I]of o.entries()){let R=Ke(i,`${String(C).padStart(5,"0")}.ts`);await qp(Ke(t.dir,I.file),R,e.signal),s.push(R)}let a=!1;if(e.live!==!1){let C=Ke(t.dir,Py(n,t.wrap)),I=Ke(i,"live.ts");if(Li(C)&&await qp(C,I,e.signal)>0){let R=s.at(-1),[A,W]=await Promise.all([Xp(e.ffprobe,I,e.signal),R?Xp(e.ffprobe,R,e.signal):Promise.resolve(-1/0)]);A!==null&&W!==null&&A>W&&(s.push(I),a=!0)}}if(s.length===0)throw new l("The replay buffer has no footage yet: the first segment is still being written. Try again in a couple of seconds.");let c=Ke(i,"join.txt");Hp(c,uo(s));let u=Ke(i,"joined.mp4"),d=le(e.lastSec+2*t.segmentSec),p=await se(e.ffmpeg,ln(c,u,{quiet:!0}),d,{signal:e.signal});if(p.code!==0)throw new l(`Joining the replay segments failed:
|
|
156
|
+
${p.stderr.trim().split(`
|
|
157
|
+
`).slice(-4).join(`
|
|
158
|
+
`)}`);let f=await se(e.ffprobe,Ir(u),3e4,{signal:e.signal}),m=f.code===0?Pr(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 g=Math.max(0,h-e.lastSec),w=await se(e.ffmpeg,Iy(u,e.output,{startSec:g,reencode:e.reencode,quality:e.quality,audio:!!m?.audioCodec}),d,{signal:e.signal});if(w.code!==0)throw new l(`Writing the replay failed:
|
|
159
|
+
${w.stderr.trim().split(`
|
|
160
|
+
`).slice(-4).join(`
|
|
161
|
+
`)}`);let b=o[0]?.start??n.at(-1)?.end??0,x=xo(b+g),$=xo(b+h),S={outputPath:e.output,durationSec:xo(h-g),fromSec:x,toSec:$,segments:s.length,includesLive:a};if(t.events){let C=t.events.startMs+x*1e3-Vp*1e3,I=Lp(t.events.raw,C),R=Fy(kc(I,{startMs:t.events.startMs,frame:t.events.frame}),x,$),{jsonl:A}=ke(e.output);Hp(A,Ec(R)),S.eventsPath=A,S.events=fn(R)}return S}finally{ji(i,{recursive:!0,force:!0})}}function nd(t){yy(t.dir,{recursive:!0})}function od(t){let e;try{e=_c(t.dir)}catch{return}for(let r of e)(Yp.test(r)||r===Kp)&&ji(Ke(t.dir,r),{force:!0})}function yo(t){try{return ji(t.dir,{recursive:!0,force:!0}),!Li(t.dir)}catch{return!1}}function id(t){let e=0;try{for(let r of _c(t.dir))try{let n=$y(Ke(t.dir,r));n.isFile()&&(e+=n.size)}catch{}}catch{}return e}function sd(t,e=Zp()){let r=new Set([...t].map(i=>i.toLowerCase())),n;try{n=_c(e)}catch{return 0}let o=0;for(let i of n){let s=Ke(e,i);if(!(!Ay.test(i)||r.has(s.toLowerCase())))try{ji(s,{recursive:!0,force:!0}),o++}catch{}}return o}async function Bi(t,e){if(!e.save)return{saved:!1,discarded:yo(t)};try{let r=e.tools?.();if(!r)throw new l("ffmpeg is not available to save the replay buffer.");let n=await Tc(t,{...r,lastSec:t.bufferSec,output:e.output,quality:e.quality,live:!1});return{saved:!0,discarded:yo(t),save:n}}catch(r){return{saved:!1,discarded:!1,error:H(r)}}}var ad=3;function Ui(t){return`${t}.stop`}function cd(t,e,r){return`Add-Type @"
|
|
162
|
+
using System;using System.Runtime.InteropServices;
|
|
163
|
+
public class ScNudge{
|
|
164
|
+
[StructLayout(LayoutKind.Sequential)] public struct RECT{public int L,T,R,B;}
|
|
165
|
+
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr h,ref RECT r,IntPtr g,uint f);
|
|
166
|
+
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h);
|
|
97
167
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
168
|
+
"@
|
|
169
|
+
$r=New-Object ScNudge+RECT;$r.R=1;$r.B=1
|
|
170
|
+
${r?`$p=Get-Process -Id ${r} -ErrorAction SilentlyContinue
|
|
171
|
+
`:""}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}}`}import{execFile as Oy}from"node:child_process";import{randomBytes as Ny}from"node:crypto";import{rmSync as Dy,writeFileSync as Ly}from"node:fs";import{tmpdir as Wy}from"node:os";import{join as jy}from"node:path";function By(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 Uy=`
|
|
172
|
+
Add-Type @"
|
|
173
|
+
using System;using System.Runtime.InteropServices;
|
|
174
|
+
public class DpiShim{ [DllImport("user32.dll")] public static extern IntPtr SetProcessDpiAwarenessContext(IntPtr v);
|
|
175
|
+
public struct PT{public int X,Y;}
|
|
176
|
+
[DllImport("user32.dll")] public static extern IntPtr MonitorFromPoint(PT p,uint f);
|
|
177
|
+
[DllImport("shcore.dll")] public static extern int GetDpiForMonitor(IntPtr m,int t,out uint x,out uint y);
|
|
178
|
+
public static int Dpi(int x,int y){try{PT p=new PT();p.X=x;p.Y=y;uint dx,dy;if(GetDpiForMonitor(MonitorFromPoint(p,2),0,out dx,out dy)==0)return (int)dx;}catch{}return 0;} }
|
|
179
|
+
"@
|
|
180
|
+
try{[void][DpiShim]::SetProcessDpiAwarenessContext([IntPtr](-4))}catch{}
|
|
181
|
+
Add-Type -AssemblyName System.Windows.Forms
|
|
182
|
+
[System.Windows.Forms.Screen]::AllScreens | ForEach-Object {
|
|
183
|
+
[pscustomobject]@{ X=$_.Bounds.X; Y=$_.Bounds.Y; Width=$_.Bounds.Width; Height=$_.Bounds.Height; Primary=$_.Primary; Dpi=[DpiShim]::Dpi($_.Bounds.X,$_.Bounds.Y) }
|
|
184
|
+
} | ConvertTo-Json -Compress
|
|
185
|
+
`,zy=5e3,gn=null,Hy=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
186
|
+
`,Gy=2e4,ld="SCREENCAST_PS_TIMEOUT_MS";function nr(t,e=process.env){let r=Number(e[ld]);return Number.isInteger(r)&&r>0?r:t}function qy(t){return`$Payload = [IO.File]::ReadAllText([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(t,"utf8").toString("base64")}')), [Text.Encoding]::UTF8)
|
|
187
|
+
`}function Xy(t,e){let r=Hy+(e===void 0?"":qy(e))+t;return["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}async function Jy(t,e){let r=jy(Wy(),`screencast-ps-${process.pid}-${Ny(6).toString("hex")}.json`);Ly(r,t,{encoding:"utf8",mode:384});try{return await e(r)}finally{Dy(r,{force:!0})}}function at(t,e,r={}){return r.payload===void 0?ud(t,e,r):Jy(r.payload,n=>ud(t,e,r,n))}function ud(t,e,r,n){let o=r.timeoutMs??nr(Gy),i=r.command?.file??"powershell",s=r.command?.args??Xy(t,n);return new Promise((a,c)=>{Oy(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 ${ld}.`));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 Yy(){let t=await at(Uy,"monitors");try{return By(JSON.parse(t))}catch(e){throw new l(`Could not parse monitor geometry: ${H(e)}`)}}function or(t=Date.now()){if(process.platform!=="win32")return Promise.reject(new l("Monitor enumeration is implemented for Windows (gdigrab) only."));if(gn&&t-gn.at<zy)return gn.monitors;let e={at:t,monitors:Yy()};return gn=e,e.monitors.catch(()=>{gn===e&&(gn=null)}),e.monitors}var Hi=["nvenc","qsv","amf"],Gi={x264:"libx264",nvenc:"h264_nvenc",qsv:"h264_qsv",amf:"h264_amf"},Ky={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 ir(t,e,r={}){if(!sc[e])throw new l(`Unknown quality preset "${e}".`);if(t==="x264")return Te(e);let{preset:n,q:o}=Ky[t][e],i=["-c:v",Gi[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 Vy(t){return["-hide_banner","-v","error","-f","lavfi","-i","color=c=black:s=256x256:r=30","-frames:v","3",...ir(t,"draft"),"-f","null","-"]}function md(t){return["-hide_banner","-v","error","-f","lavfi","-i",`ddagrab=framerate=10${t?"":",hwdownload,format=bgra"}`,"-frames:v","2",...t?ir(t,"draft",{gpuFrames:!0}):[],"-f","null","-"]}var Qy=2e4;function Ac(t){return async e=>{try{return(await se(t,e,Qy)).code===0}catch{return!1}}}var pd=new Map;function Rc(t,e,r,n){let o=`${t}\0${e}`,i=pd.get(o);return i||(i=n(r),pd.set(o,i)),i}async function Mc(t,e=Ac(t)){let r=await Promise.all(Hi.map(n=>Rc(t,`enc:${n}`,Vy(n),e)));return Object.fromEntries(Hi.map((n,o)=>[n,r[o]]))}var zi={nvenc:{width:4096,height:4096},qsv:{width:4096,height:2304},amf:{width:4096,height:2304}};function Zy(t,e){let r=zi[t];return e.width<=r.width&&e.height<=r.height}async function fd(t,e,r,n=Ac(r),o){if(t==="x264")return{encoder:"x264",gpuFrames:!1};let i=d=>!o||Zy(d,o),s=o?`${o.width}x${o.height}`:"";if(t!=="auto"&&!i(t)){let d=zi[t];throw new l(`The ${t} encoder (${Gi[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 Mc(r,n),c=t==="auto"?Hi.find(d=>a[d]&&i(d)):a[t]?t:void 0;if(!c){if(t==="auto"){let d=Hi.filter(p=>a[p]);return{encoder:"x264",gpuFrames:!1,note:d.length>0?`The capture is ${s}, larger than the hardware encoders here take (${d.map(p=>`${p}: ${zi[p].width}x${zi[p].height}`).join(", ")}); using libx264.`:"No hardware encoder passed a trial encode; using libx264."}}throw new l(`The ${t} encoder (${Gi[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 Rc(r,`dda:${c}`,md(c),n);return{encoder:c,gpuFrames:u}}async function hd(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} (${Gi[t.encoder]})`,s=r.why(n).trim(),a=`the ${i} encoder exited at start${s?`:
|
|
188
|
+
${s}`:""}`;r.beforeRetry?.();let c=await e(o);if(c.settled==="exited")return{run:c,pick:o,failure:a};let u=s.split(`
|
|
189
|
+
`).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 gd(t,e=Ac(t)){return Rc(t,"dda",md(),e)}function eS(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 tS=`
|
|
190
|
+
Add-Type -TypeDefinition @"
|
|
191
|
+
using System; using System.Runtime.InteropServices; using System.Text;
|
|
192
|
+
public static class ScDxgi {
|
|
193
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
194
|
+
public struct DESC { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string Name; public int L, T, R, B; public int Attached; public int Rot; public IntPtr Mon; }
|
|
195
|
+
[ComImport, Guid("770aae78-f26f-4dba-a829-253c83d1b387"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
|
196
|
+
interface IF1 { void a(); void b(); void c(); void d(); void e(); void f(); void g(); void h(); void i();
|
|
197
|
+
[PreserveSig] int EnumAdapters1(uint i, [MarshalAs(UnmanagedType.Interface)] out IA1 a); }
|
|
198
|
+
[ComImport, Guid("29038f61-3839-4626-91fd-086879011a05"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
|
199
|
+
interface IA1 { void a(); void b(); void c(); void d();
|
|
200
|
+
[PreserveSig] int EnumOutputs(uint i, [MarshalAs(UnmanagedType.Interface)] out IO o); }
|
|
201
|
+
[ComImport, Guid("ae02eedb-c735-4690-8d52-5a8dc20213aa"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
|
202
|
+
interface IO { void a(); void b(); void c(); void d(); [PreserveSig] int GetDesc(out DESC d); }
|
|
203
|
+
[DllImport("dxgi.dll")] static extern int CreateDXGIFactory1(ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IF1 f);
|
|
204
|
+
public static string List() {
|
|
205
|
+
Guid g = new Guid("770aae78-f26f-4dba-a829-253c83d1b387"); IF1 f;
|
|
206
|
+
if (CreateDXGIFactory1(ref g, out f) != 0) return "";
|
|
207
|
+
StringBuilder sb = new StringBuilder(); IA1 a;
|
|
208
|
+
for (uint ai = 0; f.EnumAdapters1(ai, out a) == 0; ai++) { IO o;
|
|
209
|
+
for (uint oi = 0; a.EnumOutputs(oi, out o) == 0; oi++) { DESC d;
|
|
210
|
+
if (o.GetDesc(out d) == 0) sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6}\\n", ai, oi, d.L, d.T, d.R - d.L, d.B - d.T, d.Name); } }
|
|
211
|
+
return sb.ToString(); } }
|
|
212
|
+
"@
|
|
213
|
+
[ScDxgi]::List()
|
|
214
|
+
`,rS=5e3,So=null;function bd(){if(So&&Date.now()-So.at<rS)return So.outputs;let t=at(tS,"DXGI outputs").then(eS);return So={at:Date.now(),outputs:t},t.catch(()=>{So=null}),t}var dd=t=>t-t%2;function wd(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=dd(t.w),i=dd(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 xd(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{existsSync as qi,mkdirSync as nS,renameSync as oS,rmSync as iS,statSync as sS,writeFileSync as aS}from"node:fs";import{basename as cS,dirname as uS,extname as Sd,join as vo}from"node:path";var vd=.25;function ct(t){return`${t}.parts`}function $d(t,e){return e===0?t:vo(ct(t),`part-${String(e).padStart(3,"0")}.mp4`)}function Xi(t,e){return vo(ct(t),`webcam-${String(e).padStart(3,"0")}.mp4`)}function Nr(t){let e=Sd(t);return vo(uS(t),`${cS(t,e)}.webcam.mp4`)}function Pc(t,e,r,n){if(e!==null&&e>0)return e;let o;try{o=sS(t).size}catch{return null}return o<=0?null:Math.max(.001,Math.round(n-r)/1e3)}function rt(t){return t.reduce((e,r)=>e+r.durationSec,0)}function lS(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 Ji(t,e,r){if(!t||t.parts.length===0&&!t.current)return{startMs:e,endSec:(r-e)/1e3};let n=lS(t),o=t.current?Math.max(0,(r-t.current.startMs)/1e3):0;return{startMs:n[0].startMs,endSec:rt(t.parts)+o,spans:n}}function kd(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 Ed(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 _d(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 Ic=new Set;function Td(t){Ic.add(t)}function Ad(t){return Ic.has(t)}function Rd(t){Ic.delete(t)}var Cc=new Map;function Md(t){let e=Cc.get(t);if(!e){let r;e={promise:new Promise(o=>r=o),resolve:r},Cc.set(t,e)}return e}function $o(t){return Md(t).promise}function Yi(t){Md(t).resolve(),setTimeout(()=>Cc.delete(t),6e4).unref?.()}var yd=t=>Math.round(t*1e3)/1e3;function pS(t,e,r){if(t.length===0)throw new l("No webcam parts to join.");let n=t.map((i,s)=>{let a=yd(Math.max(.001,i.durationSec)),c=yd(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,...Mr,e]}async function Cd(t,e,r){let n=ct(t),o={joined:!1},i=e.filter(u=>qi(u.path)&&u.durationSec>0),s=rt(i),a=!1;if(i.length>1||i.length===1&&i[0].path!==t){nS(n,{recursive:!0});let u=vo(n,"segments.txt"),d=vo(n,`joined${Sd(t)||".mp4"}`);aS(u,uo(i.map(f=>f.path)));let p=await se(r.ffmpeg,ln(u,d,{quiet:!0}),le(s));p.code===0&&qi(d)?(oS(d,t),o.joined=!0):(a=!0,o.error=`Joining the ${i.length} segments failed; they are kept in ${n}: ${p.stderr.trim().split(`
|
|
215
|
+
`).slice(-3).join(" ")}`)}let c=i.filter(u=>u.webcamPath&&qi(u.webcamPath));if(r.webcamOutput&&c.length>0){let u=pS(c.map(p=>({path:p.webcamPath,leadSec:p.webcamStartMs!==void 0?(p.webcamStartMs-p.startMs)/1e3:0,durationSec:p.durationSec})),r.webcamOutput,r.webcamCodec),d=await se(r.ffmpeg,u,le(s));d.code===0&&qi(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(`
|
|
216
|
+
`).slice(-3).join(" ")}`)}return a||iS(n,{recursive:!0,force:!0}),o}function Pd(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{spawnSync as Oc}from"node:child_process";import{readFileSync as Ki,writeFileSync as Fd,renameSync as Od,existsSync as dS,copyFileSync as mS,openSync as fS,closeSync as hS,unlinkSync as Nd,statSync as Dd,linkSync as gS}from"node:fs";import{basename as bS}from"node:path";var wS=100;function bn(t){return t==="recording"||t==="paused"}function xS(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 Ld(t,e,r){return bn(t.status)&&t.serverPid!==void 0&&t.serverPid!==e&&r}function Wd(t,e,r){return t.backend==="wgc"||!Ld(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 Nc(t,e=new Map){let r=t.serverPid;return r===void 0||r===process.pid||!ze(r)?!1:(e.has(r)||e.set(r,Ud(r)),yS(t,e.get(r)??null))}function jd(){return{serverPid:process.pid,serverStartedAt:new Date(Date.now()-process.uptime()*1e3).toISOString(),serverImage:bS(process.execPath).toLowerCase()}}var Bd=5e3;function yS(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+Bd)}function SS(t){let e=/^(.+)\|(\d+)\s*$/m.exec(t.trim());return e?.[1]&&e[2]?{image:e[1].trim(),startMs:Number(e[2])}:null}function Ud(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=Oc("powershell",["-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",windowsHide:!0,timeout:1e4,killSignal:"SIGKILL"});return r.status===0&&r.stdout?SS(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 zd(t){return t.processImage??(t.backend==="wgc"?"node.exe":"ffmpeg.exe")}function vS(t,e){return(t.split(/\r?\n/)[0]??"").toLowerCase().startsWith(`"${e.toLowerCase()}"`)}function $S(t,e){if(t===null||process.platform!=="win32")return!1;let r=Oc("tasklist",["/FI",`PID eq ${t}`,"/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0});return r.status!==0||!r.stdout?!1:vS(r.stdout,e)}function kS(t,e){if(!e)return!0;if(e.image.toLowerCase()!==zd(t).toLowerCase())return!1;let r=t.pidSpawnedAt;return!(typeof r=="number"&&Number.isFinite(r)&&e.startMs>r+Bd)}function Dc(t){return t.pid===null||!$S(t.pid,zd(t))?!1:t.pidSpawnedAt===void 0||kS(t,Ud(t.pid))}function Hd(t){let{code:e,backend:r,maxDurationSec:n,elapsedMs:o}=t;return r==="wgc"&&e===ad?{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 sr(t){if(process.platform==="win32")Oc("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0});else try{process.kill(t,"SIGKILL")}catch{}}function Fc(t){let e=t.filter(n=>bn(n.status)),r=t.filter(n=>!bn(n.status)).sort((n,o)=>n.startedAt<o.startedAt?1:-1).slice(0,wS);return[...e,...r]}var ES=3e4,Gd=15e3;function _S(t,e,r){return!t||typeof t.at!="number"||e-t.at>ES?!0:typeof t.pid=="number"&&!r}function qd(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function TS(t,e){let r=Date.now()+1e3;for(;;)try{Od(t,e);return}catch(n){let o=n.code;if(o!=="EPERM"&&o!=="EBUSY"&&o!=="EACCES"||Date.now()>=r)throw n;qd(15)}}function AS(t,e){let r=`${t}.${process.pid}.${Date.now()}.stale`;try{Od(t,r)}catch{return!1}let n=!0;try{Ki(r,"utf8")!==e&&(n=!1,gS(r,t))}catch{}try{Nd(r)}catch{}return n}function Id(t,e,r=Gd){let n=`${t}.lock`,o=Date.now()+r,i,s;for(let a=0;;a++)try{let c=fS(n,"wx");s=JSON.stringify({pid:process.pid,at:Date.now(),nonce:Math.random().toString(36).slice(2)}),Fd(c,s),hS(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}): ${H(c)}`);if(u==="EEXIST"){let p;try{let f=Ki(n,"utf8"),m;try{m=JSON.parse(f)}catch{m={at:Dd(n).mtimeMs}}p={raw:f,holder:m}}catch{p=null}if(p&&(i=p.holder?.pid,_S(p.holder,Date.now(),ze(p.holder?.pid??null))&&AS(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.");qd(Math.min(50,2**Math.min(a,6))*(.5+Math.random()))}try{return e()}finally{try{Ki(n,"utf8")===s&&Nd(n)}catch{}}}var Vi=class{constructor(e,r=Gd){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(!dS(this.path))return new Map;try{return this.parseDisk()}catch{try{mS(this.path,`${this.path}.bak`),process.stderr.write(`Session registry was unreadable; saved a copy to ${this.path}.bak and starting fresh.
|
|
217
|
+
`)}catch{}return new Map}}parseDisk(){let e=JSON.parse(Ki(this.path,"utf8"));return new Map(e.map(r=>[r.id,r]))}signature(){try{let e=Dd(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(Fc([...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=Id(this.path,e,this.lockWaitMs)}catch(n){process.stderr.write(`${H(n)} Reading the session registry without the lock.
|
|
218
|
+
`),r=e()}this.records=new Map(Fc([...this.overlay(r).values()]).map(n=>[n.id,n]))}persist(){Id(this.path,()=>{let e=Fc([...this.overlay(this.readDisk()).values()]),r=`${this.path}.${process.pid}.tmp`;Fd(r,JSON.stringify(e,null,2)),TS(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}: ${H(n)}
|
|
219
|
+
`);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(!bn(n.status)||Ld(n,process.pid,Nc(n,r)))continue;let o=ze(n.pid),i=xS(n,o);i.reaped&&n.pid!==null&&(Dc(n)&&sr(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}).`}:{}};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 Lc(t,e){let r=Date.now()+e;for(;Date.now()<r&&ze(t);)await new Promise(n=>setTimeout(n,100))}function Xd(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 Vd(t,e,r){if(!t.stdin||!t.stdin.writable)return!1;t.stdin.write(`q
|
|
220
|
+
`),t.stdin.end();let n=await Xd(t,r);return!n&&e!==null&&(sr(e),await Lc(e,2e3),await Xd(t,2e3)),n}async function MS(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=Pc(r.current.path,o,r.current.startMs,i)??0;n.push({...r.current,durationSec:s})}return n}function CS(t){let e=t.segments;return!!e&&(e.parts.length>0||!!t.webcam)}async function Wc(t,e){let r=await MS(t,e.ffprobe),n=await Cd(t.outputPath,r,{ffmpeg:e.ffmpeg,webcamOutput:t.webcam?Nr(t.outputPath):void 0,webcamCodec:ir(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 Jd=new WeakMap;function Qi(t,e,r,n,o={}){let i=Jd.get(t);i||Jd.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_recording 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 Qd(t,e,r){return Qi(t,e.id,"pause",()=>PS(t,t.get(e.id)??e,r))}async function PS(t,e,r){let n=t.getChild(e.id),o=Ed(e,!!n);if(o)throw new l(`Cannot pause ${e.id}: ${o}.`);Td(e.id),t.markStopping(e.id);try{let i=Date.now(),s=await Vd(n,e.pid,r.gracefulMs??8e3);t.detachChild(e.id,n);let a=e.segments.current,c=await r.probe(a.path),u=Pc(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&&Kd(a.path,{force:!0}),t.markPaused(e.id),{record:t.update(e.id,{status:"paused",pid:null,segments:{parts:p}}),recordedSec:rt(p),segmentSec:u,graceful:s}}finally{Rd(e.id),t.clearStopping(e.id)}}async function Zd(t,e,r=1e4){let n=t.activeIds(),o=n.map(async a=>{let c=t.get(a);if(c)try{await wn(t,c,{reason:"shutdown",probe:e,gracefulMs:Math.min(8e3,r)})}catch(u){process.stderr.write(`Stopping ${a} on shutdown failed: ${H(u)}
|
|
221
|
+
`)}}),i,s=new Promise(a=>{i=setTimeout(a,r)});return await Promise.race([Promise.allSettled(o),s]),clearTimeout(i),n}function wn(t,e,r){return Qi(t,e.id,"stop",async n=>{if(!n)return Yd(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}:Yd(t,o,r)},{queue:!0})}async function Yd(t,e,r){t.markStopping(e.id);let n=e.backend==="wgc"?Ui(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 Vd(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)&&Dc(e)&&(n&&(RS(n,""),await Lc(e.pid,r.gracefulMs??8e3),o=!ze(e.pid)),ze(e.pid)&&(sr(e.pid),await Lc(e.pid,2e3)),ze(e.pid)))throw s(e.pid);t.detachChild(e.id,i),e.status==="paused"&&(o=!0),Yi(e.id),t.clearPaused(e.id),await rr(e.id);let a,c={};if(CS(e)){let f=await Wc(e,E());c=f.patch,a={count:f.count,...f.error?{error:f.error}:{}}}let u=e.replay?await Bi(e.replay,{save:r.saveReplay??!1,output:e.outputPath,quality:e.quality,tools:E}):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&&Kd(n,{force:!0}),t.clearStopping(e.id)}}import{existsSync as FS,readFileSync as OS,renameSync as NS,writeFileSync as DS}from"node:fs";var Zi=t=>Math.round(t*1e3)/1e3;function ko(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 es(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-=ko(r,n.spans);return r}function Dr(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-=ko(n,i.spans),o-=ko(o,i.spans)),o<=n)return null;return[n,o]}function rm(t,e){return t.flatMap(r=>{let n=Dr(r.start,r.end,e);return n?[{start:Zi(n[0]),end:Zi(n[1])}]:[]})}function ts(t,e){return t.flatMap(r=>{let n=Dr(r.start,r.end,e);return n&&n[1]-n[0]>=.05?[{...r,start:Zi(n[0]),end:Zi(n[1])}]:[]})}var IS=/^(\d+):(\d{2}):(\d{2})\.(\d{2})$/,em=t=>{let e=t.trim().match(IS);return e?Number(e[1])*3600+Number(e[2])*60+Number(e[3])+Number(e[4])/100:null},tm=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 nm(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=em(i),u=em(s);if(c===null||u===null)return[r];let d=Dr(c,u,e);return d&&d[1]-d[0]>=.05?[`${o}${tm(d[0])},${tm(d[1])},${a}`]:[]}).join(`
|
|
222
|
+
`)}var om=500,jc=200,im=3,xn=10,Mt=t=>Math.round(t*1e3)/1e3;function ar(t){return`${t.replace(/\.[^./\\]+$/,"")}.markers.json`}function sm(t,e){return Math.max(0,Mt((e-t)/1e3))}function Eo(t,e=jc){let r=t.replace(/\s+/g," ").trim();return r.length>e?`${r.slice(0,e-1).trimEnd()}\u2026`:r}function ns(t,e){if(t.length>=om)throw new l(`A recording holds at most ${om} markers.`);let r=Eo(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:Mt(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 LS(t){let e=t;return!!e&&typeof e.t=="number"&&Number.isFinite(e.t)&&e.t>=0&&typeof e.label=="string"}function WS(t){let e;try{e=JSON.parse(t)}catch{return[]}let r=Array.isArray(e)?e:e?.markers;return Array.isArray(r)?r.filter(LS).sort((n,o)=>n.t-o.t):[]}function Le(t){let e=ar(t);if(!FS(e))return[];try{return WS(OS(e,"utf8"))}catch{return[]}}function cr(t,e,r){let n=ar(t),o=`${n}.${process.pid}.tmp`;return DS(o,JSON.stringify({...r?{sessionId:r}:{},markers:e},null,2)),NS(o,n),n}function am(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:Mt(s.t/n.factor)}));continue}if(n.op==="cut"){r=r.map(s=>({...s,t:Mt(s.t-ko(s.t,n.spans))}));continue}let o=r.filter(s=>s.t>=n.start&&s.t<n.end).map(s=>({...s,t:Mt(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 os(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:Mt(a.start),title:Eo(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:Mt(i[c+1]?.start??e),title:a.title}))}function jS(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 cm(t,e){let r=e>=3600,n=t.map(s=>`${jS(s.start,r)} ${s.title}`).join(`
|
|
223
|
+
`),o=[];t.length<im&&o.push(`YouTube needs at least ${im} 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<xn);return i.length>0&&o.push(`YouTube needs every chapter to be at least ${xn} s long; ${i.length} ${i.length===1?"is":"are"} shorter (${i.map(s=>`"${s.title}"`).join(", ")}). Raise minChapterSec to ${xn} to merge them.`),{text:n,issues:o}}function BS(t){return t.replace(/[=;#\\\n]/g,e=>`\\${e}`)}function is(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=${BS(r.title)}`);return`${e.join(`
|
|
224
|
+
`)}
|
|
225
|
+
`}function ss(t){return t.map(e=>({start:e.t,title:e.label}))}function um(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 US(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 lm(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:US(a.text)}),s=Math.max(s,a.end)}return i}var rs=8;function pm(t,e,r,n){let o=n.subtitles??[];if(o.length>rs)throw new l(`At most ${rs} 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 zS(t){return["-v","quiet","-print_format","json","-show_chapters",t]}function HS(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:Mt(o),end:Mt(i),title:r.tags?.title??`Chapter ${n+1}`}]})}async function GS(t,e){let{ffprobe:r}=E(),n=await se(r,zS(t),3e4,{signal:e});return n.code===0?HS(n.stdout):[]}async function ur(t,e){let r=Le(t);if(r.length>0)return{markers:r,from:"sidecar"};let n=await GS(t,e);return n.length>0?{markers:n.map(o=>({t:o.start,label:o.title})),from:"chapters"}:{markers:[],from:null}}function as(t,e,r,n){let o=t.get(e);if(!o)throw new l(`No session with id "${e}".`);let i=n;if(i===void 0&&o.status==="paused")i=rt(o.segments?.parts??[]);else if(i===void 0){if(o.status!=="recording")throw new l(`Session "${e}" is ${o.status}, so there is no "now" to mark.`,"Pass at (video seconds) to mark a stopped recording.");i=sm(o.videoStartMs??Date.parse(o.startedAt),Date.now())}else if(o.durationSec!=null&&i>o.durationSec)throw new l(`at ${i}s is past the end of the recording (${o.durationSec}s).`);let s={t:i,label:r,at:new Date().toISOString()},a=ns(o.markers??[],s);t.update(e,{markers:a});let c=ar(o.outputPath),u;try{c=cr(o.outputPath,a,e)}catch(d){u=`Saved in the session, but the sidecar ${c} could not be written: ${H(d)}`}return{t:i,count:a.length,markersPath:c,live:o.status==="recording"||o.status==="paused",...u?{warning:u}:{}}}import{existsSync as qS,readFileSync as XS}from"node:fs";import{dirname as dm,join as cs}from"node:path";import{fileURLToPath as JS}from"node:url";var mm="@tmhs/screencast-mcp",Bc=null,YS=null;function fm(t){try{return JSON.parse(XS(t,"utf8"))}catch{return null}}function KS(t){for(let e=t;;){let r=cs(e,"package.json");if(qS(r)&&fm(r)?.name===mm)return e;let n=dm(e);if(n===e)return null;e=n}}function Uc(){if(Bc)return Bc;let t=KS(dm(JS(import.meta.url)));if(!t)throw new l(`Cannot find the ${mm} package root (its package.json).`);return Bc=t}function wt(){return YS??=fm(cs(Uc(),"package.json"))?.version??"0.0.0"}function yn(...t){return cs(Uc(),"assets",...t)}function hm(){return cs(Uc(),"dist","wgcRecorder.js")}var wm=5;function zc(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 Hc(t,e,r={}){let n=Array.isArray(t.windows)?t.windows:[],o=n.filter(i=>!i.cloaked);try{return gm(t,o,e,r)}catch(i){if(!(i instanceof Lr)||o.length===n.length)throw i;let s;try{s=gm(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 Lr=class extends l{};function gm(t,e,r,n){let o=zc(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 Lr(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 bm(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,wm).map(f=>`"${f.title}"`).join(", ");if(s.length===0&&n.exactOnly)throw new Lr(`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 Lr(`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 bm(t,d,u)}function bm(t,e,r){let n=e[0];if(!n)throw new Lr("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,wm).map(p=>p.title)}}function lr(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 VS=`
|
|
226
|
+
$ErrorActionPreference='Stop'
|
|
227
|
+
Add-Type @"
|
|
228
|
+
using System;using System.Text;using System.Collections.Generic;using System.Runtime.InteropServices;
|
|
229
|
+
public class WinShim{
|
|
230
|
+
[DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc f,IntPtr l);
|
|
231
|
+
public delegate bool EnumWindowsProc(IntPtr h,IntPtr l);
|
|
232
|
+
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
|
|
233
|
+
[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
|
|
234
|
+
[DllImport("user32.dll",CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr h,StringBuilder s,int n);
|
|
235
|
+
[DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr h);
|
|
236
|
+
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h,out RECT r);
|
|
237
|
+
[DllImport("user32.dll")] public static extern int GetSystemMetrics(int i);
|
|
238
|
+
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h,out uint p);
|
|
239
|
+
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr h,ref PT p);
|
|
240
|
+
public struct PT{public int X,Y;}
|
|
241
|
+
[DllImport("user32.dll")] public static extern IntPtr SetProcessDpiAwarenessContext(IntPtr v);
|
|
242
|
+
public struct RECT{public int Left,Top,Right,Bottom;}
|
|
243
|
+
static List<IntPtr> _h;
|
|
244
|
+
static bool Col(IntPtr h,IntPtr l){_h.Add(h);return true;}
|
|
245
|
+
public static IntPtr[] Z(){_h=new List<IntPtr>();EnumWindows(Col,IntPtr.Zero);return _h.ToArray();}
|
|
246
|
+
public static string T(IntPtr h){int n=GetWindowTextLength(h);if(n==0)return "";var s=new StringBuilder(n+1);GetWindowText(h,s,s.Capacity);return s.ToString();}
|
|
247
|
+
[DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr h,int a,out RECT r,int n);
|
|
248
|
+
public static int[] R(IntPtr h){RECT r;if(DwmGetWindowAttribute(h,9,out r,Marshal.SizeOf(typeof(RECT)))!=0){GetWindowRect(h,out r);}return new int[]{r.Left,r.Top,r.Right,r.Bottom};}
|
|
249
|
+
[DllImport("dwmapi.dll",EntryPoint="DwmGetWindowAttribute")] public static extern int DwmInt(IntPtr h,int a,out int v,int n);
|
|
250
|
+
public static bool Ck(IntPtr h){int v;return DwmInt(h,14,out v,4)==0&&v!=0;}
|
|
251
|
+
public static bool Ic(IntPtr h){return IsIconic(h);}
|
|
252
|
+
public static bool Vis(IntPtr h){return IsWindowVisible(h);}
|
|
253
|
+
public static int SM(int i){return GetSystemMetrics(i);}
|
|
254
|
+
public static uint P(IntPtr h){uint p;GetWindowThreadProcessId(h,out p);return p;}
|
|
255
|
+
public static int[] C(IntPtr h){PT p=new PT();ClientToScreen(h,ref p);return new int[]{p.X,p.Y};}
|
|
109
256
|
}
|
|
110
|
-
|
|
111
|
-
|
|
257
|
+
"@
|
|
258
|
+
try{[void][WinShim]::SetProcessDpiAwarenessContext([IntPtr](-4))}catch{}
|
|
259
|
+
$ws=New-Object System.Collections.ArrayList
|
|
260
|
+
$exes=@{}
|
|
261
|
+
foreach($h in [WinShim]::Z()){
|
|
262
|
+
if(-not [WinShim]::Vis($h)){continue}
|
|
263
|
+
$t=[WinShim]::T($h)
|
|
264
|
+
if([string]::IsNullOrEmpty($t)){continue}
|
|
265
|
+
$r=[WinShim]::R($h)
|
|
266
|
+
$procId=[WinShim]::P($h)
|
|
267
|
+
$c=[WinShim]::C($h)
|
|
268
|
+
if(-not $exes.ContainsKey($procId)){$exes[$procId]=try{(Get-Process -Id $procId -ErrorAction Stop).ProcessName+'.exe'}catch{''}}
|
|
269
|
+
[void]$ws.Add([pscustomobject]@{title=$t;left=$r[0];top=$r[1];right=$r[2];bottom=$r[3];minimized=[bool][WinShim]::Ic($h);hwnd=[int64]$h;exe=$exes[$procId];pid=$procId;clientX=$c[0];clientY=$c[1];cloaked=[WinShim]::Ck($h)})
|
|
112
270
|
}
|
|
271
|
+
$v=[pscustomobject]@{x=[WinShim]::SM(76);y=[WinShim]::SM(77);w=[WinShim]::SM(78);h=[WinShim]::SM(79)}
|
|
272
|
+
[pscustomobject]@{virtual=$v;windows=@($ws)}|ConvertTo-Json -Compress -Depth 4
|
|
273
|
+
`;async function Gc(){if(process.platform!=="win32")throw new l("Window capture is implemented for Windows (gdigrab) only.");let t=await at(VS,"windows"),e;try{e=JSON.parse(t)}catch(i){throw new l(`Could not parse window geometry: ${H(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 xm(t,e={}){return Hc(await Gc(),t,e)}async function ut(t,e={}){let r=Hl(t);if(r.kind==="window"){let n=await xm(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 or()}:r.kind==="region"?(ql(r,await or()),{target:r,monitors:[]}):{target:r,monitors:await or()}}var QS=["virtual-audio-capturer","stereo mix","what u hear","wave out mix","cable output","voicemeeter output"],_o="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 ZS(t){return ym(t,"audio")}function ev(t){return ym(t,"video")}function ym(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 qc(t,e){if(e&&e.trim().length>0)return t.includes(e)?e:null;let r=n=>n.toLowerCase();return t.find(n=>QS.some(o=>r(n).includes(o)))??null}var tv=12e3,rv="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. "+_o,us=null,ls=null;async function Xc(t=!1){return!t&&us?us:(await vm(),us??[])}async function Jc(t=!1){return!t&&ls?ls:(await vm(),ls??[])}async function Sm(t){let e=await Jc();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 vm(){let{ffmpeg:t}=E(),e;try{e=await se(t,["-hide_banner","-list_devices","true","-f","dshow","-i","dummy"],tv)}catch(r){throw new l(`Could not enumerate audio devices (${H(r)}).`,rv)}us=ZS(e.stderr),ls=ev(e.stderr)}async function $m(t){let e=await Xc(),r=qc(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}.`,_o)}throw new l("No system-audio loopback device found.",_o)}var To="SCREENCAST_CONFIRM_CAPTURE",Yc=300*1e3;function km(t=process.env){let e=(t[To]??"").trim().toLowerCase();return["1","true","yes","on","always"].includes(e)?"always":["0","false","no","off","never"].includes(e)?"off":"auto"}function Em(t=process.env){return km(t)==="always"}function Ct(t,e){return e?`window "${e.matchedTitle}"`:t==="full"?"the full screen (all monitors)":t}async function Pt(t,e,r){let n=km();if(n==="off")return;if(!t.server.getClientCapabilities()?.elicitation?.form){if(n==="auto")return;throw new l(`Capture blocked: ${To} 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 ${To}=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:Yc}))}catch(i){throw new l(`Capture blocked: the confirmation request failed (${H(i)}). Nothing was captured.`)}if(o!=="accept")throw new l(`Capture ${o==="decline"?"declined":"cancelled"} by the user. Nothing was captured.`)}var ps=null;function ie(){return ps||(ps=new Vi(jl()),ps.load()),ps}var Vc=!1;function _m(){Vc=!0}function ms(){return Vc}var ds=0,Kc=[];function Tm(){if(Vc)throw new l("The server is shutting down; the recording was not started.");ds++;let t=!1;return()=>{if(!t&&(t=!0,ds--,ds===0)){let e=Kc;Kc=[];for(let r of e)r()}}}function Am(t){return ds===0?Promise.resolve(!0):new Promise(e=>{let r=setTimeout(()=>e(!1),t);r.unref?.(),Kc.push(()=>{clearTimeout(r),e(!0)})})}import{existsSync as Uv,mkdirSync as zv,mkdtempSync as Hv,rmSync as Mo,writeFileSync as Km}from"node:fs";import{tmpdir as Gv}from"node:os";import{spawn as nv}from"node:child_process";var Rm=15e3;async function It(t,e,r="gdigrab"){if(r==="gdigrab"){await te(Si(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(!tr())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=nv("powershell",["-NoProfile","-NonInteractive","-Command",cd(n,100,process.pid)],{stdio:"ignore",windowsHide:!0});o.on("error",()=>{});try{await te(Yl(n,e),Rm)}catch(i){throw i instanceof l&&/timed out/.test(i.message)?new l(`Windows Graphics Capture got no frame from the window in ${Rm/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 Qc}from"node:path";import{readdirSync as wv}from"node:fs";import{runInNewContext as ov}from"node:vm";var iv=[2,4],sv=1e4;function av(t){return{script:hv,payload:JSON.stringify(t)}}async function Cm(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}=av(t),o=await at(r,"text (OCR)",{timeoutMs:nr(mv+Math.max(0,t.length-2)*fv),payload:n,failure:"Could not run OCR"}),i;try{i=JSON.parse(o)}catch(a){throw new l(`Could not parse OCR output: ${H(a)}`)}return(Array.isArray(i)?i:[i]).map((a,c)=>cv(a,e[c]??1))}function cv(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,...Pm(i)})}return n}function Pm(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 uv(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 Im(t){let e=[];for(let r of t)for(let n of r){let o=e.findIndex(s=>uv(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 Ft(t){return t.toLowerCase().replace(/[-_\s]+/g,"_").replace(/[l1|]/g,"i").replace(/0/g,"o")}var Wr=500,lv=1e3,pv=`JSON.stringify(texts.map((text) => {
|
|
274
|
+
const re = new RegExp(query, "gi");
|
|
275
|
+
const seen = new Set();
|
|
276
|
+
const ranges = [];
|
|
277
|
+
for (const variant of [text, text.replace(/-/g, "_"), text.replace(/_/g, "-")]) {
|
|
278
|
+
for (const m of variant.matchAll(re)) {
|
|
279
|
+
const key = m.index + ":" + m[0].length;
|
|
280
|
+
if (m[0].length > 0 && !seen.has(key)) {
|
|
281
|
+
seen.add(key);
|
|
282
|
+
ranges.push([m.index, m.index + m[0].length]);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return ranges;
|
|
287
|
+
}))`;function Sn(t,e,r=lv){try{new RegExp(e,"gi")}catch(n){throw new l(`Invalid regex: ${H(n)}`)}try{return JSON.parse(ov(pv,{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 xt(t,e,r=!1){if(e.length>Wr)throw new l(`The query is ${e.length} characters; at most ${Wr} 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?Sn(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=Ft(e);if(!p)return;let f=a.map(h=>Ft(h.word.text)).join("_"),m=0;for(let h=f.indexOf(p,m);h!==-1;h=f.indexOf(p,m))u.push(dv(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,...Pm(m)}))}}),i}function dv(t,e,r){let n=0,o=-1,i=-1;for(let s of t){let a=Ft(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 fs(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 Fm(t,e){let r=sv/Math.max(t,e),n=iv.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 mv=6e4,fv=5e3,Mm=2e4,hv=`
|
|
288
|
+
$ErrorActionPreference = 'Stop'
|
|
289
|
+
Add-Type -AssemblyName System.Runtime.WindowsRuntime
|
|
290
|
+
$null = [Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime]
|
|
291
|
+
$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
|
|
292
|
+
$null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime]
|
|
293
|
+
$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
|
|
294
|
+
function Await($op, [Type]$t) { $task = $asTask.MakeGenericMethod($t).Invoke($null, @($op)); if (-not $task.Wait(${Mm})) { throw "The OCR engine did not answer within ${Mm/1e3} s." }; $task.Result }
|
|
295
|
+
$paths = $Payload | ConvertFrom-Json
|
|
296
|
+
$engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
|
|
297
|
+
$out = foreach ($p in $paths) {
|
|
298
|
+
try {
|
|
299
|
+
if ($null -eq $engine) { throw 'No OCR recognizer language is installed.' }
|
|
300
|
+
$file = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($p)) ([Windows.Storage.StorageFile])
|
|
301
|
+
$stream = Await ($file.OpenAsync([Windows.Storage.FileAccessMode]::Read)) ([Windows.Storage.Streams.IRandomAccessStream])
|
|
302
|
+
$decoder = Await ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ([Windows.Graphics.Imaging.BitmapDecoder])
|
|
303
|
+
$bitmap = Await ($decoder.GetSoftwareBitmapAsync()) ([Windows.Graphics.Imaging.SoftwareBitmap])
|
|
304
|
+
$result = Await ($engine.RecognizeAsync($bitmap)) ([Windows.Media.Ocr.OcrResult])
|
|
305
|
+
$stream.Dispose()
|
|
306
|
+
[pscustomobject]@{ lines = @(foreach ($l in $result.Lines) {
|
|
307
|
+
[pscustomobject]@{ text = $l.Text; words = @(foreach ($w in $l.Words) {
|
|
308
|
+
[pscustomobject]@{ text = $w.Text; x = $w.BoundingRect.X; y = $w.BoundingRect.Y; width = $w.BoundingRect.Width; height = $w.BoundingRect.Height } }) } }) }
|
|
309
|
+
} catch { [pscustomobject]@{ error = $_.Exception.Message } }
|
|
310
|
+
}
|
|
311
|
+
ConvertTo-Json -InputObject @($out) -Depth 6 -Compress
|
|
312
|
+
`;import{availableParallelism as gv}from"node:os";function bv(t=gv()){return Math.min(4,Math.max(2,Math.floor(t/4)))}async function He(t,e,r=bv()){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 xv(t,e,r){if(e.length===0||e.length!==r.length)throw new l("Each OCR pass needs one output.");let n=a=>`scale=iw*${a}:ih*${a}:flags=lanczos`,o=["-compression_level","0"];if(e.length===1)return["-y","-v","error","-i",t,"-vf",n(e[0]),...o,r[0]];let i=e.map((a,c)=>`[s${c}]`),s=[`[0:v]split=${e.length}${i.join("")}`,...e.map((a,c)=>`${i[c]}${n(a)}[o${c}]`)].join(";");return["-y","-v","error","-i",t,"-filter_complex",s,...r.flatMap((a,c)=>["-map",`[o${c}]`,...o,a])]}async function lt(t,e,r,n={}){let o=async m=>{let{width:h,height:g}=await B(m);if(!h||!g)throw new l("Could not read the image size.");return{width:h,height:g}},i=n.sameSize&&t[0]?await o(t[0]):null,s=await He(t,async m=>({source:m,...i??await o(m)})),c=(await He(s,async({source:m,width:h,height:g},w)=>{let b=Fm(h,g),x=b.map(($,S)=>Qc(e,`pass${w}-${S}.png`));return await te(xv(m,b,x),6e4,{signal:r}),b.map(($,S)=>({out:x[S],scale:$,f:w}))})).flat(),u=c.map(m=>m.out),d=c.map(m=>m.scale),p=c.map(m=>m.f),f=await Cm(u,d);return s.map(({width:m,height:h},g)=>({lines:Im(f.filter((w,b)=>p[b]===g)),width:m,height:h}))}async function hs(t,e,r,n){let o=await B(t),i=o.videoDurationSec??o.durationSec,s=e.range?e.range.duration:i,a=Ei(s,1/e.everySec,e.maxFrames);await te(_i(t,a.fps,Qc(r,"scan_%05d.png"),e.maxFrames,!1,e.range),le(o.durationSec),{signal:n});let c=wv(r).filter(m=>m.startsWith("scan_")).sort().map(m=>Qc(r,m));if(c.length===0)throw new l("Could not read any frames from the video.");let u=1/a.fps,d=m=>Math.round(m*u*1e3)/1e3,p=s??d(c.length-1)+u;return{frames:(await lt(c,r,n,{sameSize:!0})).map((m,h)=>({...m,t:d(h),path:c[h]??""})),step:u,end:p,clamped:a.clamped}}function yv(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 vn(t,e,r,n="match"){let o=[],i=[];for(let s of t.frames){let a=xt(s.lines,e,r),c=yv(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 fs(u,s))i.push({...d,...c})}return{matches:o,redactRegions:i}}var $n=30,gs=120;var Zc=600,Om=24*3600,eu=1500,Ao=new Map;function bs(t){return t.startsWith("arm-")}function Sv(){return`arm-${he()}-${ge(6)}`}function ws(t){let e=Ao.get(t)?.arm;return e?{...e}:void 0}function Nm(){return[...Ao.values()].map(t=>({...t.arm}))}function tu(t){let e=Ao.get(t);return!e||e.arm.status!=="armed"?!1:(e.abort.abort(),e.arm.status="cancelled",!0)}function Dm(){for(let t of Ao.keys())tu(t)}function ru(t){return[...t.window?[`${t.window.replace(/^window:/,"the window ")} exists`]:[],...t.text?[`"${t.text}" is on screen`]:[]].join(" and ")}async function nu(t){let e=t.now??Date.now,r=t.sleep??(o=>new Promise(i=>setTimeout(i,o))),n=e();for(;;){if(t.signal.aborted)return"cancelled";let o=!0;for(let i of t.checks)if(!await i().catch(()=>!1)){o=!1;break}if(t.signal.aborted)return"cancelled";if(o)return"met";if(e()-n>=t.timeoutMs)return"timeout";await r(t.intervalMs)}}function Lm(t){let e={id:Sv(),status:"armed",conditions:t.conditions,target:t.target,armedAt:new Date().toISOString(),timeoutSec:t.timeoutSec},r=new AbortController;return Ao.set(e.id,{arm:e,abort:r}),(async()=>{let n=await nu({checks:t.checks,timeoutMs:t.timeoutSec*1e3,intervalMs:t.intervalMs??eu,signal:r.signal});if(n!=="met"){e.status==="armed"&&(e.status=n);return}e.firedAt=new Date().toISOString();try{e.sessionId=await t.fire(),e.status="started"}catch(o){e.status="failed",e.error=o instanceof Error?o.message:String(o)}})(),{...e}}import{open as vv,stat as Wm}from"node:fs/promises";import{basename as $v}from"node:path";var jm=5,ou=5e4,iu=2e3,kv=250,Ev=1<<20;function _v(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 Tv(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 Av=t=>t.length>iu?`${t.slice(0,iu-1)}\u2026`:t;function Bm(t,e){let r=[];for(let n of t){if(!n.line.trim())continue;let o=e.spans?.length?ho(n.epochMs,e.spans):(n.epochMs-e.startMs)/1e3;if(o===null||o<0||o>e.endSec)continue;let i=Tv(n.line);r.push({t:Math.round(o*1e3)/1e3,source:n.source,line:Av(n.line),...i?{level:i}:{}})}return r.slice(-ou)}function Um(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
313
|
+
`)+(t.length?`
|
|
314
|
+
`:"")}function ys(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function Ot(t){return t.replace(/\.[^./\\]+$/,"")+".logs.jsonl"}var xs=class{constructor(e,r=Date.now){this.now=r;this.files=e.map(n=>({path:n.path,label:n.label??$v(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 Wm(e.path);e.pos=r.size,e.ino=r.ino}catch{}}follow(e=kv){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 Wm(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,Ev),o;try{o=await vv(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}=_v(e.partial,i.subarray(0,s));e.partial=c.length>iu*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>ou*2&&(this.lines=this.lines.slice(-ou))}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 Rv}from"node:child_process";import{cpus as zm,freemem as Mv,totalmem as Cv}from"node:os";var Pv=1e3,Iv=90;function Fv(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 Ov(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 Nv(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 Hm(t,e){let r=[];for(let{epochMs:n,...o}of t){let i=e.spans?.length?ho(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 vs(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)>=Iv?(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 Gm(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
315
|
+
`)+(t.length?`
|
|
316
|
+
`:"")}function qm(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function kn(t){return t.replace(/\.[^./\\]+$/,"")+".perf.jsonl"}function Dv(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 Ss=class{constructor(e,r=Pv){this.pid=e;this.intervalMs=r}pid;intervalMs;samples=[];timer=null;child=null;proc={};start(){let e=zm(),r=e.length||1;if(this.pid!==void 0){this.child=Rv("powershell",["-NoProfile","-NonInteractive","-Command",Dv(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=Ov(a);c&&(n&&(this.proc={cpu:Nv(n,c,r),rssMB:Math.round(c.rss/1048576)}),n=c)}})}this.timer=setInterval(()=>{let n=zm(),o=Cv();this.samples.push({epochMs:Date.now(),sysCpu:Fv(e,n),sysMem:o>0?Math.round((o-Mv())/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 Lv}from"node:child_process";import{mkdirSync as Wv,rmSync as Xm}from"node:fs";function su(t,e){let r="",n="",o=null,i=new Ci(()=>({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+=`
|
|
317
|
+
${s.message}`}),{head:()=>r,tail:()=>n,outputAt:()=>o}}function Ro(t,e=6){return t.tail().trim().split(`
|
|
318
|
+
`).slice(-e).join(`
|
|
319
|
+
`)}function au(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",()=>{mn(e.head())!==null&&(clearTimeout(o),n("running"))}),t.on("error",()=>{clearTimeout(o),n("exited")}),t.on("exit",()=>{clearTimeout(o),n("exited")})})}function cu(t,e,r){let n=mn(t.head());return n!==null?n:e==="ddagrab"?t.outputAt()??r:r}function uu(t,e,r,n){r.on("exit",o=>{let i=t.getChild(e);if(i&&i!==r)return;t.detachChild(e,r),Ad(e)||Yi(e);let s=t.get(e);if(!s||s.status!=="recording"||t.isStopping(e))return;let a=Hd({code:o,backend:n.backend,maxDurationSec:n.maxDurationSec,elapsedMs:Date.now()-n.spawnedAt});er(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}:
|
|
320
|
+
${Ro(n.watch)}`}:{}}),s.segments&&(s.segments.parts.length>0||s.webcam)&&jv(t,s).catch(c=>{process.stderr.write(`Joining ${e}'s segments failed: ${H(c)}
|
|
321
|
+
`)})})}async function jv(t,e){let r=E();await rr(e.id);let{patch:n,error:o}=await Wc(e,r),i=await ue(e.outputPath,{ffprobe:r.ffprobe});t.tryUpdate(e.id,{...n,durationSec:i??void 0,...o?{error:o}:{}})}function Jm(t,e,r){return Qi(t,e.id,"resume",()=>Bv(t,t.get(e.id)??e,r))}async function Bv(t,e,r){let n=_d(e,t.ownsPaused(e.id));if(n)throw new l(`Cannot resume ${e.id}: ${n}.`);let o=e.segments,i=e.capture,s=e.backend??"gdigrab",a=rt(o.parts),c=kd(e.maxDurationSec,a),u=o.parts.length,d=$d(e.outputPath,u),p=i.webcam?Xi(e.outputPath,u):void 0;(u>0||p)&&Wv(ct(e.outputPath),{recursive:!0});let f=yi(i.target,{...i.opts,output:d,maxDurationSec:c,...i.webcam&&p?{webcam:{...i.webcam,output:p}}:{}}),m=Date.now(),h=Lv(r,f,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),g=su(h,e.id),w=()=>{let C=t.getChild(e.id);C&&C!==h||(u>0&&Xm(d,{force:!0}),p&&Xm(p,{force:!0}))};if(await au(h,g,s)==="exited")throw w(),new l(`Resume failed (ffmpeg exited immediately); the recording stays paused:
|
|
322
|
+
${Ro(g)}`);let b=cu(g,s,m),x=p?mn(g.head(),i.opts.audio?2:1):null;t.attachChild(e.id,h);let $=()=>{t.detachChild(e.id,h),h.pid!==void 0&&sr(h.pid),w()},S;try{S=t.update(e.id,{status:"recording",pid:h.pid??null,pidSpawnedAt:m,videoStartMs:b-a*1e3,segments:{parts:o.parts,current:{path:d,startMs:b,...p?{webcamPath:p,...x!==null?{webcamStartMs:x}:{}}:{}}}})}catch(C){throw $(),new l(`Resume stopped: the session registry could not be written (${H(C)}).`)}if(!S)throw $(),new l(`No session with id "${e.id}".`);return t.clearPaused(e.id),uu(t,e.id,h,{backend:s,maxDurationSec:c,spawnedAt:m,watch:g}),{record:S,recordedSec:a,capSec:c}}import{basename as Vm,join as lu}from"node:path";var qv={target:ae.string().describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | region:<x>,<y>,<w>,<h>. With gdigrab a window's rectangle is resolved once at start (visible, on top); it does not follow the window."),exactTitle:ae.boolean().optional().describe("window: targets match the whole title only, never a substring (default false)."),fps:ae.number().int().min(1).max(120).optional().describe(`Frames per second (default ${bi}).`),quality:ae.enum(["draft","standard","high"]).optional().describe(`Encoder preset (default ${wi}).`),audio:ae.object({source:ae.enum(["system","none"]).describe("system = what the machine plays (needs a loopback device); none = video only."),device:ae.string().optional().describe("dshow loopback device (from list_audio_devices); auto-detected if omitted.")}).optional().describe("Audio (default none). No microphone capture."),output:ae.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:ae.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),maxDurationSec:ae.number().int().min(0).max(At).optional().describe(`Auto-stop after this many seconds (default ${ac} or SCREENCAST_MAX_RECORDING_SEC; max 7 days; 0 = no cap).`),events:ae.boolean().optional().describe("Also log clicks, scroll, cursor, and typing (video-timed, video pixels) for read_events (default false; ~1 s slower start)."),keys:ae.enum(["masked","shortcuts"]).optional().describe("With events: masked (default) logs typing only as 0.5 s-grid bursts, never keys; shortcuts also names Ctrl/Alt/Win chords. Typed text is never logged."),focus:ae.enum(["app","title"]).optional().describe("Log app switches (implies events); title adds window titles."),logs:ae.array(ae.object({path:ae.string().min(1),label:ae.string().min(1).max(40).optional()})).min(1).max(jm).optional().describe("Log files to follow onto the video clock."),perf:ae.boolean().optional().describe("Sample CPU/memory (and a window's app) to <rec>.perf.jsonl."),hotkeys:ae.boolean().optional().describe("Ctrl+Alt+Shift+M adds a marker, +S stops (implies events)."),elements:ae.boolean().optional().describe('Name the UI element each click hits, e.g. "Save" button (implies events).'),cursor:ae.enum(["os","events"]).optional().describe("events: leave the OS cursor out and log it (implies events) for the cursor tool to redraw."),backend:ae.enum(["gdigrab","wgc","ddagrab"]).optional().describe("gdigrab (default): the screen rectangle. wgc (window: targets, FFmpeg 8+): the window's own surface, even when covered or moved; client area only, no audio. ddagrab: one display on the GPU, low CPU."),encoder:ae.enum(["auto","x264","nvenc","qsv","amf"]).optional().describe("auto = first working GPU encoder, else x264 (default with ddagrab; else x264)."),webcam:ae.object({device:ae.string().optional().describe("list_video_devices name (default: first)."),corner:ae.enum(["top_left","top_right","bottom_left","bottom_right"]).optional(),size:ae.number().min(.1).max(.5).optional().describe("Share of width (0.25)."),shape:ae.enum(["rect","circle"]).optional()}).optional().describe("Also record a camera to <output>.webcam.mp4, aligned for overlay."),replayBufferSec:ae.number().int().min(Wi).max(hn).optional().describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab or ddagrab, not wgc."),startWhen:ae.object({window:ae.string().min(1).optional().describe('A window: target that must exist, e.g. "window:Error".'),text:ae.string().min(1).max(200).optional().describe("Text that must be on target (OCR)."),timeoutSec:ae.number().positive().max(Om).optional().describe(`Default ${Zc}.`)}).optional().describe("Arm: start once these hold (stop_recording disarms)."),stopWhen:ae.object({text:ae.string().min(1).max(200)}).optional().describe("Stop once this text shows (OCR).")};async function Qm(t,e,r){let n=await ut(t,{exactTitle:e}),o=Hv(lu(Gv(),"screencast-trigger-"));try{let i=lu(o,"t.png");await It(n,i);let[s]=await lt([i],o);return!!s&&xt(s.lines,r).length>0}finally{Mo(o,{recursive:!0,force:!0})}}async function Xv(t){try{return await ut(t.startsWith("window:")?t:`window:${t}`),!0}catch{return!1}}var Zm=new WeakSet;function Jv(t,e){try{let r=vi(t,e);return{width:r.w,height:r.h}}catch{return}}function Yv(t,e){let r=mn(t.head(),e?2:1);return r!==null?{webcamStartMs:r}:{}}function ef(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:qv,outputSchema:L({sessionId:ae.string(),status:ae.string(),backend:ae.string(),outputPath:ae.string()}),annotations:O},async(r,n)=>{if(r.startWhen)try{let i=r.startWhen;if(!i.window&&!i.text)throw new l("startWhen needs window and/or text.");let s=i.timeoutSec??Zc,a={...i.window?{window:i.window}:{},...i.text?{text:i.text}:{}};await ut(r.target,{exactTitle:r.exactTitle,backend:r.backend}),await Pt(t,`When ${ru(a)} (within ${s} s), start recording ${Ct(r.target)}`+(r.events?", logging mouse clicks and typing":"")+"?",n.signal);let c={...r,startWhen:void 0};Zm.add(c);let u=Lm({conditions:a,target:r.target,timeoutSec:s,checks:[...i.window?[()=>Xv(i.window)]:[],...i.text?[()=>Qm(r.target,r.exactTitle,i.text)]:[]],fire:async()=>{let d=e.handler,p=await d(c,{...n,signal:new AbortController().signal}),f=p.structuredContent;if(p.isError||!f?.sessionId)throw new Error(p.content.map(m=>m.text??"").join(" ")||"start failed");return f.sessionId}});return v({sessionId:u.id,status:"armed",backend:r.backend??"gdigrab",outputPath:"",waitingFor:ru(a),timeoutSec:s,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(i){return _(i)}let o=()=>{};try{o=Tm();let{ffmpeg:i}=E(),s=r.cursor==="events";(s||r.focus||r.elements||r.hotkeys)&&(r.events=!0);let{target:a,monitors:c,window:u}=await ut(r.target,{exactTitle:r.exactTitle,backend:r.backend}),d=r.backend??"gdigrab";if(d==="wgc"){if(!u?.hwnd)throw new l('backend "wgc" records one window: use a window: target.');if(r.audio?.source==="system")throw new l('Audio is not supported with backend "wgc" yet; use gdigrab.');if(!tr())throw new l('backend "wgc" needs FFmpeg 8 or newer (the gfxcapture filter). Use gdigrab, or update ffmpeg.')}if(r.replayBufferSec!==void 0&&d==="wgc")throw new l('replayBufferSec is not supported with backend "wgc" yet; use gdigrab or ddagrab.');let p=r.replayBufferSec!==void 0?ed(r.replayBufferSec):null,f=r.fps??bi,m=r.quality??wi,h=Xl(r.maxDurationSec),g=Kt(r.output,be("recordings"),`rec-${he()}-${ge()}.mp4`,r.overwrite),w=r.audio?.source==="system"?{device:await $m(r.audio.device)}:void 0;if(r.webcam&&(d==="wgc"||p))throw new l("webcam works with backend gdigrab or ddagrab, without replayBufferSec.");let b=r.webcam?await Sm(r.webcam.device):void 0,x=d==="ddagrab"?wd(vi(a,c),await bd()):null;Zm.has(r)||await Pt(t,(p?`Keep a rolling ${p.bufferSec} s replay buffer of `:"Record ")+`${Ct(r.target,u)} `+(h>0?`for up to ${h} s`:"with no time limit")+(w?`, with system audio (${w.device})`:", without audio")+(b?`, with the webcam (${b})`:"")+(r.events?", logging mouse clicks and typing":"")+(r.focus?r.focus==="title"?" and which window is in front, with its title":" and which app is in front":"")+(r.elements?", naming the on-screen controls you click":"")+(r.hotkeys?`, with hotkeys (${go.marker} marks, ${go.stop} stops)`:"")+(p?", kept only until save_replay or stop_recording { save: true } writes it out?":`, saved to ${g}?`),n.signal);let $=await fd(r.encoder??(d==="ddagrab"?"auto":"x264"),d==="ddagrab"?"ddagrab":"gdigrab",i,void 0,d==="wgc"?void 0:Jv(a,c)),S=async M=>!x||M.gpuFrames||await gd(i);if(!await S($))throw new l("Desktop Duplication (ddagrab) does not capture on this machine (a remote session, or no D3D11 GPU).",'Use backend "gdigrab".');let C=b?Xi(g,0):void 0;C&&zv(ct(g),{recursive:!0});let I=M=>{let U=M.encoder!=="x264",q={fps:f,quality:m,monitors:c,audio:w,drawMouse:!s,...x?{videoInput:xd(x,f,{download:!M.gpuFrames,drawMouse:!s})}:{},...U?{videoCodec:ir(M.encoder,m,{gpuFrames:M.gpuFrames})}:{}},X=b?{device:b,...U?{codec:ir(M.encoder,m)}:{}}:void 0,xe=yi(a,{...q,output:g,maxDurationSec:h,...X&&C?{webcam:{...X,output:C}}:{}});return{captureOpts:q,webcam:X,ffArgs:p?rd(xe,p):xe}};p&&nd(p);let R=r.keys??Np,A=r.events?p?{raw:lu(p.dir,"events.raw"),jsonl:""}:ke(g):null;A&&!p&&Di(A,r.overwrite);let W=r.events?vi(a,c):null;if((r.logs||r.perf)&&p)throw new l("logs and perf are not supported with replayBufferSec yet.");let Y=r.logs?new xs(r.logs):null;await Y?.mark();let j=()=>{},re=A?await Wp(A.raw,R,{...p?{rotateSec:Qp(p.bufferSec)}:{},...r.focus?{focus:r.focus}:{},...r.elements?{elements:!0}:{},...r.hotkeys?{hotkeys:!0,onHotkey:M=>j(M)}:{}}):null,F=`rec-${he()}-${ge(6)}`,de=await hd($,async M=>{let U=I(M),q=Date.now(),X=d==="wgc"?Ym(process.execPath,[hm(),JSON.stringify({ffmpeg:i,hwnd:u.hwnd,fps:f,encode:[...ir(M.encoder,m),...gi(f)],output:g,maxDurationSec:h,cursor:!s})],{stdio:["pipe","ignore","pipe"],windowsHide:!0}):Ym(i,U.ffArgs,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),xe=su(X,F),st=await au(X,xe,d);return{...U,child:X,watch:xe,spawnedAt:q,settled:st}},{why:M=>Ro(M.watch,3),canFallback:()=>S({encoder:"x264",gpuFrames:!1}),beforeRetry:()=>{p&&od(p)}}),{run:Se,failure:y}=de;$=de.pick;let{child:Z,watch:K,spawnedAt:ce,captureOpts:J,webcam:V}=Se;if(Se.settled==="exited")throw re&&await bo(re),A&&Mo(A.raw,{force:!0}),p&&yo(p),C&&Mo(ct(g),{recursive:!0,force:!0}),new l(`Recording failed to start (${d==="wgc"?"window capture":"ffmpeg"} exited immediately):
|
|
323
|
+
${Ro(K)}`+(y?`
|
|
324
|
+
(Retried with libx264 after ${y})`:""));let ne=cu(K,d,ce);if(d==="wgc"&&W&&u?.client){let M=/wgc: (\d+)x(\d+)/.exec(K.head());W={x:u.client.x,y:u.client.y,w:M?Number(M[1]):W.w,h:M?Number(M[2]):W.h}}let T={id:F,target:r.target,outputPath:g,fps:f,quality:m,pid:Z.pid??null,pidSpawnedAt:ce,...jd(),status:"recording",startedAt:new Date().toISOString(),videoStartMs:ne,...h>0?{maxDurationSec:h}:{},...u?{matchedWindow:u.matchedTitle}:{},...A&&!p?{events:{path:A.jsonl,keys:R}}:{},...p?{replay:{...p,...A&&W?{events:{raw:A.raw,keys:R,startMs:ne,frame:W}}:{}}}:{},backend:d,...$.encoder!=="x264"?{encoder:$.encoder}:{},...d!=="wgc"&&!p?{capture:{target:a,opts:J,...V?{webcam:V}:{}},segments:{parts:[],current:{path:g,startMs:ne,...C?{webcamPath:C,...Yv(K,!!w)}:{}}}}:{},...b?{webcam:{device:b,path:Nr(g),corner:r.webcam?.corner??"bottom_right",size:r.webcam?.size??vd,shape:r.webcam?.shape??"rect"}}:{},processImage:d==="wgc"?Vm(process.execPath).toLowerCase():"ffmpeg.exe"},k=ie();k.attachChild(F,Z);try{k.create(T)}catch(M){throw k.detachChild(F),Z.pid!==void 0&&sr(Z.pid),re&&await bo(re),A&&Mo(A.raw,{force:!0}),p&&yo(p),C&&Mo(ct(g),{recursive:!0,force:!0}),new l(`Recording stopped: the session registry could not be written (${H(M)}).`)}if(re&&p){let M=new Promise(U=>Z.once("exit",()=>U()));wo(F,M.then(()=>bo(re)))}else re&&A&&W&&wo(F,$o(F).then(async()=>{await bo(re);try{let M=Ji(k.get(F)?.segments,ne,Date.now()),U=zp(A,{...M,frame:W});k.tryUpdate(F,{events:{path:A.jsonl,keys:R,count:U.length,summary:fn(U)}})}catch(M){k.tryUpdate(F,{events:{path:A.jsonl,keys:R,error:H(M)}})}}).catch(M=>{process.stderr.write(`Event log for ${F} failed: ${H(M)}
|
|
325
|
+
`)}));if(uu(k,F,Z,{backend:d,maxDurationSec:h,spawnedAt:ce,watch:K}),r.perf){let M=new Ss(u?.pid);M.start();let U=kn(g);k.tryUpdate(F,{perf:{path:U}}),wo(F,$o(F).then(async()=>{try{let q=Hm(M.stop(),Ji(k.get(F)?.segments,ne,Date.now()));Km(U,Gm(q));let X=u?.pid!==void 0?{pid:u.pid,...u.exe?{exe:u.exe}:{}}:void 0;k.tryUpdate(F,{perf:{path:U,summary:vs(q,X)}})}catch(q){M.stop(),k.tryUpdate(F,{perf:{path:U,error:H(q)}})}}))}if(Y&&r.logs){Y.follow();let M=Ot(g),U=r.logs.map(q=>q.label??Vm(q.path));k.tryUpdate(F,{logs:{path:M,sources:U}}),wo(F,$o(F).then(async()=>{try{let q=Bm(await Y.stop(),Ji(k.get(F)?.segments,ne,Date.now()));Km(M,Um(q)),k.tryUpdate(F,{logs:{path:M,sources:U,count:q.length,errors:q.filter(X=>X.level==="error").length}})}catch(q){k.tryUpdate(F,{logs:{path:M,sources:U,error:H(q)}})}}))}if(r.hotkeys){let{ffprobe:M}=E();j=U=>{let q=k.get(F);if(!(!q||q.status!=="recording"&&q.status!=="paused"))if(U==="marker")try{as(k,F,"hotkey")}catch(X){process.stderr.write(`Hotkey marker for ${F} failed: ${H(X)}
|
|
326
|
+
`)}else wn(k,q,{reason:"stopped",probe:X=>ue(X,{ffprobe:M})}).catch(X=>process.stderr.write(`Hotkey stop for ${F} failed: ${H(X)}
|
|
327
|
+
`))}}if(r.stopWhen){let M=new AbortController;$o(F).then(()=>M.abort());let{ffprobe:U}=E();nu({checks:[()=>Qm(r.target,r.exactTitle,r.stopWhen.text)],timeoutMs:Number.POSITIVE_INFINITY,intervalMs:eu,signal:M.signal}).then(q=>{let X=k.get(F);q!=="met"||!X||X.status!=="recording"&&X.status!=="paused"||wn(k,X,{reason:"stopped",probe:xe=>ue(xe,{ffprobe:U})}).catch(xe=>process.stderr.write(`stopWhen stop for ${F} failed: ${H(xe)}
|
|
328
|
+
`))})}let P=re&&r.hotkeys?Bp(re):[];return v({sessionId:F,status:"recording",backend:d,outputPath:g,pid:T.pid,fps:f,quality:m,audioDevice:w?.device??null,maxDurationSec:h>0?h:null,encoder:$.encoder,...$.note?{encoderNote:$.note}:{},...x?{gpuFrames:$.gpuFrames}:{},...b?{webcam:{device:b,path:Nr(g)}}:{},...u?lr(u):{},...A&&!p?{eventsPath:A.jsonl,keys:R}:{},...r.logs?{logsPath:Ot(g),...r.logs.some(M=>!Uv(M.path))?{logsNote:"A log file does not exist yet; it is read from its start once it appears."}:{}}:{},...r.hotkeys?{hotkeys:{...go,...P.length?{unavailable:P,warning:`Another app holds ${P.map(M=>go[M]).join(" and ")}.`}:{}}}:{},...p?{replay:{bufferSec:p.bufferSec,segmentSec:p.segmentSec,dir:p.dir,events:!!A}}:{},note:(p?`Replay buffer running: save_replay keeps the last seconds (up to ${p.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"+(d==="wgc"?".":" (pause_recording/resume_recording leave stretches out)."))+(h>0?` It stops on its own after ${h}s (maxDurationSec).`:"")})}catch(i){return _(i)}finally{o()}})}import{z as En}from"zod";import{existsSync as pu}from"node:fs";function tf(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 Kv(t,e){if(t.error||!pu(t.path))return{error:t.error??`No webcam file was written (${t.path}).`};let r=async a=>{try{let c=await B(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?Pd(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 Vv={sessionId:En.string().min(1).describe("Session id returned by start_recording."),save:En.boolean().optional().describe("Replay buffer: write it all to outputPath first (default: discard).")};function rf(t){t.registerTool("stop_recording",{title:"Stop Recording",description:"Stop a recording gracefully so the file is finalized; returns the path and duration.",inputSchema:Vv,outputSchema:L({sessionId:En.string(),status:En.string(),outputPath:En.string(),durationSec:En.number().nullable()}),annotations:fi},async e=>{try{let r=ie(),n=e.sessionId;if(bs(n)){let f=ws(n);if(!f)throw new l(`No armed recording with id "${n}".`);let m={sessionId:n,outputPath:"",durationSec:null};if(tu(n))return v({...m,status:"cancelled",note:"Disarmed; nothing was recorded."});if(!f.sessionId)return v({...m,status:f.status,...f.error?{error:f.error}:{}});n=f.sessionId}let o=r.get(n);if(!o)throw new l(`No session with id "${e.sessionId}".`);if(o.status!=="recording"&&o.status!=="paused"){let f=o.replay&&pu(o.replay.dir)?await Bi(o.replay,{save:e.save??!1,output:o.outputPath,quality:o.quality,tools:E}):void 0;return v({...f?{replay:tf(f)}:{},sessionId:o.id,status:o.status,outputPath:o.outputPath,durationSec:o.durationSec??null,endReason:o.endReason??null,note:o.endReason==="max_duration"?`Recording already ended at its maxDurationSec cap (${o.maxDurationSec}s).`:o.endReason==="window_closed"?"Recording already ended: the recorded window was closed.":"Session was not active; returning its recorded final state."})}let i=Wd(o,process.pid,Nc(o));if(i)throw new l(i);let{ffprobe:s}=E(),{record:a,graceful:c,durationSec:u,replay:d,segments:p}=await wn(r,o,{reason:"stopped",probe:f=>ue(f,{ffprobe:s}),saveReplay:e.save});return v({sessionId:o.id,status:"stopped",outputPath:o.outputPath,durationSec:u??null,finalizedGracefully:c,...d?{replay:tf(d)}:{},...p&&p.count>1?{segmentsJoined:p.count}:{},...p?.error?{segmentsError:p.error}:{},...a?.webcam?{webcam:await Kv(a.webcam,o.outputPath)}:{},...a?.events?{eventsPath:a.events.path,events:a.events.summary??{},...a.events.error?{eventsError:a.events.error}:{}}:{},fileExists:pu(o.outputPath),note:c?"ffmpeg quit cleanly; file finalized.":"Process terminated by pid; fragmented mp4 keeps the file playable.",record:a})}catch(r){return _(r)}})}import{z as mr}from"zod";import{existsSync as Ru,readdirSync as jf,rmSync as H0,statSync as G0}from"node:fs";import{dirname as q0,resolve as Bf}from"node:path";import{createHash as yf}from"node:crypto";import{closeSync as T0,existsSync as _n,openSync as A0,readFileSync as R0,readdirSync as M0,readSync as C0,renameSync as P0,statSync as I0,writeFileSync as F0}from"node:fs";import{basename as Sf,dirname as O0,join as Tn,resolve as Ps}from"node:path";import{closeSync as o0,existsSync as fu,openSync as i0,readSync as s0,statSync as a0}from"node:fs";import{basename as ks,isAbsolute as c0,join as hu}from"node:path";function yt(t,e,r){if(t.length<e)throw new Error(`Truncated font: ${r}.`);return t}function Qv(t,e){let r=yt(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 yt(t(12+e*4,4),4,"collection offsets").readUInt32BE(0)}var $s=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 Zv(t){let e=yt(t,14,"cmap format 4").readUInt16BE(6),r=14,n=r+e+2,o=n+e,i=o+e;yt(t,i+e,"cmap format 4 segments");let s=new $s;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 e0(t,e){let r=yt(t,16,`cmap format ${e}`).readUInt32BE(12);yt(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 $s;for(let[i,s]of n)o.add(i,s);return o.ranges}function t0(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 nf(t,e=0){let r=Qv(t,e),n=yt(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=yt(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=yt(t(a,4),4,"cmap header").readUInt16BE(2),d=yt(t(a+4,u*8),u*8,"cmap records"),p=[];for(let f=0;f<u;f++){let m=t0(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 Zv(t(f,m.readUInt16BE(2)));if(h===12||h===13)return e0(t(f,m.readUInt32BE(4)),h)}throw new Error("Font has no Unicode cmap subtable this reader understands (formats 4, 12, 13).")}function r0(t,e){let r=0,n=t.length-1;for(;r<=n;){let o=r+n>>1,[i,s]=t[o];if(e<i)n=o-1;else if(e>s)r=o+1;else return!0}return!1}function n0(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 Co(t,e){let r=new Set,n=[];for(let o of t){let i=o.codePointAt(0);r.has(i)||(r.add(i),n0(i)&&!r0(e,i)&&n.push(o))}return n}var u0={regular:"Inter-Regular.ttf",bold:"Inter-Bold.ttf"};function Nt(t="bold"){return yn("fonts",u0[t])}function ve(t){return t.replace(/\\/g,"/").replace(/:/g,"\\\\:").replace(/'/g,"\\\\\\'").replace(/([,;[\]])/g,"\\$1")}var l0={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"]}},p0=["segoe","japanese","chineseSimplified","chineseTraditional","korean","indic","thai","ethiopic","emoji","symbol"];function d0(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,...p0.filter(r=>!e.includes(r))].map(r=>l0[r])}function m0(t,e){let r=null;for(let n of e){let o=Co(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 sf(){return hu(process.env.WINDIR??process.env.SystemRoot??"C:\\Windows","Fonts")}var of=new Map;function du(t){let e=of.get(t);if(e!==void 0)return e;let r,n=null;try{n=i0(t,"r");let o=n;r=nf((s,a)=>{let c=Buffer.alloc(a);return c.subarray(0,s0(o,c,0,a,s))})}catch{r=null}finally{n!==null&&o0(n)}return of.set(t,r),r}function f0(t){if(fu(t)&&a0(t).isFile())return t;if(!c0(t)&&ks(t)===t){let e=hu(sf(),t);if(fu(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 mu(t){let e=t.replace(/\s+/g," ").trim();return`"${e.length>40?`${e.slice(0,39)}\u2026`:e}"`}function pr(t,e={}){if(e.fontFile){let c=f0(e.fontFile),u=du(c);if(!u)return{fontFile:c,missing:[],fallback:!1,warning:`Could not read the character map of ${ks(c)}; glyph coverage of ${mu(t)} was not checked.`};let d=Co(t,u);return d.length===0?{fontFile:c,missing:d,fallback:!1}:{fontFile:c,missing:d,fallback:!1,warning:`${ks(c)} has no glyph for ${d.join(" ")} in ${mu(t)}; they render as empty boxes.`}}let r=e.weight??"bold",n=Nt(r),o=du(n);if(o&&Co(t,o).length===0)return{fontFile:n,missing:[],fallback:!1};let i=e.fontsDir??sf(),s=o?[{path:n,coverage:o}]:[];for(let c of d0(t))for(let u of c[r]){let d=hu(i,u),p=fu(d)?du(d):null;if(p){if(Co(t,p).length===0)return{fontFile:d,missing:[],fallback:!0};s.push({path:d,coverage:p});break}}let a=m0(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 ${mu(t)}; they render as empty boxes (drawn with ${ks(a.fontFile)}). Pass fontFile with a font that covers them.`}}import{mkdtempSync as h0,rmSync as g0,writeFileSync as b0}from"node:fs";import{join as gu}from"node:path";import{tmpdir as w0}from"node:os";var Po=12,af=48,Io=320;function Es(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 Oe(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 x0(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 y0(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=${ve(o)}:textfile=${ve(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 S0(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 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",..._e(r)]}async function _s(t,e,r,n,o){let i=x0(e.length,n.columns),s=h0(gu(w0(),"screencast-sheet-"));try{let a=Nt("bold");await He(e,async(c,u)=>{let d=gu(s,`label_${u}.txt`);b0(d,Oe(c));let p=gu(s,`tile_${String(u).padStart(3,"0")}.png`);await te(y0(t,c,p,n.tileWidth,a,d),6e4,{signal:o})}),await te(S0(rn(s,"tile_%03d.png"),i,r),6e4,{signal:o})}finally{g0(s,{recursive:!0,force:!0})}return i}import{existsSync as Ts}from"node:fs";var uf=t=>Math.round(t*1e3)/1e3,v0={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 bu(t){return t.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function wu(t){let e=bu(t.role),r=t.app?` in ${t.app}`:"";return t.name?`the "${t.name}" ${e}${r}`:`${/^[aeiou]/.test(e)?"an":"a"} ${e}${r}`}function lf(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} ${wu(r.element)}`:r.inFrame?`${o} at (${r.x}, ${r.y})`:`${o} outside the recorded area`}function xu(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=lf(s.button,!0,a.e),n=null;continue}let c={t:s.t,action:"click",text:lf(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 ${uf(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=v0[s.reason??"input_not_seen"],c=uf(s.durationSec??0);e.push({t:s.t,action:"gap",text:`Input may be missing for ${c} s (${a})`,durationSec:c})}}return e}function yu(t){return xu(t).map(({button:e,inFrame:r,keys:n,durationSec:o,element:i,...s})=>s)}var Su=30,As=600,vu=1,Rs=100,$u=20,Ge=["\\b(?:sk|pk|rk)-[a-z0-9_-]{8,}","\\bgh[pousr]_[a-z0-9]{10,}","\\bgithub_pat_[a-z0-9_]{10,}","\\bxox[abprs]-[a-z0-9-]{8,}","\\bAKIA[0-9A-Z]{12,}","\\bAIza[0-9a-z_-]{20,}","\\beyJ[a-z0-9_-]{8,}\\.[a-z0-9_-]{8,}","(?:api.?key|secret|token|passw(?:or)?d|bearer|authorization)\\s*[:=]?\\s*\\S+"].join("|"),Ms="error|exception|fail(?:ed|ure)?|fatal|crash|denied|refused|not found|cannot|can't|unable|invalid|timed? ?out|traceback|panic|unhandled|warning",Dt={markdown:"report.md",json:"report.json",clip:"clip.mp4",contactSheet:"contact-sheet.png",gif:t=>`repro.${t}`},Fo=t=>Math.round(t*1e3)/1e3;function df(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??Su,o=e.start??Math.max(0,r-n);if(o>=t)throw new l(`start ${o}s is past the end of the ${Fo(t)}s recording.`);if(!(r>o))throw new l("end must be after start.");if(r-o>As)throw new l(`The clip would be ${Fo(r-o)}s; at most ${As}s. Narrow start/end.`);return{start:Fo(o),end:Fo(r)}}function $0(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 mf(t){let e=[];for(let r of[...t].sort((n,o)=>n.start-o.start)){let n=e.find(s=>r.start<=s.end&&$0(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 k0="[REDACTED]";function Ne(t,e){if(t.length===0)return[];let r=Sn(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?k0:""),a=u);return s+n.slice(a)})}function ff(t,e,r){let n=new Map;for(let a of t){let c=new Set(xt(a.lines,e,!0).map(u=>u.line));for(let u of c){let d=Ft(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,$u);if(!r)return i;let s=Ne(i.map(a=>a.text),r);return i.map((a,c)=>({...a,text:s[c]??a.text}))}var E0=t=>`\`${t.replace(/`/g,"'").replace(/\s+/g," ").trim()}\``,pf=t=>t.replace(/\|/g,"\\|").replace(/\s*\n\s*/g," ");function hf(t){let e=[`# ${t.title.replace(/\s*\n\s*/g," ")}`,""],r=`${Oe(t.clip.start)}-${Oe(t.clip.end)}`;if(e.push(`Recorded repro: ${t.clip.width}x${t.clip.height}, clip ${r} of a ${Oe(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}. \`${Oe(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?Oe(i.firstSeen):`${Oe(i.firstSeen)}-${Oe(i.lastSeen)}`;e.push(`- \`${s}\` ${E0(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?"-":""}${Oe(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}) (${Fo(t.clip.end-t.clip.start)} s)`),t.files.gif&&t.gif){let i=(t.gif.sizeBytes/1e6).toFixed(1);e.push(`- ${t.gif.format==="gif"?"GIF":"WebP"}: [${t.files.gif}](${t.files.gif}) (${i} MB${t.gif.withinBudget?"":", over the size budget"})`)}t.files.contactSheet&&e.push(`- Contact sheet: [${t.files.contactSheet}](${t.files.contactSheet})`),e.push(""),e.push("## Environment","","| | |","|---|---|");for(let[i,s]of t.environment)e.push(`| ${pf(i)} | ${pf(s)} |`);e.push("");let n=t.redaction,o=n.found+n.manual;return e.push("<sub>",n.scanned?`Secret scan: OCR every ${n.everySec} s over ${n.framesScanned} frames; ${o} region${o===1?"":"s"} boxed out of the media. OCR is best-effort: review the clip before posting.`:`Not scanned for secrets${n.manual>0?` (${n.manual} region${n.manual===1?"":"s"} boxed out by hand)`:""}: review the clip before posting.`,`Generated by screencast-mcp bug_report, ${t.createdAt}.`,"</sub>",""),e.join(`
|
|
329
|
+
`)}async function Cs(t){if(t.sessionId!==void 0){let n=ie().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 rr(n.id),!Ts(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path;return{path:n.outputPath,eventsPath:o&&Ts(o)?o:null,record:n}}let e=t.input;if(!Ts(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=ke(e);return{path:e,eventsPath:Ts(r)?r:null}}var _0=40;function gf(t,e,r){let n=t.filter(i=>i.t>=e.start-5&&i.t<=e.end).slice(-_0),o=r?Ne(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 bf(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=vs(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 ${Oe(s.start)} to ${Oe(s.end)}`)]}var ku=1,Eu=.03,_u=120,vf=600,N0=10,Is=10,$f=50,wf=200,D0=5,dr=t=>Math.round(t*1e3)/1e3;function Oo(t){return`${t}.index.json`}function Tu(t){return`${t.replace(/\.[^./\\]+$/,"")}.index.json`}function No(t,e){let r=n=>process.platform==="win32"?Ps(n).toLowerCase():Ps(n);return r(t)===r(e)}function Fs(t,e,r){return typeof t.video=="string"&&No(t.video,e)?!0:r!==void 0&&!!t.fingerprint&&js(t.fingerprint,r)}function Os(t,e){let r=yf("sha1").update(Ps(t).toLowerCase()).digest("hex").slice(0,12),n=Sf(t).replace(/\.[^.]+$/,"");return Tn(e,"indexes",`${n}-${r}.index.json`)}function kf(t,e){let r=Oo(t);try{return Yt(r),r}catch{return Os(t,e)}}function Ns(t,e,r){for(let o of[Oo(t),Os(t,e)])if(_n(o))return o;let n=Tu(t);if(n!==Oo(t)&&_n(n)){let o=jr(n);if(o&&Fs(o,t,r))return n}return null}function Ef(t,e){return t!==null&&js(t.fingerprint,e.fingerprint)&&t.sceneThreshold===e.sceneThreshold&&t.maxFrames===e.maxFrames&&(t.ocr||!e.ocrAvailable)}function _f(t,e=Ge){return t.map(r=>r.ocr.length>0?{...r,ocr:Ne(r.ocr,e)}:r)}var L0=/\.(mp4|mkv|mov|webm|avi|m4v|wmv|flv|gif|ts|mpg|mpeg)$/i,xf=t=>t.replace(/\.[^.]+$/,"").toLowerCase();function Ds(t,e){let r=new Set(e.map(s=>s.toLowerCase())),n=Sf(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()&&L0.test(s)&&xf(s)===xf(n))?{path:null,ambiguous:!0}:{path:Tn(O0(t),o),ambiguous:!1}:{path:null,ambiguous:!1}}function Tf(t,e,r,n=N0){let o=cn(t.filter(i=>i.timeSec<e),r).map(dr);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,dr(o[i]+s/2))}return[...new Set(o)].sort((i,s)=>i-s)}function Af(t,e){return t.map((r,n)=>({start:r,end:dr(t[n+1]??e)}))}function Ls(t){return dr(t.start+Math.min(.25,(t.end-t.start)/2))}function Rf(t){let e=[];for(let r of t){let n=e.at(-1);n&&n.ocr.join(`
|
|
330
|
+
`)===r.ocr.join(`
|
|
331
|
+
`)&&!r.events&&!r.markers&&!r.transcript?n.end=r.end:e.push({...r,ocr:[...r.ocr]})}return e}function Mf(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?` ${bu(i.role)}${i.name?` ${i.name}`:""}${i.app?` ${i.app}`:""}`:"")}else r.type==="key"?o=`shortcut ${r.keys??"key"}`:r.type==="typing"?o=`typing ${dr(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:dr(r.t),text:o})}return e}function Cf(t){return t.map(e=>({t:dr(e.t),text:e.label}))}function Pf(t){return t.map(e=>({t:dr(e.start),text:e.text.replace(/\s+/g," ").trim()})).filter(e=>e.text)}function An(t,e,r){let n=t.map(o=>{let{[r]:i,...s}=o;return s});if(n.length===0)return n;for(let o of[...e].sort((i,s)=>i.t-s.t)){let i=n.findIndex(a=>o.t>=a.start&&o.t<a.end);i===-1&&(i=o.t<n[0].start?0:n.length-1);let s=n[i];(s[r]??=[]).push(o)}return n}function Ws(t){let e=I0(t),r=yf("sha1"),n=64*1024,o=A0(t,"r");try{let i=Buffer.alloc(n);for(let s of e.size>n?[0,e.size-n]:[0]){let a=C0(o,i,0,n,s);r.update(i.subarray(0,a))}}finally{T0(o)}return{size:e.size,mtimeMs:Math.round(e.mtimeMs),sample:r.digest("hex")}}function js(t,e){return t.size===e.size&&t.mtimeMs===e.mtimeMs&&t.sample===e.sample}function W0(t){try{let e=JSON.parse(t);return e?.version!==ku||!Array.isArray(e.segments)||!e.fingerprint?null:e}catch{return null}}function jr(t){try{return W0(R0(t,"utf8"))}catch{return null}}function If(t,e){let r=`${t}.${process.pid}.tmp`;F0(r,JSON.stringify(e)),P0(r,t)}function j0(t){let e=t.replace(/\s+/g," ").trim();return e.length>wf?`${e.slice(0,wf-1)}\u2026`:e}function B0(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 Ff(t,e){if(t.trim().length===0)throw new l("query must not be empty.");if(t.length>Wr)throw new l(`The query is ${t.length} characters; at most ${Wr} are allowed.`);if(!e&&!/[\p{L}\p{N}]/u.test(Ft(t)))throw new l("query needs at least one letter or digit.","For punctuation, use regex: true.");e&&Sn([""],t)}function Au(t,e,r={}){if(Ff(e,r.regex===!0),r.video!==void 0&&!Fs(t,r.video,r.fingerprint))throw new l(`The index found is for ${t.video}, not ${r.video}.`,"Run index_recording on this recording.");let n=r.secretPattern===void 0?Ge:r.secretPattern,o=B0(t),i=n?Ne(o.map(f=>f.text),n):o.map(f=>f.text),s=o.map((f,m)=>({...f,text:i[m]??""})),a=new Map,c=(f,m)=>{let h=a.get(f.seg)??{score:0,matches:[]};h.score+=m,h.matches.push(f),a.set(f.seg,h)};if(r.regex){let f=Sn(s.map(m=>m.text),e);s.forEach((m,h)=>{(f[h]??[]).length>0&&c(m,2)})}else{let f=Ft(e.trim()),m=f.split("_").filter(Boolean),h=s.map(g=>Ft(g.text));if(s.forEach((g,w)=>{h[w].includes(f)&&c(g,2)}),m.length>1){let g=new Map;s.forEach((w,b)=>g.set(w.seg,[...g.get(w.seg)??[],b]));for(let[w,b]of g)if(!a.has(w)&&m.every(x=>b.some($=>h[$].includes(x)))){for(let x of b)m.some($=>h[x].includes($))&&c(s[x],0);a.get(w).score=1}}}return{hits:[...a.entries()].map(([f,m])=>({seg:f,...m})).sort((f,m)=>m.score-f.score||t.segments[f.seg].start-t.segments[m.seg].start).slice(0,r.limit??Is).map(f=>{let m=t.segments[f.seg],h=f.matches.slice(0,D0).map(g=>({source:g.source,t:g.t,text:j0(g.text)}));return{start:m.start,end:m.end,t:Math.min(...f.matches.map(g=>g.t)),score:f.score,matches:h}}),total:a.size}}var U0=20;function z0(t){return[Tn(t,"recordings"),Tn(t,"edits"),Tn(t,"edits","indexes")]}function Of(t){let e=[];for(let r of z0(t)){let n;try{n=M0(r)}catch{continue}for(let o of n)o.endsWith(".index.json")&&e.push(Tn(r,o))}return e}function Nf(t,e,r={}){Ff(e,r.regex===!0);let n=new Map;for(let c of t){let u=Ps(c.index.video).toLowerCase(),d=n.get(u);(!d||c.index.createdAt>d.index.createdAt)&&n.set(u,c)}let o=r.limit??Is,i=[],s=[],a=0;for(let c of n.values()){let u=Au(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,U0),searched:n.size}}async function Bs(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=ie().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 rr(n.id),!_n(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path,i=n.markers?.length?n.markers:Le(n.outputPath);return{path:n.outputPath,eventsPath:o&&_n(o)?o:null,markers:i}}let e=t.input;if(!_n(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=ke(e);return{path:e,eventsPath:_n(r)?r:null,markers:Le(e)}}import{basename as Df}from"node:path";function Lf(t,e,r){let n=ke(t),o=Ds(t,e),i=[n.jsonl,n.raw,`${n.raw}.stop`,Nr(t),Oo(t),Os(t,r),ar(t),Ot(t),kn(t),Ui(t),...o.path&&!o.ambiguous?[o.path]:[]];return{files:[...new Set(i)].filter(s=>Df(s)!==Df(t)),dirs:[ct(t)]}}function Wf(t){if(Jt(t,"Recording"),![Fe(),...Rr()??[]].some(r=>Tr(t,r)))throw new l(`Recording ${t} is outside SCREENCAST_HOME and the allowed directories, so it is not deleted. Add its folder to SCREENCAST_ALLOWED_DIRS or the client's workspace roots, or delete it yourself.`)}var X0={sessionId:mr.string().min(1).optional().describe("Session id of the recording to delete."),input:mr.string().min(1).optional().describe("Or the recording's path.")};function Uf(t){try{let e=G0(t);return e.isDirectory()?jf(t).reduce((r,n)=>r+Uf(Bf(t,n)),0):e.size}catch{return 0}}async function J0(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form){if(Em())throw new l(`Not deleted: ${To} 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:Yc}))}catch(o){throw new l(`Not deleted: the confirmation request failed (${H(o)}).`)}if(n!=="accept")throw new l(`Not deleted: ${n==="decline"?"declined":"cancelled"} by the user.`);return!0}function zf(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:X0,outputSchema:L({outputPath:mr.string(),deleted:mr.array(mr.string()),bytesFreed:mr.number(),sessionsRemoved:mr.array(mr.string())}),annotations:Dl},async(e,r)=>{try{if(!!e.sessionId==!!e.input)throw new l("Give exactly one of sessionId or input.");let n=ie(),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=Bf(e.input);Wf(o);let i=n.list().filter(g=>No(g.outputPath,o)),s=i.find(g=>bn(g.status));if(s)throw new l(`Recording ${s.id} is still ${s.status}; stop it first.`);let a=[];try{a=jf(q0(o))}catch{}let c=Lf(o,a,be("edits")),u=[o,...c.files,...c.dirs].filter(g=>Ru(g));if(u.length===0&&i.length===0)throw new l(`Nothing to delete: ${o} does not exist.`);let d=await J0(t,`Delete ${o} and ${u.length-(Ru(o)?1:0)} sidecar file(s)? This cannot be undone.`,r.signal),p=0,f=[],m=[];for(let g of u){let w=Uf(g);try{H0(g,{recursive:!0,force:!0}),f.push(g),p+=w}catch(b){m.push(`${g}: ${H(b)}`)}}let h=Ru(o)?[]:i.map(g=>g.id);return h.length>0&&n.remove(h),v({outputPath:o,deleted:f,bytesFreed:p,sessionsRemoved:h,confirmedByUser:d,...m.length>0?{failed:m,note:"Some files could not be deleted (in use?); the registry entry was kept if the recording remains."}:{}})}catch(n){return _(n)}})}import{z as fr}from"zod";import{existsSync as Y0}from"node:fs";function D(t,e="Input file"){if(!Y0(t))throw new l(`${e} not found: ${t}`)}function z(t,e,r,n={}){return n.anyContainer||Fr(t),Kt(t,be(n.dir??"edits"),`${e}-${he()}-${ge()}${r}`,n.overwrite)}var K0={sessionId:fr.string().min(1).describe("Session id of a replay buffer."),lastSec:fr.number().positive().max(hn).optional().describe("Seconds back from now (default and max: the buffer length)."),output:fr.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:fr.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),reencode:fr.boolean().optional().describe("Frame-exact re-encode. Default: instant stream copy that may hide up to 2 s of earlier frames.")};function Hf(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:K0,outputSchema:L({sessionId:fr.string(),outputPath:fr.string(),durationSec:fr.number()}),annotations:O},async(e,r)=>{try{let n=ie().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}=E(),s=n.replay,a=Math.min(e.lastSec??s.bufferSec,s.bufferSec),c=z(e.output,"replay",".mp4",{overwrite:e.overwrite,dir:"recordings",anyContainer:!0});s.events&&Di(ke(c),e.overwrite);let u=Date.now(),d=await Tc(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;er("info",`Saved ${d.durationSec}s of replay ${n.id} to ${c}.`,{sessionId:n.id,outputPath:c,durationSec:d.durationSec});let f=d.durationSec+.25<a;return v({sessionId:n.id,...d,requestedSec:e.lastSec??null,bufferSec:s.bufferSec,bufferRunning:n.status==="recording",bufferDiskBytes:id(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 _(n)}})}import{z as Us}from"zod";var Gf=t=>Math.round(t*1e3)/1e3;function qf(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:Us.string().min(1).describe("From start_recording.")},outputSchema:L({sessionId:Us.string(),status:Us.string(),recordedSec:Us.number()}),annotations:fi},async e=>{try{let r=ie(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(n.status==="paused")return v({sessionId:n.id,status:"paused",recordedSec:Gf(rt(n.segments?.parts??[])),note:"Already paused."});let{ffprobe:o}=E(),i=await Qd(r,n,{probe:s=>ue(s,{ffprobe:o})});return v({sessionId:n.id,status:"paused",recordedSec:Gf(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 _(r)}})}import{z as zs}from"zod";var Xf=t=>Math.round(t*1e3)/1e3;function Jf(t){t.registerTool("resume_recording",{title:"Resume Recording",description:"Resume a paused recording (same target and settings).",inputSchema:{sessionId:zs.string().min(1).describe("From start_recording.")},outputSchema:L({sessionId:zs.string(),status:zs.string(),recordedSec:zs.number()}),annotations:O},async e=>{try{let r=ie(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(n.status==="recording")return v({sessionId:n.id,status:"recording",recordedSec:Xf(rt(n.segments?.parts??[])),note:"Already recording."});let{ffmpeg:o}=E(),i=await Jm(r,n,o);return er("notice",`Recording ${n.id} resumed.`,{sessionId:n.id}),v({sessionId:n.id,status:"recording",recordedSec:Xf(i.recordedSec),pid:i.record.pid,...i.capSec>0?{remainingSec:i.capSec}:{}})}catch(r){return _(r)}})}import{z as Yf}from"zod";function Kf(t){t.registerTool("list_video_devices",{title:"List Video Devices",description:"List DirectShow cameras for start_recording's webcam.device.",inputSchema:{},outputSchema:L({devices:Yf.array(Yf.string())}),annotations:fe},async()=>{try{E();let e=await Jc(!0);return v({devices:e,note:e.length?`start_recording { webcam: { device: "${e[0]}" } } records it.`:"No camera found."})}catch(e){return _(e)}})}import{z as Rn}from"zod";function Vf(t){t.registerTool("list_sessions",{title:"List Sessions",description:"List all recording sessions (active and finished) with their status, target, output path, and whether the process is still alive.",inputSchema:{},outputSchema:L({count:Rn.number().int(),sessions:Rn.array(L({id:Rn.string(),status:Rn.string(),outputPath:Rn.string(),alive:Rn.boolean()}))}),annotations:fe},async()=>{try{let e=ie().list().map(n=>({...n,alive:n.status==="recording"&&ze(n.pid)})),r=Nm();return v({count:e.length,sessions:e,...r.length?{armed:r}:{}})}catch(e){return _(e)}})}import{z as Mn}from"zod";import{existsSync as V0}from"node:fs";var Q0={sessionId:Mn.string().min(1).describe("Session id returned by start_recording.")};function Qf(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:Q0,outputSchema:L({id:Mn.string(),status:Mn.string(),outputPath:Mn.string(),alive:Mn.boolean(),fileExists:Mn.boolean()}),annotations:fe},async e=>{try{if(bs(e.sessionId)){let n=ws(e.sessionId);if(!n)throw new l(`No armed recording with id "${e.sessionId}".`);return v({...n,outputPath:"",alive:!1,fileExists:!1,...n.sessionId?{note:`It started recording ${n.sessionId}; get_session that id for it.`}:{}})}let r=ie().get(e.sessionId);if(!r)throw new l(`No session with id "${e.sessionId}".`);return v({...r,alive:r.status==="recording"&&ze(r.pid),fileExists:V0(r.outputPath)})}catch(r){return _(r)}})}import{z as We}from"zod";import{existsSync as Z0,readFileSync as e$}from"node:fs";var Zf=200,t$=5e3,r$={sessionId:We.string().min(1).optional().describe("Session id of a recording started with events: true."),input:We.string().optional().describe("Or a recording path, or its .events.jsonl."),from:We.number().min(0).optional().describe("Earliest video second."),to:We.number().min(0).optional().describe("Latest video second."),types:We.array(We.enum(vc)).optional().describe("down/up (mouse buttons; clicks are down), move (sampled cursor), wheel, key (shortcut), typing (burst), gap (events may be missing)."),inFrameOnly:We.boolean().optional().describe("Drop events whose cursor was outside the recorded area."),limit:We.number().int().min(1).max(t$).optional().describe(`Most events to return (default ${Zf}).`)};function eh(t){t.registerTool("read_events",{title:"Read Input Events",description:"Read the input events (clicks, scroll, cursor, shortcuts, typing bursts) of a recording made with events: true, in video seconds and pixels; e.g. types: ['down'], then sample_frames there.",inputSchema:r$,outputSchema:L({eventsPath:We.string(),total:We.number().int(),matched:We.number().int(),returned:We.number().int(),summary:We.record(We.string(),We.number())}),annotations:fe},async e=>{try{let r;if(e.sessionId){let a=ie().get(e.sessionId);if(!a)throw new l(`No session with id "${e.sessionId}".`);if(!a.events)throw new l(`Session "${e.sessionId}" was recorded without an event log. Start the recording with events: true.`);if(a.status==="recording"||a.status==="paused")throw new l("The recording is still running; its event log is written when it stops.");r=a.events.path}else if(e.input)r=e.input.endsWith(".jsonl")?e.input:ke(e.input).jsonl;else throw new l("Pass sessionId or input.");if(!Z0(r))throw new l(`No event log at ${r}. Record with start_recording events: true.`);let n=Ue(e$(r,"utf8")),o=Ni(n,e),i=e.limit??Zf,s=Dp(n);return v({eventsPath:r,total:n.length,matched:o.length,returned:Math.min(i,o.length),summary:fn(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 _(r)}})}import{z as Cn}from"zod";var n$={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},o$={label:Cn.string().min(1).max(jc).describe('e.g. "bug appears".'),sessionId:Cn.string().min(1).optional().describe("Recording to mark (a stopped one needs at)."),input:Cn.string().min(1).optional().describe("Or a video path (needs at)."),at:Cn.number().min(0).optional().describe("Video second (default: now, while recording).")};function th(t){t.registerTool("add_marker",{title:"Add Marker",description:"Mark a labelled moment on a recording, live or at a second. Kept in the session and a sidecar; chapters and pipeline turn markers into chapters.",inputSchema:o$,outputSchema:L({count:Cn.number().int(),markersPath:Cn.string()}),annotations:n$},async e=>{try{if(!e.sessionId&&!e.input)throw new l("Pass sessionId or input.");if(e.sessionId){let i=as(ie(),e.sessionId,e.label,e.at);return v({sessionId:e.sessionId,marker:{t:Math.round(i.t*1e3)/1e3,label:Eo(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.");D(r),Yt(ar(r));let n=ns(Le(r),{t:e.at,label:e.label,at:new Date().toISOString()}),o=cr(r,n);return v({marker:{t:Math.round(e.at*1e3)/1e3,label:Eo(e.label)},count:n.length,markersPath:o})}catch(r){return _(r)}})}import{z as ye}from"zod";import{extname as a$,join as lh}from"node:path";import{existsSync as c$,mkdtempSync as u$,readFileSync as l$,rmSync as p$,writeFileSync as d$}from"node:fs";import{tmpdir as m$}from"node:os";import{existsSync as i$}from"node:fs";var Gs="SCREENCAST_WHISPER_MODEL",rh=`Download a whisper.cpp model (ggml-base.en.bin is a good start; ggml-tiny.en.bin is fastest) from https://huggingface.co/ggerganov/whisper.cpp and pass its path as model, or set ${Gs}.`;function hr(t,e=process.env){let r=t??e[Gs];if(!r||r.trim().length===0)throw new l("No whisper model given.",rh);if(!i$(r))throw new l(`Whisper model not found: ${r}`,rh);return r}function Pn(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=${ve(e)}:language=${n}:format=srt:destination=${ve(r)}:use_gpu=false`+(o?":max_len=1":""),"-f","null","-"]}function sh(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 nh=/(\d+):(\d{2}):(\d{2})[,.](\d{3})/,oh=t=>Number(t[1])*3600+Number(t[2])*60+Number(t[3])+Number(t[4])/1e3;function ih(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 je(t,e={}){let r=[];for(let n of t.replace(/\r\n/g,`
|
|
332
|
+
`).split(/\n\s*\n/)){let o=n.split(`
|
|
333
|
+
`).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(nh),d=c?.match(nh);if(!u||!d)continue;let p=o.slice(i+1).join(`
|
|
334
|
+
`);if(!p)continue;let f=e.index&&i>0&&/^\d+$/.test(o[i-1])?Number(o[i-1]):void 0;r.push({start:oh(u),end:oh(d),text:p,...f!==void 0&&{index:f}})}return r}function pt(t){let e=[...t].sort((r,n)=>r.start-n.start);return e.map((r,n)=>{let o=e[n+1],i=o?Math.min(r.end,o.start):r.end;return{...r,end:i}}).filter(r=>r.end>r.start)}function nt(t){return t.map((e,r)=>`${r+1}
|
|
335
|
+
${ih(e.start)} --> ${ih(e.end)}
|
|
336
|
+
${e.text}
|
|
337
|
+
`).join(`
|
|
338
|
+
`)}var qs=["clean","social"],s$={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 Mu(t,e,r="clean"){let n=r===null?null:s$[r];if(n===void 0)throw new l(`Unknown caption style "${r}".`);return`subtitles=filename=${ve(t)}:fontsdir=${ve(e)}`+(n?`:force_style='${n}'`:"")}function ah(t,e,r,n,o="clean",i="standard"){return["-y","-i",t,"-vf",Mu(e,n,o),...Te(i),"-c:a","copy",r]}var Hs=1e3;function ch(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,`
|
|
339
|
+
`).trim();if(!o)throw new l(`Translation ${n+1} is empty.`);if(o.length>Hs)throw new l(`Translation ${n+1} is over ${Hs} characters.`);return{start:r.start,end:r.end,text:o.replace(/\n\s*\n/g,`
|
|
340
|
+
`)}})}function uh(t,e){return t.replace(/\.srt$/i,"")+`.${e}.srt`}var f$=new Set([".mp4",".mkv",".mov"]),h$=12,g$={input:ye.string().min(1).optional().describe("Path to the video."),sessionId:ye.string().min(1).optional().describe("Or a stopped recording's id."),from:ye.enum(["markers","scenes","transcript"]).optional().describe("markers (default; add_marker, else the file's chapters), scenes (screen changes), or transcript (SRT sections)."),chapters:ye.array(ye.object({start:ye.number().min(0),title:ye.string().min(1).max(100)})).min(1).max(200).optional().describe("Or explicit { start, title } chapters."),transcript:ye.string().optional().describe("The .srt for from: transcript."),minChapterSec:ye.number().min(0).optional().describe(`Shortest chapter (default 1; scenes ${xn}, transcript 30).`),subtitles:ye.string().optional().describe("Also mux this .srt/.vtt/.ass as a soft subtitle track."),subtitleLanguage:ye.string().regex(/^[a-z]{3}$/).optional().describe('ISO 639-2, e.g. "eng".'),subtitleTracks:ye.array(ye.object({file:ye.string().min(1),language:ye.string().regex(/^[a-z]{3}$/).optional(),title:ye.string().max(60).optional(),default:ye.boolean().optional()})).min(1).max(rs).optional().describe("Or several tracks, e.g. one per language (translate_subtitles makes them)."),textOnly:ye.boolean().optional().describe("Return chapters and YouTube text only; write no file."),output:ye.string().optional().describe("Optional .mp4/.mkv/.mov path. Defaults under SCREENCAST_HOME/edits."),overwrite:ye.boolean().optional().describe("Allow replacing an existing output file.")};function ph(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:g$,outputSchema:L({chapters:ye.array(L({start:ye.number(),end:ye.number(),title:ye.string()})),youtube:ye.string()}),annotations:O},async(e,r)=>{try{E();let n=e.input,o;if(e.sessionId){let x=ie().get(e.sessionId);if(!x)throw new l(`No session with id "${e.sessionId}".`);if(x.status==="recording"||x.status==="paused")throw new l("The recording is still running; stop it first.");n??=x.outputPath,o=x.markers}if(!n)throw new l("Pass input or sessionId.");if(D(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 x of[e.transcript,...i.map($=>$.file)])if(x!==void 0&&!c$(x))throw new l(`File not found: ${x}`);for(let x of i)if(!/\.(srt|vtt|ass|ssa)$/i.test(x.file))throw new l(`Subtitles must be .srt, .vtt, or .ass files, not ${x.file}.`);let a=(await B(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=xn;let{ffmpeg:x}=E(),$=await se(x,Qt(n,bt),le(a),{signal:r.signal});if($.code!==0)throw new l(`Scene scan failed (exit ${$.code}): ${$.stderr.trim().slice(-400)}`);u=um(Zt($.stdout),e.minChapterSec??d,h$)}else if(c==="transcript"){if(!e.transcript)throw new l("from: transcript needs transcript (an .srt path).");if(d=30,u=lm(je(l$(e.transcript,"utf8")),{minChapterSec:e.minChapterSec??d}),u.length===0)throw new l(`No cues in ${e.transcript}.`)}else{let x=o??[];if(x.length===0){let $=await ur(n,r.signal);x=$.markers,$.from==="chapters"&&(p="embedded chapters")}if(x.length===0)throw new l(`No markers for ${n}.`,"Add some with add_marker, or use from: scenes / transcript, or pass chapters.");u=ss(x)}let f=os(u,a,{minChapterSec:e.minChapterSec??d});if(f.length===0)throw new l("No chapter falls inside the video.");let m=cm(f,a),h={source:p,chapters:f,youtube:m.text,...m.issues.length>0?{youtubeIssues:m.issues}:{}};if(e.textOnly)return v(h);let g=e.output?a$(e.output).toLowerCase():ee(n);if(!f$.has(g))throw new l(`Chapters can be written to .mp4, .mkv, or .mov, not ${g||"a file without an extension"}.`);let w=z(e.output,"chapters",g,{overwrite:e.overwrite,anyContainer:!0}),b=u$(lh(m$(),"screencast-chapters-"));try{let x=lh(b,"chapters.txt");d$(x,is(f)),await G(pm(n,x,w,{container:g,subtitles:i}),{output:w,durationSec:a,extra:r})}finally{p$(b,{recursive:!0,force:!0})}return v({outputPath:w,...h,...e.subtitles?{subtitleTrack:{...i[0],codec:g===".mkv"?"copy":"mov_text"}}:{},...e.subtitleTracks?{subtitleTracks:i.map(x=>({...x,codec:g===".mkv"?"copy":"mov_text"}))}:{}})}catch(n){return _(n)}})}import{z as dt}from"zod";import{existsSync as x$,readFileSync as vh,rmSync as y$}from"node:fs";var Do="ui://screencast/player",Xs="text/html;profile=mcp-app",mh={ui:{resourceUri:Do},"ui/resourceUri":Do},dh="io.modelcontextprotocol/ui";function fh(t){let e=t,r=e?.extensions?.[dh]??e?.experimental?.[dh];return!r||typeof r!="object"?!1:!Array.isArray(r.mimeTypes)||r.mimeTypes.includes(Xs)}var Js=120,hh=300,b$=4,Cu=640,w$=.01;function gh(t,e=Js){if(!(t>0))throw new l("The video has no duration to review.");let r=Math.max(1,Math.min(e,Math.ceil(t*b$))),n=Number((t/r).toFixed(6));return{count:r,intervalSec:n,sceneGapSec:Number(Math.max(.25,n/4).toFixed(6))}}function bh(t,e,r,n,o=w$){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=${ve(n)}`,"-fps_mode","passthrough","-q:v","6","-f","image2pipe","-c:v","mjpeg","-"]}function wh(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 xh(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 yh(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 Sh=t=>vh(yn("ui",t),"utf8");function S$(){let t=Sh("player.js");if(/<\/script/i.test(t))throw new l("player.js must not contain a closing script tag.");return Sh("player.html").replace('<script src="player.js"></script>',()=>`<script>
|
|
341
|
+
${t}</script>`)}function v$(t){if(t.sessionId){let e=ie().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 $$(t){return t&&t.length>0?{markers:t.map(({t:e,label:r})=>({t:e,label:r}))}:{}}function $h(t){t.registerResource("review-player",Do,{title:"Recording review player",description:"Interactive player: scrub, trim, and draw redaction boxes on a recording.",mimeType:Xs},async()=>({contents:[{uri:Do,mimeType:Xs,text:S$(),_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:L({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:mh},async n=>{try{E();let o=v$(n);D(o);let i=await B(o);return v({input:o,durationSec:i.durationSec,width:i.width,height:i.height,fps:i.fps,hasAudio:i.audioCodec!==null,...$$(n.sessionId?ie().get(n.sessionId)?.markers??Le(o):Le(o)),note:"Clients with MCP Apps show an inline review player for this result. Without it, look with contact_sheet or sample_frames, then trim and redact with pipeline."})}catch(o){return _(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(hh).optional().describe(`Frames on the even grid (default ${Js}); scene-change frames come on top, up to as many again.`),width:dt.number().int().min(64).max(1280).optional().describe(`Frame width (default ${Cu}).`)},annotations:fe,_meta:{ui:{visibility:["app"]}}},async(n,o)=>{try{E(),D(n.input);let i=await B(n.input),s=i.durationSec??0,a=gh(s,n.maxFrames??Js),c=Be(".txt"),u,d;try{let b=await Or(bh(n.input,a,n.width??Cu,c),le(s),{signal:o.signal});u=yh(b),d=wh(x$(c)?vh(c,"utf8"):"").slice(0,u.length)}finally{y$(c,{force:!0})}let[p]=d;if(!p)throw new l("ffmpeg returned no preview frames.");let f=xh(d,a.count).flatMap(b=>{let x=d[b],$=u[b];return x&&$?[{frame:x,jpeg:$}]:[]}),m=p.timeSec,h=[];try{h=(await ur(n.input,o.signal)).markers.map(({t:b,label:x})=>({t:b,label:x}))}catch{}let g=f.map(({frame:b})=>Math.round((b.timeSec-m)*1e3)/1e3),w=f.flatMap(({frame:b},x)=>b.scene?[x]:[]);return{content:[{type:"text",text:JSON.stringify({input:n.input,durationSec:s,width:i.width,height:i.height,hasAudio:i.audioCodec!==null,frameTimes:g,intervalSec:a.intervalSec,sceneFrames:w,markers:h})},...f.map(({jpeg:b})=>({type:"image",data:b.toString("base64"),mimeType:"image/jpeg"}))]}}catch(i){return _(i)}});e.disable();let r=t.server.oninitialized;t.server.oninitialized=()=>{r?.(),fh(t.server.getClientCapabilities())&&e.enable()}}import{z as mt}from"zod";import{readFileSync as k$,rmSync as E$}from"node:fs";var Re=1280,Ys=8,Lo=20;function _$(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 Ks(t){return Math.max(0,Math.min(Lo,Math.floor(t??Ys)))}async function Me(t,e=Re,r=Ys){let n=t.slice(0,r);return{images:await He(n,async i=>{let s=Be(".jpg");try{return await te(_$(i,s,e),3e4),{type:"image",data:k$(s).toString("base64"),mimeType:"image/jpeg"}}finally{E$(s,{force:!0})}}),omitted:t.length-n.length}}var T$={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 ${Re}).`)};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:T$,outputSchema:L({outputPath:mt.string(),target:mt.string(),backend:mt.string(),inlineImages:mt.number().int()}),annotations:O},async(e,r)=>{try{E();let n=await ut(e.target,{exactTitle:e.exactTitle,backend:e.backend}),{window:o}=n,i=z(e.output,"shot",".png",{overwrite:e.overwrite,dir:"screenshots",anyContainer:!0}),s=e.backend??"gdigrab";await Pt(t,`Take a screenshot of ${Ct(e.target,o)}, saved to ${i}?`,r.signal),await It(n,i,s);let a=e.returnImage===!1?[]:(await Me([i],e.maxImageWidth??Re,1)).images;return v({outputPath:i,target:e.target,backend:s,...o?lr(o):{},inlineImages:a.length},a)}catch(n){return _(n)}})}import{z as Pe}from"zod";import{join as Pu}from"node:path";import{mkdirSync as A$,readdirSync as Eh,existsSync as R$,rmSync as M$}from"node:fs";var C$={input:Pe.string().min(1).describe("Path to the source video file."),mode:Pe.enum(["fps","timestamps","scenes"]).optional().describe("scenes: only frames where the screen changed (strongest first), usually the cheapest review. Default: fps or timestamps, whichever is given."),fps:Pe.number().positive().optional().describe("Frames per second (mode fps)."),timestamps:Pe.array(Pe.number().nonnegative()).optional().describe("Seconds to grab a frame at (mode timestamps)."),sceneThreshold:Pe.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed to count, 0-1 (default ${bt}).`),dedupe:Pe.boolean().optional().describe("Mode fps: drop near-duplicate frames (default false)."),outputDir:Pe.string().optional().describe("Optional folder for the frames (a relative path resolves under SCREENCAST_HOME/frames). Defaults to SCREENCAST_HOME/frames/<id>."),maxFrames:Pe.number().int().min(1).max(pc).optional().describe(`Frame cap (default ${ki}); fps is lowered to fit while still spanning the video.`),returnImages:Pe.boolean().optional().describe("Return the first maxInlineImages frames inline (default true)."),maxInlineImages:Pe.number().int().min(0).max(Lo).optional().describe(`Frames to embed inline (default ${Ys}); all are listed by path.`),maxImageWidth:Pe.number().int().min(16).optional().describe(`Max inline image width (default ${Re}).`)};function _h(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:C$,outputSchema:L({frameDir:Pe.string(),frameCount:Pe.number().int(),frames:Pe.array(Pe.string()),mode:Pe.string()}),annotations:fe},async(e,r)=>{try{E(),D(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??ki;if(o&&e.timestamps.length>a)throw new l(`${e.timestamps.length} timestamps exceeds maxFrames (${a}). Pass fewer timestamps, or raise maxFrames (up to ${pc}).`);let c=i==="timestamps"?null:(await B(e.input)).durationSec,u=i==="fps"?Ei(c,e.fps,a):null,d=null,p=[];if(i==="scenes"){let{ffmpeg:w}=E(),b=await se(w,Qt(e.input,e.sceneThreshold??bt),le(c),{signal:r.signal});if(b.code!==0)throw new l(`Scene scan failed (exit ${b.code}): ${b.stderr.trim().slice(-400)}`);d=Zt(b.stdout),p=cn(d,a)}let f=nn(e.outputDir,be("frames"))??Pu(be("frames"),`sample-${he()}-${ge()}`);A$(f,{recursive:!0});let m=[],h=[];if(u){let w=S=>S.endsWith(".png"),b=new Set(Eh(f).filter(w)),x=Ql(b,`${he()}-${ge()}`),$=rn(f,`${x}%05d.png`);await te(_i(e.input,u.fps,$,a,e.dedupe===!0),le(c),{signal:r.signal}),m=Eh(f).filter(S=>w(S)&&S.startsWith(x)&&!b.has(S)).sort().map(S=>Pu(f,S))}else{let w=i==="scenes"?p:e.timestamps,b=await He(w,async(x,$)=>{let S=Pu(f,`frame_${String($).padStart(3,"0")}_${x}s.png`);return M$(S,{force:!0}),await te(un(e.input,x,S),6e4,{signal:r.signal}),S});for(let[x,$]of b.entries())R$($)?m.push($):h.push(w[x])}let g=e.returnImages===!1?{images:[],omitted:0}:await Me(m,e.maxImageWidth??Re,Ks(e.maxInlineImages));return v({frameDir:f,frameCount:m.length,frames:m,mode:u?`fps=${u.fps}${e.dedupe?" (deduped)":""}`:d?`scenes (threshold ${e.sceneThreshold??bt})`:`timestamps=[${e.timestamps.join(", ")}]`,...d?{frameTimes:p,sceneChangesFound:d.length,...d.length+1>a?{capNote:`Found ${d.length} scene changes; kept the opening frame and the ${a-1} strongest (maxFrames ${a}). Raise sceneThreshold to keep only bigger changes, or raise maxFrames.`}:{}}:{},...u?.clamped?{requestedFps:e.fps,capNote:`fps=${e.fps} would write about ${u.requestedFrames} frames, over maxFrames (${a}); sampled at fps=${u.fps} instead so the frames still span the whole video. Raise maxFrames or use timestamps for more detail.`}:{},...u&&!u.clamped&&m.length>=a?{capNote:`Stopped at maxFrames (${a}); the video's length could not be probed in advance.`}:{},inlineImages:g.images.length,...g.omitted>0?{inlineNote:`Embedded the first ${g.images.length} of ${m.length} frames inline; the other ${g.omitted} are on disk at the listed paths.`}:{},...h.length>0?{skippedTimestamps:h,note:`No frame was written for ${h.length} timestamp(s) past the end of the video: [${h.join(", ")}].`}:{}},g.images)}catch(n){return _(n)}})}import{z as Ve}from"zod";var P$={input:Ve.string().min(1).describe("Path to the source video."),count:Ve.number().int().min(1).max(af).optional().describe(`Frames to tile (default ${Po}).`),mode:Ve.enum(["even","scenes"]).optional().describe("even (default) or scenes (strongest changes; static stretches take no tiles)."),sceneThreshold:Ve.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed, 0-1 (default ${bt}).`),columns:Ve.number().int().min(1).max(12).optional().describe("Tiles per row (default: roughly square)."),tileWidth:Ve.number().int().min(64).max(1920).optional().describe(`Tile width in px (default ${Io}).`),poster:Ve.boolean().optional().describe("Write one representative poster frame instead of a sheet."),output:Ve.string().optional().describe("Optional output .png path. Defaults under SCREENCAST_HOME/frames."),overwrite:Ve.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),returnImage:Ve.boolean().optional().describe("Return the sheet inline (default true)."),maxImageWidth:Ve.number().int().min(16).optional().describe(`Max inline image width (default ${Re}).`)};function Th(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:P$,outputSchema:L({outputPath:Ve.string(),inlineImages:Ve.number().int()}),annotations:O},async(e,r)=>{try{let{ffmpeg:n}=E();D(e.input);let{durationSec:o}=await B(e.input);if(o===null)throw new l(`Could not read duration of ${e.input}.`);let i=e.poster?"poster":"sheet",s=Kt(e.output,be("frames"),`${i}-${he()}-${ge()}.png`,e.overwrite),a=e.tileWidth??Io,c;if(e.poster)await te(cf(e.input,o,s,Math.max(a,1280)),le(o),{signal:r.signal}),c={outputPath:s,poster:!0};else{let d=e.count??Po,p;if(e.mode==="scenes"){let m=await se(n,Qt(e.input,e.sceneThreshold??bt),le(o),{signal:r.signal});if(m.code!==0)throw new l(`Scene scan failed (exit ${m.code}): ${m.stderr.trim().slice(-400)}`);p=cn(Zt(m.stdout),d)}else p=Es(o,d);let f=await _s(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 Me([s],e.maxImageWidth??Re,1)).images;return v({...c,inlineImages:u.length},u)}catch(n){return _(n)}})}import{z as $t}from"zod";import{rmSync as N$}from"node:fs";var Ah=320,I$=4,F$=1600,St=8,Wo=12;function Rh(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(Ah,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 Qs(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(t,Math.max(Ah,Math.min(F$,Math.ceil(t/I$)))),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function Zs(t,e){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 O$(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 vt(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??Wo,s=Math.ceil(r/St),a=Math.ceil(n/St),c=new Uint8Array(s*a);for(let b=0;b<a;b++)for(let x=0;x<s;x++){let $=0,S=0;for(let C=b*St;C<Math.min(n,(b+1)*St);C++)for(let I=x*St;I<Math.min(r,(x+1)*St);I++){let R=C*r+I;$+=Math.abs(t[R]-e[R]),S++}$/S>i&&(c[b*s+x]=1)}let u=new Uint8Array(s*a),d=[];for(let b=0;b<c.length;b++){if(!c[b]||u[b])continue;let x={x0:1/0,y0:1/0,x1:-1,y1:-1,cells:0},$=[b];for(u[b]=1;$.length>0;){let S=$.pop(),C=S%s,I=Math.floor(S/s);x.x0=Math.min(x.x0,C),x.y0=Math.min(x.y0,I),x.x1=Math.max(x.x1,C),x.y1=Math.max(x.y1,I),x.cells++;for(let R=-1;R<=1;R++)for(let A=-1;A<=1;A++){let W=C+A,Y=I+R;if(W<0||Y<0||W>=s||Y>=a)continue;let j=Y*s+W;c[j]&&!u[j]&&(u[j]=1,$.push(j))}}d.push(x)}let p=o.scaleX??o.scale??1,f=o.scaleY??o.scale??1,m=o.origin?.x??0,h=o.origin?.y??0,g=d.sort((b,x)=>x.cells-b.cells).slice(0,o.maxRegions??20).map(b=>{let x=b.x0*St,$=b.y0*St,S=Math.min(r,(b.x1+1)*St)-x,C=Math.min(n,(b.y1+1)*St)-$;return{x:m+Math.round(x*p),y:h+Math.round($*f),width:Math.round(S*p),height:Math.round(C*f)}}),w=c.reduce((b,x)=>b+x,0);return{meanDiff:O$(t,e),changedFraction:w/c.length,regions:g}}function Mh(t,e,r){return{scaleX:t.width/e.width,scaleY:t.height/e.height,pixelThreshold:r}}var Vs=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=vt(this.previous,e,this.width,this.height,this.opts).regions,n=r.length>0?r:vt(this.anchor,e,this.width,this.height,this.opts).regions;return this.previous=e,n.length>0&&(this.anchor=e),n}};function jo(t,e){return["-v","error","-i",t,"-frames:v","1","-vf",`scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function Ch(t,e,r,n){return["-v","error","-probesize","32","-analyzeduration","0","-f","gdigrab","-framerate",String(Math.round(n*1e3)/1e3),...xi(t,e),"-vf",`scale=${r.width}:${r.height}:flags=area,format=gray`,"-flush_packets","1","-f","rawvideo","-"]}function Ph(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 Bo(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 Ih(t){let e=t.match(/All:([\d.]+)/);return e?Number(e[1]):null}import{tmpdir as D$}from"node:os";import{join as L$}from"node:path";var W$={a:$t.string().min(1).describe("Before image (or video: first frame)."),b:$t.string().min(1).describe("After image (or video); scaled to a's size."),pixelThreshold:$t.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${Wo}).`),returnImage:$t.boolean().optional().describe("Return b inline with changes outlined (default true).")};function Fh(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:W$,outputSchema:L({identical:$t.boolean(),ssim:$t.number().nullable(),meanDiff:$t.number(),changedFraction:$t.number(),regions:$t.array($t.unknown())}),annotations:fe},async(e,r)=>{try{E();for(let p of[e.a,e.b])D(p);let[n,o]=await Promise.all([B(e.a),B(e.b)]);if(!n.width||!n.height)throw new l(`Could not read the size of ${e.a}.`);let i=Qs(n.width,n.height),[s,a,c]=await Promise.all([Or(jo(e.a,i),3e4,{signal:r.signal}),Or(jo(e.b,i),3e4,{signal:r.signal}),se(E().ffmpeg,Ph(e.a,e.b,i),3e4,{signal:r.signal})]),u=vt(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=L$(D$(),`screencast-diff-${he()}-${ge()}.png`);try{await te(Bo(e.b,u.regions,p),3e4,{signal:r.signal}),d.push(...(await Me([p],Re,1)).images)}finally{N$(p,{force:!0})}}return v({identical:u.regions.length===0,ssim:Ih(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 _(n)}})}import{z as Ae}from"zod";var j$=t=>new Promise(e=>setTimeout(e,t));async function Oh(t){let e=t.now??Date.now,r=t.sleep??j$,n=e(),o=await t.grab(),i=new Vs(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=vt(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 B$=t=>new Promise(e=>setTimeout(e,t));async function Nh(t){let e=t.now??Date.now,r=t.sleep??B$,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(vt(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 ea=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 ta}from"node:path";import{mkdtempSync as U$,rmSync as Uo}from"node:fs";import{tmpdir as Dh}from"node:os";var z$={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(Wr).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 ${Wo}).`),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 Lh(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:z$,outputSchema:L({outcome:Ae.string(),mode:Ae.string(),elapsedSec:Ae.number(),regions:Ae.array(Ae.unknown()),origin:L({x:Ae.number(),y:Ae.number()})}),annotations:fe},async(e,r)=>{try{E();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 Pt(t,`Watch ${Ct(e.target,p)} for up to ${i/1e3} s, until it ${f}?`,r.signal);let m=U$(ta(Dh(),"screencast-wait-")),h=0,g=async()=>{let y=ta(m,`still-${h++}.png`);return await It(c,y,o),y},w=Zs(u,d);if(o==="wgc")try{let y=await B(await g());if(!y.width||!y.height)throw new l("Could not read the window capture's size.");w={...p?.client??{x:w.x,y:w.y},width:y.width,height:y.height}}catch(y){throw Uo(m,{recursive:!0,force:!0}),y}let b=Qs(w.width,w.height),x=Mh(w,b,e.pixelThreshold),$=new ea,S=new AbortController,C=o==="gdigrab"?Oi(Ch(u,d,b,1e3/a),b.width*b.height,y=>$.push(y),i+6e4,{signal:AbortSignal.any([r.signal,S.signal])}).then(()=>$.end(),y=>$.fail(y)):Promise.resolve(),I=o==="gdigrab"?()=>$.next(15e3):async()=>{let y=await g();try{return await Or(jo(y,b),3e4,{signal:r.signal})}finally{Uo(y,{force:!0})}},R=o==="gdigrab"?async()=>{}:void 0,A,W=null,Y=0;try{if(n==="text"){let y=await Nh({grab:I,read:async()=>{let Z=await g(),[K]=await lt([Z],m,r.signal);return Uo(Z,{force:!0}),K?xt(K.lines,e.text,e.regex===!0):[]},width:b.width,height:b.height,diff:x,timeoutMs:i,intervalMs:a,gone:e.gone===!0,signal:r.signal,...R?{sleep:R}:{}});W={matches:y.matches,reads:y.reads},A={outcome:y.outcome,regions:y.matches.map(({x:Z,y:K,width:ce,height:J})=>({x:Z,y:K,width:ce,height:J})),startedAt:y.startedAt}}else A=await Oh({grab:I,mode:n,width:b.width,height:b.height,diff:x,timeoutMs:i,settleMs:s,intervalMs:a,signal:r.signal,...R?{sleep:R}:{}});Y=Date.now()}finally{S.abort(),await C,Uo(m,{recursive:!0,force:!0})}let{outcome:j,regions:re,everChanged:F,startedAt:oe}=A,de={outcome:j,mode:n,elapsedSec:Number(((Y-oe)/1e3).toFixed(2)),...n==="settle"?{changedWhileWaiting:F}:{},...W?{text:e.text,...e.gone?{gone:!0}:{},matches:W.matches,ocrReads:W.reads}:{},regions:re,origin:{x:w.x,y:w.y},...o==="wgc"?{backend:o}:{},...p?lr(p):{}},Se=[];if(e.returnImage!==!1&&j!=="cancelled"){let y=e.keep?ta(be("screenshots"),`wait-${he()}-${ge()}.png`):ta(Dh(),`screencast-wait-${he()}-${ge()}.png`);try{o==="wgc"?await It(c,y,"wgc"):await te(Si(u,y,d),6e4,{signal:r.signal}),e.keep&&(de.screenshotPath=y),Se.push(...(await Me([y],Re,1)).images)}finally{e.keep||Uo(y,{force:!0})}}return v(de,Se)}catch(n){return _(n)}})}import{z as qe}from"zod";import{extname as Wh,join as In}from"node:path";import{mkdtempSync as H$,rmSync as G$}from"node:fs";import{tmpdir as q$}from"node:os";var jh=new Set([".png",".jpg",".jpeg",".bmp",".gif",".webp",".tif",".tiff"]),ra=300,X$={target:qe.string().optional().describe("Live screen target (full | monitor:<i> | window:... | region:...), or pass input."),input:qe.string().optional().describe("Image or video file to read instead of a live target."),timestamp:qe.number().nonnegative().optional().describe("Video input: second to read (default 0)."),scanEverySec:qe.number().positive().optional().describe("Video input: scan a frame every N s across the clip (e.g. for secrets before sharing); matches and redactRegions get times. Widens to stay within maxFrames."),maxFrames:qe.number().int().min(1).max(gs).optional().describe(`scanEverySec frame cap (default ${$n}; ~1 s each).`),exactTitle:qe.boolean().optional().describe("window: targets match the whole title only (default false)."),backend:qe.enum(["gdigrab","wgc"]).optional().describe("Live target: gdigrab (default) = what is visible; wgc (window:, FFmpeg 8+) = the window even if covered."),query:qe.string().optional().describe("Text to find (case-insensitive, tolerates OCR misreads like I/l, O/0, _/-). Omit to return all text."),regex:qe.boolean().optional().describe("Treat query as a regular expression (case-insensitive)."),redact:qe.boolean().optional().describe("Also return padded match rectangles ready for redact_region's regions."),keep:qe.boolean().optional().describe("Live target: keep the capture and return its path (default false: deleted after reading)."),returnImage:qe.boolean().optional().describe("Return the image with matches outlined (default: true with a query).")};function Bh(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:X$,outputSchema:L({imageSize:L({width:qe.number(),height:qe.number()})}),annotations:fe},async(e,r)=>{try{if(E(),e.target===void 0==(e.input===void 0))throw new l("Provide exactly one of: target (live screen) or input (a file).");let n=H$(In(q$(),"screencast-ocr-"));try{if(e.scanEverySec!==void 0)return await J$(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?In(be("screenshots"),`ocr-${he()}-${ge()}.png`):In(n,"capture.png");let g=e.backend??"gdigrab";await Pt(t,`Capture ${Ct(e.target,h.window)} once to read the text on it?`,r.signal),await It(h,o,g),h.window&&(i=lr(h.window));let w=Zs(h.target,h.monitors);s=g==="wgc"&&h.window?.client?h.window.client:{x:w.x,y:w.y}}else{D(e.input);let h=jh.has(Wh(e.input).toLowerCase());o=In(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 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?xt(c,e.query,e.regex===!0):[],f=[];if(e.returnImage??!!e.query){let h=In(n,"shown.png");await te(Bo(o,p,h),3e4,{signal:r.signal}),f.push(...(await Me([h],Re,1)).images)}return v({...e.target!==void 0?e.keep?{screenshotPath:o}:{}:{input:e.input},imageSize:{width:u,height:d},...s?{origin:s}:{},...e.query?{query:e.query,matchCount:p.length,matches:p,...e.redact?{redactRegions:fs(p,{width:u,height:d})}:{}}:{},text:c.map(h=>h.text).join(`
|
|
342
|
+
`),lines:c.slice(0,ra).map(({words:h,...g})=>g),...c.length>ra?{linesTruncated:c.length-ra}:{},...i,note:"OCR is best-effort: small or stylised text can be missed. Review before relying on it, especially for redaction."},f)}finally{G$(n,{recursive:!0,force:!0})}}catch(n){return _(n)}})}async function J$(t,e,r){if(t.input===void 0)throw new l("scanEverySec reads a video file: pass input, not target.");if(D(t.input),jh.has(Wh(t.input).toLowerCase()))throw new l("scanEverySec is for a video input; an image has one frame, so drop scanEverySec.");let n=t.maxFrames??$n,o=await hs(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 g of h.lines)a.add(g.text);let{matches:c,redactRegions:u}=t.query?vn(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=In(e,"shown.png");await te(Bo(f,c.filter(g=>g.t===p.t),h),3e4,{signal:r}),d.push(...(await Me([h],Re,1)).images)}let m=[...a].join(`
|
|
343
|
+
`);return v({input:t.input,imageSize:{width:s.width,height:s.height},scan:{everySec:Math.round(i*1e3)/1e3,framesScanned:o.frames.length,...o.clamped?{note:`Widened from ${t.scanEverySec} s to fit maxFrames ${n}.`}:{}},...t.query?{query:t.query,matchCount:c.length,matches:c.slice(0,ra),...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 br}from"zod";import{dirname as Z$,join as Fu}from"node:path";import{existsSync as zo,mkdirSync as ek,mkdtempSync as tk,readFileSync as Ho,readdirSync as rk,rmSync as Nu}from"node:fs";import{tmpdir as nk}from"node:os";import{spawnSync as Y$}from"node:child_process";import{isAbsolute as K$}from"node:path";var Br=8;function na(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 Uh(t){let e=new Set,r=t.split(/^\s*---\s*$/m).slice(1).join(`
|
|
344
|
+
`)||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 Iu(t,e){try{let r=Y$(t,e,{encoding:"utf8",windowsHide:!0,timeout:1e4});return r.status!==0?null:`${r.stdout??""}${r.stderr??""}`}catch{return null}}function oa(t){return Iu(t,["-version"])}function zh(t){return Iu(t,["-hide_banner","-devices"])}function Hh(t){return K$(t)?t:Iu(process.platform==="win32"?"where":"which",[t])?.split(/\r?\n/).map(r=>r.trim()).find(r=>r.length>0)??null}var V$=`
|
|
345
|
+
$ErrorActionPreference = 'Stop'
|
|
346
|
+
$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
|
|
347
|
+
$e = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
|
|
348
|
+
[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
|
|
349
|
+
`;async function gr(){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 at(V$,"OCR languages",{timeoutMs:nr(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:H(t)}}}var Q$=["SCREENCAST_HOME","SCREENCAST_ALLOWED_DIRS","FFMPEG_PATH","FFPROBE_PATH","SCREENCAST_WHISPER_MODEL","SCREENCAST_MAX_RECORDING_SEC","SCREENCAST_JOB_TIMEOUT_MS","SCREENCAST_PS_TIMEOUT_MS","SCREENCAST_RETENTION_DAYS","SCREENCAST_CONFIRM_CAPTURE","SCREENCAST_TOOLSETS"];function Gh(t=process.env){return Object.fromEntries(Q$.map(e=>{let r=t[e];return[e,r&&r.trim().length>0?r:null]}))}var qh=[{filter:"whisper",tools:"transcribe",why:`FFmpeg ${Br}+ built with whisper.cpp`},{filter:"gfxcapture",tools:'backend: "wgc" (screenshot, start_recording, find_text)',why:`FFmpeg ${Br}+ 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 Ou=8,ok={input:br.string().optional().describe("Recording path."),sessionId:br.string().optional().describe("Or a stopped session id."),sceneThreshold:br.number().gt(0).lt(1).optional().describe(`Change starting a segment (default ${Eu}).`),maxFrames:br.number().int().min(1).max(vf).optional().describe(`Keyframes to OCR (default ${_u}).`),transcript:br.string().optional().describe("An .srt, or 'whisper' to transcribe. Default: <video>.srt if any."),force:br.boolean().optional().describe("Re-OCR despite a matching cached index.")};function Xh(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:ok,outputSchema:L({indexPath:br.string(),segments:br.number()}),annotations:O},async(e,r)=>{let n=tk(Fu(nk(),"screencast-index-"));try{let{ffmpeg:o}=E(),i=await Bs(e),s=await B(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??Eu,u=e.maxFrames??_u,d=be("edits"),p=kf(i.path,d),f=Ws(i.path),m=mo(r),h=[],g=e.force?null:Ns(i.path,d,f),w=g?jr(g):null,b=null,x=async()=>b??=process.platform==="win32"&&(await gr()).available,$=Ef(w,{fingerprint:f,sceneThreshold:c,maxFrames:u,ocrAvailable:w!==null&&!w.ocr?await x():!1}),S,C=0,I=!1;if($)S=w.segments,C=w.framesRead,I=w.ocr;else{let F=await se(o,Qt(i.path,c),le(a),{signal:r.signal});if(F.code!==0)throw new l(`Scene scan failed (exit ${F.code}): ${F.stderr.trim().slice(-400)}`);m?.(.1);let oe=Af(Tf(Zt(F.stdout),a,u),a),de=oe.map(()=>[]);if(I=await x(),I)for(let y=0;y<oe.length;y+=Ou){r.signal.throwIfAborted();let Z=oe.slice(y,y+Ou),ce=(await He(Z,async(V,ne)=>{let T=Fu(n,`key_${y+ne}.png`);return await te(un(i.path,Ls(V),T),6e4,{signal:r.signal}),{at:y+ne,path:T}})).filter(V=>zo(V.path)),J=ce.length>0?await lt(ce.map(V=>V.path),n,r.signal,{sameSize:!0}):[];J.forEach((V,ne)=>de[ce[ne].at]=V.lines.map(T=>T.text)),C+=J.length,m?.(.1+.85*Math.min(oe.length,y+Ou)/oe.length)}else h.push("Windows OCR is not available, so the index holds no screen text; install an OCR language (doctor).");let Se=oe.map((y,Z)=>({...y,ocr:de[Z]??[]}));S=I?Rf(Se):Se}S=_f(S);let R=i.eventsPath?Mf(Ue(Ho(i.eventsPath,"utf8"))):[];S=An(S,R,"events"),S=An(S,Cf(i.markers),"markers");let A=Ot(i.path);if(zo(A)){let F=ys(Ho(A,"utf8")),oe=Ne(F.map(de=>`${de.source}: ${de.line}`),Ge);S=An(S,F.map((de,Se)=>({t:de.t,text:oe[Se]??""})),"logs")}let W=await ik(e.transcript,i.path,s.audioCodec!==null,a,r.signal,h);if(W!==null)S=An(S,Pf(W),"transcript");else if($&&w){let F=w.segments.flatMap(oe=>oe.transcript??[]);S=An(S,F,"transcript")}let Y={version:ku,video:i.path,fingerprint:f,durationSec:a,createdAt:new Date().toISOString(),sceneThreshold:c,maxFrames:u,framesRead:C,ocr:I,segments:S};ek(Fu(p,".."),{recursive:!0}),If(p,Y);let j=Tu(i.path);if(j!==p&&zo(j)){let F=jr(j);F&&Fs(F,i.path,f)&&Nu(j,{force:!0})}m?.(1);let re=F=>S.reduce((oe,de)=>oe+(de[F]?.length??0),0);return v({indexPath:p,segments:S.length,cached:$,framesRead:C,durationSec:a,sources:{screenLines:S.reduce((F,oe)=>F+oe.ocr.length,0),events:re("events"),markers:re("markers"),transcriptCues:re("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 _(o)}finally{Nu(n,{recursive:!0,force:!0})}})}async function ik(t,e,r,n,o,i){if(t==="whisper"){if(!r)return i.push("The recording has no audio, so there is no transcript."),null;if(!Ye("whisper"))throw new l("This ffmpeg has no whisper filter.","transcript: 'whisper' needs FFmpeg 8 built with whisper.cpp; or pass an .srt.");let c=hr(void 0),u=Be(".srt");try{return await te(Pn(e,c,u),le(n),{signal:o}),zo(u)?pt(je(Ho(u,"utf8"))):[]}finally{Nu(u,{force:!0})}}if(t!==void 0){if(!zo(t))throw new l(`Transcript not found: ${t}`);return pt(je(Ho(t,"utf8")))}let s;try{s=rk(Z$(e))}catch{return null}let a=Ds(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(je(Ho(a.path,"utf8"))):null}import{z as Lt}from"zod";import{join as Jh}from"node:path";import{existsSync as Yh,mkdtempSync as sk,rmSync as ak}from"node:fs";import{tmpdir as ck}from"node:os";var uk=480,lk={input:Lt.string().optional().describe("Recording path."),sessionId:Lt.string().optional().describe("Or a stopped session id."),query:Lt.string().min(1).describe("Text; tolerates OCR misreads."),regex:Lt.boolean().optional().describe("query is a regex."),limit:Lt.number().int().min(1).max($f).optional().describe(`Max hits (default ${Is}).`),images:Lt.number().int().min(0).max(Lo).optional().describe("Thumbnails of the top N hits (default 0).")};function Kh(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:lk,outputSchema:L({total:Lt.number(),hits:Lt.array(Lt.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=Of(Fe()).flatMap(g=>{let w=jr(g);return w?[{indexPath:g,index:w}]:[]}),m=Nf(f,e.query,{regex:e.regex===!0,limit:e.limit}),h=m.recordings.map(g=>({...g,...Yh(g.video)?{}:{missing:!0}}));return v({query:e.query,searched:m.searched,total:m.total,hits:m.hits,recordings:h,...m.searched===0?{note:"No indexed recordings under SCREENCAST_HOME; run index_recording first."}:{}})}let n=await Bs(e),o=Ws(n.path),i=Ns(n.path,be("edits"),o),s=i?jr(i):null;if(!i||!s)throw new l(`No index for ${n.path}.`,"Run index_recording on it first.");let a=!js(s.fingerprint,o),{hits:c,total:u}=Au(s,e.query,{regex:e.regex===!0,limit:e.limit,video:n.path,fingerprint:o}),d=Math.min(Ks(e.images??0),c.length),p=[];if(d>0){E();let f=sk(Jh(ck(),"screencast-search-"));try{let m=[];for(let[h,g]of c.slice(0,d).entries()){let w=g.t===g.start?Ls(g):g.t,b=Jh(f,`hit_${h}.png`);await te(un(n.path,w,b),6e4,{signal:r.signal}),Yh(b)&&m.push(b)}p=(await Me(m,uk,d)).images}finally{ak(f,{recursive:!0,force:!0})}}return v({indexPath:i,query:e.query,total:u,hits:c,...u>c.length?{more:u-c.length}:{},...s.ocr?{}:{note:"The index has no screen text (OCR was unavailable when it was built)."},...a?{stale:!0,warning:"The recording changed since it was indexed; run index_recording again."}:{}},p)}catch(n){return _(n)}})}import{z as wr}from"zod";var pk={input:wr.string().min(1).describe("Path to the media file to probe.")};function Vh(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:pk,outputSchema:L({input:wr.string(),durationSec:wr.number().nullable(),width:wr.number().nullable(),height:wr.number().nullable(),fps:wr.number().nullable(),videoCodec:wr.string().nullable(),audioCodec:wr.string().nullable()}),annotations:fe},async e=>{try{return D(e.input),v({input:e.input,...await B(e.input)})}catch(r){return _(r)}})}import{z as Ur}from"zod";import{extname as dk}from"node:path";var mk={input:Ur.string().min(1).describe("Path to the source video."),start:Ur.number().nonnegative().describe("Start time in seconds."),end:Ur.number().positive().optional().describe("End time in seconds. Use end OR duration."),duration:Ur.number().positive().optional().describe("Clip length in seconds. Use end OR duration."),exact:Ur.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:Ur.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ur.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Qh(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:mk,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let n=e.exact===!1?dk(e.input)||".mp4":ee(e.input),o=z(e.output,"trim",n,{overwrite:e.overwrite,anyContainer:e.exact===!1}),i=ep(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 G(i,{output:o,durationSec:c,extra:r}),v({outputPath:o})}catch(n){return _(n)}})}import{z as ca}from"zod";import{extname as yk,resolve as Sk}from"node:path";import{writeFileSync as vk,rmSync as $k}from"node:fs";var fk=1920,hk=1080,Zh=30,eg=48e3,Fn=1,Du="standard";function Lu(t){return Math.round(t*1e3)/1e3}function tg(t){return t.width!==void 0&&Vt(t.width,"width"),t.height!==void 0&&Vt(t.height,"height"),{w:t.width??fk,h:t.height??hk}}function gk(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 bk(t){return`aresample=${t},aformat=sample_fmts=fltp:channel_layouts=stereo`}function wk(t,e){let r=[],n=0;for(let[o,i]of t.slice(0,-1).entries())n+=i,r.push(Math.max(0,Lu(n-(o+1)*e)));return r}function zr(t){return t.videoDurationSec??t.durationSec}function rg(t,e,r,n,o={},i=[!1,!1]){let s=cc(o.transition??"fade"),a=o.duration??Fn;if(!Number.isFinite(a)||a<=0)throw new l("transition duration must be a positive number.");if(!Number.isFinite(r[0])||r[0]<=a)throw new l(`first clip (${r[0]}s) must be longer than the transition (${a}s).`);return Go([t,e],r,n,{...o,transition:s},i)}function Go(t,e,r,n={},o=[]){if(t.length<2)throw new l("assemble_highlights requires at least two clips.");let{w:i,h:s}=tg(n),a=n.fps??Zh,c=n.audioRate??eg,u=n.transition??"cut",d=n.duration??Fn,p=t.length,f=gk(i,s,a),m=bk(c),h=o.some(Boolean),g=[];for(let b=0;b<p;b++)if(g.push(`[${b}:v]${f}[v${b}]`),!!h)if(o[b]){let x=e[b]??Number.NaN,$=Number.isFinite(x)&&x>0?`,apad,atrim=duration=${Lu(x)}`:"";g.push(`[${b}:a]${m}${$}[a${b}]`)}else{let x=e[b]??Number.NaN;if(!Number.isFinite(x)||x<=0)throw new l(`clip ${b} has no audio track and its duration is unknown, so a matching silent track cannot be generated.`);g.push(`anullsrc=channel_layout=stereo:sample_rate=${c}:d=${x}[a${b}]`)}let w=[];if(u==="cut")if(h){let b=t.map((x,$)=>`[v${$}][a${$}]`).join("");g.push(`${b}concat=n=${p}:v=1:a=1[vout][aout]`),w.push("-map","[vout]","-map","[aout]")}else{let b=t.map((x,$)=>`[v${$}]`).join("");g.push(`${b}concat=n=${p}:v=1:a=0[vout]`),w.push("-map","[vout]")}else{if(cc(u),e.length!==p)throw new l(`a ${u} transition needs a duration for each of the ${p} clips.`);if(!Number.isFinite(d)||d<=0)throw new l("transition duration must be a positive number.");let b=e.findIndex(S=>!Number.isFinite(S)||S<=d);if(b!==-1)throw new l(`clip ${b} (${e[b]}s) must be longer than the ${d}s ${u} transition. Use a shorter transition or trim fewer frames.`);let x=wk(e,d),$="v0";for(let S=1;S<p;S++){let C=S===p-1?"vout":`vx${S}`;g.push(`[${$}][v${S}]xfade=transition=${u}:duration=${d}:offset=${x[S-1]}[${C}]`),$=C}if(w.push("-map","[vout]"),h){let S="a0";for(let C=1;C<p;C++){let I=C===p-1?"aout":`ax${C}`;g.push(`[${S}][a${C}]acrossfade=d=${d}[${I}]`),S=I}w.push("-map","[aout]")}}return["-y",...t.flatMap(b=>["-i",b]),"-filter_complex",g.join(";"),...w,...$e({quality:n.quality??Du,audio:h?"aac":"none",faststart:!0}),r]}var Wu=3;function ng(t,e,r,n={}){let{w:o,h:i}=tg(n),s=n.duration??Wu,a=n.fps??Zh,c=De(n.bg??"black","bg"),u=De(n.fontColor??"white","fontColor"),d=n.fontSize??96;if(!Number.isFinite(s)||s<=0)throw new l("title duration must be a positive number.");if(!Number.isInteger(d)||d<=0)throw new l("fontSize must be a positive integer.");let p=`drawtext=fontfile=${ve(e)}:textfile=${ve(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",...$e({quality:n.quality??Du,audio:"aac",faststart:!0}),r]}function og(t,e,r,n,o,i={}){if(!Number.isFinite(n)||n<=0)throw new l("video duration must be known and positive.");let s=i.musicVolume??(o?.25:.8),a=i.fadeIn??1,c=i.fadeOut??2;for(let[h,g]of[[s,"musicVolume"],[a,"fadeIn"],[c,"fadeOut"]])if(!Number.isFinite(h)||h<0)throw new l(`${g} must be a non-negative number.`);let u=i.duck??!1,d=Math.max(0,Lu(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),...$e({video:["-c:v","copy"],audio:"aac",bitrate:"192k",faststart:!0}),r]}var On=["16:9","9:16","1:1","4:5"],ia=["pad","crop"],Nn={"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 sa(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 ig(t,e,r,n="pad",o=Du){let i=Nn[r];if(!i)throw new l(`Unknown aspect "${r}".`);return["-y","-i",t,"-vf",`${sa(i.w,i.h,n)},format=yuv420p`,...$e({quality:o,audio:"copy",faststart:!0}),e]}var aa=["youtube","instagram_reel","tiktok","x","square","steam_trailer","vertical_reel"],ju={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 xk(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 Bu(t,e="pad",r=""){let n=ju[t];if(!n)throw new l(`Unknown platform "${t}".`);let o=Nn[n.aspect],i=n.blurFill?xk(o.w,o.h,r):sa(o.w,o.h,e),s=n.loudness?`loudnorm=I=-14:TP=-1:LRA=11,aresample=${n.loudness.sampleRate??eg}`:void 0;return{vf:`${i},fps=${n.fps},format=yuv420p`,...s?{af:s}:{},encode:["-c:v","libx264","-preset","medium",...n.cbr?["-profile:v","high"]:[],"-b:v",n.videoBitrate,...n.cbr?["-minrate",n.videoBitrate,"-x264-params","nal-hrd=cbr"]:[],"-maxrate",n.videoBitrate,"-bufsize",n.bufsize,"-pix_fmt","yuv420p",...on(n.audioBitrate),...n.loudness?.sampleRate?["-ar",String(n.loudness.sampleRate),"-ac","2"]:[],"-r",String(n.fps),...Mr],width:o.w,height:o.h}}function sg(t,e,r,n="pad"){let{vf:o,af:i,encode:s}=Bu(r,n);return["-y","-i",t,"-vf",o,...i?["-af",i]:[],...s,e]}var kk={inputs:ca.array(ca.string().min(1)).min(2).describe("Video paths to join, in order."),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 ag(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:kk,outputSchema:Q,annotations:O},async(e,r)=>{try{E();let n=e.inputs.map(m=>Sk(m));for(let m of n)D(m);let o=await Promise.all(n.map(m=>B(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=>zr(m)),c=a.every(m=>m!==null)?a.reduce((m,h)=>m+h,0):null,u=rp(n,o);if(u!==null){let m=z(e.output,"concat",ee(i),{overwrite:e.overwrite}),h=w=>w!==null&&w>=2?w-w%2:void 0,g=Go(n,a.map(w=>w??0),m,{transition:"cut",width:h(s.width),height:h(s.height),fps:s.fps??void 0},o.map(w=>w.audioCodec!==null));return await G(g,{output:m,durationSec:c,extra:r}),v({outputPath:m,inputCount:n.length,mode:"reencode",reason:u})}let d=yk(i)||".mp4",p=z(e.output,"concat",d,{overwrite:e.overwrite,anyContainer:!0}),f=Be(".txt");vk(f,tp(n));try{await G(ln(f,p),{output:p,durationSec:c,extra:r})}finally{$k(f,{force:!0})}return v({outputPath:p,inputCount:n.length,mode:"copy"})}catch(n){return _(n)}})}import{z as Dn}from"zod";var Ek={input:Dn.string().min(1).describe("Path to the source media."),format:Dn.enum(["mp4","gif","webm"]).describe("mp4 (H.264), webm (VP9), or gif (palette)."),fps:Dn.number().positive().optional().describe("gif only: fps (default 12)."),width:Dn.number().positive().optional().describe("gif only: width in px (default 720)."),output:Dn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Dn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function cg(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:Ek,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let n=e.format,o=z(e.output,"convert",`.${n}`,{overwrite:e.overwrite,anyContainer:!0}),i=np(e.input,o,n,{fps:e.fps,width:e.width});return await G(i,{output:o,durationSec:await ue(e.input),extra:r}),v({outputPath:o,format:n})}catch(n){return _(n)}})}import{z as Wt}from"zod";var ua=12,la=960,xr=1e7,ug=5;function lg(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 pg(t,e,r,n){let o=n-1;if(t>=o)return null;let i=Math.max(1,Math.ceil(Math.log(e/r)/Math.log(1.8)));return Math.min(o,t+i)}function dg(t,e,r,n,o={}){if(!(n.fps>0)||!Number.isInteger(n.width)||n.width<16)throw new l("fps must be positive and width an integer of at least 16.");if(o.start!==void 0&&!(o.start>=0))throw new l("start must be >= 0.");if(o.duration!==void 0&&!(o.duration>0))throw new l("duration must be > 0.");let i=[...o.start?["-ss",String(o.start)]:[],...o.duration?["-t",String(o.duration)]:[]],s=`fps=${n.fps},scale='min(${n.width},iw)':-1:flags=lanczos`;if(r==="gif"){let a=n.colors??256;return["-y",...i,"-i",t,"-an","-vf",`${s},split[a][b];[a]palettegen=stats_mode=diff:max_colors=${a}[p];[b][p]paletteuse=dither=sierra2_4a:diff_mode=rectangle`,"-loop","0",e]}return["-y",...i,"-i",t,"-an","-vf",s,"-c:v","libwebp_anim","-lossless","0","-q:v",String(n.quality??75),"-compression_level","4","-loop","0",e]}import{basename as _k,dirname as Tk,extname as Ak,join as Rk}from"node:path";import{renameSync as Mk,rmSync as Ck,statSync as Pk}from"node:fs";async function Ln(t,e,r,n){let o=r.format??"gif",i=r.maxBytes??xr,s=await ue(t),a=r.duration??(s!==null?s-(r.start??0):null),c=lg(o,r.fps??ua,r.width??la),u=Ak(e),d=f=>Rk(Tk(e),`${_k(e,u)}.try${f}${u}`),p=[];try{let f=0;for(;f!==null&&p.length<ug;){let g=c[f];if(!g)break;let w=d(p.length),b={start:r.start,duration:r.duration};await G(dg(t,w,o,g,b),{output:w,durationSec:a,extra:n});let x=Pk(w).size;if(p.push({path:w,size:x,settings:g}),x<=i)break;f=pg(f,x,i,c.length)}let m=p.find(g=>g.size<=i),h=m??p.reduce((g,w)=>w.size<g.size?w:g);return Mk(h.path,e),{outputPath:e,format:o,sizeBytes:h.size,maxBytes:i,withinBudget:h.size<=i,settings:h.settings,attempts:p.map(g=>({...g.settings,sizeBytes:g.size})),...m?{}:{note:`Could not get under ${i} bytes; kept the smallest attempt. Export a shorter clip (start/duration), or try format: 'webp'.`}}}finally{for(let f of p)Ck(f.path,{force:!0})}}var Ik={input:Wt.string().min(1).describe("Path to the source video."),format:Wt.enum(["gif","webp"]).optional().describe("gif (default) or webp (usually much smaller)."),maxBytes:Wt.number().int().min(1e4).optional().describe(`Size budget in bytes (default ${xr}, under GitHub's 10 MB image limit).`),fps:Wt.number().positive().max(30).optional().describe(`Starting frame rate (default ${ua}).`),width:Wt.number().int().min(64).max(1920).optional().describe(`Starting width in px (default ${la}).`),start:Wt.number().nonnegative().optional().describe("Start second."),duration:Wt.number().positive().optional().describe("Seconds to export (default: to the end)."),output:Wt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Wt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function mg(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:Ik,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let n=e.format??"gif",o=e.maxBytes??xr,i=z(e.output,"anim",`.${n}`,{overwrite:e.overwrite,anyContainer:!0});return v(await Ln(e.input,i,{format:n,maxBytes:o,fps:e.fps,width:e.width,start:e.start,duration:e.duration},r))}catch(n){return _(n)}})}import{z as Hr}from"zod";var Fk={input:Hr.string().min(1).describe("Path to the source video."),x:Hr.number().int().nonnegative(),y:Hr.number().int().nonnegative(),width:Hr.number().int().positive(),height:Hr.number().int().positive(),output:Hr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Hr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function fg(t){t.registerTool("crop",{title:"Crop Video",description:"Crop a video to a pixel rectangle; one running off the frame is rejected.",inputSchema:Fk,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let{width:n,height:o,durationSec:i}=await B(e.input),s=ee(e.input),a=z(e.output,"crop",s,{overwrite:e.overwrite}),c=op(e.input,a,{x:e.x,y:e.y,width:e.width,height:e.height},{width:n,height:o});return await G(c,{output:a,durationSec:i,extra:r}),v({outputPath:a})}catch(n){return _(n)}})}import{z as qo}from"zod";var Ok={input:qo.string().min(1).describe("Path to the source video."),width:qo.number().int().positive().optional().describe("Target width in px. Omit to derive from height (keeps aspect)."),height:qo.number().int().positive().optional().describe("Target height in px. Omit to derive from width (keeps aspect)."),output:qo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:qo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function hg(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:Ok,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let n=ee(e.input),o=z(e.output,"scale",n,{overwrite:e.overwrite}),i=sp(e.input,o,{width:e.width,height:e.height});return await G(i,{output:o,durationSec:await ue(e.input),extra:r}),v({outputPath:o})}catch(n){return _(n)}})}import{z as Yo}from"zod";import{z as pa}from"zod";function kt(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 kt(e)}var qr=2,Xo=.4,Wn=200;function da(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 gg(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 ma(t,e){return gg(t,/freeze_start:\s*([\d.]+)/,/freeze_end:\s*([\d.]+)/,e)}function fa(t,e){return gg(t,/silence_start:\s*([\d.]+)/,/silence_end:\s*([\d.]+)/,e)}function ha(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 ga(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 Uu(t){if(t.length===0)throw new l("Nothing to cut.");if(t.length>Wn)throw new l(`Too many idle stretches (${t.length}); raise minIdleSec.`);let e=kt(t.map(n=>`between(t,${n.start},${n.end})`)),r=kt(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 Gr=100,ba=pa.object({start:pa.number().min(0),end:pa.number().positive(),factor:pa.number().gt(1).max(Gr)}),Jo=8;function wa(t,e){if(t.length===0)throw new l("segments needs at least one range.");if(t.length>Wn)throw new l(`Too many ranges (${t.length}); at most ${Wn}.`);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>Gr)throw new l(`Range ${n.start}-${n.end}s: factor must be above 1 and at most ${Gr} (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 Xr(t){return t.reduce((e,r)=>e+(r.end-r.start)*(1-1/r.factor),0)}function xa(t,e){if(t.length===0)throw new l("Nothing to speed up.");let r=s=>Number((1-1/s.factor).toFixed(6)),n=kt(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=kt(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 ya(t,e,r,n){let o=xa(r,n.fps);return["-y","-i",t,"-vf",o.video,...n.withAudio?["-af",o.audio]:["-an"],...$e({quality:n.quality??"standard",audio:n.withAudio?"aac":"omit"}),e]}function Sa(t,e,r,n,o="standard"){let i=Uu(r);return["-y","-i",t,"-vf",i.video,...n?["-af",i.audio]:["-an"],...$e({quality:o,audio:n?"aac":"omit"}),e]}var Nk={input:Yo.string().min(1).describe("Path to the source video."),factor:Yo.number().positive().optional().describe("Whole clip: >1 faster, <1 slower."),segments:Yo.array(ba).min(1).optional().describe("Or fast-forward just these ranges (audio shortened, not pitched)."),output:Yo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Yo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function bg(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:Nk,outputSchema:Q,annotations:O},async(e,r)=>{try{if(E(),D(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 B(e.input),s=ee(e.input),a=z(e.output,"speed",s,{overwrite:e.overwrite}),c=n!==null;if(e.segments){let p=wa(e.segments,o),f=Xr(p);return await G(ya(e.input,a,p,{withAudio:c,fps:i}),{output:a,durationSec:o!==null?o-f:null,inputDurationSec:o,extra:r}),v({outputPath:a,segments:p,savedSec:Number(f.toFixed(2)),audio:c})}let u=e.factor,d=ap(e.input,a,u,c);return await G(d,{output:a,durationSec:o!==null?o/u:null,inputDurationSec:o,extra:r}),v({outputPath:a,factor:u,audio:c})}catch(n){return _(n)}})}import{z as ft}from"zod";var Dk={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 wg(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:Dk,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input),D(e.overlay,"Overlay file");let n=ee(e.input),o=z(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=cp(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 G(a,{output:o,durationSec:s,extra:r}),v({outputPath:o})}catch(n){return _(n)}})}import{z as ot}from"zod";import{mkdtempSync as Bk,rmSync as Uk,writeFileSync as zk}from"node:fs";import{tmpdir as Hk}from"node:os";import{join as $g}from"node:path";var Sg=["side_by_side","stack","grid"],va=2,$a=9,xg=3840,Lk=1080,yg=t=>Math.max(2,Math.round(t/2)*2);function Wk(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 jk(t,e){let r=Math.min(t.height,Lk),n=t.width*r/t.height,o=Math.min(1,xg/(n*e.cols),xg/(r*e.rows));return n*=o,r*=o,{width:yg(n),height:yg(r)}}function zu(t,e){let r=t.map(n=>Math.max(0,n.durationSec-n.skipSec));return e==="longest"?Math.max(...r):Math.min(...r)}function vg(t,e,r){let n=t.length;if(n<va||n>$a)throw new l(`compose takes ${va} to ${$a} inputs.`);let o=t[0],i=Wk(r.layout,n),s=jk(o,i),a=zu(t,r.endWith);if(!(a>0))throw new l("Nothing is left to show after lining the inputs up.");let c=[];t.forEach((m,h)=>{let g=Math.max(0,a-(m.durationSec-m.skipSec)),w=m.label?`,drawtext=fontfile=${ve(m.label.fontFile)}:textfile=${ve(m.label.textFile)}:expansion=none:fontcolor=white:fontsize=${Math.max(14,Math.round(s.height/18))}:x=12:y=12:box=1:boxcolor=black@0.6:boxborderw=8`:"";c.push(`[${h}:v]fps=${r.fps},scale=${s.width}:${s.height}:force_original_aspect_ratio=decrease,pad=${s.width}:${s.height}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,format=yuv420p`+(g>.001?`,tpad=stop_mode=clone:stop_duration=${g.toFixed(3)}`:"")+`${w}[c${h}]`)});let u=t.map((m,h)=>`${h%i.cols*s.width}_${Math.floor(h/i.cols)*s.height}`).join("|");c.push(`${t.map((m,h)=>`[c${h}]`).join("")}xstack=inputs=${n}:layout=${u}:fill=black[v]`);let d=t.map((m,h)=>m.hasAudio?h:-1).filter(m=>m>=0),p=[];if(r.audio==="mix"&&d.length>0)c.push(`${d.map(m=>`[${m}:a]`).join("")}amix=inputs=${d.length}:normalize=0:duration=longest,apad[a]`),p=["-map","[a]"];else if(typeof r.audio=="number"){if(!t[r.audio])throw new l(`audio ${r.audio} is not an input (0-${n-1}).`);if(!t[r.audio].hasAudio)throw new l(`Input ${r.audio} has no audio; pick another, "mix", or "none".`);c.push(`[${r.audio}:a]apad[a]`),p=["-map","[a]"]}let f=p.length>0;return["-y",...t.flatMap(m=>[...m.skipSec>0?["-ss",m.skipSec.toFixed(3)]:[],"-i",m.path]),"-filter_complex",c.join(";"),"-map","[v]",...p,"-t",a.toFixed(3),...$e({quality:r.quality??"standard",audio:f?"aac":"omit"}),e]}var Gk={inputs:ot.array(ot.object({path:ot.string().min(1),label:ot.string().min(1).max(80).optional()})).min(va).max($a).describe('Videos in reading order, each with an optional label (e.g. "Before").'),layout:ot.enum(Sg).optional().describe("side_by_side (default), stack, or grid."),alignMarker:ot.string().min(1).optional().describe("Line inputs up on this add_marker label."),endWith:ot.enum(["longest","shortest"]).optional().describe("longest (default; shorter ones hold their last frame) or shortest."),audio:ot.union([ot.number().int().min(0),ot.enum(["mix","none"])]).optional().describe('Input index whose audio to keep (default 0), "mix", or "none".'),output:ot.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ot.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function kg(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:Gk,outputSchema:Q,annotations:O},async(e,r)=>{let n=Bk($g(Hk(),"screencast-compose-"));try{E();let o=[],i=[];for(let[f,m]of e.inputs.entries()){D(m.path,`Input ${f}`);let h=await B(m.path);if(!h.width||!h.height||h.durationSec===null)throw new l(`Input ${f} has no readable video: ${m.path}`);let g=0;if(e.alignMarker){let b=Le(m.path).find(x=>x.label===e.alignMarker);if(!b)throw new l(`Input ${f} has no marker "${e.alignMarker}".`,"Add one with add_marker, or leave alignMarker out.");g=b.t}let w;if(m.label){let b=pr(m.label);b.warning&&i.push(b.warning);let x=$g(n,`label${f}.txt`);zk(x,m.label),w={textFile:x,fontFile:b.fontFile}}o.push({path:m.path,width:h.width,height:h.height,durationSec:h.durationSec,hasAudio:h.audioCodec!==null,skipSec:g,label:w})}if(e.alignMarker){let f=Math.min(...o.map(m=>m.skipSec));for(let m of o)m.skipSec-=f}let s=e.endWith??"longest",a=e.audio??(o[0].hasAudio?0:"none"),c=(await B(o[0].path)).fps??30,u=z(e.output,"compose",".mp4",{overwrite:e.overwrite}),d=vg(o,u,{layout:e.layout??"side_by_side",endWith:s,audio:a,fps:Math.min(60,Math.round(c))}),p=zu(o,s);return await G(d,{output:u,durationSec:p,extra:r}),v({outputPath:u,durationSec:Number(p.toFixed(2)),layout:e.layout??"side_by_side",...e.alignMarker?{alignedOn:e.alignMarker,skipSec:o.map(f=>Number(f.skipSec.toFixed(3)))}:{},...i.length?{warnings:i}:{}})}catch(o){return _(o)}finally{Uk(n,{recursive:!0,force:!0})}})}import{z as jn}from"zod";import{existsSync as qk,readFileSync as Xk,writeFileSync as Jk}from"node:fs";var Hu=2e3,Yk={input:jn.string().min(1).describe("The .srt to translate (e.g. from transcribe)."),language:jn.string().regex(/^[a-z]{3}$/).optional().describe('With translations: ISO 639-2 code, e.g. "spa".'),translations:jn.array(jn.string().max(Hs)).max(Hu).optional().describe("One translated string per cue, in order. Omit to get the cues to translate."),output:jn.string().optional().describe("Default: <input>.<language>.srt."),overwrite:jn.boolean().optional().describe("Allow replacing an existing output file.")};function Eg(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:Yk,annotations:O},async e=>{try{if(D(e.input,"Subtitle file"),!/\.srt$/i.test(e.input))throw new l("input must be an .srt file.");let r=je(Xk(e.input,"utf8"));if(r.length===0)throw new l(`No cues in ${e.input}.`);if(r.length>Hu)throw new l(`${r.length} cues; at most ${Hu} per file.`);if(!e.translations)return v({input:e.input,count:r.length,cues:r.map((i,s)=>`${s+1}. ${i.text.replace(/\s*\n\s*/g," / ")}`),next:`Translate each cue's text (keep " / " as a line break), then call again with language and translations: ${r.length} strings, in order.`});if(!e.language)throw new l('translations needs language (ISO 639-2, e.g. "spa").');let n=ch(r,e.translations.map(i=>i.replace(/\s+\/\s+/g,`
|
|
350
|
+
`))),o=e.output??uh(e.input,e.language);if(!/\.srt$/i.test(o))throw new l("output must end in .srt.");if(Yt(o),qk(o)){if(!e.overwrite)throw new l(`${o} already exists.`,"Pass overwrite: true to replace it.");ic(o)}return Jk(o,nt(n)),v({outputPath:o,language:e.language,count:n.length})}catch(r){return _(r)}})}import{z as _a}from"zod";import{join as Vk}from"node:path";import{mkdtempSync as Qk,rmSync as Zk}from"node:fs";import{tmpdir as eE}from"node:os";import{z as we}from"zod";var Bn=(t,e)=>{if(!Number.isFinite(t)||t<0)throw new l(`${e} must be a non-negative number.`);return Math.round(t)};function Gu(t){let e=Ai(t.from,t.to);return e?`:enable='${e}'`:""}function _g(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 Tg(t,e){let{length:r,thickness:n,angle:o}=_g(t),i=De(t.color??"red"),s=n*3,a=o.toFixed(6),c=`if(lt(X,W-H),if(lt(abs(Y-H/2),${n}/2),255,0),if(lt(abs(Y-H/2),(W-X)/2),255,0))`;return["-y","-v","error","-f","lavfi","-i",`color=c=${i}:s=${r}x${s}`,"-vf",`format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${c}',rotate=a=${a}:ow=rotw(${a}):oh=roth(${a}):c=none`,"-frames:v","1",..._e(e)]}function Xu(t,e,r,n,o){if(t.length===0)throw new l("Give at least one callout.");let i=[],s=[],a=r;return t.forEach((c,u)=>{let d=`[${o}c${u}]`;if(c.type==="box"){let p=De(c.color??"red"),f=c.fill?"fill":String(Math.max(1,Math.round(c.thickness??4)));s.push(`${a}drawbox=x=${Bn(c.x,"x")}:y=${Bn(c.y,"y")}:w=${Bn(c.width,"width")}:h=${Bn(c.height,"height")}:color=${p}:t=${f}${Gu(c)}${d}`)}else if(c.type==="text"){let p=e.textFiles[u];if(!p)throw new l("Internal: missing text file for a text callout.");let f=De(c.color??"white"),m=Math.max(8,Math.round(c.size??32)),h=c.background===!1?"":`:box=1:boxcolor=black@0.6:boxborderw=${Math.round(m/3)}`;s.push(`${a}drawtext=fontfile=${ve(e.fontFiles?.[u]??e.fontFile)}:textfile=${ve(p)}:expansion=none:x=${Bn(c.x,"x")}:y=${Bn(c.y,"y")}:fontsize=${m}:fontcolor=${f}${h}${Gu(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}=_g(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${Gu(c)}${d}`)}a=d}),{steps:s,out:a,extraInputs:i}}function Ag(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}=Xu(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?",...Te(o),"-c:a","copy",e]}var qu={from:we.number().nonnegative().optional(),to:we.number().positive().optional(),color:we.string().optional()},yr=we.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, ...)."),ka=we.discriminatedUnion("type",[we.object({type:we.literal("box"),x:we.number(),y:we.number(),width:we.number().positive(),height:we.number().positive(),thickness:we.number().positive().optional().describe("Outline px (default 4)."),fill:we.boolean().optional().describe("Fill instead of outline."),...qu}),we.object({type:we.literal("text"),x:we.number(),y:we.number(),text:we.string().min(1),size:we.number().positive().optional().describe("Font size px (default 32)."),background:we.boolean().optional().describe("Dark panel behind the text (default true)."),...qu}),we.object({type:we.literal("arrow"),x1:we.number(),y1:we.number(),x2:we.number().describe("Head (x2,y2) is the point the arrow points at."),y2:we.number(),thickness:we.number().positive().optional().describe("Shaft px (default 8)."),...qu})]);import{join as Rg}from"node:path";import{writeFileSync as Kk}from"node:fs";function Ju(t,e){let r={fontFiles:[],fallbackFonts:[],warnings:[]};return t.forEach((n,o)=>{if(n.type!=="text"){r.fontFiles.push(null);return}let i=pr(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 Ea(t,e,r="",n){let o=Ju(t,n),i=t.map((a,c)=>{if(a.type!=="text")return null;let u=Rg(e,`${r}text_${c}.txt`);return Kk(u,a.text),u}),s=[];for(let[a,c]of t.entries()){if(c.type!=="arrow"){s.push(null);continue}let u=Rg(e,`${r}arrow_${a}.png`);await te(Tg(c,u),3e4),s.push(u)}return{fontFile:Nt("bold"),textFiles:i,arrowFiles:s,...o}}var tE={input:_a.string().min(1).describe("Path to the source video or image (png/jpg; from/to are ignored for an image)."),items:_a.array(ka).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:yr,output:_a.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:_a.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Mg(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:tE,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let n=e.items,{still:o,ext:i}=Mi(e.input,e.output),s=z(e.output,"callout",i,{overwrite:e.overwrite,anyContainer:!0}),a=Qk(Vk(eE(),"screencast-callout-"));try{let c=await Ea(n,a,"",e.fontFile),u=Ag(e.input,s,n,c,void 0,o);return await G(u,{output:s,durationSec:o?null:await ue(e.input),extra:r}),v({outputPath:s,callouts:n.length,...c.fallbackFonts.length>0&&{fallbackFonts:c.fallbackFonts},...c.warnings.length>0&&{warnings:c.warnings}})}finally{Zk(a,{recursive:!0,force:!0})}}catch(n){return _(n)}})}import{z as Vo}from"zod";import{join as hE}from"node:path";import{mkdtempSync as gE,rmSync as bE}from"node:fs";import{tmpdir as wE}from"node:os";import{z as jt}from"zod";import{existsSync as rE,readFileSync as nE,writeFileSync as oE}from"node:fs";import{join as iE}from"node:path";var sE=["bottom","bottom-left","bottom-right","top","top-left","top-right"],Yu=1.2,aE=.5,Cg=8,Pg=100,Ig="Typing\u2026",cE=new Set(["Ctrl","Alt","Shift","Win"]),uE=/^(?:[A-Z0-9]|F\d{1,2}|Enter|Tab|Esc|Space|Backspace|Delete|Insert|Left|Up|Right|Down|Home|End|PageUp|PageDown|[=\-,./`[\];'\\])$/;function lE(t,e="shortcuts"){let r=t.split("+"),n=r.pop();return n===void 0||r.length===0||!uE.test(n)||!r.every(o=>cE.has(o))||new Set(r).size!==r.length?null:[...r,e==="masked"?"\u2026":n].join(" + ")}var pE={left:"Click",right:"Right click",middle:"Middle click",x1:"Back button",x2:"Forward button"},Ta=t=>Math.round(t*1e3)/1e3;function dE(t,e={}){let r=e.lingerSec??Yu;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=lE(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=pE[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<=aE&&Math.abs(a.x-(u.x??a.x))<=Cg&&Math.abs(a.y-(u.y??a.y))<=Cg){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:Ig,base:Ig,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:Ta(a.from),to:Ta(d),label:a.label,kind:a.kind})}),s}function Aa(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>Pg)throw new l(`${e.size} different badges is more than ${Pg}; trim the video or turn off keys or clicks.`);return[...e.values()]}function mE(t,e){return t.flatMap(r=>{let n=e(r.from,r.to);return n&&n[1]-n[0]>=.05?[{...r,from:Ta(n[0]),to:Ta(n[1])}]:[]})}function Fg(t,e){return mE(t,(r,n)=>Dr(r,n,e))}function fE(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 Ku(t,e,r,n,o,i){if(t.length===0)throw new l("No badges to draw.");let s=fE(n.height,r.size),a=Math.round(s/3),c=a+Math.round(s*.6),u=r.position??"bottom",d=u.endsWith("left")?`${c}`:u.endsWith("right")?`w-tw-${c}`:"(w-tw)/2",p=u.startsWith("top")?`${c}`:`h-lh-${c}`,f=De(r.color??"white"),m=[],h=o;return t.forEach((g,w)=>{let b=e.textFiles[g.label];if(!b)throw new l(`Internal: no text file for badge "${g.label}".`);let x=kt(g.windows.map(([S,C])=>`between(t,${S},${C})`)),$=`[${i}k${w}]`;m.push(`${h}drawtext=fontfile=${ve(e.fontFile)}:textfile=${ve(b)}:expansion=none:fontsize=${s}:fontcolor=${f}:box=1:boxcolor=black@0.6:boxborderw=${a}:x=${d}:y=${p}:enable='${x}'${$}`),h=$}),{steps:m,out:h}}function Og(t,e,r,n,o,i,s="standard"){let{steps:a,out:c}=Ku(r,n,o,i,"[0:v]","");return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Te(s),"-c:a","copy",e]}var Ra={events:jt.string().optional(),clicks:jt.boolean().optional(),typing:jt.boolean().optional(),keys:jt.enum(["shortcuts","masked"]).optional(),lingerSec:jt.number().positive().max(10).optional(),position:jt.enum(sE).optional(),size:jt.number().min(8).max(400).optional(),color:jt.string().optional(),fontFile:jt.string().min(1).optional()};function Ma(t,e,r){let n=e??ke(t).jsonl;if(!rE(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=Ue(nE(n,"utf8"));return{badges:dE(o,r),shortcutsLogged:o.filter(i=>i.type==="key").length,path:n}}function Ko(t,e,r="",n){let o=pr(t.join(" "),{weight:"bold",fontFile:n}),i={};return t.forEach((s,a)=>{if(e===null){i[s]=`<badge ${a}>`;return}let c=iE(e,`${r}badge_${a}.txt`);oE(c,s),i[s]=c}),{fontFile:o.fontFile,textFiles:i,...o.fallback&&{fallbackFont:o.fontFile},warnings:o.warning?[o.warning]:[]}}var Sr=Ra,xE={input:Vo.string().min(1).describe("Path to the recording."),events:Sr.events.describe("Event log (default: the input's .events.jsonl)."),clicks:Sr.clicks.describe("Show clicks (default true)."),typing:Sr.typing.describe('Show typing as "Typing\u2026" (default true).'),keys:Sr.keys.describe("shortcuts (default): the chord (Ctrl + S); masked: modifiers only (Ctrl + \u2026)."),lingerSec:Sr.lingerSec.describe(`Seconds a badge stays up (default ${Yu}).`),position:Sr.position.describe("Default bottom (centred)."),size:Sr.size.describe("Font px (default 4.5% of the frame height)."),color:Sr.color.describe("Text color (default white)."),fontFile:yr,dryRun:Vo.boolean().optional().describe("Return the planned badges; write nothing."),output:Vo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Vo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ng(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:xE,outputSchema:L({badges:Vo.number().int()}),annotations:O},async(e,r)=>{try{E(),D(e.input);let n={clicks:e.clicks,typing:e.typing,keys:e.keys,lingerSec:e.lingerSec},{badges:o,shortcutsLogged:i}=Ma(e.input,e.events,n),s=i===0?'The log names no shortcuts (recorded with keys: "masked"), so only clicks and typing can show.':void 0;if(o.length===0)return v({badges:0,note:"Nothing to show: the log has no clicks, shortcuts, or typing; nothing written."});let a=Aa(o);if(e.dryRun){let p=Ko(a.map(f=>f.label),null,"",e.fontFile);return v({dryRun:!0,badges:o.length,plan:o,...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}let c=await B(e.input);if(!c.height)throw new l(`Could not read the size of ${e.input}.`);let u=z(e.output,"keys",ee(e.input),{overwrite:e.overwrite}),d=gE(hE(wE(),"screencast-keys-"));try{let p=Ko(a.map(h=>h.label),d,"",e.fontFile),f={position:e.position,size:e.size,color:e.color},m=Og(e.input,u,a,p,f,{height:c.height});return await G(m,{output:u,durationSec:c.durationSec,extra:r}),v({outputPath:u,badges:o.length,labels:a.map(h=>h.label),...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}finally{bE(d,{recursive:!0,force:!0})}}catch(n){return _(n)}})}import{z as Zo}from"zod";import{join as Bg}from"node:path";import{mkdtempSync as LE,rmSync as WE,writeFileSync as jE}from"node:fs";import{tmpdir as BE}from"node:os";import{z as Un}from"zod";import{existsSync as yE,readFileSync as SE}from"node:fs";var Qo={w:114,h:168,hotX:9,hotY:9,arrowH:135};function Ca(){return yn("cursor","arrow.png")}var vE=.5,Vu=2,Qu=1.5,$E=.4,Dg=240,kE=4,EE=.35,_E=new Set(["move","down","up","wheel"]),zn=t=>Math.round(t*1e3)/1e3;function TE(t){let e=6+(1-t)*34;return{omega:e,lead:Math.min(2/e,.2)}}function AE(t){let e=[],r=$c/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 RE(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 ME(t,e,r,n,o){if(t.length===0)return[];let i=1/Dg,s=0,a=w=>{let b=RE(t,w+r,s);return s=b.i,b},c=a(n),u=c.x,d=c.y,p=0,f=0,m=[{t:zn(n),x:u,y:d}],h=Math.exp(-e*i),g=Math.max(0,Math.ceil((o-n)*Dg));for(let w=1;w<=g;w++){let b=Math.min(o,n+w*i),x=a(b),$=u-x.x,S=d-x.y,C=(p+e*$)*i,I=(f+e*S)*i;p=(p-e*C)*h,f=(f-e*I)*h,u=x.x+($+C)*h,d=x.y+(S+I)*h,(w%kE===0||w===g)&&m.push({t:zn(b),x:u,y:d})}return m}function CE(t,e=EE){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 PE(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 IE(t,e={},r=null){let n=e.smoothing??vE;if(!(n>=0&&n<=1))throw new l("smoothing must be between 0 and 1.");let o=e.hideAfterSec??Vu;if(!(o>=0))throw new l("hideAfterSec must be 0 or more.");let i=t.filter(h=>_E.has(h.type)&&Number.isFinite(h.t)&&h.t>=0&&Number.isFinite(h.x)&&Number.isFinite(h.y)).filter(h=>r===null||h.t<=r).sort((h,g)=>h.t-g.t);if(i.length===0)return{path:[],visible:[],clicks:[]};let s=AE(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=TE(n);d=h.lead;let g=Math.max(0,a-d),w=Math.max(g,r??c+8/h.omega);u=ME(s,h.omega,d,g,w)}let p=Math.max(0,a-d),f=o===0?[[p,r??1/0]]:PE(i.map(h=>[Math.max(0,h.t-d),h.t+o])),m=i.filter(h=>h.type==="down").map(h=>({t:h.t,x:h.x,y:h.y}));return{path:u,visible:f.map(([h,g])=>[zn(h),r!==null?Math.min(g,r):g]).filter(([h,g])=>g>h),clicks:m}}var FE={sx:1,sy:1,ox:0,oy:0};function Pa(t,e=[],r=FE){let n=a=>{let c=es(a.t,e);return c===null?null:{t:zn(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=Dr(a,c,e);return u&&u[1]-u[0]>=.05?[[zn(u[0]),Number.isFinite(u[1])?zn(u[1]):u[1]]]:[]}),s=t.clicks.flatMap(a=>{let c=n(a);return c?[c]:[]});return{path:CE(o),visible:i,clicks:s}}var Ce=(t,e=2)=>{let r=Number(t.toFixed(e));return Object.is(r,-0)?"0":String(r)};function Lg(t,e,r){let n=Number(r.toFixed(3));return n===0?Ce(t):`${Ce(t)}${n<0?"-":"+"}(t-${Ce(e,3)})*${Ce(Math.abs(n),3)}`}function OE(t,e=Qu){if(!(e>=.25&&e<=8))throw new l("size must be between 0.25 and 8.");let r=Math.max(8,t*.025*e),n=r/Qo.arrowH,o=Math.max(12,Math.round(r*2.2));return{spriteW:Math.max(2,Math.round(Qo.w*n)),spriteH:Math.max(2,Math.round(Qo.h*n)),hotX:Qo.hotX*n,hotY:Qo.hotY*n,ripples:[.45,.72,1].map(i=>Math.max(6,Math.round(o*i/2)*2)),spotRadius:Math.max(24,Math.round(t*.12))}}function NE(t){let e=new Map;for(let r of[...t].sort((n,o)=>n.t-o.t)){let n=Ce(Math.max(0,r.t),3),o=e.get(n)??[];o.push(r.text),e.set(n,o)}return[...e.entries()].map(([r,n])=>`${r} ${n.join(", ")};`).join(`
|
|
351
|
+
`)+`
|
|
352
|
+
`}function Wg(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 ${Lg(o.x+r,o.t,c)}, ${e} y ${Lg(o.y+n,o.t,u)}`}})}function DE(t,e){return t.flatMap(([r,n])=>[{t:r,text:`${e} enable 1`},...Number.isFinite(n)?[{t:n,text:`${e} enable 0`}]:[]])}function Zu(t,e,r,n,o,i,s,a){if(t.path.length===0)throw new l("No cursor positions to draw.");let c=OE(r.height,e.size),{width:u,height:d}=r,p=b=>`overlay@${i}c${b}`,f=[],m=[],h=t.path[0],g=`[${i}cm]`;f.push(`${n}sendcmd=f=${ve(a)}${g}`);let w=(b,x,$,S,C)=>{let I=`[${i}c${x}o]`;f.push(`${g}${b}${p(x)}=x=${Ce(h.x+$)}:y=${Ce(h.y+S)}:enable=0${I}`),m.push(...DE(C,p(x))),g=I};if(e.spotlight){let x=Math.ceil(2*u/4),$=Math.ceil(2*d/4),S=c.spotRadius/4,C=S*.8,I=`255*0.55*clip((hypot(X-${Ce(x/2)},Y-${Ce($/2)})-${Ce(S)})/${Ce(C)},0,1)`;f.push(`color=c=black:s=${x}x${$}:r=1:d=1,format=rgba,geq=r=0:g=0:b=0:a='${I}',scale=${2*u}:${2*d}[${i}csm]`);let R=c.spriteW*.25-u,A=c.spriteH*.3-d;w(`[${i}csm]`,"s",R,A,t.visible),m.push(...Wg(t.path,p("s"),R,A))}if(e.clicks!==!1&&t.clicks.length>0){let b=$E/3;c.ripples.forEach((x,$)=>{let S=x/2,C=Math.max(1.5,x*.05),I=`abs(hypot(X-${Ce(S-.5)},Y-${Ce(S-.5)})-${Ce(S-C-1)})`,R=[.9,.65,.4][$],A=`255*lt(${I},${Ce(C*.45)})`;f.push(`color=c=black:s=${x}x${x}:r=1:d=1,format=rgba,geq=r='${A}':g='${A}':b='${A}':a='255*${R}*clip(${Ce(C)}-${I},0,1)'[${i}cr${$}]`);let W=t.clicks.map(Y=>[Y.t+$*b,Y.t+($+1)*b]);w(`[${i}cr${$}]`,`r${$}`,-S,-S,[]);for(let[Y,j]of t.clicks.entries()){let[re,F]=W[Y],oe=W[Y+1];m.push({t:re,text:`${p(`r${$}`)} x ${Ce(j.x-S)}, ${p(`r${$}`)} y ${Ce(j.y-S)}, ${p(`r${$}`)} enable 1`}),(!oe||oe[0]>=F)&&m.push({t:F,text:`${p(`r${$}`)} enable 0`})}})}return f.push(`[${o}:v]scale=${c.spriteW}:${c.spriteH}:flags=lanczos,format=rgba[${i}csp]`),w(`[${i}csp]`,"p",-c.hotX,-c.hotY,t.visible),m.push(...Wg(t.path,p("p"),-c.hotX,-c.hotY)),{steps:f,out:g,extraInputs:["-i",s],commands:NE(m)}}function jg(t,e,r,n,o,i,s,a="standard"){let{steps:c,out:u,extraInputs:d,commands:p}=Zu(r,n,o,"[0:v]",1,"",i,s);return{args:["-y","-i",t,...d,"-filter_complex",c.join(";"),"-map",u,"-map","0:a?",...Te(a),"-c:a","copy",e],commands:p}}var Ia={events:Un.string().optional(),size:Un.number().min(.25).max(8).optional(),smoothing:Un.number().min(0).max(1).optional(),hideAfterSec:Un.number().min(0).max(600).optional(),clicks:Un.boolean().optional(),spotlight:Un.boolean().optional()};function Fa(t,e,r,n){let o=e??ke(t).jsonl;if(!yE(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=IE(Ue(SE(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 Hn=Ia,UE={input:Zo.string().min(1).describe("Path to the recording."),events:Hn.events.describe("Event log (default: the input's .events.jsonl)."),size:Hn.size.describe(`Times a typical cursor's size (default ${Qu}).`),smoothing:Hn.smoothing.describe("0 = as logged, 1 = floaty (default 0.5)."),hideAfterSec:Hn.hideAfterSec.describe(`Hide when the mouse rests this long; 0 = never (default ${Vu}).`),clicks:Hn.clicks.describe("Ripple on clicks (default true)."),spotlight:Hn.spotlight.describe("Dim all but the area around the cursor."),dryRun:Zo.boolean().optional().describe("Return the plan; write nothing."),output:Zo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Zo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ug(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:UE,outputSchema:L({segments:Zo.number().int()}),annotations:O},async(e,r)=>{try{E(),D(e.input);let n=await B(e.input);if(!n.width||!n.height)throw new l(`Could not read the size of ${e.input}.`);let o=Pa(Fa(e.input,e.events,e,n.durationSec)),i={segments:o.path.length,clicks:o.clicks.length,shownSec:Math.round(o.visible.reduce((c,[u,d])=>c+(Math.min(d,n.durationSec??d)-u),0)*10)/10};if(e.dryRun)return v({dryRun:!0,...i,visible:o.visible});let s=z(e.output,"cursor",ee(e.input),{overwrite:e.overwrite}),a=LE(Bg(BE(),"screencast-cursor-"));try{let c=Bg(a,"cursor.cmd"),{args:u,commands:d}=jg(e.input,s,o,{size:e.size,clicks:e.clicks,spotlight:e.spotlight},{width:n.width,height:n.height},Ca(),c);return jE(c,d),await G(u,{output:s,durationSec:n.durationSec,extra:r}),v({outputPath:s,...i})}finally{WE(a,{recursive:!0,force:!0})}}catch(n){return _(n)}})}import{z as Gn}from"zod";import{existsSync as JE}from"node:fs";import{extname as YE}from"node:path";import{z as Bt}from"zod";var Gg={desktop:["#1B2330","#0A0D12"],rec:["#FF4545","#5C0F1A"],amber:["#FFB454","#FF4545"],light:["#F4F7FA","#B9C4D0"]},zE=Object.keys(Gg),HE="desktop",tl=4,GE=.5,zg=t=>2*Math.round(t/2),Oa=t=>2*Math.floor(t/2);function el(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 qE(t,e,r={}){if(!(t>0&&e>0))throw new l("The input has no frame size.");let n=el(r.padding,"padding",2e3),o=el(r.radius,"radius",1e3),i=el(r.shadow,"shadow",200),s,a,c=t,u=e,d,p,f,m=!1;if(r.aspect){let $=Nn[r.aspect];if(!$)throw new l(`Unknown aspect "${r.aspect}".`);s=$.w,a=$.h,f=zg(n??Math.max(s,a)*.06);let S=s-2*f,C=a-2*f;if(S<16||C<16)throw new l(`padding ${f} leaves no room on a ${r.aspect} canvas.`);let I=Math.min(S/t,C/e);c=Math.max(2,Oa(t*I)),u=Math.max(2,Oa(e*I)),m=c!==t||u!==e,d=Oa((s-c)/2),p=Oa((a-u)/2)}else f=zg(n??Math.max(t,e)*.06),s=t+2*f+t%2,a=e+2*f+e%2,d=f,p=f;let h=Math.max(c,u),g=Math.min(o??Math.round(h*.012),Math.floor(Math.min(c,u)/2)),w=i??Math.round(h*.025),b=a-p-u,x=w>0?Math.max(0,Math.min(Math.round(w/2),b)):0;return{canvasW:s,canvasH:a,contentW:c,contentH:u,x:d,y:p,padding:f,radius:g,shadow:w,shadowOffset:x,scaled:m}}function XE(t){if(t.colors!==void 0){if(t.colors.length<1||t.colors.length>tl)throw new l(`colors takes 1 to ${tl} colors.`);return t.colors.map((n,o)=>De(n,`colors[${o}]`))}let e=t.preset??HE,r=Gg[e];if(!r)throw new l(`Unknown backdrop preset "${e}".`);return[...r]}function Hg(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 rl(t,e,r,n,o,i=!1){let s=qE(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??GE,{canvasW:c,canvasH:u,contentW:d,contentH:p,x:f,y:m}=s,h=":r=1:d=1",g=[],w=[],b=`[${o}bg]`;if(t.image)w.push("-i",t.image),g.push(`[${n}:v]scale=${c}:${u}:force_original_aspect_ratio=increase,crop=${c}:${u},setsar=1,trim=end_frame=1,format=rgba${b}`);else{let W=XE(t);if(W.length===1)g.push(`color=c=${W[0]}:s=${c}x${u}${h},format=rgba${b}`);else{let Y=W.map((j,re)=>`c${re}=${j}`).join(":");g.push(`gradients=s=${c}x${u}:${Y}:n=${W.length}:x0=0:y0=0:x1=${c}:y1=${u}:r=1,trim=end_frame=1,format=rgba${b}`)}}let x=b;if(s.shadow>0&&a>0){let W=`[${o}sa]`,Y=`[${o}sc]`,j=`[${o}sh]`,re=`[${o}bs]`,F=s.radius>0?`format=gray,geq=lum='${Hg(s.radius)}'`:"format=gray";g.push(`color=c=white:s=${d}x${p}${h},${F},pad=${c}:${u}:${f}:${m+s.shadowOffset}:color=black,gblur=sigma=${(s.shadow/2).toFixed(2)}${W}`),g.push(`color=c=black:s=${c}x${u}${h}${Y}`),g.push(`${Y}${W}alphamerge,format=rgba,colorchannelmixer=aa=${a}${j}`),g.push(`${x}${j}overlay=0:0:format=rgb${re}`),x=re}let $=`[${o}hole]`,S=`[${o}frame]`,C=s.radius>0?`format=gray,geq=lum='${Hg(s.radius,!0)}'`:"format=gray";g.push(`color=c=black:s=${d}x${p}${h},${C},pad=${c}:${u}:${f}:${m}:color=white${$}`),g.push(`${x}${$}alphamerge,format=rgba${S}`);let I=`[${o}pad]`,R=`[${o}bd]`,A=s.scaled?`scale=${d}:${p},setsar=1,`:"";return g.push(`${r}${A}pad=${c}:${u}:${f}:${m}:color=black${I}`),g.push(`${I}${S}overlay=0:0${i?":format=rgb":""}${R}`),{steps:g,out:R,extraInputs:w,layout:s}}function qg(t,e,r,n,o=!1,i="standard"){let{steps:s,out:a,extraInputs:c,layout:u}=rl(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?",...Te(i),"-c:a","copy","-movflags","+faststart",e],layout:u}}var Na={preset:Bt.enum(zE).optional(),colors:Bt.array(Bt.string()).min(1).max(tl).optional(),image:Bt.string().min(1).optional(),padding:Bt.number().int().nonnegative().max(2e3).optional(),radius:Bt.number().int().nonnegative().max(1e3).optional(),shadow:Bt.number().int().nonnegative().max(200).optional(),shadowOpacity:Bt.number().min(0).max(1).optional(),aspect:Bt.enum(On).optional()};var Xg=/\.(png|jpe?g|bmp|tiff?|webp)$/i,vr=Na,KE={input:Gn.string().min(1).describe("Path to the source video or image (png/jpg)."),preset:vr.preset.describe("Gradient: desktop (default, dark slate), rec (red), amber, light."),colors:vr.colors.describe("Instead: 1 color = solid, 2-4 = diagonal gradient."),image:vr.image.describe("Instead: a wallpaper image, scaled to cover."),padding:vr.padding.describe("px around the content (default 6% of the longer side)."),radius:vr.radius.describe("Corner radius px (default ~1.2% of the longer side; 0 = square)."),shadow:vr.shadow.describe("Shadow blur px (default ~2.5%; 0 = none)."),shadowOpacity:vr.shadowOpacity.describe("Default 0.5."),aspect:vr.aspect.describe("Output on this aspect's canvas (1920x1080, ...), content scaled to fit."),output:Gn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits (screenshots for an image)."),overwrite:Gn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Jg(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:KE,outputSchema:L({outputPath:Gn.string(),width:Gn.number().int(),height:Gn.number().int()}),annotations:O},async(e,r)=>{try{if(E(),D(e.input),e.image&&!JE(e.image))throw new l(`Background image not found: ${e.image}`);let n=Xg.test(e.input);if(n&&e.output&&!Xg.test(e.output))throw new l("An image input writes an image: give the output a .png or .jpg extension.");n||Fr(e.output);let o=await B(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)?YE(e.input).toLowerCase():".png":ee(e.input),s=Kt(e.output,be(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}=qg(e.input,s,a,{width:o.width,height:o.height},n);return await G(c,{output:s,durationSec:n?null:o.durationSec,extra:r}),v({outputPath:s,width:u.canvasW,height:u.canvasH,content:{x:u.x,y:u.y,width:u.contentW,height:u.contentH},padding:u.padding,radius:u.radius,shadow:u.shadow,background:e.image?"image":e.colors?"colors":e.preset??"desktop"})}catch(n){return _(n)}})}import{z as ei}from"zod";var VE={input:ei.string().min(1).describe("Path to the source video."),level:ei.enum(["light","medium","heavy"]).optional().describe("CRF 23 / 28 / 32 (default medium)."),maxWidth:ei.number().int().positive().optional().describe("Width cap in px (only downscales)."),output:ei.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ei.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Yg(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:VE,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let n=ee(e.input),o=z(e.output,"compress",n,{overwrite:e.overwrite}),i=up(e.input,o,{level:e.level,maxWidth:e.maxWidth});return await G(i,{output:o,durationSec:await ue(e.input),extra:r}),v({outputPath:o,level:e.level??"medium"})}catch(n){return _(n)}})}import{z as Da}from"zod";var QE={mp3:"mp3",aac:"m4a",wav:"wav"},ZE={input:Da.string().min(1).describe("Path to the source media."),format:Da.enum(["mp3","aac","wav","copy"]).describe("Audio output codec. copy keeps the source codec without re-encoding."),output:Da.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Da.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Kg(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:ZE,outputSchema:Q,annotations:O},async(e,r)=>{try{let{ffprobe:n}=E();D(e.input);let o=e.format,i=null,s;if(o==="copy"){let c=await se(n,Ir(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=Pr(JSON.parse(c.stdout)).audioCodec,!i)throw new l(`Input has no audio stream to extract: ${e.input}`);s=lp(i)}else s=QE[o];let a=z(e.output,"audio",`.${s}`,{overwrite:e.overwrite,anyContainer:!0});return await G(pp(e.input,a,o),{output:a,durationSec:await ue(e.input),extra:r}),v({outputPath:a,format:o,...i?{sourceAudioCodec:i}:{}})}catch(n){return _(n)}})}import{z as al}from"zod";import{extname as e_}from"node:path";import{z as nl}from"zod";var t_=["youtube","podcast","broadcast"],La=nl.union([nl.enum(t_),nl.number().min(-70).max(-5)]),Vg={youtube:{i:-14,tp:-1,lra:11},podcast:{i:-16,tp:-1.5,lra:11},broadcast:{i:-23,tp:-1,lra:7}};function qn(t){if(t===void 0)return Vg.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=Vg[t];if(!e)throw new l(`Unknown loudness target "${t}".`);return e}var ol=t=>`I=${t.i}:TP=${t.tp}:LRA=${t.lra}`;function ti(t,e){return["-hide_banner","-nostats","-i",t,"-vn","-af",`loudnorm=${ol(e)}:print_format=json`,"-f","null","-"]}function ri(t){let r=t.match(/\{[^{}]*"input_i"[^{}]*\}/g)?.at(-1);if(r===void 0)throw new l("Could not measure loudness (no loudnorm report). Does the file have audio?");let n=JSON.parse(r),o=s=>Number(n[s]),i={input_i:o("input_i"),input_tp:o("input_tp"),input_lra:o("input_lra"),input_thresh:o("input_thresh"),target_offset:o("target_offset"),...n.output_i!==void 0?{output_i:o("output_i")}:{}};if(!Number.isFinite(i.input_i))throw new l("The audio is silent (loudness is -inf), so there is nothing to normalize.");return i}function Qg(t){return Ti(t)?["-map","0:a:0","-vn"]:["-map","0:v?","-map","0:a:0","-c:v","copy"]}function Wa(t){switch(e_(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 il(t,e){if(!e)return`loudnorm=${ol(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=${ol(t)}:${r}:linear=true`}function Zg(t,e,r,n){return["-y","-hide_banner","-i",t,...Qg(e),"-af",`${il(r,n)}:print_format=json`,"-ar","48000",...Wa(e),e]}var ja=["light","medium","strong"],r_={light:6,medium:12,strong:20};function Ba(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 Ua(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 n_(t){return t===null?-50:Math.max(-80,Math.min(-20,Math.round(t+5)))}function sl(t,e){let r=r_[t];if(r===void 0)throw new l(`Unknown denoise strength "${t}".`);return`afftdn=nr=${r}:nf=${n_(e)}`}function eb(t,e,r="medium",n=null){return["-y","-i",t,...Qg(e),"-af",sl(r,n),...Wa(e),e]}var o_={input:al.string().min(1).describe("Path to the source video or audio file."),target:La.optional().describe("youtube (-14 LUFS, default), podcast (-16), broadcast (-23), or a LUFS number (-70 to -5)."),output:al.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:al.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function tb(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:o_,outputSchema:Q,annotations:O},async(e,r)=>{try{let{ffmpeg:n}=E();D(e.input);let o=await B(e.input);if(!o.audioCodec)throw new l(`Input has no audio stream: ${e.input}`);let i=qn(e.target),s=ee(e.input,{audio:!0}),a=z(e.output,"loudnorm",s,{overwrite:e.overwrite}),c=le(o.durationSec),u=await se(n,ti(e.input,i),c,{signal:r.signal}),d=ri(u.stderr);await G(Zg(e.input,a,i,d),{output:a,durationSec:o.durationSec,extra:r});let p=ri((await se(n,ti(a,i),c,{signal:r.signal})).stderr);return v({outputPath:a,target:{lufs:i.i,truePeakDb:i.tp,lra:i.lra},before:{lufs:d.input_i,truePeakDb:d.input_tp},after:{lufs:p.input_i,truePeakDb:p.input_tp}})}catch(n){return _(n)}})}import{z as za}from"zod";var i_={input:za.string().min(1).describe("Path to the source video or audio file."),strength:za.enum(ja).optional().describe("How hard to reduce noise: light (6 dB), medium (12 dB, default), strong (20 dB)."),output:za.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:za.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function rb(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:i_,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let n=await B(e.input);if(!n.audioCodec)throw new l(`Input has no audio stream: ${e.input}`);let o=e.strength??"medium",i=ee(e.input,{audio:!0}),s=z(e.output,"denoise",i,{overwrite:e.overwrite}),a=await se(E().ffmpeg,Ba(e.input),le(n.durationSec),{signal:r.signal}),c=Ua(a.stdout);return await G(eb(e.input,s,o,c),{output:s,durationSec:n.durationSec,extra:r}),v({outputPath:s,strength:o,noiseFloorDb:c===null?null:Number(c.toFixed(1)),note:"Works best on steady noise (fans, hum, hiss); it does little for intermittent sounds."})}catch(n){return _(n)}})}import{z as Ut}from"zod";import{existsSync as s_,readFileSync as a_,rmSync as c_,writeFileSync as u_}from"node:fs";var l_={input:Ut.string().min(1).describe("Path to the video or audio to transcribe."),model:Ut.string().optional().describe(`Path to a whisper.cpp model file (ggml-*.bin). Defaults to ${Gs}.`),language:Ut.string().optional().describe("Spoken language code, e.g. 'en', or 'auto' (default)."),words:Ut.boolean().optional().describe("One word per cue, for word timing (cut_by_transcript)."),output:Ut.string().optional().describe("Optional output .srt path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ut.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function nb(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:l_,outputSchema:L({srtPath:Ut.string(),cues:Ut.number().int(),text:Ut.string()}),annotations:O},async(e,r)=>{try{if(E(),D(e.input),!Ye("whisper"))throw new l("This ffmpeg has no whisper filter.","transcribe needs FFmpeg 8 built with whisper.cpp (--enable-whisper); recent Windows builds such as `winget install Gyan.FFmpeg` include it. Check with `ffmpeg -h filter=whisper`.");let n=hr(e.model),o=await B(e.input);if(!o.audioCodec)throw new l(`Input has no audio to transcribe: ${e.input}`);let i=z(e.output,"captions",".srt",{overwrite:e.overwrite,anyContainer:!0}),s=Be(".srt");try{await te(Pn(e.input,n,s,e.language??"auto",e.words),le(o.durationSec),{signal:r.signal});let a=s_(s)?pt(sh(je(a_(s,"utf8")))):[];u_(i,nt(a));let c=a.map(u=>u.text.replace(/\n/g," ")).join(" ");return v({srtPath:i,cues:a.length,text:c.length>4e3?`${c.slice(0,4e3)}\u2026`:c,...a.length===0?{note:"No speech was recognised."}:{}})}finally{c_(s,{force:!0})}}catch(n){return _(n)}})}import{z as ni}from"zod";import{dirname as p_}from"node:path";import{existsSync as d_}from"node:fs";var m_={input:ni.string().min(1).describe("Path to the source video."),subtitles:ni.string().min(1).describe("Path to an .srt (e.g. from transcribe) or .ass subtitle file."),style:ni.enum(qs).optional().describe("clean (default for .srt): outlined line. social: big bold text on a dark box. .ass keeps its own styling unless set."),output:ni.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ni.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function ob(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:m_,outputSchema:Q,annotations:O},async(e,r)=>{try{E();for(let a of[e.input,e.subtitles])if(!d_(a))throw new l(`File not found: ${a}`);if(!Ye("subtitles"))throw new l("This ffmpeg has no subtitles filter (it needs libass).","Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");let n=ee(e.input),o=z(e.output,"subtitled",n,{overwrite:e.overwrite}),i=p_(Nt("regular")),s=e.style??(/\.(ass|ssa)$/i.test(e.subtitles)?null:"clean");return await G(ah(e.input,e.subtitles,o,i,s),{output:o,durationSec:(await B(e.input)).durationSec,extra:r}),v({outputPath:o,style:s??"file"})}catch(n){return _(n)}})}import{z as Et}from"zod";var f_={input:Et.string().min(1).describe("Path to the source video."),segments:Et.array(Et.object({start:Et.number().nonnegative(),end:Et.number().positive()})).min(1).describe("{start, end} segments in seconds; each becomes its own file."),output:Et.string().optional().describe("Optional output path. Only honored for a single segment; multi-segment output lands under SCREENCAST_HOME/edits."),overwrite:Et.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function ib(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:f_,outputSchema:L({outputs:Et.array(Et.string()),count:Et.number().int()}),annotations:O},async(e,r)=>{try{E(),D(e.input),Fr(e.output);let n=ee(e.input),o=e.segments.length===1,i=[];for(let[s,a]of e.segments.entries()){let c=z(o?e.output:void 0,"clip",`-${String(s).padStart(2,"0")}${n}`,{overwrite:e.overwrite});await G(dp(e.input,c,a),{output:c,durationSec:a.end-a.start,extra:r}),i.push(c)}return v({outputs:i,count:i.length})}catch(n){return _(n)}})}import{z as zt}from"zod";var h_={input:zt.string().min(1).describe("Path to the source video."),minIdleSec:zt.number().positive().optional().describe(`Only cut still stretches at least this long (default ${qr}).`),keepSec:zt.number().min(0).optional().describe(`Seconds kept at each edge of a cut (default ${Xo}).`),useAudio:zt.boolean().optional().describe("Require silent audio too (default true when there is audio)."),action:zt.enum(["cut","speed"]).optional().describe("cut (default), or speed: fast-forward them."),factor:zt.number().gt(1).max(Gr).optional().describe(`speed: times faster (default ${Jo}).`),dryRun:zt.boolean().optional().describe("Only report what would be cut."),output:zt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:zt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function sb(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:h_,annotations:O},async(e,r)=>{try{let{ffmpeg:n}=E();D(e.input);let o=await B(e.input),i=o.durationSec;if(i===null)throw new l(`Could not read duration of ${e.input}.`);let s=e.minIdleSec??qr,a=e.keepSec??Xo,c=o.audioCodec!==null,u=(e.useAudio??!0)&&c,d=await se(n,da(e.input,s,u),le(i),{signal:r.signal});if(d.code!==0)throw new l(`Idle scan failed (exit ${d.code}): ${d.stderr.trim().slice(-400)}`);let p=ma(d.stderr,i),f=u?ha(p,fa(d.stderr,i)):p,m=ga(f,s,a),h=e.action==="speed",g=e.factor??Jo,w=m.map(I=>({...I,factor:g})),b=Number((h?Xr(w):m.reduce((I,R)=>I+(R.end-R.start),0)).toFixed(2)),x={cuts:m,...h?{action:"speed",factor:g}:{},removedSec:b,originalSec:Number(i.toFixed(2)),newDurationSec:Number((i-b).toFixed(2)),idleRule:u?"frozen video and silent audio":"frozen video"};if(e.dryRun||m.length===0)return v({...x,...m.length===0?{note:"No idle stretches found; nothing to cut."}:{dryRun:!0}});let $=ee(e.input),S=z(e.output,"trimmed-idle",$,{overwrite:e.overwrite}),C=h?ya(e.input,S,w,{withAudio:c,fps:o.fps}):Sa(e.input,S,m,c);return await G(C,{output:S,durationSec:i-b,inputDurationSec:i,extra:r}),v({outputPath:S,...x})}catch(n){return _(n)}})}import{z as Qe}from"zod";import{existsSync as mb,readFileSync as v_,writeFileSync as $_}from"node:fs";var g_=["um","umm","uh","uhh","uhm","erm","er","ah","hmm","hm","mm","mhm"],ab=.5,ub=t=>t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),$r=t=>Number(t.toFixed(3));function lb(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:ub(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 b_=t=>t.flatMap((e,r)=>e.norm?[r]:[]);function w_(t,e){let r=e.split(/\s+/).map(ub).filter(Boolean);if(r.length===0)throw new l(`Quote "${e}" has no words to match.`);let n=b_(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 x_(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:$r(o.start),end:$r(i.end),text:t.slice(e,n+1).map(s=>s.raw).join(" "),exact:o.first&&i.last}}function y_(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 S_(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 pb(t,e){let r=lb(t),n=[];for(let i of e.remove??[]){if(typeof i=="number"){let a=S_(t,i);n.push({start:$r(a.start),end:$r(a.end),text:a.text.replace(/\s+/g," "),exact:!0});continue}let s=w_(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(x_(r,...s[0]))}let o=0;if(e.fillers){let i=new Set(g_);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-ab),d=Math.min(t[s.cue+1]?.start??1/0,c.end+ab);n.push({start:$r(Math.min(u,c.start)),end:$r(Math.max(d,c.end)),text:r.filter(p=>p.cue===s.cue).map(p=>p.raw).join(" "),exact:!0})})}return{cuts:y_(n),skippedFillers:o}}function cb(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 db(t,e){let r=lb(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=$r(cb(i.start,e)),p=$r(cb(i.end,e));p>d&&o.push({start:d,end:p,text:u})}),o}var k_={input:Qe.string().min(1).describe("Path to the source video."),srt:Qe.string().min(1).describe("Its .srt (transcribe; words: true for word timing)."),remove:Qe.array(Qe.union([Qe.number().int().min(0).max(99999),Qe.string().min(1)])).optional().describe("Cue numbers as the .srt numbers them, or transcript text quoted exactly (must occur once)."),fillers:Qe.boolean().optional().describe("Also cut fillers (um, uh...) that have their own cue."),dryRun:Qe.boolean().optional().describe("Only report the cuts."),output:Qe.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qe.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function fb(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:k_,outputSchema:L({cuts:Qe.array(Qe.unknown()),removedSec:Qe.number()}),annotations:O},async(e,r)=>{try{E();for(let g of[e.input,e.srt])if(!mb(g))throw new l(`File not found: ${g}`);if(!e.remove?.length&&!e.fillers)throw new l("Nothing to cut: pass remove and/or fillers: true.");let n=await B(e.input),o=n.durationSec;if(o===null||!n.videoCodec)throw new l(`Not a readable video: ${e.input}`);let i=pt(je(v_(e.srt,"utf8"),{index:!0}));if(i.length===0)throw new l(`No cues in ${e.srt}.`);let{cuts:s,skippedFillers:a}=pb(i,{remove:e.remove,fillers:e.fillers});if(s.length>Wn)throw new l(`Too many cuts (${s.length}, max ${Wn}); cut in batches.`);let c=Number(s.reduce((g,w)=>g+Math.min(w.end,o)-Math.min(w.start,o),0).toFixed(2)),u=db(i,s),d=[s.length===0&&"Nothing matched; nothing to cut.",a>0&&`${a} filler(s) inside longer cues were kept; transcribe with words: true to cut them.`,s.some(g=>!g.exact)&&"Some edges were estimated inside a cue; transcribe with words: true for word timing."].filter(Boolean),p={cuts:s,removedSec:c,originalSec:Number(o.toFixed(2)),newDurationSec:Number((o-c).toFixed(2)),...d.length?{note:d.join(" ")}:{}};if(e.dryRun||s.length===0){let g=u.map(w=>w.text.replace(/\n/g," ")).join(" ");return v({...p,...s.length?{dryRun:!0}:{},text:g.length>4e3?`${g.slice(0,4e3)}\u2026`:g})}let f=ee(e.input),m=z(e.output,"cut-transcript",f,{overwrite:e.overwrite}),h=m.replace(/\.[^.\\/]+$/,"")+".srt";if(!e.overwrite&&mb(h))throw new l(`Output already exists: ${h}. Pass overwrite: true to replace it.`);return await G(Sa(e.input,m,s,n.audioCodec!==null),{output:m,durationSec:o-c,inputDurationSec:o,extra:r}),$_(h,nt(u)),v({outputPath:m,srtPath:h,...p})}catch(n){return _(n)}})}import{z as Jr}from"zod";var E_={input:Jr.string().min(1).describe("Path to the source video or image (png/jpg; time ranges are ignored for an image)."),regions:Jr.array(pn).min(1).describe("Pixel rectangles (x, y, width, height), each optionally limited to start..end seconds."),style:Jr.enum(Ri).optional().describe("box (default): irreversible fill; blur/pixelate are partially recoverable."),pad:Jr.number().int().nonnegative().optional().describe("Grow each region by this many px (default 0)."),color:Jr.string().optional().describe("Box fill color (default black)."),output:Jr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Jr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function hb(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:E_,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let{width:n,height:o,durationSec:i}=await B(e.input),{still:s,ext:a}=Mi(e.input,e.output),c=z(e.output,"redact",a,{overwrite:e.overwrite,anyContainer:!0}),u=mp(e.input,c,e.regions,{style:e.style,pad:e.pad,color:e.color},{width:n,height:o},s);return await G(u,{output:c,durationSec:s?null:i,extra:r}),v({outputPath:c,regions:e.regions.length,style:e.style??"box"})}catch(n){return _(n)}})}import{z as Ha}from"zod";function gb(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:L({devices:Ha.array(Ha.unknown()),loopbackDevice:Ha.string().nullable(),note:Ha.string()}),annotations:fe},async()=>{try{E();let e=await Xc(!0),r=qc(e);return v({devices:e,loopbackDevice:r,note:r?`Pass "${r}" as the audio device to capture system audio.`:`No loopback device detected. ${_o}`})}catch(e){return _(e)}})}import{z as me}from"zod";function wb(t){return t.hwnd!==void 0?`window:hwnd=${t.hwnd}`:`window:${t.title}`}function __(t){let e=/^.*?[.!?](?=\s|$)/.exec(t);return e?e[0]:t}function bb(t,e,r){try{return Hc(t,wb(e).slice(7),{allowCloaked:r,exactOnly:!0}),{ok:!0}}catch(n){return{ok:!1,reason:__(H(n))}}}function xb(t,e,r){let n=r.filter??{},o=n.exe?zc(`exe=${n.exe}`):null,i=o?.kind==="exe"?o.exe:null,s=n.titleContains?.trim().toLowerCase()||null,a=co(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=bb(e,d,!1),f=r.wgcAvailable&&d.hwnd!==void 0?bb(e,d,!0):{ok:!1};n.capturableOnly&&!p.ok&&!f.ok||u.push({target:wb(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 T_={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.")},cl=me.object({x:me.number(),y:me.number(),width:me.number(),height:me.number()}),A_=L({full:me.looseObject({target:me.literal("full"),bounds:cl}),monitors:me.array(me.looseObject({target:me.string(),index:me.number(),primary:me.boolean(),bounds:cl,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:cl,minimized:me.boolean(),cloaked:me.boolean(),capturable:me.boolean(),wgcCapturable:me.boolean()})),wgcAvailable:me.boolean(),note:me.string()});function yb(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:T_,outputSchema:A_,annotations:fe},async e=>{try{let[r,n]=await Promise.all([or(),Gc()]),o=xb(r,n,{wgcAvailable:tr(),filter:{exe:e.exe,titleContains:e.titleContains,capturableOnly:e.capturableOnly}});return v({...o,note:'Pass a target string unchanged. A window handle lasts until the app closes the window; list again after an app restarts, or target it by window:exe=<app.exe>. A window with capturable false but wgcCapturable true needs backend: "wgc".'})}catch(r){return _(r)}})}import{existsSync as ul}from"node:fs";import{join as ll}from"node:path";import{z as pe}from"zod";var Sb=200,vb=1e3,Ga=.5,qa=3,Yr=t=>Math.round(t*1e3)/1e3;function kb(t,e){if(t.length===0)throw new l("lines is empty: give at least one { t | marker, text }.");if(t.length>Sb)throw new l(`At most ${Sb} 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>vb)throw new l(`lines[${o}] is ${i.length} characters; at most ${vb} 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:Yr(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:Yr(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 Eb(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 (${Yr(e)}s) and is not heard.`):s&&i>s.t+.05?r.push(`Line at ${n.t}s ${a} runs ${Yr(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 ${Yr(i-e)}s past the end of the video and is cut off.`)}),r}function _b(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:Yr(i),text:r.text}}).filter(r=>r.end>r.start)}function Tb(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 Ab(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=Yr(o),a=h=>`amix=inputs=${h}:duration=longest:dropout_transition=0:normalize=0`,c=n.map((h,g)=>{let w=Math.round(h.t*1e3);return`[${g+1}:a]aresample=48000,aformat=channel_layouts=mono,adelay=${w}[l${g}]`}),u=n.map((h,g)=>`[l${g}]`).join(""),d=!(i.hasAudio&&i.channels===1),p=`apad,atrim=end=${s}${d?",pan=stereo|c0=c0|c1=c0":""}`,f=i.hasAudio?"voice":"aout";c.push(n.length>1?`${u}${a(n.length)},${p}[${f}]`:`[l0]${p}[${f}]`),i.hasAudio&&(c.push(`[0:a]aresample=48000,aformat=channel_layouts=${d?"stereo":"mono"}[orig]`),i.duck??!0?(c.push("[voice]asplit=2[vo][key]"),c.push("[orig][key]sidechaincompress=threshold=0.02:ratio=8:attack=20:release=400[bed]"),c.push(`[bed][vo]${a(2)}[aout]`)):c.push(`[orig][voice]${a(2)}[aout]`));let m=Ti(r);return["-y","-i",t,...e.flatMap(h=>["-i",h]),"-filter_complex",c.join(";"),...m?[]:["-map","0:v?","-c:v","copy"],"-map","[aout]","-t",String(s),...Wa(r),.../\.(mp4|mov|m4a)$/i.test(r)?["-movflags","+faststart"]:[],r]}var R_=3e4,M_=1e4,$b=3e4,Rb=t=>Array.isArray(t)?t:t==null?[]:[t];function Mb(t){return Rb(t.voices).map(e=>({name:String(e.name??""),language:String(e.language??""),gender:String(e.gender??"")}))}function C_(t){return{script:I_,payload:JSON.stringify(t)}}async function Cb(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}=C_(t),i="list"in t,s=await at(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: ${H(a)}`)}}async function P_(t){let e=await Cb({list:!0},nr(15e3),t);if(e.error)throw new l(`Windows speech is unavailable: ${e.error}`);return Mb(e)}async function Pb(){if(process.platform!=="win32")return{available:!1,voices:[],error:"Windows speech is available on Windows only."};try{let t=(await P_()).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:H(t)}}}async function Ib(t,e){let r=e.rate??1;if(!Number.isFinite(r)||r<Ga||r>qa)throw new l(`rate must be between ${Ga} and ${qa} (1 is normal speed).`);let n=await Cb({voice:e.voice??null,rate:r,items:t},nr(R_+t.length*M_),e.signal);if(n.error){let o=Mb(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 Rb(n.results).forEach((o,i)=>{if(o.error)throw new l(`Could not synthesize line ${i+1}: ${o.error}`)}),String(n.voice??"")}var I_=`
|
|
353
|
+
$ErrorActionPreference = 'Stop'
|
|
354
|
+
function Out($o) { ConvertTo-Json -InputObject $o -Depth 5 -Compress }
|
|
355
|
+
try {
|
|
356
|
+
Add-Type -AssemblyName System.Runtime.WindowsRuntime
|
|
357
|
+
$null = [Windows.Media.SpeechSynthesis.SpeechSynthesizer, Windows.Media, ContentType = WindowsRuntime]
|
|
358
|
+
$req = $Payload | ConvertFrom-Json
|
|
359
|
+
$all = @([Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices)
|
|
360
|
+
$voices = @($all | ForEach-Object { [pscustomobject]@{ name = $_.DisplayName; language = $_.Language; gender = [string]$_.Gender } })
|
|
361
|
+
if ($req.list) { Out ([pscustomobject]@{ voices = $voices }); return }
|
|
362
|
+
if ($all.Count -eq 0) { Out ([pscustomobject]@{ error = 'No speech voices are installed.'; voices = $voices }); return }
|
|
363
|
+
$synth = New-Object Windows.Media.SpeechSynthesis.SpeechSynthesizer
|
|
364
|
+
if ($req.voice) {
|
|
365
|
+
$want = [string]$req.voice
|
|
366
|
+
$v = $all | Where-Object { $_.DisplayName -eq $want -or $_.Id -eq $want } | Select-Object -First 1
|
|
367
|
+
if (-not $v) { $v = $all | Where-Object { $_.DisplayName.IndexOf($want, [StringComparison]::OrdinalIgnoreCase) -ge 0 } | Select-Object -First 1 }
|
|
368
|
+
if (-not $v) { Out ([pscustomobject]@{ error = 'unknown voice'; voices = $voices }); return }
|
|
369
|
+
$synth.Voice = $v
|
|
370
|
+
}
|
|
371
|
+
$synth.Options.SpeakingRate = [double]$req.rate
|
|
372
|
+
$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
|
|
373
|
+
$results = foreach ($item in @($req.items)) {
|
|
374
|
+
try {
|
|
375
|
+
$task = $asTask.MakeGenericMethod([Windows.Media.SpeechSynthesis.SpeechSynthesisStream]).Invoke($null, @($synth.SynthesizeTextToStreamAsync([string]$item.text)))
|
|
376
|
+
if (-not $task.Wait(${$b})) { throw "The speech engine did not answer within ${$b/1e3} s." }
|
|
377
|
+
$stream = $task.Result
|
|
378
|
+
$in = [System.IO.WindowsRuntimeStreamExtensions]::AsStreamForRead($stream)
|
|
379
|
+
$fs = [System.IO.File]::Create([string]$item.path)
|
|
380
|
+
try { $in.CopyTo($fs) } finally { $fs.Dispose(); $in.Dispose(); $stream.Dispose() }
|
|
381
|
+
[pscustomobject]@{ ok = $true }
|
|
382
|
+
} catch { [pscustomobject]@{ error = $_.Exception.Message } }
|
|
383
|
+
}
|
|
384
|
+
Out ([pscustomobject]@{ voice = $synth.Voice.DisplayName; results = @($results) })
|
|
385
|
+
} catch { Out ([pscustomobject]@{ error = $_.Exception.Message }) }
|
|
386
|
+
`;var F_=wt(),Fb=pe.looseObject({found:pe.boolean(),path:pe.string().nullable(),version:pe.string().nullable(),major:pe.number().nullable()}),O_=L({ok:pe.boolean(),problems:pe.array(pe.string()),server:pe.looseObject({version:pe.string(),node:pe.string(),platform:pe.string(),arch:pe.string()}),ffmpeg:Fb.extend({meetsFfmpeg8:pe.boolean().nullable()}),ffprobe:Fb,filters:pe.record(pe.string(),pe.boolean()),devices:pe.looseObject({gdigrab:pe.boolean(),dshow:pe.boolean()}),wgc:pe.looseObject({available:pe.boolean()}),ocr:pe.looseObject({available:pe.boolean(),language:pe.string().nullable(),languages:pe.array(pe.string())}),storage:pe.looseObject({home:pe.string(),homeExists:pe.boolean()}),env:pe.record(pe.string(),pe.string().nullable())});function N_(t){let e=_(t).content[0];return e?.type==="text"?e.text.replace(/\s*\n+\s*/g," "):String(t)}function Ob(t){let e=oa(t),r=na(e??"");return{found:e!==null,path:e!==null?Hh(t):null,version:r.version,major:r.major,...r.inferred?{majorInferred:!0}:{}}}function Nb(t){t.registerTool("doctor",{title:"Check Setup",description:`Check the setup: ffmpeg/ffprobe (FFmpeg ${Br}+?), 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:O_,annotations:fe},async()=>{try{let e=[],r=null;try{r=gc()}catch(g){e.push(N_(g))}let n=Ob(r?.ffmpeg??(process.env.FFMPEG_PATH?.trim()||"ffmpeg")),o=Ob(r?.ffprobe??(process.env.FFPROBE_PATH?.trim()||"ffprobe")),i=n.major===null?null:n.major>=Br;r&&i===!1&&e.push(`FFmpeg ${n.version} is older than ${Br}: transcribe and backend "wgc" need FFmpeg ${Br}+. Windows: \`winget install Gyan.FFmpeg\`.`);let s={},a={gdigrab:!1,dshow:!1};if(r){for(let w of qh)s[w.filter]=w.filter==="gfxcapture"?tr():Ye(w.filter),!s[w.filter]&&!(w.filter==="gfxcapture"&&process.platform!=="win32")&&e.push(`No ${w.filter} filter: ${w.tools} unavailable (needs ${w.why}).`);let g=Uh(zh(r.ffmpeg)??"");a={gdigrab:g.includes("gdigrab"),dshow:g.includes("dshow")},process.platform==="win32"&&!a.gdigrab&&e.push("This ffmpeg has no gdigrab device: screenshot and start_recording cannot capture the screen.")}process.platform!=="win32"&&e.push("Not Windows: capture (screenshot, start_recording, list_targets) and OCR are unavailable; the watch and edit tools work.");let c=r?{ddagrab:process.platform==="win32"&&Ye("ddagrab"),encoders:await Mc(r.ffmpeg)}:null,[u,d]=await Promise.all([gr(),Pb()]);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=Gh(),f=p.SCREENCAST_WHISPER_MODEL;f&&!ul(f)&&e.push(`SCREENCAST_WHISPER_MODEL points at a missing file: ${f}`);let m=Fe();for(let g of io())ul(g)||e.push(`SCREENCAST_ALLOWED_DIRS names a missing folder: ${g}`);let h=mi(p.SCREENCAST_TOOLSETS??void 0);return h.unknown.length>0&&e.push(`SCREENCAST_TOOLSETS names unknown toolsets (ignored): ${h.unknown.join(", ")}.`),v({ok:e.length===0,problems:e,server:{version:F_,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:ul(m),recordings:ll(m,"recordings"),screenshots:ll(m,"screenshots"),edits:ll(m,"edits"),allowedOutputDirs:Rr()},env:p,toolsets:{enabled:h.enabled,available:["all",...di]}})}catch(e){return _(e)}})}import{z as Xn}from"zod";var D_={inputA:Xn.string().min(1).describe("Outgoing video."),inputB:Xn.string().min(1).describe("Incoming video."),transition:Xn.string().optional().describe("xfade name (default fade): fade, wipeleft, slideup, circleopen, dissolve, ..."),duration:Xn.number().positive().optional().describe(`Transition length in seconds (default ${Fn}).`),output:Xn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Xn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Db(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:D_,outputSchema:Q,annotations:O},async(e,r)=>{try{E();for(let p of[e.inputA,e.inputB])D(p);let[n,o]=await Promise.all([B(e.inputA),B(e.inputB)]),i=zr(n),s=zr(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=z(e.output,"xfade",".mp4",{overwrite:e.overwrite}),d=rg(e.inputA,e.inputB,[i,s],u,{transition:e.transition,duration:e.duration},a);return await G(d,{output:u,durationSec:i+s,extra:r}),v({outputPath:u,audio:c})}catch(n){return _(n)}})}import{z as Ht}from"zod";var L_={clips:Ht.array(Ht.string().min(1)).min(2).describe("Clip paths, in order."),transition:Ht.string().optional().describe("cut (default) or an xfade name (fade, wipeleft, slideup, ...)."),duration:Ht.number().positive().optional().describe(`Transition seconds (default ${Fn}).`),width:Ht.number().int().positive().optional().describe("Common output width (default 1920)."),height:Ht.number().int().positive().optional().describe("Common output height (default 1080)."),fps:Ht.number().int().positive().optional().describe("Common output fps (default 30)."),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 Lb(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:L_,outputSchema:Q,annotations:O},async(e,r)=>{try{E();for(let c of e.clips)D(c);let n=await Promise.all(e.clips.map(c=>B(c))),o=n.map(c=>zr(c)??0),i=n.map(c=>c.audioCodec!==null),s=z(e.output,"highlights",".mp4",{overwrite:e.overwrite}),a=Go(e.clips,o,s,{transition:e.transition,duration:e.duration,width:e.width,height:e.height,fps:e.fps},i);return await G(a,{output:s,durationSec:o.reduce((c,u)=>c+u,0)||null,extra:r}),v({outputPath:s,clips:e.clips.length,transition:e.transition??"cut",audio:i.some(Boolean)})}catch(n){return _(n)}})}import{z as ht}from"zod";import{writeFileSync as W_,rmSync as j_}from"node:fs";var B_={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:yr,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 Wb(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:B_,outputSchema:Q,annotations:O},async(e,r)=>{try{E();let n=z(e.output,"title",".mp4",{overwrite:e.overwrite}),o=pr(e.text,{weight:e.bold===!1?"regular":"bold",fontFile:e.fontFile}),i=Be(".txt");W_(i,e.text);try{let s=ng(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 G(s,{output:n,durationSec:e.duration??Wu,extra:r})}finally{j_(i,{force:!0})}return v({outputPath:n,...(o.fallback||e.fontFile)&&{fontFile:o.fontFile},...o.warning&&{warnings:[o.warning]}})}catch(n){return _(n)}})}import{z as kr}from"zod";var U_={video:kr.string().min(1).describe("Path to the video."),music:kr.string().min(1).describe("Music audio file."),musicVolume:kr.number().nonnegative().optional().describe("0..1 (default 0.25 over existing audio, 0.8 alone)."),fadeIn:kr.number().nonnegative().optional().describe("Fade-in seconds (default 1)."),fadeOut:kr.number().nonnegative().optional().describe("Fade-out seconds (default 2)."),duck:kr.boolean().optional().describe("Duck the music under the original audio (default false)."),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 jb(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:U_,outputSchema:Q,annotations:O},async(e,r)=>{try{E();for(let a of[e.video,e.music])D(a);let n=await B(e.video);if(n.durationSec===null)throw new l(`Could not read duration of ${e.video}.`);let o=ee(e.video),i=z(e.output,"music",o,{overwrite:e.overwrite}),s=og(e.video,e.music,i,n.durationSec,n.audioCodec!==null,{musicVolume:e.musicVolume,fadeIn:e.fadeIn,fadeOut:e.fadeOut,duck:e.duck});return await G(s,{output:i,durationSec:n.durationSec,extra:r}),v({outputPath:i,mixedWithOriginal:n.audioCodec!==null})}catch(n){return _(n)}})}import{z as gt}from"zod";import{existsSync as z_,mkdtempSync as H_,readFileSync as G_,rmSync as q_,writeFileSync as X_}from"node:fs";import{tmpdir as J_}from"node:os";import{join as Bb}from"node:path";var Y_={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(Ga).max(qa).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 Ub(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:Y_,outputSchema:Q,annotations:O},async(e,r)=>{let n=null;try{E(),D(e.video);let o=await B(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 ur(e.video,r.signal)).markers:[],a=kb(e.lines,s),c=z(e.output,"narrated",ee(e.video),{overwrite:e.overwrite}),u=c.replace(/\.[^./\\]+$/,"")+".srt";if(!e.overwrite&&z_(u))throw new l(`Output already exists: ${u}. Pass overwrite: true to replace it.`);n=H_(Bb(J_(),"screencast-tts-"));let d=a.map((w,b)=>Bb(n,`line-${b}.wav`)),p=await Ib(a.map((w,b)=>({text:w.text,path:d[b]})),{voice:e.voice,rate:e.rate,signal:r.signal}),f=a.map((w,b)=>({...w,durationSec:Tb(G_(d[b]))})),m=Eb(f,o.durationSec),h=Ab(e.video,d,c,f,o.durationSec,{hasAudio:o.audioCodec!==null,channels:o.channels,duck:e.duck});await G(h,{output:c,durationSec:o.durationSec,extra:r}),X_(u,nt(_b(f,o.durationSec)));let g=Le(e.video);return g.length>0&&cr(c,g),v({outputPath:c,srtPath:u,voice:p,lines:f.map(w=>({t:w.t,durationSec:Math.round(w.durationSec*100)/100})),mixedWithOriginal:o.audioCodec!==null,...m.length?{warnings:m}:{}})}catch(o){return _(o)}finally{n&&q_(n,{recursive:!0,force:!0})}})}import{z as oi}from"zod";var K_={input:oi.string().min(1).describe("Path to the source video."),aspect:oi.enum(On).describe("Target aspect ratio."),fit:oi.enum(ia).optional().describe("pad (default): letterbox, nothing lost. crop: fill and center-crop."),output:oi.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:oi.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function zb(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:K_,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let n=ee(e.input),o=z(e.output,"reframe",n,{overwrite:e.overwrite}),i=ig(e.input,o,e.aspect,e.fit??"pad");return await G(i,{output:o,durationSec:await ue(e.input),extra:r}),v({outputPath:o,aspect:e.aspect,fit:e.fit??"pad"})}catch(n){return _(n)}})}import{z as Xe}from"zod";import{z as Kr}from"zod";import{existsSync as V_,readFileSync as Q_}from"node:fs";var Gt=.6,si=6,Xa=2.5;function Ja(t,e,r,n=si){if(t.length===0)throw new l("Give at least one keyframe.");let i=[...t].sort((s,a)=>s.t-a.t).map(s=>{if(!Number.isFinite(s.t)||s.t<0)throw new l("Keyframe t must be a non-negative number.");if(s.full||s.width===void 0||s.height===void 0)return{t:s.t,z:1,cx:e/2,cy:r/2};if(!(s.width>0)||!(s.height>0))throw new l("Keyframe width and height must be positive.");let a=Math.max(1,Math.min(n,e/s.width,r/s.height));return{t:s.t,z:a,cx:(s.x??0)+s.width/2,cy:(s.y??0)+s.height/2}});return i[0]&&i[0].t>0&&i.unshift({t:0,z:1,cx:e/2,cy:r/2}),i}var Ze=t=>Number(t.toFixed(4)).toString();function pl(t,e,r){let[n,...o]=t;if(!n)throw new l("Give at least one keyframe.");let i=[Ze(n[e])],s=n;for(let a of o){let c=s[e],u=a[e],d=s.t;if(s=a,c===u)continue;let p=a.t,f=Math.max(.001,Math.min(r,p-d)),m=`clip((it-${Ze(p-f)})/${Ze(f)},0,1)`;i.push(`(${Ze(u-c)})*${m}*${m}*(3-2*${m})`)}return kt(i)}function fl(t,e,r=Gt){let{width:n,height:o,fps:i}=e,s=n<=1920?2:1,a=pl(t,"z",r),c=pl(t,"cx",r),u=pl(t,"cy",r);return`fps=${Ze(i)},scale=${n*s}:${o*s},zoompan=z='${a}':x='clip((${c})*${s}-iw/zoom/2,0,iw-iw/zoom)':y='clip((${u})*${s}-ih/zoom/2,0,ih-ih/zoom)':d=1:s=${n}x${o}:fps=${Ze(i)}`}function Hb(t,e,r,n,o=Gt,i="standard",s){let{width:a,height:c,fps:u}=n,d=fl(r,n,o);if(!s||s.clicks.length===0)return["-y","-i",t,"-vf",d,...Te(i),"-c:a","copy",e];let p=["[0:v]null[in]",...tT(s.clicks,a,c,u,s.color),`[out]${d}[v]`].join(";");return["-y","-i",t,"-filter_complex",p,"-map","[v]","-map","0:a?",...Te(i),"-c:a","copy",e]}function Gb(t,e,r,n,o={}){let i=o.step??.25,s=o.holdSec??2,a=o.maxZoom??Xa,c=o.globalFraction??.3,u=o.transition??Gt,d=r/t,p=r/a,f=n/a,m=[],h=null,g=()=>{h&&m.push(h),h=null},w=null,b=0;return{push:S=>{let C=w;if(w=S,!C){b=1;return}let I=b++*i,R=vt(C,S,t,e,{scale:d});if(R.regions.length===0){h&&I-h.last>s&&g();return}if(R.changedFraction>c){g();return}let A=ml(R.regions);h&&I-h.last<=s&&Z_(h.box,A,r,n)?(h.box=ml([h.box,A]),h.last=I):(g(),h={start:I,last:I,box:A})},finish:()=>{g();let S=[],C=0;for(let I of m){let R=qb(I.box,r,n,p,f),A=Math.max(I.start,C+u),W=Math.max(I.last+s,A+u);S.push({t:ii(A),...R},{t:ii(W),full:!0}),C=W}return S}}}var ii=t=>Math.round(t*100)/100;function ml(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 Z_(t,e,r,n){let o=ml([t,e]);return o.width<=r/2&&o.height<=n/2}function qb(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 Xb(t,e,r){return["-v","error","-i",t,"-an","-vf",`fps=${Ze(1/r)},scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function Ya(t,e,r,n={}){let o=n.holdSec??2,i=n.maxZoom??Xa,s=n.transition??Gt,a=e/i,c=r/i,u=Math.min(e,r)*.05,d=[...t].sort((h,g)=>h.t-g.t),p=[],f=0,m=-1/0;for(let h of d){let g=qb({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&&eT(w,h)){m=h.t;continue}if(h.t-m>o&&p.length>0){let x=Math.max(m+o,f+s);p.push({t:ii(x),full:!0}),f=x}let b=Math.max(h.t,f+s);p.push({t:ii(b),...g}),f=b,m=h.t}return p.length>0&&p.push({t:ii(Math.max(m+o,f+s)),full:!0}),p}function eT(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 dl=.6,Ka="#FF4545";function hl(t,e){return Math.max(40,2*Math.round(Math.min(t,e)*.045))}function tT(t,e,r,n,o){let i=hl(e,r),s=i/2,a=Math.max(3,Math.round(i/10)),c=s*.3,u=s-a/2-c,d=[],p="[in]";return t.forEach((f,m)=>{let h=`if(lt(abs(hypot(X-${s},Y-${s})-(${Ze(c)}+${Ze(u)}*T/${dl})),${a/2}),255*min(1,2-2*T/${dl}),0)`;d.push(`color=c=${o}:s=${i}x${i}:r=${Ze(n)}:d=${dl},format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${h}',setpts=PTS+${Ze(f.t)}/TB[ring${m}]`);let g=m===t.length-1?"[out]":`[r${m}]`;d.push(`${p}[ring${m}]overlay=x=${Ze(f.x-s)}:y=${Ze(f.y-s)}:eof_action=pass${g}`),p=`[r${m}]`}),d}function ai(t){return V_(t)?Ue(Q_(t,"utf8")).filter(e=>e.type==="down"&&e.inFrame).map(e=>({t:e.t,x:e.x,y:e.y})):null}var Va=Kr.object({t:Kr.number().nonnegative(),x:Kr.number().optional(),y:Kr.number().optional(),width:Kr.number().positive().optional(),height:Kr.number().positive().optional(),full:Kr.boolean().optional()});var Jb=200,rT={input:Xe.string().min(1).describe("Path to the source video."),keyframes:Xe.array(Va).max(100).optional().describe("Views reached by time t: a source rectangle (x, y, width, height), or { t, full: true } to zoom out. Omit to plan them (see follow)."),follow:Xe.enum(["auto","clicks","changes"]).optional().describe("Without keyframes: clicks (from the events log of start_recording events: true) or changes (where the screen changed). auto (default): clicks if logged, else changes."),events:Xe.string().optional().describe("Events log (default: the input's .events.jsonl); must match the input's timing and size, so use the original recording."),highlightClicks:Xe.boolean().optional().describe("Ring each logged click (default false)."),highlightColor:Xe.string().optional().describe("Ring color (default #FF4545)."),transitionSec:Xe.number().positive().max(5).optional().describe(`How long each zoom/pan eases (default ${Gt}).`),maxZoom:Xe.number().min(1).max(si).optional().describe(`Auto mode: the furthest it zooms in (default ${Xa}).`),holdSec:Xe.number().positive().max(30).optional().describe("Auto mode: stay zoomed this long after activity (default 2)."),dryRun:Xe.boolean().optional().describe("Return the planned keyframes only (editable, pass back)."),output:Xe.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Xe.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Yb(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:rT,outputSchema:L({keyframes:Xe.array(Xe.unknown())}),annotations:O},async(e,r)=>{try{E(),D(e.input);let n=await B(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??Gt,u=e.events??ke(e.input).jsonl,d=ai(u);if(e.events&&!d)throw new l(`No event log at ${e.events}.`);if((e.follow==="clicks"||e.highlightClicks)&&!d)throw new l(`No event log for ${e.input} (looked for ${u}). Record with start_recording events: true, or pass events: <path to .events.jsonl>.`);let p=De(e.highlightColor??Ka,"highlightColor"),f=e.keyframes,m=!f,h=e.follow==="clicks"||e.follow!=="changes"&&d&&d.length>0?"clicks":"changes";if(!f&&h==="clicks"&&(f=Ya(d??[],o,i,{holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c}),f.length===0))return v({keyframes:[],follow:h,note:"The event log has no clicks inside the frame; nothing written."});if(!f){let $=Rh(o,i),S=.25,C=Gb($.width,$.height,o,i,{step:S,holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c});if(await Oi(Xb(e.input,$,S),$.width*$.height,I=>C.push(I),le(s),{signal:r.signal}),f=C.finish(),f.length===0)return v({keyframes:[],note:"No localised changes found to zoom into; nothing written."})}if(e.dryRun)return v({planned:m,...m?{follow:h}:{},keyframes:f,transitionSec:c});if(e.highlightClicks&&d&&d.length>Jb)throw new l(`${d.length} clicks is more than ${Jb} rings; trim the video or the event log first.`);let g=Ja(f,o,i),w=ee(e.input),b=z(e.output,"zoom",w,{overwrite:e.overwrite}),x=e.highlightClicks?{clicks:d??[],color:p}:void 0;return await G(Hb(e.input,b,g,{width:o,height:i,fps:a},c,"standard",x),{output:b,durationSec:s,extra:r}),v({outputPath:b,planned:m,...m?{follow:h}:{},keyframes:f,...x?{ringedClicks:x.clicks.length}:{}})}catch(n){return _(n)}})}import{z as N}from"zod";import{dirname as lT,join as Vr}from"node:path";import{existsSync as Za,mkdtempSync as pT,readFileSync as ow,rmSync as dT,writeFileSync as ci}from"node:fs";import{tmpdir as mT}from"node:os";var Jn=30,_t=t=>Math.round(t*1e3)/1e3;function gl(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 Kb(t,e,r){let n=e.slice(r);return n.length>0?ts(t,n):[...t]}function Qa(t,e,r,n,o={},i="standard",s={}){if(r.length===0)throw new l("Give at least one step.");if(r.length>Jn)throw new l(`At most ${Jn} steps.`);r.forEach((y,Z)=>{if((y.op==="export_preset"||y.op==="export_gif")&&Z!==r.length-1)throw new l(`${y.op} must be the last step (it is step ${Z+1} of ${r.length}).`)});let a=r.findIndex(y=>y.op==="zoom"),c=a===-1?-1:r.findIndex((y,Z)=>Z>a&&y.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(y=>y.op==="redact");if(r.filter(y=>y.op==="cut_idle").length>1)throw new l("Use at most one cut_idle step.");let d=n.width,p=n.height,f=n.fps,m=n.durationSec,h=[],g=[],w=1,b=[],x=[],$=!1,S="[0:v]",C=null,I,R=[],A=[],W=[],Y=[],j={sx:1,sy:1,ox:0,oy:0},re=(y,Z)=>{if(!Number.isFinite(y.start)||y.start<0)throw new l(`step ${Z}: trim start must be a non-negative number.`);if(y.end===void 0==(y.duration===void 0))throw new l(`step ${Z}: trim takes end OR duration.`);let K=y.end??y.start+y.duration;if(!(K>y.start))throw new l(`step ${Z}: trim end must be after start.`);if(m!==null&&y.start>=m)throw new l(`step ${Z}: trim starts at ${y.start}s, but the video is ${_t(m)}s long at that point.`);return{start:y.start,end:m!==null?Math.min(K,m):K}};r.forEach((y,Z)=>{let K=Z+1,ce=`p${Z}`,J=`[${ce}]`,V=T=>{b.push(`${S}${T}${J}`),S=J},ne=T=>W.push({step:Z,kind:T,seek:[...h],audio:[...x],ops:[...A]});switch(y.op){case"trim":{let{start:T,end:k}=re(y,K);Z===0?(h.push("-ss",String(T),"-t",String(_t(k-T))),R.push(`trim ${T}-${_t(k)}s: input seek`)):(V(`trim=start=${T}:end=${_t(k)},setpts=PTS-STARTPTS`),x.push(`atrim=start=${T}:end=${_t(k)},asetpts=PTS-STARTPTS`),R.push(`trim ${T}-${_t(k)}s: trim filter`)),$=!0,m=k-T,A.push({op:"trim",start:T,end:k});break}case"crop":V(dc(y,{width:d,height:p})),j&&(j={...j,ox:j.ox-y.x,oy:j.oy-y.y}),d=y.width,p=y.height,R.push(`crop to ${d}x${p}`);break;case"scale":{let T=mc(y),[k,P]=[d,p];({width:d,height:p}=ip(d,p,y)),j&&(j={sx:j.sx*d/k,sy:j.sy*p/P,ox:j.ox*d/k,oy:j.oy*p/P}),V(T),R.push(`scale to ${d}x${p}`);break}case"speed":{if(y.factor===void 0==(y.segments===void 0))throw new l(`step ${K}: speed takes factor or segments.`);if(y.segments){let k=wa(y.segments,m),P=xa(k,f);V(P.video),x.push(P.audio),$=!0;let M=Xr(k);m!==null&&(m-=M),A.push({op:"cut",spans:k}),R.push(`speed up ${k.length} range(s), ${_t(M)}s saved`);break}let T=y.factor;if(!Number.isFinite(T)||T<=0)throw new l(`step ${K}: speed factor must be positive.`);V(`setpts=PTS/${T}`),x.push(fc(T)),$=!0,m!==null&&(m/=T),A.push({op:"speed",factor:T}),R.push(`speed x${T}`);break}case"redact":{let{steps:T,out:k}=hc(y.regions,y,{width:d,height:p},S,ce);b.push(...T),S=k,R.push(`redact ${y.regions.length} region(s), ${y.style??"box"}`);break}case"callout":{let T=o[Z];if(!T)throw new l(`Internal: missing callout assets for step ${K}.`);let{steps:k,out:P,extraInputs:M}=Xu(y.items,T,S,w,ce);b.push(...k),g.push(...M),w+=M.length/4,S=P,R.push(`callout ${y.items.length} item(s)`);break}case"reframe":{let T=Nn[y.aspect];if(!T)throw new l(`step ${K}: unknown aspect "${y.aspect}".`);V(`${sa(T.w,T.h,y.fit??"pad")},format=yuv420p`),j=null,d=T.w,p=T.h,R.push(`reframe to ${y.aspect} (${y.fit??"pad"})`);break}case"zoom":{let T=y.transitionSec??Gt,k=y.keyframes,P="";if(y.follow==="clicks"){if(k)throw new l(`step ${K}: zoom takes keyframes or follow, not both.`);if(!j)throw new l(`step ${K}: zoom follow "clicks" must come before reframe, backdrop or another zoom; the logged click positions no longer match the frame.`);let M=j,U=s.clicks?.[Z];if(!U)throw new l(`Internal: missing clicks for step ${K}.`);let q=U.flatMap(X=>{let xe=es(X.t,A),st=X.x*M.sx+M.ox,oo=X.y*M.sy+M.oy;return xe!==null&&st>=0&&st<d&&oo>=0&&oo<p?[{t:xe,x:st,y:oo}]:[]});k=Ya(q,d,p,{holdSec:y.holdSec,maxZoom:y.maxZoom,transition:T}),P=` from ${q.length} click(s)`}else if(!k||k.length===0)throw new l(`step ${K}: zoom needs keyframes, or follow: "clicks".`);if(k.length===0){R.push("zoom: no clicks in this part of the video; skipped");break}V(fl(Ja(k,d,p),{width:d,height:p,fps:f},T)),j=null,R.push(`zoom ${k.length} keyframe(s)${P}`);break}case"cut_idle":{if(!s.idle)throw new l(`Internal: missing idle scan for step ${K}.`);let T=ga(rm(s.idle,A),y.minIdleSec??qr,y.keepSec??Xo);if(T.length===0){R.push("cut_idle: no idle stretches here; nothing cut");break}if(y.action==="speed"){let M=y.factor??Jo,U=T.map(xe=>({...xe,factor:M})),q=xa(U,f);V(q.video),x.push(q.audio),$=!0;let X=Xr(U);m!==null&&(m-=X),A.push({op:"cut",spans:U}),R.push(`cut_idle ${T.length} stretch(es) sped up x${M}, ${_t(X)}s saved`);break}let k=Uu(T);V(k.video),x.push(k.audio),$=!0;let P=T.reduce((M,U)=>M+(U.end-U.start),0);m!==null&&(m-=P),A.push({op:"cut",spans:T}),R.push(`cut_idle ${T.length} stretch(es), ${_t(P)}s removed`);break}case"audio":{if(y.normalize===void 0&&y.denoise===void 0)throw new l(`step ${K}: audio needs normalize and/or denoise.`);if(!n.hasAudio){R.push("audio: the input has no audio; skipped");break}let T=s.audio?.[Z],k=[];if(y.denoise!==void 0&&(T?.floorDb===void 0&&ne("noisefloor"),x.push(sl(y.denoise,T?.floorDb??null)),k.push(`denoise ${y.denoise}`)),y.normalize!==void 0&&T?.silent)k.push("silent, not normalized");else if(y.normalize!==void 0){let P=qn(y.normalize);T?.loudness||ne("loudness"),x.push(il(P,T?.loudness),"aresample=48000"),k.push(`normalize to ${P.i} LUFS${T?.loudness?` (measured ${T.loudness.input_i})`:""}`)}$=!0,R.push(`audio: ${k.join(", ")}`);break}case"burn_subtitles":{if(!y.subtitles==!y.transcribe)throw new l(`step ${K}: burn_subtitles takes subtitles (a path) or transcribe: true.`);if(y.transcribe&&!n.hasAudio)throw new l(`step ${K}: transcribe needs audio, and the input has none.`);let T=s.subtitles?.[Z];if(T===""){R.push("burn_subtitles: no cues in this part of the video; skipped");break}T===void 0&&ne(y.transcribe?"transcribe":"subtitles");let k=!!y.subtitles&&/\.(ass|ssa)$/i.test(y.subtitles),P=y.style??(k?null:"clean");V(Mu(T??"<subtitles.srt>",s.fontsDir??"<fonts>",P)),R.push(`burn_subtitles ${y.transcribe?"from a transcript":"from a file"}, ${P??"file"} style`);break}case"backdrop":{let{op:T,...k}=y,{steps:P,out:M,extraInputs:U,layout:q}=rl(k,{width:d,height:p},S,w,ce);j=null,b.push(...P),g.push(...U),w+=U.length/2,S=M,d=q.canvasW,p=q.canvasH,R.push(`backdrop to ${d}x${p}`);break}case"keystroke_overlay":{let T=s.keystrokes?.[Z];if(!T)throw new l(`Internal: missing keystroke badges for step ${K}.`);let k=Fg(T.badges,A);if(k.length===0){R.push("keystroke_overlay: no badges in this part of the video");break}let{steps:P,out:M}=Ku(Aa(k),T,y,{height:p},S,ce);b.push(...P),S=M,R.push(`keystroke_overlay ${k.length} badge(s)`);break}case"cursor":{if(!j)throw new l(`step ${K}: cursor must come before zoom, reframe or backdrop; the logged positions no longer match the frame after them.`);let T=s.cursor?.[Z];if(!T)throw new l(`Internal: missing cursor plan for step ${K}.`);let k=Pa(T.plan,A,j);if(k.path.length===0||k.visible.length===0){R.push("cursor: no cursor movement in this part of the video");break}let{steps:P,out:M,extraInputs:U,commands:q}=Zu(k,y,{width:d,height:p},S,w,ce,T.sprite,T.commandsFile);b.push(...P),g.push(...U),w+=U.length/2,S=M,Y.push({path:T.commandsFile,content:q}),R.push(`cursor ${k.path.length} segment(s), ${k.clicks.length} click(s)${y.spotlight?", spotlight":""}`);break}case"export_preset":{let T=Bu(y.platform,y.fit??"pad",ce);j=null,V(T.vf),T.af&&x.push(T.af),C=T.encode,d=T.width,p=T.height,f=30,$=!0,R.push(`export_preset ${y.platform}`);break}case"export_gif":{let{op:T,...k}=y;I=k,R.push(`export_gif (${k.format??"gif"}): second stage, size-budget ladder`);break}}});let F=["-y",...h,"-i",t,...g],oe=s.chaptersFile?F.filter(y=>y==="-i").length:-1;s.chaptersFile&&F.push("-f","ffmetadata","-i",s.chaptersFile);let de=n.hasAudio&&x.length>0;de&&b.push(`[0:a]${x.join(",")}[aout]`),b.length>0&&F.push("-filter_complex",b.join(";")),F.push("-map",S==="[0:v]"?"0:v":S),n.hasAudio&&F.push("-map",de?"[aout]":"0:a");let Se=C;return Se?F.push(...Se):(F.push(...Te(I||u?"high":i)),n.hasAudio&&F.push(...$?["-c:a","aac","-b:a","160k"]:["-c:a","copy"]),F.push("-movflags","+faststart")),oe!==-1&&F.push("-map_chapters",String(oe)),F.push(e),{args:F,width:d,height:p,fps:f,durationSec:m===null?null:_t(m),gif:I,summary:R,timeOps:A,pending:W,files:Y}}var Qb=["pr_demo","tutorial","social_reel"],nT=1e7,Vb=new Set(["export_preset","export_gif"]);function Zb(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:nT});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 oT=new Set(["redact","crop","cursor"]);function bl(t,e){let r=[...t],o=r.at(-1)&&Vb.has(r.at(-1).op)?r.pop():null,i=r.length,s=new Set,a=[],c=[];for(let u of e){if(Vb.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&&oT.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 iT,statSync as sT,writeFileSync as aT}from"node:fs";var ew=1;function cT(t){return`${t}.edit.json`}function uT(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>ew)throw new l(`${e} was written by a newer version (spec ${n.version}).`,"Update screencast-mcp to re-render it.");return n}function tw(t){let e;try{e=iT(t,"utf8")}catch{throw new l(`Edit spec not found: ${t}`)}return uT(e,t)}function wl(t){let e=sT(t);return{path:t,size:e.size,mtimeMs:Math.round(e.mtimeMs)}}function rw(t){let e;try{e=wl(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 nw(t,e){let r=cT(t),n={version:ew,tool:"pipeline",createdAt:new Date().toISOString(),output:t,...e};return aT(r,JSON.stringify(n,null,2)+`
|
|
387
|
+
`),r}function fT(){if(!Ye("whisper"))return"this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";try{return hr(void 0),null}catch{return"no whisper model (set SCREENCAST_WHISPER_MODEL)."}}var hT=N.enum(On),iw=N.enum(ia).optional(),gT=N.discriminatedUnion("op",[N.object({op:N.literal("trim"),start:N.number().nonnegative(),end:N.number().positive().optional(),duration:N.number().positive().optional()}),N.object({op:N.literal("crop"),x:N.number().int().nonnegative(),y:N.number().int().nonnegative(),width:N.number().int().positive(),height:N.number().int().positive()}),N.object({op:N.literal("scale"),width:N.number().int().positive().optional(),height:N.number().int().positive().optional()}),N.object({op:N.literal("speed"),factor:N.number().positive().optional(),segments:N.array(ba).min(1).optional()}),N.object({op:N.literal("redact"),regions:N.array(pn).min(1),style:N.enum(Ri).optional(),pad:N.number().int().nonnegative().optional(),color:N.string().optional()}),N.object({op:N.literal("callout"),items:N.array(ka).min(1).max(50),fontFile:yr}),N.object({op:N.literal("reframe"),aspect:hT,fit:iw}),N.object({op:N.literal("zoom"),keyframes:N.array(Va).min(1).max(100).optional(),follow:N.literal("clicks").optional(),maxZoom:N.number().min(1).max(si).optional(),holdSec:N.number().positive().max(30).optional(),transitionSec:N.number().positive().max(5).optional()}),N.object({op:N.literal("cut_idle"),minIdleSec:N.number().positive().optional(),keepSec:N.number().min(0).optional(),action:N.enum(["cut","speed"]).optional(),factor:N.number().gt(1).max(Gr).optional()}),N.object({op:N.literal("audio"),normalize:La.optional(),denoise:N.enum(ja).optional()}),N.object({op:N.literal("burn_subtitles"),subtitles:N.string().min(1).optional(),transcribe:N.boolean().optional(),style:N.enum(qs).optional()}),N.object({op:N.literal("backdrop"),...Na}),N.object({op:N.literal("keystroke_overlay"),...Ra}),N.object({op:N.literal("cursor"),...Ia}),N.object({op:N.literal("export_preset"),platform:N.enum(aa),fit:iw}),N.object({op:N.literal("export_gif"),format:N.enum(["gif","webp"]).optional(),maxBytes:N.number().int().min(1e4).optional(),fps:N.number().positive().max(30).optional(),width:N.number().int().min(64).max(1920).optional()})]),bT={input:N.string().min(1).optional().describe("Path to the source video."),fromEdit:N.string().min(1).optional().describe("Re-render an .edit.json; steps replace same-op steps."),steps:N.array(gT).max(Jn).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:N.enum(Qb).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:N.enum(["draft","standard","high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),dryRun:N.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),output:N.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:N.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),chapters:N.boolean().optional().describe("Keep the input's markers as chapters, re-timed through trims and speed.")};function sw(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:bT,outputSchema:L({processes:N.number().int(),steps:N.array(N.string())}),annotations:O},async(e,r)=>{try{let{ffmpeg:n}=E(),o=e.fromEdit?tw(e.fromEdit):null;if(o){if(e.recipe)throw new l("fromEdit already has its steps; leave recipe out.");if(e.input&&!No(e.input,o.source.path))throw new l(`The spec is for ${o.source.path}, not ${e.input}.`);let A=rw(o);if(A)throw new l(`Cannot re-render ${e.fromEdit}: ${A}.`,"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;D(i);let c=await B(i),u=c.audioCodec!==null,d=[],p=e.steps??[];if(o&&(p=bl(o.steps,p)),e.recipe){let A=ai(ke(i).jsonl),W=Zb(e.recipe,{hasAudio:u,hasClicks:!!A&&A.length>0,transcribeBlocker:u?fT():null});p=bl(W.steps,p),d.push(...W.notes)}if(p.length===0)throw new l("Give steps, a recipe, or both.");if(p.length>Jn)throw new l(`At most ${Jn} steps.`);if(!c.width||!c.height)throw new l(`Could not read the size of ${i}.`);let f={width:c.width,height:c.height,fps:c.fps??30,durationSec:c.durationSec,hasAudio:u},m=le(c.durationSec),h=p.at(-1);if(!h)throw new l("Provide at least one step.");let g=h.op==="export_gif"?`.${h.format??"gif"}`:".mp4",w=z(e.output,"pipeline",g,{overwrite:e.overwrite,anyContainer:h.op==="export_gif"}),b=h.op!=="export_gif"&&p.some(A=>A.op==="burn_subtitles"&&A.transcribe),x=w.replace(/\.[^./\\]+$/,"")+".srt";if(b&&!e.overwrite&&Za(x))throw new l(`Output already exists: ${x}. Pass overwrite: true to replace it.`);for(let[A,W]of p.entries())if(W.op==="burn_subtitles"){if(!Ye("subtitles"))throw new l("This ffmpeg has no subtitles filter (it needs libass).","Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");if(W.subtitles&&!Za(W.subtitles))throw new l(`step ${A+1}: subtitles file not found: ${W.subtitles}`);if(W.transcribe){if(!Ye("whisper"))throw new l(`step ${A+1}: transcribe needs FFmpeg 8 built with whisper.cpp (no whisper filter here).`);hr(void 0)}}let $={};for(let[A,W]of p.entries()){if(W.op!=="zoom"||W.follow!=="clicks")continue;let Y=ke(i).jsonl,j=ai(Y);if(!j)throw new l(`step ${A+1}: no event log at ${Y}; record with start_recording events: true.`);$[A]=j}let S,C=p.findIndex(A=>A.op==="cut_idle"),I=p[C];if(I?.op==="cut_idle"){let A=c.durationSec;if(A===null)throw new l(`Could not read the duration of ${i}.`);let W=p.slice(0,C).reduce((F,oe)=>oe.op==="speed"&&oe.factor?F*oe.factor:F,1),Y=u,j=await se(n,da(i,(I.minIdleSec??qr)*W,Y),m,{signal:r.signal});if(j.code!==0)throw new l(`Idle scan failed (exit ${j.code}): ${j.stderr.trim().slice(-400)}`);let re=ma(j.stderr,A);S=Y?ha(re,fa(j.stderr,A)):re}let R=pT(Vr(mT(),"screencast-pipeline-"));try{let A={},W=[];for(let[k,P]of p.entries()){if(P.op!=="callout")continue;let M=e.dryRun?{fontFile:"<font>",textFiles:P.items.map(U=>U.type==="text"?"<text>":null),arrowFiles:P.items.map(U=>U.type==="arrow"?"<arrow.png>":null),...Ju(P.items,P.fontFile)}:await Ea(P.items,R,`s${k}_`,P.fontFile);A[k]=M,W.push(...M.fallbackFonts.map(U=>({step:k,...U}))),d.push(...M.warnings.map(U=>`Step ${k}, ${U.charAt(0).toLowerCase()}${U.slice(1)}`))}let Y={};for(let[k,P]of p.entries()){if(P.op==="backdrop"&&P.image&&!Za(P.image))throw new l(`step ${k+1}: background image not found: ${P.image}`);if(P.op!=="keystroke_overlay")continue;let{badges:M}=Ma(i,P.events,P),U=[...new Set(M.map(X=>X.label))],q=Ko(U,e.dryRun?null:R,`s${k}_`,P.fontFile);Y[k]={badges:M,fontFile:q.fontFile,textFiles:q.textFiles},d.push(...q.warnings.map(X=>`Step ${k}, ${X.charAt(0).toLowerCase()}${X.slice(1)}`))}let j={};for(let[k,P]of p.entries())P.op==="cursor"&&(j[k]={plan:Fa(i,P.events,P,c.durationSec),sprite:Ca(),commandsFile:e.dryRun?`<cursor ${k}.cmd>`:Vr(R,`s${k}_cursor.cmd`)});let re=h.op==="export_gif"?e.dryRun?"<temporary stage1.mp4>":Vr(R,"stage1.mp4"):w,F={},oe={},de=lT(Nt("regular")),Se=k=>Qa(i,re,p,f,A,s,{keystrokes:Y,cursor:j,idle:S,clicks:$,audio:F,subtitles:oe,fontsDir:de,chaptersFile:k}),y=Se(),Z;for(let k=0;!e.dryRun&&y.pending.length>0;k++){let P=y.pending[0];if(k>p.length*3)throw new l(`Internal: step ${P.step+1} ${P.kind} did not resolve.`);let M=p[P.step],U=async q=>{let X=Fi(gl(q,P));try{let xe=await se(n,X.args,m,{signal:r.signal});if(xe.code!==0)throw new l(`step ${P.step+1} ${P.kind} scan failed (exit ${xe.code}): ${xe.stderr.trim().slice(-400)}`);return xe}finally{X.cleanup()}};if(P.kind==="noisefloor")F[P.step]={...F[P.step],floorDb:Ua((await U(Ba(i))).stdout)};else if(P.kind==="loudness"&&M.op==="audio"){let q=await U(ti(i,qn(M.normalize)));try{F[P.step]={...F[P.step],loudness:ri(q.stderr)}}catch{d.push(`Step ${P.step+1}: the audio is silent; not normalized.`),F[P.step]={...F[P.step],silent:!0}}}else if(P.kind==="transcribe"&&M.op==="burn_subtitles"){let q=Vr(R,`s${P.step}_raw.srt`);await te(gl(Pn(i,hr(void 0),q),P),m,{signal:r.signal});let X=Za(q)?pt(je(ow(q,"utf8"))):[];oe[P.step]=X.length>0?Vr(R,`s${P.step}.srt`):"",X.length>0?(Z={cues:X,opsBefore:P.ops.length},ci(oe[P.step],nt(X))):d.push(`Step ${P.step+1}: no speech was recognised; no captions.`)}else if(P.kind==="subtitles"&&M.op==="burn_subtitles"&&M.subtitles)if(P.ops.length===0)oe[P.step]=M.subtitles;else{let q=ow(M.subtitles,"utf8"),X=/\.(ass|ssa)$/i.test(M.subtitles),xe=X?nm(q,P.ops):nt(ts(pt(je(q)),P.ops)),st=Vr(R,`s${P.step}${X?".ass":".srt"}`);ci(st,xe),oe[P.step]=X||xe.trim()?st:""}else throw new l(`Internal: step ${P.step+1} cannot resolve ${P.kind}.`);y=Se()}let K=[],ce=[];if(a){let k=y.gif?null:await ur(i,r.signal);if(!k)d.push("chapters: a GIF/WebP cannot hold chapters; none written.");else if(k.markers.length===0)d.push("chapters: the input has no markers (add_marker) or chapters; none written.");else if(ce=am(k.markers,y.timeOps),K=y.durationSec?os(ss(ce),y.durationSec):[],K.length===0)d.push("chapters: no marker falls inside the result; none written.");else{let P=e.dryRun?"<chapters.txt>":Vr(R,"chapters.txt");e.dryRun||ci(P,is(K)),y=Se(P)}}let J={...e.recipe&&{recipe:e.recipe,expandedSteps:p},steps:y.summary,...e.dryRun&&y.pending.length>0&&{measuredOnRun:y.pending.map(k=>`step ${k.step+1}: ${k.kind}`)},processes:y.gif?2:1,width:y.width,height:y.height,durationSec:y.durationSec,...W.length>0&&{fallbackFonts:W},...d.length>0&&{warnings:d},...K.length>0&&{chapters:K}};if(e.dryRun)return v({dryRun:!0,...J,ffmpegArgs:y.args});let V=()=>{try{let k=e.recipe??o?.recipe;return{editSpecPath:nw(w,{serverVersion:wt(),source:wl(i),steps:p,...k?{recipe:k}:{},quality:s,chapters:a})}}catch{return{}}};for(let k of y.files)ci(k.path,k.content);if(await G(y.args,{output:re,durationSec:y.durationSec,inputDurationSec:c.durationSec,extra:r}),y.gif){let k=await Ln(re,w,y.gif,r);return v({outputPath:w,...J,animation:k,...V()})}let ne;if(Z)try{let k=Kb(Z.cues,y.timeOps,Z.opsBefore);k.length>0&&(ci(x,nt(k)),ne=x)}catch{ne=void 0}let T;if(K.length>0)try{T=cr(w,ce.filter(k=>k.t<(y.durationSec??1/0)))}catch{}return v({outputPath:w,...J,...T&&{markersPath:T},...ne&&{subtitlesPath:ne},...V()})}finally{dT(R,{recursive:!0,force:!0})}}catch(n){return _(n)}})}import{z as ui}from"zod";var wT={input:ui.string().min(1).describe("Path to the source video."),platform:ui.enum(aa).describe("Sets aspect, size, fps, bitrate. steam_trailer: 1080p 5.5 Mbps CBR, -14 LUFS. vertical_reel: 1080x1920 over a blurred copy of itself, -14 LUFS (ignores fit)."),fit:ui.enum(["pad","crop"]).optional().describe("Fit to the platform aspect: pad (default) or crop."),output:ui.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ui.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function aw(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:wT,outputSchema:Q,annotations:O},async(e,r)=>{try{E(),D(e.input);let n=e.platform,o=z(e.output,n,".mp4",{overwrite:e.overwrite}),i=sg(e.input,o,n,e.fit??"pad");await G(i,{output:o,durationSec:await ue(e.input),extra:r});let s=ju[n];return v({outputPath:o,platform:n,aspect:s.aspect,fps:s.fps})}catch(n){return _(n)}})}import{z as Ee}from"zod";import{existsSync as ec,mkdirSync as xT,mkdtempSync as yT,readFileSync as xl,rmSync as yl,writeFileSync as cw}from"node:fs";import{tmpdir as ST,release as vT,version as $T}from"node:os";import{join as Qr}from"node:path";var kT=wt(),ET={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(As).optional().describe(`Clip length without start (default ${Su}).`),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(pn).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 ${vu}).`),maxFrames:Ee.number().int().min(1).max(gs).optional().describe(`Scan frame cap (default ${$n}).`),gif:Ee.boolean().optional().describe("Also export a GIF (default true)."),maxBytes:Ee.number().int().min(1e4).optional().describe(`GIF size budget (default ${xr}).`),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.")},li=t=>Math.round(t*1e3)/1e3;async function _T(){if(process.platform!=="win32")return null;try{return(await or()).map(e=>`${e.width}x${e.height}${e.dpi?` @${Math.round(e.dpi/96*100)}%`:""}${e.primary?" (primary)":""}`).join(", ")}catch{return null}}function uw(t){t.registerTool("bug_report",{title:"Bug Report Package",description:"Package a recording as a paste-ready repro folder: secret-scanned, redacted clip and GIF, contact sheet, steps from the event log, OCR'd errors, environment, report.md for gh issue create --body-file.",inputSchema:ET,outputSchema:L({outputDir:Ee.string(),reportPath:Ee.string(),jsonPath:Ee.string(),clipPath:Ee.string()}),annotations:O},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}=E(),s=await Cs(e),a=await B(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=df(c,e),d=li(u.end-u.start),p=e.redact!==!1,f=e.secretPattern??Ge;Ne(["x"],f),e.errorPattern!==void 0&&Ne(["x"],e.errorPattern);let m="gif",h=nn(e.outputDir,be("edits"))??Qr(be("edits"),`bug-report-${he()}-${ge()}`),g={markdown:Qr(h,Dt.markdown),json:Qr(h,Dt.json),clip:Qr(h,Dt.clip),gif:Qr(h,Dt.gif(m)),sheet:Qr(h,Dt.contactSheet)},w=Object.values(g).filter($=>ec($));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.`);ec(h)||(xT(h,{recursive:!0}),n=h);let b=[],x=yT(Qr(ST(),"screencast-bug-"));try{let $="unavailable",S=null,C=await gr();if(C.available)S=await hs(s.path,{everySec:e.scanEverySec??vu,maxFrames:e.maxFrames??$n,range:{start:u.start,duration:d}},x,r.signal),$="read";else{if(p)throw new l(`The secret scan needs Windows OCR, which is unavailable here${C.error?` (${C.error})`:""}.`,"Pass redact: false to package without it (then check the clip yourself before sharing), or run doctor.");b.push("Windows OCR is unavailable, so no error text was read.")}let I=S&&p?mf(vn(S,f,!0,"line").redactRegions):[],R=[...I,...e.regions??[]],A=S?ff(S.frames,e.errorPattern??Ms,p?f:null):[];r.signal.throwIfAborted();let W=[{op:"trim",start:u.start,end:u.end},...R.length>0?[{op:"redact",regions:R,style:"box"}]:[]],Y=Qa(s.path,g.clip,W,{width:a.width,height:a.height,fps:a.fps??30,durationSec:a.durationSec,hasAudio:a.audioCodec!==null});await G(Y.args,{output:g.clip,durationSec:Y.durationSec,inputDurationSec:d,extra:r}),o.push(g.clip);let j=null;e.gif!==!1&&(j=await Ln(g.clip,g.gif,{format:m,maxBytes:e.maxBytes??xr},r),o.push(g.gif),j.note&&b.push(j.note)),await _s(g.clip,Es(d,Po),g.sheet,{tileWidth:Io},r.signal),o.push(g.sheet);let re=(s.eventsPath?yu(Ue(xl(s.eventsPath,"utf8"))):[]).map(k=>p?{...k,text:Ne([k.text],f)[0]??k.text}:k),F=s.eventsPath?re.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).",oe=Ot(s.path),de=ec(oe)?gf(ys(xl(oe,"utf8")),u,p?f:null):void 0,Se=kn(s.path),y=ec(Se)?bf(qm(xl(Se,"utf8")),u,s.record?.perf?.summary?.process):[],Z=na(oa(i)??""),K=await _T(),ce=s.record,J=k=>p?Ne([k],f)[0]??k:k,V=[["OS",`${$T()} (${vT()}), ${process.arch}`],...K?[["Displays",K]]:[],...ce?[["Recorded target",J(ce.target)]]:[],...ce?.matchedWindow?[["Window",J(ce.matchedWindow)]]:[],...ce?.backend?[["Capture backend",ce.backend]]:[],["Recording",`${a.width}x${a.height}${a.fps?` @ ${Math.round(a.fps*100)/100} fps`:""}, ${li(c)} s${a.videoCodec?`, ${a.videoCodec}`:""}`],["ffmpeg",Z.version??"unknown"],["screencast-mcp",`${kT} (Node ${process.version})`]],ne={title:e.title?.trim()||"Bug report",...e.expected?{expected:e.expected}:{},...e.actual?{actual:e.actual}:{},createdAt:new Date().toISOString(),clip:{start:u.start,end:u.end,recordingDurationSec:li(c),width:a.width,height:a.height},files:{clip:Dt.clip,...j?{gif:Dt.gif(m)}:{},contactSheet:Dt.contactSheet},...j?{gif:{format:m,sizeBytes:j.sizeBytes,withinBudget:j.withinBudget}}:{},steps:re.slice(0,Rs),...re.length>Rs?{stepsOmitted:re.length-Rs}:{},...F?{stepsNote:F}:{},errors:A,...de?{logs:de}:{},...y.length?{perf:y}:{},ocr:$,redaction:{scanned:S!==null&&p,...S&&p?{everySec:li(S.step),framesScanned:S.frames.length}:{},found:I.length,manual:e.regions?.length??0},environment:V};cw(g.markdown,hf(ne)),o.push(g.markdown),cw(g.json,JSON.stringify({...ne,steps:re,redaction:{...ne.redaction,regions:R}},null,2)+`
|
|
388
|
+
`),o.push(g.json),S?.clamped&&b.push(`The scan interval was widened to ${li(S.step)} s to fit maxFrames.`);let{images:T}=await Me([g.sheet],Re,1);return v({outputDir:h,reportPath:g.markdown,jsonPath:g.json,clipPath:g.clip,...j?{gifPath:g.gif,gifSizeBytes:j.sizeBytes,gifWithinBudget:j.withinBudget}:{},contactSheetPath:g.sheet,clip:{start:u.start,end:u.end},steps:re.length,errors:A.map(k=>k.text),ocr:$,redaction:ne.redaction,...b.length>0?{warnings:b}:{},next:`Review the clip and report.md, then: gh issue create --title ${JSON.stringify(ne.title)} --body-file ${JSON.stringify(g.markdown)} and drag the GIF into the issue.`,note:"Redaction is OCR-based and best-effort: look at the clip before posting it anywhere public."},T)}finally{yl(x,{recursive:!0,force:!0})}}catch(i){if(n)yl(n,{recursive:!0,force:!0});else for(let s of o)yl(s,{force:!0});return _(i)}})}import{z as Er}from"zod";import{existsSync as tc,mkdirSync as _l,mkdtempSync as FT,readFileSync as vw,readdirSync as $w,rmSync as Zr,rmdirSync as OT,statSync as NT,writeFileSync as kw}from"node:fs";import{tmpdir as DT}from"node:os";import{join as Je}from"node:path";var pi=100,TT=.1,AT=1280,lw=40,RT=24,Kn={markdown:"guide.md",html:"guide.html",images:"images",image:t=>`step-${String(t).padStart(2,"0")}.png`};function vl(t){return t.label?`${t.text} ${t.label}`:t.text}var MT=t=>Math.round(t*1e3)/1e3;function CT(t,e,r){let n=Math.max(0,e-1/(r>0?r:30));return MT(Math.min(Math.max(0,t-TT),n))}function Sl(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 pw(t,e,r){let o=t.map(s=>({line:s,d:Sl(s,e,r)})).filter(s=>s.d<=RT&&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>lw){let s=[...o.words].sort((a,c)=>Sl(a,e,r)-Sl(c,e,r))[0];i=s?s.text.trim():`${i.slice(0,lw-1).trimEnd()}\u2026`}return i.length>0?i:null}function PT(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 $l(t,e){let r=e.secretPattern??Ge,n=i=>Ne([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:CT(i.t,e.durationSec,e.fps)},c=i.element?.name??e.labels?.[s];if(i.action==="click"||i.action==="double_click"){let u=PT(i);return i.inFrame===!1?{...a,text:i.element?.name?n(`${u} ${wu(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 dw(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 mw(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,${AT})':h=-2:flags=lanczos`,i=`[0:v]${n.length?n.join(",")+",":""}format=rgba`;if(!e.click)return`${i},${o},format=rgb24[out]`;let s=hl(t.width,t.height),a=s/2,c=Math.max(3,Math.round(s/10)),u=a-c/2-1,d=e.color??Ka;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 fw(t,e,r){return["-y","-v","error","-ss",String(e),"-i",t,"-frames:v","1",r]}var Vn=1e7,qt=[{width:1280,q:4},{width:960,q:6},{width:800,q:8},{width:640,q:10},{width:480,q:14},{width:360,q:20}],kl=t=>t.replace(/\.png$/i,".jpg");function hw(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 gw=t=>4*Math.ceil(t/3);function bw(t,e,r=Vn){let n=qt[t].width;for(let o=t+1;o<qt.length;o++)if(e*(qt[o].width/n)**2<=r)return o;return t+1<qt.length?qt.length-1:null}function ww(t,e,r){return["-y","-v","error","-i",t,"-filter_complex",e,"-map","[out]","-frames:v","1",r]}var Yn=t=>t.replace(/\s*\n\s*/g," ").replace(/([\\`*_[\]<>#|])/g,"\\$1");function xw(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 yw(t){let e=t.steps.filter(r=>r.n>0).length;return`${e} step${e===1?"":"s"} from a ${Oe(t.recording.durationSec)} recording.`}function Sw(t){let e=[`# ${Yn(t.title)}`,"",yw(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(`## ${Yn(r)}`,"")),n.n===0){e.push(`> _${Yn(n.text)}_`,"");continue}let o=n.label?`${Yn(n.text)} **${Yn(n.label)}**`:Yn(n.text);e.push(`${n.n}. ${o} <sub>${Oe(n.t)}</sub>`,""),n.image&&e.push(` `,"")}return t.stepsOmitted&&e.push(`_${t.stepsOmitted} more steps not shown._`,""),e.push("<sub>",xw(t),`Generated by screencast-mcp step_guide, ${t.createdAt}.`,"</sub>",""),e.join(`
|
|
389
|
+
`)}var et=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),IT=`:root{--bg:#f6f5f2;--card:#fff;--ink:#16161a;--dim:#6b6b74;--line:#e2e0da;--rec:#e5383b}
|
|
390
|
+
@media (prefers-color-scheme:dark){:root{--bg:#121214;--card:#1b1b1f;--ink:#ececf1;--dim:#9a9aa6;--line:#2c2c33}}
|
|
391
|
+
*{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}
|
|
392
|
+
main{max-width:920px;margin:0 auto;padding:40px 16px 64px}
|
|
393
|
+
header{border-bottom:1px solid var(--line);padding-bottom:20px;margin-bottom:28px}
|
|
394
|
+
.rec{font:600 12px/1 ui-monospace,"Cascadia Mono",Consolas,monospace;letter-spacing:.12em;color:var(--rec);text-transform:uppercase}
|
|
395
|
+
.rec::before{content:"";display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--rec);margin-right:8px;vertical-align:1px}
|
|
396
|
+
h1{font-size:30px;line-height:1.2;margin:10px 0 6px}h2{font-size:20px;margin:40px 0 16px}
|
|
397
|
+
.meta{color:var(--dim);margin:0}ol{list-style:none;margin:0;padding:0}
|
|
398
|
+
li{background:var(--card);border:1px solid var(--line);border-radius:10px;margin:0 0 18px;overflow:hidden}
|
|
399
|
+
.cap{display:flex;gap:14px;align-items:baseline;padding:14px 18px}
|
|
400
|
+
.n{flex:none;font:700 14px/1 ui-monospace,Consolas,monospace;color:var(--rec);min-width:2.2em}
|
|
401
|
+
.t{margin-left:auto;font:12px/1 ui-monospace,Consolas,monospace;color:var(--dim)}
|
|
402
|
+
li img{display:block;width:100%;height:auto;border-top:1px solid var(--line)}
|
|
403
|
+
.note{color:var(--dim);font-style:italic;margin:0 0 18px;padding-left:18px;border-left:3px solid var(--line)}
|
|
404
|
+
footer{color:var(--dim);font-size:13px;margin-top:40px;border-top:1px solid var(--line);padding-top:16px}`;function El(t,e){let r=[],n,o=!1,i=()=>{o&&r.push("</ol>"),o=!1};for(let s of t.steps){if(s.section!==void 0&&s.section!==n&&(i(),n=s.section,r.push(`<h2>${et(n)}</h2>`)),s.n===0){i(),r.push(`<p class="note">${et(s.text)}</p>`);continue}o||r.push("<ol>"),o=!0;let a=s.label?`${et(s.text)} <strong>${et(s.label)}</strong>`:et(s.text);r.push(`<li><div class="cap"><span class="n">${String(s.n).padStart(2,"0")}</span><span>${a}</span><span class="t">${Oe(s.t)}</span></div>`+(s.image?`<img src="${et(e(s.image))}" alt="Step ${s.n}: ${et(vl(s))}" loading="lazy">`:"")+"</li>")}return i(),t.steps.length===0&&r.push(`<p class="note">${et(t.stepsNote??"No steps in the recording.")}</p>`),t.stepsOmitted&&r.push(`<p class="note">${t.stepsOmitted} more steps not shown.</p>`),["<!doctype html>",'<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">',`<title>${et(t.title)}</title><style>${IT}</style></head><body><main>`,`<header><div class="rec">Step guide</div><h1>${et(t.title)}</h1><p class="meta">${et(yw(t))}</p></header>`,...r,`<footer>${et(xw(t))}<br>Generated by screencast-mcp step_guide, ${et(t.createdAt)}.</footer>`,"</main></body></html>",""].join(`
|
|
405
|
+
`)}var Ew=10,_w=5,LT={input:Er.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),sessionId:Er.string().min(1).optional().describe("Or a stopped session's id."),title:Er.string().max(200).optional().describe("Guide title."),format:Er.enum(["md","html","both"]).optional().describe("md + images/, self-contained html, or both (default)."),ocr:Er.boolean().optional().describe("OCR shots for captions and secret boxes (default true; needs Windows OCR)."),outputDir:Er.string().optional().describe("Guide folder (default: new in SCREENCAST_HOME/edits)."),overwrite:Er.boolean().optional().describe("Replace a guide already in outputDir.")};function Tw(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:LT,outputSchema:L({outputDir:Er.string()}),annotations:O},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.");E();let i=await Cs(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 B(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 I=await gr();if(!I.available)throw new l(`Captions and the secret scan need Windows OCR, which is unavailable here${I.error?` (${I.error})`:""}.`,"Pass ocr: false for a guide without them (then check the screenshots yourself before sharing), or run doctor.")}let m=nn(e.outputDir,be("edits"))??Je(be("edits"),`step-guide-${he()}-${ge()}`),h={markdown:Je(m,Kn.markdown),html:Je(m,Kn.html),images:Je(m,Kn.images)},g=[h.markdown,h.html].filter(I=>tc(I));if(g.length>0&&!e.overwrite)throw new l(`The folder already holds a guide: ${g.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);let w=xu(Ue(vw(i.eventsPath,"utf8"))),b=w.slice(0,pi),$=$l(b,{durationSec:a,fps:c}).map((I,R)=>({i:R,s:I})).filter(({s:I})=>I.shotT!==void 0),S=[];tc(m)||(_l(m,{recursive:!0}),n=m);let C=FT(Je(DT(),"screencast-guide-"));try{let I=mo(r),R=$.length*(f?3:2)||1,A=0,W=()=>I?.(++A/R),Y=await He($,async({s:J})=>{let V=Je(C,`frame-${String(J.n).padStart(3,"0")}.png`);return await te(fw(i.path,J.shotT,V),6e4,{signal:r.signal}),W(),V}),j=Y.map(()=>null);if(f)for(let J=0;J<Y.length;J+=Ew)r.signal.throwIfAborted(),(await lt(Y.slice(J,J+Ew),C,r.signal,{sameSize:!0})).forEach((ne,T)=>{j[J+T]=ne,W()});let re=b.map(()=>null),F=$.map(({i:J,s:V},ne)=>{let T=j[ne];return T?(V.x!==void 0&&V.y!==void 0&&(re[J]=pw(T.lines,V.x,V.y)),vn({frames:[{...T,t:0,path:""}],step:1,end:1},Ge,!0,"line").redactRegions):[]}),oe=dw($l(b,{durationSec:a,fps:c,labels:re}),Le(i.path)),de=d?h.images:Je(C,"images");if(d&&tc(de)&&e.overwrite)for(let J of $w(de))/^step-\d+\.png$/.test(J)&&Zr(Je(de,J),{force:!0});_l(de,{recursive:!0});let Se=0,y={width:s.width,height:s.height},Z=await He($,async({i:J},V)=>{let ne=oe[J],T=Kn.image(ne.n),k=ne.x!==void 0&&ne.y!==void 0?{x:ne.x,y:ne.y}:void 0,P=mw(y,{click:k,boxes:F[V]}),M=Je(de,T);return await te(ww(Y[V],P,M),6e4,{signal:r.signal}),W(),{step:ne,file:T,out:M}});for(let[J,{step:V,file:ne,out:T}]of Z.entries())d&&o.push(T),V.image=ne,Se+=F[J].length;let K=w.length===0?"The event log has no clicks, shortcuts, typing, or scrolls.":void 0,ce={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:oe,...w.length>pi?{stepsOmitted:w.length-pi}:{},...K?{stepsNote:K}:{},ocr:f?"read":"off",redactions:Se};if(d&&(kw(h.markdown,Sw(ce)),o.push(h.markdown)),p){let J=Je(C,"html");_l(J,{recursive:!0});let V=oe.flatMap(U=>U.image?[U.image]:[]),ne=U=>`data:image/jpeg;base64,${vw(Je(J,kl(U))).toString("base64")}`,T=async(U,q)=>{let X=Je(J,kl(U));return await te(hw(Je(de,U),q,X),6e4,{signal:r.signal}),gw(NT(X).size)},k=V.length>_w?V.filter((U,q)=>q%Math.ceil(V.length/_w)===0):[],P=0;for(;k.length>0&&P<qt.length-1;P++){let U=0;for(let q of k)U+=await T(q,qt[P]);if(U/k.length*V.length<=Vn*.9)break}let M="";for(let U=P;U!==null;){let q=qt[U],X=0;for(let oo of V)X+=await T(oo,q);M=X<=Vn?El(ce,ne):"";let xe=M?Buffer.byteLength(M):X;if(xe<=Vn)break;let st=bw(U,xe);st===null&&(M||=El(ce,ne),S.push(`guide.html is ${(Buffer.byteLength(M)/1e6).toFixed(1)} MB, over the ${Vn/1e6} MB budget even with ${q.width} px JPEGs; use format: md for a guide this long.`)),U=st}kw(h.html,M),o.push(h.html)}if(e.overwrite&&(p||Zr(h.html,{force:!0}),!d&&(Zr(h.markdown,{force:!0}),tc(h.images)))){for(let J of $w(h.images))/^step-\d+\.png$/.test(J)&&Zr(Je(h.images,J),{force:!0});try{OT(h.images)}catch{}}return ce.stepsOmitted&&S.push(`Only the first ${pi} steps were written; ${ce.stepsOmitted} more were left out.`),K&&S.push(K),v({outputDir:m,...d?{markdownPath:h.markdown,imagesDir:h.images}:{},...p?{htmlPath:h.html}:{},steps:oe.map(J=>({...J.n>0?{n:J.n}:{},t:J.t,action:J.action,caption:vl(J),...J.section?{section:J.section}:{},...J.image?{image:J.image}:{}})),ocr:ce.ocr,redactions:Se,...S.length>0?{warnings:S}:{},note:f?"Captions are OCR-based templates: rewrite them in guide.md as needed. The secret scan is best-effort: look at the screenshots before sharing.":"Not scanned for secrets: look at the screenshots before sharing."})}finally{Zr(C,{recursive:!0,force:!0})}}catch(i){if(n)Zr(n,{recursive:!0,force:!0});else for(let s of o)Zr(s,{force:!0});return _(i)}})}import{existsSync as Aw,rmSync as WT}from"node:fs";import{ResourceTemplate as Rw}from"@modelcontextprotocol/sdk/server/mcp.js";import{SubscribeRequestSchema as jT,UnsubscribeRequestSchema as BT}from"@modelcontextprotocol/sdk/types.js";var Mw=(t,e)=>({contents:[{uri:t,mimeType:"application/json",text:JSON.stringify(e,null,2)}]});function Cw(t){let e=ie().get(t);if(!e)throw new l(`No session with id ${t}.`);return e}function Iw(t){t.registerResource("sessions","screencast://sessions",{title:"Recording sessions",description:"Every recording session (active and finished), newest first.",mimeType:"application/json"},r=>Mw(r.href,ie().list())),t.registerResource("session",new Rw("screencast://sessions/{id}",{list:()=>({resources:ie().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=Cw(String(n));return Mw(r.href,{...o,fileExists:Aw(o.outputPath)})}),t.registerResource("session-poster",new Rw("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=Cw(String(n));if(!Aw(o.outputPath))throw new l(`Recording file not found: ${o.outputPath}`);let{durationSec:i}=await B(o.outputPath),s=Be(".png");try{await te(["-y","-v","error","-ss",String((i??0)/2),"-i",o.outputPath,"-frames:v","1",s],3e4);let[a]=(await Me([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{WT(s,{force:!0})}});let e=new Map;t.server.registerCapabilities({resources:{subscribe:!0}}),t.server.setRequestHandler(jT,r=>(e.set(r.params.uri,Pw(r.params.uri)),{})),t.server.setRequestHandler(BT,r=>(e.delete(r.params.uri),{})),ie().onChange(()=>{if(!(ms()||!t.isConnected())){try{t.sendResourceListChanged()}catch{}for(let[r,n]of e){let o=Pw(r);o!==n&&(e.set(r,o),t.server.sendResourceUpdated({uri:r}).catch(()=>{}))}}})}function Pw(t){if(t==="screencast://sessions")return JSON.stringify(ie().list());let e=/^screencast:\/\/sessions\/([^/]+)$/.exec(t),r=e?ie().get(decodeURIComponent(e[1])):void 0;return r?JSON.stringify(r):null}import{z as it}from"zod";var Qn=t=>({messages:[{role:"user",content:{type:"text",text:t}}]}),Zn={bugReproClip:(t,e)=>`Record a short bug-reproduction clip of ${t}.${e?` The bug: ${e}.`:""}
|
|
406
|
+
|
|
407
|
+
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.
|
|
408
|
+
2. sample_frames { input: <recording>, mode: "scenes" } to see what happened, and describe the moment the bug appears.
|
|
409
|
+
3. find_text { input: <recording>, scanEverySec: 1, query: "sk-|ghp_|api.?key|token|password", regex: true, redact: true } to check the whole clip, not one frame. If anything sensitive shows up, redact_region its redactRegions (each has its own start/end) with style "box" before sharing. OCR can miss text, so also look at the frames yourself.
|
|
410
|
+
4. trim (or clip) to the few seconds around the bug, and callout to box or point at it.
|
|
411
|
+
5. export_gif { input: <clip>, maxBytes: 10000000 } so it can be pasted into an issue or PR.
|
|
412
|
+
Report the final file path, what the clip shows, and anything you redacted. (To file it as an issue, bug_report does steps 3-5 in one call and writes report.md.)`,fileBugReport:(t,e,r)=>`File a bug report for ${t}, with a redacted repro package.${e?` The bug: ${e}.`:""}${r?` Expected: ${r}.`:""}
|
|
413
|
+
|
|
414
|
+
1. start_recording { target: "${t}", events: true } so clicks and shortcuts are logged as repro steps, then reproduce the bug (or ask me to), and stop_recording right after it shows.
|
|
415
|
+
2. contact_sheet { input: <recording> } and find the moment it goes wrong; note its time.
|
|
416
|
+
3. bug_report { sessionId: <session id>, title: <one-line summary>, actual: <what happened>, expected: <what should happen>, clipSec: 30 } (or start/end around that moment). It scans the clip for secrets with OCR and boxes them out before writing the clip, GIF, contact sheet, steps, error text, and report.md.
|
|
417
|
+
4. Read report.md and look at the contact sheet it returns: check the steps make sense and that nothing sensitive is left (OCR can miss text; add regions and rerun with overwrite: true if so).
|
|
418
|
+
5. Only if I confirm, run gh issue create --title <title> --body-file <reportPath>, then attach the GIF to the issue.
|
|
419
|
+
Report the folder path, the steps, the error text found, and what was redacted.`,demoGif:(t,e)=>`Make a demo GIF of ${t} for a README or PR, under ${e} MB.
|
|
420
|
+
|
|
421
|
+
1. start_recording { target: "${t}", events: true }, walk through the feature (or ask me to), then stop_recording.
|
|
422
|
+
2. contact_sheet { input: <recording>, mode: "scenes" } to see the whole run at a glance and pick the best stretch.
|
|
423
|
+
3. pipeline { input: <recording>, recipe: "pr_demo", steps: [{ op: "trim", ... that stretch }, { op: "export_gif", maxBytes: ${Math.round(Number(e)*1e6)||1e7} }] }: one pass that cuts idle time, zooms toward the clicks, and writes the GIF (dryRun first to see the steps). If it does not fit, try format: "webp" or a shorter stretch.
|
|
424
|
+
Report the file path, its size, and the settings export_gif chose.`,verifyUiChange:(t,e)=>`Verify a UI change in ${t}. Expected: ${e||"(describe what should change)"}.
|
|
425
|
+
|
|
426
|
+
1. screenshot { target: "${t}" } as the "before" image.
|
|
427
|
+
2. Make the change (run the action, reload, or ask me to).
|
|
428
|
+
3. wait_for_change { target: "${t}", mode: "settle" } so you check after the screen has finished updating, not mid-render.
|
|
429
|
+
4. screen_diff { a: <before>, b: <after> } and look at where it changed.
|
|
430
|
+
5. If the expectation mentions text, find_text { target: "${t}", query: <that text> } to confirm it is really on screen.
|
|
431
|
+
Say whether the change happened, whether anything changed that should not have, and show the evidence.`,reviewRecording:t=>`Review the recording at ${t} and tell me what happens in it.
|
|
432
|
+
|
|
433
|
+
1. get_media_info { input: "${t}" } for length and resolution.
|
|
434
|
+
2. contact_sheet { input: "${t}" } for an overview of the whole recording in one image.
|
|
435
|
+
3. sample_frames { input: "${t}", mode: "scenes" } to look closely at each change.
|
|
436
|
+
4. If there is on-screen text worth quoting, find_text on the relevant frame.
|
|
437
|
+
Give a timestamped summary of the main steps and anything that looks wrong.`,documentSteps:(t,e)=>`Document ${e?`how to ${e}`:"what I do next"} as a step-by-step guide.
|
|
438
|
+
|
|
439
|
+
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.
|
|
440
|
+
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.
|
|
441
|
+
3. Read the returned steps and rewrite any vague caption ("Click the marked spot") in guide.md, using the screenshot to name the control.
|
|
442
|
+
Report the guide paths, the steps, and anything you would check before sharing it.`};function Fw(t){t.registerPrompt("bug-repro-clip",{title:"Record a bug reproduction",description:"Record a target, find the bug moment, redact secrets, trim, annotate, and export a GIF for an issue.",argsSchema:{target:it.string().optional().describe("What to record, e.g. window:My App (default: full)."),notes:it.string().optional().describe("What the bug is.")}},({target:e,notes:r})=>Qn(Zn.bugReproClip(e||"full",r??""))),t.registerPrompt("file-bug-report",{title:"File a bug report",description:"Record a repro with input events, then package it with bug_report: redacted clip, GIF, steps, error text, and report.md.",argsSchema:{target:it.string().optional().describe("What to record, e.g. window:My App (default: full)."),notes:it.string().optional().describe("What the bug is."),expected:it.string().optional().describe("What should happen instead.")}},({target:e,notes:r,expected:n})=>Qn(Zn.fileBugReport(e||"full",r??"",n??""))),t.registerPrompt("demo-gif",{title:"Make a demo GIF",description:"Record a feature walkthrough and export a GIF small enough for a README or PR.",argsSchema:{target:it.string().optional().describe("What to record (default: full)."),maxMB:it.string().optional().describe("Size budget in MB (default 10).")}},({target:e,maxMB:r})=>Qn(Zn.demoGif(e||"full",r||"10"))),t.registerPrompt("verify-ui-change",{title:"Verify a UI change",description:"Screenshot before, make the change, wait for the screen to settle, diff, and check the text.",argsSchema:{target:it.string().optional().describe("What to watch (default: full)."),expectation:it.string().optional().describe("What should change.")}},({target:e,expectation:r})=>Qn(Zn.verifyUiChange(e||"full",r??""))),t.registerPrompt("review-recording",{title:"Review a recording",description:"Summarize what happens in a recording, with timestamps, using a contact sheet and scene frames.",argsSchema:{path:it.string().describe("Path to the recording.")}},({path:e})=>Qn(Zn.reviewRecording(e))),t.registerPrompt("document-steps",{title:"Document what I just did",description:"Record a task with input events and markers, then turn it into a step-by-step guide with step_guide.",argsSchema:{target:it.string().optional().describe("What to record (default: full)."),task:it.string().optional().describe("The task the guide teaches.")}},({target:e,task:r})=>Qn(Zn.documentSteps(e||"full",r??"")))}import{fileURLToPath as UT}from"node:url";import{RootsListChangedNotificationSchema as zT}from"@modelcontextprotocol/sdk/types.js";function HT(t){let e=[];for(let{uri:r}of t)if(r.startsWith("file:"))try{e.push(UT(r))}catch{}return e}function Ow(t){let e=t.server,r=async o=>{if(!e.getClientCapabilities()?.roots){so(null);return}o&&so("pending");try{let{roots:i}=await e.listRoots();so(HT(i))}catch(i){o&&so([]),process.stderr.write(`roots/list failed: ${H(i)}
|
|
443
|
+
`)}},n=e.oninitialized;e.oninitialized=()=>{n?.(),r(!0)},e.setNotificationHandler(zT,()=>r(!1))}var GT=new Set(["input","inputs","inputA","inputB","clips","a","b","image","overlay","music","video","subtitles","srt","transcript","events"]),qT=new Set(["output","outputDir","model","fontFile"]),XT=new Set(["whisper"]);function Nw(t){return typeof t=="string"?[t]:Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Dw(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(GT.has(n))for(let i of Nw(o))i.trim().length>0&&!XT.has(i)&&Ul(i,`Input "${n}"`);else if(qT.has(n))for(let i of Nw(o))Jt(i,`"${n}"`);o&&typeof o=="object"&&e(o)}};e(t)}var YT=wt();function rc(t={}){let e=mi(t.toolsets??process.env.SCREENCAST_TOOLSETS);e.unknown.length>0&&console.error(`screencast-mcp: ignoring unknown SCREENCAST_TOOLSETS entries: ${e.unknown.join(", ")} (known: all, ${di.join(", ")})`);let r=new JT({name:"screencast-mcp",version:YT},{capabilities:{logging:{}},instructions:Ol(e)});hp(r);let n=KT(r);return ef(r),rf(r),zf(r),qf(r),Jf(r),Hf(r),Vf(r),Qf(r),eh(r),th(r),$h(r),kh(r),_h(r),Th(r),Fh(r),Lh(r),Bh(r),Xh(r),Kh(r),Vh(r),Qh(r),ag(r),cg(r),mg(r),fg(r),hg(r),bg(r),wg(r),kg(r),Eg(r),Mg(r),Ng(r),Ug(r),Jg(r),Yg(r),Kg(r),tb(r),rb(r),nb(r),ob(r),ph(r),ib(r),sb(r),fb(r),hb(r),gb(r),Kf(r),yb(r),Nb(r),Db(r),Lb(r),Wb(r),jb(r),Ub(r),zb(r),Yb(r),sw(r),aw(r),uw(r),Tw(r),VT(n,e),Iw(r),Fw(r),Ow(r),r}function KT(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{Dw(a)}catch(u){return _(u)}return i(a,c)};let s=r(...n);return e.set(n[0],s),s}),e}function VT(t,e){for(let[r,n]of t){let o=Fl(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 Ww}from"node:child_process";import{copyFileSync as QT,existsSync as ZT,mkdirSync as eA,readFileSync as tA,writeFileSync as rA}from"node:fs";import{homedir as nA}from"node:os";import{dirname as oA,join as en}from"node:path";import{createInterface as iA}from"node:readline/promises";var nc=["claude-desktop","claude-code","cursor","vscode"],jw=`setup options:
|
|
444
|
+
--yes answer yes: install FFmpeg and write client configs without asking
|
|
445
|
+
--dry-run print the checks and the config changes; change nothing
|
|
446
|
+
--clients <list> detected (default) | none | a comma list of
|
|
447
|
+
${nc.join(", ")}
|
|
448
|
+
--no-install never offer to install FFmpeg
|
|
449
|
+
--force replace an existing, different "screencast" server entry
|
|
450
|
+
--test record a 3 s test clip and export a GIF
|
|
451
|
+
|
|
452
|
+
setup exits 0 when the doctor checks pass, 1 when something still needs fixing.
|
|
453
|
+
`,Al="@tmhs/screencast-mcp",eo="screencast",Tl={command:"npx",args:["-y",Al]},Lw=["install","--id","Gyan.FFmpeg","-e","--accept-source-agreements","--accept-package-agreements"];function Bw(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=>!nc.includes(u));if(c.length>0)throw new Error(`--clients: unknown client ${c.map(u=>`"${u}"`).join(", ")}; use ${nc.join(", ")}, detected, or none.`);e.clients=a;break}default:throw new Error(`Unknown setup option "${n}". Run screencast-mcp --help.`)}}return e}function sA(t){return t.env.APPDATA??en(t.home,"AppData","Roaming")}function Uw(t){let e=sA(t);return[{id:"claude-desktop",name:"Claude Desktop",path:en(e,"Claude","claude_desktop_config.json"),key:"mcpServers",entry:Tl,marker:en(e,"Claude")},{id:"cursor",name:"Cursor",path:en(t.home,".cursor","mcp.json"),key:"mcpServers",entry:Tl,marker:en(t.home,".cursor")},{id:"vscode",name:"VS Code",path:en(e,"Code","User","mcp.json"),key:"servers",entry:{type:"stdio",...Tl},marker:en(e,"Code","User")}]}function aA(t){return["mcp","add","--scope","user",eo,"--",...t==="win32"?["cmd","/c","npx","-y",Al]:["npx","-y",Al]]}var cA=(t,e)=>JSON.stringify(t)===JSON.stringify(e);function uA(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 (${H(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(cA(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)+`
|
|
454
|
+
`}}function lA(t,e){let r=t===""?[]:t.replace(/\n$/,"").split(`
|
|
455
|
+
`),n=e===""?[]:e.replace(/\n$/,"").split(`
|
|
456
|
+
`),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(`
|
|
457
|
+
`)+`
|
|
458
|
+
`}function pA(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 dA(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 mA={ok:"[ok] ",warn:"[warn]",fail:"[fail]",info:"[info]"};async function fA(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}: ${H(a)}
|
|
459
|
+
`),!1}let s=uA(i,t.key,eo,t.entry,e.force);switch(s.status){case"unchanged":return r.out(` ${t.name}: already configured (${t.path})
|
|
460
|
+
`),!0;case"invalid":return r.out(` ${t.name}: left ${t.path} alone: ${s.reason}. Add the server by hand (see docs/connect.html).
|
|
461
|
+
`),!1;case"conflict":return r.out(` ${t.name}: ${t.path} already has a different "${eo}" entry; kept it (pass --force to replace).
|
|
462
|
+
`),!1}if(e.dryRun)return r.out(` ${t.name}: would ${o?"update":"create"} ${t.path}:
|
|
463
|
+
`),r.out(lA(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).
|
|
464
|
+
`),!1;try{let a=null;return o?(a=pA(t.path,r.now()),n.copyFile(t.path,a)):n.mkdir(oA(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.
|
|
465
|
+
`),!0}catch(a){return r.out(` ${t.name}: could not write ${t.path}: ${H(a)}
|
|
466
|
+
`),!1}}async function hA(t,e){let r=aA(e.platform);if((await e.exec("claude",["mcp","get",eo])).code===0)return e.out(` Claude Code: already has a "${eo}" server (claude mcp get ${eo}).
|
|
467
|
+
`),!0;if(t.dryRun)return e.out(` Claude Code: would run: claude ${r.join(" ")}
|
|
468
|
+
`),!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(" ")}
|
|
469
|
+
`),!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}`}).
|
|
470
|
+
`),!1):(e.out(` Claude Code: added (user scope). Check it with claude mcp list.
|
|
471
|
+
`),!0)}async function gA(t){let e=[];for(let n of Uw(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"),nc.filter(n=>e.includes(n))}async function zw(t,e){let r=e.out;r(`screencast-mcp setup${t.dryRun?" (dry run: nothing is installed or written)":""}
|
|
472
|
+
|
|
473
|
+
`);let n;try{n=await e.doctor()}catch(c){return e.err(`screencast-mcp: the doctor checks failed to run: ${H(c)}
|
|
474
|
+
`),1}for(let c of dA(n,e.env,e.platform))r(`${mA[c.state]} ${c.text}
|
|
475
|
+
`);let o=n.problems??[];if(o.length>0){r(`
|
|
476
|
+
What doctor says to fix:
|
|
477
|
+
`);for(let c of o)r(` - ${c}
|
|
478
|
+
`)}let i=n.ffmpeg??{};if((!i.found||i.meetsFfmpeg8===!1)&&t.install&&e.platform==="win32"){let c=`winget ${Lw.join(" ")}`;if(r(`
|
|
479
|
+
FFmpeg 8 ${i.found?"is not installed (found an older one)":"is missing"}.
|
|
480
|
+
`),t.dryRun)r(` would run: ${c}
|
|
481
|
+
`);else if(t.yes||await e.confirm("Install FFmpeg 8 with winget now?")){r(` running: ${c}
|
|
482
|
+
`);let u=await e.exec("winget",Lw).catch(d=>({code:1,stdout:"",stderr:H(d)}));u.code===0?r(` FFmpeg installed. Open a new terminal so PATH picks it up, then run setup again.
|
|
483
|
+
`):r(` winget failed (${(u.stderr||u.stdout).trim().split(`
|
|
484
|
+
`).pop()||`exit ${u.code}`}). Install it yourself: ${c}
|
|
485
|
+
`)}else r(` skipped. Install it yourself: ${c}
|
|
486
|
+
`)}if(t.clients!=="none"){let c=t.clients==="detected"?await gA(e):t.clients;r(`
|
|
487
|
+
MCP clients:
|
|
488
|
+
`),c.length===0&&r(` none found (Claude Desktop, Claude Code, Cursor, VS Code). Name one with --clients, or see docs/connect.html.
|
|
489
|
+
`);let u=new Map(Uw(e).map(d=>[d.id,d]));for(let d of c){let p=u.get(d);p?await fA(p,t,e):await hA(t,e)}}if(t.test)if(r(`
|
|
490
|
+
Test clip:
|
|
491
|
+
`),t.dryRun)r(` would record 3 s of the screen and export a GIF.
|
|
492
|
+
`);else try{let c=await e.testClip();r(` recorded 3 s and exported ${c}
|
|
493
|
+
`),await e.open(c).catch(()=>{})}catch(c){return r(` the test clip failed: ${H(c)}
|
|
494
|
+
`),1}let a=n.ok??o.length===0;return r(a?`
|
|
495
|
+
All checks passed.
|
|
496
|
+
`:`
|
|
497
|
+
Some checks need attention (above). Run setup again after fixing them.
|
|
498
|
+
`),a?0:1}function bA(t){return(e,r)=>new Promise(n=>{let o=Ww(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 wA={exists:t=>ZT(t),readFile:t=>tA(t,"utf8"),writeFile:(t,e)=>rA(t,e),mkdir:t=>{eA(t,{recursive:!0})},copyFile:(t,e)=>QT(t,e)};function Hw(t){let e=process.platform,r=bA(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:nA(),fs:wA,exec:r,doctor:()=>n(async i=>await o(i,"doctor",{})),confirm:async i=>{if(!process.stdin.isTTY||!process.stdout.isTTY)return!1;let s=iA({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||Ww("explorer.exe",[i],{detached:!0,stdio:"ignore"}).unref()},now:()=>new Date}}var Xw=wt(),Ie=class extends Error{},_A=new Set(["record","call","setup","help","--help","-h","--version","-v"]);function Jw(t){return t.length>0&&_A.has(t[0]??"")}var TA=`screencast-mcp: an MCP server for Windows screen recording.
|
|
499
|
+
|
|
500
|
+
Usage:
|
|
501
|
+
screencast-mcp run the MCP server over stdio (default)
|
|
502
|
+
screencast-mcp record [options] -- <command...>
|
|
503
|
+
record the screen while <command> runs
|
|
504
|
+
screencast-mcp record [options] --command-env <NAME>
|
|
505
|
+
the same, running the command in env var NAME
|
|
506
|
+
screencast-mcp call <tool> [json|@file] call one tool and print its result
|
|
507
|
+
screencast-mcp setup [options] check this machine and wire up MCP clients
|
|
508
|
+
screencast-mcp --version | --help
|
|
509
|
+
|
|
510
|
+
record options:
|
|
511
|
+
--target <target> full | monitor:<i> | window:<title> | region:x,y,w,h (default full)
|
|
512
|
+
--fps <n> capture frame rate, 1-120 (default 15)
|
|
513
|
+
--out <dir> output folder (default screencast-evidence)
|
|
514
|
+
--artifacts <when> make the GIF and contact sheet on: failure | always | never (default failure)
|
|
515
|
+
--last <sec> the GIF covers the last <sec> seconds; 0 = all (default 30)
|
|
516
|
+
--no-gif skip the GIF
|
|
517
|
+
--no-contact-sheet skip the contact sheet
|
|
518
|
+
--discard-on-success delete the recording when the command exits 0
|
|
519
|
+
--ocr-errors on failure, OCR the last <sec> seconds for error lines (Windows OCR)
|
|
520
|
+
--redact-secrets OCR the recording and blur on-screen secrets (API keys, tokens,
|
|
521
|
+
password: values) in the GIF and contact sheet (Windows OCR)
|
|
522
|
+
--secret-pattern <re> with --redact-secrets, the regex to blur instead of the default
|
|
523
|
+
--max-duration <sec> stop recording after <sec> seconds, an integer 0-${At}
|
|
524
|
+
(0 = no cap; default SCREENCAST_MAX_RECORDING_SEC, else 3600)
|
|
525
|
+
--command-env <NAME> run the command line in environment variable NAME instead of
|
|
526
|
+
the arguments after --, so quotes and & survive any shell
|
|
527
|
+
|
|
528
|
+
record exits with the command's exit code and writes <out>/evidence.json.
|
|
529
|
+
|
|
530
|
+
${jw}`;function AA(t,e,r){let n=t[e+1];if(n===void 0||n==="--")throw new Ie(`${r} needs a value.`);return n}function Rl(t,e,r,n=1/0,o=!1){let i=Number(t);if(t.trim()===""||!Number.isFinite(i)||i<r||i>n||o&&!Number.isInteger(i)){let s=n===1/0?`>= ${r}`:`${r}-${n}`;throw new Ie(`${e} must be ${o?"an integer":"a number"} ${s}, got "${t}".`)}return i}function RA(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=AA(i,s,u);return s++,f};switch(u){case"--target":n.target=p();break;case"--fps":n.fps=Rl(p(),u,1,120,!0);break;case"--out":n.outDir=p();break;case"--artifacts":{let f=p();if(f!=="failure"&&f!=="always"&&f!=="never")throw new Ie(`--artifacts must be failure, always, or never, got "${f}".`);n.artifacts=f;break}case"--last":n.lastSec=Rl(p(),u,0);break;case"--max-duration":n.maxDurationSec=Rl(p(),u,0,At,!0);break;case"--command-env":o=p();break;case"--no-gif":n.gif=!1;break;case"--no-contact-sheet":n.contactSheet=!1;break;case"--discard-on-success":n.discardOnSuccess=!0;break;case"--redact-secrets":n.redactSecrets=!0;break;case"--secret-pattern":n.secretPattern=p();break;case"--ocr-errors":n.ocrErrors=!0;break;default:throw new Ie(`Unknown record option "${a}". Run screencast-mcp --help.`)}}if(o!==void 0){if(n.command.length>0)throw new Ie("Give the command either after -- or with --command-env, not both.");let s=e[o];if(s===void 0||s.trim()==="")throw new Ie(`--command-env ${o}: the environment variable is unset or empty.`);n.command=[s]}else if(n.command.length===0)throw new Ie("record needs a command after -- (or --command-env NAME), e.g. screencast-mcp record -- npm test");return n}function MA(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:RA(n,e)};case"call":{let[o,i,s]=n;if(!o||o.startsWith("-"))throw new Ie("call needs a tool name, e.g. screencast-mcp call doctor");if(s!==void 0)throw new Ie("call takes one JSON argument; quote it as a single string.");return{kind:"call",tool:o,args:i}}case"setup":{if(n[0]==="--help"||n[0]==="-h")return{kind:"help"};try{return{kind:"setup",options:Bw(n)}}catch(o){throw new Ie(H(o))}}default:throw new Ie(`Unknown command "${r??""}". Run screencast-mcp --help.`)}}var Gw=/([()\][%!^"`<>&|;, *?])/g,CA=/(\.(cmd|bat)$)|^(npm|npx|pnpm|yarn|corepack)$/i;function PA(t){return`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}var Yw=/[\s"&|<>^()!;'`$*?%,[\]]/;function IA(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=CA.test(t[0]??"");return t.map((n,o)=>{if(o===0||!Yw.test(n)&&n!=="")return n;let i=PA(n).replace(Gw,"^$1");return r&&(i=i.replace(Gw,"^$1")),i}).join(" ")}function FA(t){return t.length===1?t[0]??"":t.map(e=>Yw.test(e)||e===""?`"${e.replace(/"/g,'\\"')}"`:e).join(" ")}function Kw(t,e){return!e||t===null||t<=e?{}:{start:Math.round((t-e)*1e3)/1e3,duration:e}}function OA(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>=$u))break}return Ne(n,Ge)}function NA(t,e=r=>SA(r,"utf8")){if(t===void 0||t.trim()==="")return{};let r=t.startsWith("@")?e(t.slice(1)):t,n;try{n=JSON.parse(r)}catch(o){throw new Ie(`Tool arguments are not valid JSON: ${H(o)}`)}if(typeof n!="object"||n===null||Array.isArray(n))throw new Ie("Tool arguments must be a JSON object.");return n}async function Cl(){let[t,e]=EA.createLinkedPair();await rc({toolsets:"all"}).connect(e);let r=new kA({name:"screencast-mcp-cli",version:Xw});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(`
|
|
531
|
+
`);return{isError:i.isError===!0,text:s,structured:i.structuredContent}},close:()=>r.close()}}async function _r(t,e,r){let n=await t.call(e,r);if(n.isError)throw new Error(`${e}: ${n.text}`);return n.structured??{}}var Vw={out:t=>process.stdout.write(t),err:t=>process.stderr.write(t)};function DA(t){return new Promise(e=>{let r=xA(IA(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}
|
|
532
|
+
`),s(127)}),r.on("exit",(a,c)=>s(a??(c?1:0)))})}function LA(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 WA={connect:Cl,run:DA,now:()=>Date.now()};async function jA(t,e=Vw,r=WA){let n=$A(t.outDir);yA(n,{recursive:!0});let o={command:FA(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}
|
|
533
|
+
`)},s=await r.connect();try{let a=null;try{let p=await _r(s,"start_recording",{target:t.target,fps:t.fps,output:to(n,"recording.mp4"),overwrite:!0,...t.maxDurationSec!==void 0?{maxDurationSec:t.maxDurationSec}:{}});a=String(p.sessionId),e.err(`screencast-mcp: recording ${t.target} to ${String(p.outputPath)}
|
|
534
|
+
`)}catch(p){i(`recording did not start, running the command without it: ${H(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 _r(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=LA(o.status,o.endReason,o.durationSec);f&&i(f)}catch(p){i(`stop_recording failed: ${H(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 BA(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: ${H(m)}`),p=null}if(p&&t.gif)try{let m=await _r(s,"export_gif",{input:p,...Kw(o.durationSec,t.lastSec),output:to(n,"evidence.gif"),overwrite:!0});o.gif=String(m.outputPath)}catch(m){i(`export_gif failed: ${H(m)}`)}if(p&&t.contactSheet)try{let m=await _r(s,"contact_sheet",{input:p,output:to(n,"contact-sheet.png"),overwrite:!0,returnImage:!1});o.contactSheet=String(m.outputPath)}catch(m){i(`contact_sheet failed: ${H(m)}`)}f&&Ml(f,{force:!0})}o.recording&&u&&t.ocrErrors&&(o.errors=await UA(s,o.recording,o.durationSec,t.lastSec,n,i)),!u&&t.discardOnSuccess&&o.recording&&(Ml(o.recording,{force:!0}),o.recording=null)}finally{await s.close()}return vA(to(n,"evidence.json"),JSON.stringify(o,null,2)+`
|
|
535
|
+
`),e.err(`screencast-mcp: command exited ${o.exitCode}; evidence in ${n}`+(o.gif?` (gif: ${o.gif})`:"")+`
|
|
536
|
+
`),o.exitCode}var qw=120;async function BA(t,e,r,n,o,i){let s=Math.max(1,Math.ceil((r??0)/qw)),a=await _r(t,"find_text",{input:e,scanEverySec:s,maxFrames:qw,query:n??Ge,regex:!0,redact:!0,returnImage:!1}),c=Array.isArray(a.redactRegions)?a.redactRegions:[];if(c.length===0)return null;let u=await _r(t,"redact_region",{input:e,regions:c,style:"blur",output:to(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 UA(t,e,r,n,o,i){let s=Kw(r,n),a=e,c=null;try{if(s.start!==void 0){let p=await _r(t,"trim",{input:e,start:s.start,duration:s.duration,output:to(o,".ocr-tail.mp4"),overwrite:!0});c=String(p.outputPath),a=c}let u=await _r(t,"find_text",{input:a,scanEverySec:1,maxFrames:30,query:Ms,regex:!0,returnImage:!1}),d=Array.isArray(u.matches)?u.matches:[];return OA(d)}catch(u){return i(`OCR of error lines failed: ${H(u)}`),null}finally{c&&Ml(c,{force:!0})}}async function zA(t,e,r){let n=NA(e),o=await Cl();try{let i=await o.call(t,n);return i.isError?(r.err(`${i.text}
|
|
537
|
+
`),1):(r.out((i.structured?JSON.stringify(i.structured,null,2):i.text)+`
|
|
538
|
+
`),0)}finally{await o.close()}}async function Qw(t,e=Vw){let r;try{r=MA(t)}catch(n){if(n instanceof Ie)return e.err(`screencast-mcp: ${n.message}
|
|
539
|
+
`),2;throw n}switch(r.kind){case"help":return e.out(TA),0;case"version":return e.out(`${Xw}
|
|
540
|
+
`),0;case"record":return jA(r.options,e);case"setup":return zw(r.options,Hw({connect:Cl,io:e}));case"call":try{return await zA(r.tool,r.args,e)}catch(n){if(n instanceof Ie)return e.err(`screencast-mcp: ${n.message}
|
|
541
|
+
`),2;throw n}}}import{readdir as Zw,rmdir as HA,stat as GA,unlink as qA}from"node:fs/promises";import{join as ro}from"node:path";var Il="SCREENCAST_RETENTION_DAYS";function ex(t=process.env){let e=Number(t[Il]);return Number.isFinite(e)&&e>0?e:null}var Pl=/\.index\.json(\.\d+\.tmp)?$/;async function tx(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 Zw(s)}catch{return}for(let d of u){let p=ro(s,d);try{let f=await GA(p);if(f.isDirectory()){if(!c)continue;await i(p,a,!0),(await Zw(p)).length===0&&f.mtimeMs<n&&await HA(p)}else!a(d)&&f.mtimeMs<n&&(await qA(p),o.removed++,o.bytes+=f.size)}catch{}}};return await i(ro(r,"screenshots"),()=>!1,!0),await i(ro(r,"frames"),()=>!1,!0),await i(ro(r,"recordings"),s=>!/\.events\.raw(\.stop)?$/.test(s)&&!Pl.test(s),!1),await i(ro(r,"edits"),s=>!Pl.test(s),!1),await i(ro(r,"edits","indexes"),s=>!Pl.test(s),!1),o}var rx=1e4;async function JA(){let t=rc();YA();try{let n=ie().reapOrphans();n.length>0&&process.stderr.write(`Reaped ${n.length} orphaned recording(s) on startup.
|
|
542
|
+
`)}catch(n){process.stderr.write(`Orphan reaping skipped: ${H(n)}
|
|
543
|
+
`)}try{let n=ie().list().flatMap(i=>i.status==="recording"&&i.replay?[i.replay.dir]:[]),o=sd(n);o>0&&process.stderr.write(`Removed ${o} leftover replay buffer(s).
|
|
544
|
+
`)}catch(n){process.stderr.write(`Replay buffer cleanup skipped: ${H(n)}
|
|
545
|
+
`)}let e=new XA;await t.connect(e);let r=ex();r!==null&&tx(r).then(n=>{n.removed>0&&process.stderr.write(`Deleted ${n.removed} capture file(s) older than ${r} day(s) (${Il}).
|
|
546
|
+
`)},n=>{process.stderr.write(`Retention prune failed: ${H(n)}
|
|
547
|
+
`)}),process.stdin.on("end",()=>{no("client disconnected")}),process.stdin.on("close",()=>{no("client disconnected")}),t.server.onclose=()=>{no("transport closed")};for(let n of["SIGINT","SIGTERM","SIGHUP"])process.on(n,()=>{no(n)})}function YA(){process.stdout.on("error",t=>{t.code!=="EPIPE"&&process.stderr.write(`stdout error: ${t.message}
|
|
548
|
+
`),no("client pipe closed")}),process.on("uncaughtException",t=>{process.stderr.write(`Uncaught exception: ${t.stack??t.message}
|
|
549
|
+
`),no("uncaught exception",1)}),process.on("unhandledRejection",t=>{process.stderr.write(`Unhandled rejection: ${t instanceof Error?t.stack??t.message:String(t)}
|
|
550
|
+
`)})}async function no(t,e=0){if(ms())return;_m();let r=Ap();try{await Am(rx)||process.stderr.write(`Shutdown (${t}): a start_recording call did not finish within ${rx/1e3}s.
|
|
551
|
+
`),Dm();let o=ie();if(o.activeIds().length>0){let i=null;try{i=E().ffprobe}catch{}let s=await Zd(o,a=>i?ue(a,{ffprobe:i}):Promise.resolve(null));process.stderr.write(`Shutdown (${t}): stopped ${s.length} recording(s).
|
|
552
|
+
`)}}catch(o){process.stderr.write(`Shutdown cleanup failed: ${H(o)}
|
|
553
|
+
`)}let n=await r;n>0&&process.stderr.write(`Shutdown (${t}): cancelled ${n} edit job(s).
|
|
554
|
+
`),process.exit(e)}var nx=t=>{process.stderr.write(`Fatal error: ${H(t)}
|
|
555
|
+
`),process.exit(1)},ox=process.argv.slice(2);Jw(ox)?(process.stdout.on("error",t=>{t.code!=="EPIPE"&&process.stderr.write(`stdout error: ${t.message}
|
|
556
|
+
`)}),Qw(ox).then(t=>process.exit(t),nx)):JA().catch(nx);
|