@alexgreensh/token-optimizer 5.13.75 → 5.13.76

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 (84) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +75 -81
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -6,19 +6,22 @@ from pathlib import Path
6
6
  import re
7
7
  import shlex
8
8
  import shutil
9
+ import stat
9
10
  import subprocess
10
11
  import sys
11
12
  import time
12
13
 
14
+ from process_identity import process_start
15
+
13
16
 
14
17
  def process_info(pid):
15
- # Keep-warm watches a terminal Claude through `ps`/`lsof`; Windows has neither, so there is no
16
- # owner to find. Answering here keeps the Stop hook from spawning a `ps` that cannot exist.
18
+ # Terminal owner checks use ps and lsof, which are unavailable on Windows.
17
19
  if os.name != 'posix':
18
20
  return None
19
21
  try:
20
22
  proc = subprocess.run(['ps', '-p', str(int(pid)), '-o', 'ppid=', '-o', 'lstart=', '-o', 'comm='],
21
- capture_output=True, text=True, timeout=1, check=True)
23
+ capture_output=True, text=True, timeout=1, check=True,
24
+ env={**os.environ, 'LC_ALL': 'C'})
22
25
  parts = proc.stdout.strip().split(None, 6)
23
26
  if len(parts) != 7:
24
27
  return None
@@ -113,8 +116,9 @@ def owner_eligible(pid):
113
116
  return False
114
117
 
115
118
 
116
- def find_owner(pid=None, lookup=process_info, eligibility=owner_eligible):
119
+ def _find_claude_process(pid=None, lookup=None):
117
120
  pid = os.getppid() if pid is None else pid
121
+ lookup = process_info if lookup is None else lookup
118
122
  for _ in range(16):
119
123
  if pid <= 1:
120
124
  break
@@ -122,11 +126,16 @@ def find_owner(pid=None, lookup=process_info, eligibility=owner_eligible):
122
126
  if not info:
123
127
  break
124
128
  if is_claude_command(info['command']):
125
- return {'pid': pid, 'start': info['start']} if eligibility(pid) else None
129
+ return {'pid': pid, 'start': info['start']}
126
130
  pid = info['ppid']
127
131
  return None
128
132
 
129
133
 
134
+ def find_owner(pid=None, lookup=process_info, eligibility=owner_eligible):
135
+ process = _find_claude_process(pid, lookup)
136
+ return process if process and eligibility(process['pid']) else None
137
+
138
+
130
139
  _NO_OWNER_TTL = 300.0
131
140
 
132
141
 
@@ -136,7 +145,7 @@ def _owner_cache_path(directory, session_id):
136
145
 
137
146
 
138
147
  def _pid_exists(pid):
139
- """Subprocess-free liveness; the tick re-verifies identity with owner_alive."""
148
+ """Check whether a process may still be running."""
140
149
  if os.name != 'posix':
141
150
  return False
142
151
  try:
@@ -148,38 +157,46 @@ def _pid_exists(pid):
148
157
  return True
149
158
 
150
159
 
151
- def session_owner(directory, session_id, now=None):
152
- """find_owner once per session, not once per Stop hook.
153
-
154
- The owning Claude process is constant for a session, but find_owner walks the
155
- process table with several `ps`/`lsof` children. A positive answer is reused
156
- while the pid still exists; a negative one for _NO_OWNER_TTL seconds, so an
157
- ineligible session does not re-run the walk on every turn. Fail closed: any
158
- cache problem falls through to a fresh lookup.
159
- """
160
+ def session_owner(directory, session_id, now=None, *, parent_pid=None, parent_start=None):
161
+ """Reuse terminal eligibility only for the current hook's Claude process."""
162
+ process = _find_claude_process(parent_pid)
163
+ if process is None:
164
+ return None
160
165
  now = time.time() if now is None else now
