@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,790 @@
1
+ #!/usr/bin/env python3
2
+ """Captured-output filter for Devin: the explicit skill workflow, plus the
3
+ automatic hook entrypoint and runner. Never a shell: commands run as argv."""
4
+ from __future__ import annotations
5
+ # CLI startup imports only builtins until isolated re-execution.
6
+ import sys
7
+ # Devin reads hook exit code 2 as "block this tool call". The hook entrypoint
8
+ # must never block a command, so every refusal on that path exits 0 silently.
9
+ _HOOK_MODE = __name__ == '__main__' and sys.argv[1:2] == ['hook']
10
+ _REFUSED = 0 if _HOOK_MODE else 2
11
+ if __name__ == '__main__' and not sys.flags.isolated:
12
+ import posix
13
+ try:
14
+ posix.execv(sys.executable, [sys.executable, '-I', *sys.argv])
15
+ except OSError as _isolation_error:
16
+ print('Token Optimizer: isolated startup refused: ' + str(_isolation_error), file=sys.stderr)
17
+ raise SystemExit(_REFUSED)
18
+
19
+ import argparse
20
+ from dataclasses import dataclass
21
+ import os
22
+ import hashlib
23
+ import json
24
+ from pathlib import Path
25
+ import select
26
+ import shlex
27
+ import signal
28
+ import stat
29
+ import re
30
+ import sys
31
+
32
+ # Bootstrap uses only stdlib already imported by the entrypoint.
33
+ _source_root = Path(__file__).resolve().parent
34
+ # Source development is the canonical checkout layout, not a directory-name bypass.
35
+ _source_checkout = _source_root.parent.parent.parent
36
+ _source_development = (
37
+ _source_root == _source_checkout / 'skills/token-optimizer/scripts'
38
+ and (_source_root / 'devin_install.py').is_file()
39
+ and (_source_checkout / 'devin/SKILL.md').is_file()
40
+ and (_source_checkout / 'README.md').is_file()
41
+ and not any((directory / leaf).exists() or (directory / leaf).is_symlink()
42
+ for directory in (_source_root, *_source_root.parents)
43
+ for leaf in ('install.json', 'consent.json'))
44
+ )
45
+ if _source_development and __name__ == '__main__':
46
+ # -I removed ambient paths; restore only the checked development scripts root.
47
+ sys.path.insert(0, str(_source_root))
48
+ if not _source_development:
49
+ try:
50
+ if __name__ != '__main__' and not any(
51
+ getattr(finder, '_devin_source_root', None) == _source_root for finder in sys.meta_path):
52
+ raise ImportError('installed entrypoint requires command-line use or prior activation')
53
+ def _bootstrap_read(path, limit):
54
+ for component in [*reversed(path.parents), path]:
55
+ if component.is_symlink():
56
+ raise ImportError('symlink bootstrap path refused')
57
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
58
+ try:
59
+ info = os.fstat(fd)
60
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid()
61
+ or info.st_nlink != 1 or info.st_mode & 0o077 or info.st_size > limit):
62
+ raise ImportError('private bounded bootstrap file required')
63
+ with os.fdopen(fd, 'rb', closefd=False) as stream:
64
+ content = stream.read(limit + 1)
65
+ if len(content) > limit:
66
+ raise ImportError('bootstrap file exceeds bound')
67
+ return content
68
+ finally:
69
+ os.close(fd)
70
+ _source_path = _source_root / 'devin_source.py'
71
+ _source_record = json.loads(_bootstrap_read(_source_root.parent / 'install.json', 65536))
72
+ if (not isinstance(_source_record, dict) or _source_record.get('owner') != 'devin-output-filter-v1'
73
+ or not isinstance(_source_record.get('files'), dict)):
74
+ raise ImportError('invalid bootstrap manifest')
75
+ _source_bytes = _bootstrap_read(_source_path, 8 * 1024 * 1024)
76
+ if hashlib.sha256(_source_bytes).hexdigest() != _source_record['files'].get(str(_source_path)):
77
+ raise ImportError('bootstrap source differs from install manifest')
78
+ _source_namespace = {}
79
+ exec(compile(_source_bytes, str(_source_path), 'exec'), _source_namespace)
80
+ _source_namespace['activate'](_source_root)
81
+ except (OSError, ValueError, TypeError, ImportError, SyntaxError, RecursionError) as _bootstrap_error:
82
+ _bootstrap_message = 'Token Optimizer: bootstrap manifest gate refused: ' + str(_bootstrap_error) + '. Originals remain unchanged.'
83
+ if __name__ == '__main__':
84
+ print(_bootstrap_message, file=sys.stderr)
85
+ raise SystemExit(_REFUSED)
86
+ raise ImportError(_bootstrap_message) from None
87
+
88
+
89
+
90
+ try:
91
+ from devin_state import InstallBusy, consent_ok, install_settled, record
92
+ except (ImportError, SyntaxError) as _initial_error:
93
+ _initial_message = 'Token Optimizer: bootstrap manifest gate refused: ' + str(_initial_error) + '. Originals remain unchanged.'
94
+ if __name__ == '__main__':
95
+ print(_initial_message, file=sys.stderr)
96
+ raise SystemExit(_REFUSED)
97
+ raise ImportError(_initial_message) from None
98
+
99
+
100
+ MAX_CAPTURE = 8 * 1024 * 1024
101
+ FORMATS = {'generic': 'captured-output', 'git-status': 'git status',
102
+ 'git-log': 'git log', 'listing': 'ls', 'search': 'rg',
103
+ 'tests': 'pytest', 'build': 'tsc'}
104
+
105
+
106
+ @dataclass(frozen=True)
107
+ class FilterResult:
108
+ stdout: bytes
109
+ stderr: bytes
110
+ code: int
111
+ outcome: str
112
+ metrics_recorded: bool = False
113
+
114
+
115
+ def _directory_fd(path: Path) -> int:
116
+ """Open absolute directory components without following any symlink."""
117
+ from devin_state import directory_fd
118
+ return directory_fd(path)
119
+
120
+
121
+ def _read_leaf(directory_fd: int, name: str, cap: int) -> tuple[bytes, object]:
122
+ fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory_fd)
123
+ try:
124
+ # fstat before fdopen: a directory wraps into a stream that reports the
125
+ # bare descriptor number in its error, not the leaf being refused.
126
+ before = os.fstat(fd)
127
+ if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.geteuid()
128
+ or before.st_mode & 0o077 or before.st_nlink != 1):
129
+ raise OSError('capture leaf must be a private single-link file: ' + name)
130
+ with os.fdopen(fd, 'rb') as stream:
131
+ fd = -1
132
+ if before.st_size > cap:
133
+ raise OSError('capture exceeds the ' + str(cap) + ' byte limit; read the original files directly')
134
+ content = stream.read(cap + 1)
135
+ after = os.fstat(stream.fileno())
136
+ identity = lambda info: (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
137
+ current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
138
+ if len(content) > cap:
139
+ raise OSError('capture exceeded the ' + str(cap) + ' byte limit while reading')
140
+ if identity(before) != identity(after) or identity(after) != identity(current):
141
+ raise OSError('capture changed during reading')
142
+ return content, after
143
+ finally:
144
+ if fd >= 0:
145
+ os.close(fd)
146
+
147
+
148
+ def _repair_orphaned_seal(directory_fd: int) -> None:
149
+ """A seal killed between os.link and unlink left complete.json linked to a
150
+ stray tempfile name in this directory. Only a same-inode sibling under the
151
+ tempfile prefix is removed; any other extra link still refuses."""
152
+ try:
153
+ seal = os.stat('complete.json', dir_fd=directory_fd, follow_symlinks=False)
154
+ except FileNotFoundError:
155
+ return
156
+ if seal.st_nlink != 2 or not stat.S_ISREG(seal.st_mode):
157
+ return
158
+ for name in os.listdir(directory_fd):
159
+ if not name.startswith('tmp'):
160
+ continue
161
+ try:
162
+ info = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
163
+ except FileNotFoundError:
164
+ continue
165
+ if info.st_ino == seal.st_ino and info.st_dev == seal.st_dev and stat.S_ISREG(info.st_mode):
166
+ os.unlink(name, dir_fd=directory_fd)
167
+ break
168
+
169
+
170
+ def read_pair(directory: Path, *, sealed: bool, exit_code=None) -> tuple[bytes, bytes]:
171
+ from devin_state import data_dir
172
+ root = data_dir() / 'captures'
173
+ if directory.parent != root or not re.fullmatch(r'capture-[0-9a-f]{32}', directory.name):
174
+ raise OSError('adapter-prepared capture required')
175
+ root_fd = _directory_fd(root)
176
+ fd = None
177
+ try:
178
+ info = os.fstat(root_fd)
179
+ if info.st_uid != os.geteuid() or info.st_mode & 0o077:
180
+ raise OSError('capture root must be private')
181
+ fd = os.open(directory.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=root_fd)
182
+ info = os.fstat(fd)
183
+ if info.st_uid != os.geteuid() or info.st_mode & 0o077:
184
+ raise OSError('capture directory must be private')
185
+ marker, _ = _read_leaf(fd, '.prepared', 4096)
186
+ provenance = json.loads(marker)
187
+ if (not isinstance(provenance, dict) or set(provenance) != {'stdout', 'stderr'}
188
+ or any(not isinstance(provenance[name], list) or len(provenance[name]) != 2
189
+ or any(type(value) is not int or value < 0 for value in provenance[name])
190
+ for name in ('stdout', 'stderr'))):
191
+ raise OSError('invalid prepared capture identity shape')
192
+ out, out_info = _read_leaf(fd, 'stdout', MAX_CAPTURE)
193
+ err, err_info = _read_leaf(fd, 'stderr', MAX_CAPTURE)
194
+ # Valid JSON of the wrong type must be the normal refusal, never a crash.
195
+ if (not isinstance(provenance, dict)
196
+ or provenance.get('stdout') != [out_info.st_dev, out_info.st_ino]
197
+ or provenance.get('stderr') != [err_info.st_dev, err_info.st_ino]):
198
+ raise OSError('prepared capture identity changed')
199
+ if sealed:
200
+ _repair_orphaned_seal(fd)
201
+ content, _ = _read_leaf(fd, 'complete.json', 4096)
202
+ try:
203
+ seal = json.loads(content)
204
+ except ValueError:
205
+ raise OSError('seal record torn by an interrupted write; re-run seal to repair')
206
+ if (not isinstance(seal, dict) or seal.get('exit_code') != exit_code
207
+ or seal.get('stdout_sha256') != hashlib.sha256(out).hexdigest()
208
+ or seal.get('stderr_sha256') != hashlib.sha256(err).hexdigest()):
209
+ raise OSError('captures incomplete or changed after sealing')
210
+ return out, err
211
+ finally:
212
+ if fd is not None: os.close(fd)
213
+ os.close(root_fd)
214
+
215
+
216
+ def read_capture(path: Path) -> bytes:
217
+ if path.name not in ('stdout', 'stderr'):
218
+ raise OSError('fixed capture leaf required')
219
+ out, err = read_pair(path.parent, sealed=False)
220
+ return out if path.name == 'stdout' else err
221
+
222
+
223
+ def _looks_like_format(fmt: str, text: str) -> bool:
224
+ """Cheap strict gate: does this capture really look like <fmt> output?
225
+
226
+ Named compressors trust their input. On foreign text a coincidental
227
+ partial match (a prose line containing "ahead", an indented sentence
228
+ after a "Changes not staged" mention) collapses a large capture into a
229
+ few hundred bytes of mislabeled summary. When in doubt, say no: the
230
+ generic handler is the safe route.
231
+ """
232
+ lines = [line for line in text.splitlines() if line.strip()]
233
+ if not lines:
234
+ return False
235
+
236
+ def majority(hit: int) -> bool:
237
+ return hit * 2 > len(lines)
238
+
239
+ # Header shortcuts are only evidence where the real command prints them:
240
+ # the first non-empty line. A quoted 'On branch', 'total N' or 'commit
241
+ # <hash>' appearing mid-document is prose, not a signature.
242
+ first = lines[0]
243
+ if fmt == 'git-status':
244
+ # Long form only. The handler reads the sectioned human format; a
245
+ # short or porcelain listing (`## branch` plus XY entries) has no
246
+ # sections, so it would keep the header and drop every file name.
247
+ return bool(re.match(r'(?:On branch |HEAD detached )', first))
248
+ if fmt == 'git-log':
249
+ if re.match(r'commit [0-9a-f]{7,40}\b', first):
250
+ return True
251
+ return majority(sum(
252
+ 1 for line in lines if re.match(r'^[0-9a-f]{7,40}\s+\S', line)))
253
+ if fmt == 'listing':
254
+ if re.match(r'total \d+', first):
255
+ return True
256
+ return majority(sum(
257
+ 1 for line in lines if re.match(r'^[-bcdlpsw][-rwxsStT]{9}[+@]?\s', line)))
258
+ if fmt == 'search':
259
+ return majority(sum(
260
+ 1 for line in lines if re.match(r'^[^:\s][^:]*:\d+:', line)))
261
+ if fmt == 'tests':
262
+ if re.search(r'^=+.*\b(?:passed|failed|error|skipped|deselected|'
263
+ r'test session)\b.*=+\s*$', text, re.M):
264
+ return True
265
+ return majority(sum(
266
+ 1 for line in lines
267
+ if re.match(r'^\S+::\S+\s+(?:PASSED|FAILED|ERROR|XFAIL|SKIPPED)\b', line)
268
+ or re.match(r'^(?:FAILED|ERROR|PASSED)\s+\S+::', line)))
269
+ if fmt == 'build':
270
+ if re.search(r'\b(?:error|warning) TS\d+\b', text):
271
+ return True
272
+ return majority(sum(
273
+ 1 for line in lines
274
+ if re.match(r'^\S+\(\d+,\d+\):\s*(?:error|warning)', line)))
275
+ return False
276
+
277
+
278
+ _ARCHIVE_NOTE = 'archived in full original (retrieve via expand key)'
279
+ _CAPTURE_NOTE = 'kept in the capture (recover command above)'
280
+
281
+
282
+ def filter_capture(stdout: Path, stderr: Path, exit_code: int, format_hint: str,
283
+ session: str, *, record_metrics: bool = True,
284
+ command: str | None = None) -> FilterResult:
285
+ if os.name != 'posix' or not consent_ok():
286
+ raise OSError('Devin output filter requires a POSIX install with local data consent')
287
+ if isinstance(exit_code, bool) or not isinstance(exit_code, int) or not 0 <= exit_code <= 255:
288
+ raise ValueError('exit code must be 0 through 255')
289
+ if format_hint not in FORMATS or not isinstance(session, str) or not session or len(session) > 256:
290
+ raise ValueError('invalid format or session identifier')
291
+ if stdout == stderr or stdout.parent != stderr.parent or stdout.name != 'stdout' or stderr.name != 'stderr':
292
+ raise OSError('distinct stdout/stderr from one prepared capture required')
293
+ raw, errors = read_pair(stdout.parent, sealed=True, exit_code=exit_code)
294
+ if exit_code or errors:
295
+ return FilterResult(raw, errors, exit_code, 'passthrough')
296
+ try:
297
+ text = raw.decode('utf-8', errors='strict')
298
+ except UnicodeError:
299
+ return FilterResult(raw, b'', 0, 'binary_passthrough')
300
+ # Permit only complete SGR color CSI and OSC8 links; reject other controls.
301
+ cleaned = re.sub(r'\x1b\[[0-9;]*m|\x1b\]8;[^\x00-\x1f]*;(?:[^\x00-\x1f]*)(?:\x07|\x1b\\)', '', text)
302
+ import unicodedata
303
+ if any((unicodedata.category(ch) in ('Cc', 'Cf', 'Zl', 'Zp')) and ch not in '\n\r\t' for ch in cleaned):
304
+ return FilterResult(raw, b'', 0, 'binary_passthrough')
305
+ delivered, outcome = text, 'passthrough'
306
+ if not _source_development:
307
+ from devin_verify import verify_install
308
+ verify_install()
309
+ try:
310
+ from credential_patterns import PATTERNS_ONLY
311
+ # grep --color=always splits a token with SGR escapes, so the joined
312
+ # secret only appears once escapes are stripped; scan both spellings.
313
+ if (any(pattern.search(text) for pattern in PATTERNS_ONLY)
314
+ or any(pattern.search(cleaned) for pattern in PATTERNS_ONLY)):
315
+ return FilterResult(raw, b'', 0, 'credential_passthrough')
316
+ from bash_compress import compress
317
+ from token_estimate import estimate_tokens
318
+ # A named hint only reaches its handler when the capture actually
319
+ # looks like that command's output; foreign text takes the generic
320
+ # route. The handlers' loose matches otherwise collapse foreign
321
+ # output into a mislabeled near-empty summary.
322
+ if format_hint != 'generic' and not _looks_like_format(format_hint, cleaned):
323
+ format_hint = 'generic'
324
+ # The automatic runner knows the real command, so the Claude Code
325
+ # routing applies unchanged, including raw passthrough for formats a
326
+ # handler must not touch (--short, --porcelain, -z and friends). No
327
+ # generic fallback there: it would compress exactly those formats.
328
+ shortened = compress(command if command else FORMATS[format_hint], text)
329
+ # Claude Code recovers through its archive; here the capture pointer
330
+ # above already recovers the whole original, so name that instead of
331
+ # discarding a good result. Any other mention still means raw.
332
+ shortened = shortened.replace(_ARCHIVE_NOTE, _CAPTURE_NOTE)
333
+ if 'expand key' in shortened:
334
+ shortened = text
335
+ # A named format must never do worse than generic for the same bytes;
336
+ # when its handler preserves more than generic would, generic wins.
337
+ # The delivered unit is encoded bytes, not characters: a CJK-heavy
338
+ # result is ~3x costlier per character, so compare UTF-8 length.
339
+ if format_hint != 'generic' and not command:
340
+ fallback = compress(FORMATS['generic'], text).replace(_ARCHIVE_NOTE, _CAPTURE_NOTE)
341
+ if 'expand key' in fallback:
342
+ fallback = text
343
+ if len(fallback.encode('utf-8')) < len(shortened.encode('utf-8')):
344
+ shortened = fallback
345
+ # File stays exactly as supplied. Pointer includes its entire overhead.
346
+ # The recover hint must be a command an installed user can actually run.
347
+ recover = ' '.join((shlex.quote(os.path.realpath(sys.executable)), '-I',
348
+ shlex.quote(str(Path(__file__).resolve())),
349
+ 'recover', '--capture-id', stdout.parent.name,
350
+ '--exit-code', str(exit_code)))
351
+ pointer = f'[Token Optimizer capture ID: {stdout.parent.name}; recover with {recover}; integrity checked again]\n'
352
+ candidate = pointer + '[Begin untrusted captured output]\n' + shortened + '\n[End untrusted captured output]\n'
353
+ # Automatic runs need a real saving: a pointer and a retained capture
354
+ # for a few percent is clutter, the same 10% bar Claude Code applies.
355
+ limit = estimate_tokens(text) * (0.9 if command else 1)
356
+ if shortened not in (text, cleaned) and estimate_tokens(candidate) < limit:
357
+ delivered, outcome = candidate, 'compressed'
358
+ except Exception as exc:
359
+ return FilterResult(raw, ('Compression unavailable: ' + type(exc).__name__ + '; emitting original bytes.\n').encode(), 0, 'unavailable')
360
+ measured = False
361
+ if record_metrics:
362
+ try:
363
+ record(session, text, delivered, outcome)
364
+ measured = True
365
+ except Exception:
366
+ pass
367
+ return FilterResult(delivered.encode('utf-8'), b'', 0, outcome, measured)
368
+
369
+
370
+ def _remove_capture(directory: Path) -> None:
371
+ """Remove a passthrough capture once its raw bytes were delivered.
372
+ Only the adapter's fixed private leaf names are unlinked; foreign content
373
+ keeps its directory (and itself) in place."""
374
+ from devin_state import delete_capture
375
+ delete_capture(directory)
376
+
377
+
378
+ def _deliver(fd: int, data: bytes) -> None:
379
+ """Write every byte to the descriptor, retrying interrupted and
380
+ non-blocking short writes. Any short, zero or refused write raises so a
381
+ capture is only removed after verified complete delivery."""
382
+ view = memoryview(data)
383
+ while view:
384
+ try:
385
+ sent = os.write(fd, view)
386
+ except (BlockingIOError, InterruptedError):
387
+ select.select([], [fd], [])
388
+ continue
389
+ if not sent:
390
+ raise OSError('output stream accepted zero bytes')
391
+ view = view[sent:]
392
+
393
+
394
+ def _note(message: str) -> None:
395
+ """Best-effort diagnostic straight to fd 2. A buffered print to a closed
396
+ stderr would fail again at interpreter exit and change the exit status."""
397
+ try:
398
+ os.write(2, (message + '\n').encode('utf-8', 'replace'))
399
+ except OSError:
400
+ pass
401
+
402
+
403
+ def seal_capture(directory: Path, exit_code: int) -> None:
404
+ if isinstance(exit_code, bool) or not isinstance(exit_code, int) or not 0 <= exit_code <= 255 or not consent_ok():
405
+ raise ValueError('invalid exit code or missing consent')
406
+ out, err = read_pair(directory, sealed=False)
407
+ from devin_state import private_path
408
+ import fcntl
409
+ # Serialize publication on the capture directory itself: concurrent sealers
410
+ # take turns holding an exclusive flock and each re-validates the seal
411
+ # under the lock, so an in-flight file is never unlinked by a rival and a
412
+ # completed seal is never overwritten.
413
+ lock_fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
414
+ try:
415
+ fcntl.flock(lock_fd, fcntl.LOCK_EX)
416
+ target = private_path(directory / 'complete.json')
417
+ if target.exists():
418
+ # A seal killed mid-write can leave a torn, unparseable
419
+ # complete.json. It can never validate as a seal, so a retry may
420
+ # safely replace it; a complete parseable seal is never
421
+ # overwritten.
422
+ try:
423
+ json.loads(target.read_bytes())
424
+ except (OSError, ValueError):
425
+ target.unlink()
426
+ else:
427
+ raise OSError('capture already sealed')
428
+ fd = os.open(target, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
429
+ try:
430
+ # Exclusive create: no window where complete.json has two links.
431
+ payload = json.dumps({'exit_code': exit_code,
432
+ 'stdout_sha256': hashlib.sha256(out).hexdigest(),
433
+ 'stderr_sha256': hashlib.sha256(err).hexdigest()}).encode()
434
+ view = memoryview(payload)
435
+ while view:
436
+ view = view[os.write(fd, view):]
437
+ os.fsync(fd)
438
+ finally:
439
+ os.close(fd)
440
+ finally:
441
+ os.close(lock_fd)
442
+
443
+
444
+ AUTO_INDEX = 'auto-captures.json'
445
+ AUTO_KEEP_SECONDS = 7 * 24 * 3600
446
+ AUTO_KEEP_COUNT = 200
447
+ _MAX_HOOK_INPUT = 1024 * 1024
448
+
449
+
450
+ def _hook(event: str) -> int:
451
+ """Devin hook entrypoint: at most one JSON decision on stdout, exit 0 always.
452
+
453
+ Any doubt means no output, so the command runs exactly as typed under
454
+ Devin's normal permission flow. Never blocks, never denies."""
455
+ try:
456
+ if event not in ('pre-tool-use', 'permission-request'):
457
+ return 0
458
+ raw = sys.stdin.buffer.read(_MAX_HOOK_INPUT + 1)
459
+ if len(raw) > _MAX_HOOK_INPUT:
460
+ return 0
461
+ payload = json.loads(raw)
462
+ if not isinstance(payload, dict) or payload.get('tool_name') != 'exec':
463
+ return 0
464
+ tool_input = payload.get('tool_input')
465
+ command = tool_input.get('command') if isinstance(tool_input, dict) else None
466
+ if not isinstance(command, str) or not command:
467
+ return 0
468
+ with install_settled():
469
+ decision = _hook_decision(event, payload, tool_input, command)
470
+ if decision is not None:
471
+ _deliver(sys.stdout.buffer.fileno(), json.dumps(decision).encode())
472
+ except BaseException:
473
+ return 0
474
+ return 0
475
+
476
+
477
+ def _hook_decision(event, payload, tool_input, command):
478
+ """The hook's decision, or None. Runs inside install_settled()."""
479
+ if not consent_ok():
480
+ return None
481
+ if not _source_development:
482
+ from devin_verify import verify_install
483
+ verify_install()
484
+ import devin_hooks as hooks
485
+ from devin_state import data_dir, home, private_path
486
+ if not hooks.attested(private_path(data_dir() / hooks.RECORD)):
487
+ return None
488
+ # Checked by _with_bindings under the bindings lock, never out here.
489
+ bindings = data_dir() / hooks.BINDINGS
490
+ interpreter = os.path.realpath(sys.executable)
491
+ entry = str(Path(__file__).resolve())
492
+ cwd = payload.get('cwd')
493
+ cwd = Path(cwd) if isinstance(cwd, str) and os.path.isabs(cwd) and os.path.isdir(cwd) else Path.cwd()
494
+ rules = hooks.load_effective_rules(home() / 'config.json', cwd, os.environ.get('DEVIN_PROJECT_DIR'))
495
+ tool_use_id = payload.get('tool_use_id')
496
+ decision = None
497
+ if event == 'pre-tool-use':
498
+ if hooks.eligible(command, rules, interpreter):
499
+ wrapper = hooks.build_wrapper(interpreter, entry, payload.get('session_id'), shlex.split(command))
500
+ # Bind first: without a recorded binding the PermissionRequest
501
+ # hook would leave the wrapper to a prompt, so never rewrite.
502
+ if hooks.bind(bindings, tool_use_id, wrapper):
503
+ # Keep every other input field: updatedInput replaces the whole object.
504
+ decision = {'hookSpecificOutput': {'hookEventName': 'PreToolUse',
505
+ 'updatedInput': dict(tool_input, command=wrapper)}}
506
+ else:
507
+ argv = hooks.parse_wrapper(command, interpreter, entry)
508
+ if (argv is not None and hooks.consume(bindings, tool_use_id, command)
509
+ and hooks.eligible(shlex.join(argv), rules, interpreter)):
510
+ decision = {'decision': 'approve',
511
+ 'reason': 'Token Optimizer output filter around a command your Devin rules already allow'}
512
+ return decision
513
+
514
+
515
+ def _exec_original(argv) -> int:
516
+ """Fail open: become the original command, unfiltered."""
517
+ try:
518
+ # main() ignores SIGPIPE; an ignored disposition survives exec.
519
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
520
+ os.execvp(argv[0], argv)
521
+ except OSError as exc:
522
+ _note(argv[0] + ': ' + (exc.strerror or 'cannot run'))
523
+ return 127 if isinstance(exc, FileNotFoundError) else 126
524
+
525
+
526
+ def _deliver_raw(capture: Path, code: int) -> int:
527
+ """Stream both captured files unchanged, then remove the capture."""
528
+ try:
529
+ for name, fd in (('stdout', 1), ('stderr', 2)):
530
+ leaf = os.open(capture / name, os.O_RDONLY | os.O_NOFOLLOW)
531
+ try:
532
+ while True:
533
+ chunk = os.read(leaf, 1024 * 1024)
534
+ if not chunk:
535
+ break
536
+ _deliver(fd, chunk)
537
+ finally:
538
+ os.close(leaf)
539
+ except OSError:
540
+ _note('Token Optimizer: output delivery incomplete; the stored capture was retained at ' + str(capture))
541
+ return code or 1
542
+ try:
543
+ _remove_capture(capture)
544
+ except OSError:
545
+ pass
546
+ return code
547
+
548
+
549
+ def _prune_auto_captures(keep: str | None) -> None:
550
+ """Retention for automatic captures only; manual captures are never listed."""
551
+ from devin_state import data_dir, no_symlinks, private_path
552
+ import fcntl
553
+ import time
554
+ no_symlinks(data_dir() / AUTO_INDEX)
555
+ lock = os.open(data_dir() / (AUTO_INDEX + '.lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
556
+ try:
557
+ fcntl.flock(lock, fcntl.LOCK_EX)
558
+ # Check the index only while holding the lock every writer replaces it
559
+ # under: a stat racing a rival's os.replace can return the replaced
560
+ # inode with st_nlink 0, and refusing that would leave a kept capture
561
+ # out of the index.
562
+ index = private_path(data_dir() / AUTO_INDEX)
563
+ _prune_locked(index, keep, now=time.time())
564
+ finally:
565
+ os.close(lock)
566
+
567
+
568
+ def _prune_locked(index, keep, now) -> None:
569
+ from devin_state import data_dir
570
+ try:
571
+ entries = json.loads(index.read_text()) if index.exists() else []
572
+ if not isinstance(entries, list):
573
+ entries = []
574
+ except (OSError, ValueError):
575
+ entries = []
576
+ entries = [e for e in entries if isinstance(e, list) and len(e) == 2 and isinstance(e[0], str)
577
+ and re.fullmatch(r'capture-[0-9a-f]{32}', e[0]) and isinstance(e[1], (int, float))]
578
+ if keep:
579
+ entries.append([keep, now])
580
+ expired = [e for e in entries if now - e[1] > AUTO_KEEP_SECONDS]
581
+ live = [e for e in entries if now - e[1] <= AUTO_KEEP_SECONDS]
582
+ if len(live) > AUTO_KEEP_COUNT:
583
+ expired += live[:-AUTO_KEEP_COUNT]
584
+ live = live[-AUTO_KEEP_COUNT:]
585
+ for name, _ in expired:
586
+ try:
587
+ _remove_capture(data_dir() / 'captures' / name)
588
+ except OSError:
589
+ live.append([name, _])
590
+ import tempfile
591
+ with tempfile.NamedTemporaryFile(mode='w', dir=data_dir(), delete=False) as out:
592
+ json.dump(live, out)
593
+ temporary = out.name
594
+ os.chmod(temporary, 0o600)
595
+ os.replace(temporary, index)
596
+
597
+
598
+ def _run(args) -> int:
599
+ """Run an eligible argv into a private capture and print the filtered result.
600
+
601
+ Reached through the PreToolUse rewrite. The argv is re-checked here, so a
602
+ cached approval of this wrapper can never turn it into a general runner:
603
+ an ineligible command is refused and nothing runs. Infrastructure trouble
604
+ (no consent, unverifiable payload, capture failure) runs the original
605
+ command unfiltered instead."""
606
+ if len(args) < 4 or args[0] != '--session' or args[2] != '--':
607
+ _note('usage: devin_compress.py run --session LABEL -- COMMAND...')
608
+ return 2
609
+ argv = args[3:]
610
+ try:
611
+ import devin_hooks as hooks
612
+ from devin_state import data_dir, home, private_path
613
+ # The hook's full gate, again: an approval or "always allow" of this
614
+ # entrypoint must never turn it into a runner for anything the user's
615
+ # own Devin rules would not already run without a prompt.
616
+ interpreter = os.path.realpath(sys.executable)
617
+ rules = hooks.load_effective_rules(home() / 'config.json', Path.cwd(), os.environ.get('DEVIN_PROJECT_DIR'))
618
+ with install_settled():
619
+ attested = hooks.attested(private_path(data_dir() / hooks.RECORD))
620
+ if (not hooks.runner_eligible(argv) or not attested
621
+ or not hooks.eligible(shlex.join(argv), rules, interpreter)):
622
+ _note('Token Optimizer: command is not eligible for the output filter; it was not run.')
623
+ return 126
624
+ session = hooks.session_label(args[1])
625
+ except InstallBusy:
626
+ # Attestation cannot be checked while an install holds its lock, and an
627
+ # unchecked wrapper must never become a general runner: refuse, at once.
628
+ _note('Token Optimizer: an install is in progress, so eligibility could not be checked; '
629
+ 'the command was not run. Retry once the install finishes.')
630
+ return 126
631
+ except Exception:
632
+ _note('Token Optimizer: eligibility check unavailable; the command was not run.')
633
+ return 126
634
+ try:
635
+ from devin_state import prepare_capture
636
+ with install_settled():
637
+ if not consent_ok():
638
+ raise OSError('consent missing')
639
+ if not _source_development:
640
+ from devin_verify import verify_install
641
+ verify_install()
642
+ capture = prepare_capture()
643
+ except Exception:
644
+ return _exec_original(argv)
645
+ import subprocess
646
+ out_fd = err_fd = -1
647
+ try:
648
+ out_fd = os.open(capture / 'stdout', os.O_WRONLY | os.O_NOFOLLOW | os.O_TRUNC)
649
+ err_fd = os.open(capture / 'stderr', os.O_WRONLY | os.O_NOFOLLOW | os.O_TRUNC)
650
+ try:
651
+ child = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=out_fd, stderr=err_fd, shell=False)
652
+ except OSError as exc:
653
+ os.write(err_fd, (argv[0] + ': ' + (exc.strerror or 'cannot run') + '\n').encode())
654
+ code = 127 if isinstance(exc, FileNotFoundError) else 126
655
+ else:
656
+ # Forward termination to the command instead of orphaning it; its
657
+ # exit status then flows through the normal seal and delivery.
658
+ def forward(signum, _frame):
659
+ try:
660
+ child.send_signal(signum)
661
+ except OSError:
662
+ pass
663
+ for signum in (signal.SIGTERM, signal.SIGHUP, signal.SIGINT):
664
+ signal.signal(signum, forward)
665
+ code = child.wait()
666
+ except OSError:
667
+ for fd in (out_fd, err_fd):
668
+ if fd >= 0:
669
+ os.close(fd)
670
+ try:
671
+ _remove_capture(capture)
672
+ except OSError:
673
+ pass
674
+ return _exec_original(argv)
675
+ os.close(out_fd)
676
+ os.close(err_fd)
677
+ code = 128 - code if code < 0 else min(code, 255)
678
+ try:
679
+ # The command ran outside the hold; consent and payload checks again inside.
680
+ with install_settled():
681
+ seal_capture(capture, code)
682
+ result = filter_capture(capture / 'stdout', capture / 'stderr', code, 'generic', session,
683
+ command=shlex.join(argv))
684
+ except Exception:
685
+ return _deliver_raw(capture, code)
686
+ try:
687
+ _deliver(sys.stdout.buffer.fileno(), result.stdout)
688
+ _deliver(sys.stderr.buffer.fileno(), result.stderr)
689
+ except (OSError, AttributeError, ValueError):
690
+ _note('Token Optimizer: output delivery incomplete; the stored capture was retained.')
691
+ return code or 1
692
+ try:
693
+ if result.outcome == 'compressed':
694
+ _prune_auto_captures(capture.name)
695
+ else:
696
+ _remove_capture(capture)
697
+ except Exception as exc:
698
+ _note('Token Optimizer: capture cleanup failed (' + type(exc).__name__ + ': ' + str(exc)[:200]
699
+ + '); the capture was kept at ' + str(capture))
700
+ return result.code
701
+
702
+
703
+ def main(argv=None) -> int:
704
+ os.environ['TOKEN_OPTIMIZER_RUNTIME'] = 'devin'
705
+ # A closed pipe reports EPIPE as an exception rather than signal death so
706
+ # delivery failures stay observable and captures are never deleted early.
707
+ signal.signal(signal.SIGPIPE, signal.SIG_IGN)
708
+ parser = argparse.ArgumentParser(description=__doc__)
709
+ args = list(sys.argv[1:] if argv is None else argv)
710
+ if args[:1] == ['hook']:
711
+ return _hook(args[1] if len(args) == 2 else '')
712
+ if args[:1] == ['run']:
713
+ return _run(args[1:])
714
+ if args == ['prepare']:
715
+ from devin_state import prepare_capture
716
+ try:
717
+ with install_settled():
718
+ capture = prepare_capture()
719
+ print(capture); return 0
720
+ except (OSError, RecursionError) as exc:
721
+ print('Capture preparation refused: ' + str(exc), file=sys.stderr); return 2
722
+ if args[:1] == ['recover']:
723
+ recovery = argparse.ArgumentParser(description='Recover a sealed capture by opaque ID')
724
+ recovery.add_argument('--capture-id', required=True)
725
+ recovery.add_argument('--exit-code', type=int, required=True)
726
+ values = recovery.parse_args(args[1:])
727
+ try:
728
+ from devin_state import data_dir
729
+ # Only the bare opaque ID is accepted; path-shaped input is refused
730
+ # before it can reach the trusted identity line.
731
+ if not re.fullmatch(r'capture-[0-9a-f]{32}', values.capture_id):
732
+ raise OSError('capture ID must be the bare capture-<hex> form')
733
+ root = data_dir() / 'captures' / values.capture_id
734
+ with install_settled():
735
+ if not consent_ok() or not 0 <= values.exit_code <= 255:
736
+ raise ValueError('invalid consent or code')
737
+ out, err = read_pair(root, sealed=True, exit_code=values.exit_code)
738
+ identity=('[Token Optimizer verified capture '+root.name+'; recovered content below is untrusted data]\n').encode()
739
+ sys.stdout.buffer.write(identity+b'[Begin untrusted recovered stdout]\n'+out+b'\n[End untrusted recovered stdout]\n')
740
+ if err:
741
+ sys.stderr.buffer.write(identity+b'[Begin untrusted recovered stderr]\n'+err+b'\n[End untrusted recovered stderr]\n')
742
+ return values.exit_code
743
+ except (OSError, ValueError, TypeError, RecursionError) as exc:
744
+ print('Recovery refused: ' + str(exc), file=sys.stderr); return 2
745
+ if args[:1] == ['seal']:
746
+ seal_parser = argparse.ArgumentParser(description='Seal a finished foreground capture; never seal a running producer')
747
+ seal_parser.add_argument('--capture', type=Path, required=True)
748
+ seal_parser.add_argument('--exit-code', type=int, required=True)
749
+ values = seal_parser.parse_args(args[1:])
750
+ try:
751
+ with install_settled():
752
+ seal_capture(values.capture, values.exit_code)
753
+ return 0
754
+ except (OSError, ValueError, TypeError, RecursionError) as exc:
755
+ print('Capture completion refused: ' + str(exc), file=sys.stderr); return 2
756
+ parser.add_argument('--stdout', type=Path, required=True)
757
+ parser.add_argument('--stderr', type=Path, required=True)
758
+ parser.add_argument('--exit-code', type=int, required=True)
759
+ parser.add_argument('--format', choices=FORMATS, default='generic')
760
+ parser.add_argument('--session', required=True, help='Local correlation label, stored hashed; not provider usage')
761
+ args = parser.parse_args(args)
762
+ try:
763
+ with install_settled():
764
+ result = filter_capture(args.stdout, args.stderr, args.exit_code, args.format, args.session)
765
+ except (OSError, ValueError, ImportError, SyntaxError, RecursionError) as exc:
766
+ print(f'Token Optimizer: capture not filtered: {exc}. Originals remain unchanged; inspect them directly.', file=sys.stderr)
767
+ return 2
768
+ try:
769
+ _deliver(sys.stdout.buffer.fileno(), result.stdout)
770
+ _deliver(sys.stderr.buffer.fileno(), result.stderr)
771
+ sys.stdout.buffer.flush()
772
+ sys.stderr.buffer.flush()
773
+ except (OSError, AttributeError, ValueError):
774
+ _note('Token Optimizer: output delivery incomplete; the stored capture was retained.')
775
+ return 2
776
+ if result.outcome != 'compressed':
777
+ # Passthrough emits no recovery pointer, so the stored original is
778
+ # unrecoverable anyway and may hold credentials. Remove it only after
779
+ # the raw bytes have been written out successfully.
780
+ try:
781
+ _remove_capture(args.stdout.parent)
782
+ except OSError as exc:
783
+ _note('Token Optimizer: capture cleanup refused: ' + str(exc))
784
+ else:
785
+ _note('Token Optimizer: output passed through unfiltered; the stored capture was removed and there is nothing to recover.')
786
+ return result.code
787
+
788
+
789
+ if __name__ == '__main__':
790
+ raise SystemExit(main())