Skip to main content

trusty_code/task/
protocol.rs

1//! `task.run` JSON-RPC method (#2056, vision spec §4.3): start a
2//! session-driven task execution.
3//!
4//! Why: this is the API surface the M1 control-plane cut line needs — a
5//! caller creates (or targets an existing) session and asks the daemon to
6//! actually EXECUTE a task against it, asynchronously, streaming progress via
7//! the #2054/#2055 `session.attach` path. Kept as its own JSON-RPC method
8//! (rather than overloading `session.send`) because `session.send`'s
9//! existing #2054/#2055 contract — record an observable `SessionInput` event
10//! — is already tested and shipped; `task.run` is the deliberate, explicit
11//! "start executing" entry point the issue names.
12//! What: [`register`] wires `task.run` onto a [`Router`], sharing the SAME
13//! `Arc<SessionRegistry>` every `session.*` method uses. Params match the
14//! vision spec §4.3 example almost verbatim: `task_description`,
15//! `agent_name` (top-level/PM agent, default `"pm"`), `context` (accepted for
16//! forward-compatibility; not yet injected into the prompt — project
17//! `CLAUDE.md` context already flows through `run_task`'s existing
18//! machinery, and free-form per-call `context` injection is a smaller
19//! follow-up, not core to this cut line), `model_override` (pins the
20//! delegated ENGINEER's model for this run), and an ADDITIONAL optional
21//! `session_id` for "sessionful" execution against an already-`session.create`d
22//! session (the spec's "single-shot or sessionful" phrasing).
23//! Test: `task::protocol::tests::*`; the full flow end-to-end (a real
24//! subprocess) in `tests/task_e2e.rs`.
25
26use std::path::PathBuf;
27use std::sync::Arc;
28
29use serde::Deserialize;
30use serde_json::{Value, json};
31
32use crate::binding::ProjectBinding;
33use crate::jsonrpc::{ConnectionContext, Router, RpcError};
34use crate::session::SessionRegistry;
35use crate::workstreams::SharedWorkstreamStore;
36
37use super::executor::{TaskRunParams, spawn_task_run};
38use super::mock_llm::build_llm_client;
39
40/// Default top-level/PM agent name used when `task.run`'s `agent_name` param
41/// is omitted (#3437).
42///
43/// Why: #3437 — every GUI-initiated run omits `agent_name` (no agent-roster
44/// endpoint exists yet for the GUI to pick from), so `task_run`'s default
45/// MUST resolve against a real agent in every resolution tier (disk then
46/// embedded, see `agents::resolve_agent`) or 100% of daemon-default runs fail
47/// agent resolution before a single turn executes — exactly the failure mode
48/// #3437 traced. A shared `pub` const (referenced from both this call site
49/// and `assets::tests::default_task_run_agent_resolves_against_default_agents`)
50/// is the drift-guard: the literal here and the embedded roster entry it must
51/// resolve against can never independently rot out of sync the way two
52/// separately-typed `"pm"` string literals could.
53/// What: `"pm"` — must have a matching `EmbeddedAgent` entry in
54/// [`crate::assets::DEFAULT_AGENTS`] (see `assets/agents/pm.md`).
55/// Test: `task::protocol::tests::task_run_creates_session_when_none_given`
56/// (exercises the default through a real `task_run` call);
57/// `assets::tests::default_task_run_agent_resolves_against_default_agents`
58/// (pins that the literal resolves against the embedded roster).
59pub const DEFAULT_TASK_RUN_AGENT_NAME: &str = "pm";
60
61/// Register `task.run` onto `router`.
62///
63/// Why: the one place that wires the method, mirroring
64/// `session::protocol::register`'s role for `session.*`.
65/// What: closes over `registry`, `binding`, and `agents_dir` — all shared,
66/// cheap to clone (`Arc`/`PathBuf`) per call. `binding` replaces what was a
67/// REQUIRED `project: PathBuf`: a `PathBuf` cannot express "no project", so the
68/// projectless state the shell's entry screen renders was unreachable — the
69/// daemon could not be started, let alone run a task, without one. It is now a
70/// [`ProjectBinding`], whose `None` variant is that state.
71/// Test: `task::protocol::tests::register_wires_task_run`,
72/// `task::protocol::tests::register_wires_task_run_projectless`.
73/// (Issue #3298) `workstreams` is the daemon's shared workstream store —
74/// `task.run` resolves and persists a freshly-minted session's binding
75/// (explicit `workstream_id` param, or DOC-48 §4.2's ambient
76/// active-workstream default) through it, or enforces §4.1's immutability
77/// rule against an EXISTING session's persisted binding — see
78/// `task_run`'s docs.
79pub fn register(
80    router: &mut Router,
81    registry: Arc<SessionRegistry>,
82    binding: ProjectBinding,
83    agents_dir: PathBuf,
84    workstreams: SharedWorkstreamStore,
85) {
86    register_with_permissions(router, registry, binding, agents_dir, workstreams, None);
87}
88
89/// [`register`] with the daemon's permission broker (#7948).
90///
91/// Why: `crate::serve::build_router` owns the one broker
92/// `session.permission.respond` answers into; every other caller (tests)
93/// keeps [`register`], whose runs are headless.
94/// What: `permissions: None` makes every `task.run` headless — an `ask`
95/// resolves at once per `TCODE_PERMISSION_MODE`. The mode is read from the
96/// daemon's environment, never from the request: the caller asking to run a
97/// task must not be able to widen its own permissions.
98/// Test: `serve::http_tests::*` (through `build_router`),
99/// `permissions::tests::protocol_tests::respond_resolves_a_pending_request`.
100pub fn register_with_permissions(
101    router: &mut Router,
102    registry: Arc<SessionRegistry>,
103    binding: ProjectBinding,
104    agents_dir: PathBuf,
105    workstreams: SharedWorkstreamStore,
106    permissions: Option<Arc<crate::permissions::PermissionBroker>>,
107) {
108    router.register("task.run", move |params: Value, _ctx: ConnectionContext| {
109        let registry = Arc::clone(&registry);
110        let binding = binding.clone();
111        let agents_dir = agents_dir.clone();
112        let workstreams = workstreams.clone();
113        let permissions = permissions.clone();
114        async move {
115            task_run_with_permissions(
116                registry,
117                params,
118                binding,
119                agents_dir,
120                workstreams,
121                permissions,
122            )
123            .await
124        }
125    });
126}
127
128/// `task.run` request params (vision spec §4.3).
129#[derive(Deserialize)]
130struct TaskRunRequestParams {
131    task_description: String,
132    #[serde(default)]
133    agent_name: Option<String>,
134    /// Accepted for forward-compatibility; not yet injected into the
135    /// assembled prompt — see the module docs.
136    #[serde(default)]
137    #[allow(dead_code)]
138    context: Option<String>,
139    #[serde(default)]
140    model_override: Option<String>,
141    /// (#8030) Pins the TOP-LEVEL agent's model for this run, the sibling
142    /// `model_override` never had — that field only ever rewired the
143    /// DELEGATED engineer, so a caller could not repoint the agent that
144    /// actually orchestrates.
145    ///
146    /// Why: the owner rule (2026-09-15) is that every tcode capability is
147    /// reachable from CLI/API; before this, the top-level model was reachable
148    /// only by hand-editing a deployed `.trusty-code/agents/<agent>.md`.
149    /// What: `#[serde(default)]` — omitted means "no override", which is the
150    /// pre-#8030 behaviour exactly. A short alias (`opus`/`sonnet`/`haiku`)
151    /// is accepted and normalised downstream by
152    /// `crate::provider::resolve_model_with_override`.
153    /// Test: `task::protocol::tests::task_run_params_parse_pm_model`,
154    /// `task::protocol::tests::task_run_params_default_pm_model_to_none`.
155    #[serde(default)]
156    pm_model: Option<String>,
157    /// (#8128) Raises (or lowers) the PM loop's turn cap for this run.
158    ///
159    /// Why: the cap was `AgentLoopConfig::default()`'s 8 with no override, so
160    /// a multi-step delivery task could not be given more turns.
161    /// What: `#[serde(default)]` — omitted keeps the built-in 8. Zero is
162    /// rejected as `invalid_argument` by [`task_run`]: a zero-turn loop makes
163    /// no LLM call and would report an empty run as a normal one.
164    /// Test: `task::protocol::tests::task_run_params_parse_max_turns`,
165    /// `task::protocol::tests::task_run_rejects_zero_max_turns`.
166    #[serde(default)]
167    max_turns: Option<u32>,
168    /// #2056 extension beyond the spec's literal example: when present,
169    /// runs against an EXISTING session (created via `session.create`)
170    /// instead of minting a fresh one — the spec's "sessionful" execution
171    /// mode.
172    #[serde(default)]
173    session_id: Option<String>,
174    /// #2059: per-call `HarnessMode` override (vision spec §5.9's tier-2
175    /// precedence source, above `.claude/settings.json` and below
176    /// `TRUSTY_CODE_MODE`). Leniently parsed by
177    /// `crate::mode::resolve_mode` — an unrecognised string here degrades
178    /// to "this source does not contribute", NOT a request error.
179    #[serde(default)]
180    mode: Option<String>,
181    /// #2207: per-call wall-clock deadline override, in seconds, applied to
182    /// BOTH the PM's own loop and the delegated engineer's loop. `None`
183    /// falls through to `crate::provider::resolve_deadline_secs`'s env-var
184    /// (`TCODE_RUN_DEADLINE_SECONDS`) and default (1800s) tiers.
185    #[serde(default)]
186    deadline_secs: Option<u64>,
187    /// #3178: per-call project override (DOC-39 §5.5, AC-16.2 convergence).
188    /// `None` preserves today's back-compat behaviour — the process-boot-time
189    /// `binding` `register` closed over. `Some(path)` is resolved through the
190    /// SAME [`ProjectBinding::resolve`] `session.create`'s `CreateParams.project`
191    /// uses (see `crate::session::protocol::create`'s docs), so a nonexistent
192    /// or non-directory path maps to `-32003 invalid_argument` identically on
193    /// both surfaces — this is the keystone convergence the issue names:
194    /// `task.run` and `session.create` can no longer disagree about what a
195    /// project is or how one is resolved.
196    ///
197    /// **Invariant when paired with `session_id` (reusing an existing
198    /// session):** a session's persisted `Session.binding` is authoritative —
199    /// `SessionRegistry` has no binding-update path (it is set once, in
200    /// `SessionRegistry::create`). `project` may only RESTATE that same root;
201    /// naming a DIFFERENT root is rejected with `-32003 invalid_argument`
202    /// rather than silently executing the run against a project
203    /// `session.status`/`session.list` would never agree it is bound to. See
204    /// [`task_run`]'s docs.
205    #[serde(default)]
206    project: Option<PathBuf>,
207    /// (Issue #3298, DOC-48 §4.1/§4.2) Explicit workstream to bind a
208    /// FRESHLY-MINTED session to (`session_id` absent), or to RESTATE an
209    /// existing reused session's own persisted binding — see
210    /// [`task_run`]'s docs on the immutability check this triggers on the
211    /// `session_id`-present path. `None` on the mint path falls back to
212    /// §4.2's ambient active-workstream default; `None` on the reuse path
213    /// never re-applies ambient targeting (a session's binding, once set, is
214    /// immutable — see `crate::workstreams::protocol::check_workstream_immutable`'s
215    /// docs).
216    #[serde(default)]
217    workstream_id: Option<String>,
218    /// (#8031) Run `agent_name` ALONE — skip `delegate_to_agent` registration
219    /// for this run and give `agent_name` its own tcode tools instead, so it
220    /// does the work rather than handing it to `python-engineer`.
221    ///
222    /// Why: the API surface has to express the same run shape the CLI's
223    /// `--no-delegate` flag does, or a non-CLI caller (the GUI, an MCP
224    /// client) cannot request a guaranteed single-agent run at all.
225    /// What: `#[serde(default)]` — an omitted field is `false`, which is
226    /// exactly the pre-#8031 behaviour, so no existing caller changes. `true`
227    /// registers the same tool set, under the same `tools.allowed` and
228    /// `permissions:` gating, a delegation of `agent_name` would get — see
229    /// [`crate::task::executor::TaskRunParams::no_delegate`].
230    /// Test: `task::protocol::tests::task_run_params_default_no_delegate_to_false`,
231    /// `task::protocol::tests::task_run_params_parse_no_delegate_true`.
232    #[serde(default)]
233    no_delegate: bool,
234}
235
236/// `task.run(task_description, agent_name?, context?, model_override?,
237/// session_id?, mode?, deadline_secs?, project?, workstream_id?,
238/// no_delegate?, pm_model?, max_turns?) -> { session_id, status, mode }`.
239///
240/// Why: the single entry point that turns a request into a running
241/// background execution.
242///
243/// **(Issue #3298, DOC-48 §4.1/§4.2) Workstream binding**, mirroring the
244/// `project`/binding reconciliation immediately below: on the mint path
245/// (`session_id` absent), resolves the EFFECTIVE workstream target —
246/// `workstream_id` explicit param wins, else the daemon's active workstream
247/// is the ambient default (§4.2), else the session stays projectless — and
248/// persists it via `crate::workstreams::protocol::resolve_validate_bind`
249/// (validated BEFORE the session is minted — see that helper's docs on the
250/// PR #3354 phantom-session fix)
251/// before this session is used further. On the reuse path (`session_id`
252/// present), the session's own persisted `workstream_id` is authoritative;
253/// `crate::workstreams::protocol::check_workstream_immutable` rejects a
254/// `workstream_id` param that would silently redirect a session
255/// `session.status`/`session.list` already reports as bound to a different
256/// (or no) workstream — same rule, same rationale as the `project` mismatch
257/// guard.
258/// What: validates `task_description` is non-empty
259/// (`-32003 invalid_argument`); resolves the EFFECTIVE binding for this call —
260/// `project: Some(path)` resolves via [`ProjectBinding::resolve`] (mapping a
261/// `BindingError` onto `-32003 invalid_argument`, exactly like
262/// `session.create`); `project: None` keeps the process-boot-time `binding`
263/// `register` closed over, so an existing caller that never sends `project`
264/// observes no change (#3178 back-compat). Then resolves the target session —
265/// an existing one by `session_id` (propagating `session_not_found` if it
266/// doesn't exist) or a freshly `session.create`d one bound to the effective
267/// binding; resolves the effective `HarnessMode` via `crate::mode::resolve_mode`
268/// (#2059's three-tier precedence, rooted at the effective binding) and
269/// persists it onto the session (`SessionRegistry::set_mode`) so it is
270/// queryable afterward via `session.status`/`session.list` (`Session.mode`)
271/// and `session.get_transcript` (`TranscriptRecord.mode`); builds the shared
272/// LLM client (real or the #2056 offline mock, per `TCODE_MOCK_LLM`); and
273/// calls `spawn_task_run`, which reserves the execution slot synchronously
274/// (rejecting a second overlapping run) before handing off to the background
275/// task. Returns immediately — the caller `session.attach`es to observe
276/// progress, per the ticket's "must not block the request thread on the whole
277/// LLM run" requirement. The response's own `mode`/`binding` fields are the
278/// SAME resolved values, surfaced immediately rather than requiring a
279/// follow-up `session.status` call.
280///
281/// **Invariant: a reused session's persisted binding is authoritative.** When
282/// `session_id` is supplied, `project` may only RESTATE that session's own
283/// `Session.binding` root (or be omitted); a `project` naming a DIFFERENT
284/// root is rejected as `-32003 invalid_argument` rather than silently
285/// executing the run against a project the session itself was never bound to
286/// (`SessionRegistry` has no binding-update path — `create` sets it once).
287/// Accepting the mismatch would let `session.status`/`session.list` report
288/// the ORIGINAL binding forever while the run actually executed against a
289/// different one — a silent audit/state divergence this validation exists to
290/// prevent (code-critic HIGH finding, PR #3189).
291///
292/// **(#8184) Invariant: a reused session's agent SHAPE is authoritative too.**
293/// A session minted solo (`session.create`'s default — see
294/// `crate::session::protocol::create`) runs solo on every turn; a session
295/// minted delegating rejects a `no_delegate: true` call with
296/// `-32003 invalid_argument` rather than running a shape
297/// `session.status`/`session.list` would keep reporting as the other one.
298/// Same rule, same rationale as the `project` and `workstream_id` guards. The
299/// mint path persists this call's own `no_delegate` onto the session it
300/// creates, so the run and the record always agree.
301///
302/// The guard is ONE-DIRECTIONAL by construction: `no_delegate` is a plain
303/// `bool` with a serde default, so an omitted field and an explicit `false`
304/// are the same value on the wire and a request cannot express "I want
305/// delegation" for the daemon to reject. A solo session therefore runs solo
306/// for a caller that asked for either — which is the shape it reports.
307/// Test: `task::protocol::tests::task_run_rejects_empty_task_description`,
308/// `task::protocol::tests::task_run_creates_session_when_none_given`,
309/// `task::protocol::tests::task_run_sessionful_reuses_existing_session`,
310/// `task::protocol::tests::task_run_unknown_session_id_errors`,
311/// `task::protocol::tests::task_run_resolves_and_reports_mode`,
312/// `task::protocol::tests::task_run_without_project_keeps_boot_binding`,
313/// `task::protocol::tests::task_run_with_project_overrides_boot_binding`,
314/// `task::protocol::tests::task_run_rejects_invalid_project`,
315/// `task::protocol::tests::task_run_session_id_with_matching_project_succeeds`,
316/// `task::protocol::tests::task_run_session_id_with_mismatched_project_is_rejected`,
317/// `task::protocol::tests::task_run_on_a_default_session_never_delegates`,
318/// `task::protocol::tests::task_run_on_a_delegating_session_still_delegates`,
319/// `task::protocol::tests::task_run_minted_session_records_its_no_delegate`,
320/// `task::protocol::tests::task_run_no_delegate_against_a_delegating_session_is_rejected`.
321// #7948: production registers through `register_with_permissions`; this
322// headless five-argument form is what the unit tests drive.
323#[cfg(test)]
324async fn task_run(
325    registry: Arc<SessionRegistry>,
326    params: Value,
327    binding: ProjectBinding,
328    agents_dir: PathBuf,
329    workstreams: SharedWorkstreamStore,
330) -> Result<Value, RpcError> {
331    task_run_with_permissions(registry, params, binding, agents_dir, workstreams, None).await
332}
333
334/// [`task_run`] with the daemon's permission broker (#7948); `None` runs
335/// headless. Called by [`register_with_permissions`].
336/// Test: `task::protocol::tests::*` (through [`task_run`]).
337async fn task_run_with_permissions(
338    registry: Arc<SessionRegistry>,
339    params: Value,
340    binding: ProjectBinding,
341    agents_dir: PathBuf,
342    workstreams: SharedWorkstreamStore,
343    permissions: Option<Arc<crate::permissions::PermissionBroker>>,
344) -> Result<Value, RpcError> {
345    let p: TaskRunRequestParams = serde_json::from_value(params)
346        .map_err(|e| RpcError::invalid_params(format!("task.run: {e}")))?;
347    if p.task_description.trim().is_empty() {
348        return Err(RpcError::invalid_argument(
349            "task_description must not be empty",
350        ));
351    }
352    // #8128: a zero turn cap would run no turns at all and report the empty
353    // result as a normal one — reject it before a session is ever minted.
354    if p.max_turns == Some(0) {
355        return Err(RpcError::invalid_argument(
356            "max_turns must be at least 1 (0 would run no turns at all)",
357        ));
358    }
359    // #3178: a per-call `project` overrides the boot-time binding for this
360    // call only, resolved through the exact same helper `session.create` uses
361    // — never a second, divergent implementation of "what is a project".
362    let project_given = p.project.is_some();
363    let binding = match p.project {
364        Some(project) => ProjectBinding::resolve(Some(project))
365            .map_err(|e| RpcError::invalid_argument(format!("task.run: {e}")))?,
366        None => binding,
367    };
368    let agent_name = p
369        .agent_name
370        .unwrap_or_else(|| DEFAULT_TASK_RUN_AGENT_NAME.to_string());
371
372    // #8184: the shape this run ACTUALLY executes, which is also the one
373    // persisted on the session — the two can never disagree, see the
374    // immutability guard on the reuse arm below.
375    let mut effective_no_delegate = p.no_delegate;
376    let session_id = match &p.session_id {
377        Some(id) => {
378            let existing = registry.status(id)?; // propagate session_not_found verbatim
379            // HIGH finding (code-critic, PR #3189): a session's persisted
380            // binding is authoritative once created — reject a per-call
381            // `project` that would silently redirect the run to a DIFFERENT
382            // root than `session.status`/`session.list` will keep reporting.
383            if project_given && existing.binding.root() != binding.root() {
384                return Err(RpcError::invalid_argument(format!(
385                    "task.run: project `{}` does not match session `{id}`'s existing binding \
386                     `{}` — a session's persisted binding is authoritative; project may only \
387                     restate it, not change it",
388                    binding
389                        .label()
390                        .unwrap_or_else(|| "<projectless>".to_string()),
391                    existing
392                        .binding
393                        .label()
394                        .unwrap_or_else(|| "<projectless>".to_string()),
395                )));
396            }
397            // (Issue #3298, DOC-48 §4.1 AC-1.3) A REUSED session's own
398            // persisted `workstream_id` is likewise authoritative — the
399            // exact same rule as the `project` check just above, applied to
400            // the sibling binding. `None` here never rejects: ambient
401            // default-targeting (§4.2) applies only at a session's FIRST
402            // binding, never re-applied on reuse.
403            crate::workstreams::protocol::check_workstream_immutable(
404                existing.workstream_id,
405                p.workstream_id.as_deref(),
406                "task.run",
407            )?;
408            // (#8184) A session's agent SHAPE is immutable once set, the same
409            // rule as `binding` and `workstream_id` above and for the same
410            // reason: `session.status`/`session.list` keep reporting the
411            // persisted value, so a call that ran a DIFFERENT shape would be
412            // the silent record-vs-run divergence those two guards exist to
413            // prevent (PR #3189). A run may only restate the session's shape.
414            if p.no_delegate && !existing.no_delegate {
415                return Err(RpcError::invalid_argument(format!(
416                    "task.run: no_delegate does not match session `{id}`'s own delegating shape \
417                     — a session's agent shape is persisted at creation and authoritative; \
418                     create a session with `delegate: false` for a single-agent run"
419                )));
420            }
421            effective_no_delegate = existing.no_delegate;
422            id.clone()
423        }
424        None => {
425            // (PR #3354 code-critic HIGH 2) Validate the workstream target
426            // BEFORE minting: `SessionRegistry` has no delete/rollback, so
427            // a rejected bind (malformed/unknown/closed `workstream_id`)
428            // must fire while no session exists yet — the mint runs as a
429            // closure inside `resolve_validate_bind`, only after validation
430            // passes, under the same store lock (TOCTOU-free; see that
431            // helper's docs).
432            let (session_id, target) = crate::workstreams::protocol::resolve_validate_bind(
433                &workstreams,
434                p.workstream_id.as_deref(),
435                "task.run",
436                || {
437                    // #8184: record THIS call's shape on the session it mints,
438                    // so a later turn against the same session inherits it.
439                    registry
440                        .create_with_delegation(
441                            p.task_description.clone(),
442                            Some(agent_name.clone()),
443                            binding.clone(),
444                            p.no_delegate,
445                        )
446                        .id
447                },
448            )
449            .await?;
450            if let Some(ws_id) = target {
451                registry.bind_workstream(&session_id, ws_id)?;
452            }
453            session_id
454        }
455    };
456
457    let mode = crate::mode::resolve_mode(p.mode.as_deref(), binding.root());
458    registry.set_mode(&session_id, mode)?;
459
460    let llm = build_llm_client()?;
461    let task_params = TaskRunParams {
462        session_id: session_id.clone(),
463        task: p.task_description,
464        agent_name,
465        binding: binding.clone(),
466        agents_dir,
467        model_override: p.model_override,
468        // #8030/#8128: both carried straight through — the CLI already
469        // applied its flag-then-env tiers before the request was built.
470        pm_model: p.pm_model,
471        max_turns: p.max_turns,
472        mode,
473        deadline_secs: p.deadline_secs,
474        // #3902: no test-only override for this production call site.
475        telemetry_data_dir: None,
476        // #7948: an `ask` suspends against the daemon's broker when one is
477        // registered. The mode comes from the daemon's environment, never the
478        // request, so a caller cannot widen its own permissions.
479        permission_broker: permissions,
480        permission_mode: crate::permissions::PermissionMode::resolve(None),
481        // #8031: a single-agent run. #8184: on the reuse path this is the
482        // SESSION's persisted shape (the guard above rejects a call that
483        // would differ), on the mint path this call's own param, which the
484        // mint persisted — so the run and the record always agree.
485        no_delegate: effective_no_delegate,
486    };
487    spawn_task_run(registry, llm, task_params)?;
488
489    // #4351: `result` rides alongside the pre-existing keys, never in place of
490    // them. `task.run` returns the moment the run is spawned, so the only
491    // truthful result at this instant is `pending` with no refs — the caller
492    // polls `session.status` for the terminal one, which the executor fills in.
493    Ok(json!({
494        "session_id": session_id,
495        "status": "running",
496        "mode": mode.as_str(),
497        "binding": binding.to_json(),
498        "result": crate::session::TaskResult::pending(),
499    }))
500}
501
502#[cfg(test)]
503#[path = "protocol_tests.rs"]
504mod tests;