Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions kits/agent-kiro-kit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ A Delivery stage declares trust through the step's `config.sandbox` value:
- Headless mode ignores `sandbox` and uses the adapter's `trust_tools`; the
default is `--trust-all-tools`.

Every invocation pins `--agent-engine v3` and passes `--agent`: `tools[0]` or
constructor `agent` (`beddel-delivery`).

The step's `timeout` is the stage time bound. When `beddel run` builds this
adapter with no constructor arguments, the adapter timeout is 600 seconds, so
the step timeout must be at most 600 seconds. A step timeout kills and reaps
Expand All @@ -56,6 +59,15 @@ Delivery stage reads repository changes separately. Adapter errors use
timeouts. A step timeout is raised as `BEDDEL-EXEC-005`; under the default FAIL
strategy the step failure `BEDDEL-EXEC-002` wraps it as its cause.

### Delivery agent and hooks

Operator install/verify: `PYTHONPATH=<kit>/python python3 -m beddel_agent_kiro.agent_config install|verify`; supports `--home`, `--pointers`, `--replace`.
Pointer `<pointers>/<sha256(realpath(cwd))>.json`; policy `beddel.kiro-hook-policy/1`, first-match-wins, no rules deny all; Python 3.11+; errors `KIRO_AGENT_INVALID`/`KIRO_CLI_MISSING`.
Pointer or log path security failures deny without writing through the pointer. Logs use
`beddel.kiro-hook/1` and 16 fields; results include `type=kiro-hook`, counts,
and `log_sha256`. Exit 2 means deny/error; raw values are never logged.
`policy_sha256` is the SHA-256 of raw policy bytes.

## Headless Mode (CI/CD)

For containers, CI/CD pipelines, and headless environments where browser-based SSO is unavailable, set the `KIRO_API_KEY` environment variable. The adapter automatically detects it and activates headless mode.
Expand Down Expand Up @@ -93,6 +105,8 @@ adapter = KiroCLIAgentAdapter(
| `timeout` | `int` | `600` | Max execution time in seconds |
| `api_key` | `str \| None` | `None` | API key for headless mode (falls back to `KIRO_API_KEY` env var) |
| `trust_tools` | `list[str] \| None` | `None` | Tool categories to trust in headless mode (`None` = trust all) |
| `agent` | `str` | `"beddel-delivery"` | Agent when `tools` is absent |
| `pointers_dir` | `Path \| None` | `None` | Hook pointer directory |

### Docker Example

Expand Down Expand Up @@ -138,13 +152,13 @@ jobs:

### Binary Auto-Discovery

When `cli_path` is not provided, the adapter discovers `kiro-cli` via:
If `cli_path` is not provided, the adapter discovers an already-installed
`kiro-cli` via:

1. Default path: `~/.local/bin/kiro-cli`
2. PATH lookup: `shutil.which("kiro-cli")`
3. Auto-install: `curl -fsSL https://cli.kiro.dev/install | bash`

If all steps fail, an `AgentError(BEDDEL-AGENT-701)` is raised.
If both fail, `KIRO_CLI_MISSING` is raised. The adapter never auto-installs.

## Running Tests

Expand Down
13 changes: 12 additions & 1 deletion kits/agent-kiro-kit/python/beddel_agent_kiro/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
"""Beddel Kiro CLI agent adapter kit."""

from beddel_agent_kiro.adapter import KiroCLIAgentAdapter
from __future__ import annotations

from typing import Any

__all__ = ["KiroCLIAgentAdapter"]


def __getattr__(name: str) -> Any:
"""Load the SDK-dependent adapter without burdening the stdlib hook."""
if name == "KiroCLIAgentAdapter":
from beddel_agent_kiro.adapter import KiroCLIAgentAdapter

return KiroCLIAgentAdapter
raise AttributeError(name)
97 changes: 45 additions & 52 deletions kits/agent-kiro-kit/python/beddel_agent_kiro/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@
The CLI reports no changed-file list, so successful results always use
``files_changed=[]``.

The CLI is auto-discovered from ``~/.local/bin/kiro-cli`` or via
``shutil.which``. If neither resolves, the adapter attempts a one-time
auto-install from ``https://cli.kiro.dev/install``.
The CLI is discovered from ``~/.local/bin/kiro-cli`` or via
``shutil.which``. The adapter never installs the CLI during a workflow run.

Headless mode is activated when an ``api_key`` is provided or the
``KIRO_API_KEY`` environment variable is set. In headless mode, the
Expand All @@ -28,7 +27,6 @@
import contextlib
import os
import shutil
import subprocess
from collections.abc import AsyncGenerator
from pathlib import Path
from typing import Any
Expand All @@ -41,6 +39,9 @@
AGENT_TIMEOUT,
)

from beddel_agent_kiro import hook
from beddel_agent_kiro.errors import KIRO_AGENT_INVALID, KIRO_CLI_MISSING

__all__ = ["KiroCLIAgentAdapter"]

