@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +149 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3633 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +141 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +93 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +379 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +1011 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +288 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +426 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +400 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +716 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +59531 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1923 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,61 @@
1
+ """Read-only Claude Code tool-search configuration diagnosis.
2
+
3
+ No network probe, cost projection or automatic setting change. Proxy support,
4
+ managed policy and model/deployment fallback cannot be inferred from env alone.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from collections.abc import Mapping
10
+ from urllib.parse import urlsplit
11
+
12
+ _DOC = 'https://code.claude.com/docs/en/agent-sdk/tool-search'
13
+
14
+
15
+ def diagnose_tool_search(environ, settings, runtime='claude'):
16
+ """Return an optional doctor (status, name, detail) tuple, without secrets."""
17
+ if runtime != 'claude':
18
+ return None
19
+ if not isinstance(environ, Mapping):
20
+ environ = {}
21
+ settings_env = settings.get('env', {}) if isinstance(settings, dict) else {}
22
+ if not isinstance(settings_env, dict):
23
+ settings_env = {}
24
+
25
+ def effective(key):
26
+ value = environ[key] if key in environ else settings_env.get(key, '')
27
+ return value.strip() if isinstance(value, str) else ''
28
+
29
+ base = effective('ANTHROPIC_BASE_URL')
30
+ mode = effective('ENABLE_TOOL_SEARCH')
31
+ beta_off = effective('CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS')
32
+ label = 'Tool search'
33
+ caveat = ('Only enable through a proxy after confirming tool_reference support; '
34
+ 'model, deployment and managed policy can still disable it. ' + _DOC)
35
+ if beta_off and beta_off.lower() not in ('0', 'false', 'no'):
36
+ return ('!!', label, 'Tool search is disabled by CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS. ' + _DOC)
37
+
38
+ valid_mode = mode in ('', 'true', 'false', 'auto')
39
+ if mode.startswith('auto:'):
40
+ match = re.fullmatch(r'auto:(\d{1,3})', mode)
41
+ valid_mode = bool(match and 0 <= int(match.group(1)) <= 100)
42
+ if not valid_mode:
43
+ return ('!!', label, 'ENABLE_TOOL_SEARCH is invalid; effective behavior is unknown. ' + caveat)
44
+
45
+ custom = False
46
+ if base:
47
+ try:
48
+ parsed = urlsplit(base)
49
+ custom = not (parsed.scheme == 'https' and parsed.hostname == 'api.anthropic.com'
50
+ and parsed.port in (None, 443) and not parsed.username and not parsed.password)
51
+ except ValueError:
52
+ custom = True
53
+ if mode == 'false':
54
+ return ('!!', label, 'Tool search is explicitly off; tool definitions load upfront. ' + caveat)
55
+ if custom and not mode:
56
+ return ('!!', label, 'A non-default ANTHROPIC_BASE_URL can disable tool search by default; '
57
+ 'tool definitions may load upfront. ' + caveat)
58
+ if mode:
59
+ return ('OK', label, 'ENABLE_TOOL_SEARCH=' + mode + '; proxy compatibility is unverified, '
60
+ 'and model/deployment/managed-policy fallbacks may apply. ' + _DOC)
61
+ return None
@@ -0,0 +1,219 @@
1
+ """Process-wide UTF-8 I/O enforcement for Token Optimizer.
2
+
3
+ Token Optimizer runs as short-lived hook / statusline subprocesses spawned by the
4
+ host CLI. On hosts where the active encoding is not UTF-8 -- Windows ANSI codepages
5
+ (cp125x), an explicit non-UTF-8 LANG/LC_ALL, or PYTHONUTF8=0 -- Python's standard
6
+ streams (and the default open() encoding) fall back to that locale charset. Session
7
+ paths and transcript content frequently contain non-ASCII text (Hebrew, CJK, accented
8
+ names); decoding or printing it then raises UnicodeDecodeError / UnicodeEncodeError,
9
+ which aborts the hook before it can identify the session.
10
+
11
+ enforce_utf8_io() makes stdout / stderr / stdin UTF-8 with errors="replace" so a
12
+ stray undecodable byte degrades gracefully instead of crashing the process. It is
13
+ idempotent and safe to call at the top of every entry point. File reads still pass
14
+ encoding="utf-8" explicitly at their call sites; this module only covers the standard
15
+ streams, which have no per-call encoding hook.
16
+
17
+ Note: scripts dispatched through hooks/run.py also inherit PYTHONUTF8=1 /
18
+ PYTHONIOENCODING=utf-8 from the parent, which additionally makes the default open()
19
+ encoding UTF-8. This shim is the belt-and-suspenders for entry points invoked
20
+ directly by a host (statusline, hook bridges, the CLI).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ import sys
27
+
28
+ _DONE = False
29
+
30
+ # Sentinel so a re-exec can never loop, even if the child still reports a
31
+ # non-UTF-8 preferred encoding for some pathological reason.
32
+ _REEXEC_FLAG = "TOKEN_OPTIMIZER_UTF8_REEXEC"
33
+
34
+
35
+ def _inheritable_stream(stream):
36
+ """Return ``stream`` when it has a real OS handle Popen can pass through,
37
+ else None (fall back to default inheritance).
38
+
39
+ ``sys.std*`` can be None (GUI-subsystem ``pythonw`` -- the launcher
40
+ swap) or a wrapper with no fileno (pytest capture, embedded hosts). Passing
41
+ either to Popen raises, which would turn a UTF-8 convenience re-exec into a
42
+ hard crash of the CLI. None keeps today's behavior for those callers.
43
+ """
44
+ if stream is None:
45
+ return None
46
+ try:
47
+ fileno = stream.fileno()
48
+ except (AttributeError, OSError, ValueError):
49
+ return None
50
+ return stream if isinstance(fileno, int) and fileno >= 0 else None
51
+
52
+
53
+ def reexec_in_utf8_mode() -> None:
54
+ """Re-exec this process under Python UTF-8 mode iff the locale isn't UTF-8.
55
+
56
+ Stream reconfiguration (enforce_utf8_io) fixes stdout/stderr/stdin, but it
57
+ cannot change locale.getpreferredencoding(), which is fixed at interpreter
58
+ startup and drives the default open() encoding AND how subprocess(text=True)
59
+ decodes child output. On a non-UTF-8 host the only way to flip all of those at
60
+ once is to restart the interpreter with -X utf8 / PYTHONUTF8=1.
61
+
62
+ This re-execs at most once (guarded by an env sentinel) and only when the
63
+ active encoding is genuinely non-UTF-8, so UTF-8 users -- and scripts already
64
+ launched with PYTHONUTF8=1 by hooks/run.py -- pay nothing. Call it as the very
65
+ first statement of an entry point, before reading stdin or doing any work.
66
+ Falls back silently (caller should still call enforce_utf8_io) if re-exec is
67
+ unavailable (frozen build, no os.execv).
68
+ """
69
+ if os.environ.get(_REEXEC_FLAG) == "1":
70
+ return
71
+ if getattr(sys.flags, "utf8_mode", 0):
72
+ return
73
+ try:
74
+ import locale
75
+ enc = (locale.getpreferredencoding(False) or "").lower().replace("-", "").replace("_", "")
76
+ except (ImportError, LookupError):
77
+ enc = ""
78
+ # "cp65001"/"65001" = the Windows UTF-8 code page; treat as UTF-8 so Windows
79
+ # users on it don't re-exec on every single hook invocation. "" = undetectable
80
+ # (don't gamble on a re-exec we can't verify).
81
+ if enc in ("utf8", "cp65001", "65001", ""):
82
+ return
83
+ os.environ[_REEXEC_FLAG] = "1"
84
+ os.environ["PYTHONUTF8"] = "1"
85
+ os.environ.setdefault("PYTHONIOENCODING", "utf-8")
86
+ try:
87
+ import subprocess as _sp
88
+
89
+ if sys.platform.startswith("win"):
90
+ # On Windows, os.execv does not quote the executable path, so a
91
+ # path like "C:\Program Files\Python312\python.exe" gets split at
92
+ # the space and the relaunched interpreter dies with
93
+ # "can't open file '...\Files\Python312\python.exe'". Use
94
+ # subprocess.Popen (which quotes correctly) and exit immediately
95
+ # so the child takes over the role of this process.
96
+ #
97
+ # DETACHED_PROCESS gives the child NO console at all when the
98
+ # parent is console-less (e.g. a hook spawned by the host).
99
+ # CREATE_NO_WINDOW would still allocate a hidden console -- a
100
+ # conhost.exe spawn that flashes nothing but leaks a kernel token
101
+ # reference on the affected Windows build (issue #215). The flag
102
+ # is kept UNCONDITIONALLY -- do NOT drop it when stdout is a
103
+ # pipe. The flash/leak-sensitive case (a host-spawned
104
+ # hook/statusline) is exactly the case where stdout is not a
105
+ # tty; dropping the flag there would let Windows allocate a
106
+ # console while fixing nothing, because the stdio-binding problem
107
+ # below is solved by passing the handles explicitly, not by
108
+ # removing the flag. The detached child inherits the parent's
109
+ # stdio through those explicit handles (STARTF_USESTDHANDLES),
110
+ # never through a console it does not have.
111
+ #
112
+ # Invariant: this function must be the FIRST statement of the entry
113
+ # point (it already is at measure.py's __main__). If anything reads
114
+ # stdin before the re-exec, those buffered bytes are lost to the
115
+ # child, which continues reading the same stdin handle from the
116
+ # byte after the parent left it.
117
+ #
118
+ # Flush the parent's buffered streams BEFORE spawning. Once the
119
+ # child shares the parent's stdout/stderr fd, any parent-buffered
120
+ # text flushed AFTER the spawn interleaves out of order behind the
121
+ # child's own output. The post-wait flush below is kept as the
122
+ # final safety net (os._exit skips normal cleanup / atexit
123
+ # handlers, matching os.execv semantics).
124
+ for stream in (sys.stdout, sys.stderr):
125
+ try:
126
+ stream.flush()
127
+ except (OSError, ValueError, AttributeError):
128
+ pass
129
+ _popen_kwargs = {}
130
+ # DETACHED_PROCESS only when no console is in play. If stdout is a
131
+ # tty the CLI was typed into a console: a detached child would sit
132
+ # off that console (no Ctrl+C, console handles used from outside
133
+ # their console), and no conhost can flash, so the flag buys
134
+ # nothing. Without it the child shares the console. Streams that
135
+ # are not a tty (every host-spawned hook) keep the flag.
136
+ try:
137
+ _on_console = bool(sys.stdout is not None and sys.stdout.isatty())
138
+ except (AttributeError, OSError, ValueError):
139
+ _on_console = False
140
+ _flags = getattr(_sp, "DETACHED_PROCESS", 0)
141
+ if _flags and not _on_console:
142
+ _popen_kwargs["creationflags"] = _flags
143
+ # Pass the three std handles explicitly so CPython sets
144
+ # STARTF_USESTDHANDLES with the parent's real handles and marks
145
+ # them inheritable. This is the ONLY stdio channel a detached
146
+ # child has: with all three left None its std handles bind to
147
+ # NULL, and every byte it writes is silently discarded (the
148
+ # "silent no-op" signature on a cp1252 host).
149
+ # _inheritable_stream degrades to None for streams without a real
150
+ # OS handle (pytest capture, sys.std* None under pythonw per the
151
+ # launcher swap), so a UTF-8 convenience re-exec never hard-crashes
152
+ # the CLI.
153
+ # When at least one stream is usable, each unusable one gets DEVNULL
154
+ # rather than being left out: CPython falls back to GetStdHandle for
155
+ # an omitted stream, and a stale non-NULL value there makes
156
+ # DuplicateHandle fail (WinError 6) so Popen raises and the re-exec
157
+ # is silently skipped. With none usable nothing is passed.
158
+ _missing = []
159
+ for _name in ("stdin", "stdout", "stderr"):
160
+ _s = _inheritable_stream(getattr(sys, _name, None))
161
+ if _s is not None:
162
+ _popen_kwargs[_name] = _s
163
+ else:
164
+ _missing.append(_name)
165
+ if any(_n in _popen_kwargs for _n in ("stdin", "stdout", "stderr")):
166
+ for _name in _missing:
167
+ _popen_kwargs[_name] = _sp.DEVNULL
168
+ child = _sp.Popen([sys.executable, "-X", "utf8", *sys.argv],
169
+ **_popen_kwargs)
170
+ # Wait for the child to finish so output ordering is preserved and
171
+ # the parent's exit code reflects the child's result.
172
+ try:
173
+ child.wait()
174
+ rc = child.returncode
175
+ except (OSError, _sp.SubprocessError):
176
+ rc = 1
177
+ # Final flush of any parent-buffered output before exiting.
178
+ for stream in (sys.stdout, sys.stderr):
179
+ try:
180
+ stream.flush()
181
+ except (OSError, ValueError, AttributeError):
182
+ pass
183
+ os._exit(rc)
184
+ else:
185
+ os.execv(sys.executable, [sys.executable, "-X", "utf8", *sys.argv])
186
+ except ImportError:
187
+ # subprocess module unavailable (frozen / restricted): leave the sentinel
188
+ # set and let the caller's enforce_utf8_io() + explicit per-call encodings
189
+ # carry it.
190
+ pass
191
+ except (OSError, _sp.SubprocessError):
192
+ # execv/Popen failed: same fallback as above.
193
+ pass
194
+ except Exception:
195
+ # Any other exotic/restricted-environment failure: never crash the host
196
+ # process over a UTF-8 re-exec. Leave the sentinel set and degrade to
197
+ # enforce_utf8_io() + per-call encodings, exactly like the no-execv case.
198
+ pass
199
+
200
+
201
+ def enforce_utf8_io() -> None:
202
+ """Reconfigure std streams to UTF-8 (errors=replace). Idempotent and fail-safe."""
203
+ global _DONE
204
+ if _DONE:
205
+ return
206
+ _DONE = True
207
+ for name in ("stdout", "stderr", "stdin"):
208
+ stream = getattr(sys, name, None)
209
+ reconfigure = getattr(stream, "reconfigure", None)
210
+ if reconfigure is None:
211
+ # Stream replaced (e.g. captured in tests) or not a TextIOWrapper.
212
+ continue
213
+ if (getattr(stream, "encoding", "") or "").lower() == "utf-8":
214
+ continue
215
+ try:
216
+ reconfigure(encoding="utf-8", errors="replace")
217
+ except (ValueError, OSError, AttributeError):
218
+ # Detached/closed stream, or reconfigure unsupported -- leave as-is.
219
+ pass