feat: add single-call action protocol and Android stage interfaces

This commit is contained in:
zenord
2026-10-13 00:41:55 +08:00
parent dfd1372ba2
commit e91354c9e8
41 changed files with 1438 additions and 70 deletions
+9 -3
View File
@@ -17,6 +17,11 @@ def avatarEngineering = providers.gradleProperty('avatarEngineering').orNull ==
def avatarNatural = providers.gradleProperty('avatarNatural').orNull == 'true'
def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true'
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true'
def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger()
if (avatarActionCandidate && (!avatarMouthCandidate || actionVersionCode < 16)) {
throw new GradleException('Action stage requires the existing mouth runtime and a fresh code >=16')
}
if (avatarMouthCandidate && (!avatarNatural || avatarUiCandidate)) {
throw new GradleException('Mouth candidate requires natural runtime and a distinct version from UI-only')
}
@@ -70,8 +75,8 @@ android {
minSdk 26
targetSdk 34
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12))
versionName = (avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
versionName = avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1')
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
@@ -79,7 +84,8 @@ android {
buildFeatures { compose true; buildConfig true }
buildTypes {
debug {
if (avatarMouthCandidate) versionNameSuffix '-mouth-dev'
if (avatarActionCandidate) versionNameSuffix '-stage-dev'
else if (avatarMouthCandidate) versionNameSuffix '-mouth-dev'
else if (avatarUiCandidate) versionNameSuffix '-ui-dev'
else if (avatarNatural) versionNameSuffix '-natural-dev'
else if (avatarEngineering) versionNameSuffix '-dev'
@@ -193,6 +193,7 @@ class MainActivity : ComponentActivity() {
expressionState, shareFace, { enabled -> shareFace = enabled; session.setFaceSharing(enabled) },
connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, session::interrupt,
micGranted,cameraGranted,permissionPending,::authorizeCamera,
onCancelAction = session::cancelAction,
)
}
}
@@ -22,6 +22,7 @@ class AudioCapture {
}
private val lock = Any()
private var current: Run? = null
@Volatile private var stopConfirmed = true
fun aecAvailability(): AecAvailability = try {
if (AcousticEchoCanceler.isAvailable()) AecAvailability.AVAILABLE else AecAvailability.UNAVAILABLE
@@ -36,8 +37,9 @@ class AudioCapture {
) {
stop()
val run = Run()
stopConfirmed = false
synchronized(lock) { current = run }
worker.execute { if (run.active) record(run, onFrame, onError, onDiagnostic) }
worker.execute { if (run.active) record(run, onFrame, onError, onDiagnostic) else stopConfirmed = true }
}
fun stop() {
@@ -55,6 +57,14 @@ class AudioCapture {
worker.shutdown()
}
/** Queue after worker cleanup; stopped intent alone is not a recording-state proof. */
fun stopAndConfirm(onStopped: (Boolean) -> Unit) {
stop()
try {
worker.execute { onStopped(synchronized(lock) { current == null && stopConfirmed }) }
} catch (_: java.util.concurrent.RejectedExecutionException) { onStopped(false) }
}
private fun record(
run: Run, onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit,
onDiagnostic: (String) -> Unit,
@@ -129,8 +139,10 @@ class AudioCapture {
aec?.release()
recorder?.let {
try { it.stop() } catch (_: IllegalStateException) { }
stopConfirmed = it.recordingState != AudioRecord.RECORDSTATE_RECORDING
it.release()
}
if (recorder == null) stopConfirmed = true
}
}
@@ -1,5 +1,6 @@
package com.gorios.lanvoice.audio
import com.gorios.lanvoice.avatar.*
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
@@ -30,6 +31,7 @@ data class VoiceUiState(
val previousReplyEmotion: ReplyEmotion? = null,
val playbackActivity: PlaybackActivity? = null,
val microphoneMuted: Boolean = false,
val actionActive: Boolean = false,
) {
val roleLabel: String get() = when {
phase == VoicePhase.ANSWERING && replyEmotion.turnId != null -> replyEmotion.label
@@ -44,6 +46,9 @@ class VoiceSession(
private val onConnectionLog: (String) -> Unit = {},
private val onPreparePlayback: () -> String? = { null },
private val onVoiceStopped: () -> Unit = {},
private val reviewedActionPack: ReviewedActionPack? = null,
private val actionPlayer: ActionPlayer = UnavailableActionPlayer,
private val onPrepareExpression: (ReplyEmotion?) -> Unit = {},
private val emotionObserver: ReplyEmotionObserver = ReplyEmotionObserver {},
) {
private val main = Handler(Looper.getMainLooper())
@@ -51,6 +56,7 @@ class VoiceSession(
private var foreground = false
private var released = false
private var backgroundTimeout: Runnable? = null
private var actionTimeout: Runnable? = null
private var captureEpoch = 0L
private var capturing = false
private var currentTurn = 0L
@@ -73,10 +79,21 @@ class VoiceSession(
}
}
private val capture = AudioCapture()
private val actions = ActionController(reviewedActionPack, actionPlayer, SystemClock::elapsedRealtime,
stopCapture = { confirmed ->
captureEpoch++; capturing = false
capture.stopAndConfirm { stopped -> main.post { confirmed(stopped) } }
}, status = { status -> if (state.connection == ConnectionStatus.CONNECTED) dialogue.actionStatus(status) },
changed = { active ->
if (!active) { actionTimeout?.let { main.removeCallbacks(it) }; actionTimeout = null }
if (active) { playback.interrupt(); resetReply("action") }
update(state.copy(actionActive = active, playbackActivity = null))
if (!active && isActive() && state.phase == VoicePhase.LISTENING) startCapture()
})
private val playback: AudioPlayback = AudioPlayback(
onDrained = { turn, epoch ->
main.post {
if (isActive() && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
if (isActive() && !actions.active && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
diagnostic("playback drained turn=$turn")
if (dialogue.playbackDrained(turn)) {
resetReply("drained")
@@ -99,7 +116,7 @@ class VoiceSession(
},
onActivity = { activity ->
main.post {
if (isActive() && playbackIsCurrent(activity.turnId, activity.generation) &&
if (isActive() && !actions.active && playbackIsCurrent(activity.turnId, activity.generation) &&
currentTurn == activity.turnId && blockedTurn != activity.turnId && emotionEndedTurn != activity.turnId) {
update(state.copy(playbackActivity = activity))
}
@@ -110,6 +127,7 @@ class VoiceSession(
host, port,
onStatus = {},
onStatusReason = ::onConnection,
actionPackSha = { actions.capability?.manifestSha },
onEvent = ::onEvent,
onFrame = ::onFrame,
onProtocolError = { Log.w(TAG, it) },
@@ -179,6 +197,7 @@ class VoiceSession(
fun stopVoice(sendControls: Boolean = true) {
checkMainThread()
actions.cancel()
resetReply("stop")
val wasActive = state.voiceActive
stopCapture()
@@ -222,7 +241,7 @@ class VoiceSession(
fun interrupt() {
checkMainThread()
if (!isActive()) return
if (!isActive() || actions.active) return
resetReply("interrupt")
blockedTurn = currentTurn
playback.interrupt() // Silence locally before waiting for the server's abort event.
@@ -232,6 +251,8 @@ class VoiceSession(
}
}
fun cancelAction() { checkMainThread(); actions.cancel() }
fun permissionDenied() {
checkMainThread()
update(state.copy(guidance = "麦克风权限未授予,请允许录音;若不再弹出申请,可在系统应用权限中开启。"))
@@ -302,6 +323,8 @@ class VoiceSession(
private fun onConnection(connection: ConnectionStatus, reason: String) {
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
if (connection != ConnectionStatus.CONNECTED) {
actions.cancel()
onPrepareExpression(null)
resetReply("disconnect")
faceSupported = false
faceSent = false
@@ -328,7 +351,7 @@ class VoiceSession(
private fun startCapture() {
val active = isActive()
diagnostic("startCapture active=$active capturing=$capturing")
if (!active || capturing || state.microphoneMuted) return
if (!active || capturing || state.microphoneMuted || actions.active) return
capturing = true
val epoch = ++captureEpoch
val captureTurn = currentTurn
@@ -369,6 +392,29 @@ class VoiceSession(
private fun onEvent(event: ServerEvent) {
val turn = (event.payload.opt("turn_id") as? Number)?.toLong()
diagnostic("onEvent kind=${event.kind.name} turn_id=$turn")
if (event.kind == EventKind.EXPRESSION_PREPARE) {
if (isActive() && hasTurn && turn == currentTurn && blockedTurn != turn && !actions.active) {
if (event.type.endsWith(".cancel")) onPrepareExpression(null)
else onPrepareExpression(ReplyEmotion.fromWire(turn,event.payload.opt("seq"),event.payload.opt("emotion"),
event.payload.opt("intensity"),"model"))
}
return
}
if (event.kind == EventKind.ACTION) {
if (!isActive() || !hasTurn || turn != currentTurn) return
if (event.type == "action.cancel") actions.cancel()
else if (event.type == "action.plan") {
val id = event.payload.optString("action_id")
val ttl = (event.payload.opt("ttl_ms") as? Number)?.toLong() ?: 0L
if (!actions.offer(ActionPlan(id,currentTurn,event.payload.optString("pack_sha256"),ttl)))
dialogue.actionStatus(ActionStatus(id,currentTurn,"failed"))
else if(actions.active) {
actionTimeout?.let { main.removeCallbacks(it) }
actionTimeout = Runnable { actionTimeout = null; actions.tick() }.also { main.postDelayed(it,ttl) }
}
}
return
}
if (event.kind == EventKind.REPLY_EMOTION) { receiveReply(event, turn); return }
if (released || state.connection != ConnectionStatus.CONNECTED) {
diagnostic("event ignored: connection=${state.connection.name} released=$released")
@@ -433,7 +479,7 @@ class VoiceSession(
// The server's following LISTEN start and TTS belong to that new turn.
val reason = event.payload.optString("reason")
val listenReset = reason == "listen_start"
val announcesNewTurn = reason in setOf("listen_start", "new_turn", "voice_barge_in", "client_abort")
val announcesNewTurn = reason in setOf("listen_start", "new_turn", "voice_barge_in", "client_abort", "action_followup", "action_cancelled", "action_timeout")
blockedTurn = if (announcesNewTurn) null else oldTurn
diagnostic("ABORT blockedTurn=$blockedTurn active=${isActive()} listenReset=$listenReset oldTurn=$oldTurn currentTurn=$currentTurn")
playback.interrupt()
@@ -442,6 +488,7 @@ class VoiceSession(
startCapture()
}
}
EventKind.SPEECH -> if (isActive()) { preparedPlaybackTurn = null; emotionEndedTurn = null }
EventKind.ERROR -> if (state.voiceActive) {
stopVoice()
update(state.copy(guidance = "服务端处理失败,请重新开始语音对话"))
@@ -452,7 +499,7 @@ class VoiceSession(
private fun onFrame(frame: DownlinkFrame) {
// Avoid uploading the same acceptTurn decision for every 20 ms PCM frame.
if (!isActive() || !acceptTurn(frame.turnId, logDecision = !hasTurn || frame.turnId != currentTurn) ||
if (!isActive() || actions.active || !acceptTurn(frame.turnId, logDecision = !hasTurn || frame.turnId != currentTurn) ||
blockedTurn == frame.turnId) return
if (preparedPlaybackTurn != frame.turnId) {
val failure = onPreparePlayback()
@@ -473,6 +520,8 @@ class VoiceSession(
}
// IDs identify turns; do not assume the server allocates them in numeric order.
if (!hasTurn || id != currentTurn) {
actions.cancel()
onPrepareExpression(null)
resetReply("new_turn")
val resumeCapture = capturing
if (resumeCapture) stopCapture() // Invalidate already queued PCM before resetting seq.
@@ -499,11 +548,13 @@ class VoiceSession(
turn in retiredTurns -> "old_turn"
turn != currentTurn -> "unannounced_turn"
!isActive() -> "inactive"
actions.active -> "action"
blockedTurn == currentTurn -> "blocked_turn"
emotionEndedTurn == currentTurn -> "drained"
else -> null
}
if (reason != null) { diagnostic("role ignore reason=$reason turn=$turn"); return }
onPrepareExpression(null)
val expression = ReplyEmotion.fromWire(event.payload.opt("turn_id"), event.payload.opt("seq"),
event.payload.opt("emotion"), event.payload.opt("intensity"), event.payload.opt("source"),
event.payload.opt("reason"), event.payload.opt("parse_branch"), event.payload.opt("finish_reason"))
@@ -0,0 +1,81 @@
package com.gorios.lanvoice.avatar
data class ActionAsset(val id: String, val durationMs: Long)
data class ReviewedActionPack(val manifestSha: String, val assets: List<ActionAsset>)
data class ActionPlan(val id: String, val turn: Long, val packSha: String, val ttlMs: Long)
data class ActionStatus(val id: String, val turn: Long, val status: String, val asset: String? = null,
val micStopped: Boolean = false, val videoEnded: Boolean = false,
val audioStopped: Boolean = false, val idleRestored: Boolean = false)
data class ActionEnd(val videoEnded: Boolean, val audioStopped: Boolean, val idleRestored: Boolean)
/** An implementation must complete only AFTER decoder/music stop AND reviewed return A.
* stop's callback is a release fence, never an arbitrary fixed tail timer. */
interface ActionPlayer {
fun play(asset: ActionAsset, finished: (ActionEnd) -> Unit, failed: () -> Unit)
fun stop(released: () -> Unit)
}
/** Main-thread state machine. No pack is installed until an external exact-SHA review.
* No microphone data is stored here, and no model URL can reach the player. */
class ActionController(
private val pack: ReviewedActionPack?, private val player: ActionPlayer,
private val clock: () -> Long, private val stopCapture: ((Boolean) -> Unit) -> Unit,
private val status: (ActionStatus) -> Unit, private val changed: (Boolean) -> Unit = {},
private val choose: (Int) -> Int = { kotlin.random.Random.nextInt(it) },
) {
private var generation = 0L
private var plan: ActionPlan? = null
private var previous: String? = null
private var stopping = false
val active get() = plan != null || stopping
private var deadline = 0L
private var started = 0L
val capability: ReviewedActionPack? get() = pack?.takeIf {
it.manifestSha.matches(Regex("[0-9a-f]{64}")) &&
it.assets.map { a -> a.id }.toSet() == setOf("asset_01", "asset_02") &&
it.assets.size == 2 && it.assets.all { a -> a.durationMs in 1_000..90_000 }
}
fun offer(next: ActionPlan): Boolean {
val valid = capability
if (active || valid == null || next.packSha != valid.manifestSha || next.id.length !in 16..64 ||
next.turn !in 0..0xffff_ffffL || next.ttlMs !in 1..120_000) return false
val candidates = valid.assets.filter { it.id != previous }
val asset = candidates[choose(candidates.size)]
val fence = ++generation
plan = next; deadline = clock()+next.ttlMs; changed(true)
stopCapture { confirmed ->
if (fence != generation || plan != next) return@stopCapture
if (!confirmed || clock() >= deadline) { cancel("failed"); return@stopCapture }
started = clock(); previous = asset.id
status(ActionStatus(next.id,next.turn,"started",asset.id,micStopped=true))
player.play(asset, { end ->
if (fence == generation && plan == next) {
if (clock() >= deadline || clock()-started < asset.durationMs ||
!end.videoEnded || !end.audioStopped || !end.idleRestored) cancel("failed")
else {
plan = null; generation++
status(ActionStatus(next.id,next.turn,"completed",asset.id,true,true,true,true))
changed(false)
}
}
}, { if (fence == generation && plan == next) cancel("failed") })
}
return true
}
fun tick() { if (plan != null && clock() >= deadline) cancel("failed") }
fun cancel(reason: String = "cancelled") {
val old = plan ?: return
generation++; plan = null; stopping = true
player.stop {
stopping = false
status(ActionStatus(old.id,old.turn,if (reason == "failed") "failed" else "cancelled"))
changed(false)
}
}
}
/** Production default while no independently approved dance pack exists. */
object UnavailableActionPlayer : ActionPlayer {
override fun play(asset: ActionAsset, finished: (ActionEnd) -> Unit, failed: () -> Unit) = failed()
override fun stop(released: () -> Unit) = released()
}
@@ -77,8 +77,9 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
expression: ExpressionUiState,shareFace: Boolean,onShare: (Boolean)->Unit,
logs: List<String>,onReport: ()->Unit,reportSending: Boolean,reportResult: String?,onInterrupt: ()->Unit,
micGranted: Boolean,cameraGranted: Boolean,permissionPending: EntryPermission?,onAuthorizeCamera: ()->Unit,
onCancelAction: ()->Unit,
) {
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity)
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity.takeUnless { state.actionActive })
val latestAvatar by rememberUpdatedState(avatar)
var video by remember(pack) { mutableStateOf(VideoPresentation()) }
val latestVideo by rememberUpdatedState(video)
@@ -105,13 +106,14 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
}
}
Text(status,style=MaterialTheme.typography.titleMedium)
Text("麦克风:${if(state.voiceActive && !state.microphoneMuted && state.phase==VoicePhase.LISTENING) "正在收音" else "未收音"} · 相机:${when(expression.status) { ExpressionStatus.ACTIVE -> "开启";ExpressionStatus.STARTING -> "启动中";ExpressionStatus.UNAVAILABLE -> "不可用";else -> "关闭" }}",fontSize=13.sp)
Text("麦克风:${if(state.voiceActive && !state.microphoneMuted && !state.actionActive && state.phase==VoicePhase.LISTENING) "正在收音" else "未收音"} · 相机:${when(expression.status) { ExpressionStatus.ACTIVE -> "开启";ExpressionStatus.STARTING -> "启动中";ExpressionStatus.UNAVAILABLE -> "不可用";else -> "关闭" }}",fontSize=13.sp)
if(state.actionActive) Button(onClick=onCancelAction) { Text("结束表演") }
TextButton(onClick=onRetry) { Text("重试连接") }
permissionMessage?.let { Text(it,fontSize=13.sp) }
PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera)
state.guidance?.let { Text(it,fontSize=13.sp) }
Row(Modifier.fillMaxWidth(),horizontalArrangement=Arrangement.spacedBy(12.dp)) {
Button(onClick=onMute,enabled=state.voiceActive,modifier=Modifier.weight(1f).heightIn(min=48.dp)) {
Button(onClick=onMute,enabled=state.voiceActive && !state.actionActive,modifier=Modifier.weight(1f).heightIn(min=48.dp)) {
Text(if(state.microphoneMuted) "恢复收音" else "暂停收音")
}
OutlinedButton(onClick=onCamera,
@@ -128,7 +130,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
AvatarDiagnostics(pack,video)
Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp)
Row {
TextButton(onClick=onInterrupt,enabled=state.voiceActive) { Text("打断回答") }
TextButton(onClick=onInterrupt,enabled=state.voiceActive && !state.actionActive) { Text("打断回答") }
TextButton(onClick=onReport,enabled=!reportSending) { Text(if(reportSending) "发送中…" else "发送诊断报告") }
}
reportResult?.let { Text(it,fontSize=12.sp) }
@@ -23,7 +23,8 @@ object ContinuousAvatarManifest {
fun smallInt(v: Any?): Int { val n=integer(v);require(n in 0..1_000_000);return n.toInt() }
fun finite(v: Any?): Float { val f=(v as Number).toFloat(); require(f.isFinite()); return f }
fun hash(v: Any?)=(v as String).also { require(it.matches(Regex("[0-9a-f]{64}"))) }
val apertureMode=root["packId"]=="a01-neutral-graph-v1-runtime-04"
val apertureMode=root["packId"]=="a01-neutral-graph-v1-runtime-04" ||
(root["packId"] as? String)?.matches(Regex("a01-expression-action-v1-[a-z0-9_-]+-runtime-04"))==true
require(integer(root["schemaVersion"])==1L && root["identityId"]=="a01" &&
(apertureMode || root["packId"]=="a01-neutral-graph-v1-runtime-03"))
require(root["publishApproval"]==false && root["runtimeReady"]==true)
@@ -0,0 +1,85 @@
package com.gorios.lanvoice.avatar
import com.gorios.lanvoice.dialogue.RoleEmotion
data class EmotionActionIndex(val fallbackId: String, val packages: Map<String,ContinuousAvatarPack>,
val visuals: List<TalkPackage>, val actionPack: ReviewedActionPack?)
/** Exact external manifest pin admits the whole graph. Self-approval fields have no effect.
* loadRuntime must hash-check exact bytes and all body/patch files before returning a pack.
* An admitted index is data; playback still needs reviewed bridge execution by its driver. */
object EmotionActionManifest {
@Suppress("UNCHECKED_CAST")
fun read(root: Map<String,Any?>, actualSha: String, piPinnedSha: String,
loadRuntime: (String,String)->ContinuousAvatarPack?): EmotionActionIndex? = try {
require(piPinnedSha.matches(Regex("[0-9a-f]{64}")) && actualSha==piPinnedSha)
require(root["schemaVersion"]==2L || root["schemaVersion"]==2)
require(root["identityId"]=="a01" && root["packId"]=="a01-expression-action-v1")
fun obj(value: Any?)=value as Map<String,Any?>
fun path(value: Any?)=(value as String).also {
require(it.matches(Regex("[A-Za-z0-9_./-]+")) && !it.startsWith('/') && it.split('/').none { p -> p in setOf("..", ".", "") })
}
fun hash(value: Any?)=(value as String).also { require(it.matches(Regex("[0-9a-f]{64}"))) }
fun integer(value: Any?): Long { val n=value as Number;require(n.toDouble()==n.toLong().toDouble());return n.toLong() }
val fallback=root["fallbackPackageId"] as String
val rows=root["conversationPackages"] as List<Map<String,Any?>>
require(rows.isNotEmpty() && rows.size<=12 && rows.map { it["id"] }.distinct().size==rows.size)
val packages=linkedMapOf<String,ContinuousAvatarPack>()
val visuals=rows.map { row ->
val id=row["id"] as String;require(id.matches(Regex("[a-z0-9_-]{1,48}")))
val emotion=RoleEmotion.entries.single { it.wire==row["emotion"] }
require(emotion!=RoleEmotion.ANGRY && integer(row["visualIntensity"])==if(emotion==RoleEmotion.NEUTRAL) 0L else 1L)
val reference=obj(row["runtimeManifest"])
val runtime=checkNotNull(loadRuntime(path(reference["path"]),hash(reference["sha256"])))
require(runtime.apertureMode && runtime.body.sha256==hash(row["mouthBodySha256"]))
require(runtime.patches.size==runtime.body.frameCount && runtime.patches.all { it.levels.size==5 })
packages[id]=runtime
val pts=runtime.patches.map { it.ptsUs }
TalkPackage(id,emotion,runtime.body.sha256,hash(row["mouthBodySha256"]),pts,pts,false)
}
require(visuals.single { it.id==fallback }.emotion==RoleEmotion.NEUTRAL)
val edges=root["edges"] as List<Map<String,Any?>>
require(edges.size<=100 && edges.map { it["id"] }.distinct().size==edges.size)
edges.forEach { edge ->
require(edge["from"] in packages && edge["to"] in packages)
val from=checkNotNull(packages[edge["from"]]);val to=checkNotNull(packages[edge["to"]])
require(integer(edge["fromFrame"]) in 0 until from.body.frameCount.toLong())
require(integer(edge["toFrame"]) in 0 until to.body.frameCount.toLong())
require(edge["fromAnchor"]=="A" && edge["toAnchor"]=="A")
val clip=obj(edge["clip"]);path(clip["path"]);hash(clip["sha256"])
require(clip["hasAudio"]==false && integer(clip["frameCount"])>0 && integer(clip["durationUs"])>0)
val pts=(clip["ptsUs"] as List<*>).map(::integer)
require(pts.size==integer(clip["frameCount"]).toInt() && pts.first()==0L && pts.zipWithNext().all { (a,b)->a<b })
}
val admitted=visuals.map { visual ->
val row=rows.single { it["id"]==visual.id }
require(row["entryAnchor"]=="A" && row["exitAnchor"]=="A")
val loop=row["loopEdge"] as String
require(edges.any { it["id"]==loop && it["from"]==visual.id && it["to"]==visual.id })
val exits=(row["legalExitFrames"] as List<*>).map(::integer)
require(exits.isNotEmpty() && exits.all { it in 0 until packages.getValue(visual.id).body.frameCount.toLong() })
if(visual.id!=fallback) {
require(edges.any { it["from"]==fallback && it["to"]==visual.id })
require(edges.any { it["from"]==visual.id && it["to"]==fallback })
}
visual.copy(approvedEdges=true)
}
val actions=root["actions"] as List<Map<String,Any?>>
val actionPack=if(actions.isEmpty()) null else {
require(actions.size==2 && actions.map { it["id"] }.toSet()==setOf("asset_01","asset_02"))
val assets=actions.map { action ->
require(action["kind"]=="dance" && action["mouthAllowed"]==false && action["disallowTALK"]==true)
require(action["entryAnchor"]=="A" && action["returnAnchor"]=="A")
val clip=obj(action["clip"]);path(clip["path"]);hash(clip["sha256"])
val duration=integer(clip["durationUs"])
require(clip["hasAudio"]==true && integer(action["audioEndUs"]) in 1..duration)
val pts=(clip["ptsUs"] as List<*>).map(::integer)
require(pts.isNotEmpty() && pts.size==integer(clip["frameCount"]).toInt() && pts.zipWithNext().all { (a,b)->a<b })
require(duration in 1_000_000..90_000_000)
ActionAsset(action["id"] as String,(duration+999)/1000)
}
ReviewedActionPack(actualSha,assets)
}
EmotionActionIndex(fallback,packages,admitted,actionPack)
} catch(_: Exception) { null }
}
@@ -0,0 +1,26 @@
package com.gorios.lanvoice.avatar
import com.gorios.lanvoice.dialogue.RoleEmotion
/** Selected model intent remains separate from the actually admitted visual package. */
data class RoleVisualSelection(val selectedEmotion: RoleEmotion, val selectedIntensity: Int,
val visualEmotion: RoleEmotion, val visualIntensity: Int, val packageId: String,
val degraded: Boolean, val reason: String)
data class TalkPackage(val id: String, val emotion: RoleEmotion, val bodySha: String,
val mouthBodySha: String?, val framePtsUs: List<Long>, val mouthPtsUs: List<Long>,
val approvedEdges: Boolean)
object RoleVisualSelector {
fun select(emotion: RoleEmotion, intensity: Int, packages: List<TalkPackage>, fallbackId: String): RoleVisualSelection {
fun valid(p: TalkPackage) = p.bodySha.matches(Regex("[0-9a-f]{64}")) &&
p.mouthBodySha == p.bodySha && p.framePtsUs.size == 97 &&
p.framePtsUs == p.mouthPtsUs && p.framePtsUs.zipWithNext().all { (a,b) -> a < b } && p.approvedEdges
val usable = packages.filter(::valid)
val same = usable.firstOrNull { it.emotion == emotion && emotion != RoleEmotion.ANGRY }
val chosen = same ?: usable.firstOrNull { it.id == fallbackId }
?: error("No reviewed complete fallback TALK package")
val visualIntensity = if (chosen.emotion == RoleEmotion.NEUTRAL) 0 else 1
val reason = when { same == null -> "whole_package_fallback"; intensity > visualIntensity -> "slight_only"; else -> "none" }
return RoleVisualSelection(emotion,intensity,chosen.emotion,visualIntensity,chosen.id,reason != "none",reason)
}
}
@@ -42,6 +42,7 @@ class DialogueClient(
private val onFrame: (DownlinkFrame) -> Unit = {},
private val onProtocolError: (String) -> Unit = {},
private val onConnectionLog: (String) -> Unit = {},
private val actionPackSha: () -> String? = { null },
private val onStatusReason: (ConnectionStatus, String) -> Unit = { _, _ -> },
) {
private val main = Handler(Looper.getMainLooper())
@@ -216,6 +217,8 @@ class DialogueClient(
fun playbackDrained(turnId: Long): Boolean = send(DialogueProtocol.playbackDrained(turnId))
fun actionStatus(value: com.gorios.lanvoice.avatar.ActionStatus): Boolean = send(DialogueProtocol.actionStatus(value))
/** Optional context is best effort and never tears down the audio connection. */
fun sendFaceCue(turnId: Long, observation: FaceCueObservation, ageMs: Long): Boolean {
checkMainThread()
@@ -287,7 +290,7 @@ class DialogueClient(
if (authReceived) return@dispatch
authReceived = true
connectionLog("auth ok", "auth")
if (webSocket.send(DialogueProtocol.hello())) {
if (webSocket.send(DialogueProtocol.hello(actionPackSha()))) {
helloSent = true
connectionLog("hello sent", "auth")
} else {
@@ -10,7 +10,7 @@ import com.gorios.lanvoice.expression.FaceCueObservation
data class ServerEvent(val type: String, val kind: EventKind, val payload: JSONObject)
enum class EventKind {
AUTH, HELLO, HISTORY, LISTEN, VAD, STT, LLM, TTS, REPLY_EMOTION, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN
AUTH, HELLO, HISTORY, LISTEN, VAD, STT, LLM, TTS, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, SPEECH, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN
}
/** Header integers are unsigned, network byte order; PCM samples are signed little endian. */
@@ -26,13 +26,17 @@ object DialogueProtocol {
const val UPLINK_PCM_BYTES = 640
const val DOWNLINK_PCM_BYTES = 1_920
fun hello(): String = JSONObject()
fun hello(actionPackSha: String? = null): String = JSONObject()
.put("type", "hello")
.put("codec", "pcm16")
.put("sample_rate", 16_000)
.put("frame_duration", 20)
.put("persona", "default")
.put("voice_mode", "continuous_voice")
.apply { if (actionPackSha?.matches(Regex("[0-9a-f]{64}")) == true) {
put("action_protocol", 1); put("action_pack_sha256", actionPackSha)
put("action_kinds", org.json.JSONArray().put("dance"))
} }
.toString()
fun listen(start: Boolean): String = JSONObject()
@@ -51,6 +55,12 @@ object DialogueProtocol {
fun playbackDrained(turnId: Long): String = JSONObject()
.put("type", "playback.drained").put("turn_id", turnId).toString()
fun actionStatus(value: com.gorios.lanvoice.avatar.ActionStatus): String = JSONObject()
.put("type", "action.status").put("turn_id", value.turn).put("action_id", value.id)
.put("status", value.status).put("asset_id", value.asset ?: "")
.put("mic_stopped", value.micStopped).put("video_ended", value.videoEnded)
.put("audio_stopped", value.audioStopped).put("idle_restored", value.idleRestored).toString()
fun faceCue(turnId: Long, observation: FaceCueObservation, ageMs: Long): String {
require(turnId in 0..0xffff_ffffL)
val valid = observation.cue != FaceCue.UNKNOWN && ageMs in 0..3_000 &&
@@ -77,7 +87,7 @@ object DialogueProtocol {
val payload = JSONObject(text)
val type = payload.opt("type") as? String
require(!type.isNullOrBlank()) { "Event is missing a string type" }
val kind = if (type == "reply.emotion") EventKind.REPLY_EMOTION else when (type.substringBefore('.')) {
val kind = if (type.startsWith("reply.emotion.prepare")) EventKind.EXPRESSION_PREPARE else if (type == "reply.emotion") EventKind.REPLY_EMOTION else when (type.substringBefore('.')) {
"auth" -> EventKind.AUTH
"hello" -> EventKind.HELLO
"history" -> EventKind.HISTORY
@@ -86,6 +96,8 @@ object DialogueProtocol {
"stt" -> EventKind.STT
"llm" -> EventKind.LLM
"tts" -> EventKind.TTS
"action" -> EventKind.ACTION
"speech" -> EventKind.SPEECH
"error" -> EventKind.ERROR
"abort" -> EventKind.ABORT
"metrics" -> EventKind.METRICS
+68
View File
@@ -0,0 +1,68 @@
# 0.7.0 action/emotion stage candidate
Baseline: `e3ee004d29ac472997a813fbdb641ba4983fa5ce`, clean and matching remote main.
Clock/interface milestone: `dfd1372`. This is an implemented protocol stage, not a
completed visual-action release. Code owner made zero paid calls; asset-owner
image/video/music ledger remains separate.
Implemented: request-local explicit-zone server clock, single system, no persona/
history mutation, monotonic deadlines; Qwen schema/Doubao prompt isolation. Ordered
emotion/intensity prefix parser emits preload-only prepare, final strict validation
cancels invalid preparations. Streaming duplicates/extra fields/escaped strings/
types/truncation/old turns are tested. Complete reply goes to one TTS generator.
Single-call dance/nullable after_action schema and ephemeral owner/connection/turn/
TTL ticket implemented. Only reviewed pack capability enables dance. Pre-reply
drain releases action.plan; action drops uplink without VAD/ASR buffering. Completed
requires started/mic stopped, video ended, audio stopped, restored idle and reviewed
duration. Cancel/disconnect/expiry/new turn cannot revive a plan. Followup gets a
new speech turn, zero LLM requests, one TTS; only drained followup enters history.
Adjacent spoken assistant rows merge in provider context to preserve role ordering.
Android implements capture cleanup acknowledgement, action state/port, settings
cancel, background cancellation, no-repeat variants, stale callbacks/frames fences,
and expression preload callback separate from displayed expression. V2 metadata
parser and visual selector bind each own body-mouth SHA/97 PTS and slight-only
visual intensity, requiring complete fallback packages and reviewed bridge graph.
See [asset contract](AVATAR_PACK_V2_CONTRACT.md).
Pending: asset owner's mouth amplitude choice, happy/sad TALK packages and their
own mouths/bridges, Pi exact manifest review, idle variants, two real music dances,
asset file/decode import gate and actual v2 bridge/media renderer integration.
No new asset is admitted in this APK; default action capability remains absent.
Existing neutral runtime04 bytes are preserved. No naturalness approval is inferred
from hashes, tests or fixtures. Real device/GPU/music tail/≤1s perception: **not_run**.
Validation: full nine client JVM entry points + expression/UI source contracts;
production parser on actual runtime04 97×5 metadata; 40 offline EGL/GLES pixel cases.
95 gateway tests pass in remote staging, including existing Silero; local archive
also passes with that excluded-model test skipped. Android assemble and device-test
Kotlin compilation pass; instrumentation was not executed on a phone.
Four fixed public local Qwen probes, max_tokens160, all SSE DONE/finish_reason stop:
| Case | Expression | Action | Header prepare / complete ms |
|---|---|---|---|
| fact | neutral0 | none | 747 / 1022 |
| dance fixture capability | happy1 | dance + valid after | 939 / 2436 |
| sympathy | sad1 | none | 722 / 2217 |
| negation | neutral0 | none | 861 / 1405 |
These observations validate nested nullable/ordered decoding on the exact local
Qwen tuple. Preparation is speculative preload; complete parsed expression remains
authoritative. No cloud provider probes or retries were made. Server read-only
clock precheck: Asia/Shanghai, NTP=yes, NTPSynchronized=yes; no system changes.
APK: `0.7.0-stage-dev`, code16, arm64, min26/target34, same debug certificate
`b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1`.
[Download stage candidate](http://192.168.31.124:8080/lan-voice-v070-stage-candidate-code16-arm64-debug.apk)
(HTTP bytes verified), SHA256:
`687c350ec64d693dd8a0bc6e8f1e249816842631119f17a4cbdd38b0cb1e7336`.
Previous code15 retained, SHA256
`a4a7a4f86f2e0582e41dda65b0e5e1870d61ad1876780891598ee0519e833083`.
Detailed numeric evidence (ignored, no raw replies/keys/user audio/face reports):
`logs/action-emotion/{schema-probe.json,delivery.json,shader-golden/}`, client
`logs/avatar-safe-061/`, gateway `logs/voice-investigation/gateway-emotion-staged.json`.
Protected live deployment and public synthetic voice result will be recorded after
their actual execution; no model or unrelated service restart is authorized here.
+12 -1
View File
@@ -13,7 +13,7 @@ every file has SHA256/bytes. Pi approval pins exact manifest SHA outside the man
Self-authored approved/status fields never enable runtime capabilities.
Each conversation package: unique `id`, `emotion:neutral|happy|sad`,
`visualIntensity:0|1`, `runtimeManifest:{path,sha256}` referencing runtime04 format
`visualIntensity:0|1`, `mouthBodySha256`, `runtimeManifest:{path,sha256}` referencing runtime04 format
(continuous body + own 97 PTS registered frames × five RGBA aperture levels,
own curves/anchors/coordinates). Body SHA, frame count and decoded PTS bind every
mouth track to that exact body; no cross-body patches/masks/coordinates reuse.
@@ -29,6 +29,7 @@ reviewed edge, no arbitrary alpha cut. Supply dense seam frames, real-speed loop
and full-scale/close previews, not just matching endpoints.
Actions: exactly `asset_01`, `asset_02`, `kind:dance`, `mouthAllowed:false`,
`disallowTALK:true`,
`entryAnchor:A`, `returnAnchor:A`, `clip` with file SHA/dimensions/frameCount/PTS/
duration/audio track metadata, `audioEndUs`, `reviewEvidence`.
Use a single complete video including entry, music dance and return A, or list
@@ -50,3 +51,13 @@ Asset handoff required first: slight happy/sad TALK samples and own runtime04
mouths/entry-exit evidence. Pi reviews exact manifest + timed previews; only then
expand idle variants and two music dances. Gate1 and deterministic mock traces
cannot certify naturalness or device AudioRecord/GPU/≤1s perception.
Runtime selection keeps `selectedEmotion/selectedIntensity` (model) distinct from
`visualEmotion/visualIntensity/packageId/degraded/reason` (admitted visual). User
camera cues are independent and never select these role packages. Production
runtime04 parser: `app/src/main/java/com/gorios/lanvoice/avatar/ContinuousAvatarManifest.kt`;
v2 index parser: `app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt`.
Each package should use `packId:a01-expression-action-v1-<packageId>-runtime-04`;
runtime04 body/patchFormat/patches/mouthStates/stateRouting field shapes stay intact.
Entry/return bridges carry actual decoded frame PTS; `audioEndUs` records measured
last audio timestamp, completion also waits actual media stop and restored A.
+46 -14
View File
@@ -1,7 +1,7 @@
{
"baseline_android_commit": "9b428fb76ffa1468aa46124b33d9c598cf3740d8",
"source": "SPARK-2 deployed lan-voice gateway",
"code_version": "0.7.3 (role reply intent rules; bounded face pipeline diagnostics; schema)",
"code_version": "0.8.0",
"python": "3.12.3",
"machine": "aarch64",
"scope": "whitelisted source only; no runtime/models/credentials",
@@ -34,8 +34,8 @@
},
"gateway.py": {
"source": "workspace:gateway/gateway.py",
"sha256": "ea268a5abf36f79483427a78991d9ab2bab814ea3042ffcc08025de8c4af6b6d",
"bytes": 38914,
"sha256": "fc4f53494ff253e5016c4e951ece462ae63b0b8567f0633654bce0eb74042b07",
"bytes": 45740,
"upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce"
},
"guest_sessions.py": {
@@ -44,9 +44,10 @@
"bytes": 1429
},
"history.py": {
"source": "history.py",
"sha256": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f",
"bytes": 4842
"source": "workspace:gateway/history.py",
"sha256": "0015b3143268f3e22a8a8a53b65ef4e3522f1f881dfca213c93142899c02631e",
"bytes": 5800,
"upstream_sha256": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f"
},
"persona_resolver.py": {
"source": "persona_resolver.py",
@@ -278,8 +279,8 @@
},
"env.example": {
"source": "workspace:gateway/env.example",
"sha256": "b0c591d5e253ea4ea3ca1b177f4670a8939cfdba5c662cdaedbff7a95418ee85",
"bytes": 1266,
"sha256": "cc2b2a493c9011c262eab02e2eb0858e19eb91c31c289365b2d7cead1477256e",
"bytes": 1615,
"upstream_sha256": "d92e60812f49b02f3b0582d8b3dee03eb51cfca6dba77d9468a3ffddfce32499"
},
"pytest.ini": {
@@ -301,8 +302,8 @@
},
"tests/test_gateway_emotion.py": {
"source": "workspace:gateway/tests/test_gateway_emotion.py",
"sha256": "234310a9f44e3ece56482f4e2080e4f0882d1ea8b7dcd85795c816a8c1ebed78",
"bytes": 8596,
"sha256": "b4123066d3b50220825bf83aa3e96950a02d091d522f08085fb293d29f9706cf",
"bytes": 8597,
"upstream_sha256": "86f22211e753e4b5ebfa11266e2e33eb2ea6b85707fbe8a988be6b8ff05f3f75"
},
"tests/test_reply_emotion.py": {
@@ -313,15 +314,46 @@
},
"llm_provider.py": {
"source": "workspace:gateway/llm_provider.py",
"sha256": "21aa2885c24f3240e891fd5325b09446ae1d8a95497d07a53082410d9fac2b10",
"bytes": 2447,
"sha256": "b3cf6ab5e4c953ef13dc00802f4594055164c89b10b875dda44f071ad1ede082",
"bytes": 2894,
"upstream_sha256": "7d853adbe79f5f861a36894a9dfa28aa553d3eabea4db4c87a5fb4c319818ef1"
},
"tests/test_llm_provider.py": {
"source": "workspace:gateway/tests/test_llm_provider.py",
"sha256": "43669d1fd7e61452b96f314a7f161fbcec843e463c74208d0f892fb58b839785",
"bytes": 8360,
"sha256": "9395b0f1da36a09aebcc9c2d7c151328526449c1bcedbb5f97a190d0fc5573df",
"bytes": 8539,
"upstream_sha256": "6a8bd33679d68899c2a978bf4de672578517494c613b8e77d275c6207de3285b"
},
"action_protocol.py": {
"source": "workspace:gateway/action_protocol.py",
"sha256": "6e312aaa3736b99c24215512187a16689d4a5af8635b29bbc13c7cc1e002bace",
"bytes": 3394
},
"action_reply.py": {
"source": "workspace:gateway/action_reply.py",
"sha256": "4d66164a6668a571dc861282a5c80e408b51dfcfd67f45141e8c6701f6b81364",
"bytes": 7135
},
"server_clock.py": {
"source": "workspace:gateway/server_clock.py",
"sha256": "dc46d79fd43c8b94f52acfdea0564058c47f3a3b8b43aa53fe6868a1821f3a0e",
"bytes": 1379
},
"tests/test_action_protocol.py": {
"source": "workspace:gateway/tests/test_action_protocol.py",
"sha256": "2e19bb1471a2bab67bfb7adca1630151d466e50d9ebc103e54c2f92566f63b63",
"bytes": 9776,
"upstream_sha256": "ae564b6a6e51620a33250e160df2ae0ba6619c5ea6d1063e96bfcd8baa144a79"
},
"tests/test_action_reply.py": {
"source": "workspace:gateway/tests/test_action_reply.py",
"sha256": "0c40a937be4c6545e04ed2268df1714c34dce982058f6b19daabf06b0fa30932",
"bytes": 5209
},
"tests/test_server_clock.py": {
"source": "workspace:gateway/tests/test_server_clock.py",
"sha256": "b7e91ff717fbdcb76984829bd7b184b4633f80dc01637cff33cc0d90363a9518",
"bytes": 2681
}
},
"archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2",
+85
View File
@@ -0,0 +1,85 @@
"""Ephemeral one-owner, one-connection action tickets. No persistence or replay."""
from dataclasses import dataclass
import re
import secrets
import time
def negotiate(hello, configured):
"""Server configuration pins independently reviewed manifests, never client claims."""
if hello.get('action_protocol') != 1 or hello.get('action_kinds') != ['dance']:
return None
sha = hello.get('action_pack_sha256')
pack = configured.get(sha) if isinstance(sha, str) and re.fullmatch(r'[0-9a-f]{64}', sha) else None
if not isinstance(pack, dict) or set(pack) != {'asset_01', 'asset_02'}:
return None
if any(type(value) is not int or not 1000 <= value <= 90000 for value in pack.values()):
return None
return sha, dict(pack)
@dataclass
class ActionTicket:
id: str
owner: str
generation: str
turn: int
after: object
expires: float
pack_sha: str
durations: dict
state: str = 'awaiting_drain'
started: float | None = None
asset_id: str | None = None
class ActionPlans:
def __init__(self, owner, generation, clock=time.monotonic, ttl=120):
self.owner, self.generation, self.clock, self.ttl = owner, generation, clock, ttl
self.ticket = None
def create(self, turn, after, capability):
self.clear()
sha, durations = capability
self.ticket = ActionTicket(secrets.token_urlsafe(18), self.owner, self.generation,
turn, after, self.clock()+self.ttl, sha, durations)
return self.ticket
def clear(self):
self.ticket = None
def valid(self, turn):
ticket = self.ticket
if ticket is not None and self.clock() >= ticket.expires:
# The owning expiry task must still see the ticket and release holding.
return None
return ticket if ticket is not None and ticket.turn == turn else None
def drained(self, turn):
ticket = self.valid(turn)
if ticket is None or ticket.state != 'awaiting_drain': return None
ticket.state = 'offered'
return ticket
def status(self, data, turn, owner, generation):
ticket = self.valid(turn)
if ticket is None or owner != ticket.owner or generation != ticket.generation or \
data.get('turn_id') != ticket.turn or data.get('action_id') != ticket.id:
return 'ignored', None
status = data.get('status')
if status in ('cancelled', 'failed'):
self.clear()
return status, None
if status == 'started' and ticket.state == 'offered' and data.get('mic_stopped') is True:
asset = data.get('asset_id')
if asset not in ticket.durations: return 'ignored', None
ticket.state = 'playing'; ticket.started = self.clock(); ticket.asset_id = asset
return 'started', None
if status == 'completed' and ticket.state == 'playing' and all(
data.get(key) is True for key in ('mic_stopped','video_ended','audio_stopped','idle_restored')):
if self.clock()-ticket.started < ticket.durations[ticket.asset_id]/1000:
return 'too_early', None
after = ticket.after
self.clear() # Consume before scheduling, including reentrant/repeated events.
return 'completed', after
return 'ignored', None
+154
View File
@@ -0,0 +1,154 @@
"""Single-call action envelope and structural incremental expression preparation.
Preparation is speculative preload only. Final strict validation is authoritative.
No partial JSON regex, repaired header or nested after-action expression is published.
"""
from copy import deepcopy
from dataclasses import dataclass, replace
import json
from reply_emotion import REPLY_SCHEMA, ReplyEmotion, SAFE_REPLY, clean_reply, parse_reply
EXPRESSION_SCHEMA = deepcopy(REPLY_SCHEMA)
ACTION_SCHEMA = {
'type': 'object',
'properties': {
'emotion': deepcopy(REPLY_SCHEMA['properties']['emotion']),
'intensity': deepcopy(REPLY_SCHEMA['properties']['intensity']),
'reply': {'type': 'string'},
'action': {'type': 'string', 'enum': ['none', 'dance']},
'after_action': {'anyOf': [{'type': 'null'}, EXPRESSION_SCHEMA]},
},
'required': ['emotion', 'intensity', 'reply', 'action', 'after_action'],
'additionalProperties': False,
}
ACTION_FRAGMENT = '''外层字段按emotion、intensity、reply、action、after_action顺序输出,只有这五个字段。
reply最多20个汉字;action只能none或dance,非表演请求、否定、引用不触发表演。动作可用性以本轮网关摘要为准,不选择文件或URL;不可用时不能假装已跳舞。
action=none时after_action=null。action=dance时reply是简短表演前回应;after_action必须是同一次生成的{reply,emotion,intensity},reply最多20个汉字,表演结束后自然发问或接续对话,句式自然多样,不能断言未来用户反应、具体舞步或准确当前时刻。后续表达只属于后续发言。角色表情视觉仅slightly,不通过大张嘴/哭泣表现。'''
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError('duplicate_key')
result[key] = value
return result
def expression(emotion, intensity):
return isinstance(emotion, str) and emotion in ('neutral', 'happy', 'angry', 'sad') and \
type(intensity) is int and (intensity == 0 if emotion == 'neutral' else intensity in (1, 2))
@dataclass(frozen=True)
class ActionReply:
speech: ReplyEmotion
action: str = 'none'
after: ReplyEmotion | None = None
action_reason: str = 'unavailable'
def parse_action_reply(raw, finish_reason=None, available=False):
try:
if not isinstance(raw, str) or len(raw) > 8192:
raise ValueError('input_limit')
data = json.loads(raw, object_pairs_hook=unique_object)
if not isinstance(data, dict):
raise ValueError('not_object')
except (ValueError, RecursionError) as error:
# Legacy safe recovery is for speech only. No action survives a damaged envelope.
speech = parse_reply(raw, finish_reason)
if str(error) == 'duplicate_key':
speech = replace(speech, emotion='neutral', intensity=0, source='fallback', reason='duplicate_key')
return ActionReply(speech, action_reason='invalid_envelope')
base = {key: data[key] for key in ('reply', 'emotion', 'intensity') if key in data}
speech = parse_reply(json.dumps(base), finish_reason)
if set(data) != set(ACTION_SCHEMA['required']):
return ActionReply(speech, action_reason='envelope_fields')
if data['action'] == 'none' and data['after_action'] is None:
return ActionReply(speech, action_reason='none')
if data['action'] != 'dance':
return ActionReply(speech, action_reason='invalid_action')
if not available:
# An unsupported action promise must not be spoken to an old/unprepared client.
return ActionReply(ReplyEmotion('当前还没有可用的舞蹈,可以先聊聊天。', reason='action_unavailable'),
action_reason='unavailable')
after = data['after_action']
if not isinstance(after, dict) or set(after) != {'reply', 'emotion', 'intensity'}:
return ActionReply(speech, action_reason='invalid_after')
parsed = parse_reply(json.dumps(after), finish_reason)
if speech.source != 'model' or parsed.source != 'model' or finish_reason == 'length':
return ActionReply(speech, action_reason='invalid_or_truncated')
return ActionReply(speech, 'dance', parsed, 'none')
class ExpressionPrefix:
"""Accept exactly complete top-level header values + their delimiters, in order.
Must be gated by independently probed strict schema capability. Even there a
candidate never changes visible emotion; final mismatch cancels preparation.
"""
def __init__(self, turn):
self.turn = turn
self.raw = ''
self.candidate = None
self.invalid = False
def feed(self, chunk, current_turn):
if self.invalid or current_turn != self.turn:
self.invalid = True
return None
self.raw += chunk
if len(self.raw) > 8192:
self.invalid = True
return None
decoder = json.JSONDecoder(object_pairs_hook=unique_object)
text = self.raw.lstrip()
if not text.startswith('{'):
if text: self.invalid = True
return None
pos = 1
found = {}
for expected in ('emotion', 'intensity'):
try:
while pos < len(text) and text[pos].isspace(): pos += 1
key, pos = decoder.raw_decode(text, pos)
if key != expected:
self.invalid = True
return None
while pos < len(text) and text[pos].isspace(): pos += 1
if pos == len(text): return None
if text[pos] != ':':
self.invalid = True
return None
pos += 1
while pos < len(text) and text[pos].isspace(): pos += 1
value, pos = decoder.raw_decode(text, pos)
while pos < len(text) and text[pos].isspace(): pos += 1
if pos == len(text): return None
if text[pos] != ',':
self.invalid = True
return None
pos += 1
found[key] = value
except (ValueError, RecursionError):
return None # A split escape/number/string may become valid on next chunk.
if not expression(found['emotion'], found['intensity']):
self.invalid = True
return None
candidate = (found['emotion'], found['intensity'])
if self.candidate is None:
self.candidate = candidate
return candidate
return None
def consistent(self, result, current_turn):
try:
obj = json.loads(self.raw, object_pairs_hook=unique_object)
valid = isinstance(obj, dict) and set(obj) == set(ACTION_SCHEMA['required'])
except (ValueError, RecursionError):
valid = False
return valid and not self.invalid and current_turn == self.turn and result.speech.source == 'model' and \
self.candidate == (result.speech.emotion, result.speech.intensity)
+6
View File
@@ -19,3 +19,9 @@ LAN_LLM_CHAT_TEMPLATE_KWARGS={"enable_thinking":false}
# Alias does not identify actual weights.
# Gateway0.7.3 keeps this provider/schema contract and the160-token dialogue budget;
# camera/frame diagnostics do not add a model or inference retry.
# Request-local clock; never infer zone from host locale or client clock.
LAN_LLM_TIME_ZONE=Asia/Shanghai
# Prefix prepare is preload only; defaults on only for the probed exact local schema tuple.
# LAN_LLM_EXPRESSION_PREPARE=0
# Empty by default. Pi must pin independently reviewed manifest hashes and both actual durations.
# LAN_ACTION_PACKS={}
+124 -9
View File
@@ -20,6 +20,8 @@ import uuid
from history import History
from face_context import FaceContext
from reply_emotion import SYSTEM_FRAGMENT, parse_reply
from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply
from action_protocol import ActionPlans, negotiate
from guest_sessions import GuestSessions, COOKIE
from tts_debug import DebugStore
from persona_resolver import resolve_persona
@@ -30,7 +32,7 @@ from protocol import WavStream, pack, unpack
from vad import Config, Silero, VadSession
ROOT = Path(__file__).resolve().parent
VERSION = '0.7.3'
VERSION = '0.8.0'
DEFAULT_VOICE_ID = '9a97272c-3919-5606-9c8f-9552ab602528'
ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.0.0.1:5011'}
@@ -39,7 +41,11 @@ ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.
async def lifespan(app):
token = os.environ.get('LAN_GATEWAY_TOKEN', '')
if len(token) < 32: raise RuntimeError('missing gateway token')
app.state.llm_structured_output = LLMProvider().structured_output
provider = LLMProvider()
app.state.llm_structured_output = provider.structured_output
app.state.llm_model = provider.model
app.state.llm_time_zone = provider.clock.zone.key
app.state.expression_prepare = provider.expression_prepare
path = ROOT / 'models/silero_vad.onnx'
if hashlib.sha256(path.read_bytes()).hexdigest() != EXPECTED_HASH: raise RuntimeError('model checksum')
app.state.model = await asyncio.to_thread(Silero, path)
@@ -138,7 +144,11 @@ async def logout(request: Request):
@app.get('/health')
async def health():
return {'status': 'ok', 'version': VERSION, 'codec': 'pcm16', 'opus': False, 'busy': app.state.busy, 'llm_structured_output': getattr(app.state, 'llm_structured_output', 'prompt'), 'stt': 'batch SenseVoice', 'tts': 'per-turn full text / single streaming generator VoxCPM2', 'voice_mode_default': 'continuous_voice', 'default_voice_id': DEFAULT_VOICE_ID}
return {'status': 'ok', 'version': VERSION, 'codec': 'pcm16', 'opus': False, 'busy': app.state.busy,
'llm_model': getattr(app.state, 'llm_model', 'unknown'),
'llm_time_zone': getattr(app.state, 'llm_time_zone', 'unknown'),
'expression_prepare': getattr(app.state, 'expression_prepare', False),
'llm_structured_output': getattr(app.state, 'llm_structured_output', 'prompt'), 'stt': 'batch SenseVoice', 'tts': 'per-turn full text / single streaming generator VoxCPM2', 'voice_mode_default': 'continuous_voice', 'default_voice_id': DEFAULT_VOICE_ID}
@app.post('/debug/log')
@@ -222,6 +232,13 @@ class Dialogue:
self.face_context = FaceContext()
self.face_messages = {}
self.pending_drained = None
self.connection_generation = secrets.token_hex(16)
self.owner = secrets.token_hex(16)
self.action_plans = ActionPlans(self.owner, self.connection_generation)
self.action_capability = None
self.action_expiry_task = None
self.action_holding = False
self.followup_pending = None
self.capture_offset = 0
self.received_samples = 0
self.vad = VadSession(model, Config(max_session_seconds=600))
@@ -243,12 +260,12 @@ class Dialogue:
self.playback_waiting = False
self.auth_check = lambda: True
async def event(self, kind, turn=None, **fields):
async def event(self, event_type, turn=None, **fields):
async with self.lock:
if turn is not None and turn != self.turn: return
if not self.auth_check(): raise ValueError('guest expired')
self.event_seq += 1
await asyncio.wait_for(self.ws.send_json({'type': kind, 'turn_id': self.turn if turn is None else turn, 'seq': self.event_seq, 'server_ms': round((time.monotonic() - self.wall) * 1000, 3), **fields}), 5)
await asyncio.wait_for(self.ws.send_json({'type': event_type, 'turn_id': self.turn if turn is None else turn, 'seq': self.event_seq, 'server_ms': round((time.monotonic() - self.wall) * 1000, 3), **fields}), 5)
async def audio(self, turn, pcm):
async with self.lock:
@@ -259,6 +276,12 @@ class Dialogue:
async def invalidate(self, reason, preserve_vad=False):
old_turn = self.turn
self.action_plans.clear()
self.action_holding = False
self.followup_pending = None
expiry = self.action_expiry_task
self.action_expiry_task = None
if expiry and expiry is not asyncio.current_task(): expiry.cancel()
self.turn += 1
if reason == 'new_turn':
self.face_context.advance_capture(old_turn, self.turn)
@@ -305,6 +328,7 @@ class Dialogue:
await self.event('listen', state='stop', mode=mode)
async def input(self, frame):
if self.action_holding: return # Drop all stale input; no capture/VAD/ASR buffering.
turn, seq, pcm = unpack(frame, 1)
if turn != self.turn: return
if not self.listening: raise ValueError('not listening')
@@ -388,9 +412,20 @@ class Dialogue:
async def drained(self):
self.pending_drained = None
self.playback_waiting = False
if self.followup_pending and self.followup_pending[0] == self.turn:
_, rid, text = self.followup_pending
self.followup_pending = None
if self.history: await self.history.spoken(self.conversation_id, rid, text)
if self.history and self.run_id:
await self.history.drained(self.run_id)
await self.send_history()
ticket = self.action_plans.drained(self.turn)
if ticket is not None:
self.action_holding = True
self.capture.clear(); self.start = None; self.vad.reset()
await self.event('action.plan', action_id=ticket.id, kind='dance', pack_sha256=ticket.pack_sha,
ttl_ms=max(0, int((ticket.expires-time.monotonic())*1000)))
return
if not self.barge:
self.capture.clear(); self.start = None; self.base = 0
self.capture_offset = self.received_samples
@@ -450,6 +485,8 @@ class Dialogue:
await self.event('error', turn, code='backend_failed', message='Backend timeout, format or synthesis failure')
await self.event('tts', turn, state='stop')
finally:
if turn == self.turn and status != 'completed':
self.action_plans.clear()
answer = self.answers.pop(turn, '')
self.contexts.pop(turn, None)
self.face_messages.pop(turn, None)
@@ -470,11 +507,13 @@ class Dialogue:
metrics.update(voice_mode=self.voice_mode, voice_id=self.voice_id, tts_request_count=0)
# Exactly one initial system: Qwen's deployed template rejects a second system.
system = '以下角色设定只约束reply字段的可朗读正文。\n' + self.persona_rules + ''.join(
'\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT
'\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT + '\n' + ACTION_FRAGMENT + '\n网关实际可用动作:' + ('dance' if self.action_capability else '无')
messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}]
url, headers, body = self.llm_provider.request(messages, max_tokens=160)
url, headers, body = self.llm_provider.request(messages, max_tokens=160, action_plan=True)
metrics['llm_request_count'] = 1
raw_body = ''
prefix = ExpressionPrefix(turn)
prepare_enabled = self.llm_provider.expression_prepare
finish_reason = 'not_provided'
usage = {}
async with asyncio.timeout(30):
@@ -501,11 +540,23 @@ class Dialogue:
if not delta: continue
metrics.setdefault('llm_first_token_ms', round((time.perf_counter() - request_start) * 1000, 2))
raw_body += delta
candidate = prefix.feed(delta, self.turn)
if candidate is not None and prepare_enabled:
metrics['expression_prepare_ms'] = round((time.perf_counter()-request_start)*1000, 2)
await self.event('reply.emotion.prepare', turn, emotion=candidate[0], intensity=candidate[1], preload_only=True)
if len(raw_body) > 8192: raise ValueError('structured reply limit')
if turn != self.turn: return
if not raw_body.strip(): raise ValueError('empty LLM body')
parse_start = time.perf_counter()
result = parse_reply(raw_body, finish_reason=finish_reason)
plan = parse_action_reply(raw_body, finish_reason, bool(self.action_capability))
result = plan.speech
metrics['action_reason'] = plan.action_reason
metrics['expression_prepare_mode'] = 'schema_prefix_preload' if prepare_enabled else 'full_reply'
if prepare_enabled and prefix.candidate and not prefix.consistent(plan, self.turn):
await self.event('reply.emotion.prepare.cancel', turn, reason='final_invalid')
if plan.action == 'dance':
ticket = self.action_plans.create(turn, plan.after, self.action_capability)
self.action_expiry_task = asyncio.create_task(self.expire_action(ticket.id, turn))
metrics.update(reply_emotion_reason=result.reason, reply_parse_branch=result.parse_branch,
reply_emotion=result.emotion, reply_intensity=result.intensity,
llm_finish_reason=finish_reason, llm_usage=usage, llm_max_tokens=body['max_tokens'],
@@ -529,6 +580,60 @@ class Dialogue:
await enqueue(result.reply)
await queue.put(None)
async def expire_action(self, action_id, turn):
try:
ticket = self.action_plans.ticket
if ticket is None: return
await asyncio.sleep(max(0, ticket.expires-time.monotonic()))
if turn == self.turn and self.action_plans.ticket and self.action_plans.ticket.id == action_id:
await self.invalidate('action_timeout')
await self.event('action.cancel', action_id=action_id, reason='timeout')
await self.event('listen', state='resumed', mode=self.mode)
except asyncio.CancelledError:
pass
async def action_status(self, data):
status, after = self.action_plans.status(data, self.turn, self.owner, self.connection_generation)
if status in ('cancelled', 'failed'):
await self.invalidate('action_cancelled')
await self.event('listen', state='resumed', mode=self.mode)
elif status == 'completed':
await self.invalidate('action_followup')
turn = self.turn
self.run_id = str(uuid.uuid4())
await self.event('speech.start', turn, origin='after_action')
self.task = asyncio.create_task(self.speak_followup(turn, after))
async def speak_followup(self, turn, speech):
began = time.perf_counter()
rid = self.run_id
metrics = {'llm_request_count': 0, 'tts_request_count': 0, 'origin': 'after_action'}
try:
self.playback_waiting = True
await self.event('tts', turn, state='start', sample_rate=48000, codec='pcm16', frame_duration=20)
await self.event('llm', turn, text=speech.reply)
await self.event('reply.emotion', turn, emotion=speech.emotion, intensity=speech.intensity,
source=speech.source, reason=speech.reason, parse_branch=speech.parse_branch)
queue = asyncio.Queue(2)
await queue.put(speech.reply); await queue.put(None)
await self.synthesize(turn, queue, metrics, began)
if turn != self.turn: return
self.followup_pending = (turn, rid, speech.reply)
await self.event('metrics', turn, values=metrics)
await self.event('tts', turn, state='stop')
except asyncio.CancelledError:
raise
except Exception:
self.followup_pending = None
await self.event('error', turn, code='after_synthesis_failed', message='Action followup synthesis failed')
await self.event('tts', turn, state='stop')
finally:
capture = self.debug_captures.pop(turn, None)
if capture:
await asyncio.to_thread(capture.finalize, 'completed' if self.followup_pending else 'interrupted')
if turn == self.turn and not self.closed and self.pending_drained == turn:
await self.drained()
async def synthesize(self, turn, queue, metrics, began):
sentence = 0
previous_end = None
@@ -597,8 +702,13 @@ class Dialogue:
async def close(self):
self.closed = True
self.action_plans.clear()
self.followup_pending = None
self.action_holding = False
if self.action_expiry_task: self.action_expiry_task.cancel()
self.turn += 1
tasks = list(self.cancelled_tasks)
if self.action_expiry_task: tasks.append(self.action_expiry_task)
if self.task: tasks.append(self.task)
for task in tasks: task.cancel()
if tasks: await asyncio.gather(*tasks, return_exceptions=True)
@@ -642,6 +752,9 @@ async def dialogue(ws: WebSocket):
Segmenter(synthesis_mode)
session = Dialogue(ws, app.state.model, app.state.client, app.state.history, cid)
session.synthesis_mode = synthesis_mode
session.owner = owner or 'admin'
session.action_plans = ActionPlans(session.owner, session.connection_generation)
session.action_capability = negotiate(hello, json.loads(os.environ.get('LAN_ACTION_PACKS', '{}')))
if owner: session.auth_check = lambda: bool(app.state.guests.get(owner))
voice_mode = hello.get('voice_mode', 'continuous_voice')
if voice_mode not in ('continuous_voice', 'fragment'): raise ValueError('voice mode')
@@ -656,7 +769,7 @@ async def dialogue(ws: WebSocket):
session.voice_id = voice_id
session.debug_store = app.state.debug
session.debug_enabled = hello.get('tts_debug', True) is True
await session.event('hello', context_face_cue_version=1, reply_emotion_version=1, llm_structured_output=session.llm_provider.structured_output, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices)
await session.event('hello', action_protocol=1, action_available=bool(session.action_capability), context_face_cue_version=1, reply_emotion_version=1, llm_structured_output=session.llm_provider.structured_output, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices)
await session.send_history()
started = time.monotonic()
while time.monotonic() - started < 600:
@@ -704,6 +817,8 @@ async def dialogue(ws: WebSocket):
else: raise ValueError('history action')
elif data.get('type') == 'playback.drained':
await session.request_drained(data.get('turn_id'))
elif data.get('type') == 'action.status':
await session.action_status(data)
elif data.get('type') == 'ping': await session.event('pong')
else: raise ValueError('control')
except (WebSocketDisconnect, RuntimeError):
+22 -3
View File
@@ -58,10 +58,21 @@ CREATE TABLE IF NOT EXISTS messages(id INTEGER PRIMARY KEY AUTOINCREMENT, conver
async def context(self, cid, current):
def query(db):
rows = list(db.execute("SELECT u.text user,a.text assistant FROM messages u JOIN messages a ON u.run_id=a.run_id AND u.conversation_id=a.conversation_id WHERE u.conversation_id=? AND u.run_id<>? AND u.role='user' AND a.role='assistant' AND u.status='completed' AND a.status='completed' AND a.playback='confirmed' ORDER BY u.id DESC LIMIT 10", (cid, current)))
rows = list(db.execute("""SELECT m.role,m.text FROM messages m
WHERE m.conversation_id=? AND m.run_id<>? AND m.status='completed'
AND EXISTS (SELECT 1 FROM messages a WHERE a.conversation_id=m.conversation_id
AND a.run_id=m.run_id AND a.role='assistant' AND a.status='completed' AND a.playback='confirmed')
ORDER BY m.id DESC LIMIT 20""", (cid, current)))
# Server followups have their own persisted speech turn, but providers
# may require alternating chat roles. Join adjacent spoken assistant
# rows in the request context only; preserve original history records.
out=[]
for r in reversed(rows):
out += [{'role': 'user', 'content': r['user'][:2000]}, {'role': 'assistant', 'content': r['assistant'][:2000]}]
for row in reversed(rows):
if not out and row['role'] != 'user': continue
if out and out[-1]['role'] == row['role']:
out[-1]['content']=(out[-1]['content']+'\n'+row['text'])[:2000]
else:
out.append({'role':row['role'],'content':row['text'][:2000]})
return out
return await self.call(query)
@@ -83,3 +94,11 @@ CREATE TABLE IF NOT EXISTS messages(id INTEGER PRIMARY KEY AUTOINCREMENT, conver
async def clear(self, cid):
await self.call(lambda db: db.execute('DELETE FROM messages WHERE conversation_id=?', (cid,)))
async def spoken(self, cid, rid, text):
"""Server-initiated speech enters history only after actual playback.drained."""
def insert(db):
now = time.time()
db.execute("INSERT OR IGNORE INTO messages(conversation_id,run_id,role,text,status,playback,created,updated) VALUES (?,?,?,?,?,?,?,?)",
(cid, rid, 'assistant', text[:2000], 'completed', 'confirmed', now, now))
await self.call(insert)
+5 -2
View File
@@ -27,17 +27,20 @@ class LLMProvider:
verified_local = (self.base_url == 'http://127.0.0.1:8888/v1'
and self.model == 'qwen3.8-27b'
and self.template_kwargs == {'enable_thinking': False})
self.expression_prepare = verified_local and env.get('LAN_LLM_EXPRESSION_PREPARE', '1') == '1'
self.structured_output = env.get('LAN_LLM_STRUCTURED_OUTPUT',
'json_schema' if verified_local else 'prompt')
self.expression_prepare = self.expression_prepare and self.structured_output == 'json_schema'
if self.structured_output not in ('prompt', 'json_schema'):
raise ValueError('invalid LLM structured output mode')
def request(self, messages, *, max_tokens=64):
def request(self, messages, *, max_tokens=64, action_plan=False):
body = {'model': self.model, 'messages': self.clock.messages(messages), 'max_tokens': max_tokens, 'temperature': 0.3, 'stream': True}
if self.template_kwargs:
body['chat_template_kwargs'] = self.template_kwargs
if self.structured_output == 'json_schema':
from action_reply import ACTION_SCHEMA
body['response_format'] = {'type': 'json_schema', 'json_schema': {
'name': 'role_reply', 'strict': True, 'schema': deepcopy(REPLY_SCHEMA)}}
'name': 'role_reply', 'strict': True, 'schema': deepcopy(ACTION_SCHEMA if action_plan else REPLY_SCHEMA)}}
headers = {'Authorization': 'Bearer ' + self.api_key} if self.api_key else {}
return self.base_url + '/chat/completions', headers, body
+5 -3
View File
@@ -1,6 +1,7 @@
"""Request-local wall clock. Durations/deadlines must continue using monotonic time."""
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
import re
class ServerClock:
@@ -10,12 +11,13 @@ class ServerClock:
def messages(self, messages):
copied = [dict(message) for message in messages]
systems = [message['content'] for message in copied if message.get('role') == 'system']
systems = [re.sub(r'\n*\[gateway_request_clock\].*?\[/gateway_request_clock\]', '',
message['content'], flags=re.S) for message in copied if message.get('role') == 'system']
# Do not mutate the caller's persona/history, or accept a client time as authority.
instant = self.now()
if instant.tzinfo is None:
raise ValueError('server wall clock must be timezone aware')
reference = ('当前服务器时间:' + instant.astimezone(self.zone).isoformat(timespec='seconds') +
'\n时区:' + self.zone.key + '。这是本次请求的时间参考,不代表用户所在地。')
reference = ('[gateway_request_clock]\n当前服务器时间:' + instant.astimezone(self.zone).isoformat(timespec='seconds') +
'\n时区:' + self.zone.key + '。这是本次请求的时间参考,不代表用户所在地。\n[/gateway_request_clock]')
return [{'role': 'system', 'content': '\n\n'.join(systems + [reference])}] + [
message for message in copied if message.get('role') != 'system']
+173
View File
@@ -0,0 +1,173 @@
import asyncio
import json
import tempfile
import time
import unittest
from pathlib import Path
import httpx
from action_protocol import ActionPlans, negotiate
from action_reply import parse_action_reply
from gateway import Dialogue
from history import History
from protocol import pack
from test_gateway import Socket
import io
import wave
def wav(pcm, rate):
output=io.BytesIO()
with wave.open(output, 'wb') as file:
file.setnchannels(1);file.setsampwidth(2);file.setframerate(rate);file.writeframes(pcm)
return output.getvalue()
from tests_fake import FakeModel
SHA='a'*64
PACK=(SHA,{'asset_01':1000,'asset_02':2000})
RAW=json.dumps(dict(emotion='happy',intensity=1,reply='好呀。',action='dance',
after_action=dict(reply='还想聊什么?',emotion='sad',intensity=1)))
class ActionProtocolTests(unittest.TestCase):
def test_unknown_capability_and_independent_review_allowlist(self):
configured={SHA:PACK[1]}
for hello in ({},{'action_protocol':1},{'action_protocol':2,'action_kinds':['dance'],'action_pack_sha256':SHA},
{'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':'b'*64}):
self.assertIsNone(negotiate(hello,configured))
self.assertEqual(negotiate({'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':SHA},configured),PACK)
def test_completion_once_owner_generation_turn_delay_and_ttl(self):
now=[10.0];plans=ActionPlans('owner','conn',lambda:now[0],ttl=3)
ticket=plans.create(7,'after',PACK)
event={'action_id':ticket.id,'turn_id':7,'status':'completed','mic_stopped':True,
'video_ended':True,'audio_stopped':True,'idle_restored':True}
self.assertEqual(plans.status(event,7,'owner','conn')[0],'ignored')
self.assertEqual(plans.drained(7),ticket)
self.assertIsNone(plans.drained(7))
start={**event,'status':'started','asset_id':'asset_02'}
for owner,conn,turn in [('other','conn',7),('owner','old',7),('owner','conn',8)]:
self.assertEqual(plans.status(start,turn,owner,conn)[0],'ignored')
self.assertEqual(plans.status({**start,'mic_stopped':False},7,'owner','conn')[0],'ignored')
self.assertEqual(plans.status(start,7,'owner','conn')[0],'started')
self.assertEqual(plans.status(event,7,'owner','conn')[0],'too_early')
now[0]+=2
self.assertEqual(plans.status(event,7,'owner','conn'),('completed','after'))
self.assertEqual(plans.status(event,7,'owner','conn'),('ignored',None))
plans.create(7,'after',PACK);now[0]+=3
self.assertIsNone(plans.drained(7))
def test_cancel_failed_new_turn_and_stale_ids(self):
for status in ('cancelled','failed'):
plans=ActionPlans('o','c');ticket=plans.create(1,'after',PACK)
self.assertEqual(plans.status({'action_id':ticket.id,'turn_id':1,'status':status},1,'o','c'),(status,None))
self.assertIsNone(plans.ticket)
plans=ActionPlans('o','c');old=plans.create(1,'old',PACK);plans.create(2,'new',PACK)
self.assertEqual(plans.status({'action_id':old.id,'turn_id':1,'status':'completed'},2,'o','c')[0],'ignored')
class ActionDialogueTests(unittest.IsolatedAsyncioTestCase):
async def test_single_llm_then_drained_music_then_single_followup_and_history(self):
calls=[]
def backend(request):
calls.append(request)
if request.url.port==8888:
body=json.loads(request.content)
self.assertEqual(sum(m['role']=='system' for m in body['messages']),1)
self.assertIn('当前服务器时间:',body['messages'][0]['content'])
# Exercise arbitrary SSE chunks and escaped strings through actual generate.
text=''.join('data: '+json.dumps({'choices':[{'delta':{'content':RAW[i:i+3]}}]})+'\n\n' for i in range(0,len(RAW),3))
return httpx.Response(200,text=text+'data: {"choices":[{"finish_reason":"stop","delta":{}}]}\n\ndata: [DONE]\n\n')
self.assertEqual(request.url.port,5002)
return httpx.Response(200,content=wav(b'\x10\x02'*4800,48000))
with tempfile.TemporaryDirectory() as folder:
history=History(Path(folder)/'history.db');await history.initialize();cid=await history.conversation()
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
socket=Socket();d=Dialogue(socket,FakeModel(),client,history,cid)
d.action_capability=PACK;d.run_id='pre';await history.begin(cid,'pre','公开合成请求')
d.playback_waiting=True
queue=asyncio.Queue(2);metrics={}
await d.generate(0,'公开合成请求',queue,metrics,time.perf_counter())
self.assertFalse(any(e['type']=='action.plan' for e in socket.events))
await d.synthesize(0,queue,metrics,time.perf_counter())
await history.finish('pre',d.answers[0],'completed')
await d.drained()
ticket=d.action_plans.ticket
self.assertTrue(d.action_holding)
await d.input(pack(1,0,999,b'\0\0'*320))
self.assertEqual(d.received_samples,0)
status={'action_id':ticket.id,'turn_id':0,'status':'started','asset_id':'asset_01','mic_stopped':True}
await d.action_status(status)
ticket.started-=1.1
complete={**status,'status':'completed','video_ended':True,'audio_stopped':True,'idle_restored':True}
await d.action_status(complete)
await d.task
self.assertEqual(d.turn,1)
self.assertEqual(sum(r.url.port==8888 for r in calls),1)
self.assertEqual(sum(r.url.port==5002 for r in calls),2)
self.assertEqual(len(await history.rows(cid)),2) # after_action still unconfirmed
await d.request_drained(1)
rows=await history.rows(cid)
self.assertEqual(len(rows),3)
self.assertEqual(rows[-1]['playback'],'confirmed')
self.assertEqual(rows[-1]['text'],'还想聊什么?')
context=await history.context(cid,'next')
self.assertEqual([row['role'] for row in context],['user','assistant'])
self.assertIn('还想聊什么?',context[-1]['content'])
await d.action_status(complete)
self.assertEqual(sum(r.url.port==5002 for r in calls),2)
prepare=next(i for i,e in enumerate(socket.events) if e['type']=='reply.emotion.prepare')
final=next(i for i,e in enumerate(socket.events) if e['type']=='llm')
self.assertLess(prepare,final)
await d.close()
async def test_new_turn_discards_plan_and_after_speech(self):
d=Dialogue(Socket(),FakeModel(),None)
ticket=d.action_plans.create(0,parse_action_reply(RAW,'stop',True).after,PACK)
await d.invalidate('new_turn')
await d.action_status({'action_id':ticket.id,'turn_id':0,'status':'completed'})
self.assertIsNone(d.task)
self.assertIsNone(d.action_plans.ticket)
await d.close()
async def test_cancel_does_not_speak_followup_and_late_completion_is_ignored(self):
socket=Socket();d=Dialogue(socket,FakeModel(),None)
ticket=d.action_plans.create(0,parse_action_reply(RAW,'stop',True).after,PACK)
await d.action_status({'action_id':ticket.id,'turn_id':0,'status':'cancelled'})
self.assertIsNone(d.task)
self.assertEqual(d.turn,1)
await d.action_status({'action_id':ticket.id,'turn_id':0,'status':'completed'})
self.assertFalse(any(e['type']=='speech.start' for e in socket.events))
await d.close()
async def test_expired_status_cannot_hide_ticket_from_release_timer(self):
socket=Socket();d=Dialogue(socket,FakeModel(),None)
ticket=d.action_plans.create(0,'after',PACK);ticket.expires=time.monotonic()-1
d.action_holding=True
await d.action_status({'action_id':ticket.id,'turn_id':0,'status':'completed'})
await d.expire_action(ticket.id,0)
self.assertFalse(d.action_holding)
self.assertIsNone(d.action_plans.ticket)
self.assertTrue(any(e['type']=='action.cancel' for e in socket.events))
await d.close()
async def test_after_pending_is_discarded_by_new_turn_before_drain(self):
with tempfile.TemporaryDirectory() as folder:
h=History(Path(folder)/'h.db');await h.initialize();cid=await h.conversation()
d=Dialogue(Socket(),FakeModel(),None,h,cid)
d.followup_pending=(0,'after','未排空的公开合成正文')
d.playback_waiting=True
await d.invalidate('new_turn');await d.request_drained(0)
self.assertEqual(await h.rows(cid),[])
self.assertEqual(await h.context(cid,'current'),[])
await d.close()
async def test_missing_audio_stop_and_return_cannot_complete(self):
plans=ActionPlans('o','c',lambda:10)
ticket=plans.create(1,'after',PACK);plans.drained(1)
base={'action_id':ticket.id,'turn_id':1,'mic_stopped':True,'asset_id':'asset_01'}
plans.status({**base,'status':'started'},1,'o','c');ticket.started=8
for missing in ('video_ended','audio_stopped','idle_restored','mic_stopped'):
event={**base,'status':'completed','video_ended':True,'audio_stopped':True,'idle_restored':True}
event[missing]=False
self.assertEqual(plans.status(event,1,'o','c'),('ignored',None))
self.assertIsNotNone(plans.ticket)
+94
View File
@@ -0,0 +1,94 @@
import json
import unittest
from action_reply import ExpressionPrefix, parse_action_reply
def envelope(**fields):
return json.dumps(dict(emotion='happy', intensity=1, reply='好呀,看好了。', action='dance',
after_action=dict(reply='还想聊些什么?', emotion='neutral', intensity=0), **fields), ensure_ascii=False)
class ActionReplyTests(unittest.TestCase):
def test_every_chunk_boundary_and_escaped_strings(self):
raw=envelope().replace('好呀,看好了。', '你说\\"你好\\",\\n看好了。')
for boundary in range(len(raw)+1):
with self.subTest(boundary=boundary):
prefix=ExpressionPrefix(8)
events=[prefix.feed(raw[:boundary],8),prefix.feed(raw[boundary:],8)]
self.assertEqual([event for event in events if event], [('happy',1)])
result=parse_action_reply(raw,'stop',True)
self.assertTrue(prefix.consistent(result,8))
self.assertEqual(result.action,'dance')
def test_char_chunks_and_complete_number_delimiter(self):
prefix=ExpressionPrefix(1);events=[]
raw=envelope()
for char in raw:
found=prefix.feed(char,1)
if found:events.append(found)
self.assertEqual(events,[('happy',1)])
prefix=ExpressionPrefix(1)
self.assertIsNone(prefix.feed('{"emotion":"happy","intensity":1',1))
self.assertIsNone(prefix.feed('0,',1))
self.assertTrue(prefix.invalid)
def test_final_duplicates_extra_types_truncation_and_turn_fences(self):
valid=envelope()
bad=[valid[:-1]+',"emotion":"sad"}', valid[:-1]+',"extra":1}', valid[:-1],
valid.replace('"intensity": 1','"intensity": true',1),
valid.replace('"emotion": "happy"','"emotion": []',1),
valid.replace('"intensity": 1','"intensity": 1.0',1),
valid.replace('"emotion": "neutral", "intensity": 0','"emotion": "neutral", "emotion": "sad", "intensity": 0')]
for raw in bad:
prefix=ExpressionPrefix(1);prefix.feed(raw,1)
parsed=parse_action_reply(raw,'stop',True)
self.assertFalse(prefix.consistent(parsed,1))
self.assertEqual(parsed.action,'none')
self.assertFalse(parsed.speech.reply.startswith('{'))
prefix=ExpressionPrefix(1)
self.assertIsNone(prefix.feed(valid,2))
self.assertFalse(prefix.consistent(parse_action_reply(valid,'stop',True),2))
def test_no_partial_nested_or_reordered_header(self):
for raw in ('{"emotion":"hap', '{"reply":"正文","emotion":"happy","intensity":1,',
'{"after_action":{"emotion":"happy","intensity":1},',
'{"emotion":"happy","intensity":true,'):
self.assertIsNone(ExpressionPrefix(1).feed(raw,1))
def test_action_semantics_and_unavailable_old_client(self):
data=json.loads(envelope())
result=parse_action_reply(envelope(),'stop',False)
self.assertEqual(result.action,'none')
self.assertNotEqual(result.speech.reply,data['reply'])
for action,after in [('url',data['after_action']),('dance',None),('none',data['after_action']),
('dance',{'reply':'{bad}','emotion':'happy','intensity':1})]:
raw=json.dumps({**data,'action':action,'after_action':after})
self.assertEqual(parse_action_reply(raw,'stop',True).action,'none')
self.assertEqual(parse_action_reply(envelope(),'length',True).action,'none')
self.assertEqual(parse_action_reply(envelope(),'stop',True).after.emotion,'neutral')
def test_final_mismatched_duplicate_header_cannot_remain_model(self):
raw=envelope()[:-1]+',"intensity":2}'
prefix=ExpressionPrefix(1);self.assertEqual(prefix.feed(raw,1),('happy',1))
result=parse_action_reply(raw,'stop',True)
self.assertFalse(prefix.consistent(result,1))
self.assertEqual((result.speech.emotion,result.speech.source,result.action),('neutral','fallback','none'))
def test_after_expression_is_not_front_expression(self):
data=json.loads(envelope());data['after_action']['emotion']='sad';data['after_action']['intensity']=2
raw=json.dumps(data);prefix=ExpressionPrefix(1)
self.assertEqual(prefix.feed(raw,1),('happy',1))
result=parse_action_reply(raw,'stop',True)
self.assertEqual((result.speech.emotion,result.after.emotion,result.after.intensity),('happy','sad',2))
def test_provider_action_schema_is_nested_nullable_and_isolated(self):
from llm_provider import LLMProvider
from action_reply import ACTION_SCHEMA
qwen=LLMProvider({});body=qwen.request([],action_plan=True)[2]
self.assertEqual(body['response_format']['json_schema']['schema'],ACTION_SCHEMA)
self.assertTrue(qwen.expression_prepare)
doubao=LLMProvider({'LAN_LLM_MODEL':'doubao-seed-2-1-pro'})
self.assertFalse(doubao.expression_prepare)
self.assertNotIn('chat_template_kwargs',doubao.request([],action_plan=True)[2])
self.assertNotIn('response_format',doubao.request([],action_plan=True)[2])
+2 -2
View File
@@ -10,7 +10,7 @@ from gateway import Dialogue
from tests_fake import FakeModel
from test_gateway import Socket
from llm_provider import LLMProvider
from reply_emotion import REPLY_SCHEMA
from action_reply import ACTION_SCHEMA
class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase):
async def test_seven_states_no_envelope_in_body_history_or_tts(self):
@@ -32,7 +32,7 @@ class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase):
if 'chat' in request.url.path:
data=json.loads(request.content);self.assertEqual([m['role'] for m in data['messages']],['system','user'])
model_requests.append(data)
self.assertEqual(data['response_format']['json_schema']['schema'],REPLY_SCHEMA)
self.assertEqual(data['response_format']['json_schema']['schema'],ACTION_SCHEMA)
self.assertEqual(data['max_tokens'],160)
self.assertIn('角色设定只约束reply字段的可朗读正文',data['messages'][0]['content'])
self.assertNotIn('旧有不输出JSON',data['messages'][0]['content'])
+7
View File
@@ -38,3 +38,10 @@ class ServerClockTests(unittest.TestCase):
LLMProvider({'LAN_LLM_TIME_ZONE': 'invalid/zone'})
with self.assertRaises(ValueError):
ServerClock(now=lambda: datetime(2026, 1, 1)).messages([])
def test_rebuilt_messages_replace_only_gateway_reference(self):
clock=ServerClock(now=lambda: datetime(2026, 1, 1, tzinfo=timezone.utc))
messages=clock.messages([{'role':'system','content':'persona'},{'role':'user','content':'public'}])
again=clock.messages(messages)
self.assertEqual(again[0]['content'].count('当前服务器时间:'),1)
self.assertIn('persona',again[0]['content'])
+3 -3
View File
@@ -25,11 +25,11 @@ compiler = ':'.join([jar('org.jetbrains.kotlin','kotlin-compiler-embeddable','2.
cp = ':'.join([stdlib, jar('com.squareup.okhttp3','okhttp','4.12.0'), jar('com.squareup.okio','okio-jvm','3.6.0')])
source = ROOT/'app/src/main/java/com/gorios/lanvoice'
suites = [
('session','ConnectionCheckKt', [source/'audio/PlaybackActivity.kt', source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']),
('session','ConnectionCheckKt', [source/'audio/PlaybackActivity.kt', source/'audio/VoiceSession.kt', source/'avatar/ActionController.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']),
('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt', source/'audio/PlaybackActivity.kt']),
('avatar','AvatarCheckKt', [source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']),
('avatar','AvatarCheckKt', [source/'avatar/EmotionActionManifest.kt', source/'avatar/ActionController.kt', source/'avatar/RoleVisualSelection.kt', source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']),
('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']),
('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
('protocol','ProtocolCheckKt', [source/'avatar/ActionController.kt', source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--suite', choices=[name for name, _, _ in suites])
+1 -1
View File
@@ -55,7 +55,7 @@ with tempfile.TemporaryDirectory(prefix='reply-structure-') as d:
print(json.dumps({'status':'passed' if passed else 'failed','results':rows,'live_configuration_changed':False,'real_weights_verified':False}))
raise SystemExit(0 if passed else 1)
'''
bundle={name:base64.b64encode((root/'gateway'/name).read_bytes()).decode() for name in ('llm_provider.py','reply_emotion.py')}
bundle={name:base64.b64encode((root/'gateway'/name).read_bytes()).decode() for name in ('llm_provider.py','reply_emotion.py','server_clock.py','action_reply.py')}
payload='bundle='+repr(bundle)+'\ncore='+repr(CORE)+'\n'+REMOTE
r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'],input=payload.encode(),capture_output=True,timeout=150)
if r.stdout:
+2 -1
View File
@@ -36,7 +36,8 @@ with tempfile.TemporaryDirectory(prefix='voice-gateway-stage-') as folder:
path=stage/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(base64.b64decode(content))
test_start=time.perf_counter()
result=subprocess.run([sys.executable,str(stage/'scripts/check-archive.py'),'--vad-model',str(root/'models/silero_vad.onnx')],cwd=stage,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=120,env={**os.environ,'PYTHONDONTWRITEBYTECODE':'1'})
summary={'status':'tests_passed' if result.returncode==0 else 'tests_failed','test_output':result.stdout.decode(errors='replace'),'test_elapsed_ms':round((time.perf_counter()-test_start)*1000,2),'applied':False,'expected_hashes':original}
summary={'status':'tests_passed' if result.returncode==0 else 'tests_failed','test_output':result.stdout.decode(errors='replace'),'test_elapsed_ms':round((time.perf_counter()-test_start)*1000,2),'applied':False,'expected_hashes':original,
'candidate_source_hashes':{name:hashlib.sha256((stage/name).read_bytes()).hexdigest() for name in deploy_files}}
if result.returncode: print(json.dumps(summary));raise SystemExit(1)
if apply:
if live_hashes()!=original:raise RuntimeError('source_changed_during_tests')
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
"""Verify and publish explicit code16+ stage candidate; no new visual asset approval."""
from pathlib import Path
import argparse
import hashlib
import json
import re
import subprocess
import urllib.request
import zipfile
ROOT=Path(__file__).resolve().parents[1]
TOOLS=Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0')
sha=lambda data:hashlib.sha256(data).hexdigest()
def run(*args):
return subprocess.check_output([str(arg) for arg in args],text=True,stderr=subprocess.STDOUT)
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--version-code',type=int,default=16)
args=parser.parse_args();assert args.version_code>=16
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk'
baseline=ROOT/'artifacts/lan-voice-v062-mouth-candidate-arm64-debug.apk'
baseline_sha=sha(baseline.read_bytes())
client=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
assert client['status']=='passed' and client['jvm_entry_points']==9
for name,digest in client['hashes'].items():assert sha((ROOT/name).read_bytes())==digest,'Untested source '+name
staged=json.loads((ROOT/'logs/voice-investigation/gateway-emotion-staged.json').read_text())
assert staged['status']=='tests_passed' and re.search(r'Ran 95 tests .*\n\nOK\s*$',staged['test_output'])
for name,digest in staged['candidate_source_hashes'].items():
assert sha((ROOT/'gateway'/name).read_bytes())==digest,'Gateway changed after staged tests: '+name
pixels=json.loads((ROOT/'logs/action-emotion/shader-golden/shader-golden.json').read_text())
assert pixels['status']=='passed' and len(pixels['cases'])==40
assert pixels['shaderSourceSha']==sha((ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt').read_bytes())
badging=run(TOOLS/'aapt','dump','badging',built)
for expected in ("name='com.gorios.lanvoice'",f"versionCode='{args.version_code}'", "versionName='0.7.0-stage-dev'",
"sdkVersion:'26'","targetSdkVersion:'34'","native-code: 'arm64-v8a'"):
assert expected in badging,expected
cert_pattern=r'Signer #1 certificate SHA-256 digest: (\w+)'
signature=run(TOOLS/'apksigner','verify','--verbose','--print-certs',built)
cert=re.search(cert_pattern,signature)[1]
assert cert==re.search(cert_pattern,run(TOOLS/'apksigner','verify','--print-certs',baseline))[1]
assert cert=='b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1'
for existing in (ROOT/'artifacts').glob('*.apk'):
info=run(TOOLS/'aapt','dump','badging',existing)
assert int(re.search(r"versionCode='(\d+)'",info)[1])<args.version_code,'Version occupied: '+existing.name
with zipfile.ZipFile(built) as new, zipfile.ZipFile(baseline) as old:
assets=lambda archive:{name for name in archive.namelist() if name.startswith('assets/avatar/') and not name.endswith('/')}
assert assets(new)==assets(old),'This stage must not silently activate or import unreviewed visuals'
for name in assets(old):
assert new.read(name)==old.read(name),name
if name.endswith('.mp4'):assert new.getinfo(name).compress_type==zipfile.ZIP_STORED
output=ROOT/f'artifacts/lan-voice-v070-stage-candidate-code{args.version_code}-arm64-debug.apk'
data=built.read_bytes()
with output.open('xb') as stream:stream.write(data)
digest=sha(data);checksum=f'{digest} {output.name}\n'.encode()
with output.with_suffix('.apk.sha256').open('xb') as stream:stream.write(checksum)
url='http://192.168.31.124:8080/'+output.name
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(url,timeout=15) as response:
assert response.status==200 and sha(response.read())==digest
with opener.open(url+'.sha256',timeout=15) as response:assert response.status==200 and response.read()==checksum
assert sha(baseline.read_bytes())==baseline_sha
report={'status':'stage_candidate','version':'0.7.0-stage-dev','version_code':args.version_code,'url':url,
'sha256':digest,'bytes':len(data),'certificate_sha256':cert,'http_bytes_verified':True,
'old_package_preserved_sha256':baseline_sha,'visual_assets':'unchanged runtime04 neutral candidate',
'emotion_action_activation':'pending Pi exact v2 manifest approval and media driver integration',
'device':'not_run','naturalness':'not_certified','perceived_latency_le_1s':'not_measured','paid_calls':0}
folder=ROOT/'logs/action-emotion';folder.mkdir(parents=True,exist_ok=True)
(folder/'delivery.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2))
if __name__=='__main__':main()
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Exactly four public local-Qwen requests, 160 tokens. No raw reply/keys/voice data."""
from pathlib import Path
import base64
import json
import subprocess
ROOT = Path(__file__).resolve().parents[1]
REMOTE = r'''
import asyncio, json, pathlib, ssl, subprocess, sys, tempfile, time, urllib.request
import httpx
root=pathlib.Path('/home/gorios-spark-2/lan-voice')
result={'status':'failed','paid_calls':0,'max_tokens':160,'rows':[],'device':'not_run'}
async def main():
ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem'))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
with opener.open('https://192.168.31.61:5011/health',timeout=5) as response:health=json.load(response)
if health.get('busy'):raise RuntimeError('busy_no_probe')
pid=subprocess.check_output(['systemctl','--user','show','lan-voice-gateway.service','-p','MainPID','--value'],text=True).strip()
env=dict(item.split('=',1) for item in pathlib.Path('/proc/'+pid+'/environ').read_bytes().decode().split('\0') if '=' in item)
from llm_provider import LLMProvider
from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply
from reply_emotion import SYSTEM_FRAGMENT
provider=LLMProvider(env)
assert provider.base_url=='http://127.0.0.1:8888/v1' and provider.model=='qwen3.8-27b' and provider.structured_output=='json_schema'
cases=[('fact','七乘八等于多少?只给出结果。',False),
('dance','请跳一段舞,然后自然问我一句。',True),
('sympathy','朋友比赛落选了,请简短安慰。',False),
('negation','不要跳舞,只说你好。',True)]
async with httpx.AsyncClient(timeout=40,trust_env=False) as client:
for name,text,available in cases:
system=SYSTEM_FRAGMENT+'\n'+ACTION_FRAGMENT+'\n网关实际可用动作:'+('dance' if available else '无')
url,headers,body=provider.request([{'role':'system','content':system},{'role':'user','content':text}],max_tokens=160,action_plan=True)
parser=ExpressionPrefix(1);raw='';finish='not_provided';done=False;prepare_ms=None;first_ms=None;chunks=0
start=time.monotonic()
async with client.stream('POST',url,headers=headers,json=body) as response:
response.raise_for_status()
async for line in response.aiter_lines():
if not line.startswith('data:'):continue
payload=line[5:].strip()
if payload=='[DONE]':done=True;break
data=json.loads(payload)
for choice in data.get('choices',[]):
value=choice.get('finish_reason')
if value is not None:finish=value if value in ('stop','length','content_filter','tool_calls','function_call') else 'unknown'
delta=choice.get('delta',{}).get('content') or ''
if not delta:continue
chunks+=1
if first_ms is None:first_ms=round((time.monotonic()-start)*1000,2)
raw+=delta
if parser.feed(delta,1) is not None:prepare_ms=round((time.monotonic()-start)*1000,2)
assert len(raw)<=8192
parsed=parse_action_reply(raw,finish,available)
try:keys=list(json.loads(raw))
except ValueError:keys=[]
row={'case':name,'http_status':response.status_code,'sse_done':done,'finish_reason':finish,
'top_level_fields':keys,'source':parsed.speech.source,'emotion':parsed.speech.emotion,'intensity':parsed.speech.intensity,
'reply_chars':len(parsed.speech.reply),'action':parsed.action,'action_reason':parsed.action_reason,
'after_valid':parsed.after is not None,'chunks':chunks,'first_ms':first_ms,'prepare_ms':prepare_ms,
'complete_ms':round((time.monotonic()-start)*1000,2),'header_final_consistent':parser.consistent(parsed,1)}
result['rows'].append(row)
assert done and finish=='stop' and parsed.speech.source=='model' and parsed.action_reason=='none','schema_or_budget_failed'
assert parsed.action==('dance' if name=='dance' else 'none'),'action_semantics_failed'
result.update(status='passed',provider=provider.model,mode=provider.structured_output,zone=provider.clock.zone.key,
capability_scope='four fixed public observations; prepare preload only, final validation required')
with tempfile.TemporaryDirectory(prefix='action-schema-probe-') as folder:
import base64
for name,content in sources.items():pathlib.Path(folder,name).write_bytes(base64.b64decode(content))
sys.path.insert(0,folder)
try:asyncio.run(main())
except Exception as error:
result['error_type']=type(error).__name__
if isinstance(error,RuntimeError):result['reason']=str(error)
if isinstance(error,httpx.HTTPStatusError):result['http_status']=error.response.status_code
print(json.dumps(result))
raise SystemExit(result['status']!='passed')
'''
sources = {name: base64.b64encode((ROOT/'gateway'/name).read_bytes()).decode() for name in
('llm_provider.py','server_clock.py','reply_emotion.py','action_reply.py')}
payload = 'sources='+repr(sources)+'\n'+REMOTE
run = subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5',
'gorios-spark-2@192.168.31.61','cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'],
input=payload.encode(),capture_output=True,timeout=190)
if run.stdout:
report = json.loads(run.stdout)
out=ROOT/'logs/action-emotion/schema-probe.json';out.parent.mkdir(parents=True,exist_ok=True)
out.write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2))
if run.stderr:print('Remote stderr present; contents suppressed.')
raise SystemExit(run.returncode)
+2 -4
View File
@@ -1,12 +1,10 @@
#!/usr/bin/env python3
"""Refresh recoverable source hashes while preserving observed upstream provenance."""
from pathlib import Path
import hashlib,json
import hashlib,json,re
root=Path(__file__).resolve().parents[1]/'gateway'
manifest=json.loads((root/'SOURCE_MANIFEST.json').read_text())
manifest['archive_baseline_commit']='19a7adccd9322986eb0646b165b9ce1cf2650cf2'
manifest['workspace_release']='0.5.1'
manifest['code_version']='0.7.1 (legacy health version; reply.emotion version 1 capability)'
manifest['code_version']=re.search(r"^VERSION = '([^']+)'",(root/'gateway.py').read_text(),re.M)[1]
for path in sorted(root.rglob('*')):
if not path.is_file():continue
name=path.relative_to(root).as_posix()
+49
View File
@@ -0,0 +1,49 @@
import com.gorios.lanvoice.avatar.*
import com.gorios.lanvoice.dialogue.RoleEmotion
fun actionCheck() {
val sha="a".repeat(64)
val statuses=mutableListOf<ActionStatus>()
var now=100L; var confirm: ((Boolean)->Unit)?=null
var playing=false;var finish: ((ActionEnd)->Unit)?=null
var release: (()->Unit)?=null
val picked=mutableListOf<String>()
val player=object: ActionPlayer {
override fun play(asset: ActionAsset, finished: (ActionEnd)->Unit, failed: ()->Unit) {
check(!playing);playing=true;picked.add(asset.id);finish=finished
}
override fun stop(released: ()->Unit) { release={ playing=false;released() } }
}
val pack=ReviewedActionPack(sha,listOf(ActionAsset("asset_01",1000),ActionAsset("asset_02",1200)))
val controller=ActionController(pack,player,{now},{confirm=it},{statuses.add(it)},choose={0})
fun plan(turn: Long)=ActionPlan("id".repeat(12)+turn,turn,sha,10000)
check(controller.offer(plan(1)))
check(controller.active && !playing && statuses.isEmpty()) // Intent is not recording-stop evidence.
confirm!!(true);check(playing && statuses.single().status=="started")
now+=1000;playing=false;finish!!(ActionEnd(true,true,true))
check(!controller.active && statuses.last().status=="completed")
check(controller.offer(plan(2)));confirm!!(true)
check(picked==listOf("asset_01","asset_02"))
val stale=finish!!
controller.cancel();check(controller.active) // No recording resume before music release fence.
check(statuses.last().status=="started")
release!!();check(!controller.active && statuses.last().status=="cancelled")
stale(ActionEnd(true,true,true));check(statuses.last().status=="cancelled")
check(controller.offer(plan(3)));confirm!!(false);release!!()
check(statuses.last().status=="failed" && picked.size==2)
check(controller.offer(plan(4)));confirm!!(true)
now+=10001;controller.tick();release!!();check(statuses.last().status=="failed")
val missing=ActionController(null,player,{now},{confirm=it},{statuses.add(it)})
check(missing.capability==null && !missing.offer(plan(5)))
val pts=List(97) { it*1_000_000L/24 }
val neutral=TalkPackage("neutral",RoleEmotion.NEUTRAL,sha,sha,pts,pts,true)
val happy=TalkPackage("happy",RoleEmotion.HAPPY,"b".repeat(64),"b".repeat(64),pts,pts,true)
val slight=RoleVisualSelector.select(RoleEmotion.HAPPY,2,listOf(neutral,happy),"neutral")
check(slight.selectedIntensity==2 && slight.visualIntensity==1 && slight.reason=="slight_only")
val mismatch=RoleVisualSelector.select(RoleEmotion.HAPPY,1,listOf(neutral,happy.copy(mouthBodySha=sha)),"neutral")
check(mismatch.selectedEmotion==RoleEmotion.HAPPY && mismatch.visualEmotion==RoleEmotion.NEUTRAL && mismatch.degraded)
val shifted=RoleVisualSelector.select(RoleEmotion.HAPPY,1,listOf(neutral,happy.copy(mouthPtsUs=pts.map { it+1 })),"neutral")
check(shifted.packageId=="neutral")
println("PASS: action fixture record-stop/music-release/return-A/TTL/cancel/stale/no-repeat and expression own-body/PTS/slight-only selection; no device/naturalness claim")
}
+2
View File
@@ -6,6 +6,8 @@ import android.media.MediaPlayer
import android.view.TextureView
fun main() {
actionCheck()
emotionActionCheck()
checkContinuous()
checkEngineering()
checkSafeDriver()
+36
View File
@@ -0,0 +1,36 @@
import com.gorios.lanvoice.avatar.*
fun emotionActionCheck() {
val sha="b".repeat(64)
val runtime=continuousPack().let { old -> old.copy(apertureMode=true,patches=old.patches.map { patch ->
patch.copy(levels=List(5) { MouthPatchLevel(it,it/4f,"patches/${patch.frameIndex}-$it.png",sha) })
}) }
fun clip(audio: Boolean)=mapOf<String,Any?>("path" to "clips/bridge.mp4","sha256" to sha,"hasAudio" to audio,
"frameCount" to 48,"ptsUs" to List(48) { it*1_000_000L/24 },"durationUs" to 2_000_000L)
fun edge(id: String,from: String,to: String)=mapOf<String,Any?>("id" to id,"from" to from,"to" to to,
"fromAnchor" to "A","toAnchor" to "A","fromFrame" to 96,"toFrame" to 0,"clip" to clip(false))
fun conversation(id: String)=mapOf<String,Any?>("id" to id,"emotion" to if(id=="neutral") "neutral" else "happy",
"visualIntensity" to if(id=="neutral") 0 else 1,"mouthBodySha256" to sha,
"runtimeManifest" to mapOf("path" to "$id/manifest.json","sha256" to sha),"entryAnchor" to "A","exitAnchor" to "A",
"legalExitFrames" to listOf(96),"loopEdge" to "$id-loop")
val edges=listOf(edge("neutral-loop","neutral","neutral"),edge("happy-loop","happy","happy"),
edge("in","neutral","happy"),edge("out","happy","neutral"))
val actions=listOf("asset_01","asset_02").map { mapOf<String,Any?>("id" to it,"kind" to "dance",
"mouthAllowed" to false,"disallowTALK" to true,"entryAnchor" to "A","returnAnchor" to "A",
"clip" to clip(true),"audioEndUs" to 1_900_000L) }
val root=mapOf<String,Any?>("schemaVersion" to 2,"identityId" to "a01","packId" to "a01-expression-action-v1",
"fallbackPackageId" to "neutral","conversationPackages" to listOf(conversation("neutral"),conversation("happy")),
"edges" to edges,"actions" to actions)
fun read(data: Map<String,Any?>,pin: String=sha)=EmotionActionManifest.read(data,sha,pin) { _,hash -> if(hash==sha) runtime else null }
check(read(root)?.actionPack?.assets?.size==2)
check(read(root+("actions" to emptyList<Any>()))?.actionPack==null)
check(read(root,"a".repeat(64))==null)
check(read(root+("approved" to true),"")==null)
check(read(root+("conversationPackages" to listOf(conversation("neutral"),conversation("happy")+("mouthBodySha256" to "a".repeat(64)))))==null)
check(read(root+("edges" to edges.dropLast(1)))==null)
for(change in listOf(mapOf("mouthAllowed" to true),mapOf("disallowTALK" to false),mapOf("returnAnchor" to "B"),
mapOf("audioEndUs" to 2_000_001L),mapOf("clip" to clip(false)),mapOf("clip" to clip(true)+("path" to "../escape.mp4")))) {
check(read(root+("actions" to listOf(actions[0]+change,actions[1])))==null)
}
println("PASS: production v2 index exact external pin/own body-mouth SHA/runtime04/complete bridges/music bounds/no TALK, synthetic metadata only")
}
+6 -1
View File
@@ -31,7 +31,12 @@ fun main() {
val errors = CopyOnWriteArrayList<Exception>()
capture.start(onFrame = frames::add, onError = errors::add)
check(AudioRecord.partialReady.await(2, TimeUnit.SECONDS))
capture.stop()
val confirmed = CountDownLatch(1)
capture.stopAndConfirm { stopped ->
check(stopped && AudioRecord.activeDevices.get()==0)
confirmed.countDown()
}
check(confirmed.await(2, TimeUnit.SECONDS))
check(AudioRecord.released.await(2, TimeUnit.SECONDS))
check(errors.isEmpty())
check(frames.size == expectedCount) // 100B unfinished tail must not be sent
+3 -3
View File
@@ -19,9 +19,9 @@ class AudioRecord(source: Int, rate: Int, channel: Int, encoding: Int, buffer: I
init { if (activeDevices.incrementAndGet() > 1) overlaps.incrementAndGet() }
private val mode = scenario
val state = if (mode == "init") 0 else STATE_INITIALIZED
val recordingState = RECORDSTATE_RECORDING
var recordingState = 1
val audioSessionId = 1
fun startRecording() { if (mode == "start") throw SecurityException("synthetic mic revocation") }
fun startRecording() { if (mode == "start") throw SecurityException("synthetic mic revocation"); recordingState = RECORDSTATE_RECORDING }
private val stopped = java.util.concurrent.CountDownLatch(1)
private val ready = partialReady
private val done = released
@@ -45,6 +45,6 @@ class AudioRecord(source: Int, rate: Int, channel: Int, encoding: Int, buffer: I
streamOffset += count
return count
}
fun stop() { stopped.countDown() }
fun stop() { recordingState = 1; stopped.countDown() }
fun release() { Thread.sleep(20); activeDevices.decrementAndGet(); done.countDown() }
}
+6
View File
@@ -0,0 +1,6 @@
package org.json
class JSONArray {
private val values = mutableListOf<String>()
fun put(value: String): JSONArray { values.add(value); return this }
override fun toString() = values.joinToString(",", "[", "]") { "\"$it\"" }
}
+50
View File
@@ -0,0 +1,50 @@
import android.os.Handler
import com.gorios.lanvoice.audio.*
import com.gorios.lanvoice.avatar.*
import com.gorios.lanvoice.net.*
fun checkActionSession() {
val sha="a".repeat(64);val states=mutableListOf<VoiceUiState>()
val prepared=mutableListOf<com.gorios.lanvoice.dialogue.ReplyEmotion?>()
var plays=0;var stopped=0;var ended: ((ActionEnd)->Unit)?=null
val player=object: ActionPlayer {
override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) { plays++;ended=finished }
override fun stop(released: ()->Unit) { stopped++;released() }
}
val session=VoiceSession("localhost",5011,states::add,
reviewedActionPack=ReviewedActionPack(sha,listOf(ActionAsset("asset_01",1000),ActionAsset("asset_02",1000))),
actionPlayer=player,onPrepareExpression=prepared::add)
fun set(name: String,value: Any) { session.javaClass.getDeclaredField(name).apply { isAccessible=true }.set(session,value) }
val dialogue=session.javaClass.getDeclaredField("dialogue").apply { isAccessible=true }.get(session) as DialogueClient
val socket=FakeSocket();dialogue.setField("socket",socket);dialogue.setField("ready",true)
set("foreground",true);set("state",VoiceUiState(connection=ConnectionStatus.CONNECTED))
val onEvent=session.javaClass.getDeclaredMethod("onEvent",ServerEvent::class.java).apply { isAccessible=true }
fun event(type: String,kind: EventKind,turn: Long,fields: Map<String,Any> = emptyMap()) {
onEvent.invoke(session,ServerEvent(type,kind,Payload(turn=turn,fields=fields)))
}
session.startVoice();event("listen",EventKind.LISTEN,7,mapOf("state" to "start"))
event("reply.emotion.prepare",EventKind.EXPRESSION_PREPARE,7,mapOf("seq" to 1L,"emotion" to "happy","intensity" to 1))
check(prepared.last()?.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.HAPPY)
check(states.last().replyEmotion.turnId==null) // Preload never becomes displayed emotion.
event("reply.emotion.prepare",EventKind.EXPRESSION_PREPARE,6,mapOf("seq" to 2L,"emotion" to "sad","intensity" to 1))
check(prepared.last()?.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.HAPPY)
AudioCapture.confirmStopsAutomatically=false
val oldFrame=checkNotNull(AudioCapture.lastFrame)
event("action.plan",EventKind.ACTION,7,mapOf("action_id" to "x".repeat(24),"pack_sha256" to sha,"ttl_ms" to 10000L))
check(states.last().actionActive && plays==0)
val before=DialogueProtocol.uplinks.size
oldFrame(ByteArray(640));Handler.drain();check(DialogueProtocol.uplinks.size==before)
checkNotNull(AudioCapture.lastStopped)(true);Handler.drain();check(plays==1)
val starts=AudioCapture.starts
session.setMicrophoneMuted(true);session.setMicrophoneMuted(false);session.interrupt()
check(AudioCapture.starts==starts)
val enqueued=AudioPlayback.enqueued
session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true }.invoke(session,DownlinkFrame(7))
check(enqueued==AudioPlayback.enqueued)
val stale=checkNotNull(ended)
session.background();Handler.drain()
check(stopped==1 && !states.last().actionActive && !states.last().voiceActive)
stale(ActionEnd(true,true,true));Handler.drain();check(plays==1)
session.release();AudioCapture.confirmStopsAutomatically=true
println("PASS: actual VoiceSession action plan→capture cleanup fence→player, queued mic/downlink dropped, prepare-only/old-turn, no voice barge, background cancel; doubles only")
}
+3 -1
View File
@@ -5,9 +5,11 @@ import com.gorios.lanvoice.net.DownlinkFrame
enum class AecAvailability { AVAILABLE, UNAVAILABLE, UNKNOWN }
// No audio devices in callback propagation tests.
class AudioCapture {
companion object { var lastFrame: ((ByteArray) -> Unit)? = null; var lastError: ((Exception) -> Unit)? = null; var starts = 0 }
companion object { var lastFrame: ((ByteArray) -> Unit)? = null; var lastError: ((Exception) -> Unit)? = null; var starts = 0
var confirmStopsAutomatically = true; var lastStopped: ((Boolean)->Unit)? = null }
fun aecAvailability() = AecAvailability.UNKNOWN
fun start(onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit, onDiagnostic: (String) -> Unit = {}) { starts++; lastFrame = onFrame; lastError = onError; onDiagnostic("AudioRecord initialization ok") }
fun stopAndConfirm(confirmed: (Boolean) -> Unit) { lastStopped = confirmed; if(confirmStopsAutomatically) confirmed(true) }
fun stop() {}
fun release() {}
}
+1
View File
@@ -3,6 +3,7 @@ import com.gorios.lanvoice.audio.*
import com.gorios.lanvoice.net.*
fun checkCallControls() {
checkActionSession()
val states = mutableListOf<VoiceUiState>()
val session = VoiceSession("localhost",5011,states::add)
fun set(name: String,value: Any) { session.javaClass.getDeclaredField(name).apply { isAccessible=true }.set(session,value) }
+3 -2
View File
@@ -8,13 +8,14 @@ class Payload(private val ok: Boolean = true, private val turn: Long? = null, pr
fun optInt(key: String, fallback: Int) = if (key == "context_face_cue_version") 1 else fallback
fun opt(key: String): Any? = if (key == "turn_id") turn else fields[key]
}
enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT, REPLY_EMOTION }
enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, SPEECH }
data class ServerEvent(val type: String, val kind: EventKind, val payload: Payload)
class DownlinkFrame(val turnId: Long = 0, val sequence: Long = 0, val pcm16: ByteArray = ByteArray(2))
object DialogueProtocol {
val uplinks = mutableListOf<Triple<Long, Long, Int>>()
fun actionStatus(value: com.gorios.lanvoice.avatar.ActionStatus) = "action_status"
fun faceCue(turn: Long, observation: com.gorios.lanvoice.expression.FaceCueObservation, age: Long) = "face_cue"
fun hello() = "hello"
fun hello(actionPackSha: String? = null) = "hello"
fun listen(start: Boolean) = "listen"
fun abort(turn: Long) = "abort"
fun playbackDrained(turn: Long) = "drained"