@trillboards/edge-sdk 0.2.158 → 0.2.160

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.
@@ -2,10 +2,11 @@
2
2
  Validates a staged connector, stops the running copy, swaps bin/lib, registers
3
3
  the new hidden task, and restores the previous runnable version on failure.
4
4
  #>
5
- [CmdletBinding()]
5
+ [CmdletBinding(DefaultParameterSetName = 'Update')]
6
6
  param(
7
7
  [Parameter(Mandatory = $true)][string]$InstallDir,
8
- [Parameter(Mandatory = $true)][string]$StagingDir
8
+ [Parameter(Mandatory = $true, ParameterSetName = 'Update')][string]$StagingDir,
9
+ [Parameter(Mandatory = $true, ParameterSetName = 'Restart')][switch]$RestartLocalAi
9
10
  )
10
11
 
11
12
  $ErrorActionPreference = "Stop"
@@ -47,22 +48,29 @@ function Assert-ConnectorVersion([string]$Root) {
47
48
 
48
49
  function Register-Connector([string]$Root) {
49
50
  $register = Join-Path $Root "bin\register-task.ps1"
50
- & $register -InstallDir $InstallDir -Mode "auto-sense"
51
+ $registerArgs = @{ InstallDir = $InstallDir; Mode = 'auto-sense' }
52
+ # Rollback may invoke a released registrar without the new switch. Inspect
53
+ # its actual parameter metadata instead of passing an unsupported argument.
54
+ if ((Get-Command -Name $register -ErrorAction Stop).Parameters.ContainsKey('SkipLocalAiRepair')) {
55
+ $registerArgs.SkipLocalAiRepair = $true
56
+ }
57
+ & $register @registerArgs
51
58
  if ($LASTEXITCODE -ne 0) { throw "Scheduled-task registration failed." }
52
59
  }
53
60
 
54
61
  function Get-OwnedLocalAiProcesses {
62
+ param($Context = $script:modelRuntimeUpdate)
55
63
  # Task Scheduler can stop the uv launcher while leaving its Python child
56
64
  # alive. Match only this user's model server on the verified task's port;
57
65
  # never kill all Python processes or a different user's listener.
58
- $portPattern = '(?:^|\s)--port(?:\s+|=)' + $script:modelRuntimeUpdate.Port + '(?=\s|$)'
66
+ $portPattern = '(?:^|\s)--port(?:\s+|=)' + $Context.Port + '(?=\s|$)'
59
67
  $processes = Get-CimInstance Win32_Process -Filter "Name = 'python.exe' OR Name = 'pythonw.exe' OR Name = 'litert-lm.exe'" -OperationTimeoutSec 5 -ErrorAction Stop
60
68
  foreach ($process in $processes) {
61
69
  if (-not $process.CommandLine -or $process.CommandLine -notmatch 'litert[-_]lm' -or
62
70
  $process.CommandLine -notmatch '(?:^|\s)serve(?=\s|$)' -or $process.CommandLine -notmatch $portPattern) { continue }
63
71
  $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 5 -ErrorAction Stop
64
72
  if ($owner.ReturnValue -ne 0 -or -not $owner.Sid) { throw 'Cannot verify the model process owner; no unverified process was stopped' }
65
- if ($owner.Sid -eq $script:modelRuntimeUpdate.OwnerSid) { $process }
73
+ if ($owner.Sid -eq $Context.OwnerSid) { $process }
66
74
  }
67
75
  }
68
76
 
@@ -92,7 +100,24 @@ function Restore-LocalAiTaskState {
92
100
  }
93
101
  }
94
102
 
