diff --git "a/web/server-bundle.mjs" "b/web/server-bundle.mjs" --- "a/web/server-bundle.mjs" +++ "b/web/server-bundle.mjs" @@ -6,14 +6,14 @@ var __export = (target, all) => { // server/cloud-server.mjs import http from "node:http"; -import path5 from "node:path"; +import path6 from "node:path"; import { fileURLToPath } from "node:url"; -import { timingSafeEqual } from "node:crypto"; +import { timingSafeEqual as timingSafeEqual2 } from "node:crypto"; // server/local-api.mjs -import fs4 from "node:fs"; -import path4 from "node:path"; -import { randomUUID as randomUUID3 } from "node:crypto"; +import fs6 from "node:fs"; +import path5 from "node:path"; +import { randomUUID as randomUUID5 } from "node:crypto"; import { performance as performance3 } from "node:perf_hooks"; // server/planner.mjs @@ -789,10 +789,10 @@ function mergeDefs(...defs) { function cloneDef(schema) { return mergeDefs(schema._zod.def); } -function getElementAtPath(obj, path6) { - if (!path6) +function getElementAtPath(obj, path7) { + if (!path7) return obj; - return path6.reduce((acc, key) => acc?.[key], obj); + return path7.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); @@ -1175,11 +1175,11 @@ function aborted(x, startIndex = 0) { } return false; } -function prefixIssues(path6, issues) { +function prefixIssues(path7, issues) { return issues.map((iss) => { var _a2; (_a2 = iss).path ?? (_a2.path = []); - iss.path.unshift(path6); + iss.path.unshift(path7); return iss; }); } @@ -1362,7 +1362,7 @@ function formatError(error48, mapper = (issue2) => issue2.message) { } function treeifyError(error48, mapper = (issue2) => issue2.message) { const result = { errors: [] }; - const processError = (error49, path6 = []) => { + const processError = (error49, path7 = []) => { var _a2, _b; for (const issue2 of error49.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { @@ -1372,7 +1372,7 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) { } else if (issue2.code === "invalid_element") { processError({ issues: issue2.issues }, issue2.path); } else { - const fullpath = [...path6, ...issue2.path]; + const fullpath = [...path7, ...issue2.path]; if (fullpath.length === 0) { result.errors.push(mapper(issue2)); continue; @@ -1404,8 +1404,8 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) { } function toDotPath(_path) { const segs = []; - const path6 = _path.map((seg) => typeof seg === "object" ? seg.key : seg); - for (const seg of path6) { + const path7 = _path.map((seg) => typeof seg === "object" ? seg.key : seg); + for (const seg of path7) { if (typeof seg === "number") segs.push(`[${seg}]`); else if (typeof seg === "symbol") @@ -3056,46 +3056,46 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => } doc.write(`const newResult = {};`); for (const key of normalized.keys) { - const id = ids[key]; + const id2 = ids[key]; const k = esc(key); const schema = shape[key]; const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(`const ${id2} = ${parseStr(key)};`); if (isOptionalOut) { doc.write(` - if (${id}.issues.length) { + if (${id2}.issues.length) { if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } } - if (${id}.value === undefined) { + if (${id2}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { - newResult[${k}] = ${id}.value; + newResult[${k}] = ${id2}.value; } `); } else { doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + if (${id2}.issues.length) { + payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } - if (${id}.value === undefined) { + if (${id2}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { - newResult[${k}] = ${id}.value; + newResult[${k}] = ${id2}.value; } `); @@ -10986,26 +10986,26 @@ function extractDefs(ctx, schema) { throw new Error("Unprocessed schema. This is a bug in Zod."); const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); + const id2 = ctx.metadataRegistry.get(entry[0])?.id; + if (id2) { + const existing = idToSchema.get(id2); if (existing && existing !== entry[0]) { - throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); } - idToSchema.set(id, entry[0]); + idToSchema.set(id2, entry[0]); } } const makeURI = (entry) => { const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; if (ctx.external) { const externalId = ctx.external.registry.get(entry[0])?.id; - const uriGenerator = ctx.external.uri ?? ((id2) => id2); + const uriGenerator = ctx.external.uri ?? ((id3) => id3); if (externalId) { return { ref: uriGenerator(externalId) }; } - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; + const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id2; + return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` }; } if (entry[1] === root) { return { ref: "#" }; @@ -11020,7 +11020,7 @@ function extractDefs(ctx, schema) { return; } const seen = entry[1]; - const { ref, defId } = makeURI(entry); + const { ref: ref2, defId } = makeURI(entry); seen.def = { ...seen.schema }; if (defId) seen.defId = defId; @@ -11028,7 +11028,7 @@ function extractDefs(ctx, schema) { for (const key in schema2) { delete schema2[key]; } - schema2.$ref = ref; + schema2.$ref = ref2; }; if (ctx.cycles === "throw") { for (const entry of ctx.seen.entries()) { @@ -11053,8 +11053,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. continue; } } - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { + const id2 = ctx.metadataRegistry.get(entry[0])?.id; + if (id2) { extractToDef(entry); continue; } @@ -11080,11 +11080,11 @@ function finalize(ctx, schema) { return; const schema2 = seen.def ?? seen.schema; const _cached = { ...schema2 }; - const ref = seen.ref; + const ref2 = seen.ref; seen.ref = null; - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); + if (ref2) { + flattenRef(ref2); + const refSeen = ctx.seen.get(ref2); const refSchema = refSeen.schema; if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { schema2.allOf = schema2.allOf ?? []; @@ -11093,7 +11093,7 @@ function finalize(ctx, schema) { Object.assign(schema2, refSchema); } Object.assign(schema2, _cached); - const isParentRef = zodSchema._zod.parent === ref; + const isParentRef = zodSchema._zod.parent === ref2; if (isParentRef) { for (const key in schema2) { if (key === "$ref" || key === "allOf") @@ -11114,7 +11114,7 @@ function finalize(ctx, schema) { } } const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { + if (parent && parent !== ref2) { flattenRef(parent); const parentSeen = ctx.seen.get(parent); if (parentSeen?.schema.$ref) { @@ -11150,10 +11150,10 @@ function finalize(ctx, schema) { } else { } if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) + const id2 = ctx.external.registry.get(schema)?.id; + if (!id2) throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); + result.$id = ctx.external.uri(id2); } Object.assign(result, root.def ?? root.schema); const defs = ctx.external?.defs ?? {}; @@ -13378,23 +13378,23 @@ function detectVersion(schema, defaultTarget) { } return defaultTarget ?? "draft-2020-12"; } -function resolveRef(ref, ctx) { - if (!ref.startsWith("#")) { +function resolveRef(ref2, ctx) { + if (!ref2.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); } - const path6 = ref.slice(1).split("/").filter(Boolean); - if (path6.length === 0) { + const path7 = ref2.slice(1).split("/").filter(Boolean); + if (path7.length === 0) { return ctx.rootSchema; } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; - if (path6[0] === defsKey) { - const key = path6[1]; + if (path7[0] === defsKey) { + const key = path7[1]; if (!key || !ctx.defs[key]) { - throw new Error(`Reference not found: ${ref}`); + throw new Error(`Reference not found: ${ref2}`); } return ctx.defs[key]; } - throw new Error(`Reference not found: ${ref}`); + throw new Error(`Reference not found: ${ref2}`); } function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { @@ -13822,7 +13822,7 @@ function explicitTimes(request) { } function semanticIssues(request, plan) { if (plan.status !== "ready") return []; - const issues = [], rules = plan.rules, observed = (id) => plan.observers.find((o) => o.id === id); + const issues = [], rules = plan.rules, observed = (id2) => plan.observers.find((o) => o.id === id2); for (const o of plan.observers) if (o.input === "reference" && !/reference|compared|registered|same object/i.test(o.question_en)) issues.push("reference \u8F93\u5165\u4EC5\u7528\u4E8E\u767B\u8BB0\u7269\u4F53\u7684\u5BF9\u7167\uFF1B\u5F53\u524D\u52A8\u4F5C\u89C2\u5BDF\u5E94\u4F7F\u7528 single \u6216 pair"); if (/写作业|吃药/.test(request)) issues.push("\u9700\u8981\u5148\u786E\u8BA4\u53EF\u89C2\u5BDF\u7684\u66FF\u4EE3\u52A8\u4F5C\uFF0C\u4E0D\u80FD\u628A\u5199\u5B57\u6216\u63A5\u89E6\u836F\u76D2\u76F4\u63A5\u5F53\u6210\u5B8C\u6210\u4F5C\u4E1A\u6216\u670D\u836F"); if (/进家|进屋|进入室内|从.{0,8}进/.test(request) && !plan.observers.some((o) => o.input === "pair" && /enter|cross|mov.*in/i.test(o.question_en))) issues.push("\u8FDB\u5165\u52A8\u4F5C\u5FC5\u987B\u89C2\u5BDF\u6709\u65B9\u5411\u7684\u65F6\u5E8F\u8BC1\u636E\uFF0C\u4E0D\u80FD\u6539\u5199\u6210\u5355\u5E27\u6709\u4EBA"); @@ -13861,6 +13861,18 @@ function semanticIssues(request, plan) { return [...new Set(issues)]; } +// server/runtime-context.mjs +import { AsyncLocalStorage } from "node:async_hooks"; +var runtimeContext = new AsyncLocalStorage(); +function modelUrl(route) { + const base = runtimeContext.getStore()?.modelBase || process.env.HOME_PULSE_MODEL_URL || "http://127.0.0.1:8765"; + return base.replace(/\/$/, "") + route; +} +var cloudMode = () => process.env.HOME_PULSE_CLOUD === "1"; +function modelHeaders() { + return { "Content-Type": "application/json", ...runtimeContext.getStore()?.modelBase ? { "X-Bridge-Key": process.env.HOME_PULSE_INTERNAL_KEY } : {} }; +} + // server/planner.mjs var PLANNER_MODEL = "hackathon/v_model/kimi-k3"; var PLANNER_URL = "https://ai-router-cn-pub.anker-in.com/chat/completions"; @@ -13949,6 +13961,7 @@ Semantics: - Never output an observer that asks a single image to establish identity, a past action, motive, a long duration, or invisible facts. Ready means the plan can proceed to user confirmation and visual grounding; it does not claim the camera actually sees the target. For needs_clarification/unsupported you can return empty observers/rules. Do not fill unknown user intent with confident invented requirements.`; function readPlannerKey(root) { + if (runtimeContext.getStore()?.plannerKey) return runtimeContext.getStore().plannerKey; if (process.env.ANKER_KIMI_API_KEY) return process.env.ANKER_KIMI_API_KEY; const file2 = path.join(root, ".env.local"); if (!fs.existsSync(file2)) return ""; @@ -14034,9 +14047,9 @@ async function compilePlanReliable({ request, context = {}, root, maxAttempts = } // server/grounded-service.mjs -import fs2 from "node:fs"; +import fs3 from "node:fs"; import path2 from "node:path"; -import { randomUUID } from "node:crypto"; +import { randomUUID as randomUUID2 } from "node:crypto"; import { performance as performance2 } from "node:perf_hooks"; // server/contract-engine.mjs @@ -14244,47 +14257,61 @@ var ContractEngine = class { } }; -// server/runtime-context.mjs -import { AsyncLocalStorage } from "node:async_hooks"; -var runtimeContext = new AsyncLocalStorage(); -function modelUrl(route) { - const base = runtimeContext.getStore()?.modelBase || process.env.HOME_PULSE_MODEL_URL || "http://127.0.0.1:8765"; - return base.replace(/\/$/, "") + route; -} -var cloudMode = () => process.env.HOME_PULSE_CLOUD === "1"; -function modelHeaders() { - return { "Content-Type": "application/json", ...runtimeContext.getStore()?.modelBase ? { "X-Bridge-Key": process.env.HOME_PULSE_INTERNAL_KEY } : {} }; +// server/atomic-file.mjs +import fs2 from "node:fs"; +import { randomUUID } from "node:crypto"; +function writeAtomic(file2, contents) { + const temporary = file2 + "." + randomUUID() + ".tmp"; + fs2.writeFileSync(temporary, contents, "utf8"); + try { + for (let attempt = 0; ; attempt++) { + try { + fs2.renameSync(temporary, file2); + return; + } catch (error48) { + if (attempt >= 4 || !["EPERM", "EBUSY", "EACCES"].includes(error48.code)) throw error48; + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25 * (attempt + 1)); + } + } + } finally { + if (fs2.existsSync(temporary)) fs2.unlinkSync(temporary); + } } // server/grounded-service.mjs var image = external_exports.string().max(25e5).regex(/^data:image\/(jpeg|png|webp);base64,/); var box = external_exports.object({ x: external_exports.number().min(0).max(1), y: external_exports.number().min(0).max(1), w: external_exports.number().min(0.02).max(1), h: external_exports.number().min(0.02).max(1) }).refine((b) => b.x + b.w <= 1.001 && b.y + b.h <= 1.001, "\u9009\u533A\u8D85\u51FA\u753B\u9762"); -var source = external_exports.object({ id: external_exports.string().min(1).max(160), name: external_exports.string().min(1).max(160), camera: external_exports.string().min(1).max(80), url: external_exports.string().max(500).regex(/^\/(?:media\/|api\/media\/)/), type: external_exports.enum(["video", "image"]) }); +var source = external_exports.object({ id: external_exports.string().min(1).max(160), name: external_exports.string().min(1).max(160), camera: external_exports.string().min(1).max(80), url: external_exports.string().max(500), type: external_exports.enum(["video", "image", "live"]) }).refine((s) => s.type === "live" ? s.url === "" : /^\/(?:media\/|api\/media\/)/.test(s.url), "\u6765\u6E90\u5730\u5740\u65E0\u6548"); var draftSchema = external_exports.object({ title: external_exports.string().max(60), taskKind: external_exports.enum(["dog_boundary", "keys_check", "general"]), targetName: external_exports.string().max(80), targetDescriptionEn: external_exports.string().min(3).max(600), regionName: external_exports.string().max(80), regionDescriptionEn: external_exports.string().min(3).max(500), targetBox: box.nullable(), regionBox: box.nullable(), summary: external_exports.string().max(500), questions: external_exports.array(external_exports.object({ id: external_exports.string().max(30), question: external_exports.string().max(180), options: external_exports.array(external_exports.string().max(120)).max(4) })).max(3), viewAdvice: external_exports.string().max(250) }); var bindingSchema = external_exports.object({ source, referenceImage: image, annotatedReference: image, targetCrop: image, targetBox: box, regionBox: box, targetName: external_exports.string().min(1).max(80), regionName: external_exports.string().min(1).max(80), targetDescriptionEn: external_exports.string().min(3).max(600), regionDescriptionEn: external_exports.string().min(3).max(500), referenceMediaTime: external_exports.number().min(0), memoryId: external_exports.string().optional(), matchMode: external_exports.enum(["instance", "category"]).default("instance") }); var frameSchema = external_exports.object({ image, annotated: image, pairImage: image.optional(), mediaTime: external_exports.number().min(0), capturedAt: external_exports.string().datetime(), frameId: external_exports.string().min(1).max(200), sourceId: external_exports.string().min(1).max(160) }); +var setupDraftSchema = external_exports.object({ request: external_exports.string().min(2).max(3e3), image, source, memoryId: external_exports.string().optional() }); +var setupPrepareSchema = external_exports.object({ request: external_exports.string().min(2).max(3e3), binding: bindingSchema, taskKind: external_exports.enum(["dog_boundary", "keys_check", "general"]), answers: external_exports.array(external_exports.object({ question: external_exports.string().max(200), answer: external_exports.string().min(1).max(500) })).max(12), notification: external_exports.enum(["auto", "quiet"]), confirmed: external_exports.literal(true) }); var DRAFT_PROMPT = `You help a household camera user define a monitoring task with visual grounding. Return valid JSON only, no markdown. Use the actual supplied image, never video titles or invented objects. Coordinates are normalized fractions relative to the full image (x,y,width,height), each 0..1; return null if not visible. Boxes are proposals for user confirmation, not facts. Choose the particular task target, not every similar object. If several plausible targets exist, ask the user to choose. A region may be the cage, tray, doorway or relevant entire scene. Keep questions to missing details that affect the alarm; do not ask for technical parameters. Never repeat a question already unambiguously answered by the current request. When knownTarget.reuseConditions is true, reuse its confirmed answers, include the relevant definition in the summary, and do not ask the same questions again. For a changed task, reuse object descriptions only; do not silently reuse incompatible trigger conditions. Schema: {"title":"\u4E2D\u6587","taskKind":"dog_boundary|keys_check|general","targetName":"\u4E2D\u6587","targetDescriptionEn":"brief visible appearance in English","regionName":"\u4E2D\u6587","regionDescriptionEn":"brief region description in English","targetBox":{"x":0,"y":0,"w":0.1,"h":0.1},"regionBox":{"x":0,"y":0,"w":1,"h":1},"summary":"\u4E2D\u6587\u6267\u884C\u5EFA\u8BAE","questions":[{"id":"q1","question":"\u4E2D\u6587\u95EE\u9898","options":["\u9009\u9879"]}],"viewAdvice":"\u753B\u9762\u9700\u5982\u4F55\u8C03\u6574\uFF0C\u5DF2\u6E05\u695A\u5219\u4E3A\u7A7A"} dog_boundary: confirm fully outside vs merely reaching/climbing, and whether a person deliberately taking the dog out counts when unspecified. Do not equate all dogs with this dog. keys_check: confirm visible keys remaining on their registered tray when departure is triggered; absence from tray cannot prove the person carries keys. Ask whether the user accepts this observable task. Do not infer departure/identity from an isolated image. General: preserve the requested behavior, duration and notification timing. Identity, invisible facts, unclear completion or ambiguous durations require a short specific question. Registered memories can suggest prior definitions but must not invent current visibility. No claims of perfect recognition. Ask no more than 3 questions.`; var GroundedRepository = class { constructor(root) { this.dir = path2.join(root, ".local", "grounded"); - fs2.mkdirSync(this.dir, { recursive: true }); + fs3.mkdirSync(this.dir, { recursive: true }); } - save(kind, id, value) { - const file2 = path2.join(this.dir, kind + "-" + id + ".json"); - fs2.writeFileSync(file2 + ".tmp", JSON.stringify(value)); - fs2.renameSync(file2 + ".tmp", file2); + save(kind, id2, value) { + const file2 = path2.join(this.dir, kind + "-" + id2 + ".json"); + writeAtomic(file2, JSON.stringify(value)); return value; } - get(kind, id) { - if (!/^[a-zA-Z0-9-]{1,100}$/.test(id)) throw new Error("\u8BB0\u5F55\u7F16\u53F7\u65E0\u6548"); - const f = path2.join(this.dir, kind + "-" + id + ".json"); - if (!fs2.existsSync(f)) throw new Error("\u8BB0\u5F55\u4E0D\u5B58\u5728"); - return JSON.parse(fs2.readFileSync(f, "utf8")); + get(kind, id2) { + if (!/^[a-zA-Z0-9-]{1,100}$/.test(id2)) throw new Error("\u8BB0\u5F55\u7F16\u53F7\u65E0\u6548"); + const f = path2.join(this.dir, kind + "-" + id2 + ".json"); + if (!fs3.existsSync(f)) throw new Error("\u8BB0\u5F55\u4E0D\u5B58\u5728"); + return JSON.parse(fs3.readFileSync(f, "utf8")); } list(kind) { - return fs2.readdirSync(this.dir).filter((f) => f.startsWith(kind + "-") && f.endsWith(".json")).map((f) => JSON.parse(fs2.readFileSync(path2.join(this.dir, f), "utf8"))); + return fs3.readdirSync(this.dir).filter((f) => f.startsWith(kind + "-") && f.endsWith(".json")).map((f) => JSON.parse(fs3.readFileSync(path2.join(this.dir, f), "utf8"))); + } + remove(kind, id2) { + this.get(kind, id2); + fs3.unlinkSync(path2.join(this.dir, kind + "-" + id2 + ".json")); } }; function trialVerdict(setup, grounding, observations) { @@ -14352,7 +14379,7 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, engine.todo = new Set(saved.todo || []); engine.notices = saved.notices || []; } - const entry = { engine, previous: null, lastMediaTime: saved?.mediaTime, lastText: saved?.text, runId: saved?.runId || randomUUID(), observations: saved?.observations || [] }; + const entry = { engine, previous: null, lastMediaTime: saved?.mediaTime, lastText: saved?.text, runId: saved?.runId || randomUUID2(), observations: saved?.observations || [] }; engines.set(s.id, entry); return entry; }; @@ -14362,7 +14389,7 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, if (reports.length) { const log = journal(); for (const report of reports) { - log.update(randomUUID(), { startedAt: (/* @__PURE__ */ new Date()).toISOString(), status: "success", kind: "summary", modelAttempt: false, captureCount: 0, itemId: s.id, itemName: s.plan.title, notified: s.plan.rules.find((r) => r.id === report.ruleId)?.level > 0, verdict: report.status, source: "\u5230\u70B9\u6C47\u603B" }); + log.update(randomUUID2(), { startedAt: (/* @__PURE__ */ new Date()).toISOString(), status: "success", kind: "summary", modelAttempt: false, captureCount: 0, itemId: s.id, itemName: s.plan.title, notified: s.plan.rules.find((r) => r.id === report.ruleId)?.level > 0, verdict: report.status, source: "\u5230\u70B9\u6C47\u603B" }); } checkpoint(s, entry); } @@ -14371,8 +14398,8 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, const publicSetup = (s) => ({ id: s.id, plan: s.plan, binding: s.binding, trial: s.trial, planner: s.planner, request: s.request, answers: s.answers }); const memoryPublic = (m) => ({ ...m, referenceImage: void 0, annotatedReference: void 0, targetCrop: void 0, thumbnail: "/api/grounded/image/memory/" + m.id + "/targetCrop" }); async function model(questions, images, state, meta3) { - const id = randomUUID(), start = performance2.now(), startedAt = (/* @__PURE__ */ new Date()).toISOString(), log = journal(); - log.update(id, { startedAt, status: "running", modelAttempt: true, kind: meta3.kind || "observation", captureCount: log.list().some((r) => r.captureId === meta3.captureId) ? 0 : 1, ...meta3 }); + const id2 = randomUUID2(), start = performance2.now(), startedAt = (/* @__PURE__ */ new Date()).toISOString(), log = journal(); + log.update(id2, { startedAt, status: "running", modelAttempt: true, kind: meta3.kind || "observation", captureCount: log.list().some((r) => r.captureId === meta3.captureId) ? 0 : 1, ...meta3 }); return enqueue(async () => { try { const r = await visionFetch(modelUrl("/v1/systemone"), { method: "POST", headers: modelHeaders(), body: JSON.stringify({ questions, images, state }), signal: AbortSignal.timeout(12e4) }); @@ -14387,10 +14414,10 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, answers[key] = { choice: a.choice ?? null, abstained: !!a.abstained || a.choice === "unknown" }; } const latencyMs = Math.round(performance2.now() - start); - log.update(id, { status: Object.values(answers).some((a) => a.abstained) ? "unknown" : "success", latencyMs, inferenceMs: raw.usage?.total_ms, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }); - return { answers, latencyMs, recordId: id }; + log.update(id2, { status: Object.values(answers).some((a) => a.abstained) ? "unknown" : "success", latencyMs, inferenceMs: raw.usage?.total_ms, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }); + return { answers, latencyMs, recordId: id2 }; } catch (e) { - log.update(id, { status: "error", error: e.message, latencyMs: Math.round(performance2.now() - start), finishedAt: (/* @__PURE__ */ new Date()).toISOString() }); + log.update(id2, { status: "error", error: e.message, latencyMs: Math.round(performance2.now() - start), finishedAt: (/* @__PURE__ */ new Date()).toISOString() }); throw e; } }); @@ -14412,7 +14439,7 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, return { answers, details, latencyMs: details.reduce((n, r) => n + r.latencyMs, 0) }; } async function draft(body) { - const input = external_exports.object({ request: external_exports.string().min(2).max(3e3), image, source, memoryId: external_exports.string().optional() }).parse(body); + const input = setupDraftSchema.parse(body); const key = readPlannerKey(root); if (!key) throw new Error("\u8BF7\u5148\u914D\u7F6E Kimi API"); const prior = input.memoryId ? repo.get("memory", input.memoryId) : null; @@ -14424,7 +14451,7 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, return { draft: data, latencyMs: Math.round(performance2.now() - start), model: raw.model || PLANNER_MODEL }; } async function prepare(body) { - const input = external_exports.object({ request: external_exports.string().min(2).max(3e3), binding: bindingSchema, taskKind: external_exports.enum(["dog_boundary", "keys_check", "general"]), answers: external_exports.array(external_exports.object({ question: external_exports.string().max(200), answer: external_exports.string().min(1).max(500) })).max(12), notification: external_exports.enum(["auto", "quiet"]), confirmed: external_exports.literal(true) }).parse(body); + const input = setupPrepareSchema.parse(body); let plan, plannerInfo; const key = readPlannerKey(root); if (!key) throw new Error("\u8BF7\u5148\u914D\u7F6E Kimi API"); @@ -14448,7 +14475,7 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, plannerInfo = { model: r.model, latencyMs: r.latencyMs, version: r.version }; for (const rule of plan.rules) if (["occurrence", "sequence"].includes(rule.mode) && [...rule.condition.terms, ...rule.then?.terms || []].every((t) => plan.observers.find((o) => o.id === t.observer)?.input === "pair")) rule.confirmation_frames = 1; } - const setup = { id: randomUUID(), at: (/* @__PURE__ */ new Date()).toISOString(), request: input.request, binding: input.binding, answers: input.answers, plan, planner: plannerInfo, notification: input.notification, taskKind: input.taskKind }; + const setup = { id: randomUUID2(), at: (/* @__PURE__ */ new Date()).toISOString(), request: input.request, binding: input.binding, answers: input.answers, plan, planner: plannerInfo, notification: input.notification, taskKind: input.taskKind }; repo.save("setup", setup.id, setup); return publicSetup(setup); } @@ -14475,15 +14502,15 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, const setup = repo.get("setup", String(body.setupId)); assertActivation(setup, body.confirmation); if (setup.activatedId) return registrationPublic(repo.get("registration", setup.activatedId)); - const id = randomUUID(), at = (/* @__PURE__ */ new Date()).toISOString(), b = setup.binding; - const registration = { ...setup, id, setupId: setup.id, confirmedAt: at, revision: 1, interval: external_exports.number().min(1).max(30).parse(body.interval ?? 3) }; + const id2 = randomUUID2(), at = (/* @__PURE__ */ new Date()).toISOString(), b = setup.binding; + const registration = { ...setup, id: id2, setupId: setup.id, confirmedAt: at, revision: 1, interval: external_exports.number().min(1).max(30).parse(body.interval ?? 3) }; if (body.remember !== false) { - const memory = { ...b, id: randomUUID(), confirmedAt: at, active: true, taskSummary: setup.plan.summary_zh, request: setup.request, confirmedAnswers: setup.answers, taskKind: setup.taskKind, originRegistration: id }; + const memory = { ...b, id: randomUUID2(), confirmedAt: at, active: true, taskSummary: setup.plan.summary_zh, request: setup.request, confirmedAnswers: setup.answers, taskKind: setup.taskKind, originRegistration: id2 }; repo.save("memory", memory.id, memory); registration.memoryId = memory.id; } - repo.save("registration", id, registration); - repo.save("setup", setup.id, { ...setup, activatedId: id }); + repo.save("registration", id2, registration); + repo.save("setup", setup.id, { ...setup, activatedId: id2 }); return registrationPublic(registration); } function registrationPublic(r) { @@ -14522,7 +14549,7 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, entry.lastText = text; for (const [i, d] of r.details.entries()) journal().update(d.recordId, { committed: true, engineMs: i === 0 ? engineMs : 0, stateChanged: i === 0 && stateChanged, notified: i === 0 && notices.length > 0, verdict: text }); const result = { ...r, trace, notices, text, unknown: unknown2, pending, stateChanged, engineMs, outcome: notices.length ? "attention" : unknown2 ? "unknown" : "quiet", at: f.capturedAt }; - entry.observations = [{ id: r.details[0]?.recordId || randomUUID(), capturedAt: f.capturedAt, time: new Intl.DateTimeFormat("zh-CN", { timeZone: "Asia/Shanghai", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(new Date(f.capturedAt)), outcome: result.outcome, unknown: unknown2, pending, text, evidence: f.image, latencyMs: r.latencyMs, engineMs, details: r.details, source: input.manual ? "\u4E3B\u52A8\u67E5\u770B" : "\u786E\u8BA4\u4EFB\u52A1\u89C2\u5BDF", sourceName: s.binding.source.name, frameKey: f.frameId, sceneKey: f.sourceId, mediaTime: f.mediaTime }, ...entry.observations].slice(0, 60); + entry.observations = [{ id: r.details[0]?.recordId || randomUUID2(), capturedAt: f.capturedAt, time: new Intl.DateTimeFormat("zh-CN", { timeZone: "Asia/Shanghai", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(new Date(f.capturedAt)), outcome: result.outcome, unknown: unknown2, pending, text, evidence: f.image, latencyMs: r.latencyMs, engineMs, details: r.details, source: input.manual ? "\u4E3B\u52A8\u67E5\u770B" : "\u786E\u8BA4\u4EFB\u52A1\u89C2\u5BDF", sourceName: s.binding.source.name, frameKey: f.frameId, sceneKey: f.sourceId, mediaTime: f.mediaTime }, ...entry.observations].slice(0, 60); checkpoint(s, entry, { at: f.capturedAt, answers: r.answers, text, lastFrameId: f.frameId }); return result; }); @@ -14537,7 +14564,7 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, const s = repo.get("registration", String(body.registrationId)); const entry = entryFor(s); engines.delete(s.id); - repo.save("state", s.id, { at: (/* @__PURE__ */ new Date()).toISOString(), runId: randomUUID(), observations: entry.observations }); + repo.save("state", s.id, { at: (/* @__PURE__ */ new Date()).toISOString(), runId: randomUUID2(), observations: entry.observations }); return { ok: true }; } if (method === "POST" && url2.pathname === "/api/contracts/preferences") { @@ -14553,10 +14580,10 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, return { ok: true }; } if (method === "GET" && url2.pathname === "/api/contracts/notices") { - return (url2.searchParams.get("ids") || "").split(",").filter(Boolean).slice(0, 30).map((id) => { - const s = repo.get("registration", id), entry = entryFor(s); + return (url2.searchParams.get("ids") || "").split(",").filter(Boolean).slice(0, 30).map((id2) => { + const s = repo.get("registration", id2), entry = entryFor(s); collectSummaries(s, entry); - return { registrationId: id, notices: noticesFor(s, entry), observations: entry.observations.slice(0, 60).map((o, i) => ({ ...o, evidence: i < 3 ? o.evidence : null })) }; + return { registrationId: id2, notices: noticesFor(s, entry), observations: entry.observations.slice(0, 60).map((o, i) => ({ ...o, evidence: i < 3 ? o.evidence : null })) }; }); } if (method === "GET" && url2.pathname === "/api/memories") return repo.list("memory").filter((m) => m.active).map(memoryPublic); @@ -14569,29 +14596,29 @@ function createGroundedService(root, { journal, enqueue, router = requestRouter, if (method === "GET" && url2.pathname.startsWith("/api/contracts/")) return registrationPublic(repo.get("registration", url2.pathname.split("/").at(-1))); throw new Error("\u63A5\u53E3\u4E0D\u5B58\u5728"); } - return { handle, repo, handles: (url2) => /^\/api\/(setup\/|contracts\/|memories(?:\/|$))/.test(url2.pathname), getImage: (kind, id, field) => { + return { handle, repo, forget: (id2) => engines.delete(id2), handles: (url2) => /^\/api\/(setup\/|contracts\/|memories(?:\/|$))/.test(url2.pathname), getImage: (kind, id2, field) => { if (!["memory", "registration"].includes(kind) || !["targetCrop", "referenceImage"].includes(field)) throw new Error("\u56FE\u7247\u4E0D\u5B58\u5728"); - const r = repo.get(kind, id), data = (kind === "registration" ? r.binding : r)[field]; + const r = repo.get(kind, id2), data = (kind === "registration" ? r.binding : r)[field]; return data; } }; } // server/media-library.mjs -import fs3 from "node:fs"; +import fs4 from "node:fs"; import path3 from "node:path"; -import { randomUUID as randomUUID2 } from "node:crypto"; +import { randomUUID as randomUUID3 } from "node:crypto"; var MIME = { ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp" }; function createMediaLibrary(root) { const dir = path3.join(root, ".local", "media"); - fs3.mkdirSync(dir, { recursive: true }); + fs4.mkdirSync(dir, { recursive: true }); const sourceRoot = path3.resolve(process.env.HOME_PULSE_MEDIA_ROOT || path3.resolve(root, "../\u89C6\u9891\u7D20\u67502")), index = path3.join(sourceRoot, "\u8BF4\u660E\u4E0E\u7D22\u5F15/\u5B8C\u6574\u7D20\u6750\u7D22\u5F15.json"); - const indexed = fs3.existsSync(index) ? JSON.parse(fs3.readFileSync(index, "utf8")) : []; - const rows = indexed.map((r) => ({ id: r.clip_id, name: r.title, camera: r.scene || "\u5BB6\u5EAD\u7A7A\u95F4", url: "/api/media/clip/" + r.clip_id, type: "video", file: path3.resolve(sourceRoot, r.file), duration: r.duration_s })).filter((r) => r.file.startsWith(sourceRoot + path3.sep) && fs3.existsSync(r.file)); + const indexed = fs4.existsSync(index) ? JSON.parse(fs4.readFileSync(index, "utf8")) : []; + const rows = indexed.map((r) => ({ id: r.clip_id, name: r.title, camera: r.scene || "\u5BB6\u5EAD\u7A7A\u95F4", url: "/api/media/clip/" + r.clip_id, type: "video", file: path3.resolve(sourceRoot, r.file), duration: r.duration_s })).filter((r) => r.file.startsWith(sourceRoot + path3.sep) && fs4.existsSync(r.file)); function uploaded() { - return fs3.readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => JSON.parse(fs3.readFileSync(path3.join(dir, f), "utf8"))); + return fs4.readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => JSON.parse(fs4.readFileSync(path3.join(dir, f), "utf8"))); } function sendFile(req, res, file2) { - const { size } = fs3.statSync(file2); + const { size } = fs4.statSync(file2); res.setHeader("Content-Type", MIME[path3.extname(file2).toLowerCase()] || "application/octet-stream"); res.setHeader("Accept-Ranges", "bytes"); res.setHeader("Cache-Control", "private, max-age=3600"); @@ -14606,10 +14633,10 @@ function createMediaLibrary(root) { res.statusCode = 206; res.setHeader("Content-Range", `bytes ${start}-${end}/${size}`); res.setHeader("Content-Length", end - start + 1); - fs3.createReadStream(file2, { start, end }).pipe(res); + fs4.createReadStream(file2, { start, end }).pipe(res); } else { res.setHeader("Content-Length", size); - fs3.createReadStream(file2).pipe(res); + fs4.createReadStream(file2).pipe(res); } } return { @@ -14630,17 +14657,17 @@ function createMediaLibrary(root) { chunks.push(chunk); } if (size < 16) throw new Error("\u89C6\u9891\u6587\u4EF6\u4E3A\u7A7A"); - const id = randomUUID2(), file2 = path3.join(dir, id + extension), row = { id, name, camera: "\u6211\u7684\u753B\u9762", url: "/api/media/clip/" + id, type: "video", file: file2 }; - fs3.writeFileSync(file2, Buffer.concat(chunks)); - fs3.writeFileSync(path3.join(dir, id + ".json"), JSON.stringify(row)); + const id2 = randomUUID3(), file2 = path3.join(dir, id2 + extension), row = { id: id2, name, camera: "\u6211\u7684\u753B\u9762", url: "/api/media/clip/" + id2, type: "video", file: file2 }; + fs4.writeFileSync(file2, Buffer.concat(chunks)); + fs4.writeFileSync(path3.join(dir, id2 + ".json"), JSON.stringify(row)); res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ ...row, file: void 0 })); return true; } if (url2.pathname.startsWith("/api/media/clip/") && req.method === "GET") { - const id = url2.pathname.split("/").at(-1); - if (!/^[a-zA-Z0-9_-]+$/.test(id)) throw new Error("\u753B\u9762\u7F16\u53F7\u65E0\u6548"); - const row = [...rows, ...uploaded()].find((r) => r.id === id); + const id2 = url2.pathname.split("/").at(-1); + if (!/^[a-zA-Z0-9_-]+$/.test(id2)) throw new Error("\u753B\u9762\u7F16\u53F7\u65E0\u6548"); + const row = [...rows, ...uploaded()].find((r) => r.id === id2); if (!row) throw new Error("\u753B\u9762\u4E0D\u5B58\u5728"); sendFile(req, res, row.file); return true; @@ -14650,6 +14677,761 @@ function createMediaLibrary(root) { }; } +// server/app-api.mjs +import fs5 from "node:fs"; +import path4 from "node:path"; +import { randomBytes, randomUUID as randomUUID4, createHash, timingSafeEqual } from "node:crypto"; + +// server/app-contract.mjs +var API_VERSION = "1.1.0"; +var id = external_exports.string().min(1).max(160).regex(/^[a-zA-Z0-9_-]+$/); +var short = external_exports.string().min(1).max(120); +var iso = external_exports.string().datetime(); +var revision = external_exports.number().int().min(1); +var strict = (shape) => external_exports.object(shape).strict(); +var ACTIONS = ["night_vision.set", "ptz.preset.goto", "alarm.set", "light.set", "motion_detection.set"]; +var action = external_exports.enum(ACTIONS); +var capabilities = strict({ + live: external_exports.boolean(), + frames: external_exports.boolean(), + events: external_exports.boolean(), + actions: external_exports.array(action).max(5), + nightVisionModes: external_exports.array(strict({ key: external_exports.number().int(), label: short })).max(20).default([]), + presetIndices: external_exports.array(external_exports.number().int().min(0).max(255)).max(20).default([]), + detectionTypes: external_exports.array(short).max(20).default([]), + alarmTypes: external_exports.array(external_exports.enum(["SOUND_ONLY", "LIGHT_ONLY", "SOUND_AND_LIGHT"])).max(3).default([]) +}).strict(); +var activation = strict({ setupId: id, confirmation: strict({ target: external_exports.literal(true), rule: external_exports.literal(true) }), remember: external_exports.boolean().default(false), interval: external_exports.number().min(1).max(30).default(3) }); +var commandBase = { clientId: id, deviceId: id, reason: external_exports.string().min(1).max(240), watchId: id.optional(), eventId: id.optional(), expiresInSeconds: external_exports.number().int().min(10).max(120).default(60) }; +var command = external_exports.discriminatedUnion("action", [ + strict({ ...commandBase, action: external_exports.literal("night_vision.set"), params: strict({ modeKey: external_exports.number().int() }) }), + strict({ ...commandBase, action: external_exports.literal("ptz.preset.goto"), params: strict({ index: external_exports.number().int().min(0).max(255) }) }), + strict({ ...commandBase, action: external_exports.literal("alarm.set"), params: strict({ enabled: external_exports.boolean(), type: external_exports.enum(["SOUND_ONLY", "LIGHT_ONLY", "SOUND_AND_LIGHT"]) }) }), + strict({ ...commandBase, action: external_exports.literal("light.set"), params: strict({ enabled: external_exports.boolean() }) }), + strict({ ...commandBase, action: external_exports.literal("motion_detection.set"), params: strict({ types: external_exports.array(short).min(1).max(20) }) }) +]); +var routes = [ + ["GET", "/bootstrap", null, "\u8BFB\u53D6\u7A7A\u95F4\u548C\u670D\u52A1\u80FD\u529B"], + ["POST", "/clients", strict({ name: short, platform: external_exports.enum(["ios", "android", "web", "test"]), appVersion: short }), "\u767B\u8BB0 App \u5B89\u88C5\u5B9E\u4F8B"], + ["POST", "/clients/{id}/heartbeat", strict({ foreground: external_exports.boolean(), sdkReady: external_exports.boolean() }), "\u66F4\u65B0\u63A5\u5165\u7AEF\u5FC3\u8DF3"], + ["GET", "/devices", null, "\u67E5\u8BE2\u8BBE\u5907\u53CA\u8FDE\u63A5\u72B6\u6001"], + ["POST", "/devices", strict({ deviceId: id, clientId: id, name: short, model: short, capabilities }), "\u767B\u8BB0\u8BBE\u5907\u4E0E\u5B9E\u9645 SDK \u80FD\u529B"], + ["POST", "/devices/{id}/status", strict({ clientId: id, online: external_exports.boolean(), observedAt: iso, viewChanged: external_exports.boolean().default(false), state: external_exports.record(external_exports.string(), external_exports.union([external_exports.string().max(120), external_exports.number(), external_exports.boolean(), external_exports.array(external_exports.string().max(120))])).default({}) }), "\u4E0A\u62A5\u8BBE\u5907\u72B6\u6001\u548C\u89C6\u91CE\u53D8\u5316"], + ["POST", "/device-events", strict({ clientId: id, deviceId: id, eventId: id, type: external_exports.enum(["motion", "person", "pet", "vehicle", "doorbell", "other"]), occurredAt: iso, summary: external_exports.string().max(300).default("") }), "\u4E0A\u4F20\u786C\u4EF6\u4E8B\u4EF6\u5E76\u83B7\u53D6\u53D6\u8BC1\u5EFA\u8BAE"], + ["POST", "/setups/draft", setupDraftSchema.extend({ viewRevision: revision }), "\u7406\u89E3\u9700\u6C42\u5E76\u63D0\u51FA\u5BF9\u8C61\u4E0E\u6F84\u6E05\u95EE\u9898"], + ["POST", "/setups/prepare", setupPrepareSchema.extend({ viewRevision: revision, category: external_exports.enum(["security", "care", "memory", "routine"]).optional(), attentionLevel: external_exports.number().int().min(0).max(4).optional() }), "\u6309\u7528\u6237\u786E\u8BA4\u751F\u6210\u89C4\u5219"], + ["GET", "/setups/{id}", null, "\u6062\u590D\u8BBE\u7F6E\u8349\u7A3F\u548C\u8BD5\u89C2\u5BDF\u7ED3\u679C"], + ["POST", "/setups/{id}/trial", strict({ frames: external_exports.array(frameSchema).min(3).max(5), viewRevision: revision }), "\u8BD5\u89C2\u5BDF\u5F53\u524D\u89C6\u91CE"], + ["POST", "/watches", activation, "\u786E\u8BA4\u5E76\u542F\u7528\u5173\u6CE8"], + ["GET", "/watches", null, "\u67E5\u8BE2\u7A7A\u95F4\u7684\u5168\u90E8\u5173\u6CE8"], + ["GET", "/watches/{id}", null, "\u8BFB\u53D6\u5173\u6CE8\u548C\u6700\u8FD1\u72B6\u6001"], + ["POST", "/watches/{id}/observe", strict({ clientId: id, viewRevision: revision, frame: frameSchema, manual: external_exports.boolean().default(false), signals: external_exports.array(external_exports.enum(["away", "rain", "doorbell"])).max(3).default([]) }), "\u4E0A\u4F20\u4E00\u5E27\u5E76\u5B8C\u6210\u89C6\u89C9\u4E0E\u89C4\u5219\u5224\u65AD"], + ["POST", "/watches/{id}/state", strict({ state: external_exports.enum(["paused", "active"]) }), "\u6682\u505C\u6216\u7EE7\u7EED\u5173\u6CE8"], + ["POST", "/watches/{id}/replace", activation, "\u786E\u8BA4\u65B0\u8BBE\u7F6E\u5E76\u66FF\u6362\u65E7\u5173\u6CE8"], + ["POST", "/watches/{id}/delete", strict({ confirmed: external_exports.literal(true), deleteMemory: external_exports.boolean().default(false) }), "\u5220\u9664\u5173\u6CE8\u4E0E\u5173\u8054\u8BC1\u636E"], + ["GET", "/events", null, "\u8BFB\u53D6\u4E8B\u4EF6\u53CA\u72EC\u7ACB\u5904\u7406\u72B6\u6001"], + ["POST", "/events/{id}/actions", strict({ clientId: id, action: external_exports.enum(["read", "take_over", "user_completed", "dismiss", "reopen"]), expectedRevision: revision, note: external_exports.string().max(240).default("") }), "\u8BB0\u5F55\u7528\u6237\u5904\u7406\u52A8\u4F5C"], + ["GET", "/commands", null, "\u8BFB\u53D6\u8BBE\u5907\u64CD\u4F5C\u53CA\u72B6\u6001"], + ["POST", "/commands", command, "\u521B\u5EFA\u5F85\u786E\u8BA4\u7684\u8BBE\u5907\u64CD\u4F5C"], + ["POST", "/commands/{id}/decision", strict({ clientId: id, decision: external_exports.enum(["confirm", "cancel"]), expectedRevision: revision }), "\u786E\u8BA4\u6216\u53D6\u6D88\u5177\u4F53\u8BBE\u5907\u64CD\u4F5C"], + ["POST", "/commands/{id}/claim", strict({ clientId: id, expectedRevision: revision }), "\u552F\u4E00\u6267\u884C\u7AEF\u9886\u53D6\u64CD\u4F5C"], + ["POST", "/commands/{id}/receipt", strict({ clientId: id, executionToken: external_exports.string().length(64), outcome: external_exports.enum(["succeeded", "failed", "unknown"]), sdkCode: external_exports.string().max(80).default(""), message: external_exports.string().max(240).default(""), durationMs: external_exports.number().min(0).max(12e4) }), "\u8BB0\u5F55 SDK \u6267\u884C\u56DE\u6267"], + ["POST", "/commands/{id}/verify", strict({ clientId: id, executionToken: external_exports.string().length(64), observedAt: iso, state: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.array(external_exports.string())])).default({}), setupId: id.optional(), targetConfirmed: external_exports.boolean().optional() }), "\u9A8C\u8BC1\u8BBE\u5907\u8BFB\u56DE\u72B6\u6001\u6216\u91CD\u65B0\u8BD5\u89C2\u5BDF\u7ED3\u679C"], + ["GET", "/memories", null, "\u67E5\u8BE2\u5DF2\u786E\u8BA4\u5BF9\u8C61\u8BB0\u5FC6"], + ["GET", "/memories/{id}", null, "\u8BFB\u53D6\u5BF9\u8C61\u53C2\u8003\u56FE\u53CA\u786E\u8BA4\u4FE1\u606F"], + ["POST", "/memories/{id}/delete", strict({ confirmed: external_exports.literal(true), cascade: external_exports.boolean() }), "\u5220\u9664\u8BB0\u5FC6\u5E76\u660E\u786E\u5904\u7406\u4F9D\u8D56\u5173\u6CE8"], + ["GET", "/metrics", null, "\u8BFB\u53D6\u8BF7\u6C42 \u4E8B\u4EF6 \u8BBE\u5907\u64CD\u4F5C\u7EDF\u8BA1"], + ["GET", "/privacy", null, "\u8BFB\u53D6\u4FDD\u5B58\u7B56\u7565\u4E0E\u5904\u7406\u4F4D\u7F6E"], + ["GET", "/export", null, "\u5BFC\u51FA\u5F53\u524D\u7A7A\u95F4\u7684\u8BBE\u7F6E\u4E0E\u8BB0\u5F55"] +]; +var jsonContent = (schema) => ({ "application/json": { schema } }); +var ref = (name) => ({ $ref: "#/components/schemas/" + name }); +var arrayOf = (name) => ({ type: "array", items: ref(name) }); +var timestamp = { type: ["string", "null"], format: "date-time" }; +var record2 = { type: "object", additionalProperties: true }; +var dtoSchemas = { + 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: record2, capabilities: external_exports.toJSONSchema(capabilities) } }, + Setup: { type: "object", required: ["id", "plan", "binding", "deviceId", "viewRevision"], properties: { id: { type: "string" }, request: { type: "string" }, plan: external_exports.toJSONSchema(ContractSchema), binding: record2, 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: external_exports.toJSONSchema(ContractSchema), binding: record2, state: { enum: ["active", "paused", "replaced"] }, observationStatus: { enum: ["observing", "awaiting_evidence", "needs_reconfirmation", "connection_interrupted", "paused", "replaced"] }, sourceOnline: { type: "boolean" }, needsReconfirmation: { type: "boolean" }, viewRevision: { type: "integer" }, currentViewRevision: { type: "integer" }, lastConfirmedAt: timestamp, 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: record2 } } }, + 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: record2 } } }, + 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: record2, 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: "\u4EC5 claim \u54CD\u5E94\u8FD4\u56DE\uFF1B\u4FDD\u5B58\u5230\u5B89\u5168\u5B58\u50A8\uFF0C\u7981\u6B62\u5C55\u793A\u4E0E\u65E5\u5FD7\u8BB0\u5F55" }, receipt: record2, verification: record2 } }, + Observation: { type: "object", required: ["notices", "details", "latencyMs", "engineMs", "outcome"], properties: { answers: record2, trace: record2, notices: { type: "array", items: record2 }, details: { type: "array", items: record2 }, 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: record2, targetBox: record2, regionBox: record2, 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/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 record2; +} +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 error48 = { 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: "\u540C\u4E00\u6B21\u64CD\u4F5C\u91CD\u8BD5\u4F7F\u7528\u539F\u503C\uFF1B\u540C\u952E\u4E0D\u540C\u6B63\u6587\u8FD4\u56DE 409\u3002\u4FDD\u7559 24 \u5C0F\u65F6\uFF1B\u5FC3\u8DF3\u548C\u672A\u53D8\u66F4\u89C6\u91CE\u7684\u72B6\u6001\u4FDD\u7559 60 \u79D2\u3002" }); + if (route === "/commands") parameters.push({ name: "deviceId", in: "query", schema: { type: "string" } }); + const success2 = { ...envelope, properties: { ...envelope.properties, data: responseData(method, route) } }; + const responses = { "200": { description: "\u6210\u529F\uFF1B\u8BBE\u5907\u6267\u884C\u4E0E\u9A8C\u8BC1\u72B6\u6001\u5728 data.status \u4E2D", content: jsonContent(success2) } }; + for (const code of ["400", "401", "403", "404", "409", "410", "413", "422", "429", "502", "503"]) responses[code] = { description: "\u7ED3\u6784\u5316\u9519\u8BEF", content: jsonContent(error48) }; + 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(external_exports.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: "\u5EFA\u7ACB\u72EC\u7ACB\u8054\u8C03\u7A7A\u95F4\uFF1B\u5C06\u8FD4\u56DE\u7684 token \u4FDD\u5B58\u5728\u7CFB\u7EDF\u5B89\u5168\u5B58\u50A8", security: [], responses: { "201": { description: "token \u4EC5\u5728\u6B64\u8FD4\u56DE\uFF1B\u5B83\u662F\u7A7A\u95F4\u8BBF\u95EE\u51ED\u636E\uFF0C\u4E0D\u662F eufy \u767B\u5F55\u51ED\u636E", content: jsonContent(sessionSchema) } } } }; + paths["/api/v1/openapi.json"] = { get: { summary: "\u4E0B\u8F7D\u672C\u63A5\u53E3\u89C4\u8303", 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 \u8D1F\u8D23\u8BBE\u5907\u8FDE\u63A5\u548C\u6267\u884C\uFF1B\u672C API \u8D1F\u8D23\u4EFB\u52A1\u3001\u6A21\u578B\u3001\u72B6\u6001\u4E0E\u95ED\u73AF\u3002\u4F1A\u8BDD\u4E3A\u5171\u4EAB\u7A7A\u95F4\u51ED\u636E\uFF1B\u751F\u4EA7\u8D26\u6237\u767B\u5F55\u548C\u6210\u5458\u89D2\u8272\u53E6\u884C\u63A5\u5165\u3002\u6240\u6709\u65F6\u95F4\u4E3A UTC ISO 8601\uFF0C\u754C\u9762\u6309\u5BB6\u5EAD\u65F6\u533A\u663E\u793A\u3002" }, 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 \u7A7A\u95F4\u4EE4\u724C\uFF1B\u4E0D\u8981\u4F7F\u7528 HF\u3001Kimi \u6216 eufy \u5BC6\u94A5" } } }, paths }; +} + +// server/app-api.mjs +var WORKSPACE_TOKEN = /^[a-f0-9]{64}$/; +var DAY = 864e5; +var TERMINAL = /* @__PURE__ */ new Set(["verified", "failed", "cancelled", "expired", "verification_failed"]); +var AppError = class extends Error { + constructor(status, code, message, details) { + super(message); + Object.assign(this, { status, code, details }); + } +}; +var fail = (status, code, message, details) => { + throw new AppError(status, code, message, details); +}; +var digest = (value) => createHash("sha256").update(value).digest("hex"); +var 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); +var equal = (a, b) => { + const x = Buffer.from(a || ""), y = Buffer.from(b || ""); + return !!x.length && x.length === y.length && timingSafeEqual(x, y); +}; +var noImages = (value) => JSON.parse(JSON.stringify(value, (key, v) => ["image", "annotated", "pairImage", "referenceImage", "annotatedReference", "targetCrop", "evidence"].includes(key) ? void 0 : v)); +function appEnvelope(data, requestId = randomUUID4(), now = Date.now()) { + return { data, requestId, serverTime: new Date(now).toISOString(), apiVersion: API_VERSION }; +} +function appError(error48, requestId = randomUUID4(), now = Date.now()) { + if (error48?.code && /^E(?:PERM|ACCES|NOENT|NOSPC|IO|BUSY)$/.test(error48.code)) error48 = new AppError(503, "STORAGE_UNAVAILABLE", "\u8BB0\u5F55\u6682\u65F6\u672A\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u67E5\u8BE2\u72B6\u6001"); + const validation = error48?.name === "ZodError"; + const status = validation ? 422 : error48.status || 502; + return { status, body: { error: { code: validation ? "VALIDATION_ERROR" : error48.code || "UPSTREAM_FAILED", message: validation ? "\u8BF7\u68C0\u67E5\u8BF7\u6C42\u5B57\u6BB5" : error48.message || "\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528", retryable: [429, 502, 503, 504].includes(status), ...validation ? { details: error48.issues.map((x) => ({ path: x.path.join("."), message: x.message })) } : error48.details ? { details: error48.details } : {} }, requestId, serverTime: new Date(now).toISOString(), apiVersion: API_VERSION } }; +} +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; +} +function appPublic(req, url2) { + if (req.method === "GET" && url2.pathname === "/api/v1/openapi.json") return { status: 200, body: openapi() }; + if (req.method === "POST" && url2.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; +} +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", "\u5355\u6B21\u8BF7\u6C42\u4E0D\u80FD\u8D85\u8FC7 6 MB"); + chunks.push(chunk); + } + try { + return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"); + } catch { + fail(400, "INVALID_JSON", "\u8BF7\u6C42\u6B63\u6587\u9700\u8981\u6709\u6548 JSON"); + } +} +function createAppApi(root, { grounded, journal, metrics, clock = Date.now } = {}) { + const dir = path4.join(root, ".local", "app-api"), file2 = path4.join(dir, "state.json"); + fs5.mkdirSync(dir, { recursive: true }); + const empty = { version: 1, clients: {}, devices: {}, hardwareEvents: {}, commands: {}, events: {}, watchMeta: {}, setupMeta: {}, frames: {}, idempotency: {} }; + let db = fs5.existsSync(file2) ? { ...empty, ...JSON.parse(fs5.readFileSync(file2, "utf8")) } : empty; + const inFlight = /* @__PURE__ */ new Map(), busyWatches = /* @__PURE__ */ new Set(); + const now = () => clock(), iso2 = () => new Date(now()).toISOString(), service = () => grounded(); + const save = () => writeAtomic(file2, JSON.stringify(db)); + const list = (kind) => Object.values(db[kind]); + const get = (kind, id2) => db[kind][id2] || fail(404, "NOT_FOUND", "\u8BB0\u5F55\u4E0D\u5B58\u5728"); + 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, id2) => { + try { + return service().repo.get(kind, id2); + } catch { + fail(404, "NOT_FOUND", "\u8BB0\u5F55\u4E0D\u5B58\u5728"); + } + }; + const client = (id2) => get("clients", id2); + const isOnline = (d) => d.online && d.lastSeen && now() - Date.parse(d.lastSeen) <= 45e3 && db.clients[d.clientId]?.sdkReady && now() - Date.parse(db.clients[d.clientId].lastSeen) <= 45e3; + const device = (id2) => get("devices", id2); + const assertOwner = (d, clientId) => { + client(clientId); + if (d.clientId !== clientId) fail(403, "EXECUTOR_MISMATCH", "\u8BF7\u7531\u8FDE\u63A5\u8FD9\u53F0\u8BBE\u5907\u7684 App \u6267\u884C"); + }; + const assertLive = (d) => { + if (!isOnline(d)) fail(409, "DEVICE_OFFLINE", "\u8BBE\u5907\u63A5\u5165\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u6253\u5F00\u5DF2\u8FDE\u63A5\u8BBE\u5907\u7684 App"); + }; + const assertView = (d, viewRevision) => { + if (d.viewRevision !== viewRevision) fail(409, "VIEW_CHANGED", "\u89C2\u5BDF\u4F4D\u7F6E\u53D8\u4E86\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4\u8303\u56F4", { viewRevision: d.viewRevision }); + }; + const assertFresh = (at, maxAge = 12e4) => { + const t = Date.parse(at); + if (!Number.isFinite(t) || t > now() + 1e3 || now() - t > maxAge) fail(409, "STALE_EVIDENCE", "\u8BF7\u83B7\u53D6\u5F53\u524D\u753B\u9762\u6216\u8BBE\u5907\u72B6\u6001"); + }; + function invalidateView(d) { + d.viewRevision++; + d.viewChangedAt = iso2(); + 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 = iso2(); + changed = true; + } + if (c.status === "executing" && Date.parse(c.executionDeadline) <= now()) { + c.status = "result_unknown"; + c.revision++; + c.updatedAt = iso2(); + 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 [id2, m] of Object.entries(db.setupMeta)) if (now() - Date.parse(m.createdAt) > DAY) { + let s; + try { + s = service().repo.get("setup", id2); + } catch { + delete db.setupMeta[id2]; + changed = true; + continue; + } + if (!s.activatedId) { + service().repo.remove("setup", id2); + delete db.setupMeta[id2]; + changed = true; + } + } + 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, 6e4); + timer.unref(); + function checkAction(d, c) { + if (!d.capabilities.actions.includes(c.action)) fail(422, "UNSUPPORTED_ACTION", "\u8FD9\u53F0\u8BBE\u5907\u4E0D\u652F\u6301\u6B64\u64CD\u4F5C"); + 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", "\u8BF7\u9009\u62E9\u8BBE\u5907\u5B9E\u9645\u652F\u6301\u7684\u591C\u89C6\u6A21\u5F0F"); + if (c.action === "ptz.preset.goto" && !cap.presetIndices.includes(p.index)) fail(422, "UNSUPPORTED_OPTION", "\u8FD9\u4E2A\u9884\u7F6E\u4F4D\u7F6E\u4E0D\u53EF\u7528"); + if (c.action === "alarm.set" && !cap.alarmTypes.includes(p.type)) fail(422, "UNSUPPORTED_OPTION", "\u8FD9\u4E2A\u62A5\u8B66\u65B9\u5F0F\u4E0D\u53EF\u7528"); + if (c.action === "motion_detection.set" && p.types.some((t) => !cap.detectionTypes.includes(t))) fail(422, "UNSUPPORTED_OPTION", "\u8BF7\u9009\u62E9\u8BBE\u5907\u5B9E\u9645\u652F\u6301\u7684\u68C0\u6D4B\u7C7B\u578B"); + } + const publicCommand = (c) => { + const { executionToken, ...rest } = c; + return rest; + }; + const revise = (row, patch) => Object.assign(row, patch, { revision: row.revision + 1, updatedAt: iso2() }); + const expectRevision = (row, n) => { + if (row.revision !== n) fail(409, "REVISION_CONFLICT", "\u72B6\u6001\u5DF2\u66F4\u65B0\uFF0C\u8BF7\u5237\u65B0\u540E\u518D\u64CD\u4F5C", { revision: row.revision }); + }; + function watch(id2) { + const s = repoGet("registration", id2), m = db.watchMeta[id2]; + if (!m) fail(409, "WATCH_NOT_BOUND", "\u8FD9\u4EFD\u5173\u6CE8\u5C1A\u672A\u7ED1\u5B9A App \u8BBE\u5907\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4\u753B\u9762\u6765\u6E90"); + return { s, m, d: device(m.deviceId) }; + } + function watchPublic(id2, full = false) { + const { s, m, d } = watch(id2); + let state; + try { + state = service().repo.get("state", id2); + } catch { + } + const last = state?.at, fresh = last && now() - Date.parse(last) < 12e4; + return { + id: id2, + 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 ? "observing" : "awaiting_evidence", + lastConfirmedAt: last || null, + lastResult: fresh ? state?.text || null : null, + sourceOnline: !!isOnline(d), + currentViewRevision: d.viewRevision, + observations: (state?.observations || []).slice(0, 20) + }; + } + function ensureSetup(id2) { + const setup = repoGet("setup", id2), meta3 = db.setupMeta[id2]; + if (!meta3) fail(409, "SETUP_NOT_BOUND", "\u8BF7\u901A\u8FC7 App \u63A5\u53E3\u91CD\u65B0\u51C6\u5907\u8FD9\u4EFD\u8BBE\u7F6E"); + const d = device(meta3.deviceId); + assertLive(d); + assertView(d, meta3.viewRevision); + return { setup, meta: meta3, d }; + } + async function activate(body) { + const { meta: meta3, d } = ensureSetup(body.setupId); + if (!d.capabilities.frames) fail(409, "FRAME_SOURCE_UNAVAILABLE", "\u5F53\u524D\u8BBE\u5907\u65E0\u6CD5\u63D0\u4F9B\u89C2\u5BDF\u753B\u9762"); + const r = await legacy("POST", "/api/setup/activate", body); + db.watchMeta[r.id] ||= { id: r.id, deviceId: d.id, viewRevision: meta3.viewRevision, state: "active", needsReconfirmation: false, createdAt: iso2(), intervalSeconds: body.interval, category: meta3.category || "routine", attentionLevel: meta3.attentionLevel ?? 2 }; + save(); + return watchPublic(r.id); + } + function removeWatch(id2, deleteMemory) { + if (busyWatches.has(id2)) fail(409, "OBSERVATION_IN_PROGRESS", "\u672C\u6B21\u89C2\u5BDF\u6B63\u5728\u5B8C\u6210\uFF0C\u8BF7\u7A0D\u540E\u5220\u9664"); + if (list("commands").some((c) => c.watchId === id2 && ["executing", "result_unknown", "awaiting_verification"].includes(c.status))) fail(409, "COMMAND_UNRESOLVED", "\u8BBE\u5907\u64CD\u4F5C\u7ED3\u679C\u8FD8\u9700\u786E\u8BA4\uFF0C\u8BF7\u5148\u5904\u7406\u8FD9\u6761\u64CD\u4F5C"); + const { s } = watch(id2); + for (const kind of ["registration", "state"]) try { + service().repo.remove(kind, id2); + } catch { + } + try { + service().repo.remove("setup", s.setupId); + } catch { + } + delete db.setupMeta[s.setupId]; + if (deleteMemory && s.memoryId) { + const dependencies = list("watchMeta").filter((m) => m.id !== id2).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 { + } + } + delete db.watchMeta[id2]; + service().forget(id2); + journal?.().removeWhere?.((r) => r.itemId === id2 || r.itemId === s.setupId); + for (const kind of ["events", "frames", "commands"]) for (const [key, row] of Object.entries(db[kind])) if (row.watchId === id2) 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", "\u5173\u8054\u8D44\u6599\u5DF2\u5220\u9664\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u5F53\u524D\u72B6\u6001")); + } + 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 * 1e3).toISOString(), + createdAt: iso2(), + updatedAt: iso2(), + revision: 1, + attentionLevel: 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((e2) => e2.watchId === watchId && e2.ruleId === rule.id && !e2.visualRecoveryAt)) revise(e, { visualRecoveryAt: result.at, closedAt: e.closedAt || iso2() }); + } + async function dispatch(method, route, p, b, token) { + const current = iso2(); + 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, continuousCapture: "requires_connected_executor", storage: process.env.HOME_PULSE_CLOUD === "1" ? "hf_ephemeral_disk" : "local_disk" }; + if (route === "/clients") { + const row = { id: randomUUID4(), ...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", "\u8BBE\u5907\u5DF2\u7531\u53E6\u4E00\u4E2A App \u63A5\u5165\uFF0C\u8BF7\u4F7F\u7528\u539F\u63A5\u5165\u7AEF"); + 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", "\u8FD9\u4EFD\u8BBE\u5907\u72B6\u6001\u65E9\u4E8E\u5DF2\u4FDD\u5B58\u72B6\u6001"); + 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); + 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", "\u540C\u4E00\u8BBE\u5907\u4E8B\u4EF6\u7F16\u53F7\u5305\u542B\u4E0D\u540C\u5185\u5BB9"); + return { ...previous, duplicate: true, work: [] }; + } + assertFresh(b.occurredAt, DAY); + const active = list("watchMeta").filter((m) => m.deviceId === d.id && m.state === "active" && !m.needsReconfirmation); + const fresh = now() - Date.parse(b.occurredAt) <= 12e4; + const canCapture = fresh && isOnline(d) && d.capabilities.frames && (!d.lastCaptureRequestedAt || now() - Date.parse(d.lastCaptureRequestedAt) >= 3e3); + 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() + 3e4).toISOString(), minimumIntervalSeconds: m.intervalSeconds })) : [] }; + 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); + return legacy("POST", "/api/setup/draft", b); + } + if (route === "/setups/prepare") { + const d = device(b.binding.source.id); + assertLive(d); + assertView(d, b.viewRevision); + const r = await legacy("POST", "/api/setup/prepare", b); + assertView(d, b.viewRevision); + db.setupMeta[r.id] = { deviceId: d.id, viewRevision: d.viewRevision, createdAt: iso2(), 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 = iso2(); + 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", "\u8BF7\u91CD\u65B0\u786E\u8BA4\u5BF9\u8C61\u548C\u89C2\u5BDF\u8303\u56F4"); + if (m.state !== "active") fail(409, "WATCH_PAUSED", "\u8FD9\u4EFD\u5173\u6CE8\u5DF2\u6682\u505C"); + if (b.frame.sourceId !== d.id) fail(409, "SOURCE_MISMATCH", "\u753B\u9762\u6765\u6E90\u4E0E\u5173\u6CE8\u8BBE\u5907\u4E0D\u4E00\u81F4"); + 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", "\u540C\u4E00\u753B\u9762\u7F16\u53F7\u4E0D\u80FD\u7528\u4E8E\u4E0D\u540C\u5185\u5BB9"); + return { ...old.result, duplicate: true }; + } + if (busyWatches.has(p.id)) fail(409, "OBSERVATION_IN_PROGRESS", "\u4E0A\u4E00\u8F6E\u89C2\u5BDF\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u7B49\u5F85\u7ED3\u679C"); + 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", "\u89C2\u5BDF\u671F\u95F4\u89C6\u91CE\u6216\u5173\u6CE8\u72B6\u6001\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4"); + } + 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: iso2(), 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", "\u8BF7\u5148\u91CD\u65B0\u786E\u8BA4\u89C2\u5BDF\u8303\u56F4"); + } + m.state = b.state; + m.updatedAt = current; + save(); + return watchPublic(p.id); + } + if (route === "/watches/{id}/replace") { + const { m } = watch(p.id), { meta: meta3 } = ensureSetup(b.setupId); + if (meta3.deviceId !== m.deviceId) fail(409, "SOURCE_MISMATCH", "\u6362\u6444\u50CF\u5934\u9700\u8981\u65B0\u5EFA\u5173\u6CE8"); + if (busyWatches.has(p.id)) fail(409, "OBSERVATION_IN_PROGRESS", "\u4E0A\u4E00\u8F6E\u89C2\u5BDF\u5C1A\u672A\u5B8C\u6210"); + 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, b2) => b2.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", "\u8FD9\u6B21\u4E8B\u4EF6\u5DF2\u7ED3\u675F"); + 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", "\u753B\u9762\u5DF2\u786E\u8BA4\u6062\u590D\uFF0C\u8BF7\u7EE7\u7EED\u5173\u6CE8\u4E0B\u4E00\u6B21\u53D8\u5316"); + 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", "\u64CD\u4F5C\u8BBE\u5907\u4E0E\u5173\u6CE8\u4E0D\u4E00\u81F4"); + if (b.eventId) { + const e = get("events", b.eventId); + if (b.watchId && e.watchId !== b.watchId) fail(409, "EVENT_MISMATCH", "\u4E8B\u4EF6\u4E0D\u5C5E\u4E8E\u8FD9\u4EFD\u5173\u6CE8"); + if (watch(e.watchId).d.id !== d.id) fail(409, "SOURCE_MISMATCH", "\u64CD\u4F5C\u8BBE\u5907\u4E0E\u4E8B\u4EF6\u4E0D\u4E00\u81F4"); + } + const c = { id: randomUUID4(), ...b, status: "awaiting_confirmation", revision: 1, viewRevision: d.viewRevision, createdAt: current, updatedAt: current, expiresAt: new Date(now() + b.expiresInSeconds * 1e3).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", "\u8FD9\u6761\u64CD\u4F5C\u5DF2\u4E0D\u80FD\u786E\u8BA4\u6216\u53D6\u6D88"); + if (b.decision === "confirm") { + if (c.status !== "awaiting_confirmation") fail(409, "INVALID_TRANSITION", "\u8FD9\u6761\u64CD\u4F5C\u5DF2\u7ECF\u786E\u8BA4"); + 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", "\u8FD9\u6761\u64CD\u4F5C\u4E0D\u53EF\u91CD\u590D\u9886\u53D6"); + 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", "\u753B\u9762\u6B63\u5728\u5206\u6790\uFF0C\u8BF7\u7A0D\u540E\u8C03\u6574\u89C6\u89D2"); + const executionToken = randomBytes(32).toString("hex"); + revise(c, { status: "executing", executorId: b.clientId, executionToken, executionStartedAt: current, executionDeadline: new Date(Math.min(now() + 15e3, 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", "\u6267\u884C\u51ED\u636E\u4E0D\u5339\u914D"); + if (route.endsWith("/receipt")) { + if (!["executing", "result_unknown"].includes(c.status)) fail(409, "INVALID_TRANSITION", "\u8BE5\u56DE\u6267\u5DF2\u7ECF\u8BB0\u5F55\u6216\u64CD\u4F5C\u5DF2\u7ED3\u675F"); + 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", "\u8BF7\u5148\u63D0\u4EA4\u6267\u884C\u7ED3\u679C"); + assertFresh(b.observedAt); + if (Date.parse(b.observedAt) < Date.parse(c.executionStartedAt)) fail(409, "STALE_EVIDENCE", "\u8BF7\u8BFB\u53D6\u64CD\u4F5C\u540E\u7684\u8BBE\u5907\u72B6\u6001"); + 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", "\u8BF7\u91CD\u65B0\u5708\u9009\u5BF9\u8C61\u548C\u8303\u56F4\u5E76\u5B8C\u6210\u8BD5\u89C2\u5BDF"); + const { setup, meta: meta3 } = ensureSetup(b.setupId); + matched = meta3.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 legacy("GET", "/api/memories"); + 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", "\u8FD9\u4EFD\u8BB0\u5FC6\u4ECD\u88AB\u5173\u6CE8\u4F7F\u7528", { watchIds: deps.map((s) => s.id) }); + if (deps.some((s) => !db.watchMeta[s.id])) fail(409, "LEGACY_DEPENDENCIES", "\u4ECD\u6709\u7F51\u9875\u65E7\u5173\u6CE8\u4F7F\u7528\u8FD9\u4EFD\u8BB0\u5FC6\uFF0C\u8BF7\u5148\u5728\u7F51\u9875\u5904\u7406\u8FD9\u4E9B\u5173\u6CE8"); + if (deps.some((s) => busyWatches.has(s.id))) fail(409, "OBSERVATION_IN_PROGRESS", "\u76F8\u5173\u5173\u6CE8\u6B63\u5728\u5206\u6790\uFF0C\u8BF7\u7A0D\u540E\u5220\u9664"); + 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", "\u63A5\u53E3\u4E0D\u5B58\u5728"); + } + async function handle(req, url2, body, token) { + const requestId = randomUUID4(); + try { + sweep(); + const routePath = url2.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", "\u63A5\u53E3\u4E0D\u5B58\u5728"); + params.deviceId = url2.searchParams.get("deviceId") || void 0; + 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", "\u6BCF\u4E2A\u64CD\u4F5C\u9700\u8981 8 \u81F3 100 \u4F4D Idempotency-Key"); + const fp = digest(method + " " + url2.pathname + " " + canonical(input)), prior = db.idempotency[key]; + if (prior) { + if (prior.fingerprint !== fp) fail(409, "IDEMPOTENCY_CONFLICT", "\u540C\u4E00\u64CD\u4F5C\u7F16\u53F7\u4E0D\u80FD\u7528\u4E8E\u4E0D\u540C\u8BF7\u6C42"); + if (inFlight.has(key)) return await inFlight.get(key); + if (prior.status === "indeterminate" || prior.status === "running") fail(409, "RESULT_UNKNOWN", "\u4E0A\u6B21\u64CD\u4F5C\u88AB\u4E2D\u65AD\uFF0C\u8BF7\u5148\u67E5\u8BE2\u8D44\u6E90\u72B6\u6001\uFF0C\u4E0D\u8981\u91CD\u590D\u6267\u884C"); + return prior.response; + } + if (Object.keys(db.idempotency).length >= 2e3) fail(429, "WORKSPACE_LIMIT", "\u672C\u7A7A\u95F4\u4ECA\u65E5\u64CD\u4F5C\u6B21\u6570\u5DF2\u8FBE\u4E0A\u9650"); + const retentionMs = match[1] === "/clients/{id}/heartbeat" || match[1] === "/devices/{id}/status" && !input.viewChanged ? 6e4 : 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 }; +} + // server/local-api.mjs var TZ = "Asia/Shanghai"; function dayKey(value) { @@ -14714,31 +15496,36 @@ var Journal = class { constructor(file2) { this.file = file2; this.records = /* @__PURE__ */ new Map(); - fs4.mkdirSync(path4.dirname(file2), { recursive: true }); - if (fs4.existsSync(file2)) for (const line of fs4.readFileSync(file2, "utf8").split("\n")) { + fs6.mkdirSync(path5.dirname(file2), { recursive: true }); + if (fs6.existsSync(file2)) for (const line of fs6.readFileSync(file2, "utf8").split("\n")) { try { - const { id, ...patch } = JSON.parse(line); - this.records.set(id, { ...this.records.get(id), ...patch, id }); + const { id: id2, ...patch } = JSON.parse(line); + this.records.set(id2, { ...this.records.get(id2), ...patch, id: id2 }); } catch { } } for (const r of this.records.values()) if (r.status === "running") this.update(r.id, { status: "error", error: "\u670D\u52A1\u91CD\u542F\uFF0C\u8BF7\u91CD\u65B0\u53D6\u8BC1", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }); } - update(id, patch) { - const record2 = { ...this.records.get(id), ...patch, id }; - fs4.appendFileSync(this.file, JSON.stringify({ id, ...patch }) + "\n", "utf8"); - this.records.set(id, record2); - return record2; + update(id2, patch) { + const record3 = { ...this.records.get(id2), ...patch, id: id2 }; + fs6.appendFileSync(this.file, JSON.stringify({ id: id2, ...patch }) + "\n", "utf8"); + this.records.set(id2, record3); + return record3; } list() { return [...this.records.values()]; } + removeWhere(predicate) { + for (const [id2, row] of this.records) if (predicate(row)) this.records.delete(id2); + writeAtomic(this.file, this.list().map((r) => JSON.stringify(r)).join("\n") + "\n"); + } }; -function localApiPlugin(root) { +function localApiPlugin(root, { appScoped = false } = {}) { let journal; let queue = Promise.resolve(); - let grounded, media; - const getJournal = () => journal ||= new Journal(path4.join(root, ".local", "telemetry.jsonl")); + let grounded, media, app; + const nativeWorkspaces = /* @__PURE__ */ new Map(); + const getJournal = () => journal ||= new Journal(path5.join(root, ".local", "telemetry.jsonl")); const send = (res, code, data) => { res.statusCode = code; res.setHeader("Content-Type", "application/json; charset=utf-8"); @@ -14755,25 +15542,55 @@ function localApiPlugin(root) { } return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"); }; + const getGrounded = () => grounded ||= createGroundedService(root, { journal: getJournal, enqueue: (task) => { + const pending = queue.then(task, task); + queue = pending.catch(() => { + }); + return pending; + } }); const middleware = async (req, res, next) => { if (!req.url?.startsWith("/api/")) return next(); const url2 = new URL(req.url, "http://localhost"); if (req.headers.origin && req.headers.origin !== `http://${req.headers.host}` && req.headers.origin !== `https://${req.headers.host}`) return send(res, 403, { error: "\u6765\u6E90\u4E0D\u5339\u914D" }); try { + if (url2.pathname.startsWith("/api/v1/")) { + const publicResult = appPublic(req, url2); + if (publicResult) return send(res, publicResult.status, publicResult.body); + const token = appToken(req); + if (!token) { + const error48 = appError(new AppError(401, "UNAUTHORIZED", "\u8BF7\u63D0\u4F9B Home Pulse \u7A7A\u95F4\u4EE4\u724C")); + return send(res, error48.status, error48.body); + } + if (!appScoped) { + let middleware2 = nativeWorkspaces.get(token); + if (!middleware2) { + if (nativeWorkspaces.size >= 2e3) { + const error48 = appError(new AppError(503, "WORKSPACE_LIMIT", "\u5F53\u524D\u8FDE\u63A5\u6570\u5DF2\u6EE1")); + return send(res, error48.status, error48.body); + } + localApiPlugin(path5.join(root, ".local", "app-workspaces", token), { appScoped: true }).configureServer({ middlewares: { use: (m) => middleware2 = m } }); + nativeWorkspaces.set(token, middleware2); + } + return runtimeContext.run({ ...runtimeContext.getStore(), plannerKey: readPlannerKey(root) }, () => middleware2(req, res, next)); + } + app ||= createAppApi(root, { grounded: getGrounded, journal: getJournal, metrics: () => summarize(getJournal().list(), "today") }); + try { + const result = await app.handle(req, url2, req.method === "GET" ? {} : await readAppBody(req), token); + return send(res, result.status, result.body); + } catch (e) { + const error48 = appError(e); + return send(res, error48.status, error48.body); + } + } if (url2.pathname.startsWith("/api/media/")) { media ||= createMediaLibrary(root); if (await media.handle(req, res, url2)) return; } if (/^\/api\/(setup\/|contracts\/|memories(?:\/|$)|grounded\/)/.test(url2.pathname)) { - grounded ||= createGroundedService(root, { journal: getJournal, enqueue: (task) => { - const pending = queue.then(task, task); - queue = pending.catch(() => { - }); - return pending; - } }); + grounded = getGrounded(); if (req.method === "GET" && url2.pathname.startsWith("/api/grounded/image/")) { - const [, , , , kind, id, field] = url2.pathname.split("/"); - const value = grounded.getImage(kind, id, field), match = value.match(/^data:(image\/[a-z]+);base64,(.+)$/); + const [, , , , kind, id2, field] = url2.pathname.split("/"); + const value = grounded.getImage(kind, id2, field), match = value.match(/^data:(image\/[a-z]+);base64,(.+)$/); if (!match) throw new Error("\u56FE\u7247\u4E0D\u5B58\u5728"); res.setHeader("Content-Type", match[1]); res.setHeader("Cache-Control", "no-store"); @@ -14784,7 +15601,7 @@ function localApiPlugin(root) { if (req.method === "GET" && url2.pathname === "/api/health") { let runtime = null; try { - const r = JSON.parse(fs4.readFileSync(path4.join(root, "..", "imajev-lab", "results", "runtime_info.json"), "utf8")); + const r = JSON.parse(fs6.readFileSync(path5.join(root, "..", "imajev-lab", "results", "runtime_info.json"), "utf8")); runtime = { model: r.model, gpu: r.gpu, memoryGiB: r.allocated_gib_after_load, quantization: "NF4 \xB7 4-bit", maxImageSide: r.max_image_side }; } catch { } @@ -14811,7 +15628,7 @@ function localApiPlugin(root) { } if (req.method === "POST" && url2.pathname === "/api/capture-failure") { const b = await read(req); - return send(res, 200, getJournal().update(randomUUID3(), { startedAt: (/* @__PURE__ */ new Date()).toISOString(), kind: "observation", status: "error", modelAttempt: false, captureCount: 0, error: String(b.error || "\u753B\u9762\u83B7\u53D6\u5931\u8D25").slice(0, 200), itemName: String(b.itemName || ""), camera: String(b.camera || ""), source: String(b.source || "\u624B\u52A8\u53D6\u8BC1") })); + return send(res, 200, getJournal().update(randomUUID5(), { startedAt: (/* @__PURE__ */ new Date()).toISOString(), kind: "observation", status: "error", modelAttempt: false, captureCount: 0, error: String(b.error || "\u753B\u9762\u83B7\u53D6\u5931\u8D25").slice(0, 200), itemName: String(b.itemName || ""), camera: String(b.camera || ""), source: String(b.source || "\u624B\u52A8\u53D6\u8BC1") })); } if (req.method === "POST" && url2.pathname === "/api/decision") { const b = await read(req), old = getJournal().records.get(b.id); @@ -14822,8 +15639,8 @@ function localApiPlugin(root) { if (req.method === "POST" && url2.pathname === "/api/analyze") { const body = await read(req); if (!body.instructions || !body.criteria || Object.keys(body.criteria).length < 2 || Object.keys(body.criteria).length > 12 || typeof body.image !== "string" || !/^data:image\/(jpeg|png|webp);base64,/.test(body.image)) return send(res, 422, { error: "\u8BF7\u63D0\u4F9B\u6709\u6548\u753B\u9762\u4E0E\u5224\u65AD\u9009\u9879" }); - const id = randomUUID3(), begin = performance3.now(), meta3 = body.meta || {}; - getJournal().update(id, { startedAt: (/* @__PURE__ */ new Date()).toISOString(), status: "running", captureId: meta3.captureId || id, captureCount: meta3.captureId && getJournal().list().some((r) => r.captureId === meta3.captureId) ? 0 : 1, modelAttempt: true, kind: meta3.kind === "grounding" ? "grounding" : "observation", itemName: String(meta3.itemName || "\u89C6\u89C9\u89C2\u5BDF").slice(0, 100), itemId: String(meta3.itemId || "").slice(0, 100), camera: String(meta3.camera || "").slice(0, 80), source: String(meta3.source || "\u624B\u52A8\u53D6\u8BC1").slice(0, 80), sourceName: String(meta3.sourceName || "").slice(0, 100), mediaTime: Number.isFinite(meta3.mediaTime) ? meta3.mediaTime : null }); + const id2 = randomUUID5(), begin = performance3.now(), meta3 = body.meta || {}; + getJournal().update(id2, { startedAt: (/* @__PURE__ */ new Date()).toISOString(), status: "running", captureId: meta3.captureId || id2, captureCount: meta3.captureId && getJournal().list().some((r) => r.captureId === meta3.captureId) ? 0 : 1, modelAttempt: true, kind: meta3.kind === "grounding" ? "grounding" : "observation", itemName: String(meta3.itemName || "\u89C6\u89C9\u89C2\u5BDF").slice(0, 100), itemId: String(meta3.itemId || "").slice(0, 100), camera: String(meta3.camera || "").slice(0, 80), source: String(meta3.source || "\u624B\u52A8\u53D6\u8BC1").slice(0, 80), sourceName: String(meta3.sourceName || "").slice(0, 100), mediaTime: Number.isFinite(meta3.mediaTime) ? meta3.mediaTime : null }); const task = async () => { const queueMs = Math.round(performance3.now() - begin); try { @@ -14835,12 +15652,12 @@ function localApiPlugin(root) { const data = await upstream.json(), a = data?.answers?.q1; if (!a || a.abstained !== true && !(a.choice in body.criteria)) throw new Error("\u6A21\u578B\u54CD\u5E94\u683C\u5F0F\u5F02\u5E38"); const unknown2 = a.abstained || a.choice === "unclear"; - const record2 = getJournal().update(id, { status: unknown2 ? "unknown" : "success", choice: a.choice ?? null, abstained: !!unknown2, latencyMs: Math.round(performance3.now() - begin), inferenceMs: Number.isFinite(data?.usage?.total_ms) ? Math.round(data.usage.total_ms) : null, queueMs, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }); - return send(res, 200, { answer: { choice: a.choice ?? null, abstained: !!unknown2 }, latencyMs: record2.latencyMs, inferenceMs: record2.inferenceMs, recordId: id }); + const record3 = getJournal().update(id2, { status: unknown2 ? "unknown" : "success", choice: a.choice ?? null, abstained: !!unknown2, latencyMs: Math.round(performance3.now() - begin), inferenceMs: Number.isFinite(data?.usage?.total_ms) ? Math.round(data.usage.total_ms) : null, queueMs, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }); + return send(res, 200, { answer: { choice: a.choice ?? null, abstained: !!unknown2 }, latencyMs: record3.latencyMs, inferenceMs: record3.inferenceMs, recordId: id2 }); } catch (e) { const error48 = e.name === "TimeoutError" ? "\u6A21\u578B\u54CD\u5E94\u8D85\u65F6" : e.message === "fetch failed" ? "\u6A21\u578B\u670D\u52A1\u672A\u8FDE\u63A5" : e.message; - const record2 = getJournal().update(id, { status: "error", error: error48, latencyMs: Math.round(performance3.now() - begin), queueMs, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }); - return send(res, 502, { error: error48, recordId: id, latencyMs: record2.latencyMs }); + const record3 = getJournal().update(id2, { status: "error", error: error48, latencyMs: Math.round(performance3.now() - begin), queueMs, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }); + return send(res, 502, { error: error48, recordId: id2, latencyMs: record3.latencyMs }); } }; const pending = queue.then(task, task); @@ -14864,7 +15681,7 @@ function localApiPlugin(root) { var TOKEN = /^[a-f0-9]{64}$/; function same(a, b) { const aa = Buffer.from(a || ""), bb = Buffer.from(b || ""); - return aa.length === bb.length && aa.length > 0 && timingSafeEqual(aa, bb); + return aa.length === bb.length && aa.length > 0 && timingSafeEqual2(aa, bb); } function createCloudHandler({ dataDir, internalKey, plannerLimit = 12, totalPlannerLimit = 120 }) { const workspaces = /* @__PURE__ */ new Map(), rates = /* @__PURE__ */ new Map(); @@ -14880,19 +15697,36 @@ function createCloudHandler({ dataDir, internalKey, plannerLimit = 12, totalPlan }; return (req, res) => { if (!same(req.headers["x-home-pulse-internal"], internalKey)) return send(res, 403, "\u8BBF\u95EE\u6765\u6E90\u65E0\u6548"); - const token = String(req.headers["x-home-pulse-workspace"] || ""); - if (!TOKEN.test(token)) return send(res, 401, "\u8BF7\u5237\u65B0\u9875\u9762\uFF0C\u91CD\u65B0\u8FDE\u63A5\u4F60\u7684\u7A7A\u95F4"); const url2 = new URL(req.url, "http://localhost"); + if (req.headers.origin && req.headers.origin !== `http://${req.headers.host}` && req.headers.origin !== `https://${req.headers.host}`) return send(res, 403, "\u6765\u6E90\u4E0D\u5339\u914D"); + const native = url2.pathname.startsWith("/api/v1/"); + if (native) { + const result = appPublic(req, url2); + if (result) { + res.writeHead(result.status, { "Content-Type": "application/json", "Cache-Control": "no-store" }); + return res.end(JSON.stringify(result.body)); + } + } + const token = native ? appToken(req) : String(req.headers["x-home-pulse-workspace"] || ""); + if (!token || !TOKEN.test(token)) { + if (native) { + const result = appError(new AppError(401, "UNAUTHORIZED", "\u8BF7\u63D0\u4F9B Home Pulse \u7A7A\u95F4\u4EE4\u724C")); + res.writeHead(result.status, { "Content-Type": "application/json", "Cache-Control": "no-store" }); + return res.end(JSON.stringify(result.body)); + } + return send(res, 401, "\u8BF7\u5237\u65B0\u9875\u9762\uFF0C\u91CD\u65B0\u8FDE\u63A5\u4F60\u7684\u7A7A\u95F4"); + } + req.headers["x-home-pulse-workspace"] = token; if (!url2.pathname.startsWith("/api/")) return send(res, 404, "\u63A5\u53E3\u4E0D\u5B58\u5728"); - if (req.method === "POST" && ["/api/setup/draft", "/api/setup/prepare", "/api/plan"].includes(url2.pathname)) { + if (req.method === "POST" && ["/api/setup/draft", "/api/setup/prepare", "/api/plan", "/api/v1/setups/draft", "/api/v1/setups/prepare"].includes(url2.pathname)) { if (limited(token, plannerLimit) || limited("all", totalPlannerLimit)) return send(res, 429, "\u672C\u5C0F\u65F6\u7684\u4EFB\u52A1\u8BBE\u7F6E\u6B21\u6570\u5DF2\u7528\u5B8C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002\u5DF2\u6709\u4EFB\u52A1\u4ECD\u53EF\u89C2\u5BDF\u3002"); } let entry = workspaces.get(token); if (!entry) { if (workspaces.size >= 2e3) return send(res, 503, "\u5F53\u524D\u4F53\u9A8C\u4EBA\u6570\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5"); let middleware; - const root = path5.join(dataDir, "workspaces", token); - localApiPlugin(root).configureServer({ middlewares: { use: (m) => middleware = m } }); + const root = path6.join(dataDir, "workspaces", token); + localApiPlugin(root, { appScoped: true }).configureServer({ middlewares: { use: (m) => middleware = m } }); entry = { middleware }; workspaces.set(token, entry); } @@ -14901,9 +15735,9 @@ function createCloudHandler({ dataDir, internalKey, plannerLimit = 12, totalPlan return runtimeContext.run({ modelBase }, () => entry.middleware(req, res, () => send(res, 404, "\u63A5\u53E3\u4E0D\u5B58\u5728"))); }; } -if (process.argv[1] && path5.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { +if (process.argv[1] && path6.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { if (!process.env.HOME_PULSE_INTERNAL_KEY) throw new Error("Missing internal gateway key"); - const server = http.createServer(createCloudHandler({ dataDir: process.env.HOME_PULSE_DATA_DIR || path5.resolve(".local/cloud"), internalKey: process.env.HOME_PULSE_INTERNAL_KEY })); + const server = http.createServer(createCloudHandler({ dataDir: process.env.HOME_PULSE_DATA_DIR || path6.resolve(".local/cloud"), internalKey: process.env.HOME_PULSE_INTERNAL_KEY })); server.requestTimeout = 24e4; server.listen(Number(process.env.HOME_PULSE_API_PORT || 7861), "127.0.0.1", () => console.log("Home Pulse workspace API is ready")); }