letitloop 0.2.0__py3-none-any.whl

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 (175) hide show
  1. letitloop-0.2.0.dist-info/METADATA +232 -0
  2. letitloop-0.2.0.dist-info/RECORD +175 -0
  3. letitloop-0.2.0.dist-info/WHEEL +5 -0
  4. letitloop-0.2.0.dist-info/entry_points.txt +4 -0
  5. letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
  6. letitloop-0.2.0.dist-info/top_level.txt +1 -0
  7. orchestrator/SKILL.md +292 -0
  8. orchestrator/__init__.py +151 -0
  9. orchestrator/anti_ouroboros.py +78 -0
  10. orchestrator/approval.py +139 -0
  11. orchestrator/ast_node_splicer.py +130 -0
  12. orchestrator/ast_splicer.py +94 -0
  13. orchestrator/audit.py +88 -0
  14. orchestrator/budget.py +195 -0
  15. orchestrator/checkpoint.py +248 -0
  16. orchestrator/cli.py +1971 -0
  17. orchestrator/codebase_introspector.py +66 -0
  18. orchestrator/component_slicer.py +185 -0
  19. orchestrator/config.py +152 -0
  20. orchestrator/contract.py +404 -0
  21. orchestrator/dag_validator.py +172 -0
  22. orchestrator/elasticity_governor.py +80 -0
  23. orchestrator/env_doctor.py +166 -0
  24. orchestrator/errors.py +211 -0
  25. orchestrator/events.py +120 -0
  26. orchestrator/evidence.py +203 -0
  27. orchestrator/exceptions.py +37 -0
  28. orchestrator/experimental/arena_arbiter.py +260 -0
  29. orchestrator/experimental/fuzz_engine.py +206 -0
  30. orchestrator/experimental/mutation_tester.py +382 -0
  31. orchestrator/failure.py +226 -0
  32. orchestrator/fast_sandbox.py +126 -0
  33. orchestrator/feasibility_gate.py +115 -0
  34. orchestrator/feedback.py +302 -0
  35. orchestrator/fixtures/__init__.py +0 -0
  36. orchestrator/fixtures/example_contract.json +50 -0
  37. orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
  38. orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
  39. orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
  40. orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
  41. orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
  42. orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
  43. orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
  44. orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
  45. orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
  46. orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
  47. orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
  48. orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
  49. orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
  50. orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
  51. orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
  52. orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
  53. orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
  54. orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
  55. orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
  56. orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
  57. orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
  58. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
  59. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
  60. orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
  61. orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
  62. orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
  63. orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
  64. orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
  65. orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
  66. orchestrator/fixtures/generated/perf-step-1.json +61 -0
  67. orchestrator/fixtures/generated/perf-step-2.json +62 -0
  68. orchestrator/fixtures/generated/perf-step-3.json +62 -0
  69. orchestrator/fixtures/generated/perf-step-4.json +62 -0
  70. orchestrator/fixtures/generated/perf-step-5.json +63 -0
  71. orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
  72. orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
  73. orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
  74. orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
  75. orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
  76. orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
  77. orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
  78. orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
  79. orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
  80. orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
  81. orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
  82. orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
  83. orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
  84. orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
  85. orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
  86. orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
  87. orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
  88. orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
  89. orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
  90. orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
  91. orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
  92. orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
  93. orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
  94. orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
  95. orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
  96. orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
  97. orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
  98. orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
  99. orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
  100. orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
  101. orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
  102. orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
  103. orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
  104. orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
  105. orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
  106. orchestrator/fixtures/run_proofs.py +299 -0
  107. orchestrator/fixtures/test_normalizer.py +16 -0
  108. orchestrator/generator.py +239 -0
  109. orchestrator/goal.py +245 -0
  110. orchestrator/handoff.py +86 -0
  111. orchestrator/hybrid_worker.py +840 -0
  112. orchestrator/impossibility.py +162 -0
  113. orchestrator/limits.py +60 -0
  114. orchestrator/live_evolution_engine.py +247 -0
  115. orchestrator/llm.py +291 -0
  116. orchestrator/local_tool_calling.py +285 -0
  117. orchestrator/lock.py +404 -0
  118. orchestrator/mcp_client.py +571 -0
  119. orchestrator/mcp_server.py +344 -0
  120. orchestrator/memory_bridge.py +182 -0
  121. orchestrator/metrics.py +159 -0
  122. orchestrator/micro_epoch.py +42 -0
  123. orchestrator/models.py +350 -0
  124. orchestrator/parsing.py +237 -0
  125. orchestrator/patch_applier.py +154 -0
  126. orchestrator/plan_preview.py +138 -0
  127. orchestrator/plan_quality.py +357 -0
  128. orchestrator/planner.py +532 -0
  129. orchestrator/preferences.py +115 -0
  130. orchestrator/preflight.py +141 -0
  131. orchestrator/process_guard.py +357 -0
  132. orchestrator/prometheus_exporter.py +207 -0
  133. orchestrator/prompts.py +275 -0
  134. orchestrator/proposal_ledger.py +194 -0
  135. orchestrator/provenance.py +263 -0
  136. orchestrator/provider_scheduler.py +394 -0
  137. orchestrator/qc/__init__.py +153 -0
  138. orchestrator/qc/aggregator.py +330 -0
  139. orchestrator/qc/parsing.py +287 -0
  140. orchestrator/qc/personas.py +242 -0
  141. orchestrator/qc/runner.py +569 -0
  142. orchestrator/qc_overrule.py +87 -0
  143. orchestrator/qc_review.py +282 -0
  144. orchestrator/quality_lenses.py +314 -0
  145. orchestrator/quality_plan.py +449 -0
  146. orchestrator/quality_plane.py +103 -0
  147. orchestrator/reconcile.py +191 -0
  148. orchestrator/replanner.py +433 -0
  149. orchestrator/research.py +176 -0
  150. orchestrator/review_artifact.py +672 -0
  151. orchestrator/safety.py +271 -0
  152. orchestrator/schemas.py +230 -0
  153. orchestrator/scope.py +466 -0
  154. orchestrator/sensory_radar.py +79 -0
  155. orchestrator/skill_installer.py +140 -0
  156. orchestrator/sse_server.py +160 -0
  157. orchestrator/state.py +871 -0
  158. orchestrator/subprocess_helper.py +131 -0
  159. orchestrator/supervisor/__init__.py +184 -0
  160. orchestrator/supervisor/_shared.py +164 -0
  161. orchestrator/supervisor/cleanup.py +185 -0
  162. orchestrator/supervisor/core.py +1680 -0
  163. orchestrator/supervisor/recovery.py +367 -0
  164. orchestrator/supervisor/reporting.py +251 -0
  165. orchestrator/surgical_extractor.py +119 -0
  166. orchestrator/telemetry.py +61 -0
  167. orchestrator/templates.py +268 -0
  168. orchestrator/token_gate.py +245 -0
  169. orchestrator/tui.py +649 -0
  170. orchestrator/verifier.py +1103 -0
  171. orchestrator/webhooks.py +168 -0
  172. orchestrator/worker.py +469 -0
  173. orchestrator/worker_adapters.py +815 -0
  174. orchestrator/worker_pool.py +121 -0
  175. orchestrator/worktree.py +364 -0