_DEFAULT_CLI_PATH = Path.home() / ".local" / "bin" / "kiro-cli"
Expand Down Expand Up @@ -77,8 +78,7 @@ class KiroCLIAgentAdapter:
model: Default model identifier for CLI invocations.
cli_path: Explicit path to the ``kiro-cli`` binary. When ``None``,
auto-discovered from ``~/.local/bin/kiro-cli``, then
``shutil.which``, then auto-installed from the official
installer script.
``shutil.which``. Missing binaries raise ``KIRO_CLI_MISSING``.
timeout: Maximum execution time in seconds. The subprocess is
terminated and reaped when this bound expires or the caller
cancels the execution.
Expand All @@ -90,6 +90,8 @@ class KiroCLIAgentAdapter:
When ``None`` and headless is active, ``--trust-all-tools`` is
appended. When a list is provided, ``--trust-tools=<csv>`` is
appended instead.
agent: Installed Kiro agent name used when ``tools`` is absent.
pointers_dir: Directory containing cwd-keyed stage policy pointers.
"""

def __init__(
Expand All @@ -99,68 +101,48 @@ def __init__(
timeout: int = 600,
api_key: str | None = None,
trust_tools: list[str] | None = None,
agent: str = "beddel-delivery",
pointers_dir: Path | None = None,
) -> None:
self._model = model
self._cli_path = cli_path or self._discover_cli()
self._timeout = timeout
self._headless: bool = bool(api_key or os.environ.get("KIRO_API_KEY"))
self._trust_tools = trust_tools
self._agent = agent
self._pointers_dir = pointers_dir or hook.DEFAULT_POINTERS_DIR

# ------------------------------------------------------------------
# Binary discovery
# ------------------------------------------------------------------

@staticmethod
def _discover_cli() -> Path:
"""Discover or auto-install the ``kiro-cli`` binary.
"""Discover the already-installed ``kiro-cli`` binary.

Discovery order:
1. ``~/.local/bin/kiro-cli`` (default install location)
2. ``shutil.which("kiro-cli")`` (PATH lookup)
3. Auto-install via official installer script, then retry step 1

Returns:
Path to the resolved ``kiro-cli`` binary.

Raises:
AgentError: ``BEDDEL-AGENT-701`` if discovery and auto-install
both fail.
AgentError: ``KIRO_CLI_MISSING`` when neither location resolves.
"""
# Step 1: default location
if _DEFAULT_CLI_PATH.exists():
return _DEFAULT_CLI_PATH

# Step 2: PATH lookup
which_result = shutil.which("kiro-cli")
if which_result is not None:
return Path(which_result)

# Step 3: auto-install
try:
subprocess.run(
["bash", "-c", "curl -fsSL https://cli.kiro.dev/install | bash"],
capture_output=True,
timeout=60,
)
except (subprocess.TimeoutExpired, OSError):
pass

# Retry default location after install attempt
if _DEFAULT_CLI_PATH.exists():
return _DEFAULT_CLI_PATH

# Step 4: give up
raise AgentError(
code=AGENT_EXECUTION_FAILED,
message="kiro-cli not found and auto-install failed",
code=KIRO_CLI_MISSING,
message="kiro-cli is not installed or discoverable",
details={
"searched": [
str(_DEFAULT_CLI_PATH),
"shutil.which('kiro-cli')",
"curl -fsSL https://cli.kiro.dev/install | bash",
],
"searched": [str(_DEFAULT_CLI_PATH), "shutil.which('kiro-cli')"],
"hint": (
"Install manually: curl -fsSL https://cli.kiro.dev/install | bash"
"Install kiro-cli manually: https://kiro.dev/docs/cli/ "
"(for example curl -fsSL https://cli.kiro.dev/install | bash), "
"then re-run."
),
},
)
Expand Down Expand Up @@ -191,9 +173,9 @@ async def execute(
``--trust-tools=`` (empty value), ``"workspace-write"``
and ``"danger-full-access"`` append ``-a``. Ignored in
headless mode.
tools: Optional list of tool/agent config names. When a
single-element list is provided, appends
``--agent <name>``.
tools: Optional list of tool/agent config names. A single
element overrides the configured agent; an empty or absent
list uses the configured default agent.
output_schema: Optional JSON Schema dict (currently unused
by the CLI backend).

Expand All @@ -208,6 +190,7 @@ async def execute(
``BEDDEL-AGENT-701`` on non-zero exit code.
"""
model_used = model or self._model
agent_used = tools[0] if tools else self._agent
cmd = self._build_command(prompt, model=model_used, sandbox=sandbox, tools=tools)

proc = await asyncio.create_subprocess_exec(
Expand Down Expand Up @@ -237,6 +220,16 @@ async def execute(
stderr_text = stderr_bytes.decode("utf-8", errors="replace") if stderr_bytes else ""

if proc.returncode != 0:
if proc.returncode == 4:
raise AgentError(
code=KIRO_AGENT_INVALID,
message=f"Kiro CLI agent is not installed: {agent_used}",
details={
"exit_code": proc.returncode,
"agent": agent_used,
"hint": "Install or verify the agent with beddel_agent_kiro.agent_config.",
},
)
raise AgentError(
code=AGENT_EXECUTION_FAILED,
message=f"Kiro CLI exited with code {proc.returncode}",
Expand All @@ -250,7 +243,7 @@ async def execute(
return AgentResult(
exit_code=proc.returncode,
output=stdout_text,
events=[],
events=[hook.summarize(self._pointers_dir, Path.cwd())],
files_changed=[],
usage={"model": model_used, "timeout": self._timeout},
agent_id="kiro-cli",
Expand Down Expand Up @@ -375,18 +368,18 @@ def _build_command(
},
)

# Model
cmd.extend(["--model", model])
# Model and pinned engine
cmd.extend(["--agent-engine", "v3", "--model", model])

# Tools → --agent (CLI supports at most one --agent flag)
if tools:
if len(tools) > 1:
raise AgentError(
code=AGENT_EXECUTION_FAILED,
message=f"Kiro CLI supports at most one agent, got {len(tools)}",
details={"tools": tools},
)
cmd.extend(["--agent", tools[0]])
if tools is not None and len(tools) > 1:
raise AgentError(
code=AGENT_EXECUTION_FAILED,
message=f"Kiro CLI supports at most one agent, got {len(tools)}",
details={"tools": tools},
)
agent_name = tools[0] if tools else self._agent
cmd.extend(["--agent", agent_name])

# Prompt as final positional argument
cmd.append(prompt)
Expand Down
Loading
Loading