From baa94f2d8484883693cf70a4b3d55db2a4926f78 Mon Sep 17 00:00:00 2001 From: Pearce Kieser <5055971+Pearcekieser@users.noreply.github.com> Date: Sat, 26 Sep 2026 02:35:31 +0000 Subject: [PATCH 1/2] feat(session-control): session_create takes a model for the new session spawn_run and spawn_continue already take a per-run model, but session_create had no way to pick one, so a conductor opening worker sessions could not put them on a different model than the default. Add an optional model argument: held to the spawn_run model-id charset by the schema, refused with model_rejected by the same guard the dashboard model picker runs, pinned on the slot with the pick-generation bump a human pick gets, and recorded in the persist-at-birth metadata so an idle child keeps it across a restart. --- docs/system-specs/modules/session-control.md | 11 +- .../dashboard/handlers/session_control.py | 1 + src/kiro_crew/dashboard/session_control.py | 63 ++++++++- src/kiro_crew/docs/session-control.md | 1 + src/kiro_crew/mcp_dashboard.py | 18 ++- src/kiro_crew/validation.py | 11 ++ test/test_mcp_dashboard_folders.py | 30 ++++ test/test_session_control.py | 131 ++++++++++++++++++ 8 files changed, 262 insertions(+), 4 deletions(-) diff --git a/docs/system-specs/modules/session-control.md b/docs/system-specs/modules/session-control.md index 00f421dfc9ee..ddfdda4fd1a6 100644 --- a/docs/system-specs/modules/session-control.md +++ b/docs/system-specs/modules/session-control.md @@ -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 @@ -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 diff --git a/src/kiro_crew/dashboard/handlers/session_control.py b/src/kiro_crew/dashboard/handlers/session_control.py index 13efb360b09b..c49231ec45dc 100644 --- a/src/kiro_crew/dashboard/handlers/session_control.py +++ b/src/kiro_crew/dashboard/handlers/session_control.py @@ -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 diff --git a/src/kiro_crew/dashboard/session_control.py b/src/kiro_crew/dashboard/session_control.py index 77a4e2f807e2..c29bfdc8e240 100644 --- a/src/kiro_crew/dashboard/session_control.py +++ b/src/kiro_crew/dashboard/session_control.py @@ -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, @@ -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 @@ -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. @@ -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 @@ -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. @@ -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 @@ -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 @@ -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. @@ -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 {}), } diff --git a/src/kiro_crew/docs/session-control.md b/src/kiro_crew/docs/session-control.md index 544f59970a93..12568b5a1e94 100644 --- a/src/kiro_crew/docs/session-control.md +++ b/src/kiro_crew/docs/session-control.md @@ -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 diff --git a/src/kiro_crew/mcp_dashboard.py b/src/kiro_crew/mcp_dashboard.py index 2ef0238e6f1f..3ddb05ebf8e6 100644 --- a/src/kiro_crew/mcp_dashboard.py +++ b/src/kiro_crew/mcp_dashboard.py @@ -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": [], }, @@ -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, @@ -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." ) diff --git a/src/kiro_crew/validation.py b/src/kiro_crew/validation.py index ef44ee90682f..776873793e70 100644 --- a/src/kiro_crew/validation.py +++ b/src/kiro_crew/validation.py @@ -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, + ), ], ) diff --git a/test/test_mcp_dashboard_folders.py b/test/test_mcp_dashboard_folders.py index 5bb431394243..fe49e35f1937 100644 --- a/test/test_mcp_dashboard_folders.py +++ b/test/test_mcp_dashboard_folders.py @@ -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. diff --git a/test/test_session_control.py b/test/test_session_control.py index 44b3ccdccac4..7338d91515e8 100644 --- a/test/test_session_control.py +++ b/test/test_session_control.py @@ -30,6 +30,7 @@ class and a permissive test double would let a dead guard look alive. Second, from kiro_crew.dashboard import stop_retry from kiro_crew.dashboard.chat_utils import slot_history_key from kiro_crew.dashboard.handlers import session_control as handlers_sc +from kiro_crew.validation import MAX_SHORT_STRING # The autouse fixture below replaces ``sc.session_control_enabled`` so every # other test runs in the shipped (enabled) state without reading config. Keep a @@ -853,6 +854,39 @@ async def _json(): assert created is not None, "the route reported a target it did not create" assert created.title == "worker" + def test_create_route_forwards_the_model(self, tmp_path): + """A route dropping model pins nothing while handler tests stay green.""" + req = self._request(tmp_path, internal=True, path="/api/session-control/create") + + async def _json(): + return {"title": "worker", "model": "claude-sonnet-4.6"} + + req.json = _json + resp = asyncio.run(handlers_sc.api_session_control_create(req)) + + assert resp.status == 200 + payload = self._body(resp) + assert payload["model"] == "claude-sonnet-4.6" + created = req.app["state"].get_slot(payload["target"]) + assert created is not None + assert created.model == "claude-sonnet-4.6" + + def test_create_route_refuses_a_bad_charset_model(self, tmp_path): + """The route runs no schema, so create's own model bound must surface as a refusal.""" + req = self._request(tmp_path, internal=True, path="/api/session-control/create") + before = req.app["state"].live_slot_count() + + async def _json(): + return {"title": "worker", "model": "bad id"} + + req.json = _json + resp = asyncio.run(handlers_sc.api_session_control_create(req)) + + assert resp.status != 200 + assert resp.status < 500, "a refusal must not render as a server error" + assert self._body(resp)["code"] == "model_rejected" + assert req.app["state"].live_slot_count() == before + def test_create_renders_a_refusal_as_its_status_not_a_500(self, tmp_path, monkeypatch): """A SessionControlError from create must come back as its own refusal.""" req = self._request(tmp_path, internal=True, path="/api/session-control/create") @@ -3520,6 +3554,103 @@ def test_create_refuses_an_unknown_folder(tmp_path): assert state.live_slot_count() == before, "a refused create must not leave a slot behind" +def test_create_pins_the_requested_model_at_birth(tmp_path): + """A named model is pinned on the slot AND rides the birth metadata. + + Same disk argument as the folder: an idle newborn's birth line is its only + durable record, so a model set only in memory would come back as the default + after a restart. The pick-generation bump is what makes it an explicit + choice the fallback restore probe will not override. + """ + state = _make_state(tmp_path) + caller = _slot(state, "chat-1") + + created = asyncio.run( + sc.create_session(state, caller_session_key=_key(caller), model="claude-sonnet-4.6") + ) + + child = state.get_slot(created["target"]) + assert child is not None + assert child.model == "claude-sonnet-4.6" + assert child._model_pick_gen == 1 + assert created["model"] == "claude-sonnet-4.6" + written = state.conversation_log.get_metadata(slot_history_key(child)) + assert written.get("model") == "claude-sonnet-4.6" + + +def test_create_without_a_model_leaves_the_default(tmp_path): + """Omitting `model` changes nothing: no pin, no metadata key, no pick bump.""" + state = _make_state(tmp_path) + caller = _slot(state, "chat-1") + + created = asyncio.run(sc.create_session(state, caller_session_key=_key(caller))) + + child = state.get_slot(created["target"]) + assert child is not None + assert child.model == "" + assert child._model_pick_gen == 0 + assert "model" not in created + assert "model" not in state.conversation_log.get_metadata(slot_history_key(child)) + + +def test_create_refuses_a_model_the_picker_refuses(tmp_path, monkeypatch): + """The picker's own guard decides, and a refusal allocates nothing.""" + import kiro_crew.dashboard.chat_handlers as ch + + monkeypatch.setattr( + ch, "_model_rejected_reason", lambda name, provider=None: f"{name} is display-only" + ) + state = _make_state(tmp_path) + caller = _slot(state, "chat-1") + before = state.live_slot_count() + + with pytest.raises(sc.SessionControlError) as exc: + asyncio.run(sc.create_session(state, caller_session_key=_key(caller), model="fable-5-1m")) + + assert exc.value.code == "model_rejected" + assert state.live_slot_count() == before, "a refused create must not leave a slot behind" + + +def test_create_refuses_a_credential_shaped_model(tmp_path): + credential_shaped_id = "AKIA" + "Q" * 16 + assert sc.redact(credential_shaped_id) != credential_shaped_id + state = _make_state(tmp_path) + caller = _slot(state, "chat-1") + before = state.live_slot_count() + + with pytest.raises(sc.SessionControlError) as exc: + asyncio.run( + sc.create_session( + state, + caller_session_key=_key(caller), + model=credential_shaped_id, + ) + ) + + assert exc.value.code == "model_rejected" + assert credential_shaped_id not in exc.value.message + assert state.live_slot_count() == before, "a refused create must not leave a slot behind" + + +@pytest.mark.parametrize( + "bad_model", + ["x y", "a" * (MAX_SHORT_STRING + 1)], + ids=["bad-charset", "over-length"], +) +def test_create_refuses_an_unbounded_or_bad_charset_model(tmp_path, bad_model): + """The HTTP route does not run SESSION_CREATE_SCHEMA, so create bounds model itself.""" + state = _make_state(tmp_path) + caller = _slot(state, "chat-1") + before = state.live_slot_count() + + with pytest.raises(sc.SessionControlError) as exc: + asyncio.run(sc.create_session(state, caller_session_key=_key(caller), model=bad_model)) + + assert exc.value.code == "model_rejected" + assert bad_model not in exc.value.message + assert state.live_slot_count() == before, "a refused create must not leave a slot behind" + + def test_a_folder_deleted_mid_create_is_refused_under_the_lock(tmp_path, monkeypatch): """Folder existence is decided under the folder-store lock, late. From f7404f9b7aef28a90f7bc98d2ffe4b6f345a3519 Mon Sep 17 00:00:00 2001 From: Pearce Kieser <5055971+Pearcekieser@users.noreply.github.com> Date: Sun, 27 Sep 2026 06:08:11 +0000 Subject: [PATCH 2/2] fix(prepare-pr): trim SKILL.md back under its 68000-byte ceiling #14181 left the skill at 68015 bytes, so test_slim_skills_do_not_regrow_duplicate_guidance_or_wire_model_ids fails on main. Drop the duplicate 'never edit the goal' clause; the frozen-goal paragraph already says only the user may edit it. --- src/kiro_crew/builtin_skills/kirocrew-dev/prepare-pr/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/kiro_crew/builtin_skills/kirocrew-dev/prepare-pr/SKILL.md b/src/kiro_crew/builtin_skills/kirocrew-dev/prepare-pr/SKILL.md index 747e1643b598..a0a706f63129 100644 --- a/src/kiro_crew/builtin_skills/kirocrew-dev/prepare-pr/SKILL.md +++ b/src/kiro_crew/builtin_skills/kirocrew-dev/prepare-pr/SKILL.md @@ -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