claude-code-session-manager 0.141.0 → 0.142.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History-DJMiuXyK.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-C1v91GEO.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +52 -18
  25. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  26. package/scripts/README.md +1 -0
  27. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  28. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  29. package/scripts/scheduler-mcp-server.cjs +732 -110
  30. package/src/main/adminRouteRegistry.cjs +59 -0
  31. package/src/main/agentLibrary.cjs +72 -4
  32. package/src/main/agentsIpc.cjs +3 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/chatRunner.cjs +231 -16
  35. package/src/main/config.cjs +30 -0
  36. package/src/main/docEdit.cjs +4 -2
  37. package/src/main/health.cjs +91 -0
  38. package/src/main/index.cjs +98 -48
  39. package/src/main/ipcSchemas.cjs +161 -8
  40. package/src/main/lib/AGENTS.md +1 -1
  41. package/src/main/lib/chatBootRecovery.cjs +2 -0
  42. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  43. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  44. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  45. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  46. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  47. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  48. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  49. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  50. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  51. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  52. package/src/main/lib/demo-video-kit/cast.md +43 -0
  53. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  54. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  55. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  56. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  57. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  58. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  59. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  60. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  61. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  62. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  63. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  64. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  65. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  66. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  67. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  68. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  69. package/src/main/lib/epic/artifactStore.cjs +392 -0
  70. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  71. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  72. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  73. package/src/main/lib/epic/epicMint.cjs +43 -1
  74. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  75. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  76. package/src/main/lib/epic/epicPurge.cjs +347 -0
  77. package/src/main/lib/epic/epicReopen.cjs +5 -2
  78. package/src/main/lib/epic/epicSettle.cjs +4 -13
  79. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  80. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  81. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  82. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  83. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  84. package/src/main/lib/externalContract.cjs +37 -4
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  90. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  91. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  92. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  93. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  94. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  95. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  96. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  97. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  98. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  99. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  100. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  101. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  102. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  103. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  104. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  105. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  106. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  107. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  111. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  112. package/src/main/lib/mcpToolCatalog.cjs +304 -28
  113. package/src/main/lib/opsOwnership.cjs +29 -1
  114. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  115. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  116. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  117. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  118. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  119. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  120. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  121. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  122. package/src/main/lib/phaseProjection.cjs +103 -0
  123. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  124. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  125. package/src/main/lib/prd/prdCreate.cjs +41 -5
  126. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  127. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  128. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  129. package/src/main/lib/prd/prdSizing.cjs +3 -1
  130. package/src/main/lib/process/cleanEnv.cjs +52 -1
  131. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  132. package/src/main/lib/process/memoryScope.cjs +31 -3
  133. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  134. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  135. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  136. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  137. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  138. package/src/main/lib/promptSessionSchema.cjs +6 -0
  139. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  140. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  141. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  142. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  143. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  144. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  145. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  146. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  147. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  148. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  149. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  150. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  151. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  152. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  153. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  154. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  155. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  156. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  157. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  158. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  159. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  160. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  161. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  162. package/src/main/lib/tasks/taskRun.cjs +186 -17
  163. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  164. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  165. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  166. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  167. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  168. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  169. package/src/main/lib/toolUseClassify.cjs +181 -0
  170. package/src/main/lib/util/smfileRange.cjs +77 -0
  171. package/src/main/projectPages.cjs +3 -1
  172. package/src/main/promptSessionEvents.cjs +5 -0
  173. package/src/main/pty.cjs +68 -0
  174. package/src/main/queueOps.cjs +32 -13
  175. package/src/main/runVerify.cjs +74 -9
  176. package/src/main/scheduler/AGENTS.md +1 -0
  177. package/src/main/scheduler/budget.cjs +6 -5
  178. package/src/main/scheduler/prdParser.cjs +46 -13
  179. package/src/main/scheduler/reviewLadder.cjs +9 -25
  180. package/src/main/scheduler/utilizationHold.cjs +101 -0
  181. package/src/main/scheduler.cjs +1414 -189
  182. package/src/main/templates/PRD_AUTHORING.md +5 -2
  183. package/src/main/webRemote.cjs +463 -6
  184. package/src/preload/api.d.ts +529 -38
  185. package/src/preload/apiSurface.json +209 -7
  186. package/src/preload/index.cjs +46 -1
  187. package/src/seed/agents/architect.md +6 -1
  188. package/src/seed/agents/blender-artist.md +2 -1
  189. package/src/seed/agents/competitive-analyst.md +3 -1
  190. package/src/seed/agents/competitive-researcher.md +2 -1
  191. package/src/seed/agents/demo-video-builder.md +87 -83
  192. package/src/seed/agents/dev-lead.md +3 -3
  193. package/src/seed/agents/project-home-builder.md +9 -31
  194. package/src/seed/agents/validator.md +9 -10
  195. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  196. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  197. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  198. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  199. package/dist/assets/index-B2TQz3nd.js +0 -3121
  200. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -1,9 +1,15 @@
