@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.
- package/.claude-plugin/marketplace.json +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +448 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +788 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +149 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3633 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +141 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +93 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +379 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1011 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +288 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +426 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +400 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +716 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +59531 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1923 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
"""Automatic Devin compression: eligibility, permission proof and hook config.
|
|
2
|
+
|
|
3
|
+
Devin CLI runs Claude-style hooks. A PreToolUse hook may rewrite an ``exec``
|
|
4
|
+
command through ``hookSpecificOutput.updatedInput``, but Devin then checks
|
|
5
|
+
permissions against the REWRITTEN command: an approved ``git log`` would turn
|
|
6
|
+
into a prompt for the Python wrapper. The PermissionRequest hook clears that
|
|
7
|
+
prompt, under two hard conditions:
|
|
8
|
+
|
|
9
|
+
1. Binding. It approves only the exact wrapper bytes the PreToolUse hook
|
|
10
|
+
produced for the same ``tool_use_id``, once. Any other command, including
|
|
11
|
+
any other wrapper-shaped Python command, gets no decision.
|
|
12
|
+
2. Proof. A command is rewritten only when Devin's own documented rules show
|
|
13
|
+
it would have run WITHOUT a prompt in any mode: a user or project
|
|
14
|
+
``allow`` rule covers it, and no ``deny`` or ``ask`` rule at any readable
|
|
15
|
+
level touches it or the interpreter. Devin's built-in read-only classifier
|
|
16
|
+
is undocumented and organization rules are never stored locally, so
|
|
17
|
+
neither counts as proof: the owner must attest at install time that no
|
|
18
|
+
team policy applies. Any unreadable rule file means no rewrite.
|
|
19
|
+
|
|
20
|
+
Token Optimizer's whitelist only decides whether output is worth
|
|
21
|
+
compressing; it never stands in for a permission decision.
|
|
22
|
+
|
|
23
|
+
Pure logic only: no command execution, no output. The hook entrypoint and the
|
|
24
|
+
runner live in devin_compress.py; the installer and doctor share the config
|
|
25
|
+
helpers below.
|
|
26
|
+
"""
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
import re
|
|
33
|
+
import shlex
|
|
34
|
+
|
|
35
|
+
HOOK_EVENTS = {'PreToolUse': 'pre-tool-use', 'PermissionRequest': 'permission-request'}
|
|
36
|
+
HOOK_MATCHER = '^exec$'
|
|
37
|
+
HOOK_TIMEOUT = 10
|
|
38
|
+
BINDING_SECONDS = 600
|
|
39
|
+
BINDING_LIMIT = 256
|
|
40
|
+
TOOL_USE_ID_RE = re.compile(r'[A-Za-z0-9:#._-]{1,256}')
|
|
41
|
+
ATTESTATION = 'no-team-policy-attested'
|
|
42
|
+
RECORD = 'hooks.json'
|
|
43
|
+
BINDINGS = 'hook-bindings.json'
|
|
44
|
+
SESSION_RE = re.compile(r'[A-Za-z0-9][A-Za-z0-9._-]{0,127}')
|
|
45
|
+
DEFAULT_SESSION = 'devin-auto'
|
|
46
|
+
MAX_RULE_FILE = 1024 * 1024
|
|
47
|
+
MAX_WALK = 64
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _gates():
|
|
51
|
+
import bash_whitelist
|
|
52
|
+
return bash_whitelist
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _compression_enabled() -> bool:
|
|
56
|
+
try:
|
|
57
|
+
from plugin_env import is_v5_flag_enabled
|
|
58
|
+
return is_v5_flag_enabled('v5_bash_compress', 'TOKEN_OPTIMIZER_BASH_COMPRESS', default=True)
|
|
59
|
+
except Exception:
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def session_label(raw) -> str:
|
|
64
|
+
return raw if isinstance(raw, str) and SESSION_RE.fullmatch(raw) else DEFAULT_SESSION
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ── Devin permission rules ──────────────────────────────────────────────────
|
|
68
|
+
|
|
69
|
+
class RulesUnknown(Exception):
|
|
70
|
+
"""A rule file exists but cannot be read or parsed: decide nothing."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _read_rules(path: Path) -> dict | None:
|
|
74
|
+
try:
|
|
75
|
+
if not path.exists() and not path.is_symlink():
|
|
76
|
+
return None
|
|
77
|
+
if path.stat().st_size > MAX_RULE_FILE:
|
|
78
|
+
raise RulesUnknown(str(path))
|
|
79
|
+
record = json.loads(path.read_text(encoding='utf-8'))
|
|
80
|
+
except RulesUnknown:
|
|
81
|
+
raise
|
|
82
|
+
except (OSError, ValueError, RecursionError) as exc:
|
|
83
|
+
raise RulesUnknown(str(path)) from exc
|
|
84
|
+
if not isinstance(record, dict):
|
|
85
|
+
raise RulesUnknown(str(path))
|
|
86
|
+
permissions = record.get('permissions', {})
|
|
87
|
+
if not isinstance(permissions, dict):
|
|
88
|
+
raise RulesUnknown(str(path))
|
|
89
|
+
rules = {}
|
|
90
|
+
for kind in ('allow', 'ask', 'deny'):
|
|
91
|
+
values = permissions.get(kind, [])
|
|
92
|
+
if not isinstance(values, list) or not all(isinstance(v, str) for v in values):
|
|
93
|
+
raise RulesUnknown(str(path))
|
|
94
|
+
rules[kind] = values
|
|
95
|
+
return rules
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _project_rule_files(start: Path) -> list:
|
|
99
|
+
"""Project rule files from start up to the repository root, never past HOME."""
|
|
100
|
+
files, folder = [], start
|
|
101
|
+
stop = Path.home().resolve()
|
|
102
|
+
for _ in range(MAX_WALK):
|
|
103
|
+
for name in ('config.json', 'config.local.json'):
|
|
104
|
+
files.append(folder / '.devin' / name)
|
|
105
|
+
if (folder / '.git').exists() or folder.parent == folder or folder.resolve() == stop:
|
|
106
|
+
break
|
|
107
|
+
folder = folder.parent
|
|
108
|
+
else:
|
|
109
|
+
# Ran out of steps before the root: an unvisited ancestor may hold a
|
|
110
|
+
# deny rule, so the rules are unknown, not empty.
|
|
111
|
+
raise RulesUnknown(str(start))
|
|
112
|
+
return files
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def user_rule_files(user_config: Path) -> list:
|
|
116
|
+
return [user_config, user_config.with_name('config.local.json')]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def rule_files(user_config: Path, cwd: Path, project_dir: str | None = None) -> list:
|
|
120
|
+
"""Every file whose deny/ask rules can block: the user's and the project's."""
|
|
121
|
+
files = user_rule_files(user_config)
|
|
122
|
+
starts = [cwd]
|
|
123
|
+
if project_dir and os.path.isabs(project_dir):
|
|
124
|
+
starts.append(Path(project_dir))
|
|
125
|
+
for start in starts:
|
|
126
|
+
for path in _project_rule_files(start):
|
|
127
|
+
if path not in files:
|
|
128
|
+
files.append(path)
|
|
129
|
+
return files
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def load_rules(paths, allow_from=None) -> dict:
|
|
133
|
+
"""deny/ask from every file; allow only from allow_from (default: all).
|
|
134
|
+
|
|
135
|
+
Allow is the proof that Devin runs a command without a prompt. A cloned
|
|
136
|
+
repository's .devin/config.json must never supply that proof, so callers
|
|
137
|
+
pass the user's own files as allow_from; project files can only block."""
|
|
138
|
+
merged = {'allow': [], 'ask': [], 'deny': []}
|
|
139
|
+
for path in paths:
|
|
140
|
+
rules = _read_rules(path)
|
|
141
|
+
if rules:
|
|
142
|
+
for kind in merged:
|
|
143
|
+
if kind == 'allow' and allow_from is not None and path not in allow_from:
|
|
144
|
+
continue
|
|
145
|
+
merged[kind].extend(rules[kind])
|
|
146
|
+
return merged
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def load_effective_rules(user_config: Path, cwd: Path, project_dir: str | None = None) -> dict:
|
|
150
|
+
return load_rules(rule_files(user_config, cwd, project_dir), allow_from=user_rule_files(user_config))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
_EXEC_RULE = re.compile(r'(?i)exec(?:\((.*)\))?')
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _rule_prefix(rule: str):
|
|
157
|
+
"""None = not an exec rule; [] = every command; else prefix tokens."""
|
|
158
|
+
match = _EXEC_RULE.fullmatch(rule.strip())
|
|
159
|
+
if not match:
|
|
160
|
+
return None
|
|
161
|
+
inner = (match.group(1) or '').strip()
|
|
162
|
+
if not inner or any(ch in inner for ch in '*?['):
|
|
163
|
+
return []
|
|
164
|
+
try:
|
|
165
|
+
return shlex.split(inner)
|
|
166
|
+
except ValueError:
|
|
167
|
+
return []
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _prefix_matches(prefix, tokens) -> bool:
|
|
171
|
+
return len(tokens) >= len(prefix) and tokens[:len(prefix)] == prefix
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _touches_interpreter(prefix, interpreter: str) -> bool:
|
|
175
|
+
if not prefix:
|
|
176
|
+
return True
|
|
177
|
+
head = prefix[0]
|
|
178
|
+
base = os.path.basename(head)
|
|
179
|
+
return head == interpreter or base == os.path.basename(interpreter) or base.startswith('python')
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def blocked_by_rules(tokens, rules, interpreter: str) -> bool:
|
|
183
|
+
"""True when any deny/ask rule touches the same program or the wrapper.
|
|
184
|
+
|
|
185
|
+
Deliberately broader than Devin's own matching: `ask Exec(grep -r)` also
|
|
186
|
+
stops `grep -rn`, since flag spellings are not compared exactly."""
|
|
187
|
+
for rule in rules['deny'] + rules['ask']:
|
|
188
|
+
prefix = _rule_prefix(rule)
|
|
189
|
+
if prefix is None:
|
|
190
|
+
continue
|
|
191
|
+
if not prefix or prefix[0] == tokens[0] or _touches_interpreter(prefix, interpreter):
|
|
192
|
+
return True
|
|
193
|
+
return False
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def allowed_by_rules(tokens, rules) -> bool:
|
|
197
|
+
for rule in rules['allow']:
|
|
198
|
+
prefix = _rule_prefix(rule)
|
|
199
|
+
if prefix and _prefix_matches(prefix, tokens):
|
|
200
|
+
return True
|
|
201
|
+
return False
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# ── Eligibility ─────────────────────────────────────────────────────────────
|
|
205
|
+
|
|
206
|
+
def has_shell_expansion(command: str) -> bool:
|
|
207
|
+
"""Unquoted glob, tilde or comment characters. The shell would expand or
|
|
208
|
+
drop them, the argv runner would not, so the rewrite would change what
|
|
209
|
+
runs (`ls *.txt` would look for a file literally named '*.txt')."""
|
|
210
|
+
quote = None
|
|
211
|
+
escaped = False
|
|
212
|
+
for ch in command:
|
|
213
|
+
if escaped:
|
|
214
|
+
escaped = False
|
|
215
|
+
elif ch == '\\' and quote != "'":
|
|
216
|
+
escaped = True
|
|
217
|
+
elif quote:
|
|
218
|
+
if ch == quote:
|
|
219
|
+
quote = None
|
|
220
|
+
elif ch in ('"', "'"):
|
|
221
|
+
quote = ch
|
|
222
|
+
elif ch in '*?[]~#!':
|
|
223
|
+
return True
|
|
224
|
+
return False
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def machine_format(tokens) -> bool:
|
|
228
|
+
"""git output the caller explicitly asked to be compact or machine-readable
|
|
229
|
+
(--short, --porcelain, -z and short clusters holding s or z). Claude Code's
|
|
230
|
+
router has no handler for these and would fall back to the generic
|
|
231
|
+
summarizer; here they are simply never rewritten, so they run untouched."""
|
|
232
|
+
if len(tokens) < 2 or tokens[0] != 'git':
|
|
233
|
+
return False
|
|
234
|
+
for arg in tokens[1:]:
|
|
235
|
+
if arg.startswith(('--porcelain', '--short', '--null')) or arg == '-z':
|
|
236
|
+
return True
|
|
237
|
+
if tokens[1] == 'status' and arg.startswith('-') and not arg.startswith('--') and ('s' in arg or 'z' in arg):
|
|
238
|
+
return True
|
|
239
|
+
return False
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def eligible(command: str, rules: dict, interpreter: str) -> bool:
|
|
243
|
+
"""May this command be rewritten AND its bound wrapper approved?"""
|
|
244
|
+
if not isinstance(command, str) or not command.strip() or not _compression_enabled():
|
|
245
|
+
return False
|
|
246
|
+
gates = _gates()
|
|
247
|
+
if gates.has_dangerous_chars(command) or has_shell_expansion(command) or not gates.is_whitelisted(command):
|
|
248
|
+
return False
|
|
249
|
+
try:
|
|
250
|
+
tokens = shlex.split(command)
|
|
251
|
+
except ValueError:
|
|
252
|
+
return False
|
|
253
|
+
if (not tokens or '' in tokens or '=' in tokens[0] or machine_format(tokens)
|
|
254
|
+
or blocked_by_rules(tokens, rules, interpreter)):
|
|
255
|
+
return False
|
|
256
|
+
return allowed_by_rules(tokens, rules)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def runner_eligible(argv) -> bool:
|
|
260
|
+
"""The runner's own re-check: compressible and free of shell syntax."""
|
|
261
|
+
if not argv or not all(isinstance(a, str) and a for a in argv):
|
|
262
|
+
return False
|
|
263
|
+
command = shlex.join(argv)
|
|
264
|
+
gates = _gates()
|
|
265
|
+
return not gates.has_dangerous_chars(command) and gates.is_whitelisted(command)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
# ── Wrapper strings ─────────────────────────────────────────────────────────
|
|
269
|
+
|
|
270
|
+
def build_wrapper(interpreter: str, entry: str, session: str, argv) -> str:
|
|
271
|
+
return shlex.join([interpreter, '-I', entry, 'run', '--session', session_label(session), '--', *argv])
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def parse_wrapper(command: str, interpreter: str, entry: str):
|
|
275
|
+
"""Return the wrapped argv for an exact wrapper string, else None."""
|
|
276
|
+
if not isinstance(command, str):
|
|
277
|
+
return None
|
|
278
|
+
try:
|
|
279
|
+
tokens = shlex.split(command)
|
|
280
|
+
except ValueError:
|
|
281
|
+
return None
|
|
282
|
+
if (len(tokens) < 8 or tokens[:4] != [interpreter, '-I', entry, 'run'] or tokens[4] != '--session'
|
|
283
|
+
or not SESSION_RE.fullmatch(tokens[5]) or tokens[6] != '--'):
|
|
284
|
+
return None
|
|
285
|
+
argv = tokens[7:]
|
|
286
|
+
if build_wrapper(interpreter, entry, tokens[5], argv) != command:
|
|
287
|
+
return None
|
|
288
|
+
return argv
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
# ── Devin user config: owned hook entries ───────────────────────────────────
|
|
292
|
+
|
|
293
|
+
def hook_command(interpreter: str, entry: str, event: str) -> str:
|
|
294
|
+
# Devin reads hook exit 2 as "block", and Python exits 2 when the entry
|
|
295
|
+
# file is missing (a stale entry after a manual removal). The shell guard
|
|
296
|
+
# turns every failure into a silent pass, so a broken hook never blocks.
|
|
297
|
+
return shlex.join([interpreter, '-I', entry, 'hook', HOOK_EVENTS[event]]) + ' || true'
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def owned_entries(interpreter: str, entry: str) -> dict:
|
|
301
|
+
return {event: {'matcher': HOOK_MATCHER,
|
|
302
|
+
'hooks': [{'type': 'command', 'command': hook_command(interpreter, entry, event),
|
|
303
|
+
'timeout': HOOK_TIMEOUT}]}
|
|
304
|
+
for event in HOOK_EVENTS}
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _entry_key(value) -> str:
|
|
308
|
+
return json.dumps(value, sort_keys=True)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def merge_hooks(config: dict, entries: dict, previous: dict | None = None) -> dict:
|
|
312
|
+
"""Add owned entries; replace only previously recorded, byte-equal entries."""
|
|
313
|
+
if not isinstance(config, dict):
|
|
314
|
+
raise ValueError('Devin config must be a JSON object')
|
|
315
|
+
hooks = config.get('hooks', {})
|
|
316
|
+
if not isinstance(hooks, dict):
|
|
317
|
+
raise ValueError('Devin config "hooks" must be an object')
|
|
318
|
+
stale = {_entry_key(v) for v in (previous or {}).values()}
|
|
319
|
+
result = dict(config)
|
|
320
|
+
hooks = dict(hooks)
|
|
321
|
+
for event, entry in entries.items():
|
|
322
|
+
groups = hooks.get(event, [])
|
|
323
|
+
if not isinstance(groups, list):
|
|
324
|
+
raise ValueError('Devin config hooks.' + event + ' must be a list')
|
|
325
|
+
kept = [g for g in groups if _entry_key(g) not in stale]
|
|
326
|
+
# Already present: leave every group where it is (reinstall is a no-op).
|
|
327
|
+
hooks[event] = kept if any(_entry_key(g) == _entry_key(entry) for g in kept) else kept + [entry]
|
|
328
|
+
result['hooks'] = hooks
|
|
329
|
+
return result
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def remove_hooks(config: dict, recorded: dict) -> tuple[dict, list]:
|
|
333
|
+
"""Remove only byte-equal recorded entries. Returns (config, preserved events)."""
|
|
334
|
+
if not isinstance(config, dict):
|
|
335
|
+
raise ValueError('Devin config must be a JSON object')
|
|
336
|
+
hooks = config.get('hooks')
|
|
337
|
+
if not isinstance(hooks, dict):
|
|
338
|
+
return config, []
|
|
339
|
+
wanted = {_entry_key(v) for v in recorded.values()}
|
|
340
|
+
result, hooks, preserved = dict(config), dict(hooks), []
|
|
341
|
+
for event in recorded:
|
|
342
|
+
groups = hooks.get(event)
|
|
343
|
+
if not isinstance(groups, list):
|
|
344
|
+
continue
|
|
345
|
+
kept = [g for g in groups if _entry_key(g) not in wanted]
|
|
346
|
+
if any(_looks_owned(g) for g in kept):
|
|
347
|
+
preserved.append(event)
|
|
348
|
+
if kept:
|
|
349
|
+
hooks[event] = kept
|
|
350
|
+
else:
|
|
351
|
+
hooks.pop(event, None)
|
|
352
|
+
if hooks:
|
|
353
|
+
result['hooks'] = hooks
|
|
354
|
+
else:
|
|
355
|
+
result.pop('hooks', None)
|
|
356
|
+
return result, preserved
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _looks_owned(group) -> bool:
|
|
360
|
+
text = json.dumps(group)
|
|
361
|
+
return 'devin_compress.py' in text and ' hook ' in text
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def installed_state(config: dict, entries: dict) -> dict:
|
|
365
|
+
"""Per-event: 'wired', 'missing' or 'edited' (a TO-looking entry that differs)."""
|
|
366
|
+
hooks = config.get('hooks') if isinstance(config, dict) else None
|
|
367
|
+
hooks = hooks if isinstance(hooks, dict) else {}
|
|
368
|
+
state = {}
|
|
369
|
+
for event, entry in entries.items():
|
|
370
|
+
groups = hooks.get(event) if isinstance(hooks.get(event), list) else []
|
|
371
|
+
if any(_entry_key(g) == _entry_key(entry) for g in groups):
|
|
372
|
+
state[event] = 'wired'
|
|
373
|
+
elif any(_looks_owned(g) for g in groups):
|
|
374
|
+
state[event] = 'edited'
|
|
375
|
+
else:
|
|
376
|
+
state[event] = 'missing'
|
|
377
|
+
return state
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
# ── One-time binding between PreToolUse and PermissionRequest ───────────────
|
|
381
|
+
|
|
382
|
+
def _digest(command: str) -> str:
|
|
383
|
+
import hashlib
|
|
384
|
+
return hashlib.sha256(command.encode('utf-8', 'surrogatepass')).hexdigest()
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _with_bindings(path: Path, change):
|
|
388
|
+
"""Run change(entries, now) under an exclusive lock and persist the result."""
|
|
389
|
+
import fcntl
|
|
390
|
+
import tempfile
|
|
391
|
+
import time
|
|
392
|
+
from devin_state import no_symlinks, private_path
|
|
393
|
+
no_symlinks(path)
|
|
394
|
+
fd = os.open(path.with_name(path.name + '.lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
395
|
+
try:
|
|
396
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
397
|
+
# Check the file only under the lock every writer replaces it under: a
|
|
398
|
+
# stat racing a rival's os.replace can return the replaced inode with
|
|
399
|
+
# st_nlink 0, which would refuse a sound bindings file.
|
|
400
|
+
private_path(path)
|
|
401
|
+
try:
|
|
402
|
+
entries = json.loads(path.read_text()) if path.exists() else {}
|
|
403
|
+
except (OSError, ValueError):
|
|
404
|
+
entries = {}
|
|
405
|
+
if not isinstance(entries, dict):
|
|
406
|
+
entries = {}
|
|
407
|
+
now = time.time()
|
|
408
|
+
entries = {k: v for k, v in entries.items()
|
|
409
|
+
if isinstance(k, str) and isinstance(v, list) and len(v) == 2
|
|
410
|
+
and isinstance(v[0], str) and isinstance(v[1], (int, float))
|
|
411
|
+
and 0 <= now - v[1] <= BINDING_SECONDS}
|
|
412
|
+
result = change(entries, now)
|
|
413
|
+
if len(entries) > BINDING_LIMIT:
|
|
414
|
+
for key in sorted(entries, key=lambda k: entries[k][1])[:len(entries) - BINDING_LIMIT]:
|
|
415
|
+
del entries[key]
|
|
416
|
+
with tempfile.NamedTemporaryFile(mode='w', dir=path.parent, delete=False) as out:
|
|
417
|
+
json.dump(entries, out)
|
|
418
|
+
temporary = out.name
|
|
419
|
+
os.chmod(temporary, 0o600)
|
|
420
|
+
os.replace(temporary, path)
|
|
421
|
+
return result
|
|
422
|
+
finally:
|
|
423
|
+
os.close(fd)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def bind(path: Path, tool_use_id, wrapper: str) -> bool:
|
|
427
|
+
if not isinstance(tool_use_id, str) or not TOOL_USE_ID_RE.fullmatch(tool_use_id):
|
|
428
|
+
return False
|
|
429
|
+
|
|
430
|
+
def change(entries, now):
|
|
431
|
+
entries[tool_use_id] = [_digest(wrapper), now]
|
|
432
|
+
return True
|
|
433
|
+
return _with_bindings(path, change)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def consume(path: Path, tool_use_id, command: str) -> bool:
|
|
437
|
+
"""True once, only for the exact wrapper bound to this tool_use_id."""
|
|
438
|
+
if not isinstance(tool_use_id, str) or not TOOL_USE_ID_RE.fullmatch(tool_use_id) or not path.exists():
|
|
439
|
+
return False
|
|
440
|
+
|
|
441
|
+
def change(entries, now):
|
|
442
|
+
entry = entries.pop(tool_use_id, None)
|
|
443
|
+
return entry is not None and entry[0] == _digest(command)
|
|
444
|
+
return _with_bindings(path, change)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def attested(record_path: Path) -> bool:
|
|
448
|
+
"""The install record exists and carries the owner's no-team-policy attestation."""
|
|
449
|
+
try:
|
|
450
|
+
record = json.loads(record_path.read_text()) if record_path.exists() else None
|
|
451
|
+
except (OSError, ValueError, RecursionError):
|
|
452
|
+
return False
|
|
453
|
+
return isinstance(record, dict) and record.get('org_policy') == ATTESTATION
|