@trillboards/edge-sdk 0.2.258 → 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 (85) hide show
  1. package/deploy/windows/ci/test-published-install.ps1 +29 -1
  2. package/deploy/windows/e2e/test-recorder-family.ps1 +16 -2
  3. package/dist/CloudSensingManager.d.ts +36 -0
  4. package/dist/CloudSensingManager.d.ts.map +1 -1
  5. package/dist/CloudSensingManager.js +147 -20
  6. package/dist/CloudSensingManager.js.map +1 -1
  7. package/dist/DetectorFields.d.ts +2 -1
  8. package/dist/DetectorFields.d.ts.map +1 -1
  9. package/dist/DetectorFields.js +6 -3
  10. package/dist/DetectorFields.js.map +1 -1
  11. package/dist/EdgeAgent.js +1 -1
  12. package/dist/FloorObjects.d.ts +342 -0
  13. package/dist/FloorObjects.d.ts.map +1 -0
  14. package/dist/FloorObjects.js +961 -0
  15. package/dist/FloorObjects.js.map +1 -0
  16. package/dist/SceneMarks.d.ts +1 -1
  17. package/dist/SceneMarks.d.ts.map +1 -1
  18. package/dist/SceneMarks.js +1 -1
  19. package/dist/SceneMarks.js.map +1 -1
  20. package/dist/ScopedVlmReview.d.ts +5 -1
  21. package/dist/ScopedVlmReview.d.ts.map +1 -1
  22. package/dist/ScopedVlmReview.js +40 -4
  23. package/dist/ScopedVlmReview.js.map +1 -1
  24. package/dist/UniformSceneStore.d.ts +7 -0
  25. package/dist/UniformSceneStore.d.ts.map +1 -1
  26. package/dist/UniformSceneStore.js +26 -1
  27. package/dist/UniformSceneStore.js.map +1 -1
  28. package/dist/VideoSegmentUploader.d.ts +4 -0
  29. package/dist/VideoSegmentUploader.d.ts.map +1 -1
  30. package/dist/VideoSegmentUploader.js +21 -1
  31. package/dist/VideoSegmentUploader.js.map +1 -1
  32. package/dist/autoSense.d.ts +5 -4
  33. package/dist/autoSense.d.ts.map +1 -1
  34. package/dist/autoSense.js +24 -9
  35. package/dist/autoSense.js.map +1 -1
  36. package/dist/config.d.ts +9 -0
  37. package/dist/config.d.ts.map +1 -1
  38. package/dist/config.js +15 -0
  39. package/dist/config.js.map +1 -1
  40. package/dist/diagnose.d.ts +1 -1
  41. package/dist/diagnose.js +1 -1
  42. package/dist/localSensing.d.ts.map +1 -1
  43. package/dist/localSensing.js +2 -0
  44. package/dist/localSensing.js.map +1 -1
  45. package/dist/sensingRunMode.d.ts +8 -0
  46. package/dist/sensingRunMode.d.ts.map +1 -1
  47. package/dist/sensingRunMode.js +59 -11
  48. package/dist/sensingRunMode.js.map +1 -1
  49. package/package.json +6 -5
  50. package/retained/CapturedTheftProfile.cjs +83 -0
  51. package/retained/ExperimentalTheftConnector.cjs +392 -0
  52. package/retained/FrameTheftRuntime.cjs +111 -0
  53. package/retained/FrameTheftWorker.py +136 -0
  54. package/retained/InstalledTheftLifecycle.cjs +165 -0
  55. package/retained/InstalledTheftPackage.cjs +91 -0
  56. package/retained/LiveTheftBinding.cjs +55 -0
  57. package/retained/ObservedReviewCaseEvidence.py +188 -0
  58. package/retained/ObservedSameWristPolicy.py +205 -0
  59. package/retained/OrderedPerceptionDelivery.cjs +72 -0
  60. package/retained/PairedTheftRoute.cjs +402 -0
  61. package/retained/ReplayRpc.cjs +157 -0
  62. package/retained/RetainedCaptureClient.cjs +63 -16
  63. package/retained/SavedTheftSession.cjs +110 -0
  64. package/retained/TheftCaseContract.cjs +36 -0
  65. package/retained/TheftCaseDelivery.cjs +81 -0
  66. package/retained/TheftDeliveryPump.cjs +41 -0
  67. package/retained/TheftMovementOwner.py +234 -0
  68. package/retained/TheftReviewPolicy.cjs +8 -0
  69. package/retained/__tests__/paired-theft-manager.test.cjs +509 -0
  70. package/retained/__tests__/support/live-shelf-api.cjs +139 -0
  71. package/retained/__tests__/support/load-sdk-sources.cjs +41 -0
  72. package/retained/__tests__/support/loopback-proxy.cjs +33 -0
  73. package/retained/__tests__/support/pinned-api-loader.cjs +11 -0
  74. package/retained/__tests__/support/theft-builder.cjs +61 -0
  75. package/retained/__tests__/support/theft-packet-fixture.cjs +58 -0
  76. package/retained/__tests__/support/theft-readiness.cjs +51 -0
  77. package/retained/__tests__/test_live_theft_input.py +103 -0
  78. package/retained/__tests__/theft-case-api.test.cjs +135 -0
  79. package/retained/__tests__/theft-ci-regression.test.cjs +92 -0
  80. package/retained/__tests__/theft-config.test.cjs +84 -0
  81. package/retained/__tests__/theft-entry.test.cjs +76 -0
  82. package/retained/__tests__/theft-native-recovery.test.cjs +90 -0
  83. package/retained/__tests__/theft-readiness.test.cjs +164 -0
  84. package/retained/manager.cjs +61 -7
  85. package/retained/pilot-profile-client.cjs +4 -0
