@simplexai/localmodels-linux-x64 0.1.0-dev.43 → 0.1.0-dev.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +39 -38
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/auth_proxy.py +285 -82
  5. package/modules/localmodels/bifrost_models.py +9 -2
  6. package/modules/localmodels/bifrost_provider.py +42 -7
  7. package/modules/localmodels/debug_mode.py +2 -18
  8. package/modules/localmodels/engines.py +19 -6
  9. package/modules/localmodels/gateway_bifrost.py +10 -1
  10. package/modules/localmodels/harness.py +3 -1
  11. package/modules/localmodels/library_convert.py +491 -57
  12. package/modules/localmodels/library_gateway.py +15 -7
  13. package/modules/localmodels/library_pricing.py +159 -31
  14. package/modules/localmodels/library_status.py +29 -4
  15. package/modules/localmodels/probe.py +42 -9
  16. package/modules/localmodels/runtime_args.py +2 -1
  17. package/modules/localmodels/runtime_auth.py +75 -25
  18. package/modules/localmodels/runtime_cli.py +9 -9
  19. package/modules/localmodels/runtime_install.py +55 -22
  20. package/modules/localmodels/runtime_io.py +76 -210
  21. package/modules/localmodels/runtime_process.py +15 -7
  22. package/modules/localmodels/runtime_windows_acl.py +196 -0
  23. package/modules/localmodels/source_byok.py +116 -30
  24. package/modules/localmodels/source_byok_probe.py +57 -141
  25. package/modules/localmodels/source_cli.py +11 -17
  26. package/modules/localmodels/stack.py +12 -1
  27. package/modules/localmodels/stack_client_settings.py +8 -1
  28. package/modules/localmodels/stack_compose.py +1 -0
  29. package/modules/localmodels/stack_route.py +1 -5
  30. package/modules/localmodels/stack_up.py +20 -1
  31. package/modules/localmodels/vision.py +2 -1
  32. package/modules/localmodels/web/view/view.css +1 -1
  33. package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/METADATA +1 -1
  34. package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/RECORD +36 -35
  35. package/package.json +1 -1
  36. package/tool.json +1 -1
  37. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/WHEEL +0 -0
  38. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/entry_points.txt +0 -0
  39. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/licenses/NOTICE +0 -0
  40. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -257,11 +257,12 @@ def inspect_runtimes(
257
257
  node: str | None = None,
258
258
  launcher: str | None = None,
259
259
  before_versions: dict[str, str] | None = None,
260
+ runtimes: tuple[str, ...] | None = None,
260
261
  ) -> dict[str, Any]:
261
262
  """Read-only local native status; auth output and key material remain private."""
262
263
  validate_runtime_root(root)
263
264
  rows: list[dict[str, Any]] = []
264
- for runtime in RUNTIMES:
265
+ for runtime in RUNTIMES if runtimes is None else runtimes:
265
266
  before_version = (before_versions or {}).get(runtime)
266
267
  explicit = os.environ.get(f"SIMPLEX_{runtime.upper()}_PATH")
