@trillboards/edge-sdk 0.2.104 → 0.2.107

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.
@@ -23,6 +23,10 @@ LOCAL_BIN="$USER_HOME/.local/bin"
23
23
  SERVE_PORT="${TRILLBOARDS_DETECTOR_PORT:-9380}"
24
24
  SERVE_UNIT="trillboards-detector"
25
25
  DETECTOR_PYTHON="${TRILLBOARDS_DETECTOR_PYTHON:-3.12}"
26
+ # The environment file BOTH units declare (`EnvironmentFile=-/etc/trillboards/env`).
27
+ # Overridable like the four settings above it, and for the same reason those are:
28
+ # so this script can be RUN in a test rather than only read by one.
29
+ ENV_FILE="${TRILLBOARDS_ENV_FILE:-/etc/trillboards/env}"
26
30
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd || echo .)"
27
31
 
28
32
  mkdir -p "$LOG_DIR" 2>/dev/null || LOG_DIR="$USER_HOME/.trillboards-logs"
@@ -75,6 +79,73 @@ DETECTOR="$LOCAL_BIN/trillboards-detector"
75
79
  [ -x "$DETECTOR" ] || { log "ERROR: trillboards-detector binary missing after install"; exit 0; }
76
80
  log "trillboards-detector installed at $DETECTOR"
77
81
 
82
+ # ── THE RAM CEILING ─────────────────────────────────────────────────────────
83
+ #
84
+ # Without this the detector holds its pinned model and REFUSES to make any
85
+ # second model resident — `registry.py::_admit`, "no RAM ceiling was injected,
86
+ # so this service has no basis for a portfolio decision and will not invent
87
+ # one". That refusal is correct and stays; what was missing is the injection.
88
+ # Measured on a live GCE connector 2026-08-26: every delivered specialist sat
89
+ # permanently `idle` and `POST /detect` answered 503 naming exactly this.
90
+ #
91
+ # THE ENVIRONMENT FILE, not the ExecStart line, because on this platform the
92
+ # unit is a STATIC file `install.sh` copies verbatim — there is nothing to
93
+ # template. Both units already declare `EnvironmentFile=-/etc/trillboards/env`
94
+ # and nothing has ever written it. macOS and Windows take the same number as a
95
+ # `--ram-budget-mb` argument instead, because their supervisor definitions ARE
96
+ # generated by their setup scripts. One derivation, three transports.
97
+ #
98
+ # REWRITTEN ON EVERY RUN: the box's memory can change (a VM resize, a stick
99
+ # added) and so can the committed reservations, so an upgrade must re-derive
100
+ # rather than inherit. A run that CANNOT derive leaves an existing line alone —
101
+ # it was derived from this same box — and injects nothing new, which leaves the
102
+ # service in its existing honest refusal rather than acting on a guess.
103
+ #
104
+ # ONLY THE CEILING GOES IN THIS FILE. Assignments from `EnvironmentFile=`
105
+ # OUTRANK a unit's own `Environment=` — measured on systemd 252 with the two
106
+ # directives in both orders, the file wins either way — so anything written here
107
+ # silently beats the units. That is harmless for a value the units do not set,
108
+ # and it is a fresh outage for one they do: a `TRILLBOARDS_DATA_DIR` line here
109
+ # would move the connector's state root out of `ReadWritePaths=`, which is a
110
+ # literal and cannot follow a variable. Do not add one.
111
+ inject_ram_ceiling() {
112
+ local budget_script env_file tmp_file budget
113
+ env_file="$ENV_FILE"
114
+ budget_script="$SOURCE/ram-budget.js"
115
+
116
+ command -v node >/dev/null 2>&1 || {
117
+ log "WARN: node not found, so no RAM ceiling is derived; the detector will hold its pinned model and refuse a second one"
118
+ return 0
119
+ }
120
+ [ -f "$budget_script" ] || {
121
+ log "WARN: $budget_script is missing, so no RAM ceiling is derived"
122
+ return 0
123
+ }
124
+
125
+ budget="$(node "$budget_script" --explain 2>>"$LOG")" || {
126
+ log "WARN: could not derive a RAM ceiling for this box (see $LOG); the detector will refuse a second resident model"
127
+ return 0
128
+ }
129
+ case "$budget" in
130
+ ''|*[!0-9]*) log "WARN: the RAM-ceiling derivation returned '$budget', which is not a number of MiB; injecting nothing"; return 0 ;;
131
+ esac
132
+
133
+ mkdir -p "$(dirname "$env_file")" 2>/dev/null || true
134
+ tmp_file="$env_file.tmp.$$"
135
+ # Rewrite through a temp file so a concurrent read never sees a half-file, and
136
+ # so the key is REPLACED rather than appended — systemd takes the last
137
+ # assignment, but a file that grows a line per install is its own bug.
138
+ { [ -f "$env_file" ] && grep -v '^TRILLBOARDS_DETECTOR_RAM_BUDGET_MB=' "$env_file"; true; } > "$tmp_file" 2>/dev/null || : > "$tmp_file"
139
+ printf 'TRILLBOARDS_DETECTOR_RAM_BUDGET_MB=%s\n' "$budget" >> "$tmp_file"
140
+ if mv "$tmp_file" "$env_file" 2>/dev/null; then
141
+ log "RAM ceiling $budget MiB written to $env_file (derived from this box; see the log above for the subtraction)"
142
+ else
143
+ rm -f "$tmp_file" 2>/dev/null || true
144
+ log "WARN: could not write $env_file (owned by another user?); the detector will refuse a second resident model"
145
+ fi
146
+ }
147
+ inject_ram_ceiling
148
+
78
149
  # The unit is installed AND STARTED by install.sh, which has root. This script
