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.
- package/README.md +80 -70
- package/bin/cli.cjs +11 -0
- package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
- package/dist/assets/{History-DJMiuXyK.js → History-DpZuJXi1.js} +1 -1
- package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
- package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-BjdJjhqt.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
- package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
- package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
- package/dist/assets/{Skills-C1v91GEO.js → Skills-vv0noNVI.js} +5 -5
- package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-CXi8Pvut.js} +1 -1
- package/dist/assets/Toggle-CiYCWLjh.js +1 -0
- package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-4NKKd1sC.js} +1 -1
- package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-DDunb8Ch.js} +1 -1
- package/dist/assets/index-Cn5E9958.js +3133 -0
- package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +496 -484
- package/package.json +4 -2
- package/plugins/AGENTS.md +4 -3
- package/plugins/session-manager-dev/hooks/hooks.json +15 -0
- package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +52 -18
- package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
- package/scripts/README.md +1 -0
- package/scripts/hooks/guard-tool-risk.cjs +5 -1
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
- package/scripts/scheduler-mcp-server.cjs +732 -110
- package/src/main/adminRouteRegistry.cjs +59 -0
- package/src/main/agentLibrary.cjs +72 -4
- package/src/main/agentsIpc.cjs +3 -2
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +231 -16
- package/src/main/config.cjs +30 -0
- package/src/main/docEdit.cjs +4 -2
- package/src/main/health.cjs +91 -0
- package/src/main/index.cjs +98 -48
- package/src/main/ipcSchemas.cjs +161 -8
- package/src/main/lib/AGENTS.md +1 -1
- package/src/main/lib/chatBootRecovery.cjs +2 -0
- package/src/main/lib/claude/agentModelResolve.cjs +51 -25
- package/src/main/lib/claude/agentSnapshot.cjs +186 -0
- package/src/main/lib/claude/environmentProfiles.cjs +242 -0
- package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
- package/src/main/lib/claude/personaToolScope.cjs +82 -31
- package/src/main/lib/claude/runClaudeP.cjs +4 -2
- package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
- package/src/main/lib/claude/usageCircuit.cjs +49 -21
- package/src/main/lib/claude/vaultRefs.cjs +277 -0
- package/src/main/lib/demo-video-kit/capture.cjs +282 -12
- package/src/main/lib/demo-video-kit/cast.md +43 -0
- package/src/main/lib/demo-video-kit/character.cjs +722 -30
- package/src/main/lib/demo-video-kit/checks.cjs +120 -1
- package/src/main/lib/demo-video-kit/export.cjs +218 -0
- package/src/main/lib/demo-video-kit/frames.cjs +104 -9
- package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
- package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
- package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
- package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
- package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
- package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
- package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
- package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
- package/src/main/lib/epic/artifactIpc.cjs +153 -0
- package/src/main/lib/epic/artifactNotice.cjs +72 -0
- package/src/main/lib/epic/artifactRetention.cjs +310 -0
- package/src/main/lib/epic/artifactStore.cjs +392 -0
- package/src/main/lib/epic/delegationReadiness.cjs +76 -2
- package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
- package/src/main/lib/epic/epicEventLog.cjs +214 -0
- package/src/main/lib/epic/epicMint.cjs +43 -1
- package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
- package/src/main/lib/epic/epicOutsideState.cjs +18 -4
- package/src/main/lib/epic/epicPurge.cjs +347 -0
- package/src/main/lib/epic/epicReopen.cjs +5 -2
- package/src/main/lib/epic/epicSettle.cjs +4 -13
- package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
- package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
- package/src/main/lib/epic/epicTransitions.cjs +139 -0
- package/src/main/lib/epic/epicValidationHook.cjs +81 -2
- package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
- package/src/main/lib/externalContract.cjs +37 -4
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
- package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
- package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
- package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
- package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
- package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
- package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
- package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
- package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
- package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
- package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
- package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
- package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
- package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
- package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
- package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
- package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
- package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
- package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
- package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
- package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
- package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
- package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
- package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
- package/src/main/lib/git/worktreeDeps.cjs +77 -2
- package/src/main/lib/mcpToolCatalog.cjs +304 -28
- package/src/main/lib/opsOwnership.cjs +29 -1
- package/src/main/lib/opsRetentionSettings.cjs +27 -5
- package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
- package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
- package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
- package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
- package/src/main/lib/phaseProjection.cjs +103 -0
- package/src/main/lib/prd/depSlugResolve.cjs +4 -13
- package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
- package/src/main/lib/prd/prdCreate.cjs +41 -5
- package/src/main/lib/prd/prdCriteria.cjs +225 -0
- package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
- package/src/main/lib/prd/prdGateFiles.cjs +125 -49
- package/src/main/lib/prd/prdSizing.cjs +3 -1
- package/src/main/lib/process/cleanEnv.cjs +52 -1
- package/src/main/lib/process/leftoverRenice.cjs +178 -0
- package/src/main/lib/process/memoryScope.cjs +31 -3
- package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
- package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
- package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
- package/src/main/lib/project-pages/voicePreview.cjs +196 -0
- package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
- package/src/main/lib/promptSessionSchema.cjs +6 -0
- package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
- package/src/main/lib/scheduler/cpuSample.cjs +133 -42
- package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
- package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
- package/src/main/lib/scheduler/loadGate.cjs +82 -4
- package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
- package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
- package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
- package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
- package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
- package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
- package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
- package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
- package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
- package/src/main/lib/scheduler/toolClearance.cjs +258 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
- package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
- package/src/main/lib/tasks/mitigationReview.cjs +294 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
- package/src/main/lib/tasks/taskIpc.cjs +22 -18
- package/src/main/lib/tasks/taskLedger.cjs +147 -25
- package/src/main/lib/tasks/taskRun.cjs +186 -17
- package/src/main/lib/tasks/taskSwitch.cjs +85 -12
- package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
- package/src/main/lib/telemetry/auditEvents.cjs +207 -6
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
- package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
- package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
- package/src/main/lib/toolUseClassify.cjs +181 -0
- package/src/main/lib/util/smfileRange.cjs +77 -0
- package/src/main/projectPages.cjs +3 -1
- package/src/main/promptSessionEvents.cjs +5 -0
- package/src/main/pty.cjs +68 -0
- package/src/main/queueOps.cjs +32 -13
- package/src/main/runVerify.cjs +74 -9
- package/src/main/scheduler/AGENTS.md +1 -0
- package/src/main/scheduler/budget.cjs +6 -5
- package/src/main/scheduler/prdParser.cjs +46 -13
- package/src/main/scheduler/reviewLadder.cjs +9 -25
- package/src/main/scheduler/utilizationHold.cjs +101 -0
- package/src/main/scheduler.cjs +1414 -189
- package/src/main/templates/PRD_AUTHORING.md +5 -2
- package/src/main/webRemote.cjs +463 -6
- package/src/preload/api.d.ts +529 -38
- package/src/preload/apiSurface.json +209 -7
- package/src/preload/index.cjs +46 -1
- package/src/seed/agents/architect.md +6 -1
- package/src/seed/agents/blender-artist.md +2 -1
- package/src/seed/agents/competitive-analyst.md +3 -1
- package/src/seed/agents/competitive-researcher.md +2 -1
- package/src/seed/agents/demo-video-builder.md +87 -83
- package/src/seed/agents/dev-lead.md +3 -3
- package/src/seed/agents/project-home-builder.md +9 -31
- package/src/seed/agents/validator.md +9 -10
- package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
- package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
- package/dist/assets/Scheduler-cyr61UAC.js +0 -16
- package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
- package/dist/assets/index-B2TQz3nd.js +0 -3121
- package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# Playbook: TikTok kind
|
|
2
|
+
|
|
3
|
+
Read this when the `Video kind:` line is TikTok. It is for the demo-video-builder persona: short
|
|
4
|
+
imperative rules for one vertical short built to go viral with this project's own audience.
|
|
5
|
+
|
|
6
|
+
This playbook overrides three persona rules: the stage size, the keystone holds, and the scene
|
|
7
|
+
structure. Everything else in the persona still holds: plain language, the claims list, the
|
|
8
|
+
voice-first rule, the character, the kit-tool failure rule, and the single save call.
|
|
9
|
+
|
|
10
|
+
## Format
|
|
11
|
+
|
|
12
|
+
- Stage: vertical 9:16, 1080x1920 logical pixels, scaled to fit with letterboxing.
|
|
13
|
+
- Put `<meta name="sm-demo-aspect" content="9:16">` in the document head. frames.cjs and export.cjs
|
|
14
|
+
read it to size the viewport and the MP4.
|
|
15
|
+
- Length: 30 s by default; any whole number of seconds from 15 to 60 when the goal asks for it.
|
|
16
|
+
The duration meta and `smDemo.duration` both say it.
|
|
17
|
+
- Frame 0 is the live scene: the subject already on screen, no title card, no fade from black.
|
|
18
|
+
- The hook is visible by 3 s: one on-screen line that names the problem or the surprise.
|
|
19
|
+
- Captions read with the sound muted. Each caption is at most 12 words. Captions carry every
|
|
20
|
+
point the narration makes, so the short works on mute.
|
|
21
|
+
- A cut or a camera move (push in, pan, pull out) at least every 3 s. No hold longer than 3 s;
|
|
22
|
+
the persona's 5 s keystone hold does not apply here.
|
|
23
|
+
- The payoff lands in the last 5 s: what the viewer gets, shown, not told.
|
|
24
|
+
- A loop ending: the last frame matches frame 0's framing and light, so the clip loops cleanly.
|
|
25
|
+
A small "next" tag over the live scene is fine; never a full-screen end card.
|
|
26
|
+
- Safe zone: no text in the bottom 20% or the right 15% of the frame (the app's own buttons and
|
|
27
|
+
caption sit there). Keep text clear of the top bar too.
|
|
28
|
+
|
|
29
|
+
## Structure
|
|
30
|
+
|
|
31
|
+
Replace the persona's title-problem-reveal order with these beats, in order:
|
|
32
|
+
|
|
33
|
+
1. Live open with the hook (0-3 s).
|
|
34
|
+
2. The problem or the mistake, shown.
|
|
35
|
+
3. The turn: the project does the one thing, captured whenever a capture exists.
|
|
36
|
+
4. The payoff (last 5 s).
|
|
37
|
+
5. The loop back to frame 0's framing.
|
|
38
|
+
|
|
39
|
+
One idea per short. If the target has three features, pick the one this audience cares about most.
|
|
40
|
+
|
|
41
|
+
## Episode contract
|
|
42
|
+
|
|
43
|
+
- `seek(t)` is pure: the frame for `t` depends only on `t`, never on history or on the previous
|
|
44
|
+
frame. Re-render from scratch each call.
|
|
45
|
+
- Seeded randomness only: no `Math.random`, no `Date`, in render code. Use a small seeded PRNG
|
|
46
|
+
(mulberry32 or similar) created at module level.
|
|
47
|
+
- One clock: `play()` drives `seek()` from one `requestAnimationFrame` loop. No per-scene timers.
|
|
48
|
+
- Expose on `window.smDemo`, besides the persona's `duration`, `seek`, `play`, `pause`:
|
|
49
|
+
- `smDemo.beats = { hook, payoff, loop }`: the second each beat lands.
|
|
50
|
+
- `smDemo.cuts = [ ... ]`: the second of every cut or camera move, ascending.
|
|
51
|
+
|
|
52
|
+
## Kit checks
|
|
53
|
+
|
|
54
|
+
Run the kit from `~/.claude/session-manager/demo-video-kit/` exactly as the persona says, plus:
|
|
55
|
+
|
|
56
|
+
- Stills check: run frames.cjs `sampleFrames({ htmlPath, lengthS })`, open its contact sheet PNG,
|
|
57
|
+
and look at every still. Each one must read on a phone: subject large, captions legible and inside
|
|
58
|
+
the safe zone, no frame cut off or empty. Fix and re-run until all pass.
|
|
59
|
+
- checks.cjs: pass `tiktok` in the input JSON as
|
|
60
|
+
`{ beats: smDemo.beats, cuts: smDemo.cuts, postCaption: meta.post.caption }`, together with the
|
|
61
|
+
frames from sampleFrames and `lengthS`. The hook, cadence, payoff, loop, safe-zone and
|
|
62
|
+
post-caption checks must all pass before you save.
|
|
63
|
+
- sound.cjs: mix the narration over the music bed; the bed is ducked under speech and the mix is
|
|
64
|
+
normalised to -14 LUFS. When the project has a saved character with a command voice, speak its
|
|
65
|
+
lines with `node character.cjs speak spec.json` first.
|
|
66
|
+
- export.cjs: `node export.cjs spec.json` with `{ htmlPath, lengthS, audioPath, outDir }` writes
|
|
67
|
+
`video.mp4` (1080x1920, H.264/AAC) and `poster.png` in `outDir`. It must exit 0.
|
|
68
|
+
|
|
69
|
+
## Audience rule
|
|
70
|
+
|
|
71
|
+
Decide who the short is for from what the project is and who it is for: read its README, its
|
|
72
|
+
landing copy and its docs, not your guess. Write every hook, caption and line for that audience's
|
|
73
|
+
words and that audience's problem. Save it as `meta.post.audience`, one short sentence.
|
|
74
|
+
|
|
75
|
+
## Post caption rule
|
|
76
|
+
|
|
77
|
+
- At most 150 characters.
|
|
78
|
+
- At most 2 hashtags, at the end.
|
|
79
|
+
- No link, no URL, no domain.
|
|
80
|
+
- The text before the hashtags ends in a short question that invites a comment.
|
|
81
|
+
|
|
82
|
+
Save it as `meta.post.caption`. A style file that forbids questions does not apply here: the
|
|
83
|
+
caption always ends in a short question.
|
|
84
|
+
|
|
85
|
+
## Series rule
|
|
86
|
+
|
|
87
|
+
When the `Video target:` line names a series brief file:
|
|
88
|
+
|
|
89
|
+
1. Read the brief, then every season, canon and ledger file it names.
|
|
90
|
+
2. Make the next episode exactly as they say: its premise, cast, topic and beats. Follow the
|
|
91
|
+
brief's topic; never invent a premise, never pick an episode the files do not schedule.
|
|
92
|
+
3. Use the project persona for the host and voice; never borrow another project's characters.
|
|
93
|
+
4. When the files have no next episode left, in the review stage or the final stage alike,
|
|
94
|
+
call `project_video_outcome_write` once with `{ videoId: <the Entry id>, outcome:
|
|
95
|
+
'season-complete', text: 'Season complete: <brief path> has no next episode' }`. Save no
|
|
96
|
+
video and no review material, end the report with that same `Season complete` line, and
|
|
97
|
+
end PASS: a finished season is a passing run, not a failure.
|
|
98
|
+
|
|
99
|
+
Never update the series files yourself unless the brief says to.
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* kokoroSay.cjs — speak Kokoro-82M (kokoro-onnx) voices from the kit itself.
|
|
3
|
+
*
|
|
4
|
+
* One spawnSync of python loads the model ONCE and writes one WAV per line, so
|
|
5
|
+
* a voice preview and a full video run go through the same code (and the same
|
|
6
|
+
* voice lane). Node built-ins only: this file is copied into the per-machine
|
|
7
|
+
* kit folder by seedKit.cjs and required from any project's cwd.
|
|
8
|
+
*
|
|
9
|
+
* const { sayKokoro } = require('<kit>/kokoroSay.cjs');
|
|
10
|
+
* sayKokoro([{ text: 'Hello.', out: 'a.wav', voice: 'af_heart' }], { cwd })
|
|
11
|
+
* -> { ok: true, outs: [abs...], audioSeconds, seconds: [...] } | { ok: false, error }
|
|
12
|
+
*
|
|
13
|
+
* python: opts.python, else $SM_KOKORO_PYTHON, else python3 (argv ['-c', KOKORO_SCRIPT],
|
|
14
|
+
* JSON {modelDir, lines} on stdin, no shell). Model dir: opts.modelDir, else
|
|
15
|
+
* $KOKORO_MODEL_DIR, else ~/.cache/kokoro-onnx.
|
|
16
|
+
*/
|
|
17
|
+
'use strict';
|
|
18
|
+
|
|
19
|
+
const fs = require('node:fs');
|
|
20
|
+
const os = require('node:os');
|
|
21
|
+
const path = require('node:path');
|
|
22
|
+
const { spawnSync } = require('node:child_process');
|
|
23
|
+
|
|
24
|
+
const MODEL_FILE = 'kokoro-v1.0.onnx';
|
|
25
|
+
const VOICES_FILE = 'voices-v1.0.bin';
|
|
26
|
+
const MODEL_URL_BASE = 'https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0';
|
|
27
|
+
const PIP_INSTALL = 'python3 -m pip install --user --break-system-packages kokoro-onnx soundfile';
|
|
28
|
+
const WAV_HEADER_BYTES = 44;
|
|
29
|
+
const STDERR_TAIL = 500;
|
|
30
|
+
const PER_LINE_TIMEOUT_MS = 15 * 60 * 1000;
|
|
31
|
+
const TIMEOUT_CAP_MS = 180 * 60 * 1000;
|
|
32
|
+
const MAX_BUFFER = 16 * 1024 * 1024;
|
|
33
|
+
const SPEED_MIN = 0.5;
|
|
34
|
+
const SPEED_MAX = 2.0;
|
|
35
|
+
const DEFAULT_LANG = 'en-us';
|
|
36
|
+
|
|
37
|
+
/** Python source run as `python -c KOKORO_SCRIPT`; reads {modelDir, lines} JSON from stdin. */
|
|
38
|
+
const KOKORO_SCRIPT = `
|
|
39
|
+
import json, sys
|
|
40
|
+
def fail(msg):
|
|
41
|
+
print(json.dumps({"ok": False, "error": msg}))
|
|
42
|
+
sys.stdout.flush()
|
|
43
|
+
sys.exit(1)
|
|
44
|
+
try:
|
|
45
|
+
req = json.loads(sys.stdin.read())
|
|
46
|
+
except Exception as e:
|
|
47
|
+
fail("bad request JSON on stdin: %s" % e)
|
|
48
|
+
try:
|
|
49
|
+
import soundfile
|
|
50
|
+
from kokoro_onnx import Kokoro
|
|
51
|
+
except Exception as e:
|
|
52
|
+
fail("import failed (%s: %s); install with: ${PIP_INSTALL}" % (type(e).__name__, e))
|
|
53
|
+
try:
|
|
54
|
+
d = req["modelDir"]
|
|
55
|
+
k = Kokoro(d + "/${MODEL_FILE}", d + "/${VOICES_FILE}")
|
|
56
|
+
seconds = []
|
|
57
|
+
for ln in req["lines"]:
|
|
58
|
+
samples, sr = k.create(ln["text"], voice=ln["voice"], speed=float(ln["speed"]), lang=ln["lang"])
|
|
59
|
+
soundfile.write(ln["out"], samples, sr)
|
|
60
|
+
seconds.append(round(len(samples) / float(sr), 3))
|
|
61
|
+
print(json.dumps({"ok": True, "seconds": seconds}))
|
|
62
|
+
except Exception as e:
|
|
63
|
+
fail("%s: %s" % (type(e).__name__, e))
|
|
64
|
+
`;
|
|
65
|
+
|
|
66
|
+
function curlCommand(modelDir, file) {
|
|
67
|
+
return `curl -L --max-time 600 -o "${path.join(modelDir, file)}" ${MODEL_URL_BASE}/${file}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function resolveModelDir(opts, env) {
|
|
71
|
+
if (opts.modelDir) return path.resolve(String(opts.modelDir));
|
|
72
|
+
if (env.KOKORO_MODEL_DIR) return path.resolve(env.KOKORO_MODEL_DIR);
|
|
73
|
+
return path.join(os.homedir(), '.cache', 'kokoro-onnx');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** -> {ok: true, lines: normalized[]} | {ok: false, error}. Pure (no fs). */
|
|
77
|
+
function validateLines(lines, cwd) {
|
|
78
|
+
if (!Array.isArray(lines) || lines.length === 0) return { ok: false, error: 'lines must be a non-empty array' };
|
|
79
|
+
const seen = new Map();
|
|
80
|
+
const out = [];
|
|
81
|
+
for (let i = 0; i < lines.length; i++) {
|
|
82
|
+
const ln = lines[i];
|
|
83
|
+
const at = `lines[${i}]`;
|
|
84
|
+
if (!ln || typeof ln !== 'object') return { ok: false, error: `${at} must be an object {text, out, voice, speed?, lang?}` };
|
|
85
|
+
if (typeof ln.text !== 'string' || !ln.text.trim()) return { ok: false, error: `${at}.text must be a non-empty string` };
|
|
86
|
+
if (typeof ln.out !== 'string' || !ln.out.trim() || !ln.out.toLowerCase().endsWith('.wav')) {
|
|
87
|
+
return { ok: false, error: `${at}.out must be a path ending in .wav` };
|
|
88
|
+
}
|
|
89
|
+
if (typeof ln.voice !== 'string' || !ln.voice.trim()) return { ok: false, error: `${at}.voice must be a non-empty string` };
|
|
90
|
+
let speed = 1.0;
|
|
91
|
+
if (ln.speed !== undefined && ln.speed !== null) {
|
|
92
|
+
speed = ln.speed;
|
|
93
|
+
if (typeof speed !== 'number' || !Number.isFinite(speed) || speed < SPEED_MIN || speed > SPEED_MAX) {
|
|
94
|
+
return { ok: false, error: `${at}.speed must be a number from ${SPEED_MIN} to ${SPEED_MAX}` };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
let lang = DEFAULT_LANG;
|
|
98
|
+
if (ln.lang !== undefined && ln.lang !== null) {
|
|
99
|
+
if (typeof ln.lang !== 'string' || !ln.lang.trim()) return { ok: false, error: `${at}.lang must be a non-empty string` };
|
|
100
|
+
lang = ln.lang.trim();
|
|
101
|
+
}
|
|
102
|
+
const abs = path.resolve(cwd, ln.out);
|
|
103
|
+
if (seen.has(abs)) return { ok: false, error: `${at}.out duplicates lines[${seen.get(abs)}].out (${abs})` };
|
|
104
|
+
seen.set(abs, i);
|
|
105
|
+
out.push({ text: ln.text, out: abs, voice: ln.voice.trim(), speed, lang });
|
|
106
|
+
}
|
|
107
|
+
return { ok: true, lines: out };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function timeoutFor(lineCount, timeoutMs) {
|
|
111
|
+
const base = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : lineCount * PER_LINE_TIMEOUT_MS;
|
|
112
|
+
return Math.min(base, TIMEOUT_CAP_MS);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function parseLastJsonLine(stdout) {
|
|
116
|
+
const rows = String(stdout || '').trim().split('\n').reverse();
|
|
117
|
+
for (const row of rows) {
|
|
118
|
+
try {
|
|
119
|
+
const v = JSON.parse(row);
|
|
120
|
+
if (v && typeof v === 'object') return v;
|
|
121
|
+
} catch { /* not JSON */ }
|
|
122
|
+
}
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function isWav(p) {
|
|
127
|
+
try {
|
|
128
|
+
return fs.statSync(p).size > WAV_HEADER_BYTES;
|
|
129
|
+
} catch {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Speak `lines` with Kokoro in ONE python process.
|
|
136
|
+
* opts: {python, modelDir, cwd, timeoutMs, env}
|
|
137
|
+
* -> {ok: true, outs, audioSeconds, seconds} | {ok: false, error}
|
|
138
|
+
*/
|
|
139
|
+
function sayKokoro(lines, opts = {}) {
|
|
140
|
+
const env = opts.env || process.env;
|
|
141
|
+
const cwd = path.resolve(opts.cwd || process.cwd());
|
|
142
|
+
const v = validateLines(lines, cwd);
|
|
143
|
+
if (!v.ok) return v;
|
|
144
|
+
|
|
145
|
+
const modelDir = resolveModelDir(opts, env);
|
|
146
|
+
for (const f of [MODEL_FILE, VOICES_FILE]) {
|
|
147
|
+
if (!fs.existsSync(path.join(modelDir, f))) {
|
|
148
|
+
return { ok: false, error: `Kokoro model file ${f} is missing from ${modelDir}; download it with: ${curlCommand(modelDir, f)}` };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
try {
|
|
153
|
+
for (const ln of v.lines) {
|
|
154
|
+
fs.mkdirSync(path.dirname(ln.out), { recursive: true });
|
|
155
|
+
fs.rmSync(ln.out, { force: true }); // a stale WAV must never count as this run's output
|
|
156
|
+
}
|
|
157
|
+
} catch (e) {
|
|
158
|
+
return { ok: false, error: `cannot prepare output paths: ${e.message}` };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const python = opts.python || env.SM_KOKORO_PYTHON || 'python3';
|
|
162
|
+
const limit = timeoutFor(v.lines.length, opts.timeoutMs);
|
|
163
|
+
const r = spawnSync(python, ['-c', KOKORO_SCRIPT], {
|
|
164
|
+
shell: false,
|
|
165
|
+
cwd,
|
|
166
|
+
env,
|
|
167
|
+
input: JSON.stringify({ modelDir, lines: v.lines }),
|
|
168
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
169
|
+
timeout: limit,
|
|
170
|
+
maxBuffer: MAX_BUFFER,
|
|
171
|
+
});
|
|
172
|
+
const stderr = r.stderr ? r.stderr.toString('utf8').trim().slice(-STDERR_TAIL) : '';
|
|
173
|
+
const withStderr = (msg) => (stderr ? `${msg}: ${stderr}` : msg);
|
|
174
|
+
const result = parseLastJsonLine(r.stdout ? r.stdout.toString('utf8') : '');
|
|
175
|
+
|
|
176
|
+
if (r.error) {
|
|
177
|
+
if (r.error.code === 'ETIMEDOUT') return { ok: false, error: withStderr(`Kokoro timed out after ${limit} ms`) };
|
|
178
|
+
return { ok: false, error: withStderr(`cannot run ${python}: ${r.error.message}`) };
|
|
179
|
+
}
|
|
180
|
+
if (r.status !== 0) {
|
|
181
|
+
const why = r.signal ? `killed by ${r.signal}` : `exit ${r.status}`;
|
|
182
|
+
let msg = result && result.ok === false && result.error ? `Kokoro failed (${why}): ${result.error}` : `Kokoro failed (${why})`;
|
|
183
|
+
if (/ModuleNotFoundError|ImportError|No module named/.test(stderr) && !msg.includes(PIP_INSTALL)) {
|
|
184
|
+
msg += `; install with: ${PIP_INSTALL}`;
|
|
185
|
+
}
|
|
186
|
+
return { ok: false, error: withStderr(msg) };
|
|
187
|
+
}
|
|
188
|
+
const missing = v.lines.filter((ln) => !isWav(ln.out)).map((ln) => ln.out);
|
|
189
|
+
if (missing.length) return { ok: false, error: withStderr(`Kokoro wrote no WAV to ${missing.join(', ')}`) };
|
|
190
|
+
|
|
191
|
+
const seconds = result && Array.isArray(result.seconds) ? result.seconds.map(Number) : [];
|
|
192
|
+
const audioSeconds = Math.round(seconds.reduce((a, s) => a + (Number.isFinite(s) ? s : 0), 0) * 1000) / 1000;
|
|
193
|
+
return { ok: true, outs: v.lines.map((ln) => ln.out), audioSeconds, seconds };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
module.exports = {
|
|
197
|
+
sayKokoro,
|
|
198
|
+
KOKORO_SCRIPT,
|
|
199
|
+
validateLines,
|
|
200
|
+
MODEL_FILE,
|
|
201
|
+
VOICES_FILE,
|
|
202
|
+
PIP_INSTALL,
|
|
203
|
+
PER_LINE_TIMEOUT_MS,
|
|
204
|
+
TIMEOUT_CAP_MS,
|
|
205
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Project Home HTML — shared rules
|
|
2
|
+
|
|
3
|
+
The rules every persona that writes HTML for Project Home follows (a demo video, a Knowledge
|
|
4
|
+
Page). Your persona file adds its own kind's rules on top; where it says something stricter or
|
|
5
|
+
different (scripts, size cap), the persona file wins for that point.
|
|
6
|
+
|
|
7
|
+
## Where you run
|
|
8
|
+
|
|
9
|
+
You run inside a Session Manager Epic for the target project. The HTML you produce is rendered
|
|
10
|
+
inside a sandboxed frame in that project's Project Home tab. It is regenerated only when a human
|
|
11
|
+
deliberately presses that Project Home button — never automatically and never in a loop — so this
|
|
12
|
+
run is the one chance to get it right before a person sees it.
|
|
13
|
+
|
|
14
|
+
## Grounding
|
|
15
|
+
|
|
16
|
+
Ground every claim in something you read: the project's manifest (`package.json`,
|
|
17
|
+
`pyproject.toml`, or equivalent), its README or docs, its source tree, or its git log. If you
|
|
18
|
+
can't point to where a claim came from, leave it out rather than guess — leaving something out is
|
|
19
|
+
far better than inventing it. Never invent statistics, metrics, quotes, logos, testimonials,
|
|
20
|
+
screenshots, or features that don't exist. Where the project already describes itself well (a
|
|
21
|
+
tagline, a feature list, a mission statement), reuse its own wording instead of paraphrasing.
|
|
22
|
+
|
|
23
|
+
Read with a bounded pass: the manifest, the README or top-level docs index, the top-level
|
|
24
|
+
directory tree, and `git log --oneline -30` for a sense of recent direction. Stop once you have
|
|
25
|
+
enough to describe the project honestly — you don't need to read every file. Keep a claims list:
|
|
26
|
+
every fact you plan to show, with the source you read it from; drop any claim with no source.
|
|
27
|
+
|
|
28
|
+
## One document
|
|
29
|
+
|
|
30
|
+
Produce exactly one complete HTML document:
|
|
31
|
+
- All CSS lives inline in a single `<style>` block — no `<link href="http...">`, no `@import`,
|
|
32
|
+
and no `url(http...)`. Scripts follow your persona file: a Knowledge Page has no `<script>` at
|
|
33
|
+
all; a demo video has one inline `<script>` block and never `<script src="...">`.
|
|
34
|
+
- No external fonts or images; nothing the browser needs to fetch over the network.
|
|
35
|
+
- Stay under your persona file's size cap.
|
|
36
|
+
|
|
37
|
+
## When the write tool fails
|
|
38
|
+
|
|
39
|
+
If the save tool rejects the HTML, fix the specific problem it reported and call it again — up to
|
|
40
|
+
3 attempts total. If the save tool isn't available in this session at all, that is a Session
|
|
41
|
+
Manager launch bug, not an obstacle to route around: say so plainly, give the absolute path of the
|
|
42
|
+
HTML file you built in your final result, and stop. Don't start Session Manager's MCP server
|
|
43
|
+
yourself, call its admin API, write the saved file by hand, or build any other workaround or tooling, in the target project or anywhere else.
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Demo-video kit resumable run: one long kit step (e.g. a slow local voice)
|
|
3
|
+
// runs under a detached supervisor, and callers wait for it in slices.
|
|
4
|
+
//
|
|
5
|
+
// Why: a headless scheduler job's foreground Bash call is capped at 15 minutes
|
|
6
|
+
// and its idle watchdog fires after 20 minutes without output, so a step that
|
|
7
|
+
// can take longer must outlive one call. Each call runs startOrAttach (same
|
|
8
|
+
// key -> attach to the live run) then waitForResult for one slice; 'pending'
|
|
9
|
+
// means "call again".
|
|
10
|
+
//
|
|
11
|
+
// How it ends: on Linux the job's scope and the scheduler's leftover sweep stop
|
|
12
|
+
// the supervisor's process group with the job. On every platform (macOS sweeps
|
|
13
|
+
// only the job's own process group) the caller lease ends it: startOrAttach and
|
|
14
|
+
// every waitForResult check refresh <stateDir>/lease, and the supervisor writes
|
|
15
|
+
// an 'abandoned' result and SIGTERMs its whole group once no caller has checked
|
|
16
|
+
// in for DEFAULT_LEASE_MS.
|
|
17
|
+
//
|
|
18
|
+
// Why own pid check, single-write result file and tolerant JSON read although
|
|
19
|
+
// src/main/lib/AGENTS.md says to reuse process/pidAlive.cjs and
|
|
20
|
+
// util/atomicFs.cjs: kit files are seeded to ~/.claude/session-manager/
|
|
21
|
+
// demo-video-kit/ and must load standalone (node built-ins and this folder
|
|
22
|
+
// only), so they cannot require those modules. A partial result.json reads as
|
|
23
|
+
// "not written yet".
|
|
24
|
+
//
|
|
25
|
+
// Files in stateDir: state.json { key, pid, startedAt }, lease (mtime only),
|
|
26
|
+
// result.json { key, result }, run.log (supervisor + step stdout/stderr of the
|
|
27
|
+
// latest fresh run; truncated on each fresh start), start.lock (held only while
|
|
28
|
+
// startOrAttach starts a run, so two concurrent starts spawn one supervisor).
|
|
29
|
+
//
|
|
30
|
+
// Process tree: on POSIX the supervisor leads its own process group and stops
|
|
31
|
+
// the whole group (SIGTERM) on lease expiry and after its step exits, so a
|
|
32
|
+
// voice wrapper's grandchildren never outlive the run. On win32 the same
|
|
33
|
+
// points run `taskkill /PID <pid> /T /F` (winTreeKillArgv).
|
|
34
|
+
const fs = require('node:fs');
|
|
35
|
+
const path = require('node:path');
|
|
36
|
+
const { spawn, spawnSync } = require('node:child_process');
|
|
37
|
+
|
|
38
|
+
const DEFAULT_LEASE_MS = 20 * 60 * 1000;
|
|
39
|
+
const LEASE_CHECK_MAX_MS = 15 * 1000;
|
|
40
|
+
const DEFAULT_POLL_MS = 1000;
|
|
41
|
+
const LOG_TAIL_BYTES = 500;
|
|
42
|
+
const START_LOCK_STALE_MS = 30 * 1000;
|
|
43
|
+
const START_LOCK_WAIT_MS = 50;
|
|
44
|
+
const START_LOCK_MAX_WAITS = 40;
|
|
45
|
+
|
|
46
|
+
const statePath = (d) => path.join(d, 'state.json');
|
|
47
|
+
const leasePath = (d) => path.join(d, 'lease');
|
|
48
|
+
const resultPath = (d) => path.join(d, 'result.json');
|
|
49
|
+
const logPath = (d) => path.join(d, 'run.log');
|
|
50
|
+
const lockPath = (d) => path.join(d, 'start.lock');
|
|
51
|
+
|
|
52
|
+
function readJson(file) {
|
|
53
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** process.kill(pid, 0): ESRCH = dead, EPERM = alive (someone else's). */
|
|
57
|
+
function pidAlive(pid) {
|
|
58
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
59
|
+
try { process.kill(pid, 0); return true; } catch (err) { return err && err.code === 'EPERM'; }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function rmQuiet(file) {
|
|
63
|
+
try { fs.rmSync(file, { force: true }); } catch { /* ignore */ }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function refreshLease(stateDir) {
|
|
67
|
+
const p = leasePath(stateDir);
|
|
68
|
+
try {
|
|
69
|
+
fs.closeSync(fs.openSync(p, 'a'));
|
|
70
|
+
const now = new Date();
|
|
71
|
+
fs.utimesSync(p, now, now);
|
|
72
|
+
} catch { /* stateDir gone: the run was stopped */ }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function readState(stateDir) {
|
|
76
|
+
const s = readJson(statePath(stateDir));
|
|
77
|
+
return s && typeof s === 'object' && typeof s.key === 'string' && Number.isInteger(s.pid) ? s : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Single write of { key, result }; readers treat a partial file as not written yet. */
|
|
81
|
+
function writeResult(stateDir, key, result) {
|
|
82
|
+
fs.writeFileSync(resultPath(stateDir), JSON.stringify({ key, result }));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function readResult(stateDir, key) {
|
|
86
|
+
const r = readJson(resultPath(stateDir));
|
|
87
|
+
if (!r || typeof r !== 'object' || r.key !== key || !('result' in r)) return null;
|
|
88
|
+
return r;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Last `bytes` of run.log as text ('' when missing). */
|
|
92
|
+
function readLogTail(stateDir, bytes = LOG_TAIL_BYTES) {
|
|
93
|
+
let fd;
|
|
94
|
+
try {
|
|
95
|
+
fd = fs.openSync(logPath(stateDir), 'r');
|
|
96
|
+
const size = fs.fstatSync(fd).size;
|
|
97
|
+
const len = Math.min(size, Math.max(0, bytes));
|
|
98
|
+
const buf = Buffer.alloc(len);
|
|
99
|
+
fs.readSync(fd, buf, 0, len, size - len);
|
|
100
|
+
return buf.toString('utf8');
|
|
101
|
+
} catch {
|
|
102
|
+
return '';
|
|
103
|
+
} finally {
|
|
104
|
+
if (fd !== undefined) try { fs.closeSync(fd); } catch { /* ignore */ }
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function killQuiet(pid, sig) {
|
|
109
|
+
try { process.kill(pid, sig); } catch { /* ESRCH: already gone */ }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** win32 argv that ends pid and every descendant. */
|
|
113
|
+
function winTreeKillArgv(pid) {
|
|
114
|
+
return ['taskkill', '/PID', String(pid), '/T', '/F'];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** End pid's whole tree: taskkill /T on win32, SIGTERM to its process group on POSIX. */
|
|
118
|
+
function killTree(pid) {
|
|
119
|
+
if (process.platform === 'win32') {
|
|
120
|
+
const argv = winTreeKillArgv(pid);
|
|
121
|
+
try { spawnSync(argv[0], argv.slice(1), { shell: false, windowsHide: true, stdio: 'ignore' }); } catch { /* ignore */ }
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
killQuiet(-pid, 'SIGTERM');
|
|
125
|
+
killQuiet(pid, 'SIGTERM');
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Synchronous pause without a busy loop. */
|
|
129
|
+
function sleepSync(ms) {
|
|
130
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Stop the recorded run (its whole process tree) and clear its files. */
|
|
134
|
+
function stopRun(stateDir) {
|
|
135
|
+
const s = readState(stateDir);
|
|
136
|
+
if (s) killTree(s.pid);
|
|
137
|
+
rmQuiet(statePath(stateDir));
|
|
138
|
+
rmQuiet(resultPath(stateDir));
|
|
139
|
+
rmQuiet(leasePath(stateDir));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Start `argv` (node args, run with process.execPath) under a detached
|
|
144
|
+
* supervisor, or attach when the same key's supervisor is still alive.
|
|
145
|
+
* -> { pid, started }
|
|
146
|
+
*/
|
|
147
|
+
function startOrAttach({ stateDir, key, argv, cwd, leaseMs = DEFAULT_LEASE_MS }) {
|
|
148
|
+
if (!stateDir || typeof key !== 'string' || !key) throw new Error('resumableRun: stateDir and key are required');
|
|
149
|
+
if (!Array.isArray(argv) || argv.length === 0) throw new Error('resumableRun: argv must be a non-empty array');
|
|
150
|
+
fs.mkdirSync(stateDir, { recursive: true });
|
|
151
|
+
const attached = attachLive(stateDir, key);
|
|
152
|
+
if (attached) return attached;
|
|
153
|
+
const lock = lockPath(stateDir);
|
|
154
|
+
let waits = 0;
|
|
155
|
+
let staleRemoved = false;
|
|
156
|
+
for (;;) {
|
|
157
|
+
try {
|
|
158
|
+
fs.closeSync(fs.openSync(lock, 'wx'));
|
|
159
|
+
break;
|
|
160
|
+
} catch (err) {
|
|
161
|
+
if (!err || err.code !== 'EEXIST') throw err;
|
|
162
|
+
}
|
|
163
|
+
// Another caller is starting a run: attach to it once it is recorded.
|
|
164
|
+
const other = attachLive(stateDir, key);
|
|
165
|
+
if (other) return other;
|
|
166
|
+
let age = 0;
|
|
167
|
+
try { age = Date.now() - fs.statSync(lock).mtimeMs; } catch { /* released meanwhile: retry */ }
|
|
168
|
+
if (age > START_LOCK_STALE_MS && !staleRemoved) {
|
|
169
|
+
staleRemoved = true;
|
|
170
|
+
rmQuiet(lock);
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (waits >= START_LOCK_MAX_WAITS) {
|
|
174
|
+
throw new Error(`resumableRun: start lock ${lock} is still held after ${START_LOCK_MAX_WAITS * START_LOCK_WAIT_MS} ms`);
|
|
175
|
+
}
|
|
176
|
+
waits++;
|
|
177
|
+
sleepSync(START_LOCK_WAIT_MS);
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
return startLocked({ stateDir, key, argv, cwd, leaseMs });
|
|
181
|
+
} finally {
|
|
182
|
+
rmQuiet(lock);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Same key with a live supervisor -> attach result; otherwise null. */
|
|
187
|
+
function attachLive(stateDir, key) {
|
|
188
|
+
const s = readState(stateDir);
|
|
189
|
+
if (s && s.key === key && pidAlive(s.pid)) {
|
|
190
|
+
refreshLease(stateDir);
|
|
191
|
+
return { pid: s.pid, started: false };
|
|
192
|
+
}
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Called with start.lock held: re-check, then start a fresh run. */
|
|
197
|
+
function startLocked({ stateDir, key, argv, cwd, leaseMs }) {
|
|
198
|
+
const s = readState(stateDir);
|
|
199
|
+
if (s && pidAlive(s.pid)) {
|
|
200
|
+
if (s.key === key) {
|
|
201
|
+
refreshLease(stateDir);
|
|
202
|
+
return { pid: s.pid, started: false };
|
|
203
|
+
}
|
|
204
|
+
stopRun(stateDir);
|
|
205
|
+
}
|
|
206
|
+
// A fresh run: its waiter must see only its own result and its own log.
|
|
207
|
+
rmQuiet(resultPath(stateDir));
|
|
208
|
+
refreshLease(stateDir);
|
|
209
|
+
const logFd = fs.openSync(logPath(stateDir), 'w');
|
|
210
|
+
let child;
|
|
211
|
+
try {
|
|
212
|
+
child = spawn(process.execPath, [__filename, '__supervise', stateDir, key, String(leaseMs), '--', ...argv], {
|
|
213
|
+
detached: true,
|
|
214
|
+
stdio: ['ignore', logFd, logFd],
|
|
215
|
+
cwd,
|
|
216
|
+
env: process.env,
|
|
217
|
+
});
|
|
218
|
+
child.unref();
|
|
219
|
+
} finally {
|
|
220
|
+
fs.closeSync(logFd);
|
|
221
|
+
}
|
|
222
|
+
fs.writeFileSync(statePath(stateDir), JSON.stringify({ key, pid: child.pid, startedAt: Date.now() }));
|
|
223
|
+
refreshLease(stateDir);
|
|
224
|
+
return { pid: child.pid, started: true };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Wait up to waitMs (never more than waitMs + pollMs) for the key's result.
|
|
231
|
+
* -> { status: 'done', result } | { status: 'pending', pid, elapsedMs } | { status: 'lost', error }
|
|
232
|
+
*/
|
|
233
|
+
async function waitForResult({ stateDir, key, waitMs, pollMs = DEFAULT_POLL_MS }) {
|
|
234
|
+
const t0 = Date.now();
|
|
235
|
+
const wait = Math.max(0, Number(waitMs) || 0);
|
|
236
|
+
const poll = Math.max(1, Number(pollMs) || DEFAULT_POLL_MS);
|
|
237
|
+
for (;;) {
|
|
238
|
+
refreshLease(stateDir);
|
|
239
|
+
let r = readResult(stateDir, key);
|
|
240
|
+
if (r) return { status: 'done', result: r.result };
|
|
241
|
+
const s = readState(stateDir);
|
|
242
|
+
if (!s || s.key !== key || !pidAlive(s.pid)) {
|
|
243
|
+
r = readResult(stateDir, key); // the step may have written it just before exiting
|
|
244
|
+
if (r) return { status: 'done', result: r.result };
|
|
245
|
+
const why = !s || s.key !== key ? `no run recorded for key ${key}` : `run ${s.pid} ended without a result`;
|
|
246
|
+
return { status: 'lost', error: `${why}; log tail:\n${readLogTail(stateDir, LOG_TAIL_BYTES)}` };
|
|
247
|
+
}
|
|
248
|
+
const spent = Date.now() - t0;
|
|
249
|
+
if (spent >= wait) {
|
|
250
|
+
return { status: 'pending', pid: s.pid, elapsedMs: Date.now() - (Number(s.startedAt) || t0) };
|
|
251
|
+
}
|
|
252
|
+
await sleep(Math.min(poll, wait - spent));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function supervise(args) {
|
|
257
|
+
const [stateDir, key, leaseArg, sep, ...argv] = args;
|
|
258
|
+
const leaseMs = Number(leaseArg) > 0 ? Number(leaseArg) : DEFAULT_LEASE_MS;
|
|
259
|
+
if (sep !== '--' || argv.length === 0) {
|
|
260
|
+
process.stderr.write('resumableRun supervisor: missing step argv\n');
|
|
261
|
+
process.exit(2);
|
|
262
|
+
}
|
|
263
|
+
// Not detached: the step and anything it spawns stay in this process group.
|
|
264
|
+
const step = spawn(process.execPath, argv, { stdio: ['ignore', 'inherit', 'inherit'], cwd: process.cwd() });
|
|
265
|
+
const every = Math.min(LEASE_CHECK_MAX_MS, Math.max(1, Math.floor(leaseMs / 4)));
|
|
266
|
+
const timer = setInterval(() => {
|
|
267
|
+
let age = Infinity;
|
|
268
|
+
try { age = Date.now() - fs.statSync(leasePath(stateDir)).mtimeMs; } catch { /* missing lease = no caller */ }
|
|
269
|
+
if (age <= leaseMs) return;
|
|
270
|
+
clearInterval(timer);
|
|
271
|
+
try {
|
|
272
|
+
writeResult(stateDir, key, { ok: false, error: `abandoned: no caller for ${Math.round(leaseMs / 60000)} min` });
|
|
273
|
+
} catch { /* stateDir gone */ }
|
|
274
|
+
process.stderr.write(`resumableRun supervisor: lease expired, stopping group ${process.pid}\n`);
|
|
275
|
+
killTree(process.pid);
|
|
276
|
+
process.exit(1);
|
|
277
|
+
}, every);
|
|
278
|
+
step.on('error', (err) => {
|
|
279
|
+
process.stderr.write(`resumableRun supervisor: step failed to start: ${err.message}\n`);
|
|
280
|
+
clearInterval(timer);
|
|
281
|
+
process.exit(1);
|
|
282
|
+
});
|
|
283
|
+
step.on('exit', (code, signal) => {
|
|
284
|
+
clearInterval(timer);
|
|
285
|
+
// The step wrote its result before exiting; stop whatever it left in this
|
|
286
|
+
// group (e.g. a voice wrapper's grandchildren). The waiter is not in it.
|
|
287
|
+
const exitCode = code ?? (signal ? 1 : 0);
|
|
288
|
+
process.on('SIGTERM', () => process.exit(exitCode));
|
|
289
|
+
killTree(process.pid);
|
|
290
|
+
process.exit(exitCode);
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
if (require.main === module && process.argv[2] === '__supervise') {
|
|
295
|
+
supervise(process.argv.slice(3));
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
module.exports = { startOrAttach, waitForResult, writeResult, stopRun, readLogTail, winTreeKillArgv, DEFAULT_LEASE_MS };
|
|
@@ -19,10 +19,10 @@ const path = require('node:path');
|
|
|
19
19
|
const { schedulerHome } = require('../scheduler/schedulerPaths.cjs');
|
|
20
20
|
const { writeTextAtomic } = require('../util/atomicFs.cjs');
|
|
21
21
|
|
|
22
|
-
const KIT_VERSION = '
|
|
22
|
+
const KIT_VERSION = '35';
|
|
23
23
|
// sha256 of kitDigest(__dirname). Update together with a KIT_VERSION bump.
|
|
24
|
-
const KIT_DIGEST = '
|
|
25
|
-
const KIT_FILES = Object.freeze(['checks.cjs', 'sound.cjs', 'capture.cjs', 'frames.cjs', 'character.cjs', 'playwrightLoader.cjs']);
|
|
24
|
+
const KIT_DIGEST = 'e57da95c91468324e32bd88ee3cb35b1aa7b359e07da2875cbfc75234e5334ac';
|
|
25
|
+
const KIT_FILES = Object.freeze(['checks.cjs', 'sound.cjs', 'capture.cjs', 'frames.cjs', 'character.cjs', 'playwrightLoader.cjs', 'export.cjs', 'kind-tiktok.md', 'kind-marketing.md', 'cast.md', 'project-home-html.md', 'resumableRun.cjs', 'voiceLibrary.cjs', 'voiceLane.cjs', 'kokoroSay.cjs']);
|
|
26
26
|
const STAMP_FILE = 'KIT_VERSION';
|
|
27
27
|
|
|
28
28
|
/** The single list of kit files (paths relative to the kit dir) the seeder copies. */
|