1
1
  'use strict';
2
- // Demo-video kit capture helper: up to 6 size-budgeted screenshots (and optional short clips)
3
- // of the live product at one URL. Playwright is resolved at runtime via playwrightLoader.cjs (cwd, global npm root,
4
- // npx cache, or an injected loader) and is never installed here. Node builtins only.
2
+ // Demo-video kit capture helper: up to 6 size-budgeted screenshots and short clips of the live
3
+ // product at one URL. Playwright is resolved at runtime via playwrightLoader.cjs (cwd, global npm root,
4
+ // npx cache, or an injected loader) and is never installed here. A clip shot with no injected encoder
5
+ // is recorded with Playwright's recordVideo and transcoded by ffmpeg (no shell, bounded) to an
6
+ // H.264/yuv420p/+faststart MP4 with no audio; ffprobe (no shell, bounded; SM_FFPROBE, else the ffprobe
7
+ // beside SM_FFMPEG, else PATH) then checks its length, falling back to ffmpeg's own decode output
8
+ // (`-i clip -f null -`) when no ffprobe is usable. A clip is dropped as 'probe-failed' only when neither
9
+ // yields a length, and one shorter than durationS minus one frame as 'too-short'. Node builtins only.
5
10
  const fs = require('fs');
6
11
  const path = require('path');
12
+ const { spawnSync } = require('child_process');
7
13
  const { loadPlaywright: defaultLoader } = require('./playwrightLoader.cjs');
8
14
 
9
15
  const MAX_SHOTS = 6;
@@ -12,9 +18,252 @@ const CLIP_BUDGET = 280 * 1024;
12
18
  const QUALITY_STEPS = [80, 65, 52, 40, 30, 20]; // at most 6 tries
13
19
  const NAV_TIMEOUT_MS = 30000;
14
20
  const VIEWPORT = { width: 1280, height: 720 };