166
+ if parent_pid is not None:
167
+ # Check the wrapper itself after the ancestry walk. Its replacement
168
+ # could otherwise lead to an older, unrelated Claude process.
169
+ if parent_start is not None and process_start(parent_pid) != parent_start:
170
+ return None
171
+ try:
172
+ started = time.mktime(time.strptime(process['start'], '%a %b %d %H:%M:%S %Y'))
173
+ except (ValueError, OverflowError, OSError):
174
+ return None
175
+ # ps reports whole seconds. A start in the hook's own second is
176
+ # ambiguous if the original parent exited and its PID was reused.
177
+ if started >= int(now):
178
+ return None
161
179
  path = _owner_cache_path(directory, session_id) if session_id else None
162
180
  if path is not None:
163
181
  try:
164
182
  cached = json.loads(path.read_text(encoding='utf-8'))
165
- owner = cached.get('owner')
166
- if isinstance(owner, dict) and owner.get('pid') and owner.get('start'):
167
- if _pid_exists(owner['pid']):
168
- return owner
169
- elif owner is None and 0 <= now - float(cached.get('ts')) < _NO_OWNER_TTL:
170
- return None
183
+ if cached.get('process') == process:
184
+ if cached.get('eligible') is True:
185
+ return process
186
+ if cached.get('eligible') is False and 0 <= now - float(cached.get('ts')) < _NO_OWNER_TTL:
187
+ return None
171
188
  except (OSError, ValueError, TypeError, AttributeError):
172
189
  pass
173
- owner = find_owner()
190
+ eligible = owner_eligible(process['pid'])
174
191
  if path is not None:
175
192
  try:
176
193
  Path(directory).mkdir(parents=True, exist_ok=True)
177
194
  fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0), 0o600)
178
195
  with os.fdopen(fd, 'w', encoding='utf-8') as stream:
179
- json.dump({'owner': owner, 'ts': now}, stream)
196
+ json.dump({'process': process, 'eligible': eligible, 'ts': now}, stream)
180
197
  except OSError:
181
198
  pass
182
- return owner
199
+ return process if eligible else None
183
200
 
184
201
 
185
202
  def owner_alive(owner, lookup=process_info, eligibility=owner_eligible):
@@ -223,6 +240,45 @@ def ended_since(directory, session_id, armed_at):
223
240
  return True
224
241
 
225
242
 
243
+ def terminal_turn(path):
244
+ """Return the last conversation row's identity from a bounded suffix."""
245
+ try:
246
+ with path.open("rb") as stream:
247
+ end = stream.seek(0, os.SEEK_END)
248
+ start = max(0, end - 1024 * 1024)
249
+ stream.seek(start)
250
+ suffix = stream.read(end - start)
251
+ if not suffix.endswith(b"\n") or len(suffix) != end - start:
252
+ return None
253
+ lines = suffix[:-1].split(b"\n")
254
+ for line in reversed(lines[bool(start):]):
255
+ row_end = end
256
+ end -= len(line) + 1
257
+ if not line.strip():
258
+ continue
259
+ row = json.loads(line)
260
+ if not isinstance(row, dict):
261
+ continue
262
+ if row.get("subtype") == "compact_boundary" or row.get("isCompactSummary"):
263
+ return None
264
+ if row.get("type") in ("user", "assistant"):
265
+ return {"end": row_end, "digest": hashlib.sha256(line).hexdigest(),
266
+ "timestamp": row.get("timestamp") or row.get("ts")}
267
+ except (OSError, ValueError, RecursionError):
268
+ return None
269
+ return None
270
+
271
+
272
+ def same_pause(existing, record):
273
+ if "terminal_turn" in record and "terminal_turn" in existing:
274
+ return existing["terminal_turn"] == record["terminal_turn"]
275
+ try:
276
+ return (abs(float(existing.get("transcript_mtime") or 0) - record["transcript_mtime"]) < 0.001
277
+ and int(existing["byte_size"]) == record["byte_size"])
278
+ except (KeyError, TypeError, ValueError):
279
+ return False
280
+
281
+
226
282
  def compacted_since(record):
227
283
  """Fail closed if the post-arm transcript is missing, truncated or too large."""
228
284
  try:
@@ -258,3 +314,471 @@ def reconcile_attempts(record, rows):
258
314
  record['ping_failed'] = True
259
315
  changed = True
260
316
  return changed