@@ -0,0 +1,164 @@
1
+ 'use strict';
2
+ const assert=require('node:assert/strict'),{test}=require('node:test');
3
+ const {load,supervisorFixture,Spool,NativeError}=require('./support/theft-readiness.cjs');
4
+ const {InstalledTheftLifecycle}=require('../InstalledTheftLifecycle.cjs');
5
+ const Cloud=load('src/CloudSensingManager.ts').CloudSensingManager;
6
+ const paired=load('retained/PairedTheftRoute.cjs');
7
+ const tick=()=>new Promise(resolve=>setImmediate(resolve));
8
+ function manager(events,name='manager',native=true) {
9
+ const value={async start(options){events.push([name,'start',options]);},async stop(){events.push([name,'stop']);},
10
+ getSensingHealth:()=>({localInferences:0})};
11
+ if(native)value.startNativeTheftOnly=async()=>{events.push([name,'native']);};return value;
12
+ }
13
+ function cloudState(values={}) {
14
+ return Object.assign(Object.create(Cloud.prototype),{running:false,healthOnlyMode:false,nativeTheftOnlyMode:false,
15
+ startGeneration:1,loops:[],frameGroupers:new Map(),candidates:null,now:()=>1000,cadenceSource:null,
16
+ periodicIntervalMs:500,cameraHealthHeartbeatIntervalMs:60000,motionScanIntervalMs:null,
17
+ actorPerceptionBusy:false,actorPerceptionNextFeed:0,orderedDirty:new Set(),
18
+ isCurrentStart:()=>true,emit(){},emitLoopError(_loop,error){throw error;},...values});
19
+ }
20
+ function selectedLoop(name,active=true) {
21
+ return {deps:{name,client:{isReviewActive:()=>true,isNativeTheftActive:()=>active,
22
+ hasPendingNativeTheftPerception:()=>false},camera:{setIdle(){}}},faceDetected:false,readinessWait:null};
23
+ }
24
+ test('ordinary supervisor still waits in health-only mode when Gemma is unavailable',async()=>{
25
+ const events=[],m=manager(events,'ordinary',false),s=supervisorFixture(m);
26
+ try{assert.equal(await s.supervisor.startInitial(),true);assert.equal(s.supervisor.currentMode,'waiting');
27
+ assert.equal(events.length,1);assert.equal(events[0][0],'ordinary');assert.equal(events[0][1],'start');
28
+ assert.deepEqual(Object.entries(events[0][2]),[['healthOnly',true]]);assert.equal(s.probes,1);}
29
+ finally{await s.supervisor.shutdown();assert.equal(s.timers.size,0);}
30
+ });
31
+ test('explicit native supervisor starts without declaring Gemma healthy',async()=>{
32
+ const events=[],m=manager(events),s=supervisorFixture(m);
33
+ try{await s.supervisor.startInitial();assert.deepEqual(events,[['manager','native']]);
34
+ assert.equal(s.supervisor.currentMode,'waiting');assert.equal(m.getSensingHealth().localInferences,0);
35
+ assert(s.logs.some(line=>line.includes('Gemma is unavailable')));assert(!s.logs.some(line=>line.includes('LOCAL on-device sensing selected')));}
36
+ finally{await s.supervisor.shutdown();assert.equal(s.timers.size,0);}
37
+ });
38
+ test('healthy Gemma keeps the original full local start even with an installed theft owner',async()=>{
39
+ const events=[],s=supervisorFixture(manager(events),{ok:true,reason:'expected Gemma model listed'});
40
+ try{await s.supervisor.startInitial();assert.equal(s.supervisor.currentMode,'local');
41
+ assert.deepEqual(events,[['manager','start',undefined]]);}
42
+ finally{await s.supervisor.shutdown();}
43
+ });
44
+ test('promotion stops native-only before the same manager resumes ordinary local work',async()=>{
45
+ let health={ok:false,reason:'Gemma unavailable'};const events=[],s=supervisorFixture(manager(events),()=>health);
46
+ try{await s.supervisor.startInitial();health={ok:true,reason:'expected model listed'};await s.supervisor.recheck();
47
+ assert.equal(s.supervisor.currentMode,'local');assert.deepEqual(events,[['manager','native'],['manager','stop'],['manager','start',undefined]]);}
48
+ finally{await s.supervisor.shutdown();}
49
+ });
50
+ test('waiting reconfiguration uses native admission after commit and preserves ordering',async()=>{
51
+ const events=[],s=supervisorFixture(manager(events,'previous'));
52
+ try{await s.supervisor.startInitial();await s.supervisor.reconfigure(async()=>manager(events,'next'),()=>events.push(['commit']),()=>events.push(['rollback']));
53
+ assert.deepEqual(events,[['previous','native'],['previous','stop'],['commit'],['next','native']]);
54
+ assert.equal(s.supervisor.currentMode,'waiting');}
55
+ finally{await s.supervisor.shutdown();}
56
+ });
57
+ test('failed native reconfiguration preserves the error and restarts the previous waiting path',async()=>{
58
+ const events=[],failure=Error('planned native startup failure'),s=supervisorFixture(manager(events,'previous'));
59
+ const next=manager(events,'next');next.startNativeTheftOnly=async()=>{events.push(['next','native']);throw failure;};
60
+ try{await s.supervisor.startInitial();await assert.rejects(s.supervisor.reconfigure(async()=>next,
61
+ ()=>events.push(['commit']),()=>events.push(['rollback'])),error=>error===failure);
62
+ assert.deepEqual(events,[['previous','native'],['previous','stop'],['commit'],['next','native'],['next','stop'],['rollback'],['previous','native']]);
63
+ assert.equal(s.supervisor.currentMode,'waiting');}
64
+ finally{await s.supervisor.shutdown();}
65
+ });
66
+ test('native-only manager start reuses all existing camera-loop starts and sets a distinct mode',async()=>{
67
+ const events=[],theft=selectedLoop('theft'),ordinary={deps:{name:'ordinary',client:{}}};
68
+ const m=cloudState({loops:[theft,ordinary],startLoop:async(loop)=>events.push(loop.deps.name),scheduleCandidatePump:()=>events.push('pump')});
69
+ await m.start({nativeTheftOnly:true});assert.deepEqual(events,['theft','ordinary','pump']);
70
+ assert.equal(m.nativeTheftOnlyMode,true);assert.equal(m.healthOnlyMode,false);
71
+ assert.equal(m.startNativeTheftOnly,undefined,'Ordinary class prototype must not expose the installed capability');
72
+ });
73
+ test('native-only start without a registered route refuses before any camera work',async()=>{
74
+ const m=cloudState({loops:[{deps:{client:{}}}],candidates:{startRun(){throw Error('must not reach camera/queue startup');}}});
75
+ await assert.rejects(m.start({nativeTheftOnly:true}),/registered route/);assert.equal(m.running,false);
76
+ });
77
+ test('health-only and native-only are distinct and cannot be requested together',async()=>{
78
+ const m=cloudState({loops:[selectedLoop('theft')]});
79
+ await assert.rejects(m.start({nativeTheftOnly:true,healthOnly:true}),/cannot be health-only/);assert.equal(m.running,false);
80
+ });
81
+ test('native-only capture admits the selected theft camera and health-checks the ordinary camera',async()=>{
82
+ const events=[],m=cloudState({nativeTheftOnlyMode:true,
83
+ captureAndPost:async loop=>{events.push(['analyze',loop.deps.name]);return null;},
84
+ captureHealthFrame:async loop=>events.push(['health',loop.deps.name])});
85
+ const theft=selectedLoop('theft'),ordinary={deps:{name:'ordinary',client:{},camera:{setIdle:value=>events.push(['idle',value])}}};
86
+ await m.captureWork(theft);await m.captureWork(ordinary);
87
+ assert.deepEqual(events,[['analyze','theft'],['idle',true],['health','ordinary']]);
88
+ });
89
+ test('health-only mode admits no theft inference even when the selected route is ready',async()=>{
90
+ const events=[],m=cloudState({healthOnlyMode:true,captureHealthFrame:async()=>events.push('health'),
91
+ captureAndPost:async()=>{throw Error('must not analyze in health-only mode');}});
92
+ await m.captureWork(selectedLoop('theft'));assert.deepEqual(events,['health']);
93
+ });
94
+ test('ordinary default capture never consults the experimental selection predicate',async()=>{
95
+ const m=cloudState({captureAndPost:async()=>({ordinary:true})}),loop=selectedLoop('ordinary');
96
+ loop.deps.client.isNativeTheftActive=()=>{throw Error('ordinary mode must not consult theft');};
97
+ assert.deepEqual(await m.captureWork(loop),{ordinary:true});
98
+ });
99
+ test('selection changes preserve health cadence and truthful per-camera sensing state',()=>{
100
+ let active=true;const m=cloudState({nativeTheftOnlyMode:true}),loop=selectedLoop('theft');loop.deps.client.isNativeTheftActive=()=>active;
101
+ assert.equal(m.intervalFor(loop),500);assert.equal(m.idleSensingState(loop),'idle');
102
+ active=false;assert.equal(m.intervalFor(loop),60000);assert.equal(m.idleSensingState(loop),'unavailable');
103
+ const other={deps:{client:{isReviewActive:()=>true}}};assert.equal(m.intervalFor(other),60000);
104
+ assert.equal(m.idleSensingState(other),'unavailable');
105
+ });
106
+ test('ordered perception skips ordinary work but drains original theft after profile deactivation',async()=>{
107
+ const events=[],ordinary={deps:{name:'ordinary',client:{hasPendingOrderedPerception:()=>true,
108
+ perceiveNextOrderedCapture:async()=>{throw Error('ordinary perception must remain held');}}}},theft=selectedLoop('theft',false);
109
+ theft.deps.client.hasPendingNativeTheftPerception=()=>true;theft.deps.client.hasPendingOrderedPerception=()=>true;
110
+ theft.deps.client.perceiveNextOrderedCapture=async()=>{events.push('captured-theft');return true;};
111
+ const m=cloudState({nativeTheftOnlyMode:true,loops:[ordinary,theft]});m.pumpOrderedPerception(1);
112
+ await tick();assert.deepEqual(events,['captured-theft']);assert.equal(m.actorPerceptionBusy,false);assert(m.orderedDirty.has('theft'));
113
+ });
114
+ test('native-only pump allows completed deliveries but holds ordinary model, triage and backlog work',()=>{
115
+ const events=[],spool=new Spool(),m=cloudState({nativeTheftOnlyMode:true,candidates:spool,continuousReview:{independentUploads:true},
116
+ pumpOrderedPerception:()=>events.push('native'),pumpDeliveries:()=>events.push('delivery'),
117
+ pumpUrgentTriage:()=>{throw Error('ordinary triage must remain held');},pumpBacklog:()=>{throw Error('backlog review must remain held');},
118
+ admissionGate:{getMaxInFlight(){throw Error('Gemma admission must remain held');}}});
119
+ m.pumpOrdinaryCandidates(1);assert.deepEqual(events,['native','delivery']);assert.equal(spool.expired,1);
120
+ });
121
+ test('ordinary default pump retains its original triage/admission path',()=>{
122
+ const events=[],spool=new Spool();spool.size=()=>0;
123
+ const m=cloudState({candidates:spool,continuousReview:{independentUploads:false},orderedSweepAtMs:0,
124
+ reviewsInFlight:new Set(),reviewHoldUntilMs:0,optionalReviewInFlight:null,
125
+ pumpOrderedPerception:()=>events.push('ordered'),pumpUrgentTriage:()=>events.push('triage'),
126
+ admissionGate:{getMaxInFlight(){events.push('admission');return 1;}}});
127
+ m.pumpOrdinaryCandidates(1);assert.deepEqual(events,['ordered','triage','admission','admission']);assert.equal(spool.expired,1);
128
+ });
129
+ test('native-only mode cannot dispatch optional Gemma reviews or open audio sessions',async()=>{
130
+ const m=cloudState({nativeTheftOnlyMode:true,optionalReviewSources:[{hasPending(){throw Error('optional review forbidden');}}],
131
+ audioSensingOptions:{enabled:true},loops:[{deps:{audioRtspUrl:'rtsp://example.invalid'}}]});
132
+ m.pumpOptionalReviews(1);await m.attachAudioSensing();
133
+ });
134
+ test('paired capture predicate uses the prepared current profile and preserves readiness failures',()=>{
135
+ const client=Object.create(paired.PairedTheftCaptureClient.prototype);
136
+ const route={registration:{profileId:'theft',reviewMode:'human_only'}};route.selected=context=>paired.PairedTheftRoute.prototype.selected.call(route,context);
137
+ client.theftRoute=route;client.reviewActive=true;client.context={profileState:'active',websiteReviewAdmission:{profileId:'theft'}};
138
+ assert.equal(client.isNativeTheftActive(),true);client.context.websiteReviewAdmission.profileId='ordinary';assert.equal(client.isNativeTheftActive(),false);
139
+ client.contextError=new NativeError('native preparation still pending');assert.equal(client.isNativeTheftActive(),false);
140
+ client.contextError=Error('invalid authority must stay visible');assert.throws(()=>client.isNativeTheftActive(),/invalid authority/);
141
+ client.reviewActive=false;assert.equal(client.isNativeTheftActive(),false);
142
+ });
143
+ test('paired pending predicate never skips an ordinary record or changes captured profile identity',()=>{
144
+ const client=Object.create(paired.PairedTheftCaptureClient.prototype),route={registration:{profileId:'theft',reviewMode:'human_only'}};
145
+ route.selected=context=>paired.PairedTheftRoute.prototype.selected.call(route,context);client.theftRoute=route;
146
+ const row=id=>({perceptionDelivery:{consumerId:'paired_theft_same_wrist_v1'},candidate:{reviewContext:{profileState:'active',websiteReviewAdmission:{profileId:id}}}});
147
+ client.pending=row('ordinary');Object.defineProperty(client,'laterRecords',{get(){throw Error('do not search/reorder later records');}});
148
+ assert.equal(client.hasPendingNativeTheftPerception(),false);client.pending=row('theft');client.context={profileState:'inactive'};
149
+ assert.equal(client.hasPendingNativeTheftPerception(),true);client.pending.perceptionDelivery.consumerId='another-consumer';
150
+ assert.equal(client.hasPendingNativeTheftPerception(),false);client.busy=true;assert.equal(client.hasPendingNativeTheftPerception(),false);
151
+ });
152
+ test('legacy optional-Gemma registration cannot claim native-only capture or pending admission',()=>{
153
+ const client=Object.create(paired.PairedTheftCaptureClient.prototype);
154
+ client.theftRoute={registration:{reviewMode:'optional_gemma'},selected:()=>true};
155
+ client.reviewActive=true;client.context={profileState:'active'};client.pending={candidate:{reviewContext:client.context}};
156
+ assert.equal(client.isNativeTheftActive(),false);assert.equal(client.hasPendingNativeTheftPerception(),false);
157
+ });
158
+ test('installed helper is internal and forwards native-only start without loading a model',async()=>{
159
+ const events=[],m=manager(events,'owned',false),lifecycle=new InstalledTheftLifecycle({
160
+ makeFrame(){throw Error('must remain lazy');},describeOriginal:value=>value,availableBytes:()=>5000000000,onDiagnostic(){}});
161
+ lifecycle.attach(m);assert(!Object.keys(m).includes('startNativeTheftOnly'));
162
+ await m.startNativeTheftOnly();assert.deepEqual(events,[['owned','start',{nativeTheftOnly:true}]]);assert.equal(lifecycle.runtime.reviewer,null);
163
+ assert.equal(lifecycle.contract.reviewPictures,13);assert.equal(lifecycle.contract.queueInclusiveReviewLimitMs,90000);await m.stop();
164
+ });
@@ -6,6 +6,13 @@ const {createHash}=require('node:crypto');
6
6
  const take = name => require('../dist/' + name);
