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
11 changes: 9 additions & 2 deletions docs/system-specs/modules/session-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,12 @@ loses nothing — existence is confirmed read-only under the folder-store lock
only after the filing has landed, so a refused create leaves no folder-tree
mutation behind.

`session_create` also takes an optional `model` — the model the child starts
on, pinned as the person's own pick in the model dropdown would be (same
`_model_rejected_reason` guard, same pick-generation bump). An id the guard
refuses fails the whole create with `model_rejected`; omitted, the child starts
on the agent's or the global default.

### `session_fork`: a created child that carries a transcript

`session_create` opens an empty session, and the case it cannot serve is the
Expand Down Expand Up @@ -360,10 +366,11 @@ create already in flight. Revoking mid-call yields an untrusted child.

Nothing about trust is persisted at birth. The birth metadata carries
`tab_id`, `origin`, `created_at`, `workspace`, `agent`, `project`, `title`,
`memory_mode`, and `folder_id` / `created_by` when set — no trust field — so a
`memory_mode`, and `folder_id` / `created_by` / `model` when set — no trust field — so a
restart returns the child to interactive along with its creator.

The create's SEL record carries `agent`, `folder_id`, and what the child was
The create's SEL record carries `agent`, `folder_id`, `model` (empty when none
was asked for), and what the child was
born with: `inherited_trust` and `inherited_trust_reads`, present on both
outcomes so `"false"` is positive evidence the posture did not transfer. That is
what makes an auto-approved tool call in a dispatched session traceable to the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Ask in order:
1. **Is it legitimate?** Verify the code, reachable input, call path and consequence.
2. **Is it proportional?** Stay within the frozen goal and actual code shape;
reject speculative hardening, single-caller abstractions and unnecessary redesign.
Out of goal: rebut or defer, never edit the goal. A defect in code this PR adds or
Out of goal: rebut or defer. A defect in code this PR adds or
changes is always in scope and gets fixed; 'out of goal' applies only to new scope — a
new feature, surface, or hardening this PR does not need.
3. **Did an earlier round of this PR add the mechanism?** Check
Expand Down
1 change: 1 addition & 0 deletions src/kiro_crew/dashboard/handlers/session_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ async def api_session_control_create(request: web.Request) -> web.Response:
title=str(body.get("title") or ""),
agent=str(body.get("agent") or ""),
folder_id=str(body.get("folder_id") or ""),
model=str(body.get("model") or ""),
# The fence verdict this request's admission already settled, for the
# same reason every other route forwards it as
# `precomputed_ownership_fenced`: `create_session` consults it after
Expand Down
63 changes: 62 additions & 1 deletion src/kiro_crew/dashboard/session_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
)
from kiro_crew.dashboard.chat_persistence import _TRANSIENT_ROLES as _PERSISTENCE_TRANSIENT_ROLES
from kiro_crew.dashboard.chat_utils import (
_normalize_model,
drained_to_thread,
effective_session_key,
slot_history_key,
Expand Down Expand Up @@ -90,7 +91,12 @@
from kiro_crew.messaging.transport import DM_TARGET_PREFIX, sole_direct_target
from kiro_crew.security import redact, redact_and_truncate
from kiro_crew.sel import sel
from kiro_crew.validation import MAX_ACP_SESSION_ID_LEN, MAX_LONG_STRING
from kiro_crew.validation import (
_MODEL_NAME_RE,
MAX_ACP_SESSION_ID_LEN,
MAX_LONG_STRING,
MAX_SHORT_STRING,
)

if TYPE_CHECKING: # pragma: no cover - typing only
from kiro_crew.dashboard.state import DashboardState, _ChatSlot
Expand Down Expand Up @@ -1623,6 +1629,7 @@ async def create_session(
title: str = "",
agent: str = "",
folder_id: str = "",
model: str = "",
caller_fenced: bool | None = None,
) -> dict[str, Any]:
"""Open a new session in the caller's workspace, persisted at birth.
Expand Down Expand Up @@ -1662,6 +1669,13 @@ async def create_session(
already refused above it -- an app-scoped caller cannot create a session at
all (`app_scoped_caller`).

``model`` pins the model the child starts on, as the person's own pick in the
model dropdown would: same rejection guard, same pick-generation bump, and
recorded in the persist-at-birth metadata so an idle child keeps it across a
restart. Empty leaves the slot on the agent's or the global default, exactly
as before. It is not a privilege the caller lacks -- ``spawn_run`` already
takes a per-run ``model`` -- and it moves no memory boundary.

``caller_fenced`` is the ownership-fence verdict the HTTP gate already settled
on the caller's VERIFIED scope, carried in for the same reason
``authorize_target`` takes ``precomputed_ownership_fenced``: the inline
Expand Down Expand Up @@ -1831,6 +1845,38 @@ async def create_session(
code="agent_unresolved",
)

# The model the child starts on. Checked by the SAME guard the dashboard's
# model picker runs (`_model_rejected_reason`), against the provider from the
# config snapshot already loaded off the loop, so an id the picker would refuse
# is refused here too -- before anything is allocated, where refusing loses
# nothing. Length and charset are bounded HERE, not left to the MCP schema:
# SESSION_CREATE_SCHEMA runs only in mcp_dashboard, and the HTTP route
# forwards the body's model string as-is, so without this bound an
# internal-secret caller could persist, broadcast and audit-log an
# arbitrarily long or arbitrarily shaped value.
model_name = _normalize_model(model.strip())
if model_name:
if len(model_name) > MAX_SHORT_STRING or not _MODEL_NAME_RE.fullmatch(model_name):
raise SessionControlError(
"model id is too long or contains characters outside the model-id charset",
code="model_rejected",
)

# Never persist or broadcast a value the security scrubber classifies.
if redact(model_name) != model_name:
raise SessionControlError(
"model id looks like a credential and was refused",
code="model_rejected",
)

# circular import: chat_handlers imports session_control lazily, and this
# module is imported by the dashboard package before chat_handlers loads.
from kiro_crew.dashboard.chat_handlers import _model_rejected_reason

model_reason = _model_rejected_reason(model_name, provider=cfg.agent.provider or "")
if model_reason:
raise SessionControlError(model_reason, code="model_rejected")

# Capture the child route once. Inherited member/store identity survives
# renamed aliases or changed config; an explicit member selection is resolved
# from the config snapshot admitted above.
Expand Down Expand Up @@ -2253,6 +2299,14 @@ def _exists(folders: list[dict[str, Any]]) -> bool:
# (`is_new` in chat_runner), so the [FOLDER] line reaches the model
# without it.
slot.folder_id = folder_id
if model_name:
# Pinned the way a person's pick in the model dropdown pins it: the
# slot has no provider session yet, so there is nothing to switch --
# the first turn starts on this model. The pick-generation bump marks
# it as an explicit choice, so the fallback restore probe treats it
# exactly as it treats a human pick rather than as a backfilled value.
slot.model = model_name
slot._model_pick_gen += 1
if title.strip():
slot.title = sanitize_outbound(title.strip())[:200]
slot._titled = True
Expand Down Expand Up @@ -2325,6 +2379,11 @@ def _persist_birth(metadata: dict[str, Any]) -> None:
# the filing would not survive a restart: for an idle newborn
# THIS dict is the only record of the placement on disk.
**({"folder_id": slot.folder_id} if slot.folder_id else {}),
# The pinned model, only when one was asked for -- the normal
# save path writes `model` too, but for an idle newborn this
# dict is the only record, and without it a restart would
# bring the session back on the default model.
**({"model": slot.model} if model_name else {}),
# Creator attribution, only when this entry point set it. The
# member ownership boundary in `authorize_target` reads it, so
# losing it on restart would strand every worker a member
Expand Down Expand Up @@ -2407,6 +2466,7 @@ def _persist_birth(metadata: dict[str, Any]) -> None:
detail={
"agent": slot.agent or "",
"folder_id": slot.folder_id or "",
"model": model_name,
# What the child was BORN with, so an auto-approved tool call in it is
# traceable to the creator's grant rather than appearing unexplained.
# Always present: "false" is the record that the grant did not transfer.
Expand All @@ -2418,6 +2478,7 @@ def _persist_birth(metadata: dict[str, Any]) -> None:
"ok": True,
"target": slot.key,
"title": slot.title or slot.key,
**({"model": model_name} if model_name else {}),
}


Expand Down
1 change: 1 addition & 0 deletions src/kiro_crew/docs/session-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ conductor: a session that can dispatch but cannot edit a file. Always pass
| `title` | no | Short sidebar name. Say what the session is FOR |
| `agent` | no (but always pass it) | Agent to bind the session to |
| `folder` | no | Sidebar folder id or `/`-separated path to file it into, atomically with creation. Missing path segments are created (`mkdir -p`) |
| `model` | no | Model the session starts on, pinned as if the person picked it in the model dropdown (same guard; refused with `model_rejected` when the picker would refuse it). Omit for the agent's or global default |

No argument is formally required. The new session **starts empty** — nothing runs
in it until the person types, or until you send it a message. The reply carries
Expand Down
18 changes: 17 additions & 1 deletion src/kiro_crew/mcp_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,19 @@ def _tool_definitions() -> list[dict[str, Any]]:
"`parent`. Omit to leave the session at the top level."
),
},
"model": {
"type": "string",
"description": (
"Model the new session starts on, pinned exactly as if the "
"person had picked it in the session's model dropdown: an id "
"from that same list, or 'auto'. Omit to use the agent's or "
"the global default. A well-formed id the account cannot serve "
"is accepted here but withheld at the session's first turn: "
"the turn succeeds on the account's default model, and the only "
"signal is a notice in that session's transcript. The person "
"can still change it later."
),
},
},
"required": [],
},
Expand Down Expand Up @@ -1793,6 +1806,8 @@ def _call_tool_inner(name: str, args: dict[str, Any]) -> str:
return fld_err
if fld_id:
payload["folder_id"] = fld_id
if args.get("model"):
payload["model"] = args["model"]
resp = _post(
"/api/session-control/create",
payload,
Expand All @@ -1801,8 +1816,9 @@ def _call_tool_inner(name: str, args: dict[str, Any]) -> str:
if resp.get("error"):
return redact(f"Error: could not create a session: {resp['error']}{made_note}")
filed = f" filed in `{folder_label}`" if folder_label else ""
on_model = f" on model `{resp['model']}`" if resp.get("model") else ""
return redact(
f"\U0001f195 Opened `{resp.get('target')}` ({resp.get('title')}){filed}.{made_note} "
f"\U0001f195 Opened `{resp.get('target')}` ({resp.get('title')}){filed}{on_model}.{made_note} "
"It is empty and waiting in the user's sidebar; watch it with "
"session_read_message."
)
Expand Down
11 changes: 11 additions & 0 deletions src/kiro_crew/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3326,6 +3326,17 @@ def _validate_channel_routing(cleaned: dict[str, Any]) -> None:
# folder reference; the two readings share no charset, so only the
# length is checked here.
FieldSpec("folder", str, required=False, default="", max_len=_ARTIFACT_FOLDER_REF_MAX),
# Model the new session starts on, the same field ``spawn_run.model``
# takes and under the same charset: the id is persisted to the metadata
# line and later handed to the backend, so arbitrary strings stay out.
FieldSpec(
"model",
str,
required=False,
default="",
max_len=MAX_SHORT_STRING,
pattern=_MODEL_NAME_RE,
),
],
)

Expand Down
30 changes: 30 additions & 0 deletions test/test_mcp_dashboard_folders.py
Original file line number Diff line number Diff line change
Expand Up @@ -1690,6 +1690,36 @@ def test_an_unverifiable_caller_never_reaches_the_request(self):
get.assert_not_called()


class TestSessionCreateModel:
"""`session_create.model` — the model id reaches the create route verbatim."""

def test_model_rides_the_create_payload(self) -> None:
created = {"target": "chat-9-900", "title": "worker", "model": "claude-sonnet-4.6"}
with patch("kiro_crew.mcp_dashboard._post", return_value=created) as post:
out = _call_tool_inner(
"session_create", {"title": "worker", "model": "claude-sonnet-4.6"}
)
path, body = post.call_args.args
assert path == "/api/session-control/create"
assert body["model"] == "claude-sonnet-4.6"
assert "claude-sonnet-4.6" in out

def test_omitted_model_sends_no_key(self) -> None:
with patch(
"kiro_crew.mcp_dashboard._post", return_value={"target": "chat-9-900", "title": "w"}
) as post:
_call_tool_inner("session_create", {"title": "w"})
assert "model" not in post.call_args.args[1]

def test_a_malformed_model_is_refused_before_any_call(self) -> None:
from kiro_crew.validation import ValidationError

with patch("kiro_crew.mcp_dashboard._post") as post:
with pytest.raises(ValidationError, match="model"):
_call_tool_inner("session_create", {"title": "w", "model": "x; rm -rf"})
assert post.call_count == 0


class TestSessionCreateFolder:
"""`session_create.folder` — filing atomic with creation.

Expand Down
Loading
Loading