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
4 changes: 4 additions & 0 deletions docs/system-specs/modules/acp-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -2169,6 +2169,10 @@ spec the same way kiro-cli v2 does where the wire allows it:
kiro-cli 2.35.1: the deny with the target excluded left the call to its
permission request, with another name excluded it was refused by the rule, and
the allow ran it with no request.
- `toolsSettings.shell.allowedCommands` travels as no rule: a shell allow would
skip the permission request Crew's deny floor runs on. Crew answers a matching
command at that request itself, through the gate's `spec-builtin-grant` row
([security](security.md) § KAS spec built-in grant).
- The spec's `hooks` run from Crew's turn loop (`agent_sdk/spec_hooks.py`); a
PostToolUse spec hook's tool matcher is matched on the id the call's permission
request stated, or for a call the frame classified as a shell command, KAS's
Expand Down
4 changes: 3 additions & 1 deletion docs/system-specs/modules/governance.md
Original file line number Diff line number Diff line change
Expand Up @@ -1329,7 +1329,9 @@ reads the profile, so any profile at all would withhold every such grant. The ce
the one in the gate's own context snapshot, so a ceiling or profile with any opinion on
the tool's scopes keeps the call at the prompt; an unresolved profile store or an error
withholds. The KAS projection asks `may_grant_builtin_at_gate_now` once when it records
the grant; the gate asks again on every call.
the grant; the gate asks again on every call. A spec's `toolsSettings.shell.allowedCommands`
takes the same row and the same question, asked about `execute_bash`: the patterns are
recorded only when it holds, and the row asks it again for every matching command.

What no hook can do is narrow a session **already negotiated**: kiro-cli holds the grants it
was given, and nothing reaches into a running one. That limit has the same shape as an
Expand Down
18 changes: 18 additions & 0 deletions docs/system-specs/modules/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -2242,6 +2242,24 @@ run. `may_grant_builtin_at_gate` differs from `may_skip_gate` only by omitting t
floor clause, which exists because a static grant skips this gate; this grant is
made inside it.

The same row answers a spec's `toolsSettings.shell.allowedCommands` (#25320). The
projection records the patterns (`kas_permissions.crew_answered_commands`, at most 64; each entry
read by `platform/allowed_commands.py`, which keeps only literal characters,
escaped punctuation and `.*`, the subset Rust's `regex` and Python read alike, and
matches it in linear time without `re`, so a POSIX class cannot widen a grant and
nested repetition cannot stall the gateway; an entry outside it, an over-long list,
and a list the projection withholds are named in the session-start notice) only when
`may_grant_builtin_at_gate_now("execute_bash")` holds and no restriction the spec's author wrote on the shell withholds it (`withhold_answered_under_authored_rules`, read over every `toolsSettings` shell key except `allowedCommands` itself, `kas_permissions.without_allowed_commands`, so a `deniedCommands` or `denyByDefault` beside it keeps every command prompting), the handle keeps them
(`AcpSessionHandle.kas_crew_answered_commands`) and stamps them on the same own
requests (`AcpEvent.spec_granted_commands`). In place of the built-in name, the row
then needs a shell call (`execute_bash` among its names, `is_shell`) whose
host-recovered command, at most 4,096 characters, holds none of
`; & | < > $ \` ( ) { }`, newline or carriage return, and that one entry
matches whole, as kiro-cli anchors each entry at both ends. Every other
condition above still holds, so a matching command the deny floor, governance or
`confirm_tools` refuses is still refused, and a command that chains, pipes,
redirects, groups or substitutes is never granted whatever the pattern says.