@@ -0,0 +1,245 @@
1
+ """token_gate.py — hard per-call token ceiling guard.
2
+
3
+ User directive: NO single LLM API call may exceed ``HARD_CAP_TOTAL`` tokens
4
+ (prompt + completion). Passing the cap is a HARD STOP:
5
+
6
+ - pre-flight: refuse to dispatch (exit code 3) BEFORE any bytes leave
7
+ - in-flight: abort the response stream the moment the estimate passes
8
+ - authoritative: if the API reports actual usage.total_tokens > cap, the
9
+ call is recorded as a violation even after completion
10
+
11
+ Every hard stop appends a record to the violation ledger
12
+ (``scratch/token_gate_violations.jsonl`` by default; override with the
13
+ ``TOKEN_GATE_LEDGER`` env var).
14
+
15
+ Shared by Python (import) and JS (CLI subcommand).
16
+
17
+ Usage:
18
+ from orchestrator.token_gate import preflight, TokenGateError, record_violation
19
+ python -m orchestrator.token_gate check --chars 400000 --max-tokens 200000 --caller foo
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import math
26
+ import os
27
+ import sys
28
+ import time
29
+ from datetime import datetime, timezone
30
+ from pathlib import Path
31
+
32
+ HARD_CAP_TOTAL = 1_000_000 # tokens per single call (prompt + completion)
33
+ CHARS_PER_TOKEN = 3 # conservative estimate: fewer chars per token -> earlier refusal
34
+ EXIT_GATE = 3
35
+
36
+ DEFAULT_LEDGER = Path(os.environ.get("TOKEN_GATE_LEDGER", str(Path.cwd() / "scratch" / "token_gate_violations.jsonl")))
37
+ MODELS_CACHE = Path(os.environ.get("TOKEN_GATE_MODELS_CACHE", str(Path.cwd() / "scratch" / "llm_models.json")))
38
+ MODELS_CACHE_TTL_SEC = 24 * 3600
39
+
40
+
41
+ class TokenGateError(RuntimeError):
42
+ """Raised pre-flight when a call would exceed the hard cap."""
43
+
44
+
45
+ def approx_tokens(chars: int) -> int:
46
+ """Conservative token estimate: chars / CHARS_PER_TOKEN, minimum 1."""
47
+ return max(1, math.ceil(chars / CHARS_PER_TOKEN))
48
+
49
+
50
+ def _lock_file() -> object:
51
+ if sys.platform == "win32":
52
+ import msvcrt
53
+
54
+ return msvcrt
55
+ import fcntl
56
+
57
+ return fcntl
58
+
59
+
60
+ def record_violation(
61
+ *,
62
+ caller: str,
63
+ kind: str,
64
+ est_prompt_tokens: int,
65
+ max_tokens: int | None = None,
66
+ est_completion_tokens: int | None = None,
67
+ actual_usage: dict | None = None,
68
+ model: str | None = None,
69
+ reason: str,
70
+ ) -> None:
71
+ """Append a JSONL violation record to the ledger (serialized via lock file)."""
72
+ entry = {
73
+ "ts": datetime.now(timezone.utc).isoformat(),
74
+ "caller": caller,
75
+ "kind": kind,
76
+ "reason": reason,
77
+ "model": model,
78
+ "est_prompt_tokens": est_prompt_tokens,
79
+ "max_tokens": max_tokens,
80
+ "est_completion_tokens": est_completion_tokens,
81
+ "actual_usage": actual_usage,
82
+ "cap": HARD_CAP_TOTAL,
83
+ }
84
+ try:
85
+ DEFAULT_LEDGER.parent.mkdir(parents=True, exist_ok=True)
86
+ lock = DEFAULT_LEDGER.with_suffix(".lock")
87
+ handle = open(lock, "a+", encoding="utf-8")
88
+ try:
89
+ _lock_file().lockf(handle, _lock_file().LOCK_EX)
90
+ with open(DEFAULT_LEDGER, "a", encoding="utf-8") as f:
91
+ f.write(json.dumps(entry) + "\n")
92
+ _lock_file().lockf(handle, _lock_file().LOCK_UN)
93
+ finally:
94
+ handle.close()
95
+ except (OSError, ImportError, ValueError, AttributeError):
96
+ # Ledger write must never crash the caller; the gate itself already stopped the call.
97
+ pass
98
+
99
+
100
+ def preflight(prompt_chars: int, max_tokens: int | None = None, caller: str = "unknown") -> None:
101
+ """Refuse the dispatch if prompt + requested max_tokens exceed the cap.
102
+
103
+ Raises TokenGateError (callers should exit EXIT_GATE). A violation record
104
+ is written before raising.
105
+ """
106
+ est_prompt = approx_tokens(prompt_chars)
107
+ total = est_prompt + (max_tokens or 0)
108
+ if total > HARD_CAP_TOTAL:
109
+ record_violation(
110
+ caller=caller,
111
+ kind="preflight_refused",
112
+ est_prompt_tokens=est_prompt,
113
+ max_tokens=max_tokens,
114
+ reason=f"est_prompt({est_prompt}) + max_tokens({max_tokens}) = {total} > {HARD_CAP_TOTAL}",
115
+ )
116
+ raise TokenGateError(
117
+ f"TOKEN GATE: pre-flight refusal. est_prompt={est_prompt} "
118
+ f"+ max_tokens={max_tokens} = {total} > cap {HARD_CAP_TOTAL}. "
119
+ f"Split the payload. (caller={caller})"
120
+ )
121
+
122
+
123
+ class StreamGuard:
124
+ """In-flight completion counter. Abort the stream once the cap is passed."""
125
+
126
+ def __init__(self, prompt_chars: int, caller: str = "unknown", model: str | None = None):
127
+ self.est_prompt = approx_tokens(prompt_chars)
128
+ self.completion_chars = 0
129
+ self.caller = caller
130
+ self.model = model
131
+
132
+ def add(self, text: str) -> None:
133
+ self.completion_chars += len(text or "")
134
+
135
+ @property
136
+ def est_completion(self) -> int:
137
+ return approx_tokens(self.completion_chars)
138
+
139
+ @property
140
+ def est_total(self) -> int:
141
+ return self.est_prompt + self.est_completion
142
+
143
+ @property
144
+ def exceeded(self) -> bool:
145
+ return self.est_total > HARD_CAP_TOTAL
146
+
147
+ def report(self, actual_usage: dict | None = None) -> None:
148
+ record_violation(
149
+ caller=self.caller,
150
+ kind="stream_aborted",
151
+ est_prompt_tokens=self.est_prompt,
152
+ est_completion_tokens=self.est_completion,
153
+ actual_usage=actual_usage,
154
+ model=self.model,
155
+ reason=f"est_prompt({self.est_prompt}) + est_completion({self.est_completion}) "
156
+ f"= {self.est_total} > cap {HARD_CAP_TOTAL}",
157
+ )
158
+
159
+
160
+ def check_usage_authoritative(usage: dict, est_prompt: int, caller: str = "unknown", model: str | None = None) -> bool:
161
+ """Post-check: the API's own reported total over the cap -> violation record.
162
+
163
+ Returns True when the call is over the cap (caller should treat it as a hard stop).
164
+ """
165
+ total = usage.get("total_tokens")
166
+ if total is not None and int(total) > HARD_CAP_TOTAL:
167
+ record_violation(
168
+ caller=caller,
169
+ kind="usage_over_cap",
170
+ est_prompt_tokens=est_prompt,
171
+ actual_usage=usage,
172
+ model=model,
173
+ reason=f"provider-reported total_tokens={total} > cap {HARD_CAP_TOTAL}",
174
+ )
175
+ return True
176
+ return False
177
+
178
+
179
+ def _cached_models(refresh: bool = False) -> list[str]:
180
+ """Live model IDs from the provider, cached for MODELS_CACHE_TTL_SEC."""
181
+ if not refresh and MODELS_CACHE.exists():
182
+ try:
183
+ stale = time.time() - MODELS_CACHE.stat().st_mtime > MODELS_CACHE_TTL_SEC
184
+ if not stale:
185
+ data = json.loads(MODELS_CACHE.read_text(encoding="utf-8"))
186
+ return list(data)
187
+ except (json.JSONDecodeError, OSError, UnicodeDecodeError):
188
+ pass
189
+ return []
190
+
191
+
192
+ def check_model_available(model: str) -> bool:
193
+ """Capability preflight: refuse dispatch to a model the provider does not serve.
194
+
195
+ Consults the cached /v1/models snapshot (``scratch/llm_models.json``), fetched
196
+ by the JS dispatchers on a TTL. Unknown model -> False.
197
+ """
198
+ if not model:
199
+ return False
200
+ live = _cached_models()
201
+ if not live:
202
+ return True # no cache: allow (dispatcher refreshes on next run); preflight is advisory
203
+ return model in live
204
+
205
+
206
+ def main(argv: list[str] | None = None) -> int:
207
+ args = list(argv if argv is not None else sys.argv[1:])
208
+ if not args:
209
+ print(__doc__)
210
+ return 1
211
+ if args[0] == "check":
212
+
213
+ def _val(flag: str) -> int | None:
214
+ for i, a in enumerate(args):
215
+ if a == flag and i + 1 < len(args):
216
+ try:
217
+ return int(args[i + 1])
218
+ except ValueError:
219
+ return None
220
+ return None
221
+
222
+ chars = _val("--chars")
223
+ max_tokens = _val("--max-tokens")
224
+ caller = "cli"
225
+ for i, a in enumerate(args):
226
+ if a == "--caller" and i + 1 < len(args):
227
+ caller = args[i + 1]
228
+ if chars is None:
229
+ print("check requires --chars N [--max-tokens M] [--caller NAME]", file=sys.stderr)
230
+ return 1
231
+ try:
232
+ preflight(chars, max_tokens=max_tokens, caller=caller)
233
+ est = approx_tokens(chars)
234
+ total = est + (max_tokens or 0)
235
+ print(f"TOKEN GATE: OK est_prompt={est} total={total} cap={HARD_CAP_TOTAL}")
236
+ return 0
237
+ except TokenGateError as e:
238
+ print(str(e), file=sys.stderr)
239
+ return EXIT_GATE
240
+ print(f"unknown subcommand: {args[0]}", file=sys.stderr)
241
+ return 1
242
+
243
+
244
+ if __name__ == "__main__":
245
+ sys.exit(main())