@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
|
@@ -0,0 +1,953 @@
|
|
|
1
|
+
"""forge decide: the decision-model gates, their providers, budgets and the privacy floor (#36).
|
|
2
|
+
|
|
3
|
+
status [--repo DIR] [--json]
|
|
4
|
+
gate <gate> off|shadow|on [--force] [--provider P] [--model M] [--profile NAME | --repo DIR]
|
|
5
|
+
provider add jev|clef --name N [--url U] [--account-id A] [--model M] [--context N]
|
|
6
|
+
[--price X] [--deadline S] [--local] [--key-stdin | --key-env VAR]
|
|
7
|
+
provider list [--json]
|
|
8
|
+
provider rm N
|
|
9
|
+
budget [--run tokens=N,usd=X] [--daily tokens=N,usd=X] [--repo DIR]
|
|
10
|
+
privacy never-send|allow --repo DIR
|
|
11
|
+
doctor [--live] [--json] [--repo DIR]
|
|
12
|
+
migrate [--force] [--json]
|
|
13
|
+
report [--runs N] [--run DIR]... [--site S] [--all] [--json]
|
|
14
|
+
replay --site S --provider P --model M [--runs N] [--send] [--workers 3] [--seed 7]
|
|
15
|
+
[--margin 0.02] [--json]
|
|
16
|
+
|
|
17
|
+
`report` sums each site's jev.jsonl calls, cache hits, skips, tokens and cost over the newest
|
|
18
|
+
N (default 10) registered runs of the repo (--all: of every repo; --run: those dirs), with how
|
|
19
|
+
often it fired and was right on the dataset's free labels (forge_decide.report). Its --json
|
|
20
|
+
is {runs: [{dir, uid}], skipped_runs, sites: {site: {...}}, totals: {...}}; keys are stable.
|
|
21
|
+
|
|
22
|
+
`replay` re-asks the site's labelled live requests from the dataset on provider P (a user
|
|
23
|
+
provider, else the legacy typesafe/cloudflare transport) with model M (forge_decide.replay).
|
|
24
|
+
Without --send it only prints the count, estimated input tokens and cost. With --send it asks
|
|
25
|
+
the unanswered ones, outside any budget, then judges replay, baseline and live answers on the
|
|
26
|
+
newer half of the runs and records the result in replays/<gate>.json, which `gate on` reads.
|
|
27
|
+
Its --json is the dry run's estimate, or the evaluation (also `sent`). An unknown provider is
|
|
28
|
+
exit 2, a provider with no key that is not local exit 1.
|
|
29
|
+
|
|
30
|
+
`gate G on` is the promotion rule: it writes `on` only when replays/<gate>.json holds a
|
|
31
|
+
passing replay for the provider and model the gate resolves to once written (providers.identity
|
|
32
|
+
of the resolved gate, so a provider or model inherited from another level counts). Otherwise it
|
|
33
|
+
writes nothing, not even the jev.json migration, and exits 3, naming the replay command to run; --force writes it
|
|
34
|
+
anyway with "force": true. Writing off or shadow, or `on` with a passing replay, drops `force`.
|
|
35
|
+
|
|
36
|
+
Every subcommand works offline and with no key, except `doctor --live`. Exit codes: 0 ok,
|
|
37
|
+
2 usage or invalid input, 1 a failed check (doctor) or a config file that cannot be read,
|
|
38
|
+
3 refused (`gate on` with no passing replay and no --force).
|
|
39
|
+
--repo defaults to FORGE_DECIDE_REPO, else the git top level of the working directory.
|
|
40
|
+
|
|
41
|
+
Commands that write the user file (`gate` without --repo, `provider`, `budget` without
|
|
42
|
+
--repo, `migrate`) first run the one-time migration from jev.json, so a legacy config is
|
|
43
|
+
never dropped. `status` and `doctor` never write.
|
|
44
|
+
|
|
45
|
+
A key is never an argument: `provider add` reads it from stdin (--key-stdin, one line, into
|
|
46
|
+
keys/<N>.key mode 0600), names a variable (--key-env, only the name is stored) or prompts on
|
|
47
|
+
a terminal. No output of this command holds a key; providers show `key: present|missing`.
|
|
48
|
+
|
|
49
|
+
`status --json` is forge-ui's data source; its shape is stable:
|
|
50
|
+
|
|
51
|
+
{"repo": str | null, the repo whose settings apply
|
|
52
|
+
"user_path": str, "repo_path": str | null,
|
|
53
|
+
"migrated": bool, decide.json exists (jev.json is no longer read)
|
|
54
|
+
"legacy": bool, jev.json exists
|
|
55
|
+
"profile": str | null,
|
|
56
|
+
"gates": {"<gate>": {"mode": "off"|"shadow"|"on", "source": "default"|"legacy"|"repo"|
|
|
57
|
+
"user"|"profile"|"env"|"flags", "provider": str | null,
|
|
58
|
+
"model": str | null, "skip": null|"privacy"|"kill", "site": str,
|
|
59
|
+
"replay": {"provider", "model", "passes": bool, "at": epoch} | null,
|
|
60
|
+
"forced": bool}},
|
|
61
|
+
"providers": {"<name>": {"type", "url", "model", "local": bool,
|
|
62
|
+
"key": "present"|"missing", "key_source": "file"|"env"|null,
|
|
63
|
+
"context", "price_usd_per_mtok", "deadline_s"}},
|
|
64
|
+
"budget": {"caps": {"run_tokens", "run_usd", "daily_tokens", "daily_usd"},
|
|
65
|
+
"spend": {"date": "YYYY-MM-DD", "today": {"tokens", "usd"},
|
|
66
|
+
"run": {"tokens", "usd"} | null}},
|
|
67
|
+
"privacy": {"floor": bool, "path": str | null},
|
|
68
|
+
"shadowed": [{"key", "repo", "user"}],
|
|
69
|
+
"errors": [str]}
|
|
70
|
+
|
|
71
|
+
A gate's `replay` is the recorded replay for the provider and model it would use (null: none);
|
|
72
|
+
`forced` is true when its mode is `on` and that replay is missing or does not pass, whatever
|
|
73
|
+
level turned it on. The run spend is filled when FORGE_DECIDE_RUN_DIR is set. New keys may be added; none of
|
|
74
|
+
these is removed or changes meaning.
|
|
75
|
+
"""
|
|
76
|
+
from __future__ import annotations
|
|
77
|
+
|
|
78
|
+
import argparse
|
|
79
|
+
import copy
|
|
80
|
+
import getpass
|
|
81
|
+
import json
|
|
82
|
+
import os
|
|
83
|
+
from pathlib import Path
|
|
84
|
+
import re
|
|
85
|
+
import sys
|
|
86
|
+
import tempfile
|
|
87
|
+
import time
|
|
88
|
+
|
|
89
|
+
from . import (GATE_SITE, GATES, MODES, PROVIDER_TYPES, config_dir, load_repo, load_user,
|
|
90
|
+
repo_path, save_repo, save_user, user_path)
|
|
91
|
+
from . import budget as budget_module
|
|
92
|
+
from . import doctor as doctor_module
|
|
93
|
+
from . import migrate as migrate_module
|
|
94
|
+
from . import providers as providers_module
|
|
95
|
+
from .resolve import PRIVACY_FLOOR, resolve
|
|
96
|
+
|
|
97
|
+
ADVICE_KINDS = ('threshold-override', 'shadowed', 'privacy-floor')
|
|
98
|
+
NAME = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$')
|
|
99
|
+
ENV_NAME = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
|
|
100
|
+
JEV_MODEL = 'jev-latest'
|
|
101
|
+
CLEF_MODEL = 'clef'
|
|
102
|
+
NO_KEY_ARG = ('forge decide: a key is never accepted as an argument (it would land in shell '
|
|
103
|
+
'history and process listings); use --key-stdin or --key-env VAR')
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class Usage(Exception):
|
|
107
|
+
"""Invalid input: exit 2."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class Failed(Exception):
|
|
111
|
+
"""A config file that cannot be read safely, or another failure: exit 1."""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class Refused(Exception):
|
|
115
|
+
"""A gate turned `on` without a passing replay or --force: exit 3."""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _err(message: str) -> None:
|
|
119
|
+
print('forge decide: ' + message, file=sys.stderr)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ------------------------------------------------------------------------------- reading
|
|
123
|
+
|
|
124
|
+
def _repo(arg):
|
|
125
|
+
"""--repo as an absolute directory; without it, find_repo()'s answer (or None)."""
|
|
126
|
+
if arg is None:
|
|
127
|
+
found = providers_module.find_repo(None)
|
|
128
|
+
return os.path.abspath(found) if found else None
|
|
129
|
+
if not os.path.isdir(arg):
|
|
130
|
+
raise Usage(f'--repo {arg} is not a directory')
|
|
131
|
+
return os.path.abspath(arg)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _key_info(entry: dict) -> tuple[str, str | None]:
|
|
135
|
+
"""('present'|'missing', 'file'|'env'|None). The key is read to test it, never kept."""
|
|
136
|
+
present = bool(providers_module._key(entry))
|
|
137
|
+
source = 'env' if isinstance(entry.get('key_env'), str) and entry.get('key_env') else \
|
|
138
|
+
'file' if isinstance(entry.get('key_file'), str) and entry.get('key_file') else None
|
|
139
|
+
return ('present' if present else 'missing'), source
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _provider_rows(user: dict) -> dict:
|
|
143
|
+
stored = user.get('providers')
|
|
144
|
+
stored = stored if isinstance(stored, dict) else {}
|
|
145
|
+
out = {}
|
|
146
|
+
for name in sorted(stored):
|
|
147
|
+
entry = stored[name] if isinstance(stored[name], dict) else {}
|
|
148
|
+
key, source = _key_info(entry)
|
|
149
|
+
out[name] = dict(type=entry.get('type'), url=entry.get('url'), model=entry.get('model'),
|
|
150
|
+
local=entry.get('local') is True, key=key, key_source=source,
|
|
151
|
+
context=entry.get('context'),
|
|
152
|
+
price_usd_per_mtok=entry.get('price_usd_per_mtok'),
|
|
153
|
+
deadline_s=entry.get('deadline_s'))
|
|
154
|
+
return out
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _legacy_exists() -> bool:
|
|
158
|
+
import forge_jev
|
|
159
|
+
return forge_jev.config_path().exists()
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _replay_row(name: str, gate: dict, config: dict, errors: list) -> dict | None:
|
|
163
|
+
"""The recorded replay of `gate`'s effective provider and model, as status shows it."""
|
|
164
|
+
from . import replay as replay_module
|
|
165
|
+
try:
|
|
166
|
+
provider, model = providers_module.identity(GATE_SITE[name], gate, config=config)
|
|
167
|
+
except Exception as error: # status never fails on a broken config
|
|
168
|
+
errors.append('%s: provider and model unknown (%r)' % (name, error))
|
|
169
|
+
return None
|
|
170
|
+
stored = replay_module.recorded(name, provider, model)
|
|
171
|
+
if stored is None:
|
|
172
|
+
return None
|
|
173
|
+
return dict(provider=provider, model=model, passes=stored.get('passes') is True, at=stored.get('at'))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def status_data(repo=None, *, profile=None) -> dict:
|
|
177
|
+
"""The `status --json` object (shape in the module docstring)."""
|
|
178
|
+
import forge_jev
|
|
179
|
+
resolved = resolve(repo, profile=profile)
|
|
180
|
+
user, _ = load_user()
|
|
181
|
+
caps = resolved['budget']
|
|
182
|
+
spend = budget_module.spend()
|
|
183
|
+
config = forge_jev.load_config()
|
|
184
|
+
gates = {}
|
|
185
|
+
for name, gate in resolved['gates'].items():
|
|
186
|
+
replay = _replay_row(name, gate, config, resolved['errors'])
|
|
187
|
+
gates[name] = dict(mode=gate['mode'], source=gate['source'], provider=gate['provider'],
|
|
188
|
+
model=gate['model'], skip=gate['skip'], site=GATE_SITE[name], replay=replay,
|
|
189
|
+
forced=gate['mode'] == 'on' and not (replay and replay['passes']))
|
|
190
|
+
privacy = resolved['privacy']
|
|
191
|
+
return dict(repo=repo, user_path=str(user_path()),
|
|
192
|
+
repo_path=str(repo_path(repo)) if repo is not None else None,
|
|
193
|
+
migrated=user_path().exists(), legacy=_legacy_exists(),
|
|
194
|
+
profile=resolved['profile'], gates=gates, providers=_provider_rows(user),
|
|
195
|
+
budget=dict(caps=caps, spend=spend),
|
|
196
|
+
privacy=dict(floor=privacy.get('floor') == PRIVACY_FLOOR, path=privacy.get('path')),
|
|
197
|
+
shadowed=resolved['shadowed'], errors=resolved['errors'])
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def config_block(repo=None) -> dict:
|
|
201
|
+
"""forge config show's `decide` block."""
|
|
202
|
+
data = status_data(repo)
|
|
203
|
+
return dict(path=data['user_path'], exists=data['migrated'], migrated=data['migrated'],
|
|
204
|
+
gates={name: gate['mode'] for name, gate in data['gates'].items()},
|
|
205
|
+
providers=sorted(data['providers']), privacy_floor=data['privacy']['floor'],
|
|
206
|
+
budget=data['budget']['caps'])
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _cap(value) -> str:
|
|
210
|
+
return 'none' if value is None else str(value)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _budget_lines(caps: dict, spend: dict) -> list:
|
|
214
|
+
today = spend['today']
|
|
215
|
+
lines = ['budget:',
|
|
216
|
+
' run: tokens %s, usd %s' % (_cap(caps.get('run_tokens')), _cap(caps.get('run_usd'))),
|
|
217
|
+
' daily: tokens %s, usd %s' % (_cap(caps.get('daily_tokens')), _cap(caps.get('daily_usd'))),
|
|
218
|
+
' today (%s): %d tokens of %s, $%.4f of %s'
|
|
219
|
+
% (spend['date'], today['tokens'], _cap(caps.get('daily_tokens')), today['usd'],
|
|
220
|
+
_cap(caps.get('daily_usd')))]
|
|
221
|
+
if spend.get('run') is not None:
|
|
222
|
+
run = spend['run']
|
|
223
|
+
lines.append(' this run: %d tokens of %s, $%.4f of %s'
|
|
224
|
+
% (run['tokens'], _cap(caps.get('run_tokens')), run['usd'], _cap(caps.get('run_usd'))))
|
|
225
|
+
return lines
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _provider_line(name: str, row: dict) -> str:
|
|
229
|
+
return ' %s: %s %s model %s%s, key %s%s' % (
|
|
230
|
+
name, row['type'], row['url'] or '(no url)', row['model'] or '(default)',
|
|
231
|
+
', local' if row['local'] else '', row['key'],
|
|
232
|
+
' (%s)' % row['key_source'] if row['key_source'] else '')
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _date(at) -> str:
|
|
236
|
+
if isinstance(at, bool) or not isinstance(at, (int, float)):
|
|
237
|
+
return '?'
|
|
238
|
+
try:
|
|
239
|
+
return time.strftime('%Y-%m-%d', time.localtime(at))
|
|
240
|
+
except (OverflowError, OSError, ValueError):
|
|
241
|
+
return '?'
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _gate_line(name: str, gate: dict) -> str:
|
|
245
|
+
extra = []
|
|
246
|
+
if gate['provider']:
|
|
247
|
+
extra.append('provider ' + gate['provider'])
|
|
248
|
+
if gate['model']:
|
|
249
|
+
extra.append('model ' + gate['model'])
|
|
250
|
+
if gate['skip']:
|
|
251
|
+
extra.append('skip ' + gate['skip'])
|
|
252
|
+
if gate['forced']:
|
|
253
|
+
extra.append('forced')
|
|
254
|
+
elif gate['replay'] and gate['replay']['passes']:
|
|
255
|
+
extra.append('replayed ' + _date(gate['replay']['at']))
|
|
256
|
+
return ' %-16s %-6s (%s)%s' % (name, gate['mode'], gate['source'],
|
|
257
|
+
(' ' + ', '.join(extra)) if extra else '')
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def cmd_status(args) -> int:
|
|
261
|
+
data = status_data(_repo(args.repo))
|
|
262
|
+
if args.json:
|
|
263
|
+
print(json.dumps(data, indent=2))
|
|
264
|
+
return 0
|
|
265
|
+
print('user config: %s (%s)' % (data['user_path'], 'present' if data['migrated'] else 'absent'))
|
|
266
|
+
if data['repo']:
|
|
267
|
+
print('repo: %s' % data['repo'])
|
|
268
|
+
print('migrated: %s' % ('yes' if data['migrated'] else
|
|
269
|
+
'no (jev.json is read; `forge decide migrate` moves it)' if data['legacy'] else 'no'))
|
|
270
|
+
print('profile: %s' % (data['profile'] or 'none'))
|
|
271
|
+
privacy = data['privacy']
|
|
272
|
+
print('privacy floor: %s' % (('yes (%s): every gate is off' % privacy['path']) if privacy['floor'] else 'no'))
|
|
273
|
+
print('gates:')
|
|
274
|
+
for name, gate in data['gates'].items():
|
|
275
|
+
print(_gate_line(name, gate))
|
|
276
|
+
print('providers:%s' % ('' if data['providers'] else ' none'))
|
|
277
|
+
for name, row in data['providers'].items():
|
|
278
|
+
print(_provider_line(name, row))
|
|
279
|
+
for line in _budget_lines(data['budget']['caps'], data['budget']['spend']):
|
|
280
|
+
print(line)
|
|
281
|
+
for entry in data['shadowed']:
|
|
282
|
+
print('shadowed: %s: the repo sets %r, the user file\'s %r wins' % (entry['key'], entry['repo'], entry['user']))
|
|
283
|
+
for error in data['errors']:
|
|
284
|
+
print('warning: ' + error)
|
|
285
|
+
return 0
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
# ------------------------------------------------------------------------------- writing
|
|
289
|
+
|
|
290
|
+
def _migrate_first() -> None:
|
|
291
|
+
"""The migration rule: run it before any write to the user file, so jev.json is never
|
|
292
|
+
silently dropped."""
|
|
293
|
+
result = migrate_module.run()
|
|
294
|
+
if result['status'] == 'migrated':
|
|
295
|
+
print('forge decide: migrated jev.json into %s first (providers: %s)'
|
|
296
|
+
% (user_path(), ', '.join(result['providers']) or 'none'), file=sys.stderr)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _user_for_write() -> dict:
|
|
300
|
+
_migrate_first()
|
|
301
|
+
data, error = load_user()
|
|
302
|
+
if error:
|
|
303
|
+
raise Failed(error + '; fix or remove it before changing settings')
|
|
304
|
+
return data
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _repo_for_write(repo: str) -> dict:
|
|
308
|
+
data, error = load_repo(repo)
|
|
309
|
+
if error:
|
|
310
|
+
raise Failed(error + '; fix or remove it before changing settings')
|
|
311
|
+
return data
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _section(data: dict, key: str) -> dict:
|
|
315
|
+
value = data.get(key)
|
|
316
|
+
if not isinstance(value, dict):
|
|
317
|
+
value = data[key] = {}
|
|
318
|
+
return value
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _user_providers() -> dict:
|
|
322
|
+
data, _ = load_user()
|
|
323
|
+
stored = data.get('providers')
|
|
324
|
+
return stored if isinstance(stored, dict) else {}
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _user_preview() -> dict:
|
|
328
|
+
"""The user decide.json a write would start from: the file, or, before migration, what
|
|
329
|
+
migrating jev.json would write. Writes nothing (a refused write must leave no trace)."""
|
|
330
|
+
if user_path().exists():
|
|
331
|
+
data, error = load_user()
|
|
332
|
+
if error:
|
|
333
|
+
raise Failed(error + '; fix or remove it before changing settings')
|
|
334
|
+
return data
|
|
335
|
+
return migrate_module.preview() or {}
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _gates_for(data: dict, args, repo) -> tuple[dict, str]:
|
|
339
|
+
"""(the `gates` object `gate` writes into, where that is, for the message)."""
|
|
340
|
+
if repo is not None:
|
|
341
|
+
return _section(data, 'gates'), str(repo_path(repo))
|
|
342
|
+
if args.profile is not None:
|
|
343
|
+
return (_section(_section(_section(data, 'profiles'), args.profile), 'gates'),
|
|
344
|
+
'%s profile %s' % (user_path(), args.profile))
|
|
345
|
+
return _section(data, 'gates'), str(user_path())
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _write_entry(gates: dict, args) -> dict:
|
|
349
|
+
"""Set the mode, provider and model of `args.gate` in `gates`; never a `force`."""
|
|
350
|
+
entry = gates.get(args.gate)
|
|
351
|
+
entry = dict(mode=entry) if isinstance(entry, str) else dict(entry) if isinstance(entry, dict) else {}
|
|
352
|
+
entry['mode'] = args.mode
|
|
353
|
+
if args.provider is not None:
|
|
354
|
+
entry['provider'] = args.provider
|
|
355
|
+
if args.model is not None:
|
|
356
|
+
entry['model'] = args.model
|
|
357
|
+
# Kept unknown keys must not carry an old force: only --force writes it.
|
|
358
|
+
entry.pop('force', None)
|
|
359
|
+
gates[args.gate] = entry
|
|
360
|
+
return entry
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _promotion(gate: str, settings: list, force: bool, providers: dict) -> str | None:
|
|
364
|
+
"""The promotion rule for `gate` turned `on`. `settings` are its resolved settings once
|
|
365
|
+
written (so a provider or model inherited from a lower level counts): the written level's
|
|
366
|
+
own, then the effective one when it acts. Each identity they name needs a passing replay;
|
|
367
|
+
why it may be ('replayed <date>' or 'forced'), else Refused."""
|
|
368
|
+
from . import replay as replay_module
|
|
369
|
+
site = GATE_SITE[gate]
|
|
370
|
+
seen, passing = [], None
|
|
371
|
+
for setting in settings:
|
|
372
|
+
provider, model = providers_module.identity(site, setting, providers=providers, env={})
|
|
373
|
+
if (provider, model) in seen:
|
|
374
|
+
continue
|
|
375
|
+
seen.append((provider, model))
|
|
376
|
+
stored = replay_module.recorded(gate, provider, model)
|
|
377
|
+
if stored is not None and stored.get('passes') is True:
|
|
378
|
+
passing = passing or 'replayed %s on %s/%s' % (_date(stored.get('at')), provider, model)
|
|
379
|
+
continue
|
|
380
|
+
if force:
|
|
381
|
+
return 'forced: no passing replay on %s/%s' % (provider, model)
|
|
382
|
+
why = ('no replay is recorded for it' if stored is None else
|
|
383
|
+
'its replay of %s does not pass: %s' % (_date(stored.get('at')), stored.get('reason') or 'no reason recorded'))
|
|
384
|
+
raise Refused('%s on refused: provider %s, model %s: %s.\n'
|
|
385
|
+
'Run `forge decide replay --site %s --provider %s --model %s --send`, '
|
|
386
|
+
'or turn it on anyway with --force (shown as forced).'
|
|
387
|
+
% (gate, provider, model, why, site, provider, model))
|
|
388
|
+
return passing
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def cmd_gate(args) -> int:
|
|
392
|
+
if args.profile is not None and args.repo is not None:
|
|
393
|
+
raise Usage('--profile and --repo are exclusive')
|
|
394
|
+
if args.force and args.mode != 'on':
|
|
395
|
+
raise Usage('--force only applies to `on`')
|
|
396
|
+
repo = _repo(args.repo) if args.repo is not None else None
|
|
397
|
+
# Everything is checked on the files as they would be written, before anything is: a
|
|
398
|
+
# refused `on` writes nothing, not even the migration.
|
|
399
|
+
if repo is not None:
|
|
400
|
+
data = _repo_for_write(repo)
|
|
401
|
+
configured = _user_providers()
|
|
402
|
+
else:
|
|
403
|
+
data = _user_preview()
|
|
404
|
+
configured = data.get('providers') if isinstance(data.get('providers'), dict) else {}
|
|
405
|
+
if args.provider is not None and args.provider not in configured:
|
|
406
|
+
# A legacy provider exists only once migrated; a --repo write never touches the user
|
|
407
|
+
# file, so there it has to be migrated already.
|
|
408
|
+
raise Usage('unknown provider %r; configured: %s (add one with `forge decide provider add`)'
|
|
409
|
+
% (args.provider, ', '.join(sorted(configured)) or 'none'))
|
|
410
|
+
gates, where = _gates_for(data, args, repo)
|
|
411
|
+
entry = _write_entry(gates, args)
|
|
412
|
+
effective_repo = repo if repo is not None else _repo(None)
|
|
413
|
+
promotion = None
|
|
414
|
+
if args.mode == 'on':
|
|
415
|
+
# The written level on its own (lower levels under it, nothing above): what acts once
|
|
416
|
+
# a profile or env override above it goes away. Then what acts now, if it does.
|
|
417
|
+
written = dict(repo_data=data) if repo is not None else dict(user_data=data)
|
|
418
|
+
alone = dict(repo_data=data, user_data={}) if repo is not None else dict(user_data=data)
|
|
419
|
+
settings = [resolve(effective_repo, profile=args.profile, env={}, **alone)['gates'][args.gate]]
|
|
420
|
+
effective = resolve(effective_repo, profile=args.profile, **written)['gates'][args.gate]
|
|
421
|
+
if effective['mode'] == 'on':
|
|
422
|
+
settings.append(effective)
|
|
423
|
+
promotion = _promotion(args.gate, settings, args.force, configured)
|
|
424
|
+
if repo is None and not user_path().exists():
|
|
425
|
+
# Allowed: migrate for real (key files too), then write the entry into the result.
|
|
426
|
+
data = _user_for_write()
|
|
427
|
+
gates, where = _gates_for(data, args, None)
|
|
428
|
+
entry = _write_entry(gates, args)
|
|
429
|
+
if args.force:
|
|
430
|
+
entry['force'] = True
|
|
431
|
+
if repo is not None:
|
|
432
|
+
save_repo(repo, data)
|
|
433
|
+
else:
|
|
434
|
+
data.setdefault('version', 1)
|
|
435
|
+
save_user(data)
|
|
436
|
+
|
|
437
|
+
resolved = resolve(effective_repo, profile=args.profile)
|
|
438
|
+
gate = resolved['gates'][args.gate]
|
|
439
|
+
print('%s: %s written to %s' % (args.gate, args.mode, where))
|
|
440
|
+
if promotion:
|
|
441
|
+
print(promotion)
|
|
442
|
+
print('effective: %s (source %s)%s' % (gate['mode'], gate['source'],
|
|
443
|
+
', skip ' + gate['skip'] if gate['skip'] else ''))
|
|
444
|
+
if gate['skip'] == 'privacy':
|
|
445
|
+
print('note: the privacy floor of %s keeps every gate off' % resolved['privacy']['path'])
|
|
446
|
+
elif gate['skip'] == 'kill':
|
|
447
|
+
print('note: FORGE_JEV=off keeps every gate off')
|
|
448
|
+
elif gate['mode'] != args.mode:
|
|
449
|
+
print('note: the %s level overrides what was written' % gate['source'])
|
|
450
|
+
for item in resolved['shadowed']:
|
|
451
|
+
if item['key'].startswith('gates.%s.' % args.gate):
|
|
452
|
+
print('note: %s: the user file\'s %r wins over the repo\'s %r'
|
|
453
|
+
% (item['key'], item['user'], item['repo']))
|
|
454
|
+
return 0
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _read_stdin_key() -> str:
|
|
458
|
+
line = sys.stdin.readline()
|
|
459
|
+
key = line.strip()
|
|
460
|
+
if not key:
|
|
461
|
+
raise Usage('--key-stdin: no key on stdin')
|
|
462
|
+
return key
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _prompt_key(label: str) -> str | None:
|
|
466
|
+
"""getpass on the controlling terminal; None when there is none (a background run must
|
|
467
|
+
never block on a prompt)."""
|
|
468
|
+
try:
|
|
469
|
+
tty = open('/dev/tty', 'r')
|
|
470
|
+
except OSError:
|
|
471
|
+
return None
|
|
472
|
+
try:
|
|
473
|
+
if not os.isatty(tty.fileno()):
|
|
474
|
+
return None
|
|
475
|
+
finally:
|
|
476
|
+
tty.close()
|
|
477
|
+
return getpass.getpass('%s key (empty for none): ' % label, stream=sys.stderr) or None
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _own_key_file(name: str) -> Path:
|
|
481
|
+
return config_dir() / migrate_module.KEYS_DIR / f'{name}.key'
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _drop_own_key(name: str, entry: dict) -> None:
|
|
485
|
+
"""Delete keys/<name>.key when the entry points at it; a key file elsewhere (a migrated
|
|
486
|
+
cloudflare.env) is the user's and stays."""
|
|
487
|
+
key_file = entry.get('key_file')
|
|
488
|
+
if not isinstance(key_file, str) or not key_file:
|
|
489
|
+
return
|
|
490
|
+
path = Path(key_file).expanduser()
|
|
491
|
+
path = path if path.is_absolute() else config_dir() / path
|
|
492
|
+
if os.path.abspath(path) == os.path.abspath(_own_key_file(name)):
|
|
493
|
+
try:
|
|
494
|
+
path.unlink()
|
|
495
|
+
except FileNotFoundError:
|
|
496
|
+
pass
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def cmd_provider_add(args) -> int:
|
|
500
|
+
name = args.name
|
|
501
|
+
if not NAME.match(name):
|
|
502
|
+
raise Usage('--name %r: use letters, digits, `.`, `_` and `-` (up to 64), starting with a letter or digit'
|
|
503
|
+
% name)
|
|
504
|
+
if args.key_env is not None and not ENV_NAME.match(args.key_env):
|
|
505
|
+
raise Usage('--key-env %r is not a variable name' % args.key_env)
|
|
506
|
+
for flag, value in (('--context', args.context), ('--price', args.price), ('--deadline', args.deadline)):
|
|
507
|
+
# Not just `> 0`: inf passes that, and json.dumps would write Infinity, which is not JSON.
|
|
508
|
+
if value is not None and not 0 < value < float('inf'):
|
|
509
|
+
raise Usage('%s must be a finite number above zero' % flag)
|
|
510
|
+
if args.type == 'jev':
|
|
511
|
+
url = args.url or (None if args.local else _jev_endpoint())
|
|
512
|
+
model = args.model or JEV_MODEL
|
|
513
|
+
else:
|
|
514
|
+
if args.url:
|
|
515
|
+
url = args.url
|
|
516
|
+
else:
|
|
517
|
+
account = args.account_id or os.environ.get('CLOUDFLARE_ACCOUNT_ID')
|
|
518
|
+
if not account:
|
|
519
|
+
raise Usage('clef needs --url, or --account-id (else CLOUDFLARE_ACCOUNT_ID) for the hosted URL')
|
|
520
|
+
url = _clef_url().replace('{account}', account)
|
|
521
|
+
model = args.model or CLEF_MODEL
|
|
522
|
+
if args.local and not args.url:
|
|
523
|
+
raise Usage('--local needs --url: a local provider has no default address')
|
|
524
|
+
secret = _read_stdin_key() if args.key_stdin else None
|
|
525
|
+
|
|
526
|
+
data = _user_for_write()
|
|
527
|
+
providers = _section(data, 'providers')
|
|
528
|
+
old = providers.get(name) if isinstance(providers.get(name), dict) else {}
|
|
529
|
+
entry = dict(type=args.type, url=url, model=model, local=bool(args.local))
|
|
530
|
+
for field, value in (('context', args.context), ('price_usd_per_mtok', args.price),
|
|
531
|
+
('deadline_s', args.deadline)):
|
|
532
|
+
if value is not None:
|
|
533
|
+
entry[field] = value
|
|
534
|
+
if secret is None and args.key_env is None and not args.local:
|
|
535
|
+
secret = _prompt_key(name)
|
|
536
|
+
if secret is not None:
|
|
537
|
+
migrate_module._write_key(name, secret)
|
|
538
|
+
entry['key_file'] = f'{migrate_module.KEYS_DIR}/{name}.key'
|
|
539
|
+
elif args.key_env is not None:
|
|
540
|
+
entry['key_env'] = args.key_env
|
|
541
|
+
_drop_own_key(name, old)
|
|
542
|
+
else:
|
|
543
|
+
# Re-adding a provider without a new key keeps the key it already has.
|
|
544
|
+
for field in ('key_file', 'key_env'):
|
|
545
|
+
if old.get(field):
|
|
546
|
+
entry[field] = old[field]
|
|
547
|
+
providers[name] = entry
|
|
548
|
+
data.setdefault('version', 1)
|
|
549
|
+
save_user(data)
|
|
550
|
+
key, source = _key_info(entry)
|
|
551
|
+
print('provider %s: %s %s model %s, key %s%s' % (name, args.type, url, model, key,
|
|
552
|
+
' (%s)' % source if source else ''))
|
|
553
|
+
if key == 'missing' and not args.local:
|
|
554
|
+
print('forge decide: provider %s has no key yet; add one with --key-stdin or --key-env VAR' % name,
|
|
555
|
+
file=sys.stderr)
|
|
556
|
+
return 0
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def _jev_endpoint() -> str:
|
|
560
|
+
import forge_jev
|
|
561
|
+
return forge_jev.ENDPOINT
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def _clef_url() -> str:
|
|
565
|
+
import forge_jev
|
|
566
|
+
return forge_jev.CLOUDFLARE_URL
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def cmd_provider_list(args) -> int:
|
|
570
|
+
rows = _provider_rows(load_user()[0])
|
|
571
|
+
if args.json:
|
|
572
|
+
print(json.dumps(rows, indent=2))
|
|
573
|
+
return 0
|
|
574
|
+
if not rows:
|
|
575
|
+
print('no providers (add one with `forge decide provider add jev|clef --name N`)')
|
|
576
|
+
for name, row in rows.items():
|
|
577
|
+
print(_provider_line(name, row).strip())
|
|
578
|
+
return 0
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _gates_using(data: dict, name: str, label: str) -> list:
|
|
582
|
+
out = []
|
|
583
|
+
bodies = [('', data)]
|
|
584
|
+
profiles = data.get('profiles')
|
|
585
|
+
if isinstance(profiles, dict):
|
|
586
|
+
bodies += [('profile %s ' % p, body) for p, body in sorted(profiles.items()) if isinstance(body, dict)]
|
|
587
|
+
for prefix, body in bodies:
|
|
588
|
+
gates = body.get('gates')
|
|
589
|
+
if not isinstance(gates, dict):
|
|
590
|
+
continue
|
|
591
|
+
for gate, entry in gates.items():
|
|
592
|
+
if isinstance(entry, dict) and entry.get('provider') == name:
|
|
593
|
+
out.append('%s %s%s' % (label, prefix, gate))
|
|
594
|
+
return out
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def cmd_provider_rm(args) -> int:
|
|
598
|
+
data = _user_for_write()
|
|
599
|
+
providers = _section(data, 'providers')
|
|
600
|
+
if args.name not in providers:
|
|
601
|
+
raise Usage('unknown provider %r; configured: %s' % (args.name, ', '.join(sorted(providers)) or 'none'))
|
|
602
|
+
using = _gates_using(data, args.name, 'user')
|
|
603
|
+
repo = _repo(None)
|
|
604
|
+
if repo is not None:
|
|
605
|
+
using += _gates_using(load_repo(repo)[0], args.name, 'repo %s' % repo)
|
|
606
|
+
if using:
|
|
607
|
+
raise Usage('provider %s is used by: %s; move those gates off it first' % (args.name, ', '.join(using)))
|
|
608
|
+
entry = providers.pop(args.name)
|
|
609
|
+
save_user(data)
|
|
610
|
+
_drop_own_key(args.name, entry if isinstance(entry, dict) else {})
|
|
611
|
+
print('provider %s removed' % args.name)
|
|
612
|
+
return 0
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _parse_caps(text: str, scope: str) -> dict:
|
|
616
|
+
"""'tokens=N,usd=X' -> {scope_tokens: N, scope_usd: X}; `none` (whole or per value) clears."""
|
|
617
|
+
if text.strip() == 'none':
|
|
618
|
+
return {f'{scope}_tokens': None, f'{scope}_usd': None}
|
|
619
|
+
out = {}
|
|
620
|
+
for part in text.split(','):
|
|
621
|
+
field, sep, value = part.strip().partition('=')
|
|
622
|
+
if not sep or field not in ('tokens', 'usd'):
|
|
623
|
+
raise Usage('--%s expects tokens=N,usd=X (or none); got %r' % (scope, part))
|
|
624
|
+
value = value.strip()
|
|
625
|
+
if value == 'none':
|
|
626
|
+
out[f'{scope}_{field}'] = None
|
|
627
|
+
continue
|
|
628
|
+
try:
|
|
629
|
+
number = int(value) if field == 'tokens' else float(value)
|
|
630
|
+
except ValueError:
|
|
631
|
+
raise Usage('--%s %s=%r is not a %s' % (scope, field, value,
|
|
632
|
+
'whole number' if field == 'tokens' else 'number'))
|
|
633
|
+
if not number >= 0 or number == float('inf'):
|
|
634
|
+
raise Usage('--%s %s must be a finite number >= 0' % (scope, field))
|
|
635
|
+
out[f'{scope}_{field}'] = number
|
|
636
|
+
return out
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def cmd_budget(args) -> int:
|
|
640
|
+
if args.daily is not None and args.repo is not None:
|
|
641
|
+
raise Usage('--daily is user-level only; drop --repo (a repo file sets only --run)')
|
|
642
|
+
repo = _repo(args.repo) if args.repo is not None else None
|
|
643
|
+
changes = {}
|
|
644
|
+
if args.run is not None:
|
|
645
|
+
changes.update(_parse_caps(args.run, 'run'))
|
|
646
|
+
if args.daily is not None:
|
|
647
|
+
changes.update(_parse_caps(args.daily, 'daily'))
|
|
648
|
+
if changes:
|
|
649
|
+
data = _repo_for_write(repo) if repo is not None else _user_for_write()
|
|
650
|
+
stored = _section(data, 'budget')
|
|
651
|
+
for key, value in changes.items():
|
|
652
|
+
if value is None:
|
|
653
|
+
stored.pop(key, None)
|
|
654
|
+
else:
|
|
655
|
+
stored[key] = value
|
|
656
|
+
if repo is not None:
|
|
657
|
+
save_repo(repo, data)
|
|
658
|
+
else:
|
|
659
|
+
data.setdefault('version', 1)
|
|
660
|
+
save_user(data)
|
|
661
|
+
resolved = resolve(repo if repo is not None else _repo(None))
|
|
662
|
+
for line in _budget_lines(resolved['budget'], budget_module.spend()):
|
|
663
|
+
print(line)
|
|
664
|
+
return 0
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def cmd_privacy(args) -> int:
|
|
668
|
+
repo = _repo(args.repo)
|
|
669
|
+
data = _repo_for_write(repo)
|
|
670
|
+
if args.setting == 'never-send':
|
|
671
|
+
data['privacy'] = PRIVACY_FLOOR
|
|
672
|
+
save_repo(repo, data)
|
|
673
|
+
print('privacy floor on for %s: no decision-model request leaves this repo' % repo)
|
|
674
|
+
else:
|
|
675
|
+
if 'privacy' in data:
|
|
676
|
+
data.pop('privacy')
|
|
677
|
+
save_repo(repo, data)
|
|
678
|
+
print('privacy floor off for %s' % repo)
|
|
679
|
+
return 0
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
# ------------------------------------------------------------------------- doctor / migrate
|
|
683
|
+
|
|
684
|
+
def _live_probe(name: str, repo) -> tuple[bool, str | None]:
|
|
685
|
+
"""One fixed, synthetic request (no repo data) to provider `name`, through its transport:
|
|
686
|
+
ask() for the drift site, with the drift gate pointed at `name`. Not a judgment, so
|
|
687
|
+
client._dataset is silenced for the call: the setup-probe site is skipped there too, but it
|
|
688
|
+
cannot name a provider."""
|
|
689
|
+
from forge_jev import client, questions
|
|
690
|
+
real = resolve(repo)
|
|
691
|
+
fake = copy.deepcopy(real)
|
|
692
|
+
fake['gates']['drift'].update(provider=name, model=None)
|
|
693
|
+
original, original_dataset = client._resolve, client._dataset
|
|
694
|
+
client._resolve = lambda _repo=None, **_: fake
|
|
695
|
+
client._dataset = lambda *_, **__: None
|
|
696
|
+
try:
|
|
697
|
+
with tempfile.TemporaryDirectory() as run_dir:
|
|
698
|
+
result = client.ask(questions.PROBE_STATE, questions.PROBE, site=GATE_SITE['drift'],
|
|
699
|
+
run_dir=run_dir, repo=repo)
|
|
700
|
+
if result is not None:
|
|
701
|
+
return True, None
|
|
702
|
+
reason = None
|
|
703
|
+
log = Path(run_dir) / 'jev.jsonl'
|
|
704
|
+
if log.exists():
|
|
705
|
+
lines = log.read_text().splitlines()
|
|
706
|
+
if lines:
|
|
707
|
+
reason = json.loads(lines[-1]).get('reason')
|
|
708
|
+
return False, reason or 'no answer'
|
|
709
|
+
finally:
|
|
710
|
+
client._resolve = original
|
|
711
|
+
client._dataset = original_dataset
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def cmd_doctor(args) -> int:
|
|
715
|
+
repo = _repo(args.repo)
|
|
716
|
+
items = doctor_module.checks(repo)
|
|
717
|
+
problems = [item for item in items if item['kind'] not in ADVICE_KINDS]
|
|
718
|
+
live = []
|
|
719
|
+
live_note = None
|
|
720
|
+
if args.live:
|
|
721
|
+
if repo is not None and providers_module.privacy_floor(repo):
|
|
722
|
+
live_note = 'live probes skipped: the privacy floor of %s' % repo_path(repo)
|
|
723
|
+
else:
|
|
724
|
+
for name in sorted(_user_providers()):
|
|
725
|
+
ok, reason = _live_probe(name, repo)
|
|
726
|
+
live.append(dict(provider=name, ok=ok, reason=reason))
|
|
727
|
+
ok = not problems and all(probe['ok'] for probe in live)
|
|
728
|
+
if args.json:
|
|
729
|
+
print(json.dumps(dict(ok=ok, items=items, live=live if args.live else None,
|
|
730
|
+
live_note=live_note), indent=2))
|
|
731
|
+
else:
|
|
732
|
+
for item in items:
|
|
733
|
+
print('[%s] %s: %s' % ('advice' if item['kind'] in ADVICE_KINDS else 'problem', item['kind'],
|
|
734
|
+
item['message']))
|
|
735
|
+
if args.live:
|
|
736
|
+
if live_note:
|
|
737
|
+
print(live_note)
|
|
738
|
+
elif not live:
|
|
739
|
+
print('live: no providers configured')
|
|
740
|
+
for probe in live:
|
|
741
|
+
print('[%s] live probe %s%s' % ('ok' if probe['ok'] else 'FAIL', probe['provider'],
|
|
742
|
+
': ' + probe['reason'] if probe['reason'] else ''))
|
|
743
|
+
print('ok' if ok else 'problems found')
|
|
744
|
+
return 0 if ok else 1
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def cmd_migrate(args) -> int:
|
|
748
|
+
result = migrate_module.run(force=args.force)
|
|
749
|
+
if args.json:
|
|
750
|
+
print(json.dumps(result, indent=2))
|
|
751
|
+
elif result['status'] == 'exists':
|
|
752
|
+
print('%s already exists; nothing changed (--force migrates jev.json again)' % user_path())
|
|
753
|
+
elif result['status'] == 'nothing':
|
|
754
|
+
print('no jev.json and no Cloudflare token: nothing to migrate')
|
|
755
|
+
else:
|
|
756
|
+
print('migrated jev.json into %s' % user_path())
|
|
757
|
+
print('providers: %s' % (', '.join(result['providers']) or 'none'))
|
|
758
|
+
for gate, entry in result['gates'].items():
|
|
759
|
+
parts = ['mode ' + entry['mode']] if entry.get('mode') else []
|
|
760
|
+
if entry.get('provider'):
|
|
761
|
+
parts.append('provider ' + entry['provider'])
|
|
762
|
+
if entry.get('thresholds'):
|
|
763
|
+
parts.append('thresholds ' + ', '.join(sorted(entry['thresholds'])))
|
|
764
|
+
print(' %s: %s' % (gate, ', '.join(parts) or 'defaults'))
|
|
765
|
+
return 0
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def cmd_report(args) -> int:
|
|
769
|
+
from . import report as report_module
|
|
770
|
+
if args.runs is not None and args.runs < 1:
|
|
771
|
+
raise Usage('--runs must be at least 1')
|
|
772
|
+
if args.run and (args.all or args.runs is not None):
|
|
773
|
+
raise Usage('--run names the runs itself; drop --all and --runs')
|
|
774
|
+
repo = _repo(None)
|
|
775
|
+
if not args.run and not args.all and repo is None:
|
|
776
|
+
raise Usage('not inside a git repo: run it from one, or use --run DIR or --all')
|
|
777
|
+
dirs, missing = report_module.collect_runs(repo=repo, dirs=args.run or (), every=args.all,
|
|
778
|
+
limit=args.runs or report_module.DEFAULT_RUNS)
|
|
779
|
+
summary = report_module.summarize(dirs, repo=repo, site=args.site)
|
|
780
|
+
data = dict(runs=summary['runs'], skipped_runs=missing, sites=summary['sites'], totals=summary['totals'])
|
|
781
|
+
if args.json:
|
|
782
|
+
print(json.dumps(data, indent=2))
|
|
783
|
+
else:
|
|
784
|
+
print(report_module.render(data))
|
|
785
|
+
return 0
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def cmd_replay(args) -> int:
|
|
789
|
+
from . import replay as replay_module
|
|
790
|
+
from . import sites as sites_module
|
|
791
|
+
record = sites_module.site(args.site)
|
|
792
|
+
if record is None:
|
|
793
|
+
raise Usage('unknown site %s (one of: %s)' % (args.site, ', '.join(sorted(sites_module.SITES))))
|
|
794
|
+
if record.label is None:
|
|
795
|
+
raise Usage('%s has no free label yet (%s): nothing to judge a replay on' % (args.site, record.label_issue))
|
|
796
|
+
if args.runs is not None and args.runs < 1:
|
|
797
|
+
raise Usage('--runs must be at least 1')
|
|
798
|
+
if args.workers < 1:
|
|
799
|
+
raise Usage('--workers must be at least 1')
|
|
800
|
+
if args.margin < 0:
|
|
801
|
+
raise Usage('--margin must not be negative')
|
|
802
|
+
try:
|
|
803
|
+
spec = providers_module.spec_for_provider(args.provider, args.model)
|
|
804
|
+
except KeyError as error:
|
|
805
|
+
raise Failed('the %s provider url cannot be formatted: stray brace %s' % (args.provider, error))
|
|
806
|
+
if spec is None:
|
|
807
|
+
raise Usage('unknown provider %s (configured: %s)' % (args.provider, ', '.join(providers_module.provider_names())))
|
|
808
|
+
if not spec['key'] and not spec['local']:
|
|
809
|
+
raise Failed('provider %s has no key (forge decide provider add ... --key-stdin, or its key_env)'
|
|
810
|
+
% args.provider)
|
|
811
|
+
plan = replay_module.plan(args.site, spec['name'], spec['model'], spec, runs=args.runs)
|
|
812
|
+
if not args.send:
|
|
813
|
+
data = replay_module.estimate(plan)
|
|
814
|
+
print(json.dumps(data, indent=2) if args.json else replay_module.render_estimate(data))
|
|
815
|
+
return 0
|
|
816
|
+
sent = replay_module.send_all(plan, workers=args.workers)
|
|
817
|
+
if not args.json:
|
|
818
|
+
failed = ', '.join('%s %d' % item for item in sorted(sent['failed'].items()))
|
|
819
|
+
print('sent %d, answered %d%s' % (sent['sent'], sent['answered'], ' (failed: %s)' % failed if failed else ''))
|
|
820
|
+
result = replay_module.evaluate(plan, seed=args.seed, margin=args.margin)
|
|
821
|
+
if result['judged']['decisions']:
|
|
822
|
+
result['recorded'] = str(replay_module.record(record.gate, result))
|
|
823
|
+
else:
|
|
824
|
+
result['recorded'] = None
|
|
825
|
+
result['sent'] = sent
|
|
826
|
+
if args.json:
|
|
827
|
+
print(json.dumps(result, indent=2))
|
|
828
|
+
else:
|
|
829
|
+
print(replay_module.render(result))
|
|
830
|
+
print('recorded in %s' % result['recorded'] if result['recorded']
|
|
831
|
+
else 'nothing judged yet: not recorded')
|
|
832
|
+
return 0
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
# ------------------------------------------------------------------------------- parser
|
|
836
|
+
|
|
837
|
+
def parser() -> argparse.ArgumentParser:
|
|
838
|
+
p = argparse.ArgumentParser(prog='forge decide', allow_abbrev=False,
|
|
839
|
+
description='Decision-model gates: status, gate, provider, budget, '
|
|
840
|
+
'privacy, doctor, migrate, report, replay')
|
|
841
|
+
sub = p.add_subparsers(dest='command', required=True)
|
|
842
|
+
|
|
843
|
+
s = sub.add_parser('status', allow_abbrev=False, help='what is on, and why')
|
|
844
|
+
s.add_argument('--repo')
|
|
845
|
+
s.add_argument('--json', action='store_true')
|
|
846
|
+
s.set_defaults(fn=cmd_status)
|
|
847
|
+
|
|
848
|
+
s = sub.add_parser('gate', allow_abbrev=False, help='set one gate off, shadow or on')
|
|
849
|
+
s.add_argument('gate', choices=GATES)
|
|
850
|
+
s.add_argument('mode', choices=MODES)
|
|
851
|
+
s.add_argument('--force', action='store_true',
|
|
852
|
+
help='turn it on without a passing replay (shown as forced)')
|
|
853
|
+
s.add_argument('--provider')
|
|
854
|
+
s.add_argument('--model')
|
|
855
|
+
s.add_argument('--profile')
|
|
856
|
+
s.add_argument('--repo')
|
|
857
|
+
s.set_defaults(fn=cmd_gate)
|
|
858
|
+
|
|
859
|
+
s = sub.add_parser('provider', allow_abbrev=False, help='add, list or remove a provider')
|
|
860
|
+
psub = s.add_subparsers(dest='action', required=True)
|
|
861
|
+
a = psub.add_parser('add', allow_abbrev=False)
|
|
862
|
+
a.add_argument('type', choices=PROVIDER_TYPES)
|
|
863
|
+
a.add_argument('--name', required=True)
|
|
864
|
+
a.add_argument('--url')
|
|
865
|
+
a.add_argument('--account-id', help='Cloudflare account id for clef (else CLOUDFLARE_ACCOUNT_ID)')
|
|
866
|
+
a.add_argument('--model')
|
|
867
|
+
a.add_argument('--context', type=int, help='context limit in tokens')
|
|
868
|
+
a.add_argument('--price', type=float, help='USD per million tokens')
|
|
869
|
+
a.add_argument('--deadline', type=float, help='seconds per request')
|
|
870
|
+
a.add_argument('--local', action='store_true', help='a local server: no key needed, costs nothing')
|
|
871
|
+
keys = a.add_mutually_exclusive_group()
|
|
872
|
+
keys.add_argument('--key-stdin', action='store_true', help='read the key from one line of stdin')
|
|
873
|
+
keys.add_argument('--key-env', metavar='VAR', help='read the key from this variable at request time')
|
|
874
|
+
a.set_defaults(fn=cmd_provider_add)
|
|
875
|
+
a = psub.add_parser('list', allow_abbrev=False)
|
|
876
|
+
a.add_argument('--json', action='store_true')
|
|
877
|
+
a.set_defaults(fn=cmd_provider_list)
|
|
878
|
+
a = psub.add_parser('rm', allow_abbrev=False)
|
|
879
|
+
a.add_argument('name')
|
|
880
|
+
a.set_defaults(fn=cmd_provider_rm)
|
|
881
|
+
|
|
882
|
+
s = sub.add_parser('budget', allow_abbrev=False, help='show or set the request caps')
|
|
883
|
+
s.add_argument('--run', metavar='tokens=N,usd=X')
|
|
884
|
+
s.add_argument('--daily', metavar='tokens=N,usd=X')
|
|
885
|
+
s.add_argument('--repo')
|
|
886
|
+
s.set_defaults(fn=cmd_budget)
|
|
887
|
+
|
|
888
|
+
s = sub.add_parser('privacy', allow_abbrev=False, help="set or remove a repo's privacy floor")
|
|
889
|
+
s.add_argument('setting', choices=('never-send', 'allow'))
|
|
890
|
+
s.add_argument('--repo', required=True)
|
|
891
|
+
s.set_defaults(fn=cmd_privacy)
|
|
892
|
+
|
|
893
|
+
s = sub.add_parser('doctor', allow_abbrev=False, help='stale or inconsistent settings')
|
|
894
|
+
s.add_argument('--live', action='store_true', help='also probe each provider')
|
|
895
|
+
s.add_argument('--json', action='store_true')
|
|
896
|
+
s.add_argument('--repo')
|
|
897
|
+
s.set_defaults(fn=cmd_doctor)
|
|
898
|
+
|
|
899
|
+
s = sub.add_parser('migrate', allow_abbrev=False, help='move jev.json into decide.json, once')
|
|
900
|
+
s.add_argument('--force', action='store_true')
|
|
901
|
+
s.add_argument('--json', action='store_true')
|
|
902
|
+
s.set_defaults(fn=cmd_migrate)
|
|
903
|
+
|
|
904
|
+
s = sub.add_parser('report', allow_abbrev=False, help='calls, tokens, cost and hit rate per site')
|
|
905
|
+
s.add_argument('--runs', type=int, metavar='N', help='the newest N registered runs (default 10)')
|
|
906
|
+
s.add_argument('--run', action='append', metavar='DIR', help='read this run dir (repeatable)')
|
|
907
|
+
s.add_argument('--site', metavar='S', help='only this site')
|
|
908
|
+
s.add_argument('--all', action='store_true', help="every repo's registered runs")
|
|
909
|
+
s.add_argument('--json', action='store_true')
|
|
910
|
+
s.set_defaults(fn=cmd_report)
|
|
911
|
+
|
|
912
|
+
s = sub.add_parser('replay', allow_abbrev=False,
|
|
913
|
+
help='re-ask stored requests on a provider and model; judge them on the labels')
|
|
914
|
+
s.add_argument('--site', required=True, metavar='S', help='a live site, such as jev-drift')
|
|
915
|
+
s.add_argument('--provider', required=True, metavar='P')
|
|
916
|
+
s.add_argument('--model', required=True, metavar='M')
|
|
917
|
+
s.add_argument('--runs', type=int, metavar='N', help='only the newest N dataset runs')
|
|
918
|
+
s.add_argument('--send', action='store_true', help='ask the provider (without it: a dry run)')
|
|
919
|
+
s.add_argument('--workers', type=int, default=3)
|
|
920
|
+
s.add_argument('--seed', type=int, default=7, help='bootstrap seed of the reported interval')
|
|
921
|
+
s.add_argument('--margin', type=float, default=0.02)
|
|
922
|
+
s.add_argument('--json', action='store_true')
|
|
923
|
+
s.set_defaults(fn=cmd_replay)
|
|
924
|
+
return p
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
def main(argv: list[str] | None = None) -> int:
|
|
928
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
929
|
+
# Checked before argparse, whose error would echo the value back.
|
|
930
|
+
if any(arg == '--key' or arg.startswith('--key=') for arg in argv):
|
|
931
|
+
print(NO_KEY_ARG, file=sys.stderr)
|
|
932
|
+
return 2
|
|
933
|
+
try:
|
|
934
|
+
args = parser().parse_args(argv)
|
|
935
|
+
return args.fn(args)
|
|
936
|
+
except SystemExit as exit:
|
|
937
|
+
return int(exit.code or 0)
|
|
938
|
+
except KeyboardInterrupt:
|
|
939
|
+
return 130
|
|
940
|
+
except Usage as error:
|
|
941
|
+
_err(str(error))
|
|
942
|
+
return 2
|
|
943
|
+
except Failed as error:
|
|
944
|
+
_err(str(error))
|
|
945
|
+
return 1
|
|
946
|
+
except Refused as error:
|
|
947
|
+
_err(str(error))
|
|
948
|
+
return 3
|
|
949
|
+
except OSError as error:
|
|
950
|
+
# The type and the file name only: an OSError's text never carries a key here, but a
|
|
951
|
+
# path is enough to act on.
|
|
952
|
+
_err('%s: %s' % (type(error).__name__, getattr(error, 'filename', None) or error.strerror or ''))
|
|
953
|
+
return 1
|