7
7
  const { checkRetainedApi } = require('./website-api-capability.cjs');
8
8
 
9
+ function captureBinding(feed, cameraId) {
10
+ const sourceUrl = typeof feed?.rtspUrl === 'string' ? new URL(feed.rtspUrl) : null;
11
+ if (sourceUrl) { sourceUrl.username = ''; sourceUrl.password = ''; sourceUrl.hash = ''; }
12
+ return { cameraId, sourceId: createHash('sha256').update(JSON.stringify({
13
+ url: sourceUrl?.toString() ?? null, crop: feed?.crop ?? null })).digest('hex') };
14
+ }
15
+
9
16
  // Capture startup and the native qualification use the same model admission.
10
17
  function assertSelectedModelsPrepared(models, actorPolicy, requiresDetector) {
11
18
  const nativePins = [
@@ -80,10 +87,17 @@ async function createWebsiteManager(input, stateDirectory, deps = {}) {
80
87
  const websiteManaged = config.pilot?.websiteManaged === true;
81
88
  assert(feeds.length && (websiteManaged || Object.keys(config.pilot?.alertRules ?? {}).length === feeds.length),
82
89
  'Choose one explicit rule per active feed');
90
+ const theftModule = config.pilot?.experimentalTheft === undefined && deps.theftRuntime === undefined
91
+ ? null : require('./PairedTheftRoute.cjs');
92
+ const theftRegistrations = theftModule?.registrations(config.pilot?.experimentalTheft, deps.theftRuntime,
93
+ websiteManaged, config.pilot?.crossCameraPipelining === true, feeds) ?? new Map();
94
+ const theftRoutes = new Map();
83
95
  const capabilities = new Map();
84
96
  // Complete every check before constructing cameras/providers. A failed gate
85
97
  // does not start capture, submit historical images, or change account settings.
86
98
  for (const feed of feeds) capabilities.set(feed.name, await (deps.capabilityCheck ?? checkRetainedApi)(base, feed));
99
+ const bindings = new Map(feeds.map(feed => [feed.name, captureBinding(feed, capabilities.get(feed.name).cameraId)]));
100
+ const liveBinding = theftModule ? require('./LiveTheftBinding.cjs') : null;
87
101
  // One live-alert age bound: the value the server suppresses late alerts with
88
102
  // (SENSING_LOCAL_MAX_CAPTURE_AGE_MS), or this connector's review window when
89
103
  // an older API does not serve it. Realtime reviews never start past it.
@@ -125,6 +139,7 @@ async function createWebsiteManager(input, stateDirectory, deps = {}) {
125
139
  continuingImagelessReview: feed => capabilities.get(feed.name)?.continuingImagelessReview === true,
126
140
  profileClientFactory: deps.profileClientFactory ?? (feed => require('./pilot-profile-client.cjs').createPilotProfileClient(
127
141
  { apiBaseUrl: config.apiBaseUrl, deviceToken: feed.deviceToken, screenId: feed.screenId,
142
+ liveShelf: liveBinding?.profileHeader(theftRegistrations.get(feed.name), bindings.get(feed.name)),
128
143
  connectorModelGrantScreens:feeds.filter(candidate=>candidate.deviceToken&&candidate.screenId).map(candidate=>String(candidate.screenId)) },
129
144
  { ...take('SensingProfileClient'), ...take('AudienceAnalyzeClient') }, deps.httpPoster)),
130
145
  }), clients = [];
@@ -155,15 +170,20 @@ async function createWebsiteManager(input, stateDirectory, deps = {}) {
155
170
  if(!websiteManaged||!isNativeReadinessUnavailable(error))throw error;
156
171
  }
157
172
  const feed=feeds.find(f=>f.name===loop.name);
158
- const sourceUrl=typeof feed?.rtspUrl==='string'?new URL(feed.rtspUrl):null;
159
- if(sourceUrl){sourceUrl.username='';sourceUrl.password='';sourceUrl.hash='';}
160
- const binding={cameraId:capabilities.get(loop.name).cameraId,
161
- sourceId:createHash('sha256').update(JSON.stringify({url:sourceUrl?.toString()??null,crop:feed?.crop??null})).digest('hex')};
173
+ const binding = bindings.get(loop.name);
162
174
  const validateCaptureContext=current=>{
163
175
  assert(current&&typeof current==='object','Missing paired capture context');
164
176
  const active=current.profileState!=='inactive';
165
177
  assert(websiteManaged||active,'The explicitly selected pilot camera has no active profile');
166
178
  assert(!active||current.modelSelection?.models?.length,'The active website profile has no pinned model selection');
179
+ if (current.websiteReviewAdmission?.kind === 'live_shelf_review_v1') {
180
+ const env = theftRegistrations.get(loop.name)?.environment;
181
+ if (!env || !liveBinding?.profileHeader(theftRegistrations.get(loop.name), binding)
182
+ || !liveBinding.readLiveAdmission(current, env, Date.now())) {
183
+ const { NativeReadinessError } = take('NativeReadiness');
184
+ throw new NativeReadinessError('Live shelf profile is unavailable for the current camera and shelf', 'unavailable');
185
+ }
186
+ }
167
187
  const actorPolicy=actorPerceptionPolicyFromSelection(current.modelSelection,binding);
168
188
  assert(!actorPolicy||rule.mode==='immediate','Actor task profiles require continuous original capture');
169
189
  assertSelectedModelsPrepared(current.modelSelection?.models,actorPolicy,config.pilot.requiresDetector);
@@ -192,7 +212,22 @@ async function createWebsiteManager(input, stateDirectory, deps = {}) {
192
212
  configuredApiBaseUrl: base, pairedCameraId: capabilities.get(loop.name).cameraId,
193
213
  });
194
214
  }
195
- const Capture = websiteManaged ? WebsiteAdmissionCaptureClient
215
+ const theftRegistration = theftRegistrations.get(loop.name);
216
+ let theftRuntime=deps.theftRuntime;
217
+ if(theftRegistration&&theftRuntime?.enableCaseDelivery===true&&!theftRuntime.caseTransportFor){
218
+ assert(theftRegistration.reviewMode==='human_only','Case delivery is limited to explicit human review');
219
+ assert(feed.screenId===binding.cameraId,'Case-delivery token camera differs');
220
+ const {createAuthenticatedCaseTransport}=require('./TheftCaseDelivery.cjs');
221
+ const {requestReviewCaseClips}=take('VideoSegmentUploader');
222
+ theftRuntime={...theftRuntime,caseTransportFor:()=>createAuthenticatedCaseTransport({apiBaseUrl:base,
223
+ cameraId:binding.cameraId,deviceToken:feed.deviceToken,consumeClipRequests:requests=>requestReviewCaseClips(binding.cameraId,requests)})};
224
+ }
225
+ const theftRoute = theftRegistration ? new theftModule.PairedTheftRoute({
226
+ directory: path.join(stateDirectory, 'private-theft-' + loop.name), binding,
227
+ registration: theftRegistration, runtime: theftRuntime,
228
+ }) : null;
229
+ if (theftRoute) theftRoutes.set(loop.name, theftRoute);
230
+ const Capture = theftRoute ? theftModule.PairedTheftCaptureClient : websiteManaged ? WebsiteAdmissionCaptureClient
196
231
  : rule.mode === 'wait_recheck' ? WaitRecheckCaptureClient : RetainedCaptureClient;
197
232
  const client = new Capture(inner, path.join(stateDirectory, 'archive-' + loop.name), {
198
233
  cameraId: loop.name, configuredApiBaseUrl: base, intervalMs: 500,
@@ -204,12 +239,14 @@ async function createWebsiteManager(input, stateDirectory, deps = {}) {
204
239
  // Latest frame wins per camera; capture-order contracts keep their window.
205
240
  realtimeReview: { freshnessMs },
206
241
  ...(websiteManaged ? { liveLookIntervalMs: LIVE_LOOK_INTERVAL_MS } : {}),
207
- ...(rule.mode==='immediate'?{actorPerceiver:new SelectedActorPerceptionClient(binding)}:{}),
242
+ ...(theftRoute ? {actorPerceiver: theftRoute.perceiver, perceptionSink: theftRoute.sink, theftRoute}
243
+ : rule.mode==='immediate'?{actorPerceiver:new SelectedActorPerceptionClient(binding)}:{}),
208
244
  onOfferStall: report => offerStallSink(loop.name, report),
209
245
  // Plan v7 W8: a frame a model answered directly becomes the frame later captures are judged
210
246
  // against for look reuse (FrameGroupingShadow.noteReviewed). Bound once the manager exists.
211
247
  onReviewed: row => reviewedSink(loop.name, row),
212
248
  });
249
+ if (theftRoute && context) theftRoute.stamp(context);
213
250
  loop.client = client; clients.push(client);
214
251
  }
215
252
  const manager = new CloudSensingManager({ loops, retainedApiBaseUrl: base, maxConcurrentAnalyses: pipeline ? 2 : 1, feedStaggerMs: 50,
@@ -217,6 +254,23 @@ async function createWebsiteManager(input, stateDirectory, deps = {}) {
217
254
  candidateBuffer: { ...config.cloudSensing.candidateBuffer, diskSpool: {
218
255
  directory: path.join(stateDirectory, 'spool'), maxFrames: 512, maxPerFeed: 128,
219
256
  maxBytes: 512 * 1024 ** 2, preserveArchivedPending: true }, pumpIntervalMs: 50 } });
257
+ if (theftRoutes.size) {
258
+ for (const [name, route] of theftRoutes) manager.registerOptionalReviewSource({name,
259
+ hasPending: () => [...route.sessions.values()].some(session => session.consumer.pending.size > 0),
260
+ reviewOne: options => route.reviewOne(options),
261
+ });
262
+ const start = manager.start.bind(manager);
263
+ const casePump=[...theftRoutes.values()].some(r=>r.runtime.caseTransportFor)?new (require('./TheftDeliveryPump.cjs').TheftDeliveryPump)(theftRoutes,
264
+ {onError:error=>manager.emit('theftCaseDeliveryError',{name:error.name,message:error.message,stack:error.stack})}):null;
265
+ manager.start = (...args) => {
266
+ if (!manager.isRunning()) for (const route of theftRoutes.values()) route.beginCaptureEpoch();
267
+ const result=start(...args);if(casePump&&casePump.stopped)casePump.start();return result;
268
+ };
269
+ if(casePump){const stop=manager.stop.bind(manager);manager.stop=async(...args)=>{
270
+ const results=await Promise.allSettled([casePump.stop(),stop(...args)]);
271
+ const failures=results.filter(r=>r.status==='rejected').map(r=>r.reason);if(failures.length)throw new AggregateError(failures,'Camera/case-delivery cleanup failed');
272
+ };}
273
+ }
220
274
  for (const client of clients) client.attachReviewQueue(manager.candidates);
221
275
  offerStallSink = (name, report) => manager.emit('archiveOfferStalled', { name, report });
222
276
  // The native manager constructs a shadow grouper per feed. Match it to the
@@ -239,6 +293,6 @@ async function createWebsiteManager(input, stateDirectory, deps = {}) {
239
293
  loops.find(loop => loop.name === candidate.name).client.offered(candidate, result);
240
294
  return result;
241
295
  };
242
- return { manager, clients, loops, ...(stages ? { stageScheduler: stages } : {}) };
296
+ return { manager, clients, loops, ...(theftRoutes.size ? {theftRoutes} : {}), ...(stages ? { stageScheduler: stages } : {}) };
243
297
  }
244
298
  module.exports = { createWebsiteManager, assertSelectedModelsPrepared, answerOccupied };
@@ -57,6 +57,10 @@ function createPilotProfileClient(options, sdk, poster) {
57
57
  let raw,refused=false;
58
58
  const client = new sdk.SensingProfileClient(options, async (url, request, body) => {
59
59
  assert(url === original && request.method === 'GET', 'Unexpected pilot profile request');
60
+ if (options.liveShelf) {
61
+ assert(/^[a-f0-9]{64}\.[a-f0-9]{64}$/.test(options.liveShelf), 'Verified live camera and shelf fingerprint required');
62
+ request = { ...request, headers: { ...request.headers, 'X-CCTV-Live-Shelf': options.liveShelf } };
63
+ }
60
64
  let result;
61
65
  try { result = native ? await nativeProfileRequest(poster, endpoint, request, body) : await poster(endpoint, request, body); }
62
66
  catch (error) { requestError = error; throw error; }