startriage 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.
- startriage/__init__.py +1 -0
- startriage/__main__.py +6 -0
- startriage/ai/__init__.py +66 -0
- startriage/ai/agent.py +112 -0
- startriage/ai/contract.py +108 -0
- startriage/ai/provider.py +230 -0
- startriage/ai/render.py +204 -0
- startriage/ai/run.py +200 -0
- startriage/cli.py +541 -0
- startriage/config.py +368 -0
- startriage/data/agents_prompt.md +213 -0
- startriage/data/defaults.toml +54 -0
- startriage/data/report.html +385 -0
- startriage/dates.py +209 -0
- startriage/htmlreport.py +186 -0
- startriage/log.py +27 -0
- startriage/output.py +166 -0
- startriage/report.py +211 -0
- startriage/savebugs.py +135 -0
- startriage/source.py +35 -0
- startriage/sources/__init__.py +0 -0
- startriage/sources/discourse/__init__.py +4 -0
- startriage/sources/discourse/finder.py +217 -0
- startriage/sources/discourse/models.py +200 -0
- startriage/sources/discourse/triage.py +402 -0
- startriage/sources/github/__init__.py +0 -0
- startriage/sources/github/auth.py +142 -0
- startriage/sources/github/finder.py +345 -0
- startriage/sources/github/models.py +170 -0
- startriage/sources/github/triage.py +341 -0
- startriage/sources/launchpad/__init__.py +0 -0
- startriage/sources/launchpad/finder.py +462 -0
- startriage/sources/launchpad/models.py +506 -0
- startriage/sources/launchpad/triage.py +417 -0
- startriage/sources/proposed/__init__.py +0 -0
- startriage/sources/proposed/finder.py +166 -0
- startriage/sources/proposed/models.py +23 -0
- startriage/sources/proposed/triage.py +249 -0
- startriage/spinner.py +108 -0
- startriage/triage.py +105 -0
- startriage-0.1.0.dist-info/METADATA +251 -0
- startriage-0.1.0.dist-info/RECORD +62 -0
- startriage-0.1.0.dist-info/WHEEL +5 -0
- startriage-0.1.0.dist-info/entry_points.txt +2 -0
- startriage-0.1.0.dist-info/licenses/LICENSE +674 -0
- startriage-0.1.0.dist-info/top_level.txt +2 -0
- tests/__init__.py +0 -0
- tests/test_ai_agent.py +180 -0
- tests/test_ai_logging.py +73 -0
- tests/test_ai_provider.py +157 -0
- tests/test_ai_render.py +192 -0
- tests/test_ai_run.py +171 -0
- tests/test_api.py +143 -0
- tests/test_config.py +312 -0
- tests/test_dates.py +214 -0
- tests/test_discourse.py +300 -0
- tests/test_github_finder.py +262 -0
- tests/test_htmlreport.py +141 -0
- tests/test_launchpad_models.py +165 -0
- tests/test_launchpad_table.py +61 -0
- tests/test_proposed.py +72 -0
- tests/test_spinner.py +45 -0
startriage/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""startriage - unified triage tool for Ubuntu."""
|
startriage/__main__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""AI/agentic triage layer for startriage."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .agent import BugOutcome, load_system_prompt, triage_bug, triage_bugs
|
|
6
|
+
from .contract import (
|
|
7
|
+
AgentResult,
|
|
8
|
+
AgentResultError,
|
|
9
|
+
ProposedFix,
|
|
10
|
+
extract_json_block,
|
|
11
|
+
parse_agent_result,
|
|
12
|
+
)
|
|
13
|
+
from .provider import (
|
|
14
|
+
CopilotProvider,
|
|
15
|
+
FakeProvider,
|
|
16
|
+
Provider,
|
|
17
|
+
build_client_kwargs,
|
|
18
|
+
build_permission_handler,
|
|
19
|
+
build_provider,
|
|
20
|
+
build_session_kwargs,
|
|
21
|
+
)
|
|
22
|
+
from .render import (
|
|
23
|
+
append_report,
|
|
24
|
+
emit_ai_report,
|
|
25
|
+
render_bug_metadata,
|
|
26
|
+
render_report,
|
|
27
|
+
)
|
|
28
|
+
from .run import (
|
|
29
|
+
describe_bug_specs,
|
|
30
|
+
gather_user_bug_payloads,
|
|
31
|
+
parse_bug_number,
|
|
32
|
+
payloads_from_tasks,
|
|
33
|
+
run_agent_on_payloads,
|
|
34
|
+
run_ai_over_bug_specs,
|
|
35
|
+
run_ai_over_triage_results,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"AgentResult",
|
|
40
|
+
"AgentResultError",
|
|
41
|
+
"BugOutcome",
|
|
42
|
+
"CopilotProvider",
|
|
43
|
+
"FakeProvider",
|
|
44
|
+
"ProposedFix",
|
|
45
|
+
"Provider",
|
|
46
|
+
"append_report",
|
|
47
|
+
"build_client_kwargs",
|
|
48
|
+
"build_permission_handler",
|
|
49
|
+
"build_provider",
|
|
50
|
+
"build_session_kwargs",
|
|
51
|
+
"describe_bug_specs",
|
|
52
|
+
"emit_ai_report",
|
|
53
|
+
"extract_json_block",
|
|
54
|
+
"gather_user_bug_payloads",
|
|
55
|
+
"load_system_prompt",
|
|
56
|
+
"parse_agent_result",
|
|
57
|
+
"parse_bug_number",
|
|
58
|
+
"payloads_from_tasks",
|
|
59
|
+
"render_bug_metadata",
|
|
60
|
+
"render_report",
|
|
61
|
+
"run_agent_on_payloads",
|
|
62
|
+
"run_ai_over_bug_specs",
|
|
63
|
+
"run_ai_over_triage_results",
|
|
64
|
+
"triage_bug",
|
|
65
|
+
"triage_bugs",
|
|
66
|
+
]
|
startriage/ai/agent.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Sequential agent loop: run one triage session per bug, skip-and-continue.
|
|
2
|
+
|
|
3
|
+
The provider (see :mod:`startriage.ai.provider`) runs the agent and returns its
|
|
4
|
+
final text; this module loads the behavioural system prompt, feeds each bug's
|
|
5
|
+
payload as the user message, and parses the result via the contract. A failure on
|
|
6
|
+
one bug is recorded and the run continues with the next, never aborting the batch.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from importlib.resources import files
|
|
16
|
+
|
|
17
|
+
from .contract import AgentResult, AgentResultError, parse_agent_result
|
|
18
|
+
from .provider import Provider
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class BugOutcome:
|
|
25
|
+
"""Result of triaging a single bug: either a parsed result or a failure."""
|
|
26
|
+
|
|
27
|
+
bug: str
|
|
28
|
+
result: AgentResult | None
|
|
29
|
+
error: str | None
|
|
30
|
+
raw: str
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def ok(self) -> bool:
|
|
34
|
+
return self.result is not None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def load_system_prompt() -> str:
|
|
38
|
+
"""Load the agent behavioural prompt shipped as a package resource."""
|
|
39
|
+
prompt_path = files("startriage") / "data" / "agents_prompt.md"
|
|
40
|
+
return prompt_path.read_text(encoding="utf-8")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _log_outcome(outcome: BugOutcome) -> None:
|
|
44
|
+
"""Emit a per-bug step log: the decision at -v, deeper detail at -vv."""
|
|
45
|
+
if outcome.ok and outcome.result is not None:
|
|
46
|
+
result = outcome.result
|
|
47
|
+
logger.info(
|
|
48
|
+
"Bug %s → status=%s, tags=%s",
|
|
49
|
+
outcome.bug,
|
|
50
|
+
result.status.value,
|
|
51
|
+
", ".join(result.tags) or "(none)",
|
|
52
|
+
)
|
|
53
|
+
logger.debug("Bug %s proposed fix: %s", outcome.bug, result.proposed_fix.kind.value)
|
|
54
|
+
if result.thought_process:
|
|
55
|
+
logger.debug("Bug %s thought process: %s", outcome.bug, result.thought_process)
|
|
56
|
+
else:
|
|
57
|
+
logger.warning("Bug %s failed: %s", outcome.bug, outcome.error)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def triage_bug(
|
|
61
|
+
provider: Provider,
|
|
62
|
+
payload: dict,
|
|
63
|
+
system_prompt: str,
|
|
64
|
+
) -> BugOutcome:
|
|
65
|
+
"""Run one agent session for ``payload`` and parse its result.
|
|
66
|
+
|
|
67
|
+
Never raises for triage/agent failures: any error is captured on the returned
|
|
68
|
+
:class:`BugOutcome` so the caller can record it and continue.
|
|
69
|
+
"""
|
|
70
|
+
bug = str(payload.get("number", ""))
|
|
71
|
+
user_message = json.dumps(payload, ensure_ascii=False)
|
|
72
|
+
logger.debug("Bug %s: sending %d-char payload to the agent", bug, len(user_message))
|
|
73
|
+
try:
|
|
74
|
+
raw = await provider.run(system_prompt, user_message)
|
|
75
|
+
except Exception as exc:
|
|
76
|
+
# Record any provider/runtime failure and keep going (skip-and-continue).
|
|
77
|
+
logger.warning("Bug %s: provider run failed", bug, exc_info=True)
|
|
78
|
+
return BugOutcome(bug=bug, result=None, error=f"provider error: {exc}", raw="")
|
|
79
|
+
logger.debug("Bug %s: received %d-char agent response", bug, len(raw))
|
|
80
|
+
try:
|
|
81
|
+
result = parse_agent_result(raw)
|
|
82
|
+
except AgentResultError as exc:
|
|
83
|
+
return BugOutcome(bug=bug, result=None, error=str(exc), raw=raw)
|
|
84
|
+
return BugOutcome(bug=bug, result=result, error=None, raw=raw)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def triage_bugs(
|
|
88
|
+
provider: Provider,
|
|
89
|
+
payloads: list[dict],
|
|
90
|
+
system_prompt: str | None = None,
|
|
91
|
+
*,
|
|
92
|
+
on_progress: Callable[[int, int, str], None] | None = None,
|
|
93
|
+
) -> list[BugOutcome]:
|
|
94
|
+
"""Triage ``payloads`` sequentially, recording per-bug failures and continuing.
|
|
95
|
+
|
|
96
|
+
``on_progress`` (when given) is called as ``(index, total, bug)`` just before
|
|
97
|
+
each bug is sent to the agent, so a caller can drive a spinner/progress line.
|
|
98
|
+
"""
|
|
99
|
+
prompt = system_prompt if system_prompt is not None else load_system_prompt()
|
|
100
|
+
total = len(payloads)
|
|
101
|
+
outcomes: list[BugOutcome] = []
|
|
102
|
+
for index, payload in enumerate(payloads, start=1):
|
|
103
|
+
bug = str(payload.get("number", ""))
|
|
104
|
+
if on_progress is not None:
|
|
105
|
+
on_progress(index, total, bug)
|
|
106
|
+
logger.info("Triaging bug %s (%d/%d)…", bug, index, total)
|
|
107
|
+
outcome = await triage_bug(provider, payload, prompt)
|
|
108
|
+
_log_outcome(outcome)
|
|
109
|
+
outcomes.append(outcome)
|
|
110
|
+
succeeded = sum(o.ok for o in outcomes)
|
|
111
|
+
logger.info("AI triage complete: %d succeeded, %d failed", succeeded, total - succeeded)
|
|
112
|
+
return outcomes
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Agent → tool result contract: the JSON each bug triage must return.
|
|
2
|
+
|
|
3
|
+
The Copilot CLI returns a free-text final assistant message, so the agent is
|
|
4
|
+
instructed to end with a single fenced ``json`` block. This module extracts that
|
|
5
|
+
block, parses it, and validates it against the schema in ``agents_prompt.md``.
|
|
6
|
+
Validation is enforced in code (status / fix-kind enums) so a hallucinated or
|
|
7
|
+
malformed result is rejected rather than trusted.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
from enum import StrEnum
|
|
15
|
+
|
|
16
|
+
from pydantic import BaseModel, ConfigDict, ValidationError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TriageStatus(StrEnum):
|
|
20
|
+
"""Status the agent recommends for a triaged bug."""
|
|
21
|
+
|
|
22
|
+
invalid = "Invalid" # not a bug, or already fixed in the reported version
|
|
23
|
+
incomplete = "Incomplete" # more information needed from the reporter
|
|
24
|
+
triaged = "Triaged" # valid and reproducible
|
|
25
|
+
duplicate = "Duplicate" # duplicate of another report
|
|
26
|
+
no_change = "no-change" # leave as-is; needs further engineering input
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ProposedFixKind(StrEnum):
|
|
30
|
+
"""How the agent's proposed fix should be interpreted."""
|
|
31
|
+
|
|
32
|
+
none = "none" # no fix proposed
|
|
33
|
+
reference = "reference" # value is a URL/commit pointing at an existing fix
|
|
34
|
+
diff = "diff" # value is a unified diff generated by the agent
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# Matches fenced code blocks, optionally tagged with a language (e.g. ```json).
|
|
38
|
+
_FENCED_BLOCK = re.compile(
|
|
39
|
+
r"```[ \t]*([A-Za-z0-9_+-]*)[ \t]*\r?\n(.*?)\r?\n```",
|
|
40
|
+
re.DOTALL,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class AgentResultError(ValueError):
|
|
45
|
+
"""Raised when the agent's output cannot be parsed/validated as a result."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ProposedFix(BaseModel):
|
|
49
|
+
model_config = ConfigDict(extra="forbid")
|
|
50
|
+
|
|
51
|
+
kind: ProposedFixKind
|
|
52
|
+
value: str = ""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class AgentResult(BaseModel):
|
|
56
|
+
"""One bug's triage result, as returned by the agent and rendered by the tool."""
|
|
57
|
+
|
|
58
|
+
# Tolerate extra keys: LLM output is noisy and harmless additions should not
|
|
59
|
+
# fail an otherwise-valid result. The fields below are still validated strictly.
|
|
60
|
+
model_config = ConfigDict(extra="ignore")
|
|
61
|
+
|
|
62
|
+
bug: str
|
|
63
|
+
package: str = ""
|
|
64
|
+
short_title: str = ""
|
|
65
|
+
status: TriageStatus
|
|
66
|
+
tags: list[str] = []
|
|
67
|
+
analysis: str = ""
|
|
68
|
+
thought_process: str = ""
|
|
69
|
+
proposed_fix: ProposedFix
|
|
70
|
+
references: list[str] = []
|
|
71
|
+
suggested_improvements: str = ""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def extract_json_block(text: str) -> str:
|
|
75
|
+
"""Return the JSON payload of the last fenced block in ``text``.
|
|
76
|
+
|
|
77
|
+
Prefers a ```json-tagged block; falls back to the last untagged fenced block so
|
|
78
|
+
a missing language hint does not break parsing. Raises :class:`AgentResultError`
|
|
79
|
+
when no fenced block is present.
|
|
80
|
+
"""
|
|
81
|
+
matches = _FENCED_BLOCK.findall(text)
|
|
82
|
+
if not matches:
|
|
83
|
+
raise AgentResultError("no fenced code block found in agent output")
|
|
84
|
+
|
|
85
|
+
json_blocks = [body for lang, body in matches if lang.lower() == "json"]
|
|
86
|
+
if json_blocks:
|
|
87
|
+
return json_blocks[-1].strip()
|
|
88
|
+
# No language-tagged json block; use the last fenced block of any kind.
|
|
89
|
+
return matches[-1][1].strip()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def parse_agent_result(text: str) -> AgentResult:
|
|
93
|
+
"""Extract, decode, and validate a single :class:`AgentResult` from agent text.
|
|
94
|
+
|
|
95
|
+
Raises :class:`AgentResultError` on a missing block, invalid JSON, or schema /
|
|
96
|
+
enum validation failure.
|
|
97
|
+
"""
|
|
98
|
+
block = extract_json_block(text)
|
|
99
|
+
try:
|
|
100
|
+
data = json.loads(block)
|
|
101
|
+
except json.JSONDecodeError as exc:
|
|
102
|
+
raise AgentResultError(f"agent output is not valid JSON: {exc}") from exc
|
|
103
|
+
if not isinstance(data, dict):
|
|
104
|
+
raise AgentResultError("agent JSON result must be an object")
|
|
105
|
+
try:
|
|
106
|
+
return AgentResult.model_validate(data)
|
|
107
|
+
except ValidationError as exc:
|
|
108
|
+
raise AgentResultError(f"agent result failed validation: {exc}") from exc
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Provider abstraction over the Copilot SDK for agentic triage.
|
|
2
|
+
|
|
3
|
+
The Copilot CLI is itself the agent loop (built-in shell/file/web tools plus its
|
|
4
|
+
own tool-calling loop), so a "provider" is deliberately thin: it only starts a
|
|
5
|
+
session with the right auth/model and returns the agent's final assistant message.
|
|
6
|
+
|
|
7
|
+
The only thing that differs between providers is *where* the credential goes:
|
|
8
|
+
|
|
9
|
+
- **Copilot** authenticates the CLI process itself, so its GitHub token is a
|
|
10
|
+
``CopilotClient(...)`` kwarg (see :func:`build_client_kwargs`).
|
|
11
|
+
- **OpenRouter** is BYOK through the same loop, supplied as the
|
|
12
|
+
``create_session(provider=...)`` kwarg (see :func:`build_session_kwargs`).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import asyncio
|
|
18
|
+
import logging
|
|
19
|
+
from abc import ABC, abstractmethod
|
|
20
|
+
from enum import StrEnum
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from ..config import AI_SETUP_HINT, AIConfig, AIConfigError, AIProvider
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class AIPermission(StrEnum):
|
|
27
|
+
"""How much the triage agent is allowed to execute on the host."""
|
|
28
|
+
|
|
29
|
+
restricted = "restricted" # no tool execution; reason over the provided metadata only
|
|
30
|
+
full = "full" # auto-approve every tool call (shell, file, web)
|
|
31
|
+
ask = "ask" # prompt on the terminal before each tool call
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
# Appended to the system prompt in restricted mode, where every tool call is
|
|
37
|
+
# rejected. Without it the agent would keep trying to run commands and only
|
|
38
|
+
# discover they are denied one failure at a time.
|
|
39
|
+
RESTRICTED_PROMPT_NOTE = (
|
|
40
|
+
"\n\nTool execution is disabled for this run. Reason only over the bug metadata "
|
|
41
|
+
"provided in the user message; do not attempt to run shell commands, read or write "
|
|
42
|
+
"files, or fetch URLs. If a step would require executing a tool, say so and explain "
|
|
43
|
+
"what you would have done instead of trying."
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Provider(ABC):
|
|
48
|
+
"""A backend capable of running one agent session and returning its final text."""
|
|
49
|
+
|
|
50
|
+
#: Model id passed to the underlying session.
|
|
51
|
+
model: str
|
|
52
|
+
|
|
53
|
+
@abstractmethod
|
|
54
|
+
async def run(self, system_prompt: str, user_message: str) -> str:
|
|
55
|
+
"""Run a single agent session and return the final assistant text."""
|
|
56
|
+
raise NotImplementedError
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def build_client_kwargs(ai_config: AIConfig) -> dict[str, Any]:
|
|
60
|
+
"""Build the ``CopilotClient(...)`` kwargs for ``ai_config``.
|
|
61
|
+
|
|
62
|
+
For the Copilot provider this carries the GitHub token that authenticates the
|
|
63
|
+
CLI process (optional here — the SDK also reads it from the environment). For
|
|
64
|
+
OpenRouter (BYOK) the credential travels on the session instead, so no client
|
|
65
|
+
auth is needed. The token is resolved with config-over-env precedence via
|
|
66
|
+
:meth:`AIConfig.resolve_token`.
|
|
67
|
+
"""
|
|
68
|
+
match ai_config.provider:
|
|
69
|
+
case AIProvider.copilot:
|
|
70
|
+
token = ai_config.resolve_token()
|
|
71
|
+
if token:
|
|
72
|
+
return {"github_token": token}
|
|
73
|
+
return {}
|
|
74
|
+
case _:
|
|
75
|
+
return {}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def build_session_kwargs(ai_config: AIConfig) -> dict[str, Any]:
|
|
79
|
+
"""Build the ``create_session(...)`` provider kwargs for ``ai_config``.
|
|
80
|
+
|
|
81
|
+
Only OpenRouter (BYOK) contributes here, as an OpenAI-compatible ``provider``
|
|
82
|
+
block; the Copilot provider authenticates at the client level instead.
|
|
83
|
+
"""
|
|
84
|
+
match ai_config.provider:
|
|
85
|
+
case AIProvider.openrouter:
|
|
86
|
+
return {
|
|
87
|
+
"provider": {
|
|
88
|
+
"type": "openai",
|
|
89
|
+
"base_url": ai_config.openrouter_base_url,
|
|
90
|
+
"api_key": ai_config.resolve_token(),
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
case _:
|
|
94
|
+
return {}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _log_session_event(event: Any) -> None:
|
|
98
|
+
"""Log a Copilot session step event at DEBUG (subscribed only under -vv)."""
|
|
99
|
+
event_type = getattr(event, "type", None) or type(event).__name__
|
|
100
|
+
logger.debug("Copilot session event: %s", event_type)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class CopilotProvider(Provider):
|
|
104
|
+
"""Real provider backed by the Copilot Python SDK (lazily imported).
|
|
105
|
+
|
|
106
|
+
The SDK (and the Node Copilot CLI it spawns) is imported only when a session is
|
|
107
|
+
actually run, so non-AI commands and offline tests never need it installed.
|
|
108
|
+
The ``permission`` level decides how tool calls are handled: ``restricted``
|
|
109
|
+
rejects every tool (text-only reasoning), ``full`` auto-approves them, and
|
|
110
|
+
``ask`` prompts on the terminal before each call.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
def __init__(self, ai_config: AIConfig, permission: AIPermission) -> None:
|
|
114
|
+
if not ai_config.model:
|
|
115
|
+
raise AIConfigError(AI_SETUP_HINT)
|
|
116
|
+
self._ai_config = ai_config
|
|
117
|
+
self._permission = permission
|
|
118
|
+
self.model = ai_config.model
|
|
119
|
+
|
|
120
|
+
async def run(self, system_prompt: str, user_message: str) -> str:
|
|
121
|
+
# Lazy import keeps the SDK (and the Node CLI it spawns) optional; it is
|
|
122
|
+
# bundled by the snap rather than declared as a hard Python dependency.
|
|
123
|
+
from copilot import CopilotClient # ty: ignore[unresolved-import]
|
|
124
|
+
|
|
125
|
+
if self._permission is AIPermission.restricted:
|
|
126
|
+
system_prompt += RESTRICTED_PROMPT_NOTE
|
|
127
|
+
|
|
128
|
+
logger.debug("Starting Copilot session (model=%s, permission=%s)", self.model, self._permission)
|
|
129
|
+
async with CopilotClient(**build_client_kwargs(self._ai_config)) as client:
|
|
130
|
+
async with await client.create_session(
|
|
131
|
+
on_permission_request=build_permission_handler(self._permission),
|
|
132
|
+
model=self.model,
|
|
133
|
+
# "append" keeps the CLI's tool-use foundation and layers our
|
|
134
|
+
# behavioural prompt on top ("replace" would drop its guardrails).
|
|
135
|
+
system_message={"mode": "append", "content": system_prompt},
|
|
136
|
+
**build_session_kwargs(self._ai_config),
|
|
137
|
+
) as session:
|
|
138
|
+
# At -vv, stream the agent's step events (tool calls, reasoning)
|
|
139
|
+
# so unattended runs are auditable; cheap no-op otherwise.
|
|
140
|
+
if logger.isEnabledFor(logging.DEBUG):
|
|
141
|
+
session.on(_log_session_event)
|
|
142
|
+
# timeout=None waits until the agent is idle rather than aborting
|
|
143
|
+
# after the SDK's 60s default; triage turns routinely run longer
|
|
144
|
+
# (source pulls, debdiffs). The user can cancel with Ctrl-C.
|
|
145
|
+
message = await session.send_and_wait(user_message, timeout=None)
|
|
146
|
+
return (message.data.content or "") if message else ""
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class FakeProvider(Provider):
|
|
150
|
+
"""Deterministic in-memory provider for offline tests.
|
|
151
|
+
|
|
152
|
+
Returns queued ``responses`` in order, falling back to ``default_response`` once
|
|
153
|
+
the queue is drained, and records every ``(system_prompt, user_message)`` call
|
|
154
|
+
on :attr:`calls` for assertions.
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
def __init__(
|
|
158
|
+
self,
|
|
159
|
+
responses: list[str] | None = None,
|
|
160
|
+
*,
|
|
161
|
+
model: str = "fake-model",
|
|
162
|
+
default_response: str = "",
|
|
163
|
+
) -> None:
|
|
164
|
+
self.model = model
|
|
165
|
+
self._responses = list(responses or [])
|
|
166
|
+
self._default_response = default_response
|
|
167
|
+
self.calls: list[tuple[str, str]] = []
|
|
168
|
+
|
|
169
|
+
async def run(self, system_prompt: str, user_message: str) -> str:
|
|
170
|
+
self.calls.append((system_prompt, user_message))
|
|
171
|
+
if self._responses:
|
|
172
|
+
return self._responses.pop(0)
|
|
173
|
+
return self._default_response
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def build_permission_handler(permission: AIPermission) -> Any:
|
|
177
|
+
"""Return the Copilot ``on_permission_request`` handler for ``permission``.
|
|
178
|
+
|
|
179
|
+
- ``full`` auto-approves every tool call (:meth:`PermissionHandler.approve_all`).
|
|
180
|
+
- ``restricted`` rejects every tool call, so the agent can only reason over the
|
|
181
|
+
metadata it was given.
|
|
182
|
+
- ``ask`` prompts on the terminal and approves or rejects each call.
|
|
183
|
+
|
|
184
|
+
The Copilot SDK is imported lazily so non-AI commands and offline tests never
|
|
185
|
+
need it installed. Passing ``None`` (the SDK's "leave pending" mode) is
|
|
186
|
+
deliberately avoided: our runs drive the session with ``send_and_wait`` and do
|
|
187
|
+
not resolve pending permission RPCs, so an unanswered request would hang.
|
|
188
|
+
"""
|
|
189
|
+
from copilot.rpc import ( # ty: ignore[unresolved-import]
|
|
190
|
+
PermissionDecisionApproveOnce,
|
|
191
|
+
PermissionDecisionReject,
|
|
192
|
+
)
|
|
193
|
+
from copilot.session import PermissionHandler # ty: ignore[unresolved-import]
|
|
194
|
+
|
|
195
|
+
match permission:
|
|
196
|
+
case AIPermission.full:
|
|
197
|
+
return PermissionHandler.approve_all
|
|
198
|
+
case AIPermission.restricted:
|
|
199
|
+
|
|
200
|
+
def reject(request: Any, invocation: Any) -> Any:
|
|
201
|
+
return PermissionDecisionReject(feedback="Tool execution is disabled for this run.")
|
|
202
|
+
|
|
203
|
+
return reject
|
|
204
|
+
case AIPermission.ask:
|
|
205
|
+
|
|
206
|
+
async def ask(request: Any, invocation: Any) -> Any:
|
|
207
|
+
summary = getattr(request, "full_command_text", None) or type(request).__name__
|
|
208
|
+
answer = await asyncio.to_thread(input, f"Allow the agent to run: {summary}? [y/N] ")
|
|
209
|
+
if answer.strip().lower() in ("y", "yes"):
|
|
210
|
+
return PermissionDecisionApproveOnce()
|
|
211
|
+
return PermissionDecisionReject(feedback="User denied this action.")
|
|
212
|
+
|
|
213
|
+
return ask
|
|
214
|
+
case _:
|
|
215
|
+
raise RuntimeError("unhandled permission")
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def build_provider(ai_config: AIConfig, permission: AIPermission) -> Provider:
|
|
219
|
+
"""Return a ready provider for ``ai_config``, validating the backend first.
|
|
220
|
+
|
|
221
|
+
The readiness check lives on :class:`AIConfig` as a context-gated model
|
|
222
|
+
validator; re-validating here with ``require_ai`` context runs it at the AI
|
|
223
|
+
entry point, raising :class:`~startriage.config.AIConfigError` when no
|
|
224
|
+
provider/model has been chosen, or when the active provider has no usable
|
|
225
|
+
credential (from config or env), so misconfig fails before any session is
|
|
226
|
+
started. ``permission`` decides how the agent's tool calls are handled at run
|
|
227
|
+
time (see :func:`build_permission_handler`).
|
|
228
|
+
"""
|
|
229
|
+
AIConfig.model_validate(ai_config.model_dump(), context={"require_ai": True})
|
|
230
|
+
return CopilotProvider(ai_config, permission)
|