claude-code-session-manager 0.141.0 → 0.143.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/.claude-plugin/marketplace.json +1 -1
- package/README.md +76 -153
- package/bin/cli.cjs +11 -0
- package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
- package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
- package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
- package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
- package/dist/assets/Scheduler-CNLjn90m.js +16 -0
- package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
- package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
- package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
- package/dist/assets/Toggle-CYajnSdx.js +1 -0
- package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
- package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
- package/dist/assets/index-CdTppjKR.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 +6 -4
- package/plugins/AGENTS.md +4 -3
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
- 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/builder/SKILL.md +5 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
- package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
- package/scripts/README.md +2 -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 +1032 -112
- package/src/main/adminRouteRegistry.cjs +69 -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 +336 -23
- package/src/main/config.cjs +35 -1
- package/src/main/docEdit.cjs +4 -2
- package/src/main/health.cjs +129 -2
- package/src/main/index.cjs +110 -52
- package/src/main/ipcSchemas.cjs +172 -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 +52 -0
- package/src/main/lib/demo-video-kit/character.cjs +778 -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 +103 -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/projectSounds.cjs +191 -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/sound.cjs +166 -9
- package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
- 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/activeIndexMerge.cjs +5 -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 +356 -0
- package/src/main/lib/epic/artifactStore.cjs +435 -0
- package/src/main/lib/epic/delegationReadiness.cjs +83 -2
- package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
- package/src/main/lib/epic/epicEventLog.cjs +258 -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/epicStateEmitter.cjs +248 -0
- 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 +94 -4
- package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
- package/src/main/lib/externalContract.cjs +48 -4
- package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
- 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 +32 -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 +207 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
- package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
- 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/gitWorktree.cjs +8 -0
- package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
- package/src/main/lib/git/worktreeDeps.cjs +182 -4
- package/src/main/lib/mcpToolCatalog.cjs +399 -29
- package/src/main/lib/opsOwnership.cjs +141 -28
- 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 +309 -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 +387 -228
- package/src/main/lib/prd/prdCriteria.cjs +228 -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/videoPressLines.cjs +145 -0
- package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
- package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
- package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
- package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
- package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
- 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 +313 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
- package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
- package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
- package/src/main/lib/scheduler/loadGate.cjs +82 -4
- package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
- package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
- package/src/main/lib/scheduler/queueStore.cjs +16 -0
- package/src/main/lib/scheduler/rcaReport.cjs +79 -15
- package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -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 +9 -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 +251 -0
- package/src/main/lib/scheduler/toolClearance.cjs +258 -0
- package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
- package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
- package/src/main/lib/tasks/mitigationReview.cjs +314 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
- 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 +204 -6
- package/src/main/lib/telemetry/auditLog.cjs +6 -2
- 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/atomicFs.cjs +2 -2
- package/src/main/lib/util/smfileRange.cjs +77 -0
- package/src/main/projectPages.cjs +3 -1
- package/src/main/promptSessionEvents.cjs +21 -1
- package/src/main/pty.cjs +77 -0
- package/src/main/queueOps.cjs +33 -14
- 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 +191 -0
- package/src/main/scheduler.cjs +1932 -213
- package/src/main/templates/PRD_AUTHORING.md +11 -3
- package/src/main/webRemote.cjs +463 -6
- package/src/preload/api.d.ts +576 -39
- package/src/preload/apiSurface.json +223 -7
- package/src/preload/index.cjs +48 -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 +98 -87
- 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 +23 -23
- 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,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* videoScriptSwitchRoute.cjs — the agent path for 'Scripts may run Demo Video'.
|
|
3
|
+
*
|
|
4
|
+
* POST /admin/project-home/videos/script-switch (body ≤ 64 KiB)
|
|
5
|
+
* { enabled, humanRequestQuote, originClaudeSessionId, cwd?, originProjectRoot? }
|
|
6
|
+
* Sets ONE project's switch on or off, and only on a verbatim quote of what
|
|
7
|
+
* the human typed in the calling chat session (humanPromptLedger). Checks,
|
|
8
|
+
* in order, each refusal writing and auditing nothing:
|
|
9
|
+
* 1. 403 human_request_unverified — the quote is not in a prompt the
|
|
10
|
+
* human typed in originClaudeSessionId (the ledger is the only proof);
|
|
11
|
+
* 2. 403 quote_does_not_name_switch — the quote does not say
|
|
12
|
+
* 'Scripts may run Demo Video' (quoteNamesVideoScriptSwitch);
|
|
13
|
+
* 3. 403 quote_does_not_name_project — the target is not the calling
|
|
14
|
+
* session's own project and the quote does not name it
|
|
15
|
+
* (crossProjectFeedback.quoteNamesTarget);
|
|
16
|
+
* 4. 409 request_older_than_switch — the matched prompt is not later
|
|
17
|
+
* than the switch's last change: one human instruction authorizes one
|
|
18
|
+
* write, and never undoes a later click.
|
|
19
|
+
* Success: videoScriptPress.setVideoScriptSwitch(target, enabled, { via:'agent',
|
|
20
|
+
* claudeSessionId, quote, promptAt }), one video_script_switch_changed audit
|
|
21
|
+
* event, 200 { ok, cwd, enabled, changedAt, by, previous }.
|
|
22
|
+
* Setting the value the switch already has re-stamps the attribution.
|
|
23
|
+
*
|
|
24
|
+
* Same shape as lib/tasks/taskSwitchRoute.cjs, minus the held-slot resync
|
|
25
|
+
* (that is Task-only). Scripts, scheduled jobs and Tasks cannot reach this:
|
|
26
|
+
* their prompts are never recorded in humanPromptLedger (only the Chat view
|
|
27
|
+
* records them). Registered by adminRouteRegistry.cjs.
|
|
28
|
+
*/
|
|
29
|
+
'use strict';
|
|
30
|
+
|
|
31
|
+
const path = require('node:path');
|
|
32
|
+
const { z } = require('zod');
|
|
33
|
+
const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
|
|
34
|
+
|
|
35
|
+
const ROUTE_PATH = '/admin/project-home/videos/script-switch';
|
|
36
|
+
const MAX_SWITCH_BODY_BYTES = 64 * 1024;
|
|
37
|
+
|
|
38
|
+
const switchBodySchema = z.object({
|
|
39
|
+
enabled: z.boolean(),
|
|
40
|
+
humanRequestQuote: z.string().min(1).max(2000),
|
|
41
|
+
originClaudeSessionId: z.string().min(1).max(128),
|
|
42
|
+
cwd: z.string().min(1).optional(),
|
|
43
|
+
originProjectRoot: z.string().min(1).optional(),
|
|
44
|
+
}).strict();
|
|
45
|
+
|
|
46
|
+
const SWITCH_RE = /(^|[^a-z0-9])scripts?\s+(may|can)\s+run\s+demo\s+videos?($|[^a-z0-9])/;
|
|
47
|
+
|
|
48
|
+
/** True when the quote names the 'Scripts may run Demo Video' switch (case, quote-mark, hyphen variants; 'can' for 'may'). */
|
|
49
|
+
function quoteNamesVideoScriptSwitch(quote) {
|
|
50
|
+
if (typeof quote !== 'string') return false;
|
|
51
|
+
const q = quote
|
|
52
|
+
.toLowerCase()
|
|
53
|
+
.replace(/[-_'"‘’‚‛“”„‟′″`]/g, ' ')
|
|
54
|
+
.replace(/\s+/g, ' ');
|
|
55
|
+
return SWITCH_RE.test(q);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {{ registerRoute: Function }} adminHttp
|
|
60
|
+
* @param {{ findHumanPromptContaining?: Function, resolveProjectContext?: Function,
|
|
61
|
+
* resolveProjectRoot?: Function, videoScriptPress?: any, appendAuditEvent?: Function,
|
|
62
|
+
* quoteNamesTarget?: Function, now?: () => number }} [deps]
|
|
63
|
+
*/
|
|
64
|
+
function registerVideoScriptSwitchRoute(adminHttp, deps = {}) {
|
|
65
|
+
const findPrompt = deps.findHumanPromptContaining
|
|
66
|
+
|| ((/** @type {string} */ s, /** @type {string} */ q, /** @type {number} */ n) => require('../feedback-remote/humanPromptLedger.cjs').findHumanPromptContaining(s, q, n));
|
|
67
|
+
const resolveContext = deps.resolveProjectContext
|
|
68
|
+
|| ((/** @type {any} */ o) => require('../projectRootResolve.cjs').resolveProjectContext(o));
|
|
69
|
+
const projectRoot = deps.resolveProjectRoot
|
|
70
|
+
|| ((/** @type {string} */ c, /** @type {any} */ o) => require('../opsOwnership.cjs').resolveProjectRoot(c, o));
|
|
71
|
+
const store = () => deps.videoScriptPress || require('./videoScriptPress.cjs');
|
|
72
|
+
const audit = deps.appendAuditEvent
|
|
73
|
+
|| ((/** @type {string} */ k, /** @type {any} */ f) => require('../telemetry/auditLog.cjs').appendAuditEvent(k, f));
|
|
74
|
+
const namesTarget = deps.quoteNamesTarget
|
|
75
|
+
|| ((/** @type {string} */ q, /** @type {string} */ c) => require('../feedback-remote/crossProjectFeedback.cjs').quoteNamesTarget(q, c));
|
|
76
|
+
const now = deps.now || Date.now;
|
|
77
|
+
|
|
78
|
+
adminHttp.registerRoute('POST', ROUTE_PATH, async (/** @type {any} */ req, /** @type {any} */ res) => {
|
|
79
|
+
const bad = (/** @type {any} */ details) => sendJson(res, 400, { ok: false, error: 'invalid_request', details });
|
|
80
|
+
const refuse = (/** @type {number} */ status, /** @type {string} */ error, /** @type {string} */ reason) =>
|
|
81
|
+
sendJson(res, status, { ok: false, error, reason });
|
|
82
|
+
|
|
83
|
+
let raw;
|
|
84
|
+
try {
|
|
85
|
+
raw = await readBody(req, MAX_SWITCH_BODY_BYTES);
|
|
86
|
+
} catch (e) {
|
|
87
|
+
bad(e instanceof Error ? e.message : String(e));
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
let json;
|
|
91
|
+
try { json = JSON.parse(raw || '{}'); } catch {
|
|
92
|
+
bad('body is not valid JSON');
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const parsed = switchBodySchema.safeParse(json);
|
|
96
|
+
if (!parsed.success) {
|
|
97
|
+
bad(parsed.error.issues);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const { enabled, humanRequestQuote: quote, originClaudeSessionId, cwd: rawCwd, originProjectRoot } = parsed.data;
|
|
101
|
+
|
|
102
|
+
// The calling session's own project.
|
|
103
|
+
let origin = null;
|
|
104
|
+
try {
|
|
105
|
+
const ctx = resolveContext({ originClaudeSessionId, originProjectRoot });
|
|
106
|
+
const o = ctx && (ctx.epicCwd || ctx.cwd);
|
|
107
|
+
if (typeof o === 'string' && o) origin = path.resolve(o);
|
|
108
|
+
} catch { origin = null; }
|
|
109
|
+
|
|
110
|
+
let target = origin;
|
|
111
|
+
if (rawCwd !== undefined) {
|
|
112
|
+
try {
|
|
113
|
+
const root = projectRoot(rawCwd, { opsInternal: 'refuse' });
|
|
114
|
+
if (path.resolve(root) !== path.resolve(rawCwd)) throw new Error(`cwd is not a project root (its root is "${root}")`);
|
|
115
|
+
target = path.resolve(root);
|
|
116
|
+
} catch (e) {
|
|
117
|
+
bad(e instanceof Error ? e.message : String(e));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (!target) {
|
|
122
|
+
bad('no target project: pass cwd, or call from a Session Manager chat session whose project can be resolved');
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const found = findPrompt(originClaudeSessionId, quote, now());
|
|
127
|
+
if (!found) {
|
|
128
|
+
refuse(403, 'human_request_unverified', 'humanRequestQuote was not found in a prompt the human typed in this chat session');
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (!quoteNamesVideoScriptSwitch(quote)) {
|
|
132
|
+
refuse(403, 'quote_does_not_name_switch', "the human's quote does not name the 'Scripts may run Demo Video' switch");
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (target !== origin && !namesTarget(quote, target)) {
|
|
136
|
+
refuse(403, 'quote_does_not_name_project', `the target is not this session's project and the human's quote does not name it (${path.basename(target)})`);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const current = store().getVideoScriptSwitch(target);
|
|
140
|
+
const promptMs = Number(found.at);
|
|
141
|
+
const changedMs = current && current.changedAt ? Date.parse(current.changedAt) : NaN;
|
|
142
|
+
if (!Number.isFinite(promptMs) || (Number.isFinite(changedMs) && !(promptMs > changedMs))) {
|
|
143
|
+
refuse(409, 'request_older_than_switch', "the human's request is not newer than the switch's last change; ask the human again");
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const promptAt = new Date(promptMs).toISOString();
|
|
148
|
+
let saved;
|
|
149
|
+
try {
|
|
150
|
+
saved = store().setVideoScriptSwitch(target, enabled, { via: 'agent', claudeSessionId: originClaudeSessionId, quote, promptAt });
|
|
151
|
+
} catch (e) {
|
|
152
|
+
sendJson(res, 500, { ok: false, error: 'switch_write_failed', details: e instanceof Error ? e.message : String(e) });
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
try {
|
|
156
|
+
audit('video_script_switch_changed', { cwd: saved.cwd, enabled: saved.enabled, via: 'agent', claudeSessionId: originClaudeSessionId, quote });
|
|
157
|
+
} catch { /* audit is best-effort, like the Task switch route */ }
|
|
158
|
+
|
|
159
|
+
sendJson(res, 200, {
|
|
160
|
+
ok: true,
|
|
161
|
+
cwd: saved.cwd,
|
|
162
|
+
enabled: saved.enabled,
|
|
163
|
+
changedAt: saved.changedAt,
|
|
164
|
+
by: saved.by,
|
|
165
|
+
previous: {
|
|
166
|
+
enabled: !!(current && current.enabled),
|
|
167
|
+
by: current ? current.by : null,
|
|
168
|
+
},
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
module.exports = { registerVideoScriptSwitchRoute, quoteNamesVideoScriptSwitch, MAX_SWITCH_BODY_BYTES, ROUTE_PATH };
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* voiceAdminRoutes.cjs — the voice library's READ routes for agents (MCP
|
|
5
|
+
* voice_list / voice_preview). Neither route can change a voice: approving,
|
|
6
|
+
* unapproving and deleting stay renderer-IPC only (voicesIpc.cjs).
|
|
7
|
+
*
|
|
8
|
+
* GET /admin/voices?cwd=<abs> -> {ok, voices, errors} (voiceLibrary.listVoices)
|
|
9
|
+
* POST /admin/voices/preview {cwd, voiceId, text}
|
|
10
|
+
* -> {ok:true, status:'ready', cached, wavPath, wallMs, audioSeconds}
|
|
11
|
+
* when previewVoice finishes within WAIT_MS (60 s), else
|
|
12
|
+
* -> {ok:true, status:'queued', lane, position}
|
|
13
|
+
* while the run keeps going in-process. A repeat call with the same
|
|
14
|
+
* (project, voiceId, text) joins that run, or — once it finished —
|
|
15
|
+
* previewVoice answers from its clip cache.
|
|
16
|
+
*
|
|
17
|
+
* cwd goes through projectHomeAdminRoutes.resolveCwd (the shared project-root
|
|
18
|
+
* resolver + allowed-roots check); voiceId must match VOICE_ID_RE and text be
|
|
19
|
+
* 1-TEXT_MAX chars after trimming; bad input answers 400.
|
|
20
|
+
*
|
|
21
|
+
* deps (tests): { resolveCwd, voiceLibrary, voiceLane, previewVoice, waitMs, now }.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
|
|
25
|
+
const { wavSeconds } = require('../demo-video-kit/character.cjs');
|
|
26
|
+
|
|
27
|
+
const { VOICE_ID_RE } = require('../demo-video-kit/voiceLibrary.cjs');
|
|
28
|
+
const TEXT_MAX = 300;
|
|
29
|
+
const WAIT_MS = 60 * 1000;
|
|
30
|
+
const BODY_MAX = 64 * 1024;
|
|
31
|
+
|
|
32
|
+
/** key -> {promise, startedAt} for previews still running in-process. */
|
|
33
|
+
const pending = new Map();
|
|
34
|
+
|
|
35
|
+
function depsOf(deps) {
|
|
36
|
+
return {
|
|
37
|
+
resolveCwd: deps.resolveCwd || require('../feedback-remote/projectHomeAdminRoutes.cjs').resolveCwd,
|
|
38
|
+
voiceLibrary: deps.voiceLibrary || require('../demo-video-kit/voiceLibrary.cjs'),
|
|
39
|
+
voiceLane: deps.voiceLane || require('../demo-video-kit/voiceLane.cjs'),
|
|
40
|
+
previewVoice: deps.previewVoice || require('./voicePreview.cjs').previewVoice,
|
|
41
|
+
waitMs: Number.isFinite(deps.waitMs) && deps.waitMs >= 0 ? deps.waitMs : WAIT_MS,
|
|
42
|
+
now: deps.now || Date.now,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Seconds of audio in the clip at wavPath (character.cjs wavSeconds, 3 dp), else null. */
|
|
47
|
+
function clipSeconds(wavPath) {
|
|
48
|
+
if (!wavPath) return null;
|
|
49
|
+
const s = wavSeconds(wavPath);
|
|
50
|
+
return s > 0 ? Math.round(s * 1000) / 1000 : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** -> null when the preview body is acceptable, else the 400 reason. */
|
|
54
|
+
function validatePreviewBody(body) {
|
|
55
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return 'invalid payload';
|
|
56
|
+
if (typeof body.voiceId !== 'string' || !VOICE_ID_RE.test(body.voiceId)) {
|
|
57
|
+
return `voiceId must match /${VOICE_ID_RE.source}/`;
|
|
58
|
+
}
|
|
59
|
+
const t = typeof body.text === 'string' ? body.text.trim() : '';
|
|
60
|
+
if (t.length < 1 || t.length > TEXT_MAX) return `text must be 1-${TEXT_MAX} chars`;
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** This preview's place in the voice lane: {lane, position} or {lane:null, position:null}. */
|
|
65
|
+
function lanePositionOf(d, root, voiceId) {
|
|
66
|
+
let snapshot = {};
|
|
67
|
+
try { snapshot = d.voiceLane.laneSnapshot() || {}; } catch { snapshot = {}; }
|
|
68
|
+
for (const [lane, tickets] of Object.entries(snapshot)) {
|
|
69
|
+
for (const t of Array.isArray(tickets) ? tickets : []) {
|
|
70
|
+
if (!t || t.voiceId !== voiceId) continue;
|
|
71
|
+
if (t.projectRoot && t.projectRoot !== root) continue;
|
|
72
|
+
return { lane, position: Number.isFinite(t.position) ? t.position : null };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { lane: null, position: null };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function listHandler(deps) {
|
|
79
|
+
return async (_req, res, query) => {
|
|
80
|
+
const d = depsOf(deps);
|
|
81
|
+
const resolved = d.resolveCwd(query?.get('cwd') ?? '');
|
|
82
|
+
if (!resolved.ok) {
|
|
83
|
+
sendJson(res, resolved.status || 400, { ok: false, error: resolved.error });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const { voices, errors } = d.voiceLibrary.listVoices(resolved.cwd);
|
|
87
|
+
sendJson(res, 200, { ok: true, voices, errors });
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function previewHandler(deps) {
|
|
92
|
+
return async (req, res) => {
|
|
93
|
+
const d = depsOf(deps);
|
|
94
|
+
let raw;
|
|
95
|
+
try {
|
|
96
|
+
raw = await readBody(req, BODY_MAX);
|
|
97
|
+
} catch (e) {
|
|
98
|
+
sendJson(res, 400, { ok: false, error: `request body rejected: ${e?.message ?? 'unreadable'}` });
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
let body;
|
|
102
|
+
try {
|
|
103
|
+
body = raw ? JSON.parse(raw) : {};
|
|
104
|
+
} catch {
|
|
105
|
+
sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const invalid = validatePreviewBody(body);
|
|
109
|
+
if (invalid) {
|
|
110
|
+
sendJson(res, 400, { ok: false, error: invalid });
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const resolved = d.resolveCwd(body.cwd);
|
|
114
|
+
if (!resolved.ok) {
|
|
115
|
+
sendJson(res, resolved.status || 400, { ok: false, error: resolved.error });
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const root = resolved.cwd;
|
|
119
|
+
const voiceId = body.voiceId;
|
|
120
|
+
const text = body.text.trim();
|
|
121
|
+
const rv = d.voiceLibrary.resolveVoiceId(root, voiceId);
|
|
122
|
+
if (!rv || !rv.ok) {
|
|
123
|
+
sendJson(res, 400, { ok: false, error: (rv && rv.error) || `unknown voice '${voiceId}'` });
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const key = JSON.stringify([root, voiceId, text]);
|
|
128
|
+
let run = pending.get(key);
|
|
129
|
+
if (!run) {
|
|
130
|
+
const startedAt = d.now();
|
|
131
|
+
const promise = Promise.resolve()
|
|
132
|
+
.then(() => d.previewVoice({ projectRoot: root, voiceId, text }))
|
|
133
|
+
.catch((e) => ({ ok: false, error: `voice preview failed: ${e?.message ?? String(e)}` }))
|
|
134
|
+
.then((r) => ({ r, endedAt: d.now() }))
|
|
135
|
+
.finally(() => { if (pending.get(key) === run) pending.delete(key); });
|
|
136
|
+
run = { promise, startedAt };
|
|
137
|
+
pending.set(key, run);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
let timer = null;
|
|
141
|
+
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), d.waitMs); });
|
|
142
|
+
const outcome = await Promise.race([run.promise, timeout]);
|
|
143
|
+
clearTimeout(timer);
|
|
144
|
+
|
|
145
|
+
if (!outcome) {
|
|
146
|
+
sendJson(res, 200, { ok: true, status: 'queued', ...lanePositionOf(d, root, voiceId) });
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const { r, endedAt } = outcome;
|
|
150
|
+
if (!r || r.ok !== true) {
|
|
151
|
+
sendJson(res, 500, { ok: false, error: (r && r.error) || 'voice preview failed' });
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
sendJson(res, 200, {
|
|
155
|
+
ok: true,
|
|
156
|
+
status: 'ready',
|
|
157
|
+
cached: !!r.cached,
|
|
158
|
+
wavPath: r.wavPath,
|
|
159
|
+
wallMs: Math.max(0, endedAt - run.startedAt),
|
|
160
|
+
audioSeconds: clipSeconds(r.wavPath),
|
|
161
|
+
});
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function registerAdminRoute(adminHttp, deps = {}) {
|
|
166
|
+
adminHttp.registerRoute('GET', '/admin/voices', listHandler(deps));
|
|
167
|
+
adminHttp.registerRoute('POST', '/admin/voices/preview', previewHandler(deps));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Tests only: forget previews still tracked in-process. */
|
|
171
|
+
function _resetPending() {
|
|
172
|
+
pending.clear();
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
module.exports = { registerAdminRoute, validatePreviewBody, VOICE_ID_RE, TEXT_MAX, WAIT_MS, _resetPending };
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* voicePreview.cjs — the one preview path for a library voice (the Voices
|
|
5
|
+
* screen and the MCP preview tool both call previewVoice).
|
|
6
|
+
*
|
|
7
|
+
* A clip is cached at <voicesHome>/cache/<previewKey>.wav, where previewKey is
|
|
8
|
+
* the sha256 of voice id + trimmed text + canonical resolved voice JSON + the
|
|
9
|
+
* approval pin (voiceLibrary.pinOf) — editing a voice's params or pin files
|
|
10
|
+
* changes the key, so a stale clip is never served. A hit answers without
|
|
11
|
+
* spawning anything.
|
|
12
|
+
*
|
|
13
|
+
* A miss runs the kit speak CLI (demo-video-kit/character.cjs speak <spec>)
|
|
14
|
+
* as an ASYNC child (process.execPath + ELECTRON_RUN_AS_NODE=1, no shell), so
|
|
15
|
+
* the main process never blocks and the preview waits in the same voice lane
|
|
16
|
+
* as video runs. Exit 75 = still speaking: the same command is re-run until it
|
|
17
|
+
* finishes or timeoutMs passes. Concurrent calls for one key share one run.
|
|
18
|
+
* The cache keeps at most CACHE_MAX clips (oldest mtime removed).
|
|
19
|
+
* Plain Node: no Electron import.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const fs = require('node:fs');
|
|
23
|
+
const os = require('node:os');
|
|
24
|
+
const path = require('node:path');
|
|
25
|
+
const crypto = require('node:crypto');
|
|
26
|
+
const childProcess = require('node:child_process');
|
|
27
|
+
const voiceLibrary = require('../demo-video-kit/voiceLibrary.cjs');
|
|
28
|
+
const { cleanChildEnv } = require('../process/cleanEnv.cjs');
|
|
29
|
+
|
|
30
|
+
const CHARACTER_CJS = path.join(__dirname, '..', 'demo-video-kit', 'character.cjs');
|
|
31
|
+
const TEXT_MAX = 300;
|
|
32
|
+
const CACHE_MAX = 200;
|
|
33
|
+
const DEFAULT_TIMEOUT_MS = 20 * 60 * 1000;
|
|
34
|
+
const EXIT_PENDING = 75;
|
|
35
|
+
const RETRY_DELAY_MS = 200;
|
|
36
|
+
const OUTPUT_TAIL = 4000;
|
|
37
|
+
|
|
38
|
+
/** @type {Map<string, Promise<any>>} key -> in-flight preview */
|
|
39
|
+
const inFlight = new Map();
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* sha256 hex of voiceId, text, canonical resolved voice JSON, the approval pin
|
|
43
|
+
* and — for a project-scope voice only — the resolved projectRoot: two projects
|
|
44
|
+
* may define the same project voice id + JSON over different scripts, so their
|
|
45
|
+
* clips must not share a key; machine and built-in voices stay shared.
|
|
46
|
+
*/
|
|
47
|
+
function previewKey({ voiceId, text, voice, pin, scope, projectRoot }) {
|
|
48
|
+
const root = scope === 'project' && projectRoot ? path.resolve(String(projectRoot)) : undefined;
|
|
49
|
+
return crypto.createHash('sha256')
|
|
50
|
+
.update(voiceLibrary.canonical({ voiceId: String(voiceId), text: String(text), voice: voice ?? null, pin: String(pin ?? ''), projectRoot: root }))
|
|
51
|
+
.digest('hex');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const cacheDir = () => path.join(voiceLibrary.voicesHome(), 'cache');
|
|
55
|
+
|
|
56
|
+
/** Remove the oldest-mtime clips until at most CACHE_MAX remain; never throws. */
|
|
57
|
+
function pruneCache(dir, keep) {
|
|
58
|
+
let files;
|
|
59
|
+
try {
|
|
60
|
+
files = fs.readdirSync(dir).filter((f) => f.endsWith('.wav') && !f.endsWith('.tmp.wav')).map((f) => {
|
|
61
|
+
const p = path.join(dir, f);
|
|
62
|
+
try { return { p, f, m: fs.statSync(p).mtimeMs }; } catch { return null; }
|
|
63
|
+
}).filter(Boolean);
|
|
64
|
+
} catch {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (files.length <= CACHE_MAX) return;
|
|
68
|
+
files.sort((a, b) => a.m - b.m);
|
|
69
|
+
let excess = files.length - CACHE_MAX;
|
|
70
|
+
for (const x of files) {
|
|
71
|
+
if (excess <= 0) break;
|
|
72
|
+
if (x.p === keep) continue;
|
|
73
|
+
try { fs.rmSync(x.p, { force: true }); } catch { /* best effort */ }
|
|
74
|
+
excess -= 1;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** One async run of the speak CLI -> {code, signal, stdout, stderr, error?}. */
|
|
79
|
+
function runOnce(specPath, cwd, killAfterMs) {
|
|
80
|
+
return new Promise((resolve) => {
|
|
81
|
+
let stdout = '';
|
|
82
|
+
let stderr = '';
|
|
83
|
+
let settled = false;
|
|
84
|
+
let timer = null;
|
|
85
|
+
const done = (r) => {
|
|
86
|
+
if (settled) return;
|
|
87
|
+
settled = true;
|
|
88
|
+
if (timer) clearTimeout(timer);
|
|
89
|
+
resolve({ stdout, stderr, ...r });
|
|
90
|
+
};
|
|
91
|
+
let child;
|
|
92
|
+
try {
|
|
93
|
+
child = childProcess.spawn(process.execPath, [CHARACTER_CJS, 'speak', specPath], {
|
|
94
|
+
cwd,
|
|
95
|
+
env: cleanChildEnv({ ELECTRON_RUN_AS_NODE: '1' }),
|
|
96
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
97
|
+
shell: false,
|
|
98
|
+
windowsHide: true,
|
|
99
|
+
});
|
|
100
|
+
} catch (e) {
|
|
101
|
+
done({ code: null, signal: null, error: e.message });
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
child.stdout?.on('data', (d) => { stdout = (stdout + d).slice(-OUTPUT_TAIL); });
|
|
105
|
+
child.stderr?.on('data', (d) => { stderr = (stderr + d).slice(-OUTPUT_TAIL); });
|
|
106
|
+
child.on('error', (e) => done({ code: null, signal: null, error: e.message }));
|
|
107
|
+
child.on('close', (code, signal) => done({ code, signal }));
|
|
108
|
+
timer = setTimeout(() => {
|
|
109
|
+
try { child.kill('SIGTERM'); } catch { /* gone */ }
|
|
110
|
+
done({ code: null, signal: 'SIGTERM', timedOut: true });
|
|
111
|
+
}, Math.max(1, killAfterMs));
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The CLI's own error: its JSON result line's error, else stderr, else the exit. */
|
|
116
|
+
function cliError(r) {
|
|
117
|
+
const last = String(r.stdout || '').trim().split('\n').pop() || '';
|
|
118
|
+
try {
|
|
119
|
+
const j = JSON.parse(last);
|
|
120
|
+
if (j && typeof j.error === 'string' && j.error) return j.error;
|
|
121
|
+
} catch { /* not JSON */ }
|
|
122
|
+
const err = String(r.stderr || '').trim();
|
|
123
|
+
if (err) return err;
|
|
124
|
+
if (r.error) return r.error;
|
|
125
|
+
return `speak CLI failed (${r.signal ? `killed by ${r.signal}` : `exit ${r.code}`})`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function synthesize({ root, voiceId, text, key, timeoutMs }) {
|
|
129
|
+
const dir = cacheDir();
|
|
130
|
+
const wavPath = path.join(dir, `${key}.wav`);
|
|
131
|
+
const tmpOut = path.join(dir, `${key}.tmp.wav`);
|
|
132
|
+
let specDir = null;
|
|
133
|
+
try {
|
|
134
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
135
|
+
fs.rmSync(tmpOut, { force: true });
|
|
136
|
+
specDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-voice-preview-'));
|
|
137
|
+
const specPath = path.join(specDir, 'spec.json');
|
|
138
|
+
const spec = { projectRoot: root, voice: voiceId, kind: 'preview', label: `preview ${voiceId}`, lines: [{ text, out: tmpOut }] };
|
|
139
|
+
fs.writeFileSync(specPath, JSON.stringify(spec));
|
|
140
|
+
const deadline = Date.now() + timeoutMs;
|
|
141
|
+
for (;;) {
|
|
142
|
+
const left = deadline - Date.now();
|
|
143
|
+
if (left <= 0) return { ok: false, error: `voice preview for '${voiceId}' timed out after ${Math.round(timeoutMs / 1000)}s` };
|
|
144
|
+
const r = await runOnce(specPath, root, left);
|
|
145
|
+
if (r.timedOut) return { ok: false, error: `voice preview for '${voiceId}' timed out after ${Math.round(timeoutMs / 1000)}s` };
|
|
146
|
+
if (r.code === EXIT_PENDING) {
|
|
147
|
+
await new Promise((res) => setTimeout(res, Math.min(RETRY_DELAY_MS, Math.max(0, deadline - Date.now()))));
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (r.code !== 0) return { ok: false, error: cliError(r) };
|
|
151
|
+
if (!fs.existsSync(tmpOut)) return { ok: false, error: `speak CLI exited 0 but wrote no clip to ${tmpOut}` };
|
|
152
|
+
fs.renameSync(tmpOut, wavPath);
|
|
153
|
+
pruneCache(dir, wavPath);
|
|
154
|
+
return { ok: true, cached: false, wavPath, bytes: fs.readFileSync(wavPath) };
|
|
155
|
+
}
|
|
156
|
+
} catch (e) {
|
|
157
|
+
return { ok: false, error: `voice preview failed: ${e && e.message ? e.message : String(e)}` };
|
|
158
|
+
} finally {
|
|
159
|
+
try { fs.rmSync(tmpOut, { force: true }); } catch { /* best effort */ }
|
|
160
|
+
if (specDir) {
|
|
161
|
+
try { require('../demo-video-kit/resumableRun.cjs').stopRun(path.join(specDir, 'spec.json.run')); } catch { /* none */ }
|
|
162
|
+
try { fs.rmSync(specDir, { recursive: true, force: true }); } catch { /* best effort */ }
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Preview one library voice speaking `text`.
|
|
169
|
+
* -> {ok:true, cached, wavPath, bytes: Buffer} | {ok:false, error}
|
|
170
|
+
* @param {{ projectRoot?: string, voiceId: string, text: string, timeoutMs?: number }} args
|
|
171
|
+
*/
|
|
172
|
+
async function previewVoice({ projectRoot, voiceId, text, timeoutMs } = /** @type {any} */ ({})) {
|
|
173
|
+
if (!projectRoot || typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) {
|
|
174
|
+
return { ok: false, error: 'projectRoot must be an absolute path' };
|
|
175
|
+
}
|
|
176
|
+
const root = path.resolve(projectRoot);
|
|
177
|
+
const t = typeof text === 'string' ? text.trim() : '';
|
|
178
|
+
if (t.length < 1 || t.length > TEXT_MAX) return { ok: false, error: `text must be 1-${TEXT_MAX} chars after trimming` };
|
|
179
|
+
const rv = voiceLibrary.resolveVoiceId(root, voiceId);
|
|
180
|
+
if (!rv.ok) return { ok: false, error: rv.error };
|
|
181
|
+
const key = previewKey({ voiceId, text: t, voice: rv.voice, pin: voiceLibrary.pinOf(rv.entry, root), scope: rv.scope, projectRoot: root });
|
|
182
|
+
const wavPath = path.join(cacheDir(), `${key}.wav`);
|
|
183
|
+
try {
|
|
184
|
+
const bytes = fs.readFileSync(wavPath);
|
|
185
|
+
try { const now = new Date(); fs.utimesSync(wavPath, now, now); } catch { /* best effort */ }
|
|
186
|
+
return { ok: true, cached: true, wavPath, bytes };
|
|
187
|
+
} catch { /* miss */ }
|
|
188
|
+
const running = inFlight.get(key);
|
|
189
|
+
if (running) return running;
|
|
190
|
+
const ms = Number.isFinite(timeoutMs) && /** @type {number} */ (timeoutMs) > 0 ? /** @type {number} */ (timeoutMs) : DEFAULT_TIMEOUT_MS;
|
|
191
|
+
const p = synthesize({ root, voiceId, text: t, key, timeoutMs: ms }).finally(() => inFlight.delete(key));
|
|
192
|
+
inFlight.set(key, p);
|
|
193
|
+
return p;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
module.exports = { previewVoice, previewKey, CACHE_MAX, TEXT_MAX, DEFAULT_TIMEOUT_MS };
|