ganymede-flow 0.8.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. ganymede_flow-0.8.0/LICENSE +21 -0
  2. ganymede_flow-0.8.0/PKG-INFO +140 -0
  3. ganymede_flow-0.8.0/README.md +110 -0
  4. ganymede_flow-0.8.0/ganymede_flow/__init__.py +22 -0
  5. ganymede_flow-0.8.0/ganymede_flow/api.py +332 -0
  6. ganymede_flow-0.8.0/ganymede_flow/budget.py +236 -0
  7. ganymede_flow-0.8.0/ganymede_flow/checker.py +694 -0
  8. ganymede_flow-0.8.0/ganymede_flow/diagnostics.py +39 -0
  9. ganymede_flow-0.8.0/ganymede_flow/doctor.py +186 -0
  10. ganymede_flow-0.8.0/ganymede_flow/effects.py +414 -0
  11. ganymede_flow-0.8.0/ganymede_flow/errors.py +80 -0
  12. ganymede_flow-0.8.0/ganymede_flow/estimate.py +359 -0
  13. ganymede_flow-0.8.0/ganymede_flow/ganymede.lark +108 -0
  14. ganymede_flow-0.8.0/ganymede_flow/host/__init__.py +470 -0
  15. ganymede_flow-0.8.0/ganymede_flow/host/worker_node.mjs +125 -0
  16. ganymede_flow-0.8.0/ganymede_flow/host/worker_py.py +329 -0
  17. ganymede_flow-0.8.0/ganymede_flow/interp.py +287 -0
  18. ganymede_flow-0.8.0/ganymede_flow/journal.py +361 -0
  19. ganymede_flow-0.8.0/ganymede_flow/journaled.py +233 -0
  20. ganymede_flow-0.8.0/ganymede_flow/modules.py +217 -0
  21. ganymede_flow-0.8.0/ganymede_flow/nodes.py +277 -0
  22. ganymede_flow-0.8.0/ganymede_flow/parser.py +281 -0
  23. ganymede_flow-0.8.0/ganymede_flow/project.py +342 -0
  24. ganymede_flow-0.8.0/ganymede_flow/providers.py +147 -0
  25. ganymede_flow-0.8.0/ganymede_flow/runner.py +149 -0
  26. ganymede_flow-0.8.0/ganymede_flow/sandbox.py +48 -0
  27. ganymede_flow-0.8.0/ganymede_flow/scaffold.py +153 -0
  28. ganymede_flow-0.8.0/ganymede_flow/syntaxhelp.py +55 -0
  29. ganymede_flow-0.8.0/ganymede_flow/trace.py +91 -0
  30. ganymede_flow-0.8.0/ganymede_flow/typeops.py +165 -0
  31. ganymede_flow-0.8.0/ganymede_flow/values.py +63 -0
  32. ganymede_flow-0.8.0/ganymede_flow.egg-info/PKG-INFO +140 -0
  33. ganymede_flow-0.8.0/ganymede_flow.egg-info/SOURCES.txt +56 -0
  34. ganymede_flow-0.8.0/ganymede_flow.egg-info/dependency_links.txt +1 -0
  35. ganymede_flow-0.8.0/ganymede_flow.egg-info/requires.txt +4 -0
  36. ganymede_flow-0.8.0/ganymede_flow.egg-info/top_level.txt +1 -0
  37. ganymede_flow-0.8.0/pyproject.toml +48 -0
  38. ganymede_flow-0.8.0/setup.cfg +4 -0
  39. ganymede_flow-0.8.0/tests/test_api.py +222 -0
  40. ganymede_flow-0.8.0/tests/test_budget.py +304 -0
  41. ganymede_flow-0.8.0/tests/test_checker.py +221 -0
  42. ganymede_flow-0.8.0/tests/test_cli.py +175 -0
  43. ganymede_flow-0.8.0/tests/test_estimate.py +320 -0
  44. ganymede_flow-0.8.0/tests/test_host.py +677 -0
  45. ganymede_flow-0.8.0/tests/test_imports.py +159 -0
  46. ganymede_flow-0.8.0/tests/test_interp.py +324 -0
  47. ganymede_flow-0.8.0/tests/test_journal.py +384 -0
  48. ganymede_flow-0.8.0/tests/test_journal_format.py +150 -0
  49. ganymede_flow-0.8.0/tests/test_language_spec.py +170 -0
  50. ganymede_flow-0.8.0/tests/test_layering.py +19 -0
  51. ganymede_flow-0.8.0/tests/test_lists.py +185 -0
  52. ganymede_flow-0.8.0/tests/test_lsp.py +270 -0
  53. ganymede_flow-0.8.0/tests/test_parser.py +80 -0
  54. ganymede_flow-0.8.0/tests/test_project.py +412 -0
  55. ganymede_flow-0.8.0/tests/test_public_api.py +104 -0
  56. ganymede_flow-0.8.0/tests/test_release.py +106 -0
  57. ganymede_flow-0.8.0/tests/test_security.py +123 -0
  58. ganymede_flow-0.8.0/tests/test_serve.py +675 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Ganymede contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: ganymede-flow