79
150
  # runs as the unprivileged `trillboards` service user (nologin, no sudoers
80
151
  # entry), so on a fresh install BOTH attempts below fail by design.
@@ -43,6 +43,65 @@ function Register-Connector([string]$Root) {
43
43
  if ($LASTEXITCODE -ne 0) { throw "Scheduled-task registration failed." }
44
44
  }
45
45
 
46
+ <#
47
+ Carry the detector's RAM ceiling onto an EXISTING install.
48
+
49
+ WHY THE UPDATE TRANSACTION HAS TO DO THIS. Nothing else on an upgraded box
50
+ will. This script only calls Register-Connector, and trillboards-edge.cmd
51
+ re-runs setup-detector.ps1 only when the task is MISSING or /health answers
52
+ 000 - so a HEALTHY detector keeps the task action it was registered with. A
53
+ box that updates normally would therefore keep an action with no
54
+ `--ram-budget-mb` for ever, every delivered specialist would stay `idle`, and
55
+ the fix would reach NEW INSTALLS ONLY. That is the exact shape of the
56
+ 2026-08-19 Windows BOM incident, and it is why this is here rather than left
57
+ to the repair path.
58
+
59
+ RE-REGISTER, NOT RE-PROVISION. `setup-detector.ps1` runs `uv tool install
60
+ --force`, which rebuilds a venv and needs the network; putting that inside an
61
+ update transaction would give the upgrade a new way to be slow and a new way
62
+ to fail. Re-registering the task is the whole of what has to change, and
63
+ register-detector-task.ps1 already stops the running service, replaces the
64
+ action and starts it again - so this both migrates and restarts it.
65
+
66
+ BEST EFFORT, ALWAYS. The detector is a cost optimisation: without it every
67
+ frame goes to the VLM exactly as it does today. It must never be able to fail
68
+ a customer's upgrade, so every path here returns quietly.
69
+ #>
70
+ function Update-DetectorTask([string]$Root) {
71
+ try {
72
+ $task = Get-ScheduledTask -TaskName "TrillboardsDetector" -ErrorAction SilentlyContinue
73
+ if (-not $task) { return } # nothing registered yet; the cmd repair path owns that case
74
+ # The interpreter path comes off the task we are replacing rather than being
75
+ # re-derived - setup-detector.ps1 resolved it under the USER profile, and
76
+ # re-deriving here could resolve somewhere else entirely. Same rule
77
+ # register-task.ps1 states for its own repair.
78
+ $exe = ($task.Actions | Select-Object -First 1).Execute
79
+ if (-not $exe) { return }
80
+
81
+ $register = Join-Path $Root "bin\register-detector-task.ps1"
82
+ if (-not (Test-Path -LiteralPath $register)) { return }
83
+
84
+ # Re-DERIVED, not carried: the box may have gained memory since it was
85
+ # installed, and the reservations this is computed from are committed values
86
+ # that move with a release. If it cannot be derived we pass nothing, and
87
+ # register-detector-task.ps1 keeps whatever ceiling the old action carried.
88
+ $budget = ""
89
+ $budgetScript = Join-Path $Root "bin\detector\ram-budget.js"
90
+ $nodeExe = Join-Path $Root "bin\node.exe"
91
+ if ((Test-Path -LiteralPath $budgetScript) -and (Test-Path -LiteralPath $nodeExe)) {
92
+ $derived = ("" + (& $nodeExe $budgetScript)).Trim()
93
+ if ($LASTEXITCODE -eq 0 -and $derived -match '^\d+$') { $budget = $derived }
94
+ }
95
+
96
+ $registerArgs = @('-DetectorPath', $exe)
97
+ if ($budget) { $registerArgs += @('-RamBudgetMb', $budget) }
98
+ & $register @registerArgs | Out-Null
99
+ Write-Host "Detector task migrated$(if ($budget) { " (RAM ceiling $budget MiB)" })."
100
+ } catch {
101
+ Write-Warning "Could not migrate the detector task: $($_.Exception.Message). Sensing is unaffected; every frame keeps going to the VLM."
102
+ }
103
+ }
104
+
46
105
  function Assert-ConnectorScheduled {
47
106
  # stop-existing.ps1 DISABLES the task so restart-on-failure cannot relaunch
48
107
  # node.exe mid-swap. A disabled task suppresses the AtLogOn trigger too, so
@@ -92,6 +151,7 @@ try {
92
151
  Assert-ConnectorVersion $InstallDir
93
152
  Register-Connector $InstallDir
94
153
  Assert-ConnectorScheduled
154
+ Update-DetectorTask $InstallDir
95
155
  if (Test-Path (Join-Path $InstallDir "trillboards.config.json")) {
96
156
  Start-ScheduledTask -TaskName "TrillboardsEdge" -ErrorAction Stop
97
157
  }
@@ -35,13 +35,48 @@
35
35
  param(
36
36
  [Parameter(Mandatory = $true)][string]$DetectorPath,
37
37
  [string]$Port = "9380",
38
- [string]$LogFile = ""
38
+ [string]$LogFile = "",
39
+ # The portfolio RAM ceiling, in MiB, DERIVED FROM THIS MACHINE by
40
+ # deploy/detector/ram-budget.js and passed in by setup-detector.ps1.
41
+ #
42
+ # EMPTY IS A REAL VALUE AND MUST STAY REACHABLE. `registry.py::_admit` treats
43
+ # an absent ceiling as "nobody has told me one" and refuses to make a second
44
+ # model resident rather than inventing a number, which is the correct thing
45
+ # for this task to say when the box could not be measured. A default here
46
+ # would make this file a second allocation authority - and one that cannot see
47
+ # how much memory the machine has.
48
+ [string]$RamBudgetMb = ""
39
49
  )
40
50
  $ErrorActionPreference = "Stop"
41
51
 
42
52
  $TaskName = "TrillboardsDetector"
43
53
  $UserId = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
44
54
 
55
+ # RECOVER THE CEILING FROM THE TASK WE ARE REPLACING, when the caller did not
56
+ # supply one.
57
+ #
58
+ # register-task.ps1 repairs a non-headless TrillboardsDetector inside its own
59
+ # elevated pass and calls us with ONLY -DetectorPath. Without this, the empty
60
+ # default would win and the replacement action would silently lose
61
+ # --ram-budget-mb -- turning a box that HAD a ceiling back into one that refuses
62
+ # every specialist, on a path whose whole purpose is repair.
63
+ #
64
+ # It is the same idiom that caller already applies to the interpreter path:
65
+ # "Recover ... from the task we are replacing rather than re-deriving it".
66
+ # Re-deriving here would also be wrong for a subtler reason -- an elevated
67
+ # repair pass may not see the same machine state the original derivation did,
68
+ # and a repair must not quietly change a value nobody asked it to change.
69
+ if ([string]::IsNullOrWhiteSpace($RamBudgetMb)) {
70
+ try {
71
+ $existingAction = (Get-ScheduledTask -TaskName $TaskName -ErrorAction Stop).Actions |
72
+ Select-Object -First 1
73
+ if ($existingAction -and $existingAction.Arguments -match '--ram-budget-mb\s+(\d+)') {
74
+ $RamBudgetMb = $Matches[1]
75
+ Write-Host "Carrying the existing RAM ceiling ($RamBudgetMb MiB) onto the replacement task."
76
+ }
77
+ } catch { }
78
+ }
79
+
45
80
  if ([string]::IsNullOrWhiteSpace($LogFile)) {
46
81
  $LogFile = Join-Path (Join-Path $env:LOCALAPPDATA "Trillboards\logs") "detector.service.log"
47
82
  }
@@ -51,6 +86,15 @@ try { New-Item -ItemType Directory -Force -Path (Split-Path -Parent $LogFile) |
51
86
  # Loopback only -- LocalDetectorClient is local; nothing off-box has any
52
87
  # business reaching this.
53
88
  $argument = 'serve --host 127.0.0.1 --port ' + $Port + ' --log-file "' + $LogFile + '"'
89
+ # Appended only when it was derived, and validated here rather than trusted:
90
+ # this string becomes a command line, and a malformed one would either fail the
91
+ # service's own argument parse on every restart or - worse - be silently
92
+ # reinterpreted. Digits only.
93
+ if ($RamBudgetMb -match '^\d+$') {
94
+ $argument += ' --ram-budget-mb ' + $RamBudgetMb
95
+ } elseif (-not [string]::IsNullOrWhiteSpace($RamBudgetMb)) {
96
+ Write-Warning "Ignoring a RAM ceiling that is not a whole number of MiB: '$RamBudgetMb'. The detector will hold its pinned model and refuse to make a second one resident."
97
+ }
54
98
  $Action = New-ScheduledTaskAction -Execute $DetectorPath -Argument $argument
55
99
 
56
100
  # NOT AT LOGON ONLY -- see register-task.ps1 for the full rationale, including
@@ -140,6 +140,48 @@ if (-not (Test-Path -LiteralPath $detectorPath)) {
140
140
  }
141
141
  Log "trillboards-detector installed at $detectorPath"
142
142
 
143
+ # --- 2b. The RAM ceiling, derived from THIS machine --------------------------
144
+ #
145
+ # Without it the service holds its pinned model and refuses to make any second
146
+ # model resident - `registry.py::_admit`, "no RAM ceiling was injected, so this
147
+ # service has no basis for a portfolio decision and will not invent one". The
148
+ # refusal is correct; the injection was missing from all six supervisor
149
+ # definitions until 2026-08-26, so every delivered specialist stayed `idle`.
150
+ #
151
+ # A TASK ARGUMENT, not an environment variable. A Scheduled Task action has no
152
+ # environment block of its own, and setting a User-scope variable would put a
153
+ # per-machine tuning knob into global machine state where nothing associates it
154
+ # with this service. macOS also takes an argument (its plist is generated too);
155
+ # only Linux, whose unit is a static file with an EnvironmentFile already
156
+ # declared, uses the variable. ONE derivation, three transports.
157
+ #
158
+ # EMPTY WHEN IT CANNOT BE DERIVED, never a placeholder: "nobody has told me a
159
+ # ceiling" is a state the detector handles correctly and loudly.
160
+ $ramBudgetMb = ""
161
+ $budgetScript = Join-Path $source "ram-budget.js"
162
+ $nodeExe = Join-Path $Here "node.exe"
163
+ if (-not (Test-Path -LiteralPath $nodeExe)) {
164
+ $foundNode = Get-Command node -ErrorAction SilentlyContinue
165
+ if ($foundNode) { $nodeExe = $foundNode.Source } else { $nodeExe = $null }
166
+ }
167
+ if (-not $nodeExe) {
168
+ Log "WARN: no node runtime found, so no RAM ceiling is derived; the detector will refuse a second resident model"
169
+ } elseif (-not (Test-Path -LiteralPath $budgetScript)) {
170
+ Log "WARN: $budgetScript is missing, so no RAM ceiling is derived"
171
+ } else {
172
+ # `--explain` writes the subtraction to stderr and the bare integer to stdout,
173
+ # so the log carries WHY and the variable carries only the number. 2>&1 is
174
+ # deliberately NOT used: it would fold the explanation into the value.
175
+ $derived = & $nodeExe $budgetScript "--explain" 2>> $LogPath
176
+ $derived = ("$derived").Trim()
177
+ if ($LASTEXITCODE -eq 0 -and $derived -match '^\d+$') {
178
+ $ramBudgetMb = $derived
179
+ Log "RAM ceiling $ramBudgetMb MiB (derived from this machine; see the log above for the subtraction)"
180
+ } else {
181
+ Log "WARN: could not derive a RAM ceiling for this machine (see $LogPath); the detector will refuse a second resident model"
182
+ }
183
+ }
184
+
143
185
  # --- 3. The Scheduled Task ---------------------------------------------------
144
186
  $registration = Join-Path $Here "register-detector-task.ps1"
145
187
  if (-not (Test-Path -LiteralPath $registration)) {
@@ -147,7 +189,17 @@ if (-not (Test-Path -LiteralPath $registration)) {
147
189
  exit 0
148
190
  }
149
191
  Log "registering the detector Scheduled Task on :$Port"
150
- & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $registration -DetectorPath $detectorPath -Port $Port *>> $LogPath
192
+ # OMITTED, not passed empty, when nothing was derived. Windows PowerShell drops
193
+ # an empty-string argument to a native command, so `-RamBudgetMb ""` arrives as a
194
+ # bare `-RamBudgetMb` with nothing after it and the whole registration dies with
195
+ # "Missing an argument for parameter" - turning an undeterminable ceiling into an
196
+ # unsupervised detector. The task script's own default covers the omission.
197
+ $registrationArgs = @(
198
+ '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $registration,
199
+ '-DetectorPath', $detectorPath, '-Port', $Port
200
+ )
201
+ if ($ramBudgetMb) { $registrationArgs += @('-RamBudgetMb', $ramBudgetMb) }
202
+ & powershell.exe @registrationArgs *>> $LogPath
151
203
  if ($LASTEXITCODE -ne 0) {
152
204
  Log "ERROR: the detector Scheduled Task could not be registered; the cascade stays off"
153
205
  exit 0
package/dist/EdgeAgent.js CHANGED
@@ -44,7 +44,7 @@ const edge_ads_1 = require("@trillboards/edge-ads");
44
44
  const CommandRouter_1 = require("./CommandRouter");
45
45
  const config_1 = require("./config");
46
46
  const dataDir_1 = require("./dataDir");
47
- const SDK_VERSION = '0.2.104';
47
+ const SDK_VERSION = '0.2.107';
48
48
  class EdgeAgent extends events_1.EventEmitter {
49
49
  constructor(config, deps) {
50
50
  super();
@@ -31,7 +31,7 @@ export interface DiagnosticReport {
31
31
  skipped: number;
32
32
  };
33
33
  }
34
- declare const SDK_VERSION = "0.2.104";
34
+ declare const SDK_VERSION = "0.2.107";
35
35
  declare function checkNodeVersion(): CheckResult;
36
36
  declare function checkPlatform(): CheckResult;
37
37
  declare function checkMemory(): CheckResult;
package/dist/diagnose.js CHANGED
@@ -63,7 +63,7 @@ const localNetworkAccess_1 = require("./localNetworkAccess");
63
63
  // ---------------------------------------------------------------------------
64
64
  // SDK version — mirrors package.json; kept in sync by CI
65
65
  // ---------------------------------------------------------------------------
66
- const SDK_VERSION = '0.2.104';
66
+ const SDK_VERSION = '0.2.107';
67
67
  exports._SDK_VERSION = SDK_VERSION;
68
68
  // ---------------------------------------------------------------------------
69
69
  // ANSI helpers (no external deps)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trillboards/edge-sdk",
3
- "version": "0.2.104",
3
+ "version": "0.2.107",
4
4
  "description": "Composable cross-platform Edge AI SDK for audience sensing on DOOH/CTV devices",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",