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.
@@ -0,0 +1,86 @@
1
+ """Cloud Run executor: one job execution per work item, against the same image.
2
+
3
+ Requires the optional dependency: `pip install tina-cli[cloudrun]`.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from tina.config import CloudRunOptions
12
+ from tina.executors.base import ExecutorError
13
+ from tina.log import get_logger
14
+
15
+ log = get_logger(__name__)
16
+
17
+ INSTALL_HINT = (
18
+ "install tina with the extra: `uv add 'tina-cli[cloudrun]'` or "
19
+ "`pip install 'tina-cli[cloudrun]'`"
20
+ )
21
+
22
+
23
+ class CloudRunExecutor:
24
+ """Create a Cloud Run job execution with per-item args overrides."""
25
+
26
+ name = "cloudrun"
27
+
28
+ def __init__(
29
+ self,
30
+ options: CloudRunOptions,
31
+ config_path: Path | str = "tina.toml",
32
+ client: Any = None,
33
+ ) -> None:
34
+ # Required keys are enforced by CloudRunOptions at config load, so a
35
+ # misconfigured job fails before the first query runs, not after.
36
+ self.options = options
37
+ self.config_path = str(config_path)
38
+ self._client = client
39
+
40
+ @property
41
+ def client(self) -> Any:
42
+ if self._client is None:
43
+ self._client = _jobs_client()
44
+ return self._client
45
+
46
+ @property
47
+ def job_path(self) -> str:
48
+ return self.options.job_path()
49
+
50
+ def enqueue(self, workflow: str, item_id: str) -> None:
51
+ run_v2 = _run_v2()
52
+ args = [
53
+ "run",
54
+ "--workflow",
55
+ workflow,
56
+ "--item",
57
+ item_id,
58
+ "--config",
59
+ self.config_path,
60
+ ]
61
+ request = run_v2.RunJobRequest(
62
+ name=self.job_path,
63
+ overrides=run_v2.RunJobRequest.Overrides(
64
+ container_overrides=[run_v2.RunJobRequest.Overrides.ContainerOverride(args=args)]
65
+ ),
66
+ )
67
+ self.client.run_job(request=request)
68
+ log.info(
69
+ "worker enqueued",
70
+ extra={"workflow": workflow, "item": item_id, "job": self.job_path},
71
+ )
72
+
73
+
74
+ def _run_v2() -> Any:
75
+ try:
76
+ # only present with the `cloudrun` extra
77
+ from google.cloud import run_v2
78
+ except ImportError as exc: # pragma: no cover - exercised only without the extra
79
+ raise ExecutorError(
80
+ "the cloudrun executor needs google-cloud-run", fix=INSTALL_HINT
81
+ ) from exc
82
+ return run_v2
83
+
84
+
85
+ def _jobs_client() -> Any:
86
+ return _run_v2().JobsClient()
@@ -0,0 +1,47 @@
1
+ """Local executor: run each worker as a blocking subprocess, one after another.
2
+
3
+ Not optional — this is how anyone tries Tina without cloud infrastructure.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import subprocess
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from tina.executors.base import ExecutorError
13
+ from tina.log import get_logger
14
+
15
+ log = get_logger(__name__)
16
+
17
+
18
+ class LocalExecutor:
19
+ """Sequential subprocess fan-out."""
20
+
21
+ name = "local"
22
+
23
+ def __init__(self, config_path: Path | str) -> None:
24
+ self.config_path = Path(config_path)
25
+
26
+ def enqueue(self, workflow: str, item_id: str) -> None:
27
+ command = [
28
+ sys.executable,
29
+ "-m",
30
+ "tina",
31
+ "run",
32
+ "--workflow",
33
+ workflow,
34
+ "--item",
35
+ item_id,
36
+ "--config",
37
+ str(self.config_path),
38
+ ]
39
+ log.info("worker starting", extra={"workflow": workflow, "item": item_id})
40
+ try:
41
+ completed = subprocess.run(command, check=False)
42
+ except OSError as exc:
43
+ raise ExecutorError(f"local executor could not start a worker: {exc}") from exc
44
+ log.info(
45
+ "worker finished",
46
+ extra={"workflow": workflow, "item": item_id, "exit_code": completed.returncode},
47
+ )
tina/harness.py ADDED
@@ -0,0 +1,115 @@
1
+ """Harness invocation.
2
+
3
+ Tina does not parse harness stdout. Each harness reports differently, and
4
+ parsing per-harness output is where swappability rots. The agent writes
5
+ `outcome.json` to a path Tina provides; the exit code is only the fallback for
6
+ "the agent died before writing" (architecture §12).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import subprocess
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ from pydantic import ValidationError
17
+
18
+ from tina.config import HarnessConfig
19
+ from tina.log import get_logger
20
+ from tina.models import OutcomeReport, OutcomeStatus
21
+
22
+ log = get_logger(__name__)
23
+
24
+ OUTCOME_FILE = "outcome.json"
25
+ PROMPT_FILE = "prompt.md"
26
+ DEFAULT_TIMEOUT = 3600.0
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class HarnessResult:
31
+ """What the harness produced, and how its process ended."""
32
+
33
+ report: OutcomeReport
34
+ exit_code: int | None
35
+
36
+
37
+ def outcome_path(workdir: Path) -> Path:
38
+ """Where the agent is told to write its report."""
39
+ return workdir / OUTCOME_FILE
40
+
41
+
42
+ def default_timeout() -> float:
43
+ raw = os.environ.get("TINA_HARNESS_TIMEOUT")
44
+ if not raw:
45
+ return DEFAULT_TIMEOUT
46
+ try:
47
+ return float(raw)
48
+ except ValueError:
49
+ log.warning("ignoring invalid TINA_HARNESS_TIMEOUT", extra={"value": raw})
50
+ return DEFAULT_TIMEOUT
51
+
52
+
53
+ def run(
54
+ config: HarnessConfig,
55
+ prompt: str,
56
+ workdir: Path,
57
+ timeout: float | None = None,
58
+ ) -> HarnessResult:
59
+ """Write the prompt, run the harness once, read whatever it left behind."""
60
+ workdir.mkdir(parents=True, exist_ok=True)
61
+ prompt_file = workdir / PROMPT_FILE
62
+ prompt_file.write_text(prompt, encoding="utf-8")
63
+
64
+ command = config.command.render(prompt_file, workdir)
65
+ log.info("harness starting", extra={"harness": config.name, "command": command})
66
+
67
+ try:
68
+ completed = subprocess.run(
69
+ command,
70
+ check=False,
71
+ cwd=workdir,
72
+ timeout=timeout if timeout is not None else default_timeout(),
73
+ )
74
+ except subprocess.TimeoutExpired as exc:
75
+ return HarnessResult(
76
+ report=OutcomeReport(
77
+ outcome=OutcomeStatus.FAILED,
78
+ details=f"agent timed out after {exc.timeout:g}s",
79
+ ),
80
+ exit_code=None,
81
+ )
82
+ except OSError as exc:
83
+ return HarnessResult(
84
+ report=OutcomeReport(
85
+ outcome=OutcomeStatus.FAILED,
86
+ details=f"could not start harness {config.name!r}: {exc}",
87
+ ),
88
+ exit_code=None,
89
+ )
90
+
91
+ report = read_outcome(outcome_path(workdir), completed.returncode)
92
+ return HarnessResult(report=report, exit_code=completed.returncode)
93
+
94
+
95
+ def read_outcome(path: Path, exit_code: int) -> OutcomeReport:
96
+ """Read the agent's report, falling back to `failed` when it is unusable."""
97
+ try:
98
+ raw = path.read_text(encoding="utf-8")
99
+ except OSError:
100
+ return OutcomeReport(outcome=OutcomeStatus.FAILED, details=_missing_details(exit_code))
101
+
102
+ # Covers both malformed JSON and a well-formed document that is not a report.
103
+ try:
104
+ return OutcomeReport.model_validate_json(raw)
105
+ except ValidationError as exc:
106
+ return OutcomeReport(
107
+ outcome=OutcomeStatus.FAILED,
108
+ details=f"agent wrote an invalid {OUTCOME_FILE}: {exc}",
109
+ )
110
+
111
+
112
+ def _missing_details(exit_code: int) -> str:
113
+ if exit_code == 0:
114
+ return f"agent exited without writing {OUTCOME_FILE}"
115
+ return f"agent exited {exit_code} without writing {OUTCOME_FILE}"
tina/log.py ADDED
@@ -0,0 +1,45 @@
1
+ """Structured logging: one JSON object per line on stdout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import sys
8
+ from typing import Any
9
+
10
+ _RESERVED = frozenset(logging.LogRecord("", 0, "", 0, "", None, None).__dict__) | {
11
+ "message",
12
+ "asctime",
13
+ "taskName",
14
+ }
15
+
16
+
17
+ class JSONFormatter(logging.Formatter):
18
+ """Render a record as a single JSON line, merging in any extra fields."""
19
+
20
+ def format(self, record: logging.LogRecord) -> str:
21
+ payload: dict[str, Any] = {
22
+ "ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%S%z"),
23
+ "level": record.levelname.lower(),
24
+ "logger": record.name,
25
+ "message": record.getMessage(),
26
+ }
27
+ payload.update({k: v for k, v in record.__dict__.items() if k not in _RESERVED})
28
+ if record.exc_info:
29
+ payload["exception"] = self.formatException(record.exc_info)
30
+ return json.dumps(payload, default=str)
31
+
32
+
33
+ def configure(level: int = logging.INFO) -> None:
34
+ """Install the JSON handler on the root logger. Idempotent."""
35
+ root = logging.getLogger()
36
+ for handler in root.handlers[:]:
37
+ root.removeHandler(handler)
38
+ handler = logging.StreamHandler(sys.stdout)
39
+ handler.setFormatter(JSONFormatter())
40
+ root.addHandler(handler)
41
+ root.setLevel(level)
42
+
43
+
44
+ def get_logger(name: str) -> logging.Logger:
45
+ return logging.getLogger(name)
tina/models.py ADDED
@@ -0,0 +1,90 @@
1
+ """The data Tina passes around: work items in, outcome reports out."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import StrEnum
6
+ from typing import Any
7
+
8
+ from pydantic import AnyHttpUrl, BaseModel, Field
9
+
10
+
11
+ class WorkItem(BaseModel):
12
+ """One unit of work, normalized out of whatever tracker produced it."""
13
+
14
+ id: str
15
+ source: str
16
+ title: str = ""
17
+ description: str = ""
18
+ # None rather than "" — a tracker that returned no link has no link, and an
19
+ # empty string is not a URL.
20
+ url: AnyHttpUrl | None = None
21
+ # The untouched tracker payload, so an activity can reach fields Tina does
22
+ # not model. Deliberately unvalidated: this is the escape hatch.
23
+ raw: dict[str, Any] = Field(default_factory=dict)
24
+
25
+
26
+ class OutcomeStatus(StrEnum):
27
+ """The four terminal states of a run. Models what Tina does next."""
28
+
29
+ RESOLVED = "resolved"
30
+ NO_ACTION_NEEDED = "no_action_needed"
31
+ NEEDS_HUMAN = "needs_human"
32
+ FAILED = "failed"
33
+
34
+
35
+ class Artifact(BaseModel):
36
+ """Something the agent claims to have produced, in some other system.
37
+
38
+ The URL is validated when outcome.json is parsed, not when verification
39
+ fetches it: an agent that writes `"url": "TBD"` has written a broken report,
40
+ and that is a `failed` run rather than an artifact that merely 404s.
41
+ """
42
+
43
+ kind: str
44
+ url: AnyHttpUrl
45
+
46
+
47
+ class OutcomeReport(BaseModel):
48
+ """What the agent wrote to outcome.json, plus Tina's verification verdict."""
49
+
50
+ outcome: OutcomeStatus
51
+ details: str = ""
52
+ artifacts: list[Artifact] = Field(default_factory=list)
53
+ verified: bool | None = None
54
+
55
+ @property
56
+ def effective_status(self) -> OutcomeStatus:
57
+ """The agent's report is never overwritten — failed verification is
58
+ recorded alongside it and shifts the status a human sees."""
59
+ if self.verified is False:
60
+ return OutcomeStatus.NEEDS_HUMAN
61
+ return self.outcome
62
+
63
+
64
+ class RunRecord(BaseModel):
65
+ """The final log line of `tina run`."""
66
+
67
+ workflow: str
68
+ item: str
69
+ report: OutcomeReport
70
+ effective_status: OutcomeStatus
71
+ exit_code: int | None = None
72
+ duration_seconds: float = 0.0
73
+
74
+ @classmethod
75
+ def build(
76
+ cls,
77
+ workflow: str,
78
+ item: str,
79
+ report: OutcomeReport,
80
+ exit_code: int | None,
81
+ duration_seconds: float,
82
+ ) -> RunRecord:
83
+ return cls(
84
+ workflow=workflow,
85
+ item=item,
86
+ report=report,
87
+ effective_status=report.effective_status,
88
+ exit_code=exit_code,
89
+ duration_seconds=round(duration_seconds, 3),
90
+ )
tina/output.py ADDED
@@ -0,0 +1,51 @@
1
+ """Human-facing output. The other half of the boundary from `tina.log`.
2
+
3
+ `tina.log` owns stdout: one JSON object per line, for whatever is collecting run
4
+ records. This module owns stderr: prose for the person who ran the command. The
5
+ two never overlap, and styling here is decorative only — every line reads the
6
+ same with ANSI stripped.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import typer
12
+
13
+ ERROR = typer.colors.RED
14
+ DIM = typer.colors.BRIGHT_BLACK
15
+ DRY_RUN = typer.colors.YELLOW
16
+
17
+
18
+ def error(message: str, cause: str = "", fix: str = "") -> None:
19
+ """Render a failure on stderr as `✗ message` plus what is known about it.
20
+
21
+ `Cause:`/`Fix:` are omitted entirely when empty, so an error with no useful
22
+ remedy is a single line rather than a label with nothing after it.
23
+ """
24
+ typer.echo(typer.style("✗ ", fg=ERROR) + message, err=True)
25
+ if cause:
26
+ typer.echo(typer.style(" Cause: ", fg=DIM) + cause, err=True)
27
+ if fix:
28
+ typer.echo(typer.style(" Fix: ", fg=DIM) + fix, err=True)
29
+
30
+
31
+ def dry_run_header() -> None:
32
+ """Open a preview. Nothing printed after this line changed anything."""
33
+ typer.echo(typer.style("Dry run", fg=DRY_RUN) + " — no workers will be enqueued\n", err=True)
34
+
35
+
36
+ def would(message: str) -> None:
37
+ """One thing a real run would have done, indented under the header."""
38
+ typer.echo(" " + message, err=True)
39
+
40
+
41
+ def dry_run_footer(summary: str = "") -> None:
42
+ """Close a preview, with an optional tally.
43
+
44
+ `summary` is omitted when empty, the same way `error()` drops an empty
45
+ `Cause:`/`Fix:` rather than printing a label with nothing after it.
46
+ """
47
+ typer.echo("", err=True)
48
+ if summary:
49
+ typer.echo(summary, err=True)
50
+ typer.echo("", err=True)
51
+ typer.echo(typer.style("Run without --dry-run to enqueue.", fg=DIM), err=True)
tina/prompt.py ADDED
@@ -0,0 +1,86 @@
1
+ """One-shot prompt assembly: activity skill + work item + outcome instructions.
2
+
3
+ Tina ships no activities. They are skills installed with napoln at image build
4
+ time; Tina only reads them off disk.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ from tina.errors import TinaError
12
+ from tina.models import WorkItem
13
+
14
+ SKILL_FILE = "SKILL.md"
15
+
16
+
17
+ class PromptError(TinaError, RuntimeError):
18
+ """The activity skill could not be read."""
19
+
20
+
21
+ OUTCOME_INSTRUCTIONS = """\
22
+ ## Reporting the outcome
23
+
24
+ You run once. There is no follow-up turn, and nothing reads your stdout.
25
+
26
+ Before you finish, write a JSON file to exactly this path:
27
+
28
+ {outcome_path}
29
+
30
+ The file must contain a single JSON object:
31
+
32
+ {{
33
+ "outcome": "resolved | no_action_needed | needs_human | failed",
34
+ "details": "free-form prose describing what you did and why",
35
+ "artifacts": [{{"kind": "github:pr", "url": "https://..."}}]
36
+ }}
37
+
38
+ `outcome` must be one of exactly these four values:
39
+
40
+ - `resolved` — the work item is handled and you produced the result.
41
+ - `no_action_needed` — nothing needed doing; explain why in `details`.
42
+ - `needs_human` — you correctly concluded a person must decide. Not an error.
43
+ - `failed` — you could not complete the work. Put the reason in `details`.
44
+
45
+ `details` is prose and unmodeled; use as much of it as you want. `artifacts`
46
+ lists everything you created in another system, and may be empty. Every URL you
47
+ list under `resolved` will be fetched to confirm it exists, so do not list an
48
+ artifact you did not actually create.
49
+
50
+ If this file is missing when you exit, the run is recorded as failed.
51
+ """
52
+
53
+
54
+ def build(activity_dir: Path, item: WorkItem, outcome_path: Path) -> str:
55
+ """Assemble the full prompt handed to the harness."""
56
+ skill = read_skill(activity_dir)
57
+ return "\n".join(
58
+ [
59
+ skill.rstrip(),
60
+ "",
61
+ "## Work item",
62
+ "",
63
+ "This is the single work item for this run, as JSON:",
64
+ "",
65
+ "```json",
66
+ item.model_dump_json(indent=2),
67
+ "```",
68
+ "",
69
+ OUTCOME_INSTRUCTIONS.format(outcome_path=outcome_path),
70
+ ]
71
+ )
72
+
73
+
74
+ def read_skill(activity_dir: Path) -> str:
75
+ """Read `<activity_dir>/SKILL.md`."""
76
+ path = activity_dir / SKILL_FILE
77
+ try:
78
+ return path.read_text(encoding="utf-8")
79
+ except FileNotFoundError:
80
+ raise PromptError(
81
+ f"activity skill not found at {path}",
82
+ fix="Activities are installed into the activities directory with"
83
+ " napoln; tina ships none.",
84
+ ) from None
85
+ except OSError as exc:
86
+ raise PromptError(f"could not read activity skill at {path}: {exc}") from exc
@@ -0,0 +1,21 @@
1
+ """Source adapters: where work items come from, and how they get claimed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import httpx
6
+
7
+ from tina.config import WorkflowConfig
8
+ from tina.sources.base import Source
9
+ from tina.sources.github import GitHubSource
10
+ from tina.sources.jira import JiraSource
11
+
12
+ __all__ = ["Source", "JiraSource", "GitHubSource", "build"]
13
+
14
+
15
+ def build(workflow: WorkflowConfig, client: httpx.Client | None = None) -> Source:
16
+ """Instantiate the source adapter a workflow declares."""
17
+ if workflow.source == "jira":
18
+ return JiraSource(client=client)
19
+ if workflow.source == "github":
20
+ return GitHubSource(repo=workflow.repo or "", client=client)
21
+ raise ValueError(f"unknown source {workflow.source!r}")
tina/sources/base.py ADDED
@@ -0,0 +1,68 @@
1
+ """The source adapter contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Protocol, runtime_checkable
7
+
8
+ import httpx
9
+ from pydantic import BaseModel, ValidationError
10
+
11
+ from tina.errors import TinaError
12
+ from tina.models import WorkItem
13
+
14
+
15
+ @runtime_checkable
16
+ class Source(Protocol):
17
+ """A ticket tracker, seen through a query and a claim.
18
+
19
+ Tina never inspects the content of a work item — it only knows the item
20
+ matched a query. All judgment about what the item is happens in the activity.
21
+ """
22
+
23
+ def query(self, q: str) -> list[WorkItem]:
24
+ """Run the configured query and return matching items."""
25
+ ...
26
+
27
+ def get(self, item_id: str) -> WorkItem:
28
+ """Fetch a single item by tracker identifier."""
29
+ ...
30
+
31
+ def claim(self, item: WorkItem) -> bool:
32
+ """Take ownership of an item.
33
+
34
+ True means this worker now owns it. False means somebody else does and
35
+ the worker should exit `no_action_needed`.
36
+ """
37
+ ...
38
+
39
+
40
+ class SourceError(TinaError, RuntimeError):
41
+ """A source adapter could not talk to its tracker."""
42
+
43
+
44
+ def require_env(name: str, source: str) -> str:
45
+ """Read a required environment variable or fail with a usable message."""
46
+ value = os.environ.get(name)
47
+ if not value:
48
+ raise SourceError(
49
+ f"{source} source requires the {name} environment variable",
50
+ fix=f"Set {name} in the worker environment.",
51
+ )
52
+ return value
53
+
54
+
55
+ def parse_payload[M: BaseModel](
56
+ model: type[M], response: httpx.Response, source: str, path: str
57
+ ) -> M:
58
+ """Validate a tracker response against the shape Tina expects.
59
+
60
+ The models only declare the fields Tina reads and tolerate unknown ones, so
61
+ this fires when a tracker returns something genuinely different — not every
62
+ time an API grows a field.
63
+ """
64
+ try:
65
+ return model.model_validate(response.json())
66
+ except ValueError as exc:
67
+ detail = exc if isinstance(exc, ValidationError) else f"response was not JSON: {exc}"
68
+ raise SourceError(f"{source}: unexpected response from {path}: {detail}") from None