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
|
@@ -4,7 +4,14 @@
|
|
|
4
4
|
// Reading is plain file reading; writing goes only through the
|
|
5
5
|
// POST /admin/project-home/character/write route (writer 'project-home').
|
|
6
6
|
// speakWithCommand spawns the user's TTS argv directly — never through a shell.
|
|
7
|
+
// speakLines runs a {lines} (batch) voice once per speaker with a JSON manifest
|
|
8
|
+
// of { text, out }, and a kokoro voice once per speaker through kokoroSay.cjs, each
|
|
9
|
+
// with a time limit capped by SM_SCHEDULER_JOB_DEADLINE_MS. {voiceId} voices
|
|
10
|
+
// resolve through voiceLibrary.cjs. Every synthesis call runs inside the kit
|
|
11
|
+
// voice lane (voiceLane.cjs): it waits its turn (bounded by laneWaitMs), prints
|
|
12
|
+
// its position to stderr while waiting, and logs a usage line when it leaves.
|
|
7
13
|
const fs = require('node:fs');
|
|
14
|
+
const os = require('node:os');
|
|
8
15
|
const path = require('node:path');
|
|
9
16
|
const { spawnSync } = require('node:child_process');
|
|
10
17
|
// Kit files are seeded to ~/.claude/session-manager/demo-video-kit/ and must
|
|
@@ -14,7 +21,44 @@ const OPS_ROOT_DIR = 'session-manager-operations';
|
|
|
14
21
|
|
|
15
22
|
const MAX_JS_BYTES = 300 * 1024;
|
|
16
23
|
const MAX_JSON_BYTES = 16 * 1024;
|
|
17
|
-
|
|
24
|
+
// Per narration line: slow CPU voices can take minutes for one sentence.
|
|
25
|
+
const COMMAND_TIMEOUT_MS = 900000;
|
|
26
|
+
const STDERR_TAIL = 500;
|
|
27
|
+
const BATCH_TIMEOUT_CEILING_MS = 180 * 60 * 1000;
|
|
28
|
+
const SPEAK_DEADLINE_MARGIN_MS = 45 * 60 * 1000;
|
|
29
|
+
const MIN_BATCH_TIMEOUT_MS = 60 * 1000;
|
|
30
|
+
const WAV_HEADER_BYTES = 44;
|
|
31
|
+
const LANE_WAIT_DEFAULT_MS = 6 * 60 * 60 * 1000;
|
|
32
|
+
const WAV_SCAN_BYTES = 64 * 1024;
|
|
33
|
+
|
|
34
|
+
const PERSONALITY_TEXT = Object.freeze({ who: 400, speech: 400, readingLevel: 40 });
|
|
35
|
+
const NEVER_SAY_MAX_ITEMS = 40;
|
|
36
|
+
const NEVER_SAY_MAX_CHARS = 40;
|
|
37
|
+
const MAX_CAST_MEMBERS = 8;
|
|
38
|
+
const CAST_NAME_MAX = 40;
|
|
39
|
+
const CAST_NOTE_MAX = 400;
|
|
40
|
+
|
|
41
|
+
/** -> null when `p` is a valid personality object, else a reason string. */
|
|
42
|
+
function validatePersonality(p) {
|
|
43
|
+
if (!p || typeof p !== 'object' || Array.isArray(p)) return 'personality must be an object';
|
|
44
|
+
for (const k of Object.keys(p)) {
|
|
45
|
+
if (k === 'neverSay') continue;
|
|
46
|
+
const max = PERSONALITY_TEXT[k];
|
|
47
|
+
if (!max) return `personality.${k} is not a known key (who, speech, readingLevel, neverSay)`;
|
|
48
|
+
const v = p[k];
|
|
49
|
+
if (typeof v !== 'string' || v.length < 1 || v.length > max) return `personality.${k} must be a 1-${max} char string`;
|
|
50
|
+
}
|
|
51
|
+
if ('neverSay' in p) {
|
|
52
|
+
const n = p.neverSay;
|
|
53
|
+
if (!Array.isArray(n) || n.length > NEVER_SAY_MAX_ITEMS) {
|
|
54
|
+
return `personality.neverSay must be an array of at most ${NEVER_SAY_MAX_ITEMS} strings`;
|
|
55
|
+
}
|
|
56
|
+
if (!n.every((w) => typeof w === 'string' && w.length >= 1 && w.length <= NEVER_SAY_MAX_CHARS)) {
|
|
57
|
+
return `personality.neverSay items must be 1-${NEVER_SAY_MAX_CHARS} char strings`;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
18
62
|
|
|
19
63
|
/** -> null when `c` is a valid character.json object, else a reason string. */
|
|
20
64
|
function validateCharacterJson(c) {
|
|
@@ -23,23 +67,106 @@ function validateCharacterJson(c) {
|
|
|
23
67
|
if (!Array.isArray(c.palette) || c.palette.length === 0 || !c.palette.every((p) => typeof p === 'string' && p)) {
|
|
24
68
|
return 'palette must be a non-empty array of strings';
|
|
25
69
|
}
|
|
70
|
+
if ('personality' in c) {
|
|
71
|
+
const pErr = validatePersonality(c.personality);
|
|
72
|
+
if (pErr) return pErr;
|
|
73
|
+
}
|
|
26
74
|
const v = c.voice;
|
|
27
75
|
if (!v || typeof v !== 'object') return 'voice is required';
|
|
76
|
+
const vErr = validateVoiceOrRef(v, 'voice');
|
|
77
|
+
if (vErr) return vErr;
|
|
78
|
+
if ('cast' in c) return validateCast(c.cast, c.name);
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** -> null when `v` is a valid voice ({engine:'kokoro',id} | {engine:'command',command}),
|
|
83
|
+
* else a reason string prefixed with `label` (e.g. 'voice', 'cast[1].voice'). */
|
|
84
|
+
function validateVoice(v, label) {
|
|
85
|
+
if (!v || typeof v !== 'object') return `${label} must be an object`;
|
|
28
86
|
if (v.engine === 'kokoro') {
|
|
29
|
-
if (typeof v.id !== 'string' || !v.id) return
|
|
87
|
+
if (typeof v.id !== 'string' || !v.id) return `${label}.id must be a non-empty string for engine kokoro`;
|
|
30
88
|
return null;
|
|
31
89
|
}
|
|
32
90
|
if (v.engine === 'command') {
|
|
33
91
|
const cmd = v.command;
|
|
34
92
|
if (!Array.isArray(cmd) || cmd.length === 0 || !cmd.every((a) => typeof a === 'string')) {
|
|
35
|
-
return
|
|
93
|
+
return `${label}.command must be a non-empty string[]`;
|
|
94
|
+
}
|
|
95
|
+
if (!cmd[0]) return `${label}.command[0] must be a program name`;
|
|
96
|
+
const batch = cmd.some((a) => a.includes('{lines}'));
|
|
97
|
+
if (batch) {
|
|
98
|
+
if (cmd.some((a) => a.includes('{text}') || a.includes('{out}'))) {
|
|
99
|
+
return `${label}.command mixes {lines} with {text}/{out}; use {lines} alone or {text} with {out}`;
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
36
102
|
}
|
|
37
|
-
if (!cmd
|
|
38
|
-
if (!cmd.some((a) => a.includes('{
|
|
39
|
-
if (!cmd.some((a) => a.includes('{out}'))) return 'voice.command must contain an {out} placeholder';
|
|
103
|
+
if (!cmd.some((a) => a.includes('{text}'))) return `${label}.command must contain a {text} placeholder`;
|
|
104
|
+
if (!cmd.some((a) => a.includes('{out}'))) return `${label}.command must contain an {out} placeholder`;
|
|
40
105
|
return null;
|
|
41
106
|
}
|
|
42
|
-
return
|
|
107
|
+
return `${label}.engine must be 'kokoro' or 'command'`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** True when `v` is a voice-library reference ({voiceId, ...}) rather than an inline engine voice. */
|
|
111
|
+
function isVoiceIdRef(v) {
|
|
112
|
+
return !!v && typeof v === 'object' && !Array.isArray(v) && 'voiceId' in v;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A {voiceId} ref (exactly that one key, a library id) or an inline voice. The ref is
|
|
116
|
+
* only checked for shape here; the write route resolves it in the voice library. */
|
|
117
|
+
function validateVoiceOrRef(v, label) {
|
|
118
|
+
if (!isVoiceIdRef(v)) return validateVoice(v, label);
|
|
119
|
+
for (const k of Object.keys(v)) {
|
|
120
|
+
if (k !== 'voiceId') return `${label}.${k} is not allowed beside voiceId; a {voiceId} voice has exactly one key`;
|
|
121
|
+
}
|
|
122
|
+
// Lazy: voiceLibrary.cjs requires this file at load, so a top-level require would see it half-built.
|
|
123
|
+
const { VOICE_ID_RE } = require('./voiceLibrary.cjs');
|
|
124
|
+
if (typeof v.voiceId !== 'string' || !VOICE_ID_RE.test(v.voiceId)) return `${label}.voiceId must match ${VOICE_ID_RE}`;
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Every {voiceId} the host and cast name, in order: [{ label, voiceId }]. Assumes a valid character.json. */
|
|
129
|
+
function voiceIdRefsOf(c) {
|
|
130
|
+
const refs = [];
|
|
131
|
+
if (c && isVoiceIdRef(c.voice)) refs.push({ label: 'voice', voiceId: c.voice.voiceId });
|
|
132
|
+
if (c && Array.isArray(c.cast)) {
|
|
133
|
+
c.cast.forEach((m, i) => { if (m && isVoiceIdRef(m.voice)) refs.push({ label: `cast[${i}].voice`, voiceId: m.voice.voiceId }); });
|
|
134
|
+
}
|
|
135
|
+
return refs;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const CAST_KEYS = Object.freeze(['name', 'voice', 'note']);
|
|
139
|
+
|
|
140
|
+
/** -> null when `cast` is a valid supporting cast for host `hostName`, else a reason.
|
|
141
|
+
* A member without `voice` is valid: it never speaks. */
|
|
142
|
+
function validateCast(cast, hostName) {
|
|
143
|
+
if (!Array.isArray(cast) || cast.length > MAX_CAST_MEMBERS) {
|
|
144
|
+
return `cast must be an array of at most ${MAX_CAST_MEMBERS} members`;
|
|
145
|
+
}
|
|
146
|
+
const host = String(hostName).trim().toLowerCase();
|
|
147
|
+
const seen = new Map();
|
|
148
|
+
for (let i = 0; i < cast.length; i++) {
|
|
149
|
+
const m = cast[i];
|
|
150
|
+
const at = `cast[${i}]`;
|
|
151
|
+
if (!m || typeof m !== 'object' || Array.isArray(m)) return `${at} must be an object`;
|
|
152
|
+
for (const k of Object.keys(m)) {
|
|
153
|
+
if (!CAST_KEYS.includes(k)) return `${at}.${k} is not a known key (${CAST_KEYS.join(', ')})`;
|
|
154
|
+
}
|
|
155
|
+
const name = typeof m.name === 'string' ? m.name.trim() : '';
|
|
156
|
+
if (name.length < 1 || name.length > CAST_NAME_MAX) return `${at}.name must be a 1-${CAST_NAME_MAX} char string`;
|
|
157
|
+
const key = name.toLowerCase();
|
|
158
|
+
if (key === host) return `${at}.name "${name}" is the host's name`;
|
|
159
|
+
if (seen.has(key)) return `${at}.name "${name}" duplicates cast[${seen.get(key)}].name`;
|
|
160
|
+
seen.set(key, i);
|
|
161
|
+
if ('voice' in m) {
|
|
162
|
+
const vErr = validateVoiceOrRef(m.voice, `${at}.voice`);
|
|
163
|
+
if (vErr) return vErr;
|
|
164
|
+
}
|
|
165
|
+
if ('note' in m && (typeof m.note !== 'string' || m.note.length < 1 || m.note.length > CAST_NOTE_MAX)) {
|
|
166
|
+
return `${at}.note must be a 1-${CAST_NOTE_MAX} char string`;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
43
170
|
}
|
|
44
171
|
|
|
45
172
|
/** -> null when `js` is acceptable character.js source, else a reason. Needs the
|
|
@@ -62,30 +189,67 @@ function validateCharacterJs(js, networkChecks = []) {
|
|
|
62
189
|
* caller's writer-checked writeTextAtomic (assertOpsWrite).
|
|
63
190
|
*/
|
|
64
191
|
function characterDir(projectRoot) {
|
|
65
|
-
|
|
192
|
+
return path.join(projectRootOf(projectRoot, 'characterDir'), OPS_ROOT_DIR, 'project-pages', 'videos', '_character');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The project root for `projectRoot` (absolute), with any ops-root suffix stripped. */
|
|
196
|
+
function projectRootOf(projectRoot, who = 'projectRootOf') {
|
|
197
|
+
if (!projectRoot || typeof projectRoot !== 'string') throw new Error(`${who}: projectRoot is required`);
|
|
66
198
|
if (!path.isAbsolute(projectRoot)) {
|
|
67
|
-
throw new Error(
|
|
199
|
+
throw new Error(`${who}: projectRoot must be an absolute path, got "${projectRoot}"`);
|
|
68
200
|
}
|
|
69
201
|
const segs = path.resolve(projectRoot).split(path.sep);
|
|
70
202
|
const idx = segs.indexOf(OPS_ROOT_DIR);
|
|
71
|
-
|
|
72
|
-
return path.join(root, OPS_ROOT_DIR, 'project-pages', 'videos', '_character');
|
|
203
|
+
return idx === -1 ? segs.join(path.sep) : (segs.slice(0, idx).join(path.sep) || path.sep);
|
|
73
204
|
}
|
|
74
205
|
|
|
75
|
-
/**
|
|
76
|
-
|
|
206
|
+
/**
|
|
207
|
+
* -> { ok: true, json, js } | { ok: false, exists, error }.
|
|
208
|
+
* `exists` is true when character.json or character.js is on disk, so callers
|
|
209
|
+
* can tell 'no persona saved' from 'a persona is saved but unusable'.
|
|
210
|
+
*/
|
|
211
|
+
function inspectCharacter(projectRoot) {
|
|
212
|
+
let dir;
|
|
77
213
|
try {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
214
|
+
dir = characterDir(projectRoot);
|
|
215
|
+
} catch (e) {
|
|
216
|
+
return { ok: false, exists: false, error: e.message };
|
|
217
|
+
}
|
|
218
|
+
const jsonPath = path.join(dir, 'character.json');
|
|
219
|
+
const jsPath = path.join(dir, 'character.js');
|
|
220
|
+
const hasJson = fs.existsSync(jsonPath);
|
|
221
|
+
const hasJs = fs.existsSync(jsPath);
|
|
222
|
+
const exists = hasJson || hasJs;
|
|
223
|
+
const fail = (error) => ({ ok: false, exists, error });
|
|
224
|
+
if (!exists) return fail(`no character saved in ${dir}`);
|
|
225
|
+
if (!hasJson) return fail(`character.json is missing in ${dir}`);
|
|
226
|
+
let json;
|
|
227
|
+
try {
|
|
228
|
+
const jsonRaw = fs.readFileSync(jsonPath, 'utf8');
|
|
229
|
+
if (Buffer.byteLength(jsonRaw, 'utf8') > MAX_JSON_BYTES) {
|
|
230
|
+
return fail(`character.json exceeds the ${MAX_JSON_BYTES}-byte limit`);
|
|
231
|
+
}
|
|
232
|
+
json = JSON.parse(jsonRaw);
|
|
233
|
+
} catch (e) {
|
|
234
|
+
return fail(`character.json is not valid JSON: ${e.message}`);
|
|
235
|
+
}
|
|
236
|
+
const reason = validateCharacterJson(json);
|
|
237
|
+
if (reason) return fail(`character.json invalid: ${reason}`);
|
|
238
|
+
if (!hasJs) return fail(`character.js is missing in ${dir}`);
|
|
239
|
+
let js;
|
|
240
|
+
try {
|
|
241
|
+
js = fs.readFileSync(jsPath, 'utf8');
|
|
242
|
+
} catch (e) {
|
|
243
|
+
return fail(`character.js cannot be read: ${e.message}`);
|
|
88
244
|
}
|
|
245
|
+
if (!js.trim()) return fail('character.js is empty');
|
|
246
|
+
return { ok: true, json, js };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** -> {json, js} | null (absent or invalid). */
|
|
250
|
+
function readCharacter(projectRoot) {
|
|
251
|
+
const r = inspectCharacter(projectRoot);
|
|
252
|
+
return r.ok ? { json: r.json, js: r.js } : null;
|
|
89
253
|
}
|
|
90
254
|
|
|
91
255
|
/** Substitute {text}/{out} into each argv element; the argv is never joined. */
|
|
@@ -93,23 +257,551 @@ function buildCommandArgv(voice, text, out) {
|
|
|
93
257
|
return voice.command.map((a) => a.split('{text}').join(text).split('{out}').join(out));
|
|
94
258
|
}
|
|
95
259
|
|
|
96
|
-
/**
|
|
97
|
-
function
|
|
98
|
-
|
|
260
|
+
/** True only for a valid engine 'command' voice whose command holds '{lines}' (one call per speaker). */
|
|
261
|
+
function isBatchVoice(voice) {
|
|
262
|
+
return !!voice && voice.engine === 'command' && validateVoice(voice, 'voice') === null
|
|
263
|
+
&& voice.command.some((a) => a.includes('{lines}'));
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Substitute {lines} (the manifest path) into each argv element; the argv is never joined. */
|
|
267
|
+
function buildBatchArgv(voice, manifestPath) {
|
|
268
|
+
return voice.command.map((a) => a.split('{lines}').join(manifestPath));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** True when `file` exists, is larger than a bare WAV header and starts with 'RIFF'. */
|
|
272
|
+
function isWav(file) {
|
|
273
|
+
let fd;
|
|
274
|
+
try {
|
|
275
|
+
if (fs.statSync(file).size <= WAV_HEADER_BYTES) return false;
|
|
276
|
+
fd = fs.openSync(file, 'r');
|
|
277
|
+
const head = Buffer.alloc(4);
|
|
278
|
+
fs.readSync(fd, head, 0, 4, 0);
|
|
279
|
+
return head.toString('latin1') === 'RIFF';
|
|
280
|
+
} catch {
|
|
281
|
+
return false;
|
|
282
|
+
} finally {
|
|
283
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Seconds of audio in a WAV from its RIFF fmt byteRate and data chunk size; 0 when unparseable. */
|
|
288
|
+
function wavSeconds(file) {
|
|
289
|
+
let fd;
|
|
290
|
+
try {
|
|
291
|
+
fd = fs.openSync(file, 'r');
|
|
292
|
+
const size = fs.fstatSync(fd).size;
|
|
293
|
+
const buf = Buffer.alloc(Math.min(size, WAV_SCAN_BYTES));
|
|
294
|
+
fs.readSync(fd, buf, 0, buf.length, 0);
|
|
295
|
+
if (buf.length < 12 || buf.toString('latin1', 0, 4) !== 'RIFF' || buf.toString('latin1', 8, 12) !== 'WAVE') return 0;
|
|
296
|
+
let byteRate = 0;
|
|
297
|
+
for (let off = 12; off + 8 <= buf.length;) {
|
|
298
|
+
const id = buf.toString('latin1', off, off + 4);
|
|
299
|
+
const len = buf.readUInt32LE(off + 4);
|
|
300
|
+
if (id === 'fmt ' && off + 16 <= buf.length) byteRate = buf.readUInt32LE(off + 16);
|
|
301
|
+
if (id === 'data') {
|
|
302
|
+
if (!(byteRate > 0)) return 0;
|
|
303
|
+
const bytes = Math.min(len, Math.max(0, size - off - 8));
|
|
304
|
+
return bytes / byteRate;
|
|
305
|
+
}
|
|
306
|
+
off += 8 + len + (len % 2);
|
|
307
|
+
}
|
|
308
|
+
return 0;
|
|
309
|
+
} catch {
|
|
310
|
+
return 0;
|
|
311
|
+
} finally {
|
|
312
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* How long one synthesis call may wait for its voice lane: the time left before
|
|
318
|
+
* env.SM_SCHEDULER_JOB_DEADLINE_MS minus SPEAK_DEADLINE_MARGIN_MS when that is set
|
|
319
|
+
* (may be <= 0: no time left), else LANE_WAIT_DEFAULT_MS (6 h).
|
|
320
|
+
*/
|
|
321
|
+
function laneWaitMs({ now = Date.now(), env = process.env } = {}) {
|
|
322
|
+
const raw = env && env.SM_SCHEDULER_JOB_DEADLINE_MS;
|
|
323
|
+
const deadline = Number(raw);
|
|
324
|
+
if (raw !== undefined && raw !== null && raw !== '' && Number.isFinite(deadline)) return deadline - now - SPEAK_DEADLINE_MARGIN_MS;
|
|
325
|
+
return LANE_WAIT_DEFAULT_MS;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** 'voice lane: waiting, position 1 of 2 (ahead: video demo inline:command)' — ahead = the lane holder. */
|
|
329
|
+
function lanePositionLine(pos) {
|
|
330
|
+
const h = pos && Array.isArray(pos.ahead) && pos.ahead.length ? pos.ahead[0] : null;
|
|
331
|
+
const ahead = h ? `${h.label ?? '?'} ${h.voiceId ?? '?'}` : '?';
|
|
332
|
+
return `voice lane: waiting, position ${pos.position} of ${pos.total} (ahead: ${ahead})`;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Run one synthesis call `fn` (-> {ok, error?}) inside the voice lane of rv's voice.
|
|
337
|
+
* ctx: {root, kind, label, onLanePosition?}. Always leaves the lane; the usage line
|
|
338
|
+
* carries ok, audioSeconds (sum over `outs`' WAV headers) and wallMs.
|
|
339
|
+
*/
|
|
340
|
+
function inLane(ctx, rv, outs, fn) {
|
|
341
|
+
const lane = require('./voiceLane.cjs');
|
|
342
|
+
const voiceId = rv.voiceId ? String(rv.voiceId) : `inline:${rv.voice.engine}`;
|
|
343
|
+
const ticket = lane.enterLane({ lane: lane.laneFor(rv.voice, rv.entry), voiceId, label: ctx.label, projectRoot: ctx.root, kind: ctx.kind });
|
|
344
|
+
let granted = false;
|
|
345
|
+
let ok = false;
|
|
346
|
+
try {
|
|
347
|
+
const left = laneWaitMs();
|
|
348
|
+
const w = lane.waitTurn(ticket, {
|
|
349
|
+
timeoutMs: Math.max(1, left),
|
|
350
|
+
onPosition: (pos) => {
|
|
351
|
+
if (pos.position > 0) process.stderr.write(`${lanePositionLine(pos)}\n`);
|
|
352
|
+
if (typeof ctx.onLanePosition === 'function') ctx.onLanePosition({ lane: ticket.lane, ...pos });
|
|
353
|
+
},
|
|
354
|
+
});
|
|
355
|
+
if (!w.ok) {
|
|
356
|
+
const why = left <= 0 ? ` (no time left before the job deadline minus a ${SPEAK_DEADLINE_MARGIN_MS / 60000} min margin)` : '';
|
|
357
|
+
return { ok: false, error: `${w.error}${why}` };
|
|
358
|
+
}
|
|
359
|
+
granted = true;
|
|
360
|
+
const r = fn();
|
|
361
|
+
ok = !!(r && r.ok);
|
|
362
|
+
return r;
|
|
363
|
+
} finally {
|
|
364
|
+
if (granted) {
|
|
365
|
+
const audioSeconds = outs.reduce((sum, o) => sum + wavSeconds(o), 0);
|
|
366
|
+
lane.leaveLane(ticket, { ok, audioSeconds: Math.round(audioSeconds * 1000) / 1000 });
|
|
367
|
+
} else {
|
|
368
|
+
lane.leaveLane(ticket, { ok: false, record: false });
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Run the voice command (no shell). -> {ok, status, error?}
|
|
375
|
+
* ok only when the command exited 0 AND wrote a WAV to `out`; the error carries
|
|
376
|
+
* the last STDERR_TAIL chars of the command's stderr.
|
|
377
|
+
*/
|
|
378
|
+
function speakWithCommand(voice, text, out, { cwd } = {}) {
|
|
379
|
+
if (!voice || voice.engine !== 'command' || validateVoice(voice, 'voice')) {
|
|
99
380
|
return { ok: false, status: null, error: 'not a valid command voice' };
|
|
100
381
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
382
|
+
if (isBatchVoice(voice)) {
|
|
383
|
+
return { ok: false, status: null, error: 'a {lines} voice is spoken by speakLines in one call per speaker, not per line' };
|
|
384
|
+
}
|
|
385
|
+
const outStr = String(out);
|
|
386
|
+
const [bin, ...args] = buildCommandArgv(voice, String(text), outStr);
|
|
387
|
+
const r = spawnSync(bin, args, {
|
|
388
|
+
shell: false,
|
|
389
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
390
|
+
timeout: COMMAND_TIMEOUT_MS,
|
|
391
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
392
|
+
...(cwd ? { cwd } : {}),
|
|
393
|
+
});
|
|
394
|
+
const stderr = r.stderr ? r.stderr.toString('utf8').trim().slice(-STDERR_TAIL) : '';
|
|
395
|
+
const withStderr = (msg) => (stderr ? `${msg}: ${stderr}` : msg);
|
|
396
|
+
if (r.error) return { ok: false, status: r.status, error: withStderr(r.error.message) };
|
|
397
|
+
if (r.status !== 0) {
|
|
398
|
+
const why = r.signal ? `killed by ${r.signal}` : `exit ${r.status}`;
|
|
399
|
+
return { ok: false, status: r.status, error: withStderr(`voice command failed (${why})`) };
|
|
400
|
+
}
|
|
401
|
+
const outAbs = path.resolve(cwd || process.cwd(), outStr);
|
|
402
|
+
if (!isWav(outAbs)) {
|
|
403
|
+
return { ok: false, status: r.status, error: withStderr(`the voice command wrote no WAV to ${outAbs}`) };
|
|
404
|
+
}
|
|
405
|
+
return { ok: true, status: r.status };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Time limit for one batch voice call over `lineCount` lines -> {ok: true, ms} | {ok: false, error}.
|
|
410
|
+
* ms = min(lineCount * COMMAND_TIMEOUT_MS, BATCH_TIMEOUT_CEILING_MS), capped at the scheduler's
|
|
411
|
+
* job deadline (env.SM_SCHEDULER_JOB_DEADLINE_MS) minus SPEAK_DEADLINE_MARGIN_MS when that is a
|
|
412
|
+
* finite number: the voice runs first, so the whole video is still to be built after it.
|
|
413
|
+
*/
|
|
414
|
+
function batchTimeoutMs(lineCount, { now = Date.now(), env = process.env } = {}) {
|
|
415
|
+
let ms = Math.min(lineCount * COMMAND_TIMEOUT_MS, BATCH_TIMEOUT_CEILING_MS);
|
|
416
|
+
const deadline = Number(env && env.SM_SCHEDULER_JOB_DEADLINE_MS);
|
|
417
|
+
const raw = env && env.SM_SCHEDULER_JOB_DEADLINE_MS;
|
|
418
|
+
if (raw !== undefined && raw !== null && raw !== '' && Number.isFinite(deadline)) {
|
|
419
|
+
ms = Math.min(ms, deadline - now - SPEAK_DEADLINE_MARGIN_MS);
|
|
420
|
+
}
|
|
421
|
+
if (ms < MIN_BATCH_TIMEOUT_MS) {
|
|
422
|
+
const left = Math.max(0, Math.floor(ms / 1000));
|
|
423
|
+
return {
|
|
424
|
+
ok: false,
|
|
425
|
+
error: `only ${left}s left before the job deadline (minus a ${SPEAK_DEADLINE_MARGIN_MS / 60000} min margin) for ${lineCount} lines; need at least ${MIN_BATCH_TIMEOUT_MS / 1000}s`,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
return { ok: true, ms };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Run one batch ({lines}) voice over `items` ([{ text, out }], out absolute), cwd = root.
|
|
433
|
+
* -> {ok: true} | {ok: false, error}. Old files at the outs are removed first; stderr goes
|
|
434
|
+
* to a file (never a pipe) so a long run cannot overflow spawnSync's maxBuffer.
|
|
435
|
+
*/
|
|
436
|
+
function speakBatch(voice, items, root) {
|
|
437
|
+
const limit = batchTimeoutMs(items.length);
|
|
438
|
+
if (!limit.ok) return limit;
|
|
439
|
+
for (const it of items) {
|
|
440
|
+
try {
|
|
441
|
+
fs.rmSync(it.out, { force: true });
|
|
442
|
+
} catch (e) {
|
|
443
|
+
return { ok: false, error: `cannot clear ${it.out}: ${e.message}` };
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
let dir;
|
|
447
|
+
try {
|
|
448
|
+
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-voice-'));
|
|
449
|
+
const manifest = path.join(dir, 'lines.json');
|
|
450
|
+
fs.writeFileSync(manifest, JSON.stringify(items.map(({ text, out }) => ({ text, out }))));
|
|
451
|
+
const errPath = path.join(dir, 'stderr.log');
|
|
452
|
+
const errFd = fs.openSync(errPath, 'w');
|
|
453
|
+
let r;
|
|
454
|
+
try {
|
|
455
|
+
const [bin, ...args] = buildBatchArgv(voice, manifest);
|
|
456
|
+
r = spawnSync(bin, args, { shell: false, stdio: ['ignore', 'ignore', errFd], timeout: limit.ms, cwd: root });
|
|
457
|
+
} finally {
|
|
458
|
+
fs.closeSync(errFd);
|
|
459
|
+
}
|
|
460
|
+
let stderr = '';
|
|
461
|
+
try { stderr = fs.readFileSync(errPath, 'utf8').trim().slice(-STDERR_TAIL); } catch { /* none */ }
|
|
462
|
+
const withStderr = (msg) => (stderr ? `${msg}: ${stderr}` : msg);
|
|
463
|
+
const mins = Math.round((limit.ms / 60000) * 10) / 10;
|
|
464
|
+
if (r.error && r.error.code === 'ETIMEDOUT') {
|
|
465
|
+
return { ok: false, error: withStderr(`voice command killed by ${r.signal || 'SIGTERM'} at its ${mins} min limit`) };
|
|
466
|
+
}
|
|
467
|
+
if (r.error) return { ok: false, error: withStderr(r.error.message) };
|
|
468
|
+
if (r.status !== 0) {
|
|
469
|
+
const why = r.signal ? `killed by ${r.signal} (limit ${mins} min)` : `exit ${r.status}`;
|
|
470
|
+
return { ok: false, error: withStderr(`voice command failed (${why})`) };
|
|
471
|
+
}
|
|
472
|
+
const missing = items.filter((it) => !isWav(it.out)).map((it) => it.out);
|
|
473
|
+
if (missing.length) {
|
|
474
|
+
return { ok: false, error: withStderr(`the voice command left ${missing.length} of ${items.length} outs missing (no WAV at ${missing[0]})`) };
|
|
475
|
+
}
|
|
476
|
+
return { ok: true };
|
|
477
|
+
} catch (e) {
|
|
478
|
+
return { ok: false, error: e.message };
|
|
479
|
+
} finally {
|
|
480
|
+
if (dir) fs.rmSync(dir, { recursive: true, force: true });
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Resolve one speaker's voice to an inline engine voice. A {voiceId} ref (or a bare
|
|
486
|
+
* id string) goes through voiceLibrary.resolveVoiceId; an inline voice is checked
|
|
487
|
+
* with validateVoice. -> {ok: true, voice, voiceId?, entry?} | {ok: false, voiceId?, error}
|
|
488
|
+
*/
|
|
489
|
+
function resolveSpeakerVoice(root, voice) {
|
|
490
|
+
const v = typeof voice === 'string' ? { voiceId: voice } : voice;
|
|
491
|
+
if (isVoiceIdRef(v)) {
|
|
492
|
+
const refErr = validateVoiceOrRef(v, 'voice');
|
|
493
|
+
if (refErr) return { ok: false, voiceId: String(v.voiceId), error: refErr };
|
|
494
|
+
// Lazy: voiceLibrary.cjs requires this file.
|
|
495
|
+
const r = require('./voiceLibrary.cjs').resolveVoiceId(root, v.voiceId);
|
|
496
|
+
if (!r.ok) return { ok: false, voiceId: v.voiceId, error: r.error };
|
|
497
|
+
return { ok: true, voice: r.voice, voiceId: v.voiceId, entry: r.entry };
|
|
498
|
+
}
|
|
499
|
+
const err = validateVoice(v, 'voice');
|
|
500
|
+
if (err) return { ok: false, error: err };
|
|
501
|
+
return { ok: true, voice: v };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** 'af_heart' / 'kokoro af_heart' / 'command bin/tts' — names a voice in an error. */
|
|
505
|
+
function voiceLabel(rv, voice) {
|
|
506
|
+
if (rv && rv.voiceId) return `voice '${rv.voiceId}'`;
|
|
507
|
+
const v = rv && rv.voice ? rv.voice : voice;
|
|
508
|
+
if (v && v.engine === 'kokoro') return `kokoro voice '${v.id}'`;
|
|
509
|
+
if (v && v.engine === 'command' && Array.isArray(v.command)) return `command voice '${v.command[0]}'`;
|
|
510
|
+
return 'voice';
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** One Kokoro group: every line of one speaker in ONE sayKokoro call, within batchTimeoutMs. */
|
|
514
|
+
function speakKokoro(voice, items, root) {
|
|
515
|
+
const limit = batchTimeoutMs(items.length);
|
|
516
|
+
if (!limit.ok) return limit;
|
|
517
|
+
const { sayKokoro } = require('./kokoroSay.cjs');
|
|
518
|
+
const r = sayKokoro(kokoroItems(voice, items), { cwd: root, timeoutMs: limit.ms });
|
|
519
|
+
return r.ok ? { ok: true } : { ok: false, error: r.error };
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function kokoroItems(voice, items) {
|
|
523
|
+
return items.map((l) => ({ text: l.text, out: l.out, voice: voice.id, speed: voice.speed, lang: voice.lang }));
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Speak every narration line, in order, cwd = the project root. A line is
|
|
528
|
+
* { text, out, speaker? }: an absent/null speaker (or the host's name) uses the
|
|
529
|
+
* host's voice; a cast member's name (case-insensitive, trimmed) uses that
|
|
530
|
+
* member's voice. opts.voice (a library voice id or an inline voice) replaces the
|
|
531
|
+
* host's voice for this run only, and needs no saved character (then a named
|
|
532
|
+
* speaker is refused). A {voiceId} voice resolves through voiceLibrary.resolveVoiceId.
|
|
533
|
+
* Every line's speaker and voice are resolved before any voice runs. A per-line
|
|
534
|
+
* ({text}/{out}) command voice runs once per line. A batch ({lines}) command voice
|
|
535
|
+
* runs ONCE, at its speaker's first line, over a JSON manifest [{ text, out }] of
|
|
536
|
+
* all its lines; a kokoro voice runs ONCE per speaker the same way through
|
|
537
|
+
* kokoroSay.sayKokoro (its id, speed, lang). Grouped outs must end in .wav and be
|
|
538
|
+
* distinct; groups run within batchTimeoutMs and succeed only when every out is a
|
|
539
|
+
* WAV. No fallback voice: the first failure stops the run.
|
|
540
|
+
* Every call (per line, per batch group, per kokoro group) runs in the voice lane
|
|
541
|
+
* voiceLane.laneFor(voice, entry); opts.kind (default 'video') and opts.label
|
|
542
|
+
* (default 'video <basename of root>') go on the lane ticket and usage line, and
|
|
543
|
+
* opts.onLanePosition(pos) sees each lane position change.
|
|
544
|
+
* -> {ok: true, outs} | {ok: false, line?, lines?, speaker?, error}
|
|
545
|
+
*/
|
|
546
|
+
function speakLines(projectRoot, lines, opts = {}) {
|
|
547
|
+
let root;
|
|
548
|
+
try {
|
|
549
|
+
root = projectRootOf(projectRoot, 'speakLines');
|
|
550
|
+
} catch (e) {
|
|
551
|
+
return { ok: false, error: e.message };
|
|
552
|
+
}
|
|
553
|
+
if (!Array.isArray(lines) || lines.length === 0) return { ok: false, error: 'lines must be a non-empty array of { text, out, speaker? }' };
|
|
554
|
+
const laneCtx = {
|
|
555
|
+
root,
|
|
556
|
+
kind: opts && typeof opts.kind === 'string' && opts.kind ? opts.kind : 'video',
|
|
557
|
+
label: opts && typeof opts.label === 'string' && opts.label ? opts.label : `video ${path.basename(root)}`,
|
|
558
|
+
onLanePosition: opts ? opts.onLanePosition : undefined,
|
|
559
|
+
};
|
|
560
|
+
const override = opts && opts.voice !== undefined && opts.voice !== null ? opts.voice : undefined;
|
|
561
|
+
if (override !== undefined) {
|
|
562
|
+
const ov = typeof override === 'string' ? { voiceId: override } : override;
|
|
563
|
+
const oErr = !ov || typeof ov !== 'object' || Array.isArray(ov)
|
|
564
|
+
? 'spec.voice must be a voice id string or a voice object'
|
|
565
|
+
: validateVoiceOrRef(ov, 'spec.voice');
|
|
566
|
+
if (oErr) return { ok: false, error: oErr };
|
|
567
|
+
}
|
|
568
|
+
const ch = inspectCharacter(root);
|
|
569
|
+
const noCharacter = !ch.ok && !ch.exists && override !== undefined;
|
|
570
|
+
if (!ch.ok && !noCharacter) return { ok: false, error: `no valid saved character in ${characterDir(root)}: ${ch.error}` };
|
|
571
|
+
const host = noCharacter
|
|
572
|
+
? { name: 'spec.voice', voice: override }
|
|
573
|
+
: { name: ch.json.name, voice: override !== undefined ? override : ch.json.voice };
|
|
574
|
+
const cast = !noCharacter && Array.isArray(ch.json.cast) ? ch.json.cast : [];
|
|
575
|
+
const speakers = [host, ...cast];
|
|
576
|
+
const byKey = noCharacter ? new Map() : new Map(speakers.map((m) => [String(m.name).trim().toLowerCase(), m]));
|
|
577
|
+
const names = speakers.map((m) => String(m.name).trim());
|
|
578
|
+
const nonEmpty = (v) => typeof v === 'string' && v.length > 0;
|
|
579
|
+
const voices = new Map(); // speaker name -> resolveSpeakerVoice result
|
|
580
|
+
const resolved = [];
|
|
581
|
+
const groups = new Map(); // speaker name -> { kind: 'batch'|'kokoro', voice, indices, seen: Map<absOut, lineIndex> }
|
|
582
|
+
for (let i = 0; i < lines.length; i++) {
|
|
583
|
+
const l = lines[i];
|
|
584
|
+
const sp = l ? l.speaker : undefined;
|
|
585
|
+
if (!l || !nonEmpty(l.text) || !nonEmpty(l.out) || !(sp === undefined || sp === null || (nonEmpty(sp) && sp.trim()))) {
|
|
586
|
+
return { ok: false, line: i, error: `line ${i} must be { text, out, speaker? } with non-empty strings` };
|
|
587
|
+
}
|
|
588
|
+
if (noCharacter && !(sp === undefined || sp === null)) {
|
|
589
|
+
return { ok: false, line: i, error: `line ${i}: speaker "${sp}" is refused: no character is saved, so only spec.voice speaks (omit speaker)` };
|
|
590
|
+
}
|
|
591
|
+
const m = sp === undefined || sp === null ? host : byKey.get(sp.trim().toLowerCase());
|
|
592
|
+
if (!m) return { ok: false, line: i, error: `line ${i}: unknown speaker "${sp}" (speakers: ${names.join(', ')})` };
|
|
593
|
+
const name = String(m.name).trim();
|
|
594
|
+
if (!m.voice) return { ok: false, line: i, error: `line ${i}: "${name}" has no voice and never speaks lines` };
|
|
595
|
+
let rv = voices.get(name);
|
|
596
|
+
if (!rv) { rv = resolveSpeakerVoice(root, m.voice); voices.set(name, rv); }
|
|
597
|
+
if (!rv.ok) return { ok: false, line: i, speaker: name, error: `line ${i}: "${name}" ${voiceLabel(rv, m.voice)}: ${rv.error}` };
|
|
598
|
+
const voice = rv.voice;
|
|
599
|
+
const kind = voice.engine === 'kokoro' ? 'kokoro' : isBatchVoice(voice) ? 'batch' : null;
|
|
600
|
+
if (kind) {
|
|
601
|
+
const what = kind === 'kokoro' ? 'a kokoro' : 'a {lines}';
|
|
602
|
+
if (!l.out.toLowerCase().endsWith('.wav')) return { ok: false, line: i, error: `line ${i}: ${what} voice's out must end in .wav` };
|
|
603
|
+
const abs = path.resolve(root, l.out);
|
|
604
|
+
let b = groups.get(name);
|
|
605
|
+
if (!b) { b = { kind, voice, rv, label: voiceLabel(rv), indices: [], seen: new Map() }; groups.set(name, b); }
|
|
606
|
+
if (b.seen.has(abs)) return { ok: false, line: i, error: `line ${i}: out ${abs} repeats line ${b.seen.get(abs)}'s out` };
|
|
607
|
+
b.seen.set(abs, i);
|
|
608
|
+
b.indices.push(i);
|
|
609
|
+
}
|
|
610
|
+
resolved.push({ name, voice, rv, label: voiceLabel(rv), text: l.text, out: l.out });
|
|
611
|
+
}
|
|
612
|
+
const itemsOf = (b) => b.indices.map((j) => ({ text: resolved[j].text, out: path.resolve(root, resolved[j].out) }));
|
|
613
|
+
for (const [name, b] of groups) {
|
|
614
|
+
if (b.kind !== 'kokoro') continue;
|
|
615
|
+
const v = require('./kokoroSay.cjs').validateLines(kokoroItems(b.voice, itemsOf(b)), root);
|
|
616
|
+
if (!v.ok) return { ok: false, line: b.indices[0], lines: b.indices.slice(), speaker: name, error: `"${name}" ${b.label}: ${v.error}` };
|
|
617
|
+
}
|
|
618
|
+
const outs = [];
|
|
619
|
+
const spoken = new Set();
|
|
620
|
+
for (let i = 0; i < resolved.length; i++) {
|
|
621
|
+
const { name, voice, rv, label, text, out } = resolved[i];
|
|
622
|
+
const b = groups.get(name);
|
|
623
|
+
if (b) {
|
|
624
|
+
if (!spoken.has(name)) {
|
|
625
|
+
spoken.add(name);
|
|
626
|
+
const items = itemsOf(b);
|
|
627
|
+
const r = inLane(laneCtx, b.rv, items.map((it) => it.out), () => (b.kind === 'kokoro' ? speakKokoro(b.voice, items, root) : speakBatch(b.voice, items, root)));
|
|
628
|
+
if (!r.ok) {
|
|
629
|
+
const who = b.kind === 'kokoro' ? `"${name}" ${b.label}` : `"${name}"`;
|
|
630
|
+
return { ok: false, line: b.indices[0], lines: b.indices.slice(), speaker: name, error: `${who}: ${r.error}` };
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
} else {
|
|
634
|
+
const r = inLane(laneCtx, rv, [path.resolve(root, out)], () => speakWithCommand(voice, text, out, { cwd: root }));
|
|
635
|
+
if (!r.ok) return { ok: false, line: i, speaker: name, error: `"${name}"${label.startsWith('voice ') ? ` ${label}` : ''}: ${r.error}` };
|
|
636
|
+
}
|
|
637
|
+
outs.push(out);
|
|
638
|
+
}
|
|
639
|
+
return { ok: true, outs };
|
|
105
640
|
}
|
|
106
641
|
|
|
107
642
|
module.exports = {
|
|
108
643
|
readCharacter,
|
|
109
644
|
speakWithCommand,
|
|
645
|
+
speakLines,
|
|
646
|
+
resolveSpeakerVoice,
|
|
110
647
|
buildCommandArgv,
|
|
648
|
+
buildBatchArgv,
|
|
649
|
+
isBatchVoice,
|
|
650
|
+
wavSeconds,
|
|
651
|
+
laneWaitMs,
|
|
652
|
+
lanePositionLine,
|
|
653
|
+
LANE_WAIT_DEFAULT_MS,
|
|
111
654
|
validateCharacterJson,
|
|
112
655
|
validateCharacterJs,
|
|
656
|
+
validatePersonality,
|
|
657
|
+
validateVoice,
|
|
658
|
+
isVoiceIdRef,
|
|
659
|
+
voiceIdRefsOf,
|
|
660
|
+
inspectCharacter,
|
|
113
661
|
characterDir,
|
|
114
662
|
MAX_JS_BYTES,
|
|
663
|
+
MAX_JSON_BYTES,
|
|
664
|
+
MAX_CAST_MEMBERS,
|
|
665
|
+
COMMAND_TIMEOUT_MS,
|
|
666
|
+
batchTimeoutMs,
|
|
667
|
+
BATCH_TIMEOUT_CEILING_MS,
|
|
668
|
+
SPEAK_DEADLINE_MARGIN_MS,
|
|
669
|
+
MIN_BATCH_TIMEOUT_MS,
|
|
115
670
|
};
|
|
671
|
+
|
|
672
|
+
// CLI: node character.cjs speak spec.json [--wait <seconds>]
|
|
673
|
+
// (spec { projectRoot, lines: [{ text, out, speaker? }], voice?, kind?, label? }; voice = a
|
|
674
|
+
// library voice id or an inline voice replacing the host's voice for this run; kind and
|
|
675
|
+
// label name the run in the voice lane and its usage log)
|
|
676
|
+
// speakLines runs in a detached runner (resumableRun.cjs) keyed by the sha256
|
|
677
|
+
// of the spec bytes, state in <abs spec>.run/. Each call waits one slice: the
|
|
678
|
+
// result (exit 0/1) or, while still speaking, a pending line with exit 75 —
|
|
679
|
+
// run the same command again to attach to the same run. The runner writes its
|
|
680
|
+
// latest voice lane position to <abs spec>.run/lane.json; the pending line carries it.
|
|
681
|
+
const SPEAK_USAGE = 'usage: node character.cjs speak spec.json [--wait seconds]';
|
|
682
|
+
const EXIT_PENDING = 75;
|
|
683
|
+
const MAX_WAIT_S = 840;
|
|
684
|
+
|
|
685
|
+
/** Slice length in ms from --wait, else BASH_DEFAULT_TIMEOUT_MS - 30 s clamped to 10-840 s, else 90 s. */
|
|
686
|
+
function speakWaitMs(flags, env = process.env) {
|
|
687
|
+
if (flags.length) {
|
|
688
|
+
if (flags.length !== 2 || flags[0] !== '--wait' || !/^\d+$/.test(flags[1])) return null;
|
|
689
|
+
const n = Number(flags[1]);
|
|
690
|
+
return n >= 1 && n <= MAX_WAIT_S ? n * 1000 : null;
|
|
691
|
+
}
|
|
692
|
+
const bash = Number(env.BASH_DEFAULT_TIMEOUT_MS);
|
|
693
|
+
if (!(bash > 0)) return 90 * 1000;
|
|
694
|
+
return Math.min(MAX_WAIT_S * 1000, Math.max(10 * 1000, bash - 30 * 1000));
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
const lanePath = (stateDir) => path.join(stateDir, 'lane.json');
|
|
698
|
+
|
|
699
|
+
function specOuts(spec) {
|
|
700
|
+
const lines = spec && Array.isArray(spec.lines) ? spec.lines : [];
|
|
701
|
+
const root = spec && typeof spec.projectRoot === 'string' ? spec.projectRoot : '';
|
|
702
|
+
return lines.map((l) => (l && typeof l.out === 'string' && l.out ? path.resolve(root, l.out) : null));
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
function readSpec(specPath) {
|
|
706
|
+
const bytes = fs.readFileSync(specPath);
|
|
707
|
+
return { bytes, spec: JSON.parse(bytes.toString('utf8')) };
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
async function speakCli(specPath, flags) {
|
|
711
|
+
const waitMs = speakWaitMs(flags);
|
|
712
|
+
if (waitMs === null) return { result: { ok: false, error: SPEAK_USAGE } };
|
|
713
|
+
let bytes;
|
|
714
|
+
let spec;
|
|
715
|
+
try {
|
|
716
|
+
({ bytes, spec } = readSpec(specPath));
|
|
717
|
+
} catch (e) {
|
|
718
|
+
return { result: { ok: false, error: `cannot read spec ${specPath}: ${e.message}` } };
|
|
719
|
+
}
|
|
720
|
+
const rr = require('./resumableRun.cjs');
|
|
721
|
+
const crypto = require('node:crypto');
|
|
722
|
+
const key = crypto.createHash('sha256').update(bytes).digest('hex');
|
|
723
|
+
const absSpec = path.resolve(specPath);
|
|
724
|
+
const stateDir = `${absSpec}.run`;
|
|
725
|
+
const outs = specOuts(spec);
|
|
726
|
+
const allWavs = () => outs.length > 0 && outs.every((o) => o && isWav(o));
|
|
727
|
+
let prior = null;
|
|
728
|
+
try { prior = JSON.parse(fs.readFileSync(path.join(stateDir, 'result.json'), 'utf8')); } catch { /* none yet */ }
|
|
729
|
+
if (prior && prior.key === key && prior.result && prior.result.ok === true) {
|
|
730
|
+
if (allWavs()) return { result: prior.result };
|
|
731
|
+
rr.stopRun(stateDir);
|
|
732
|
+
}
|
|
733
|
+
const att = rr.startOrAttach({ stateDir, key, argv: [__filename, '__speak-run', absSpec, key], cwd: path.dirname(absSpec) });
|
|
734
|
+
if (att.started) fs.rmSync(lanePath(stateDir), { force: true });
|
|
735
|
+
const w = await rr.waitForResult({ stateDir, key, waitMs });
|
|
736
|
+
if (w.status === 'done') return { result: w.result };
|
|
737
|
+
if (w.status === 'lost') return { result: { ok: false, error: `speak runner (node character.cjs __speak-run ${absSpec}): ${w.error}` } };
|
|
738
|
+
const wavs = outs.filter((o) => o && isWav(o)).length;
|
|
739
|
+
let lane = null;
|
|
740
|
+
try { const j = JSON.parse(fs.readFileSync(lanePath(stateDir), 'utf8')); if (j && j.key === key && j.pos) lane = j.pos; } catch { /* not in a lane yet */ }
|
|
741
|
+
const waiting = lane && lane.position > 0 ? `; ${lanePositionLine(lane)}` : '';
|
|
742
|
+
return {
|
|
743
|
+
pending: true,
|
|
744
|
+
result: {
|
|
745
|
+
ok: false,
|
|
746
|
+
pending: true,
|
|
747
|
+
pid: w.pid,
|
|
748
|
+
elapsedS: Math.round(w.elapsedMs / 1000),
|
|
749
|
+
wavs,
|
|
750
|
+
lines: outs.length,
|
|
751
|
+
...(lane ? { lane: { lane: lane.lane, position: lane.position, total: lane.total, ahead: lane.ahead } } : {}),
|
|
752
|
+
message: `still speaking (${wavs}/${outs.length} WAVs so far${waiting}); run the same command again`,
|
|
753
|
+
},
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
function speakRunner(specPath, key) {
|
|
758
|
+
const rr = require('./resumableRun.cjs');
|
|
759
|
+
const crypto = require('node:crypto');
|
|
760
|
+
const stateDir = `${path.resolve(specPath)}.run`;
|
|
761
|
+
let result;
|
|
762
|
+
try {
|
|
763
|
+
const { bytes, spec } = readSpec(specPath);
|
|
764
|
+
const got = crypto.createHash('sha256').update(bytes).digest('hex');
|
|
765
|
+
result = got !== key
|
|
766
|
+
? { ok: false, error: `spec ${specPath} changed since this run started` }
|
|
767
|
+
: speakLines(spec && spec.projectRoot, spec && spec.lines, {
|
|
768
|
+
voice: spec ? spec.voice : undefined,
|
|
769
|
+
kind: spec ? spec.kind : undefined,
|
|
770
|
+
label: spec ? spec.label : undefined,
|
|
771
|
+
onLanePosition: (pos) => {
|
|
772
|
+
try { fs.writeFileSync(lanePath(stateDir), JSON.stringify({ key, pos })); } catch { /* stateDir gone: run stopped */ }
|
|
773
|
+
},
|
|
774
|
+
});
|
|
775
|
+
} catch (e) {
|
|
776
|
+
result = { ok: false, error: `cannot read spec ${specPath}: ${e.message}` };
|
|
777
|
+
}
|
|
778
|
+
rr.writeResult(stateDir, key, result);
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
async function main(argv) {
|
|
782
|
+
const [cmdName, specPath, ...rest] = argv;
|
|
783
|
+
if (cmdName === '__speak-run' && specPath && rest.length === 1 && rest[0]) {
|
|
784
|
+
speakRunner(specPath, rest[0]);
|
|
785
|
+
process.exitCode = 0; // the waiting call reports failures
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
const out = cmdName === 'speak' && specPath
|
|
789
|
+
? await speakCli(specPath, rest)
|
|
790
|
+
: { result: { ok: false, error: SPEAK_USAGE } };
|
|
791
|
+
const { result } = out;
|
|
792
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
793
|
+
if (out.pending) {
|
|
794
|
+
process.exitCode = EXIT_PENDING;
|
|
795
|
+
} else if (!result.ok) {
|
|
796
|
+
process.stderr.write(`${result.error}\n`);
|
|
797
|
+
process.exitCode = 1;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
if (require.main === module) {
|
|
802
|
+
main(process.argv.slice(2)).catch((e) => {
|
|
803
|
+
process.stdout.write(`${JSON.stringify({ ok: false, error: e && e.message ? e.message : String(e) })}\n`);
|
|
804
|
+
process.stderr.write(`${e && e.stack ? e.stack : e}\n`);
|
|
805
|
+
process.exitCode = 1;
|
|
806
|
+
});
|
|
807
|
+
}
|