**Read-only auto-approve** — kiro-cli's `autoAllowReadonly` is not used;
the tool gate auto-approves read-only tool calls itself, as its `read-only` row —
the **last** of `GATE_TIERS`, before `judge`'s fall-through `allow()` — after every
Expand Down
3 changes: 3 additions & 0 deletions src/kiro_crew/acp/harness/kas.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,9 @@ def record_session_projection(self, handle: Any, custom_agents: Any, active_agen
handle.kas_crew_answered = kas_agents_mod.projected_crew_answered(
custom_agents, active_agent
)
handle.kas_crew_answered_commands = kas_agents_mod.projected_crew_answered_commands(
custom_agents, active_agent
)
handle.kas_projected_agent = active_agent if custom_agents else ""
handle.kas_registered_agents = list(custom_agents) if custom_agents else []
handle.kas_agent_prompt_notice = self.agent_prompt_notice if custom_agents else ""
Expand Down
77 changes: 76 additions & 1 deletion src/kiro_crew/acp/kas_agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,16 @@
from kiro_crew.acp.kas_permissions import (
AUTO_APPROVABLE_CAPABILITIES,
CREW_ANSWERED_BUILTINS_KEY,
CREW_ANSWERED_COMMANDS_KEY,
allowed_tools_to_permissions,
auto_approved_capabilities,
crew_answered_builtins,
crew_answered_commands,
merge_user_permissions,
tools_settings_to_permissions,
withhold_answered_under_authored_rules,
withhold_hook_gated_auto_approval,
without_allowed_commands,
)
from kiro_crew.agent_discovery import (
AgentsDirMemo,
Expand Down Expand Up @@ -235,7 +238,40 @@ def spec_keys_without_carrier(
return sorted(lost)
_, not_carried = tools_settings_to_permissions(tools_settings)
lost.extend(f"toolsSettings.{path}" for path in not_carried)
return sorted(lost)
if (
isinstance(tools_settings, dict)
and crew_answered_commands(tools_settings)
and _allowed_commands_withheld(spec, None)
):
# Every entry is usable, but the session answers none of them: name each
# shell key that carries one, so the operator learns why they prompt.
lost.extend(
f"toolsSettings.{key}.allowedCommands"
for key in ("execute_bash", "shell")
if isinstance(tools_settings.get(key), dict)
and tools_settings[key].get("allowedCommands")
)
return sorted(set(lost))


def _allowed_commands_withheld(spec: dict[str, Any], policy: dict[str, Any] | None) -> bool:
"""Whether *spec*'s usable ``shell.allowedCommands`` go unanswered on KAS.

They do when the governance ceiling withholds the shell grant at the gate, or
when the spec's own author restricted the shell elsewhere (an ``ask``/``deny``
in *policy* or the raw ``permissions`` block, or another shell setting): the
same reading a shell grant in ``allowedTools`` gets. The ``allowedCommands``
key itself is the grant, so it is not read as a restriction. One reader for the
projection and the session-start notice, so the two cannot disagree.
"""
if not may_grant_builtin_at_gate_now("execute_bash"):
return True
return not withhold_answered_under_authored_rules(
{"execute_bash"},
policy,
authored_permissions=spec.get("permissions"),
tools_settings=without_allowed_commands(spec.get("toolsSettings")),
)


class KasAgentTranslationError(ValueError):
Expand Down Expand Up @@ -1173,6 +1209,14 @@ def to_client_custom_agent(
)
if crew_answered:
out[CREW_ANSWERED_BUILTINS_KEY] = sorted(crew_answered)
# `toolsSettings.shell.allowedCommands`, answered the same way: the gate
# approves a shell request whose command fullmatches one, after its checks.
# Asked of the ceiling as the shell tool, which is what the call runs, and
# withheld under the same authored restrictions as a shell grant. The
# `allowedCommands` key itself is the grant, so it is not read as one of them.
answered_commands = crew_answered_commands(spec.get("toolsSettings"))
if answered_commands and not _allowed_commands_withheld(spec, permissions):
out[CREW_ANSWERED_COMMANDS_KEY] = answered_commands

description = spec.get("description")
if isinstance(description, str) and description:
Expand Down Expand Up @@ -1434,6 +1478,37 @@ def _entry_crew_answered(entry: Any) -> frozenset[str]:
return frozenset(n for n in raw if isinstance(n, str) and n)


def _entry_crew_answered_commands(entry: Any) -> tuple[str, ...]:
"""The :data:`CREW_ANSWERED_COMMANDS_KEY` patterns of one projected entry, read
like :func:`_entry_crew_answered`: anything malformed answers empty."""
raw = entry.get(CREW_ANSWERED_COMMANDS_KEY) if isinstance(entry, dict) else None
if not isinstance(raw, list):
return ()
return tuple(p for p in raw if isinstance(p, str) and p)


def _registered_entry(custom_agents: Any, agent_id: str) -> Any:
entries = [a for a in custom_agents if isinstance(a, dict)] if custom_agents else []
return next((a for a in entries if a.get("id") == agent_id), None)


def _switched_entry(custom_agents: Any, mode_id: str) -> Any:
entries = [a for a in custom_agents if isinstance(a, dict)] if custom_agents else []
return next((a for a in entries if kas_wire_agent_id(str(a.get("id") or "")) == mode_id), None)


def projected_crew_answered_commands(custom_agents: Any, agent_id: str) -> tuple[str, ...]:
"""The ``allowedCommands`` patterns Crew answers for *agent_id*'s registered
entry, matched like :func:`projected_crew_answered`."""
return _entry_crew_answered_commands(_registered_entry(custom_agents, agent_id))


def switched_crew_answered_commands(custom_agents: Any, mode_id: str) -> tuple[str, ...]:
"""Those patterns once a KAS mode switch moves the session to *mode_id*,
matched like :func:`switched_crew_answered`."""
return _entry_crew_answered_commands(_switched_entry(custom_agents, mode_id))


def projected_crew_answered(custom_agents: Any, agent_id: str) -> frozenset[str]:
"""The built-ins Crew answers itself for *agent_id*'s registered entry.

Expand Down
91 changes: 90 additions & 1 deletion src/kiro_crew/acp/kas_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
from collections.abc import Callable, Iterable
from typing import Any

from kiro_crew.platform import allowed_commands as allowed_commands_mod
from kiro_crew.platform.tool_names import KIRO_CLI_NAME_BY_KAS_TOOL, KIRO_TOOL_ALIASES

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -142,8 +143,83 @@
#: (``_dispatch.attach_kas_custom_agents``).
CREW_ANSWERED_BUILTINS_KEY = "_crewAnsweredBuiltins"

#: The key a projected entry carries its :func:`crew_answered_commands` under, for
#: the session's own record, like :data:`CREW_ANSWERED_BUILTINS_KEY`.
CREW_ANSWERED_COMMANDS_KEY = "_crewAnsweredCommands"

#: Keys of a projected ``customAgents`` entry that never reach the engine.
CREW_ONLY_ENTRY_KEYS: frozenset[str] = frozenset({CREW_ANSWERED_BUILTINS_KEY})
CREW_ONLY_ENTRY_KEYS: frozenset[str] = frozenset(
{CREW_ANSWERED_BUILTINS_KEY, CREW_ANSWERED_COMMANDS_KEY}
)

#: The ``toolsSettings`` keys kiro-cli reads its shell settings under.
_SHELL_SETTINGS_KEYS = ("execute_bash", "shell")

#: Bounds on what :func:`crew_answered_commands` keeps, so the record the session
#: carries and the work the gate does per shell call stay small.
_MAX_ALLOWED_COMMANDS = 64


def allowed_command_pattern(raw: Any) -> str | None:
"""One kiro-cli ``allowedCommands`` entry as Crew records it, or ``None``.

Only the subset :mod:`kiro_crew.platform.allowed_commands` reads the same way
kiro-cli does, and matches in linear time, is kept (stripped); any other entry
is ``None`` and its commands keep prompting. Kept verbatim, as kiro-cli reads it.
"""
if allowed_commands_mod.parse(raw) is None:
return None
assert isinstance(raw, str)
return raw


def without_allowed_commands(tools_settings: Any) -> Any:
"""*tools_settings* with each shell entry's ``allowedCommands`` key left out.

For :func:`withhold_answered_under_authored_rules`, which reads ANY entry for a
built-in as a restriction: the grant itself is not one. A shell entry that held
only that key goes too; every other key, and any malformed value, is kept, so
it still withholds.
"""
if not isinstance(tools_settings, dict):
return tools_settings
out = dict(tools_settings)
for key in _SHELL_SETTINGS_KEYS:
entry = out.get(key)
if isinstance(entry, dict) and "allowedCommands" in entry:
rest = {k: v for k, v in entry.items() if k != "allowedCommands"}
if rest:
out[key] = rest
else:
del out[key]
return out


def _usable_allowed_commands(tools_settings: Any) -> list[str]:
"""Every distinct usable ``allowedCommands`` entry of both shell keys, in order."""
if not isinstance(tools_settings, dict):
return []
out: list[str] = []
for key in _SHELL_SETTINGS_KEYS:
settings = tools_settings.get(key)
entries = settings.get("allowedCommands") if isinstance(settings, dict) else None
for raw in entries if isinstance(entries, list) else ():
pattern = allowed_command_pattern(raw)
if pattern is not None:
out.append(pattern)
return list(dict.fromkeys(out))


def crew_answered_commands(tools_settings: Any) -> list[str]:
"""The ``shell.allowedCommands`` patterns Crew answers a KAS shell request for.

A shell allow never reaches the KAS policy (:data:`WITHHELD_CAPABILITIES`),
so each command raises a permission request; the gate's ``spec-builtin-grant``
tier approves one whose recovered command fullmatches a pattern here, after
every deny tier and governance (``gate_tiers._tier_spec_builtin_grant``).
Pure: the caller asks the governance ceiling about the shell tool.
"""
return _usable_allowed_commands(tools_settings)[:_MAX_ALLOWED_COMMANDS]


def crew_answered_builtins(allowed_tools: Any) -> frozenset[str]:
Expand Down Expand Up @@ -1379,6 +1455,19 @@ def url_glob(raw: str) -> str | None:
f"{tool}.deniedCommands", settings.get("deniedCommands"), _regex_to_glob
)
rules.extend(_chunked_rules("shell", "deny", denied))
# No rule: Crew answers the shell requests these match itself, at
# the gate (`crew_answered_commands`). Only an entry it cannot use
# is named.
handled.add("allowedCommands")
allowed = settings.get("allowedCommands")
# Named when an entry is unusable, and when the bound cuts the list:
# those commands keep prompting.
if allowed and (
not isinstance(allowed, list)
or any(allowed_command_pattern(p) is None for p in allowed)
or len(_usable_allowed_commands(tools_settings)) > _MAX_ALLOWED_COMMANDS
):
lost.append(f"{tool}.allowedCommands")
elif family in ("read", "write"):
capability = "fs_read" if family == "read" else "fs_write"
handled.add("deniedPaths")
Expand Down
3 changes: 3 additions & 0 deletions src/kiro_crew/acp/session_handle_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,9 @@ def __init__(
# their permission requests itself, after the deny floor, the
# sensitive-path check and the governance ceiling. Empty with no batch.
self.kas_crew_answered: frozenset[str] = frozenset()
# The agent's `toolsSettings.shell.allowedCommands` as the gate matches
# them (``kas_permissions.crew_answered_commands``), answered the same way.
self.kas_crew_answered_commands: tuple[str, ...] = ()
# The agent this session runs: the one the batch was registered for, then
# whichever a KAS mode switch moves it to ("" with no batch). A turn that
# names no agent runs this one, so its spec hooks are this agent's.
Expand Down
9 changes: 7 additions & 2 deletions src/kiro_crew/acp/session_handle_kas.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class binds it by name, so it reads and writes the session's own state on the in

Instance fields written: ``_compaction_failed_at``, ``_compaction_terminal_seen``,
``_hook_tasks``, ``_kas_prompt_row``, ``_last_kas_mode_id``, ``kas_auto_approved``,
``kas_crew_answered``, ``kas_projected_agent``, ``last_compaction_transient``.
``kas_crew_answered``, ``kas_crew_answered_commands``, ``kas_projected_agent``, ``last_compaction_transient``.

Instance fields read: ``_crew_agent``, ``_listed_hooks``, ``_prompt_starts``,
``_runtime``, ``_session_id``, ``_session_key``, ``_turn_done``,
Expand Down Expand Up @@ -264,11 +264,16 @@ def _handle_kas_update(
# -- chosen by wire id, so a built-in of the same name never inherits
# the crewmate's approvals.
if self.kas_projected_agent:
from kiro_crew.acp.kas_agents import switched_auto_approved, switched_crew_answered
from kiro_crew.acp.kas_agents import (
switched_auto_approved,
switched_crew_answered,
switched_crew_answered_commands,
)

self.kas_projected_agent = crew_id
self.kas_auto_approved = switched_auto_approved(registered, mode_id)
self.kas_crew_answered = switched_crew_answered(registered, mode_id)
self.kas_crew_answered_commands = switched_crew_answered_commands(registered, mode_id)
return [AcpEvent(kind=EVENT_AGENT_SWITCHED, text=crew_id)]
if session_update == UPDATE_SESSION_INFO:
return self._handle_kas_session_info(update)
Expand Down
3 changes: 2 additions & 1 deletion src/kiro_crew/acp/session_handle_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class binds it by name, so it reads and writes the session's own state on the in
``_tool_call_cache_overflow``, ``_tool_call_diff_path``,
``_tool_call_harness_tool_name``, ``_tool_call_input_redacted``, ``_tool_call_inputs``,
``_tool_call_is_shell``, ``_tool_call_mcp_server``, ``_tool_call_raw_params``,
``_tool_call_tool_name``, ``kas_crew_answered``, ``mirror_used``, ``spec_denied_tools``.
``_tool_call_tool_name``, ``kas_crew_answered``, ``kas_crew_answered_commands``, ``mirror_used``, ``spec_denied_tools``.
"""

from __future__ import annotations
Expand Down Expand Up @@ -655,4 +655,5 @@ def _build_permission_event(self: AcpSessionHandle, msg: JsonRpcMessage) -> AcpE
# which shares this session's id and is told apart by the id its
# agentSubtaskId frame recorded.
event.spec_granted_builtins = frozenset(getattr(self, "kas_crew_answered", ()))
event.spec_granted_commands = tuple(getattr(self, "kas_crew_answered_commands", ()))
return event
6 changes: 6 additions & 0 deletions src/kiro_crew/acp/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -1112,6 +1112,12 @@ class AcpEvent:
#: tier and governance, and approves only a host-identified built-in it names.
#: Empty everywhere else, which grants nothing.
spec_granted_builtins: frozenset[str] = frozenset()
#: spec_granted_commands: on the same requests, the agent's
#: ``toolsSettings.shell.allowedCommands`` as Python regexes
#: (``AcpSessionHandle.kas_crew_answered_commands``), written the same way. The
#: ``spec-builtin-grant`` tier approves a shell call whose recovered command
#: fullmatches one. Empty everywhere else, which grants nothing.
spec_granted_commands: tuple[str, ...] = ()
# Canonical, NON-model-authored tool identity from adapter-authored
# ``_meta.kiro`` or ``_meta.goose`` (see ``_dispatch._kiro_tool_name``).
# ``title`` is LLM-authored prose — for shell tools ``select_tool_title``
Expand Down
Loading
Loading