ganymede-flow-cli 0.8.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ganymede_flow_cli/__init__.py +5 -0
- ganymede_flow_cli/__main__.py +4 -0
- ganymede_flow_cli/cli.py +616 -0
- ganymede_flow_cli/httpapi.py +270 -0
- ganymede_flow_cli/lsp.py +432 -0
- ganymede_flow_cli/serve.py +457 -0
- ganymede_flow_cli-0.8.0.dist-info/METADATA +36 -0
- ganymede_flow_cli-0.8.0.dist-info/RECORD +12 -0
- ganymede_flow_cli-0.8.0.dist-info/WHEEL +5 -0
- ganymede_flow_cli-0.8.0.dist-info/entry_points.txt +2 -0
- ganymede_flow_cli-0.8.0.dist-info/licenses/LICENSE +21 -0
- ganymede_flow_cli-0.8.0.dist-info/top_level.txt +1 -0
ganymede_flow_cli/cli.py
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
"""The `gmd` command line: new, doctor, check, estimate, run, resume, runs, show, serve, lsp."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import difflib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import secrets
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from ganymede_flow import __version__ as ENGINE_VERSION
|
|
16
|
+
from ganymede_flow import nodes as N
|
|
17
|
+
from ganymede_flow.budget import fmt_cost
|
|
18
|
+
from ganymede_flow.doctor import (FAIL, Check, check_api_key, check_flow_file, check_host_mode, check_journal, check_lark, check_manifest,
|
|
19
|
+
check_models, check_python, flow_files, format_checks)
|
|
20
|
+
from ganymede_flow.host import HostSettings, settings_for
|
|
21
|
+
from .httpapi import Auth, make_server
|
|
22
|
+
from ganymede_flow.estimate import EstimateConfig, Estimator, budget_diagnostics, format_estimate, missing_prices
|
|
23
|
+
from ganymede_flow.journal import Journal, JournalFormatError, loads
|
|
24
|
+
from ganymede_flow.modules import compile_file, compile_stored
|
|
25
|
+
from ganymede_flow.parser import MissingDependency, parse
|
|
26
|
+
from ganymede_flow.project import LANGUAGE_DEFAULT, Manifest, ManifestError, ServeConfig, discover
|
|
27
|
+
from ganymede_flow.providers import AnthropicProvider, MockProvider
|
|
28
|
+
from ganymede_flow.runner import RunOptions, resume_run, start_run
|
|
29
|
+
from ganymede_flow.scaffold import ScaffoldError, create_project
|
|
30
|
+
from .serve import Scheduler, Service
|
|
31
|
+
from ganymede_flow.trace import Tracer
|
|
32
|
+
from ganymede_flow.typeops import TypeEnv, ValidationError
|
|
33
|
+
from ganymede_flow.values import short, to_jsonable
|
|
34
|
+
|
|
35
|
+
CAP_CODES = {"E031", "E032", "E033", "E034", "E063"}
|
|
36
|
+
DEFAULT_JOURNAL = ".ganymede/journal.db"
|
|
37
|
+
VERSION_LINE = f"gmd {__version__} (ganymede-flow {ENGINE_VERSION})"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _prog() -> str:
|
|
41
|
+
"""How to invoke ourselves in hints: `gmd` if installed as a script, else `python -m ganymede_flow_cli`."""
|
|
42
|
+
stem = Path(sys.argv[0]).stem if sys.argv and sys.argv[0] else ""
|
|
43
|
+
return "gmd" if stem == "gmd" else "python -m ganymede_flow_cli"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _plural(n: int, word: str) -> str:
|
|
47
|
+
return f"{n} {word}" + ("" if n == 1 else "s")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _manifest(start: Path):
|
|
51
|
+
try:
|
|
52
|
+
return discover(start)
|
|
53
|
+
except ManifestError as e:
|
|
54
|
+
raise SystemExit(f"error: {e}")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _journal_path(args, manifest) -> Path:
|
|
58
|
+
if getattr(args, "journal", None):
|
|
59
|
+
return Path(args.journal)
|
|
60
|
+
if manifest is not None and manifest.journal_path() is not None:
|
|
61
|
+
return manifest.journal_path()
|
|
62
|
+
return Path(DEFAULT_JOURNAL)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
_OPEN_JOURNALS: list = [] # every journal a command opens; main() closes them all, even on errors
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _open_journal(args, manifest, must_exist: bool = False) -> Journal:
|
|
69
|
+
if getattr(args, "no_journal", False):
|
|
70
|
+
journal = Journal(":memory:")
|
|
71
|
+
else:
|
|
72
|
+
path = _journal_path(args, manifest)
|
|
73
|
+
if must_exist and not path.exists():
|
|
74
|
+
raise SystemExit(f"no journal at {path} (use --journal PATH, or run from your project folder)")
|
|
75
|
+
try:
|
|
76
|
+
journal = Journal(path)
|
|
77
|
+
except JournalFormatError as e:
|
|
78
|
+
raise SystemExit(f"error: {e}") from None
|
|
79
|
+
_OPEN_JOURNALS.append(journal)
|
|
80
|
+
return journal
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _close_journals() -> None:
|
|
84
|
+
while _OPEN_JOURNALS:
|
|
85
|
+
_OPEN_JOURNALS.pop().close()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _missing_file_hint(path: Path) -> str:
|
|
89
|
+
"""` Did you mean ...?` for a path that is not a file: same name as .gmd, else a close .gmd name nearby."""
|
|
90
|
+
if path.suffix != ".gmd" and path.with_suffix(".gmd").is_file():
|
|
91
|
+
return f" Did you mean `{path.with_suffix('.gmd')}`?"
|
|
92
|
+
folder = path.parent if path.parent.is_dir() else None
|
|
93
|
+
if folder is None:
|
|
94
|
+
return ""
|
|
95
|
+
near = difflib.get_close_matches(path.with_suffix(".gmd").name, [p.name for p in folder.glob("*.gmd")], n=1)
|
|
96
|
+
return f" Did you mean `{folder / near[0]}`?" if near else ""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _parse(source: str):
|
|
100
|
+
return parse(source) # looked up on each call, so tests can substitute `cli.parse`
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _load(path: Path, out=None):
|
|
104
|
+
"""Parse and check a file and its imports. Returns the Unit, or None (after printing why) when some file does
|
|
105
|
+
not parse or an import is missing."""
|
|
106
|
+
if not path.is_file():
|
|
107
|
+
what = "is a folder, not a .gmd file" if path.is_dir() else "does not exist"
|
|
108
|
+
raise SystemExit(f"error: {path} {what}.{_missing_file_hint(path)}")
|
|
109
|
+
unit = compile_file(path, parse=_parse)
|
|
110
|
+
if unit.program is None:
|
|
111
|
+
for d in unit.diagnostics:
|
|
112
|
+
print(unit.render(d) + "\n", file=out or sys.stdout)
|
|
113
|
+
return None
|
|
114
|
+
return unit
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _estimator(chk, manifest, override=None) -> Estimator:
|
|
118
|
+
cfg = EstimateConfig(**({**manifest.run_limits, **manifest.estimate} if manifest else {}))
|
|
119
|
+
return Estimator(chk, cfg, prices=manifest.prices if manifest else None,
|
|
120
|
+
models=manifest.models if manifest else None, model_override=override)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _host_settings(manifest, fallback_cwd) -> HostSettings:
|
|
124
|
+
return settings_for(manifest, fallback_cwd)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _run_options(args, manifest, fallback_cwd=None, **extra) -> RunOptions:
|
|
128
|
+
return RunOptions(auto_yes=getattr(args, "yes", False), model=getattr(args, "model", None),
|
|
129
|
+
models=manifest.models if manifest else None, prices=manifest.prices if manifest else None,
|
|
130
|
+
host=_host_settings(manifest, fallback_cwd or Path.cwd()),
|
|
131
|
+
language=manifest.language if manifest else LANGUAGE_DEFAULT,
|
|
132
|
+
**(manifest.run_limits if manifest else {}), **extra)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ---------------------------------------------------------------- new
|
|
136
|
+
def cmd_new(args) -> int:
|
|
137
|
+
target = Path(args.path)
|
|
138
|
+
try:
|
|
139
|
+
created = create_project(target, args.name)
|
|
140
|
+
except ScaffoldError as e:
|
|
141
|
+
raise SystemExit(f"error: {e}")
|
|
142
|
+
print(f"created {target}{os.sep}")
|
|
143
|
+
for rel in created:
|
|
144
|
+
print(f" {rel}")
|
|
145
|
+
p = _prog()
|
|
146
|
+
print(f"\nNext:\n cd {target}\n {p} doctor\n"
|
|
147
|
+
f' {p} run src/main.gmd triage "I was charged twice!" --mock mock.json --yes\n'
|
|
148
|
+
f"\n(no API key needed for that last one; see README.md for the real thing)")
|
|
149
|
+
return 0
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# ---------------------------------------------------------------- doctor
|
|
153
|
+
def _doctor_file_checks(f: Path, root: Path) -> list:
|
|
154
|
+
"""Check one .gmd file exactly as `run` would see it: the manifest nearest to the file (not just the one
|
|
155
|
+
above the folder doctor was started in) and the same host-tool search path."""
|
|
156
|
+
here = f.resolve().parent
|
|
157
|
+
try:
|
|
158
|
+
manifest = discover(here)
|
|
159
|
+
except ManifestError as e:
|
|
160
|
+
return [Check(FAIL, f"{f}: {e}", "fix the ganymede.toml nearest to this file")]
|
|
161
|
+
base = (manifest.host_dirs() if manifest else []) + [here, here.parent, Path.cwd()]
|
|
162
|
+
return check_flow_file(f, parse, root, base, manifest, _host_settings(manifest, here))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def cmd_doctor(args) -> int:
|
|
166
|
+
start = Path(args.path)
|
|
167
|
+
checks = [check_python(), check_lark()]
|
|
168
|
+
manifest_checks, manifest = check_manifest(start)
|
|
169
|
+
checks += manifest_checks
|
|
170
|
+
checks.append(check_api_key(os.environ))
|
|
171
|
+
checks.append(check_models(manifest, os.environ))
|
|
172
|
+
checks.append(check_host_mode(_host_settings(manifest, start.resolve())))
|
|
173
|
+
root = manifest.root if manifest else start.resolve()
|
|
174
|
+
checks.append(check_journal(manifest.journal_path() if manifest and manifest.journal_path()
|
|
175
|
+
else start.resolve() / DEFAULT_JOURNAL))
|
|
176
|
+
|
|
177
|
+
files = flow_files(root)
|
|
178
|
+
lark_ok = next(c for c in checks if c.text.startswith("lark")).status != FAIL
|
|
179
|
+
if not files:
|
|
180
|
+
checks.append(Check("warn", f"no .gmd files found under {root}", "create one, or run `gmd new`"))
|
|
181
|
+
elif not lark_ok:
|
|
182
|
+
checks.append(Check("warn", f"{_plural(len(files), '.gmd file')} found but not checked (needs lark)"))
|
|
183
|
+
else:
|
|
184
|
+
for f in files:
|
|
185
|
+
checks += _doctor_file_checks(f, root)
|
|
186
|
+
|
|
187
|
+
print(f"{VERSION_LINE}\n")
|
|
188
|
+
print(format_checks(checks))
|
|
189
|
+
failed = sum(c.status == FAIL for c in checks)
|
|
190
|
+
warned = sum(c.status == "warn" for c in checks)
|
|
191
|
+
print(f"\n{_plural(failed, 'problem')}, {_plural(warned, 'warning')}")
|
|
192
|
+
return 1 if failed else 0
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# ---------------------------------------------------------------- check
|
|
196
|
+
def _check_file(path: Path) -> int:
|
|
197
|
+
unit = _load(path)
|
|
198
|
+
if unit is None:
|
|
199
|
+
return 1
|
|
200
|
+
program, chk, diags = unit.program, unit.chk, unit.diagnostics
|
|
201
|
+
if not any(d.is_error for d in diags): # estimates only make sense for a valid program
|
|
202
|
+
diags = diags + budget_diagnostics(chk, _estimator(chk, _manifest(path.resolve().parent)))
|
|
203
|
+
for d in diags:
|
|
204
|
+
print(unit.render(d))
|
|
205
|
+
print()
|
|
206
|
+
count = lambda t: sum(isinstance(x, t) and unit.owns(x) for x in program.decls) # noqa: E731
|
|
207
|
+
errors = sum(d.is_error for d in diags)
|
|
208
|
+
imported = len(unit.sources) - 1
|
|
209
|
+
print(" " + ", ".join([_plural(count(N.TypeDecl), "type"), _plural(count(N.ToolDecl), "tool"),
|
|
210
|
+
_plural(count(N.AgentDecl), "agent"), _plural(count(N.FlowDecl), "flow")])
|
|
211
|
+
+ (f" (and {_plural(imported, 'imported file')})" if imported else ""))
|
|
212
|
+
if not any(d.code in CAP_CODES for d in diags):
|
|
213
|
+
print(" ✓ capabilities: ok")
|
|
214
|
+
print(f" {_plural(errors, 'error')}, {_plural(len(diags) - errors, 'warning')}")
|
|
215
|
+
return 1 if errors else 0
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def cmd_check(args) -> int:
|
|
219
|
+
files = [Path(f) for f in args.files]
|
|
220
|
+
if not files:
|
|
221
|
+
manifest = _manifest(Path.cwd())
|
|
222
|
+
root = manifest.root if manifest else Path.cwd()
|
|
223
|
+
files = flow_files(root)
|
|
224
|
+
if not files:
|
|
225
|
+
print(f"no .gmd files found under {root}", file=sys.stderr)
|
|
226
|
+
return 1
|
|
227
|
+
code = 0
|
|
228
|
+
for i, path in enumerate(files):
|
|
229
|
+
if len(files) > 1:
|
|
230
|
+
print(f"── {path}")
|
|
231
|
+
code |= _check_file(path)
|
|
232
|
+
if len(files) > 1 and i < len(files) - 1:
|
|
233
|
+
print()
|
|
234
|
+
return code
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
# ---------------------------------------------------------------- shared run helpers
|
|
238
|
+
def _coerce_args(flow: N.FlowDecl, raw: list, tenv: TypeEnv) -> dict:
|
|
239
|
+
if len(raw) != len(flow.params):
|
|
240
|
+
sig = ", ".join(p.name for p in flow.params) or "no arguments"
|
|
241
|
+
raise SystemExit(f"flow `{flow.name}` takes {_plural(len(flow.params), 'argument')} ({sig}), got {len(raw)}")
|
|
242
|
+
out = {}
|
|
243
|
+
for p, s in zip(flow.params, raw):
|
|
244
|
+
if tenv.is_text(p.type):
|
|
245
|
+
out[p.name] = s
|
|
246
|
+
continue
|
|
247
|
+
try:
|
|
248
|
+
out[p.name] = tenv.validate(p.type, json.loads(s))
|
|
249
|
+
except (ValueError, ValidationError) as e:
|
|
250
|
+
raise SystemExit(f"argument `{p.name}` must be JSON matching its type: {e}")
|
|
251
|
+
return out
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _provider(args):
|
|
255
|
+
if getattr(args, "mock", None):
|
|
256
|
+
return MockProvider.from_file(args.mock)
|
|
257
|
+
key = os.environ.get("ANTHROPIC_API_KEY")
|
|
258
|
+
if not key:
|
|
259
|
+
raise SystemExit("ANTHROPIC_API_KEY is not set (or pass --mock FILE to replay a script). "
|
|
260
|
+
f"`{_prog()} doctor` shows what is missing.")
|
|
261
|
+
return AnthropicProvider(key)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _report(outcome, tracer: Tracer, journaled: bool) -> int:
|
|
265
|
+
o, p = outcome, _prog()
|
|
266
|
+
if o.status == "done":
|
|
267
|
+
tracer.summary(True, "done")
|
|
268
|
+
out = to_jsonable(o.result)
|
|
269
|
+
print(out if isinstance(out, str) else json.dumps(out, indent=2, ensure_ascii=False))
|
|
270
|
+
elif o.status == "suspended":
|
|
271
|
+
print(f"\n⏸ suspended: {o.message}", file=sys.stderr)
|
|
272
|
+
print(f" asking about: {short(o.value, 100)}", file=sys.stderr)
|
|
273
|
+
if journaled:
|
|
274
|
+
print(f" resume with: {p} resume {o.run_id} --approve (or --reject)", file=sys.stderr)
|
|
275
|
+
else:
|
|
276
|
+
print(" journaling is off, so this run cannot be resumed; rerun with --yes or without --no-journal",
|
|
277
|
+
file=sys.stderr)
|
|
278
|
+
else:
|
|
279
|
+
first, _, rest = o.message.partition("\n")
|
|
280
|
+
tracer.summary(False, first or o.status)
|
|
281
|
+
if rest:
|
|
282
|
+
print(rest, file=sys.stderr)
|
|
283
|
+
if journaled and o.status in ("error", "interrupted"):
|
|
284
|
+
print(f" run {o.run_id} is saved; fix the cause and run: {p} resume {o.run_id}", file=sys.stderr)
|
|
285
|
+
return o.exit_code
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
# ---------------------------------------------------------------- run
|
|
289
|
+
def cmd_run(args) -> int:
|
|
290
|
+
path = Path(args.file)
|
|
291
|
+
manifest = _manifest(path.resolve().parent)
|
|
292
|
+
unit = _load(path, out=sys.stderr)
|
|
293
|
+
if unit is None:
|
|
294
|
+
return 1
|
|
295
|
+
program, chk, diags = unit.program, unit.chk, unit.diagnostics
|
|
296
|
+
if not any(d.is_error for d in diags):
|
|
297
|
+
diags = diags + [d for d in budget_diagnostics(chk, _estimator(chk, manifest, args.model))
|
|
298
|
+
if d.code == "B001"]
|
|
299
|
+
for d in diags:
|
|
300
|
+
print(unit.render(d), file=sys.stderr)
|
|
301
|
+
print(file=sys.stderr)
|
|
302
|
+
if any(d.is_error for d in diags):
|
|
303
|
+
print("not running: fix the errors above first (see `check`)", file=sys.stderr)
|
|
304
|
+
return 1
|
|
305
|
+
absent = missing_prices(chk, manifest.prices if manifest else {}, manifest.models if manifest else None,
|
|
306
|
+
args.model)
|
|
307
|
+
if absent:
|
|
308
|
+
print("not running: a budget limits `cost`, but no price is configured for: " + ", ".join(absent) +
|
|
309
|
+
"\nAdd it to ganymede.toml (USD per million tokens, from your provider's pricing page):\n",
|
|
310
|
+
file=sys.stderr)
|
|
311
|
+
for m in absent:
|
|
312
|
+
print(f'[prices."{m}"]\ninput = <price>\noutput = <price>\n', file=sys.stderr)
|
|
313
|
+
return 1
|
|
314
|
+
|
|
315
|
+
flows = [d.name for d in program.decls if isinstance(d, N.FlowDecl)]
|
|
316
|
+
flow = next((d for d in program.decls if isinstance(d, N.FlowDecl) and d.name == args.flow), None)
|
|
317
|
+
if flow is None:
|
|
318
|
+
near = difflib.get_close_matches(args.flow, flows, n=1)
|
|
319
|
+
hint = f" Did you mean `{near[0]}`?" if near else ""
|
|
320
|
+
raise SystemExit(f"no flow named `{args.flow}`.{hint} Flows in this file: {', '.join(flows) or '(none)'}")
|
|
321
|
+
values = _coerce_args(flow, args.args, TypeEnv(chk.types))
|
|
322
|
+
provider = _provider(args)
|
|
323
|
+
|
|
324
|
+
journal = _open_journal(args, manifest)
|
|
325
|
+
tracer = Tracer(enabled=not args.quiet)
|
|
326
|
+
base_dirs = (manifest.host_dirs() if manifest else []) + [path.resolve().parent, path.resolve().parent.parent,
|
|
327
|
+
Path.cwd()]
|
|
328
|
+
opts = _run_options(args, manifest, path.resolve().parent)
|
|
329
|
+
outcome = start_run(journal, chk, flow, values, unit.stored, path, base_dirs, provider, tracer, opts)
|
|
330
|
+
return _report(outcome, tracer, journaled=not args.no_journal)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
# ---------------------------------------------------------------- resume
|
|
334
|
+
def cmd_resume(args) -> int:
|
|
335
|
+
manifest = _manifest(Path.cwd())
|
|
336
|
+
journal = _open_journal(args, manifest, must_exist=True)
|
|
337
|
+
run = journal.get_run(args.run_id)
|
|
338
|
+
if run is None:
|
|
339
|
+
known = [r["run_id"] for r in journal.list_runs()]
|
|
340
|
+
near = difflib.get_close_matches(args.run_id, known, n=1)
|
|
341
|
+
raise SystemExit(f"no run `{args.run_id}` in {journal.path}" + (f". Did you mean `{near[0]}`?" if near else ""))
|
|
342
|
+
|
|
343
|
+
if run["file_path"] and Path(run["file_path"]).is_file():
|
|
344
|
+
try:
|
|
345
|
+
changed = compile_file(Path(run["file_path"]), parse=_parse).stored != run["source"]
|
|
346
|
+
except OSError:
|
|
347
|
+
changed = True
|
|
348
|
+
if changed:
|
|
349
|
+
print(f"note: {run['file_path']} (or a file it imports) changed since this run started; "
|
|
350
|
+
f"resuming with the version the run began with", file=sys.stderr)
|
|
351
|
+
|
|
352
|
+
def loader(source: str):
|
|
353
|
+
unit = compile_stored(source, run["file_path"], parse=_parse)
|
|
354
|
+
if unit.errors:
|
|
355
|
+
raise SystemExit("the stored source has errors; this run cannot be resumed:\n\n"
|
|
356
|
+
+ "\n\n".join(unit.render(d) for d in unit.errors))
|
|
357
|
+
return unit.chk
|
|
358
|
+
|
|
359
|
+
decision = True if args.approve else False if args.reject else None
|
|
360
|
+
opts = _run_options(args, manifest, Path.cwd(), rerun=args.rerun, decision=decision)
|
|
361
|
+
tracer = Tracer(enabled=not args.quiet)
|
|
362
|
+
outcome = resume_run(journal, args.run_id, loader, _provider(args), tracer, opts)
|
|
363
|
+
return _report(outcome, tracer, journaled=True)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
# ---------------------------------------------------------------- runs / show
|
|
367
|
+
def _when(ts: float) -> str:
|
|
368
|
+
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def cmd_runs(args) -> int:
|
|
372
|
+
journal = _open_journal(args, _manifest(Path.cwd()), must_exist=True)
|
|
373
|
+
rows = journal.list_runs()
|
|
374
|
+
if not rows:
|
|
375
|
+
print("no runs yet")
|
|
376
|
+
for r in rows:
|
|
377
|
+
print(f"{r['run_id']} {r['status']:<11} {r['flow']:<16} {_when(r['created'])} {r['file_path'] or ''}")
|
|
378
|
+
return 0
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def cmd_show(args) -> int:
|
|
382
|
+
journal = _open_journal(args, _manifest(Path.cwd()), must_exist=True)
|
|
383
|
+
run = journal.get_run(args.run_id)
|
|
384
|
+
if run is None:
|
|
385
|
+
known = [r["run_id"] for r in journal.list_runs()]
|
|
386
|
+
near = difflib.get_close_matches(args.run_id, known, n=1)
|
|
387
|
+
raise SystemExit(f"no run `{args.run_id}` in {journal.path}" + (f". Did you mean `{near[0]}`?" if near else ""))
|
|
388
|
+
print(f"{run['run_id']} flow={run['flow']} status={run['status']} started={_when(run['created'])}")
|
|
389
|
+
print(f"args: {short(loads(run['args']), 100)}")
|
|
390
|
+
print(f"engine: ganymede-flow {run['engine_version']}, language {run['language']}")
|
|
391
|
+
if run["error"]:
|
|
392
|
+
print(f"note: {run['error']}")
|
|
393
|
+
if run["result"]:
|
|
394
|
+
print(f"result: {short(loads(run['result']), 100)}")
|
|
395
|
+
print(f"\n{'step':>7} {'kind':<6} {'name':<16} {'status':<8} {'tokens':>12} {'cost':>9} {'ms':>7}")
|
|
396
|
+
for r in journal.steps(args.run_id):
|
|
397
|
+
tokens = f"{r['tokens_in']:,}→{r['tokens_out']:,}" if r["sub"] == 0 and r["kind"] == "agent" else ""
|
|
398
|
+
if r["sub"] == 0:
|
|
399
|
+
cost = fmt_cost(r["cost"]) if r.get("cost") else ""
|
|
400
|
+
print(f"{r['step']:>7} {r['kind']:<6} {r['name']:<16} {r['status']:<8} {tokens:>12} {cost:>9} "
|
|
401
|
+
f"{r['duration_ms'] or 0:>7}")
|
|
402
|
+
else:
|
|
403
|
+
print(f" └ tool {r['name']:<12} {r['status']:<8} {short(loads(r['input']), 40)}")
|
|
404
|
+
if r["status"] in ("error", "breach") and r["error"]:
|
|
405
|
+
text = r["error"]
|
|
406
|
+
if r["status"] == "breach":
|
|
407
|
+
try:
|
|
408
|
+
text = json.loads(text)["message"]
|
|
409
|
+
except (ValueError, KeyError, TypeError):
|
|
410
|
+
pass
|
|
411
|
+
print(f" ! {text[:110]}")
|
|
412
|
+
return 0
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
# ---------------------------------------------------------------- estimate
|
|
416
|
+
def cmd_estimate(args) -> int:
|
|
417
|
+
path = Path(args.file)
|
|
418
|
+
manifest = _manifest(path.resolve().parent)
|
|
419
|
+
unit = _load(path)
|
|
420
|
+
if unit is None:
|
|
421
|
+
return 1
|
|
422
|
+
program, chk = unit.program, unit.chk
|
|
423
|
+
errors = unit.errors
|
|
424
|
+
for d in errors:
|
|
425
|
+
print(unit.render(d))
|
|
426
|
+
print()
|
|
427
|
+
if errors:
|
|
428
|
+
print("fix the errors above first (see `check`)", file=sys.stderr)
|
|
429
|
+
return 1
|
|
430
|
+
flows = [d for d in program.decls if isinstance(d, N.FlowDecl) and (args.flow or unit.owns(d))]
|
|
431
|
+
if args.flow:
|
|
432
|
+
names = [f.name for f in flows]
|
|
433
|
+
flows = [f for f in flows if f.name == args.flow]
|
|
434
|
+
if not flows:
|
|
435
|
+
near = difflib.get_close_matches(args.flow, names, n=1)
|
|
436
|
+
raise SystemExit(f"no flow named `{args.flow}`." + (f" Did you mean `{near[0]}`?" if near else "")
|
|
437
|
+
+ f" Flows in this file: {', '.join(names) or '(none)'}")
|
|
438
|
+
if not flows:
|
|
439
|
+
print("no flows in this file")
|
|
440
|
+
return 0
|
|
441
|
+
est = _estimator(chk, manifest, args.model)
|
|
442
|
+
for i, f in enumerate(flows):
|
|
443
|
+
if i:
|
|
444
|
+
print()
|
|
445
|
+
print(format_estimate(chk, est, f))
|
|
446
|
+
return 0
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
# ---------------------------------------------------------------- serve
|
|
450
|
+
def cmd_serve(args) -> int:
|
|
451
|
+
root = Path(args.path).resolve()
|
|
452
|
+
manifest = _manifest(root)
|
|
453
|
+
cfg = manifest.serve if manifest else ServeConfig()
|
|
454
|
+
host = args.host or cfg.host
|
|
455
|
+
port = cfg.port if args.port is None else args.port
|
|
456
|
+
loopback = host in ("127.0.0.1", "localhost", "::1")
|
|
457
|
+
|
|
458
|
+
if args.no_auth:
|
|
459
|
+
if not loopback:
|
|
460
|
+
raise SystemExit("error: --no-auth is only allowed when binding to a loopback address (127.0.0.1)")
|
|
461
|
+
auth = Auth(open=True)
|
|
462
|
+
else:
|
|
463
|
+
admin = os.environ.get(cfg.token_env) or None
|
|
464
|
+
if admin is None:
|
|
465
|
+
admin = secrets.token_urlsafe(24)
|
|
466
|
+
print(f"admin token (generated for this run; set {cfg.token_env} to choose your own):\n {admin}",
|
|
467
|
+
file=sys.stderr)
|
|
468
|
+
auth = Auth(admin, os.environ.get(cfg.approver_token_env) or None)
|
|
469
|
+
|
|
470
|
+
if args.mock:
|
|
471
|
+
mock_path = args.mock
|
|
472
|
+
factory = lambda: MockProvider.from_file(mock_path) # noqa: E731 (fresh script per run)
|
|
473
|
+
else:
|
|
474
|
+
key = os.environ.get("ANTHROPIC_API_KEY")
|
|
475
|
+
if not key:
|
|
476
|
+
raise SystemExit("ANTHROPIC_API_KEY is not set (or pass --mock FILE to replay a script). "
|
|
477
|
+
f"`{_prog()} doctor` shows what is missing.")
|
|
478
|
+
factory = lambda: AnthropicProvider(key) # noqa: E731
|
|
479
|
+
|
|
480
|
+
journal = _open_journal(args, manifest)
|
|
481
|
+
service = Service(root, journal, manifest, provider_factory=factory, host_settings=_host_settings(manifest, root),
|
|
482
|
+
config=cfg, parse_fn=_parse)
|
|
483
|
+
problems = service.validate()
|
|
484
|
+
if problems:
|
|
485
|
+
print("not starting:\n " + "\n ".join(problems), file=sys.stderr)
|
|
486
|
+
return 1
|
|
487
|
+
recovered = service.recover()
|
|
488
|
+
|
|
489
|
+
server = make_server(service, auth, host, port, cfg.max_body_bytes)
|
|
490
|
+
bound = server.server_address[1]
|
|
491
|
+
stop = threading.Event()
|
|
492
|
+
if cfg.schedules:
|
|
493
|
+
scheduler = Scheduler(service, cfg.schedules)
|
|
494
|
+
threading.Thread(target=scheduler.run_forever, args=(stop,), daemon=True, name="flow-scheduler").start()
|
|
495
|
+
|
|
496
|
+
n_flows = len(service.flows()["flows"])
|
|
497
|
+
print(f"gmd serve: http://{host}:{bound} ({_plural(n_flows, 'flow')}, {_plural(len(cfg.hooks), 'hook')}, "
|
|
498
|
+
f"{_plural(len(cfg.schedules), 'schedule')}, up to {cfg.max_concurrent_runs} runs at once)", file=sys.stderr)
|
|
499
|
+
if recovered:
|
|
500
|
+
print(f"{_plural(len(recovered), 'run')} left in progress by a previous process "
|
|
501
|
+
f"{'resumed' if cfg.resume_interrupted else 'marked interrupted'}: {', '.join(recovered)}", file=sys.stderr)
|
|
502
|
+
if not loopback:
|
|
503
|
+
print("warning: this address is not loopback and there is no TLS here; put a reverse proxy in front",
|
|
504
|
+
file=sys.stderr)
|
|
505
|
+
try:
|
|
506
|
+
server.serve_forever()
|
|
507
|
+
except KeyboardInterrupt:
|
|
508
|
+
print("\nshutting down (running runs stay resumable)...", file=sys.stderr)
|
|
509
|
+
finally:
|
|
510
|
+
stop.set()
|
|
511
|
+
server.server_close()
|
|
512
|
+
service.shutdown()
|
|
513
|
+
return 0
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
# ---------------------------------------------------------------- lsp
|
|
517
|
+
def cmd_lsp(args) -> int:
|
|
518
|
+
from .lsp import main as lsp_main
|
|
519
|
+
return lsp_main()
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
# ---------------------------------------------------------------- main
|
|
523
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
524
|
+
ap = argparse.ArgumentParser(prog="gmd", description="Ganymede: typed agent workflows that can pause and resume.")
|
|
525
|
+
ap.add_argument("--version", action="version", version=VERSION_LINE)
|
|
526
|
+
sub = ap.add_subparsers(dest="cmd", required=True, metavar="command")
|
|
527
|
+
|
|
528
|
+
def journal_opt(p):
|
|
529
|
+
p.add_argument("--journal", help=f"journal database (default: from ganymede.toml, else {DEFAULT_JOURNAL})")
|
|
530
|
+
|
|
531
|
+
n = sub.add_parser("new", help="create a project that runs with just an API key (or --mock)")
|
|
532
|
+
n.add_argument("path")
|
|
533
|
+
n.add_argument("--name", help="project name (default: the folder name)")
|
|
534
|
+
n.set_defaults(fn=cmd_new)
|
|
535
|
+
|
|
536
|
+
d = sub.add_parser("doctor", help="check your setup and say how to fix what is missing")
|
|
537
|
+
d.add_argument("path", nargs="?", default=".", help="project folder (default: current)")
|
|
538
|
+
d.set_defaults(fn=cmd_doctor)
|
|
539
|
+
|
|
540
|
+
c = sub.add_parser("check", help="statically check .gmd files (default: every one in the project)")
|
|
541
|
+
c.add_argument("files", nargs="*")
|
|
542
|
+
c.set_defaults(fn=cmd_check)
|
|
543
|
+
|
|
544
|
+
ls = sub.add_parser("lsp", help="language server for editors (speaks LSP on stdin/stdout)")
|
|
545
|
+
ls.set_defaults(fn=cmd_lsp)
|
|
546
|
+
|
|
547
|
+
sv = sub.add_parser("serve", help="run an HTTP API, webhooks and schedules for this project")
|
|
548
|
+
sv.add_argument("path", nargs="?", default=".", help="project folder (default: current)")
|
|
549
|
+
sv.add_argument("--host", help="address to bind (default: from ganymede.toml, else 127.0.0.1)")
|
|
550
|
+
sv.add_argument("--port", type=int, help="port (default: from ganymede.toml, else 8787; 0 picks a free one)")
|
|
551
|
+
sv.add_argument("--mock", metavar="FILE", help="scripted agent responses instead of calling a model")
|
|
552
|
+
sv.add_argument("--no-auth", action="store_true", help="no bearer token (loopback only; for local experiments)")
|
|
553
|
+
journal_opt(sv)
|
|
554
|
+
sv.set_defaults(fn=cmd_serve)
|
|
555
|
+
|
|
556
|
+
e = sub.add_parser("estimate", help="worst-case calls, tokens, cost and time of a flow (static, no API calls)")
|
|
557
|
+
e.add_argument("file")
|
|
558
|
+
e.add_argument("flow", nargs="?", help="flow name (default: every flow in the file)")
|
|
559
|
+
e.add_argument("--model", help="price every agent as if it used this model")
|
|
560
|
+
e.set_defaults(fn=cmd_estimate)
|
|
561
|
+
|
|
562
|
+
r = sub.add_parser("run", help="execute a flow (journaled, so it can be resumed)")
|
|
563
|
+
r.add_argument("file")
|
|
564
|
+
r.add_argument("flow", help="name of the flow to run")
|
|
565
|
+
r.add_argument("args", nargs="*", help="flow arguments in order (Text as-is, other types as JSON)")
|
|
566
|
+
r.add_argument("--mock", metavar="FILE", help="replay scripted agent responses instead of calling a model")
|
|
567
|
+
r.add_argument("--yes", action="store_true", help="auto-approve human.approve steps")
|
|
568
|
+
r.add_argument("--quiet", action="store_true", help="suppress the execution trace")
|
|
569
|
+
r.add_argument("--model", help="override the model for every agent")
|
|
570
|
+
r.add_argument("--no-journal", action="store_true", help="do not persist this run (cannot be resumed)")
|
|
571
|
+
journal_opt(r)
|
|
572
|
+
r.set_defaults(fn=cmd_run)
|
|
573
|
+
|
|
574
|
+
s = sub.add_parser("resume", help="continue a suspended, failed or interrupted run")
|
|
575
|
+
s.add_argument("run_id")
|
|
576
|
+
g = s.add_mutually_exclusive_group()
|
|
577
|
+
g.add_argument("--approve", action="store_true", help="answer a pending human.approve with yes")
|
|
578
|
+
g.add_argument("--reject", action="store_true", help="answer a pending human.approve with no")
|
|
579
|
+
s.add_argument("--rerun", action="store_true",
|
|
580
|
+
help="re-execute a tool call that may already have run (its side effects may repeat)")
|
|
581
|
+
s.add_argument("--mock", metavar="FILE", help="scripted responses (replayed steps are skipped automatically)")
|
|
582
|
+
s.add_argument("--yes", action="store_true")
|
|
583
|
+
s.add_argument("--quiet", action="store_true")
|
|
584
|
+
s.add_argument("--model")
|
|
585
|
+
journal_opt(s)
|
|
586
|
+
s.set_defaults(fn=cmd_resume)
|
|
587
|
+
|
|
588
|
+
l = sub.add_parser("runs", help="list runs")
|
|
589
|
+
journal_opt(l)
|
|
590
|
+
l.set_defaults(fn=cmd_runs)
|
|
591
|
+
|
|
592
|
+
w = sub.add_parser("show", help="show one run and its journal")
|
|
593
|
+
w.add_argument("run_id")
|
|
594
|
+
journal_opt(w)
|
|
595
|
+
w.set_defaults(fn=cmd_show)
|
|
596
|
+
return ap
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def main(argv=None) -> int:
|
|
600
|
+
for stream in (sys.stdout, sys.stderr):
|
|
601
|
+
try:
|
|
602
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
603
|
+
except (AttributeError, ValueError):
|
|
604
|
+
pass
|
|
605
|
+
args = build_parser().parse_args(argv)
|
|
606
|
+
try:
|
|
607
|
+
return args.fn(args)
|
|
608
|
+
except MissingDependency as e:
|
|
609
|
+
print(f"error: {e}", file=sys.stderr)
|
|
610
|
+
return 1
|
|
611
|
+
finally:
|
|
612
|
+
_close_journals()
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
if __name__ == "__main__":
|
|
616
|
+
sys.exit(main())
|