@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.
- package/deploy/windows/README.md +17 -0
- package/deploy/windows/build-windows.ps1 +1 -0
- package/deploy/windows/ci/test-local-ai-diagnostic.ps1 +213 -0
- package/deploy/windows/ci/test-published-install.ps1 +243 -0
- package/deploy/windows/install-update.ps1 +124 -15
- package/deploy/windows/installer.nsi +19 -1
- package/deploy/windows/register-detector-task.ps1 +25 -24
- package/deploy/windows/register-litertlm-task.ps1 +29 -34
- package/deploy/windows/register-task.ps1 +26 -3
- package/deploy/windows/setup-detector.ps1 +20 -34
- package/deploy/windows/setup-litertlm.ps1 +170 -30
- package/deploy/windows/stop-existing.ps1 +62 -3
- package/deploy/windows/stop-local-ai.ps1 +256 -0
- package/deploy/windows/trillboards-hidden-run.vbs +17 -2
- package/dist/EdgeAgent.js +1 -1
- package/dist/LiteRtVlmProvider.d.ts +6 -3
- package/dist/LiteRtVlmProvider.d.ts.map +1 -1
- package/dist/LiteRtVlmProvider.js +12 -5
- package/dist/LiteRtVlmProvider.js.map +1 -1
- package/dist/diagnose.d.ts +1 -1
- package/dist/diagnose.js +1 -1
- package/dist/gemmaModelOta.d.ts +3 -1
- package/dist/gemmaModelOta.d.ts.map +1 -1
- package/dist/gemmaModelOta.js +18 -8
- package/dist/gemmaModelOta.js.map +1 -1
- package/package.json +1 -1
|
@@ -169,6 +169,53 @@ $script:LitertlmProbeJpegB64 = "/9j/4AAQSkZJRgABAgAAAQABAAD//gAPTGF2YzYzLjEuMTAx
|
|
|
169
169
|
|
|
170
170
|
function Get-LitertlmConfigPath { Join-Path $LitertDir "config.json" }
|
|
171
171
|
|
|
172
|
+
$script:LitertlmVerifiedInferenceModel = ''
|
|
173
|
+
|
|
174
|
+
# The pinned CLI resolves a bare model id through config.models[id].backend.
|
|
175
|
+
# Reuse that selection on a retry instead of rebuilding a failed GPU engine
|
|
176
|
+
# after the preceding setup has already proved its CPU fallback.
|
|
177
|
+
function Get-LitertlmPreferredInferenceModel {
|
|
178
|
+
try {
|
|
179
|
+
$path = Get-LitertlmConfigPath
|
|
180
|
+
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { return '' }
|
|
181
|
+
$config = Get-Content -LiteralPath $path -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
|
|
182
|
+
$models = $config.PSObject.Properties['models']
|
|
183
|
+
if ($null -eq $models) { return '' }
|
|
184
|
+
$model = $models.Value.PSObject.Properties[$ModelId]
|
|
185
|
+
if ($null -eq $model) { return '' }
|
|
186
|
+
$backend = $model.Value.PSObject.Properties['backend']
|
|
187
|
+
if ($null -ne $backend -and [string]$backend.Value -in @('cpu','gpu','npu')) { return $ModelId }
|
|
188
|
+
} catch { }
|
|
189
|
+
return ''
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function Set-LitertlmVerifiedBackend([string]$InferenceModel) {
|
|
193
|
+
$ErrorActionPreference = 'Stop'
|
|
194
|
+
if ($InferenceModel -notin @($ModelId, "$ModelId,cpu", "$ModelId,gpu", "$ModelId,npu")) {
|
|
195
|
+
throw 'Cannot retain an unverified inference model'
|
|
196
|
+
}
|
|
197
|
+
$path = Get-LitertlmConfigPath
|
|
198
|
+
$config = Get-Content -LiteralPath $path -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
|
|
199
|
+
$models = $config.PSObject.Properties['models']
|
|
200
|
+
if ($null -eq $models) { throw 'The verified model configuration is missing' }
|
|
201
|
+
$model = $models.Value.PSObject.Properties[$ModelId]
|
|
202
|
+
if ($null -eq $model) { throw 'The verified model configuration is missing' }
|
|
203
|
+
$previous = $model.Value.PSObject.Properties['backend']
|
|
204
|
+
$backend = if ($InferenceModel -eq $ModelId) {
|
|
205
|
+
if ($null -ne $previous -and [string]$previous.Value -in @('cpu','gpu','npu')) { ([string]$previous.Value).ToLowerInvariant() } else { 'cpu' }
|
|
206
|
+
} else { $InferenceModel.Substring($ModelId.Length + 1) }
|
|
207
|
+
if ($null -ne $previous -and [string]$previous.Value -ceq $backend) { return }
|
|
208
|
+
$model.Value | Add-Member -NotePropertyName backend -NotePropertyValue $backend -Force
|
|
209
|
+
$temporary = "$path.$PID.backend.tmp"
|
|
210
|
+
try {
|
|
211
|
+
[IO.File]::WriteAllText($temporary, ($config | ConvertTo-Json -Depth 12), [Text.UTF8Encoding]::new($false))
|
|
212
|
+
Move-Item -LiteralPath $temporary -Destination $path -Force -ErrorAction Stop
|
|
213
|
+
} finally {
|
|
214
|
+
if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force -ErrorAction SilentlyContinue }
|
|
215
|
+
}
|
|
216
|
+
Log "retained verified inference backend '$backend' in $path"
|
|
217
|
+
}
|
|
218
|
+
|
|
172
219
|
# $VisionBackend = "gpu" pins the vision encoder; "" leaves it on the CPU
|
|
173
220
|
# default. $SpeculativeDecoding is the second engine setting this file writes.
|
|
174
221
|
#
|
|
@@ -232,6 +279,7 @@ function Write-LitertlmConfig {
|
|
|
232
279
|
# GPU encoder from one that fails on first use.
|
|
233
280
|
function Test-LitertlmVision {
|
|
234
281
|
param([string]$InferenceModel = "$ModelId,gpu")
|
|
282
|
+
$script:LitertlmVerifiedInferenceModel = ''
|
|
235
283
|
try {
|
|
236
284
|
$dataUri = "data:image/jpeg;base64," + $script:LitertlmProbeJpegB64
|
|
237
285
|
$body = @{
|
|
@@ -251,8 +299,10 @@ function Test-LitertlmVision {
|
|
|
251
299
|
$proof = ($resp.Content | ConvertFrom-Json).runtimeModel
|
|
252
300
|
$runtimeMatches = $proof.runtimeModelId -eq $InferenceModel `
|
|
253
301
|
-or ($InferenceModel -eq $ModelId -and $proof.runtimeModelId -eq "$ModelId,cpu")
|
|
254
|
-
|
|
302
|
+
$verified = ($null -ne $proof -and $proof.version -eq 1 -and $proof.format -eq "litert-lm" `
|
|
255
303
|
-and $proof.sha256 -eq $BundledModelSha256 -and $runtimeMatches)
|
|
304
|
+
if ($verified) { $script:LitertlmVerifiedInferenceModel = $InferenceModel }
|
|
305
|
+
return $verified
|
|
256
306
|
} catch {
|
|
257
307
|
Log "vision probe for '$InferenceModel' did not answer: $_"
|
|
258
308
|
return $false
|
|
@@ -291,6 +341,10 @@ function Write-DelegateDiagnostic {
|
|
|
291
341
|
}
|
|
292
342
|
|
|
293
343
|
function Complete-Setup {
|
|
344
|
+
try { Set-LitertlmVerifiedBackend $script:LitertlmVerifiedInferenceModel } catch {
|
|
345
|
+
Fail-LocalAi "Local AI responded, but its verified runtime configuration could not be saved. Retry setup."
|
|
346
|
+
throw
|
|
347
|
+
}
|
|
294
348
|
Log "local AI is healthy on :$Port"
|
|
295
349
|
Write-DelegateDiagnostic
|
|
296
350
|
Write-SetupProgress -Stage "ready" -Title "Camera setup is complete" -Message "Local AI is installed and healthy. Trillboards is running in the background." -Phase "verifying" -Percent 100
|
|
@@ -311,11 +365,14 @@ function Test-LitertLmModel([string]$ExecutablePath) {
|
|
|
311
365
|
catch { return $false }
|
|
312
366
|
}
|
|
313
367
|
|
|
368
|
+
$script:ModelImportPreviousState = $null
|
|
314
369
|
function Import-VerifiedModel([string]$SourcePath, [string]$ExecutablePath) {
|
|
370
|
+
$script:ModelImportPreviousState = $null
|
|
315
371
|
if ((Get-FileHash -LiteralPath $SourcePath -Algorithm SHA256).Hash.ToLowerInvariant() -ne $BundledModelSha256) {
|
|
316
372
|
Log "refusing to import an unverified local AI artifact"
|
|
317
373
|
return $false
|
|
318
374
|
}
|
|
375
|
+
$stoppedModel = $null
|
|
319
376
|
$modelFile = Join-Path $StoreDir "model.litertlm"
|
|
320
377
|
if (Test-Path -LiteralPath $modelFile -PathType Leaf) {
|
|
321
378
|
$previousSha = (Get-FileHash -LiteralPath $modelFile -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
@@ -330,15 +387,74 @@ function Import-VerifiedModel([string]$SourcePath, [string]$ExecutablePath) {
|
|
|
330
387
|
Log "previous model rollback copy could not be verified"
|
|
331
388
|
return $false
|
|
332
389
|
}
|
|
333
|
-
|
|
390
|
+
# The task may be a hidden waiting host, or have been deleted while its
|
|
391
|
+
# native child survives. Prove owner/process/port shutdown before import.
|
|
392
|
+
$stoppedModel = & (Join-Path $Here 'stop-local-ai.ps1') -Service Model -ToolPath $ExecutablePath -Port ([int]$Port)
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
$importVerified = $false
|
|
396
|
+
try {
|
|
397
|
+
& $ExecutablePath import $SourcePath $ModelId *>> $LogPath
|
|
398
|
+
$importVerified = (($LASTEXITCODE -eq 0) -and (Test-LitertLmModel $ExecutablePath))
|
|
399
|
+
if ($importVerified -and $stoppedModel) { $script:ModelImportPreviousState = $stoppedModel }
|
|
400
|
+
return $importVerified
|
|
401
|
+
} finally {
|
|
402
|
+
if ($stoppedModel -and -not $importVerified) {
|
|
403
|
+
# Import can fail after truncating/replacing the destination. Restore and
|
|
404
|
+
# verify the previous bytes before allowing its service to run again.
|
|
405
|
+
if (-not (Test-Path -LiteralPath $modelFile -PathType Leaf) -or
|
|
406
|
+
(Get-FileHash -LiteralPath $modelFile -Algorithm SHA256).Hash.ToLowerInvariant() -ne $previousSha) {
|
|
407
|
+
Copy-Item -LiteralPath $backupPath -Destination $modelFile -Force -ErrorAction Stop
|
|
408
|
+
}
|
|
409
|
+
if ((Get-FileHash -LiteralPath $modelFile -Algorithm SHA256).Hash.ToLowerInvariant() -ne $previousSha) {
|
|
410
|
+
throw 'The previous local AI model could not be restored; its service remains stopped'
|
|
411
|
+
}
|
|
334
412
|
}
|
|
413
|
+
if ($stoppedModel -and $stoppedModel.TaskPresent -and $stoppedModel.Enabled) {
|
|
414
|
+
Enable-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -TaskPath '\' -ErrorAction Stop | Out-Null
|
|
415
|
+
# Logon-only fallback tasks have no repeat trigger to recover for us.
|
|
416
|
+
# Successful import is started by registration below; failed import must
|
|
417
|
+
# immediately restore a service that was running before this attempt.
|
|
418
|
+
if (-not $importVerified -and $stoppedModel.Running) {
|
|
419
|
+
Start-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -TaskPath '\' -ErrorAction Stop
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function Restore-ImportedModelService {
|
|
426
|
+
$prior = $script:ModelImportPreviousState
|
|
427
|
+
if (-not $prior -or -not $prior.TaskPresent -or -not $prior.Enabled) { return }
|
|
428
|
+
# The child registrar sees Ready after a successful import. The parent owns
|
|
429
|
+
# the pre-import state until registration commits, including its failure path.
|
|
430
|
+
$current = & (Join-Path $Here 'stop-local-ai.ps1') -Service Model -Inspect
|
|
431
|
+
if (-not $current.TaskPresent -or $current.Port -ne $prior.Port) { throw 'The model task changed before registration recovery' }
|
|
432
|
+
Enable-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -TaskPath '\' -ErrorAction Stop | Out-Null
|
|
433
|
+
if ($prior.Running -and $current.TaskState -notin @('Running','Queued') -and
|
|
434
|
+
$current.OwnedProcessCount -eq 0 -and $current.ListenerCount -eq 0) {
|
|
435
|
+
Start-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -TaskPath '\' -ErrorAction Stop
|
|
335
436
|
}
|
|
336
|
-
& $ExecutablePath import $SourcePath $ModelId *>> $LogPath
|
|
337
|
-
return (($LASTEXITCODE -eq 0) -and (Test-LitertLmModel $ExecutablePath))
|
|
338
437
|
}
|
|
339
438
|
|
|
340
439
|
# One owner for the shim on fresh installs AND upgrades. None of these helpers
|
|
341
440
|
# import a model, rewrite model config, install dependencies or register tasks.
|
|
441
|
+
# Windows PowerShell 5.1 turns redirected native stderr into ErrorRecords.
|
|
442
|
+
# The adapter prints ACTIVE there on a successful import. Only the native exit
|
|
443
|
+
# status decides success; keep this preference local to this invocation so the
|
|
444
|
+
# caller's filesystem/backup verification remains terminating.
|
|
445
|
+
function Invoke-LitertlmShimNative {
|
|
446
|
+
param([string]$Executable, [string[]]$Arguments, [switch]$LogOutput)
|
|
447
|
+
$ErrorActionPreference = 'Continue'
|
|
448
|
+
# Native execution updates the automatic global status, even in a function.
|
|
449
|
+
$global:LASTEXITCODE = $null
|
|
450
|
+
if ($LogOutput) {
|
|
451
|
+
& $Executable @Arguments *>> $LogPath
|
|
452
|
+
return [pscustomobject]@{ ExitCode = $global:LASTEXITCODE; Output = @() }
|
|
453
|
+
}
|
|
454
|
+
$output = @(& $Executable @Arguments 2>$null)
|
|
455
|
+
return [pscustomobject]@{ ExitCode = $global:LASTEXITCODE; Output = $output }
|
|
456
|
+
}
|
|
457
|
+
|
|
342
458
|
function Get-LitertlmShimPaths([string]$UvPath) {
|
|
343
459
|
$shim = $null
|
|
344
460
|
foreach ($candidate in @(
|
|
@@ -348,17 +464,15 @@ function Get-LitertlmShimPaths([string]$UvPath) {
|
|
|
348
464
|
if (-not $shim) { throw 'The released litert-lm shim is missing' }
|
|
349
465
|
# PS 5.1 stops a native process when Select-Object -First has its line,
|
|
350
466
|
# turning a successful lookup into exit -1. Drain stdout before selecting.
|
|
351
|
-
$
|
|
352
|
-
$
|
|
353
|
-
$
|
|
354
|
-
if ($toolDirExit -ne 0 -or [string]::IsNullOrWhiteSpace($toolDir)) { throw 'Cannot resolve uv tool dir' }
|
|
467
|
+
$toolDirResult = Invoke-LitertlmShimNative -Executable $UvPath -Arguments @('tool', 'dir')
|
|
468
|
+
$toolDir = $toolDirResult.Output | Select-Object -First 1
|
|
469
|
+
if ($toolDirResult.ExitCode -ne 0 -or [string]::IsNullOrWhiteSpace($toolDir)) { throw 'Cannot resolve uv tool dir' }
|
|
355
470
|
$venv = [IO.Path]::GetFullPath((Join-Path $toolDir.Trim() 'litert-lm'))
|
|
356
471
|
$py = Join-Path $venv 'Scripts\python.exe'
|
|
357
472
|
if (-not (Test-Path -LiteralPath $py -PathType Leaf)) { throw 'The installed litert-lm Python is missing' }
|
|
358
|
-
$
|
|
359
|
-
$
|
|
360
|
-
$
|
|
361
|
-
if ($siteExit -ne 0 -or [string]::IsNullOrWhiteSpace($site)) { throw 'Cannot resolve litert-lm site-packages' }
|
|
473
|
+
$siteResult = Invoke-LitertlmShimNative -Executable $py -Arguments @('-c', "import sysconfig;print(sysconfig.get_paths()['purelib'])")
|
|
474
|
+
$site = $siteResult.Output | Select-Object -First 1
|
|
475
|
+
if ($siteResult.ExitCode -ne 0 -or [string]::IsNullOrWhiteSpace($site)) { throw 'Cannot resolve litert-lm site-packages' }
|
|
362
476
|
$site = [IO.Path]::GetFullPath($site.Trim())
|
|
363
477
|
if (-not $site.StartsWith(($venv.TrimEnd('\') + '\'), [StringComparison]::OrdinalIgnoreCase) -or
|
|
364
478
|
-not (Test-Path -LiteralPath $site -PathType Container)) { throw 'The runtime site is outside its managed venv' }
|
|
@@ -455,8 +569,8 @@ function Install-LitertlmShim {
|
|
|
455
569
|
}
|
|
456
570
|
# A fresh interpreter proves the installed wrapper imports. No engine,
|
|
457
571
|
# weights, image inference, model config or camera credentials are loaded.
|
|
458
|
-
|
|
459
|
-
if ($
|
|
572
|
+
$importResult = Invoke-LitertlmShimNative -Executable $paths.Python -Arguments @('-c', "import litert_lm,sys; sys.exit(0 if getattr(litert_lm.Engine.create_conversation,'_trillboards_litertlm_shim',False) else 1)") -LogOutput
|
|
573
|
+
if ($importResult.ExitCode -ne 0) { throw 'The refreshed model-service shim did not import' }
|
|
460
574
|
Log "litert-lm fast-conversation shim active in $($paths.Site)"
|
|
461
575
|
return $true
|
|
462
576
|
} catch {
|
|
@@ -499,11 +613,10 @@ if (-not $haveSetupMutex) {
|
|
|
499
613
|
exit 0
|
|
500
614
|
}
|
|
501
615
|
for ($attempt = 0; $attempt -lt 600 -and -not $haveSetupMutex; $attempt++) {
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
}
|
|
616
|
+
# The owner may be switching/restarting inference backends. A waiter
|
|
617
|
+
# must not initialize a GPU engine or claim readiness during that work.
|
|
618
|
+
# Acquire ownership first; the existing version/task/image checks below
|
|
619
|
+
# then verify the completed configuration before taking their fast path.
|
|
507
620
|
if ((Get-PartialModelBytes) -gt 0) {
|
|
508
621
|
Write-DownloadProgress
|
|
509
622
|
} else {
|
|
@@ -589,19 +702,45 @@ function Get-LitertLmVersion {
|
|
|
589
702
|
# operation that just failed.
|
|
590
703
|
$installedLitertLmVersion = Get-LitertLmVersion
|
|
591
704
|
$serveHealthy = Test-ServeHealthy
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
705
|
+
# A reinstall also migrates legacy console actions. Only the already-hidden
|
|
706
|
+
# task may take the healthy fast path; the normal verified setup below owns
|
|
707
|
+
# registration and proves the replacement service before reporting ready.
|
|
708
|
+
$serveTaskHidden = $false
|
|
709
|
+
try {
|
|
710
|
+
$serviceTask = Get-ScheduledTask -TaskName 'TrillboardsLiteRtLm' -ErrorAction Stop
|
|
711
|
+
$serviceActions = @($serviceTask.Actions)
|
|
712
|
+
$serviceUser = [string]$serviceTask.Principal.UserId
|
|
713
|
+
$serviceSid = if ($serviceUser -match '^S-1-') { $serviceUser } else {
|
|
714
|
+
(New-Object Security.Principal.NTAccount($serviceUser)).Translate([Security.Principal.SecurityIdentifier]).Value
|
|
597
715
|
}
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
716
|
+
$hiddenPrefix = '//B //NoLogo "' + (Join-Path $Here 'trillboards-hidden-run.vbs') + '" --wait "' + $litertlmPath + '" serve --host 127.0.0.1 --port ' + $Port
|
|
717
|
+
$serveTaskHidden = $serviceTask.Settings.Enabled -and $serviceTask.State -eq 'Running' -and
|
|
718
|
+
$serviceSid -eq [Security.Principal.WindowsIdentity]::GetCurrent().User.Value -and $serviceActions.Count -eq 1 -and
|
|
719
|
+
[IO.Path]::GetFullPath($serviceActions[0].Execute) -ieq [IO.Path]::GetFullPath((Join-Path $env:WINDIR 'System32\wscript.exe')) -and
|
|
720
|
+
([string]$serviceActions[0].Arguments).Equals($hiddenPrefix, [StringComparison]::OrdinalIgnoreCase)
|
|
721
|
+
} catch { }
|
|
722
|
+
if ($serveHealthy -and ($installedLitertLmVersion -eq $LitertLmVersion) -and $serveTaskHidden) {
|
|
723
|
+
$preferredInferenceModel = Get-LitertlmPreferredInferenceModel
|
|
724
|
+
if ($preferredInferenceModel) {
|
|
725
|
+
if (Test-LitertlmVision -InferenceModel $preferredInferenceModel) {
|
|
726
|
+
Complete-Setup
|
|
727
|
+
Stop-SetupLock
|
|
728
|
+
exit 0
|
|
729
|
+
}
|
|
730
|
+
} else {
|
|
731
|
+
if (Test-LitertlmVision -InferenceModel "$ModelId,gpu") {
|
|
732
|
+
Complete-Setup
|
|
733
|
+
Stop-SetupLock
|
|
734
|
+
exit 0
|
|
735
|
+
}
|
|
736
|
+
if (Test-LitertlmVision -InferenceModel $ModelId) {
|
|
737
|
+
Log "local AI healthy on the previously configured full CPU fallback (slower, but serving)"
|
|
738
|
+
Complete-Setup
|
|
739
|
+
Stop-SetupLock
|
|
740
|
+
exit 0
|
|
741
|
+
}
|
|
603
742
|
}
|
|
604
|
-
Log "WARN: the pinned serve answers /v1/models but not a
|
|
743
|
+
Log "WARN: the pinned serve answers /v1/models but not a verified image inference on its selected backend; reprovisioning local AI"
|
|
605
744
|
}
|
|
606
745
|
if ($serveHealthy -and ($installedLitertLmVersion -ne $LitertLmVersion)) {
|
|
607
746
|
Log "serve is healthy but litert-lm is $(if ($installedLitertLmVersion) { $installedLitertLmVersion } else { 'unknown' }) not pinned $LitertLmVersion; reinstalling and restarting the serve"
|
|
@@ -861,6 +1000,7 @@ Write-LitertlmConfig -VisionBackend "gpu" -SpeculativeDecoding $true | Out-Null
|
|
|
861
1000
|
Log "registering litert-lm serve Scheduled Task on :$Port"
|
|
862
1001
|
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $registration -LitertLmPath $litertlmPath -Port $Port *>> $LogPath
|
|
863
1002
|
if ($LASTEXITCODE -ne 0) {
|
|
1003
|
+
try { Restore-ImportedModelService } catch { Log "WARN: the prior local AI service could not be restored: $_" }
|
|
864
1004
|
Fail-LocalAi "The local AI service could not be started. Restart Windows, then retry Local AI."
|
|
865
1005
|
Stop-SetupLock
|
|
866
1006
|
exit 1
|
|
@@ -5,13 +5,33 @@
|
|
|
5
5
|
#>
|
|
6
6
|
[CmdletBinding()]
|
|
7
7
|
param(
|
|
8
|
-
[Parameter(Mandatory = $true)][string]$InstallDir
|
|
8
|
+
[Parameter(Mandatory = $true)][string]$InstallDir,
|
|
9
|
+
[switch]$IncludeLocalAi
|
|
9
10
|
)
|
|
10
11
|
|
|
11
12
|
$ErrorActionPreference = "Stop"
|
|
12
13
|
$root = [IO.Path]::GetFullPath($InstallDir).TrimEnd('\')
|
|
13
14
|
$rootPrefix = $root + '\'
|
|
14
15
|
|
|
16
|
+
$stoppedLocalAi = @()
|
|
17
|
+
$priorConnector = $null
|
|
18
|
+
try {
|
|
19
|
+
if ($IncludeLocalAi) {
|
|
20
|
+
$connectorErrors = @()
|
|
21
|
+
$connector = Get-ScheduledTask -TaskName 'TrillboardsEdge' -TaskPath '\' -ErrorAction SilentlyContinue -ErrorVariable connectorErrors
|
|
22
|
+
if (@($connectorErrors | Where-Object { $_.CategoryInfo.Category -ne 'ObjectNotFound' }).Count) { throw 'Cannot inspect the connector schedule before uninstall' }
|
|
23
|
+
if ($connector) { $priorConnector = [pscustomobject]@{ Enabled=[bool]$connector.Settings.Enabled; Running=($connector.State -eq 'Running') } }
|
|
24
|
+
}
|
|
25
|
+
if ($IncludeLocalAi) {
|
|
26
|
+
$stopLocalAi = Join-Path $PSScriptRoot 'stop-local-ai.ps1'
|
|
27
|
+
# Verify both tasks before changing either. An uninstall must not remove its
|
|
28
|
+
# files while a foreign/ambiguous service is still running under them.
|
|
29
|
+
foreach ($service in @('Model','Detector')) { & $stopLocalAi -Service $service -Inspect | Out-Null }
|
|
30
|
+
foreach ($service in @('Model','Detector')) {
|
|
31
|
+
$stoppedLocalAi += [pscustomobject]@{ Service=$service; State=(& $stopLocalAi -Service $service) }
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
15
35
|
# DISABLE BEFORE STOP. register-task.ps1 registers the task with
|
|
16
36
|
# `-RestartCount 99 -RestartInterval 1 minute`, so Stop-ScheduledTask ends the
|
|
17
37
|
# instance as a FAILURE and Task Scheduler relaunches node.exe about a minute
|
|
@@ -24,6 +44,8 @@ Stop-ScheduledTask -TaskName "TrillboardsEdge" -ErrorAction SilentlyContinue
|
|
|
24
44
|
Start-Sleep -Milliseconds 750
|
|
25
45
|
|
|
26
46
|
function Get-TrillboardsEdgeProcesses {
|
|
47
|
+
param([switch]$VerifyRecovery)
|
|
48
|
+
$queryErrorAction = if ($VerifyRecovery) { 'Stop' } else { 'SilentlyContinue' }
|
|
27
49
|
# The process that actually holds bin\node.exe open is node.exe itself, and
|
|
28
50
|
# its command line names NONE of these scripts - it names the cli.js entry.
|
|
29
51
|
# Win32_Process.ExecutablePath is empty across a 32/64-bit boundary, and then
|
|
@@ -41,9 +63,17 @@ function Get-TrillboardsEdgeProcesses {
|
|
|
41
63
|
'ffmpeg.exe'
|
|
42
64
|
)
|
|
43
65
|
|
|
44
|
-
@(Get-CimInstance Win32_Process -ErrorAction
|
|
66
|
+
@(Get-CimInstance Win32_Process -ErrorAction $queryErrorAction | Where-Object {
|
|
45
67
|
if ($_.ProcessId -eq $PID) { return $false }
|
|
46
68
|
$exe = if ($_.ExecutablePath) { [IO.Path]::GetFullPath($_.ExecutablePath) } else { '' }
|
|
69
|
+
$commandLine = [string]$_.CommandLine
|
|
70
|
+
# Waiting AI hosts belong to their own scheduled tasks and hold neither
|
|
71
|
+
# connector binary open. The runtime refresh/repair paths own their stop
|
|
72
|
+
# and restart; a routine SDK update may leave their adapter unchanged.
|
|
73
|
+
# Name is available even when cross-bitness hides ExecutablePath.
|
|
74
|
+
$servicePrefix = '"' + (Join-Path $root 'bin\trillboards-hidden-run.vbs') + '" --wait "'
|
|
75
|
+
if ($_.Name -ieq 'wscript.exe' -and
|
|
76
|
+
$commandLine.IndexOf($servicePrefix, [StringComparison]::OrdinalIgnoreCase) -ge 0) { return $false }
|
|
47
77
|
$isInstalledExecutable = (
|
|
48
78
|
$exe.Equals($root, [StringComparison]::OrdinalIgnoreCase) -or
|
|
49
79
|
$exe.StartsWith($rootPrefix, [StringComparison]::OrdinalIgnoreCase)
|
|
@@ -51,7 +81,6 @@ function Get-TrillboardsEdgeProcesses {
|
|
|
51
81
|
if ($isInstalledExecutable) {
|
|
52
82
|
return $true
|
|
53
83
|
}
|
|
54
|
-
$commandLine = [string]$_.CommandLine
|
|
55
84
|
if ($commandLine.IndexOf($root, [StringComparison]::OrdinalIgnoreCase) -lt 0) {
|
|
56
85
|
return $false
|
|
57
86
|
}
|
|
@@ -121,3 +150,33 @@ function Assert-BinariesUnlocked {
|
|
|
121
150
|
Assert-BinariesUnlocked -Root $root
|
|
122
151
|
|
|
123
152
|
Write-Host "Stopped existing Trillboards Edge processes."
|
|
153
|
+
|
|
154
|
+
} catch {
|
|
155
|
+
$stopError = $_
|
|
156
|
+
# A later service/connector failure must also restore services already
|
|
157
|
+
# stopped successfully; the failing helper restores only its own schedule.
|
|
158
|
+
foreach ($entry in $stoppedLocalAi) {
|
|
159
|
+
if ($entry.State.TaskPresent -and $entry.State.Enabled) {
|
|
160
|
+
try {
|
|
161
|
+
$current = & $stopLocalAi -Service $entry.Service -Inspect
|
|
162
|
+
if (-not $current.TaskPresent -or $current.Port -ne $entry.State.Port) { throw 'The local AI task changed during cleanup' }
|
|
163
|
+
Enable-ScheduledTask -TaskName $entry.State.TaskName -TaskPath '\' -ErrorAction Stop | Out-Null
|
|
164
|
+
if ($entry.State.Running -and $current.TaskState -notin @('Running','Queued') -and
|
|
165
|
+
$current.OwnedProcessCount -eq 0 -and $current.ListenerCount -eq 0) {
|
|
166
|
+
Start-ScheduledTask -TaskName $entry.State.TaskName -TaskPath '\' -ErrorAction Stop
|
|
167
|
+
}
|
|
168
|
+
} catch { Write-Warning ("Could not restore the previously stopped local AI service: " + $_.Exception.Message) }
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if ($priorConnector -and $priorConnector.Enabled) {
|
|
172
|
+
try {
|
|
173
|
+
Enable-ScheduledTask -TaskName 'TrillboardsEdge' -TaskPath '\' -ErrorAction Stop | Out-Null
|
|
174
|
+
$state = (Get-ScheduledTask -TaskName 'TrillboardsEdge' -TaskPath '\' -ErrorAction Stop).State
|
|
175
|
+
if ($priorConnector.Running -and $state -notin @('Running','Queued') -and
|
|
176
|
+
@(Get-TrillboardsEdgeProcesses -VerifyRecovery).Count -eq 0) {
|
|
177
|
+
Start-ScheduledTask -TaskName 'TrillboardsEdge' -TaskPath '\' -ErrorAction Stop
|
|
178
|
+
}
|
|
179
|
+
} catch { Write-Warning ("Could not restore the connector schedule after failed uninstall: " + $_.Exception.Message) }
|
|
180
|
+
}
|
|
181
|
+
throw $stopError
|
|
182
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
<#
|
|
2
|
+
Stop one verified per-user local AI service, including native children left
|
|
3
|
+
behind when Task Scheduler ends its waiting hidden host. Return the original
|
|
4
|
+
schedule state; callers own re-registration, restoration or task deletion.
|
|
5
|
+
-Inspect verifies the same ownership without changing anything.
|
|
6
|
+
-InspectTaskOnly verifies task identity without native queries for enablement
|
|
7
|
+
recovery; native availability still requires a full inspection before start.
|
|
8
|
+
#>
|
|
9
|
+
[CmdletBinding()]
|
|
10
|
+
param(
|
|
11
|
+
[Parameter(Mandatory = $true)][ValidateSet('Model','Detector')][string]$Service,
|
|
12
|
+
[string]$ToolPath = '',
|
|
13
|
+
[ValidateRange(0,65535)][int]$Port = 0,
|
|
14
|
+
[switch]$Inspect,
|
|
15
|
+
[switch]$InspectTaskOnly
|
|
16
|
+
)
|
|
17
|
+
$ErrorActionPreference = 'Stop'
|
|
18
|
+
$toolName = if ($Service -eq 'Model') { 'litert-lm.exe' } else { 'trillboards-detector.exe' }
|
|
19
|
+
$taskName = if ($Service -eq 'Model') { 'TrillboardsLiteRtLm' } else { 'TrillboardsDetector' }
|
|
20
|
+
$packageName = if ($Service -eq 'Model') { 'litert-lm' } else { 'trillboards-detector' }
|
|
21
|
+
$commandPattern = if ($Service -eq 'Model') { 'litert[-_]lm' } else { 'trillboards[-_.]detector' }
|
|
22
|
+
$ownerSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
|
23
|
+
$explicitTool = $PSBoundParameters.ContainsKey('ToolPath')
|
|
24
|
+
if (-not $ToolPath) { $ToolPath = Join-Path $env:USERPROFILE ('.local\bin\' + $toolName) }
|
|
25
|
+
if (-not [IO.Path]::IsPathRooted($ToolPath) -or [IO.Path]::GetFileName($ToolPath) -ine $toolName) { throw 'Cannot verify the local AI executable' }
|
|
26
|
+
$ToolPath = [IO.Path]::GetFullPath($ToolPath)
|
|
27
|
+
$taskErrors = @()
|
|
28
|
+
$task = Get-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction SilentlyContinue -ErrorVariable taskErrors
|
|
29
|
+
if (@($taskErrors | Where-Object { $_.CategoryInfo.Category -ne 'ObjectNotFound' }).Count) { throw 'Cannot inspect the local AI task; nothing was stopped' }
|
|
30
|
+
if (@($task).Count -gt 1) { throw 'The local AI task is ambiguous; nothing was stopped' }
|
|
31
|
+
if ($task) {
|
|
32
|
+
$taskUser = [string]$task.Principal.UserId
|
|
33
|
+
$taskSid = if ($taskUser -match '^S-1-') { $taskUser } else {
|
|
34
|
+
(New-Object Security.Principal.NTAccount($taskUser)).Translate([Security.Principal.SecurityIdentifier]).Value
|
|
35
|
+
}
|
|
36
|
+
if ($taskSid -ne $ownerSid) { throw 'The local AI task belongs to another user; nothing was stopped' }
|
|
37
|
+
$actions = @($task.Actions)
|
|
38
|
+
if ($actions.Count -ne 1) { throw 'Cannot verify the local AI task action; nothing was stopped' }
|
|
39
|
+
$execute = [string]$actions[0].Execute
|
|
40
|
+
$arguments = [string]$actions[0].Arguments
|
|
41
|
+
# Recover only the historical array-splatting corruption already recognized
|
|
42
|
+
# by the updater. A malformed task cannot carry a valid old serve port.
|
|
43
|
+
if ($Service -eq 'Detector' -and $execute -eq '-DetectorPath') {
|
|
44
|
+
$ownTool = [IO.Path]::GetFullPath((Join-Path $env:USERPROFILE '.local\bin\trillboards-detector.exe'))
|
|
45
|
+
if ($ToolPath -ine $ownTool -or $arguments -notmatch '^serve --host 127\.0\.0\.1 --port (.+?) --log-file "-RamBudgetMb" --ram-budget-mb \d+$') {
|
|
46
|
+
throw 'Cannot verify the malformed detector task; nothing was stopped'
|
|
47
|
+
}
|
|
48
|
+
$recovered = $Matches[1]
|
|
49
|
+
if (-not [IO.Path]::IsPathRooted($recovered) -or [IO.Path]::GetFullPath($recovered) -ine $ownTool -or -not (Test-Path -LiteralPath $ownTool -PathType Leaf)) {
|
|
50
|
+
throw 'The malformed detector task does not identify this user installation'
|
|
51
|
+
}
|
|
52
|
+
$execute = $ownTool
|
|
53
|
+
$arguments = 'serve --host 127.0.0.1 --port ' + $(if ($Port) { $Port } else { 9380 })
|
|
54
|
+
}
|
|
55
|
+
$wscript = Join-Path $env:WINDIR 'System32\wscript.exe'
|
|
56
|
+
if ([IO.Path]::GetFullPath($execute) -ieq [IO.Path]::GetFullPath($wscript)) {
|
|
57
|
+
$prefix = '//B //NoLogo "' + (Join-Path $PSScriptRoot 'trillboards-hidden-run.vbs') + '" --wait "'
|
|
58
|
+
if (-not $arguments.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { throw 'Cannot verify the hidden local AI action; nothing was stopped' }
|
|
59
|
+
$tail = $arguments.Substring($prefix.Length)
|
|
60
|
+
$endQuote = $tail.IndexOf('"')
|
|
61
|
+
if ($endQuote -lt 1) { throw 'Cannot verify the hidden local AI executable; nothing was stopped' }
|
|
62
|
+
$execute = $tail.Substring(0, $endQuote)
|
|
63
|
+
$arguments = $tail.Substring($endQuote + 1).TrimStart()
|
|
64
|
+
}
|
|
65
|
+
if (-not $explicitTool -and [IO.Path]::IsPathRooted($execute) -and [IO.Path]::GetFileName($execute) -ieq $toolName) { $ToolPath = [IO.Path]::GetFullPath($execute) }
|
|
66
|
+
if (-not [IO.Path]::IsPathRooted($execute) -or [IO.Path]::GetFullPath($execute) -ine $ToolPath) { throw 'The local AI task executable belongs to another installation; nothing was stopped' }
|
|
67
|
+
$ports = [regex]::Matches($arguments, '(?:^|\s)--port(?:\s+|=)([0-9]+)(?=\s|$)')
|
|
68
|
+
if ($arguments -notmatch '^serve\s' -or $ports.Count -ne 1 -or [long]$ports[0].Groups[1].Value -lt 1 -or [long]$ports[0].Groups[1].Value -gt 65535) { throw 'Cannot verify the local AI serve port; nothing was stopped' }
|
|
69
|
+
# Stop the recorded OLD port when re-registering onto a new one.
|
|
70
|
+
$Port = [int]$ports[0].Groups[1].Value
|
|
71
|
+
}
|
|
72
|
+
if (-not $Port) { $Port = if ($Service -eq 'Model') { 9379 } else { 9380 } }
|
|
73
|
+
$context = [pscustomobject]@{ TaskName=$taskName; TaskPresent=[bool]$task; Enabled=($task -and [bool]$task.Settings.Enabled); Running=($task -and $task.State -eq 'Running'); TaskState=$(if($task){[string]$task.State}else{'Absent'}); Port=$Port }
|
|
74
|
+
# Enablement recovery needs task ownership even when a foreign process occupies
|
|
75
|
+
# the port. This read-only mode never enumerates or stops native processes.
|
|
76
|
+
if ($InspectTaskOnly) { return $context }
|
|
77
|
+
|
|
78
|
+
# uv source formats: crates/uv-trampoline-builder/src/lib.rs (current PE
|
|
79
|
+
# resources and released0.8.22 EOF metadata). Read data; never execute a probe.
|
|
80
|
+
function Get-RecordedUvToolRuntime([string]$Launcher, [string]$PackageName) {
|
|
81
|
+
if (-not [IO.File]::Exists($Launcher)) { return }
|
|
82
|
+
if (-not ('TrillboardsUvToolMetadata' -as [type])) {
|
|
83
|
+
Add-Type -TypeDefinition @'
|
|
84
|
+
using System;
|
|
85
|
+
using System.IO;
|
|
86
|
+
using System.Text;
|
|
87
|
+
using System.Runtime.InteropServices;
|
|
88
|
+
public static class TrillboardsUvToolMetadata {
|
|
89
|
+
[DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern IntPtr LoadLibraryExW(string path, IntPtr file, uint flags);
|
|
90
|
+
[DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern IntPtr FindResourceW(IntPtr module, string name, IntPtr type);
|
|
91
|
+
[DllImport("kernel32.dll")] static extern uint SizeofResource(IntPtr module, IntPtr resource);
|
|
92
|
+
[DllImport("kernel32.dll")] static extern IntPtr LoadResource(IntPtr module, IntPtr resource);
|
|
93
|
+
[DllImport("kernel32.dll")] static extern IntPtr LockResource(IntPtr resource);
|
|
94
|
+
[DllImport("kernel32.dll")] static extern bool FreeLibrary(IntPtr module);
|
|
95
|
+
static byte[] Resource(IntPtr module, string name) {
|
|
96
|
+
IntPtr info=FindResourceW(module,name,new IntPtr(10)); if(info==IntPtr.Zero)return null;
|
|
97
|
+
uint size=SizeofResource(module,info); if(size==0||size>32768)return null;
|
|
98
|
+
IntPtr data=LockResource(LoadResource(module,info)); if(data==IntPtr.Zero)return null;
|
|
99
|
+
byte[] bytes=new byte[size]; Marshal.Copy(data,bytes,0,bytes.Length); return bytes;
|
|
100
|
+
}
|
|
101
|
+
static string Decode(byte[] bytes) {
|
|
102
|
+
try { return new UTF8Encoding(false,true).GetString(bytes); }
|
|
103
|
+
catch(DecoderFallbackException) { return null; }
|
|
104
|
+
}
|
|
105
|
+
public static string Read(string path) {
|
|
106
|
+
// Map PE data/resources only: no entrypoint, imports or launcher execution.
|
|
107
|
+
IntPtr module=LoadLibraryExW(path,IntPtr.Zero,0x22); if(module==IntPtr.Zero)return null;
|
|
108
|
+
try {
|
|
109
|
+
byte[] kind=Resource(module,"UV_TRAMPOLINE_KIND");
|
|
110
|
+
byte[] python=Resource(module,"UV_PYTHON_PATH");
|
|
111
|
+
if(kind!=null||python!=null) {
|
|
112
|
+
if(kind==null||kind.Length!=1||(kind[0]!=1&&kind[0]!=2)||python==null)return null;
|
|
113
|
+
return Decode(python);
|
|
114
|
+
}
|
|
115
|
+
} finally { FreeLibrary(module); }
|
|
116
|
+
// Released uv0.8.x: UTF8 interpreter + u32LE byte count + UVSC/UVPY
|
|
117
|
+
// at EOF. Do not search arbitrary strings or an unmerged ZIP layout.
|
|
118
|
+
try {
|
|
119
|
+
using(FileStream file=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read)) {
|
|
120
|
+
if(file.Length<9||file.Length>16*1024*1024)return null;
|
|
121
|
+
file.Seek(-8,SeekOrigin.End); byte[] tail=new byte[8];
|
|
122
|
+
if(file.Read(tail,0,tail.Length)!=tail.Length)return null;
|
|
123
|
+
string magic=Encoding.ASCII.GetString(tail,4,4);
|
|
124
|
+
if(magic!="UVSC"&&magic!="UVPY")return null;
|
|
125
|
+
uint length=BitConverter.ToUInt32(tail,0);
|
|
126
|
+
if(length==0||length>32768||length>file.Length-8)return null;
|
|
127
|
+
file.Seek(-8-(long)length,SeekOrigin.End); byte[] bytes=new byte[length];
|
|
128
|
+
if(file.Read(bytes,0,bytes.Length)!=bytes.Length)return null;
|
|
129
|
+
return Decode(bytes);
|
|
130
|
+
}
|
|
131
|
+
} catch(IOException) { return null; }
|
|
132
|
+
catch(UnauthorizedAccessException) { return null; }
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
'@
|
|
136
|
+
}
|
|
137
|
+
$python = [TrillboardsUvToolMetadata]::Read($Launcher)
|
|
138
|
+
if ([string]::IsNullOrWhiteSpace($python) -or $python.IndexOf([char]0) -ge 0) { return }
|
|
139
|
+
try {
|
|
140
|
+
if ([IO.Path]::IsPathRooted($python) -and $python -notmatch '^(?:[a-z]:[\\/]|\\\\[^\\]+\\[^\\]+\\)') { return }
|
|
141
|
+
if (-not [IO.Path]::IsPathRooted($python)) { $python = Join-Path ([IO.Path]::GetDirectoryName($Launcher)) $python }
|
|
142
|
+
$python = [IO.Path]::GetFullPath($python)
|
|
143
|
+
$scripts = [IO.Path]::GetDirectoryName($python)
|
|
144
|
+
$toolRoot = [IO.Path]::GetDirectoryName($scripts)
|
|
145
|
+
if ([IO.Path]::GetFileName($python) -notin @('python.exe','pythonw.exe') -or
|
|
146
|
+
[IO.Path]::GetFileName($scripts) -ine 'Scripts' -or [IO.Path]::GetFileName($toolRoot) -ine $PackageName) { return }
|
|
147
|
+
[pscustomobject]@{ Python = $python; ToolRoot = ($toolRoot.TrimEnd('\') + '\') }
|
|
148
|
+
} catch { return }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function Get-FirstCommandExecutable([string]$CommandLine) {
|
|
152
|
+
$first = [regex]::Match($CommandLine, '^\s*(?:"([^"]+)"|([^\s"]+))(?=\s|$)')
|
|
153
|
+
if (-not $first.Success) { return }
|
|
154
|
+
$path = if ($first.Groups[1].Success) { $first.Groups[1].Value } else { $first.Groups[2].Value }
|
|
155
|
+
if ($path -notmatch '^(?:[a-z]:[\\/]|\\\\[^\\]+\\[^\\]+\\)') { return }
|
|
156
|
+
try { [IO.Path]::GetFullPath($path) } catch { return }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
# Resolve the recorded launcher's venv, including custom UV_TOOL_DIR installs.
|
|
160
|
+
# A current environment variable cannot identify a previous installation.
|
|
161
|
+
$recordedRuntime = Get-RecordedUvToolRuntime $ToolPath $packageName
|
|
162
|
+
$toolRoot = if ($recordedRuntime) { $recordedRuntime.ToolRoot } else {
|
|
163
|
+
[IO.Path]::GetFullPath((Join-Path $env:APPDATA ('uv\tools\' + $packageName))).TrimEnd('\') + '\'
|
|
164
|
+
}
|
|
165
|
+
$portPattern = '(?:^|\s)--port(?:\s+|=)' + $Port + '(?=\s|$)'
|
|
166
|
+
|
|
167
|
+
function Get-OwnedServiceProcesses {
|
|
168
|
+
$filter = "Name = 'python.exe' OR Name = 'pythonw.exe' OR Name = '" + $toolName + "'"
|
|
169
|
+
foreach ($process in @(Get-CimInstance Win32_Process -Filter $filter -OperationTimeoutSec 5 -ErrorAction Stop)) {
|
|
170
|
+
if (-not $process.CommandLine -or $process.CommandLine -notmatch $commandPattern -or
|
|
171
|
+
$process.CommandLine -notmatch '(?:^|\s)serve(?=\s|$)' -or $process.CommandLine -notmatch $portPattern) { continue }
|
|
172
|
+
try { $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 5 -ErrorAction Stop } catch {
|
|
173
|
+
if (-not (Get-CimInstance Win32_Process -Filter ('ProcessId=' + $process.ProcessId) -OperationTimeoutSec 5 -ErrorAction Stop)) { continue }
|
|
174
|
+
throw
|
|
175
|
+
}
|
|
176
|
+
if ($owner.ReturnValue -ne 0 -or -not $owner.Sid) { throw 'Cannot verify a local AI process owner; nothing unverified was stopped' }
|
|
177
|
+
if ($owner.Sid -ne $ownerSid) { continue }
|
|
178
|
+
$exe = [string]$process.ExecutablePath
|
|
179
|
+
# A venv redirector can report the shared base Python as ExecutablePath.
|
|
180
|
+
# Trust only the exact recorded interpreter in the FIRST command argument.
|
|
181
|
+
$recordedInterpreter = $recordedRuntime -and (Get-FirstCommandExecutable $process.CommandLine) -ieq $recordedRuntime.Python
|
|
182
|
+
if (-not $exe -or ($exe -ine $ToolPath -and -not $exe.StartsWith($toolRoot, [StringComparison]::OrdinalIgnoreCase) -and
|
|
183
|
+
-not $recordedInterpreter -and $process.CommandLine.IndexOf($ToolPath, [StringComparison]::OrdinalIgnoreCase) -lt 0)) { continue }
|
|
184
|
+
$process
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function Get-ServiceListeners {
|
|
188
|
+
$listenerErrors = @()
|
|
189
|
+
$listeners = @(Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue -ErrorVariable listenerErrors)
|
|
190
|
+
if (@($listenerErrors | Where-Object { $_.CategoryInfo.Category -ne 'ObjectNotFound' }).Count) { throw 'Cannot verify the local AI listening port' }
|
|
191
|
+
$listeners
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
$owned = @(Get-OwnedServiceProcesses)
|
|
195
|
+
$ownedIds = @($owned | ForEach-Object { $_.ProcessId })
|
|
196
|
+
$listeners = @(Get-ServiceListeners)
|
|
197
|
+
foreach ($listener in $listeners) {
|
|
198
|
+
if ($ownedIds -notcontains $listener.OwningProcess) { throw 'The local AI port has an unverified listener; no task or process was stopped' }
|
|
199
|
+
}
|
|
200
|
+
$context | Add-Member -NotePropertyName OwnedProcessCount -NotePropertyValue $owned.Count
|
|
201
|
+
$context | Add-Member -NotePropertyName ListenerCount -NotePropertyValue $listeners.Count
|
|
202
|
+
# Ready describes the scheduler host, not the availability of its native
|
|
203
|
+
# service. Preserve a live owned child too when rolling back a stopped host.
|
|
204
|
+
$context.Running = $context.Running -or ($context.TaskPresent -and $owned.Count -gt 0)
|
|
205
|
+
if ($Inspect) { return $context }
|
|
206
|
+
try {
|
|
207
|
+
if ($task) {
|
|
208
|
+
Disable-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction Stop | Out-Null
|
|
209
|
+
Stop-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction Stop
|
|
210
|
+
}
|
|
211
|
+
for ($attempt = 0; $attempt -lt 15; $attempt++) {
|
|
212
|
+
foreach ($process in @(Get-OwnedServiceProcesses)) {
|
|
213
|
+
# A launcher may exit between the CIM snapshot and termination. Recheck
|
|
214
|
+
# identity, including creation time, so a recycled PID is never a target.
|
|
215
|
+
$live = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $process.ProcessId) -OperationTimeoutSec 5 -ErrorAction Stop
|
|
216
|
+
if (-not $live) { continue }
|
|
217
|
+
# CIM can return an incomplete record while a child is exiting. Never
|
|
218
|
+
# terminate that PID; the bounded outer loop takes a fresh owned snapshot.
|
|
219
|
+
# A known creation-time or executable change still fails closed.
|
|
220
|
+
if (($live.CreationDate -and $process.CreationDate -and $live.CreationDate -ne $process.CreationDate) -or
|
|
221
|
+
($live.ExecutablePath -and $live.ExecutablePath -ine $process.ExecutablePath)) {
|
|
222
|
+
throw ("The local AI process identity changed; retry the operation (PID {0}; creation '{1}' -> '{2}'; executable '{3}' -> '{4}')" -f
|
|
223
|
+
$process.ProcessId, $process.CreationDate, $live.CreationDate, $process.ExecutablePath, $live.ExecutablePath)
|
|
224
|
+
}
|
|
225
|
+
if (-not $process.CreationDate -or -not $live.CreationDate -or -not $live.ExecutablePath) { continue }
|
|
226
|
+
try { Stop-Process -Id $process.ProcessId -Force -ErrorAction Stop } catch {
|
|
227
|
+
if (Get-CimInstance Win32_Process -Filter ('ProcessId=' + $process.ProcessId) -OperationTimeoutSec 5 -ErrorAction Stop) { throw }
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
$remaining = @(Get-OwnedServiceProcesses)
|
|
231
|
+
$listeners = @(Get-ServiceListeners)
|
|
232
|
+
$state = if ($task) { (Get-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction Stop).State } else { 'Absent' }
|
|
233
|
+
if ($state -notin @('Running','Queued') -and $remaining.Count -eq 0 -and $listeners.Count -eq 0) { return $context }
|
|
234
|
+
Start-Sleep -Seconds 1
|
|
235
|
+
}
|
|
236
|
+
throw 'The local AI server or port did not stop; runtime files were left untouched'
|
|
237
|
+
} catch {
|
|
238
|
+
$stopError = $_
|
|
239
|
+
if ($context.TaskPresent -and $context.Enabled) {
|
|
240
|
+
try {
|
|
241
|
+
Enable-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction Stop | Out-Null
|
|
242
|
+
if ($context.Running) {
|
|
243
|
+
$state = (Get-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction Stop).State
|
|
244
|
+
if ($state -notin @('Running','Queued')) {
|
|
245
|
+
# A stop can fail after ending the waiting host and its native child.
|
|
246
|
+
# Logon-only tasks need an explicit restart. Never launch a duplicate
|
|
247
|
+
# while an owned child survives or a listener cannot be cleared.
|
|
248
|
+
if (@(Get-OwnedServiceProcesses).Count -eq 0 -and @(Get-ServiceListeners).Count -eq 0) {
|
|
249
|
+
Start-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction Stop
|
|
250
|
+
} else { Write-Warning 'Local AI recovery left the schedule enabled; a native process or listener still occupies the service' }
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
} catch { Write-Warning ("Could not restore the local AI schedule after the failed stop: " + $_.Exception.Message) }
|
|
254
|
+
}
|
|
255
|
+
throw $stopError
|
|
256
|
+
}
|