@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,119 @@
1
+ """Source-only imports for the installed payload. Never trust cached bytecode."""
2
+ import importlib.abc
3
+ import importlib.util
4
+ import hashlib
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import stat
9
+ import sys
10
+
11
+ PAYLOAD = ('devin_compress.py', 'devin_state.py', 'devin_doctor.py', 'devin_verify.py', 'devin_source.py',
12
+ 'bash_compress.py', 'bash_whitelist.py', 'credential_patterns.py',
13
+ 'token_estimate.py', 'command_filters.py', 'runtime_env.py', 'py_trust.py', 'plugin_env.py', 'refetch_fingerprint.py',
14
+ 'devin_hooks.py')
15
+ ALLOWED_MODULES = frozenset(Path(name).stem for name in PAYLOAD)
16
+
17
+ # Repo names outside the installed closure must never fall back to sys.path.
18
+ REPO_MODULES = frozenset((
19
+ 'activity_tracker', 'antigravity_doctor', 'antigravity_hook_bridge', 'antigravity_install',
20
+ 'antigravity_proto', 'antigravity_session', 'antigravity_state', 'archive_result',
21
+ 'bash_compress', 'bash_compress_hook', 'bash_hook', 'bash_whitelist', 'benchmark', 'cloud_kit',
22
+ 'build_output_compress', 'codex_command_compress', 'codex_compact_prompt', 'codex_doctor',
23
+ 'codex_hook_bridge', 'codex_install', 'codex_io', 'codex_log_index', 'codex_models',
24
+ 'codex_session', 'codex_state', 'codex_statusline', 'command_filters',
25
+ 'compression_backfill', 'compression_log', 'context_intel', 'context_pressure',
26
+ 'copilot_doctor', 'copilot_hook_bridge', 'copilot_install', 'copilot_session',
27
+ 'copilot_state', 'copilot_vscode', 'cowork_doctor', 'cowork_install',
28
+ 'credential_patterns', 'cursor_doctor', 'cursor_hook_bridge', 'cursor_install',
29
+ 'cursor_session', 'cursor_state', 'delta_diff', 'detectors', 'deterministic_candidates',
30
+ 'devin_compress', 'devin_doctor', 'devin_hooks', 'devin_install', 'devin_source', 'devin_state',
31
+ 'devin_verify', 'grok_doctor', 'grok_hook_bridge', 'grok_install', 'grok_session',
32
+ 'grok_state', 'hermes_doctor', 'hermes_hook_bridge', 'hermes_install', 'hermes_session',
33
+ 'hermes_state', 'hook_io', 'hook_runtime', 'injection', 'install_reconcile', 'measure',
34
+ 'outline', 'pipeline_analyzer', 'plugin_env', 'py_trust', 'quality_cache_gate',
35
+ 'read_cache', 'recovery_output', 'refetch_fingerprint', 'refetch_guard', 'routing_advisor',
36
+ 'runtime_env', 'session_store', 'spawn_utils', 'structure_map', 'structure_map_ts',
37
+ 'structure_replay', 'thrash_guard', 'token_estimate', 'tool_search_diagnostic', 'utf8_io',
38
+ ))
39
+
40
+ class SourceOnly(importlib.abc.MetaPathFinder, importlib.abc.Loader):
41
+ def __init__(self, root):
42
+ self.root=Path(root)
43
+ self.digests={}
44
+ def find_spec(self, fullname, path=None, target=None):
45
+ if fullname not in ALLOWED_MODULES:
46
+ if fullname.split('.')[0] in REPO_MODULES:
47
+ raise ImportError('repo module outside Devin payload')
48
+ return None
49
+ candidate=self.root/(fullname+'.py')
50
+ try:info=candidate.lstat()
51
+ except FileNotFoundError as exc:raise ImportError('manifested payload source missing: '+str(candidate)) from exc
52
+ if not stat.S_ISREG(info.st_mode):raise ImportError('regular payload source required')
53
+ return importlib.util.spec_from_file_location(fullname,candidate,loader=self)
54
+ def create_module(self,spec):return None
55
+ def exec_module(self,module):
56
+ source=Path(module.__spec__.origin)
57
+ fd=os.open(source,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() or info.st_nlink!=1 or info.st_mode&0o077:
61
+ raise ImportError('private regular payload source required')
62
+ chunks=[];remaining=8*1024*1024+1
63
+ while remaining:
64
+ chunk=os.read(fd,min(65536,remaining))
65
+ if not chunk:break
66
+ chunks.append(chunk);remaining-=len(chunk)
67
+ content=b''.join(chunks)
68
+ if len(content)>8*1024*1024:raise ImportError('payload source exceeds bound')
69
+ finally:os.close(fd)
70
+ if hashlib.sha256(content).hexdigest()!=self.digests.get(str(source)):
71
+ raise ImportError('payload source differs from install manifest: '+str(source))
72
+ exec(compile(content,str(source),'exec'),module.__dict__)
73
+
74
+ def activate(root):
75
+ root=Path(root).resolve()
76
+ # Imported payload entrypoints activate again; do not evict in-progress modules.
77
+ for active in sys.meta_path:
78
+ if getattr(active,'_devin_source_root',None)==root:
79
+ return
80
+ finder=SourceOnly(root)
81
+ finder._devin_source_root=root
82
+ manifest=root.parent/'install.json'
83
+ fd=os.open(manifest,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK)
84
+ try:
85
+ info=os.fstat(fd)
86
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid!=os.geteuid()
87
+ or info.st_nlink!=1 or info.st_mode&0o077 or info.st_size>65536):
88
+ raise ImportError('private bounded install manifest required')
89
+ with os.fdopen(fd,'rb',closefd=False) as stream:
90
+ content=stream.read(65537)
91
+ finally:os.close(fd)
92
+ if len(content)>65536:raise ImportError('install manifest exceeds bound')
93
+ record=json.loads(content)
94
+ if not isinstance(record,dict) or record.get('owner')!='devin-output-filter-v1':
95
+ raise ImportError('invalid install manifest')
96
+ digests=record.get('files')
97
+ if not isinstance(digests,dict):raise ImportError('invalid install manifest files')
98
+ expected={str(root/name) for name in PAYLOAD}
99
+ if not expected.issubset(digests):raise ImportError('missing payload commitments')
100
+ if any(not isinstance(digests[name],str) or len(digests[name])!=64
101
+ or any(ch not in '0123456789abcdef' for ch in digests[name]) for name in expected):
102
+ raise ImportError('invalid payload digest')
103
+ finder.digests={name:digests[name] for name in expected}
104
+ # Remove root, ancestor and descendant routes, including current-directory and symlink aliases.
105
+ # This is an activation-time boundary, not control over later path mutations.
106
+ retained=[]
107
+ for entry in sys.path:
108
+ if not isinstance(entry,str):continue
109
+ try:
110
+ candidate=Path(entry or os.getcwd()).resolve()
111
+ if root==candidate or root.is_relative_to(candidate) or candidate.is_relative_to(root):continue
112
+ except (OSError,RuntimeError,ValueError):
113
+ continue
114
+ retained.append(entry)
115
+ sys.path[:]=retained
116
+ for name in tuple(sys.modules):
117
+ if name.split('.')[0] in REPO_MODULES:
118
+ sys.modules.pop(name,None)
119
+ sys.meta_path.insert(0,finder)
@@ -0,0 +1,330 @@
1
+ """Private local output estimates for Devin. Never stores captured text."""
2
+ from __future__ import annotations
3
+ import contextlib
4
+
5
+ import hashlib
6
+ import hmac
7
+ import secrets
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import sqlite3
13
+ import stat
14
+ import tempfile
15
+ import time
16
+ import uuid
17
+
18
+ SOURCE = 'devin_captured_output_estimate'
19
+ MAX_RECORDS = 10000
20
+ RETENTION_DAYS = 30
21
+
22
+
23
+ def home() -> Path:
24
+ base = Path.home().absolute()
25
+ raw = os.environ.get('TOKEN_OPTIMIZER_DEVIN_HOME')
26
+ if raw:
27
+ candidate = Path(raw)
28
+ else:
29
+ xdg = os.environ.get('XDG_CONFIG_HOME')
30
+ candidate = Path(xdg) / 'devin' if xdg else base / '.config' / 'devin'
31
+ if not candidate.is_absolute():
32
+ raise OSError('Devin home must be an absolute path inside HOME')
33
+ # A symlinked component is the first thing to name: resolving through it
34
+ # would mask the real cause behind an 'outside HOME' error.
35
+ no_symlinks(candidate)
36
+ resolved = candidate.resolve()
37
+ if not resolved.is_relative_to(base.resolve()):
38
+ raise OSError('Devin home must be an absolute path inside HOME')
39
+ if resolved == base.resolve() or resolved.name in ('.claude', '.codex', '.cursor', '.config'):
40
+ raise OSError('Devin home must be a dedicated directory, not HOME or another tool home')
41
+ if any(not ch.isprintable() or ch == '`' for ch in str(candidate)):
42
+ raise OSError('unsupported control/markdown characters in home path')
43
+ return candidate.resolve()
44
+
45
+
46
+ def loader_path_info() -> dict:
47
+ """Documented loader location, not evidence that an agent loaded the skill."""
48
+ documented = Path.home().resolve() / '.config' / 'devin'
49
+ installed = home()
50
+ return {
51
+ 'documented_home': str(documented),
52
+ 'installed_home': str(installed),
53
+ 'status': 'documented_default' if installed == documented else 'nondefault_discovery_unknown',
54
+ 'desktop_loading_verified': False,
55
+ }
56
+
57
+
58
+ NUMERIC_STATE_LEAVES = ('metrics.db', 'session-salt', 'metrics.db-journal', 'metrics.db-wal', 'metrics.db-shm')
59
+
60
+
61
+ def data_dir() -> Path:
62
+ return home() / 'token-optimizer'
63
+
64
+
65
+ def no_symlinks(path: Path) -> None:
66
+ for component in [*reversed(path.absolute().parents), path.absolute()]:
67
+ if component.is_symlink():
68
+ raise OSError('symlink path refused: ' + str(component))
69
+
70
+
71
+ def private_dir(path: Path) -> Path:
72
+ """Create path and missing ancestors at mode 0700. Directories this creates
73
+ are always owner-only; pre-existing ancestors must not be writable by
74
+ group/other unless sticky, or another local user could rename the private
75
+ tree out from under the adapter."""
76
+ no_symlinks(path)
77
+ missing = []
78
+ cursor = path
79
+ while not cursor.exists():
80
+ missing.append(cursor)
81
+ cursor = cursor.parent
82
+ for ancestor in (cursor, *cursor.parents):
83
+ info = ancestor.lstat()
84
+ if info.st_mode & 0o022 and not info.st_mode & stat.S_ISVTX:
85
+ raise OSError('group/other-writable ancestor directory refused: ' + str(ancestor) + ' (chmod go-w it, or set its sticky bit)')
86
+ for folder in reversed(missing):
87
+ folder.mkdir(mode=0o700)
88
+ return path
89
+
90
+
91
+ def private_path(path: Path, *, directory=False, create=False) -> Path:
92
+ no_symlinks(path)
93
+ if create:
94
+ if directory:
95
+ private_dir(path)
96
+ elif not path.exists():
97
+ try:
98
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
99
+ os.close(fd)
100
+ except FileExistsError:
101
+ no_symlinks(path)
102
+ try:
103
+ info = path.lstat()
104
+ except FileNotFoundError:
105
+ return path
106
+ else:
107
+ if not directory and not stat.S_ISREG(info.st_mode):
108
+ raise OSError('regular state file required: ' + str(path))
109
+ if directory != stat.S_ISDIR(info.st_mode):
110
+ raise OSError('unexpected state type: ' + str(path))
111
+ if info.st_uid != os.geteuid() or info.st_mode & 0o077 or info.st_nlink != 1 and not directory:
112
+ raise OSError('adapter state must be owner-only: ' + str(path) +
113
+ ' (owned by you, ' + ('chmod 700' if directory else 'chmod 600, no extra hard links') + ')')
114
+ return path
115
+
116
+
117
+ class InstallBusy(OSError):
118
+ """install.lock stayed exclusively held for the whole bounded wait. An
119
+ OSError, so every caller takes its existing fail-open or refuse path."""
120
+
121
+
122
+ INSTALL_WAIT_SECONDS = 2.0
123
+
124
+
125
+ @contextlib.contextmanager
126
+ def install_settled():
127
+ """Hold install.lock shared. Install, refresh and uninstall replace
128
+ consent.json, install.json, the payload and hooks.json only while holding
129
+ it exclusively, and a stat racing os.replace can return the replaced inode
130
+ with st_nlink 0, so checks of those files belong inside this hold. Before
131
+ any install there is no lock and nothing to replace.
132
+
133
+ The wait is bounded: a hung or stopped installer must never freeze a hook
134
+ or a run, so after INSTALL_WAIT_SECONDS this raises InstallBusy."""
135
+ import errno
136
+ import fcntl
137
+ try:
138
+ lock = data_dir() / 'install.lock'
139
+ no_symlinks(lock)
140
+ fd = os.open(lock, os.O_RDONLY | os.O_NOFOLLOW)
141
+ except OSError:
142
+ fd = -1 # the gated check reports any real problem itself
143
+ try:
144
+ if fd >= 0:
145
+ deadline = time.monotonic() + INSTALL_WAIT_SECONDS
146
+ while True:
147
+ try:
148
+ fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
149
+ break
150
+ except OSError as exc:
151
+ if exc.errno not in (errno.EAGAIN, errno.EWOULDBLOCK, errno.EACCES):
152
+ raise
153
+ if time.monotonic() >= deadline:
154
+ raise InstallBusy('a Token Optimizer install is still in progress')
155
+ time.sleep(0.02)
156
+ yield
157
+ finally:
158
+ if fd >= 0:
159
+ os.close(fd)
160
+
161
+
162
+ def enable_consent() -> None:
163
+ private_path(data_dir(), directory=True, create=True)
164
+ target = private_path(data_dir() / 'consent.json')
165
+ with tempfile.NamedTemporaryFile(mode='w', dir=data_dir(), delete=False) as out:
166
+ json.dump({'devin_consent': True, 'schema': 1}, out)
167
+ temporary = out.name
168
+ os.replace(temporary, target)
169
+
170
+
171
+ def consent_ok() -> bool:
172
+ try:
173
+ private_path(data_dir(), directory=True)
174
+ p = private_path(data_dir() / 'consent.json')
175
+ return json.loads(p.read_text()) == {'devin_consent': True, 'schema': 1}
176
+ except (OSError, ValueError, TypeError, RecursionError):
177
+ return False
178
+
179
+
180
+ def record(session: str, original: str, delivered: str, outcome: str) -> None:
181
+ from token_estimate import estimate_tokens
182
+ private_path(data_dir(), directory=True)
183
+ target = private_path(data_dir() / 'metrics.db', create=True)
184
+ # SQLite sidecars inherit the DB's private mode. Refuse existing redirects.
185
+ for suffix in ('-journal', '-wal', '-shm'):
186
+ sidecar=Path(str(target)+suffix)
187
+ no_symlinks(sidecar)
188
+ try:info=sidecar.lstat()
189
+ except FileNotFoundError:continue
190
+ if not stat.S_ISREG(info.st_mode) or info.st_uid!=os.geteuid():
191
+ raise OSError('foreign SQLite sidecar refused')
192
+ # 'with connect()' only commits; the connection must also be closed.
193
+ with contextlib.closing(sqlite3.connect(target, timeout=10)) as db:
194
+ with db:
195
+ db.execute('CREATE TABLE IF NOT EXISTS events (id TEXT PRIMARY KEY, session_key TEXT, created REAL, source TEXT, original_estimate INTEGER, delivered_estimate INTEGER, outcome TEXT)')
196
+ db.execute('INSERT INTO events VALUES (?,?,?,?,?,?,?)',
197
+ (uuid.uuid4().hex, hmac.new(session_salt(), session.encode(), hashlib.sha256).hexdigest(), time.time(),
198
+ SOURCE, estimate_tokens(original), estimate_tokens(delivered), outcome))
199
+ db.execute('DELETE FROM events WHERE created < ?', (time.time() - RETENTION_DAYS * 86400,))
200
+ db.execute('DELETE FROM events WHERE id IN (SELECT id FROM events ORDER BY created DESC LIMIT -1 OFFSET ?)', (MAX_RECORDS,))
201
+
202
+
203
+ def summary() -> dict:
204
+ result = {'source': SOURCE, 'provider_tokens': None, 'cost': None,
205
+ 'quality_score': None, 'delivery_verified': False, 'events': 0,
206
+ 'original_estimate': 0, 'delivered_estimate': 0,
207
+ 'estimated_output_reduction': 0}
208
+ private_path(data_dir(), directory=True)
209
+ target = private_path(data_dir() / 'metrics.db')
210
+ if not target.exists():
211
+ return result
212
+ with contextlib.closing(sqlite3.connect(target.as_uri() + '?mode=ro', uri=True)) as db:
213
+ row = db.execute('SELECT COUNT(*), COALESCE(SUM(original_estimate),0), COALESCE(SUM(delivered_estimate),0) FROM events WHERE created >= ?', (time.time() - RETENTION_DAYS * 86400,)).fetchone()
214
+ result.update(events=row[0], original_estimate=row[1], delivered_estimate=row[2],
215
+ estimated_output_reduction=row[1] - row[2])
216
+ return result
217
+
218
+
219
+ def session_salt() -> bytes:
220
+ p = private_path(data_dir() / 'session-salt', create=True)
221
+ import fcntl
222
+ with p.open('r+b') as handle:
223
+ fcntl.flock(handle, fcntl.LOCK_EX)
224
+ content = handle.read()
225
+ if not content:
226
+ content = secrets.token_bytes(32)
227
+ handle.write(content); handle.flush()
228
+ if len(content) != 32:
229
+ raise OSError('invalid session salt')
230
+ return content
231
+
232
+
233
+ def prepare_capture() -> Path:
234
+ if not consent_ok():
235
+ raise OSError('local data consent required')
236
+ root = private_path(data_dir() / 'captures', directory=True, create=True)
237
+ result = root / ('capture-' + uuid.uuid4().hex)
238
+ result.mkdir(mode=0o700)
239
+ temporary = None
240
+ try:
241
+ for name in ('stdout', 'stderr'):
242
+ private_path(result / name, create=True)
243
+ provenance = {}
244
+ for name in ('stdout', 'stderr'):
245
+ info = (result / name).stat()
246
+ provenance[name] = [info.st_dev, info.st_ino]
247
+ p = private_path(result / '.prepared')
248
+ # Atomic publish: a kill mid-write must never leave a torn .prepared.
249
+ with tempfile.NamedTemporaryFile(mode='w', dir=result, delete=False) as out:
250
+ temporary = out.name
251
+ out.write(json.dumps(provenance))
252
+ out.flush()
253
+ os.fsync(out.fileno())
254
+ os.replace(temporary, p)
255
+ except BaseException:
256
+ # Callers fall back to the original command; a half-made capture
257
+ # would otherwise stay on disk, unindexed and never cleaned up.
258
+ if temporary is not None:
259
+ with contextlib.suppress(OSError):
260
+ os.unlink(temporary)
261
+ with contextlib.suppress(OSError):
262
+ delete_capture(result)
263
+ raise
264
+ return result
265
+
266
+
267
+ def directory_fd(path: Path) -> int:
268
+ """Open absolute directory components without following any symlink."""
269
+ if not path.is_absolute():
270
+ raise OSError('absolute directory required')
271
+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
272
+ fd = os.open('/', flags)
273
+ try:
274
+ for component in path.parts[1:]:
275
+ if component in ('.', '..'):
276
+ raise OSError('relative directory component refused')
277
+ next_fd = os.open(component, flags, dir_fd=fd)
278
+ os.close(fd); fd = next_fd
279
+ return fd
280
+ except Exception:
281
+ os.close(fd); raise
282
+
283
+
284
+ def delete_capture(directory: Path) -> None:
285
+ """Unlink a capture's fixed leaves and remove the capture directory,
286
+ contained to already-opened descriptors so a renamed or swapped directory
287
+ cannot redirect deletion outside the captures root. Foreign or unsafe
288
+ content keeps the directory in place; no path string is followed once the
289
+ descriptors are open."""
290
+ root = data_dir() / 'captures'
291
+ if not isinstance(directory, Path) or directory.parent != root or not re.fullmatch(r'capture-[0-9a-f]{32}', directory.name):
292
+ raise OSError('adapter-prepared capture required')
293
+ # Lexical pre-check only; the descriptor operations below are the boundary.
294
+ no_symlinks(directory)
295
+ for name in ('stdout', 'stderr', '.prepared', 'complete.json'):
296
+ no_symlinks(directory / name)
297
+ root_fd = directory_fd(root)
298
+ capture_fd = None
299
+ try:
300
+ try:
301
+ capture_fd = os.open(directory.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=root_fd)
302
+ except OSError:
303
+ return # Missing or swapped away before open: nothing here is ours.
304
+ info = os.fstat(capture_fd)
305
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077:
306
+ raise OSError('capture directory must be private')
307
+ for name in ('stdout', 'stderr', '.prepared', 'complete.json'):
308
+ try:
309
+ leaf = os.stat(name, dir_fd=capture_fd, follow_symlinks=False)
310
+ except FileNotFoundError:
311
+ continue
312
+ if stat.S_ISREG(leaf.st_mode):
313
+ os.unlink(name, dir_fd=capture_fd)
314
+ # Skip the rmdir when the name no longer points at the opened directory.
315
+ # rmdir only ever removes an EMPTY directory, so a swap between this
316
+ # check and the call cannot delete anyone's files.
317
+ try:
318
+ current = os.stat(directory.name, dir_fd=root_fd, follow_symlinks=False)
319
+ except FileNotFoundError:
320
+ return
321
+ if (current.st_dev, current.st_ino) != (info.st_dev, info.st_ino):
322
+ return
323
+ try:
324
+ os.rmdir(directory.name, dir_fd=root_fd)
325
+ except OSError:
326
+ pass
327
+ finally:
328
+ if capture_fd is not None:
329
+ os.close(capture_fd)
330
+ os.close(root_fd)
@@ -0,0 +1,67 @@
1
+ """Installed payload integrity/readiness shared by doctor and filter."""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import re
7
+ import stat
8
+ from pathlib import Path
9
+ import devin_state as state
10
+
11
+ from devin_source import PAYLOAD
12
+
13
+ def verify_install():
14
+ root=state.data_dir()
15
+ plugin=state.private_path(root/'plugin',directory=True)
16
+ for entry in plugin.iterdir():
17
+ if entry.name in PAYLOAD:
18
+ state.private_path(entry)
19
+ continue
20
+ if entry.name=='__pycache__':
21
+ state.no_symlinks(entry)
22
+ info=entry.lstat()
23
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid!=os.geteuid() or info.st_mode&0o022:
24
+ raise OSError('unsafe incidental cache directory')
25
+ for cached in entry.iterdir():
26
+ state.no_symlinks(cached)
27
+ try:
28
+ info=cached.lstat()
29
+ except FileNotFoundError:
30
+ continue # a concurrent import renamed its temporary file into place
31
+ # Python writes NAME.pyc.<digits> and renames it to NAME.pyc;
32
+ # parallel first runs see that in-flight file. It is never imported.
33
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid!=os.geteuid()
34
+ or info.st_nlink!=1 or info.st_mode&0o022
35
+ or not re.fullmatch(r'[\w.-]+\.pyc(?:\.[0-9]+)?',cached.name)):
36
+ raise OSError('unmanifested artifact in incidental cache: ' + str(cached) +
37
+ '; remove it and retry')
38
+ continue
39
+ raise OSError('unmanifested artifact in installed payload: ' + str(entry) +
40
+ '; remove it and retry')
41
+ manifest=state.private_path(root/'install.json')
42
+ if manifest.stat().st_nlink!=1:raise OSError('manifest hardlink refused')
43
+ try:
44
+ record=json.loads(manifest.read_text())
45
+ except (ValueError,RecursionError):
46
+ raise OSError('invalid installed payload manifest')
47
+ if not isinstance(record,dict) or not isinstance(record.get('files'),dict):
48
+ raise OSError('invalid installed payload manifest types')
49
+ if any(not isinstance(k,str) for k in record['files']):
50
+ raise OSError('invalid installed payload manifest')
51
+ if any(not isinstance(v,str) or len(v)!=64 or any(ch not in '0123456789abcdef' for ch in v) for v in record['files'].values()):
52
+ raise OSError('invalid manifest digest')
53
+ expected={str(root/'plugin'/name) for name in PAYLOAD}|{str(state.home()/'skills/token-optimizer-output/SKILL.md')}
54
+ if record.get('owner')!='devin-output-filter-v1' or set(record.get('files',{}))!=expected:
55
+ raise OSError('invalid installed payload manifest')
56
+ for name,digest in record['files'].items():
57
+ path=state.private_path(Path(name))
58
+ if path.stat().st_nlink!=1:raise OSError('payload hardlink refused')
59
+ content=path.read_bytes()
60
+ if hashlib.sha256(content).hexdigest()!=digest:raise OSError('installed payload missing or changed')
61
+ if path.suffix=='.py':compile(content,str(path),'exec')
62
+ # Name an unsafe data directory or consent file before reporting consent
63
+ # as missing: the record may be present and merely unreadable by policy.
64
+ state.private_path(state.data_dir(),directory=True)
65
+ state.private_path(state.data_dir()/'consent.json')
66
+ if not state.consent_ok():raise OSError('missing local data consent')
67
+ return True