@giamme/forge 0.12.1 → 0.13.1
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 +66 -0
- package/README.md +1 -1
- package/SKILL.md +29 -12
- package/VERSION +1 -1
- package/docs/add-ons.md +11 -6
- package/docs/artifacts.md +12 -6
- package/docs/commands.md +179 -17
- package/docs/decomposed-runs.md +13 -5
- package/docs/forge-ui.md +14 -4
- package/docs/memory.md +2 -1
- package/docs/models.md +4 -2
- package/docs/reviews.md +49 -20
- package/docs/troubleshooting.md +3 -1
- package/forge +17 -1
- package/package.json +1 -1
- package/references/dataset.md +39 -13
- package/references/decision-models.md +763 -0
- package/references/decompose.md +166 -29
- package/references/harnesses.md +10 -3
- package/references/planning.md +8 -0
- package/references/solo.md +13 -3
- package/scripts/forge-artifact.sh +30 -4
- package/scripts/forge-config.py +238 -29
- package/scripts/forge-contract.py +95 -56
- package/scripts/forge-control.py +40 -9
- package/scripts/forge-decide.py +6 -0
- package/scripts/forge-dispatch.sh +38 -16
- 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 +321 -33
- 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 +22 -6
- package/scripts/forge-lib-review.sh +22 -17
- package/scripts/forge-lib-task.sh +217 -38
- package/scripts/forge-lib-verify.sh +45 -8
- package/scripts/forge-memory.sh +3 -3
- package/scripts/forge-parallel-options.sh +18 -5
- package/scripts/forge-parallel.sh +457 -303
- 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 +10 -4
- package/scripts/forge-schedule.py +21 -5
- package/scripts/forge-shadow.py +2 -2
- package/scripts/forge-solo.sh +39 -9
- package/scripts/forge-submodules.py +389 -0
- package/scripts/forge-ui-options.sh +25 -0
- package/scripts/forge_dataset/cli.py +12 -6
- package/scripts/forge_dataset/export.py +140 -84
- 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 +180 -0
- package/scripts/forge_decide/cache.py +66 -0
- package/scripts/forge_decide/cli.py +953 -0
- package/scripts/forge_decide/doctor.py +270 -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 +2 -2
- package/ui/docs/api.md +92 -39
- package/ui/forge_ui/control.py +71 -14
- package/ui/forge_ui/export.py +2 -1
- package/ui/forge_ui/models.py +17 -16
- package/ui/forge_ui/reader.py +132 -21
- package/ui/forge_ui/repos.py +428 -0
- package/ui/forge_ui/static/app.js +24 -5
- package/ui/forge_ui/static/cloudmodel.js +8 -5
- package/ui/forge_ui/static/controls.js +20 -13
- package/ui/forge_ui/static/modelstats.js +12 -8
- package/ui/forge_ui/static/panel.js +63 -17
- package/ui/forge_ui/static/runmodel.js +48 -7
- package/ui/forge_ui/static/scene3d.js +2 -15
- package/ui/forge_ui/static/settings.js +481 -68
- package/ui/forge_ui/static/style.css +56 -9
- 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
|
@@ -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,180 @@
|
|
|
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. A stored usd of positive
|
|
11
|
+
infinity is kept: an overflowed cost has reached the USD caps, and a later charge leaves it
|
|
12
|
+
infinite. NaN, a negative, a non-number and an integer too big for a float still count as
|
|
13
|
+
zero. Several processes of one run may charge at once, so each read-modify-write holds
|
|
14
|
+
flock(LOCK_EX) on a sibling .lock file and the write is a temp file plus os.replace. Standard
|
|
15
|
+
library only.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import fcntl
|
|
20
|
+
import json
|
|
21
|
+
import math
|
|
22
|
+
import os
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
import time
|
|
25
|
+
|
|
26
|
+
from . import state_dir
|
|
27
|
+
|
|
28
|
+
RUN_FILE = 'decide.budget.json'
|
|
29
|
+
RUN_DIR_ENV = 'FORGE_DECIDE_RUN_DIR'
|
|
30
|
+
SKIP = 'budget'
|
|
31
|
+
USD_SLACK = 1e-9 # relative: float drift in summed charges (ten $0.10 ones) must not miss a cap
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _number(value) -> float:
|
|
35
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
36
|
+
return 0
|
|
37
|
+
try:
|
|
38
|
+
return value if math.isfinite(value) and value > 0 else 0
|
|
39
|
+
except OverflowError: # an integer too big for a float is corrupt, not a huge spend
|
|
40
|
+
return 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _usd(value) -> float:
|
|
44
|
+
"""Stored USD spend. +inf stays inf: an overflowed cost reached the cap. NaN, a negative,
|
|
45
|
+
a non-number, or an integer too big for a float counts as zero."""
|
|
46
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
47
|
+
return 0.0
|
|
48
|
+
try:
|
|
49
|
+
number = float(value)
|
|
50
|
+
except OverflowError:
|
|
51
|
+
return 0.0
|
|
52
|
+
if math.isnan(number) or number <= 0:
|
|
53
|
+
return 0.0
|
|
54
|
+
return number
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _sum_usd(current: float, extra: float) -> float:
|
|
58
|
+
"""Positive infinity stays infinity. A later charge must not turn it into NaN or zero."""
|
|
59
|
+
if _positive_inf(current) or _positive_inf(extra):
|
|
60
|
+
return math.inf
|
|
61
|
+
return current + extra
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _positive_inf(value) -> bool:
|
|
65
|
+
return isinstance(value, float) and math.isinf(value) and value > 0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def usage_tokens(usage) -> int:
|
|
69
|
+
"""Tokens a response used: input+output, else prompt+completion, else total."""
|
|
70
|
+
if not isinstance(usage, dict):
|
|
71
|
+
return 0
|
|
72
|
+
for keys in (('input_tokens', 'output_tokens'), ('prompt_tokens', 'completion_tokens')):
|
|
73
|
+
if any(k in usage for k in keys):
|
|
74
|
+
return int(sum(_number(usage.get(k)) for k in keys))
|
|
75
|
+
return int(_number(usage.get('total_tokens')))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def cost(provider, usage) -> float:
|
|
79
|
+
"""Estimated USD for one response; a local provider, or one with no price, costs 0."""
|
|
80
|
+
if not isinstance(provider, dict) or provider.get('local'):
|
|
81
|
+
return 0.0
|
|
82
|
+
price = _number(provider.get('price_usd_per_mtok'))
|
|
83
|
+
return usage_tokens(usage) / 1e6 * price if price else 0.0
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _run_path(run_dir) -> Path | None:
|
|
87
|
+
# The runners export the run's directory; it wins over a caller's own (a task or
|
|
88
|
+
# integrate dir, where jev.jsonl goes), so every site of one run shares one counter.
|
|
89
|
+
run_dir = os.environ.get(RUN_DIR_ENV) or run_dir
|
|
90
|
+
return Path(run_dir) / RUN_FILE if run_dir else None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _day(now) -> str:
|
|
94
|
+
return time.strftime('%Y-%m-%d', time.localtime(now))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _daily_path(now) -> Path:
|
|
98
|
+
return state_dir() / 'spend' / f'{_day(now)}.json'
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _read(path: Path | None) -> dict:
|
|
102
|
+
zero = {'tokens': 0, 'usd': 0.0}
|
|
103
|
+
if path is None:
|
|
104
|
+
return zero
|
|
105
|
+
try:
|
|
106
|
+
data = json.loads(path.read_text())
|
|
107
|
+
return {'tokens': int(_number(data['tokens'])), 'usd': _usd(data['usd'])}
|
|
108
|
+
except (OSError, ValueError, KeyError, TypeError, OverflowError, RecursionError):
|
|
109
|
+
return zero
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _add(path: Path, tokens: int, usd: float) -> None:
|
|
113
|
+
try:
|
|
114
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
115
|
+
with open(f'{path}.lock', 'a') as lock:
|
|
116
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
117
|
+
total = _read(path)
|
|
118
|
+
total['tokens'] += tokens
|
|
119
|
+
total['usd'] = _sum_usd(total['usd'], usd)
|
|
120
|
+
tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
|
|
121
|
+
try:
|
|
122
|
+
tmp.write_text(json.dumps(total))
|
|
123
|
+
os.replace(tmp, path)
|
|
124
|
+
finally:
|
|
125
|
+
tmp.unlink(missing_ok=True)
|
|
126
|
+
except Exception: # fail-open: a charge that cannot be recorded is dropped
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _reached(spent, cap, slack=0.0) -> bool:
|
|
131
|
+
# Token caps pass no slack and compare as integers, so a count above 2^53 is exact.
|
|
132
|
+
# USD caps pass USD_SLACK, which scales the (finite) spend, never the cap: an int cap
|
|
133
|
+
# too big for a float still compares exactly. A cap that cannot be compared never
|
|
134
|
+
# blocks, and never stops the other caps from being checked.
|
|
135
|
+
if cap is None:
|
|
136
|
+
return False
|
|
137
|
+
try:
|
|
138
|
+
if not slack:
|
|
139
|
+
return spent >= cap
|
|
140
|
+
return spent * (1 + slack) >= cap
|
|
141
|
+
except Exception:
|
|
142
|
+
return False
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def check(caps, *, run_dir=None, now=None) -> str | None:
|
|
146
|
+
"""'budget' once any set cap (run or day, tokens or usd) has been reached, else None."""
|
|
147
|
+
try:
|
|
148
|
+
now = time.time() if now is None else now
|
|
149
|
+
caps = caps if isinstance(caps, dict) else {}
|
|
150
|
+
run, day = _read(_run_path(run_dir)), _read(_daily_path(now))
|
|
151
|
+
for counter, scope in ((run, 'run'), (day, 'daily')):
|
|
152
|
+
if (_reached(counter['tokens'], caps.get(f'{scope}_tokens'))
|
|
153
|
+
or _reached(counter['usd'], caps.get(f'{scope}_usd'), USD_SLACK)):
|
|
154
|
+
return SKIP
|
|
155
|
+
except Exception:
|
|
156
|
+
pass
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def charge(provider, usage, *, run_dir=None, now=None) -> None:
|
|
161
|
+
"""Add one response's tokens and estimated cost to the run counter and today's."""
|
|
162
|
+
try:
|
|
163
|
+
now = time.time() if now is None else now
|
|
164
|
+
tokens, usd = usage_tokens(usage), cost(provider, usage)
|
|
165
|
+
if not tokens and not usd:
|
|
166
|
+
return
|
|
167
|
+
run = _run_path(run_dir)
|
|
168
|
+
if run is not None:
|
|
169
|
+
_add(run, tokens, usd)
|
|
170
|
+
_add(_daily_path(now), tokens, usd)
|
|
171
|
+
except Exception:
|
|
172
|
+
pass
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def spend(*, run_dir=None, now=None) -> dict:
|
|
176
|
+
"""{'run': counter | None, 'today': counter, 'date': 'YYYY-MM-DD'}; run is None with no run dir."""
|
|
177
|
+
now = time.time() if now is None else now
|
|
178
|
+
run = _run_path(run_dir)
|
|
179
|
+
return {'run': _read(run) if run else None, 'today': _read(_daily_path(now)),
|
|
180
|
+
'date': _day(now)}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Request cache for decision-model calls (GitHub #37): a question already answered in a run is
|
|
2
|
+
never paid for twice.
|
|
3
|
+
|
|
4
|
+
One file per request in <run>/decide.cache, named by sha256 of the request key (the sha256 of
|
|
5
|
+
the canonical body, which carries state, model and questions) plus the provider's name and
|
|
6
|
+
url, so a body sent to another provider or url is a miss. FORGE_DECIDE_RUN_DIR beats the
|
|
7
|
+
caller's run_dir, as in budget.py, so every task of one plan shares one cache.
|
|
8
|
+
FORGE_DECIDE_CACHE=off (0, no, false) turns it off.
|
|
9
|
+
|
|
10
|
+
Fail-open: get() treats a missing, unreadable or malformed file as a miss, put() ignores a
|
|
11
|
+
failed write. Standard library only.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
import time
|
|
20
|
+
|
|
21
|
+
DIR_NAME = 'decide.cache'
|
|
22
|
+
RUN_DIR_ENV = 'FORGE_DECIDE_RUN_DIR'
|
|
23
|
+
SWITCH_ENV = 'FORGE_DECIDE_CACHE'
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def cache_dir(run_dir) -> Path | None:
|
|
27
|
+
if os.environ.get(SWITCH_ENV, '').strip().lower() in ('off', '0', 'no', 'false'):
|
|
28
|
+
return None
|
|
29
|
+
run_dir = os.environ.get(RUN_DIR_ENV) or run_dir
|
|
30
|
+
return Path(run_dir) / DIR_NAME if run_dir else None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def entry_name(key, spec) -> str:
|
|
34
|
+
parts = (str(key), str(spec.get('name')), str(spec.get('url')))
|
|
35
|
+
return hashlib.sha256('\0'.join(parts).encode()).hexdigest()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get(run_dir, key, spec) -> dict | None:
|
|
39
|
+
directory = cache_dir(run_dir)
|
|
40
|
+
if directory is None:
|
|
41
|
+
return None
|
|
42
|
+
try:
|
|
43
|
+
entry = json.loads((directory / (entry_name(key, spec) + '.json')).read_text())
|
|
44
|
+
except (OSError, ValueError, RecursionError):
|
|
45
|
+
return None
|
|
46
|
+
return entry if isinstance(entry, dict) and isinstance(entry.get('answers'), dict) else None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def put(run_dir, key, spec, site, model, answers, usage) -> None:
|
|
50
|
+
directory = cache_dir(run_dir)
|
|
51
|
+
if directory is None:
|
|
52
|
+
return
|
|
53
|
+
entry = dict(site=site, key=key, provider=spec.get('name'), model=model, answers=answers, usage=usage,
|
|
54
|
+
at=time.time())
|
|
55
|
+
temp = directory / f'.{os.getpid()}-{os.urandom(4).hex()}.tmp'
|
|
56
|
+
try:
|
|
57
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
58
|
+
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
59
|
+
with os.fdopen(fd, 'w') as handle:
|
|
60
|
+
handle.write(json.dumps(entry))
|
|
61
|
+
os.replace(temp, directory / (entry_name(key, spec) + '.json'))
|
|
62
|
+
except (OSError, TypeError, ValueError):
|
|
63
|
+
try:
|
|
64
|
+
temp.unlink()
|
|
65
|
+
except OSError:
|
|
66
|
+
pass
|