tina-cli 0.1.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.
- tina/__init__.py +23 -0
- tina/__main__.py +11 -0
- tina/cli.py +254 -0
- tina/config.py +284 -0
- tina/errors.py +25 -0
- tina/executors/__init__.py +22 -0
- tina/executors/base.py +20 -0
- tina/executors/cloudrun.py +86 -0
- tina/executors/local.py +47 -0
- tina/harness.py +115 -0
- tina/log.py +45 -0
- tina/models.py +90 -0
- tina/output.py +51 -0
- tina/prompt.py +86 -0
- tina/sources/__init__.py +21 -0
- tina/sources/base.py +68 -0
- tina/sources/github.py +154 -0
- tina/sources/jira.py +171 -0
- tina/verify.py +92 -0
- tina_cli-0.1.0.dist-info/METADATA +112 -0
- tina_cli-0.1.0.dist-info/RECORD +24 -0
- tina_cli-0.1.0.dist-info/WHEEL +4 -0
- tina_cli-0.1.0.dist-info/entry_points.txt +2 -0
- tina_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
tina/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Tina — an autonomous factory.
|
|
2
|
+
|
|
3
|
+
Orchestration only: select a work item, claim it, call an agent once with a
|
|
4
|
+
one-shot prompt, read the outcome the agent wrote, verify it, record it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
8
|
+
|
|
9
|
+
#: `project.name` in pyproject.toml. The import package is `tina`, the
|
|
10
|
+
#: distribution is `tina-cli`; tests/test_version.py pins the two together so a
|
|
11
|
+
#: rename cannot silently drop `__version__` to the fallback.
|
|
12
|
+
DIST_NAME = "tina-cli"
|
|
13
|
+
|
|
14
|
+
#: Used when the distribution is not installed — running straight from a
|
|
15
|
+
#: checkout, for example. Importing `tina` must never raise.
|
|
16
|
+
FALLBACK_VERSION = "0.0.0+unknown"
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
__version__ = version(DIST_NAME)
|
|
20
|
+
except PackageNotFoundError:
|
|
21
|
+
__version__ = FALLBACK_VERSION
|
|
22
|
+
|
|
23
|
+
__all__ = ["DIST_NAME", "FALLBACK_VERSION", "__version__"]
|
tina/__main__.py
ADDED
tina/cli.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""`tina dispatch` and `tina run`. Two roles, one image.
|
|
2
|
+
|
|
3
|
+
The typer commands are a thin shell: they parse argv, load config, and turn a
|
|
4
|
+
`TinaError` into exit 1. The orchestration lives in `dispatch_workflow` and
|
|
5
|
+
`run_item`, which take already-built objects so callers (and tests) can inject
|
|
6
|
+
a source or executor.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import tempfile
|
|
12
|
+
import time
|
|
13
|
+
from collections.abc import Iterator
|
|
14
|
+
from contextlib import contextmanager
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Annotated
|
|
17
|
+
|
|
18
|
+
import typer
|
|
19
|
+
|
|
20
|
+
from tina import executors, harness, log, output, prompt, sources, verify
|
|
21
|
+
from tina.config import Config, WorkflowConfig
|
|
22
|
+
from tina.config import load as load_config
|
|
23
|
+
from tina.errors import TinaError
|
|
24
|
+
from tina.executors.base import Executor
|
|
25
|
+
from tina.models import OutcomeReport, OutcomeStatus, RunRecord, WorkItem
|
|
26
|
+
from tina.sources.base import Source
|
|
27
|
+
|
|
28
|
+
DEFAULT_CONFIG = Path("tina.toml")
|
|
29
|
+
|
|
30
|
+
logger = log.get_logger("tina")
|
|
31
|
+
|
|
32
|
+
app = typer.Typer(
|
|
33
|
+
name="tina",
|
|
34
|
+
help="An autonomous factory: claim a work item, run an agent once, record it.",
|
|
35
|
+
no_args_is_help=True,
|
|
36
|
+
add_completion=False,
|
|
37
|
+
pretty_exceptions_enable=False,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
WorkflowOption = Annotated[str, typer.Option("--workflow", help="Workflow table in the config.")]
|
|
41
|
+
ConfigOption = Annotated[Path, typer.Option("--config", help="Path to the TOML config file.")]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _version_callback(value: bool) -> None:
|
|
45
|
+
"""Print the version and stop before any config is loaded.
|
|
46
|
+
|
|
47
|
+
The module is imported and read through, rather than binding `__version__`
|
|
48
|
+
at import time, so the value stays correct when tests reload `tina`.
|
|
49
|
+
"""
|
|
50
|
+
if value:
|
|
51
|
+
import tina
|
|
52
|
+
|
|
53
|
+
typer.echo(f"tina {tina.__version__}")
|
|
54
|
+
raise typer.Exit()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@app.callback()
|
|
58
|
+
def _global_options(
|
|
59
|
+
version: Annotated[
|
|
60
|
+
bool,
|
|
61
|
+
typer.Option(
|
|
62
|
+
"--version", callback=_version_callback, is_eager=True, help="Show tina version."
|
|
63
|
+
),
|
|
64
|
+
] = False,
|
|
65
|
+
) -> None:
|
|
66
|
+
"""An autonomous factory: claim a work item, run an agent once, record it."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@app.command()
|
|
70
|
+
def dispatch(
|
|
71
|
+
workflow: WorkflowOption,
|
|
72
|
+
limit: Annotated[
|
|
73
|
+
int, typer.Option("--limit", help="Maximum number of workers to enqueue.")
|
|
74
|
+
] = 1,
|
|
75
|
+
config: ConfigOption = DEFAULT_CONFIG,
|
|
76
|
+
dry_run: Annotated[
|
|
77
|
+
bool,
|
|
78
|
+
typer.Option("--dry-run", help="Preview the matched items without enqueueing anything."),
|
|
79
|
+
] = False,
|
|
80
|
+
) -> None:
|
|
81
|
+
"""Run the source query and enqueue up to --limit workers."""
|
|
82
|
+
with _exit_on_tina_error("dispatch"):
|
|
83
|
+
dispatch_workflow(load_config(config), workflow, limit, dry_run=dry_run)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@app.command()
|
|
87
|
+
def run(
|
|
88
|
+
workflow: WorkflowOption,
|
|
89
|
+
item: Annotated[str, typer.Option("--item", help="Tracker identifier of the work item.")],
|
|
90
|
+
config: ConfigOption = DEFAULT_CONFIG,
|
|
91
|
+
) -> None:
|
|
92
|
+
"""Claim one work item, run the agent, record the outcome."""
|
|
93
|
+
with _exit_on_tina_error("run"):
|
|
94
|
+
run_item(load_config(config), workflow, item)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@contextmanager
|
|
98
|
+
def _exit_on_tina_error(command: str) -> Iterator[None]:
|
|
99
|
+
"""Exit 1 for Tina's own failures — and only those.
|
|
100
|
+
|
|
101
|
+
An agent reporting `failed` never lands here: that is an outcome, not a
|
|
102
|
+
process failure, so the run still exits 0.
|
|
103
|
+
|
|
104
|
+
Both halves of the boundary fire: the JSON record on stdout for whatever is
|
|
105
|
+
collecting runs, and the human block on stderr for whoever ran the command.
|
|
106
|
+
"""
|
|
107
|
+
log.configure()
|
|
108
|
+
try:
|
|
109
|
+
yield
|
|
110
|
+
except TinaError as exc:
|
|
111
|
+
logger.error(str(exc), extra={"command": command})
|
|
112
|
+
output.error(str(exc), exc.cause, exc.fix)
|
|
113
|
+
raise typer.Exit(code=1) from None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def dispatch_workflow(
|
|
117
|
+
config: Config,
|
|
118
|
+
workflow_name: str,
|
|
119
|
+
limit: int,
|
|
120
|
+
source: Source | None = None,
|
|
121
|
+
executor: Executor | None = None,
|
|
122
|
+
dry_run: bool = False,
|
|
123
|
+
) -> None:
|
|
124
|
+
"""Query, take up to `limit` items, enqueue one worker each.
|
|
125
|
+
|
|
126
|
+
The dispatcher never runs an agent and never claims — workers claim, so a
|
|
127
|
+
dispatcher that dies mid-loop leaves nothing stuck.
|
|
128
|
+
|
|
129
|
+
`dry_run` moves the boundary to the last step only: the real source is built
|
|
130
|
+
and the real query runs against the live tracker, but no executor is ever
|
|
131
|
+
constructed. That a preview enqueues nothing follows from the absence of an
|
|
132
|
+
executor, not from a branch inside the loop that nobody took. The one thing
|
|
133
|
+
it therefore cannot report is a `cloudrun` executor with no
|
|
134
|
+
`[executors.cloudrun]` table — a table that is present but incomplete still
|
|
135
|
+
fails at config load, whichever mode this runs in.
|
|
136
|
+
"""
|
|
137
|
+
workflow = config.workflow(workflow_name)
|
|
138
|
+
source = source or sources.build(workflow)
|
|
139
|
+
if dry_run:
|
|
140
|
+
_preview(config, workflow, source.query(workflow.query)[: max(limit, 0)], limit)
|
|
141
|
+
return
|
|
142
|
+
|
|
143
|
+
executor = executor or executors.build(config)
|
|
144
|
+
items = source.query(workflow.query)[: max(limit, 0)]
|
|
145
|
+
logger.info(
|
|
146
|
+
"dispatching",
|
|
147
|
+
extra={"workflow": workflow.name, "limit": limit, "matched": len(items)},
|
|
148
|
+
)
|
|
149
|
+
for item in items:
|
|
150
|
+
executor.enqueue(workflow.name, item.id)
|
|
151
|
+
logger.info("enqueued", extra=_item_fields(workflow.name, item, config.executor))
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _item_fields(workflow: str, item: WorkItem, executor: str) -> dict[str, str]:
|
|
155
|
+
"""The per-item stdout schema, shared by `enqueued` and `would enqueue`.
|
|
156
|
+
|
|
157
|
+
One function so the two lines cannot drift: anything parsing the log by
|
|
158
|
+
field keeps working across both modes.
|
|
159
|
+
"""
|
|
160
|
+
return {
|
|
161
|
+
"workflow": workflow,
|
|
162
|
+
"item": item.id,
|
|
163
|
+
"url": str(item.url or ""),
|
|
164
|
+
"executor": executor,
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _preview(config: Config, workflow: WorkflowConfig, items: list[WorkItem], limit: int) -> None:
|
|
169
|
+
"""The dry-run half: same query, same fields, no executor and no enqueue.
|
|
170
|
+
|
|
171
|
+
The message is `would enqueue`, never `enqueued`, so a collector filtering
|
|
172
|
+
on `message` can never count a preview as a real dispatch. The `dry_run`
|
|
173
|
+
marker is added only here, so a normal dispatch carries no such key at all.
|
|
174
|
+
"""
|
|
175
|
+
logger.info(
|
|
176
|
+
"dispatching",
|
|
177
|
+
extra={"workflow": workflow.name, "limit": limit, "matched": len(items), "dry_run": True},
|
|
178
|
+
)
|
|
179
|
+
output.dry_run_header()
|
|
180
|
+
for item in items:
|
|
181
|
+
line = f"Would enqueue {item.id} via {config.executor}"
|
|
182
|
+
output.would(f"{line} — {item.title}" if item.title else line)
|
|
183
|
+
logger.info(
|
|
184
|
+
"would enqueue",
|
|
185
|
+
extra=_item_fields(workflow.name, item, config.executor) | {"dry_run": True},
|
|
186
|
+
)
|
|
187
|
+
output.dry_run_footer(f"{len(items)} items matched (limit {limit}).")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def run_item(
|
|
191
|
+
config: Config,
|
|
192
|
+
workflow_name: str,
|
|
193
|
+
item_id: str,
|
|
194
|
+
source: Source | None = None,
|
|
195
|
+
) -> RunRecord:
|
|
196
|
+
"""Claim one item, run the agent once, verify, record.
|
|
197
|
+
|
|
198
|
+
Returns the record it logged. Every agent outcome is a successful run — the
|
|
199
|
+
outcome is data, not a process failure — so this never signals via an
|
|
200
|
+
exception unless Tina itself broke.
|
|
201
|
+
"""
|
|
202
|
+
started = time.monotonic()
|
|
203
|
+
workflow = config.workflow(workflow_name)
|
|
204
|
+
source = source or sources.build(workflow)
|
|
205
|
+
|
|
206
|
+
item = source.get(item_id)
|
|
207
|
+
if not source.claim(item):
|
|
208
|
+
logger.info("already claimed", extra={"workflow": workflow.name, "item": item.id})
|
|
209
|
+
return _record(
|
|
210
|
+
workflow.name,
|
|
211
|
+
item.id,
|
|
212
|
+
OutcomeReport(
|
|
213
|
+
outcome=OutcomeStatus.NO_ACTION_NEEDED,
|
|
214
|
+
details="another worker holds this item",
|
|
215
|
+
),
|
|
216
|
+
exit_code=None,
|
|
217
|
+
started=started,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
harness_config = config.harness_config()
|
|
221
|
+
with tempfile.TemporaryDirectory(prefix="tina-") as tmp:
|
|
222
|
+
workdir = Path(tmp)
|
|
223
|
+
text = prompt.build(config.activity_dir(workflow), item, harness.outcome_path(workdir))
|
|
224
|
+
result = harness.run(harness_config, text, workdir)
|
|
225
|
+
|
|
226
|
+
report = verify.verify(result.report)
|
|
227
|
+
return _record(workflow.name, item.id, report, result.exit_code, started)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _record(
|
|
231
|
+
workflow: str,
|
|
232
|
+
item: str,
|
|
233
|
+
report: OutcomeReport,
|
|
234
|
+
exit_code: int | None,
|
|
235
|
+
started: float,
|
|
236
|
+
) -> RunRecord:
|
|
237
|
+
record = RunRecord.build(
|
|
238
|
+
workflow=workflow,
|
|
239
|
+
item=item,
|
|
240
|
+
report=report,
|
|
241
|
+
exit_code=exit_code,
|
|
242
|
+
duration_seconds=time.monotonic() - started,
|
|
243
|
+
)
|
|
244
|
+
logger.info("run complete", extra=record.model_dump(mode="json"))
|
|
245
|
+
return record
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def main() -> None:
|
|
249
|
+
"""Console script and `python -m tina` entrypoint."""
|
|
250
|
+
app()
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
if __name__ == "__main__": # pragma: no cover
|
|
254
|
+
main()
|
tina/config.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""TOML configuration.
|
|
2
|
+
|
|
3
|
+
A config file declares which harness and executor to use, how to invoke each
|
|
4
|
+
harness, and one table per workflow::
|
|
5
|
+
|
|
6
|
+
harness = "pi"
|
|
7
|
+
executor = "local"
|
|
8
|
+
activities_dir = "activities"
|
|
9
|
+
|
|
10
|
+
[harnesses.pi]
|
|
11
|
+
command = ["pi", "--prompt-file", "{prompt_file}"]
|
|
12
|
+
|
|
13
|
+
[vul]
|
|
14
|
+
source = "jira"
|
|
15
|
+
query = "project = VUL AND status = Open AND assignee IS EMPTY"
|
|
16
|
+
activity = "remediate"
|
|
17
|
+
result = "github:pr"
|
|
18
|
+
|
|
19
|
+
Every table that is not `harnesses` or `executors` is a workflow, keyed by its
|
|
20
|
+
table name.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import re
|
|
26
|
+
import tomllib
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any, Literal
|
|
29
|
+
|
|
30
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
|
|
31
|
+
|
|
32
|
+
from tina.errors import TinaError
|
|
33
|
+
|
|
34
|
+
SOURCES = ("jira", "github")
|
|
35
|
+
EXECUTORS = ("local", "cloudrun")
|
|
36
|
+
|
|
37
|
+
#: The only substitutions a harness command line may reference.
|
|
38
|
+
PLACEHOLDERS = frozenset({"prompt_file", "outcome_dir"})
|
|
39
|
+
# Hyphens are matched so that `{prompt-file}` is reported as the typo it is,
|
|
40
|
+
# rather than falling through to the vaguer "no {prompt_file}" complaint. JSON
|
|
41
|
+
# and shell brace expansions do not match: they contain quotes, colons, commas.
|
|
42
|
+
_PLACEHOLDER = re.compile(r"\{([a-z][a-z0-9_-]*)\}")
|
|
43
|
+
|
|
44
|
+
# Top-level scalars, as opposed to tables that define adapters or workflows.
|
|
45
|
+
_SCALAR_KEYS = frozenset({"harness", "executor", "activities_dir"})
|
|
46
|
+
_ADAPTER_TABLES = frozenset({"harnesses", "executors"})
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ConfigError(TinaError, ValueError):
|
|
50
|
+
"""Raised for anything wrong with a config file. Always names the file."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ArgvTemplate(BaseModel):
|
|
54
|
+
"""A harness command line with the run-specific paths still to fill in.
|
|
55
|
+
|
|
56
|
+
Validated at config load, because both mistakes it catches are otherwise
|
|
57
|
+
silent: a typo'd placeholder is passed to the agent verbatim as a literal
|
|
58
|
+
argument, and a template with no `{prompt_file}` runs an agent that was
|
|
59
|
+
never given the prompt.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
args: list[str] = Field(min_length=1)
|
|
63
|
+
|
|
64
|
+
@model_validator(mode="before")
|
|
65
|
+
@classmethod
|
|
66
|
+
def _accept_bare_list(cls, data: Any) -> Any:
|
|
67
|
+
"""`command = [...]` in TOML is the list itself, not a table."""
|
|
68
|
+
return {"args": data} if isinstance(data, list) else data
|
|
69
|
+
|
|
70
|
+
@model_validator(mode="after")
|
|
71
|
+
def _check_placeholders(self) -> ArgvTemplate:
|
|
72
|
+
used = {match.group(1) for arg in self.args for match in _PLACEHOLDER.finditer(arg)}
|
|
73
|
+
unknown = sorted(used - PLACEHOLDERS)
|
|
74
|
+
if unknown:
|
|
75
|
+
known = ", ".join(f"{{{name}}}" for name in sorted(PLACEHOLDERS))
|
|
76
|
+
named = ", ".join(f"{{{name}}}" for name in unknown)
|
|
77
|
+
raise ValueError(f"unknown placeholder(s) {named}; only {known} are substituted")
|
|
78
|
+
if "prompt_file" not in used:
|
|
79
|
+
raise ValueError(
|
|
80
|
+
"must reference {prompt_file} somewhere, or the agent never receives the prompt"
|
|
81
|
+
)
|
|
82
|
+
return self
|
|
83
|
+
|
|
84
|
+
def render(self, prompt_file: Path, outcome_dir: Path) -> list[str]:
|
|
85
|
+
"""Substitute the run-specific paths. Everything else passes through."""
|
|
86
|
+
substitutions = {"{prompt_file}": str(prompt_file), "{outcome_dir}": str(outcome_dir)}
|
|
87
|
+
rendered = []
|
|
88
|
+
for arg in self.args:
|
|
89
|
+
for token, value in substitutions.items():
|
|
90
|
+
arg = arg.replace(token, value)
|
|
91
|
+
rendered.append(arg)
|
|
92
|
+
return rendered
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class HarnessConfig(BaseModel):
|
|
96
|
+
"""How to invoke one agent harness."""
|
|
97
|
+
|
|
98
|
+
model_config = ConfigDict(extra="forbid")
|
|
99
|
+
|
|
100
|
+
name: str
|
|
101
|
+
command: ArgvTemplate
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class CloudRunOptions(BaseModel):
|
|
105
|
+
"""`[executors.cloudrun]`. Which job the dispatcher creates executions of."""
|
|
106
|
+
|
|
107
|
+
model_config = ConfigDict(extra="forbid")
|
|
108
|
+
|
|
109
|
+
project: str = Field(min_length=1)
|
|
110
|
+
region: str = Field(min_length=1)
|
|
111
|
+
job: str = Field(min_length=1)
|
|
112
|
+
|
|
113
|
+
def job_path(self) -> str:
|
|
114
|
+
return f"projects/{self.project}/locations/{self.region}/jobs/{self.job}"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class ExecutorOptions(BaseModel):
|
|
118
|
+
"""The `[executors.*]` tables. `local` takes none, so it has no entry."""
|
|
119
|
+
|
|
120
|
+
model_config = ConfigDict(extra="forbid")
|
|
121
|
+
|
|
122
|
+
cloudrun: CloudRunOptions | None = None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class WorkflowConfig(BaseModel):
|
|
126
|
+
"""One `source -> activity -> result` pipeline."""
|
|
127
|
+
|
|
128
|
+
model_config = ConfigDict(extra="forbid")
|
|
129
|
+
|
|
130
|
+
name: str
|
|
131
|
+
source: Literal["jira", "github"]
|
|
132
|
+
query: str
|
|
133
|
+
activity: str
|
|
134
|
+
# A declaration only: the agent produces the result with its own tools.
|
|
135
|
+
result: str | None = None
|
|
136
|
+
# GitHub Issues needs to know which repo the query and claims apply to.
|
|
137
|
+
repo: str | None = None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class Config(BaseModel):
|
|
141
|
+
"""A parsed config file."""
|
|
142
|
+
|
|
143
|
+
path: Path
|
|
144
|
+
harness: str
|
|
145
|
+
executor: str = "local"
|
|
146
|
+
activities_dir: Path = Path("activities")
|
|
147
|
+
harnesses: dict[str, HarnessConfig] = Field(default_factory=dict)
|
|
148
|
+
executors: ExecutorOptions = Field(default_factory=ExecutorOptions)
|
|
149
|
+
workflows: dict[str, WorkflowConfig] = Field(default_factory=dict)
|
|
150
|
+
|
|
151
|
+
def harness_config(self) -> HarnessConfig:
|
|
152
|
+
return self.harnesses[self.harness]
|
|
153
|
+
|
|
154
|
+
def workflow(self, name: str) -> WorkflowConfig:
|
|
155
|
+
try:
|
|
156
|
+
return self.workflows[name]
|
|
157
|
+
except KeyError:
|
|
158
|
+
known = ", ".join(sorted(self.workflows)) or "none"
|
|
159
|
+
raise ConfigError(
|
|
160
|
+
f"{self.path}: no workflow named {name!r} (defined: {known})"
|
|
161
|
+
) from None
|
|
162
|
+
|
|
163
|
+
def cloudrun_options(self) -> CloudRunOptions:
|
|
164
|
+
if self.executors.cloudrun is None:
|
|
165
|
+
raise ConfigError(
|
|
166
|
+
f"{self.path}: executor 'cloudrun' requires an [executors.cloudrun] table",
|
|
167
|
+
fix="Add an [executors.cloudrun] table with project, region, and job keys.",
|
|
168
|
+
)
|
|
169
|
+
return self.executors.cloudrun
|
|
170
|
+
|
|
171
|
+
def activity_dir(self, workflow: WorkflowConfig) -> Path:
|
|
172
|
+
"""Absolute path of the activity skill, resolved against the config file."""
|
|
173
|
+
base = self.activities_dir
|
|
174
|
+
if not base.is_absolute():
|
|
175
|
+
base = self.path.parent / base
|
|
176
|
+
return base / workflow.activity
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def load(path: Path | str) -> Config:
|
|
180
|
+
"""Read and validate a config file. Fails fast with the file name in the message."""
|
|
181
|
+
path = Path(path)
|
|
182
|
+
try:
|
|
183
|
+
raw = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
184
|
+
except FileNotFoundError:
|
|
185
|
+
raise ConfigError(f"{path}: config file not found") from None
|
|
186
|
+
except tomllib.TOMLDecodeError as exc:
|
|
187
|
+
fix = ""
|
|
188
|
+
if "overwrite" in str(exc):
|
|
189
|
+
# The common one: `harness = "pi"` followed by `[harness.pi]`. TOML
|
|
190
|
+
# forbids reusing a scalar key as a table, so definitions live under
|
|
191
|
+
# the plural `[harnesses.*]` / `[executors.*]`.
|
|
192
|
+
fix = (
|
|
193
|
+
"harness/executor select an adapter by name; define them under"
|
|
194
|
+
" [harnesses.<name>] and [executors.<name>]"
|
|
195
|
+
)
|
|
196
|
+
raise ConfigError(f"{path}: invalid TOML: {exc}", fix=fix) from None
|
|
197
|
+
return parse(raw, path)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def parse(raw: dict[str, Any], path: Path | str = "<config>") -> Config:
|
|
201
|
+
"""Build a Config from an already-decoded TOML mapping."""
|
|
202
|
+
path = Path(path)
|
|
203
|
+
|
|
204
|
+
if "harness" not in raw:
|
|
205
|
+
raise ConfigError(f"{path}: missing required top-level key 'harness'")
|
|
206
|
+
|
|
207
|
+
harnesses = {
|
|
208
|
+
name: _build(HarnessConfig, {"name": name, **table}, path, f"[harnesses.{name}]")
|
|
209
|
+
for name, table in _tables(raw.get("harnesses", {}), path, "harnesses")
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
workflows = {}
|
|
213
|
+
for name, table in raw.items():
|
|
214
|
+
if name in _SCALAR_KEYS or name in _ADAPTER_TABLES:
|
|
215
|
+
continue
|
|
216
|
+
if not isinstance(table, dict):
|
|
217
|
+
raise ConfigError(
|
|
218
|
+
f"{path}: unexpected top-level key {name!r}; expected one of "
|
|
219
|
+
f"{', '.join(sorted(_SCALAR_KEYS))} or a workflow table"
|
|
220
|
+
)
|
|
221
|
+
workflows[name] = _build(
|
|
222
|
+
WorkflowConfig,
|
|
223
|
+
{"name": name, "activity": name, **table},
|
|
224
|
+
path,
|
|
225
|
+
f"[{name}]",
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
config = _build(
|
|
229
|
+
Config,
|
|
230
|
+
{
|
|
231
|
+
"path": path,
|
|
232
|
+
"harness": raw["harness"],
|
|
233
|
+
"executor": raw.get("executor", "local"),
|
|
234
|
+
"activities_dir": raw.get("activities_dir", "activities"),
|
|
235
|
+
"harnesses": harnesses,
|
|
236
|
+
"executors": dict(_tables(raw.get("executors", {}), path, "executors")),
|
|
237
|
+
"workflows": workflows,
|
|
238
|
+
},
|
|
239
|
+
path,
|
|
240
|
+
"config",
|
|
241
|
+
)
|
|
242
|
+
_validate_names(config)
|
|
243
|
+
return config
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _tables(value: Any, path: Path, key: str) -> list[tuple[str, dict[str, Any]]]:
|
|
247
|
+
if not isinstance(value, dict):
|
|
248
|
+
raise ConfigError(f"{path}: [{key}] must be a table of named tables")
|
|
249
|
+
tables: list[tuple[str, dict[str, Any]]] = []
|
|
250
|
+
for name, table in value.items():
|
|
251
|
+
if not isinstance(table, dict):
|
|
252
|
+
raise ConfigError(f"{path}: [{key}.{name}] must be a table")
|
|
253
|
+
tables.append((str(name), table))
|
|
254
|
+
return tables
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _build[M: BaseModel](model: type[M], data: dict[str, Any], path: Path, where: str) -> M:
|
|
258
|
+
try:
|
|
259
|
+
return model(**data)
|
|
260
|
+
except ValidationError as exc:
|
|
261
|
+
problems = "; ".join(
|
|
262
|
+
f"{'.'.join(str(p) for p in err['loc']) or where}: {err['msg']}" for err in exc.errors()
|
|
263
|
+
)
|
|
264
|
+
raise ConfigError(f"{path}: {where}: {problems}") from None
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _validate_names(config: Config) -> None:
|
|
268
|
+
"""Unknown adapter names are a config bug, not a runtime surprise."""
|
|
269
|
+
if config.harness not in config.harnesses:
|
|
270
|
+
known = ", ".join(sorted(config.harnesses)) or "none"
|
|
271
|
+
raise ConfigError(
|
|
272
|
+
f"{config.path}: harness {config.harness!r} has no [harnesses.{config.harness}] "
|
|
273
|
+
f"table (defined: {known})"
|
|
274
|
+
)
|
|
275
|
+
if config.executor not in EXECUTORS:
|
|
276
|
+
raise ConfigError(
|
|
277
|
+
f"{config.path}: unknown executor {config.executor!r} "
|
|
278
|
+
f"(supported: {', '.join(EXECUTORS)})"
|
|
279
|
+
)
|
|
280
|
+
for workflow in config.workflows.values():
|
|
281
|
+
if workflow.source == "github" and not workflow.repo:
|
|
282
|
+
raise ConfigError(
|
|
283
|
+
f"{config.path}: [{workflow.name}]: source 'github' requires repo = \"owner/name\""
|
|
284
|
+
)
|
tina/errors.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""The one thing the CLI catches.
|
|
2
|
+
|
|
3
|
+
Every failure Tina is responsible for — a bad config, an unreachable tracker, a
|
|
4
|
+
missing activity — is a `TinaError` and exits nonzero. An *agent* reporting
|
|
5
|
+
`failed` is not one of these: that outcome is data, and the run still exits 0.
|
|
6
|
+
|
|
7
|
+
The subclasses keep their historical builtin bases so existing `except
|
|
8
|
+
ValueError` / `except RuntimeError` call sites keep working.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TinaError(Exception):
|
|
15
|
+
"""A failure in Tina itself, as opposed to an outcome an agent reported.
|
|
16
|
+
|
|
17
|
+
`message` says what broke and names the file or path involved; `cause` is
|
|
18
|
+
the underlying detail when there is one; `fix` is the single action that
|
|
19
|
+
resolves it. Only the CLI boundary renders them — see `tina.output`.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, message: str, cause: str = "", fix: str = "") -> None:
|
|
23
|
+
super().__init__(message)
|
|
24
|
+
self.cause = cause
|
|
25
|
+
self.fix = fix
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Executor adapters: how the dispatcher enqueues workers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from tina.config import EXECUTORS, Config
|
|
6
|
+
from tina.executors.base import Executor, ExecutorError
|
|
7
|
+
from tina.executors.cloudrun import CloudRunExecutor
|
|
8
|
+
from tina.executors.local import LocalExecutor
|
|
9
|
+
|
|
10
|
+
__all__ = ["Executor", "ExecutorError", "LocalExecutor", "CloudRunExecutor", "build"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build(config: Config) -> Executor:
|
|
14
|
+
"""Instantiate the executor a config selects."""
|
|
15
|
+
if config.executor == "local":
|
|
16
|
+
return LocalExecutor(config_path=config.path)
|
|
17
|
+
if config.executor == "cloudrun":
|
|
18
|
+
return CloudRunExecutor(config.cloudrun_options(), config.path)
|
|
19
|
+
raise ExecutorError(
|
|
20
|
+
f"unknown executor {config.executor!r}",
|
|
21
|
+
fix=f"Set executor to one of: {', '.join(EXECUTORS)}.",
|
|
22
|
+
)
|
tina/executors/base.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""The executor contract."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Protocol, runtime_checkable
|
|
6
|
+
|
|
7
|
+
from tina.errors import TinaError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@runtime_checkable
|
|
11
|
+
class Executor(Protocol):
|
|
12
|
+
"""How the dispatcher enqueues workers. One item = one worker."""
|
|
13
|
+
|
|
14
|
+
def enqueue(self, workflow: str, item_id: str) -> None:
|
|
15
|
+
"""Start a `tina run --workflow <workflow> --item <item_id>` worker."""
|
|
16
|
+
...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ExecutorError(TinaError, RuntimeError):
|
|
20
|
+
"""An executor could not enqueue a worker."""
|