267
268
  hosts = (
@@ -396,13 +397,9 @@ def build_plan(
396
397
  raise ValueError("Unknown runtime")
397
398
  if before_version is not None:
398
399
  _stable_version(before_version)
399
- status = next(
400
- row
401
- for row in inspect_runtimes(
402
- root, before_versions={runtime: before_version} if before_version is not None else None
403
- )["runtimes"]
404
- if row["runtime"] == runtime
405
- )
400
+ before = {runtime: before_version} if before_version is not None else None
401
+ rows = inspect_runtimes(root, before_versions=before, runtimes=(runtime,))["runtimes"]
402
+ status = next(row for row in rows if row["runtime"] == runtime)
406
403
  if os.environ.get(f"SIMPLEX_{runtime.upper()}_PATH") is not None and status["executable"]:
407
404
  if not _compatible_version(runtime, status["version"], before_version=before_version):
408
405
  raise ValueError(
@@ -680,7 +677,10 @@ def _act(args: argparse.Namespace) -> dict[str, Any]:
680
677
  "authenticated": True,
681
678
  }
682
679
  elif args.harness_action == "status":
683
- value = inspect_runtimes(args.root, node=args.node, launcher=args.launcher)
680
+ selected = (args.runtime,) if args.runtime else None
681
+ value = inspect_runtimes(
682
+ args.root, node=args.node, launcher=args.launcher, runtimes=selected
683
+ )
684
684
  if args.runtime:
685
685
  value["runtimes"] = [row for row in value["runtimes"] if row["runtime"] == args.runtime]
686
686
  elif args.harness_action == "plan":
@@ -38,6 +38,7 @@ def downloads_dir(root: Path, runtime: str) -> Path:
38
38
 
39
39
 
40
40
  MODULE_DOWNLOADS = 8 # Pi's dependency tree is ~120 small tarballs; one at a time takes minutes
41
+ MODULE_EXTRACTS = 8 # Unpack independent verified archives in parallel into private staging dirs
41
42
 
42
43
 
43
44
  def fetch_all(
@@ -141,6 +142,39 @@ def take(kept: Path, file: Path) -> None:
141
142
  private_permissions(file, created=True)
142
143
 
143
144
 
145
+ def _run_extract_jobs(jobs: list[Callable[[], None]]) -> None:
146
+ if len(jobs) <= 1:
147
+ for job in jobs:
148
+ job()
149
+ return
150
+ pool = ThreadPoolExecutor(min(MODULE_EXTRACTS, len(jobs)))
151
+ try:
152
+ futures = [pool.submit(job) for job in jobs]
153
+ for future in as_completed(futures):
154
+ future.result()
155
+ finally:
156
+ pool.shutdown(wait=True, cancel_futures=True)
157
+
158
+
159
+ def _place_unpacked(tree: Path, unpacked: list[tuple[int, dict[str, Any], Path]]) -> None:
160
+ for _, artifact, unpack in unpacked:
161
+ if not artifact.get("destination"):
162
+ for entry in unpack.iterdir():
163
+ entry.rename(tree / entry.name)
164
+ modules = sorted(
165
+ (item for item in unpacked if item[1].get("destination")),
166
+ key=lambda item: (len(Path(item[1]["destination"]).parts), item[0]),
167
+ )
168
+ verified_parents: set[Path] = {tree}
169
+ for _, artifact, unpack in modules:
170
+ (top,) = unpack.iterdir() # npm drops the archive's one top directory
171
+ target = tree / artifact["destination"]
172
+ if target.parent not in verified_parents:
173
+ private_directory(target.parent)
174
+ verified_parents.add(target.parent)
175
+ top.rename(target)
176
+
177
+
144
178
  def install_tree(
145
179
  plan: dict[str, Any],
146
180
  stage: Path,
@@ -151,33 +185,32 @@ def install_tree(
151
185
  tree = stage / "t" # short: see apply_plan
152
186
  private_directory(tree)
153
187
  fetched = fetch_all(plan, event, download_fn=download_fn)
154
- for index, artifact in enumerate(plan["artifacts"]):
155
- file = stage / f"artifact-{index}"
156
- take(fetched[index], file)
188
+ if plan["artifacts"]:
157
189
  event({"kind": "stage", "stage": "extract", "state": "running"})
190
+ unpacked: list[tuple[int, dict[str, Any], Path]] = []
191
+ jobs: list[Callable[[], None]] = []
192
+ for index, artifact in enumerate(plan["artifacts"]):
193
+ source = fetched[index]
158
194
  if artifact["format"] == "binary":
159
- shutil.copyfile(file, tree / artifact["executable"])
160
- (tree / artifact["executable"]).chmod(0o700)
161
- private_permissions(tree / artifact["executable"], created=True)
195
+ destination = tree / artifact["executable"]
196
+ shutil.copyfile(source, destination)
197
+ destination.chmod(0o700)
198
+ private_permissions(destination, created=True)
162
199
  else:
163
- unpack = stage / f"unpack-{index}"
164
- extract_archive(file, unpack)
165
- if artifact.get("destination"): # a module of Pi's dependency tree
166
- (top,) = unpack.iterdir() # npm drops the archive's one top directory
167
- target = tree / artifact["destination"]
168
- private_directory(target.parent)
169
- top.rename(target)
170
- else:
171
- for entry in unpack.iterdir():
172
- entry.rename(tree / entry.name)
200
+ unpack = stage / f"u{index}"
201
+ unpacked.append((index, artifact, unpack))
202
+ jobs.append(partial(extract_archive, source, unpack))
173
203
  if plan.get("nodeArtifact"):
174
- node_archive = stage / "node-archive"
175
- take(fetched[-2], node_archive)
176
- extract_binary(
177
- node_archive,
178
- plan["nodeArtifact"]["member"],
179
- tree / ("node.exe" if os.name == "nt" else "node"),
204
+ jobs.append(
205
+ partial(
206
+ extract_binary,
207
+ fetched[-2],
208
+ plan["nodeArtifact"]["member"],
209
+ tree / ("node.exe" if os.name == "nt" else "node"),
210
+ )
180
211
  )
212
+ _run_extract_jobs(jobs)
213
+ _place_unpacked(tree, unpacked)
181
214
  if plan.get("launcherArtifact"):
182
215
  take(fetched[-1], tree / "pi.exe")
183
216
  for item in plan["bootstrap"]:
@@ -24,7 +24,7 @@ from pathlib import Path
24
24
  from typing import Any, cast
25
25
 
26
26
  # remote_ops before remote_ops_download: the bundle's entry module loads its siblings
27
- from localmodels import region, remote_ops, remote_ops_download
27
+ from localmodels import region, remote_ops, remote_ops_download, runtime_windows_acl
28
28
 
29
29
  Event = Callable[[dict[str, Any]], None]
30
30
 
@@ -53,8 +53,8 @@ def validate_runtime_root(root: Path) -> Path:
53
53
  return root
54
54
 
55
55
 
56
- def private_directory(path: Path) -> None:
57
- """Create each missing directory privately; existing state must already be private."""
56
+ def _create_private_directory(path: Path) -> bool:
57
+ """Create missing directories privately; return True when ``path`` itself was created."""
58
58
  if not path.is_absolute() or any(part == ".." for part in path.parts):
59
59
  raise ValueError("Runtime directory must be absolute and normalized")
60
60
  regular_directories(path)
@@ -65,14 +65,23 @@ def private_directory(path: Path) -> None:
65
65
  current = current.parent
66
66
  if not missing:
67
67
  private_permissions(path)
68
- return
68
+ return False
69
+ created = False
69
70
  for directory in reversed(missing):
70
71
  try:
71
72
  directory.mkdir(mode=0o700)
72
73
  except FileExistsError:
73
74
  private_permissions(directory)
75
+ created = False
74
76
  else:
75
77
  private_permissions(directory, created=True)
78
+ created = True
79
+ return created
80
+
81
+
82
+ def private_directory(path: Path) -> None:
83
+ """Create each missing directory privately; existing state must already be private."""
84
+ _create_private_directory(path)
76
85
 
77
86
 
78
87
  def private_permissions(path: Path, *, created: bool = False) -> None:
@@ -96,199 +105,10 @@ def private_permissions(path: Path, *, created: bool = False) -> None:
96
105
  raise ValueError("Existing runtime state must already be private")
97
106
 
98
107
 
99
- def _windows_api() -> tuple[Any, Any]:
100
- import ctypes
101
-
102
- load: Any = vars(ctypes)["WinDLL"]
103
- api, kernel = load("advapi32", use_last_error=True), load("kernel32", use_last_error=True)
104
- pointer, integer = ctypes.c_void_p, ctypes.c_uint
105
- out = ctypes.POINTER(pointer)
106
- signatures = {
107
- "OpenProcessToken": [pointer, integer, out],
108
- "GetTokenInformation": [pointer, integer, pointer, integer, ctypes.POINTER(integer)],
109
- "GetNamedSecurityInfoW": [ctypes.c_wchar_p, integer, integer, out, out, out, out, out],
110
- "SetNamedSecurityInfoW": [
111
- ctypes.c_wchar_p,
112
- integer,
113
- integer,
114
- pointer,
115
- pointer,
116
- pointer,
117
- pointer,
118
- ],
119
- "EqualSid": [pointer, pointer],
120
- "ConvertSidToStringSidW": [pointer, out],
121
- "ConvertStringSecurityDescriptorToSecurityDescriptorW": [
122
- ctypes.c_wchar_p,
123
- integer,
124
- out,
125
- ctypes.POINTER(integer),
126
- ],
127
- "GetSecurityDescriptorDacl": [
128
- pointer,
129
- ctypes.POINTER(ctypes.c_int),
130
- out,
131
- ctypes.POINTER(ctypes.c_int),
132
- ],
133
- "GetSecurityDescriptorControl": [
134
- pointer,
135
- ctypes.POINTER(ctypes.c_ushort),
136
- ctypes.POINTER(integer),
137
- ],
138
- "GetAce": [pointer, integer, out],
139
- }
140
- for name, arguments in signatures.items():
141
- function = getattr(api, name)
142
- function.argtypes, function.restype = arguments, integer
143
- kernel.GetCurrentProcess.restype = pointer
144
- kernel.CloseHandle.argtypes = [pointer]
145
- kernel.LocalFree.argtypes, kernel.LocalFree.restype = [pointer], pointer
146
- return api, kernel
147
-
148
-
149
- def _windows_private(path: Path, created: bool) -> None:
150
- """Query owner/DACL only; protect a newly created DACL without changing owner/group/SACL."""
151
- import ctypes
152
-
153
- api, kernel = _windows_api()
154
- token, descriptor = ctypes.c_void_p(), ctypes.c_void_p()
155
- try:
156
- if not api.OpenProcessToken(kernel.GetCurrentProcess(), 0x8, ctypes.byref(token)):
157
- raise ValueError("Cannot query current user SID")
158
- size = ctypes.c_uint()
159
- api.GetTokenInformation(token, 1, None, 0, ctypes.byref(size))
160
- buffer = ctypes.create_string_buffer(size.value)
161
- if not api.GetTokenInformation(token, 1, buffer, size, ctypes.byref(size)):
162
- raise ValueError("Cannot query current user SID")
163
- user = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_void_p))[0]
164
- # TokenOwner (4): the owner this process gives what it creates. An elevated
165
- # administrator's token (the built-in Administrator always) names BUILTIN\Administrators,
166
- # so this process's own new files are owned by that group, not by its user.
167
- api.GetTokenInformation(token, 4, None, 0, ctypes.byref(size))
168
- default = ctypes.create_string_buffer(max(size.value, 8))
169
- creator = (
170
- ctypes.cast(default, ctypes.POINTER(ctypes.c_void_p))[0]
171
- if api.GetTokenInformation(token, 4, default, size, ctypes.byref(size))
172
- else None
173
- )
174
- owner, dacl = ctypes.c_void_p(), ctypes.c_void_p()
175
- # OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; never request SACL.
176
- error = api.GetNamedSecurityInfoW(
177
- str(path),
178
- 1,
179
- 0x5,
180
- ctypes.byref(owner),
181
- None,
182
- ctypes.byref(dacl),
183
- None,
184
- ctypes.byref(descriptor),
185
- )
186
- if error or not (
187
- api.EqualSid(owner, user) or (creator is not None and api.EqualSid(owner, creator))
188
- ):
189
- raise ValueError("Runtime state has a foreign or unreadable owner")
190
- if created:
191
- _windows_protect(api, kernel, path, user)
192
- else:
193
- control, revision = ctypes.c_ushort(), ctypes.c_uint()
194
- # Protected (SE_DACL_PROTECTED), or inherited whole from a private parent: a program
195
- # this tool runs (Magpie) replaces its own files, which then inherit that DACL.
196
- if (
197
- not api.GetSecurityDescriptorControl(
198
- descriptor, ctypes.byref(control), ctypes.byref(revision)
199
- )
200
- or not dacl.value
201
- ):
202
- raise ValueError("Existing runtime state must already have a private DACL")
203
- count = ctypes.c_ushort.from_address(dacl.value + 4).value
204
- entries: list[tuple[int, int, int, str]] = []
205
- if count not in (1, 2):
206
- raise ValueError("Existing runtime state must already have a private DACL")
207
- for index in range(count):
208
- ace = ctypes.c_void_p()
209
- if not api.GetAce(dacl, index, ctypes.byref(ace)) or not ace.value:
210
- raise ValueError("Cannot inspect runtime DACL entry")
211
- kind = ctypes.c_ubyte.from_address(ace.value).value
212
- if kind != 0:
213
- raise ValueError("Existing runtime state must already have a private DACL")
214
- entries.append(
215
- (
216
- kind,
217
- ctypes.c_ubyte.from_address(ace.value + 1).value,
218
- ctypes.c_uint.from_address(ace.value + 4).value,
219
- _windows_sid_text(api, kernel, ace.value + 8),
220
- )
221
- )
222
- if not _private_dacl_entries(
223
- entries, _windows_sid_text(api, kernel, user), protected=True,
224
- inherited=not control.value & 0x1000,
225
- ): # fmt: skip
226
- raise ValueError("Existing runtime state must already have a private DACL")
227
- finally:
228
- if descriptor.value:
229
- kernel.LocalFree(descriptor)
230
- if token.value:
231
- kernel.CloseHandle(token)
232
-
233
-
234
- def _private_dacl_entries(
235
- entries: list[tuple[int, int, int, str]],
236
- user_sid: str,
237
- *,
238
- protected: bool,
239
- inherited: bool = False,
240
- ) -> bool:
241
- """A private DACL grants full access to the owner and optionally Local System only. An
242
- ``inherited`` (unprotected) DACL counts only when every entry came from its parent."""
243
- identities = [sid for _, _, _, sid in entries]
244
- return (
245
- protected
246
- and (not inherited or all(flags & 0x10 for _, flags, _, _ in entries))
247
- and len(identities) in (1, 2)
248
- and user_sid in identities
249
- and len(set(identities)) == len(identities)
250
- and set(identities).issubset({user_sid, "S-1-5-18"})
251
- and all(
252
- kind == 0 and not flags & 0x8 and mask & 0x1F01FF == 0x1F01FF
253
- for kind, flags, mask, _ in entries
254
- )
255
- )
256
-
257
-
258
- def _windows_sid_text(api: Any, kernel: Any, sid: Any) -> str:
259
- import ctypes
260
-
261
- text = ctypes.c_void_p()
262
- try:
263
- if not api.ConvertSidToStringSidW(sid, ctypes.byref(text)) or text.value is None:
264
- raise ValueError("Cannot format runtime SID")
265
- return ctypes.wstring_at(text.value)
266
- finally:
267
- if text.value:
268
- kernel.LocalFree(text)
269
-
270
-
271
- def _windows_protect(api: Any, kernel: Any, path: Path, user: Any) -> None:
272
- import ctypes
273
-
274
- security = ctypes.c_void_p()
275
- try:
276
- inheritance = "OICI" if path.is_dir() else ""
277
- sddl = f"D:P(A;{inheritance};FA;;;{_windows_sid_text(api, kernel, user)})"
278
- if not api.ConvertStringSecurityDescriptorToSecurityDescriptorW(
279
- sddl, 1, ctypes.byref(security), None
280
- ):
281
- raise ValueError("Cannot construct private runtime DACL")
282
- present, defaulted, dacl = ctypes.c_int(), ctypes.c_int(), ctypes.c_void_p()
283
- if not api.GetSecurityDescriptorDacl(
284
- security, ctypes.byref(present), ctypes.byref(dacl), ctypes.byref(defaulted)
285
- ):
286
- raise ValueError("Cannot inspect private runtime DACL")
287
- if api.SetNamedSecurityInfoW(str(path), 1, 0x80000004, None, None, dacl, None):
288
- raise ValueError("Cannot protect new runtime state DACL")
289
- finally:
290
- if security.value:
291
- kernel.LocalFree(security)
108
+ _windows_api = runtime_windows_acl.api
109
+ _windows_private = runtime_windows_acl.private_permissions
110
+ _private_dacl_entries = runtime_windows_acl.private_dacl_entries
111
+ _windows_sid_text = runtime_windows_acl.sid_text
292
112
 
293
113
 
294
114
  def _safe_member(name: str) -> Path:
@@ -310,26 +130,72 @@ def _safe_member(name: str) -> Path:
310
130
  return Path(*parts)
311
131
 
312
132
 
133
+ def _ensure_extract_dir(directory: Path, known: set[Path] | None) -> None:
134
+ if known is None:
135
+ private_directory(directory)
136
+ return
137
+ if directory in known:
138
+ return
139
+ missing: list[Path] = []
140
+ current = directory
141
+ while current not in known:
142
+ if current == current.parent:
143
+ raise ValueError("Unsafe archive path")
144
+ missing.append(current)
145
+ current = current.parent
146
+ for part in reversed(missing):
147
+ try:
148
+ part.mkdir(mode=0o700)
149
+ except FileExistsError as exc:
150
+ raise ValueError("Runtime parent must be a directory") from exc
151
+ if os.name != "nt":
152
+ part.chmod(0o700)
153
+ known.add(part)
154
+
155
+
156
+ def _write_extracted(source: Any, destination: Path, mode: int, *, inherited: bool) -> None:
157
+ if inherited:
158
+ flags = (
159
+ os.O_WRONLY
160
+ | os.O_CREAT
161
+ | os.O_EXCL
162
+ | getattr(os, "O_BINARY", 0)
163
+ | getattr(os, "O_NOFOLLOW", 0)
164
+ )
165
+ with os.fdopen(os.open(destination, flags, mode), "wb") as output:
166
+ shutil.copyfileobj(source, output)
167
+ if os.name != "nt":
168
+ destination.chmod(mode)
169
+ return
170
+ with destination.open("xb") as output:
171
+ shutil.copyfileobj(source, output)
172
+ if os.name != "nt":
173
+ destination.chmod(mode)
174
+ private_permissions(destination, created=True)
175
+
176
+
313
177
  def _extract_archive(archive: Path, target: Path) -> None:
314
178
  """Validate the complete member list before writing; never materialize links."""
315
- private_directory(target)
179
+ # A freshly created target has a protected OICI DACL on Windows, so new subdirectories and
180
+ # files beneath it inherit owner-only access without per-file SetNamedSecurityInfoW calls.
181
+ fresh = _create_private_directory(target)
182
+ known = {target} if fresh else None
316
183
  if zipfile.is_zipfile(archive):
317
184
  with zipfile.ZipFile(archive) as stream:
318
185
  members = stream.infolist()
319
186
  for member in members:
320
187
  _safe_member(member.filename)
321
188
  mode = member.external_attr >> 16
322
- if stat.S_ISLNK(mode) or (stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)):
189
+ if stat.S_ISLNK(mode) or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR):
323
190
  raise ValueError("Unsafe archive member")
324
191
  for member in members:
325
192
  destination = target / _safe_member(member.filename)
326
193
  if member.is_dir():
327
- private_directory(destination)
194
+ _ensure_extract_dir(destination, known)
328
195
  else:
329
- private_directory(destination.parent)
330
- with stream.open(member) as source, destination.open("xb") as output:
331
- shutil.copyfileobj(source, output)
332
- private_permissions(destination, created=True)
196
+ _ensure_extract_dir(destination.parent, known)
197
+ with stream.open(member) as source:
198
+ _write_extracted(source, destination, 0o600, inherited=fresh)
333
199
  return
334
200
  with tarfile.open(archive) as tar:
335
201
  # npm tarballs may repeat a/b as a/./b; the last wins, as with tar (scripts/pin_pi.py
@@ -343,16 +209,16 @@ def _extract_archive(archive: Path, target: Path) -> None:
343
209
  for entry in entries:
344
210
  destination = target / _safe_member(entry.name)
345
211
  if entry.isdir():
346
- private_directory(destination)
212
+ _ensure_extract_dir(destination, known)
347
213
  continue
348
- private_directory(destination.parent)
214
+ _ensure_extract_dir(destination.parent, known)
349
215
  tar_source = tar.extractfile(entry)
350
216
  if tar_source is None:
351
217
  raise ValueError("Unsafe archive member")
352
- with tar_source, destination.open("xb") as output:
353
- shutil.copyfileobj(tar_source, output)
354
- destination.chmod(0o700 if entry.mode & 0o111 else 0o600)
355
- private_permissions(destination, created=True)
218
+ with tar_source:
219
+ _write_extracted(
220
+ tar_source, destination, 0o700 if entry.mode & 0o111 else 0o600, inherited=fresh
221
+ )
356
222
 
357
223
 
358
224
  DOWNLOAD_ATTEMPTS = 5
@@ -98,7 +98,8 @@ PROBE_TIMEOUT = -1000
98
98
  # A just-unpacked executable can be briefly unavailable to CreateProcess on Windows (for
99
99
  # example while antivirus or indexing scans or locks it), so these spawn errors are retried.
100
100
  SPAWN_RETRY_DELAYS = (0.25, 0.5, 1.0, 2.0, 4.0, 4.0)
101
- _RETRYABLE_WINERRORS = (2, 5, 32, 225)
101
+ _WINERROR_FILE_NOT_FOUND = 2
102
+ _LOCKED_WINERRORS = (5, 32, 225)
102
103
 
103
104
 
104
105
  # taskkill's exit code when the PID no longer exists: the child exited before cleanup reached it.
@@ -141,16 +142,23 @@ def _spawn(
141
142
  )
142
143
  except OSError as error:
143
144
  winerror = getattr(error, "winerror", None)
145
+ absolute = bool(argv and Path(argv[0]).is_absolute())
146
+ exists = "unknown"
147
+ if absolute:
148
+ with contextlib.suppress(OSError, ValueError):
149
+ exists = "true" if Path(argv[0]).exists() else "false"
150
+ # Bare PATH names and absent paths failing with ERROR_FILE_NOT_FOUND are ordinary
151
+ # "not installed" results; only retry locks or a present absolute executable.
144
152
  retrying = (
145
153
  _windows()
146
- and winerror in _RETRYABLE_WINERRORS
154
+ and absolute
147
155
  and attempt <= len(SPAWN_RETRY_DELAYS)
156
+ and (
157
+ winerror in _LOCKED_WINERRORS
158
+ or (winerror == _WINERROR_FILE_NOT_FOUND and exists != "false")
159
+ )
148
160
  )
149
- # A bare PATH name that fails to spawn is an ordinary "not installed" result.
150
- if argv and Path(argv[0]).is_absolute():
151
- exists = "unknown"
152
- with contextlib.suppress(OSError, ValueError):
153
- exists = "true" if Path(argv[0]).exists() else "false"
161
+ if absolute:
154
162
  _diagnose(
155
163
  "spawn failed",
156
164
  attempt=attempt,