@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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/module_runner.py +1 -1
- package/hooks/posttooluse_runner.py +7 -9
- package/hooks/run.py +5 -1
- package/hooks/stop_runner.py +15 -56
- package/hooks/userpromptsubmit_runner.py +29 -4
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +30 -14
- package/skills/token-optimizer/assets/savings_story.js +103 -27
- package/skills/token-optimizer/references/agent-prompts.md +2 -0
- package/skills/token-optimizer/references/implementation-playbook.md +1 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
- package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
- package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
- package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
- package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
- package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
- package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
- package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
- package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
- package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
- package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
- package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
- package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
- package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
- package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
- package/skills/token-optimizer/scripts/_measure/savings.py +75 -81
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
- package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
- package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
- package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
- package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
- package/skills/token-optimizer/scripts/archive_result.py +16 -28
- package/skills/token-optimizer/scripts/archive_verify.py +1 -1
- package/skills/token-optimizer/scripts/bash_compress.py +156 -176
- package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
- package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
- package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
- package/skills/token-optimizer/scripts/benchmark.py +11 -13
- package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
- package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
- package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
- package/skills/token-optimizer/scripts/compact_markers.py +129 -0
- package/skills/token-optimizer/scripts/copilot_install.py +3 -0
- package/skills/token-optimizer/scripts/cursor_install.py +7 -0
- package/skills/token-optimizer/scripts/devin_source.py +5 -5
- package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
- package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
- package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
- package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
- package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
- package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
- package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
- package/skills/token-optimizer/scripts/grok_install.py +3 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
- package/skills/token-optimizer/scripts/hermes_install.py +10 -1
- package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
- package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
- package/skills/token-optimizer/scripts/measure.py +10 -12
- package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
- package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
- package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
- package/skills/token-optimizer/scripts/process_identity.py +66 -0
- package/skills/token-optimizer/scripts/read_cache.py +51 -60
- package/skills/token-optimizer/scripts/statusline.js +21 -3
- package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
|
@@ -266,10 +266,60 @@ def _run(payload: dict) -> None:
|
|
|
266
266
|
_emit_updated_tool_output(stdout, stderr, nudge=_nudge)
|
|
267
267
|
return
|
|
268
268
|
|
|
269
|
+
# Explicit output-limit guard (head -n, tail -n, sed -n) + Step 3 cat re-read.
|
|
270
|
+
try:
|
|
271
|
+
from pipe_file_compress import (
|
|
272
|
+
FEATURE_BASH_REREAD, has_explicit_output_limit as _has_exp_lim,
|
|
273
|
+
hook_try_cat_reread as _try_cat,
|
|
274
|
+
)
|
|
275
|
+
if _has_exp_lim(command):
|
|
276
|
+
_cov("not_read_only", "explicit_limit", text=stdout)
|
|
277
|
+
if _nudge:
|
|
278
|
+
_emit_updated_tool_output(stdout, stderr, nudge=_nudge)
|
|
279
|
+
return
|
|
280
|
+
if "cat" in command:
|
|
281
|
+
_cat_sid = _dedup_store_id(
|
|
282
|
+
os.environ.get("CLAUDE_SESSION_ID", ""),
|
|
283
|
+
os.environ.get(_DEDUP_AGENT_ENV, _MAIN_AGENT_SENTINEL),
|
|
284
|
+
)
|
|
285
|
+
_is_cat, _cat_out = _try_cat(command, stdout, payload, _cat_sid, exit_code, stderr)
|
|
286
|
+
if _is_cat:
|
|
287
|
+
if _cat_out is not None:
|
|
288
|
+
try:
|
|
289
|
+
from emit_safety_gate import gate_or_none as _emit_gate_none
|
|
290
|
+
_cat_out = _emit_gate_none(
|
|
291
|
+
stdout, _cat_out, feature=FEATURE_BASH_REREAD,
|
|
292
|
+
tool_name="Bash", command=command, exit_code=exit_code,
|
|
293
|
+
require_expand=True,
|
|
294
|
+
)
|
|
295
|
+
except Exception:
|
|
296
|
+
_cat_out = None
|
|
297
|
+
if _cat_out is not None:
|
|
298
|
+
_log_event(command, stdout, _cat_out, feature=FEATURE_BASH_REREAD)
|
|
299
|
+
_cov("compressed", FEATURE_BASH_REREAD, "cat", stdout, _removed_tokens(stdout, _cat_out))
|
|
300
|
+
_emit_updated_tool_output(_cat_out, stderr, nudge=_nudge)
|
|
301
|
+
else:
|
|
302
|
+
_cov("not_read_only", "cat_file_read", text=stdout)
|
|
303
|
+
if _nudge:
|
|
304
|
+
_emit_updated_tool_output(stdout, stderr, nudge=_nudge)
|
|
305
|
+
return
|
|
306
|
+
# Never chop deliberate bare cat / cat-chain file reads even when cwd
|
|
307
|
+
# is unavailable or the file path cannot be resolved on disk.
|
|
308
|
+
from large_output_policy import is_deliberate_content_read as _is_delib_read
|
|
309
|
+
if _is_delib_read(command):
|
|
310
|
+
_cov("not_read_only", "deliberate_read", text=stdout)
|
|
311
|
+
if _nudge:
|
|
312
|
+
_emit_updated_tool_output(stdout, stderr, nudge=_nudge)
|
|
313
|
+
return
|
|
314
|
+
except Exception:
|
|
315
|
+
pass # Fail open
|
|
316
|
+
|
|
269
317
|
# A single renderer cannot safely separate output from multiple producers.
|
|
270
318
|
try:
|
|
271
319
|
from post_run_classify import unsafe_compound_output
|
|
272
320
|
if unsafe_compound_output(command):
|
|
321
|
+
if _try_large_output_policy(command, stdout, stderr, payload, _nudge, _cov, exit_code=exit_code):
|
|
322
|
+
return
|
|
273
323
|
_cov("not_read_only", "mixed_output", text=stdout)
|
|
274
324
|
if _nudge:
|
|
275
325
|
_emit_updated_tool_output(stdout, stderr, nudge=_nudge)
|
|
@@ -301,6 +351,23 @@ def _run(payload: dict) -> None:
|
|
|
301
351
|
except Exception:
|
|
302
352
|
pass # Fail open: the baseline path below runs unchanged
|
|
303
353
|
if not is_ro:
|
|
354
|
+
# Step 2: Safe read-only pipelines / harmless-prefix chains (pipe_compress).
|
|
355
|
+
_prc_env = os.environ.get("TOKEN_OPTIMIZER_POST_RUN_CLASSIFY", "").strip().lower()
|
|
356
|
+
if _prc_env not in ("0", "off", "false", "no", "shadow"):
|
|
357
|
+
try:
|
|
358
|
+
from pipe_file_compress import FEATURE_PIPE_COMPRESS, classify_safe_pipeline, hook_try_pipe_compress
|
|
359
|
+
_pipe_cls = classify_safe_pipeline(command)
|
|
360
|
+
_pipe_is_search = bool(_pipe_cls and _pipe_cls[1] == "search_results")
|
|
361
|
+
if _pipe_cls is not None and not _stdout_has_error_patterns(stdout, is_search=_pipe_is_search):
|
|
362
|
+
_pr = hook_try_pipe_compress(command, stdout, exit_code, stderr)
|
|
363
|
+
if _pr is not None:
|
|
364
|
+
_pipe_out, _clean_orig, _pipe_pat = _pr
|
|
365
|
+
_log_event(command, _clean_orig, _pipe_out, feature=FEATURE_PIPE_COMPRESS)
|
|
366
|
+
_cov("compressed", FEATURE_PIPE_COMPRESS, _pipe_pat, stdout, _removed_tokens(_clean_orig, _pipe_out))
|
|
367
|
+
_emit_updated_tool_output(_pipe_out, stderr, nudge=_nudge)
|
|
368
|
+
return
|
|
369
|
+
except Exception:
|
|
370
|
+
pass # Fail open: fall through to build/raw
|
|
304
371
|
# --- K1: build/test/run output compression (PostToolUse) ---
|
|
305
372
|
# The command is not read-only, so the standard compression path
|
|
306
373
|
# skips it. But build/test/run commands (gcc, pytest, cargo, npm,
|
|
@@ -336,6 +403,8 @@ def _run(payload: dict) -> None:
|
|
|
336
403
|
return
|
|
337
404
|
except Exception:
|
|
338
405
|
pass # Fail open: raw output stands
|
|
406
|
+
if _try_large_output_policy(command, stdout, stderr, payload, _nudge, _cov, exit_code=exit_code):
|
|
407
|
+
return
|
|
339
408
|
_cov("not_read_only", reason, text=stdout)
|
|
340
409
|
if _post_run_shadow is not None:
|
|
341
410
|
try:
|
|
@@ -371,6 +440,8 @@ def _run(payload: dict) -> None:
|
|
|
371
440
|
|
|
372
441
|
# --- check for failure (exit code or stderr patterns) ---
|
|
373
442
|
if _looks_like_failure(exit_code, stderr):
|
|
443
|
+
if _try_large_output_policy(command, stdout, stderr, payload, _nudge, _cov, exit_code=exit_code):
|
|
444
|
+
return
|
|
374
445
|
_cov("error_or_short", "failed_command", text=stdout)
|
|
375
446
|
if _nudge:
|
|
376
447
|
_emit_updated_tool_output(stdout, stderr, nudge=_nudge)
|
|
@@ -381,9 +452,12 @@ def _run(payload: dict) -> None:
|
|
|
381
452
|
|
|
382
453
|
# --- also scan stdout for error patterns ---
|
|
383
454
|
# When stderr is redirected to stdout (2>&1), error lines appear
|
|
384
|
-
# on stdout.
|
|
385
|
-
#
|
|
386
|
-
|
|
455
|
+
# on stdout. For search commands, structured file:line:content hits of
|
|
456
|
+
# literal "error" are ordinary search hits, not tool failures.
|
|
457
|
+
_is_search_cmd = _detect_pattern(compress_command) == "search_results"
|
|
458
|
+
if _stdout_has_error_patterns(cleaned_stdout, is_search=_is_search_cmd):
|
|
459
|
+
if _try_large_output_policy(command, stdout, stderr, payload, _nudge, _cov, exit_code=exit_code):
|
|
460
|
+
return
|
|
387
461
|
_cov("error_or_short", "error_words", text=stdout)
|
|
388
462
|
if _nudge:
|
|
389
463
|
_emit_updated_tool_output(stdout, stderr, nudge=_nudge)
|
|
@@ -400,70 +474,94 @@ def _run(payload: dict) -> None:
|
|
|
400
474
|
orig_tokens == 0 or (1.0 - _est(compressed) / orig_tokens) >= 0.10)
|
|
401
475
|
best = compressed if comp_helped else cleaned_stdout
|
|
402
476
|
|
|
403
|
-
# Cross-turn
|
|
404
|
-
# run, emit a compact delta reference instead. Catches repeats even when
|
|
405
|
-
# single-output compression did not help (a small repeated `git status`),
|
|
406
|
-
# which per-command tools cannot do -- they have no session memory.
|
|
407
|
-
deduped = _crossturn_dedup(command, best, str(payload.get("tool_use_id", "") or ""))
|
|
477
|
+
# Cross-turn / rerun dedupe removed per DECISION row 12.
|
|
408
478
|
_log_feature = "bash_compress_pipeline"
|
|
409
|
-
if
|
|
410
|
-
|
|
411
|
-
|
|
479
|
+
if comp_helped and "[Folded noisy matches:" in best:
|
|
480
|
+
_log_feature = "bash_search_noise_fold"
|
|
481
|
+
else:
|
|
482
|
+
try:
|
|
483
|
+
from command_compress_extra import feature_for_command as _extra_feat
|
|
484
|
+
_log_feature = _extra_feat(compress_command, cleaned_stdout) or "bash_compress_pipeline"
|
|
485
|
+
except Exception:
|
|
486
|
+
pass
|
|
412
487
|
|
|
413
488
|
if not comp_helped:
|
|
489
|
+
if _try_large_output_policy(command, stdout, stderr, payload, _nudge, _cov, exit_code=exit_code):
|
|
490
|
+
return
|
|
414
491
|
_cov("under_10pct", "read_only", _detect_pattern(command), stdout)
|
|
415
492
|
if _nudge:
|
|
416
493
|
_emit_updated_tool_output(stdout, stderr, nudge=_nudge)
|
|
417
494
|
return # nothing shrank the output -> pass through raw
|
|
418
495
|
compressed = best
|
|
419
496
|
|
|
497
|
+
# Enforce visibility rule (a)+(b)+(c): never hide critical lines and
|
|
498
|
+
# declare exact hidden count + line range before attaching the pointer.
|
|
499
|
+
try:
|
|
500
|
+
from visibility_rule import enforce_visibility_and_exact_hidden as _vis_guard
|
|
501
|
+
compressed = _vis_guard(
|
|
502
|
+
cleaned_stdout, compressed, is_search=_is_search_cmd,
|
|
503
|
+
skip_hidden_check=(_log_feature in ("cmd_git_diff_stat", "cmd_git_ls")),
|
|
504
|
+
)
|
|
505
|
+
except Exception:
|
|
506
|
+
pass
|
|
507
|
+
|
|
420
508
|
# --- archive raw stdout + attach a retrieval pointer ---
|
|
421
|
-
#
|
|
422
|
-
#
|
|
423
|
-
#
|
|
509
|
+
# Rule (d): every compressed output must have a verified archive entry
|
|
510
|
+
# and exact runnable expand command; if storage write fails or entry was
|
|
511
|
+
# pruned, return original stdout untouched.
|
|
424
512
|
_archive_key = None
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
compressed = build_archive_pointer(compressed, len(stdout), _archive_key)
|
|
439
|
-
else:
|
|
440
|
-
# Entry was pruned after write — serve raw, not lossy preview.
|
|
441
|
-
# This matches the guarantee in bash_compress.main().
|
|
442
|
-
compressed = stdout
|
|
443
|
-
_archive_key = None
|
|
444
|
-
else:
|
|
445
|
-
_archive_key = None
|
|
446
|
-
except Exception:
|
|
513
|
+
try:
|
|
514
|
+
from archive_result import (
|
|
515
|
+
archive_entry_exists,
|
|
516
|
+
archive_original,
|
|
517
|
+
build_archive_pointer,
|
|
518
|
+
)
|
|
519
|
+
_session_id = os.environ.get("CLAUDE_SESSION_ID", "")
|
|
520
|
+
_archive_key = hashlib.sha256(
|
|
521
|
+
f"{_session_id}|{command}|{stdout}".encode("utf-8", errors="replace")
|
|
522
|
+
).hexdigest()[:16]
|
|
523
|
+
if archive_original(stdout, _session_id, _archive_key, "Bash") is not None and archive_entry_exists(_session_id, _archive_key):
|
|
524
|
+
compressed = build_archive_pointer(compressed, len(stdout), _archive_key)
|
|
525
|
+
else:
|
|
447
526
|
_archive_key = None
|
|
527
|
+
except Exception:
|
|
528
|
+
_archive_key = None
|
|
448
529
|
|
|
449
|
-
|
|
450
|
-
# or when the archive write fails. Other handlers keep their contracts.
|
|
451
|
-
if _archive_key is None and _detect_pattern(compress_command) == "search_results":
|
|
530
|
+
if _archive_key is None:
|
|
452
531
|
compressed = stdout
|
|
453
532
|
|
|
454
533
|
# --- enforce the baseline-size invariant ---
|
|
455
534
|
# If our compressed preview + archive pointer would exceed what
|
|
456
|
-
# Claude Code would show as a baseline stub, shrink to fit.
|
|
535
|
+
# Claude Code would show as a baseline stub, shrink to fit or pass raw.
|
|
457
536
|
try:
|
|
458
537
|
compressed = _enforce_baseline_invariant(compressed, stdout, _archive_key)
|
|
459
538
|
except Exception:
|
|
460
539
|
pass
|
|
461
540
|
|
|
541
|
+
# Final pre-emit safety gate: verify (a) critical lines, (b) declared
|
|
542
|
+
# count/place, (c) working expand pointer; fail-closed to raw stdout.
|
|
543
|
+
if compressed != stdout:
|
|
544
|
+
try:
|
|
545
|
+
from emit_safety_gate import gate_or_raw as _emit_gate
|
|
546
|
+
compressed = _emit_gate(
|
|
547
|
+
stdout, compressed, feature=_log_feature,
|
|
548
|
+
tool_name="Bash", command=command, exit_code=exit_code,
|
|
549
|
+
require_expand=True,
|
|
550
|
+
)
|
|
551
|
+
except Exception:
|
|
552
|
+
compressed = stdout
|
|
553
|
+
|
|
554
|
+
# If archive failed or baseline guard fell back to raw stdout, do not
|
|
555
|
+
# emit updatedToolOutput or log a bogus compression event.
|
|
556
|
+
if compressed == stdout:
|
|
557
|
+
_cov("under_10pct", "read_only", _detect_pattern(command), stdout)
|
|
558
|
+
if _nudge:
|
|
559
|
+
_emit_updated_tool_output(stdout, stderr, nudge=_nudge)
|
|
560
|
+
return
|
|
561
|
+
|
|
462
562
|
# Log compression event to trends.db
|
|
463
563
|
_log_event(command, cleaned_stdout, compressed, feature=_log_feature)
|
|
464
|
-
_cov("compressed",
|
|
465
|
-
"crossturn_dedup" if _log_feature == "crossturn_dedup" else "read_only",
|
|
466
|
-
"crossturn_dedup" if _log_feature == "crossturn_dedup" else _detect_pattern(command),
|
|
564
|
+
_cov("compressed", "read_only", _detect_pattern(command),
|
|
467
565
|
stdout, _removed_tokens(cleaned_stdout, compressed))
|
|
468
566
|
|
|
469
567
|
# Emit updatedToolOutput to replace what Claude sees. The thrash nudge,
|
|
@@ -514,52 +612,44 @@ def _get_combined_error_re():
|
|
|
514
612
|
return _COMBINED_ERROR_RE
|
|
515
613
|
|
|
516
614
|
|
|
517
|
-
def _stdout_has_error_patterns(stdout: str) -> bool:
|
|
615
|
+
def _stdout_has_error_patterns(stdout: str, *, is_search: bool = False) -> bool:
|
|
518
616
|
"""Check stdout for error patterns (covers 2>&1 redirect case).
|
|
519
617
|
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
meaningful (>500 chars), so small outputs with coincidental
|
|
523
|
-
error-keyword lines are not blocked.
|
|
618
|
+
When ``is_search`` is True, structured ``file:line:content`` search matches
|
|
619
|
+
are skipped so grepping for literal ``error`` does not disable compression.
|
|
524
620
|
"""
|
|
525
621
|
if not stdout or len(stdout) < 500:
|
|
526
622
|
return False
|
|
527
623
|
try:
|
|
624
|
+
try:
|
|
625
|
+
from visibility_rule import is_search_match_line as _is_hit
|
|
626
|
+
except Exception:
|
|
627
|
+
_is_hit = None
|
|
528
628
|
combined = _get_combined_error_re()
|
|
629
|
+
lines = stdout.splitlines()
|
|
630
|
+
total_lines = len(lines)
|
|
631
|
+
threshold = total_lines * 0.10
|
|
632
|
+
match_count = 0
|
|
529
633
|
if not combined:
|
|
530
|
-
# Fallback: fall back to the old per-pattern loop if the
|
|
531
|
-
# combined regex could not be built.
|
|
532
634
|
from bash_compress import _ERROR_STDERR_PATTERNS
|
|
533
|
-
lines = stdout.splitlines()
|
|
534
|
-
match_count = 0
|
|
535
635
|
for line in lines:
|
|
636
|
+
if is_search and _is_hit is not None and _is_hit(line):
|
|
637
|
+
continue
|
|
536
638
|
for pat in _ERROR_STDERR_PATTERNS:
|
|
537
639
|
if pat.search(line):
|
|
538
640
|
match_count += 1
|
|
539
641
|
break
|
|
540
|
-
|
|
541
|
-
return True
|
|
542
|
-
return False
|
|
543
|
-
# C-3: single combined regex per line + early exit when the
|
|
544
|
-
# density threshold is met. O(lines × 1) instead of O(lines × 13).
|
|
545
|
-
lines = stdout.splitlines()
|
|
546
|
-
total_lines = len(lines)
|
|
547
|
-
threshold = total_lines * 0.10
|
|
548
|
-
match_count = 0
|
|
642
|
+
return match_count >= 3 and match_count > threshold
|
|
549
643
|
for line in lines:
|
|
644
|
+
if is_search and _is_hit is not None and _is_hit(line):
|
|
645
|
+
continue
|
|
550
646
|
if combined.search(line):
|
|
551
647
|
match_count += 1
|
|
552
|
-
# Early exit: once we have enough matches AND the density
|
|
553
|
-
# threshold is met, no need to scan the rest.
|
|
554
648
|
if match_count >= 3 and match_count > threshold:
|
|
555
649
|
return True
|
|
556
|
-
|
|
557
|
-
# the full scan meets the threshold.
|
|
558
|
-
if match_count >= 3 and match_count > threshold:
|
|
559
|
-
return True
|
|
650
|
+
return match_count >= 3 and match_count > threshold
|
|
560
651
|
except Exception:
|
|
561
652
|
return False
|
|
562
|
-
return False
|
|
563
653
|
|
|
564
654
|
|
|
565
655
|
def _dedup_store_id(session_id: str, agent_id: str) -> str:
|
|
@@ -584,108 +674,8 @@ def _dedup_store_id(session_id: str, agent_id: str) -> str:
|
|
|
584
674
|
|
|
585
675
|
|
|
586
676
|
def _crossturn_dedup(command: str, output: str, tool_use_id: str = ""):
|
|
587
|
-
"""
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
Per-command wrappers (e.g. Boost) compress each invocation in isolation and
|
|
591
|
-
so re-pay for every re-run of `git status`, `ls`, a test suite, etc. Token
|
|
592
|
-
Optimizer is a session-stateful hook, so it can collapse the repeat: the
|
|
593
|
-
identical case becomes a one-line note, a small change becomes just the diff.
|
|
594
|
-
Reuses the (previously dormant) command_outputs store + delta_diff. The
|
|
595
|
-
caller still attaches the progressive-disclosure pointer, so `expand`
|
|
596
|
-
recovers the full (credential-redacted) output even if the referenced run
|
|
597
|
-
has scrolled out of context -- the reference is self-sufficient, never a
|
|
598
|
-
dangling pointer.
|
|
599
|
-
Never raises (fail-open): any trouble returns None and normal output stands.
|
|
600
|
-
"""
|
|
601
|
-
try:
|
|
602
|
-
session_id = os.environ.get("CLAUDE_SESSION_ID", "")
|
|
603
|
-
if not session_id or len(output) < 200:
|
|
604
|
-
return None
|
|
605
|
-
from session_store import SessionStore
|
|
606
|
-
from delta_diff import content_hash, compute_delta
|
|
607
|
-
# Canonical source: credential_patterns.redact_credentials. Importing the
|
|
608
|
-
# private archive_result._redact_credentials wrapper coupled this hot path
|
|
609
|
-
# to archive_result's import side effects and its _TOKEN_PATTERNS fallback
|
|
610
|
-
# (which emits generic [REDACTED] labels). The shared module is the single
|
|
611
|
-
# owner of the labeled-placeholder redaction contract (L-1).
|
|
612
|
-
from credential_patterns import redact_credentials as _redact_credentials
|
|
613
|
-
|
|
614
|
-
agent_id = os.environ.get(_DEDUP_AGENT_ENV, _MAIN_AGENT_SENTINEL)
|
|
615
|
-
store = SessionStore(_dedup_store_id(session_id, agent_id))
|
|
616
|
-
try:
|
|
617
|
-
cmd_h = content_hash(command.strip())
|
|
618
|
-
out_h = content_hash(output) # identical-detection stays on raw bytes
|
|
619
|
-
# Redact before anything is persisted or diffed, mirroring the
|
|
620
|
-
# archive path (archive_result._redact_credentials), so a secret in
|
|
621
|
-
# command output never reaches the on-disk dedup store.
|
|
622
|
-
safe_output = _redact_credentials(output)
|
|
623
|
-
# The command itself can carry inline secrets (an auth header, a
|
|
624
|
-
# -pPASSWORD, a connection string). Redact BEFORE truncating so a
|
|
625
|
-
# secret split across the 500-char cutoff can't survive, matching the
|
|
626
|
-
# archive path which redacts the command too. cmd_h stays on the raw
|
|
627
|
-
# command -- the hash is non-reversible, like out_h.
|
|
628
|
-
safe_command = _redact_credentials(command, command=True)[:500]
|
|
629
|
-
prior = store.get_command_output(cmd_h)
|
|
630
|
-
# Record THIS run (redacted output) for the next comparison BEFORE we
|
|
631
|
-
# return a delta, so deltas always chain off full (redacted) outputs,
|
|
632
|
-
# not refs.
|
|
633
|
-
store.insert_command_output(
|
|
634
|
-
cmd_h, safe_command, out_h, len(output), safe_output,
|
|
635
|
-
tool_use_id=tool_use_id,
|
|
636
|
-
)
|
|
637
|
-
if not prior or not prior.get("compressed_output"):
|
|
638
|
-
return None
|
|
639
|
-
# Same tool_use_id = the SAME command seen by a second Token Optimizer
|
|
640
|
-
# install (e.g. a synced Cowork copy that predates the stand-down fix),
|
|
641
|
-
# not a re-run. Referencing it would say "identical to your previous
|
|
642
|
-
# output" about output the model has never seen.
|
|
643
|
-
if tool_use_id and prior.get("last_tool_use_id") == tool_use_id:
|
|
644
|
-
return None
|
|
645
|
-
# A pre-fix install writes no tool_use_id, so its twin row can only be
|
|
646
|
-
# recognised by shape: same bytes, written a moment ago. A genuine
|
|
647
|
-
# re-run this fast is rare, and missing one dedup costs nothing.
|
|
648
|
-
if (tool_use_id and not prior.get("last_tool_use_id")
|
|
649
|
-
and prior.get("output_hash") == out_h
|
|
650
|
-
and time.time() - float(prior.get("timestamp") or 0) < _LEGACY_TWIN_SECONDS):
|
|
651
|
-
return None
|
|
652
|
-
# Recency guard: only reference a run from the last hour, a rough
|
|
653
|
-
# proxy for "probably still in the agent's context".
|
|
654
|
-
if time.time() - float(prior.get("timestamp") or 0) > 3600:
|
|
655
|
-
return None
|
|
656
|
-
# C-1: the label is embedded in the ref string that becomes
|
|
657
|
-
# updatedToolOutput.stdout (the model sees it) AND is logged to
|
|
658
|
-
# trends.db as compressed_text via _log_event. Use the redacted
|
|
659
|
-
# command so an inline secret (Bearer token, -pPASSWORD, connection
|
|
660
|
-
# string) never reaches the model context or disk. safe_command is
|
|
661
|
-
# already computed above and in scope.
|
|
662
|
-
label = safe_command.strip()[:60]
|
|
663
|
-
if prior.get("output_hash") == out_h:
|
|
664
|
-
ref = (f"[Token Optimizer: identical to your previous `{label}` "
|
|
665
|
-
f"output this session; unchanged.]")
|
|
666
|
-
else:
|
|
667
|
-
delta, _stats = compute_delta(
|
|
668
|
-
prior["compressed_output"], safe_output, filename=label)
|
|
669
|
-
if not delta:
|
|
670
|
-
return None
|
|
671
|
-
ref = (f"[Token Optimizer: same as your previous `{label}` output "
|
|
672
|
-
f"this session, except:]\n{delta}")
|
|
673
|
-
return ref if len(ref) < len(output) * 0.85 else None
|
|
674
|
-
finally:
|
|
675
|
-
store.close()
|
|
676
|
-
except Exception as exc:
|
|
677
|
-
# M-15: log the exception type (not the message, which may contain
|
|
678
|
-
# unredacted text) so an admin can distinguish "no prior run" from
|
|
679
|
-
# "redaction failed" from logs. Fail-open: still return None.
|
|
680
|
-
try:
|
|
681
|
-
sys.stderr.write(
|
|
682
|
-
f"[Token Optimizer] crossturn dedup failed: "
|
|
683
|
-
f"{type(exc).__name__}\n"
|
|
684
|
-
)
|
|
685
|
-
sys.stderr.flush()
|
|
686
|
-
except (OSError, ValueError):
|
|
687
|
-
pass
|
|
688
|
-
return None
|
|
677
|
+
"""Removed per DECISION row 12 (rerun / cross-output dedupe cut)."""
|
|
678
|
+
return None
|
|
689
679
|
|
|
690
680
|
|
|
691
681
|
def _holdout_control() -> bool:
|
|
@@ -814,7 +804,7 @@ def _try_build_output_compress(command: str, stdout: str) -> str | None:
|
|
|
814
804
|
# returned None, or the entry was pruned after write), return None so
|
|
815
805
|
# the caller serves raw stdout. Never return a lossy preview with no
|
|
816
806
|
# archive pointer — the model would have no way to retrieve the original.
|
|
817
|
-
_archive_attempted =
|
|
807
|
+
_archive_attempted = True
|
|
818
808
|
_archive_key = None
|
|
819
809
|
if _archive_attempted:
|
|
820
810
|
try:
|
|
@@ -825,7 +815,7 @@ def _try_build_output_compress(command: str, stdout: str) -> str | None:
|
|
|
825
815
|
)
|
|
826
816
|
_session_id = os.environ.get("CLAUDE_SESSION_ID", "")
|
|
827
817
|
_key = hashlib.sha256(
|
|
828
|
-
f"{_session_id}|{command}|{
|
|
818
|
+
f"{_session_id}|{command}|{stdout}".encode("utf-8", errors="replace")
|
|
829
819
|
).hexdigest()[:16]
|
|
830
820
|
# _archive_key stays None until both archive write and
|
|
831
821
|
# existence check succeed, so any failure path (exception,
|
|
@@ -848,14 +838,68 @@ def _try_build_output_compress(command: str, stdout: str) -> str | None:
|
|
|
848
838
|
except Exception:
|
|
849
839
|
pass
|
|
850
840
|
|
|
851
|
-
# Log to trends.db with the
|
|
852
|
-
|
|
841
|
+
# Log to trends.db with the dedicated B2 feature when applicable, else build_output_compress
|
|
842
|
+
_feature = "build_output_compress"
|
|
843
|
+
try:
|
|
844
|
+
from command_compress_extra import feature_for_command as _extra_feat
|
|
845
|
+
_feature = _extra_feat(command, cleaned_stdout) or "build_output_compress"
|
|
846
|
+
except Exception:
|
|
847
|
+
pass
|
|
848
|
+
try:
|
|
849
|
+
from emit_safety_gate import gate_or_none as _emit_gate_none
|
|
850
|
+
compressed = _emit_gate_none(
|
|
851
|
+
stdout, compressed, feature=_feature,
|
|
852
|
+
tool_name="Bash", command=command, require_expand=True,
|
|
853
|
+
)
|
|
854
|
+
except Exception:
|
|
855
|
+
compressed = None
|
|
856
|
+
if compressed is None:
|
|
857
|
+
return None
|
|
858
|
+
_log_event(command, cleaned_stdout, compressed, feature=_feature)
|
|
853
859
|
|
|
854
860
|
return compressed
|
|
855
861
|
except Exception:
|
|
856
862
|
return None
|
|
857
863
|
|
|
858
864
|
|
|
865
|
+
def _try_large_output_policy(command: str, stdout: str, stderr: str,
|
|
866
|
+
payload: dict, nudge: str | None,
|
|
867
|
+
cov_fn, *, exit_code: int | None = None) -> bool:
|
|
868
|
+
"""Run large_output_policy after existing compressors (opt-in, default OFF).
|
|
869
|
+
|
|
870
|
+
When TOKEN_OPTIMIZER_LARGE_OUTPUT != '1', returns False immediately without
|
|
871
|
+
importing or inspecting stdout. When enabled ('1'), archives first, passes
|
|
872
|
+
through the shared emit safety verifier (with exit_code), logs measured
|
|
873
|
+
savings under large_output_policy, and emits updatedToolOutput.
|
|
874
|
+
"""
|
|
875
|
+
if os.environ.get("TOKEN_OPTIMIZER_LARGE_OUTPUT", "").strip() != "1":
|
|
876
|
+
return False
|
|
877
|
+
if not stdout or len(stdout.encode("utf-8", errors="replace")) < 16384:
|
|
878
|
+
return False
|
|
879
|
+
try:
|
|
880
|
+
from large_output_policy import FEATURE_NAME, handle_post_tool_use
|
|
881
|
+
_tr = payload.get("tool_response") if isinstance(payload, dict) else {}
|
|
882
|
+
_interrupted = bool(_tr.get("interrupted", False)) if isinstance(_tr, dict) else False
|
|
883
|
+
compressed, cleaned_orig = handle_post_tool_use(
|
|
884
|
+
command,
|
|
885
|
+
stdout,
|
|
886
|
+
session_id=os.environ.get("CLAUDE_SESSION_ID", ""),
|
|
887
|
+
tool_use_id=str(payload.get("tool_use_id", "") or ""),
|
|
888
|
+
exit_code=exit_code,
|
|
889
|
+
stderr=stderr,
|
|
890
|
+
interrupted=_interrupted,
|
|
891
|
+
)
|
|
892
|
+
if compressed is None:
|
|
893
|
+
return False
|
|
894
|
+
_log_event(command, cleaned_orig, compressed, feature=FEATURE_NAME)
|
|
895
|
+
cov_fn("compressed", FEATURE_NAME, FEATURE_NAME, stdout,
|
|
896
|
+
_removed_tokens(cleaned_orig, compressed))
|
|
897
|
+
_emit_updated_tool_output(compressed, stderr, nudge=nudge)
|
|
898
|
+
return True
|
|
899
|
+
except Exception:
|
|
900
|
+
return False
|
|
901
|
+
|
|
902
|
+
|
|
859
903
|
def _emit_updated_tool_output(stdout: str, stderr: str,
|
|
860
904
|
nudge: str | None = None) -> None:
|
|
861
905
|
"""Emit the PostToolUse updatedToolOutput envelope, with an optional nudge
|