@trillboards/edge-sdk 0.2.260 → 0.2.263

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/deploy/windows/ci/test-published-install.ps1 +10 -1
  2. package/dist/CloudSensingManager.d.ts +36 -0
  3. package/dist/CloudSensingManager.d.ts.map +1 -1
  4. package/dist/CloudSensingManager.js +147 -20
  5. package/dist/CloudSensingManager.js.map +1 -1
  6. package/dist/EdgeAgent.js +1 -1
  7. package/dist/VideoSegmentUploader.d.ts +4 -0
  8. package/dist/VideoSegmentUploader.d.ts.map +1 -1
  9. package/dist/VideoSegmentUploader.js +21 -1
  10. package/dist/VideoSegmentUploader.js.map +1 -1
  11. package/dist/autoSense.d.ts +5 -4
  12. package/dist/autoSense.d.ts.map +1 -1
  13. package/dist/autoSense.js +24 -9
  14. package/dist/autoSense.js.map +1 -1
  15. package/dist/config.d.ts +9 -0
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js +15 -0
  18. package/dist/config.js.map +1 -1
  19. package/dist/diagnose.d.ts +1 -1
  20. package/dist/diagnose.js +1 -1
  21. package/dist/sensingRunMode.d.ts +8 -0
  22. package/dist/sensingRunMode.d.ts.map +1 -1
  23. package/dist/sensingRunMode.js +59 -11
  24. package/dist/sensingRunMode.js.map +1 -1
  25. package/package.json +5 -4
  26. package/retained/CapturedTheftProfile.cjs +83 -0
  27. package/retained/ExperimentalTheftConnector.cjs +392 -0
  28. package/retained/FrameTheftRuntime.cjs +111 -0
  29. package/retained/FrameTheftWorker.py +136 -0
  30. package/retained/InstalledTheftLifecycle.cjs +165 -0
  31. package/retained/InstalledTheftPackage.cjs +91 -0
  32. package/retained/LiveTheftBinding.cjs +55 -0
  33. package/retained/ObservedReviewCaseEvidence.py +188 -0
  34. package/retained/ObservedSameWristPolicy.py +205 -0
  35. package/retained/OrderedPerceptionDelivery.cjs +72 -0
  36. package/retained/PairedTheftRoute.cjs +402 -0
  37. package/retained/ReplayRpc.cjs +157 -0
  38. package/retained/RetainedCaptureClient.cjs +63 -16
  39. package/retained/SavedTheftSession.cjs +110 -0
  40. package/retained/TheftCaseContract.cjs +36 -0
  41. package/retained/TheftCaseDelivery.cjs +81 -0
  42. package/retained/TheftDeliveryPump.cjs +41 -0
  43. package/retained/TheftMovementOwner.py +234 -0
  44. package/retained/TheftReviewPolicy.cjs +8 -0
  45. package/retained/__tests__/paired-theft-manager.test.cjs +509 -0
  46. package/retained/__tests__/support/live-shelf-api.cjs +139 -0
  47. package/retained/__tests__/support/load-sdk-sources.cjs +41 -0
  48. package/retained/__tests__/support/loopback-proxy.cjs +33 -0
  49. package/retained/__tests__/support/pinned-api-loader.cjs +11 -0
  50. package/retained/__tests__/support/theft-builder.cjs +61 -0
  51. package/retained/__tests__/support/theft-packet-fixture.cjs +58 -0
  52. package/retained/__tests__/support/theft-readiness.cjs +51 -0
  53. package/retained/__tests__/test_live_theft_input.py +103 -0
  54. package/retained/__tests__/theft-case-api.test.cjs +135 -0
  55. package/retained/__tests__/theft-ci-regression.test.cjs +92 -0
  56. package/retained/__tests__/theft-config.test.cjs +84 -0
  57. package/retained/__tests__/theft-entry.test.cjs +76 -0
  58. package/retained/__tests__/theft-native-recovery.test.cjs +90 -0
  59. package/retained/__tests__/theft-readiness.test.cjs +164 -0
  60. package/retained/manager.cjs +61 -7
  61. package/retained/pilot-profile-client.cjs +4 -0