95
- function Update-LocalAiRuntime([string]$Root) {
103
+ function Resolve-BackgroundToolAction($Action, [string]$Root, [string]$ToolName) {
104
+ $wscript = Join-Path $env:WINDIR 'System32\wscript.exe'
105
+ if ([IO.Path]::GetFullPath([string]$Action.Execute) -ine [IO.Path]::GetFullPath($wscript)) { return $Action }
106
+ $hostPath = Join-Path $Root 'bin\trillboards-hidden-run.vbs'
107
+ $prefix = '//B //NoLogo "' + $hostPath + '" --wait "'
108
+ $arguments = [string]$Action.Arguments
109
+ if (-not $arguments.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { throw 'Cannot verify the hidden service action; no runtime was changed' }
110
+ $tail = $arguments.Substring($prefix.Length)
111
+ $endQuote = $tail.IndexOf('"')
112
+ if ($endQuote -lt 1) { throw 'Cannot verify the hidden service action; no runtime was changed' }
113
+ $tool = $tail.Substring(0, $endQuote)
114
+ $serverArguments = $tail.Substring($endQuote + 1)
115
+ if (-not [IO.Path]::IsPathRooted($tool) -or [IO.Path]::GetFileName($tool) -ine $ToolName -or
116
+ -not $serverArguments.StartsWith(' serve ', [StringComparison]::OrdinalIgnoreCase)) { throw 'Cannot verify the hidden service action; no runtime was changed' }
117
+ return [pscustomobject]@{ Execute = $tool; Arguments = $serverArguments.Substring(1) }
118
+ }
119
+
120
+ function Get-LocalAiTaskContext([string]$Root, [switch]$AllowCustomToolPath) {
96
121
  $modelTaskErrors = @()
97
122
  $task = Get-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -ErrorAction SilentlyContinue -ErrorVariable modelTaskErrors
98
123
  if (-not $task) {
@@ -109,9 +134,21 @@ function Update-LocalAiRuntime([string]$Root) {
109
134
  }
110
135
  $currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
111
136
  $action = @($task.Actions)
137
+ if ($action.Count -eq 1) { $action = @(Resolve-BackgroundToolAction $action[0] $Root 'litert-lm.exe') }
112
138
  $ownTool = Join-Path $env:USERPROFILE '.local\bin\litert-lm.exe'
113
- if ($taskSid -ne $currentSid -or $action.Count -ne 1 -or
114
- [IO.Path]::GetFullPath([string]$action[0].Execute) -ine [IO.Path]::GetFullPath($ownTool)) {
139
+ $toolVerified = $false
140
+ if ($action.Count -eq 1) {
141
+ $tool = [string]$action[0].Execute
142
+ if ($AllowCustomToolPath) {
143
+ # Restart the recorded task without changing its executable or venv.
144
+ # Current-user ownership and the verified serve port still gate stops.
145
+ $toolVerified = [IO.Path]::IsPathRooted($tool) -and [IO.Path]::GetFileName($tool) -ieq 'litert-lm.exe'
146
+ } else {
147
+ # File refresh keeps its stricter managed-runtime location contract.
148
+ $toolVerified = [IO.Path]::GetFullPath($tool) -ieq [IO.Path]::GetFullPath($ownTool)
149
+ }
150
+ }
151
+ if ($taskSid -ne $currentSid -or -not $toolVerified) {
115
152
  throw 'Cannot verify ownership of the local AI task; no runtime was changed'
116
153
  }
117
154
  $serverArguments = [string]$action[0].Arguments
@@ -122,12 +159,7 @@ function Update-LocalAiRuntime([string]$Root) {
122
159
  }
123
160
  $setup = Join-Path $Root 'bin\setup-litertlm.ps1'
124
161
  if (-not (Test-Path -LiteralPath $setup -PathType Leaf)) { throw 'The released local AI setup is missing' }
125
- # Inspect first: an unchanged shim does NOT restart a healthy model server on
126
- # every SDK update. /v1/models and the CLI version cannot detect stale code.
127
- $state = (& $setup -RuntimeAction Inspect | Out-String).Trim() | ConvertFrom-Json
128
- if ($LASTEXITCODE -ne 0 -or $state.version -ne 1) { throw 'Could not inspect the installed local AI runtime' }
129
- if (-not $state.needsRefresh) { return }
130
- $script:modelRuntimeUpdate = [pscustomobject]@{
162
+ $context = [pscustomobject]@{
131
163
  Enabled = [bool]$task.Settings.Enabled
132
164
  Running = ($task.State -eq 'Running')
133
165
  OwnerSid = $currentSid
@@ -135,6 +167,48 @@ function Update-LocalAiRuntime([string]$Root) {
135
167
  Setup = $setup
136
168
  Backup = (Join-Path $previousDir 'litertlm-runtime')
137
169
  }
170
+ # A Ready task may still have a live native server. Preserve availability
171
+ # before stopping it, including OTA stop failures and runtime refresh.
172
+ $context.Running = $context.Running -or (@(Get-OwnedLocalAiProcesses -Context $context).Count -gt 0)
173
+ return $context
174
+ }
175
+
176
+ function Restart-LocalAiServe([string]$Root) {
177
+ $context = Get-LocalAiTaskContext $Root -AllowCustomToolPath
178
+ if ($null -eq $context) { throw 'The local AI task is missing; no server was restarted' }
179
+ if (-not $context.Enabled) { throw 'The local AI task is disabled; it was left disabled' }
180
+ $script:modelRuntimeUpdate = $context
181
+ try {
182
+ Stop-LocalAiForUpdate
183
+ # OTA also repairs an already-orphaned native listener whose task is Ready.
184
+ $script:modelRuntimeUpdate.Running = $true
185
+ Restore-LocalAiTaskState
186
+ } catch {
187
+ $restartError = $_
188
+ try {
189
+ Enable-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -ErrorAction Stop | Out-Null
190
+ $state = (Get-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -ErrorAction Stop).State
191
+ if ($context.Running -and $state -notin @('Running','Queued') -and @(Get-OwnedLocalAiProcesses).Count -eq 0) {
192
+ $listenerErrors = @()
193
+ $listeners = @(Get-NetTCPConnection -LocalPort $context.Port -State Listen -ErrorAction SilentlyContinue -ErrorVariable listenerErrors)
194
+ if (@($listenerErrors | Where-Object { $_.CategoryInfo.Category -ne 'ObjectNotFound' }).Count) { throw 'Cannot verify the model recovery port' }
195
+ if ($listeners.Count -eq 0) { Start-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -ErrorAction Stop }
196
+ }
197
+ } catch { Write-Warning ("Could not restore the model schedule after failed OTA restart: " + $_.Exception.Message) }
198
+ throw $restartError
199
+ } finally { $script:modelRuntimeUpdate = $null }
200
+ }
201
+
202
+ function Update-LocalAiRuntime([string]$Root) {
203
+ $context = Get-LocalAiTaskContext $Root
204
+ if ($null -eq $context) { return }
205
+ $setup = $context.Setup
206
+ # Inspect first: an unchanged shim does NOT restart a healthy model server on
207
+ # every SDK update. /v1/models and the CLI version cannot detect stale code.
208
+ $state = (& $setup -RuntimeAction Inspect | Out-String).Trim() | ConvertFrom-Json
209
+ if ($LASTEXITCODE -ne 0 -or $state.version -ne 1) { throw 'Could not inspect the installed local AI runtime' }
210
+ if (-not $state.needsRefresh) { return }
211
+ $script:modelRuntimeUpdate = $context
138
212
  Stop-LocalAiForUpdate
139
213
  # This mode is local file replacement only. It never downloads a CLI/model,
140
214
  # imports weights, resets tuning, re-registers tasks or runs image inference.
@@ -143,6 +217,30 @@ function Update-LocalAiRuntime([string]$Root) {
143
217
  Restore-LocalAiTaskState
144
218
  }
145
219
 
220
+ function Update-LocalAiTask([string]$Root) {
221
+ try {
222
+ $context = Get-LocalAiTaskContext $Root -AllowCustomToolPath
223
+ if ($null -eq $context -or -not $context.Enabled) { return }
224
+ $task = Get-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -ErrorAction Stop
225
+ $action = @($task.Actions)[0]
226
+ $wscript = Join-Path $env:WINDIR 'System32\wscript.exe'
227
+ if ([IO.Path]::GetFullPath([string]$action.Execute) -ieq [IO.Path]::GetFullPath($wscript)) {
228
+ $definition = Export-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -ErrorAction Stop
229
+ $headless = (($definition -match '<BootTrigger>') -or ($definition -match '<Repetition>')) -and
230
+ ($definition -notmatch '<LogonType>InteractiveToken</LogonType>')
231
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
232
+ $elevated = (New-Object Security.Principal.WindowsPrincipal($identity)).IsInRole(
233
+ [Security.Principal.WindowsBuiltInRole]::Administrator)
234
+ if ($headless -or -not $elevated) { return }
235
+ }
236
+ $native = Resolve-BackgroundToolAction $action $Root 'litert-lm.exe'
237
+ & (Join-Path $Root 'bin\register-litertlm-task.ps1') -LitertLmPath $native.Execute -Port ([string]$context.Port)
238
+ if ($LASTEXITCODE -ne 0) { throw 'The hidden local AI task could not be registered' }
239
+ } catch {
240
+ Write-Warning "Connector installed; the hidden local AI schedule needs repair: $($_.Exception.Message)"
241
+ }
242
+ }
243
+
146
244
  function Restore-LocalAiRuntime {
147
245
  if ($null -eq $script:modelRuntimeUpdate) { return }
148
246
  Stop-LocalAiForUpdate
@@ -180,11 +278,13 @@ function Update-DetectorTask([string]$Root) {
180
278
  try {
181
279
  $task = Get-ScheduledTask -TaskName "TrillboardsDetector" -ErrorAction SilentlyContinue
182
280
  if (-not $task) { return } # nothing registered yet; the cmd repair path owns that case
281
+ if ($task.Settings -and -not $task.Settings.Enabled) { return } # preserve an intentionally disabled detector
183
282
  # The interpreter path comes off the task we are replacing rather than being
184
283
  # re-derived - setup-detector.ps1 resolved it under the USER profile, and
185
284
  # re-deriving here could resolve somewhere else entirely. Same rule
186
285
  # register-task.ps1 states for its own repair.
187
- $exe = ($task.Actions | Select-Object -First 1).Execute
286
+ $resolvedAction = Resolve-BackgroundToolAction (@($task.Actions)[0]) $Root 'trillboards-detector.exe'
287
+ $exe = $resolvedAction.Execute
188
288
  if (-not $exe) { return }
189
289
  # Older updater array-splatting bound the text '-DetectorPath' positionally
190
290
  # as the executable, shifting the real path into --port. Recover ONLY this
@@ -281,6 +381,11 @@ function Restore-ConnectorSchedule {
281
381
  }
282
382
  }
283
383
 
384
+ if ($RestartLocalAi) {
385
+ Restart-LocalAiServe $InstallDir
386
+ exit 0
387
+ }
388
+
284
389
  try {
285
390
  Assert-ConnectorVersion $StagingDir
286
391
  & (Join-Path $StagingDir "bin\stop-existing.ps1") -InstallDir $InstallDir
@@ -354,3 +459,7 @@ try {
354
459
  try { Restore-ConnectorSchedule } catch {}
355
460
  throw "Trillboards Edge update failed and the previous version was restored: $($failure.Exception.Message)"
356
461
  }
462
+
463
+ # Migrate the independent model schedule only after the SDK transaction commits.
464
+ # A later connector rollback must not pair a new --wait action with an old host.
465
+ Update-LocalAiTask $InstallDir
@@ -87,7 +87,15 @@ FunctionEnd
87
87
  !insertmacro MUI_UNPAGE_INSTFILES
88
88
  !insertmacro MUI_LANGUAGE "English"
89
89
 
90
+ ; A PowerShell7 caller lends its Core module path to native Windows
91
+ ; PowerShell5.1 through this GUI process. Let native children construct their
92
+ ; own module path. This changes only this process and its future children.
93
+ !macro NativePowerShellModuleEnvironment
94
+ System::Call 'kernel32::SetEnvironmentVariableW(w "PSModulePath", p 0) i .r9'
95
+ !macroend
96
+
90
97
  Function .onInit
98
+ !insertmacro NativePowerShellModuleEnvironment
91
99
  ; -- Unattended parameters ------------------------------------------------
92
100
  ; /S NSIS silent install (no pages, no prompts)
93
101
  ; /ENROLLMENT_TOKEN=<tok> the FLEET enrollment credential from the portal
@@ -272,9 +280,19 @@ Section "Install"
272
280
  WriteRegDWORD HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\TrillboardsEdge" "NoRepair" 1
273
281
  SectionEnd
274
282
 
283
+ Function un.onInit
284
+ !insertmacro NativePowerShellModuleEnvironment
285
+ FunctionEnd
286
+
275
287
  Section "Uninstall"
276
288
  ; Stop + remove the background tasks (connector + litert-lm serve + detector).
277
- nsExec::ExecToLog 'powershell -NoProfile -ExecutionPolicy Bypass -File "$INSTDIR\bin\stop-existing.ps1" -InstallDir "$INSTDIR"'
289
+ nsExec::ExecToLog 'powershell -NoProfile -ExecutionPolicy Bypass -File "$INSTDIR\bin\stop-existing.ps1" -InstallDir "$INSTDIR" -IncludeLocalAi'
290
+ Pop $0
291
+ ${If} $0 != 0
292
+ MessageBox MB_OK|MB_ICONSTOP "The background services could not be stopped safely. Your installation has been kept. Retry uninstall after closing Sense Anything." /SD IDOK
293
+ SetErrorLevel 1
294
+ Abort
295
+ ${EndIf}
278
296
  nsExec::ExecToLog 'schtasks /End /TN "${TASK_NAME}"'
279
297
  nsExec::ExecToLog 'schtasks /Delete /F /TN "${TASK_NAME}"'
280
298
  nsExec::ExecToLog 'schtasks /End /TN "${LITERT_TASK_NAME}"'
@@ -95,7 +95,13 @@ if ($RamBudgetMb -match '^\d+$') {
95
95
  } elseif (-not [string]::IsNullOrWhiteSpace($RamBudgetMb)) {
96
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
97
  }
98
- $Action = New-ScheduledTaskAction -Execute $DetectorPath -Argument $argument
98
+ # The interactive fallback must remain windowless too. Wait in the GUI host
99
+ # so Task Scheduler observes the service lifetime and its actual exit code.
100
+ $hiddenHost = Join-Path $PSScriptRoot 'trillboards-hidden-run.vbs'
101
+ if (-not (Test-Path -LiteralPath $hiddenHost -PathType Leaf)) { throw 'The hidden service launcher is missing' }
102
+ $wscript = Join-Path $env:WINDIR 'System32\wscript.exe'
103
+ $hiddenArgument = '//B //NoLogo "' + $hiddenHost + '" --wait "' + $DetectorPath + '" ' + $argument
104
+ $Action = New-ScheduledTaskAction -Execute $wscript -Argument $hiddenArgument
99
105
 
100
106
  # NOT AT LOGON ONLY -- see register-task.ps1 for the full rationale, including
101
107
  # why the REPEATING trigger (not the boot trigger) is the load-bearing one: only
@@ -149,26 +155,13 @@ $Attempts = @(
149
155
  #
150
156
  # Done ONCE, before the ladder below, which may unregister and re-register
151
157
  # several times.
152
- Stop-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
153
-
154
- # Belt and braces: kill any detector process still listening on the port. Scoped
155
- # to THIS user's processes whose command line carries our port AND our tool
156
- # name, so a developer's unrelated python is never touched.
158
+ # Disable the schedule and stop the verified native child before replacing the
159
+ # action. A hidden waiting host alone is not the service's lifetime boundary.
160
+ $priorService = & (Join-Path $PSScriptRoot 'stop-local-ai.ps1') -Service Detector -ToolPath $DetectorPath -Port ([int]$Port) -Inspect
161
+ $priorXml = if ($priorService.TaskPresent) { Export-ScheduledTask -TaskName $TaskName -TaskPath '\' } else { $null }
162
+ & (Join-Path $PSScriptRoot 'stop-local-ai.ps1') -Service Detector -ToolPath $DetectorPath -Port ([int]$Port) | Out-Null
157
163
  try {
158
- Get-CimInstance Win32_Process -Filter "Name = 'trillboards-detector.exe' OR Name = 'python.exe' OR Name = 'pythonw.exe'" -ErrorAction SilentlyContinue |
159
- Where-Object { $_.CommandLine -and $_.CommandLine -match 'trillboards.detector' -and $_.CommandLine -match ('--port\s+' + [regex]::Escape($Port)) } |
160
- ForEach-Object {
161
- Write-Host "stopping previous detector service (pid $($_.ProcessId)) before re-registering"
162
- Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
163
- }
164
- } catch { }
165
-
166
- for ($i = 0; $i -lt 15; $i++) {
167
- $inUse = $null
168
- try { $inUse = Get-NetTCPConnection -LocalPort ([int]$Port) -State Listen -ErrorAction SilentlyContinue } catch { }
169
- if (-not $inUse) { break }
170
- Start-Sleep -Seconds 1
171
- }
164
+ if (@(Get-NetTCPConnection -LocalPort ([int]$Port) -State Listen -ErrorAction SilentlyContinue).Count) { throw 'The requested local AI port is still occupied' }
172
165
 
173
166
  $Landed = $null
174
167
  foreach ($attempt in $Attempts) {
@@ -183,14 +176,12 @@ foreach ($attempt in $Attempts) {
183
176
  }
184
177
  }
185
178
  if (-not $Landed) {
186
- Write-Error "Scheduled task '$TaskName' could not be registered in ANY supported shape."
187
- exit 1
179
+ throw "Scheduled task '$TaskName' could not be registered in ANY supported shape."
188
180
  }
189
181
 
190
182
  $registered = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
191
183
  if (-not $registered) {
192
- Write-Error "Scheduled task '$TaskName' did NOT register (Get-ScheduledTask found nothing)."
193
- exit 1
184
+ throw "Scheduled task '$TaskName' did NOT register (Get-ScheduledTask found nothing)."
194
185
  }
195
186
  $definition = Export-ScheduledTask -TaskName $TaskName
196
187
  $logonType = if ($definition -match "<LogonType>([^<]+)</LogonType>") { $Matches[1] } else { "unknown" }
@@ -203,3 +194,13 @@ if ($logonType -eq "InteractiveToken") {
203
194
 
204
195
  Start-ScheduledTask -TaskName $TaskName
205
196
  Write-Host "Registered scheduled task '$TaskName' (trillboards-detector serve on :$Port, shape '$($Landed.Label)', logon type $logonType, restarts on failure, log $LogFile)."
197
+
198
+ } catch {
199
+ $registrationFailure = $_
200
+ if ($priorXml) {
201
+ Register-ScheduledTask -TaskName $TaskName -TaskPath '\' -Xml $priorXml -Force -ErrorAction Stop | Out-Null
202
+ if (-not $priorService.Enabled) { Disable-ScheduledTask -TaskName $TaskName -TaskPath '\' -ErrorAction Stop | Out-Null }
203
+ elseif ($priorService.Running) { Start-ScheduledTask -TaskName $TaskName -TaskPath '\' -ErrorAction Stop }
204
+ }
205
+ throw $registrationFailure
206
+ }
@@ -40,16 +40,18 @@ $UserId = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
40
40
  # STILL unknown for exactly this reason -- the one process that knows why wrote
41
41
  # its explanation to a handle nobody was holding.
42
42
  #
43
- # DO NOT "fix" this by wrapping the action in cmd.exe /c "... >> log 2>&1". The
44
- # stop path below filters Win32_Process on Name = python.exe|litert-lm.exe|
45
- # pythonw.exe, so a cmd.exe parent is invisible to it and would be orphaned on
46
- # every re-register, and Task Scheduler's restart-on-failure would then be
47
- # watching the wrapper instead of the server. Capturing this needs either an
48
- # upstream --log-file or a purpose-built launcher that keeps the image name, and
49
- # it must be proved against the S4U/boot-trigger ladder (the 0.2.17 incident)
50
- # before it ships.
43
+ # The hidden wscript host waits for this exact executable and forwards its
44
+ # exit status. Re-registration and the updater also stop owned native server
45
+ # processes and verify the port is free, including a child left by a stopped
46
+ # host. A fire-and-forget action would discard Task Scheduler supervision.
51
47
  $argument = 'serve --host 127.0.0.1 --port ' + $Port
52
- $Action = New-ScheduledTaskAction -Execute $LitertLmPath -Argument $argument
48
+ # The interactive fallback must remain windowless too. Wait in the GUI host
49
+ # so Task Scheduler observes the service lifetime and its actual exit code.
50
+ $hiddenHost = Join-Path $PSScriptRoot 'trillboards-hidden-run.vbs'
51
+ if (-not (Test-Path -LiteralPath $hiddenHost -PathType Leaf)) { throw 'The hidden service launcher is missing' }
52
+ $wscript = Join-Path $env:WINDIR 'System32\wscript.exe'
53
+ $hiddenArgument = '//B //NoLogo "' + $hiddenHost + '" --wait "' + $LitertLmPath + '" ' + $argument
54
+ $Action = New-ScheduledTaskAction -Execute $wscript -Argument $hiddenArgument
53
55
 
54
56
  # NOT AT LOGON -- see register-task.ps1 for the full rationale, including why
55
57
  # the REPEATING trigger (not the boot trigger) is the load-bearing one: only an
@@ -104,28 +106,13 @@ $Attempts = @(
104
106
  # Done ONCE, before the degradation ladder below: the ladder may unregister and
105
107
  # re-register several times, and killing the serve on each attempt would only
106
108
  # lengthen the window with no model server.
107
- Stop-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
108
-
109
- # Belt and braces: kill any litert-lm process still listening on the port. Scoped
110
- # to THIS user's processes whose command line carries our port, so a developer's
111
- # unrelated python is never touched.
109
+ # Disable the schedule and stop the verified native child before replacing the
110
+ # action. A hidden waiting host alone is not the service's lifetime boundary.
111
+ $priorService = & (Join-Path $PSScriptRoot 'stop-local-ai.ps1') -Service Model -ToolPath $LitertLmPath -Port ([int]$Port) -Inspect
112
+ $priorXml = if ($priorService.TaskPresent) { Export-ScheduledTask -TaskName $TaskName -TaskPath '\' } else { $null }
113
+ & (Join-Path $PSScriptRoot 'stop-local-ai.ps1') -Service Model -ToolPath $LitertLmPath -Port ([int]$Port) | Out-Null
112
114
  try {
113
- Get-CimInstance Win32_Process -Filter "Name = 'python.exe' OR Name = 'litert-lm.exe' OR Name = 'pythonw.exe'" -ErrorAction SilentlyContinue |
114
- Where-Object { $_.CommandLine -and $_.CommandLine -match 'litert-lm' -and $_.CommandLine -match ('--port\s+' + [regex]::Escape($Port)) } |
115
- ForEach-Object {
116
- Write-Host "stopping previous litert-lm serve (pid $($_.ProcessId)) before re-registering"
117
- Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
118
- }
119
- } catch { }
120
-
121
- # Wait for the port to free, so the Start-ScheduledTask below does not race a
122
- # dying serve.
123
- for ($i = 0; $i -lt 15; $i++) {
124
- $inUse = $null
125
- try { $inUse = Get-NetTCPConnection -LocalPort ([int]$Port) -State Listen -ErrorAction SilentlyContinue } catch { }
126
- if (-not $inUse) { break }
127
- Start-Sleep -Seconds 1
128
- }
115
+ if (@(Get-NetTCPConnection -LocalPort ([int]$Port) -State Listen -ErrorAction SilentlyContinue).Count) { throw 'The requested local AI port is still occupied' }
129
116
 
130
117
  $Landed = $null
131
118
  foreach ($attempt in $Attempts) {
@@ -140,14 +127,12 @@ foreach ($attempt in $Attempts) {
140
127
  }
141
128
  }
142
129
  if (-not $Landed) {
143
- Write-Error "Scheduled task '$TaskName' could not be registered in ANY supported shape."
144
- exit 1
130
+ throw "Scheduled task '$TaskName' could not be registered in ANY supported shape."
145
131
  }
146
132
 
147
133
  $registered = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
148
134
  if (-not $registered) {
149
- Write-Error "Scheduled task '$TaskName' did NOT register (Get-ScheduledTask found nothing)."
150
- exit 1
135
+ throw "Scheduled task '$TaskName' did NOT register (Get-ScheduledTask found nothing)."
151
136
  }
152
137
  $definition = Export-ScheduledTask -TaskName $TaskName
153
138
  $logonType = if ($definition -match "<LogonType>([^<]+)</LogonType>") { $Matches[1] } else { "unknown" }
@@ -161,3 +146,13 @@ if ($logonType -eq "InteractiveToken") {
161
146
  # Start it now (don't wait for the next boot) so first-run sensing has a server.
162
147
  Start-ScheduledTask -TaskName $TaskName
163
148
  Write-Host "Registered scheduled task '$TaskName' (litert-lm serve on :$Port, shape '$($Landed.Label)', logon type $logonType, restarts on failure)."
149
+
150
+ } catch {
151
+ $registrationFailure = $_
152
+ if ($priorXml) {
153
+ Register-ScheduledTask -TaskName $TaskName -TaskPath '\' -Xml $priorXml -Force -ErrorAction Stop | Out-Null
154
+ if (-not $priorService.Enabled) { Disable-ScheduledTask -TaskName $TaskName -TaskPath '\' -ErrorAction Stop | Out-Null }
155
+ elseif ($priorService.Running) { Start-ScheduledTask -TaskName $TaskName -TaskPath '\' -ErrorAction Stop }
156
+ }
157
+ throw $registrationFailure
158
+ }
@@ -12,7 +12,9 @@ param(
12
12
  # the set any more: the connector is local-inference only, and ValidateSet
13
13
  # rejecting the value at registration is better than a task that registers
14
14
  # fine and then exits 1 on every start.
15
- [ValidateSet("auto-sense", "local-sense")][string]$Mode = "auto-sense"
15
+ [ValidateSet("auto-sense", "local-sense")][string]$Mode = "auto-sense",
16
+ # A reversible SDK swap must not upgrade independent AI task actions yet.
17
+ [switch]$SkipLocalAiRepair
16
18
  )
17
19
  $ErrorActionPreference = "Stop"
18
20
 
@@ -175,7 +177,28 @@ function Test-IsElevated {
175
177
  [System.Security.Principal.WindowsBuiltInRole]::Administrator)
176
178
  }
177
179
 
180
+ function Get-BackgroundToolPath($Task, [string]$ToolName) {
181
+ $action = @($Task.Actions)[0]
182
+ $wscript = Join-Path $env:WINDIR 'System32\wscript.exe'
183
+ if ([IO.Path]::GetFullPath([string]$action.Execute) -ine [IO.Path]::GetFullPath($wscript)) { return $action.Execute }
184
+ $hostPath = Join-Path $InstallDir 'bin\trillboards-hidden-run.vbs'
185
+ $prefix = '//B //NoLogo "' + $hostPath + '" --wait "'
186
+ $arguments = [string]$action.Arguments
187
+ if (-not $arguments.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { throw 'Cannot verify the hidden service action' }
188
+ $tail = $arguments.Substring($prefix.Length)
189
+ $endQuote = $tail.IndexOf('"')
190
+ if ($endQuote -lt 1) { throw 'Cannot verify the hidden service action' }
191
+ $tool = $tail.Substring(0, $endQuote)
192
+ if (-not [IO.Path]::IsPathRooted($tool) -or [IO.Path]::GetFileName($tool) -ine $ToolName -or
193
+ -not $tail.Substring($endQuote + 1).StartsWith(' serve ', [StringComparison]::OrdinalIgnoreCase)) { throw 'Cannot verify the hidden service action' }
194
+ # Preserve the recorded native path, including a custom uv tool location.
195
+ return $tool
196
+ }
197
+
178
198
  if (Test-IsElevated) {
199
+ # The updater repairs AI tasks after committing bin/lib. Otherwise rollback
200
+ # can restore an old host beneath a successfully upgraded --wait action.
201
+ if ($SkipLocalAiRepair) { return }
179
202
  $litertTask = Get-ScheduledTask -TaskName "TrillboardsLiteRtLm" -ErrorAction SilentlyContinue
180
203
  if ($litertTask) {
181
204
  $litertXml = Export-ScheduledTask -TaskName "TrillboardsLiteRtLm"
@@ -185,7 +208,7 @@ if (Test-IsElevated) {
185
208
  # Recover the interpreter path from the task we are replacing rather than
186
209
  # re-deriving it: setup-litertlm.ps1 resolved it under the USER profile,
187
210
  # and an elevated re-derivation could resolve somewhere else entirely.
188
- $litertExe = ($litertTask.Actions | Select-Object -First 1).Execute
211
+ $litertExe = Get-BackgroundToolPath $litertTask 'litert-lm.exe'
189
212
  $litertRegister = Join-Path $InstallDir "bin\register-litertlm-task.ps1"
190
213
  if ($litertExe -and (Test-Path $litertRegister)) {
191
214
  Write-Host "Repairing 'TrillboardsLiteRtLm' in the same elevated pass."
@@ -212,7 +235,7 @@ if (Test-IsElevated) {
212
235
  # Recover the interpreter path from the task we are replacing rather than
213
236
  # re-deriving it: setup-detector.ps1 resolved it under the USER profile,
214
237
  # and an elevated re-derivation could resolve somewhere else entirely.
215
- $detectorExe = ($detectorTask.Actions | Select-Object -First 1).Execute
238
+ $detectorExe = Get-BackgroundToolPath $detectorTask 'trillboards-detector.exe'
216
239
  $detectorRegister = Join-Path $InstallDir "bin\register-detector-task.ps1"
217
240
  if ($detectorExe -and (Test-Path $detectorRegister)) {
218
241
  Write-Host "Repairing 'TrillboardsDetector' in the same elevated pass."
@@ -131,44 +131,19 @@ if (-not $haveDetectorSetupMutex) {
131
131
  }
132
132
  $pausedDetectorTask = $null
133
133
  $pausedDetectorWasEnabled = $false
134
+ $pausedDetectorWasRunning = $false
134
135
  $detectorTaskReplaced = $false
135
136
 
136
137
  function Stop-OwnedDetectorForRepair {
138
+ $script:pausedDetectorHelper = Join-Path $Here 'stop-local-ai.ps1'
137
139
  $ownLauncher = [IO.Path]::GetFullPath((Join-Path $LocalBin 'trillboards-detector.exe'))
138
- $ownToolRoot = [IO.Path]::GetFullPath((Join-Path $env:APPDATA 'uv\tools\trillboards-detector')).TrimEnd('\') + '\'
139
- $task = Get-ScheduledTask -TaskName 'TrillboardsDetector' -ErrorAction SilentlyContinue
140
- if ($task) {
141
- $actions = @($task.Actions)
142
- if ($actions.Count -ne 1 -or [IO.Path]::GetFullPath($actions[0].Execute) -ine $ownLauncher) {
143
- throw 'The detector task is not owned by this user installation; refusing to stop or replace it'
144
- }
145
- $taskSid = (New-Object System.Security.Principal.NTAccount($task.Principal.UserId)).Translate([System.Security.Principal.SecurityIdentifier]).Value
146
- if ($taskSid -ne $detectorUserSid) { throw 'The detector task principal belongs to another user' }
147
- if (-not $script:pausedDetectorTask) {
148
- $script:pausedDetectorTask = $task
149
- $script:pausedDetectorWasEnabled = [bool]$task.Settings.Enabled
150
- }
151
- Disable-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop | Out-Null
152
- Stop-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop
153
- }
154
- # Task Scheduler may leave a child after stopping its launcher. Scope by this
155
- # user's exact tool paths AND SID, never by all Python processes or a port.
156
- foreach ($process in @(Get-CimInstance Win32_Process -ErrorAction Stop)) {
157
- $exe = $process.ExecutablePath
158
- if (-not $exe -or ($exe -ine $ownLauncher -and -not $exe.StartsWith($ownToolRoot, [StringComparison]::OrdinalIgnoreCase))) { continue }
159
- try { $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -ErrorAction Stop } catch {
160
- # Stopping the launcher can also finish a child from this CIM snapshot.
161
- # Only an independently confirmed absent PID is already stopped; a live
162
- # process with an unverifiable owner remains a visible repair failure.
163
- if (-not (Get-CimInstance Win32_Process -Filter ("ProcessId=" + $process.ProcessId) -ErrorAction Stop)) { continue }
164
- throw
165
- }
166
- if ($owner.ReturnValue -ne 0 -or $owner.Sid -ne $detectorUserSid) { throw 'Cannot verify detector process ownership' }
167
- Log "stopping this user's detector process before venv repair (pid $($process.ProcessId))"
168
- Stop-Process -Id $process.ProcessId -Force -ErrorAction SilentlyContinue
169
- $remaining = Get-Process -Id $process.ProcessId -ErrorAction SilentlyContinue
170
- if ($remaining -and -not $remaining.WaitForExit(10000)) { throw 'Owned detector process did not stop before venv repair' }
140
+ $prior = & $script:pausedDetectorHelper -Service Detector -ToolPath $ownLauncher -Port ([int]$Port) -Inspect
141
+ if ($prior.TaskPresent -and -not $script:pausedDetectorTask) {
142
+ $script:pausedDetectorTask = [pscustomobject]@{ TaskName = $prior.TaskName; TaskPath = '\' }
143
+ $script:pausedDetectorWasEnabled = $prior.Enabled
144
+ $script:pausedDetectorWasRunning = $prior.Running
171
145
  }
146
+ & $script:pausedDetectorHelper -Service Detector -ToolPath $ownLauncher -Port ([int]$Port) | Out-Null
172
147
  }
173
148
 
174
149
  try {
@@ -430,7 +405,18 @@ Log "done"
430
405
  exit 0
431
406
  } finally {
432
407
  if ($pausedDetectorTask -and -not $detectorTaskReplaced -and $pausedDetectorWasEnabled) {
433
- Enable-ScheduledTask -TaskName $pausedDetectorTask.TaskName -TaskPath $pausedDetectorTask.TaskPath -ErrorAction SilentlyContinue | Out-Null
408
+ try {
409
+ # A failed uv install/version check/child registration must also restore
410
+ # availability for a logon-only task. Do not duplicate surviving children.
411
+ $currentTask = & $pausedDetectorHelper -Service Detector -ToolPath (Join-Path $LocalBin 'trillboards-detector.exe') -Port ([int]$Port) -InspectTaskOnly
412
+ if (-not $currentTask.TaskPresent) { throw 'The previous detector task is missing after failed repair' }
413
+ Enable-ScheduledTask -TaskName $pausedDetectorTask.TaskName -TaskPath $pausedDetectorTask.TaskPath -ErrorAction Stop | Out-Null
414
+ $current = & $pausedDetectorHelper -Service Detector -ToolPath (Join-Path $LocalBin 'trillboards-detector.exe') -Port ([int]$Port) -Inspect
415
+ if ($pausedDetectorWasRunning -and $current.TaskState -notin @('Running','Queued') -and
416
+ $current.OwnedProcessCount -eq 0 -and $current.ListenerCount -eq 0) {
417
+ Start-ScheduledTask -TaskName $pausedDetectorTask.TaskName -TaskPath $pausedDetectorTask.TaskPath -ErrorAction Stop
418
+ }
419
+ } catch { Log ('WARN: could not restore the detector after failed repair: ' + $_.Exception.Message) }
434
420
  }
435
421
  if ($haveDetectorSetupMutex) { $detectorSetupMutex.ReleaseMutex() }
436
422
  $detectorSetupMutex.Dispose()