Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(local-installation): pin localmodels 0.1.0.dev31 and load its npm-packed kit

chendongdong7f0f06dafef2
diff --git a/apps/desktop/distribution/darwin-arm64.json b/apps/desktop/distribution/darwin-arm64.json
index 46ac3ad6..a095582e 100644
--- a/apps/desktop/distribution/darwin-arm64.json
+++ b/apps/desktop/distribution/darwin-arm64.json
@@ -2,11 +2,11 @@
"platform": "darwin",
"arch": "arm64",
"localmodelsTool": {
- "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev28/darwin-arm64.tgz",
- "sha256": "abd3baeabd3d43bd4a4e5fc3694ed2456d5b32b3b8d0b3805856d9b0a57272c8",
- "bytes": 40530675,
- "sourceCommit": "c77bed6e5b65c30314d96dfe8dc9b7ab964c5332",
- "manifestSha256": "4aea49a70a826d9926762e12dac0fd6e358876e959f05c2bd825dfd4070ddf3a"
+ "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev31/darwin-arm64.tgz",
+ "sha256": "7bcc62fbd4c15398577d2f328af79c3acc88644c208007870c5b19e87229ecf7",
+ "bytes": 40736176,
+ "sourceCommit": "531c092c88589aa261f0f8d82e60b94d8136f65b",
+ "manifestSha256": "6ddca9a017727abcc472ce491a12b4d8bc6955b909297ae777dee90b187677b7"
},
"nativeSources": [
{
diff --git a/apps/desktop/distribution/linux-x64.json b/apps/desktop/distribution/linux-x64.json
index 9a844ce9..bb7eff14 100644
--- a/apps/desktop/distribution/linux-x64.json
+++ b/apps/desktop/distribution/linux-x64.json
@@ -2,11 +2,11 @@
"platform": "linux",
"arch": "x64",
"localmodelsTool": {
- "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev28/linux-x64.tgz",
- "sha256": "2923a04c83c88237814e753cfc3637bdc80545aa77defa669d8ff42cd85d6eb8",
- "bytes": 68559312,
- "sourceCommit": "c77bed6e5b65c30314d96dfe8dc9b7ab964c5332",
- "manifestSha256": "374f72b64796a57d66344462881415bf0b1ab02b5884a55b82d1f9d2b6607877"
+ "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev31/linux-x64.tgz",
+ "sha256": "86a1d7ace3c82ecc3b3118fccdd2a91540223a8c3884cbac4d26c50c512852a3",
+ "bytes": 68881199,
+ "sourceCommit": "531c092c88589aa261f0f8d82e60b94d8136f65b",
+ "manifestSha256": "820efa2d5645c49c0e677818e9b11748d29124528518f1b877ac3b2f37821633"
},
"nativeSources": [
{
diff --git a/apps/desktop/distribution/win32-x64.json b/apps/desktop/distribution/win32-x64.json
index 1b08ad9f..ebd8a3e8 100644
--- a/apps/desktop/distribution/win32-x64.json
+++ b/apps/desktop/distribution/win32-x64.json
@@ -2,11 +2,11 @@
"platform": "win32",
"arch": "x64",
"localmodelsTool": {
- "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev28/win32-x64.tgz",
- "sha256": "a2301caae3ce51a48b1a9a2409c61bf6c1c8af9b095169e19348c5f2b817cce7",
- "bytes": 22743233,
- "sourceCommit": "c77bed6e5b65c30314d96dfe8dc9b7ab964c5332",
- "manifestSha256": "5a5a310b46ab43f0dd981a785185fc9638b827cc6d784f7faf5aad22e5167764"
+ "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev31/win32-x64.tgz",
+ "sha256": "11a00223c55638f10b7b407341febd641a7440c6935bc518f0f001a4cffbb7fb",
+ "bytes": 23120974,
+ "sourceCommit": "531c092c88589aa261f0f8d82e60b94d8136f65b",
+ "manifestSha256": "8b04c8724468b9a3c8f470ddcacb884f3f76b7592a5254cb326d3759bb09d7c2"
},
"nativeSources": [
{
diff --git a/apps/desktop/src/main/distribution.test.ts b/apps/desktop/src/main/distribution.test.ts
index 96867fa1..899bcbc4 100644
--- a/apps/desktop/src/main/distribution.test.ts
+++ b/apps/desktop/src/main/distribution.test.ts
@@ -58,7 +58,6 @@ describe("desktop distributions", () => {
voice.map((source) => [source.target, source.file !== undefined]),
).toEqual([[target, true]]);
const tool = validateToolSource(value.localmodelsTool);
- expect(tool.url).toBe(`${pin("STACK_BASE_URL")}/${target}.tgz`);
expect(value.localmodelsTool.sourceCommit).toBe(
pin("STACK_SOURCE_COMMIT"),
);
diff --git a/packages/local-installation/src/localmodels-tool.test.ts b/packages/local-installation/src/localmodels-tool.test.ts
index 9e4ff610..be2c6b64 100644
--- a/packages/local-installation/src/localmodels-tool.test.ts
+++ b/packages/local-installation/src/localmodels-tool.test.ts
@@ -7,6 +7,7 @@ import {
rm,
readFile,
readdir,
+ rename,
stat,
utimes,
} from "node:fs/promises";
@@ -75,6 +76,18 @@ async function fixture() {
);
return { home, source, directory };
}
+// The published archive of the fixture kit: an npm tarball, whose files sit
+// under package/. The fixture's own directory is moved into it.
+async function packed(f: Awaited<ReturnType<typeof fixture>>) {
+ const root = path.join(f.home, "packed");
+ await mkdir(root);
+ await rename(f.directory, path.join(root, "package"));
+ const archive = path.join(f.home, "kit.tgz");
+ execFileSync("tar", ["-czf", archive, "-C", root, "package"], {
+ env: { ...process.env, COPYFILE_DISABLE: "1" },
+ });
+ return readFile(archive);
+}
test("requires a fixed authenticated-free tool source and source identity", () => {
expect(() =>
validateToolSource({
@@ -168,11 +181,7 @@ test.skipIf(process.platform === "win32")(
"repairs a kit altered after verification by fetching the same pinned archive",
async () => {
const f = await fixture();
- const archive = path.join(f.home, "kit.tgz");
- execFileSync("tar", ["-czf", archive, "-C", f.directory, "."], {
- env: { ...process.env, COPYFILE_DISABLE: "1" },
- });
- const bytes = await readFile(archive);
+ const bytes = await packed(f);
const source = { ...f.source, sha256: hash(bytes), bytes: bytes.length };
const directory = path.join(f.home, "tools/localmodels", source.sha256);
const first = vi.fn(async () => new Response(bytes));
@@ -215,16 +224,32 @@ test.skipIf(process.platform === "win32")(
).toEqual([]);
},
);
+test.skipIf(process.platform === "win32")(
+ "installs the published kit, whose files sit under package/",
+ async () => {
+ const f = await fixture();
+ const bytes = await packed(f);
+ const source = { ...f.source, sha256: hash(bytes), bytes: bytes.length };
+ const directory = path.join(f.home, "tools/localmodels", source.sha256);
+ const tool = await ensureLocalmodelsTool(
+ f.home,
+ {},
+ { source, fetcher: async () => new Response(bytes) },
+ );
+ expect(tool.python).toBe(path.join(directory, "python/python"));
+ expect((await readdir(directory)).sort()).toEqual([
+ "modules",
+ "python",
+ "tool.json",
+ ]);
+ expect((await stat(directory)).mode & 0o777).toBe(0o500);
+ },
+);
test.skipIf(process.platform === "win32")(
"downloads the kit from the publisher's mirror when the primary host fails",
async () => {
const f = await fixture();
- const archive = path.join(f.home, "kit.tgz");
- execFileSync("tar", ["-czf", archive, "-C", f.directory, "."], {
- env: { ...process.env, COPYFILE_DISABLE: "1" },
- });
- await rm(f.directory, { recursive: true, force: true });
- const bytes = await readFile(archive);
+ const bytes = await packed(f);
const source = {
...f.source,
mirrors: ["https://mirror.example/tool.tgz"],
diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.ts
index d2294e27..de7981b1 100644
--- a/packages/local-installation/src/localmodels-tool.ts
+++ b/packages/local-installation/src/localmodels-tool.ts
@@ -337,13 +337,15 @@ async function prepareLocalmodelsTool(
dependencies.fetcher,
);
await unpack(archive, stage);
- const tool = await verify(stage, source);
+ // The kit is an npm tarball: its files sit under package/.
+ const kit = path.join(stage, "package");
+ const tool = await verify(kit, source);
if (process.platform !== "win32") await chmod(tool.python, 0o700);
// The kit manifest is private state; publisher bytes stay unchanged for digest checks.
- const body = await readFile(path.join(stage, "tool.json"), "utf8");
- await atomicPrivate(path.join(stage, "tool.json"), body);
+ const body = await readFile(path.join(kit, "tool.json"), "utf8");
+ await atomicPrivate(path.join(kit, "tool.json"), body);
signal.throwIfAborted();
- await renameRetrying(stage, directory, { signal });
+ await renameRetrying(kit, directory, { signal });
// The rename keeps every stamp, so this checks the published kit
// without hashing it a second time.
const verified = await verify(directory, source, tool.stamps);
diff --git a/scripts/installs/README.md b/scripts/installs/README.md
index 5d2e26bc..e5ba3229 100644
--- a/scripts/installs/README.md
+++ b/scripts/installs/README.md
@@ -40,7 +40,7 @@ diagnostics.
`stack.sh` (Linux, macOS) and `stack.ps1` (Windows) run a pinned version of `localmodels stack`.
Both scripts hold only the version pin, no source: the first run downloads that version's
-self-contained Python + localmodels kit for the platform from the CDN, checks the archive SHA256
+self-contained Python + localmodels kit from `@simplexai/localmodels-<target>` on npm, checks the archive SHA256
pinned in the script and every file listed in the kit's `tool.json`, then caches it; later runs start
offline and need no system Python.
@@ -55,25 +55,47 @@ scripts/installs/stack.sh apply "/path/to/plan.json" --approve CONFIRMATION_ID
powershell -ExecutionPolicy Bypass -File scripts\installs\stack.ps1 --help
```
-Arguments pass unchanged to `localmodels stack`; with no arguments it shows the help. Where the CLI
+`--region auto|global|cn` before the command selects the registry (`-Region` in PowerShell).
+The flag overrides `SIMPLEX_REGION`, which defaults to `auto`. Auto probes the first 256 KiB of
+the pinned tarball from both registries in parallel with a five second deadline. It chooses the
+faster success and defaults to global if both fail. A download error retries the other registry
+once. A SHA256 mismatch is fatal. The resolved region is passed to localmodels and its Bifrost
+downloader through `SIMPLEX_REGION`; a resolved parent value does not probe again.
+An untouched `auto` on a cached launch stays `auto`, so a later Bifrost download probes its own tarball.
+Redirects stay on HTTPS and are limited to five hops.
+
+Other arguments pass unchanged to `localmodels stack`; with no arguments it shows the help. Where the CLI
hints say `python3 -m localmodels stack`, use `stack.sh` here. `apply` still needs the full
confirmation ID the plan prints; the scripts never plan or install on their own.
Environment variables:
- `LOCALMODELS_KIT_HOME`: kit cache directory, default `~/.cache/linger-localmodels/kits` (on Windows `%LOCALAPPDATA%\linger-localmodels\kits`).
-- `LOCALMODELS_KIT_BASE_URL`: download the same files from an internal mirror; SHA256 is still checked against the pin in the script.
+- `SIMPLEX_NPM_REGISTRY`: replace both registry bases with a test registry or private mirror. Archive SHA256 and size pins still apply.
+- `SIMPLEX_REGION`: `global` uses `registry.npmjs.org`; `cn` uses `registry.npmmirror.com`; `auto` probes both.
+- `LOCALMODELS_KIT_BASE_URL`: legacy mirror layout serving the same pinned npm archives as `<target>.tgz`.
The Linger installer does not go through `stack.sh`; it calls the same kind of localmodels kit
directly and by convention pins the same version as here.
-The same script also runs without cloning the repository: `curl -fsSL https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/<version>/stack.sh | sh -s -- --help`.
-To follow the latest main build, use `…/cli/localmodels/mac-main/stack.sh` or `…/cli/localmodels/lin-main/stack.sh`
-on macOS and Linux (the two are the same file and run on both), and `…/cli/localmodels/win-main/stack.ps1` on Windows.
+Run the pinned script without cloning the repository:
+
+```sh
+# global
+curl -fsSL https://cdn.jsdelivr.net/npm/@simplexai/[email protected]/stack.sh | sh -s -- --region global --help
+# cn
+curl -fsSL https://registry.npmmirror.com/@simplexai/localmodels/0.1.0-dev.31/files/stack.sh | sh -s -- --region cn --help
+```
+
+```powershell
+irm https://cdn.jsdelivr.net/npm/@simplexai/[email protected]/stack.ps1 -OutFile stack.ps1
+powershell -ExecutionPolicy Bypass -File .\stack.ps1 -Region global --help
+# cn script URL: https://registry.npmmirror.com/@simplexai/localmodels/0.1.0-dev.31/files/stack.ps1
+```
-The localmodels release process publishes each version's kits, both scripts and `release.json` under
-`https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/<version>/`, and rewrites `stack.sh`, `stack.ps1` and this section
-with the new pin. Do not edit them by hand. The version pin only says which published CLI runs; it does not state which
-platforms or GPUs are supported.
+The localmodels release process publishes each version's platform kits, its patched Bifrost packages and the
+platform-independent `@simplexai/localmodels` package holding both scripts and `release.json`. `stack.sh`, `stack.ps1`
+and this section carry that release's pin; do not edit them by hand. The version pin only says which published CLI
+runs; it does not state which platforms or GPUs are supported.
<!-- <<< llm-inference-lab: stack -->
diff --git a/scripts/installs/stack.ps1 b/scripts/installs/stack.ps1
index f1a92e59..ec13893a 100644
--- a/scripts/installs/stack.ps1
+++ b/scripts/installs/stack.ps1
@@ -1,97 +1,588 @@
-# `stack.ps1 ARGS` runs `localmodels stack ARGS` from the release pinned below. The first run
-# downloads that release's self-contained Python + localmodels kit, checks its SHA256 and every
-# file it lists, and caches it; later runs start offline. No system Python is needed.
-# The localmodels release process writes the pin; do not edit it by hand.
-# Windows PowerShell 5.1 or PowerShell 7; Windows needs tar.exe (Windows 10 1803 or newer).
Set-StrictMode -Version 3.0
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
# >>> release pin
-$StackVersion = '0.1.0.dev28'
-$StackSourceCommit = 'c77bed6e5b65c30314d96dfe8dc9b7ab964c5332'
-$StackBaseUrl = 'https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev28'
+$StackVersion = '0.1.0.dev31'
+$StackSourceCommit = '531c092c88589aa261f0f8d82e60b94d8136f65b'
+$StackNpmVersion = '0.1.0-dev.31'
$StackKits = @{
- 'darwin-arm64' = 'abd3baeabd3d43bd4a4e5fc3694ed2456d5b32b3b8d0b3805856d9b0a57272c8'
- 'darwin-x64' = 'c3aeb71c912948acb2fb8a4ef8a9f278d16a767d34323c655be83801ef1a8789'
- 'linux-arm64' = 'feffffef4bdfff3d3aff4f248b1daaf804d5a238c3dc58560b42947cb2ecaa09'
- 'linux-x64' = '2923a04c83c88237814e753cfc3637bdc80545aa77defa669d8ff42cd85d6eb8'
- 'win32-x64' = 'a2301caae3ce51a48b1a9a2409c61bf6c1c8af9b095169e19348c5f2b817cce7'
+ 'darwin-arm64' = '7bcc62fbd4c15398577d2f328af79c3acc88644c208007870c5b19e87229ecf7'
+ 'darwin-x64' = '7bf03622cac43a3b2bcbf66f7c59ccc7899b0d84287e4aab718a9bfb9be5ad3f'
+ 'linux-arm64' = 'dd0d821e1c1423134968328bf0de48f79d254895dad92d8a5be3bc79e9e6adcf'
+ 'linux-x64' = '86a1d7ace3c82ecc3b3118fccdd2a91540223a8c3884cbac4d26c50c512852a3'
+ 'win32-x64' = '11a00223c55638f10b7b407341febd641a7440c6935bc518f0f001a4cffbb7fb'
+}
+$StackBootstrap = @{
+ 'darwin-arm64' = @{
+ manifest = '6ddca9a017727abcc472ce491a12b4d8bc6955b909297ae777dee90b187677b7'
+ inventory = 'a18823b294727757d3db8fb2625faf34b8606a88f2d3061ddf5978e6cc2738c6'
+ bytes = '40736176'
+ files = '1867'
+ entries = '2031'
+ python = 'python/bin/python3.12'
+ modules = 'modules'
+ }
+ 'darwin-x64' = @{
+ manifest = '13c86430d1d78829a5a6f4fcc7b34006fa840b5a36fb603729e28e72760c707a'
+ inventory = '74e0f22297176839d122ee74346989544a02da07f85b9dcb4a8925f9c6a466f5'
+ bytes = '40216514'
+ files = '1864'
+ entries = '2027'
+ python = 'python/bin/python3.12'
+ modules = 'modules'
+ }
+ 'linux-arm64' = @{
+ manifest = '2de0e3506bf51667850cd2cae0875072102171185e88f9e0040141a5360200d9'
+ inventory = '928f37183944753ad43b6f4818a3fae858b5413dd9dbcb43968c6221524b26c5'
+ bytes = '55686495'
+ files = '4738'
+ entries = '4945'
+ python = 'python/bin/python3.12'
+ modules = 'modules'
+ }
+ 'linux-x64' = @{
+ manifest = '820efa2d5645c49c0e677818e9b11748d29124528518f1b877ac3b2f37821633'
+ inventory = '245d6eb7508cf9354067690c18ed8a1f6acfbdad3c7911f6577f3d775aff1b04'
+ bytes = '68881199'
+ files = '4738'
+ entries = '4945'
+ python = 'python/bin/python3.12'
+ modules = 'modules'
+ }
+ 'win32-x64' = @{
+ manifest = '8b04c8724468b9a3c8f470ddcacb884f3f76b7592a5254cb326d3759bb09d7c2'
+ inventory = '9338100bad6eb93d9f8fda11ca8a35f7b4741c8f7374d90fdba3f344c9a3b15e'
+ bytes = '23120974'
+ files = '3550'
+ entries = '3819'
+ python = 'python/python.exe'
+ modules = 'modules'
+ }
}
# <<< release pin
function Stop-Stack([string]$Message) {
- [Console]::Error.WriteLine("stack.ps1: $Message")
- exit 2
+ $failure = [InvalidOperationException]::new($Message)
+ $failure.Data['StackError'] = $true
+ throw $failure
}
-
-if (-not $StackVersion) {
- Stop-Stack 'this is the unpinned template; run the copy a release wrote to linger scripts/installs'
+function Quote-Native([string]$Value) {
+ return '"' + [regex]::Replace([regex]::Replace($Value, '(\\*)"', '$1$1\"'), '(\\+)$', '$1$1') + '"'
}
-
-$onWindows = $PSVersionTable.PSVersion.Major -lt 6 -or $IsWindows
-if ($onWindows) {
- $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
- $target = @{ 'AMD64' = 'win32-x64' }[$arch]
- $python = 'python\python.exe'
- $cacheBase = $env:LOCALAPPDATA
-} else {
- $os = if ($IsMacOS) { 'darwin' } else { 'linux' }
- $machine = (& uname -m).Trim()
- $target = @{ 'x86_64' = "$os-x64"; 'amd64' = "$os-x64"; 'arm64' = "$os-arm64"; 'aarch64' = "$os-arm64" }[$machine]
- $python = 'python/bin/python3'
- $cacheBase = if ($env:XDG_CACHE_HOME) { $env:XDG_CACHE_HOME } else { Join-Path $HOME '.cache' }
-}
-if (-not $target -or -not $StackKits.ContainsKey($target)) {
- Stop-Stack "release $StackVersion has no kit for this platform"
-}
-$kit = $StackKits[$target]
-
-# Kits are keyed by archive SHA256, so a new pin never reuses an older kit.
-$root = if ($env:LOCALMODELS_KIT_HOME) { $env:LOCALMODELS_KIT_HOME } else { Join-Path $cacheBase 'linger-localmodels/kits' }
-$final = Join-Path $root $kit
-
-function Install-Kit {
- # LOCALMODELS_KIT_BASE_URL serves the same files from a mirror; the pinned SHA256 still applies.
- $base = if ($env:LOCALMODELS_KIT_BASE_URL) { $env:LOCALMODELS_KIT_BASE_URL } else { $StackBaseUrl }
- $url = "$base/$target.tgz"
- New-Item -ItemType Directory -Force -Path $root | Out-Null
- $staging = Join-Path $root ('.staging.' + [Guid]::NewGuid().ToString('N'))
- New-Item -ItemType Directory -Path $staging | Out-Null
+function Invoke-Native([string]$File, [string[]]$Arguments) {
+ $start = New-Object Diagnostics.ProcessStartInfo
+ $start.FileName = $File
+ $start.UseShellExecute = $false
+ if ($start.PSObject.Properties['ArgumentList']) {
+ foreach ($argument in $Arguments) { $start.ArgumentList.Add($argument) }
+ } else {
+ $start.Arguments = (($Arguments | ForEach-Object { Quote-Native $_ }) -join ' ')
+ }
+ $process = New-Object Diagnostics.Process
+ $process.StartInfo = $start
+ $started = $false
+ try {
+ $started = $process.Start()
+ while (-not $process.WaitForExit(100)) { }
+ return $process.ExitCode
+ } finally {
+ if ($started -and -not $process.HasExited) { $process.Kill() }
+ $process.Dispose()
+ }
+}
+function Get-Digest([string]$Path) {
+ return (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant()
+}
+function Assert-Relative([string]$Name) {
+ if ($Name -cnotmatch '^[A-Za-z0-9_+./-]+$' -or $Name.StartsWith('/') -or
+ @($Name.Split('/') | Where-Object {
+ $_ -in @('', '.', '..') -or $_.EndsWith('.') -or
+ $_ -imatch '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)'
+ }).Count) { Stop-Stack 'unsafe kit relative path' }
+}
+function Assert-Item([string]$Path, [bool]$Directory) {
+ $item = Get-Item -LiteralPath $Path -Force
+ if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($item -is [IO.DirectoryInfo]) -ne $Directory) {
+ Stop-Stack 'unsafe kit path'
+ }
+ return $item
+}
+function Assert-WindowsPrivate([string]$Path, [bool]$Repair, [bool]$AllowInherited = $false) {
+ $item = Get-Item -LiteralPath $Path -Force
+ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User
+ $system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
+ $admins = 'S-1-5-32-544'
+ $trustedInstaller = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { Stop-Stack 'linked private path' }
+ $acl = Get-Acl -LiteralPath $Path
+ $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
+ if ($owner -ne $sid.Value -and -not ($Repair -and $owner -eq $admins)) { Stop-Stack 'foreign kit owner' }
+ $parent = if (($item -is [IO.DirectoryInfo])) { $item.Parent } else { $item.Directory }
+ while ($parent) {
+ if ($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) { Stop-Stack 'linked private parent' }
+ $parentAcl = Get-Acl -LiteralPath $parent.FullName
+ if ($parentAcl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @($sid.Value, $system.Value, $admins, $trustedInstaller)) {
+ Stop-Stack 'foreign private parent'
+ }
+ foreach ($rule in $parentAcl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
+ if ($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) { continue }
+ if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($sid.Value, $system.Value, $admins, 'S-1-3-0', 'S-1-3-4', $trustedInstaller) -and
+ ($rule.FileSystemRights -band [Security.AccessControl.FileSystemRights]'Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership')) {
+ Stop-Stack 'unsafe private parent permissions'
+ }
+ }
+ $parent = $parent.Parent
+ }
+ if ($Repair) {
+ $acl = if (($item -is [IO.DirectoryInfo])) { [Security.AccessControl.DirectorySecurity]::new() } else { [Security.AccessControl.FileSecurity]::new() }
+ $acl.SetOwner($sid)
+ $acl.SetAccessRuleProtection($true, $false)
+ foreach ($principal in @($sid, $system)) {
+ $rule = if (($item -is [IO.DirectoryInfo])) {
+ [Security.AccessControl.FileSystemAccessRule]::new($principal, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
+ } else { [Security.AccessControl.FileSystemAccessRule]::new($principal, 'FullControl', 'Allow') }
+ $acl.AddAccessRule($rule)
+ }
+ if ($PSVersionTable.PSEdition -eq 'Core') { [IO.FileSystemAclExtensions]::SetAccessControl($item, $acl) } else { $item.SetAccessControl($acl) }
+ $acl = Get-Acl -LiteralPath $Path
+ }
+ if (($item -is [IO.DirectoryInfo]) -and -not $AllowInherited -and -not $acl.AreAccessRulesProtected) { Stop-Stack 'inherited private permissions' }
+ $allowed = $false
+ foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
+ if ($rule.AccessControlType -eq 'Allow') {
+ if ($rule.IdentityReference.Value -notin @($sid.Value, $system.Value)) { Stop-Stack 'shared kit permissions' }
+ if ($rule.IdentityReference.Value -eq $sid.Value) { $allowed = $true }
+ }
+ }
+ if (-not $allowed) { Stop-Stack 'missing owner access' }
+}
+function Assert-PosixMode([string]$Path, [string[]]$Modes = @()) {
+ $info = if ($IsMacOS) { & stat -f '%u %Lp' $Path } else { & stat -c '%u %a' -- $Path }
+ if ($LASTEXITCODE -ne 0) { Stop-Stack 'could not inspect kit permissions' }
+ $parts = $info.Trim().Split(' ')
+ if ($parts[0] -ne $script:Owner -or ($Modes.Count -gt 0 -and $parts[1] -notin $Modes)) { Stop-Stack 'kit must be private, owned and sealed' }
+}
+function Assert-Root {
+ $null = Assert-Item $root $true
+ if ($onWindows) { Assert-WindowsPrivate $root $false } else {
+ Assert-PosixMode $root @('700', '500')
+ $ancestor = [IO.Directory]::GetParent($root)
+ while ($ancestor) {
+ $null = Assert-Item $ancestor.FullName $true
+ $info = if ($IsMacOS) { & stat -f '%u %Lp' $ancestor.FullName } else { & stat -c '%u %a' -- $ancestor.FullName }
+ if ($LASTEXITCODE -ne 0) { Stop-Stack 'could not inspect private parent' }
+ $parts = $info.Trim().Split(' ')
+ $mode = [Convert]::ToInt32($parts[1], 8)
+ if ($parts[0] -notin @($script:Owner, '0') -or (($mode -band 18) -and -not ($mode -band 512))) {
+ Stop-Stack 'unsafe private parent permissions'
+ }
+ $ancestor = $ancestor.Parent
+ }
+ }
+}
+function Get-KitTree([string]$Directory) {
+ $queue = New-Object 'Collections.Generic.Queue[IO.FileSystemInfo]'
+ $queue.Enqueue((Assert-Item $Directory $true))
+ $count = 0
+ while ($queue.Count) {
+ $item = $queue.Dequeue()
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { Stop-Stack 'linked kit path' }
+ $count++
+ if ($count -gt [int]$pin.entries) { Stop-Stack 'kit tree exceeds entry limit' }
+ $item
+ if (($item -is [IO.DirectoryInfo])) {
+ foreach ($child in Get-ChildItem -LiteralPath $item.FullName -Force) { $queue.Enqueue($child) }
+ }
+ }
+}
+function Assert-Kit([string]$Directory) {
+ $tree = @(Get-KitTree $Directory)
+ $payload = @($tree | Where-Object { $_ -isnot [IO.DirectoryInfo] })
+ if ($tree.Count -ne [int]$pin.entries -or $payload.Count -ne [int]$pin.files) { Stop-Stack 'kit tree mismatch' }
+ foreach ($item in $tree) {
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { Stop-Stack 'linked kit path' }
+ if ($onWindows) {
+ Assert-WindowsPrivate $item.FullName $false
+ } else {
+ $modes = if (($item -is [IO.DirectoryInfo])) { @('500') } else { @('400', '500') }
+ Assert-PosixMode $item.FullName $modes
+ }
+ }
+ if (-not $onWindows) { Assert-PosixMode (Join-Path $Directory $pin.python) @('500') }
+ $inventory = Join-Path $Directory 'bootstrap.sha256'
+ $manifest = Join-Path $Directory 'tool.json'
+ if ((Get-Digest $inventory) -ne $pin.inventory -or (Get-Digest $manifest) -ne $pin.manifest) { Stop-Stack 'kit metadata checksum mismatch' }
+ $identity = [IO.File]::ReadAllText((Join-Path $Directory 'bootstrap.identity')).TrimEnd("`n")
+ if ($identity -cne "$target $StackSourceCommit $StackVersion $($pin.python) $($pin.modules)") { Stop-Stack 'kit identity mismatch' }
+ $json = [IO.File]::ReadAllText($manifest)
+ $body = if ($PSVersionTable.PSVersion.Major -ge 6) { $json | ConvertFrom-Json -AsHashtable } else { $json | ConvertFrom-Json }
+ $assets = [Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal)
+ if ($body.assets -is [Collections.IDictionary]) {
+ foreach ($asset in $body.assets.GetEnumerator()) { $assets.Add($asset.Key, $asset.Value) }
+ } elseif ($body.assets -is [pscustomobject]) {
+ foreach ($asset in $body.assets.PSObject.Properties) { $assets.Add($asset.Name, $asset.Value) }
+ } else { Stop-Stack 'invalid manifest assets type' }
+ foreach ($field in @('platform', 'arch', 'sourceCommit', 'python', 'moduleDir')) {
+ if ($body.$field -isnot [string]) { Stop-Stack 'invalid manifest identity type' }
+ }
+ if ($body.schemaVersion -isnot [ValueType] -or
+ $body.schemaVersion -is [bool] -or $body.schemaVersion -ne 1 -or "$($body.platform)-$($body.arch)" -cne $target -or
+ $body.sourceCommit -cne $StackSourceCommit -or $body.python -cne $pin.python -or $body.moduleDir -cne $pin.modules -or
+ -not $assets.ContainsKey($pin.python)) { Stop-Stack 'manifest target or source mismatch' }
+ $lines = [IO.File]::ReadAllLines($inventory)
+ $checks = [Collections.Generic.Dictionary[string,string]]::new([StringComparer]::Ordinal)
+ foreach ($line in $lines) {
+ if ($line -cnotmatch '^([a-f0-9]{64}) ([A-Za-z0-9_+./-]+)$') { Stop-Stack 'invalid checksum inventory' }
+ $expected = $Matches[1]; $relative = $Matches[2]
+ Assert-Relative $relative
+ if ($checks.ContainsKey($relative)) { Stop-Stack 'duplicate inventory path' }
+ $checks.Add($relative, $expected)
+ $file = Join-Path $Directory $relative
+ $null = Assert-Item $file $false
+ if ((Get-Digest $file) -cne $expected) { Stop-Stack 'kit payload checksum mismatch' }
+ }
+ if ($checks.Count -ne $payload.Count - 1 -or $assets.Count -ne $checks.Count - 2) { Stop-Stack 'manifest asset list mismatch' }
+ foreach ($asset in $assets.GetEnumerator()) {
+ if ($asset.Value -isnot [string] -or $asset.Key -in @('tool.json', 'bootstrap.identity', 'bootstrap.sha256') -or
+ -not $checks.ContainsKey($asset.Key) -or $asset.Value -cne $checks[$asset.Key]) {
+ Stop-Stack 'manifest asset checksum mismatch'
+ }
+ }
+}
+function Set-KitMode([string]$Directory) {
+ $tree = @(Get-KitTree $Directory)
+ foreach ($item in $tree) {
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { Stop-Stack 'linked kit path' }
+ if ($onWindows) {
+ Assert-WindowsPrivate $item.FullName $true
+ if (-not ($item -is [IO.DirectoryInfo])) { $item.IsReadOnly = $true }
+ } else {
+ $mode = if (($item -is [IO.DirectoryInfo])) { '500' } else { 'a-w,go-rwx' }
+ & chmod $mode -- $item.FullName
+ if ($LASTEXITCODE -ne 0) { Stop-Stack 'could not seal kit' }
+ }
+ }
+}
+function Assert-NpmUrl([string]$Url, [bool]$Redirect = $false) {
+ try { $uri = [uri]::new($Url, [UriKind]::Absolute) } catch {
+ throw [Net.WebException]::new('invalid npm URL')
+ }
+ $localFixture = -not $Redirect -and $uri.Scheme -eq 'http' -and $uri.IsLoopback -and
+ ($env:SIMPLEX_NPM_REGISTRY -or $env:LOCALMODELS_KIT_BASE_URL)
+ if (($uri.Scheme -ne 'https' -and -not $localFixture) -or $uri.UserInfo) {
+ throw [Net.WebException]::new('npm URL must use HTTPS without credentials')
+ }
+ return $uri.AbsoluteUri
+}
+function Get-RedirectUrl([string]$Base, [string]$Location, [int]$Hops) {
+ if ($Hops -ge 5 -or -not $Location) { throw [Net.WebException]::new('npm redirect limit or invalid target') }
+ try { $next = [uri]::new([uri]$Base, $Location).AbsoluteUri } catch {
+ throw [Net.WebException]::new('invalid npm redirect')
+ }
+ return Assert-NpmUrl $next $true
+}
+function Get-RegistryResponse([string]$Url) {
+ if ($PSVersionTable.PSVersion.Major -lt 6) {
+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
+ }
+ $Url = Assert-NpmUrl $Url
+ for ($hops = 0; $hops -le 5; $hops++) {
+ $request = [Net.WebRequest]::Create($Url)
+ $request.Timeout = 300000
+ $request.ReadWriteTimeout = 300000
+ $request.AllowAutoRedirect = $false
+ $response = $request.GetResponse()
+ if ([int]$response.StatusCode -notin @(301, 302, 303, 307, 308)) { return $response }
+ $location = $response.Headers['Location']
+ $response.Dispose()
+ $Url = Get-RedirectUrl $Url $location $hops
+ }
+}
+function Get-Archive([string]$Url, [string]$Destination) {
+ $response = $null; $inputStream = $null; $outputStream = $null
try {
- [Console]::Error.WriteLine("stack.ps1: downloading localmodels $StackVersion (source $StackSourceCommit, $target)")
- $archive = Join-Path $staging 'kit.tgz'
+ $response = Get-RegistryResponse $Url
+ if ($response.ContentLength -gt [long]$pin.bytes) { Stop-Stack 'archive size exceeds pin' }
+ $inputStream = $response.GetResponseStream()
+ $outputStream = [IO.File]::Open($Destination, 'CreateNew', 'Write', 'None')
+ if ($onWindows) { Assert-WindowsPrivate $Destination $true }
+ $buffer = New-Object byte[] 65536
+ $total = 0L
+ while (($count = $inputStream.Read($buffer, 0, $buffer.Length)) -gt 0) {
+ $total += $count
+ if ($total -gt [long]$pin.bytes) { Stop-Stack 'archive size exceeds pin' }
+ $outputStream.Write($buffer, 0, $count)
+ }
+ } finally {
+ if ($outputStream) { $outputStream.Dispose() }
+ if ($inputStream) { $inputStream.Dispose() }
+ if ($response) { $response.Dispose() }
+ }
+}
+function Get-NpmUrl([string]$Region) {
+ $base = if ($Region -eq 'cn') { 'https://registry.npmmirror.com' } else { 'https://registry.npmjs.org' }
+ if ($env:SIMPLEX_NPM_REGISTRY) { $base = $env:SIMPLEX_NPM_REGISTRY }
+ $name = "localmodels-$target"
+ return "$($base.TrimEnd('/'))/@simplexai/$name/-/$name-$StackNpmVersion.tgz"
+}
+function Resolve-Region {
+ if ($script:region -eq 'auto' -and $env:LOCALMODELS_KIT_BASE_URL) { $script:region = 'global' }
+ if ($script:region -eq 'auto') {
if ($PSVersionTable.PSVersion.Major -lt 6) {
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
}
+ Add-Type -AssemblyName System.Net.Http
+ $handler = [Net.Http.HttpClientHandler]::new()
+ $handler.AllowAutoRedirect = $false
+ $client = [Net.Http.HttpClient]::new($handler)
+ $client.Timeout = [TimeSpan]::FromSeconds(5)
+ $client.MaxResponseContentBufferSize = 262144
+ $client.DefaultRequestHeaders.Range = [Net.Http.Headers.RangeHeaderValue]::new(0, 262143)
+ $tasks = @{}; $urls = @{}; $hops = @{}; $timeouts = @{}
try {
- Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $archive
- } catch {
- Stop-Stack "download failed: $url"
- }
- $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $archive).Hash.ToLowerInvariant()
- if ($actual -ne $kit) {
- Stop-Stack "SHA256 mismatch for ${url}: expected $kit, got $actual"
- }
- $unpacked = Join-Path $staging 'kit'
- New-Item -ItemType Directory -Path $unpacked | Out-Null
- & tar -xzf $archive -C $unpacked
- if ($LASTEXITCODE -ne 0) { Stop-Stack "could not unpack $archive" }
- & (Join-Path $unpacked $python) -I -B (Join-Path $unpacked 'kit.py') prepare $unpacked
- if ($LASTEXITCODE -ne 0) { Stop-Stack 'the downloaded kit failed verification' }
- # Renamed here, after the kit's python exits: Windows cannot rename a running program's folder.
- try {
- [IO.Directory]::Move($unpacked, $final)
- } catch {
- if (-not (Test-Path -LiteralPath (Join-Path $final 'kit.py'))) { throw }
+ foreach ($candidate in @('global', 'cn')) {
+ $urls[$candidate] = Assert-NpmUrl (Get-NpmUrl $candidate)
+ $hops[$candidate] = 0
+ $timeouts[$candidate] = [Threading.CancellationTokenSource]::new(5000)
+ $tasks[$candidate] = $client.GetAsync($urls[$candidate], $timeouts[$candidate].Token)
+ }
+ $script:region = 'global'
+ while ($tasks.Count) {
+ $finished = [Threading.Tasks.Task]::WhenAny([Threading.Tasks.Task[]]@($tasks.Values)).GetAwaiter().GetResult()
+ $candidate = @($tasks.Keys | Where-Object { $tasks[$_] -eq $finished })[0]
+ if ($finished.Status -eq 'RanToCompletion') {
+ $response = $finished.Result
+ try {
+ if ($response.IsSuccessStatusCode) {
+ $script:region = $candidate
+ break
+ }
+ if ([int]$response.StatusCode -in @(301, 302, 303, 307, 308)) {
+ $urls[$candidate] = Get-RedirectUrl $urls[$candidate] "$($response.Headers.Location)" $hops[$candidate]
+ $hops[$candidate]++
+ $tasks[$candidate] = $client.GetAsync($urls[$candidate], $timeouts[$candidate].Token)
+ continue
+ }
+ } catch [Net.WebException] { } finally { $response.Dispose() }
+ }
+ $tasks.Remove($candidate)
+ }
+ } finally {
+ $client.CancelPendingRequests()
+ $client.Dispose()
+ foreach ($timeout in $timeouts.Values) { $timeout.Cancel(); $timeout.Dispose() }
+ }
+ }
+ $hostName = ([uri](Get-NpmUrl $script:region)).Authority
+ [Console]::Error.WriteLine("stack.ps1: using npm mirror $hostName ($script:region)")
+}
+function Remove-KitStage([string]$Path, [bool]$AllowLinks = $false) {
+ Assert-Root
+ $stageRoot = Assert-Item $Path $true
+ if ($stageRoot.Parent.FullName -cne $root -or
+ $stageRoot.Name -cnotmatch '\A\.staging\.[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\z') {
+ Stop-Stack 'unsafe staging path'
+ }
+ $tree = New-Object 'Collections.Generic.List[IO.FileSystemInfo]'
+ $tree.Add($stageRoot)
+ for ($index = 0; $index -lt $tree.Count; $index++) {
+ $item = $tree[$index]
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {
+ if (-not $AllowLinks) { Stop-Stack 'linked staging path' }
+ if ($onWindows) {
+ $owner = (Get-Acl -LiteralPath $item.FullName).GetOwner([Security.Principal.SecurityIdentifier]).Value
+ if ($owner -ne [Security.Principal.WindowsIdentity]::GetCurrent().User.Value) { Stop-Stack 'foreign staging owner' }
+ } else { Assert-PosixMode $item.FullName }
+ continue
+ }
+ if ($onWindows) { Assert-WindowsPrivate $item.FullName $false $true } else { Assert-PosixMode $item.FullName }
+ if ($item -is [IO.DirectoryInfo]) {
+ foreach ($child in Get-ChildItem -LiteralPath $item.FullName -Force) { $tree.Add($child) }
}
+ }
+ if (-not $onWindows) {
+ foreach ($item in $tree) {
+ if ($item -is [IO.DirectoryInfo] -and -not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
+ & chmod u+w -- $item.FullName
+ if ($LASTEXITCODE -ne 0) { Stop-Stack 'could not reopen staging directory' }
+ }
+ }
+ }
+ for ($index = $tree.Count - 1; $index -ge 0; $index--) {
+ $item = $tree[$index]
+ if ($item -is [IO.DirectoryInfo]) { [IO.Directory]::Delete($item.FullName) } else {
+ if ($onWindows -and -not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { $item.IsReadOnly = $false }
+ [IO.File]::Delete($item.FullName)
+ }
+ }
+}
+function Enter-KitLock([int]$Attempts, [int]$DelayMilliseconds) {
+ $lockPath = Join-Path $root ".lock-$kit"
+ for ($attempt = 0; $attempt -lt $Attempts; $attempt++) {
+ if ($onWindows) {
+ try {
+ return [IO.FileStream]::new($lockPath, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None, 1, [IO.FileOptions]::DeleteOnClose)
+ } catch [IO.IOException] { }
+ } else {
+ & mkdir -- $lockPath 2>$null
+ if ($LASTEXITCODE -eq 0) { return $true }
+ }
+ Start-Sleep -Milliseconds $DelayMilliseconds
+ }
+ Stop-Stack 'cache lock timeout'
+}
+function Exit-KitLock($Handle) {
+ if ($onWindows) { $Handle.Dispose() } else { [IO.Directory]::Delete((Join-Path $root ".lock-$kit")) }
+}
+function Remove-OperationStage {
+ if (-not (Test-Path -LiteralPath $root)) { return }
+ Assert-Root
+ $lockHandle = Enter-KitLock 50 100
+ try {
+ $stage = Join-Path $root ('.staging.' + $operationId)
+ if (Test-Path -LiteralPath $stage) { Remove-KitStage $stage }
+ } finally { Exit-KitLock $lockHandle }
+}
+function Install-Kit {
+ if (-not (Test-Path -LiteralPath $root)) { $null = [IO.Directory]::CreateDirectory($root) }
+ $null = Assert-Item $root $true
+ if ($onWindows) { Assert-WindowsPrivate $root $true } else {
+ Assert-PosixMode $root
+ & chmod 700 -- $root
+ if ($LASTEXITCODE -ne 0) { Stop-Stack 'could not protect cache root' }
+ }
+ Assert-Root
+ $lockHandle = $null; $stage = $null
+ try {
+ $lockHandle = Enter-KitLock 120 1000
+ try { Assert-Kit $final; return } catch { }
+ if (Test-Path -LiteralPath $final) {
+ $null = Assert-Item $final $true
+ if ($onWindows) { Assert-WindowsPrivate $final $true } else {
+ Assert-PosixMode $final
+ }
+ }
+ $stageId = if ($operationId) { $operationId } else { [Guid]::NewGuid().ToString('D') }
+ $candidate = Join-Path $root ('.staging.' + $stageId)
+ if (Test-Path -LiteralPath $candidate) { Stop-Stack 'operation staging path already exists' }
+ $stage = $candidate
+ $null = [IO.Directory]::CreateDirectory($stage)
+ if ($onWindows) { Assert-WindowsPrivate $stage $true } else { & chmod 700 -- $stage }
+ [Console]::Error.WriteLine("stack.ps1: downloading localmodels $StackVersion")
+ $archive = Join-Path $stage 'kit.tgz'
+ Resolve-Region
+ if ($env:LOCALMODELS_KIT_BASE_URL) {
+ Get-Archive "$($env:LOCALMODELS_KIT_BASE_URL.TrimEnd('/'))/$target.tgz" $archive
+ } else {
+ try { Get-Archive (Get-NpmUrl $script:region) $archive } catch [Net.WebException], [IO.IOException] {
+ if (Test-Path -LiteralPath $archive) { [IO.File]::Delete($archive) }
+ $script:region = if ($script:region -eq 'cn') { 'global' } else { 'cn' }
+ Get-Archive (Get-NpmUrl $script:region) $archive
+ }
+ }
+ if ((Get-Item -LiteralPath $archive).Length -ne [long]$pin.bytes -or (Get-Digest $archive) -cne $kit) { Stop-Stack 'archive SHA256 mismatch or size mismatch' }
+ $members = @(& tar -tvzf $archive 2>$null)
+ if ($LASTEXITCODE -ne 0 -or $members.Count -gt [int]$pin.entries) { Stop-Stack 'invalid kit archive' }
+ $sizeColumn = if ($onWindows -or $IsMacOS) { 4 } else { 2 }
+ $expandedSize = 0L
+ foreach ($member in $members) {
+ if ($member -notmatch '^[-d]') { Stop-Stack 'linked or special archive member' }
+ $fields = @($member -split '\s+')
+ $size = 0L
+ if (-not [long]::TryParse($fields[$sizeColumn], [ref]$size) -or $size -lt 0) { Stop-Stack 'invalid archive size' }
+ $expandedSize += $size
+ if ($expandedSize -gt 1073741824) { Stop-Stack 'kit archive exceeds extracted size limit' }
+ }
+ $names = @(& tar -tzf $archive 2>$null)
+ if ($LASTEXITCODE -ne 0) { Stop-Stack 'invalid kit archive' }
+ foreach ($name in $names) {
+ $relative = $name.TrimEnd('/')
+ Assert-Relative $relative
+ if (-not $relative.StartsWith('package/')) { Stop-Stack 'invalid npm package prefix' }
+ }
+ $unpacked = Join-Path $stage 'kit'
+ $null = [IO.Directory]::CreateDirectory($unpacked)
+ if ((Invoke-Native 'tar' @('-xzf', $archive, '--strip-components=1', '-C', $unpacked)) -ne 0) { Stop-Stack 'could not unpack kit' }
+ if (-not $onWindows) {
+ & chmod 755 -- (Join-Path $unpacked $pin.python) (Join-Path $unpacked 'kit.py')
+ if ($LASTEXITCODE -ne 0) { Stop-Stack 'could not restore executables' }
+ }
+ Set-KitMode $unpacked
+ Assert-Kit $unpacked
+ if (Test-Path -LiteralPath $final) {
+ if (-not $onWindows) { & chmod 700 -- $final }
+ [IO.Directory]::Move($final, (Join-Path $stage 'invalid'))
+ }
+ if (-not $onWindows) { & chmod 700 -- $unpacked }
+ [IO.Directory]::Move($unpacked, $final)
+ if (-not $onWindows) { & chmod 500 -- $final }
} finally {
- Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue
+ if ($stage -and (Test-Path -LiteralPath $stage)) {
+ try { Remove-KitStage $stage $true } catch { }
+ }
+ if ($lockHandle) { Exit-KitLock $lockHandle }
}
}
-if (-not (Test-Path -LiteralPath (Join-Path $final 'kit.py'))) { Install-Kit }
-$arguments = @($args)
-if ($arguments.Count -eq 0) { $arguments = @('--help') }
-& (Join-Path $final $python) -I -B (Join-Path $final 'kit.py') run stack @arguments
-exit $LASTEXITCODE
+try {
+ if (-not $StackVersion) { Stop-Stack 'this is the unpinned template; use a released launcher' }
+ $arguments = @($args)
+ $script:region = if ($env:SIMPLEX_REGION) { $env:SIMPLEX_REGION } else { 'auto' }
+ if ($arguments.Count -gt 0 -and $arguments[0] -in @('-Region', '--region')) {
+ if ($arguments.Count -lt 2) { Stop-Stack 'Region requires auto, global or cn' }
+ $script:region = $arguments[1]
+ $arguments = @($arguments | Select-Object -Skip 2)
+ }
+ if ($script:region -cnotin @('auto', 'global', 'cn')) { Stop-Stack 'Region requires auto, global or cn' }
+ $bootstrap = $arguments.Count -gt 0 -and $arguments[0] -ceq '--bootstrap-json'
+ $cleanup = $arguments.Count -gt 0 -and $arguments[0] -ceq '--bootstrap-cleanup'
+ $installedOnly = $false
+ $operationId = $null
+ if ($bootstrap -or $cleanup) {
+ if ($bootstrap -and $arguments.Count -eq 2 -and $arguments[1] -ceq '--installed-only') { $installedOnly = $true }
+ elseif ($arguments.Count -eq 3 -and $arguments[1] -ceq '--operation-id' -and
+ $arguments[2] -cmatch '\A[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\z') {
+ $operationId = $arguments[2]
+ } elseif (-not ($bootstrap -and $arguments.Count -eq 1)) { Stop-Stack 'invalid bootstrap control arguments' }
+ } elseif (@($arguments | Where-Object { $_ -match '^--(bootstrap-json|bootstrap-cleanup|installed-only|operation-id)(=|$)' }).Count) {
+ Stop-Stack 'invalid bootstrap control arguments'
+ }
+ $onWindows = $PSVersionTable.PSVersion.Major -lt 6 -or $IsWindows
+ if ($onWindows) {
+ if ($installedOnly) { Stop-Stack 'installed-only validation is unsupported on Windows' }
+ $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
+ $target = @{ AMD64 = 'win32-x64' }[$arch]
+ $cacheBase = $env:LOCALAPPDATA
+ } else {
+ $os = if ($IsMacOS) { 'darwin' } else { 'linux' }
+ $machine = (& uname -m).Trim()
+ $target = @{ x86_64 = "$os-x64"; amd64 = "$os-x64"; arm64 = "$os-arm64"; aarch64 = "$os-arm64" }[$machine]
+ $cacheBase = if ($env:XDG_CACHE_HOME) { $env:XDG_CACHE_HOME } else { Join-Path $HOME '.cache' }
+ $script:Owner = (& id -u).Trim()
+ }
+ if (-not $target -or -not $StackKits.ContainsKey($target)) { Stop-Stack 'release has no kit for this platform' }
+ $kit = $StackKits[$target]; $pin = $StackBootstrap[$target]
+ $root = if ($env:LOCALMODELS_KIT_HOME) { $env:LOCALMODELS_KIT_HOME } else { Join-Path $cacheBase 'linger-localmodels/kits' }
+ $root = [IO.Path]::GetFullPath($root)
+ $final = Join-Path $root $kit
+ if ($cleanup) { Remove-OperationStage; exit 0 }
+ $valid = $false
+ try { Assert-Root; Assert-Kit $final; $valid = $true } catch { }
+ if (-not $valid) {
+ if ($installedOnly) { Stop-Stack 'installed kit validation failed' }
+ Install-Kit
+ }
+ $env:SIMPLEX_REGION = $script:region
+ if ($bootstrap) {
+ $exitCode = Invoke-Native (Join-Path $final $pin.python) @('-I', '-B', (Join-Path $final 'kit.py'), 'describe', $StackVersion, $target, $StackSourceCommit, $kit, $pin.manifest, $pin.python, $pin.modules)
+ } else {
+ if ($arguments.Count -eq 0) { $arguments = @('--help') }
+ $exitCode = Invoke-Native (Join-Path $final $pin.python) (@('-I', '-B', (Join-Path $final 'kit.py'), 'run', 'stack') + $arguments)
+ }
+ exit $exitCode
+} catch {
+ $message = if ($_.Exception.Data['StackError']) { $_.Exception.Message } else { 'bootstrap validation or preparation failed' }
+ [Console]::Error.WriteLine("stack.ps1: $message")
+ exit 2
+}
diff --git a/scripts/installs/stack.sh b/scripts/installs/stack.sh
index d6dcfd28..541ff1ad 100755
--- a/scripts/installs/stack.sh
+++ b/scripts/installs/stack.sh
@@ -1,81 +1,336 @@
#!/bin/sh
-# `stack.sh ARGS` runs `localmodels stack ARGS` from the release pinned below. The first run
-# downloads that release's self-contained Python + localmodels kit, checks its SHA256 and every
-# file it lists, and caches it; later runs start offline. No system Python is needed.
-# The localmodels release process writes the pin; do not edit it by hand.
set -eu
# >>> release pin
-STACK_VERSION='0.1.0.dev28'
-STACK_SOURCE_COMMIT='c77bed6e5b65c30314d96dfe8dc9b7ab964c5332'
-STACK_BASE_URL='https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev28'
-STACK_KIT_darwin_arm64='abd3baeabd3d43bd4a4e5fc3694ed2456d5b32b3b8d0b3805856d9b0a57272c8'
-STACK_KIT_darwin_x64='c3aeb71c912948acb2fb8a4ef8a9f278d16a767d34323c655be83801ef1a8789'
-STACK_KIT_linux_arm64='feffffef4bdfff3d3aff4f248b1daaf804d5a238c3dc58560b42947cb2ecaa09'
-STACK_KIT_linux_x64='2923a04c83c88237814e753cfc3637bdc80545aa77defa669d8ff42cd85d6eb8'
+STACK_VERSION='0.1.0.dev31'
+STACK_SOURCE_COMMIT='531c092c88589aa261f0f8d82e60b94d8136f65b'
+STACK_NPM_VERSION='0.1.0-dev.31'
+STACK_KIT_darwin_arm64='7bcc62fbd4c15398577d2f328af79c3acc88644c208007870c5b19e87229ecf7'
+STACK_KIT_darwin_x64='7bf03622cac43a3b2bcbf66f7c59ccc7899b0d84287e4aab718a9bfb9be5ad3f'
+STACK_KIT_linux_arm64='dd0d821e1c1423134968328bf0de48f79d254895dad92d8a5be3bc79e9e6adcf'
+STACK_KIT_linux_x64='86a1d7ace3c82ecc3b3118fccdd2a91540223a8c3884cbac4d26c50c512852a3'
# <<< release pin
die() {
- printf 'stack.sh: %s\n' "$*" >&2
+ printf 'stack.sh: %s\n' "$1" >&2
exit 2
}
-[ -n "${STACK_VERSION}" ] ||
- die "this is the unpinned template; run the copy a release wrote to linger scripts/installs"
+[ -n "${STACK_VERSION}" ] || die 'this is the unpinned template; use a released launcher'
+region=${SIMPLEX_REGION:-auto}
+if [ "${1:-}" = --region ]; then
+ [ "$#" -ge 2 ] || die '--region requires auto, global or cn'
+ region=$2
+ shift 2
+fi
+case "$region" in auto | global | cn) ;; *) die '--region requires auto, global or cn' ;; esac
+bootstrap=false
+installed_only=false
+if [ "${1:-}" = --bootstrap-json ]; then
+ bootstrap=true
+ shift
+ if [ "${1:-}" = --installed-only ]; then installed_only=true; shift; fi
+ [ "$#" -eq 0 ] || die 'usage: --bootstrap-json [--installed-only]'
+elif [ "${1:-}" = --installed-only ]; then
+ die '--installed-only requires --bootstrap-json'
+fi
case "$(uname -s)-$(uname -m)" in
- Linux-x86_64 | Linux-amd64) target=linux-x64 kit=${STACK_KIT_linux_x64} ;;
- Linux-aarch64 | Linux-arm64) target=linux-arm64 kit=${STACK_KIT_linux_arm64} ;;
- Darwin-arm64) target=darwin-arm64 kit=${STACK_KIT_darwin_arm64} ;;
- Darwin-x86_64) target=darwin-x64 kit=${STACK_KIT_darwin_x64} ;;
- *) die "no localmodels kit for $(uname -s) $(uname -m); on Windows run stack.ps1" ;;
+ Linux-x86_64 | Linux-amd64) target=linux-x64; kit=${STACK_KIT_linux_x64} ;;
+ Linux-aarch64 | Linux-arm64) target=linux-arm64; kit=${STACK_KIT_linux_arm64} ;;
+ Darwin-arm64) target=darwin-arm64; kit=${STACK_KIT_darwin_arm64} ;;
+ Darwin-x86_64) target=darwin-x64; kit=${STACK_KIT_darwin_x64} ;;
+ *) die 'no localmodels kit for this platform; on Windows use stack.ps1' ;;
esac
[ -n "${kit}" ] || die "release ${STACK_VERSION} has no ${target} kit"
+manifest='' inventory='' bytes='' files='' entries='' python='' modules=''
+# >>> bootstrap targets
+case "$target" in
+ darwin-arm64) manifest='6ddca9a017727abcc472ce491a12b4d8bc6955b909297ae777dee90b187677b7'; inventory='a18823b294727757d3db8fb2625faf34b8606a88f2d3061ddf5978e6cc2738c6'; bytes='40736176'; files='1867'; entries='2031'; python='python/bin/python3.12'; modules='modules' ;;
+ darwin-x64) manifest='13c86430d1d78829a5a6f4fcc7b34006fa840b5a36fb603729e28e72760c707a'; inventory='74e0f22297176839d122ee74346989544a02da07f85b9dcb4a8925f9c6a466f5'; bytes='40216514'; files='1864'; entries='2027'; python='python/bin/python3.12'; modules='modules' ;;
+ linux-arm64) manifest='2de0e3506bf51667850cd2cae0875072102171185e88f9e0040141a5360200d9'; inventory='928f37183944753ad43b6f4818a3fae858b5413dd9dbcb43968c6221524b26c5'; bytes='55686495'; files='4738'; entries='4945'; python='python/bin/python3.12'; modules='modules' ;;
+ linux-x64) manifest='820efa2d5645c49c0e677818e9b11748d29124528518f1b877ac3b2f37821633'; inventory='245d6eb7508cf9354067690c18ed8a1f6acfbdad3c7911f6577f3d775aff1b04'; bytes='68881199'; files='4738'; entries='4945'; python='python/bin/python3.12'; modules='modules' ;;
+ *) die 'release lacks bootstrap pins' ;;
+esac
+# <<< bootstrap targets
+[ -n "$inventory" ] || die 'release lacks bootstrap pins'
-# Kits are keyed by archive SHA256, so a new pin never reuses an older kit.
root=${LOCALMODELS_KIT_HOME:-${XDG_CACHE_HOME:-${HOME}/.cache}/linger-localmodels/kits}
-final=${root}/${kit}
+case "$root" in /*) ;; *) root=$PWD/$root ;; esac
+while [ "$root" != / ] && [ "${root%/}" != "$root" ]; do root=${root%/}; done
+final=$root/$kit
+owner=$(id -u)
+staging=''
+lock=''
+child=''
+
+cleanup() {
+ if [ -n "$child" ]; then kill "$child" 2>/dev/null || :; wait "$child" 2>/dev/null || :; fi
+ if [ -n "$staging" ]; then
+ find "$staging" -type d -user "$owner" -exec chmod 0700 {} + 2>/dev/null || :
+ rm -rf "$staging" 2>/dev/null || printf 'stack.sh: staging cleanup failed\n' >&2
+ fi
+ if [ -n "$lock" ]; then rmdir "$lock" 2>/dev/null || :; fi
+}
+trap cleanup EXIT
+trap 'exit 130' INT
+trap 'exit 143' TERM
-sha256_of() {
+sha256_of() (
+ if [ "$1" != - ]; then exec < "$1"; fi
if command -v sha256sum >/dev/null 2>&1; then
- sha256sum "$1" | cut -d ' ' -f 1
+ sha256sum | cut -d ' ' -f 1
elif command -v shasum >/dev/null 2>&1; then
- shasum -a 256 "$1" | cut -d ' ' -f 1
+ shasum -a 256 | cut -d ' ' -f 1
else
- die "sha256sum or shasum is required"
+ die 'sha256sum or shasum is required'
fi
+)
+
+private_root() {
+ [ -d "$root" ] && [ ! -L "$root" ] &&
+ [ -z "$(find "$root" -prune \( ! -user "$owner" -o -perm -0040 -o -perm -0020 -o -perm -0010 -o -perm -0004 -o -perm -0002 -o -perm -0001 \) -print)" ] || return 1
+ ancestor=$(dirname "$root")
+ while :; do
+ [ ! -L "$ancestor" ] || return 1
+ bad_parent=$(find "$ancestor" -prune \( \( ! -user "$owner" ! -user 0 \) -o \( \( -perm -0020 -o -perm -0002 \) ! -perm -1000 \) \) -print) || return 1
+ [ -z "$bad_parent" ] || return 1
+ [ "$ancestor" != / ] || break
+ ancestor=$(dirname "$ancestor")
+ done
}
-fetch() {
+verify_tree() (
+ directory=$1
+ [ -d "$directory" ] && [ ! -L "$directory" ] || exit 1
+ bad=$(find "$directory" \( ! -user "$owner" -o ! \( -type d -o -type f \) -o \( -type d ! -perm 0500 \) -o \( -type f ! \( -perm 0400 -o -perm 0500 \) \) -o \( -type f -links +1 \) \) -print) || exit 1
+ [ -z "$bad" ] || exit 1
+ [ -x "$directory/$python" ] || exit 1
+ [ "$(find "$directory" -type f | wc -l | tr -d ' ')" = "$files" ] || exit 1
+ [ "$(find "$directory" | wc -l | tr -d ' ')" = "$entries" ] || exit 1
+ [ "$(sha256_of "$directory/bootstrap.sha256")" = "$inventory" ] || exit 1
+ [ "$(sha256_of "$directory/tool.json")" = "$manifest" ] || exit 1
+ [ "$(cat "$directory/bootstrap.identity")" = "$target $STACK_SOURCE_COMMIT $STACK_VERSION $python $modules" ] || exit 1
+ platform=${target%-*}
+ arch=${target##*-}
+ prefix="{\"schemaVersion\":1,\"platform\":\"$platform\",\"arch\":\"$arch\",\"sourceCommit\":\"$STACK_SOURCE_COMMIT\",\"python\":\"$python\",\"moduleDir\":\"$modules\""
+ reconstructed=$(LC_ALL=C awk -v prefix="$prefix" '
+ BEGIN {printf "%s,\"assets\":{", prefix}
+ $2!="tool.json" && $2!="bootstrap.identity" {
+ if(n++) printf ","
+ printf "\"%s\":\"%s\"", $2, $1
+ }
+ END {printf "}}"}
+ ' "$directory/bootstrap.sha256" | sha256_of -)
+ [ "$reconstructed" = "$manifest" ] || exit 1
+ cd "$directory"
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum -c bootstrap.sha256 >/dev/null 2>&1
+ else
+ shasum -a 256 -c bootstrap.sha256 >/dev/null 2>&1
+ fi
+) 2>/dev/null
+
+curl_protocol() {
+ case "$1" in
+ http://127.0.0.1:* | http://localhost:*)
+ if [ -n "${SIMPLEX_NPM_REGISTRY:-}${LOCALMODELS_KIT_BASE_URL:-}" ]; then
+ printf '=http,https'
+ return
+ fi ;;
+ esac
+ printf '=https'
+}
+
+select_downloader() {
if command -v curl >/dev/null 2>&1; then
- curl -fsSL --retry 3 -o "$2" "$1"
- elif command -v wget >/dev/null 2>&1; then
- wget -q -O "$2" "$1"
+ downloader=curl
+ return
+ fi
+ downloader=wget
+ wget_requirement='curl or GNU Wget is required; BusyBox wget cannot restrict redirects to HTTPS (on Alpine: apk add curl)'
+ wget_version=$(wget --version 2>/dev/null) || wget_version=''
+ case "$wget_version" in *'GNU Wget'*) ;; *) die "$wget_requirement" ;; esac
+ wget_help=$(wget --help 2>/dev/null) || wget_help=''
+ for wget_option in --https-only --max-redirect --server-response --ca-certificate; do
+ case "$wget_help" in *"$wget_option"*) ;; *) die "$wget_requirement" ;; esac
+ done
+}
+
+wget_secure() {
+ wget_url=$1 wget_output=$2 wget_timeout=$3 wget_range=${4:-}
+ wget_hops=0 wget_child=''
+ wget_headers=$(mktemp "$staging/.wget-headers.XXXXXX") || return 1
+ trap 'if [ -n "$wget_child" ]; then kill "$wget_child" 2>/dev/null || :; wait "$wget_child" 2>/dev/null || :; fi; rm -f "$wget_headers"' EXIT
+ trap 'exit 143' TERM
+ trap 'exit 130' INT
+ while :; do
+ case "$wget_url" in
+ https://*) ;;
+ http://127.0.0.1:* | http://localhost:*) [ "$wget_hops" -eq 0 ] && [ "$(curl_protocol "$wget_url")" = '=http,https' ] || return 1 ;;
+ *) return 1 ;;
+ esac
+ wget_authority=${wget_url#*://}; wget_authority=${wget_authority%%/*}
+ case "$wget_authority" in *@*) return 1 ;; esac
+ set -- --https-only --max-redirect=0 --server-response --tries=1 --timeout="$wget_timeout" -O "$wget_output"
+ if [ -n "${SSL_CERT_FILE:-}" ]; then set -- --ca-certificate "$SSL_CERT_FILE" "$@"; fi
+ if [ "$wget_range" = range ]; then set -- --header='Range: bytes=0-262143' "$@"; fi
+ wget "$@" "$wget_url" 2>"$wget_headers" &
+ wget_child=$! wget_status=0
+ wait "$wget_child" || wget_status=$?
+ wget_child=''
+ [ "$wget_status" -ne 0 ] || return 0
+ wget_code=$(LC_ALL=C awk '/^[[:space:]]*HTTP\// {code=$2} END {print code}' "$wget_headers")
+ case "$wget_code" in 301 | 302 | 303 | 307 | 308) ;; *) return "$wget_status" ;; esac
+ [ "$wget_hops" -lt 5 ] || return 1
+ wget_location=$(LC_ALL=C awk 'tolower($1)=="location:" {sub(/^[^:]*:[[:space:]]*/, ""); sub(/\r$/, ""); target=$0} END {print target}' "$wget_headers")
+ case "$wget_location" in
+ https://*) wget_url=$wget_location ;;
+ //*) wget_url=https:$wget_location ;;
+ /*) wget_url=$(printf '%s' "$wget_url" | cut -d / -f 1-3)$wget_location ;;
+ *://* | '') return 1 ;;
+ *) wget_url=${wget_url%/*}/$wget_location ;;
+ esac
+ wget_hops=$((wget_hops + 1))
+ done
+}
+
+fetch() {
+ if [ "$downloader" = curl ]; then
+ (ulimit -f "$(( (bytes + 511) / 512 ))"; exec curl -q -fsSL --proto "$(curl_protocol "$1")" --proto-redir '=https' --max-redirs 5 --retry 2 --connect-timeout 15 --max-time 300 --max-filesize "$bytes" -o "$2" "$1") 2>/dev/null &
else
- die "curl or wget is required"
+ (ulimit -f "$(( (bytes + 511) / 512 ))"; wget_secure "$1" "$2" 300) 2>/dev/null &
fi
+ child=$!
+ status=0
+ wait "$child" || status=$?
+ child=''
+ return "$status"
+}
+
+npm_url() {
+ case "$1" in
+ cn) base=https://registry.npmmirror.com ;;
+ global) base=https://registry.npmjs.org ;;
+ esac
+ base=${SIMPLEX_NPM_REGISTRY:-$base}
+ name=localmodels-$target
+ printf '%s/@simplexai/%s/-/%s-%s.tgz\n' "${base%/}" "$name" "$name" "$STACK_NPM_VERSION"
+}
+
+probe() (
+ if [ "$downloader" = curl ]; then
+ url=$(npm_url "$1")
+ curl -q -fsSL --proto "$(curl_protocol "$url")" --proto-redir '=https' --max-redirs 5 --range 0-262143 --max-time 5 -o /dev/null "$url" 2>/dev/null || exit 0
+ else
+ wget_secure "$(npm_url "$1")" /dev/null 5 range 2>/dev/null || exit 0
+ fi
+ if mkdir "$staging/winner" 2>/dev/null; then printf '%s\n' "$1" > "$staging/winner/region"; fi
+)
+
+resolve_region() {
+ if [ "$region" = auto ] && [ -n "${LOCALMODELS_KIT_BASE_URL:-}" ]; then region=global; fi
+ if [ "$region" = auto ]; then
+ probe global & global_probe=$!
+ probe cn & cn_probe=$!
+ (sleep 5; kill "$global_probe" "$cn_probe" 2>/dev/null || :) & probe_timer=$!
+ wait "$global_probe" || :
+ wait "$cn_probe" || :
+ kill "$probe_timer" 2>/dev/null || :
+ wait "$probe_timer" 2>/dev/null || :
+ region=global
+ if [ -f "$staging/winner/region" ]; then region=$(cat "$staging/winner/region"); fi
+ fi
+ printf 'stack.sh: using npm mirror %s (%s)\n' "$(npm_url "$region" | cut -d / -f 3)" "$region" >&2
}
install_kit() {
- # LOCALMODELS_KIT_BASE_URL serves the same files from a mirror; the pinned SHA256 still applies.
- url=${LOCALMODELS_KIT_BASE_URL:-${STACK_BASE_URL}}/${target}.tgz
- mkdir -p "${root}"
- staging=$(mktemp -d "${root}/.staging.XXXXXX")
- trap 'rm -rf "${staging}"' EXIT
- trap 'exit 130' INT TERM
- printf 'stack.sh: downloading localmodels %s (source %s, %s)\n' \
- "${STACK_VERSION}" "${STACK_SOURCE_COMMIT}" "${target}" >&2
- fetch "${url}" "${staging}/kit.tgz" || die "download failed: ${url}"
- actual=$(sha256_of "${staging}/kit.tgz")
- [ "${actual}" = "${kit}" ] || die "SHA256 mismatch for ${url}: expected ${kit}, got ${actual}"
- mkdir "${staging}/kit"
- tar -xzf "${staging}/kit.tgz" -C "${staging}/kit"
- "${staging}/kit/python/bin/python3" -I -B "${staging}/kit/kit.py" activate \
- "${staging}/kit" "${final}" || die "the downloaded kit failed verification"
- rm -rf "${staging}"
- trap - EXIT INT TERM
+ umask 077
+ if [ ! -e "$root" ] && [ ! -L "$root" ]; then
+ mkdir -p "$root" 2>/dev/null || die 'could not create cache root'
+ fi
+ # shellcheck disable=SC2015 # die exits, so "A && B || die" is a guard
+ [ -d "$root" ] && [ ! -L "$root" ] &&
+ [ -z "$(find "$root" -prune ! -user "$owner" -print)" ] || die 'cache root must be an owned directory'
+ chmod 0700 "$root" 2>/dev/null || die 'could not protect cache root'
+ private_root || die 'cache root must be a private owned directory'
+ attempts=0
+ while ! mkdir "$root/.lock-$kit" 2>/dev/null; do
+ attempts=$((attempts + 1))
+ [ "$attempts" -lt 120 ] || die 'cache lock timeout; retry after the other bootstrap exits'
+ sleep 1 &
+ child=$!
+ wait "$child"
+ child=''
+ done
+ lock=$root/.lock-$kit
+ if verify_tree "$final"; then return; fi
+ if [ -e "$final" ] || [ -L "$final" ]; then
+ # shellcheck disable=SC2015 # die exits, so "A && B || die" is a guard
+ [ -d "$final" ] && [ ! -L "$final" ] || die 'cache kit must be an owned directory'
+ [ -z "$(find "$final" -prune ! -user "$owner" -print)" ] || die 'cache kit must be an owned directory'
+ fi
+ staging=$(mktemp -d "$root/.staging.XXXXXX") || die 'could not create staging directory'
+ select_downloader
+ printf 'stack.sh: downloading localmodels %s\n' "$STACK_VERSION" >&2
+ resolve_region
+ if [ -n "${LOCALMODELS_KIT_BASE_URL:-}" ]; then
+ fetch "${LOCALMODELS_KIT_BASE_URL%/}/${target}.tgz" "$staging/kit.tgz" || die 'download failed'
+ elif ! fetch "$(npm_url "$region")" "$staging/kit.tgz"; then
+ if [ "$region" = cn ]; then region=global; else region=cn; fi
+ fetch "$(npm_url "$region")" "$staging/kit.tgz" || die 'download failed from both npm registries'
+ fi
+ # shellcheck disable=SC2015 # die exits, so "A && B || die" is a guard
+ [ "$(wc -c < "$staging/kit.tgz" | tr -d ' ')" = "$bytes" ] &&
+ [ "$(sha256_of "$staging/kit.tgz")" = "$kit" ] || die 'archive SHA256 mismatch or size mismatch'
+ tar -tzf "$staging/kit.tgz" > "$staging/names" 2>/dev/null || die 'invalid kit archive'
+ LC_ALL=C awk '
+ !/^package\// {exit 1}
+ /[^A-Za-z0-9_.+\/-]/ {exit 1}
+ /^\// {exit 1}
+ {sub(/\/$/, ""); n=split($0,p,"/"); for(i=1;i<=n;i++)
+ if(p[i]=="" || p[i]=="." || p[i]==".." || p[i]~/\.$/ ||
+ tolower(p[i])~/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/) exit 1}
+ ' "$staging/names" || die 'unsafe kit archive path'
+ tar -tvzf "$staging/kit.tgz" > "$staging/members" 2>/dev/null || die 'invalid kit archive'
+ LC_ALL=C awk 'substr($0,1,1)!="-" && substr($0,1,1)!="d" {exit 1}' "$staging/members" || die 'linked or special kit archive member'
+ size_column=3
+ [ "$(uname -s)" != Darwin ] || size_column=5
+ LC_ALL=C awk -v column="$size_column" '
+ $column !~ /^[0-9]+$/ {exit 1}
+ {size+=$column; if(size>1073741824) exit 1}
+ ' "$staging/members" || die 'kit archive exceeds extracted size limit'
+ mkdir "$staging/kit" 2>/dev/null || die 'could not create kit directory'
+ tar -xzf "$staging/kit.tgz" --strip-components=1 -C "$staging/kit" 2>/dev/null &
+ child=$!
+ wait "$child" || die 'could not unpack kit'
+ child=''
+ chmod 0755 "$staging/kit/$python" "$staging/kit/kit.py" 2>/dev/null || die 'could not restore executables'
+ find "$staging/kit" -type f -exec chmod a-w,go-rwx {} + 2>/dev/null || die 'could not seal kit files'
+ find "$staging/kit" -type d -exec chmod 0500 {} + 2>/dev/null || die 'could not seal kit directories'
+ verify_tree "$staging/kit" || die 'downloaded kit failed verification'
+ if [ -e "$final" ]; then
+ chmod u+w "$final" 2>/dev/null || die 'could not reopen damaged kit'
+ mv "$final" "$staging/invalid" 2>/dev/null || die 'could not quarantine damaged kit'
+ fi
+ chmod 0700 "$staging/kit" 2>/dev/null || die 'could not prepare kit activation'
+ mv "$staging/kit" "$final" 2>/dev/null || die 'could not activate kit'
+ chmod 0500 "$final" 2>/dev/null || die 'could not seal activated kit'
}
-[ -f "${final}/kit.py" ] || install_kit
+if ! private_root || ! verify_tree "$final"; then
+ "$installed_only" && die 'installed kit validation failed'
+ install_kit
+fi
+cleanup
+staging=''
+lock=''
+SIMPLEX_REGION=$region
+export SIMPLEX_REGION
+final=$(cd "$final" && pwd -P) || die 'could not resolve verified kit location'
+if "$bootstrap"; then
+ exec "$final/$python" -I -B "$final/kit.py" describe "$STACK_VERSION" "$target" \
+ "$STACK_SOURCE_COMMIT" "$kit" "$manifest" "$python" "$modules"
+fi
[ "$#" -gt 0 ] || set -- --help
-exec "${final}/python/bin/python3" -I -B "${final}/kit.py" run stack "$@"
+exec "$final/$python" -I -B "$final/kit.py" run stack "$@"