@alexgreensh/token-optimizer 5.13.70 → 5.13.72
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 +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/module_runner.py +3 -3
- package/hooks/sessionstart_runner.py +6 -0
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +361 -289
- package/skills/token-optimizer/assets/savings_story.js +140 -36
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -3
- package/skills/token-optimizer/scripts/_measure/config_cache.py +63 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +3 -1
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +4 -2
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +11 -1
- package/skills/token-optimizer/scripts/_measure/dashboard.py +35 -64
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +5 -1
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +4 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +6 -7
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +4 -3
- package/skills/token-optimizer/scripts/_measure/savings.py +11 -4
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +7 -0
- package/skills/token-optimizer/scripts/_measure/setup_observation_cache.py +99 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +4 -5
- package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +218 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +25 -6
- package/skills/token-optimizer/scripts/_measure/structural_value.py +16 -10
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -2
- package/skills/token-optimizer/scripts/codemap.py +33 -5
- package/skills/token-optimizer/scripts/codemap_hint.py +152 -11
- package/skills/token-optimizer/scripts/codemap_index.py +100 -11
- package/skills/token-optimizer/scripts/codemap_ledger.py +29 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +3 -3
- package/skills/token-optimizer/scripts/hermes_doctor.py +3 -3
- package/skills/token-optimizer/scripts/hermes_install.py +3 -3
- package/skills/token-optimizer/scripts/statusline.js +157 -30
- package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +0 -140
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +0 -35
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +0 -85
- package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +0 -143
- package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +0 -84
|
@@ -1,140 +0,0 @@
|
|
|
1
|
-
"""Prepare an isolated interactive Claude fork for guarded cache refresh."""
|
|
2
|
-
import re
|
|
3
|
-
from pathlib import Path
|
|
4
|
-
from urllib.parse import urlsplit
|
|
5
|
-
|
|
6
|
-
_ARG = re.compile(r'^[A-Za-z0-9._][A-Za-z0-9._-]{0,127}$')
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
def fork_command(executable, session_id, model, prompt):
|
|
10
|
-
if (not Path(executable).is_absolute() or not _ARG.fullmatch(str(session_id)) or
|
|
11
|
-
not _ARG.fullmatch(str(model)) or not isinstance(prompt, str) or not prompt):
|
|
12
|
-
raise ValueError('invalid fork arguments')
|
|
13
|
-
return [str(executable), '--resume', str(session_id), '--fork-session',
|
|
14
|
-
'--settings', '{"disableAllHooks":true}', '--model', str(model), prompt]
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def fork_environment(source, api_key, local_url):
|
|
18
|
-
parsed = urlsplit(local_url)
|
|
19
|
-
if (not isinstance(api_key, str) or not api_key or parsed.scheme != 'http' or
|
|
20
|
-
parsed.hostname != '127.0.0.1' or parsed.username or parsed.password or
|
|
21
|
-
not parsed.port or parsed.path or parsed.query or parsed.fragment):
|
|
22
|
-
raise ValueError('invalid guarded endpoint or API key')
|
|
23
|
-
allowed = ('PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'CLAUDE_CONFIG_DIR',
|
|
24
|
-
'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME')
|
|
25
|
-
env = {key: str(source[key]) for key in allowed if source.get(key) is not None}
|
|
26
|
-
env.update({'TERM': 'xterm-256color', 'ANTHROPIC_API_KEY': api_key,
|
|
27
|
-
'ANTHROPIC_BASE_URL': local_url, 'CLAUDE_CODE_SKIP_PROMPT_HISTORY': '1',
|
|
28
|
-
'TOKEN_OPTIMIZER_KEEPWARM_PING': '1'})
|
|
29
|
-
return env
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
def _recorded_parent(record):
|
|
33
|
-
import json
|
|
34
|
-
import os
|
|
35
|
-
import stat
|
|
36
|
-
from .keepwarm_prefix import reconstruct
|
|
37
|
-
path = str(record['transcript_path'])
|
|
38
|
-
flags = os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)
|
|
39
|
-
fd = os.open(path, flags)
|
|
40
|
-
try:
|
|
41
|
-
before = os.fstat(fd)
|
|
42
|
-
if (not stat.S_ISREG(before.st_mode) or before.st_size > 128 * 1024 * 1024 or
|
|
43
|
-
before.st_size != int(record['byte_size']) or before.st_mtime != float(record['transcript_mtime'])):
|
|
44
|
-
raise ValueError('parent transcript changed or is too large')
|
|
45
|
-
with os.fdopen(fd, 'rb') as stream:
|
|
46
|
-
fd = None
|
|
47
|
-
def rows():
|
|
48
|
-
for line in stream:
|
|
49
|
-
if len(line) > 16 * 1024 * 1024:
|
|
50
|
-
raise ValueError('parent record is too large')
|
|
51
|
-
yield json.loads(line)
|
|
52
|
-
result = reconstruct(rows())
|
|
53
|
-
after = os.fstat(stream.fileno())
|
|
54
|
-
current = os.stat(path, follow_symlinks=False)
|
|
55
|
-
identity = lambda st: (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns)
|
|
56
|
-
if identity(before) != identity(after) or identity(before) != identity(current):
|
|
57
|
-
raise ValueError('parent transcript changed')
|
|
58
|
-
return result
|
|
59
|
-
finally:
|
|
60
|
-
if fd is not None:
|
|
61
|
-
os.close(fd)
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
def run_guarded(record, cwd, executable, api_key, source_env, is_paused, timeout=60, forward=None):
|
|
65
|
-
"""Run a one-request fork; no model content reaches the CLI.
|
|
66
|
-
|
|
67
|
-
This entry point is intentionally not enabled by the production gate until
|
|
68
|
-
the cache hit and all safety checks are proven against a real API session.
|
|
69
|
-
"""
|
|
70
|
-
import os
|
|
71
|
-
import pty
|
|
72
|
-
import select
|
|
73
|
-
import signal
|
|
74
|
-
import subprocess
|
|
75
|
-
import time
|
|
76
|
-
from .keepwarm_guard_server import official_forward, server
|
|
77
|
-
|
|
78
|
-
if not isinstance(api_key, str) or not api_key:
|
|
79
|
-
return {'ok': False, 'reason': 'api-key-unavailable'}
|
|
80
|
-
if os.name != 'posix':
|
|
81
|
-
return {'ok': False, 'reason': 'platform-unsupported'}
|
|
82
|
-
if str(source_env.get('TOKEN_OPTIMIZER_KEEPWARM', '1')).strip().lower() in ('0', 'false', 'no', 'off'):
|
|
83
|
-
return {'ok': False, 'reason': 'kill-switch'}
|
|
84
|
-
base = source_env.get('ANTHROPIC_BASE_URL', '')
|
|
85
|
-
if base and str(base).rstrip('/') != 'https://api.anthropic.com':
|
|
86
|
-
return {'ok': False, 'reason': 'custom-api-endpoint'}
|
|
87
|
-
master = slave = None
|
|
88
|
-
child = None
|
|
89
|
-
try:
|
|
90
|
-
if not is_paused():
|
|
91
|
-
return {'ok': False, 'reason': 'parent-not-paused'}
|
|
92
|
-
parent = _recorded_parent(record)
|
|
93
|
-
command = fork_command(executable, record['session_id'], record['model'], 'Reply with exactly: ok')
|
|
94
|
-
send = forward or official_forward
|
|
95
|
-
def send_if_paused(body, headers):
|
|
96
|
-
if not is_paused():
|
|
97
|
-
raise ValueError('parent is no longer paused')
|
|
98
|
-
return send(body, headers)
|
|
99
|
-
with server(parent, api_key, send_if_paused) as live:
|
|
100
|
-
env = fork_environment(source_env, api_key, live.url)
|
|
101
|
-
master, slave = pty.openpty()
|
|
102
|
-
child = subprocess.Popen(command, cwd=cwd, env=env, stdin=slave, stdout=slave, stderr=slave,
|
|
103
|
-
start_new_session=True, close_fds=True)
|
|
104
|
-
os.close(slave)
|
|
105
|
-
slave = None
|
|
106
|
-
deadline = time.monotonic() + max(1, min(float(timeout), 180))
|
|
107
|
-
while time.monotonic() < deadline:
|
|
108
|
-
if live.usage is not None:
|
|
109
|
-
return {'ok': True, 'reason': 'ok', 'usage': live.usage}
|
|
110
|
-
if child.poll() is not None:
|
|
111
|
-
break
|
|
112
|
-
ready, _, _ = select.select([master], [], [], min(0.2, max(0, deadline - time.monotonic())))
|
|
113
|
-
if ready:
|
|
114
|
-
try:
|
|
115
|
-
if not os.read(master, 65536):
|
|
116
|
-
break
|
|
117
|
-
except OSError:
|
|
118
|
-
break
|
|
119
|
-
if live.usage is not None:
|
|
120
|
-
return {'ok': True, 'reason': 'ok', 'usage': live.usage}
|
|
121
|
-
return {'ok': False, 'reason': 'guard-not-completed', 'exit_code': child.poll()}
|
|
122
|
-
except Exception:
|
|
123
|
-
return {'ok': False, 'reason': 'fork-unavailable'}
|
|
124
|
-
finally:
|
|
125
|
-
if child is not None and child.poll() is None:
|
|
126
|
-
try:
|
|
127
|
-
os.killpg(child.pid, signal.SIGTERM)
|
|
128
|
-
child.wait(timeout=2)
|
|
129
|
-
except (OSError, subprocess.TimeoutExpired):
|
|
130
|
-
try:
|
|
131
|
-
os.killpg(child.pid, signal.SIGKILL)
|
|
132
|
-
child.wait(timeout=2)
|
|
133
|
-
except (OSError, subprocess.TimeoutExpired):
|
|
134
|
-
pass
|
|
135
|
-
for fd in (slave, master):
|
|
136
|
-
if fd is not None:
|
|
137
|
-
try:
|
|
138
|
-
os.close(fd)
|
|
139
|
-
except OSError:
|
|
140
|
-
pass
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
"""Single-use request guard for an isolated keep-warm fork."""
|
|
2
|
-
import hmac
|
|
3
|
-
import threading
|
|
4
|
-
from .keepwarm_prefix import prepare
|
|
5
|
-
from .keepwarm_response_filter import sanitize_stream
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class Guard:
|
|
9
|
-
"""Verify one fork request before forwarding, and never forward model output."""
|
|
10
|
-
|
|
11
|
-
def __init__(self, parent, api_key, forward):
|
|
12
|
-
if not isinstance(api_key, str) or not api_key:
|
|
13
|
-
raise ValueError('API key unavailable')
|
|
14
|
-
self.parent = parent
|
|
15
|
-
self._key = api_key
|
|
16
|
-
self.forward = forward
|
|
17
|
-
self._lock = threading.Lock()
|
|
18
|
-
self._used = False
|
|
19
|
-
|
|
20
|
-
def process(self, fork, headers):
|
|
21
|
-
headers = {str(key).lower(): value for key, value in headers.items()}
|
|
22
|
-
key = headers.get('x-api-key')
|
|
23
|
-
if not isinstance(key, str) or not hmac.compare_digest(key, self._key):
|
|
24
|
-
raise ValueError('request not authorized')
|
|
25
|
-
beta_header = headers.get('anthropic-beta', '')
|
|
26
|
-
if not isinstance(beta_header, str):
|
|
27
|
-
raise ValueError('invalid beta header')
|
|
28
|
-
betas = [item.strip() for item in beta_header.split(',') if item.strip()]
|
|
29
|
-
request = prepare(fork, self.parent, betas)
|
|
30
|
-
with self._lock:
|
|
31
|
-
if self._used:
|
|
32
|
-
raise ValueError('request already used')
|
|
33
|
-
self._used = True
|
|
34
|
-
payload = self.forward(request, headers)
|
|
35
|
-
return sanitize_stream(payload, self.parent['body']['model'])
|
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
"""A single-use, loopback-only guard for a keep-warm fork."""
|
|
2
|
-
from contextlib import contextmanager
|
|
3
|
-
from http.client import HTTPSConnection
|
|
4
|
-
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
5
|
-
import json
|
|
6
|
-
import threading
|
|
7
|
-
from urllib.parse import urlsplit
|
|
8
|
-
|
|
9
|
-
from .keepwarm_guard import Guard
|
|
10
|
-
|
|
11
|
-
_MAX_REQUEST = 64 * 1024 * 1024
|
|
12
|
-
_MAX_RESPONSE = 8 * 1024 * 1024
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
def official_forward(body, headers):
|
|
16
|
-
"""Send only the guarded request to Anthropic's fixed HTTPS endpoint."""
|
|
17
|
-
encoded = json.dumps(body, ensure_ascii=False, separators=(',', ':'), allow_nan=False).encode('utf-8')
|
|
18
|
-
allowed = ('x-api-key', 'anthropic-version', 'anthropic-beta', 'user-agent')
|
|
19
|
-
sent = {key: headers[key] for key in allowed if key in headers}
|
|
20
|
-
if not sent.get('x-api-key') or not sent.get('anthropic-version'):
|
|
21
|
-
raise ValueError('required API headers unavailable')
|
|
22
|
-
sent['content-type'] = 'application/json'
|
|
23
|
-
conn = HTTPSConnection('api.anthropic.com', 443, timeout=60)
|
|
24
|
-
try:
|
|
25
|
-
conn.request('POST', '/v1/messages?beta=true', body=encoded, headers=sent)
|
|
26
|
-
response = conn.getresponse()
|
|
27
|
-
if response.status != 200 or 'text/event-stream' not in (response.getheader('Content-Type') or '').lower():
|
|
28
|
-
raise ValueError('upstream request failed')
|
|
29
|
-
payload = response.read(_MAX_RESPONSE + 1)
|
|
30
|
-
if len(payload) > _MAX_RESPONSE:
|
|
31
|
-
raise ValueError('upstream response too large')
|
|
32
|
-
return payload
|
|
33
|
-
finally:
|
|
34
|
-
conn.close()
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
@contextmanager
|
|
38
|
-
def server(parent, api_key, forward=official_forward, port=0):
|
|
39
|
-
guard = Guard(parent, api_key, forward)
|
|
40
|
-
class Handler(BaseHTTPRequestHandler):
|
|
41
|
-
def log_message(self, *args):
|
|
42
|
-
pass
|
|
43
|
-
|
|
44
|
-
def do_POST(self):
|
|
45
|
-
try:
|
|
46
|
-
self.connection.settimeout(5)
|
|
47
|
-
url = urlsplit(self.path)
|
|
48
|
-
host = self.headers.get('Host', '')
|
|
49
|
-
if (url.path != '/v1/messages' or url.query not in ('', 'beta=true') or
|
|
50
|
-
host != '127.0.0.1:' + str(self.server.server_port) or
|
|
51
|
-
self.headers.get('Transfer-Encoding')):
|
|
52
|
-
raise ValueError('invalid request')
|
|
53
|
-
length = int(self.headers.get('Content-Length', '0'))
|
|
54
|
-
if length <= 0 or length > _MAX_REQUEST:
|
|
55
|
-
raise ValueError('invalid request')
|
|
56
|
-
raw = self.rfile.read(length)
|
|
57
|
-
if len(raw) != length:
|
|
58
|
-
raise ValueError('incomplete request')
|
|
59
|
-
body = json.loads(raw)
|
|
60
|
-
if not isinstance(body, dict) or body.get('stream') is not True:
|
|
61
|
-
raise ValueError('invalid request')
|
|
62
|
-
response, usage = guard.process(body, dict(self.headers))
|
|
63
|
-
self.server.usage = usage
|
|
64
|
-
self.send_response(200)
|
|
65
|
-
self.send_header('Content-Type', 'text/event-stream')
|
|
66
|
-
self.send_header('Content-Length', str(len(response)))
|
|
67
|
-
self.end_headers()
|
|
68
|
-
self.wfile.write(response)
|
|
69
|
-
except Exception:
|
|
70
|
-
self.send_response(400)
|
|
71
|
-
self.send_header('Content-Length', '0')
|
|
72
|
-
self.end_headers()
|
|
73
|
-
|
|
74
|
-
httpd = ThreadingHTTPServer(('127.0.0.1', port), Handler)
|
|
75
|
-
httpd.daemon_threads = True
|
|
76
|
-
httpd.usage = None
|
|
77
|
-
httpd.url = 'http://127.0.0.1:' + str(httpd.server_port)
|
|
78
|
-
thread = threading.Thread(target=httpd.serve_forever, kwargs={'poll_interval': 0.1}, daemon=True)
|
|
79
|
-
thread.start()
|
|
80
|
-
try:
|
|
81
|
-
yield httpd
|
|
82
|
-
finally:
|
|
83
|
-
httpd.shutdown()
|
|
84
|
-
httpd.server_close()
|
|
85
|
-
thread.join(timeout=2)
|
|
@@ -1,143 +0,0 @@
|
|
|
1
|
-
"""Fail-closed reconstruction and validation of a recorded Claude request."""
|
|
2
|
-
import copy
|
|
3
|
-
import hashlib
|
|
4
|
-
import hmac
|
|
5
|
-
import json
|
|
6
|
-
import re
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
class UnsafePrefix(ValueError):
|
|
10
|
-
"""The recorded request cannot be matched safely."""
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def _digest(value):
|
|
14
|
-
try:
|
|
15
|
-
data = json.dumps(value, sort_keys=True, separators=(',', ':'),
|
|
16
|
-
ensure_ascii=False, allow_nan=False).encode('utf-8')
|
|
17
|
-
return hashlib.sha256(data).hexdigest()
|
|
18
|
-
except (TypeError, ValueError, UnicodeError) as exc:
|
|
19
|
-
raise UnsafePrefix('request cannot be normalized') from exc
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def _strip(value):
|
|
23
|
-
if isinstance(value, list):
|
|
24
|
-
return [_strip(item) for item in value]
|
|
25
|
-
if isinstance(value, dict):
|
|
26
|
-
return {key: _strip(item) for key, item in value.items() if key != 'cache_control'}
|
|
27
|
-
return value
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
def _apply_controls(body, controls):
|
|
31
|
-
for item in controls:
|
|
32
|
-
path = item.get('path')
|
|
33
|
-
if not isinstance(path, list) or not path or path[0] not in ('system', 'tools', 'messages'):
|
|
34
|
-
raise UnsafePrefix('invalid cache checkpoint')
|
|
35
|
-
try:
|
|
36
|
-
target = body
|
|
37
|
-
for key in path:
|
|
38
|
-
target = target[key]
|
|
39
|
-
if not isinstance(target, dict) or not isinstance(item.get('value'), dict):
|
|
40
|
-
raise UnsafePrefix('invalid cache checkpoint')
|
|
41
|
-
target['cache_control'] = copy.deepcopy(item['value'])
|
|
42
|
-
except (KeyError, IndexError, TypeError) as exc:
|
|
43
|
-
raise UnsafePrefix('missing cache checkpoint target') from exc
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
def _check_tools(tools):
|
|
47
|
-
if not isinstance(tools, list):
|
|
48
|
-
raise UnsafePrefix('missing tool definitions')
|
|
49
|
-
for tool in tools:
|
|
50
|
-
if not isinstance(tool, dict) or tool.get('type', 'custom') != 'custom':
|
|
51
|
-
raise UnsafePrefix('server-side tools cannot be intercepted')
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
def reconstruct(rows):
|
|
55
|
-
"""Verify the latest recorded main-thread request and its content chain."""
|
|
56
|
-
shapes, blobs, chains = {}, {}, {}
|
|
57
|
-
last = None
|
|
58
|
-
last_assistant = None
|
|
59
|
-
try:
|
|
60
|
-
for row in rows:
|
|
61
|
-
if not isinstance(row, dict):
|
|
62
|
-
continue
|
|
63
|
-
typ = row.get('type')
|
|
64
|
-
if typ == 'api-request-shape':
|
|
65
|
-
shapes[row['shapeHash']] = row['shape']
|
|
66
|
-
elif typ == 'api-request-blob':
|
|
67
|
-
blobs[row['hash']] = row['message']
|
|
68
|
-
elif typ == 'assistant' and not row.get('isSidechain'):
|
|
69
|
-
message = row.get('message')
|
|
70
|
-
if isinstance(message, dict) and isinstance(message.get('usage'), dict):
|
|
71
|
-
last_assistant = row.get('requestRef')
|
|
72
|
-
elif typ == 'api-request':
|
|
73
|
-
keep = row.get('keep', 0)
|
|
74
|
-
if not isinstance(keep, int) or keep < 0:
|
|
75
|
-
raise UnsafePrefix('invalid request chain')
|
|
76
|
-
base = chains[row['base']] if keep else []
|
|
77
|
-
if keep > len(base):
|
|
78
|
-
raise UnsafePrefix('incomplete request chain')
|
|
79
|
-
messages = base[:keep] + [blobs[key] for key in row['tail']]
|
|
80
|
-
chains[row['id']] = messages
|
|
81
|
-
if row.get('querySource') == 'repl_main_thread':
|
|
82
|
-
last = (row, messages)
|
|
83
|
-
if not last:
|
|
84
|
-
raise UnsafePrefix('no recorded parent request')
|
|
85
|
-
row, messages = last
|
|
86
|
-
if last_assistant != row['id']:
|
|
87
|
-
raise UnsafePrefix('parent request is not the completed last turn')
|
|
88
|
-
if row.get('cut') or row.get('withheld') or not row.get('requestDigest'):
|
|
89
|
-
raise UnsafePrefix('request was redacted or incomplete')
|
|
90
|
-
body = copy.deepcopy(row['params'])
|
|
91
|
-
body.update(copy.deepcopy(shapes[row['shapeHash']]))
|
|
92
|
-
body['messages'] = copy.deepcopy(messages)
|
|
93
|
-
_check_tools(body['tools'])
|
|
94
|
-
_apply_controls(body, row.get('cacheControl', []))
|
|
95
|
-
if not hmac.compare_digest(_digest(body), row['requestDigest']):
|
|
96
|
-
raise UnsafePrefix('recorded request digest differs')
|
|
97
|
-
last_content = body['messages'][-1]['content']
|
|
98
|
-
if (not isinstance(last_content, list) or not last_content or not isinstance(last_content[-1], dict) or
|
|
99
|
-
not isinstance(last_content[-1].get('cache_control'), dict) or
|
|
100
|
-
last_content[-1].get('cache_control', {}).get('type') != 'ephemeral' or
|
|
101
|
-
not isinstance(row.get('version'), str)):
|
|
102
|
-
raise UnsafePrefix('cache checkpoint or CLI version unavailable')
|
|
103
|
-
return {'body': body, 'digest': row['requestDigest'], 'version': row['version']}
|
|
104
|
-
except (KeyError, TypeError, IndexError) as exc:
|
|
105
|
-
raise UnsafePrefix('incomplete recorded request') from exc
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
def prepare(fork, parent, betas):
|
|
109
|
-
"""Restore recorded cache checkpoints only after verifying the whole prefix.
|
|
110
|
-
|
|
111
|
-
The CLI omits the billing header from its transcript digest. Its prefix and
|
|
112
|
-
version are checked, but the complete header cannot be reconstructed here.
|
|
113
|
-
"""
|
|
114
|
-
try:
|
|
115
|
-
output = copy.deepcopy(fork)
|
|
116
|
-
expected = parent['body']
|
|
117
|
-
systems = output['system']
|
|
118
|
-
header = systems[0]
|
|
119
|
-
pattern = r'^x-anthropic-billing-header: cc_version=' + re.escape(parent['version']) + r'\.[A-Za-z0-9]+; cc_entrypoint=cli;'
|
|
120
|
-
if not isinstance(header, dict) or not re.match(pattern, header.get('text', '')):
|
|
121
|
-
raise UnsafePrefix('unrecognized billing header')
|
|
122
|
-
count = len(expected['messages'])
|
|
123
|
-
if len(output['messages']) <= count:
|
|
124
|
-
raise UnsafePrefix('fork has no new ping message')
|
|
125
|
-
_check_tools(output['tools'])
|
|
126
|
-
if (_strip(systems[1:]) != _strip(expected['system']) or
|
|
127
|
-
_strip(output['tools']) != _strip(expected['tools']) or
|
|
128
|
-
_strip(output['messages'][:count]) != _strip(expected['messages'])):
|
|
129
|
-
raise UnsafePrefix('fork prefix differs from parent')
|
|
130
|
-
output['system'][1:] = copy.deepcopy(expected['system'])
|
|
131
|
-
output['tools'] = copy.deepcopy(expected['tools'])
|
|
132
|
-
output['messages'] = copy.deepcopy(expected['messages']) + _strip(output['messages'][count:])
|
|
133
|
-
projected = {key: value for key, value in output.items()
|
|
134
|
-
if key not in ('metadata', 'stream', 'thread', 'diagnostics', 'safeguards')}
|
|
135
|
-
projected['system'] = projected['system'][1:]
|
|
136
|
-
projected['messages'] = projected['messages'][:count]
|
|
137
|
-
if 'betas' in expected:
|
|
138
|
-
projected['betas'] = betas
|
|
139
|
-
if not hmac.compare_digest(_digest(projected), parent['digest']):
|
|
140
|
-
raise UnsafePrefix('fork request differs from recorded parent')
|
|
141
|
-
return output
|
|
142
|
-
except (KeyError, TypeError, IndexError) as exc:
|
|
143
|
-
raise UnsafePrefix('invalid fork request') from exc
|
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
"""Replace a completed ping response with inert text, preserving usage only."""
|
|
2
|
-
import json
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
class UnsafeResponse(ValueError):
|
|
6
|
-
"""A malformed or untrusted response cannot be sent to the CLI."""
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
def _event(name, data):
|
|
10
|
-
return ('event: ' + name + '\ndata: ' + json.dumps(data, separators=(',', ':')) + '\n\n').encode('utf-8')
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def sanitize_stream(payload, expected_model):
|
|
14
|
-
"""Never forward upstream content; accept only a complete Messages SSE."""
|
|
15
|
-
if not isinstance(payload, bytes) or len(payload) > 8 * 1024 * 1024:
|
|
16
|
-
raise UnsafeResponse('response is missing or too large')
|
|
17
|
-
try:
|
|
18
|
-
text = payload.decode('utf-8').replace('\r\n', '\n')
|
|
19
|
-
start = None
|
|
20
|
-
usage = {}
|
|
21
|
-
finished = False
|
|
22
|
-
delta_seen = False
|
|
23
|
-
for chunk in text.split('\n\n'):
|
|
24
|
-
if not chunk.strip():
|
|
25
|
-
continue
|
|
26
|
-
if finished:
|
|
27
|
-
raise UnsafeResponse('events after message stop')
|
|
28
|
-
lines = chunk.split('\n')
|
|
29
|
-
name = next((line[6:].strip() for line in lines if line.startswith('event:')), None)
|
|
30
|
-
data = '\n'.join(line[5:].lstrip() for line in lines if line.startswith('data:'))
|
|
31
|
-
if name == 'ping' and not data:
|
|
32
|
-
continue
|
|
33
|
-
obj = json.loads(data)
|
|
34
|
-
if not isinstance(obj, dict) or obj.get('type') != name:
|
|
35
|
-
raise UnsafeResponse('invalid event')
|
|
36
|
-
if start is None and name not in ('message_start', 'ping', 'error'):
|
|
37
|
-
raise UnsafeResponse('event before message start')
|
|
38
|
-
if name == 'message_start':
|
|
39
|
-
if start is not None:
|
|
40
|
-
raise UnsafeResponse('multiple message starts')
|
|
41
|
-
start = obj.get('message')
|
|
42
|
-
if not isinstance(start, dict) or start.get('model') != expected_model:
|
|
43
|
-
raise UnsafeResponse('unexpected response model')
|
|
44
|
-
usage.update(start.get('usage') or {})
|
|
45
|
-
elif name == 'content_block_start':
|
|
46
|
-
if (obj.get('content_block') or {}).get('type') == 'server_tool_use':
|
|
47
|
-
raise UnsafeResponse('server-side tool use')
|
|
48
|
-
elif name == 'message_delta':
|
|
49
|
-
delta_seen = True
|
|
50
|
-
usage.update(obj.get('usage') or {})
|
|
51
|
-
elif name == 'message_stop':
|
|
52
|
-
finished = True
|
|
53
|
-
elif name == 'error':
|
|
54
|
-
raise UnsafeResponse('upstream error')
|
|
55
|
-
if start is None or not delta_seen or not finished:
|
|
56
|
-
raise UnsafeResponse('incomplete response')
|
|
57
|
-
identifier = start.get('id')
|
|
58
|
-
if not isinstance(identifier, str) or not identifier:
|
|
59
|
-
raise UnsafeResponse('missing message id')
|
|
60
|
-
keys = ('input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens')
|
|
61
|
-
for key in keys:
|
|
62
|
-
value = usage.get(key, 0)
|
|
63
|
-
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
|
64
|
-
raise UnsafeResponse('invalid usage')
|
|
65
|
-
usage = {key: usage.get(key, 0) for key in keys}
|
|
66
|
-
message = {'id': identifier, 'type': 'message', 'role': 'assistant', 'content': [],
|
|
67
|
-
'model': expected_model, 'stop_reason': None, 'stop_sequence': None,
|
|
68
|
-
'usage': usage}
|
|
69
|
-
result = b''.join((
|
|
70
|
-
_event('message_start', {'type': 'message_start', 'message': message}),
|
|
71
|
-
_event('content_block_start', {'type': 'content_block_start', 'index': 0,
|
|
72
|
-
'content_block': {'type': 'text', 'text': ''}}),
|
|
73
|
-
_event('content_block_delta', {'type': 'content_block_delta', 'index': 0,
|
|
74
|
-
'delta': {'type': 'text_delta', 'text': 'ok'}}),
|
|
75
|
-
_event('content_block_stop', {'type': 'content_block_stop', 'index': 0}),
|
|
76
|
-
_event('message_delta', {'type': 'message_delta', 'delta': {'stop_reason': 'end_turn', 'stop_sequence': None},
|
|
77
|
-
'usage': {'output_tokens': usage.get('output_tokens', 0)}}),
|
|
78
|
-
_event('message_stop', {'type': 'message_stop'}),
|
|
79
|
-
))
|
|
80
|
-
return result, usage
|
|
81
|
-
except (ValueError, TypeError, UnicodeError, KeyError) as exc:
|
|
82
|
-
if isinstance(exc, UnsafeResponse):
|
|
83
|
-
raise
|
|
84
|
-
raise UnsafeResponse('invalid upstream response') from exc
|