@alexgreensh/token-optimizer 5.13.68 → 5.13.70

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 (182) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -0,0 +1,121 @@
1
+ """User-scoped systemd timer for keep-warm ticks."""
2
+ import subprocess
3
+
4
+
5
+ def _quote(value, exec_arg=False):
6
+ value = str(value)
7
+ if any(char in value for char in ('\n', '\r', '\x00')):
8
+ raise ValueError('invalid systemd unit value')
9
+ value = value.replace('\\', '\\\\').replace('"', '\\"').replace('%', '%%')
10
+ if exec_arg:
11
+ value = value.replace('$', '$$')
12
+ return '"' + value + '"'
13
+
14
+
15
+ def unit_texts(python, script, snapshot, interval):
16
+ interval = int(interval)
17
+ if interval < 1:
18
+ raise ValueError('timer interval must be positive')
19
+ service = ('[Unit]\nDescription=Token Optimizer keep-warm tick\n\n'
20
+ '[Service]\nType=oneshot\nExecStart=' + _quote(python, True) + ' ' +
21
+ _quote(script, True) + ' keepwarm-tick --quiet\nEnvironment=' +
22
+ _quote('TOKEN_OPTIMIZER_SNAPSHOT_DIR=' + str(snapshot)) + '\n')
23
+ timer = ('[Unit]\nDescription=Token Optimizer keep-warm timer\n\n'
24
+ '[Timer]\nOnBootSec={0}s\nOnUnitActiveSec={0}s\n'
25
+ 'Unit=token-optimizer-keepwarm.service\n\n'
26
+ '[Install]\nWantedBy=timers.target\n').format(interval)
27
+ return service, timer
28
+
29
+
30
+ def _paths(facade):
31
+ xdg = facade.os.environ.get('XDG_CONFIG_HOME', '').strip()
32
+ base = facade.Path(xdg) if xdg else facade.Path.home() / '.config'
33
+ if not base.is_absolute():
34
+ raise ValueError('XDG_CONFIG_HOME must be absolute')
35
+ user = base / 'systemd' / 'user'
36
+ return (user / 'token-optimizer-keepwarm.service',
37
+ user / 'token-optimizer-keepwarm.timer',
38
+ facade.SNAPSHOT_DIR / 'keepwarm-linux-installed')
39
+
40
+
41
+ def install(facade):
42
+ if facade._scheduler_install_refused():
43
+ return False, facade._SCHEDULER_REFUSAL
44
+ try:
45
+ service, timer, marker = _paths(facade)
46
+ if any(path.is_symlink() for path in (service, timer, marker)):
47
+ return False, 'Refusing a symlinked scheduler file.'
48
+ if (service.exists() or timer.exists()) and not marker.is_file():
49
+ return False, 'A keep-warm systemd unit exists without this installation’s marker.'
50
+ content = unit_texts(facade._keepwarm_python3_path(),
51
+ facade._keepwarm_measure_script_path(),
52
+ facade.SNAPSHOT_DIR, facade._KEEPWARM_SCHEDULER_START_INTERVAL)
53
+ service.parent.mkdir(parents=True, exist_ok=True)
54
+ marker.parent.mkdir(parents=True, exist_ok=True)
55
+ marker.write_text('pending\n', encoding='utf-8')
56
+ service.write_text(content[0], encoding='utf-8')
57
+ timer.write_text(content[1], encoding='utf-8')
58
+ for command in (['systemctl', '--user', 'daemon-reload'],
59
+ ['systemctl', '--user', 'enable', '--now', timer.name]):
60
+ proc = facade.subprocess.run(command, capture_output=True, text=True,
61
+ timeout=10, creationflags=facade._NO_WINDOW)
62
+ if proc.returncode:
63
+ return False, 'Could not enable the systemd user timer: ' + (proc.stderr or '').strip()
64
+ marker.write_text('enabled\n', encoding='utf-8')
65
+ return True, 'Keep-warm systemd user timer enabled.'
66
+ except (OSError, ValueError, TypeError, subprocess.TimeoutExpired) as exc:
67
+ return False, 'Could not install the systemd user timer: ' + str(exc)
68
+
69
+
70
+ def status(facade, gate):
71
+ service, timer, marker = _paths(facade)
72
+ try:
73
+ owned = marker.is_file() and marker.read_text(encoding='utf-8').strip() == 'enabled'
74
+ except OSError:
75
+ owned = False
76
+ allowed, reason = gate()
77
+ result = {'installed': bool(owned and service.is_file() and timer.is_file()),
78
+ 'label': timer.name, 'plist_path': str(timer),
79
+ 'last_tick_ok': facade._keepwarm_scheduler_last_tick_ok(),
80
+ 'last_tick_age': facade._keepwarm_scheduler_last_tick_age(),
81
+ 'gate_allowed': bool(allowed), 'consent': facade.keepwarm_consent(),
82
+ 'billing_mode': facade.keepwarm_billing_mode()}
83
+ if not allowed:
84
+ result['reason'] = reason
85
+ return result
86
+
87
+
88
+ def uninstall(facade):
89
+ try:
90
+ _, timer, marker = _paths(facade)
91
+ if not marker.is_file() or marker.is_symlink():
92
+ return True, 'Keep-warm systemd timer is not owned by this installation.'
93
+ proc = facade.subprocess.run(['systemctl', '--user', 'disable', '--now', timer.name],
94
+ capture_output=True, text=True, timeout=10,
95
+ creationflags=facade._NO_WINDOW)
96
+ if proc.returncode:
97
+ return False, 'Could not disable keep-warm timer: ' + (proc.stderr or '').strip()
98
+ marker.write_text('disabled\n', encoding='utf-8')
99
+ return True, 'Keep-warm systemd timer disabled.'
100
+ except (OSError, ValueError, subprocess.TimeoutExpired) as exc:
101
+ return False, 'Could not disable keep-warm timer: ' + str(exc)
102
+
103
+
104
+ def repair(facade, gate):
105
+ allowed, _ = gate()
106
+ if not allowed:
107
+ return 'noop-gate'
108
+ try:
109
+ service, timer, marker = _paths(facade)
110
+ if not marker.is_file() or marker.read_text(encoding='utf-8').strip() != 'enabled':
111
+ return 'noop-no-marker'
112
+ expected = unit_texts(facade._keepwarm_python3_path(), facade._keepwarm_measure_script_path(),
113
+ facade.SNAPSHOT_DIR, facade._KEEPWARM_SCHEDULER_START_INTERVAL)
114
+ if service.read_text(encoding='utf-8') == expected[0] and timer.read_text(encoding='utf-8') == expected[1]:
115
+ return 'noop-fresh'
116
+ except (OSError, ValueError):
117
+ pass
118
+ with facade._keepwarm_scheduler_install_lock(soft_fail=True) as acquired:
119
+ if not acquired:
120
+ return 'repair-failed'
121
+ return 'repaired' if install(facade)[0] else 'repair-failed'
@@ -0,0 +1,143 @@
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
@@ -0,0 +1,84 @@
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
@@ -0,0 +1,256 @@
1
+ """Fail-closed liveness checks for paused Claude sessions."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import shlex
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import time
12
+
13
+
14
+ def process_info(pid):
15
+ try:
16
+ proc = subprocess.run(['ps', '-p', str(int(pid)), '-o', 'ppid=', '-o', 'lstart=', '-o', 'comm='],
17
+ capture_output=True, text=True, timeout=1, check=True)
18
+ parts = proc.stdout.strip().split(None, 6)
19
+ if len(parts) != 7:
20
+ return None
21
+ return {'ppid': int(parts[0]), 'start': ' '.join(parts[1:6]), 'command': parts[6]}
22
+ except (OSError, ValueError, subprocess.SubprocessError):
23
+ return None
24
+
25
+
26
+ def interactive_parent(argv, tty, descriptors, ancestors):
27
+ """Require real terminal I/O and reject explicit print or known delegates."""
28
+ if not tty or len(descriptors) != 2:
29
+ return False
30
+ if not all(path.startswith(('/dev/tty', '/dev/pts/')) for path in descriptors):
31
+ return False
32
+ for arg in argv[1:]:
33
+ if arg == '--':
34
+ break
35
+ if arg == '--print' or arg.startswith('--print=') or (arg.startswith('-') and not arg.startswith('--') and 'p' in arg[1:]):
36
+ return False
37
+ return not any('outsourcerer' in command.lower() or 'osrc-' in command.lower() for command in ancestors)
38
+
39
+
40
+ def is_claude_command(command):
41
+ path = Path(str(command))
42
+ return (path.name.lower() == 'claude' or
43
+ (path.parent.name == 'versions' and path.parent.parent.name == 'claude' and
44
+ bool(re.fullmatch(r'\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?', path.name))))
45
+
46
+
47
+ def _ps_command(pid):
48
+ proc = subprocess.run(['ps', '-p', str(int(pid)), '-o', 'tty=', '-o', 'args='],
49
+ capture_output=True, text=True, timeout=1, check=True)
50
+ tty, args = proc.stdout.strip().split(None, 1)
51
+ return tty, shlex.split(args)
52
+
53
+
54
+ def _terminal_descriptors(pid):
55
+ if sys.platform.startswith('linux'):
56
+ return [os.readlink('/proc/%s/fd/%s' % (pid, fd)) for fd in (0, 1)]
57
+ if sys.platform == 'darwin':
58
+ proc = subprocess.run(['/usr/sbin/lsof', '-nP', '-a', '-p', str(int(pid)), '-d', '0,1', '-Ffn'],
59
+ capture_output=True, text=True, timeout=2, check=True)
60
+ found, descriptor = {}, None
61
+ for line in proc.stdout.splitlines():
62
+ if line.startswith('f'):
63
+ descriptor = line[1:]
64
+ elif line.startswith('n') and descriptor in ('0', '1'):
65
+ found[descriptor] = line[1:]
66
+ return [found.get('0', ''), found.get('1', '')]
67
+ return []
68
+
69
+
70
+ def tmux_parent_allowed(panes, ancestry):
71
+ """Reject identifiable delegate sessions and unknown pane ancestry."""
72
+ names = []
73
+ for line in panes.splitlines():
74
+ try:
75
+ pane_pid, name = line.split('\t', 1)
76
+ if int(pane_pid) in ancestry:
77
+ names.append(name.lower())
78
+ except (ValueError, TypeError):
79
+ continue
80
+ return bool(names) and not any(name.startswith(('outsourcerer-', 'osrc-')) for name in names)
81
+
82
+
83
+ def owner_eligible(pid):
84
+ try:
85
+ tty, argv = _ps_command(pid)
86
+ ancestors, ancestry, has_tmux = [], {pid}, False
87
+ info = process_info(pid)
88
+ for _ in range(16):
89
+ if not info or info['ppid'] <= 1:
90
+ break
91
+ parent = info['ppid']
92
+ _, args = _ps_command(parent)
93
+ ancestors.append(' '.join(args))
94
+ info = process_info(parent)
95
+ if not info:
96
+ return False
97
+ ancestry.add(parent)
98
+ has_tmux = has_tmux or Path(info['command']).name.lower().startswith('tmux')
99
+ if has_tmux:
100
+ binary = shutil.which('tmux') or next((path for path in ('/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux') if os.path.isfile(path)), None)
101
+ if not binary:
102
+ return False
103
+ panes = subprocess.run([binary, 'list-panes', '-a', '-F', '#{pane_pid}\t#{session_name}'],
104
+ capture_output=True, text=True, timeout=2, check=True).stdout
105
+ if not tmux_parent_allowed(panes, ancestry):
106
+ return False
107
+ return interactive_parent(argv, tty, _terminal_descriptors(pid), ancestors)
108
+ except (OSError, ValueError, subprocess.SubprocessError):
109
+ return False
110
+
111
+
112
+ def find_owner(pid=None, lookup=process_info, eligibility=owner_eligible):
113
+ pid = os.getppid() if pid is None else pid
114
+ for _ in range(16):
115
+ if pid <= 1:
116
+ break
117
+ info = lookup(pid)
118
+ if not info:
119
+ break
120
+ if is_claude_command(info['command']):
121
+ return {'pid': pid, 'start': info['start']} if eligibility(pid) else None
122
+ pid = info['ppid']
123
+ return None
124
+
125
+
126
+ _NO_OWNER_TTL = 300.0
127
+
128
+
129
+ def _owner_cache_path(directory, session_id):
130
+ name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
131
+ return Path(directory) / ('keepwarm-owner-' + name)
132
+
133
+
134
+ def _pid_exists(pid):
135
+ """Subprocess-free liveness; the tick re-verifies identity with owner_alive."""
136
+ if os.name != 'posix':
137
+ return False
138
+ try:
139
+ os.kill(int(pid), 0)
140
+ except PermissionError:
141
+ return True
142
+ except (OSError, ValueError, TypeError):
143
+ return False
144
+ return True
145
+
146
+
147
+ def session_owner(directory, session_id, now=None):
148
+ """find_owner once per session, not once per Stop hook.
149
+
150
+ The owning Claude process is constant for a session, but find_owner walks the
151
+ process table with several `ps`/`lsof` children. A positive answer is reused
152
+ while the pid still exists; a negative one for _NO_OWNER_TTL seconds, so an
153
+ ineligible session does not re-run the walk on every turn. Fail closed: any
154
+ cache problem falls through to a fresh lookup.
155
+ """
156
+ now = time.time() if now is None else now
157
+ path = _owner_cache_path(directory, session_id) if session_id else None
158
+ if path is not None:
159
+ try:
160
+ cached = json.loads(path.read_text(encoding='utf-8'))
161
+ owner = cached.get('owner')
162
+ if isinstance(owner, dict) and owner.get('pid') and owner.get('start'):
163
+ if _pid_exists(owner['pid']):
164
+ return owner
165
+ elif owner is None and 0 <= now - float(cached.get('ts')) < _NO_OWNER_TTL:
166
+ return None
167
+ except (OSError, ValueError, TypeError, AttributeError):
168
+ pass
169
+ owner = find_owner()
170
+ if path is not None:
171
+ try:
172
+ Path(directory).mkdir(parents=True, exist_ok=True)
173
+ fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0), 0o600)
174
+ with os.fdopen(fd, 'w', encoding='utf-8') as stream:
175
+ json.dump({'owner': owner, 'ts': now}, stream)
176
+ except OSError:
177
+ pass
178
+ return owner
179
+
180
+
181
+ def owner_alive(owner, lookup=process_info, eligibility=owner_eligible):
182
+ if not isinstance(owner, dict) or not owner.get('pid') or not owner.get('start'):
183
+ return False
184
+ info = lookup(owner['pid'])
185
+ return bool(info and is_claude_command(info['command']) and info['start'] == owner['start'] and eligibility(owner['pid']))
186
+
187
+
188
+ def _end_path(directory, session_id):
189
+ name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
190
+ return Path(directory) / ('keepwarm-ended-' + name)
191
+
192
+
193
+ def mark_ended(directory, session_id):
194
+ if not session_id:
195
+ return False
196
+ try:
197
+ Path(directory).mkdir(parents=True, exist_ok=True)
198
+ path = _end_path(directory, session_id)
199
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0)
200
+ fd = os.open(str(path), flags, 0o600)
201
+ with os.fdopen(fd, 'w', encoding='utf-8') as stream:
202
+ if hasattr(os, 'fchmod'):
203
+ os.fchmod(stream.fileno(), 0o600)
204
+ stream.write(str(time.time()))
205
+ return True
206
+ except OSError:
207
+ return False
208
+
209
+
210
+ def ended_since(directory, session_id, armed_at):
211
+ try:
212
+ path = _end_path(directory, session_id)
213
+ if path.is_symlink():
214
+ return True
215
+ return float(path.read_text(encoding='utf-8')) >= float(armed_at)
216
+ except FileNotFoundError:
217
+ return False
218
+ except (OSError, ValueError, TypeError):
219
+ return True
220
+
221
+
222
+ def compacted_since(record):
223
+ """Fail closed if the post-arm transcript is missing, truncated or too large."""
224
+ try:
225
+ path = Path(record['transcript_path'])
226
+ offset = int(record['byte_size'])
227
+ if offset < 0 or path.stat().st_size < offset or path.stat().st_size - offset > 5 * 1024 * 1024:
228
+ return True
229
+ with path.open('rb') as stream:
230
+ stream.seek(offset)
231
+ tail = stream.read()
232
+ return b'compact_boundary' in tail or b'isCompactSummary' in tail
233
+ except (KeyError, OSError, TypeError, ValueError):
234
+ return True
235
+
236
+
237
+ def reconcile_attempts(record, rows):
238
+ """Recover attempt caps from the append-only ledger after a tick crash."""
239
+ session = str(record.get('session_id') or '')
240
+ start = float(record.get('ts') or 0)
241
+ relevant = [row for row in rows if str(row.get('session_id') or '') == session
242
+ and float(row.get('ts') or 0) >= start]
243
+ attempts = [float(row['ts']) for row in relevant if row.get('status') == 'firing']
244
+ outcomes = [row for row in relevant if row.get('status') in ('ok', 'error', 'timeout')]
245
+ changed = False
246
+ if len(attempts) > len(record.get('pings_fired') or []):
247
+ record['pings_fired'] = sorted(attempts)
248
+ changed = True
249
+ prefix = int(record.get('prefix_proxy') or 0)
250
+ unsafe = any(row.get('status') != 'ok' or int(row.get('cache_read') or 0) < prefix * 0.5
251
+ or int(row.get('cache_write') or 0) >= prefix * 0.5 for row in outcomes)
252
+ if attempts and (len(outcomes) < len(attempts) or unsafe):
253
+ if not record.get('ping_failed'):
254
+ record['ping_failed'] = True
255
+ changed = True
256
+ return changed