OneAlign / web /server /app-contract.mjs
loveaa's picture
Home Pulse 1.2: app interface, recommended event policies and independent location reminders
133b124 verified
Raw History Blame Contribute Delete
15.7 kB
import {z} from 'zod'
import {frameSchema,draftSchema,setupDraftSchema,setupPrepareSchema} from './grounded-service.mjs'
import {ContractSchema} from './planner.mjs'
import {capturePolicySchema,locationAlertsSchema,recommendationSchema} from './observation-policy.mjs'
export const API_VERSION='1.2.0'
export const id=z.string().min(1).max(160).regex(/^[a-zA-Z0-9_-]+$/)
const short=z.string().min(1).max(120),iso=z.string().datetime(),revision=z.number().int().min(1)
const strict=shape=>z.object(shape).strict()
export const ACTIONS=['night_vision.set','ptz.preset.goto','alarm.set','light.set','motion_detection.set']
const action=z.enum(ACTIONS)
export const capabilities=strict({
live:z.boolean(),frames:z.boolean(),events:z.boolean(),scheduledCapture:z.boolean().default(false),actions:z.array(action).max(5),
nightVisionModes:z.array(strict({key:z.number().int(),label:short})).max(20).default([]),
presetIndices:z.array(z.number().int().min(0).max(255)).max(20).default([]),
detectionTypes:z.array(short).max(20).default([]),
alarmTypes:z.array(z.enum(['SOUND_ONLY','LIGHT_ONLY','SOUND_AND_LIGHT'])).max(3).default([]),
}).strict()
export const activation=strict({setupId:id,confirmation:strict({target:z.literal(true),rule:z.literal(true)}),remember:z.boolean().default(false),interval:z.number().min(1).max(86400).default(300)})
const commandBase={clientId:id,deviceId:id,reason:z.string().min(1).max(240),watchId:id.optional(),eventId:id.optional(),expiresInSeconds:z.number().int().min(10).max(120).default(60)}
export const command=z.discriminatedUnion('action',[
strict({...commandBase,action:z.literal('night_vision.set'),params:strict({modeKey:z.number().int()})}),
strict({...commandBase,action:z.literal('ptz.preset.goto'),params:strict({index:z.number().int().min(0).max(255)})}),
strict({...commandBase,action:z.literal('alarm.set'),params:strict({enabled:z.boolean(),type:z.enum(['SOUND_ONLY','LIGHT_ONLY','SOUND_AND_LIGHT'])})}),
strict({...commandBase,action:z.literal('light.set'),params:strict({enabled:z.boolean()})}),
strict({...commandBase,action:z.literal('motion_detection.set'),params:strict({types:z.array(short).min(1).max(20)})}),
])
// These declarations drive request validation and the downloadable OpenAPI file.
// Every POST requires Idempotency-Key except the unauthenticated session bootstrap.
export const routes=[
['GET','/bootstrap',null,'读取空间和服务能力'],
['POST','/clients',strict({name:short,platform:z.enum(['ios','android','web','test']),appVersion:short}),'登记 App 安装实例'],
['POST','/clients/{id}/heartbeat',strict({foreground:z.boolean(),sdkReady:z.boolean()}),'更新接入端心跳'],
['GET','/devices',null,'查询设备及连接状态'],
['POST','/devices',strict({deviceId:id,clientId:id,name:short,model:short,capabilities}),'登记设备与实际 SDK 能力'],
['POST','/devices/{id}/status',strict({clientId:id,online:z.boolean(),observedAt:iso,viewChanged:z.boolean().default(false),state:z.record(z.string(),z.union([z.string().max(120),z.number(),z.boolean(),z.array(z.string().max(120))])).default({})}),'上报设备状态和视野变化'],
['POST','/device-events',strict({clientId:id,deviceId:id,eventId:id,type:z.enum(['motion','person','pet','vehicle','doorbell','other']),occurredAt:iso,summary:z.string().max(300).default('')}),'上传硬件事件并获取取证建议'],
['POST','/setups/draft',setupDraftSchema.extend({viewRevision:revision}),'理解需求,提出对象、澄清问题及观察提醒建议'],
['POST','/setups/prepare',setupPrepareSchema.extend({viewRevision:revision,capturePolicy:capturePolicySchema.default({mode:'event',intervalSeconds:300,comparisonMaxAgeSeconds:86400}),category:z.enum(['security','care','memory','routine']).optional(),attentionLevel:z.number().int().min(0).max(4).optional()}),'按用户确认生成规则'],
['GET','/setups/{id}',null,'恢复设置草稿和试观察结果'],
['POST','/setups/{id}/trial',strict({frames:z.array(frameSchema).min(1).max(5),viewRevision:revision}),'用可用画面试观察当前视野'],
['POST','/watches',activation,'确认并启用关注'],
['GET','/watches',null,'查询空间的全部关注'],
['GET','/watches/{id}',null,'读取关注和最近状态'],
['POST','/watches/{id}/observe',strict({clientId:id,viewRevision:revision,frame:frameSchema,manual:z.boolean().default(false),signals:z.array(z.enum(['away','rain','doorbell'])).max(3).default([])}),'上传一帧并完成视觉与规则判断'],
['POST','/watches/{id}/state',strict({state:z.enum(['paused','active'])}),'暂停或继续关注'],
['POST','/watches/{id}/replace',activation,'确认新设置并替换旧关注'],
['POST','/watches/{id}/delete',strict({confirmed:z.literal(true),deleteMemory:z.boolean().default(false)}),'删除关注与关联证据'],
['GET','/events',null,'读取事件及独立处理状态'],
['POST','/events/{id}/actions',strict({clientId:id,action:z.enum(['read','take_over','user_completed','dismiss','reopen']),expectedRevision:revision,note:z.string().max(240).default('')}),'记录用户处理动作'],
['GET','/commands',null,'读取设备操作及状态'],
['POST','/commands',command,'创建待确认的设备操作'],
['POST','/commands/{id}/decision',strict({clientId:id,decision:z.enum(['confirm','cancel']),expectedRevision:revision}),'确认或取消具体设备操作'],
['POST','/commands/{id}/claim',strict({clientId:id,expectedRevision:revision}),'唯一执行端领取操作'],
['POST','/commands/{id}/receipt',strict({clientId:id,executionToken:z.string().length(64),outcome:z.enum(['succeeded','failed','unknown']),sdkCode:z.string().max(80).default(''),message:z.string().max(240).default(''),durationMs:z.number().min(0).max(120000)}),'记录 SDK 执行回执'],
['POST','/commands/{id}/verify',strict({clientId:id,executionToken:z.string().length(64),observedAt:iso,state:z.record(z.string(),z.union([z.string(),z.number(),z.boolean(),z.array(z.string())])).default({}),setupId:id.optional(),targetConfirmed:z.boolean().optional()}),'验证设备读回状态或重新试观察结果'],
['GET','/memories',null,'查询已确认对象记忆'],
['GET','/memories/{id}',null,'读取对象参考图及确认信息'],
['POST','/memories/{id}/delete',strict({confirmed:z.literal(true),cascade:z.boolean()}),'删除记忆并明确处理依赖关注'],
['GET','/metrics',null,'读取请求 事件 设备操作统计'],
['GET','/privacy',null,'读取保存策略与处理位置'],
['GET','/export',null,'导出当前空间的设置与记录'],
]
const jsonContent=schema=>({'application/json':{schema}})
const ref=name=>({$ref:'#/components/schemas/'+name})
const arrayOf=name=>({type:'array',items:ref(name)})
const timestamp={type:['string','null'],format:'date-time'}
const record={type:'object',additionalProperties:true}
const dtoSchemas={
Draft:z.toJSONSchema(draftSchema),
DraftResponse:{type:'object',required:['draft','latencyMs'],properties:{draft:ref('Draft'),latencyMs:{type:'number'},model:{type:'string'}}},
Recommendation:z.toJSONSchema(recommendationSchema),
Client:{type:'object',required:['id','platform','lastSeen','sdkReady'],properties:{id:{type:'string'},name:{type:'string'},platform:{enum:['ios','android','web','test']},lastSeen:timestamp,foreground:{type:'boolean'},sdkReady:{type:'boolean'}}},
Device:{type:'object',required:['id','clientId','name','model','capabilities','online','viewRevision'],properties:{id:{type:'string'},clientId:{type:'string'},name:{type:'string'},model:{type:'string'},online:{type:'boolean'},viewRevision:{type:'integer',minimum:1},lastSeen:timestamp,state:record,capabilities:z.toJSONSchema(capabilities)}},
Setup:{type:'object',required:['id','plan','binding','deviceId','viewRevision'],properties:{id:{type:'string'},request:{type:'string'},plan:z.toJSONSchema(ContractSchema),binding:record,capturePolicy:z.toJSONSchema(capturePolicySchema),locationAlerts:z.toJSONSchema(locationAlertsSchema),recommendationReason:{type:'string'},deviceId:{type:'string'},viewRevision:{type:'integer'},trial:ref('Trial')}},
Trial:{type:'object',required:['passed','checks','at','latencyMs'],properties:{passed:{type:'boolean'},at:timestamp,latencyMs:{type:'number'},checks:{type:'array',items:{type:'object',required:['label','passed'],properties:{label:{type:'string'},passed:{type:'boolean'},usable:{type:'integer'},needed:{type:'integer'}}}}}},
Watch:{type:'object',required:['id','deviceId','title','plan','binding','state','observationStatus','sourceOnline','attentionLevel'],properties:{id:{type:'string'},deviceId:{type:'string'},title:{type:'string'},request:{type:'string'},plan:z.toJSONSchema(ContractSchema),binding:record,state:{enum:['active','paused','replaced']},observationStatus:{enum:['recently_checked','waiting_event','ready_for_check','waiting_schedule','awaiting_evidence','needs_reconfirmation','connection_interrupted','paused','replaced']},sourceOnline:{type:'boolean'},needsReconfirmation:{type:'boolean'},viewRevision:{type:'integer'},currentViewRevision:{type:'integer'},lastConfirmedAt:timestamp,lastObservedAt:timestamp,capturePolicy:z.toJSONSchema(capturePolicySchema),locationAlerts:z.toJSONSchema(locationAlertsSchema),lastResult:{type:['string','null']},attentionLevel:{type:'integer',minimum:0,maximum:4},category:{enum:['security','care','memory','routine']},memoryId:{type:['string','null']},observations:{type:'array',items:record}}},
Event:{type:'object',required:['id','watchId','ruleId','title','handlingState','attentionLevel','revision'],properties:{id:{type:'string'},watchId:{type:'string'},ruleId:{type:'string'},title:{type:'string'},handlingState:{enum:['unread','read','handling','user_completed','dismissed']},category:{enum:['security','care','memory','routine']},attentionLevel:{type:'integer',minimum:0,maximum:4},revision:{type:'integer'},occurredAt:timestamp,visualRecoveryAt:timestamp,userCompletedAt:timestamp,closedAt:timestamp,actions:{type:'array',items:record}}},
Command:{type:'object',required:['id','deviceId','action','params','status','revision','expiresAt'],properties:{id:{type:'string'},deviceId:{type:'string'},watchId:{type:'string'},eventId:{type:'string'},action:{enum:ACTIONS},params:record,status:{enum:['awaiting_confirmation','queued','executing','awaiting_verification','verified','verification_failed','result_unknown','failed','cancelled','expired']},revision:{type:'integer'},expiresAt:timestamp,executionDeadline:timestamp,executionToken:{type:'string',description:'仅 claim 响应返回;保存到安全存储,禁止展示与日志记录'},receipt:record,verification:record}},
Observation:{type:'object',required:['notices','details','latencyMs','engineMs','outcome'],properties:{answers:record,trace:record,notices:{type:'array',items:record},details:{type:'array',items:record},text:{type:'string'},latencyMs:{type:'number'},engineMs:{type:'number'},unknown:{type:'boolean'},pending:{type:'boolean'},duplicate:{type:'boolean'},outcome:{enum:['quiet','unknown','attention']},at:timestamp}},
Memory:{type:'object',required:['id','targetName','regionName','source'],properties:{id:{type:'string'},targetName:{type:'string'},regionName:{type:'string'},source:record,targetBox:record,regionBox:record,targetCrop:{type:'string'},referenceImage:{type:'string'},thumbnail:{type:'string'},active:{type:'boolean'},confirmedAt:timestamp}},
}
function responseData(method,route){
if(route==='/clients'||route.endsWith('/heartbeat'))return ref('Client')
if(route==='/devices')return method==='GET'?arrayOf('Device'):ref('Device')
if(route==='/devices/{id}/status')return ref('Device')
if(route==='/setups/draft')return ref('DraftResponse')
if(route==='/setups/prepare'||route==='/setups/{id}')return ref('Setup')
if(route.endsWith('/trial'))return ref('Trial')
if(route==='/watches')return method==='GET'?arrayOf('Watch'):ref('Watch')
if(['/watches/{id}','/watches/{id}/state','/watches/{id}/replace'].includes(route))return ref('Watch')
if(route.endsWith('/observe'))return ref('Observation')
if(route==='/events')return arrayOf('Event')
if(route==='/events/{id}/actions')return ref('Event')
if(route.startsWith('/commands'))return route==='/commands'&&method==='GET'?arrayOf('Command'):ref('Command')
if(route==='/memories')return arrayOf('Memory')
if(route==='/memories/{id}')return ref('Memory')
return record
}
export function openapi(){
const envelope={type:'object',required:['data','requestId','serverTime','apiVersion'],properties:{data:{},requestId:{type:'string'},serverTime:{type:'string',format:'date-time'},apiVersion:{type:'string'}}}
const error={type:'object',required:['error','requestId','serverTime','apiVersion'],properties:{error:{type:'object',required:['code','message','retryable'],properties:{code:{type:'string'},message:{type:'string'},retryable:{type:'boolean'},details:{}}},requestId:{type:'string'},serverTime:{type:'string',format:'date-time'},apiVersion:{type:'string'}}}
const paths={}
for(const [method,route,schema,summary] of routes){
const parameters=[]
if(route.includes('{id}'))parameters.push({name:'id',in:'path',required:true,schema:{type:'string'}})
if(method==='POST')parameters.push({name:'Idempotency-Key',in:'header',required:true,schema:{type:'string',minLength:8,maxLength:100},description:'同一次操作重试使用原值;同键不同正文返回 409。保留 24 小时;心跳和未变更视野的状态保留 60 秒。'})
if(route==='/commands')parameters.push({name:'deviceId',in:'query',schema:{type:'string'}})
const success={...envelope,properties:{...envelope.properties,data:responseData(method,route)}}
const responses={'200':{description:'成功;设备执行与验证状态在 data.status 中',content:jsonContent(success)}}
for(const code of ['400','401','403','404','409','410','413','422','429','502','503'])responses[code]={description:'结构化错误',content:jsonContent(error)}
const operation={summary,operationId:method.toLowerCase()+route.replace(/[^a-zA-Z0-9]+/g,'_'),security:[{WorkspaceBearer:[]}],parameters,responses}
if(schema)operation.requestBody={required:true,content:jsonContent(z.toJSONSchema(schema,{unrepresentable:'any'}))}
;(paths['/api/v1'+route]||={})[method.toLowerCase()]=operation
}
const sessionSchema={type:'object',properties:{data:{type:'object',required:['token','workspaceId'],properties:{token:{type:'string',pattern:'^[a-f0-9]{64}$'},workspaceId:{type:'string'}}},requestId:{type:'string'},serverTime:{type:'string'},apiVersion:{type:'string'}}}
paths['/api/v1/sessions']={post:{summary:'建立独立联调空间;将返回的 token 保存在系统安全存储',security:[],responses:{'201':{description:'token 仅在此返回;它是空间访问凭据,不是 eufy 登录凭据',content:jsonContent(sessionSchema)}}}}
paths['/api/v1/openapi.json']={get:{summary:'下载本接口规范',security:[],responses:{'200':{description:'OpenAPI 3.1 JSON'}}}}
return {openapi:'3.1.0',info:{title:'Home Pulse App API',version:API_VERSION,description:'App SDK 负责设备连接和执行;本 API 负责任务、模型、状态与闭环。会话为共享空间凭据;生产账户登录和成员角色另行接入。所有时间为 UTC ISO 8601,界面按家庭时区显示。'},servers:[{url:'https://loveaa-onealign.hf.space'},{url:'http://127.0.0.1:7101'}],components:{schemas:dtoSchemas,securitySchemes:{WorkspaceBearer:{type:'http',scheme:'bearer',description:'Home Pulse 空间令牌;不要使用 HF、Kimi 或 eufy 密钥'}}},paths}
}