317
+
318
+
319
+ def _headless_latch(facade):
320
+ return facade.SNAPSHOT_DIR / 'keepwarm-headless-unproved'
321
+
322
+
323
+ def _headless_preference_disabled(facade, env):
324
+ from . import keepwarm_auto
325
+
326
+ if env.get(facade._KEEPWARM_PING_ENV):
327
+ return 'ping-process'
328
+ if facade._keepwarm_llm_ping_disabled(env):
329
+ return 'kill-switch'
330
+ if (str(env.get('TOKEN_OPTIMIZER_KEEPWARM_HEADLESS', 'on')).strip().lower() in keepwarm_auto.OFF
331
+ or facade._read_config_flag('keepwarm_auto', None) is False):
332
+ return 'settings-disabled'
333
+ if facade.keepwarm_consent() == 'declined':
334
+ return 'consent-declined'
335
+
336
+
337
+ def _headless_latch_reason(facade):
338
+ try:
339
+ path = _headless_latch(facade)
340
+ if path.is_symlink():
341
+ return 'headless-proof'
342
+ with path.open(encoding='utf-8') as stream:
343
+ state = stream.read(128).split()
344
+ if state and state[0] == 'pending':
345
+ if len(state) == 3 and state[2].isdecimal() and int(state[2]) > 1 and _pid_exists(state[2]):
346
+ return 'headless-busy'
347
+ if 0 <= facade.time.time() - path.stat().st_mtime < 200:
348
+ return 'headless-busy'
349
+ return 'headless-proof'
350
+ except FileNotFoundError:
351
+ return None
352
+ except OSError:
353
+ return 'accounting-unavailable'
354
+ except UnicodeError:
355
+ return 'headless-proof'
356
+
357
+
358
+ def headless_disabled(facade, env=None):
359
+ """Flags, opt-out and install-wide proof latch, without reading transcripts."""
360
+ env = facade.os.environ if env is None else env
361
+ return _headless_preference_disabled(facade, env) or _headless_latch_reason(facade)
362
+
363
+
364
+ def reset_headless_proof(facade):
365
+ """Clear an install-wide proof stop after the active attempt has finished."""
366
+ from .mod_action_booking import _lock
367
+
368
+ try:
369
+ with _lock(facade) as held:
370
+ if not held:
371
+ return 'ledger-locked'
372
+ reason = _headless_latch_reason(facade)
373
+ if reason == 'headless-proof':
374
+ _headless_latch(facade).unlink(missing_ok=True)
375
+ return None
376
+ return reason
377
+ except OSError:
378
+ return 'accounting-unavailable'
379
+
380
+
381
+ def scheduler_gate(facade, env=None):
382
+ reason = headless_disabled(facade, env)
383
+ if reason is None and (facade._remote_lean_profile() or facade.detect_runtime() != 'claude'):
384
+ reason = 'platform-gap'
385
+ if reason is None and facade.keepwarm_tripwire_mode() == 'off':
386
+ reason = 'tripwire-off'
387
+ return reason is None, reason or 'headless-enabled'
388
+
389
+
390
+ def _run_ping(facade, runner, command, cwd, env, context, fallback_cost):
391
+ """Return only usage and bounded machine-readable diagnostics from the child."""
392
+ import math
393
+ from .keepwarm_auto import proof_ok
394
+
395
+ row = {'status': 'error', 'reason': 'unproved-cache-read', 'proof': False,
396
+ 'cost_usd': fallback_cost}
397
+ try:
398
+ if runner is None:
399
+ def runner(args, folder, environment, timeout):
400
+ return subprocess.run(args, cwd=folder, env=environment, timeout=timeout,
401
+ stdin=subprocess.DEVNULL, capture_output=True, text=True,
402
+ encoding='utf-8', errors='replace')
403
+ output = runner(command, cwd, env, facade._KEEPWARM_PING_TIMEOUT_SECONDS)
404
+ try:
405
+ data = json.loads(output.stdout)
406
+ except (ValueError, TypeError):
407
+ data = {}
408
+ if not isinstance(data, dict):
409
+ data = {}
410
+ reported = data.get('total_cost_usd')
411
+ if type(reported) in (float, int) and math.isfinite(reported) and reported > 0:
412
+ row['cost_usd'] = reported
413
+ usage = data.get('usage')
414
+ row['proof'] = (output.returncode == 0 and data.get('is_error') is not True
415
+ and proof_ok(usage, context))
416
+ if row['proof']:
417
+ row.update(status='ok', reason='proved',
418
+ cache_read=usage['cache_read_input_tokens'],
419
+ cache_write=usage['cache_creation_input_tokens'])
420
+ elif output.returncode != 0 or data.get('is_error') is True:
421
+ cache_used = isinstance(usage, dict) and any(
422
+ type(usage.get(key)) is int and usage[key] > 0
423
+ for key in ('cache_read_input_tokens', 'cache_creation_input_tokens'))
424
+ error_fields = (data.get('errors'), data.get('result'), data.get('error'), getattr(output, 'stderr', ''))
425
+ if not cache_used and any(re.search(
426
+ r'\b(?:rate[ _-]limit(?:ed|[ _-]error)?|(?:http|api error:?)\s+429|too many requests)\b',
427
+ str(field)[:4096], re.IGNORECASE) for field in error_fields):
428
+ row['reason'] = 'rate-limited'
429
+ except subprocess.TimeoutExpired:
430
+ row.update(status='timeout', reason='timeout')
431
+ except (OSError, ValueError, AttributeError, TypeError):
432
+ pass
433
+ return row
434
+
435
+
436
+ def _pending_attempt(rows, sid, now):
437
+ pending = {r.get('action_id') for r in rows if r.get('session_id') == sid
438
+ and r.get('action_id') and r.get('status') == 'firing'
439
+ and float(r['ts']) > now - 600}
440
+ finished = {r.get('action_id') for r in rows if r.get('session_id') == sid
441
+ and r.get('status') in ('ok', 'error', 'timeout', 'cancelled', 'unproved')}
442
+ return bool(pending - finished)
443
+
444
+
445
+ def fire_headless(facade, record, *, now, env=None, runner=None, live=None, meters=None):
446
+ """Reserve once under the shared lock, then run one bounded fork and prove it."""
447
+ from .mod_action_booking import _append, _lock
448
+
449
+ sid, model = record['session_id'], record['model']
450
+ context = record['prefix_proxy']
451
+ if not facade._keepwarm_valid_arg(sid) or not facade._keepwarm_valid_arg(model):
452
+ return {'fired': False, 'reason': 'bad-record'}
453
+ binary, cwd = facade._keepwarm_resolve_claude_bin(), facade._keepwarm_extract_cwd(record['transcript_path'])
454
+ if not binary or not cwd:
455
+ return {'fired': False, 'reason': 'launch-unavailable'}
456
+ if live is None:
457
+ live = lambda: facade.classify_keepwarm_record(record, now=now) == 'still_paused'
458
+ if meters is None:
459
+ meters = _headless_meters(facade, now)
460
+ if env is None:
461
+ env = facade.os.environ
462
+ latch = _headless_latch(facade)
463
+ with _lock(facade) as held:
464
+ if not held:
465
+ return {'fired': False, 'reason': 'ledger-locked'}
466
+ rows = facade._keepwarm_load_ledger_rows()
467
+ decision = _headless_decision(facade, record, now, env, meters, rows)
468
+ if decision['action'] != 'ping':
469
+ return {'fired': False, 'reason': decision['reason']}
470
+ if _pending_attempt(rows, sid, now) or not live():
471
+ return {'fired': False, 'reason': 'session-changed-or-busy'}
472
+ action_id = 'headless-' + os.urandom(16).hex()
473
+ pause_key = facade._keepwarm_pause_key(sid, record['ts'])
474
+ fallback = facade._get_model_cost(model, 1000, 0, 0, context,
475
+ cache_create_1h=context, cache_create_5m=0, per_request=True)
476
+ if fallback <= 0:
477
+ return {'fired': False, 'reason': 'unpriced'}
478
+ common = {'source': 'keepwarm-headless', 'action': 'warm', 'auto': True,
479
+ 'session_id': sid, 'action_id': action_id, 'attempt_key': action_id,
480
+ 'pause_key': pause_key, 'model': model, 'prefix_proxy': context}
481
+ command = facade._keepwarm_build_ping_cmd(sid, model, binary,
482
+ budget_usd=max(facade._KEEPWARM_PING_BUDGET_USD, 2 * decision['ping_cost_usd']))
483
+ # Ask rules preserve the tool definitions while unattended prompts deny tool calls.
484
+ settings = json.dumps({'disableAllHooks': True, 'permissions': {'ask': ['*']}})
485
+ command.extend(['--max-turns', '1', '--permission-mode', 'default',
486
+ '--permission-prompts', 'none', '--settings', settings,
487
+ '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}'])
488
+ try:
489
+ fd = os.open(str(latch), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
490
+ except OSError:
491
+ return {'fired': False, 'reason': 'headless-proof'}
492
+ try:
493
+ with os.fdopen(fd, 'w') as stream:
494
+ stream.write(f'pending {action_id} {os.getpid()}')
495
+ _append(facade._keepwarm_ledger_path(), {**common, 'status': 'firing',
496
+ 'ts': now, 'est_cost_usd': fallback})
497
+ reason = _headless_preference_disabled(facade, env) if live() else 'session-changed'
498
+ if reason:
499
+ _append(facade._keepwarm_ledger_path(), {**common, 'status': 'cancelled', 'ts': now})
500
+ latch.unlink()
501
+ return {'fired': False, 'reason': reason}
502
+ except OSError:
503
+ latch.unlink(missing_ok=True)
504
+ return {'fired': False, 'reason': 'accounting-unavailable'}
505
+ child_env = dict(env)
506
+ child_env.pop('CLAUDECODE', None)
507
+ child_env[facade._KEEPWARM_PING_ENV] = '1'
508
+ # Keep the live session's environment: DISABLE_TELEMETRY alone changed the prompt prefix and rewrote 63% of the cache.
509
+ child_env['PATH'] = os.path.dirname(binary) + os.pathsep + child_env.get('PATH', os.defpath)
510
+ outcome = _run_ping(facade, runner, command, cwd, child_env, context, fallback)
511
+ recorded = False
512
+ try:
513
+ for _ in range(2):
514
+ with _lock(facade) as held:
515
+ if not held:
516
+ continue
517
+ _append(facade._keepwarm_ledger_path(), {**common, **outcome, 'ts': max(now, facade.time.time())})
518
+ recorded = True
519
+ if outcome['proof']:
520
+ _track_proven_ping(facade, record, now)
521
+ break
522
+ finally:
523
+ # The pending marker excludes other headless pings until we settle it.
524
+ # If the ledger stays locked, the reservation still counts at fallback cost.
525
+ if outcome['proof'] or outcome['reason'] in ('timeout', 'rate-limited'):
526
+ latch.unlink(missing_ok=True)
527
+ else:
528
+ fd = os.open(str(latch), os.O_WRONLY | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0))
529
+ with os.fdopen(fd, 'w') as stream:
530
+ stream.write('failed ' + action_id)
531
+ if not recorded:
532
+ outcome['reason'] = 'ledger-locked'
533
+ return {'fired': True, **outcome}
534
+
535
+
536
+ def _track_proven_ping(facade, record, now):
537
+ """Append a replacement arm under the shared lock, only after proven usage."""
538
+ from .mod_action_booking import _append
539
+
540
+ found = next((rec for rec in reversed(facade.load_keepwarm_records())
541
+ if rec.get('session_id') == record['session_id']
542
+ and rec.get('byte_size') == record['byte_size']
543
+ and rec.get('transcript_mtime') == record['transcript_mtime']), None)
544
+ latest = found or record
545
+ updated = dict(latest, auto_warm=True, pings_fired=[*(latest.get('pings_fired') or []), now])
546
+ _append(facade._keepwarm_sidecar_path(), updated)
547
+
548
+
549
+ def _headless_meters(facade, now):
550
+ data = facade._keepwarm_read_meters(now=now)
551
+ age = data['age_s']
552
+ if age is None or not 0 <= age <= 5 * 60:
553
+ return None, None
554
+ return data['five_hour_pct'], data['seven_day_pct']
555
+
556
+
557
+ def _headless_decision(facade, record, now, env, meters, rows):
558
+ from . import keepwarm_auto as policy
559
+
560
+ since_turn = now - record['last_turn_ts']
561
+ last_ping = max((float(r['ts']) for r in rows if r.get('session_id') == record['session_id']
562
+ and r.get('action') == 'warm' and r.get('status') == 'ok'
563
+ and r.get('proof') is not False and record['last_turn_ts'] <= float(r['ts']) <= now),
564
+ default=record['last_turn_ts'])
565
+ since_cache = now - last_ping
566
+ if since_cache < policy.BUCKETS[0]:
567
+ return {'action': 'stop', 'reason': 'not-due', 'due_in_s': policy.BUCKETS[0] - since_cache}
568
+ if since_cache >= policy.CACHE_LIFETIME - 15:
569
+ return {'action': 'stop', 'reason': 'cache-expired'}
570
+ return policy.decide(facade, record['session_id'], record['prefix_proxy'], since_turn, record['model'],
571
+ policy.CACHE_LIFETIME if record['ttl_kind'] == '1h' else 0,
572
+ *meters, now, headless=True, env=env, rows=rows)
573
+
574
+
575
+ def scheduler_tick(facade, now, dry_run, env, runner):
576
+ """Process the latest arm per session, with the same policy as the band."""
577
+ allowed, reason = scheduler_gate(facade, env)
578
+ summary = {'allowed': allowed, 'reason': reason, 'decisions': [], 'fired': 0, 'skipped': 0, 'errors': 0}
579
+ with facade._keepwarm_tick_singleton() as held:
580
+ if not held:
581
+ return dict(summary, reason='tick-already-running')
582
+ if not dry_run:
583
+ booked = facade.keepwarm_detect_realized(now=now)
584
+ facade.compact_keepwarm_sidecar(now=now)
585
+ if allowed:
586
+ latest = {record['session_id']: record for record in facade.load_keepwarm_records()
587
+ if record.get('owner')}
588
+ for sid, record in latest.items():
589
+ try:
590
+ at = now if dry_run or runner is not None else facade.time.time()
591
+ if facade.classify_keepwarm_record(record, now=at) != 'still_paused':
592
+ continue
593
+ decision = _headless_decision(facade, record, at, env, _headless_meters(facade, at),
594
+ facade._keepwarm_load_ledger_rows())
595
+ entry = {'session_id': sid, 'action': decision['action'], 'reason': decision['reason']}
596
+ summary['decisions'].append(entry)
597
+ if decision['action'] == 'ping' and not dry_run:
598
+ result = fire_headless(facade, record, now=at, env=env, runner=runner)
599
+ summary['fired' if result['fired'] else 'skipped'] += 1
600
+ entry['fire_reason'] = result['reason']
601
+ if result.get('proof') is False:
602
+ break
603
+ except Exception:
604
+ summary['errors'] += 1
605
+ if not dry_run:
606
+ facade._keepwarm_emit_tick_observability(
607
+ now=now, allowed=allowed, reason=reason, armed=len(summary['decisions']),
608
+ fired=summary['fired'], skipped=summary['skipped'],
609
+ booked=booked.get('realized', 0), errors=summary['errors'])
610
+ return summary
611
+
612
+
613
+ def desktop_headless_main(facade, args):
614
+ """Desktop fallback uses a fresh transcript snapshot supplied by the live mod."""
615
+ from .keepwarm_auto import _parse_args
616
+ from .mod_action_booking import _snapshot, _snapshot_still_usable
617
+
618
+ try:
619
+ event = json.loads(facade.sys.stdin.read(8193))
620
+ values = _parse_args(args)
621
+ sid = values.session_id
622
+ now = facade.time.time()
623
+ path = Path(event['transcript_path']).resolve(strict=True)
624
+ projects = (facade.CLAUDE_DIR / 'projects').resolve(strict=True)
625
+ if projects not in path.parents:
626
+ raise ValueError('unexpected transcript path')
627
+ snapshot = _snapshot(facade, {**event, 'auto': True}, sid)
628
+ if snapshot['model'] != values.model or not snapshot['last_turn']:
629
+ raise ValueError('stale model or transcript')
630
+ matches = next((rec for rec in reversed(facade.load_keepwarm_records())
631
+ if rec.get('session_id') == sid and rec.get('byte_size') == snapshot['byte_size']
632
+ and rec.get('transcript_mtime') == snapshot['mtime']), None)
633
+ record = matches or {'session_id': sid, 'ts': now, 'owner': None,
634
+ 'byte_size': snapshot['byte_size'], 'transcript_mtime': snapshot['mtime'],
635
+ 'transcript_path': snapshot['path'], 'prefix_proxy': snapshot['prefix'],
636
+ 'model': snapshot['model'], 'ttl_kind': snapshot['ttl'],
637
+ 'last_turn_ts': snapshot['last_turn']}
638
+
639
+ def live():
640
+ return (_snapshot_still_usable(snapshot) and path.stat().st_size == snapshot['byte_size']
641
+ and not ended_since(facade.SNAPSHOT_DIR, sid, record['ts']))
642
+
643
+ result = fire_headless(facade, record, now=now, live=live,
644
+ meters=(values.five_hour_pct, values.week_pct))
645
+ except (OSError, ValueError, TypeError, KeyError):
646
+ result = {'fired': False, 'reason': 'snapshot-unavailable'}
647
+ print(json.dumps(result))
648
+ return 0
649
+
650
+
651
+ HOOK_PARENT_PID_ENV = 'TOKEN_OPTIMIZER_HOOK_PARENT_PID'
652
+
653
+
654
+ def stop_flush_args(facade, args, hook_input):
655
+ """Forward the hook payload and opt the existing worker into eligible arms."""
656
+ args = list(args)
657
+ sid, transcript = hook_input.get('session_id'), hook_input.get('transcript_path')
658
+ for flag, value in (('--session-id', sid), ('--transcript-path', transcript)):
659
+ if isinstance(value, str) and value and len(value) <= 4096 and '\x00' not in value:
660
+ args += [flag, value]
661
+ try:
662
+ now = time.time()
663
+ if (os.name != 'posix' or '--no-defer' in args or facade._remote_lean_profile()
664
+ or os.environ.get('TOKEN_OPTIMIZER_RUNTIME') != 'claude'
665
+ or 'agent_id' in hook_input or 'agent_type' in hook_input
666
+ or str(hook_input.get('hook_event_name', 'Stop')).lower() != 'stop'
667
+ or not facade._keepwarm_valid_arg(sid)
668
+ or '--transcript-path' not in args
669
+ or headless_disabled(facade) not in (None, 'headless-busy')):
670
+ return args
671
+ parent_pid = int(os.environ.get(HOOK_PARENT_PID_ENV, '0'))
672
+ path = Path(transcript)
673
+ if parent_pid <= 1 or 'subagents' in path.parts or not stat.S_ISREG(path.stat().st_mode):
674
+ return args
675
+ from .cold_guard import _bounded_last_usage
676
+ from .keepwarm_auto import MIN_CONTEXT
677
+
678
+ usage, _, _ = _bounded_last_usage(path)
679
+ if usage and facade._keepwarm_prefix_proxy(usage) >= MIN_CONTEXT:
680
+ parent_start = process_start(parent_pid)
681
+ if parent_start:
682
+ args += ['--keepwarm-parent-pid', str(parent_pid), '--keepwarm-parent-start', parent_start,
683
+ '--keepwarm-stop-at', str(now)]
684
+ except Exception:
685
+ pass
686
+ return args
687
+
688
+
689
+ def flush_hook_args(facade, args):
690
+ """Read a real hook's payload once, record session end, or forward the Stop owner."""
691
+ if facade.os.name != 'posix' or not facade.os.environ.get(HOOK_PARENT_PID_ENV):
692
+ return args
693
+ payload = facade._read_stdin_hook_input()
694
+ if str(payload.get('hook_event_name', '')).lower() == 'sessionend':
695
+ mark_ended(facade.SNAPSHOT_DIR, payload.get('session_id'))
696
+ elif args[1:3] == ['--trigger', 'stop']:
697
+ return stop_flush_args(facade, args, payload)
698
+ return args
699
+
700
+
701
+ def run_flush_worker(facade, args):
702
+ """Arm before the refresh throttle and watch after releasing the flush lock."""
703
+ record = None
704
+ try:
705
+ def value(flag):
706
+ return next(v for k, v in reversed(list(zip(args, args[1:]))) if k == flag)
707
+
708
+ if (os.name == 'posix' and '--keepwarm-parent-pid' in args
709
+ and value('--trigger') == 'stop' and not facade._remote_lean_profile()):
710
+ parent_pid = int(value('--keepwarm-parent-pid'))
711
+ parent_start = value('--keepwarm-parent-start')
712
+ if parent_pid > 1 and parent_start:
713
+ record = facade.write_keepwarm_arm_record(
714
+ value('--session-id'), value('--transcript-path'),
715
+ now=float(value('--keepwarm-stop-at')), parent_pid=parent_pid, parent_start=parent_start,
716
+ )
717
+ except Exception:
718
+ pass
719
+ facade._run_session_end_flush_worker(args)
720
+ if (record and not facade._daemon_snapshot_sandboxed() and record['ttl_kind'] == '1h'
721
+ and not headless_disabled(facade) and facade._is_priced_model(record['model'])):
722
+ try:
723
+ watch_armed_terminal(facade, record['session_id'])
724
+ except OSError:
725
+ pass
726
+
727
+
728
+ def watch_armed_terminal(facade, sid):
729
+ """Reuse the flush process, with one watcher per terminal session."""
730
+ import fcntl
731
+ filename = hashlib.sha256(sid.encode('utf-8')).hexdigest()
732
+ path = facade.SNAPSHOT_DIR / ('keepwarm-owner-watch-' + filename)
733
+ fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | getattr(os, 'O_NOFOLLOW', 0), 0o600)
734
+ try:
735
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
736
+ os.utime(fd)
737
+ except BaseException:
738
+ os.close(fd)
739
+ raise
740
+ watch_terminal(facade, sid, fd)
741
+
742
+
743
+ def watch_terminal(facade, sid, fd):
744
+ """Use current arm and meter evidence at the deadline, then yield at the caps."""
745
+ from . import keepwarm_auto as policy
746
+ if not facade._keepwarm_valid_arg(sid):
747
+ return 1
748
+ try:
749
+ os.fstat(fd)
750
+ while True:
751
+ now = facade.time.time()
752
+ disabled = headless_disabled(facade)
753
+ if disabled == 'headless-busy':
754
+ facade.time.sleep(5)
755
+ continue
756
+ if disabled:
757
+ return 0
758
+ records = [r for r in facade.load_keepwarm_records() if r.get('session_id') == sid and r.get('owner')]
759
+ if not records:
760
+ return 0
761
+ record = records[-1]
762
+ if not owner_alive(record['owner']) or ended_since(facade.SNAPSHOT_DIR, sid, record['ts']):
763
+ return 0
764
+ if now - record['last_turn_ts'] > policy.CACHE_LIFETIME * policy.MAX_PER_PAUSE:
765
+ return 0
766
+ if now - os.fstat(fd).st_mtime > policy.DAY:
767
+ os.utime(fd)
768
+ state = facade.classify_keepwarm_record(record, now=now)
769
+ if state != 'still_paused':
770
+ # A new turn is writing its transcript and will arm on Stop.
771
+ facade.time.sleep(30)
772
+ continue
773
+ rows = facade._keepwarm_load_ledger_rows()
774
+ decision = _headless_decision(facade, record, now, None, _headless_meters(facade, now), rows)
775
+ if decision['reason'] == 'not-due':
776
+ facade.time.sleep(min(60, max(1, decision['due_in_s'])))
777
+ continue
778
+ if decision['action'] != 'ping':
779
+ return 0
780
+ result = fire_headless(facade, record, now=now)
781
+ if not result.get('proof'):
782
+ return 0
783
+ finally:
784
+ os.close(fd)