@@ -0,0 +1,402 @@
1
+ 'use strict';
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs'), path = require('node:path'), crypto = require('node:crypto');
4
+ const {SelectedActorPerceptionClient} = require('../dist/ActorPerception');
5
+ const {readJpegFrameSize} = require('../dist/jpegFrameSize');
6
+ const {readAdmission, WebsiteAdmissionCaptureClient} = require('./WebsiteAdmissionCaptureClient.cjs');
7
+ const {ExperimentalTheftEvidence, LabPerceiver, PrivateAlertReceiver} = require('./ExperimentalTheftConnector.cjs');
8
+ const {CapturedTheftProfile} = require('./CapturedTheftProfile.cjs');
9
+ const {receipt} = require('./OrderedPerceptionDelivery.cjs');
10
+ const {reviewMode,HUMAN_ONLY}=require('./TheftReviewPolicy.cjs');
11
+ const {isNativeReadinessUnavailable}=require('../dist/NativeReadiness');
12
+ const liveBinding = require('./LiveTheftBinding.cjs');
13
+ const hash = value => crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
14
+ const clone = structuredClone;
15
+ const id = value => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(value);
16
+ const digest = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
17
+ const FIELD = 'privateTheftSession';
18
+ const SINK = 'paired_theft_same_wrist_v1';
19
+
20
+ function registrations(config, runtime, websiteManaged, pipeline, feeds) {
21
+ if (config === undefined) { assert(runtime === undefined, 'Theft runtime requires explicit profile registration'); return new Map(); }
22
+ assert(websiteManaged && !pipeline, 'Private theft registration requires the website capture owner');
23
+ assert(config && Object.keys(config).sort().join(',') === 'profiles,version' && config.version === 1 &&
24
+ Array.isArray(config.profiles) && config.profiles.length > 0, 'Explicit private theft profile list required');
25
+ assert(runtime && runtime.rpc && typeof runtime.rpc.call === 'function' && typeof runtime.describeOriginal === 'function',
26
+ 'Prepared frame runtime and original-frame metadata source required');
27
+ const result = new Map();
28
+ for (const row of config.profiles) {
29
+ if (row?.environment?.kind === liveBinding.KIND) {
30
+ assert(Object.keys(row).sort().join(',') === 'environment,feedName,reviewMode,sceneId,templateId'
31
+ && row.reviewMode === HUMAN_ONLY && row.templateId === liveBinding.TEMPLATE && id(row.feedName)
32
+ && Number.isSafeInteger(row.sceneId) && row.sceneId >= 0, 'Exact live shelf review registration required');
33
+ liveBinding.validateEnvironment(row.environment);
34
+ assert(feeds.some(f => f.name === row.feedName && f.screenId === row.environment.cameraId)
35
+ && !result.has(row.feedName), 'Live registration must match one paired feed');
36
+ result.set(row.feedName, clone(row));
37
+ continue;
38
+ }
39
+ reviewMode(row?.reviewMode);
40
+ assert(row && Object.keys(row).sort().join(',') ===
41
+ ['environment','feedName','profileId','sceneId','selectionId',...(Object.hasOwn(row,'reviewMode')?['reviewMode']:[])].sort().join(',') &&
42
+ ['feedName','profileId','selectionId'].every(k => id(row[k])) && Number.isSafeInteger(row.sceneId) && row.sceneId >= 0,
43
+ 'Exact private theft registration required');
44
+ assert(feeds.some(f => f.name === row.feedName) && !result.has(row.feedName), 'Unknown or duplicate theft feed');
45
+ assert(row.environment && digest(row.environment.sourceVideoSha256) && digest(row.environment.regionConfigurationSha256) &&
46
+ Array.isArray(row.environment.frameSize) && row.environment.frameSize.length === 2 &&
47
+ row.environment.frameSize.every(n => Number.isSafeInteger(n) && n > 0), 'Verified original source and marked shelf environment required');
48
+ result.set(row.feedName, clone(row));
49
+ }
50
+ return result;
51
+ }
52
+
53
+ class PairedTheftRoute {
54
+ constructor({directory, binding, registration, runtime, now = Date.now}) {
55
+ this.directory = directory; this.binding = clone(binding); this.registration = clone(registration);
56
+ this.runtime = runtime; this.now = now; this.archive = null; this.active = null;
57
+ this.epoch = crypto.randomUUID(); this.liveEpochs = new Set([this.epoch]); this.generation = 0; this.sessions = new Map();
58
+ this.caseDeliveries = new Map();
59
+ this.live = registration.environment.kind === liveBinding.KIND;
60
+ this.fallback = new SelectedActorPerceptionClient(binding);
61
+ this.bindingProfile = {version: 1, archiveCameraId: registration.feedName, pairedCameraId: binding.cameraId,
62
+ sourceId: binding.sourceId, ...(this.live ? {sourceKind: liveBinding.KIND,
63
+ regionConfigurationSha256: registration.environment.regionConfigurationSha256}
64
+ : {profileId: registration.profileId, selectionId: registration.selectionId}),
65
+ ...(Object.hasOwn(registration,'reviewMode')?{reviewMode:reviewMode(registration.reviewMode)}:{})};
66
+ const owner = this;
67
+ this.perceiver = {
68
+ policyForContext(context) {
69
+ const policy = owner.fallback.policyForContext(context);
70
+ if (owner.selected(context)) owner.validateContext(context);
71
+ return policy;
72
+ },
73
+ validate(value, input, policy) { return owner.fallback.validate(value, input, policy); },
74
+ async perceive(input, policy) {
75
+ const record = owner.archive?.recordFor(input.frameId); assert(record, 'Original manager capture required');
76
+ const context = record.candidate.reviewContext;
77
+ if (!owner.selected(context)) return owner.fallback.perceive(input, policy);
78
+ const scope = owner.validateContext(context, record.capturedAt);
79
+ assert(owner.liveEpochs.has(scope.captureEpoch), 'Unprocessed old-epoch capture requires explicit recovery; do not restart its tracker');
80
+ const session = owner.session(scope, context);
81
+ const metadata = clone(await runtime.describeOriginal({record: clone(record), input: {...input, jpeg: Buffer.from(input.jpeg)}}));
82
+ assert(metadata && metadata.jpegBase64 === undefined && metadata.capturedAtMs === record.capturedAt &&
83
+ metadata.sha256 === record.imageSha256 && metadata.sourceTimeMs === null && metadata.sceneId === scope.sceneId &&
84
+ Number.isSafeInteger(metadata.sourceIndex) && metadata.sourceIndex >= 0,
85
+ 'Exact original source metadata required; never fabricate timestamps or video positions');
86
+ assert.deepEqual([metadata.width, metadata.height], registration.environment.frameSize);
87
+ session.perceiver.frames.set(record.id, metadata); session.metadata.set(record.id, metadata);
88
+ return session.perceiver.perceive(input, policy);
89
+ }
90
+ };
91
+ this.sink = {id: SINK,
92
+ handlesContext(context) { if (!owner.selected(context)) return false; owner.validateContext(context); return true; },
93
+ prepare({record}) {
94
+ const scope = owner.validateContext(record.candidate.reviewContext, record.capturedAt);
95
+ const session = owner.session(scope, record.candidate.reviewContext);
96
+ const metadata = session.metadata.get(record.id), side = session.perceiver.sidecars.get(record.id);
97
+ assert(metadata && side, 'Exact manager-frame movement output required'); return {metadata: clone(metadata), side: clone(side)};
98
+ },
99
+ deliver({record, payload, payloadSha256}) {
100
+ const scope = owner.validateContext(record.candidate.reviewContext, record.capturedAt);
101
+ const session = owner.session(scope, record.candidate.reviewContext);
102
+ session.consumer.acceptCapture(record.id, payload.metadata, payload.side);
103
+ session.metadata.delete(record.id); session.perceiver.sidecars.delete(record.id);
104
+ return receipt(SINK, record.id, payloadSha256);
105
+ }};
106
+ }
107
+ beginCaptureEpoch() {
108
+ this.active = null;
109
+ this.epoch = crypto.randomUUID(); this.liveEpochs.add(this.epoch);
110
+ this.retireResolved();
111
+ const owed = new Set([...this.archive.perceptionPending.values()].map(row => row.candidate.reviewContext?.[FIELD]?.scope?.captureEpoch));
112
+ for (const epoch of this.liveEpochs) {
113
+ if (epoch !== this.epoch && !owed.has(epoch) && ![...this.sessions.values()].some(s => s.scope.captureEpoch === epoch))
114
+ this.liveEpochs.delete(epoch);
115
+ }
116
+ }
117
+ selected(context) {
118
+ if (this.live) return !!liveBinding.readLiveAdmission(context, this.liveAuthority(), context?.websiteReviewAdmission?.lease?.issuedAtMs);
119
+ return context?.profileState === 'active' && context.websiteReviewAdmission?.profileId === this.registration.profileId;
120
+ }
121
+ liveAuthority() {
122
+ return { ...this.binding, regionConfigurationSha256: this.registration.environment.regionConfigurationSha256 };
123
+ }
124
+ profileBindingFor(context, at) {
125
+ if (!this.live) return this.bindingProfile;
126
+ const admission = liveBinding.readLiveAdmission(context, this.liveAuthority(), at);
127
+ assert(admission, 'Invalid captured live camera and shelf authority');
128
+ return { ...this.bindingProfile, profileId: admission.profileId, selectionId: admission.selectionId, routeId: admission.routeId };
129
+ }
130
+ scope(context) {
131
+ const mark = context?.[FIELD];
132
+ assert(mark && Object.keys(mark).sort().join(',') === 'scope,version' && mark.version === 1, 'Explicit captured theft session required');
133
+ const scope = mark.scope;
134
+ assert(scope && scope.cameraId === this.binding.cameraId && scope.sourceId === this.binding.sourceId &&
135
+ typeof scope.captureEpoch === 'string' && id(scope.captureEpoch) && Number.isSafeInteger(scope.profileGeneration) && scope.profileGeneration >= 1 &&
136
+ scope.sceneId === this.registration.sceneId &&
137
+ (this.live ? scope.sourceKind === liveBinding.KIND && !Object.hasOwn(scope, 'sourceVideoSha256')
138
+ : scope.sourceVideoSha256 === this.registration.environment.sourceVideoSha256 && !Object.hasOwn(scope, 'sourceKind')) &&
139
+ scope.regionConfigurationSha256 === this.registration.environment.regionConfigurationSha256, 'Captured theft scope differs from registered source');
140
+ return clone(scope);
141
+ }
142
+ validateContext(context, at = context?.websiteReviewAdmission?.lease?.issuedAtMs) {
143
+ assert(this.archive, 'The camera archive must be attached before theft capture');
144
+ const scope = this.scope(context);
145
+ const profile = new CapturedTheftProfile(this.archive, scope, this.profileBindingFor(context, at), context);
146
+ profile.assertContext(context, at); return scope;
147
+ }
148
+ stamp(context) {
149
+ assert(context?.[FIELD] === undefined, 'Website context cannot supply a private runtime session');
150
+ if (!this.selected(context) || this.live && !liveBinding.readLiveAdmission(context, this.liveAuthority(), this.now())) {
151
+ this.active = null; this.retireResolved(); return context;
152
+ }
153
+ assert(this.archive, 'Theft profile cannot be selected before the archive is attached');
154
+ if (!this.live) assert(readAdmission(context, this.binding.cameraId, context.websiteReviewAdmission?.lease?.issuedAtMs), 'Invalid original theft profile authority');
155
+ const semantic = clone(context); delete semantic.websiteReviewAdmission.lease;
156
+ const identity = hash(semantic);
157
+ if (this.active?.identity !== identity) {
158
+ const scope = {...this.binding, captureEpoch: this.epoch, profileGeneration: ++this.generation,
159
+ sceneId: this.registration.sceneId,
160
+ ...(this.live ? {sourceKind: liveBinding.KIND} : {sourceVideoSha256: this.registration.environment.sourceVideoSha256}),
161
+ regionConfigurationSha256: this.registration.environment.regionConfigurationSha256};
162
+ this.active = {identity, scope};
163
+ }
164
+ if (this.live) this.active.expiresAtMs = context.websiteReviewAdmission.lease.expiresAtMs;
165
+ const captured = {...clone(context), [FIELD]: {version: 1, scope: clone(this.active.scope)}};
166
+ this.validateContext(captured); this.verifyRegistration(identity); this.retireResolved(); return captured;
167
+ }
168
+ verifyRegistration(contextHash) {
169
+ const identity = this.live ? {version: 2, binding: this.bindingProfile, registration: this.registration}
170
+ : {version: 1, binding: this.bindingProfile, registration: this.registration, contextHash};
171
+ fs.mkdirSync(this.directory, {recursive: true});
172
+ const file = path.join(this.directory, 'REGISTRATION.json');
173
+ if (fs.existsSync(file)) {
174
+ assert.deepEqual(JSON.parse(fs.readFileSync(file)), identity,
175
+ 'Registered theft definition changed; verify a matching shelf environment before activation');
176
+ return;
177
+ }
178
+ const fd = fs.openSync(file, 'wx', 0o600);
179
+ try { fs.writeFileSync(fd, JSON.stringify(identity)); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
180
+ }
181
+ attach(archive) {
182
+ assert(!this.archive && archive instanceof WebsiteAdmissionCaptureClient && archive.cameraId === this.registration.feedName);
183
+ assert(archive.actorPerceiver === this.perceiver && archive.perceptionSink === this.sink, 'Use one original archive and perception lane');
184
+ this.archive = archive;
185
+ const saved = new Map();
186
+ for (const row of archive.records.values()) {
187
+ if (!row.candidate.reviewContext?.[FIELD]) continue;
188
+ const scope = this.validateContext(row.candidate.reviewContext, row.capturedAt);
189
+ this.generation = Math.max(this.generation, scope.profileGeneration);
190
+ saved.set(hash(scope), {scope, context: row.candidate.reviewContext});
191
+ }
192
+ for (const [identity, entry] of saved) {
193
+ if (fs.existsSync(path.join(this.directory, identity))) this.session(entry.scope, entry.context);
194
+ }
195
+ // Receipts retain all 13 originals independently of the rolling capture
196
+ // archive. Resume delivery even if that session's captures were pruned.
197
+ if(this.runtime.caseTransportFor&&reviewMode(this.registration.reviewMode)===HUMAN_ONLY&&fs.existsSync(this.directory))
198
+ for(const item of fs.readdirSync(this.directory,{withFileTypes:true}))if(item.isDirectory()&&digest(item.name)){
199
+ const dir=path.join(this.directory,item.name),alerts=path.join(dir,'alerts');
200
+ if (fs.existsSync(alerts)) {
201
+ let context;
202
+ if (this.live) {
203
+ context = JSON.parse(fs.readFileSync(path.join(dir, 'LIVE-CAPTURE-CONTEXT.json')));
204
+ assert.equal(hash(this.validateContext(context)), item.name, 'Recovered live case scope differs');
205
+ }
206
+ this.attachCaseDelivery(item.name,dir,new PrivateAlertReceiver(alerts),context);
207
+ }
208
+ }
209
+ }
210
+ attachCaseDelivery(identity,directory,receiver,context){
211
+ if(!this.runtime.caseTransportFor||reviewMode(this.registration.reviewMode)!==HUMAN_ONLY||this.caseDeliveries.has(identity))return;
212
+ const {CaseDelivery}=require('./TheftCaseDelivery.cjs');
213
+ const binding = this.profileBindingFor(context,context?.websiteReviewAdmission?.lease?.issuedAtMs);
214
+ const transport=this.runtime.caseTransportFor(binding);
215
+ this.caseDeliveries.set(identity,new CaseDelivery({directory:path.join(directory,'case-delivery'),receiver,binding,transport}));
216
+ }
217
+ deliveries() {
218
+ if (!this.live) return [...this.caseDeliveries.values()];
219
+ const delivery = this.active && this.caseDeliveries.get(hash(this.active.scope));
220
+ return delivery && this.now() < this.active.expiresAtMs ? [delivery] : [];
221
+ }
222
+ session(scope, context) {
223
+ const identity = hash(scope); if (this.sessions.has(identity)) return this.sessions.get(identity);
224
+ const directory = path.join(this.directory, identity);
225
+ const perceiver = new LabPerceiver(scope, this.runtime.rpc), receiver = new PrivateAlertReceiver(path.join(directory, 'alerts'));
226
+ if (this.live) {
227
+ const file = path.join(directory, 'LIVE-CAPTURE-CONTEXT.json');
228
+ if (fs.existsSync(file)) {
229
+ const saved = JSON.parse(fs.readFileSync(file));
230
+ assert.equal(hash(this.validateContext(saved)), identity, 'Stored live capture scope changed');
231
+ assert.deepEqual(this.profileBindingFor(saved, saved.websiteReviewAdmission.lease.issuedAtMs),
232
+ this.profileBindingFor(context, context.websiteReviewAdmission.lease.issuedAtMs));
233
+ } else {
234
+ const fd = fs.openSync(file, 'wx', 0o600);
235
+ try { fs.writeFileSync(fd, JSON.stringify(context)); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
236
+ }
237
+ }
238
+ this.attachCaseDelivery(identity,directory,receiver,context);
239
+ const binding = this.profileBindingFor(context, context.websiteReviewAdmission?.lease?.issuedAtMs);
240
+ const consumer = new ExperimentalTheftEvidence({directory, scope, environment: this.registration.environment, archive: this.archive,
241
+ receiver, reviewer: reviewMode(this.registration.reviewMode)===HUMAN_ONLY?null:this.runtime.reviewer ?? null,
242
+ now: this.now, captureContext: context, profileBinding: binding});
243
+ consumer.recoverSavedSession(SINK);
244
+ const session = {scope: clone(scope), perceiver, consumer, metadata: new Map(), reviewing: false};
245
+ this.sessions.set(identity, session); return session;
246
+ }
247
+ async reviewOne(options) {
248
+ assert(options && typeof options.cameraBusy === 'boolean', 'Explicit shared-lane admission required');
249
+ assert(![...this.sessions.values()].some(s => s.reviewing), 'One optional theft review at a time');
250
+ const session = [...this.sessions.values()].find(s => s.consumer.pending.size);
251
+ if (!session) return null;
252
+ session.reviewing = true;
253
+ try { return await session.consumer.reviewOne(options); }
254
+ finally { session.reviewing = false; this.retireResolved(); }
255
+ }
256
+ retireResolved() {
257
+ if (!this.archive) return;
258
+ for (const [identity, session] of this.sessions) {
259
+ if (identity === (this.active ? hash(this.active.scope) : null) || session.consumer.pending.size || session.reviewing) continue;
260
+ const unresolved = [...this.archive.perceptionPending.values()].some(row =>
261
+ row.candidate.reviewContext?.[FIELD] && hash(row.candidate.reviewContext[FIELD].scope) === identity);
262
+ if (unresolved) continue;
263
+ session.consumer.close(); this.sessions.delete(identity);
264
+ }
265
+ }
266
+ pins() { return [...this.sessions.values()].flatMap(s => s.consumer.rows.map(p => p.row.id)); }
267
+ }
268
+
269
+ class PairedTheftCaptureClient extends WebsiteAdmissionCaptureClient {
270
+ constructor(client, directory, options) {
271
+ super(client, directory, options); this.theftRoute = options.theftRoute; this.theftRoute.attach(this);
272
+ this.privateHealth = {pendingSinceMs: null, progressAtMs: null, lastReportAtMs: null, lastReport: null, completed: 0, stalls: 0};
273
+ }
274
+ isReviewActive() {
275
+ const active = super.isReviewActive();
276
+ if (!active && this.theftRoute) { this.theftRoute.active = null; this.theftRoute.retireResolved(); }
277
+ return active;
278
+ }
279
+ async prepareReview() {
280
+ const value = await super.prepareReview();
281
+ if (this.theftRoute?.live) this.captureReviewContext();
282
+ return value;
283
+ }
284
+ isNativeTheftActive() {
285
+ if(this.theftRoute.registration.reviewMode!==HUMAN_ONLY)return false;
286
+ if(!super.isReviewActive())return false;
287
+ try{
288
+ const context = super.captureReviewContext();
289
+ return this.theftRoute.live ? !!this.theftRoute.stamp(context)[FIELD] : this.theftRoute.selected(context);
290
+ }
291
+ catch(error){if(isNativeReadinessUnavailable(error))return false;throw error;}
292
+ }
293
+ hasPendingNativeTheftPerception() {
294
+ if(this.theftRoute.registration.reviewMode!==HUMAN_ONLY)return false;
295
+ if(!super.hasPendingOrderedPerception())return false;
296
+ const record=this.pendingPerception();
297
+ return !!record&&record.perceptionDelivery?.consumerId===SINK
298
+ &&this.theftRoute.selected(record.candidate.reviewContext);
299
+ }
300
+ pendingPerception(at) {
301
+ if (this.theftRoute?.live && !this.perceptionBusy) {
302
+ const active = this.theftRoute.active;
303
+ const activeScope = active && this.theftRoute.now() < active.expiresAtMs ? hash(active.scope) : null;
304
+ for (const row of this.perceptionPending.values()) {
305
+ const scope = row.candidate.reviewContext?.[FIELD]?.scope;
306
+ if (scope?.sourceKind === liveBinding.KIND && hash(scope) !== activeScope) this.withholdEndedLivePerception(row);
307
+ }
308
+ this.theftRoute.retireResolved();
309
+ }
310
+ return super.pendingPerception(at);
311
+ }
312
+ captureReviewContext() { return this.theftRoute.stamp(super.captureReviewContext()); }
313
+ captureCadenceFromStart() { return this.theftRoute.selected(this.captureReviewContext()); }
314
+ retainOrderedCapture(candidate) {
315
+ if (!this.theftRoute.selected(candidate.reviewContext)) return super.retainOrderedCapture(candidate);
316
+ assert(candidate.privateOriginalFrame === undefined && candidate.privateOriginalFrameKind === undefined,
317
+ 'Capture caller cannot supply private original metadata');
318
+ this.theftRoute.validateContext(candidate.reviewContext, candidate.enqueuedAtMs);
319
+ const size = readJpegFrameSize(candidate.jpeg);
320
+ assert(size && Buffer.isBuffer(candidate.jpeg), 'Readable original JPEG dimensions required');
321
+ assert.deepEqual([size.width, size.height], this.theftRoute.registration.environment.frameSize,
322
+ 'Actual captured JPEG geometry differs from the registered shelf');
323
+ assert(Number.isSafeInteger(this.counts.captures) && this.counts.captures >= 0, 'Durable capture ordinal required');
324
+ // This is the archive's observed-capture ordinal, NOT a decoder frame number
325
+ // or a fabricated position in a video. Count advances only after commit;
326
+ // the original archive owns duplicate/restart/pruning continuity.
327
+ return super.retainOrderedCapture({...candidate, privateOriginalFrameKind: 'captured_archive_ordinal/v1',
328
+ privateOriginalFrame: {sourceIndex: this.counts.captures, sourceTimeMs: null,
329
+ sceneId: this.theftRoute.registration.sceneId, width: size.width, height: size.height,
330
+ capturedAtMs: candidate.enqueuedAtMs, sha256: crypto.createHash('sha256').update(candidate.jpeg).digest('hex')}});
331
+ }
332
+ async perceiveNextOrderedCapture() {
333
+ const original = this.perceptionBusy ? null : this.pendingPerception();
334
+ const result = await super.perceiveNextOrderedCapture();
335
+ if (result && original?.perceptionDelivery?.consumerId === SINK) {
336
+ assert.equal(original.perceptionDelivery.status, 'delivered', 'Private health requires a committed delivery');
337
+ this.privateHealth.progressAtMs = this.clockNow(); this.privateHealth.completed++;
338
+ if (!this.pendingPrivateCapture()) this.privateHealth.pendingSinceMs = null;
339
+ }
340
+ this.theftRoute.retireResolved(); return result;
341
+ }
342
+ pendingPrivateCapture() {
343
+ for (const row of this.perceptionPending.values()) if (row.perceptionDelivery?.consumerId === SINK) return row;
344
+ return null;
345
+ }
346
+ watchOfferPath() {
347
+ // Private records intentionally never enter the website offer spool. Do not
348
+ // invent an ordinary offer receipt to keep its watchdog quiet. Old ordinary
349
+ // work still has that watchdog, even while the selected profile is private.
350
+ const ordinaryOwed = this.entries.size || this.deferred.size || this.queued.size ||
351
+ this.backlog.size || this.backlogUndecided.size;
352
+ if (this.previousCaptureRecord?.perceptionDelivery?.consumerId === SINK && !ordinaryOwed)
353
+ this.offerProgressAtMs = null;
354
+ else super.watchOfferPath();
355
+ const health = this.privateHealth, now = this.clockNow();
356
+ const pending = this.pendingPrivateCapture();
357
+ if (!pending) { health.pendingSinceMs = null; return; }
358
+ if (health.pendingSinceMs === null) health.pendingSinceMs = now;
359
+ const progress = Math.max(health.pendingSinceMs, health.progressAtMs ?? -Infinity);
360
+ const stallMs = Math.max(240000, (this.realtime?.freshnessMs ?? 0) + 60000);
361
+ if (this.captureAttemptAtMs === null || now - this.captureAttemptAtMs > 30000 || now - progress < stallMs ||
362
+ health.lastReportAtMs !== null && now - health.lastReportAtMs < stallMs) return;
363
+ const failure = pending.perceptionDeliveryFailure ?? pending.actorPerceptionFailure ?? null;
364
+ const report = {camera: this.cameraId, kind: 'private_perception_stalled', frame_id: pending.id,
365
+ idle_ms: now - progress, last_capture_age_ms: now - this.captureAttemptAtMs,
366
+ perception_pending: this.perceptionPending.size, perception_busy: this.perceptionBusy,
367
+ phase: pending.perceptionDeliveryFailure?.phase ?? (this.perceptionBusy ? 'perception' : pending.perceptionDelivery.status),
368
+ saved_failure: failure === null ? null : clone(failure), perception_released: false,
369
+ completed_private_deliveries: health.completed, stalls: ++health.stalls};
370
+ health.lastReportAtMs = now; health.lastReport = report;
371
+ console.error('[retained] ' + this.cameraId + ': private perception stalled; owner retained ' + JSON.stringify(report));
372
+ try { this.onOfferStall?.(report); }
373
+ catch (error) { console.error('[retained] ' + this.cameraId + ': private stall telemetry failed: ' + String(error)); }
374
+ }
375
+ resetOfferPath(now, stallMs) {
376
+ // The original promise owns the perception lane until it exits. A clock
377
+ // cannot prove that a native worker has stopped. Retain that reservation;
378
+ // still repair orphaned website offers and the future live-look clock.
379
+ let released = 0;
380
+ if (typeof this.reviewQueue?.holds === 'function') for (const id of [...this.queued])
381
+ if (this.reviewQueue.holds(id) === null) { this.queued.delete(id); released++; }
382
+ const liveLookReset = this.liveLookStartedAtMs !== null && this.liveLookStartedAtMs > now;
383
+ if (liveLookReset) this.liveLookStartedAtMs = null;
384
+ this.phoneProofChecks.clear();
385
+ return {released_queued: released, perception_released: false, perception_owner_active: this.perceptionBusy,
386
+ live_look_reset: liveLookReset};
387
+ }
388
+ chooseReview(candidate, digest, due, stage) {
389
+ if (this.theftRoute?.selected(candidate.reviewContext)) {
390
+ assert(stage !== null, 'An inactive capture cannot enter the private theft route');
391
+ this.theftRoute.validateContext(candidate.reviewContext, candidate.enqueuedAtMs);
392
+ return {selected: false, disposition: 'archived_private_theft_profile', selectionReason: 'explicit_private_theft_profile'};
393
+ }
394
+ return super.chooseReview(candidate, digest, due, stage);
395
+ }
396
+ archivePins() {
397
+ const pins = super.archivePins();
398
+ for (const id of this.theftRoute?.pins() ?? []) { assert(this.records.has(id), 'Original theft history missing before cleanup'); pins.add(id); }
399
+ return pins;
400
+ }
401
+ }
402
+ module.exports = {registrations, PairedTheftRoute, PairedTheftCaptureClient, FIELD, SINK};
@@ -0,0 +1,157 @@
1
+ 'use strict';
2
+ const assert = require('node:assert/strict');
3
+ const {spawn} = require('node:child_process');
4
+ const fs = require('node:fs');
5
+ const MAX_RESPONSE_BYTES = 32 * 1024 ** 2;
6
+ function errorRecord(e,seen=new Set()) {
7
+ if(seen.has(e))return {name:'Error',message:'Circular error cause retained by reference'};
8
+ seen.add(e);
9
+ const row={name:e?.name??'Error',code:e?.code??null,message:e?.message??String(e),stack:e?.stack??null};
10
+ for(const key of ['rawResponse','nativeResponse','cleanup','exit','errno','syscall','path','spawnargs','diagnosticErrors'])
11
+ if(e?.[key]!==undefined)row[key]=e[key];
12
+ if(e?.cause!==undefined)row.cause=errorRecord(e.cause,seen);
13
+ if(e?.originalError!==undefined)row.originalError=errorRecord(e.originalError,seen);
14
+ if(e instanceof AggregateError)row.errors=e.errors.map(item=>errorRecord(item,seen));
15
+ return row;
16
+ }
17
+ const failure = (code,message,extra={}) => Object.assign(new Error(message),{code,...extra});
18
+ async function waitForExit(exit,milliseconds) {
19
+ let timer;
20
+ try { return await Promise.race([exit,new Promise(resolve=>{timer=setTimeout(()=>resolve(null),milliseconds);})]); }
21
+ finally { clearTimeout(timer); }
22
+ }
23
+
24
+ /** Own one newline-JSON worker. The first row is startup; each subsequent row
25
+ * belongs to exactly one request. A failed stream is never reused. No models,
26
+ * media readers, installs, retries or process discovery live in this adapter. */
27
+ class ReplayRpc {
28
+ constructor(command,args,{cwd,errorFile,timeoutMs=120000,cleanupLimitMs=25000}) {
29
+ assert(typeof command==='string'&&command&&Array.isArray(args)&&args.every(a=>typeof a==='string'));
30
+ assert(Number.isSafeInteger(timeoutMs)&&timeoutMs>0&&timeoutMs<=120000);
31
+ assert(Number.isSafeInteger(cleanupLimitMs)&&cleanupLimitMs>0&&cleanupLimitMs<=25000);
32
+ Object.assign(this,{timeoutMs,cleanupLimitMs,errorFile});
33
+ this.buffer='';this.waiter=null;this.startupRow=null;this.startupRequested=false;this.startupConsumed=false;
34
+ this.ended=false;this.failure=null;this.closing=false;this.closePromise=null;this.exitResult=null;
35
+ this.diagnosticErrors=[];this.closeWriteErrors=[];this.events=[];
36
+ this.errorFd=fs.openSync(errorFile,'wx',0o600);
37
+ try { this.eventFd=fs.openSync(errorFile+'.events.jsonl','wx',0o600); }
38
+ catch(error){fs.closeSync(this.errorFd);throw error;}
39
+ try {
40
+ this.record('starting',{command,args,cwd});
41
+ this.child=spawn(command,args,{cwd,shell:false,windowsHide:true,stdio:['pipe','pipe',this.errorFd]});
42
+ } catch(error) {fs.closeSync(this.errorFd);fs.closeSync(this.eventFd);throw error;}
43
+ // close, unlike exit, also follows spawn failure and waits for owned pipes.
44
+ this.exit=new Promise(resolve=>this.child.once('close',(code,signal)=>{
45
+ this.ended=true;this.exitResult={exited:true,code,signal};
46
+ if(!this.closing&&!this.failure) this.fail(failure(code===0?'NATIVE_UNEXPECTED_EXIT':'NATIVE_EXIT_NONZERO',
47
+ `Native worker closed before shutdown: ${code}/${signal}`,{exit:this.exitResult}));
48
+ else if(this.waiter) this.fail(failure('NATIVE_UNEXPECTED_EXIT','Native worker closed before its response',{exit:this.exitResult}));
49
+ this.recordSafely('closed',this.exitResult);
50
+ for(const fd of [this.errorFd,this.eventFd])try{fs.closeSync(fd);}catch(error){this.diagnosticErrors.push(errorRecord(error));}
51
+ this.errorFd=this.eventFd=null;resolve(this.exitResult);
52
+ }));
53
+ this.child.on('error',error=>this.fail(failure('NATIVE_SPAWN_ERROR',error.message,{cause:error,originalError:errorRecord(error)})));
54
+ this.child.stdin.on('error',error=>{
55
+ if(this.closing){this.closeWriteErrors.push(errorRecord(error));this.recordSafely('shutdown_write_error',errorRecord(error));}
56
+ else this.fail(failure('NATIVE_WRITE_ERROR',error.message,{cause:error}));
57
+ });
58
+ this.child.stdout.setEncoding('utf8');
59
+ this.child.stdout.on('error',error=>this.fail(failure('NATIVE_READ_ERROR',error.message,{cause:error})));
60
+ this.child.stdout.on('data',data=>this.receive(data));
61
+ }
62
+ record(event,details) {
63
+ const row={event,atMs:Date.now(),...details};
64
+ this.events.push(row);assert(this.events.length<=128,'Native diagnostic event bound exceeded');
65
+ fs.writeSync(this.eventFd,JSON.stringify(row)+'\n');fs.fsyncSync(this.eventFd);
66
+ }
67
+ recordSafely(event,details) {
68
+ if(this.eventFd===null)return;
69
+ try { this.record(event,details); }
70
+ catch(error){this.diagnosticErrors.push(errorRecord(error));}
71
+ }
72
+ fail(error) {
73
+ if(!this.failure){this.failure=error;this.recordSafely('failure',{error:errorRecord(error)});}
74
+ const waiting=this.waiter;this.waiter=null;
75
+ if(waiting){clearTimeout(waiting.timer);waiting.reject(this.failure);}
76
+ return this.failure;
77
+ }
78
+ receive(data) {
79
+ if(this.failure||this.closing)return; // diagnostics already own the failed stream
80
+ this.buffer+=data;
81
+ if(Buffer.byteLength(this.buffer)>MAX_RESPONSE_BYTES){this.fail(failure('NATIVE_PROTOCOL_ERROR','Native response exceeds 32 MiB; no truncation accepted'));return;}
82
+ let at;
83
+ while((at=this.buffer.indexOf('\n'))>=0&&!this.failure){
84
+ const text=this.buffer.slice(0,at);this.buffer=this.buffer.slice(at+1);
85
+ let row;
86
+ try{row=JSON.parse(text);assert(row&&typeof row==='object'&&!Array.isArray(row),'Native row must be an object');}
87
+ catch(error){this.fail(failure('NATIVE_PROTOCOL_ERROR','Invalid native JSON response: '+error.message,{cause:error,rawResponse:text}));return;}
88
+ if(row.failure){this.fail(failure('NATIVE_WORKER_FAILURE',typeof row.failure==='string'?row.failure:'Native worker reported failure',{nativeResponse:row}));return;}
89
+ if(this.waiter){const waiting=this.waiter;this.waiter=null;clearTimeout(waiting.timer);waiting.resolve(row);}
90
+ else if(!this.startupRequested&&this.startupRow===null)this.startupRow=row;
91
+ else this.fail(failure('NATIVE_PROTOCOL_ERROR','Unexpected native response without an owned request',{nativeResponse:row}));
92
+ }
93
+ }
94
+ available() {
95
+ if(this.failure||this.closing||this.ended)throw failure('NATIVE_UNAVAILABLE','Native worker is retired; no new operation started',{cause:this.failure});
96
+ assert(!this.waiter,'One open RPC only');
97
+ }
98
+ response() {
99
+ this.available();
100
+ return new Promise((resolve,reject)=>{
101
+ const waiting={resolve,reject,timer:null};
102
+ waiting.timer=setTimeout(()=>this.fail(failure('NATIVE_RESPONSE_TIMEOUT','Native worker response timed out')),this.timeoutMs);
103
+ this.waiter=waiting;
104
+ });
105
+ }
106
+ async next() {
107
+ // Do not wrap a saved native/spawn failure as generic unavailability during startup.
108
+ if(this.failure)throw this.failure;
109
+ this.available();assert(!this.startupRequested,'Startup readiness is consumed once');this.startupRequested=true;
110
+ const row=this.startupRow??await this.response();this.startupRow=null;
111
+ if(this.failure)throw this.failure;
112
+ this.startupConsumed=true;this.recordSafely('ready',{pid:this.child.pid??null});
113
+ if(this.diagnosticErrors.length)throw this.fail(failure('NATIVE_DIAGNOSTIC_ERROR','Native startup diagnostic could not be saved',{diagnosticErrors:this.diagnosticErrors}));
114
+ return row;
115
+ }
116
+ async call(method,value) {
117
+ this.available();assert(this.startupConsumed,'Consume native startup before an operation');
118
+ assert(typeof method==='string'&&method.length>0,'Explicit native operation required');
119
+ const line=JSON.stringify([method==='detect'?'/detect':method,value])+'\n';
120
+ assert(Buffer.byteLength(line)<=8*1024**2,'Complete native request exceeds 8 MiB; do not truncate');
121
+ const response=this.response();
122
+ try{this.child.stdin.write(line,error=>{if(error)this.fail(failure('NATIVE_WRITE_ERROR',error.message,{cause:error}));});}
123
+ catch(error){this.fail(failure('NATIVE_WRITE_ERROR',error.message,{cause:error}));}
124
+ const row=await response;
125
+ if(this.failure)throw this.failure;
126
+ if(!Object.hasOwn(row,'result'))throw this.fail(failure('NATIVE_PROTOCOL_ERROR','Native response has no result',{nativeResponse:row}));
127
+ return row.result;
128
+ }
129
+ close() {
130
+ if(!this.closePromise){this.closing=true;this.closePromise=this.closeOwned();}
131
+ return this.closePromise;
132
+ }
133
+ async closeOwned() {
134
+ this.recordSafely('closing',{pid:this.child.pid??null});
135
+ if(this.waiter){const waiting=this.waiter;this.waiter=null;clearTimeout(waiting.timer);waiting.reject(failure('NATIVE_CLOSING','Native owner is shutting down'));}
136
+ const reserve=Math.min(5000,Math.ceil(this.cleanupLimitMs/5));
137
+ if(!this.ended&&!this.child.stdin.destroyed&&!this.child.stdin.writableEnded){
138
+ try{this.child.stdin.end();}catch(error){this.closeWriteErrors.push(errorRecord(error));}
139
+ }
140
+ let exited=this.exitResult??await waitForExit(this.exit,this.cleanupLimitMs-reserve),forced=false;
141
+ if(!exited){
142
+ forced=true;this.recordSafely('force_exit',{pid:this.child.pid??null,signal:'SIGKILL'});
143
+ try{this.child.kill('SIGKILL');}catch(error){this.closeWriteErrors.push(errorRecord(error));}
144
+ exited=await waitForExit(this.exit,reserve);
145
+ }
146
+ const cleanup={...(exited??{exited:false,code:null,signal:null}),forced,
147
+ errorFile:this.errorFile,diagnosticFile:this.errorFile+'.events.jsonl',
148
+ writeErrors:this.closeWriteErrors,diagnosticErrors:this.diagnosticErrors};
149
+ if(!exited)throw failure('NATIVE_CLEANUP_UNCONFIRMED','Owned native process exit was not confirmed within the cleanup limit',{cleanup});
150
+ if(forced)throw failure('NATIVE_FORCED_EXIT','Native worker required forced termination',{cleanup});
151
+ if(this.failure?.code==='NATIVE_SPAWN_ERROR')throw failure('NATIVE_SPAWN_ERROR',this.failure.message,{cause:this.failure,cleanup});
152
+ if(exited.code!==0)throw failure('NATIVE_EXIT_NONZERO','Native worker exited unsuccessfully',{cleanup});
153
+ if(this.closeWriteErrors.length||this.diagnosticErrors.length)throw failure('NATIVE_CLEANUP_ERROR','Native cleanup or diagnostic errors retained',{cleanup});
154
+ return cleanup;
155
+ }
156
+ }
157
+ module.exports={ReplayRpc,nativeErrorDetails:errorRecord};