@giamme/forge 0.12.0 → 0.13.0
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/CHANGELOG.md +77 -0
- package/README.md +1 -1
- package/SKILL.md +31 -12
- package/VERSION +1 -1
- package/docs/add-ons.md +11 -6
- package/docs/artifacts.md +18 -6
- package/docs/commands.md +189 -17
- package/docs/decomposed-runs.md +13 -5
- package/docs/forge-ui.md +34 -4
- package/docs/memory.md +2 -1
- package/docs/models.md +4 -2
- package/docs/reviews.md +81 -19
- package/docs/troubleshooting.md +3 -1
- package/forge +17 -1
- package/package.json +1 -1
- package/references/dataset.md +40 -14
- package/references/decision-models.md +759 -0
- package/references/decompose.md +197 -28
- package/references/harnesses.md +10 -3
- package/references/planning.md +8 -0
- package/references/solo.md +13 -3
- package/references/ui.md +11 -0
- package/scripts/forge-artifact.sh +30 -4
- package/scripts/forge-config.py +238 -29
- package/scripts/forge-contract.py +127 -58
- package/scripts/forge-control.py +40 -9
- package/scripts/forge-decide.py +6 -0
- package/scripts/forge-dispatch.sh +47 -15
- package/scripts/forge-fail-first.py +2 -2
- package/scripts/forge-gate-addressed.sh +40 -0
- package/scripts/forge-gate-message.sh +64 -0
- package/scripts/forge-issues.py +368 -36
- package/scripts/forge-jev-options.sh +269 -42
- package/scripts/forge-lib-attribute.sh +447 -0
- package/scripts/forge-lib-gates.sh +32 -0
- package/scripts/forge-lib-plans.sh +17 -6
- package/scripts/forge-lib-review.sh +24 -19
- package/scripts/forge-lib-task.sh +219 -39
- package/scripts/forge-lib-verify.sh +45 -8
- package/scripts/forge-memory.sh +3 -3
- package/scripts/forge-parallel-options.sh +44 -5
- package/scripts/forge-parallel.sh +503 -304
- package/scripts/forge-plan-check.py +35 -1
- package/scripts/forge-pre-review.py +437 -0
- package/scripts/forge-prompt.py +25 -5
- package/scripts/forge-route.py +2 -2
- package/scripts/forge-runtime.py +55 -1
- package/scripts/forge-schedule.py +70 -9
- package/scripts/forge-shadow.py +2 -2
- package/scripts/forge-solo.sh +41 -10
- package/scripts/forge-submodules.py +389 -0
- package/scripts/forge-sweep.py +542 -0
- package/scripts/forge_dataset/cli.py +12 -6
- package/scripts/forge_dataset/export.py +55 -45
- package/scripts/forge_dataset/forecast.py +4 -1
- package/scripts/forge_dataset/harvest.py +33 -5
- package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
- package/scripts/forge_decide/__init__.py +141 -0
- package/scripts/forge_decide/budget.py +149 -0
- package/scripts/forge_decide/cache.py +66 -0
- package/scripts/forge_decide/cli.py +953 -0
- package/scripts/forge_decide/doctor.py +221 -0
- package/scripts/forge_decide/label_addressed.py +75 -0
- package/scripts/forge_decide/label_attribution.py +62 -0
- package/scripts/forge_decide/label_coverage.py +81 -0
- package/scripts/forge_decide/label_message.py +38 -0
- package/scripts/forge_decide/label_prompt.py +139 -0
- package/scripts/forge_decide/labels.py +328 -0
- package/scripts/forge_decide/metrics.py +125 -0
- package/scripts/forge_decide/migrate.py +226 -0
- package/scripts/forge_decide/providers.py +292 -0
- package/scripts/forge_decide/replay.py +350 -0
- package/scripts/forge_decide/report.py +382 -0
- package/scripts/forge_decide/resolve.py +397 -0
- package/scripts/forge_decide/sites.py +377 -0
- package/scripts/forge_jev/__init__.py +202 -104
- package/scripts/forge_jev/addressed.py +171 -0
- package/scripts/forge_jev/attribution.py +198 -0
- package/scripts/forge_jev/cli.py +460 -382
- package/scripts/forge_jev/client.py +155 -77
- package/scripts/forge_jev/coupling.py +19 -87
- package/scripts/forge_jev/coverage.py +303 -0
- package/scripts/forge_jev/findings.py +219 -0
- package/scripts/forge_jev/gates.py +225 -27
- package/scripts/forge_jev/memory.py +65 -4
- package/scripts/forge_jev/message.py +134 -0
- package/scripts/forge_jev/plan_gates.py +294 -0
- package/scripts/forge_jev/questions.py +173 -313
- package/scripts/forge_jev/verify.py +130 -104
- package/ui/README.md +41 -10
- package/ui/docs/api.md +212 -44
- package/ui/forge_ui/checks.py +331 -0
- package/ui/forge_ui/control.py +60 -11
- package/ui/forge_ui/export.py +8 -3
- package/ui/forge_ui/models.py +1 -0
- package/ui/forge_ui/reader.py +436 -26
- package/ui/forge_ui/server.py +13 -0
- package/ui/forge_ui/static/app.js +15 -8
- package/ui/forge_ui/static/checksview.js +449 -0
- package/ui/forge_ui/static/controls.js +20 -13
- package/ui/forge_ui/static/convo.js +11 -2
- package/ui/forge_ui/static/findingsview.js +6 -4
- package/ui/forge_ui/static/index.html +1 -0
- package/ui/forge_ui/static/panel.js +105 -17
- package/ui/forge_ui/static/runmodel.js +40 -2
- package/ui/forge_ui/static/scene3d.js +2 -15
- package/ui/forge_ui/static/settings.js +336 -41
- package/ui/forge_ui/static/style.css +72 -7
- package/ui/forge_ui/transcripts.py +225 -54
- package/references/jev.md +0 -865
- package/scripts/forge_jev/backtest.py +0 -322
- package/scripts/forge_jev/corpus.py +0 -156
- package/scripts/forge_jev/features.py +0 -24
- package/scripts/forge_jev/predict.py +0 -204
- package/scripts/forge_jev/review.py +0 -73
- package/scripts/forge_jev/routing.py +0 -271
- package/scripts/forge_jev/subset.py +0 -123
|
@@ -32,12 +32,9 @@ import time
|
|
|
32
32
|
from collections import Counter, defaultdict
|
|
33
33
|
from pathlib import Path
|
|
34
34
|
|
|
35
|
-
from forge_jev import outcome
|
|
36
|
-
from forge_jev.features import task_size
|
|
37
|
-
from forge_jev.questions import first_pass, retry_pass # noqa: F401 shared with live forge
|
|
38
|
-
|
|
39
35
|
from . import SKILL, connect, data_home, read_blob
|
|
40
36
|
from .harvest import review_completeness
|
|
37
|
+
from .states import assemble, retry, siblings, task_size
|
|
41
38
|
|
|
42
39
|
SLICES = ('routing', 'retry', 'review', 'drift', 'citation', 'memory')
|
|
43
40
|
|
|
@@ -150,6 +147,37 @@ def declared_tier() -> dict:
|
|
|
150
147
|
'or state/concurrency, or the right approach is not obvious from the goal.'})
|
|
151
148
|
|
|
152
149
|
|
|
150
|
+
# Frozen: these strings are part of every exported routing and retry case.
|
|
151
|
+
|
|
152
|
+
def first_pass() -> dict:
|
|
153
|
+
return dict(type='noul', instructions=(
|
|
154
|
+
'This Forge task is dispatched to the model in state.dwarf, at the effort shown, in its '
|
|
155
|
+
'own worktree. An independent model (state.reviewer) then reviews the resulting diff '
|
|
156
|
+
'against the task. Will that FIRST attempt pass review, with no retry needed?'),
|
|
157
|
+
criteria={
|
|
158
|
+
'true': 'The task is within reach of this model at this effort on the first try: the '
|
|
159
|
+
'requirements are clear, the change is contained, and nothing in it is likely '
|
|
160
|
+
'to be missed or subtly wrong.',
|
|
161
|
+
'false': 'The first attempt is likely to fail review: the task has edge cases, '
|
|
162
|
+
'cross-cutting effects, unclear requirements or subtle state that a first '
|
|
163
|
+
'attempt by this model at this effort typically gets wrong, so a retry would '
|
|
164
|
+
'be needed.'})
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def retry_pass() -> dict:
|
|
168
|
+
return dict(type='noul', instructions=(
|
|
169
|
+
'An earlier attempt at this Forge task failed review. The task is now dispatched again, to '
|
|
170
|
+
'the model in state.dwarf at the effort shown, with that review\'s findings '
|
|
171
|
+
'(state.previous_review) to fix; state.attempt is which try this is, and the model in '
|
|
172
|
+
'state.reviewer reviews the result. Will this attempt pass review?'),
|
|
173
|
+
criteria={
|
|
174
|
+
'true': 'The findings are specific and fixable, and this model at this effort can address '
|
|
175
|
+
'them without breaking something else: the retry is likely to pass.',
|
|
176
|
+
'false': 'The findings point at a design problem, an unclear requirement or a recurring '
|
|
177
|
+
'mistake that another attempt by this model at this effort is likely to repeat: '
|
|
178
|
+
'the retry is likely to fail again and should be escalated or rethought.'})
|
|
179
|
+
|
|
180
|
+
|
|
153
181
|
def review_passes() -> dict:
|
|
154
182
|
return dict(type='noul', instructions=(
|
|
155
183
|
'A diff is about to be reviewed for correctness by an independent model that did not '
|
|
@@ -233,20 +261,6 @@ class Runs:
|
|
|
233
261
|
held = self.survival.get(d['reviewed'])
|
|
234
262
|
if held is None or d['horizon_days'] > held['horizon_days']:
|
|
235
263
|
self.survival[d['reviewed']] = d
|
|
236
|
-
# Live Clef predictions (forge_jev/predict.py), recorded before the attempt they are
|
|
237
|
-
# about: {(run, task, attempt): [(ts, p, model, assignment)]}, oldest first.
|
|
238
|
-
self.clef = defaultdict(list)
|
|
239
|
-
for e in sorted(store.of('jev'), key=lambda e: e['ts']):
|
|
240
|
-
d = e['d']
|
|
241
|
-
site = d.get('site')
|
|
242
|
-
if site not in ('clef-first-pass', 'clef-retry-pass') or not d.get('ok'):
|
|
243
|
-
continue
|
|
244
|
-
qid = 'first_pass' if site == 'clef-first-pass' else 'retry_pass'
|
|
245
|
-
p = ((d.get('answers') or {}).get(qid) or {}).get('noul')
|
|
246
|
-
n = d.get('intended_attempt') if site == 'clef-first-pass' else d.get('attempt')
|
|
247
|
-
if isinstance(p, (int, float)) and n:
|
|
248
|
-
self.clef[(e['run'], e['task'] or d.get('task'), int(n))].append(
|
|
249
|
-
(e['ts'], float(p), d.get('model'), d.get('assignment') or {}))
|
|
250
264
|
self.integrate_verification = {}
|
|
251
265
|
for e in sorted(store.of('verification'), key=lambda e: e['ts']):
|
|
252
266
|
if e['d'].get('scope') == 'integrate' and e['d'].get('status'):
|
|
@@ -308,7 +322,7 @@ def _file_excerpts(store: Store, plan, files) -> dict:
|
|
|
308
322
|
|
|
309
323
|
|
|
310
324
|
def _siblings(plan, task_id) -> list:
|
|
311
|
-
return
|
|
325
|
+
return siblings([dict(row, id=tid) for tid, row in (plan['d'].get('tasks') or {}).items()], task_id)
|
|
312
326
|
|
|
313
327
|
|
|
314
328
|
def _attempts(runs: Runs, run, task, rows) -> list:
|
|
@@ -358,6 +372,12 @@ def _verdicts(runs: Runs, run, task) -> dict:
|
|
|
358
372
|
return out
|
|
359
373
|
|
|
360
374
|
|
|
375
|
+
def _gate_decision(line) -> str | None:
|
|
376
|
+
"""The decision cell of a `qa.gate` line (`thr<TAB>decision<TAB>...`), None when absent or unknown."""
|
|
377
|
+
cells = (line or '').split('\t')
|
|
378
|
+
return cells[1] if len(cells) > 1 and cells[1] in ('accept', 'fail', 'keep') else None
|
|
379
|
+
|
|
380
|
+
|
|
361
381
|
def _course(runs: Runs, run, task, attempts) -> dict:
|
|
362
382
|
"""How the task went, for meta: what a single first-pass bit leaves out."""
|
|
363
383
|
raw = _verdicts(runs, run, task)
|
|
@@ -374,7 +394,9 @@ def _course(runs: Runs, run, task, attempts) -> dict:
|
|
|
374
394
|
stop = 'interrupted'
|
|
375
395
|
else:
|
|
376
396
|
stop = 'no_pass_observed'
|
|
397
|
+
gate = _gate_decision(attempts[0]['events'][-1]['d'].get('gate')) if attempts else None
|
|
377
398
|
return dict(attempts_observed=len(attempts), raw_verdict=raw.get(first),
|
|
399
|
+
gate_fail=gate == 'fail',
|
|
378
400
|
gate_pass=bool(attempts) and attempts[0]['events'][-1]['d'].get('status') == 'PASS'
|
|
379
401
|
and raw.get(first) == 'FAIL',
|
|
380
402
|
first_raw_pass_attempt=min((n for n, v in raw.items() if v == 'PASS'), default=None),
|
|
@@ -398,7 +420,7 @@ def _task_state(runs: Runs, run, task, attempt):
|
|
|
398
420
|
return None, None, None
|
|
399
421
|
dwarf = runs.resolved(run, task, 'dwarf', attempt['attempt']) or _spec(attempt['d'].get('dwarf'))
|
|
400
422
|
reviewer = runs.resolved(run, task, 'qa', attempt['attempt']) or _spec(attempt['d'].get('qa'))
|
|
401
|
-
state =
|
|
423
|
+
state = assemble(
|
|
402
424
|
goal=store.text((plan['d'].get('blobs') or {}).get('goal')) or plan['d'].get('goal') or '',
|
|
403
425
|
task_id=task, title=row.get('title', ''), files=row.get('files', ''), deps=row.get('deps', ''),
|
|
404
426
|
prompt=prompt, approach=store.text(row.get('approach')), plan_tasks=_siblings(plan, task),
|
|
@@ -452,12 +474,6 @@ def routing_cases(runs: Runs):
|
|
|
452
474
|
if declared in ('low', 'medium', 'high'):
|
|
453
475
|
baseline.setdefault('first_pass_declared', dict(source='declared difficulty', risk=
|
|
454
476
|
dict(low=0.0, medium=0.5, high=1.0)[declared]))
|
|
455
|
-
live = _clef_before(runs, run, task, 1, first['d'].get('wall_started') or first['ts'])
|
|
456
|
-
if live:
|
|
457
|
-
# Followed: attempt 1 ran the dwarf the prediction was about. A gate edit or a
|
|
458
|
-
# `retry --dwarf` in between makes it a prediction about a model that never ran.
|
|
459
|
-
baseline['first_pass_clef'] = dict(source='live clef first-pass', p=live[1], model=live[2],
|
|
460
|
-
followed=live[3].get('dwarf') == first['d'].get('dwarf'))
|
|
461
477
|
yield dict(slice='routing', key=(run, task), run=run, repo=first['repo'], task=task,
|
|
462
478
|
state=state, questions=questions, expected=expected, baseline=baseline,
|
|
463
479
|
label_source=dict(first_pass='final status of the first real attempt',
|
|
@@ -531,30 +547,14 @@ def retry_cases(runs: Runs):
|
|
|
531
547
|
state, _row, plan = _task_state(runs, run, task, start)
|
|
532
548
|
if state is None:
|
|
533
549
|
continue
|
|
534
|
-
state =
|
|
550
|
+
state = retry(state, attempt=a['n'], previous_review=findings)
|
|
535
551
|
yield dict(slice='retry', key=(run, task, a['n']), run=run, repo=start['repo'], task=task,
|
|
536
552
|
state=state, questions=dict(retry_pass=retry_pass()),
|
|
537
|
-
expected=dict(retry_pass=a['outcome']), baseline=
|
|
553
|
+
expected=dict(retry_pass=a['outcome']), baseline={},
|
|
538
554
|
label_source=dict(retry_pass='final status of this retry attempt'),
|
|
539
555
|
dwarf=state['dwarf'].get('model'), meta=_meta(runs, run, plan, a['events'][-1]))
|
|
540
556
|
|
|
541
557
|
|
|
542
|
-
def _clef_before(runs: Runs, run, task, attempt, started):
|
|
543
|
-
"""The last plan-time Clef prediction about attempt 1 made before it started, or None."""
|
|
544
|
-
found = None
|
|
545
|
-
for item in runs.clef.get((run, task, attempt), []):
|
|
546
|
-
if item[0] <= (started or 0):
|
|
547
|
-
found = item
|
|
548
|
-
return found
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
def _retry_baseline(runs: Runs, run, task, n) -> dict:
|
|
552
|
-
"""The Clef prediction about retry attempt n. It is made once, as the attempt begins
|
|
553
|
-
(after its receipt opened, so not timed against it): the attempt number is the join."""
|
|
554
|
-
live = (runs.clef.get((run, task, n)) or [None])[0]
|
|
555
|
-
return dict(retry_pass_clef=dict(source='live clef retry-pass', p=live[1], model=live[2])) if live else {}
|
|
556
|
-
|
|
557
|
-
|
|
558
558
|
def _float(value):
|
|
559
559
|
try:
|
|
560
560
|
return float(value)
|
|
@@ -581,8 +581,10 @@ def _qa_rows(runs: Runs):
|
|
|
581
581
|
"""
|
|
582
582
|
store = runs.store
|
|
583
583
|
effort = {}
|
|
584
|
+
gates = {}
|
|
584
585
|
for (run, task), rows in runs.attempts.items():
|
|
585
586
|
for e in rows:
|
|
587
|
+
gates[(run, task, e['attempt'])] = _gate_decision(e['d'].get('gate'))
|
|
586
588
|
text = store.text((e['d'].get('blobs') or {}).get('qa_effort_jev'))
|
|
587
589
|
if text.strip():
|
|
588
590
|
word, _, conf = text.strip().partition('\t')
|
|
@@ -602,6 +604,7 @@ def _qa_rows(runs: Runs):
|
|
|
602
604
|
continue
|
|
603
605
|
found = d.get('findings') or []
|
|
604
606
|
yield dict(run=run, task=task, attempt=e['attempt'], repo=e['repo'], verdict=d['verdict'],
|
|
607
|
+
gate=gates.get((run, task, e['attempt'])),
|
|
605
608
|
diff=blocks[-1], review=store.text((d.get('blobs') or {}).get('message')),
|
|
606
609
|
effort=effort.get((run, task, e['attempt'])), model=d.get('model'),
|
|
607
610
|
reviewer=dict(model=d.get('model'), effort=d.get('effort'), harness=d.get('harness')),
|
|
@@ -707,7 +710,7 @@ def review_cases(runs: Runs):
|
|
|
707
710
|
len({item['worst'] for item, _ in items}) == 1:
|
|
708
711
|
questions['severity'], expected['severity'] = review_severity(), r['worst']
|
|
709
712
|
label_source['severity'] = 'worst CONFIRMED finding (%s)' % r['completeness']
|
|
710
|
-
meta = dict(completeness=r['completeness'])
|
|
713
|
+
meta = dict(completeness=r['completeness'], gate=r['gate'])
|
|
711
714
|
# A second reviewer of the same diff, never consulted by the run: agreement is how
|
|
712
715
|
# much of this label is the diff and how much is who happened to review it.
|
|
713
716
|
paired = next((shadows[k] for k in ((i['run'], i['task'], i['attempt']) for i, _ in items) if k in shadows), None)
|
|
@@ -939,6 +942,13 @@ def memory_cases(runs: Runs, rng_seed: int):
|
|
|
939
942
|
'or in an area it never touched (false)'))
|
|
940
943
|
|
|
941
944
|
|
|
945
|
+
# The joins forge_decide.labels reuses to label live requests the same way.
|
|
946
|
+
final_pass = _final_pass
|
|
947
|
+
area = _area
|
|
948
|
+
words = _words
|
|
949
|
+
ANCHOR = _ANCHOR
|
|
950
|
+
|
|
951
|
+
|
|
942
952
|
# --- sampling and output ---------------------------------------------------------------
|
|
943
953
|
|
|
944
954
|
def _sample(cases: list, limit: int | None, seed: int) -> list:
|
|
@@ -337,7 +337,10 @@ def budget() -> float:
|
|
|
337
337
|
value = float(os.environ.get('FORGE_FORECAST_BUDGET_S') or BUDGET_S)
|
|
338
338
|
except ValueError:
|
|
339
339
|
return BUDGET_S
|
|
340
|
-
|
|
340
|
+
if not value > 0:
|
|
341
|
+
return BUDGET_S
|
|
342
|
+
# Thread.join refuses a timeout past TIMEOUT_MAX (inf, 1e10, ...): that budget means no limit.
|
|
343
|
+
return min(value, threading.TIMEOUT_MAX)
|
|
341
344
|
|
|
342
345
|
|
|
343
346
|
def main(args) -> int:
|
|
@@ -30,7 +30,8 @@ PIPELINE_ROLES = ('task', 'solo', 'verification', 'parallel')
|
|
|
30
30
|
TASKS_COLS = ('id', 'deps', 'difficulty', 'files', 'dwarf', 'qa', 'title')
|
|
31
31
|
STRUCTURED = ('codex', 'claude', 'openclaude', 'grok', 'opencode') # as forge-runtime.py's: .last is the message, not the log
|
|
32
32
|
# Plan files that change what a plan decides, added to its rid only when present (see plan_event).
|
|
33
|
-
PLAN_RID_LATER = ('decompose_level', 'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session'
|
|
33
|
+
PLAN_RID_LATER = ('decompose_level', 'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session',
|
|
34
|
+
'implementer_session', 'pre_review_tests')
|
|
34
35
|
|
|
35
36
|
# Files a task or solo execution may write. begin() snapshots their signatures so
|
|
36
37
|
# finish() can tell this execution's outputs from what an earlier one left behind.
|
|
@@ -44,8 +45,12 @@ WATCHED = (
|
|
|
44
45
|
'verification.retry.log', 'verification.flaky', 'verification.coverage.txt',
|
|
45
46
|
'verification.jev.json', 'verification.runs.tsv', 'verification.commit', 'verification.fingerprint',
|
|
46
47
|
'verification.lanes.json', 'results.tsv',
|
|
48
|
+
'prereview.failed', 'bounced', 'message.failed', 'needs_input.md',
|
|
47
49
|
)
|
|
48
50
|
|
|
51
|
+
# The markers of an attempt forge sent back without a review, and the kind each one records.
|
|
52
|
+
SENT_BACK = (('prereview.failed', 'prereview'), ('bounced', 'bounce'), ('message.failed', 'message'))
|
|
53
|
+
|
|
49
54
|
_VERDICT = re.compile(r'^FORGE_VERDICT: (PASS|FAIL)([ \t]+(—|–|-)( .*)?)?[ \t]*$')
|
|
50
55
|
_LEARNING = re.compile(r'^\s*FORGE_LEARNING:\s*(.+)$')
|
|
51
56
|
|
|
@@ -481,6 +486,8 @@ def task_event(attempt: Path, tdir: Path, rc, prov: dict, src: str = 'live') ->
|
|
|
481
486
|
drift=(text(tdir / 'drift.txt') or '').split() if made('drift.txt') else [],
|
|
482
487
|
guard=(text(tdir / 'guard.txt') or '').splitlines() if made('guard.txt') else [],
|
|
483
488
|
noretry=made('noretry'), gate=gate, infra=infra or None,
|
|
489
|
+
sent_back=next((kind for marker, kind in SENT_BACK if made(marker)), None),
|
|
490
|
+
retry_source=first_line(tdir / 'retry_findings.source'),
|
|
484
491
|
identical_retry=bool(diff) and made('changes.prev.diff') and diff == text(tdir / 'changes.prev.diff'),
|
|
485
492
|
produced=sorted(n for n in WATCHED if made(n)),
|
|
486
493
|
carried=sorted(n for n in WATCHED if (tdir / n).exists() and not made(n)),
|
|
@@ -508,6 +515,16 @@ def task_event(attempt: Path, tdir: Path, rc, prov: dict, src: str = 'live') ->
|
|
|
508
515
|
attempt=number, parent=prov.get('parent'), inv=prov.get('inv'), data=data)
|
|
509
516
|
|
|
510
517
|
|
|
518
|
+
def effective_threshold(plan: Path):
|
|
519
|
+
"""The blocking threshold a plan ran with and whether the plan set it: file, else the default."""
|
|
520
|
+
value = (first_line(plan / 'qa_threshold') or '').strip().upper() if (plan / 'qa_threshold').exists() else ''
|
|
521
|
+
if value == 'NONE':
|
|
522
|
+
value = 'P3'
|
|
523
|
+
if value in ('P0', 'P1', 'P2', 'P3'):
|
|
524
|
+
return value, 'set'
|
|
525
|
+
return contract().DEFAULT_THRESHOLD, 'default'
|
|
526
|
+
|
|
527
|
+
|
|
511
528
|
def solo_event(attempt: Path, run: Path, rc, prov: dict, src: str = 'live') -> dict:
|
|
512
529
|
before = prov.get('files')
|
|
513
530
|
made = lambda name: produced(run, before, name)
|
|
@@ -521,6 +538,7 @@ def solo_event(attempt: Path, run: Path, rc, prov: dict, src: str = 'live') -> d
|
|
|
521
538
|
guard=(text(run / 'guard.txt') or '').splitlines() if made('guard.txt') else [],
|
|
522
539
|
start_tree=first_line(run / 'start.tree') if made('start.tree') else None,
|
|
523
540
|
reviewed_tree=first_line(run / 'reviewed.tree') if made('reviewed.tree') else None,
|
|
541
|
+
gate=first_line(run / 'qa.gate') if made('qa.gate') else None,
|
|
524
542
|
produced=sorted(n for n in WATCHED if made(n)), children=children(run, attempt.name),
|
|
525
543
|
**(diff_summary(diff) if diff is not None else dict(changed_files=[], numstat={}, binary=[], patch_key=None)),
|
|
526
544
|
)
|
|
@@ -531,6 +549,7 @@ def solo_event(attempt: Path, run: Path, rc, prov: dict, src: str = 'live') -> d
|
|
|
531
549
|
request=put_file(run / 'request.md', 'prompt'),
|
|
532
550
|
dwarf_memory=put_file(run / 'dwarf.memory') if made('dwarf.memory') else None,
|
|
533
551
|
qa_memory=put_file(run / 'qa.memory') if made('qa.memory') else None,
|
|
552
|
+
known_issues=put_file(run / 'known_issues.md') if made('known_issues.md') else None,
|
|
534
553
|
)
|
|
535
554
|
return dict(rid=attempt.name, kind='attempt', ts=prov.get('wall_ended') or time.time(), src=src,
|
|
536
555
|
run=prov.get('run'), run_id=prov.get('run_id'), mode='solo', task=None, attempt=number,
|
|
@@ -685,9 +704,14 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
|
|
|
685
704
|
routes = {tid: [d.get('decision') for d in r['route']] for tid, r in per_task.items() if r.get('route')}
|
|
686
705
|
if routes:
|
|
687
706
|
later['route'] = routes
|
|
707
|
+
# PLAN_RID_LATER hashes a file's first line, which is `{` for any JSON record: hash the content.
|
|
708
|
+
plan_gates = read_json(plan / 'plan-gates.json')
|
|
709
|
+
if plan_gates is not None:
|
|
710
|
+
later['plan_gates'] = plan_gates
|
|
688
711
|
inputs = json.dumps([text(plan / 'goal.txt'), text(plan / 'tasks.tsv'), text(declared_path),
|
|
689
712
|
{t: [r['prompt'], r['approach']] for t, r in per_task.items()}] + ([later] if later else []),
|
|
690
713
|
sort_keys=True, default=str)
|
|
714
|
+
threshold, threshold_source = effective_threshold(plan)
|
|
691
715
|
snapshot_excerpts = decision_snapshot(repo, rows, head) if repo else None
|
|
692
716
|
listing = _git(repo, 'ls-tree', '-r', '--name-only', head) if inventory and repo and head else None
|
|
693
717
|
data = dict(
|
|
@@ -698,10 +722,12 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
|
|
|
698
722
|
pools=read_json(plan / 'fractal-routing.json'), jev_selection=read_json(plan / 'jev-selection.json'),
|
|
699
723
|
fractal_selection=read_json(plan / 'fractal-selection.json'),
|
|
700
724
|
jev_coupling=read_json(plan / 'jev-coupling.json'),
|
|
701
|
-
options={name: first_line(plan / name) for name in ('
|
|
702
|
-
'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session'
|
|
703
|
-
|
|
704
|
-
|
|
725
|
+
options=dict({name: first_line(plan / name) for name in ('verify_retries', 'timeout', 'final_qa',
|
|
726
|
+
'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session',
|
|
727
|
+
'implementer_session')
|
|
728
|
+
if (plan / name).exists()}, qa_threshold=threshold, qa_threshold_source=threshold_source),
|
|
729
|
+
flags=sorted(name for name in ('no_memory', 'no_ripwire', 'yolo_dwarf', 'yolo_qa', 'pre_review_tests')
|
|
730
|
+
if (plan / name).exists()),
|
|
705
731
|
blobs=blobs(goal=put_file(plan / 'goal.txt'), request=put_file(plan / 'request.md', 'prompt'),
|
|
706
732
|
tasks=put_file(plan / 'tasks.tsv'), tasks_declared=put_file(declared_path),
|
|
707
733
|
jev_routing=put_file(plan / 'jev-routing.tsv'),
|
|
@@ -709,6 +735,8 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
|
|
|
709
735
|
inventory=put_blob(listing, 'request') if listing else None,
|
|
710
736
|
memory=put_file(Path(repo) / '.forge' / 'memory.md') if repo else None),
|
|
711
737
|
)
|
|
738
|
+
if plan_gates is not None:
|
|
739
|
+
data['plan_gates'] = plan_gates
|
|
712
740
|
return dict(rid='plan:%s:%s' % (prov.get('run'), sha256(inputs.encode())[:16]), kind='plan',
|
|
713
741
|
ts=time.time(), src=src, run=prov.get('run'), run_id=prov.get('run_id'), mode='parallel',
|
|
714
742
|
inv=prov.get('inv'), data=data)
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""State assemblers for the dataset export's routing and retry slices.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
the state it answers in production cannot drift apart in shape. Pure: no file reads.
|
|
3
|
+
`siblings`, `assemble` and `retry` build the state of those slices from events the
|
|
4
|
+
export has already read. `task_size` is the size block on that state. This only caps
|
|
5
|
+
and arranges what callers pass in. Pure: no file reads.
|
|
7
6
|
|
|
8
|
-
The caps are the export's (`forge dataset export`)
|
|
9
|
-
|
|
7
|
+
The caps are the export's (`forge dataset export`): goal and prompt are not cut.
|
|
8
|
+
|
|
9
|
+
A task's size is the strongest regime signal in forge's run history: the median prompt of
|
|
10
|
+
the newest runs is twice the older ones' and their first-pass rate is half. A model reading
|
|
11
|
+
prose and a 40-entry sibling list can only estimate that, so the state spells it out.
|
|
10
12
|
"""
|
|
11
13
|
from __future__ import annotations
|
|
12
14
|
|
|
@@ -47,3 +49,15 @@ def retry(state: dict, *, attempt: int, previous_review: str) -> dict:
|
|
|
47
49
|
review = previous_review or ''
|
|
48
50
|
return dict(state, attempt=attempt, previous_review=review[:REVIEW_CHARS],
|
|
49
51
|
previous_review_truncated=len(review) > REVIEW_CHARS)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _count(value) -> int:
|
|
55
|
+
if isinstance(value, (list, tuple)):
|
|
56
|
+
return len([v for v in value if v])
|
|
57
|
+
return len([w for w in str(value or '').replace(',', ' ').split() if w and w != '-'])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def task_size(*, prompt: str, declared_files, plan_tasks: int, deps, decompose_level: str | None) -> dict:
|
|
61
|
+
return dict(prompt_chars=len(prompt or ''), declared_files=_count(declared_files),
|
|
62
|
+
plan_tasks=int(plan_tasks), deps=_count(deps),
|
|
63
|
+
decompose_level=decompose_level if decompose_level in ('low', 'medium', 'high') else None)
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Decision-model gates: where their settings live, and how they are read and written.
|
|
2
|
+
|
|
3
|
+
Each kept decision-model site is one gate, set to `off` (the default), `shadow` (ask and
|
|
4
|
+
record, change nothing) or `on` (act), with an optional provider, model and threshold
|
|
5
|
+
overrides. Settings live per repo (<repo>/.forge/decide.json) and per user
|
|
6
|
+
(${XDG_CONFIG_HOME:-~/.config}/forge/decide.json); resolve.resolve() combines them with
|
|
7
|
+
the profile, env and run flags. Standard library only; importing this never reads a file.
|
|
8
|
+
|
|
9
|
+
File schema, the same at both levels (unknown keys are kept and ignored):
|
|
10
|
+
|
|
11
|
+
{"version": 1,
|
|
12
|
+
"gates": {"<gate>": {"mode", "provider", "model", "thresholds": {name: float},
|
|
13
|
+
"thresholds_model"}},
|
|
14
|
+
"budget": {"run_tokens", "run_usd", "daily_tokens", "daily_usd"},
|
|
15
|
+
"providers": {"<name>": {"type", "url", "model", "key_env", "key_file", "context",
|
|
16
|
+
"price_usd_per_mtok", "local"}},
|
|
17
|
+
"profiles": {"<name>": {"gates", "budget"}},
|
|
18
|
+
"privacy": "never-send"}
|
|
19
|
+
|
|
20
|
+
A provider's key comes from `key_env` when that variable is set, else from `key_file`; it
|
|
21
|
+
may name both, or neither (a local server may need no key).
|
|
22
|
+
A gate may also be written as a bare mode string ("drift": "on"). USER_ONLY keys count only
|
|
23
|
+
in the user file and REPO_ONLY keys only in the repo file.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
import uuid
|
|
31
|
+
|
|
32
|
+
GATES = ('drift', 'forward', 'prompt', 'memory-curate', 'memory-slice', 'memory-stale',
|
|
33
|
+
'verify-discover', 'coverage', 'retry-addressed', 'dwarf-message', 'attribution',
|
|
34
|
+
'findings')
|
|
35
|
+
MODES = ('off', 'shadow', 'on')
|
|
36
|
+
GATE_SITE = {
|
|
37
|
+
'drift': 'jev-drift', 'forward': 'jev-forward', 'prompt': 'jev-prompt',
|
|
38
|
+
'memory-curate': 'jev-memory-curate', 'memory-slice': 'jev-memory-slice',
|
|
39
|
+
'memory-stale': 'jev-memory-stale', 'verify-discover': 'jev-verify-discover',
|
|
40
|
+
'coverage': 'jev-coverage', 'retry-addressed': 'jev-retry-addressed',
|
|
41
|
+
'dwarf-message': 'jev-dwarf-message', 'attribution': 'jev-attribution',
|
|
42
|
+
'findings': 'jev-findings',
|
|
43
|
+
}
|
|
44
|
+
SITE_GATE = {site: gate for gate, site in GATE_SITE.items()}
|
|
45
|
+
# The forge_jev capability each gate used to belong to: what the legacy jev.json and the
|
|
46
|
+
# FORGE_JEV_<CAP> variables switch. None for a gate with no legacy capability: the legacy
|
|
47
|
+
# level never turns it on, so it is off until its own mode is set.
|
|
48
|
+
GATE_CAPABILITY = {
|
|
49
|
+
'drift': 'gates', 'forward': 'gates', 'prompt': 'gates',
|
|
50
|
+
'memory-curate': 'memory', 'memory-slice': 'memory', 'memory-stale': 'memory',
|
|
51
|
+
'verify-discover': 'tests',
|
|
52
|
+
'coverage': None, 'retry-addressed': None, 'dwarf-message': None, 'attribution': None,
|
|
53
|
+
'findings': None,
|
|
54
|
+
}
|
|
55
|
+
PROVIDER_TYPES = ('jev', 'clef')
|
|
56
|
+
USER_ONLY = ('providers', 'budget.daily_tokens', 'budget.daily_usd')
|
|
57
|
+
REPO_ONLY = ('privacy',)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _xdg(var: str, fallback: str) -> Path:
|
|
61
|
+
# An empty or relative value counts as unset (XDG spec), as in forge_jev.config_path().
|
|
62
|
+
value = os.environ.get(var) or ''
|
|
63
|
+
base = Path(value).expanduser() if value else None
|
|
64
|
+
if base is None or not base.is_absolute():
|
|
65
|
+
base = Path.home() / fallback
|
|
66
|
+
return base
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def config_dir() -> Path:
|
|
70
|
+
return _xdg('XDG_CONFIG_HOME', '.config') / 'forge'
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def user_path() -> Path:
|
|
74
|
+
return config_dir() / 'decide.json'
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def repo_path(repo) -> Path:
|
|
78
|
+
return Path(repo) / '.forge' / 'decide.json'
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def state_dir() -> Path:
|
|
82
|
+
return _xdg('XDG_STATE_HOME', '.local/state') / 'forge' / 'decide'
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _load(path: Path) -> tuple[dict, str | None]:
|
|
86
|
+
try:
|
|
87
|
+
text = path.read_text()
|
|
88
|
+
except FileNotFoundError:
|
|
89
|
+
return {}, None
|
|
90
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
91
|
+
return {}, f'{path}: {exc}'
|
|
92
|
+
try:
|
|
93
|
+
data = json.loads(text)
|
|
94
|
+
except (ValueError, RecursionError) as exc: # RecursionError: nested too deep to parse
|
|
95
|
+
return {}, f'{path}: not valid JSON ({exc})'
|
|
96
|
+
if not isinstance(data, dict):
|
|
97
|
+
return {}, f'{path}: not a JSON object'
|
|
98
|
+
return data, None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def load_user() -> tuple[dict, str | None]:
|
|
102
|
+
"""(data, error): ({}, None) when the file is missing, ({}, "<path>: <reason>") when it
|
|
103
|
+
cannot be read or is not a JSON object."""
|
|
104
|
+
return _load(user_path())
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def load_repo(repo) -> tuple[dict, str | None]:
|
|
108
|
+
"""As load_user(), for <repo>/.forge/decide.json."""
|
|
109
|
+
return _load(repo_path(repo))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _save(path: Path, data: dict, mode: int) -> None:
|
|
113
|
+
temporary = path.with_name(path.name + '.' + uuid.uuid4().hex)
|
|
114
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
|
|
115
|
+
try:
|
|
116
|
+
with os.fdopen(fd, 'w') as handle:
|
|
117
|
+
handle.write(json.dumps(data, indent=2) + '\n')
|
|
118
|
+
os.chmod(temporary, mode) # the umask may have narrowed os.open's mode
|
|
119
|
+
os.replace(temporary, path)
|
|
120
|
+
except BaseException:
|
|
121
|
+
try:
|
|
122
|
+
os.unlink(temporary)
|
|
123
|
+
except OSError:
|
|
124
|
+
pass
|
|
125
|
+
raise
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def save_user(data: dict) -> None:
|
|
129
|
+
"""Atomic write, mode 0600; a missing config directory is created 0700."""
|
|
130
|
+
path = user_path()
|
|
131
|
+
if not path.parent.exists():
|
|
132
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
133
|
+
path.parent.chmod(0o700)
|
|
134
|
+
_save(path, data, 0o600)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def save_repo(repo, data: dict) -> None:
|
|
138
|
+
"""Atomic write, mode 0644: the repo file is meant to be shared."""
|
|
139
|
+
path = repo_path(repo)
|
|
140
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
141
|
+
_save(path, data, 0o644)
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Spend caps for decision-model requests, in tokens and estimated cost (GitHub #36).
|
|
2
|
+
|
|
3
|
+
Two counters, each a JSON file {"tokens": int, "usd": float}: one per run
|
|
4
|
+
(<run_dir>/decide.budget.json, where FORGE_DECIDE_RUN_DIR beats the caller's run_dir) and one per day for the user
|
|
5
|
+
(<state_dir>/spend/<YYYY-MM-DD>.json, local date; a new day is a new file and old files are
|
|
6
|
+
left alone). The transports call check() before a request and charge() after it; a cap that
|
|
7
|
+
has been reached turns every remaining call into a skip with reason 'budget'.
|
|
8
|
+
|
|
9
|
+
Fail-open throughout: check() and charge() never raise, a counter that cannot be read or
|
|
10
|
+
parsed counts as zero, and a lock or write failure skips the charge. Several processes of one
|
|
11
|
+
run may charge at once, so each read-modify-write holds flock(LOCK_EX) on a sibling .lock
|
|
12
|
+
file and the write is a temp file plus os.replace. Standard library only.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import fcntl
|
|
17
|
+
import json
|
|
18
|
+
import math
|
|
19
|
+
import os
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
import time
|
|
22
|
+
|
|
23
|
+
from . import state_dir
|
|
24
|
+
|
|
25
|
+
RUN_FILE = 'decide.budget.json'
|
|
26
|
+
RUN_DIR_ENV = 'FORGE_DECIDE_RUN_DIR'
|
|
27
|
+
SKIP = 'budget'
|
|
28
|
+
USD_SLACK = 1e-9 # relative: float drift in summed charges (ten $0.10 ones) must not miss a cap
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _number(value) -> float:
|
|
32
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
33
|
+
return 0
|
|
34
|
+
try:
|
|
35
|
+
return value if math.isfinite(value) and value > 0 else 0
|
|
36
|
+
except OverflowError: # an integer too big for a float is corrupt, not a huge spend
|
|
37
|
+
return 0
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def usage_tokens(usage) -> int:
|
|
41
|
+
"""Tokens a response used: input+output, else prompt+completion, else total."""
|
|
42
|
+
if not isinstance(usage, dict):
|
|
43
|
+
return 0
|
|
44
|
+
for keys in (('input_tokens', 'output_tokens'), ('prompt_tokens', 'completion_tokens')):
|
|
45
|
+
if any(k in usage for k in keys):
|
|
46
|
+
return int(sum(_number(usage.get(k)) for k in keys))
|
|
47
|
+
return int(_number(usage.get('total_tokens')))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cost(provider, usage) -> float:
|
|
51
|
+
"""Estimated USD for one response; a local provider, or one with no price, costs 0."""
|
|
52
|
+
if not isinstance(provider, dict) or provider.get('local'):
|
|
53
|
+
return 0.0
|
|
54
|
+
price = _number(provider.get('price_usd_per_mtok'))
|
|
55
|
+
return usage_tokens(usage) / 1e6 * price if price else 0.0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _run_path(run_dir) -> Path | None:
|
|
59
|
+
# The runners export the run's directory; it wins over a caller's own (a task or
|
|
60
|
+
# integrate dir, where jev.jsonl goes), so every site of one run shares one counter.
|
|
61
|
+
run_dir = os.environ.get(RUN_DIR_ENV) or run_dir
|
|
62
|
+
return Path(run_dir) / RUN_FILE if run_dir else None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _day(now) -> str:
|
|
66
|
+
return time.strftime('%Y-%m-%d', time.localtime(now))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _daily_path(now) -> Path:
|
|
70
|
+
return state_dir() / 'spend' / f'{_day(now)}.json'
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _read(path: Path | None) -> dict:
|
|
74
|
+
zero = {'tokens': 0, 'usd': 0.0}
|
|
75
|
+
if path is None:
|
|
76
|
+
return zero
|
|
77
|
+
try:
|
|
78
|
+
data = json.loads(path.read_text())
|
|
79
|
+
return {'tokens': int(_number(data['tokens'])), 'usd': float(_number(data['usd']))}
|
|
80
|
+
except (OSError, ValueError, KeyError, TypeError, OverflowError, RecursionError):
|
|
81
|
+
return zero
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _add(path: Path, tokens: int, usd: float) -> None:
|
|
85
|
+
try:
|
|
86
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
with open(f'{path}.lock', 'a') as lock:
|
|
88
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
89
|
+
total = _read(path)
|
|
90
|
+
total['tokens'] += tokens
|
|
91
|
+
total['usd'] += usd
|
|
92
|
+
tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
|
|
93
|
+
try:
|
|
94
|
+
tmp.write_text(json.dumps(total))
|
|
95
|
+
os.replace(tmp, path)
|
|
96
|
+
finally:
|
|
97
|
+
tmp.unlink(missing_ok=True)
|
|
98
|
+
except Exception: # fail-open: a charge that cannot be recorded is dropped
|
|
99
|
+
pass
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _reached(spent, cap, slack=0.0) -> bool:
|
|
103
|
+
# The slack scales the (finite) spend, never the cap: an int cap too big for a float
|
|
104
|
+
# still compares exactly. A cap that cannot be compared never blocks, and never stops
|
|
105
|
+
# the other caps from being checked.
|
|
106
|
+
if cap is None:
|
|
107
|
+
return False
|
|
108
|
+
try:
|
|
109
|
+
return spent * (1 + slack) >= cap
|
|
110
|
+
except Exception:
|
|
111
|
+
return False
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def check(caps, *, run_dir=None, now=None) -> str | None:
|
|
115
|
+
"""'budget' once any set cap (run or day, tokens or usd) has been reached, else None."""
|
|
116
|
+
try:
|
|
117
|
+
now = time.time() if now is None else now
|
|
118
|
+
caps = caps if isinstance(caps, dict) else {}
|
|
119
|
+
run, day = _read(_run_path(run_dir)), _read(_daily_path(now))
|
|
120
|
+
for counter, scope in ((run, 'run'), (day, 'daily')):
|
|
121
|
+
if (_reached(counter['tokens'], caps.get(f'{scope}_tokens'))
|
|
122
|
+
or _reached(counter['usd'], caps.get(f'{scope}_usd'), USD_SLACK)):
|
|
123
|
+
return SKIP
|
|
124
|
+
except Exception:
|
|
125
|
+
pass
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def charge(provider, usage, *, run_dir=None, now=None) -> None:
|
|
130
|
+
"""Add one response's tokens and estimated cost to the run counter and today's."""
|
|
131
|
+
try:
|
|
132
|
+
now = time.time() if now is None else now
|
|
133
|
+
tokens, usd = usage_tokens(usage), cost(provider, usage)
|
|
134
|
+
if not tokens and not usd:
|
|
135
|
+
return
|
|
136
|
+
run = _run_path(run_dir)
|
|
137
|
+
if run is not None:
|
|
138
|
+
_add(run, tokens, usd)
|
|
139
|
+
_add(_daily_path(now), tokens, usd)
|
|
140
|
+
except Exception:
|
|
141
|
+
pass
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def spend(*, run_dir=None, now=None) -> dict:
|
|
145
|
+
"""{'run': counter | None, 'today': counter, 'date': 'YYYY-MM-DD'}; run is None with no run dir."""
|
|
146
|
+
now = time.time() if now is None else now
|
|
147
|
+
run = _run_path(run_dir)
|
|
148
|
+
return {'run': _read(run) if run else None, 'today': _read(_daily_path(now)),
|
|
149
|
+
'date': _day(now)}
|