OneAlign / web /server /app-api.mjs
loveaa's picture
Home Pulse 1.2: app interface, recommended event policies and independent location reminders
133b124 verified
Raw History Blame Contribute Delete
31.2 kB
import fs from 'node:fs'
import path from 'node:path'
import {randomBytes,randomUUID,createHash,timingSafeEqual} from 'node:crypto'
import {API_VERSION,routes,openapi} from './app-contract.mjs'
import {writeAtomic} from './atomic-file.mjs'
export const WORKSPACE_TOKEN=/^[a-f0-9]{64}$/
const DAY=86400000,TERMINAL=new Set(['verified','failed','cancelled','expired','verification_failed'])
export class AppError extends Error{
constructor(status,code,message,details){super(message);Object.assign(this,{status,code,details})}
}
const fail=(status,code,message,details)=>{throw new AppError(status,code,message,details)}
const digest=value=>createHash('sha256').update(value).digest('hex')
const canonical=value=>JSON.stringify(value,(_,v)=>v&&typeof v==='object'&&!Array.isArray(v)?Object.fromEntries(Object.keys(v).sort().map(k=>[k,v[k]])):v)
const equal=(a,b)=>{const x=Buffer.from(a||''),y=Buffer.from(b||'');return !!x.length&&x.length===y.length&&timingSafeEqual(x,y)}
const noImages=value=>JSON.parse(JSON.stringify(value,(key,v)=>['image','annotated','pairImage','referenceImage','annotatedReference','targetCrop','evidence'].includes(key)?undefined:v))
export function appEnvelope(data,requestId=randomUUID(),now=Date.now()){
return {data,requestId,serverTime:new Date(now).toISOString(),apiVersion:API_VERSION}
}
export function appError(error,requestId=randomUUID(),now=Date.now()){
if(error?.code&&/^E(?:PERM|ACCES|NOENT|NOSPC|IO|BUSY)$/.test(error.code))error=new AppError(503,'STORAGE_UNAVAILABLE','记录暂时未保存,请稍后重新查询状态')
const validation=error?.name==='ZodError'
const status=validation?422:error.status||502
return {status,body:{error:{code:validation?'VALIDATION_ERROR':error.code||'UPSTREAM_FAILED',message:validation?'请检查请求字段':error.message||'服务暂时不可用',retryable:[429,502,503,504].includes(status),...(validation?{details:error.issues.map(x=>({path:x.path.join('.'),message:x.message}))}:error.details?{details:error.details}:{})},requestId,serverTime:new Date(now).toISOString(),apiVersion:API_VERSION}}
}
export function appToken(req){
const auth=String(req.headers.authorization||'')
const token=auth.startsWith('Bearer ')?auth.slice(7):String(req.headers['x-home-pulse-workspace']||'')
return WORKSPACE_TOKEN.test(token)?token:null
}
export function appPublic(req,url){
if(req.method==='GET'&&url.pathname==='/api/v1/openapi.json')return {status:200,body:openapi()}
if(req.method==='POST'&&url.pathname==='/api/v1/sessions'){
const token=randomBytes(32).toString('hex')
return {status:201,body:appEnvelope({token,workspaceId:'ws_'+digest(token).slice(0,24),authentication:'workspace_bearer',saveIn:'Keychain or Android Keystore'})}
}
return null
}
export async function readAppBody(req){
let size=0;const chunks=[]
for await(const chunk of req){size+=chunk.length;if(size>6*1024*1024)fail(413,'BODY_TOO_LARGE','单次请求不能超过 6 MB');chunks.push(chunk)}
try{return JSON.parse(Buffer.concat(chunks).toString('utf8')||'{}')}catch{fail(400,'INVALID_JSON','请求正文需要有效 JSON')}
}
export function createAppApi(root,{grounded,journal,metrics,clock=Date.now}={}){
const dir=path.join(root,'.local','app-api'),file=path.join(dir,'state.json')
fs.mkdirSync(dir,{recursive:true})
const empty={version:1,clients:{},devices:{},hardwareEvents:{},commands:{},events:{},watchMeta:{},setupMeta:{},frames:{},idempotency:{}}
let db=fs.existsSync(file)?{...empty,...JSON.parse(fs.readFileSync(file,'utf8'))}:empty
const inFlight=new Map(),busyWatches=new Set()
const now=()=>clock(),iso=()=>new Date(now()).toISOString(),service=()=>grounded()
const save=()=>writeAtomic(file,JSON.stringify(db))
const list=kind=>Object.values(db[kind])
const get=(kind,id)=>db[kind][id]||fail(404,'NOT_FOUND','记录不存在')
const legacy=async(method,route,body={})=>{
try{return await service().handle(method,new URL(route,'http://localhost'),body)}
catch(e){if(e.name==='ZodError'||e instanceof AppError)throw e;if(/记录不存在/.test(e.message))fail(404,'NOT_FOUND',e.message);if(/请先|请确认|请重新|来源|时间|已收起|未采纳|顺序|重复/.test(e.message))fail(409,'PRECONDITION_FAILED',e.message);throw e}
}
const repoGet=(kind,id)=>{try{return service().repo.get(kind,id)}catch{fail(404,'NOT_FOUND','记录不存在')}}
const client=id=>get('clients',id)
const isOnline=d=>d.online&&d.lastSeen&&now()-Date.parse(d.lastSeen)<=45000&&db.clients[d.clientId]?.sdkReady&&now()-Date.parse(db.clients[d.clientId].lastSeen)<=45000
const device=id=>get('devices',id)
const assertOwner=(d,clientId)=>{client(clientId);if(d.clientId!==clientId)fail(403,'EXECUTOR_MISMATCH','请由连接这台设备的 App 执行')}
const assertLive=d=>{if(!isOnline(d))fail(409,'DEVICE_OFFLINE','设备接入已中断,请打开已连接设备的 App')}
const assertView=(d,viewRevision)=>{if(d.viewRevision!==viewRevision)fail(409,'VIEW_CHANGED','观察位置变了,请重新确认范围',{viewRevision:d.viewRevision})}
const assertCapturePolicy=(d,policy)=>{if(policy?.mode==='event'&&!d.capabilities.events)fail(422,'EVENT_SOURCE_UNAVAILABLE','这台设备尚未提供事件,请选择按需检查');if(policy?.mode==='scheduled'&&!d.capabilities.scheduledCapture)fail(422,'SCHEDULED_CAPTURE_UNAVAILABLE','这台设备尚未提供定时取图,请使用设备事件或按需检查')}
const assertFresh=(at,maxAge=120000)=>{const t=Date.parse(at);if(!Number.isFinite(t)||t>now()+1000||now()-t>maxAge)fail(409,'STALE_EVIDENCE','请获取当前画面或设备状态')}
function invalidateView(d){
d.viewRevision++;d.viewChangedAt=iso()
for(const m of list('watchMeta'))if(m.deviceId===d.id&&m.state!=='replaced')m.needsReconfirmation=true
}
function sweep(){
let changed=false
for(const c of list('commands')){
if(['awaiting_confirmation','queued'].includes(c.status)&&Date.parse(c.expiresAt)<=now()){c.status='expired';c.revision++;c.updatedAt=iso();changed=true}
if(c.status==='executing'&&Date.parse(c.executionDeadline)<=now()){c.status='result_unknown';c.revision++;c.updatedAt=iso();changed=true}
}
for(const [key,row] of Object.entries(db.idempotency)){
if(row.status==='running'&&!inFlight.has(key)){row.status='indeterminate';changed=true}
if(now()-row.at>(row.retentionMs||DAY)){delete db.idempotency[key];changed=true}
}
for(const kind of ['hardwareEvents','frames'])for(const [key,row] of Object.entries(db[kind]))if(now()-Date.parse(row.receivedAt)>DAY){delete db[kind][key];changed=true}
for(const kind of ['events','commands'])for(const [key,row] of Object.entries(db[kind]))if(now()-Date.parse(row.updatedAt||row.createdAt)>30*DAY&&(kind==='events'?row.closedAt:TERMINAL.has(row.status))){delete db[kind][key];changed=true}
for(const [id,m] of Object.entries(db.setupMeta))if(now()-Date.parse(m.createdAt)>DAY){
let s;try{s=service().repo.get('setup',id)}catch{delete db.setupMeta[id];changed=true;continue}
if(!s.activatedId){service().repo.remove('setup',id);delete db.setupMeta[id];changed=true}
}
// Expired raw evidence is removed from the durable checkpoint and the in-memory engine together.
for(const m of list('watchMeta')){
let state;try{state=service().repo.get('state',m.id)}catch{continue}
let purged=false
state.observations=(state.observations||[]).filter(o=>{if(now()-Date.parse(o.capturedAt)>30*DAY){purged=true;return false}return true}).map(o=>{if(o.evidence&&now()-Date.parse(o.capturedAt)>DAY){purged=true;return {...o,evidence:null}}return o})
if(purged&&!busyWatches.has(m.id)){service().repo.save('state',m.id,state);service().forget(m.id)}
}
if(changed)save()
}
const timer=setInterval(sweep,60000);timer.unref()
function checkAction(d,c){
if(!d.capabilities.actions.includes(c.action))fail(422,'UNSUPPORTED_ACTION','这台设备不支持此操作')
const p=c.params,cap=d.capabilities
if(c.action==='night_vision.set'&&!cap.nightVisionModes.some(m=>m.key===p.modeKey))fail(422,'UNSUPPORTED_OPTION','请选择设备实际支持的夜视模式')
if(c.action==='ptz.preset.goto'&&!cap.presetIndices.includes(p.index))fail(422,'UNSUPPORTED_OPTION','这个预置位置不可用')
if(c.action==='alarm.set'&&!cap.alarmTypes.includes(p.type))fail(422,'UNSUPPORTED_OPTION','这个报警方式不可用')
if(c.action==='motion_detection.set'&&p.types.some(t=>!cap.detectionTypes.includes(t)))fail(422,'UNSUPPORTED_OPTION','请选择设备实际支持的检测类型')
}
const publicCommand=c=>{const {executionToken,...rest}=c;return rest}
const revise=(row,patch)=>Object.assign(row,patch,{revision:row.revision+1,updatedAt:iso()})
const expectRevision=(row,n)=>{if(row.revision!==n)fail(409,'REVISION_CONFLICT','状态已更新,请刷新后再操作',{revision:row.revision})}
function watch(id){
const s=repoGet('registration',id),m=db.watchMeta[id]
if(!m)fail(409,'WATCH_NOT_BOUND','这份关注尚未绑定 App 设备,请重新确认画面来源')
return {s,m,d:device(m.deviceId)}
}
function watchPublic(id,full=false){
const {s,m,d}=watch(id)
let state;try{state=service().repo.get('state',id)}catch{/* No observation yet. */}
const last=state?.at,fresh=last&&now()-Date.parse(last)<120000
const confirmed=state?.observations?.find(o=>!o.unknown&&!o.pending)?.capturedAt
return {id,request:s.request,title:s.plan.title,plan:s.plan,binding:full?s.binding:noImages(s.binding),memoryId:s.memoryId||null,confirmedAt:s.confirmedAt,...m,
observationStatus:m.state!=='active'?m.state:m.needsReconfirmation?'needs_reconfirmation':!isOnline(d)?'connection_interrupted':fresh?'recently_checked':m.capturePolicy?.mode==='event'?'waiting_event':m.capturePolicy?.mode==='manual'?'ready_for_check':m.capturePolicy?.mode==='scheduled'?'waiting_schedule':'awaiting_evidence',
lastConfirmedAt:confirmed||null,lastObservedAt:state?.observations?.[0]?.capturedAt||null,lastResult:state?.text||null,sourceOnline:!!isOnline(d),currentViewRevision:d.viewRevision,observations:(state?.observations||[]).slice(0,20)}
}
function ensureSetup(id){
const setup=repoGet('setup',id),meta=db.setupMeta[id]
if(!meta)fail(409,'SETUP_NOT_BOUND','请通过 App 接口重新准备这份设置')
const d=device(meta.deviceId);assertLive(d);assertView(d,meta.viewRevision)
return {setup,meta,d}
}
async function activate(body){
const {meta,d}=ensureSetup(body.setupId)
if(!d.capabilities.frames)fail(409,'FRAME_SOURCE_UNAVAILABLE','当前设备无法提供观察画面')
assertCapturePolicy(d,meta.capturePolicy)
const intervalSeconds=meta.capturePolicy?.intervalSeconds||300
const r=await legacy('POST','/api/setup/activate',{...body,interval:intervalSeconds})
db.watchMeta[r.id]||={id:r.id,deviceId:d.id,viewRevision:meta.viewRevision,state:'active',needsReconfirmation:false,createdAt:iso(),intervalSeconds,capturePolicy:meta.capturePolicy,locationAlerts:meta.locationAlerts,ruleAttention:meta.ruleAttention,category:meta.category||'routine',attentionLevel:meta.attentionLevel??2}
save();return watchPublic(r.id)
}
function removeWatch(id,deleteMemory){
if(busyWatches.has(id))fail(409,'OBSERVATION_IN_PROGRESS','本次观察正在完成,请稍后删除')
if(list('commands').some(c=>c.watchId===id&&['executing','result_unknown','awaiting_verification'].includes(c.status)))fail(409,'COMMAND_UNRESOLVED','设备操作结果还需确认,请先处理这条操作')
const {s}=watch(id)
for(const kind of ['registration','state'])try{service().repo.remove(kind,id)}catch{/* Absent optional state. */}
try{service().repo.remove('setup',s.setupId)}catch{/* A setup may already have expired. */}
delete db.setupMeta[s.setupId]
if(deleteMemory&&s.memoryId){
const dependencies=list('watchMeta').filter(m=>m.id!==id).filter(m=>{try{return repoGet('registration',m.id).memoryId===s.memoryId}catch{return false}})
if(!dependencies.length)try{service().repo.remove('memory',s.memoryId)}catch{/* Already deleted. */}
}
delete db.watchMeta[id];service().forget(id)
journal?.().removeWhere?.(r=>r.itemId===id||r.itemId===s.setupId)
for(const kind of ['events','frames','commands'])for(const [key,row] of Object.entries(db[kind]))if(row.watchId===id)delete db[kind][key]
}
function eraseCachedResults(){
for(const row of Object.values(db.idempotency))if(row.status==='completed')row.response=appError(new AppError(410,'RESULT_DELETED','关联资料已删除,请重新读取当前状态'))
}
function recordNotices(watchId,result){
const {m}=watch(watchId)
for(const n of result.notices||[]){
const origin=n.eventId||[watchId,n.ruleId,n.at,n.frameId].join(':')
const key='evt_'+digest(origin).slice(0,32)
db.events[key]||={id:key,watchId,ruleId:n.ruleId,title:n.title,occurredAt:new Date(n.at*1000).toISOString(),createdAt:iso(),updatedAt:iso(),revision:1,attentionLevel:m.ruleAttention?.[n.ruleId]??m.attentionLevel,category:m.category,
evidenceState:'confirmed',handlingState:'unread',visualRecoveryAt:null,userCompletedAt:null,closedAt:null,originEventId:origin,actions:[]}
}
for(const rule of result.trace?.rules||[])if(rule.recovered)for(const e of list('events').filter(e=>e.watchId===watchId&&e.ruleId===rule.id&&!e.visualRecoveryAt))revise(e,{visualRecoveryAt:result.at,closedAt:e.closedAt||iso()})
}
async function dispatch(method,route,p,b,token){
const current=iso()
if(route==='/bootstrap')return {workspaceId:'ws_'+digest(token).slice(0,24),timezone:'Asia/Shanghai',authentication:'workspace_bearer',sdk:'ESIotKit v2.2.7',heartbeatSeconds:15,offlineAfterSeconds:45,frameMaxAgeSeconds:120,commandsRequireConfirmation:true,phonePushConnected:false,captureDefault:'event',continuousRecording:false,scheduledCapture:'requires_device_capability',storage:process.env.HOME_PULSE_CLOUD==='1'?'hf_ephemeral_disk':'local_disk'}
if(route==='/clients'){
const row={id:randomUUID(),...b,createdAt:current,lastSeen:current,foreground:true,sdkReady:false};db.clients[row.id]=row;save();return row
}
if(route==='/clients/{id}/heartbeat'){const row=client(p.id);Object.assign(row,b,{lastSeen:current});save();return row}
if(route==='/devices'&&method==='GET')return list('devices').map(d=>({...d,online:!!isOnline(d)}))
if(route==='/devices'&&method==='POST'){
client(b.clientId);const previous=db.devices[b.deviceId]
if(previous&&previous.clientId!==b.clientId)fail(409,'DEVICE_ALREADY_BOUND','设备已由另一个 App 接入,请使用原接入端')
const d={...previous,id:b.deviceId,...b,lastSeen:current,online:true,viewRevision:previous?.viewRevision||1};db.devices[d.id]=d;save();return {...d,online:!!isOnline(d)}
}
if(route==='/devices/{id}/status'){
const d=device(p.id);assertOwner(d,b.clientId);assertFresh(b.observedAt)
if(d.observedAt&&Date.parse(b.observedAt)<Date.parse(d.observedAt))fail(409,'OUT_OF_ORDER','这份设备状态早于已保存状态')
Object.assign(d,{online:b.online,state:b.state,observedAt:b.observedAt,lastSeen:current});if(b.viewChanged)invalidateView(d);save();return {...d,online:!!isOnline(d)}
}
if(route==='/device-events'){
const d=device(b.deviceId);assertOwner(d,b.clientId)
if(!d.capabilities.events)fail(422,'EVENT_SOURCE_UNAVAILABLE','这台设备尚未提供事件')
const key=d.id+':'+b.eventId,previous=db.hardwareEvents[key]
if(previous){if(previous.type!==b.type||previous.occurredAt!==b.occurredAt||previous.summary!==b.summary)fail(409,'EVENT_ID_CONFLICT','同一设备事件编号包含不同内容');return {...previous,duplicate:true,work:[]}}
assertFresh(b.occurredAt,DAY)
const active=list('watchMeta').filter(m=>m.deviceId===d.id&&m.state==='active'&&!m.needsReconfirmation&&(!m.capturePolicy||m.capturePolicy.mode==='event'))
const fresh=now()-Date.parse(b.occurredAt)<=120000
const canCapture=fresh&&isOnline(d)&&d.capabilities.frames&&(!d.lastCaptureRequestedAt||now()-Date.parse(d.lastCaptureRequestedAt)>=3000)
const row={...b,id:key,receivedAt:current,duplicate:false,work:canCapture?active.map(m=>({watchId:m.id,deviceId:d.id,viewRevision:d.viewRevision,action:'capture_then_observe',expiresAt:new Date(now()+30000).toISOString(),captureMode:'event',useEventImageWhenAvailable:true})):[]}
if(row.work.length)d.lastCaptureRequestedAt=current
db.hardwareEvents[key]=row;save();return row
}
if(route==='/setups/draft'){
const d=device(b.source.id);assertLive(d);assertView(d,b.viewRevision)
const result=await legacy('POST','/api/setup/draft',{...b,observationContext:{events:d.capabilities.events,scheduledCapture:!!d.capabilities.scheduledCapture,continuousRecording:false}})
if(result.draft?.recommendation)assertCapturePolicy(d,result.draft.recommendation.capturePolicy)
return result
}
if(route==='/setups/prepare'){
const d=device(b.binding.source.id);assertLive(d);assertView(d,b.viewRevision)
assertCapturePolicy(d,b.capturePolicy)
if(b.taskKind==='dog_boundary'&&b.locationAlerts){b.notification='auto';b.attentionLevel=Math.max(0,...[b.locationAlerts.notSeen,b.locationAlerts.outside].filter(a=>a.enabled).map(a=>a.attentionLevel))}
const r=await legacy('POST','/api/setup/prepare',b);assertView(d,b.viewRevision)
db.setupMeta[r.id]={deviceId:d.id,viewRevision:d.viewRevision,createdAt:iso(),capturePolicy:b.capturePolicy,locationAlerts:b.locationAlerts,ruleAttention:b.locationAlerts?{not_seen:b.locationAlerts.notSeen.attentionLevel,outside:b.locationAlerts.outside.attentionLevel}:undefined,category:b.category||(b.taskKind==='dog_boundary'?'care':'routine'),attentionLevel:b.attentionLevel??(['dog_boundary','keys_check'].includes(b.taskKind)?3:2)};save()
return {...noImages(r),deviceId:d.id,viewRevision:d.viewRevision}
}
if(route==='/setups/{id}')return {...repoGet('setup',p.id),...get('setupMeta',p.id)}
if(route==='/setups/{id}/trial'){
const {d}=ensureSetup(p.id);assertView(d,b.viewRevision);b.frames.forEach(f=>assertFresh(f.capturedAt))
const r=await legacy('POST','/api/setup/trial',{setupId:p.id,frames:b.frames});assertView(d,b.viewRevision)
db.setupMeta[p.id].trialAt=iso();save();return r
}
if(route==='/watches'&&method==='POST')return activate(b)
if(route==='/watches'&&method==='GET')return list('watchMeta').map(m=>watchPublic(m.id))
if(route==='/watches/{id}')return watchPublic(p.id,true)
if(route==='/watches/{id}/observe'){
const {s,m,d}=watch(p.id);assertOwner(d,b.clientId);assertLive(d);assertView(d,b.viewRevision)
if(m.needsReconfirmation)fail(409,'VIEW_RECONFIRMATION_REQUIRED','请重新确认对象和观察范围')
if(m.state!=='active')fail(409,'WATCH_PAUSED','这份关注已暂停')
if(b.frame.sourceId!==d.id)fail(409,'SOURCE_MISMATCH','画面来源与关注设备不一致')
assertFresh(b.frame.capturedAt)
const key=p.id+':'+b.frame.frameId,old=db.frames[key],frameFingerprint=digest(canonical({frame:b.frame,signals:b.signals,manual:b.manual}))
if(old){if(old.fingerprint&&old.fingerprint!==frameFingerprint)fail(409,'FRAME_ID_CONFLICT','同一画面编号不能用于不同内容');return {...old.result,duplicate:true}}
if(busyWatches.has(p.id))fail(409,'OBSERVATION_IN_PROGRESS','上一轮观察尚未完成,请等待结果')
busyWatches.add(p.id)
try{
const result=await legacy('POST','/api/contracts/observe',{registrationId:s.id,...b})
if(d.viewRevision!==b.viewRevision||m.state!=='active'){
await legacy('POST','/api/contracts/reset',{registrationId:s.id});fail(409,'VIEW_CHANGED','观察期间视野或关注状态发生变化,请重新确认')
}
recordNotices(p.id,result)
db.frames[key]={id:key,watchId:p.id,deviceId:d.id,frameId:b.frame.frameId,fingerprint:frameFingerprint,capturedAt:b.frame.capturedAt,receivedAt:iso(),viewRevision:b.viewRevision,result:noImages(result)}
save();return result
}finally{busyWatches.delete(p.id)}
}
if(route==='/watches/{id}/state'){
const {m,d}=watch(p.id)
if(b.state==='active'){assertLive(d);if(m.needsReconfirmation)fail(409,'VIEW_RECONFIRMATION_REQUIRED','请先重新确认观察范围')}
m.state=b.state;m.updatedAt=current;save();return watchPublic(p.id)
}
if(route==='/watches/{id}/replace'){
const {m}=watch(p.id),{meta}=ensureSetup(b.setupId)
if(meta.deviceId!==m.deviceId)fail(409,'SOURCE_MISMATCH','换摄像头需要新建关注')
if(busyWatches.has(p.id))fail(409,'OBSERVATION_IN_PROGRESS','上一轮观察尚未完成')
const next=await activate(b);m.state='replaced';m.replacedBy=next.id;db.watchMeta[next.id].replaces=p.id;save();return watchPublic(next.id)
}
if(route==='/watches/{id}/delete'){removeWatch(p.id,b.deleteMemory);eraseCachedResults();save();return {deleted:true}}
if(route==='/events'&&method==='GET')return list('events').sort((a,b)=>b.createdAt.localeCompare(a.createdAt))
if(route==='/events/{id}/actions'){
client(b.clientId);const e=get('events',p.id);expectRevision(e,b.expectedRevision)
const patch={}
if(b.action==='read'){patch.readAt=e.readAt||current;if(e.handlingState==='unread')patch.handlingState='read'}
if(b.action==='take_over'){if(e.closedAt)fail(409,'EVENT_CLOSED','这次事件已结束');patch.handlingState='handling';patch.takenOverAt=current}
if(b.action==='user_completed'){patch.handlingState='user_completed';patch.userCompletedAt=current;patch.closedAt=current}
if(b.action==='dismiss'){patch.handlingState='dismissed';patch.closedAt=current}
if(b.action==='reopen'){if(e.visualRecoveryAt)fail(409,'EVENT_RECOVERED','画面已确认恢复,请继续关注下一次变化');patch.handlingState='handling';patch.closedAt=null}
e.actions.push({clientId:b.clientId,action:b.action,note:b.note,at:current});revise(e,patch);save();return e
}
if(route==='/commands'&&method==='GET')return list('commands').filter(c=>!p.deviceId||c.deviceId===p.deviceId).map(publicCommand)
if(route==='/commands'&&method==='POST'){
client(b.clientId);const d=device(b.deviceId);assertLive(d);checkAction(d,b)
if(b.watchId&&watch(b.watchId).d.id!==d.id)fail(409,'SOURCE_MISMATCH','操作设备与关注不一致')
if(b.eventId){const e=get('events',b.eventId);if(b.watchId&&e.watchId!==b.watchId)fail(409,'EVENT_MISMATCH','事件不属于这份关注');if(watch(e.watchId).d.id!==d.id)fail(409,'SOURCE_MISMATCH','操作设备与事件不一致')}
const c={id:randomUUID(),...b,status:'awaiting_confirmation',revision:1,viewRevision:d.viewRevision,createdAt:current,updatedAt:current,expiresAt:new Date(now()+b.expiresInSeconds*1000).toISOString(),confirmationRequired:true}
db.commands[c.id]=c;save();return publicCommand(c)
}
if(route.startsWith('/commands/{id}/')){
const c=get('commands',p.id),d=device(c.deviceId);client(b.clientId)
if(route.endsWith('/decision')){
expectRevision(c,b.expectedRevision)
if(!['awaiting_confirmation','queued'].includes(c.status))fail(409,'INVALID_TRANSITION','这条操作已不能确认或取消')
if(b.decision==='confirm'){
if(c.status!=='awaiting_confirmation')fail(409,'INVALID_TRANSITION','这条操作已经确认')
assertLive(d);assertView(d,c.viewRevision);checkAction(d,c)
}
revise(c,{status:b.decision==='confirm'?'queued':'cancelled',decisionBy:b.clientId,decisionAt:current});save();return publicCommand(c)
}
assertOwner(d,b.clientId)
if(route.endsWith('/claim')){
expectRevision(c,b.expectedRevision)
if(c.status!=='queued')fail(409,'INVALID_TRANSITION','这条操作不可重复领取')
assertLive(d);assertView(d,c.viewRevision);checkAction(d,c)
if(c.action==='ptz.preset.goto'&&list('watchMeta').some(m=>m.deviceId===d.id&&busyWatches.has(m.id)))fail(409,'OBSERVATION_IN_PROGRESS','画面正在分析,请稍后调整视角')
const executionToken=randomBytes(32).toString('hex')
revise(c,{status:'executing',executorId:b.clientId,executionToken,executionStartedAt:current,executionDeadline:new Date(Math.min(now()+15000,Date.parse(c.expiresAt))).toISOString()})
if(c.action==='ptz.preset.goto')invalidateView(d)
save();return {...publicCommand(c),executionToken,currentViewRevision:d.viewRevision}
}
if(!equal(c.executionToken,b.executionToken))fail(403,'INVALID_EXECUTION_TOKEN','执行凭据不匹配')
if(route.endsWith('/receipt')){
if(!['executing','result_unknown'].includes(c.status))fail(409,'INVALID_TRANSITION','该回执已经记录或操作已结束')
revise(c,{status:b.outcome==='succeeded'?'awaiting_verification':b.outcome==='failed'?'failed':'result_unknown',receipt:{outcome:b.outcome,sdkCode:b.sdkCode,message:b.message,durationMs:b.durationMs,at:current,clientId:b.clientId}})
save();return publicCommand(c)
}
if(route.endsWith('/verify')){
if(!['awaiting_verification','result_unknown'].includes(c.status))fail(409,'INVALID_TRANSITION','请先提交执行结果')
assertFresh(b.observedAt)
if(Date.parse(b.observedAt)<Date.parse(c.executionStartedAt))fail(409,'STALE_EVIDENCE','请读取操作后的设备状态')
let matched=false
if(c.action==='night_vision.set')matched=b.state.nightVisionModeKey===c.params.modeKey
if(c.action==='light.set')matched=b.state.lightEnabled===c.params.enabled
if(c.action==='alarm.set')matched=b.state.alarmEnabled===c.params.enabled&&b.state.alarmType===c.params.type
if(c.action==='motion_detection.set')matched=Array.isArray(b.state.detectionTypes)&&c.params.types.every(t=>b.state.detectionTypes.includes(t))
if(c.action==='ptz.preset.goto'){
if(!b.setupId||b.targetConfirmed!==true)fail(409,'VIEW_RECONFIRMATION_REQUIRED','请重新圈选对象和范围并完成试观察')
const {setup,meta}=ensureSetup(b.setupId)
matched=meta.deviceId===d.id&&setup.trial?.passed===true&&Date.parse(setup.trial.at)>=Date.parse(c.executionStartedAt)
}
revise(c,{status:matched?'verified':'verification_failed',verification:{matched,observedAt:b.observedAt,state:b.state,setupId:b.setupId||null,source:c.action==='ptz.preset.goto'?'user_and_visual_trial':'sdk_state_readback',at:current}})
save();return publicCommand(c)
}
}
if(route==='/memories')return service().repo.list('memory').filter(m=>m.active).map(m=>({...noImages(m),thumbnail:m.targetCrop}))
if(route==='/memories/{id}')return legacy('GET','/api/memories/'+p.id)
if(route==='/memories/{id}/delete'){
repoGet('memory',p.id)
const deps=service().repo.list('registration').filter(s=>s.memoryId===p.id||s.binding?.memoryId===p.id)
if(deps.length&&!b.cascade)fail(409,'DEPENDENCIES_EXIST','这份记忆仍被关注使用',{watchIds:deps.map(s=>s.id)})
if(deps.some(s=>!db.watchMeta[s.id]))fail(409,'LEGACY_DEPENDENCIES','仍有网页旧关注使用这份记忆,请先在网页处理这些关注')
if(deps.some(s=>busyWatches.has(s.id)))fail(409,'OBSERVATION_IN_PROGRESS','相关关注正在分析,请稍后删除')
for(const s of deps)removeWatch(s.id,false)
service().repo.remove('memory',p.id);eraseCachedResults();save();return {deleted:true,deletedWatchIds:deps.map(s=>s.id)}
}
if(route==='/metrics'){
const commands=list('commands'),receipts=commands.filter(c=>c.receipt),verified=commands.filter(c=>c.status==='verified'),complete=receipts.filter(c=>c.receipt.outcome!=='unknown'),counts={}
for(const c of commands)counts[c.status]=(counts[c.status]||0)+1
return {model:metrics(),app:{devices:list('devices').length,onlineDevices:list('devices').filter(isOnline).length,hardwareEvents24h:list('hardwareEvents').length,uniqueFrames24h:new Set(list('frames').map(f=>f.deviceId+':'+f.frameId)).size,observationRuns24h:list('frames').length,eventsRetained:list('events').length,commandStatuses:counts,sdkCompleted:complete.length,sdkSuccessRate:complete.length?complete.filter(c=>c.receipt.outcome==='succeeded').length/complete.length:null,verificationCount:verified.length,verificationRate:commands.filter(c=>c.verification).length?verified.length/commands.filter(c=>c.verification).length:null}}
}
if(route==='/privacy')return {rawVideoStoredByApi:false,observationImages:{retentionHours:24,maxPerWatch:3},closedEventsRetentionDays:30,hardwareEventsRetentionHours:24,referenceImages:'until_explicit_deletion',objectMemory:'explicit_opt_in',purge:'every_60_seconds_while_process_runs_and_on_requests',processing:{intent:'Kimi API',vision:process.env.HOME_PULSE_CLOUD==='1'?'HF shared imajev':'configured imajev service'},deletionRoutes:['/watches/{id}/delete','/memories/{id}/delete'],scope:'App API data; camera recording and external provider retention have separate controls'}
if(route==='/export')return {exportedAt:current,clients:list('clients'),devices:list('devices'),watches:list('watchMeta').map(m=>watchPublic(m.id,true)),memories:service().repo.list('memory'),events:list('events'),commands:list('commands').map(publicCommand),hardwareEvents:list('hardwareEvents'),metrics:metrics(),apiVersion:API_VERSION}
fail(404,'NOT_FOUND','接口不存在')
}
async function handle(req,url,body,token){
const requestId=randomUUID()
try{
sweep()
const routePath=url.pathname.slice('/api/v1'.length),method=req.method
let match,params={}
for(const row of routes){if(row[0]!==method)continue;const re=new RegExp('^'+row[1].replace('{id}','([a-zA-Z0-9_-]{1,160})')+'$'),m=routePath.match(re);if(m){match=row;if(m[1])params.id=m[1];break}}
if(!match)fail(404,'NOT_FOUND','接口不存在')
params.deviceId=url.searchParams.get('deviceId')||undefined
const [,,schema]=match,input=schema?schema.parse(body):{}
if(method==='GET')return {status:200,body:appEnvelope(await dispatch(method,match[1],params,input,token),requestId,now())}
const key=String(req.headers['idempotency-key']||'')
if(!/^[a-zA-Z0-9_.:-]{8,100}$/.test(key))fail(400,'IDEMPOTENCY_KEY_REQUIRED','每个操作需要 8 至 100 位 Idempotency-Key')
const fp=digest(method+' '+url.pathname+' '+canonical(input)),prior=db.idempotency[key]
if(prior){
if(prior.fingerprint!==fp)fail(409,'IDEMPOTENCY_CONFLICT','同一操作编号不能用于不同请求')
if(inFlight.has(key))return await inFlight.get(key)
if(prior.status==='indeterminate'||prior.status==='running')fail(409,'RESULT_UNKNOWN','上次操作被中断,请先查询资源状态,不要重复执行')
return prior.response
}
if(Object.keys(db.idempotency).length>=2000)fail(429,'WORKSPACE_LIMIT','本空间今日操作次数已达上限')
const retentionMs=match[1]==='/clients/{id}/heartbeat'||(match[1]==='/devices/{id}/status'&&!input.viewChanged)?60000:DAY
db.idempotency[key]={fingerprint:fp,status:'running',at:now(),retentionMs};save()
const task=(async()=>{
let response
try{response={status:200,body:appEnvelope(await dispatch(method,match[1],params,input,token),requestId,now())}}
catch(e){response=appError(e,requestId,now())}
db.idempotency[key]={fingerprint:fp,status:'completed',at:now(),retentionMs,response:structuredClone(response)};save();return response
})()
inFlight.set(key,task)
try{return await task}finally{inFlight.delete(key)}
}catch(e){return appError(e,requestId,now())}
}
return {handle,close:()=>clearInterval(timer),sweep}
}