3
+ Version: 0.8.0
4
+ Summary: Ganymede: typed agent workflows, written in their own small language, that can pause for a human and resume after a crash.
5
+ Author: The Ganymede contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ziv-shapira/ganymede-flow
8
+ Project-URL: Documentation, https://github.com/ziv-shapira/ganymede-flow/tree/main/docs
9
+ Project-URL: Changelog, https://github.com/ziv-shapira/ganymede-flow/blob/main/CHANGELOG.md
10
+ Project-URL: Issues, https://github.com/ziv-shapira/ganymede-flow/issues
11
+ Keywords: agents,llm,workflow,language,durable-execution,human-in-the-loop
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: 3.15
21
+ Classifier: Topic :: Software Development :: Interpreters
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.12
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: lark>=1.1
27
+ Provides-Extra: test
28
+ Requires-Dist: pytest; extra == "test"
29
+ Dynamic: license-file
30
+
31
+ # Ganymede
32
+
33
+ Typed agent workflows you can put into production. You write workflows in Ganymede's own small language (`.gmd` files), where
34
+ agents have typed signatures, control flow is ordinary code, capabilities are declared and checked, budgets
35
+ are hard limits, and every run is journaled so it can pause for a human and resume later without redoing
36
+ finished work.
37
+
38
+ This repo holds two Python packages that are versioned and released together:
39
+
40
+ | folder | PyPI | import | what it is |
41
+ |---|---|---|---|
42
+ | `.` (root) | `ganymede-flow` | `ganymede_flow` | the engine and Python API; depends only on `lark` |
43
+ | `cli/` | `ganymede-flow-cli` | `ganymede_flow_cli` | the `gmd` command, HTTP server and language server |
44
+
45
+ ## Install from a checkout
46
+
47
+ pip install -e . -e cli
48
+
49
+ ## Try it
50
+
51
+ gmd new my-app && cd my-app
52
+ gmd doctor
53
+ gmd run src/main.gmd triage "I was charged twice!" --mock mock.json --yes
54
+
55
+ `demo/` is a ready-made project; see its README. The language reference, including every diagnostic code and
56
+ how language versions work, is [docs/language.md](docs/language.md). How run journals stay readable across
57
+ upgrades is in [docs/journal.md](docs/journal.md). The stable interfaces are the
58
+ [Python API](docs/python-api.md) and the [HTTP API](docs/http-api.md); everything else is internal.
59
+ Read [docs/security.md](docs/security.md) before exposing `gmd serve` or running tools you did not write.
60
+
61
+ ## Commands
62
+
63
+ `new`, `doctor`, `check`, `estimate`, `run`, `resume`, `runs`, `show`, `serve`, `lsp`.
64
+ Without the script installed, use `python -m ganymede_flow_cli <command>`.
65
+
66
+ - `gmd estimate` shows a flow's worst case (calls, tokens, time, cost) before you spend anything.
67
+ - `gmd serve` runs an HTTP API for a project: start runs, approve or reject paused ones (with a separate
68
+ approver token that can do nothing else), signed webhooks and schedules.
69
+ - `gmd lsp` is a language server; `editors/vscode` has a VS Code extension for it.
70
+
71
+ ## From Python (engine only)
72
+
73
+ import ganymede_flow
74
+ with ganymede_flow.load("my-app") as app: # a project folder (or a single .gmd file)
75
+ r = app.run("triage", "I was charged twice!")
76
+ if r.suspended:
77
+ r = app.resume(r.run_id, approve=True)
78
+ print(r.result)
79
+
80
+ ## What the engine does
81
+
82
+ - **Typed agents.** Each agent declares its inputs and output type; answers are validated and retried.
83
+ - **Static checks** before anything runs: capability violations, unhandled match arms, unknown variants,
84
+ unbounded loops (`loop max N` is required).
85
+ - **Capabilities, enforced.** Tools run in separate worker processes (Python and TypeScript) with a clean
86
+ environment, sandboxed to what they declare and the calling agent holds.
87
+ - **Budgets.** `within { cost: $0.50, time: 5min, calls: 20, tokens: 60k }` on a flow, an agent or a block,
88
+ with an optional `on_exceed` fallback.
89
+ - **Journaled runs.** Every model call, tool call and human decision is recorded (SQLite), so a run can wait
90
+ for approval, survive a crash, and resume by replaying finished steps instead of re-running them.
91
+
92
+ ## Layout
93
+
94
+ ganymede_flow/ engine: parser (ganymede.lark), checker, interpreter, runner, journal, host (sandboxed
95
+ tool workers), budgets, estimate, doctor, project manifests, scaffold, Python API
96
+ cli/ the ganymede-flow-cli package: gmd command line, serve (HTTP), lsp
97
+ docs/ language reference, journal compatibility, Python API, HTTP API, security
98
+ tests/ all tests: python -m pytest (works from a checkout, no install needed)
99
+ examples/ example .gmd programs used by the tests
100
+ demo/ a ready-made project
101
+ editors/vscode/ VS Code extension (talks to `gmd lsp`)
102
+
103
+ The engine never imports the CLI (`tests/test_layering.py` checks this), so `ganymede-flow` stays usable on
104
+ its own. If the two ever need separate repos, `cli/` can move out with its history.
105
+
106
+ ## Releasing
107
+
108
+ 1. Set the version in `pyproject.toml`, `cli/pyproject.toml` (and its pin on `ganymede-flow`), both `__init__.py`
109
+ files and `editors/vscode/package.json`. CI refuses to build if these disagree.
110
+ 2. In [CHANGELOG.md](CHANGELOG.md), date that version's section: `## 0.8.0 - 2026-12-01`.
111
+ 3. Merge to `main`, wait for CI to pass, then tag that commit and push the tag:
112
+ `git tag v0.8.0 && git push origin v0.8.0`.
113
+
114
+ The tag starts `.github/workflows/release.yml`. It checks the tag against every version and the CHANGELOG, runs the
115
+ tests, builds and smoke-tests the wheels, publishes both packages to PyPI, and creates a GitHub release with the
116
+ wheels, source archives and `.vsix` attached and the CHANGELOG section as its notes. A PyPI upload cannot be
117
+ replaced: if something is wrong after publishing, fix it and release the next patch version.
118
+
119
+ One-time setup, before the first release:
120
+
121
+ - On GitHub, create two environments (Settings → Environments): `pypi` and `pypi-cli`. Add yourself as a
122
+ required reviewer on both if every release should wait for your approval before publishing.
123
+ - On PyPI, add a trusted publisher for each project (for a project that does not exist yet, a "pending
124
+ publisher" under your account's Publishing settings), both with this repository and workflow `release.yml`:
125
+ `ganymede-flow` with environment `pypi`, and `ganymede-flow-cli` with environment `pypi-cli`. (PyPI allows
126
+ only one pending publisher per repository, workflow and environment, hence two environments.) No API token is
127
+ needed or stored.
128
+
129
+ The VS Code extension is attached to the GitHub release but not published to the Marketplace, which needs a
130
+ publisher account and a token; install it with `code --install-extension ganymede-vscode-0.8.0.vsix`.
131
+
132
+ CI builds are numbered by the GitHub Actions run:
133
+
134
+ - **On `main`**, a standard development version of the coming release: `ganymede_flow-0.8.0.dev18-py3-none-any.whl`,
135
+ `ganymede-vscode-0.8.0-18.vsix`, `gmd 0.8.0.dev18`. These sort below the 0.8.0 release.
136
+ - **On any other branch**, the run and the branch only: `ganymede_flow-18+feature.x-py3-none-any.whl`,
137
+ `ganymede-vscode-18-feature.x.vsix`, `gmd 18+feature.x`. These are for testing only: PyPI refuses them, and run
138
+ numbers sort above release versions, so never put them on a package index.
139
+
140
+ Neither kind is uploaded anywhere; they are kept as GitHub Actions artifacts. Only a `v*` tag publishes.
@@ -0,0 +1,110 @@
1
+ # Ganymede
2
+
3
+ Typed agent workflows you can put into production. You write workflows in Ganymede's own small language (`.gmd` files), where
4
+ agents have typed signatures, control flow is ordinary code, capabilities are declared and checked, budgets
5
+ are hard limits, and every run is journaled so it can pause for a human and resume later without redoing
6
+ finished work.
7
+
8
+ This repo holds two Python packages that are versioned and released together:
9
+
10
+ | folder | PyPI | import | what it is |
11
+ |---|---|---|---|
12
+ | `.` (root) | `ganymede-flow` | `ganymede_flow` | the engine and Python API; depends only on `lark` |
13
+ | `cli/` | `ganymede-flow-cli` | `ganymede_flow_cli` | the `gmd` command, HTTP server and language server |
14
+
15
+ ## Install from a checkout
16
+
17
+ pip install -e . -e cli
18
+
19
+ ## Try it
20
+
21
+ gmd new my-app && cd my-app
22
+ gmd doctor
23
+ gmd run src/main.gmd triage "I was charged twice!" --mock mock.json --yes
24
+
25
+ `demo/` is a ready-made project; see its README. The language reference, including every diagnostic code and
26
+ how language versions work, is [docs/language.md](docs/language.md). How run journals stay readable across
27
+ upgrades is in [docs/journal.md](docs/journal.md). The stable interfaces are the
28
+ [Python API](docs/python-api.md) and the [HTTP API](docs/http-api.md); everything else is internal.
29
+ Read [docs/security.md](docs/security.md) before exposing `gmd serve` or running tools you did not write.
30
+
31
+ ## Commands
32
+
33
+ `new`, `doctor`, `check`, `estimate`, `run`, `resume`, `runs`, `show`, `serve`, `lsp`.
34
+ Without the script installed, use `python -m ganymede_flow_cli <command>`.
35
+
36
+ - `gmd estimate` shows a flow's worst case (calls, tokens, time, cost) before you spend anything.
37
+ - `gmd serve` runs an HTTP API for a project: start runs, approve or reject paused ones (with a separate
38
+ approver token that can do nothing else), signed webhooks and schedules.
39
+ - `gmd lsp` is a language server; `editors/vscode` has a VS Code extension for it.
40
+
41
+ ## From Python (engine only)
42
+
43
+ import ganymede_flow
44
+ with ganymede_flow.load("my-app") as app: # a project folder (or a single .gmd file)
45
+ r = app.run("triage", "I was charged twice!")
46
+ if r.suspended:
47
+ r = app.resume(r.run_id, approve=True)
48
+ print(r.result)
49
+
50
+ ## What the engine does
51
+
52
+ - **Typed agents.** Each agent declares its inputs and output type; answers are validated and retried.
53
+ - **Static checks** before anything runs: capability violations, unhandled match arms, unknown variants,
54
+ unbounded loops (`loop max N` is required).
55
+ - **Capabilities, enforced.** Tools run in separate worker processes (Python and TypeScript) with a clean
56
+ environment, sandboxed to what they declare and the calling agent holds.
57
+ - **Budgets.** `within { cost: $0.50, time: 5min, calls: 20, tokens: 60k }` on a flow, an agent or a block,
58
+ with an optional `on_exceed` fallback.
59
+ - **Journaled runs.** Every model call, tool call and human decision is recorded (SQLite), so a run can wait
60
+ for approval, survive a crash, and resume by replaying finished steps instead of re-running them.
61
+
62
+ ## Layout
63
+
64
+ ganymede_flow/ engine: parser (ganymede.lark), checker, interpreter, runner, journal, host (sandboxed
65
+ tool workers), budgets, estimate, doctor, project manifests, scaffold, Python API
66
+ cli/ the ganymede-flow-cli package: gmd command line, serve (HTTP), lsp
67
+ docs/ language reference, journal compatibility, Python API, HTTP API, security
68
+ tests/ all tests: python -m pytest (works from a checkout, no install needed)
69
+ examples/ example .gmd programs used by the tests
70
+ demo/ a ready-made project
71
+ editors/vscode/ VS Code extension (talks to `gmd lsp`)
72
+
73
+ The engine never imports the CLI (`tests/test_layering.py` checks this), so `ganymede-flow` stays usable on
74
+ its own. If the two ever need separate repos, `cli/` can move out with its history.
75
+
76
+ ## Releasing
77
+
78
+ 1. Set the version in `pyproject.toml`, `cli/pyproject.toml` (and its pin on `ganymede-flow`), both `__init__.py`
79
+ files and `editors/vscode/package.json`. CI refuses to build if these disagree.
80
+ 2. In [CHANGELOG.md](CHANGELOG.md), date that version's section: `## 0.8.0 - 2026-12-01`.
81
+ 3. Merge to `main`, wait for CI to pass, then tag that commit and push the tag:
82
+ `git tag v0.8.0 && git push origin v0.8.0`.
83
+
84
+ The tag starts `.github/workflows/release.yml`. It checks the tag against every version and the CHANGELOG, runs the
85
+ tests, builds and smoke-tests the wheels, publishes both packages to PyPI, and creates a GitHub release with the
86
+ wheels, source archives and `.vsix` attached and the CHANGELOG section as its notes. A PyPI upload cannot be
87
+ replaced: if something is wrong after publishing, fix it and release the next patch version.
88
+
89
+ One-time setup, before the first release:
90
+
91
+ - On GitHub, create two environments (Settings → Environments): `pypi` and `pypi-cli`. Add yourself as a
92
+ required reviewer on both if every release should wait for your approval before publishing.
93
+ - On PyPI, add a trusted publisher for each project (for a project that does not exist yet, a "pending
94
+ publisher" under your account's Publishing settings), both with this repository and workflow `release.yml`:
95
+ `ganymede-flow` with environment `pypi`, and `ganymede-flow-cli` with environment `pypi-cli`. (PyPI allows
96
+ only one pending publisher per repository, workflow and environment, hence two environments.) No API token is
97
+ needed or stored.
98
+
99
+ The VS Code extension is attached to the GitHub release but not published to the Marketplace, which needs a
100
+ publisher account and a token; install it with `code --install-extension ganymede-vscode-0.8.0.vsix`.
101
+
102
+ CI builds are numbered by the GitHub Actions run:
103
+
104
+ - **On `main`**, a standard development version of the coming release: `ganymede_flow-0.8.0.dev18-py3-none-any.whl`,
105
+ `ganymede-vscode-0.8.0-18.vsix`, `gmd 0.8.0.dev18`. These sort below the 0.8.0 release.
106
+ - **On any other branch**, the run and the branch only: `ganymede_flow-18+feature.x-py3-none-any.whl`,
107
+ `ganymede-vscode-18-feature.x.vsix`, `gmd 18+feature.x`. These are for testing only: PyPI refuses them, and run
108
+ numbers sort above release versions, so never put them on a package index.
109
+
110
+ Neither kind is uploaded anywhere; they are kept as GitHub Actions artifacts. Only a `v*` tag publishes.
@@ -0,0 +1,22 @@
1
+ """Ganymede: typed agent workflows in a small language of their own, with declared capabilities, budgets, and runs that
2
+ pause and resume.
3
+
4
+ import ganymede_flow
5
+ with ganymede_flow.load("my-app") as app:
6
+ r = app.run("triage", "I was charged twice!")
7
+
8
+ The public Python API is exactly the names in __all__, documented in docs/python-api.md. Every submodule
9
+ (ganymede_flow.parser, .journal, ...) is internal and may change in any release.
10
+ """
11
+ __version__ = "0.8.0"
12
+
13
+ _API = ("load", "run", "Project", "RunResult", "GanymedeError", "GanymedeCheckError", "GanymedeUsageError",
14
+ "RunFailed")
15
+ __all__ = ["__version__", *_API]
16
+
17
+
18
+ def __getattr__(name): # loaded on first use: `import ganymede_flow` stays cheap and cycle-free
19
+ if name in _API:
20
+ from . import api
21
+ return getattr(api, name)
22
+ raise AttributeError(f"module 'ganymede_flow' has no attribute {name!r}")
@@ -0,0 +1,332 @@
1
+ """Use Ganymede from Python, without the command line.
2
+
3
+ import ganymede_flow
4
+
5
+ with ganymede_flow.load("my-app") as app: # a project folder (or a single .gmd file)
6
+ r = app.run("triage", "I was charged twice!") # same checks, budgets, journal and sandbox as `gmd run`
7
+ if r.suspended: # waiting at human.approve
8
+ print(r.awaiting["asking"])
9
+ r = app.resume(r.run_id, approve=True)
10
+ print(r.status, r.result) # result is plain Python data (dicts, lists, strings)
11
+
12
+ reply = ganymede_flow.run("my-app", "triage", "I was charged twice!", auto_approve=True) # one call, value or raise
13
+
14
+ Nothing here prompts on the console or prints unless you pass `trace=True`; a run that needs a person comes
15
+ back `suspended` and you decide when to resume it. Runs are journaled exactly like CLI runs (in the project's
16
+ journal by default), so `gmd runs`, `gmd show` and `gmd serve` see them too.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import copy
21
+ import difflib
22
+ import json
23
+ import os
24
+ import sys
25
+ from dataclasses import dataclass
26
+ from pathlib import Path
27
+ from typing import Any, Optional, Union
28
+
29
+ from . import nodes as N
30
+ from .checker import Checker
31
+ from .diagnostics import Diagnostic, render
32
+ from .doctor import flow_files
33
+ from .errors import GanymedeError
34
+ from .estimate import EstimateConfig, Estimator, missing_prices
35
+ from .host import settings_for
36
+ from .journal import Journal, loads
37
+ from .modules import Unit, compile_file, compile_stored
38
+ from .parser import parse
39
+
40
+
41
+ def _parse(source: str):
42
+ return parse(source) # looked up on each call, so tests can substitute `api.parse`
43
+ from .project import Manifest, discover
44
+ from .providers import AnthropicProvider, MockProvider
45
+ from .runner import RunOptions, resume_run, start_run
46
+ from .trace import Tracer
47
+ from .typeops import TypeEnv, ValidationError
48
+ from .values import to_jsonable
49
+
50
+ DEFAULT_JOURNAL = ".ganymede/journal.db"
51
+
52
+
53
+ class GanymedeCheckError(GanymedeError):
54
+ """A .gmd file does not parse or check. `diagnostics` holds every problem; str() shows them like `gmd check`."""
55
+
56
+ def __init__(self, path: Path, source: str, diagnostics: list, unit: Optional[Unit] = None):
57
+ self.path, self.source, self.diagnostics = path, source, diagnostics
58
+ errors = [d for d in diagnostics if d.is_error]
59
+ show = unit.render if unit is not None else (lambda d: render(d, source, str(path)))
60
+ super().__init__(f"{path} has {len(errors)} error(s):\n\n" + "\n\n".join(show(d) for d in errors))
61
+
62
+ @classmethod
63
+ def of(cls, unit: Unit) -> "GanymedeCheckError":
64
+ return cls(unit.path, unit.source, unit.diagnostics, unit)
65
+
66
+
67
+ class GanymedeUsageError(GanymedeError):
68
+ """The call itself is wrong: an unknown flow, bad arguments, no model configured, a missing price."""
69
+
70
+
71
+ class RunFailed(GanymedeError):
72
+ """Raised by `ganymede_flow.run(...)` and `RunResult.value()` when a run did not finish with a result."""
73
+
74
+ def __init__(self, result: "RunResult"):
75
+ super().__init__(f"run {result.run_id} ended `{result.status}`: {result.message or 'no details'}")
76
+ self.result = result
77
+
78
+
79
+ @dataclass
80
+ class RunResult:
81
+ run_id: str
82
+ status: str # done | suspended | failed | error | interrupted
83
+ result: Any = None # plain Python data when status == "done"
84
+ message: str = "" # why it stopped, when it did not finish
85
+ awaiting: Optional[dict] = None # {"step": "1", "asking": ...} when suspended
86
+ replayed: int = 0 # steps answered from the journal instead of being run again
87
+
88
+ @property
89
+ def done(self) -> bool:
90
+ return self.status == "done"
91
+
92
+ @property
93
+ def suspended(self) -> bool:
94
+ return self.status == "suspended"
95
+
96
+ def value(self) -> Any:
97
+ """The result, or RunFailed if the run did not finish (a suspended run did not finish either)."""
98
+ if not self.done:
99
+ raise RunFailed(self)
100
+ return self.result
101
+
102
+
103
+ class Project:
104
+ """A Ganymede project (a folder with .gmd files and usually a ganymede.toml) or a single .gmd file.
105
+
106
+ Model access, in order: `provider` (any object with the provider interface), `mock` (a dict or the path of
107
+ a JSON script, as for --mock), `api_key`, else the ANTHROPIC_API_KEY environment variable.
108
+ """
109
+
110
+ def __init__(self, path: Union[str, os.PathLike] = ".", *, api_key: Optional[str] = None, provider=None,
111
+ mock: Union[None, str, os.PathLike, dict] = None, journal: Union[None, str, os.PathLike] = None,
112
+ model: Optional[str] = None, trace: Union[bool, Any] = False):
113
+ target = Path(path).resolve()
114
+ if not target.exists():
115
+ raise FileNotFoundError(f"no such project or file: {target}")
116
+ self.single_file = target if target.is_file() else None
117
+ folder = target.parent if self.single_file else target
118
+ self.manifest: Optional[Manifest] = discover(folder)
119
+ self.root = self.manifest.root if self.manifest else folder
120
+ self._api_key, self._provider, self._model = api_key, provider, model
121
+ self._mock = self._load_mock(mock)
122
+ self._trace = trace
123
+ if journal is None:
124
+ jp = (self.manifest.journal_path() if self.manifest and self.manifest.journal_path()
125
+ else self.root / DEFAULT_JOURNAL)
126
+ else:
127
+ jp = journal if str(journal) == ":memory:" else Path(journal)
128
+ self.journal = Journal(jp)
129
+ self._files: dict = {}
130
+
131
+ # ---------------------------------------------------------------- lifecycle
132
+ def close(self) -> None:
133
+ self.journal.close()
134
+
135
+ def __enter__(self) -> "Project":
136
+ return self
137
+
138
+ def __exit__(self, *exc) -> None:
139
+ self.close()
140
+
141
+ # ---------------------------------------------------------------- loading
142
+ @staticmethod
143
+ def _load_mock(mock):
144
+ if mock is None or isinstance(mock, dict):
145
+ return mock
146
+ with open(mock, encoding="utf-8") as f:
147
+ return json.load(f)
148
+
149
+ def _paths(self) -> list:
150
+ return [self.single_file] if self.single_file else flow_files(self.root)
151
+
152
+ def _file(self, path: Path) -> Unit:
153
+ """The file with its imports, checked; recompiled only when it or something it imports changed."""
154
+ cached = self._files.get(path)
155
+ if cached is not None and cached.fresh():
156
+ return cached
157
+ unit = self._files[path] = compile_file(path, parse=_parse)
158
+ return unit
159
+
160
+ def check(self) -> dict:
161
+ """Every .gmd file's diagnostics (errors and warnings), keyed by path. Empty lists mean clean. A file's
162
+ diagnostics include problems in the files it imports (each diagnostic's `pos.file` says which)."""
163
+ return {u.path: u.diagnostics for u in (self._file(p) for p in self._paths())}
164
+
165
+ def flows(self) -> list:
166
+ """Names of the flows in files that check cleanly (each flow once, in the file that declares it)."""
167
+ out = []
168
+ for p in self._paths():
169
+ f = self._file(p)
170
+ if f.ok:
171
+ out += [d.name for d in f.program.decls if isinstance(d, N.FlowDecl) and f.owns(d)]
172
+ return out
173
+
174
+ def _find(self, name: str, file):
175
+ paths = self._paths()
176
+ if file is not None:
177
+ target = (self.root / file).resolve()
178
+ paths = [p for p in paths if p.resolve() == target]
179
+ if not paths:
180
+ raise GanymedeUsageError(f"no .gmd file {file} in {self.root}")
181
+ found, broken = [], []
182
+ for p in paths:
183
+ f = self._file(p)
184
+ mine = [] if f.program is None else [d for d in f.program.decls
185
+ if isinstance(d, N.FlowDecl) and d.name == name and f.owns(d)]
186
+ if f.program is None or not f.ok:
187
+ if mine:
188
+ raise GanymedeCheckError.of(f)
189
+ if f.program is None:
190
+ broken.append(f)
191
+ continue
192
+ found += [(f, d) for d in mine]
193
+ if not found:
194
+ if len(broken) == 1 and (self.single_file or file):
195
+ raise GanymedeCheckError.of(broken[0])
196
+ names = self.flows()
197
+ near = difflib.get_close_matches(name, names, n=1)
198
+ raise GanymedeUsageError(f"no flow named `{name}`" + (f"; did you mean `{near[0]}`?" if near else
199
+ f"; flows here: {', '.join(names) or '(none)'}")
200
+ + (f" ({len(broken)} file(s) did not parse; see check())" if broken else ""))
201
+ if len(found) > 1:
202
+ raise GanymedeUsageError(f"`{name}` is defined in more than one file "
203
+ f"({', '.join(str(f.path) for f, _ in found)}); pass file=")
204
+ return found[0]
205
+
206
+ # ---------------------------------------------------------------- running
207
+ def _args(self, flow: N.FlowDecl, chk: Checker, args: tuple, kwargs: dict) -> dict:
208
+ names = [p.name for p in flow.params]
209
+ if args and kwargs:
210
+ raise GanymedeUsageError("pass the flow's arguments either by position or by name, not both")
211
+ if kwargs:
212
+ if set(kwargs) != set(names):
213
+ raise GanymedeUsageError(f"flow `{flow.name}` takes {names}; got {sorted(kwargs)}")
214
+ ordered = [kwargs[n] for n in names]
215
+ else:
216
+ if len(args) != len(names):
217
+ raise GanymedeUsageError(f"flow `{flow.name}` takes {len(names)} argument(s) {names}, got {len(args)}")
218
+ ordered = list(args)
219
+ tenv, out = TypeEnv(chk.types), {}
220
+ for p, v in zip(flow.params, ordered):
221
+ if tenv.is_text(p.type):
222
+ if not isinstance(v, str):
223
+ raise GanymedeUsageError(f"argument `{p.name}` must be a str")
224
+ out[p.name] = v
225
+ continue
226
+ try:
227
+ out[p.name] = tenv.validate(p.type, v)
228
+ except ValidationError as e:
229
+ raise GanymedeUsageError(f"argument `{p.name}`: {e}") from None
230
+ return out
231
+
232
+ def _provider_now(self):
233
+ if self._provider is not None:
234
+ return self._provider
235
+ if self._mock is not None:
236
+ return MockProvider(copy.deepcopy(self._mock)) # a fresh script for every run
237
+ key = self._api_key or os.environ.get("ANTHROPIC_API_KEY")
238
+ if not key:
239
+ raise GanymedeUsageError("no model access: pass api_key=, provider= or mock=, or set ANTHROPIC_API_KEY")
240
+ return AnthropicProvider(key)
241
+
242
+ def _tracer(self) -> Tracer:
243
+ if self._trace is True:
244
+ return Tracer(stream=sys.stderr)
245
+ if self._trace:
246
+ return Tracer(stream=self._trace) # a file-like object to write the trace to
247
+ return Tracer(enabled=False)
248
+
249
+ def _opts(self, **extra) -> RunOptions:
250
+ m = self.manifest
251
+ return RunOptions(interactive=False, model=self._model, models=m.models if m else None,
252
+ prices=m.prices if m else None, host=settings_for(m, self.root),
253
+ language=m.language if m else "1",
254
+ **(m.run_limits if m else {}), **extra)
255
+
256
+ def _result(self, outcome) -> RunResult:
257
+ r = RunResult(outcome.run_id, outcome.status, to_jsonable(outcome.result) if outcome.status == "done" else None,
258
+ outcome.message, None, outcome.replayed)
259
+ if outcome.status == "suspended":
260
+ r.awaiting = {"step": outcome.step, "asking": to_jsonable(outcome.value)}
261
+ return r
262
+
263
+ def run(self, flow: str, *args, file: Optional[str] = None, auto_approve: bool = False, **kwargs) -> RunResult:
264
+ """Start a run and carry it as far as it goes: to a result, a failure, or a pause for a person."""
265
+ entry, decl = self._find(flow, file)
266
+ values = self._args(decl, entry.chk, args, kwargs)
267
+ m = self.manifest
268
+ absent = missing_prices(entry.chk, m.prices if m else {}, m.models if m else None, self._model)
269
+ if absent:
270
+ raise GanymedeUsageError("a budget limits `cost`, but no price is configured for: " + ", ".join(absent)
271
+ + ' (add [prices."<model>"] with input and output to ganymede.toml)')
272
+ base = (m.host_dirs() if m else []) + [entry.path.parent, entry.path.parent.parent, self.root]
273
+ outcome = start_run(self.journal, entry.chk, decl, values, entry.stored, entry.path, base,
274
+ self._provider_now(), self._tracer(), self._opts(auto_yes=auto_approve))
275
+ return self._result(outcome)
276
+
277
+ def resume(self, run_id: str, *, approve: Optional[bool] = None, rerun: bool = False,
278
+ by: str = "python") -> RunResult:
279
+ """Continue a run: answer its pending approval (approve=True/False), or retry one that errored."""
280
+ if self.journal.get_run(run_id) is None:
281
+ raise GanymedeUsageError(f"no run `{run_id}` in {self.journal.path}")
282
+
283
+ def loader(source: str) -> Checker:
284
+ unit = compile_stored(source, self.journal.get_run(run_id)["file_path"] or None, parse=_parse)
285
+ if unit.errors:
286
+ raise GanymedeCheckError(Path(unit.path or "stored source"), unit.source, unit.errors, unit)
287
+ return unit.chk
288
+
289
+ outcome = resume_run(self.journal, run_id, loader, self._provider_now(), self._tracer(),
290
+ self._opts(decision=approve, decision_source=f"api:{by}", rerun=rerun))
291
+ return self._result(outcome)
292
+
293
+ def get(self, run_id: str) -> RunResult:
294
+ """The current state of a run, without running anything."""
295
+ run = self.journal.get_run(run_id)
296
+ if run is None:
297
+ raise GanymedeUsageError(f"no run `{run_id}` in {self.journal.path}")
298
+ r = RunResult(run_id, run["status"], to_jsonable(loads(run["result"])) if run["result"] else None,
299
+ run["error"] or "")
300
+ pending = self.journal.pending_step(run_id) if run["status"] == "suspended" else None
301
+ if pending:
302
+ r.awaiting = {"step": pending["step"], "asking": to_jsonable((loads(pending["input"]) or {}).get("value"))}
303
+ return r
304
+
305
+ def runs(self, status: Optional[str] = None, limit: int = 50) -> list:
306
+ return [{k: r[k] for k in ("run_id", "flow", "status", "trigger", "created")}
307
+ for r in self.journal.list_runs(status, limit)]
308
+
309
+ def estimate(self, flow: str, *, file: Optional[str] = None) -> dict:
310
+ """The flow's static worst case (see `gmd estimate`): calls, tokens, cost in USD (None if a model has no
311
+ price) and seconds."""
312
+ entry, decl = self._find(flow, file)
313
+ m = self.manifest
314
+ cfg = EstimateConfig(**({**m.run_limits, **m.estimate} if m else {}))
315
+ e = Estimator(entry.chk, cfg, prices=m.prices if m else None, models=m.models if m else None,
316
+ model_override=self._model).flow(decl, cap=False)
317
+ return {"calls": e.calls, "input_tokens": e.tin, "output_tokens": e.tout,
318
+ "cost_usd": None if e.cost is None else e.cost / 1_000_000, "seconds": e.ms / 1000}
319
+
320
+
321
+ def load(path: Union[str, os.PathLike] = ".", **kwargs) -> Project:
322
+ """Open a project folder or a single .gmd file. See Project for the options."""
323
+ return Project(path, **kwargs)
324
+
325
+
326
+ def run(path: Union[str, os.PathLike], flow: str, *args, auto_approve: bool = False, **kwargs):
327
+ """Run a flow once and return its result. Raises RunFailed if it does not finish (including when it stops to
328
+ wait for a person and auto_approve is False). Project options (mock=, api_key=, ...) go in kwargs."""
329
+ options = {k: kwargs.pop(k) for k in list(kwargs) if k in ("api_key", "provider", "mock", "journal", "model", "trace")}
330
+ file = kwargs.pop("file", None)
331
+ with Project(path, **options) as project:
332
+ return project.run(flow, *args, file=file, auto_approve=auto_approve, **kwargs).value()