feat: inject request-local server time and freeze action asset contract
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
# Action/emotion runtime v2 contract
|
||||
|
||||
Development baseline: `e3ee004d29ac472997a813fbdb641ba4983fa5ce` (clean, remote main matched).
|
||||
This contract reserves the interface; it grants no naturalness/publication approval.
|
||||
|
||||
Asset owner: Localv-i-asset w8:p1. Code/importer owner: baji-action-emotion.
|
||||
No paid calls by code owner. Existing owner directories/previews are read only.
|
||||
|
||||
Deliver a new directory, `manifest.json` exact bytes SHA256 and preview/evidence paths.
|
||||
Manifest `schemaVersion:2`, `identityId:a01`, `packId`, `fallbackPackageId`,
|
||||
`conversationPackages`, `edges`, `actions`, `files`. Paths are relative without `..`/URLs;
|
||||
every file has SHA256/bytes. Pi approval pins exact manifest SHA outside the manifest.
|
||||
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
|
||||
(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.
|
||||
Happy/sad are slightly only, including model intensity2. Body is silent.
|
||||
No layer means whole-package fallback, never a neutral mouth over another body.
|
||||
Provide 0.9/1.1/1.2 aperture previews; Pi chooses before import.
|
||||
|
||||
Edges: `id`, `from`, `to`, `fromAnchor`, `toAnchor`, `fromFrame`, `toFrame`,
|
||||
`clip:{path,sha256,width,height,frameCount,ptsUs,durationUs,hasAudio:false}`.
|
||||
Each package declares `entryAnchor`, `exitAnchor`, `legalExitFrames`, `loopEdge`.
|
||||
Frame indices/PTS are actual decoded values. Every changed body phase requires a
|
||||
reviewed edge, no arbitrary alpha cut. Supply dense seam frames, real-speed loops
|
||||
and full-scale/close previews, not just matching endpoints.
|
||||
|
||||
Actions: exactly `asset_01`, `asset_02`, `kind:dance`, `mouthAllowed:false`,
|
||||
`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
|
||||
explicitly hashed sequential segments with reviewed edges. Music must actually
|
||||
exist, end naturally, and actor must not talk/sing. Source/music provenance and
|
||||
job/fee ledger stay in owner storage; Git stores metadata only.
|
||||
|
||||
Client advertises only Pi-pinned, machine-validated packs: `action_protocol:1`,
|
||||
`action_pack_sha256`, `action_kinds:[dance]`. Server has independent exact SHA
|
||||
allowlist/duration; unknown clients/packs get no actions. Server creates opaque
|
||||
action_id, connection generation/turn binding and TTL; never accepts URLs from LLM.
|
||||
`action.plan` is emitted only after pre-reply playback.drained. Client stops and
|
||||
confirms AudioRecord before playing; `action.status` started/completed/cancelled/
|
||||
failed echoes action_id/turn_id. Completed requires video_ended, audio_stopped,
|
||||
idle_restored, mic_stopped, and minimum reviewed duration elapsed. Settings cancel,
|
||||
background, disconnect, new turn and expiry discard the after reply.
|
||||
|
||||
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.
|
||||
@@ -3,11 +3,13 @@ import os
|
||||
from copy import deepcopy
|
||||
from urllib.parse import urlsplit
|
||||
from reply_emotion import REPLY_SCHEMA
|
||||
from server_clock import ServerClock
|
||||
|
||||
|
||||
class LLMProvider:
|
||||
def __init__(self, environ=None):
|
||||
env = os.environ if environ is None else environ
|
||||
self.clock = ServerClock(env.get('LAN_LLM_TIME_ZONE', 'Asia/Shanghai'))
|
||||
self.base_url = env.get('LAN_LLM_BASE_URL', 'http://127.0.0.1:8888/v1').rstrip('/')
|
||||
self.model = env.get('LAN_LLM_MODEL', 'qwen3.8-27b')
|
||||
self.api_key = env.get('LAN_LLM_API_KEY', '')
|
||||
@@ -31,7 +33,7 @@ class LLMProvider:
|
||||
raise ValueError('invalid LLM structured output mode')
|
||||
|
||||
def request(self, messages, *, max_tokens=64):
|
||||
body = {'model': self.model, 'messages': messages, 'max_tokens': max_tokens, 'temperature': 0.3, 'stream': True}
|
||||
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':
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Request-local wall clock. Durations/deadlines must continue using monotonic time."""
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
|
||||
class ServerClock:
|
||||
def __init__(self, zone='Asia/Shanghai', now=None):
|
||||
self.zone = ZoneInfo(zone) # Invalid configuration fails before any HTTP request.
|
||||
self.now = now or (lambda: datetime.now(timezone.utc))
|
||||
|
||||
def messages(self, messages):
|
||||
copied = [dict(message) for message in messages]
|
||||
systems = [message['content'] 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 + '。这是本次请求的时间参考,不代表用户所在地。')
|
||||
return [{'role': 'system', 'content': '\n\n'.join(systems + [reference])}] + [
|
||||
message for message in copied if message.get('role') != 'system']
|
||||
@@ -56,7 +56,9 @@ class ProviderTests(unittest.TestCase):
|
||||
url, headers, body = provider.request(messages)
|
||||
self.assertEqual(url, 'http://192.168.31.53:4000/v1/chat/completions')
|
||||
self.assertEqual(headers['Authorization'], 'Bearer unit-key')
|
||||
self.assertEqual(body['messages'], messages)
|
||||
self.assertEqual(body['messages'][1:], messages[1:])
|
||||
self.assertTrue(body['messages'][0]['content'].startswith(messages[0]['content']))
|
||||
self.assertIn('时区:Asia/Shanghai', body['messages'][0]['content'])
|
||||
self.assertEqual(body['max_tokens'], 64)
|
||||
self.assertTrue(body['stream'])
|
||||
self.assertNotIn('chat_template_kwargs', body)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import copy
|
||||
from datetime import datetime, timezone
|
||||
import unittest
|
||||
from zoneinfo import ZoneInfoNotFoundError
|
||||
|
||||
from llm_provider import LLMProvider
|
||||
from server_clock import ServerClock
|
||||
|
||||
|
||||
class ServerClockTests(unittest.TestCase):
|
||||
def test_each_actual_request_crosses_day_and_year_without_mutation(self):
|
||||
moments = iter([datetime(2026, 12, 31, 15, 59, 59, tzinfo=timezone.utc),
|
||||
datetime(2026, 12, 31, 16, 0, 1, tzinfo=timezone.utc)])
|
||||
provider = LLMProvider({})
|
||||
provider.clock = ServerClock(now=lambda: next(moments))
|
||||
messages = [{'role': 'system', 'content': 'persona'}, {'role': 'user', 'content': 'public'}]
|
||||
original = copy.deepcopy(messages)
|
||||
first = provider.request(messages)[2]['messages']
|
||||
second = provider.request(messages)[2]['messages']
|
||||
self.assertIn('2026-12-31T23:59:59+08:00', first[0]['content'])
|
||||
self.assertIn('2027-01-01T00:00:01+08:00', second[0]['content'])
|
||||
self.assertEqual(messages, original)
|
||||
self.assertEqual(second[0]['content'].count('当前服务器时间:'), 1)
|
||||
|
||||
def test_zone_and_single_system_for_each_provider(self):
|
||||
for model in ('qwen3.8-27b', 'doubao-seed-2-1-pro'):
|
||||
provider = LLMProvider({'LAN_LLM_MODEL': model, 'LAN_LLM_TIME_ZONE': 'America/New_York'})
|
||||
provider.clock.now = lambda: datetime(2026, 1, 1, 0, 0, tzinfo=timezone.utc)
|
||||
body = provider.request([{'role': 'system', 'content': 'a'},
|
||||
{'role': 'system', 'content': 'b'}, {'role': 'user', 'content': 'public'}])[2]
|
||||
self.assertEqual(sum(m['role'] == 'system' for m in body['messages']), 1)
|
||||
self.assertIn('2025-12-31T19:00:00-05:00', body['messages'][0]['content'])
|
||||
self.assertIn('时区:America/New_York', body['messages'][0]['content'])
|
||||
self.assertEqual('chat_template_kwargs' in body, model.startswith('qwen'))
|
||||
|
||||
def test_invalid_zone_and_naive_clock_fail_closed(self):
|
||||
with self.assertRaises(ZoneInfoNotFoundError):
|
||||
LLMProvider({'LAN_LLM_TIME_ZONE': 'invalid/zone'})
|
||||
with self.assertRaises(ValueError):
|
||||
ServerClock(now=lambda: datetime(2026, 1, 1)).messages([])
|
||||
Reference in New Issue
Block a user