21
+ const CLIP_MIN_S = 2;
22
+ const CLIP_MAX_S = 6;
23
+ const CLIP_DEFAULT_S = 4;
24
+ const CLIP_SETTLE_MS = 500;
25
+ const FFMPEG_TIMEOUT_MS = 60000;
26
+ const FFPROBE_TIMEOUT_MS = 15000;
27
+ // Step-down ladder for the default clip encoder: width, fps, then quality (crf) — at most 6 tries.
28
+ const CLIP_STEPS = Object.freeze([
29
+ { width: 1280, fps: 30, crf: 28 },
30
+ { width: 1280, fps: 24, crf: 32 },
31
+ { width: 960, fps: 24, crf: 34 },
32
+ { width: 960, fps: 20, crf: 37 },
33
+ { width: 720, fps: 15, crf: 40 },
34
+ { width: 640, fps: 12, crf: 44 },
35
+ ]);
36
+
37
+ /** Default ffmpeg runner: no shell, bounded by a timeout. Returns spawnSync's result. */
38
+ function defaultFfmpeg(args) {
39
+ const bin = process.env.SM_FFMPEG || 'ffmpeg';
40
+ return spawnSync(bin, args, { encoding: 'utf8', timeout: FFMPEG_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024, shell: false });
41
+ }
42
+
43
+ /**
44
+ * The ffprobe binary to run: SM_FFPROBE when set; else, when SM_FFMPEG is a path, the ffprobe beside it
45
+ * (its basename with 'ffmpeg' swapped for 'ffprobe', e.g. ffmpeg-7.exe -> ffprobe-7.exe, or plain
46
+ * ffprobe[.exe]) if that file exists; else 'ffprobe' from PATH.
47
+ */
48
+ function resolveFfprobeBin(env = process.env) {
49
+ if (env.SM_FFPROBE) return env.SM_FFPROBE;
50
+ const ff = env.SM_FFMPEG;
51
+ if (ff && /[\\/]/.test(ff)) {
52
+ const dir = path.dirname(ff);
53
+ const base = path.basename(ff);
54
+ const ext = path.extname(base);
55
+ const names = [];
56
+ if (/ffmpeg/i.test(base)) names.push(base.replace(/ffmpeg/i, (m) => (m === 'FFMPEG' ? 'FFPROBE' : 'ffprobe')));
57
+ names.push(`ffprobe${ext}`);
58
+ for (const n of names) {
59
+ const cand = path.join(dir, n);
60
+ try { if (fs.statSync(cand).isFile()) return cand; } catch { /* not there */ }
61
+ }
62
+ }
63
+ return 'ffprobe';
64
+ }
65
+
66
+ /** Default ffprobe runner: no shell, bounded by a timeout. Returns spawnSync's result. */
67
+ function defaultFfprobe(args) {
68
+ return spawnSync(resolveFfprobeBin(), args, { encoding: 'utf8', timeout: FFPROBE_TIMEOUT_MS, maxBuffer: 1024 * 1024, shell: false });
69
+ }
70
+
71
+ function hmsToSeconds(h, m, s) {
72
+ const v = Number(h) * 3600 + Number(m) * 60 + Number.parseFloat(s);
73
+ return Number.isFinite(v) ? v : null;
74
+ }
75
+
76
+ /** Seconds from ffmpeg's stderr: the final `time=HH:MM:SS.ss` progress value, else `Duration:`; or null. */
77
+ function parseFfmpegDuration(text) {
78
+ const t = String(text || '');
79
+ let last = null;
80
+ for (const m of t.matchAll(/time=\s*(\d+):(\d{2}):(\d{2}(?:\.\d+)?)/g)) last = m;
81
+ if (last) return hmsToSeconds(last[1], last[2], last[3]);
82
+ const d = /Duration:\s*(\d+):(\d{2}):(\d{2}(?:\.\d+)?)/.exec(t);
83
+ return d ? hmsToSeconds(d[1], d[2], d[3]) : null;
84
+ }
85
+
86
+ /** A media file's duration in seconds from ffmpeg itself (decode to the null muxer): {seconds} or {reason}. */
87
+ function ffmpegDuration(run, file) {
88
+ let r;
89
+ try {
90
+ r = run(['-hide_banner', '-nostdin', '-i', file, '-map', '0:v:0?', '-f', 'null', '-']);
91
+ } catch (e) { return { reason: e && e.message ? e.message : String(e) }; }
92
+ if (!r) return { reason: 'no result' };
93
+ if (r.error) return { reason: r.error.message || String(r.error) };
94
+ const seconds = parseFfmpegDuration(`${r.stderr || ''}\n${r.stdout || ''}`);
95
+ if (seconds === null) return { reason: r.status !== 0 ? `exit ${r.status}: no duration` : 'no duration' };
96
+ return { seconds };
97
+ }
98
+
99
+ /** Clip length via ffprobe, else via ffmpeg's own output; {reason: 'probe-failed: ...'} only when both fail. */
100
+ function clipLength(probe, run, file) {
101
+ const viaProbe = probeDuration(probe, file);
102
+ if (!viaProbe.reason) return viaProbe;
103
+ const viaFfmpeg = ffmpegDuration(run, file);
104
+ if (!viaFfmpeg.reason) return viaFfmpeg;
105
+ return { reason: `${viaProbe.reason}; ffmpeg: ${viaFfmpeg.reason}` };
106
+ }
107
+
108
+ /** A media file's duration in seconds via ffprobe: {seconds} or {reason}. */
109
+ function probeDuration(probe, file) {
110
+ let r;
111
+ try {
112
+ r = probe(['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file]);
113
+ } catch (e) { return { reason: `probe-failed: ${e && e.message ? e.message : String(e)}` }; }
114
+ const fail = ffmpegFailure(r);
115
+ if (fail) return { reason: `probe-failed: ${fail}` };
116
+ const seconds = Number.parseFloat(String(r.stdout || '').trim());
117
+ if (!Number.isFinite(seconds)) return { reason: 'probe-failed: no duration' };
118
+ return { seconds };
119
+ }
120
+
121
+ function ffmpegFailure(r) {
122
+ if (!r) return 'no result';
123
+ if (r.error) return r.error.message || String(r.error);
124
+ if (r.status !== 0) return `exit ${r.status}: ${String(r.stderr || '').slice(-300)}`;
125
+ return null;
126
+ }
127
+
128
+ function ffmpegAvailable(run) {
129
+ try {
130
+ const r = run(['-hide_banner', '-version']);
131
+ return !ffmpegFailure(r);
132
+ } catch { return false; }
133
+ }
134
+
135
+ /** Monotonic milliseconds (unaffected by wall-clock changes). */
136
+ function monoNow() {
137
+ return Number(process.hrtime.bigint()) / 1e6;
138
+ }
139
+
140
+ /** Seconds as an ffmpeg time string, millisecond precision. */
141
+ function secs(s) {
142
+ return (Math.max(0, Number(s) || 0)).toFixed(3);
143
+ }
144
+
145
+ /**
146
+ * ffmpeg args for one ladder step. `startS` is an input seek (-ss before -i, accurate when
147
+ * transcoding) that skips the recording's load lead-in; `durationS` caps the output with -t.
148
+ */
149
+ function clipArgs(input, output, { width, fps, crf, startS, durationS }) {
150
+ return ['-hide_banner', '-nostats', '-loglevel', 'error', '-y', '-ss', secs(startS), '-i', input, '-t', secs(durationS), '-an',
151
+ '-vf', `fps=${fps},scale=${width}:-2:flags=lanczos`,
152
+ '-c:v', 'libx264', '-preset', 'veryfast', '-crf', String(crf), '-pix_fmt', 'yuv420p',
153
+ '-movflags', '+faststart', output];
154
+ }
155
+
156
+ /** Transcode a recorded clip, stepping width/fps/quality down until it fits; {buf, fps} or {reason}. */
157
+ function transcodeToBudget(run, input, outFile, maxWidth, budget, trim) {
158
+ let lastSize = null;
159
+ for (const step of CLIP_STEPS) {
160
+ const width = Math.max(2, Math.min(step.width, maxWidth) & ~1);
161
+ let r;
162
+ try { r = run(clipArgs(input, outFile, { ...step, width, ...trim })); } catch (e) { return { reason: `transcode-failed: ${e.message}` }; }
163
+ const fail = ffmpegFailure(r);
164
+ if (fail) return { reason: `transcode-failed: ${fail}` };
165
+ let buf;
166
+ try { buf = fs.readFileSync(outFile); } catch { return { reason: 'transcode-failed: no output' }; }
167
+ if (buf.length <= budget) return { buf, fps: step.fps };
168
+ lastSize = buf.length;
169
+ }
170
+ try { fs.rmSync(outFile, { force: true }); } catch { /* ignore */ }
171
+ return { reason: `over-budget: smallest ${lastSize} bytes > ${budget}` };
172
+ }
173
+
174
+ /** A clip's length in seconds: 4 when durationS is missing or not a number, else clamped to 2-6. */
175
+ function clipDuration(shot) {
176
+ const d = shot.durationS;
177
+ if (typeof d !== 'number' || !Number.isFinite(d)) return CLIP_DEFAULT_S;
178
+ return Math.max(CLIP_MIN_S, Math.min(CLIP_MAX_S, d));
179
+ }
180
+
181
+ function shotViewport(shot) {
182
+ const v = shot.viewport;
183
+ const w = v && Number(v.width);
184
+ const h = v && Number(v.height);
185
+ if (w > 0 && h > 0) return { width: Math.round(w), height: Math.round(h) };
186
+ return { ...VIEWPORT };
187
+ }
188
+
189
+ /** Scroll by `px` pixels spread over `ms`, or just hold when px is 0. */
190
+ async function scrollOver(page, px, ms) {
191
+ const steps = px ? Math.max(1, Math.round(ms / 100)) : 0;
192
+ if (!steps) { await page.waitForTimeout(ms); return; }
193
+ const per = px / steps;
194
+ for (let i = 0; i < steps; i++) {
195
+ await page.evaluate((dy) => window.scrollBy(0, dy), per);
196
+ await page.waitForTimeout(ms / steps);
197
+ }
198
+ }
199
+
200
+ function scrollPx(shot) {
201
+ const s = shot.scroll;
202
+ if (typeof s === 'number' && Number.isFinite(s)) return s;
203
+ if (s && typeof s === 'object' && Number.isFinite(Number(s.y))) return Number(s.y);
204
+ return 0;
205
+ }
206
+
207
+ /**
208
+ * Default clip path: fresh recordVideo context, then ffmpeg to a budgeted MP4. {buf, focus} or {reason}.
209
+ * Playwright starts a page's video when ctx.newPage() creates the page, before navigation and the
210
+ * settle wait, so the time from right after newPage() to the start of the scripted scroll is
211
+ * measured and trimmed off: the clip starts on the settled page and lasts durationS. The context
212
+ * is closed once (the close flushes the .webm). The transcoded clip's length is then read with
213
+ * ffprobe, or ffmpeg's own output when no ffprobe is usable; one shorter than durationS minus one
214
+ * frame is dropped as 'too-short'.
215
+ */
216
+ async function recordClip({ browser, url, shot, timeout, outDir, outFile, run, probe = defaultFfprobe, now = monoNow }) {
217
+ const viewport = shotViewport(shot);
218
+ const durationS = clipDuration(shot);
219
+ const tmpDir = fs.mkdtempSync(path.join(outDir, '.clip-'));
220
+ try {
221
+ let webm;
222
+ let focus;
223
+ let leadInS = 0;
224
+ try {
225
+ const ctx = await browser.newContext({ viewport, recordVideo: { dir: tmpDir, size: viewport } });
226
+ let closed = false;
227
+ try {
228
+ const page = await ctx.newPage();
229
+ const recStart = now(); // the page's video origin
230
+ page.setDefaultTimeout(timeout);
231
+ await page.goto(url, { timeout, waitUntil: 'load' });
232
+ await page.waitForTimeout(Number(shot.waitMs) >= 0 ? Math.min(Number(shot.waitMs), 10000) : CLIP_SETTLE_MS);
233
+ if (shot.selector) {
234
+ try { await page.locator(shot.selector).first().scrollIntoViewIfNeeded({ timeout }); } catch { /* keep going */ }
235
+ }
236
+ leadInS = Math.max(0, (now() - recStart) / 1000);
237
+ await scrollOver(page, scrollPx(shot), durationS * 1000);
238
+ focus = await focusFor(page, shot, viewport);
239
+ const video = page.video && page.video();
240
+ if (!video) throw new Error('recordVideo produced no video');
241
+ closed = true;
242
+ await ctx.close(); // flushes the .webm
243
+ webm = await video.path();
244
+ } finally {
245
+ if (!closed) await ctx.close().catch(() => {});
246
+ }
247
+ if (!webm || !fs.existsSync(webm)) throw new Error('recorded video file missing');
248
+ } catch (e) {
249
+ return { reason: `record-failed: ${e && e.message ? e.message : String(e)}` };
250
+ }
251
+ const out = transcodeToBudget(run, webm, outFile, viewport.width, CLIP_BUDGET, { startS: leadInS, durationS });
252
+ if (!out.buf) return out;
253
+ const len = clipLength(probe, run, outFile);
254
+ const minS = durationS - 1 / out.fps;
255
+ if (len.reason || len.seconds < minS) {
256
+ try { fs.rmSync(outFile, { force: true }); } catch { /* ignore */ }
257
+ return { reason: len.reason || 'too-short' };
258
+ }
259
+ return { buf: out.buf, focus, durationS };
260
+ } finally {
261
+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* ignore */ }
262
+ }
263
+ }
15
264
 
16
265
  async function defaultEncode(page, { kind, quality }) {
17
- if (kind !== 'image') return null; // clips need an injected encoder; dropped otherwise
266
+ if (kind !== 'image') return null; // clips without an injected encoder go through recordClip
18
267
  return page.screenshot({ type: 'jpeg', quality });
19
268
  }
20
269
 
@@ -29,7 +278,7 @@ async function fitBudget(encode, page, kind, budget) {
29
278
  return null;
30
279
  }
31
280
 
32
- async function focusFor(page, shot) {
281
+ async function focusFor(page, shot, vp = VIEWPORT) {
33
282
  const sel = shot.focusSelector || shot.selector;
34
283
  if (sel) {
35
284
  try {
@@ -37,10 +286,18 @@ async function focusFor(page, shot) {
37
286
  if (b) return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.width), h: Math.round(b.height) };
38
287
  } catch { /* fall through to default */ }
39
288
  }
40
- return { x: Math.round(VIEWPORT.width * 0.25), y: Math.round(VIEWPORT.height * 0.25), w: Math.round(VIEWPORT.width * 0.5), h: Math.round(VIEWPORT.height * 0.5) };
289
+ return { x: Math.round(vp.width * 0.25), y: Math.round(vp.height * 0.25), w: Math.round(vp.width * 0.5), h: Math.round(vp.height * 0.5) };
41
290
  }
42
291
 
43
- async function capture({ url, outDir, shots, max = MAX_SHOTS, loadPlaywright, encode, navTimeoutMs } = {}) {
292
+ /**
293
+ * Capture up to 6 shots of `url`. A shot is `{ kind: 'image' | 'clip', selector?, focusSelector?,
294
+ * scroll?, waitMs?, viewport?, durationS? }`. A clip's durationS defaults to 4 s when missing or not
295
+ * a number and is clamped to 2-6 s; the returned clip starts on the settled page and lasts durationS
296
+ * (a clip that comes out shorter than durationS minus one frame is dropped as 'too-short').
297
+ * `ffmpeg`, `ffprobe` (runners) and `now` (monotonic ms) are injectable for tests.
298
+ * Returns { items, dropped } or { skipped }.
299
+ */
300
+ async function capture({ url, outDir, shots, max = MAX_SHOTS, loadPlaywright, encode, navTimeoutMs, ffmpeg, ffprobe, now } = {}) {
44
301
  if (!url || typeof url !== 'string') return { skipped: 'no-url' };
45
302
  const pw = (loadPlaywright || (() => defaultLoader()))();
46
303
  const resolved = pw && typeof pw.then === 'function' ? await pw : pw;
@@ -53,7 +310,10 @@ async function capture({ url, outDir, shots, max = MAX_SHOTS, loadPlaywright, en
53
310
  const timeout = Math.min(Number(navTimeoutMs) || NAV_TIMEOUT_MS, NAV_TIMEOUT_MS);
54
311
  fs.mkdirSync(outDir, { recursive: true });
55
312
 
313
+ const run = ffmpeg || defaultFfmpeg;
314
+ let hasFfmpeg = null; // probed once, on the first default-encoded clip
56
315
  const items = [];
316
+ const dropped = [];
57
317
  const browser = await chromium.launch({ headless: true });
58
318
  try {
59
319
  const page = await browser.newPage({ viewport: VIEWPORT });
@@ -62,19 +322,29 @@ async function capture({ url, outDir, shots, max = MAX_SHOTS, loadPlaywright, en
62
322
  for (let i = 0; i < list.length; i++) {
63
323
  const shot = list[i] || {};
64
324
  const kind = shot.kind === 'clip' ? 'clip' : 'image';
325
+ const num = String(i + 1).padStart(2, '0');
326
+ if (kind === 'clip' && !encode) {
327
+ if (hasFfmpeg === null) hasFfmpeg = ffmpegAvailable(run);
328
+ if (!hasFfmpeg) { dropped.push({ index: i, kind, reason: 'no-ffmpeg' }); continue; }
329
+ const file = path.join(outDir, `shot-${num}.mp4`);
330
+ const r = await recordClip({ browser, url, shot, timeout, outDir, outFile: file, run, probe: ffprobe || defaultFfprobe, now });
331
+ if (!r.buf) { dropped.push({ index: i, kind, reason: r.reason }); continue; }
332
+ items.push({ file, kind, mime: 'video/mp4', bytes: r.buf.length, durationS: r.durationS, focus: r.focus });
333
+ continue;
334
+ }
65
335
  if (shot.selector) {
66
336
  try { await page.locator(shot.selector).first().scrollIntoViewIfNeeded({ timeout }); } catch { /* keep going */ }
67
337
  }
68
338
  const buf = await fitBudget(enc, page, kind, kind === 'image' ? IMAGE_BUDGET : CLIP_BUDGET);
69
- if (!buf) continue;
70
- const file = path.join(outDir, `shot-${String(i + 1).padStart(2, '0')}.${kind === 'image' ? 'jpg' : 'webm'}`);
339
+ if (!buf) { dropped.push({ index: i, kind, reason: 'over-budget' }); continue; }
340
+ const file = path.join(outDir, `shot-${num}.${kind === 'image' ? 'jpg' : 'webm'}`);
71
341
  fs.writeFileSync(file, buf);
72
- items.push({ file, kind, bytes: buf.length, focus: await focusFor(page, shot) });
342
+ items.push({ file, kind, mime: kind === 'image' ? 'image/jpeg' : 'video/webm', bytes: buf.length, focus: await focusFor(page, shot) });
73
343
  }
74
344
  } finally {
75
345
  await browser.close().catch(() => {});
76
346
  }
77
- return { items };
347
+ return { items, dropped };
78
348
  }
79
349
 
80
- module.exports = { capture, IMAGE_BUDGET, CLIP_BUDGET, QUALITY_STEPS };
350
+ module.exports = { capture, IMAGE_BUDGET, CLIP_BUDGET, QUALITY_STEPS, CLIP_STEPS, resolveFfprobeBin, parseFfmpegDuration };
@@ -0,0 +1,43 @@
1
+ # Playbook: supporting cast
2
+
3
+ Read this when the saved character has a `cast`. It is for the demo-video-builder persona: short
4
+ rules for a video where the host shares the screen with cast members. Everything else in the
5
+ persona still holds.
6
+
7
+ ## Who speaks each line
8
+
9
+ - Every line has one speaker. The speaker is the host, unless the script gives the line to a cast
10
+ member by `name`.
11
+ - A member's lines fit its `note`: its role, manner and the kind of thing it says.
12
+
13
+ ## Which voice speaks it
14
+
15
+ - A `command`-voice line is spoken with `node <kit>/character.cjs speak spec.json`. Each line in
16
+ the spec carries that line's `speaker`, the member's `name`. Omit `speaker` for the host.
17
+ - A `kokoro`-voice line uses the persona's Kokoro recipe with that speaker's `id`.
18
+ - A line is never spoken in another speaker's voice, in Kokoro's default voices, or in any
19
+ fallback voice. There is no fallback.
20
+ - A failing voice fails the run with its error. `character.cjs speak` stops at the first failure
21
+ and refuses an unknown speaker, a member without a voice, and a `kokoro` speaker; report that
22
+ error as it is. Never retry the line in another voice.
23
+
24
+ ## A member without a voice
25
+
26
+ - A member without `voice` never speaks. Give it no lines.
27
+ - It gets sound effects only: sound.cjs cues on its moments, never words.
28
+
29
+ ## Captions
30
+
31
+ - Captions never show a speaker's name unless the script calls for it.
32
+
33
+ ## Looks and lip-sync
34
+
35
+ - A member is drawn only as `character.js` draws it. Never invent a look.
36
+ - A member that `character.js` does not draw is heard, not seen.
37
+ - Each on-screen speaker's mouth moves only on its own lines. The others stay still while
38
+ someone else speaks.
39
+
40
+ ## Character: off
41
+
42
+ - 'Character: off' means no host and no cast: no one drawn, no character voice.
43
+ - meta.character stays the host's name, never a cast member's.