Skip to main content

session_core/
core.rs

1//! The session actor: one session (format-4 journal), its lane (the `rlm` kernel over the composition root's host
2//! stack) and the run in progress, owned by one thread. Every client operation is an [`Op`] answered through its
3//! reply; the run's progress is reported as TypeScript lane-watch events (`run_start`, `message_*`, `tool_*`,
4//! `entry_added`, `queue_update`, `compaction_*`, `config_update`, `run_end`) through the event sink, which the
5//! session worker folds into its `ultron.transcript` state.
6//!
7//! The run executes the agent loop on a thread of its own; its events come back to the actor as [`Input::Agent`],
8//! so operations keep being answered while a run streams. Runs and compactions are journaled as the harness journals
9//! them ([`crate::journal`], [`crate::compaction_op`]); reads see the session as Pi entries ([`crate::pi_view`]).
10
11use crate::compaction_op::CompactionOp;
12use jsrt::sync;
13
14pub const AUTO_NAME_ENV: &str = "ULTRON_AUTO_NAME";
15pub const AUTO_REFINE_ENV: &str = "ULTRON_AUTO_REFINE";
16pub const RECOVERY_RESUME_ENV: &str = "ULTRON_RECOVERY_RESUME";
17
18#[path = "navigate.rs"]
19mod navigate;
20use crate::compose::{Runtime, Services};
21use crate::durable_store::{SharedSession, lock as lock_session};
22use crate::journal::RunJournal;
23use crate::lane::{self, Lane, Provider, api_supported};
24use crate::view;
25use crate::{ModelFlags, RunEnv, naming, pi_view};
26use agent::{AgentEvent, StreamFn};
27use ai::{AbortSignal, AssistantMessage, Message, Model, SimpleStreamOptions, StreamOptions};
28use jsrt::date::now_ms;
29use protocol::pi_message::text as message_text;
30use serde_json::{Map, Value, json};
31use session_file::SessionManager;
32use session_journal::ns::PENDING_ENTRY;
33use session_journal::ns::{BRANCH_TIP, LANE_CONFIG, LANE_STATE};
34use session_journal::repo::Metadata;
35use session_journal::run::{self, MAIN_LANE};
36use session_journal::{Session, SessionRepo, SystemClock, Write, names};
37use std::path::{Path, PathBuf};
38use std::sync::mpsc::Sender;
39use std::sync::{Arc, Mutex};
40use std::thread::JoinHandle;
41
42/// `InvalidMessage` (`reason: "empty"`) of a queued message without text or image (lane.ts `enqueue`).
43pub const EMPTY_QUEUED: &str = "Queued input must contain text or an image";
44/// The error of a call to a [`Core`] whose thread has stopped.
45pub const SESSION_CLOSED: &str = "Session is closed";
46
47use protocol::watch::{Ended, Failure, QueueItem, QueueKind, WatchEvent};
48
49/// What an operation answers: data for the response (`None`: no data), or the error text.
50pub type OpResult = Result<Option<Value>, String>;
51/// Where an operation's answer goes (called once, possibly later, from the actor's thread).
52pub type Reply = Box<dyn FnOnce(OpResult) + Send>;
53
54/// The operations a client sends (the commands of `rpc-native.ts` the session worker serves, and the agent
55/// controller's members). Session selection (new, switch, fork, clone) is the server's: clients re-attach.
56#[derive(Clone, Debug, PartialEq)]
57pub enum Op {
58    /// Start a run; with a run in progress the message joins `queue` (none: refused).
59    Prompt {
60        message: String,
61        images: Vec<Value>,
62        queue: Option<QueueKind>,
63    },
64    /// Start a run and answer when it ends (`{accepted, operationId, error}`), as the agent controller does.
65    PromptAndWait {
66        message: String,
67        images: Vec<Value>,
68    },
69    /// Queue a message (as `entry_id` when the client chose it); answers its entry id.
70    Enqueue {
71        kind: QueueKind,
72        message: String,
73        images: Vec<Value>,
74        entry_id: Option<String>,
75    },
76    /// Drop one queued message; answers whether it was queued.
77    CancelQueued {
78        entry_id: String,
79    },
80    /// Empty the queues: `{steering, followUp}` texts.
81    ClearQueue,
82    Abort,
83    State,
84    AvailableModels,
85    SetModel {
86        provider: String,
87        model_id: String,
88    },
89    CycleModel,
90    ThinkingLevels,
91    SetThinking {
92        level: String,
93    },
94    CycleThinking,
95    SetQueueMode {
96        kind: QueueKind,
97        mode: String,
98    },
99    Compact {
100        instructions: Option<String>,
101    },
102    SetAutoCompaction(bool),
103    SetAutoRetry(bool),
104    /// The terminal appearance the attached TUI detected (`"light"` / `"dark"`: OSC 11, a scheme report, else its
105    /// `COLORFGBG`): what `diagram.mermaid`'s `auto` theme follows ([`crate::compose::Config::terminal_theme`]).
106    SetTerminalTheme {
107        theme: String,
108    },
109    AbortRetry,
110    /// A user's own command (RPC `bash`, the TUI's `!`/`!!`), run by the shell.
111    /// `id` tags its streamed output (`bash_execution_update`), as AgentSession's `executeBash` `options.id`.
112    Bash {
113        command: String,
114        exclude: bool,
115        id: Option<String>,
116    },
117    AbortBash,
118    /// `/bug`'s summary written by the session's model (AgentSession `summarizeForBugReport`): the report text.
119    BugSummary {
120        hint: Option<String>,
121    },
122    /// Cancel the bug report summary in progress (its loader's Esc).
123    AbortBugSummary,
124    /// What a shared or reported session carries besides its entries (session-share.ts
125    /// `createShareTrailingEntries`): `{ systemPrompt, tools: [{ name, description, parameters }] }`.
126    ShareContext,
127    /// `sessionManager.appendCustomEntry(customType, data)` (`/bug` records its report): after the run in progress.
128    AppendCustom {
129        custom_type: String,
130        data: Value,
131    },
132    Stats,
133    ForkMessages,
134    Entries {
135        since: Option<String>,
136    },
137    Tree,
138    LastAssistantText,
139    SetName {
140        name: String,
141    },
142    Messages,
143    /// The text of the user message `entry_id`, which a fork starts before (an error for any other entry).
144    ForkSource {
145        entry_id: String,
146    },
147    /// The current Pi leaf (an error without one), which a clone copies to.
148    CloneSource,
149    /// Record the session-start marker in the forked session file `target` (`control.forked`), as TypeScript
150    /// records it: its first worker removes it (TypeScript's tells its extensions the session started as a fork).
151    Forked {
152        target: String,
153    },
154    /// The whole session as the TUI shows it: `{sessionId, sessionFile, name, messages, model, thinkingLevel}`.
155    Describe,
156    /// The main lane's snapshot as transcript state starts from ([`Core::snapshot`]): what a watcher rebases on after
157    /// a navigation, which its events cannot fold.
158    LaneSnapshot,
159    /// Sessions of this working directory, newest first (`{path, id, name, modified, messageCount, firstMessage,
160    /// allMessagesText, cwd}`).
161    ListSessions,
162    /// Continue what a dead worker left (crate::recovery): the first queued message runs, else an interrupted run
163    /// continues. Answers `{resumed, runId, reason, recovered}`; nothing starts while a run is in progress.
164    Recover,
165    /// The subagents of the root lane (`rlm.list_subagents` as the root sees them: `{subagents: [...]}`), for the
166    /// TUI's agent hub.
167    Agents,
168    /// Move `main`'s tip to `target_id` (`None`: the root), optionally summarizing the branch left (`/tree`), and
169    /// label the target (or the branch summary).
170    Navigate {
171        target_id: Option<String>,
172        summarize: bool,
173        instructions: Option<String>,
174        label: Option<String>,
175    },
176    /// Label a tree entry (`None` removes the label).
177    SetLabel {
178        entry_id: String,
179        label: Option<String>,
180    },
181    /// Cancel a subagent and its unfinished descendants (the agent hub's kill).
182    KillAgent {
183        id: String,
184    },
185    /// Steer a subagent with `message` (the agent hub's steer: `agent_message.send` from the root lane with
186    /// `receiver_role: "child"` and `steer: true`); answers the family module's `{id, duplicate, state, steered}`.
187    SteerAgent {
188        id: String,
189        message: String,
190    },
191    /// Start an interrupted subagent again from its brief (the agent hub's revive); answers `{id, revived}`.
192    ReviveAgent {
193        id: String,
194    },
195    /// A subagent's transcript (`agents.transcript`): `{id, busy, messages}`, its child conversation's messages.
196    AgentTranscript {
197        id: String,
198    },
199    /// `/goal <args>`: the session goal's command (set, pause, resume, clear, check); answers its text.
200    Goal {
201        args: String,
202    },
203    Observer {
204        args: String,
205    },
206    /// Start another root conversation in the session's durable runtime with `message` (Pi Durable's ownerless
207    /// conversations: each runs, survives restarts and resumes on its own); answers `{conversationId}`.
208    StartConversation {
209        message: String,
210    },
211    /// Give conversation `id` another input (queued while it runs).
212    ConversationInput {
213        id: u64,
214        message: String,
215    },
216    /// Conversation `id`: `{id, busy, messages: [{role, text}]}`; without an id, every root conversation's.
217    Conversations {
218        id: Option<u64>,
219    },
220    /// Root-owned work whose completion may still re-invoke the root (`async.pending`): running jobs and subagents
221    /// of the root lane, events waiting for delivery, a run in progress.
222    AsyncPending,
223    /// A read-only inspection request (crate::inspect: `agents.status`, `memory.list`, `rlm.frames`, ...) answered
224    /// by the session's host stack as the root lane's; anything else is refused.
225    Inspect {
226        request: String,
227        payload: Value,
228    },
229    /// The session's slash commands (RPC `get_commands`: crate::commands).
230    Commands,
231    /// The session's working-tree checkpoints (core::checkpoints): `{checkpoints: [...], enabled}`.
232    Checkpoints,
233    /// Restore the working tree's files from checkpoint `checkpoint`, else from the checkpoint of entry `entry_id`
234    /// (the start of its turn), saving the current files as another checkpoint first.
235    RestoreFiles {
236        entry_id: Option<String>,
237        checkpoint: Option<String>,
238    },
239    /// Run scheduled prompt `id` for its slot `due` (the server's timer, crates/daemon `prompt_schedules`): the
240    /// prompt starts a run, or waits for the run in progress to end (core::schedule_ops). Answers
241    /// `{fired, run, schedules}`.
242    ScheduleFire {
243        id: String,
244        due: i64,
245    },
246    /// Cancel the active schedule `id` (or name); answers it.
247    ScheduleCancel {
248        id: String,
249    },
250    /// `/persona on|off|auto` (empty: report): the session's own persona toggle over the settings'
251    /// (resources::keep_going). Answers `{text, persona, effective, keepGoing}`.
252    Persona {
253        args: String,
254    },
255    /// `/keepgoing on|off` (empty: report): the session's keep-going mode. Answers as [`Op::Persona`].
256    KeepGoing {
257        args: String,
258    },
259    /// `/continue`: this new session continues session `session` by searching its log (crate::continuation).
260    /// Answers `{session, name}`.
261    ContinueFrom {
262        session: String,
263    },
264}
265
266/// The JSON request a client sends for an operation ([`Op::to_json`]).
267impl From<&Op> for Value {
268    fn from(op: &Op) -> Value {
269        op.to_json()
270    }
271}
272
273impl Op {
274    /// The operation a JSON request names (`{op, ...}`), as clients send it over the worker's control service.
275    pub fn from_json(value: &Value) -> Result<Op, String> {
276        let text = |key: &str| value.get(key).and_then(Value::as_str).map(str::to_string);
277        let need = |key: &str| text(key).ok_or_else(|| format!("{key} must be a string"));
278        let images = || value["images"].as_array().cloned().unwrap_or_default();
279        let kind = |key: &str| text(key).as_deref().and_then(QueueKind::parse);
280        let op = value["op"].as_str().ok_or("op must be a string")?;
281        Ok(match op {
282            "prompt" => Op::Prompt {
283                message: need("message")?,
284                images: images(),
285                queue: kind("queue"),
286            },
287            "promptAndWait" => Op::PromptAndWait {
288                message: need("message")?,
289                images: images(),
290            },
291            "enqueue" => Op::Enqueue {
292                kind: kind("kind").ok_or("kind must be steer, followUp or nextRun")?,
293                message: need("message")?,
294                images: images(),
295                entry_id: text("entryId"),
296            },
297            "cancelQueued" => Op::CancelQueued {
298                entry_id: need("entryId")?,
299            },
300            "clearQueue" => Op::ClearQueue,
301            "abort" => Op::Abort,
302            "state" => Op::State,
303            "availableModels" => Op::AvailableModels,
304            "setModel" => Op::SetModel {
305                provider: need("provider")?,
306                model_id: need("modelId")?,
307            },
308            "cycleModel" => Op::CycleModel,
309            "thinkingLevels" => Op::ThinkingLevels,
310            "setThinking" => Op::SetThinking { level: need("level")? },
311            "cycleThinking" => Op::CycleThinking,
312            "setQueueMode" => Op::SetQueueMode {
313                kind: kind("kind")
314                    .filter(|kind| *kind != QueueKind::NextRun)
315                    .ok_or("kind must be steer or followUp")?,
316                mode: need("mode")?,
317            },
318            "compact" => Op::Compact {
319                instructions: text("instructions"),
320            },
321            "setAutoCompaction" => Op::SetAutoCompaction(value["enabled"] == true),
322            "setAutoRetry" => Op::SetAutoRetry(value["enabled"] == true),
323            "setTerminalTheme" => Op::SetTerminalTheme { theme: need("theme")? },
324            "abortRetry" => Op::AbortRetry,
325            "bash" => Op::Bash {
326                command: need("command")?,
327                exclude: value["exclude"] == true,
328                id: value["id"].as_str().map(str::to_string),
329            },
330            "abortBash" => Op::AbortBash,
331            "checkpoints" => Op::Checkpoints,
332            "restoreFiles" => Op::RestoreFiles {
333                entry_id: text("entryId"),
334                checkpoint: text("checkpoint"),
335            },
336            "bugSummary" => Op::BugSummary {
337                hint: value["hint"].as_str().map(str::to_string),
338            },
339            "abortBugSummary" => Op::AbortBugSummary,
340            "shareContext" => Op::ShareContext,
341            "appendCustom" => Op::AppendCustom {
342                custom_type: need("customType")?,
343                data: value["data"].clone(),
344            },
345            "stats" => Op::Stats,
346            "forkMessages" => Op::ForkMessages,
347            "entries" => Op::Entries { since: text("since") },
348            "tree" => Op::Tree,
349            "lastAssistantText" => Op::LastAssistantText,
350            "setName" => Op::SetName { name: need("name")? },
351            "messages" => Op::Messages,
352            "forkSource" => Op::ForkSource {
353                entry_id: need("entryId")?,
354            },
355            "cloneSource" => Op::CloneSource,
356            "forked" => Op::Forked {
357                target: need("target")?,
358            },
359            "describe" => Op::Describe,
360            "laneSnapshot" => Op::LaneSnapshot,
361            "listSessions" => Op::ListSessions,
362            "recover" => Op::Recover,
363            "agents" => Op::Agents,
364            "setLabel" => Op::SetLabel {
365                entry_id: need("entryId")?,
366                label: text("label"),
367            },
368            "navigate" => Op::Navigate {
369                target_id: text("targetId"),
370                summarize: value["summarize"] == true,
371                instructions: text("customInstructions"),
372                label: text("label"),
373            },
374            "killAgent" => Op::KillAgent { id: need("id")? },
375            "steerAgent" => Op::SteerAgent {
376                id: need("id")?,
377                message: need("message")?,
378            },
379            "reviveAgent" => Op::ReviveAgent { id: need("id")? },
380            "agentTranscript" => Op::AgentTranscript { id: need("id")? },
381            "observer" => Op::Observer {
382                args: text("args").unwrap_or_default(),
383            },
384            "goal" => Op::Goal {
385                args: text("args").unwrap_or_default(),
386            },
387            "startConversation" => Op::StartConversation {
388                message: need("message")?,
389            },
390            "conversationInput" => Op::ConversationInput {
391                id: value["id"].as_u64().ok_or("id must be a conversation id")?,
392                message: need("message")?,
393            },
394            "conversations" => Op::Conversations {
395                id: value["id"].as_u64(),
396            },
397            "asyncPending" => Op::AsyncPending,
398            "commands" => Op::Commands,
399            "inspect" => Op::Inspect {
400                request: need("request")?,
401                payload: value.get("payload").cloned().unwrap_or(Value::Null),
402            },
403            "scheduleFire" => Op::ScheduleFire {
404                id: need("id")?,
405                due: value["due"].as_i64().ok_or("due must be a time in ms")?,
406            },
407            "scheduleCancel" => Op::ScheduleCancel { id: need("id")? },
408            "persona" => Op::Persona {
409                args: text("args").unwrap_or_default(),
410            },
411            "keepGoing" => Op::KeepGoing {
412                args: text("args").unwrap_or_default(),
413            },
414            "continueFrom" => Op::ContinueFrom {
415                session: need("session")?,
416            },
417            other => return Err(format!("Unknown session operation: {other}")),
418        })
419    }
420
421    /// The JSON request for this operation ([`Op::from_json`] reads it back).
422    pub fn to_json(&self) -> Value {
423        match self {
424            Op::Prompt { message, images, queue } => {
425                json!({"op": "prompt", "message": message, "images": images, "queue": queue.map(QueueKind::name)})
426            }
427            Op::PromptAndWait { message, images } => {
428                json!({"op": "promptAndWait", "message": message, "images": images})
429            }
430            Op::Enqueue {
431                kind,
432                message,
433                images,
434                entry_id,
435            } => {
436                json!({"op": "enqueue", "kind": kind.name(), "message": message, "images": images, "entryId": entry_id})
437            }
438            Op::CancelQueued { entry_id } => json!({"op": "cancelQueued", "entryId": entry_id}),
439            Op::ClearQueue => json!({"op": "clearQueue"}),
440            Op::Abort => json!({"op": "abort"}),
441            Op::State => json!({"op": "state"}),
442            Op::AvailableModels => json!({"op": "availableModels"}),
443            Op::SetModel { provider, model_id } => json!({"op": "setModel", "provider": provider, "modelId": model_id}),
444            Op::CycleModel => json!({"op": "cycleModel"}),
445            Op::ThinkingLevels => json!({"op": "thinkingLevels"}),
446            Op::SetThinking { level } => json!({"op": "setThinking", "level": level}),
447            Op::CycleThinking => json!({"op": "cycleThinking"}),
448            Op::SetQueueMode { kind, mode } => json!({"op": "setQueueMode", "kind": kind.name(), "mode": mode}),
449            Op::Compact { instructions } => json!({"op": "compact", "instructions": instructions}),
450            Op::SetAutoCompaction(enabled) => json!({"op": "setAutoCompaction", "enabled": enabled}),
451            Op::SetAutoRetry(enabled) => json!({"op": "setAutoRetry", "enabled": enabled}),
452            Op::SetTerminalTheme { theme } => json!({"op": "setTerminalTheme", "theme": theme}),
453            Op::AbortRetry => json!({"op": "abortRetry"}),
454            Op::Bash { command, exclude, id } => {
455                let mut op = json!({"op": "bash", "command": command, "exclude": exclude});
456                if let Some(id) = id {
457                    op["id"] = json!(id);
458                }
459                op
460            }
461            Op::AbortBash => json!({"op": "abortBash"}),
462            Op::BugSummary { hint } => json!({"op": "bugSummary", "hint": hint}),
463            Op::AbortBugSummary => json!({"op": "abortBugSummary"}),
464            Op::ShareContext => json!({"op": "shareContext"}),
465            Op::AppendCustom { custom_type, data } => {
466                json!({"op": "appendCustom", "customType": custom_type, "data": data})
467            }
468            Op::Stats => json!({"op": "stats"}),
469            Op::ForkMessages => json!({"op": "forkMessages"}),
470            Op::Entries { since } => json!({"op": "entries", "since": since}),
471            Op::Tree => json!({"op": "tree"}),
472            Op::LastAssistantText => json!({"op": "lastAssistantText"}),
473            Op::SetName { name } => json!({"op": "setName", "name": name}),
474            Op::Messages => json!({"op": "messages"}),
475            Op::ForkSource { entry_id } => json!({"op": "forkSource", "entryId": entry_id}),
476            Op::CloneSource => json!({"op": "cloneSource"}),
477            Op::Forked { target } => json!({"op": "forked", "target": target}),
478            Op::Describe => json!({"op": "describe"}),
479            Op::LaneSnapshot => json!({"op": "laneSnapshot"}),
480            Op::ListSessions => json!({"op": "listSessions"}),
481            Op::Recover => json!({"op": "recover"}),
482            Op::Agents => json!({"op": "agents"}),
483            Op::SetLabel { entry_id, label } => json!({"op": "setLabel", "entryId": entry_id, "label": label}),
484            Op::Navigate {
485                target_id,
486                summarize,
487                instructions,
488                label,
489            } => {
490                json!({"op": "navigate", "targetId": target_id, "summarize": summarize, "customInstructions": instructions, "label": label})
491            }
492            Op::KillAgent { id } => json!({"op": "killAgent", "id": id}),
493            Op::SteerAgent { id, message } => json!({"op": "steerAgent", "id": id, "message": message}),
494            Op::ReviveAgent { id } => json!({"op": "reviveAgent", "id": id}),
495            Op::AgentTranscript { id } => json!({"op": "agentTranscript", "id": id}),
496            Op::Goal { args } => json!({"op": "goal", "args": args}),
497            Op::Observer { args } => json!({"op": "observer", "args": args}),
498            Op::StartConversation { message } => json!({"op": "startConversation", "message": message}),
499            Op::ConversationInput { id, message } => json!({"op": "conversationInput", "id": id, "message": message}),
500            Op::Conversations { id } => json!({"op": "conversations", "id": id}),
501            Op::AsyncPending => json!({"op": "asyncPending"}),
502            Op::Inspect { request, payload } => json!({"op": "inspect", "request": request, "payload": payload}),
503            Op::Commands => json!({"op": "commands"}),
504            Op::Checkpoints => json!({"op": "checkpoints"}),
505            Op::RestoreFiles { entry_id, checkpoint } => {
506                json!({"op": "restoreFiles", "entryId": entry_id, "checkpoint": checkpoint})
507            }
508            Op::ScheduleFire { id, due } => json!({"op": "scheduleFire", "id": id, "due": due}),
509            Op::ScheduleCancel { id } => json!({"op": "scheduleCancel", "id": id}),
510            Op::Persona { args } => json!({"op": "persona", "args": args}),
511            Op::KeepGoing { args } => json!({"op": "keepGoing", "args": args}),
512            Op::ContinueFrom { session } => json!({"op": "continueFrom", "session": session}),
513        }
514    }
515}
516
517/// What reaches the actor.
518pub enum Input {
519    Op(Op, Reply),
520    ObserverCompleted(observer::Completion),
521    Agent(Box<AgentEvent>),
522    /// The model's title for the session arrived.
523    Title(Box<AssistantMessage>),
524    /// The bug report summary with this number ended.
525    BugSummaryEnded(u64),
526    /// A background memory keep ended (crate::auto_memory::keep): shown to the user when it is worth a line.
527    MemoryKept(crate::auto_memory::Outcome),
528    /// A user's command ended: its `BashResult` (camelCase, as recorded), or the error that failed it.
529    BashDone {
530        command: String,
531        exclude: bool,
532        result: Result<Value, String>,
533        reply: Reply,
534    },
535    /// A chunk of a running user command's output (`bash_execution_update`).
536    BashOutput {
537        id: Option<String>,
538        delta: String,
539    },
540    /// Stop the lane; the sender is told when done.
541    Close(std::sync::mpsc::Sender<()>),
542    /// Stop the lane for a successor worker (its shell jobs keep running for it); the sender is told when done.
543    HandOver(std::sync::mpsc::Sender<()>),
544    /// The completion-event dispatcher's question about the root lane (crate::async_events).
545    EventLane(event_lanes::LaneCall, std::sync::mpsc::Sender<event_lanes::LaneAnswer>),
546    /// Report whether detached work is active (the worker keeps itself alive while it is).
547    ActivityTick,
548    /// The durable runtime running the turn (crate::turns).
549    Turn(crate::turns::Request),
550    /// The durable runtime has no work for the root conversation.
551    HarnessIdle,
552    /// A compaction's work off the actor ended (core::compacting).
553    Woken,
554    /// A fired schedule's prompt that waited for the run in progress (core::schedule_ops).
555    Scheduled(Value),
556    /// The turn-end checks numbered `id` ended (core::turn_guard): the labels and evidence of the ones that failed.
557    TurnChecked {
558        id: u64,
559        failed: Vec<String>,
560    },
561}
562
563/// Where lane-watch events go.
564pub type EventSink = Box<dyn FnMut(Value) + Send>;
565
566#[derive(Clone)]
567struct Queued {
568    kind: QueueKind,
569    message: Value,
570    /// The pending entry (`ultron.pending.entry`) the message waits as; it becomes the message's entry id.
571    entry_id: String,
572    /// The run's turn the loop took it for (`turn_start`s it had emitted, plus one); 0 while queued.
573    turn: u64,
574    /// The durable runtime's submission it waits as (none while no run is in progress).
575    submission: Option<durable::SubmissionId>,
576}
577
578/// The steering and follow-up queues, drained by the running loop. `delivered` holds drained messages until their
579/// `message_end` reaches the actor, so clients see them queued until then.
580struct Queues {
581    items: Vec<Queued>,
582    delivered: Vec<Queued>,
583    steering_all: bool,
584    follow_up_all: bool,
585}
586
587impl Queues {
588    fn visible(&self) -> Vec<&Queued> {
589        self.delivered.iter().chain(&self.items).collect()
590    }
591}
592
593/// `selectAcceptedInbox` (lane.ts): the queued messages a run's admission takes, in queue order: every next-run
594/// message and, when `take_queued`, every steering and follow-up message (only the first of a kind whose mode is
595/// one-at-a-time). Messages already waiting in the durable runtime's inbox belong to a run and are never taken.
596fn select_accepted(queues: &Queues, take_queued: bool) -> Vec<(String, Value)> {
597    let (mut steer_taken, mut follow_up_taken) = (false, false);
598    let mut selected = Vec::new();
599    for item in queues.items.iter().filter(|q| q.submission.is_none()) {
600        let eligible = match item.kind {
601            QueueKind::NextRun => true,
602            QueueKind::Steer => take_queued && (queues.steering_all || !steer_taken),
603            QueueKind::FollowUp => take_queued && (queues.follow_up_all || !follow_up_taken),
604        };
605        if eligible {
606            steer_taken |= item.kind == QueueKind::Steer;
607            follow_up_taken |= item.kind == QueueKind::FollowUp;
608            selected.push((item.entry_id.clone(), item.message.clone()));
609        }
610    }
611    selected
612}
613
614struct Running {
615    id: String,
616    signal: AbortSignal,
617    journal: RunJournal,
618    /// The run's prompt (its transcript message), announced when the first generation starts.
619    prompt: Value,
620    /// The queued messages its admission placed before the prompt, announced with it.
621    captured: Vec<Value>,
622    /// The durable runtime's submission of the prompt.
623    submission: Option<durable::SubmissionId>,
624    /// The run's own prompt has not reached `message_end` yet (later user messages are steering or follow-ups).
625    prompt_pending: bool,
626    /// The `turn_start`s the actor has processed; the loop counts its own in `Queues::turns`.
627    turns: u64,
628    started_tip: Value,
629    /// The last assistant message's error, if the run ended on one.
630    error: Option<String>,
631    /// Answered when the run ends (`PromptAndWait`).
632    waiter: Option<Reply>,
633    /// A client aborted the run (it ends `aborted`, whatever its last response says).
634    cancelled: bool,
635    /// An automatic compaction failed: the run ends with its error and compacts no more.
636    compaction_failed: bool,
637    /// The worker died during an overflow compaction of this run: the next checkpoint compacts first, resuming
638    /// this `resumeAfter` (crate::core::auto_compact).
639    resume_overflow: Option<Value>,
640    /// The provider message being hidden: the empty response an aborted run ends with (its `message_start` came,
641    /// its `message_end` is swallowed). Per run: a start whose end never comes cannot hide the next run's message.
642    hiding: bool,
643    /// The run's last boundary is done; only its terminal transaction is outstanding (it failed once).
644    ending: bool,
645}
646
647pub struct OpenOptions {
648    pub env: RunEnv,
649    pub flags: ModelFlags,
650    /// The session root (`<root>/--<cwd>--/<file>.jsonl`).
651    pub session_root: PathBuf,
652    pub metadata: Metadata,
653    /// `print`, `json`, `rpc`, `interactive`.
654    pub mode: String,
655    pub services: Services,
656    /// Name the session from its first prompt (and by the model's title); off for sessions removed at the end.
657    pub auto_name: bool,
658}
659
660/// How long a quiet session's tail may take to reach Hindsight.
661const IDLE_WAIT: std::time::Duration = std::time::Duration::from_secs(60);
662
663pub struct Core {
664    /// The lane's stored model no longer resolves: each run fails with `model_unavailable` until a model is
665    /// selected (see [`unavailable_model`]).
666    model_unavailable: bool,
667    env: RunEnv,
668    /// The key of each request's provider: `--api-key` for the starting model's, the profile's credentials for
669    /// every provider, resolved per request.
670    keys: crate::request_keys::Keys,
671    repo: SessionRepo,
672    runtime: Runtime,
673    provider: Arc<Provider>,
674    model: Model,
675    models: Vec<Model>,
676    thinking: String,
677    session: SharedSession,
678    lane: Lane,
679    tx: Sender<Input>,
680    sink: EventSink,
681    run: Option<Running>,
682    /// Loki's one-time setup note, for the first root turn that follows it (crate::loki_notice).
683    loki_notice: crate::loki_notice::LokiNotice,
684    /// Automatic recall before user messages and retain of compaction summaries (crate::auto_memory).
685    auto_memory: crate::auto_memory::AutoMemory,
686    /// Memory paused at start (memorantado did not answer), for the first root turn (crate::auto_memory).
687    memory_notice: Option<String>,
688    /// Instruction refinements proposed after compactions and delivered before user messages (crate::auto_refine).
689    auto_refine: crate::auto_refine::AutoRefine,
690    queues: Arc<Mutex<Queues>>,
691    auto_compaction: bool,
692    auto_retry: bool,
693    bash: Option<kernel::Signal>,
694    /// The bug report summary in progress (its number, and its signal); cleared when it ends.
695    bug_summary: Option<(u64, AbortSignal)>,
696    /// How many of the session's entries were announced (`entry_added`).
697    announced: usize,
698    /// How many of the session's usage rows were announced (`usage`).
699    announced_usage: usize,
700    /// Queued messages committed with the generation that takes them, until their `message_end` arrives.
701    taken: Vec<String>,
702    auto_name: bool,
703    /// What opening the session settled (crate::recovery), until [`Op::Recover`] acts on it.
704    recovered: Option<crate::recovery::Recovered>,
705    /// The durable runtime that runs every turn (crate::turns).
706    durable: durable_turns::Durable,
707    /// The run reopened from a dead worker's journal and resumed in the durable runtime.
708    resumed: Option<String>,
709    /// Completions of detached work, delivered to the lanes that own it (crate::async_events).
710    events: Arc<crate::async_events::Dispatcher>,
711    /// Model-owned context (`ctx.*`) and collapse on return on `main` (core::context_lane).
712    context: Arc<kernel_apis::ContextControl>,
713    branches: Arc<context_lane::RootBranches>,
714    /// The actor's input, while `run_loop` serves it (a compaction's work reads it too, core::compacting).
715    inputs: Option<std::sync::mpsc::Receiver<Input>>,
716    /// Inputs that arrived during a compaction and wait for its end, in order.
717    deferred: std::collections::VecDeque<Input>,
718    /// The compaction or branch summary in progress (manual or automatic): `abort` cancels it, `state` reports it
719    /// (`isCompacting`).
720    compacting: Option<AbortSignal>,
721    /// A tree navigation's branch summary is in progress (core::navigate).
722    navigating: bool,
723    /// What waits for the run in progress to end: a manual `compact` aborts the run first (AgentSession `compact`
724    /// awaits `abort()`), then runs.
725    after_run: Vec<Input>,
726    /// The research-loop brake and the skill hint on `main`'s turns (crate::nudge).
727    nudger: crate::nudge::ToolRoundNudger,
728    skill_nudger: crate::nudge::SkillExtractionNudger,
729    /// The persona's auto-nudge chain (core::persona_nudge).
730    persona: resources::persona::Chain,
731    /// The session's persona toggle and keep-going mode (the session value `ultron.module/persona`).
732    persona_session: resources::keep_going::SessionPersona,
733    observer: observer::Observer,
734    /// What the host checks when a run ends (core::turn_guard).
735    turn_guard: turn_guard::TurnGuard,
736}
737
738mod auto_compact;
739mod checkpoints;
740pub use checkpoints::{RESTORE_IN_SANDBOX, RESTORE_WHILE_STREAMING};
741mod agent_ops;
742pub(crate) mod budget_gate;
743mod compacting;
744mod context_children;
745mod context_lane;
746mod continue_from;
747pub mod durable_turns;
748pub mod event_lanes;
749mod observer;
750mod persona_nudge;
751mod schedule_ops;
752pub mod turn_guard;
753mod user_bash;
754
755/// The fork marker the session a client forked to carries until its first worker reads it
756/// (`forkedSessionStart` of session-start.ts).
757const SESSION_START: (&str, &str) = ("ultron.session.start", "fork");
758
759/// A user message with text and images, as the transcript stores it.
760pub fn user_message(text: String, images: Vec<Value>) -> Value {
761    let mut content = vec![json!({"type": "text", "text": text})];
762    content.extend(images);
763    json!({"role": "user", "content": content, "timestamp": now_ms()})
764}
765
766/// A transcript message as stored: a failed tool's result carries no `details`.
767fn stored(message: &Message) -> Value {
768    let mut value = serde_json::to_value(message).unwrap_or(Value::Null);
769    if value["role"] == "toolResult" && value["isError"] == true && value["details"] == json!({}) {
770        value.as_object_mut().map(|m| m.remove("details"));
771    }
772    value
773}
774
775/// generation.ts `configurationError`'s message for `model_unavailable`.
776const MODEL_UNAVAILABLE: &str = "The configured model is unavailable in this process";
777
778/// `ULTRON_ROOT=claude` (what `ultron --claude` sets for the session workers it starts): the root lane runs on
779/// Claude Code.
780pub const ROOT_ENV: &str = "ULTRON_ROOT";
781
782/// worker-root.ts `claudeRootRequested`: [`ROOT_ENV`] is `claude`.
783pub fn claude_root_requested(var: &dyn Fn(&str) -> Option<String>) -> bool {
784    var(ROOT_ENV).is_some_and(|v| jsrt::string::trim(&v).to_lowercase() == "claude")
785}
786
787/// A model the stored lane names that no longer resolves (removed from the catalog or models.json): the session
788/// still opens on it, and its next generation fails with `model_unavailable` (generation.ts `prepareGeneration`), so
789/// `/model` can pick another.
790fn unavailable_model(provider: &str, id: &str) -> Model {
791    Model {
792        id: id.to_string(),
793        name: id.to_string(),
794        api: String::new(),
795        provider: provider.to_string(),
796        base_url: String::new(),
797        reasoning: false,
798        thinking_level_map: None,
799        input: vec!["text".to_string()],
800        input_limits: None,
801        cost: Default::default(),
802        prompt_cache: None,
803        context_window: 0,
804        max_tokens: 0,
805        sampling_params: None,
806        headers: None,
807        compat: None,
808        request: None,
809        extra: Default::default(),
810    }
811}
812
813/// The lane configuration a session runs with: the session's own for a resumed session without model flags, else
814/// the flags' (written for a new session). Returns the stored configuration and the model it names.
815pub fn lane_config(flags: &ModelFlags, env: &RunEnv, session: Option<&mut Session>) -> Result<(Value, Model), String> {
816    lane_config_resolving(flags, env, session).map(|(config, model, _)| (config, model))
817}
818
819/// [`lane_config`], and whether the model the stored lane names is unavailable (then the model is a stand-in of
820/// that identity, see [`unavailable_model`]).
821fn lane_config_resolving(
822    flags: &ModelFlags,
823    env: &RunEnv,
824    session: Option<&mut Session>,
825) -> Result<(Value, Model, bool), String> {
826    let stored = session
827        .as_ref()
828        .and_then(|s| s.value(session_journal::ns::LANE_CONFIG, "main").cloned());
829    // Without --model a resumed session restores its own model; a new one starts on the settings' default
830    // (sdk.ts: restore from the session first, then `findInitialModel`).
831    // A `--model <pattern>:<thinking>` suffix or a scoped pattern's level names the thinking level unless
832    // `--thinking` does; otherwise the settings' level for the model.
833    let choice = match (&flags.model, &stored) {
834        (None, Some(_)) => Err("No model selected: pass --model <provider>/<id>".to_string()),
835        _ => lane::resolve_choice(flags, env, stored.is_some()),
836    };
837    let thinking = match (&flags.thinking, &choice) {
838        (Some(level), _) => level.clone(),
839        (None, Ok(choice)) => choice
840            .thinking
841            .clone()
842            .unwrap_or_else(|| lane::initial_thinking(&choice.model, env)),
843        (None, Err(_)) => "medium".into(),
844    };
845    let flag_model = choice.map(|choice| choice.model);
846    let wanted = match (&flag_model, stored) {
847        (Ok(m), _) => run::lane_config(&m.provider, &m.id, &thinking, &["rlm"]),
848        (Err(_), Some(mut stored)) => {
849            stored["activeToolNames"] = json!(["rlm"]);
850            stored
851        }
852        (Err(e), None) => return Err(e.clone()),
853    };
854    let config = match session {
855        Some(session) => {
856            let mut config = run::ensure_lane(session, &wanted)?;
857            // `--thinking` holds for a resumed session that keeps its own model (no `--model`). With `--model`, the
858            // stored lane (model and level) is kept, as the TypeScript native server keeps it (recorded:
859            // print-continue-keeps-lane-model).
860            if let Some(level) = flags.thinking.as_ref().filter(|_| flags.model.is_none())
861                && config["thinkingLevel"] != json!(level)
862            {
863                config["thinkingLevel"] = json!(level);
864                session.commit(&[Write::set(LANE_CONFIG, session_journal::run::MAIN_LANE, config.clone())])?;
865            }
866            // `ultron --claude` (session-worker.ts): a resumed lane that is not on the Claude root's provider moves
867            // to the root model, as `lane.setModel` does (its thinking level stays). A plain `--model` keeps the
868            // stored lane (above).
869            if claude_root_requested(&*env.var)
870                && let Ok(m) = &flag_model
871                && config["model"]["provider"] != json!(m.provider)
872            {
873                config["model"] = json!({"provider": m.provider, "modelId": m.id});
874                session.commit(&[Write::set(LANE_CONFIG, session_journal::run::MAIN_LANE, config.clone())])?;
875            }
876            config
877        }
878        None => wanted,
879    };
880    let model = match (
881        config["model"]["provider"].as_str(),
882        config["model"]["modelId"].as_str(),
883        flag_model,
884    ) {
885        (Some(provider), Some(id), Ok(m)) if (provider, id) == (m.provider.as_str(), m.id.as_str()) => m,
886        (Some(provider), Some(id), _) => match lane::catalog_model(provider, id, env) {
887            Ok(model) => model,
888            Err(_) => return Ok((config.clone(), unavailable_model(provider, id), true)),
889        },
890        (_, _, m) => m?,
891    };
892    Ok((config, model, false))
893}
894
895/// Commit `usage` (an `ai::Usage` as JSON) as a usage row of its own, outside any turn, with `details` saying what
896/// spent it (`details.source`: `session-naming`, `judge`).
897pub fn record_usage_row(session: &mut Session, usage: Value, details: Value) -> Result<(), String> {
898    let id = session_journal::lock_clock(&session.clock()).next_id();
899    let mut row = Write::usage(&id, usage, None);
900    if let Write::Usage(fields) = &mut row {
901        fields.insert("details".into(), details);
902    }
903    session.commit(&[row]).map(|_| ())
904}
905
906/// Apply a naming response: its usage as a row of its own, and its title while the name is still automatic.
907pub fn record_naming(session: &mut Session, response: &AssistantMessage) -> Result<(), String> {
908    let usage = serde_json::to_value(&response.usage).map_err(|e| e.to_string())?;
909    record_usage_row(
910        session,
911        usage,
912        json!({"source": "session-naming", "model": format!("{}/{}", response.provider, response.model)}),
913    )?;
914    if let Some(title) = naming::title_of(response) {
915        names::replace_auto_name(session, &title)?;
916    }
917    Ok(())
918}
919
920impl Core {
921    /// Open `options.metadata`'s session with its lane. `tx` is the actor's own input (runs report through it).
922    pub fn open(options: OpenOptions, tx: Sender<Input>, sink: EventSink) -> Result<Core, String> {
923        let OpenOptions {
924            env,
925            flags,
926            session_root,
927            metadata,
928            mode,
929            services,
930            auto_name,
931        } = options;
932        let repo = SessionRepo::new(&session_root, SystemClock::shared());
933        let mut session = repo.open(&metadata)?;
934        // A session written by a newer Ultron fails here, naming the value and its format version, before any of it
935        // is loaded, settled or rewritten (session-worker.ts `assertSessionFormatsReadable`).
936        crate::format_version::assert_session_formats_readable(&session)?;
937        // A worker that died left its run open. A run of the durable runtime resumes there; one journaled without
938        // it (an older build, the TypeScript product) is settled before anything reads the lane.
939        let open_operation = session
940            .value(LANE_STATE, MAIN_LANE)
941            .and_then(|state| state["currentOperationId"].as_str().map(str::to_string));
942        // Only a run resumes in the durable runtime; another operation a dead worker left (a manual compaction, a
943        // navigation) is settled as interrupted.
944        let durable_records = crate::durable_store::has_records(&session)
945            && open_operation.as_ref().is_none_or(|operation| {
946                session
947                    .value(session_journal::ns::OP_META, operation)
948                    .is_none_or(|meta| meta["intent"]["kind"].as_str().is_none_or(|kind| kind == "run"))
949            });
950        let recovered = match &open_operation {
951            Some(_) if !durable_records => crate::recovery::settle(&mut session)?,
952            _ => crate::recovery::Recovered {
953                queued: crate::recovery::inbox(&session),
954                ..Default::default()
955            },
956        };
957        let resume = open_operation.filter(|_| durable_records);
958        let sessions_dir = session_root.join(session_journal::catalog::session_directory_name(&metadata.cwd));
959        let trace = |label: &str| {
960            crate::startup_trace::trace_startup((env.var)(crate::startup_trace::TRACE_ENV).as_deref(), label)
961        };
962        trace("worker.harness");
963        let mut runtime = Runtime::new(&env, &mode, sessions_dir, services)?;
964        trace("worker.resources-loaded");
965        // Loki's setup (the minimal install where allowed, its commit in the background) before any cell runs.
966        let loki_notice = crate::loki_notice::LokiNotice::start(&runtime.config);
967        let (config, model, model_unavailable) = lane_config_resolving(&flags, &env, Some(&mut session))?;
968        // `setRuntimeApiKey(resolved.model.provider, apiKey)`: `--api-key` is the starting model's provider's key.
969        let keys = crate::request_keys::Keys::session(flags.api_key.clone(), &model.provider, &env);
970        let announced = session.state().entries().len();
971        let announced_usage = session.state().usage_rows().len();
972        let session_id = session.id().to_string();
973        let session: SharedSession = Arc::new(Mutex::new(session));
974        let values = crate::session_modules::session_values(&session);
975        runtime.services.values = Some(values.clone());
976        let children = crate::subagents::DurableChildren::new();
977        let unfinished = crate::subagents::unfinished(&session);
978        trace("worker.harness-create");
979        let lane = Lane::open_with(
980            &runtime,
981            &model,
982            flags.api_key.clone(),
983            &session_id,
984            Some(children.host(values)),
985        )?;
986        trace("worker.host");
987        lane.stack
988            .stats
989            .attach(Arc::new(crate::session_stats::SessionStore(session.clone())));
990        let branches = Arc::new(context_lane::RootBranches::new(session.clone()));
991        let child_context = Arc::new(context_children::ChildContext::new(children.clone(), session.clone()));
992        // `ULTRON_COMPACTION_TRIM` of the session's environment, as every other session switch.
993        let context = Arc::new(
994            kernel_apis::ContextControl::new(Arc::new(context_children::LaneBranches {
995                root: branches.clone(),
996                children: child_context.clone(),
997            }))
998            .with_trim(!env.flag_off(kernel_apis::context_control::COMPACTION_TRIM_ENV)),
999        );
1000        child_context.observe(&context);
1001        let _ = lane.stack.context.set(context.clone());
1002        // Requests read the settings as they are now (crate::request_settings): the stream options, transport and
1003        // idle timeout of `/settings` apply to the next request.
1004        let provider = Arc::new(Provider::new().with_live_settings(runtime.config.settings_reader()));
1005        let queues = Arc::new(Mutex::new(Queues {
1006            items: recovered
1007                .queued
1008                .iter()
1009                .filter_map(|q| {
1010                    Some(Queued {
1011                        kind: QueueKind::parse(&q.kind)?,
1012                        message: q.message.clone(),
1013                        entry_id: q.entry_id.clone(),
1014                        turn: 0,
1015                        submission: None,
1016                    })
1017                })
1018                .collect(),
1019            delivered: Vec::new(),
1020            steering_all: config::keys::QUEUE_DEFAULT == config::keys::QUEUE_ALL,
1021            follow_up_all: config::keys::QUEUE_DEFAULT == config::keys::QUEUE_ALL,
1022        }));
1023        let durable = durable_turns::open_durable(
1024            &session,
1025            &tx,
1026            &lane,
1027            provider.clone(),
1028            &env,
1029            &keys,
1030            queues.clone(),
1031            children.clone(),
1032            child_context,
1033            runtime.config.context_images,
1034        )?;
1035        children.attach(durable.chat.clone());
1036        let steer_children = children.clone();
1037        let _ = lane
1038            .stack
1039            .lane_steer
1040            .set(Arc::new(move |child_lane: &str, message: &str| {
1041                let (Some(chat), Some(conversation)) =
1042                    (steer_children.chat(), steer_children.conversation_of_lane(child_lane))
1043                else {
1044                    return false;
1045                };
1046                if chat.live(conversation).map_or(true, |live| live["run"].is_null()) {
1047                    return false;
1048                }
1049                chat.conversation(conversation).ok().flatten().is_some_and(|handle| {
1050                    handle
1051                        .submit(harness::chat::SubmissionDraft::Input {
1052                            content: json!(message),
1053                            when_busy: harness::chat::WhenBusy::Steer,
1054                            request_id: None,
1055                        })
1056                        .is_ok()
1057                })
1058            }));
1059        let _ = lane.stack.budget_note.set(crate::budget_note::budget_note(
1060            children.clone(),
1061            lane.stack.agents.clone(),
1062            lane.stack.usage.clone(),
1063        ));
1064        // Each lane's context use for its reminder: the estimate the harness compacts by, over the lane's durable
1065        // conversation (the root's, or the child's); its summary entry marks a compaction.
1066        let meter_children = children.clone();
1067        lane.stack.context_reminders.set_meter(Arc::new(move |lane_name: &str| {
1068            let chat = meter_children.chat()?;
1069            let conversation = if lane_name == session_journal::run::MAIN_LANE {
1070                durable::ROOT_CONVERSATION_ID
1071            } else {
1072                meter_children.conversation_of_lane(lane_name)?
1073            };
1074            let view = chat.conversation(conversation).ok().flatten()?.context(None).ok()?;
1075            Some(crate::context_reminder::Measure {
1076                tokens: harness::chat::compaction::estimate_context(&view, &[]),
1077                epoch: view.head.as_ref().map(|head| head.id.0),
1078            })
1079        }));
1080        let _ = lane.stack.swarm.set(Arc::new(
1081            crate::swarm_ops::SwarmOps::new(children.clone()).with_contracts(Arc::downgrade(&lane.stack)),
1082        ));
1083        // rlm.spawn(fork=True): the child's conversation starts as its caller's.
1084        lane.stack.delegation.set_fork_point(children.fork_point_hook());
1085        // rlm.progress reads a running child's transcript from the runtime.
1086        let transcripts = durable.chat.clone();
1087        lane.stack.delegation.set_transcripts(Arc::new(move |lane: &str| {
1088            crate::agent_hub::child_transcript(&transcripts, lane).map(|(messages, _)| messages)
1089        }));
1090        children.restore(&lane.stack, &unfinished)?;
1091        let events = event_lanes::install(
1092            &lane,
1093            &env,
1094            tx.clone(),
1095            durable.chat.clone(),
1096            children.clone(),
1097            durable.stop.clone(),
1098            session.clone(),
1099        );
1100        event_lanes::tick_activity(tx.clone(), durable.stop.clone());
1101        // Idle kernels are swept every minute (evicted after their idle TTL), not only when a lane is leased.
1102        let sweep_stop = durable.stop.clone();
1103        lane.stack
1104            .lanes
1105            .sweep_every(lanes::IDLE_SWEEP_INTERVAL, move |interval| {
1106                sweep_stop.wait_timeout(interval).is_some()
1107            });
1108        // `compaction.enabled` (default on); `set_auto_compaction` changes it for the session.
1109        let auto_compaction = runtime.config.settings["compaction"]["enabled"] != false;
1110        let nudger = crate::nudge::ToolRoundNudger::new(runtime.config.tool_rounds_nudge, runtime.config.async_events);
1111        let skill_nudger = crate::nudge::SkillExtractionNudger::new(runtime.config.skill_nudge);
1112        let auto_memory = crate::auto_memory::AutoMemory::new(&runtime.config.settings, runtime.memory_explicit);
1113        let auto_refine =
1114            crate::auto_refine::AutoRefine::new(&runtime.config.settings, (env.var)(AUTO_REFINE_ENV).as_deref());
1115        let observer =
1116            observer::Observer::new(runtime.config.settings["observer"]["enabled"].as_bool().unwrap_or(true));
1117        let mut core = Core {
1118            model_unavailable,
1119            loki_notice,
1120            memory_notice: runtime.memory_notice.clone(),
1121            auto_memory,
1122            auto_refine,
1123            thinking: config["thinkingLevel"].as_str().unwrap_or("medium").to_string(),
1124            models: lane::available_models(&env),
1125            provider,
1126            env,
1127            keys,
1128            repo,
1129            runtime,
1130            model,
1131            session,
1132            lane,
1133            tx,
1134            sink,
1135            run: None,
1136            queues,
1137            auto_compaction,
1138            auto_retry: true,
1139            bash: None,
1140            bug_summary: None,
1141            announced_usage,
1142            announced,
1143            taken: Vec::new(),
1144            auto_name,
1145            recovered: Some(recovered),
1146            durable,
1147            resumed: None,
1148            events,
1149            context,
1150            branches,
1151            inputs: None,
1152            deferred: std::collections::VecDeque::new(),
1153            compacting: None,
1154            navigating: false,
1155            after_run: Vec::new(),
1156            nudger,
1157            skill_nudger,
1158            persona: Default::default(),
1159            persona_session: Default::default(),
1160            observer,
1161            turn_guard: Default::default(),
1162        };
1163        // The session's persona toggle and keep-going mode, before a resumed run can end.
1164        core.persona_load();
1165        if let Some(operation) = resume {
1166            core.resumed = Some(core.reopen_run(&operation)?);
1167        } else {
1168            // Context entries a dead worker's run left waiting join the branch now; a resumed run places them at
1169            // its next boundary.
1170            core.branches.place(true)?;
1171        }
1172        core.durable.chat.resume().map_err(|e| e.to_string())?;
1173        // A fork's first worker consumes the marker its source recorded (`forkedSessionStart` of session-start.ts).
1174        let forked = lock_session(&core.session)
1175            .value(SESSION_START.0, SESSION_START.1)
1176            .is_some();
1177        if forked {
1178            lock_session(&core.session).commit(&[Write::delete(SESSION_START.0, SESSION_START.1)])?;
1179        }
1180        Ok(core)
1181    }
1182
1183    pub fn model(&self) -> &Model {
1184        &self.model
1185    }
1186
1187    pub fn thinking_level(&self) -> &str {
1188        &self.thinking
1189    }
1190
1191    pub fn session(&self) -> SharedSession {
1192        self.session.clone()
1193    }
1194
1195    pub fn runtime(&self) -> &Runtime {
1196        &self.runtime
1197    }
1198
1199    /// The lane snapshot transcript state starts from (`LaneSnapshot`): the branch's entries, configuration, usage.
1200    pub fn snapshot(&self) -> Value {
1201        let entries = lock_session(&self.session)
1202            .branch_entries(MAIN_LANE)
1203            .unwrap_or_default();
1204        let mut usage = session_journal::usage::empty_usage();
1205        for row in lock_session(&self.session).state().usage_rows() {
1206            usage = session_journal::usage::add_usage(&usage, &row["usage"]);
1207        }
1208        json!({
1209            "lane": MAIN_LANE,
1210            "transcript": entries,
1211            "tipId": lock_session(&self.session).branch_tip(MAIN_LANE).flatten(),
1212            "configuration": {"model": {"provider": self.model.provider, "modelId": self.model.id}, "thinkingLevel": self.thinking, "activeToolNames": ["rlm"]},
1213            "stats": {"messageCount": entries.iter().filter(|e| e["type"] == "message").count(), "usage": usage},
1214            "operation": null,
1215            "queues": [],
1216            "faulted": false,
1217        })
1218    }
1219
1220    /// Serve inputs until a close (or the input ends).
1221    pub fn run_loop(mut self, inputs: std::sync::mpsc::Receiver<Input>) {
1222        self.inputs = Some(inputs);
1223        while let Some(input) = self.next_input() {
1224            match input {
1225                Input::Op(op, reply) => self.op(op, reply),
1226                Input::ObserverCompleted(completion) => self.observer_completed(completion),
1227                Input::Agent(event) => self.on_agent_event(*event),
1228                Input::Title(response) => {
1229                    if record_naming(&mut lock_session(&self.session), &response).is_ok() {
1230                        self.name_changed();
1231                    }
1232                }
1233                Input::Turn(request) => self.on_turn(request),
1234                Input::HarnessIdle => self.harness_idle(),
1235                Input::BugSummaryEnded(number) => {
1236                    if self.bug_summary.as_ref().is_some_and(|(current, _)| *current == number) {
1237                        self.bug_summary = None;
1238                    }
1239                }
1240                Input::MemoryKept(outcome) => self.memory_kept(outcome),
1241                Input::BashDone {
1242                    command,
1243                    exclude,
1244                    result,
1245                    reply,
1246                } => self.bash_done(command, exclude, result, reply),
1247                Input::BashOutput { id, delta } => self.emit_bash_output(id, delta),
1248                Input::Close(done) => {
1249                    self.close();
1250                    let _ = done.send(());
1251                    return;
1252                }
1253                Input::HandOver(done) => {
1254                    self.close_for_successor();
1255                    let _ = done.send(());
1256                    return;
1257                }
1258                Input::EventLane(call, reply) => self.event_lane(call, reply),
1259                Input::ActivityTick => {
1260                    // A run whose terminal transaction failed tries it again.
1261                    if self.run.as_ref().is_some_and(|run| run.ending) {
1262                        self.run_end();
1263                    }
1264                    self.report_activity();
1265                }
1266                // A compaction's wake-up is read by the compaction itself.
1267                Input::Woken => {}
1268                // A queued fire was counted when it was taken; one that cannot start now is dropped (the next slot
1269                // fires as usual).
1270                Input::Scheduled(message) => {
1271                    let _ = self.schedule_start(message);
1272                }
1273                Input::TurnChecked { id, failed } => self.turn_checked(id, failed),
1274            }
1275        }
1276        self.close();
1277    }
1278
1279    /// What waited for a compaction first, then the actor's input.
1280    fn next_input(&mut self) -> Option<Input> {
1281        if let Some(input) = self.deferred.pop_front() {
1282            return Some(input);
1283        }
1284        loop {
1285            // A held stream frame is journaled when its window ends, even if the stream stalls before the next one.
1286            let due = self.run.as_ref().and_then(|run| run.journal.held_until());
1287            let inputs = self.inputs.as_ref()?;
1288            let Some(due) = due else {
1289                return inputs.recv().ok();
1290            };
1291            match inputs.recv_timeout(due.saturating_duration_since(std::time::Instant::now())) {
1292                Ok(input) => return Some(input),
1293                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return None,
1294                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
1295                    if let Some(run) = self.run.as_mut() {
1296                        run.journal.flush_held(&mut lock_session(&self.session));
1297                    }
1298                }
1299            }
1300        }
1301    }
1302
1303    fn emit(&mut self, event: WatchEvent) {
1304        (self.sink)(event.to_value());
1305    }
1306
1307    /// The session's name now (`session_name`, a Rust-only event the worker serves as `ultron.session-ops` state,
1308    /// not on the transcript).
1309    fn name_changed(&mut self) {
1310        let name = lock_session(&self.session).name();
1311        self.emit(WatchEvent::SessionName {
1312            lane: MAIN_LANE.into(),
1313            name,
1314        });
1315    }
1316
1317    /// AgentSession `setSessionName`: `session_info_changed` to clients (Pi's RPC event).
1318    fn session_info_changed(&mut self) {
1319        let name = lock_session(&self.session).name();
1320        self.emit(WatchEvent::SessionInfoChanged {
1321            lane: MAIN_LANE.into(),
1322            name,
1323        });
1324    }
1325
1326    fn api_key(&self) -> Option<String> {
1327        self.keys.key(&self.model.provider)
1328    }
1329
1330    fn run_id(&self) -> Option<String> {
1331        self.run.as_ref().map(|r| r.id.clone())
1332    }
1333
1334    /// Announce the entries and usage rows committed since the last announcement, as `entry_added` and `usage`
1335    /// events (a usage event carries the lane's totals after it).
1336    fn announce(&mut self) {
1337        let entries: Vec<Value> = lock_session(&self.session).state().entries()[self.announced..].to_vec();
1338        self.announced += entries.len();
1339        for entry in entries {
1340            let _ = self.context.entry_added(MAIN_LANE, &entry);
1341            self.emit(WatchEvent::EntryAdded {
1342                lane: MAIN_LANE.into(),
1343                entry,
1344            });
1345        }
1346        let rows: Vec<Value> = lock_session(&self.session)
1347            .state()
1348            .usage_rows()
1349            .into_iter()
1350            .cloned()
1351            .collect();
1352        for index in self.announced_usage..rows.len() {
1353            let totals = rows[..=index]
1354                .iter()
1355                .fold(session_journal::usage::empty_usage(), |total, row| {
1356                    session_journal::usage::add_usage(&total, &row["usage"])
1357                });
1358            self.emit(WatchEvent::Usage {
1359                lane: MAIN_LANE.into(),
1360                row: rows[index].clone(),
1361                totals,
1362            });
1363        }
1364        self.announced_usage = rows.len();
1365    }
1366
1367    fn tip(&self) -> Option<String> {
1368        lock_session(&self.session).branch_tip(MAIN_LANE).flatten()
1369    }
1370
1371    /// The lane's stored state (`ultron.lane.state`), idle when none is stored.
1372    fn lane_state(&self) -> Value {
1373        lock_session(&self.session)
1374            .value(LANE_STATE, MAIN_LANE)
1375            .cloned()
1376            .unwrap_or_else(|| json!({"currentOperationId": null, "lastOperationId": null, "inbox": []}))
1377    }
1378
1379    /// Append a message to `main` outside a run (the lane's `appendMessage`: the entry, the new tip and the lane's
1380    /// state in one transaction) and announce the entry.
1381    fn append(&mut self, message: Value) -> Result<(), String> {
1382        let id = session_journal::lock_clock(&lock_session(&self.session).clock()).next_id();
1383        let entry = Write::message_entry(&id, self.tip().as_deref(), message);
1384        let lane_state = self.lane_state();
1385        lock_session(&self.session).commit(&[
1386            entry,
1387            Write::set(BRANCH_TIP, MAIN_LANE, id.into()),
1388            Write::set(LANE_STATE, MAIN_LANE, lane_state),
1389        ])?;
1390        self.announce();
1391        Ok(())
1392    }
1393
1394    /// A user message's `message_end`: the run's prompt (committed when the run was admitted), a queued message
1395    /// the runtime placed (`queued`: its pending entry; it joins the branch when the loop takes it, see
1396    /// [`Core::begin_generation`]), or another user message (appended now).
1397    pub(super) fn user_message_end(&mut self, value: Value, queued: Option<String>) {
1398        let shown = self.persona_shown(value.clone());
1399        self.emit(WatchEvent::MessageEnd {
1400            run_id: self.run_id(),
1401            lane: MAIN_LANE.into(),
1402            message: shown,
1403        });
1404        let delivered = queued.and_then(|entry_id| {
1405            let mut queues = sync::lock(&self.queues);
1406            let found = queues.delivered.iter().position(|q| q.entry_id == entry_id);
1407            found.map(|i| queues.delivered.remove(i))
1408        });
1409        let first = self
1410            .run
1411            .as_mut()
1412            .is_some_and(|run| std::mem::take(&mut run.prompt_pending));
1413        let committed = match &delivered {
1414            Some(queued) if self.taken.contains(&queued.entry_id) => {
1415                self.taken.retain(|id| *id != queued.entry_id);
1416                Ok(())
1417            }
1418            Some(queued) => self.commit_queued(queued, value),
1419            None if !first => lock_session(&self.session).append_message(MAIN_LANE, value).map(drop),
1420            None => Ok(()),
1421        };
1422        if let Err(error) = committed {
1423            self.fail_run(error);
1424        }
1425        self.announce();
1426        if delivered.is_some() {
1427            self.queue_update();
1428        }
1429    }
1430
1431    /// A queued message taken by the loop joins the branch under its pending entry's id.
1432    fn commit_queued(&mut self, queued: &Queued, message: Value) -> Result<(), String> {
1433        let entry = Write::message_entry(&queued.entry_id, self.tip().as_deref(), message);
1434        lock_session(&self.session).commit(&[
1435            entry,
1436            Write::delete(PENDING_ENTRY, &queued.entry_id),
1437            Write::set(BRANCH_TIP, MAIN_LANE, queued.entry_id.clone().into()),
1438        ])?;
1439        Ok(())
1440    }
1441
1442    fn queue_update(&mut self) {
1443        let queues = sync::lock(&self.queues)
1444            .visible()
1445            .into_iter()
1446            .map(|q| QueueItem {
1447                item: "message".into(),
1448                kind: q.kind,
1449                entry_id: q.entry_id.clone(),
1450                message: Some(q.message.clone()),
1451                custom_type: None,
1452            })
1453            .collect();
1454        self.emit(WatchEvent::QueueUpdate {
1455            lane: MAIN_LANE.into(),
1456            queues,
1457        });
1458    }
1459
1460    /// Store the model and thinking level as the lane's configuration (`ultron.lane.config`).
1461    fn store_lane_config(&mut self) -> Result<(), String> {
1462        let mut config = lock_session(&self.session)
1463            .value(LANE_CONFIG, MAIN_LANE)
1464            .cloned()
1465            .unwrap_or_else(|| run::lane_config("", "", "", &["rlm"]));
1466        config["model"] = json!({"provider": self.model.provider, "modelId": self.model.id});
1467        config["thinkingLevel"] = json!(self.thinking);
1468        if lock_session(&self.session).value(LANE_CONFIG, MAIN_LANE) != Some(&config) {
1469            lock_session(&self.session).commit(&[Write::set(LANE_CONFIG, MAIN_LANE, config)])?;
1470        }
1471        Ok(())
1472    }
1473
1474    fn idle(&self) -> Result<(), String> {
1475        if self.run.is_some() {
1476            return Err("Agent is already processing".into());
1477        }
1478        Ok(())
1479    }
1480
1481    fn journal(&mut self, event: &AgentEvent) {
1482        if let Some(run) = self.run.as_mut() {
1483            run.journal.event(&mut lock_session(&self.session), event);
1484        }
1485    }
1486
1487    fn on_agent_event(&mut self, agent_event: AgentEvent) {
1488        let run = self.run_id();
1489        match &agent_event {
1490            AgentEvent::MessageStart { message } => {
1491                let value = stored(message);
1492                let aborted = self.run.as_ref().is_some_and(|r| r.signal.aborted());
1493                if aborted
1494                    && value["role"] == "assistant"
1495                    && value["stopReason"] == "aborted"
1496                    && value["content"].as_array().is_none_or(Vec::is_empty)
1497                {
1498                    if let Some(run) = self.run.as_mut() {
1499                        run.hiding = true;
1500                    }
1501                    return;
1502                }
1503                self.journal(&agent_event);
1504                let shown = self.persona_shown(value);
1505                self.emit(WatchEvent::MessageStart {
1506                    run_id: run,
1507                    lane: MAIN_LANE.into(),
1508                    message: shown,
1509                });
1510            }
1511            AgentEvent::MessageUpdate {
1512                message,
1513                assistant_message_event,
1514            } => {
1515                if self.run.as_ref().is_some_and(|run| run.hiding) {
1516                    return;
1517                }
1518                self.journal(&agent_event);
1519                // The frame (`AssistantMessageFrame`) and the usage, never the message (crate::journal::update_fields).
1520                let (frame, usage) = crate::journal::update_fields(message, assistant_message_event);
1521                self.emit(WatchEvent::MessageUpdate {
1522                    run_id: run,
1523                    lane: MAIN_LANE.into(),
1524                    frame,
1525                    usage,
1526                    message: None,
1527                });
1528            }
1529            AgentEvent::MessageEnd { message } => {
1530                if self.run.as_mut().is_some_and(|run| std::mem::take(&mut run.hiding)) {
1531                    return;
1532                }
1533                let value = stored(message);
1534                if value["role"] == "user" {
1535                    return self.user_message_end(value, None);
1536                }
1537                if value["role"] == "assistant"
1538                    && let Some(running) = self.run.as_mut()
1539                {
1540                    running.error = value["errorMessage"].as_str().map(str::to_string);
1541                }
1542                let shown = self.persona_shown(value.clone());
1543                self.emit(WatchEvent::MessageEnd {
1544                    run_id: run,
1545                    lane: MAIN_LANE.into(),
1546                    message: shown,
1547                });
1548                let answered = value["role"] == "assistant";
1549                let round_message = Some(value.clone());
1550                let mut retry = None;
1551                if let Message::Assistant(answer) = message {
1552                    retry = self.retry_decision(answer);
1553                }
1554                if value["role"] == "assistant" {
1555                    self.persona_assistant(&value);
1556                    self.turn_guard_assistant(&value);
1557                }
1558                self.journal(&agent_event);
1559                self.announce();
1560                let retried = matches!(retry, Some(WatchEvent::RetryScheduled { .. }));
1561                if let Some(note) = retry {
1562                    self.emit(note);
1563                }
1564                // A response that is retried ends no turn (no `turn_end` at `assistant.retry_wait`).
1565                if let Some(message) = round_message.filter(|_| !retried) {
1566                    self.count_round(&message);
1567                }
1568                // Once the model answered after a cell's output that returned finished tasks, it collapses.
1569                if answered {
1570                    let _ = self.context.message_end(MAIN_LANE, "assistant");
1571                }
1572            }
1573            AgentEvent::ToolExecutionStart {
1574                tool_call_id,
1575                tool_name,
1576                args,
1577            } => {
1578                self.journal(&agent_event);
1579                self.emit(WatchEvent::ToolStart {
1580                    run_id: run,
1581                    lane: MAIN_LANE.into(),
1582                    tool_call_id: tool_call_id.clone(),
1583                    tool_name: tool_name.clone(),
1584                    args: args.clone(),
1585                });
1586            }
1587            AgentEvent::ToolExecutionUpdate {
1588                tool_call_id,
1589                tool_name,
1590                args,
1591                partial_result,
1592            } => self.emit(WatchEvent::ToolUpdate {
1593                run_id: run,
1594                lane: MAIN_LANE.into(),
1595                tool_call_id: tool_call_id.clone(),
1596                tool_name: tool_name.clone(),
1597                args: args.clone(),
1598                partial_result: serde_json::to_value(partial_result).unwrap_or(Value::Null),
1599            }),
1600            AgentEvent::ToolExecutionEnd {
1601                tool_call_id,
1602                tool_name,
1603                result,
1604                is_error,
1605            } => {
1606                let mut result = serde_json::to_value(result).unwrap_or(Value::Null);
1607                if *is_error && result["details"] == json!({}) {
1608                    result.as_object_mut().map(|m| m.remove("details"));
1609                }
1610                self.emit(WatchEvent::ToolEnd {
1611                    run_id: run,
1612                    lane: MAIN_LANE.into(),
1613                    tool_call_id: tool_call_id.clone(),
1614                    tool_name: tool_name.clone(),
1615                    result,
1616                    is_error: *is_error,
1617                });
1618            }
1619            // The lane's own boundaries: turns and the run's end are reconstructed by clients.
1620            AgentEvent::TurnStart => self.begin_generation(),
1621            AgentEvent::AgentStart | AgentEvent::AgentEnd { .. } | AgentEvent::TurnEnd { .. } => {}
1622        }
1623    }
1624
1625    /// A generation begins. The queued messages the loop took for it (drained before its `turn_start`) join the
1626    /// branch in the same transaction as `assistant.ready`, and the lane's inbox keeps the rest. A cancelled run
1627    /// starts no generation.
1628    ///
1629    /// Only messages taken for this turn or an earlier one: the actor processes `turn_start` after the loop emitted
1630    /// it, and by then a fast loop may already have drained the next turn's follow-up. Taking every delivered message
1631    /// committed that follow-up before this turn's assistant message (seen under load as `steer`, `follow-up`,
1632    /// `assistant`, `assistant` instead of `steer`, `assistant`, `follow-up`, `assistant`).
1633    fn begin_generation(&mut self) {
1634        let Some(run) = self.run.as_mut() else { return };
1635        run.turns += 1;
1636        let turn = run.turns;
1637        if run.signal.aborted() {
1638            return;
1639        }
1640        let taken: Vec<Queued> = sync::lock(&self.queues)
1641            .delivered
1642            .iter()
1643            .filter(|q| q.turn <= turn && !self.taken.contains(&q.entry_id))
1644            .cloned()
1645            .collect();
1646        // Context entries appended since the last boundary join the branch first, in the same transaction.
1647        let tip = self.tip();
1648        let (mut writes, mut parent) = context_lane::placement(&lock_session(&self.session), tip.clone());
1649        for queued in &taken {
1650            writes.push(Write::message_entry(
1651                &queued.entry_id,
1652                parent.as_deref(),
1653                queued.message.clone(),
1654            ));
1655            writes.push(Write::delete(PENDING_ENTRY, &queued.entry_id));
1656            parent = Some(queued.entry_id.clone());
1657        }
1658        let trigger = taken.last().map(|q| q.entry_id.clone());
1659        // The retry wait ended (`runRetryWait`): the step's next attempt starts.
1660        let retry_start = self
1661            .run
1662            .as_ref()
1663            .and_then(|run| run.journal.run())
1664            .and_then(|journal| Some((journal.retry_waiting()?, journal.step_id().to_string())));
1665        if let Some((attempt, step)) = retry_start {
1666            let run_id = self.run_id();
1667            self.emit(WatchEvent::RetryStart {
1668                lane: MAIN_LANE.into(),
1669                run_id,
1670                step,
1671                attempt,
1672            });
1673        }
1674        if let Some(placed) = parent.filter(|placed| Some(placed) != tip.as_ref()) {
1675            writes.push(Write::set(BRANCH_TIP, MAIN_LANE, placed.into()));
1676        }
1677        let mut inbox = self.lane_state()["inbox"].clone();
1678        if let Some(items) = inbox.as_array_mut() {
1679            items.retain(|item| !taken.iter().any(|q| item["entryId"] == q.entry_id.as_str()));
1680        }
1681        self.taken.extend(taken.iter().map(|q| q.entry_id.clone()));
1682        if let Some(run) = self.run.as_mut() {
1683            run.journal.set_inbox(inbox);
1684            run.journal
1685                .begin_with(&mut lock_session(&self.session), writes, trigger);
1686        }
1687    }
1688
1689    /// A journal write failed: the run stops (its error is reported when it ends).
1690    fn fail_run(&mut self, error: String) {
1691        if let Some(run) = self.run.as_mut() {
1692            run.signal.abort();
1693            run.error.get_or_insert(error);
1694        }
1695    }
1696
1697    /// The run ends: its last boundary, then its terminal transaction, then its end is reported. The run is taken
1698    /// only once the terminal transaction committed: when it fails, the run stays (`ending`) and the transaction is
1699    /// tried again on the next activity tick, so a run is never reported ended while its operation stays open (a
1700    /// successor would end it a second time).
1701    fn run_end(&mut self) {
1702        self.observer.cancel();
1703        let operation = self.operation_id();
1704        let Some(ending) = self.run.as_ref().map(|run| run.ending) else {
1705            return;
1706        };
1707        if !ending {
1708            if let Some(operation) = &operation {
1709                self.lane.stack.agents.end_root_turn(operation);
1710            }
1711            let unanswered = self
1712                .run
1713                .as_ref()
1714                .filter(|run| !run.cancelled && run.error.is_none())
1715                .and_then(|run| self.unanswered(run.submission));
1716            // The run's last boundary: collapse what the model answered after, then place what is still waiting.
1717            let _ = self.context.run_end(MAIN_LANE);
1718            let waiting = context_lane::pending_count(&lock_session(&self.session));
1719            let placed = self.branches.place(true);
1720            if let Some(run) = self.run.as_mut() {
1721                run.ending = true;
1722                if let Some(unanswered) = unanswered {
1723                    run.error = Some(unanswered);
1724                }
1725                if let Err(error) = placed {
1726                    run.error.get_or_insert(error);
1727                }
1728                if let Some(write) = run.journal.error() {
1729                    run.error.get_or_insert(write.to_string());
1730                }
1731            }
1732            self.announce();
1733            if waiting > 0 {
1734                self.queue_update();
1735            }
1736            self.durable.bridge.set_user_abort(false);
1737        }
1738        let Some(run) = self.run.as_ref() else { return };
1739        let aborted = run.cancelled;
1740        let finished = if aborted {
1741            run.journal.finish_aborted(&mut lock_session(&self.session))
1742        } else {
1743            let code = if run.compaction_failed {
1744                "summarization_failed"
1745            } else {
1746                "assistant_error"
1747            };
1748            let failure = run.error.as_deref().map(|m| (code, m));
1749            run.journal.finish(Some(&mut lock_session(&self.session)), failure)
1750        };
1751        if finished.is_err() {
1752            return;
1753        }
1754        let Some(run) = self.run.take() else { return };
1755        let error = if aborted { None } else { run.error.clone() };
1756        self.announce();
1757        self.taken.clear();
1758        sync::lock(&self.queues).delivered.clear();
1759        let status = if aborted {
1760            Ended::Aborted
1761        } else if error.is_some() {
1762            Ended::Failed
1763        } else {
1764            Ended::Completed
1765        };
1766        // Detached work the run leaves running keeps the worker alive: reported before the run's end is.
1767        self.report_activity();
1768        self.emit(WatchEvent::RunEnd {
1769            lane: MAIN_LANE.into(),
1770            run_id: run.id.clone(),
1771            status,
1772            error: error.as_ref().map(|message| Failure {
1773                code: Some("run_failed".into()),
1774                message: message.clone(),
1775            }),
1776            from_tip_id: run.started_tip.as_str().map(str::to_string),
1777            tip_id: self.tip(),
1778            ended_at: now_ms(),
1779        });
1780        let failed = error.is_some();
1781        if let Some(operation) = &operation {
1782            self.events.run_ended(MAIN_LANE, operation, aborted);
1783        }
1784        self.nudger.run_ended(&run.id);
1785        self.skill_nudger.run_ended(&run.id);
1786        // What the run counted is in the session file when its end is reported.
1787        self.lane.stack.stats.flush();
1788        self.lane.stack.cell_hints().run_ended(MAIN_LANE);
1789        if let Some(waiter) = run.waiter {
1790            let error = error.map_or(Value::Null, |m| json!({"code": "run_failed", "message": m}));
1791            waiter(Ok(Some(
1792                json!({"accepted": true, "operationId": run.id, "error": error}),
1793            )));
1794        }
1795        for input in std::mem::take(&mut self.after_run).into_iter().rev() {
1796            self.deferred.push_front(input);
1797        }
1798        self.persona_run_ended(aborted, failed);
1799        self.turn_guard_run_ended(aborted, failed);
1800    }
1801
1802    /// `appendCustomEntry`: a `custom` entry at the tip of `main`, announced; after the run in progress (a custom
1803    /// entry joins the branch at a boundary).
1804    fn append_custom(&mut self, custom_type: String, data: Value, reply: Reply) {
1805        if self.run.is_some() {
1806            self.after_run
1807                .push(Input::Op(Op::AppendCustom { custom_type, data }, reply));
1808            return;
1809        }
1810        let id = session_journal::lock_clock(&lock_session(&self.session).clock()).next_id();
1811        let entry = Write::custom_entry(
1812            &id,
1813            self.tip().as_deref(),
1814            &custom_type,
1815            Some(data).filter(|d| !d.is_null()),
1816        );
1817        let lane_state = self.lane_state();
1818        let committed = lock_session(&self.session).commit(&[
1819            entry,
1820            Write::set(session_journal::ns::BRANCH_TIP, MAIN_LANE, id.into()),
1821            Write::set(session_journal::ns::LANE_STATE, MAIN_LANE, lane_state),
1822        ]);
1823        if committed.is_ok() {
1824            self.announce();
1825        }
1826        reply(committed.map(|_| None));
1827    }
1828
1829    fn bash_done(&mut self, command: String, exclude: bool, result: Result<Value, String>, reply: Reply) {
1830        self.bash = None;
1831        let result = match result {
1832            Ok(result) => result,
1833            Err(e) => return reply(Err(e)),
1834        };
1835        let message = user_bash::bash_message(&command, &result, exclude, now_ms());
1836        self.announce_message(&message);
1837        if let Err(error) = self.append(message) {
1838            return reply(Err(error));
1839        }
1840        reply(Ok(Some(result)));
1841    }
1842
1843    /// A message outside a run: its `message_start` and `message_end`.
1844    fn announce_message(&mut self, message: &Value) {
1845        self.emit(WatchEvent::MessageStart {
1846            run_id: None,
1847            lane: MAIN_LANE.into(),
1848            message: message.clone(),
1849        });
1850        self.emit(WatchEvent::MessageEnd {
1851            run_id: None,
1852            lane: MAIN_LANE.into(),
1853            message: message.clone(),
1854        });
1855    }
1856
1857    /// AgentSession's `bash_execution_update`: a chunk of the running command's output, under its id.
1858    fn emit_bash_output(&mut self, id: Option<String>, delta: String) {
1859        self.emit(WatchEvent::BashExecutionUpdate {
1860            lane: MAIN_LANE.into(),
1861            id,
1862            delta,
1863        });
1864    }
1865
1866    /// Stop the lane (kernels, subagents).
1867    pub fn close(&mut self) {
1868        self.stop(false);
1869    }
1870
1871    /// As [`Core::close`] when a successor worker takes the session over: shell jobs keep running for it.
1872    pub fn close_for_successor(&mut self) {
1873        self.stop(true);
1874    }
1875
1876    fn stop(&mut self, hand_over: bool) {
1877        self.observer.shutdown();
1878        // A successor keeps the session going; a run in progress resumes when the session opens again.
1879        if !hand_over && self.run.is_none() {
1880            self.retain_tail(false);
1881        }
1882        if let Some(run) = &self.run {
1883            run.signal.abort();
1884        }
1885        self.turn_guard_cancel();
1886        // A successor takes the session: what this worker's hosts would still journal (a subagent's wait failing
1887        // as the runtime closes) is dropped, so its tasks stay unfinished for the successor to reattach.
1888        if hand_over && let Some(values) = &self.runtime.services.values {
1889            values.hand_over();
1890        }
1891        // The durable runtime stops without settling anything: a run in progress resumes when the session opens.
1892        self.durable.stop.abort();
1893        // `cleanupSessionResources(sessionId)` of AgentSession.dispose: the provider connections cached under this
1894        // session's provider session IDs (the Codex WebSockets) are closed with it.
1895        for id in self.durable.chat.provider_session_ids().unwrap_or_default() {
1896            ai::openai_codex_responses::close_openai_codex_websocket_sessions(Some(&id));
1897        }
1898        let _ = self.durable.chat.close();
1899        if let Some(signal) = &self.bash {
1900            signal.abort("closing");
1901        }
1902        if hand_over {
1903            self.lane.hand_over();
1904        } else {
1905            self.lane.shutdown();
1906        }
1907        self.events.close();
1908    }
1909
1910    /// The Pi view of the session the read operations use.
1911    fn pi(&self) -> SessionManager {
1912        pi_view::pi_manager(&lock_session(&self.session))
1913    }
1914
1915    fn session_file(&self) -> String {
1916        lock_session(&self.session).metadata().path.display().to_string()
1917    }
1918
1919    fn op(&mut self, op: Op, reply: Reply) {
1920        match op {
1921            Op::Prompt { message, images, queue } => {
1922                let (message, notice) = self.user_text(&message);
1923                let result = if self.run.is_some() {
1924                    match queue {
1925                        Some(kind) => self.enqueue(kind, message, images, None).map(drop),
1926                        None => Err("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.".into()),
1927                    }
1928                } else {
1929                    self.prompt(message, images, None).map_err(|(error, _)| error)
1930                };
1931                reply(result.map(|()| notice.map(|notice| json!({"keepGoing": notice}))));
1932            }
1933            Op::PromptAndWait { message, images } => {
1934                let (message, _) = self.user_text(&message);
1935                if self.run.is_some() {
1936                    return reply(Err("Agent is already processing".into()));
1937                }
1938                if let Err((error, reply)) = self.prompt(message, images, Some(reply)) {
1939                    reply(Err(error));
1940                }
1941            }
1942            bash @ Op::Bash { .. } => self.bash(bash, reply),
1943            Op::AppendCustom { custom_type, data } => self.append_custom(custom_type, data, reply),
1944            Op::BugSummary { hint } => {
1945                let summarizer = self.summarizer();
1946                let messages = view::messages(&self.pi());
1947                let retry = self.summary_retry();
1948                let signal = AbortSignal::new();
1949                static SUMMARIES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1950                let number = SUMMARIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1951                self.bug_summary = Some((number, signal.clone()));
1952                let tx = self.tx.clone();
1953                std::thread::spawn(move || {
1954                    reply(
1955                        summarizer
1956                            .bug_report(&messages, hint.as_deref(), retry, &signal)
1957                            .map(|text| Some(json!(text))),
1958                    );
1959                    let _ = tx.send(Input::BugSummaryEnded(number));
1960                });
1961            }
1962            // AgentSession `compact`: `await this.abort()` first, then compact once the session is idle.
1963            compact @ Op::Compact { .. } if self.run.is_some() => {
1964                self.abort();
1965                self.after_run.push(Input::Op(compact, reply));
1966            }
1967            Op::Recover => {
1968                let result = self.recover();
1969                reply(result);
1970            }
1971            other => {
1972                let result = self.sync_op(other);
1973                reply(result);
1974            }
1975        }
1976    }
1977
1978    /// A prompt's or queued message's text as the session takes it: `/review` expanded (agent-controller-provider.ts
1979    /// `toTextPrompt`, crate::review_command), seen by the persona as that text (`persona_user_input`), then a prompt
1980    /// template's `/name args` expanded. The persona's keep-going notice, if any.
1981    fn user_text(&mut self, message: &str) -> (String, Option<String>) {
1982        let message = crate::review_command::expand_review_command(message);
1983        let notice = self.persona_user_input(&message);
1984        self.turn_guard_user_input();
1985        (self.expand_prompt_template(message), notice)
1986    }
1987
1988    /// AgentSession `expandPromptTemplate`: a prompt or queued message `/name args` naming one of the session's
1989    /// prompt templates (the `/name` commands it lists) becomes the template's text with the arguments substituted.
1990    fn expand_prompt_template(&self, message: String) -> String {
1991        if !message.starts_with('/') {
1992            return message;
1993        }
1994        resources::prompt_templates::expand_prompt_template(&message, &self.lane.stack.prompt_templates())
1995    }
1996
1997    fn sync_op(&mut self, op: Op) -> OpResult {
1998        // `/usage` reads the session file it describes: the counters still in memory are saved first.
1999        if matches!(op, Op::Describe) {
2000            self.lane.stack.stats.flush();
2001        }
2002        match op {
2003            Op::Prompt { .. }
2004            | Op::PromptAndWait { .. }
2005            | Op::Bash { .. }
2006            | Op::BugSummary { .. }
2007            | Op::AppendCustom { .. }
2008            | Op::Recover => {
2009                unreachable!("answered in op")
2010            }
2011            Op::Enqueue {
2012                kind,
2013                message,
2014                images,
2015                entry_id,
2016            } => {
2017                let (message, _) = self.user_text(&message);
2018                self.enqueue(kind, message, images, entry_id).map(|id| Some(json!(id)))
2019            }
2020            Op::CancelQueued { entry_id } => {
2021                let found = sync::lock(&self.queues).items.iter().any(|q| q.entry_id == entry_id);
2022                if found {
2023                    self.remove_queued(&[entry_id])?;
2024                }
2025                Ok(Some(json!(found)))
2026            }
2027            Op::ClearQueue => Ok(Some(self.clear_queue())),
2028            Op::Abort => {
2029                self.abort();
2030                Ok(None)
2031            }
2032            Op::State => Ok(Some(self.state())),
2033            Op::AvailableModels => {
2034                // The registry is read now (credentials change while the session runs).
2035                self.models = lane::available_models(&self.env);
2036                Ok(Some(Value::Array(
2037                    self.models
2038                        .iter()
2039                        .filter_map(|m| serde_json::to_value(m).ok())
2040                        .collect(),
2041                )))
2042            }
2043            Op::SetModel { provider, model_id } => {
2044                let find = |models: &[Model]| {
2045                    models
2046                        .iter()
2047                        .find(|m| m.provider == provider && m.id == model_id)
2048                        .cloned()
2049                };
2050                let model = match find(&self.models) {
2051                    Some(model) => model,
2052                    None => {
2053                        self.models = lane::available_models(&self.env);
2054                        find(&self.models).ok_or_else(|| format!("Model not found: {provider}/{model_id}"))?
2055                    }
2056                };
2057                self.model = model;
2058                self.model_unavailable = false;
2059                self.lane.stack.set_root_model(&self.model);
2060                self.store_lane_config()?;
2061                serde_json::to_value(&self.model).map(Some).map_err(|e| e.to_string())
2062            }
2063            Op::CycleModel => {
2064                if self.models.len() < 2 {
2065                    return Ok(Some(Value::Null));
2066                }
2067                let index = self
2068                    .models
2069                    .iter()
2070                    .position(|m| m.provider == self.model.provider && m.id == self.model.id);
2071                self.model = self.models[index.map_or(0, |i| (i + 1) % self.models.len())].clone();
2072                self.model_unavailable = false;
2073                self.lane.stack.set_root_model(&self.model);
2074                self.store_lane_config()?;
2075                Ok(Some(json!({
2076                    "model": serde_json::to_value(&self.model).map_err(|e| e.to_string())?,
2077                    "thinkingLevel": self.thinking,
2078                    "isScoped": false,
2079                })))
2080            }
2081            Op::ThinkingLevels => Ok(Some(json!(self.thinking_levels()))),
2082            Op::SetThinking { level } => self.set_thinking(&level).map(|()| None),
2083            Op::CycleThinking => {
2084                let levels = self.thinking_levels();
2085                if levels.len() < 2 {
2086                    return Ok(Some(Value::Null));
2087                }
2088                let index = levels.iter().position(|l| *l == self.thinking);
2089                let next = levels[index.map_or(0, |i| (i + 1) % levels.len())].clone();
2090                self.set_thinking(&next)?;
2091                Ok(Some(json!(next)))
2092            }
2093            Op::SetQueueMode { kind, mode } => {
2094                let mut queues = sync::lock(&self.queues);
2095                let all = mode == config::keys::QUEUE_ALL;
2096                match kind {
2097                    QueueKind::Steer => queues.steering_all = all,
2098                    QueueKind::FollowUp => queues.follow_up_all = all,
2099                    QueueKind::NextRun => return Err("kind must be steer or followUp".into()),
2100                }
2101                Ok(None)
2102            }
2103            Op::Compact { instructions } => self.compact(instructions.as_deref()).map(Some),
2104            Op::SetAutoCompaction(enabled) => {
2105                self.auto_compaction = enabled;
2106                Ok(None)
2107            }
2108            Op::SetAutoRetry(enabled) => {
2109                self.auto_retry = enabled;
2110                self.durable
2111                    .auto_retry
2112                    .store(enabled, std::sync::atomic::Ordering::SeqCst);
2113                Ok(None)
2114            }
2115            Op::SetTerminalTheme { theme } => {
2116                if theme != "light" && theme != "dark" {
2117                    return Err(format!("theme must be light or dark, not {theme:?}"));
2118                }
2119                *self
2120                    .runtime
2121                    .config
2122                    .terminal_theme
2123                    .lock()
2124                    .unwrap_or_else(|e| e.into_inner()) = Some(theme);
2125                Ok(None)
2126            }
2127            // `abort_retry`: a run waiting to retry its generation is aborted (`requestAbort` of the operation).
2128            Op::AbortRetry => {
2129                if self
2130                    .run
2131                    .as_ref()
2132                    .and_then(|run| run.journal.run())
2133                    .is_some_and(|journal| journal.retry_waiting().is_some())
2134                {
2135                    self.abort();
2136                }
2137                Ok(None)
2138            }
2139            Op::AbortBash => {
2140                if let Some(signal) = &self.bash {
2141                    signal.abort("abort_bash");
2142                }
2143                Ok(None)
2144            }
2145            Op::AbortBugSummary => {
2146                if let Some((_, signal)) = self.bug_summary.take() {
2147                    signal.abort();
2148                }
2149                Ok(None)
2150            }
2151            Op::ShareContext => {
2152                let tool = agent::AgentTool::tool(&*self.lane.tool);
2153                Ok(Some(json!({
2154                    "systemPrompt": self.runtime.system.current(),
2155                    "tools": [{"name": tool.name, "description": tool.description, "parameters": tool.parameters}],
2156                })))
2157            }
2158            Op::Stats => Ok(Some(view::stats(
2159                &self.pi(),
2160                Some(&self.session_file()),
2161                lock_session(&self.session).id(),
2162                self.model.context_window,
2163            ))),
2164            Op::ForkMessages => Ok(Some(Value::Array(view::fork_messages(&self.pi())))),
2165            Op::Entries { since } => {
2166                let pi = self.pi();
2167                let mut entries = view::entries(&pi);
2168                if let Some(since) = since {
2169                    let index = entries
2170                        .iter()
2171                        .position(|e| e["id"] == since.as_str())
2172                        .ok_or_else(|| format!("Entry not found: {since}"))?;
2173                    entries.drain(..=index);
2174                }
2175                Ok(Some(
2176                    json!({"entries": entries, "leafId": pi.leaf_id().cloned().unwrap_or(Value::Null)}),
2177                ))
2178            }
2179            Op::Tree => Ok(Some(self.labeled_tree())),
2180            Op::LastAssistantText => Ok(Some(json!(view::last_assistant_text(&self.pi())))),
2181            Op::SetName { name } => {
2182                names::set_user_name(&mut lock_session(&self.session), Some(&name))?;
2183                self.name_changed();
2184                self.session_info_changed();
2185                Ok(None)
2186            }
2187            Op::Messages => Ok(Some(Value::Array(view::messages(&self.pi())))),
2188            Op::LaneSnapshot => Ok(Some(self.snapshot())),
2189            Op::ForkSource { entry_id } => {
2190                self.idle()?;
2191                let pi = self.pi();
2192                let entry = pi
2193                    .entry(&entry_id)
2194                    .filter(|e| e["type"] == "message" && e["message"]["role"] == "user")
2195                    .ok_or_else(|| format!("Entry is not a user message: {entry_id}"))?;
2196                Ok(Some(json!(message_text(&entry["message"]))))
2197            }
2198            Op::CloneSource => {
2199                self.idle()?;
2200                let leaf = self.pi().leaf_id().cloned().filter(|l| !l.is_null());
2201                leaf.map(Some)
2202                    .ok_or_else(|| "Cannot clone session: no current entry selected".to_string())
2203            }
2204            Op::Forked { target } => {
2205                let metadata = session_journal::catalog::read_metadata(Path::new(&target))
2206                    .ok_or_else(|| format!("Not a session file: {target}"))?;
2207                let mut session = self.repo.open(&metadata)?;
2208                session.commit(&[Write::set(
2209                    SESSION_START.0,
2210                    SESSION_START.1,
2211                    json!({"previousSessionFile": self.session_file()}),
2212                )])?;
2213                Ok(None)
2214            }
2215            Op::Describe => Ok(Some(json!({
2216                "sessionId": lock_session(&self.session).id(),
2217                "sessionFile": self.session_file(),
2218                "name": lock_session(&self.session).name(),
2219                "messages": view::messages(&self.pi()),
2220                // The lane's own entries (compactions and branch summaries as entries), as the TUI draws them.
2221                "entries": lock_session(&self.session).branch_entries(MAIN_LANE).unwrap_or_default(),
2222                "model": serde_json::to_value(&self.model).unwrap_or(Value::Null),
2223                "thinkingLevel": self.thinking,
2224            }))),
2225            Op::Navigate {
2226                target_id,
2227                summarize,
2228                instructions,
2229                label,
2230            } => self
2231                .navigate(target_id, summarize, instructions.as_deref(), label)
2232                .map(Some),
2233            Op::SetLabel { entry_id, label } => self.set_label(&entry_id, label.as_deref()).map(|()| None),
2234            Op::Checkpoints => Ok(Some(self.list_checkpoints())),
2235            Op::ScheduleFire { id, due } => self.schedule_fire(&id, due),
2236            Op::ScheduleCancel { id } => self.schedule_cancel(&id),
2237            Op::Persona { args } => self.persona_command("persona", &args).map(Some),
2238            Op::KeepGoing { args } => self.persona_command("keepgoing", &args).map(Some),
2239            Op::ContinueFrom { session } => self.continue_from(&session).map(Some),
2240            Op::RestoreFiles { entry_id, checkpoint } => self.restore_files(entry_id, checkpoint).map(Some),
2241            // `rlm.list_subagents` with each subagent's name, model and times, for the agent hub and the RLM views.
2242            Op::Agents => self.lane.stack.delegation.subagent_views(MAIN_LANE).map(Some),
2243            Op::KillAgent { id } => self
2244                .lane
2245                .stack
2246                .delegation
2247                .cancel(&id, "Killed from the agent hub")
2248                .map(Some),
2249            Op::SteerAgent { id, message } => self.steer_agent(&id, &message).map(Some),
2250            Op::ReviveAgent { id } => self.revive_agent(&id).map(Some),
2251            Op::AgentTranscript { id } => self.agent_transcript(&id).map(Some),
2252            Op::StartConversation { message } => self.start_conversation(&message).map(Some),
2253            Op::ConversationInput { id, message } => self.conversation_input(id, &message).map(|()| None),
2254            Op::Conversations { id } => self.conversations(id).map(Some),
2255            Op::AsyncPending => Ok(Some(self.async_pending())),
2256            Op::Commands => Ok(Some(Value::Array(self.lane.stack.commands()))),
2257            Op::Inspect { request, .. } if request == "async.pending" => Ok(Some(self.async_pending())),
2258            // The root lane's detached cells (`rlm.cells` lists them to a cell, without their times).
2259            Op::Inspect { request, .. } if request == "rlm.detached" => Ok(Some(
2260                json!({ "cells": self.lane.stack.lanes.detached_cells(MAIN_LANE) }),
2261            )),
2262            // The worker answers the pool itself (session-worker.ts `inspect`): kernels and guard statistics.
2263            Op::Inspect { request, .. } if request == "rlm.pool" => Ok(Some(self.lane.stack.pool_stats())),
2264            Op::Inspect { request, payload } => {
2265                let runtime = self.lane.stack.cell_handler(MAIN_LANE, None);
2266                crate::inspect::inspect(Some(&*runtime), &request, payload, &kernel::Signal::new()).map(Some)
2267            }
2268            Op::Goal { args } => self.lane.stack.goal.command(&args).map(|text| Some(json!(text))),
2269            Op::Observer { args } => self.observer_command(&args).map(|text| Some(json!(text))),
2270            Op::ListSessions => {
2271                let listed =
2272                    names::list_sessions(Path::new(self.repo.root()), &lock_session(&self.session).metadata().cwd);
2273                Ok(Some(Value::Array(
2274                    listed
2275                        .into_iter()
2276                        .map(|s| {
2277                            json!({"path": s.metadata.path.display().to_string(), "id": s.metadata.id, "name": s.name,
2278                                "modified": s.metadata.modified_at as i64, "messageCount": s.message_count,
2279                                "firstMessage": s.first_message, "allMessagesText": s.all_messages_text,
2280                                "cwd": s.metadata.cwd})
2281                        })
2282                        .collect(),
2283                )))
2284            }
2285        }
2286    }
2287
2288    /// What a response means for the generation's retries (the harness's `publishResponse`): a retryable error
2289    /// within the policy's attempts is retried after `retryDelayMs` (journaled as `assistant.retry_wait`); a later
2290    /// attempt's response ends the retries: `retry_scheduled` / `retry_end` of the run's generation.
2291    fn retry_decision(&mut self, answer: &ai::AssistantMessage) -> Option<WatchEvent> {
2292        let policy = self.summary_retry();
2293        let run = self.run.as_mut()?;
2294        if run.signal.aborted() {
2295            return None;
2296        }
2297        let journal = run.journal.run()?;
2298        let (attempt, step) = (journal.attempt(), journal.step_id().to_string());
2299        if !harness::chat::models::is_context_overflow(answer)
2300            && let Some(delay) = policy.retry_delay(attempt, answer)
2301        {
2302            let not_before = now_ms().saturating_add(i64::try_from(delay).unwrap_or(i64::MAX));
2303            let message = answer
2304                .error_message
2305                .clone()
2306                .unwrap_or_else(|| "Assistant request failed".into());
2307            run.journal.schedule_retry(not_before, message.clone());
2308            return Some(WatchEvent::RetryScheduled {
2309                lane: MAIN_LANE.into(),
2310                run_id: Some(run.id.clone()),
2311                step,
2312                attempt: attempt + 1,
2313                max_attempts: policy.max_attempts(),
2314                delay_ms: delay,
2315                not_before,
2316                error_message: message,
2317            });
2318        }
2319        if attempt <= 1 {
2320            return None;
2321        }
2322        let success = !matches!(answer.stop_reason, ai::StopReason::Error | ai::StopReason::Aborted);
2323        let final_error = (!success).then(|| {
2324            answer.error_message.clone().unwrap_or_else(|| {
2325                let reason = serde_json::to_value(answer.stop_reason).unwrap_or(Value::Null);
2326                format!("Assistant request ended with {}", reason.as_str().unwrap_or_default())
2327            })
2328        });
2329        Some(WatchEvent::RetryEnd {
2330            lane: MAIN_LANE.into(),
2331            run_id: Some(run.id.clone()),
2332            step,
2333            attempt,
2334            success,
2335            final_error,
2336        })
2337    }
2338
2339    /// A model turn of the run that answers without tools ends with its answer (`turn_end`); a tool round's turn
2340    /// ends with its last cell ([`crate::turns::Request::RoundEnded`]).
2341    fn count_round(&mut self, message: &Value) {
2342        if self.run.is_none() || message["role"] != "assistant" {
2343            return;
2344        }
2345        let calls = message["content"]
2346            .as_array()
2347            .map_or(0, |c| c.iter().filter(|b| b["type"] == "toolCall").count());
2348        if calls == 0 {
2349            self.turn_ended(0, 0);
2350        }
2351    }
2352
2353    /// `turn_end` on `main`: the brake and the skill hint steer the run when due.
2354    pub(super) fn turn_ended(&mut self, calls: usize, failed: usize) {
2355        let Some(run) = self.run.as_ref().map(|r| r.id.clone()) else {
2356            return;
2357        };
2358        let running = self.root_started_running();
2359        let steers: Vec<String> = [
2360            self.nudger.turn_ended(&run, calls, running),
2361            self.skill_nudger.turn_ended(&run, calls, failed, running),
2362        ]
2363        .into_iter()
2364        .flatten()
2365        .collect();
2366        for steer in steers {
2367            self.lane.stack.stats.nudge(&steer);
2368            let _ = self.enqueue(QueueKind::Steer, steer, Vec::new(), None);
2369        }
2370    }
2371
2372    /// `pendingRootNotifications`: subagents and root-level tasks the root started that have not ended.
2373    fn root_started_running(&self) -> u64 {
2374        use kernel_apis::TaskHost;
2375        let subagents = self.lane.stack.delegation.running(MAIN_LANE).len();
2376        let tasks = self
2377            .lane
2378            .stack
2379            .agents
2380            .tasks()
2381            .unwrap_or_default()
2382            .iter()
2383            .filter(|task| task["parentId"].is_null() && task["result"].is_null())
2384            .count();
2385        (subagents + tasks) as u64
2386    }
2387
2388    fn thinking_levels(&self) -> Vec<String> {
2389        ai::models::supported_thinking_levels(&self.model)
2390            .into_iter()
2391            .map(str::to_string)
2392            .collect()
2393    }
2394
2395    fn set_thinking(&mut self, level: &str) -> Result<(), String> {
2396        let levels = self.thinking_levels();
2397        if !levels.iter().any(|l| l == level) {
2398            return Err(format!(
2399                "Thinking level {level} is unavailable; choose one of: {}",
2400                levels.join(", ")
2401            ));
2402        }
2403        if self.thinking != level {
2404            self.thinking = level.to_string();
2405            self.store_lane_config()?;
2406            self.emit(WatchEvent::ConfigUpdate {
2407                lane: MAIN_LANE.into(),
2408                property: "thinkingLevel".into(),
2409                value: json!(level),
2410            });
2411        }
2412        Ok(())
2413    }
2414
2415    fn state(&self) -> Value {
2416        let queues = sync::lock(&self.queues);
2417        let mut state = Map::new();
2418        state.insert("model".into(), serde_json::to_value(&self.model).unwrap_or(Value::Null));
2419        state.insert("thinkingLevel".into(), self.thinking.clone().into());
2420        state.insert("isStreaming".into(), self.run.is_some().into());
2421        state.insert("isCompacting".into(), self.compacting.is_some().into());
2422        // Only while turn-end checks run (core::turn_guard): they may continue the turn.
2423        if self.turn_guard_checking() {
2424            state.insert("isChecking".into(), true.into());
2425        }
2426        let mode = |all: bool| {
2427            if all {
2428                config::keys::QUEUE_ALL
2429            } else {
2430                config::keys::QUEUE_ONE_AT_A_TIME
2431            }
2432        };
2433        state.insert("steeringMode".into(), mode(queues.steering_all).into());
2434        state.insert("followUpMode".into(), mode(queues.follow_up_all).into());
2435        state.insert("sessionFile".into(), self.session_file().into());
2436        state.insert("sessionId".into(), lock_session(&self.session).id().into());
2437        if let Some(name) = lock_session(&self.session).name() {
2438            state.insert("sessionName".into(), name.into());
2439        }
2440        state.insert("autoCompactionEnabled".into(), self.auto_compaction.into());
2441        state.insert("messageCount".into(), view::messages(&self.pi()).len().into());
2442        state.insert(
2443            "pendingMessageCount".into(),
2444            (queues.items.len() + queues.delivered.len()).into(),
2445        );
2446        Value::Object(state)
2447    }
2448
2449    /// The `ultron.memory` message a run of the user message `text` opens with, when automatic recall finds
2450    /// memories the context does not show yet (crate::auto_memory).
2451    fn recalled_memory(&self, text: &str) -> Option<Value> {
2452        if !self.auto_memory.recall_ready() || !crate::auto_memory::worth_recalling(text) {
2453            return None;
2454        }
2455        let entries = lock_session(&self.session)
2456            .branch_entries(MAIN_LANE)
2457            .unwrap_or_default();
2458        let shown = crate::auto_memory::shown(&entries);
2459        let recalled = self.auto_memory.recall(&self.lane.stack, text, &shown);
2460        crate::auto_memory::recall_message(&recalled, now_ms() as u64)
2461    }
2462
2463    /// The `ultron.playbook` message a run of the user message `text` opens with, in engineering mode
2464    /// (crate::playbook_route).
2465    fn routed_playbook(&self, text: &str) -> Option<Value> {
2466        crate::playbook_route::route(text)?;
2467        let manager = (self.runtime.config.settings_reader())();
2468        if manager.settings().get("engineering") != Some(&Value::Bool(true)) {
2469            return None;
2470        }
2471        let rigor = std::path::PathBuf::from(self.runtime.config.bundled_skills()?).join("pstack/rigor");
2472        let entries = lock_session(&self.session)
2473            .branch_entries(MAIN_LANE)
2474            .unwrap_or_default();
2475        let shown = crate::playbook_route::shown(&entries);
2476        crate::playbook_route::playbook_message(text, &rigor, &shown, now_ms() as u64)
2477    }
2478
2479    /// The `ultron.refinements` message a root user run opens with, when the active refinements differ from what the
2480    /// context shows (crate::auto_refine).
2481    fn refinements_message(&self) -> Option<Value> {
2482        if !self.auto_refine.on {
2483            return None;
2484        }
2485        let entries = lock_session(&self.session)
2486            .branch_entries(MAIN_LANE)
2487            .unwrap_or_default();
2488        let shown = crate::auto_refine::shown(&entries);
2489        let active = self.lane.stack.ledger.active();
2490        crate::auto_refine::message(&active, shown.as_deref(), now_ms() as u64)
2491    }
2492
2493    /// Propose refinements from the newest compaction's summary in the background, when automatic refinement is on
2494    /// and past its cooldown (crate::auto_refine).
2495    fn refine_after_compaction(&self) {
2496        let newest = {
2497            let session = lock_session(&self.session);
2498            let entries = session.branch_entries(MAIN_LANE).unwrap_or_default();
2499            entries
2500                .iter()
2501                .rev()
2502                .find(|entry| entry["type"] == "compaction")
2503                .and_then(|entry| {
2504                    Some((
2505                        entry["id"].as_str()?.to_string(),
2506                        entry["summary"].as_str()?.to_string(),
2507                    ))
2508                })
2509        };
2510        let Some((id, summary)) = newest.filter(|(_, summary)| !summary.trim().is_empty()) else {
2511            return;
2512        };
2513        if !self.auto_refine.start_pass() {
2514            return;
2515        }
2516        let summarizer = self.summarizer();
2517        crate::auto_refine::propose(self.lane.stack.ledger.clone(), id, summary, move |system, prompt| {
2518            summarizer.ask(system, prompt)
2519        });
2520    }
2521
2522    /// After a completed compaction: distil its summary into long-term memory, when automatic retain is on
2523    /// (crate::auto_memory), and propose refinements from it (crate::auto_refine).
2524    pub(super) fn retain_compaction(&self) {
2525        self.refine_after_compaction();
2526        if !self.auto_memory.retain {
2527            return;
2528        }
2529        let (session_id, entries) = {
2530            let session = lock_session(&self.session);
2531            (
2532                session.id().to_string(),
2533                session.branch_entries(MAIN_LANE).unwrap_or_default(),
2534            )
2535        };
2536        let cwd = self.runtime.config.cwd.display().to_string();
2537        if let Some(keep) = crate::auto_memory::summary_keep(&session_id, &cwd, &entries) {
2538            self.keep_in_background(keep);
2539        }
2540    }
2541
2542    /// Keep what no compaction summarized in long-term memory, when automatic retain is on (crate::auto_memory).
2543    /// `in_background` when the session stays open (it went quiet): the call does not hold the session up, and its
2544    /// outcome is shown. As it closes, the keep waits at most [`crate::auto_memory::CLOSE_TIMEOUT`] and is not shown.
2545    pub(super) fn retain_tail(&self, in_background: bool) {
2546        if !self.auto_memory.retain {
2547            return;
2548        }
2549        let (session_id, entries) = {
2550            let session = lock_session(&self.session);
2551            (
2552                session.id().to_string(),
2553                session.branch_entries(MAIN_LANE).unwrap_or_default(),
2554            )
2555        };
2556        let cwd = self.runtime.config.cwd.display().to_string();
2557        let Some(keep) = crate::auto_memory::tail_keep(&session_id, &cwd, &entries) else {
2558            return;
2559        };
2560        if in_background {
2561            self.keep_in_background(keep);
2562        } else {
2563            let summarizer = self.summarizer();
2564            let agent_dir = self.runtime.config.agent_dir.clone();
2565            crate::auto_memory::keep(
2566                &self.lane.stack,
2567                &agent_dir,
2568                keep,
2569                move |system, prompt| summarizer.ask(system, prompt),
2570                crate::auto_memory::CLOSE_TIMEOUT,
2571            );
2572        }
2573    }
2574
2575    /// Distils `keep` on a thread (the side request is the session's summarizer, bounded by IDLE_WAIT); its outcome
2576    /// comes back to the actor as `Input::MemoryKept`.
2577    fn keep_in_background(&self, keep: crate::auto_memory::Keep) {
2578        let summarizer = self.summarizer();
2579        let (stack, agent_dir, tx) = (
2580            self.lane.stack.clone(),
2581            self.runtime.config.agent_dir.clone(),
2582            self.tx.clone(),
2583        );
2584        std::thread::spawn(move || {
2585            let outcome = crate::auto_memory::keep(
2586                &stack,
2587                &agent_dir,
2588                keep,
2589                move |system, prompt| summarizer.ask(system, prompt),
2590                IDLE_WAIT,
2591            );
2592            if let Some(outcome) = outcome {
2593                let _ = tx.send(Input::MemoryKept(outcome));
2594            }
2595        });
2596    }
2597
2598    /// Shows a background keep's outcome as one display-only line, when the outcome is worth one. Not journaled: the
2599    /// model never sees it.
2600    fn memory_kept(&mut self, outcome: crate::auto_memory::Outcome) {
2601        if outcome.shown() {
2602            let message = crate::auto_memory::outcome_message(&outcome, now_ms() as u64);
2603            self.announce_message(&message);
2604        }
2605    }
2606
2607    /// Start a run of `message`; `waiter` is answered when it ends. On failure the waiter comes back with the error.
2608    fn prompt(&mut self, message: String, images: Vec<Value>, waiter: Option<Reply>) -> Result<(), (String, Reply)> {
2609        self.prompt_with(user_message(message, images), waiter, true)
2610    }
2611
2612    /// Start a run of the user message `prompt` (see [`Core::prompt`]).
2613    ///
2614    /// `take_queued`: the admission also takes the steering and follow-up messages queued while the lane was idle
2615    /// (by the queue modes); messages queued for the next run are always taken.
2616    #[allow(clippy::result_large_err)]
2617    fn prompt_with(&mut self, prompt: Value, waiter: Option<Reply>, take_queued: bool) -> Result<(), (String, Reply)> {
2618        let fail = |error: String, waiter: Option<Reply>| -> Result<(), (String, Reply)> {
2619            match waiter {
2620                Some(waiter) => Err((error, waiter)),
2621                None => Err((error, Box::new(|_| {}))),
2622            }
2623        };
2624        // A stored OAuth credential may authenticate by header alone (Kimi's bearer): no key, but `getAuth` resolves.
2625        let api_key = self.api_key();
2626        if api_key.is_none() && !lane::header_auth(&self.env, &self.model.provider) {
2627            return fail(format!("No API key found for {}", self.model.provider), waiter);
2628        }
2629        let text = message_text(&prompt);
2630        let continuation = prompt.get(crate::recovery::RECOVERY_DEPTH).is_some();
2631        // Name a new conversation from its first prompt; the model's title may replace it before the run ends.
2632        let mut naming_request = None;
2633        // RPC clients see the session as TypeScript's RPC mode does: unnamed until they name it.
2634        // A completion event's run (a custom message) never names the session.
2635        let auto_name = self.auto_name
2636            && !continuation
2637            && prompt["role"] != "custom"
2638            && self.runtime.mode != "rpc"
2639            && !self.env.flag_off(AUTO_NAME_ENV);
2640        let named = if auto_name {
2641            names::apply_auto_name(&mut lock_session(&self.session), &text)
2642        } else {
2643            Ok(None)
2644        };
2645        match named {
2646            Ok(Some(_)) => {
2647                self.name_changed();
2648                let naming = naming::naming_settings(&self.runtime.config.settings);
2649                if naming.enabled {
2650                    // A `provider/id` setting names a built-in or models.json model; else the provider's
2651                    // cheapest, which models.json may override (its URL, headers).
2652                    let named = naming
2653                        .model
2654                        .as_deref()
2655                        .and_then(|spec| spec.split_once('/'))
2656                        .and_then(|(provider, id)| lane::catalog_model(provider, id, &self.env).ok());
2657                    let naming_model = named.unwrap_or_else(|| {
2658                        let chosen = naming::naming_model(naming.model.as_deref(), &self.model, &api_supported);
2659                        if chosen.provider == self.model.provider && chosen.id == self.model.id {
2660                            return self.model.clone();
2661                        }
2662                        lane::catalog_model(&chosen.provider, &chosen.id, &self.env).unwrap_or(chosen)
2663                    });
2664                    let key = self.keys.request_key(&naming_model.provider);
2665                    naming_request = Some((naming_model, key, text.clone()));
2666                }
2667            }
2668            Ok(None) => {}
2669            Err(error) => return fail(error, waiter),
2670        }
2671        // The messages the run opens with: Loki's setup note for the first root turn that follows it
2672        // (`installLokiNotice`) and the memory-paused notice for the first root turn; for a user message, the long-term memory recalled for it (crate::auto_memory), in
2673        // engineering mode the rigor playbook that fits it (crate::playbook_route), and the active instruction
2674        // refinements when the context does not show them as they are (crate::auto_refine).
2675        let mut opening: Vec<Value> = self
2676            .loki_notice
2677            .take(crate::loki_notice::NOTICE_WAIT)
2678            .map(|text| crate::loki_notice::notice_message(&text, now_ms() as u64))
2679            .into_iter()
2680            .chain(
2681                self.memory_notice
2682                    .take()
2683                    .map(|text| crate::auto_memory::paused_message(&text, now_ms() as u64)),
2684            )
2685            .collect();
2686        if prompt["role"] == "user" && !continuation {
2687            opening.extend(self.recalled_memory(&text));
2688            opening.extend(self.routed_playbook(&text));
2689            opening.extend(self.refinements_message());
2690        }
2691        for message in opening {
2692            self.announce_message(&message);
2693            if let Err(error) = self.append(message) {
2694                return fail(error, waiter);
2695            }
2696        }
2697        if let Err(error) = self.store_lane_config() {
2698            return fail(error, waiter);
2699        }
2700        let lane_config = lock_session(&self.session)
2701            .value(LANE_CONFIG, MAIN_LANE)
2702            .cloned()
2703            .unwrap_or(Value::Null);
2704        let started_tip = self.tip().map_or(Value::Null, Value::from);
2705        let settings = self.run_settings();
2706        // The run takes the messages queued while the lane was idle, placed before its prompt in the order they were
2707        // queued (`selectAcceptedInbox`); the rest wait in the inbox and the run delivers them.
2708        let captured: Vec<(String, Value)> = select_accepted(&sync::lock(&self.queues), take_queued);
2709        let mut inbox = self.lane_state()["inbox"].clone();
2710        if let Some(items) = inbox.as_array_mut() {
2711            items.retain(|item| !captured.iter().any(|(id, _)| item["entryId"] == id.as_str()));
2712        }
2713        let mut journal = match RunJournal::admit(
2714            Some(&mut lock_session(&self.session)),
2715            lane_config,
2716            prompt.clone(),
2717            (self.model.max_tokens, self.model.context_window),
2718            settings,
2719            &captured,
2720            inbox,
2721        ) {
2722            Ok(journal) => journal,
2723            Err(error) => return fail(error, waiter),
2724        };
2725        if !captured.is_empty() {
2726            sync::lock(&self.queues)
2727                .items
2728                .retain(|q| !captured.iter().any(|(id, _)| *id == q.entry_id));
2729            self.queue_update();
2730        }
2731        let captured: Vec<Value> = captured.into_iter().map(|(_, message)| message).collect();
2732        // The title call runs beside the turn and is applied whenever it answers (while the name is automatic).
2733        if let Some((naming_model, key, text)) = naming_request {
2734            let (tx, provider) = (self.tx.clone(), self.provider.clone());
2735            std::thread::spawn(move || {
2736                let Ok(runtime) = tokio::runtime::Builder::new_current_thread().enable_all().build() else {
2737                    return;
2738                };
2739                let request = naming::request(&text);
2740                let options = naming::options(key);
2741                let mut sink = |_: &ai::AssistantMessageEvent| {};
2742                let call = provider.stream(&naming_model, &request, &options, &mut sink);
2743                if let Ok(title) = runtime.block_on(async { tokio::time::timeout(naming::TIMEOUT, call).await }) {
2744                    let _ = tx.send(Input::Title(Box::new(title)));
2745                }
2746            });
2747        }
2748        // Work the turn admits is charged to a usage root of its own; the ledger counts its responses.
2749        journal.ledger_counts_turns();
2750        journal.set_retry_policy(self.summary_retry().journal_value());
2751        if let Some(options) = self.provider.stream_options() {
2752            journal.set_stream_options(options);
2753        }
2754        if let Some(run) = journal.run() {
2755            self.lane.stack.agents.begin_root_turn(run.operation_id());
2756            self.durable.children.set_root(
2757                self.lane
2758                    .stack
2759                    .agents
2760                    .usage_root_for_lane(MAIN_LANE, run.operation_id()),
2761            );
2762        }
2763        // `prepareGeneration`: a model that does not resolve fails the run at its first generation, before any
2764        // request (generation.ts `configurationError("model_unavailable", identity)`).
2765        if self.model_unavailable {
2766            let identity = json!({"provider": self.model.provider, "modelId": self.model.id});
2767            let result = journal.fail_configuration(
2768                &mut lock_session(&self.session),
2769                "model_unavailable",
2770                MODEL_UNAVAILABLE,
2771                identity,
2772            );
2773            self.announce();
2774            return fail(result.err().unwrap_or_else(|| MODEL_UNAVAILABLE.to_string()), waiter);
2775        }
2776        // The turn runs in the durable runtime; its prompt is the entry the run just admitted.
2777        let prompt_entry = self.tip().unwrap_or_default();
2778        if !continuation && prompt["role"] == "user" {
2779            self.checkpoint_turn(&prompt_entry);
2780        }
2781        let submission = match self.start_turn(&prompt, &prompt_entry) {
2782            Ok(submission) => submission,
2783            Err(error) => {
2784                let _ = journal.finish(Some(&mut lock_session(&self.session)), Some(("run_failed", &error)));
2785                return fail(error, waiter);
2786            }
2787        };
2788        let signal = AbortSignal::new();
2789        let id = jsrt::random::uuid_v7(now_ms());
2790        self.branches.run_started();
2791        // Per-turn guard times start from zero (`fileHooks.beginTurn()` on the root lane's `run_start`), and a
2792        // session in which the root ran keeps its counters, even when they are all zero.
2793        self.lane.stack.begin_turn();
2794        self.lane.stack.stats.touch();
2795        self.run = Some(Running {
2796            id: id.clone(),
2797            signal,
2798            journal,
2799            prompt,
2800            captured,
2801            submission: Some(submission),
2802            prompt_pending: true,
2803            turns: 0,
2804            started_tip,
2805            error: None,
2806            waiter,
2807            cancelled: false,
2808            compaction_failed: false,
2809            resume_overflow: None,
2810            hiding: false,
2811            ending: false,
2812        });
2813        self.persona_run_started();
2814        // Checks of an earlier turn's end are not this run's.
2815        self.turn_guard_cancel();
2816        self.emit(WatchEvent::RunStart {
2817            run_id: id,
2818            started_at: now_ms(),
2819            lane: MAIN_LANE.into(),
2820        });
2821        self.spawn_waiter();
2822        Ok(())
2823    }
2824
2825    /// [`Op::Recover`]: start what the dead worker left: the first queued message, else the interrupted run's
2826    /// continuation (unless it was interrupted [`crate::recovery::MAX_RECOVERY_DEPTH`] times in a row, or
2827    /// `ULTRON_RECOVERY_RESUME` is `off`).
2828    fn recover(&mut self) -> OpResult {
2829        let Some(recovered) = self.recovered.take() else {
2830            return Ok(Some(json!({"resumed": false, "reason": "nothing to recover"})));
2831        };
2832        let summary = json!({
2833            "operationId": recovered.operation_id, "status": recovered.status, "depth": recovered.depth,
2834            "interruptedCalls": recovered.interrupted_calls, "queued": recovered.queued.len(),
2835        });
2836        let answer = |resumed: bool, run: Value, reason: &str| {
2837            Ok(Some(
2838                json!({"resumed": resumed, "runId": run, "reason": reason, "recovered": summary}),
2839            ))
2840        };
2841        // A run of the durable runtime was resumed when the session opened.
2842        if let Some(run) = self.resumed.take() {
2843            return answer(true, json!(run), "durable run resumed");
2844        }
2845        if self.run.is_some() {
2846            return answer(false, Value::Null, "a run is in progress");
2847        }
2848        let resume_off = self.env.flag_off(RECOVERY_RESUME_ENV);
2849        // The interrupted run continues first; queued messages stay queued and the loop delivers them as it would
2850        // have (steering during the run, follow-ups when it would end). Without one, the first queued message runs.
2851        // A message queued for the next run waits for one; it never starts it.
2852        let first = sync::lock(&self.queues)
2853            .items
2854            .iter()
2855            .find(|q| q.kind != QueueKind::NextRun)
2856            .cloned();
2857        let prompt = match first {
2858            _ if recovered.resume && !resume_off => {
2859                let mut prompt = user_message(crate::recovery::CONTINUE_PROMPT.to_string(), Vec::new());
2860                prompt[crate::recovery::RECOVERY_DEPTH] = json!(recovered.depth + 1);
2861                Some((prompt, "interrupted run"))
2862            }
2863            // An aborted run's queue waits for the user, as it would have after a live abort.
2864            Some(queued) if recovered.status.as_deref() != Some("aborted") => {
2865                self.remove_queued(std::slice::from_ref(&queued.entry_id))?;
2866                let mut prompt = queued.message;
2867                prompt["timestamp"] = json!(now_ms());
2868                Some((prompt, "queued message"))
2869            }
2870            _ => None,
2871        };
2872        let Some((prompt, reason)) = prompt else {
2873            let reason = if recovered.operation_id.is_none() {
2874                "nothing to recover"
2875            } else if recovered.resume {
2876                "resuming is off"
2877            } else {
2878                "the interrupted run is not resumed"
2879            };
2880            return answer(false, Value::Null, reason);
2881        };
2882        match self.prompt_with(prompt, None, false) {
2883            Ok(()) => answer(true, json!(self.run_id()), reason),
2884            Err((error, _)) => Err(error),
2885        }
2886    }
2887
2888    fn enqueue(
2889        &mut self,
2890        kind: QueueKind,
2891        message: String,
2892        images: Vec<Value>,
2893        entry_id: Option<String>,
2894    ) -> Result<String, String> {
2895        if message.is_empty() && images.is_empty() {
2896            return Err(EMPTY_QUEUED.into());
2897        }
2898        let message = user_message(message, images);
2899        let entry_id =
2900            entry_id.unwrap_or_else(|| session_journal::lock_clock(&lock_session(&self.session).clock()).next_id());
2901        let mut lane_state = self.lane_state();
2902        if let Some(inbox) = lane_state["inbox"].as_array_mut() {
2903            inbox.push(json!({"entryId": entry_id, "kind": kind.name()}));
2904        }
2905        if let Some(run) = self.run.as_mut() {
2906            run.journal.set_inbox(lane_state["inbox"].clone());
2907        }
2908        lock_session(&self.session).commit(&[
2909            Write::set(PENDING_ENTRY, &entry_id, json!({"type": "message", "payload": message})),
2910            Write::set(LANE_STATE, MAIN_LANE, lane_state),
2911        ])?;
2912        sync::lock(&self.queues).items.push(Queued {
2913            kind,
2914            message,
2915            entry_id: entry_id.clone(),
2916            turn: 0,
2917            submission: None,
2918        });
2919        // During a run the message waits in the durable runtime's inbox for its boundary.
2920        if self.run.is_some() {
2921            self.submit_queued()?;
2922        }
2923        self.queue_update();
2924        Ok(entry_id)
2925    }
2926
2927    /// Remove queued messages (their pending entries and inbox items) in one transaction.
2928    fn remove_queued(&mut self, ids: &[String]) -> Result<(), String> {
2929        let mut lane_state = self.lane_state();
2930        if let Some(inbox) = lane_state["inbox"].as_array_mut() {
2931            inbox.retain(|item| !ids.iter().any(|id| item["entryId"] == id.as_str()));
2932        }
2933        if let Some(run) = self.run.as_mut() {
2934            run.journal.set_inbox(lane_state["inbox"].clone());
2935        }
2936        let mut writes: Vec<Write> = ids.iter().map(|id| Write::delete(PENDING_ENTRY, id)).collect();
2937        writes.push(Write::set(LANE_STATE, MAIN_LANE, lane_state));
2938        lock_session(&self.session).commit(&writes)?;
2939        if !ids.is_empty() {
2940            self.withdraw_queued(ids);
2941        }
2942        for id in ids {
2943            let mut queues = sync::lock(&self.queues);
2944            if let Some(index) = queues.items.iter().position(|q| q.entry_id == *id) {
2945                queues.items.remove(index);
2946            }
2947            drop(queues);
2948            self.queue_update();
2949        }
2950        Ok(())
2951    }
2952
2953    fn clear_queue(&mut self) -> Value {
2954        let (steering, follow_up, cleared) = {
2955            let queues = sync::lock(&self.queues);
2956            let visible = queues.visible();
2957            let pick = |kind: QueueKind| -> Vec<String> {
2958                visible
2959                    .iter()
2960                    .filter(|q| q.kind == kind)
2961                    .map(|q| message_text(&q.message))
2962                    .collect()
2963            };
2964            let cleared: Vec<String> = queues.items.iter().map(|q| q.entry_id.clone()).collect();
2965            // A next-run message is listed with the follow-ups, as RPC's `queue_update` lists it.
2966            let mut follow_up = pick(QueueKind::FollowUp);
2967            follow_up.extend(pick(QueueKind::NextRun));
2968            (pick(QueueKind::Steer), follow_up, cleared)
2969        };
2970        if !cleared.is_empty() {
2971            let _ = self.remove_queued(&cleared);
2972        }
2973        json!({"steering": steering, "followUp": follow_up})
2974    }
2975
2976    fn bash(&mut self, op: Op, reply: Reply) {
2977        let Op::Bash { command, exclude, id } = op else { return };
2978        let signal = kernel::Signal::new();
2979        self.bash = Some(signal.clone());
2980        let host = self.lane.host.clone();
2981        let tx = self.tx.clone();
2982        // session-control-provider.ts `bash`: the `shellCommandPrefix` setting runs first; the message keeps the
2983        // command as typed.
2984        let prefix = self
2985            .runtime
2986            .config
2987            .settings
2988            .as_object()
2989            .and_then(config::keys::shell_command_prefix);
2990        std::thread::spawn(move || {
2991            // Off the actor: the actor keeps serving while the command runs.
2992            let result = user_bash::run(&host, &command, prefix.as_deref(), &signal, &mut |delta| {
2993                let _ = tx.send(Input::BashOutput {
2994                    id: id.clone(),
2995                    delta: delta.to_string(),
2996                });
2997            });
2998            let _ = tx.send(Input::BashDone {
2999                command,
3000                exclude,
3001                result,
3002                reply,
3003            });
3004        });
3005    }
3006}
3007
3008/// Start an actor for `options` on its own thread; returns its input, or the open error.
3009pub fn spawn(options: OpenOptions, sink: EventSink) -> Result<(Sender<Input>, JoinHandle<()>, Value), String> {
3010    let (tx, rx) = std::sync::mpsc::channel();
3011    let (ready_tx, ready_rx) = std::sync::mpsc::channel();
3012    let input = tx.clone();
3013    let trace_path = (options.env.var)(crate::startup_trace::TRACE_ENV);
3014    let handle = std::thread::spawn(move || match Core::open(options, input, sink) {
3015        Ok(core) => {
3016            crate::startup_trace::trace_startup(trace_path.as_deref(), "worker.ready");
3017            let _ = ready_tx.send(Ok((
3018                core.snapshot(),
3019                core.model().clone(),
3020                core.thinking_level().to_string(),
3021            )));
3022            core.run_loop(rx);
3023        }
3024        Err(error) => {
3025            let _ = ready_tx.send(Err(error));
3026        }
3027    });
3028    let ready = ready_rx.recv().map_err(|e| e.to_string())??;
3029    let (snapshot, model, thinking) = ready;
3030    let mut summary = json!({"snapshot": snapshot, "model": serde_json::to_value(&model).unwrap_or(Value::Null)});
3031    summary["thinkingLevel"] = json!(thinking);
3032    Ok((tx, handle, summary))
3033}
3034
3035/// Run `op` on the actor and wait for its answer.
3036pub fn call(tx: &Sender<Input>, op: Op) -> OpResult {
3037    let (reply_tx, reply_rx) = std::sync::mpsc::channel();
3038    tx.send(Input::Op(
3039        op,
3040        Box::new(move |result| {
3041            let _ = reply_tx.send(result);
3042        }),
3043    ))
3044    .map_err(|_| SESSION_CLOSED.to_string())?;
3045    reply_rx.recv().map_err(|_| SESSION_CLOSED.to_string())?
3046}