Skip to content

robotsix_chat.chat.server

Chat SSE server — HTTP + Server-Sent Events bridge for human-to-agent chat.

Re-exports the public API that used to live in the monolithic server.py, preserving backward compatibility for all existing import sites (tests/, src/robotsix_chat/chat/__init__.py, etc.).

create_agent_from_settings(instruction=None, settings=None, *, conversation_store=None, model_level=None, subsession_env=None, subsession_ctx=None, subsession_close_state=None, tool_wrapper=None, bare=False, memory_enabled=True, event_sink=None, diagnostic_store=None, knowledge_store=None, continuation_store=None, operator_attended=True)

Build an :class:LlmioChatAgent wired from settings.

The backend is chosen by robotsix-llmio's capability level: model_level when given, else settings.chat_default_model_level. The level encodes the transport + model; settings.openrouter_api_key is forwarded only when the effective level's transport needs a key (keyless claudeSDK levels 2, 4, 5 never receive one).

When settings is None, Settings.load() resolves configuration from the YAML config file and environment. When instruction is None, it is taken from settings.agent_instruction.

bare (default False) skips skill injection, feature tools, subsession wiring, and memory — the agent gets a NullMemory and no tools. Use it for bounded text-transformation calls (e.g. the compaction summary agent).

memory_enabled (default True) gates only the full long-term memory while leaving tools and subsession wiring intact. Set False for unattended background agents (subsession workers, periodic auto-continue) that would otherwise recall + cognify every turn around the clock; they get a NullMemory. The interactive main-chat agent keeps the default. bare already implies no memory regardless.

operator_attended (default True) must be False for agents no operator is watching (periodic sessions); it withholds the operator-instruction-only repo creation / fork tools. Subsession agents (subsession_ctx set) are always treated as unattended.

Subsession wiring (subsession_env):

  • Main chat agent — pass subsession_env with subsession_ctx=None. Per-request tools are built via request_tools_factory so each tool closure captures the owning session_id lexically.
  • Subsession agent — pass subsession_env, the worker's subsession_ctx, and its subsession_close_state. The depth-aware tools (including complete_subsession) are baked in statically; identity is fixed at construction.
  • None (default) — no subsession tools.

event_sink is forwarded to :class:~robotsix_chat.llm.LlmioChatAgent for live tool/thinking activity frames on the GET /events channel. Pass the same :class:~robotsix_chat.chat.events.EventBus given to create_app — typically only for the main chat agent.

Source code in src/robotsix_chat/chat/server/agent_factory.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def create_agent_from_settings(
    instruction: str | None = None,
    settings: Settings | None = None,
    *,
    conversation_store: ConversationStore | None = None,
    model_level: int | None = None,
    subsession_env: SubsessionEnv | None = None,
    subsession_ctx: SubsessionContext | None = None,
    subsession_close_state: CloseState | None = None,
    tool_wrapper: Callable[[list[Any]], list[Any]] | None = None,
    bare: bool = False,
    memory_enabled: bool = True,
    event_sink: EventSink | None = None,
    diagnostic_store: Any = None,
    knowledge_store: Any = None,
    continuation_store: Any = None,
    operator_attended: bool = True,
) -> LlmioChatAgent:
    """Build an :class:`LlmioChatAgent` wired from *settings*.

    The backend is chosen by robotsix-llmio's capability level: *model_level*
    when given, else ``settings.chat_default_model_level``.  The level encodes the
    transport + model; ``settings.openrouter_api_key`` is forwarded only when the
    effective level's transport needs a key (keyless claudeSDK levels 2, 4, 5
    never receive one).

    When *settings* is ``None``, ``Settings.load()`` resolves configuration
    from the YAML config file and environment. When *instruction* is ``None``,
    it is taken from ``settings.agent_instruction``.

    *bare* (default ``False``) skips skill injection, feature tools,
    subsession wiring, and memory — the agent gets a ``NullMemory`` and no
    tools.  Use it for bounded text-transformation calls (e.g. the
    compaction summary agent).

    *memory_enabled* (default ``True``) gates only the full long-term memory
    while leaving tools and subsession wiring intact.  Set ``False`` for
    unattended background agents (subsession workers, periodic
    auto-continue) that would otherwise recall + cognify every turn around
    the clock; they get a ``NullMemory``.  The interactive main-chat agent
    keeps the default.  ``bare`` already implies no memory regardless.

    *operator_attended* (default ``True``) must be ``False`` for agents no
    operator is watching (periodic sessions); it withholds the
    operator-instruction-only repo creation / fork tools.  Subsession agents
    (*subsession_ctx* set) are always treated as unattended.

    Subsession wiring (*subsession_env*):

    * **Main chat agent** — pass *subsession_env* with ``subsession_ctx=None``.
      Per-request tools are built via ``request_tools_factory`` so each tool
      closure captures the owning ``session_id`` lexically.
    * **Subsession agent** — pass *subsession_env*, the worker's
      *subsession_ctx*, and its *subsession_close_state*.  The depth-aware
      tools (including ``complete_subsession``) are baked in statically;
      identity is fixed at construction.
    * ``None`` (default) — no subsession tools.

    *event_sink* is forwarded to :class:`~robotsix_chat.llm.LlmioChatAgent`
    for live tool/thinking activity frames on the ``GET /events`` channel.
    Pass the same :class:`~robotsix_chat.chat.events.EventBus` given to
    ``create_app`` — typically only for the main chat agent.
    """
    if settings is None:
        settings = Settings.load()
    if instruction is None:
        instruction = settings.agent_instruction

    instruction = _inject_skills(settings, instruction, bare=bare)

    # The main chat agent (operator-attended, no fixed subsession identity)
    # gets the standing suggestion-chip contract so multiple-choice decisions
    # render as clickable answer buttons.  Bare text-transformation agents and
    # subsession children are excluded — subsessions get their own suggestion
    # directive via ``USER_CHAT_FIRST_TURN_NOTE`` (subsessions/prompts.py) in
    # the worker.
    if not bare and subsession_ctx is None:
        instruction = instruction + _SUGGESTIONS_INSTRUCTION

    effective_level = (
        model_level if model_level is not None else settings.chat_default_model_level
    )
    # Frontier subsessions (level 3) get an orchestration directive so they
    # delegate bulk reading/extraction to cheaper child subsessions by
    # default instead of burning frontier-model turns on it themselves.
    # Only subsession agents receive it — the main chat agent is
    # operator-attended and already interactive.
    if subsession_ctx is not None:
        from robotsix_chat.subsessions.models import (
            COSTLY_TIER_MIN_LEVEL,
            COSTLY_TIER_ORCHESTRATION_DIRECTIVE,
        )

        if effective_level >= COSTLY_TIER_MIN_LEVEL:
            instruction = instruction + COSTLY_TIER_ORCHESTRATION_DIRECTIVE
    # Always hand over the configured key. LlmioChatAgent forwards it only
    # to keyed (OpenRouter) slot attempts, and it needs to be holding it for
    # llmio's provider failover to reach the keyed fallback slot when the
    # shared Claude credential or quota is what failed — the mode that takes
    # the whole default slot down at once.
    api_key = settings.openrouter_api_key.get_secret_value()
    # The direct Anthropic Messages API slot takes its own credential; an
    # empty value lets llmio fall back to the ANTHROPIC_API_KEY env var.
    anthropic_api_key = settings.anthropic_api_key.get_secret_value()

    tools = _build_static_tools(
        settings,
        bare=bare,
        conversation_store=conversation_store,
        diagnostic_store=diagnostic_store,
        knowledge_store=knowledge_store,
        continuation_store=continuation_store,
        operator_attended=operator_attended and subsession_ctx is None,
    )
    if tool_wrapper is not None:
        tools = tool_wrapper(tools)

    request_tools_factory: Callable[[str], list[Any]] | None = None
    if not bare:
        if subsession_env is not None and subsession_ctx is not None:
            # Subsession agent: identity fixed at construction.
            from robotsix_chat.subsessions import build_subsession_tools

            tools.extend(
                build_subsession_tools(
                    subsession_env,
                    ctx=subsession_ctx,
                    close_state=subsession_close_state,
                )
            )
        # Build per-request tools factory — subsession and escalation tools
        # for the main agent.
        request_tools_factory = _build_request_tools_factory(
            settings,
            subsession_env if subsession_ctx is None else None,
            event_sink,
            # Escalation is a main-chat affordance only: subsessions already
            # choose their own level when spawned, and a periodic/bare
            # agent has no operator watching the badge change.
            conversation_store if subsession_ctx is None and not bare else None,
            (
                settings.chat_default_model_level
                if subsession_ctx is None and not bare
                else None
            ),
        )

    # Read/write split for background agents. Recall is a retrieval-only
    # lookup (~0.4 s warm, no LLM call); cognify is a multi-minute LLM
    # pipeline that also contends with every concurrent recall. So an agent
    # whose WRITE gate is off can still safely READ — denying it the context
    # the main conversation already learned buys nothing.
    if bare:
        memory: ChatMemory = NullMemory()
    elif memory_enabled:
        memory = build_memory(settings.memory_component)
    elif settings.memory_component.enabled:
        memory = ReadOnlyMemory(build_memory(settings.memory_component))
    else:
        memory = NullMemory()
    # Deep on-demand memory search: the automatic per-message recall is
    # retrieval-only and cheap; the expensive LLM-mediated graph search is a
    # tool the model invokes deliberately. Returns [] for NullMemory, so this
    # is safe unconditionally.
    from robotsix_chat.memory.tools import build_memory_tools

    tools.extend(build_memory_tools(memory))

    agent = LlmioChatAgent(
        model_level=effective_level,
        instruction=instruction,
        api_key=api_key,
        anthropic_api_key=anthropic_api_key,
        memory=memory,
        tools=tools,
        request_tools_factory=request_tools_factory,
        event_sink=event_sink,
        failover_window_seconds=settings.llmio_failover_window_seconds,
        tier_overrides=settings.llmio_tier_overrides,
    )
    # Wire guarded auto-recovery (self-restart) for the top-level chat agent's
    # memory only — never for bare summary agents, subsession children, or any
    # agent whose memory was gated off (a NullMemory has nothing to recover).
    # It needs the lifecycle transport; without it a freeze is still surfaced
    # (via ERROR log + GET /health) but not auto-healed.
    if (
        not bare
        and memory_enabled
        and subsession_ctx is None
        and settings.lifecycle.enabled
    ):
        from robotsix_chat.lifecycle.client import LifecycleClient

        # The canonical deploy URL must be passed explicitly — constructing
        # the client without it left auto-recovery pointing at an empty base
        # URL, so every self-restart attempt failed with a URL protocol
        # error (and boot logged "central_deploy.url is empty" although the
        # config had it): a frozen memory backend was never auto-healed.
        agent.memory.set_recovery_callback(
            LifecycleClient(
                settings.lifecycle, settings.central_deploy.url
            ).self_restart
        )
    return agent

create_app(agent, *, summary_agent=None, serve_ui=True, idle_timeout_minutes=30, max_images_per_message=8, max_image_bytes=5242880, allowed_image_media_types=None, cors_allow_origins=None, correlation_id_header='X-Request-ID', conversation_store=None, event_bus=None, run_serializer=None, msg_id_store=None, message_coalescer=None, message_coalesce_seconds=0.3, subsession_registry=None, subsession_delivery=None, feedback_runner=None, periodic_definitions=None, periodic_agent_factory=None, periodic_state_path=None, on_startup=None, on_startup_async=None, on_shutdown=None, direct_repo_settings=None, central_deploy_settings=None, github_security_settings=None, github_actions_settings=None, mobile_auth=None, config_path=None, draft_store_dir=None, diagnostic_store=None, knowledge_store=None, health_settings=None, evergoing_settings=None, memory_component_settings=None, continuation_store=None)

Return a Starlette ASGI app wired to agent.

The returned app is a fully-initialised ASGI application that can be mounted directly in tests via httpx.ASGITransport or passed to uvicorn.run().

Parameters:

Name Type Description Default
agent ChatAgent

Object whose stream(message) yields response tokens.

required
summary_agent ChatAgent | None

Dedicated summariser agent used for the idle-timeout compaction summary, the carryover summary and conversation titles. None (default) reuses agent — pass a separate agent built on settings.summary_model_level with the summariser system prompt (see cli.py) so those bounded text-transformation calls neither pay for the main agent's tier nor inherit its tool-oriented instructions.

None
serve_ui bool

When True (default), serve the bundled browser chat UI at GET / so the UI and /chat share one origin.

True
idle_timeout_minutes int

Minutes of no user activity before the UI auto-restarts the conversation; 0 disables.

30
max_images_per_message int

Maximum number of images a client may attach to a single POST /chat request. Default 8.

8
max_image_bytes int

Maximum decoded size (bytes) of a single attached image. Default 5_242_880 (5 MiB).

5242880
allowed_image_media_types list[str] | None

Media types accepted for image attachments. Default ["image/png", "image/jpeg", "image/gif", "image/webp"].

None
cors_allow_origins list[str] | None

Origins permitted to call /chat cross-origin (e.g. when the UI is hosted separately). None (default) adds no CORS headers; ["*"] allows any origin.

None
correlation_id_header str

HTTP header name for the correlation / request-id. Default X-Request-ID.

'X-Request-ID'
conversation_store ConversationStore | None

Tracks per-client multi-turn conversation history and trace sessions. None (default) builds one with default settings.

None
event_bus EventBus | None

Per-client SSE notification bus for GET /events. When None (default), a fresh :class:EventBus is created. Pass the same instance given to the SubsessionRegistry so lifecycle frames published by the registry reach the SSE subscribers.

None
run_serializer RunSerializer | None

Per-owner RunSerializer that prevents overlapping agent runs for the same owner. When None (default), a fresh RunSerializer is created. Pass the same instance to the ParentDelivery so subsession summary writes and user-initiated /chat requests are serialized.

None
msg_id_store MessageIdempotencyStore | None

Per-session message idempotency store that ensures duplicate messages return the cached reply. When None (default), a fresh :class:MessageIdempotencyStore is created.

None
message_coalescer MessageCoalescer | None

Per-session message coalescer that batches rapid-fire user messages into a single agent run. When None (default), a fresh :class:MessageCoalescer is created with message_coalesce_seconds.

None
message_coalesce_seconds float

Debounce window (seconds) that the coalescer waits before draining the pending-message batch. Default 0.3.

0.3
subsession_registry SubsessionRegistry | None

Shared :class:~robotsix_chat.subsessions.SubsessionRegistry for the unified subsession system. Leave None when subsessions are not wired — the /subsessions routes then return 503.

None
subsession_delivery ParentDelivery | None

The :class:~robotsix_chat.subsessions.ParentDelivery used by the /subsessions/{id}/close route to deliver the summary of an externally-closed subsession. Required together with subsession_registry for full functionality.

None
feedback_runner Any

Optional :class:~robotsix_chat.feedback.FeedbackRunner that schedules feedback analysis runs at compaction and session-end boundaries. When None (default), feedback runs are disabled.

None
periodic_definitions list[Any] | None

Enabled :class:~robotsix_chat.config.periodic_models.PeriodicSessionDefinition presets. When None/empty, no periodic scheduler is created.

None
periodic_agent_factory Callable[[int | None], ChatAgent] | None

Callable mapping a preset's model_level (None for the global default) to the agent that runs its turns. When None, the main agent runs every periodic turn.

None
periodic_state_path str | None

Override for the scheduler's firing-state file (tests); defaults to the standard /data location.

None
on_startup Callable[[], None] | None

Optional callable invoked during application startup (the Starlette lifespan startup phase). Pass a closure that e.g. resumes persisted subsessions.

None
on_startup_async Callable[[], Any] | None

Optional async callable invoked after on_startup during application startup. Pass a coroutine function that e.g. starts the component-agent responder.

None
on_shutdown Callable[[], Any] | None

Optional async callable invoked during application shutdown (after yield). Pass a coroutine function that e.g. stops the component-agent responder.

None
direct_repo_settings DirectRepoSettings | None

GitHub App credentials (app id, private key, installation id) used by the PATCH /chat/github/repos/{owner}/{repo}/settings endpoint. When None, the endpoint returns 503.

None
central_deploy_settings CentralDeploySettings | None

Canonical deploy-plane settings (URL and API key) used by the GitHub security/actions endpoints for inbound X-API-Key matching. When None, those endpoints return 503.

None
github_security_settings GitHubSecuritySettings | None

GitHub security-feature toggle config (org, deploy API key) used by the PATCH /chat/github/repos/{owner}/{repo}/settings endpoint. When None, the endpoint returns 503.

None
github_actions_settings GitHubActionsSettings | None

GitHub Actions config (org, deploy API key) used by the Actions secrets and workflow dispatch endpoints. When None, the endpoints return 503.

None
mobile_auth MobileAuthSettings | None

Mobile SSO authentication settings. When None or disabled, the auth endpoints return 404.

None
config_path str | None

Path to the config JSON file, used by the GET /config and PUT /config endpoints. When None (default), the path is resolved from the ROBOTSIX_CONFIG_FILE environment variable or the default config/config.json.

None
draft_store_dir str | None

Path to the session-drafts directory, used by the GET /sessions/{session_id}/draft and PUT /sessions/{session_id}/draft endpoints. Each session gets its own {session_id}.json file inside this directory. When None (default), the directory /data/session_drafts is used.

None
diagnostic_store Any

Shared :class:~robotsix_chat.diagnostics.DiagnosticStore instance, used by the POST /diagnostics/events and GET /diagnostics/events endpoints. When None (default), the diagnostic endpoints return 503.

None
knowledge_store Any

Shared :class:~robotsix_chat.knowledge.KnowledgeStore instance used for session carryover persistence. When None (default), carryover is disabled.

None
health_settings HealthSettings | None

Optional :class:~robotsix_chat.config.models.HealthSettings controlling the periodic health-check scheduler. When None (default), the default settings are used (enabled, 300 s interval).

None
evergoing_settings EvergoingSettings | None

Optional :class:~robotsix_chat.config.models.EvergoingSettings controlling the periodic summarising compaction scheduler (interval, runs kept verbatim). When None (default), the default settings are used.

None
memory_component_settings MemoryComponentSettings | None

Optional :class:~robotsix_chat.config.models.MemoryComponentSettings — summary pushes to the robotsix-memory component.

None
continuation_store Any

Shared :class:~robotsix_chat.continuation.store.ContinuationStore instance for pending post-restart continuations. When None (default), the chat endpoint does not reset the consecutive-continuation guardrail counter on operator messages.

None
Source code in src/robotsix_chat/chat/server/app.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
def create_app(
    agent: ChatAgent,
    *,
    summary_agent: ChatAgent | None = None,
    serve_ui: bool = True,
    idle_timeout_minutes: int = 30,
    max_images_per_message: int = 8,
    max_image_bytes: int = 5_242_880,
    allowed_image_media_types: list[str] | None = None,
    cors_allow_origins: list[str] | None = None,
    correlation_id_header: str = "X-Request-ID",
    conversation_store: ConversationStore | None = None,
    event_bus: EventBus | None = None,
    run_serializer: RunSerializer | None = None,
    msg_id_store: MessageIdempotencyStore | None = None,
    message_coalescer: MessageCoalescer | None = None,
    message_coalesce_seconds: float = 0.3,
    subsession_registry: SubsessionRegistry | None = None,
    subsession_delivery: ParentDelivery | None = None,
    feedback_runner: Any = None,
    periodic_definitions: list[Any] | None = None,
    periodic_agent_factory: Callable[[int | None], ChatAgent] | None = None,
    periodic_state_path: str | None = None,
    on_startup: Callable[[], None] | None = None,
    on_startup_async: Callable[[], Any] | None = None,
    on_shutdown: Callable[[], Any] | None = None,
    direct_repo_settings: DirectRepoSettings | None = None,
    central_deploy_settings: CentralDeploySettings | None = None,
    github_security_settings: GitHubSecuritySettings | None = None,
    github_actions_settings: GitHubActionsSettings | None = None,
    mobile_auth: MobileAuthSettings | None = None,
    config_path: str | None = None,
    draft_store_dir: str | None = None,
    diagnostic_store: Any = None,
    knowledge_store: Any = None,
    health_settings: HealthSettings | None = None,
    evergoing_settings: EvergoingSettings | None = None,
    memory_component_settings: MemoryComponentSettings | None = None,
    continuation_store: Any = None,
) -> Starlette:
    """Return a Starlette ASGI app wired to ``agent``.

    The returned app is a fully-initialised ASGI application that can be
    mounted directly in tests via ``httpx.ASGITransport`` or passed to
    ``uvicorn.run()``.

    Args:
        agent: Object whose ``stream(message)`` yields response tokens.
        summary_agent: Dedicated summariser agent used for the idle-timeout
            compaction summary, the carryover summary and conversation
            titles. ``None`` (default) reuses *agent* — pass a separate
            agent built on ``settings.summary_model_level`` with the
            summariser system prompt (see ``cli.py``) so those bounded
            text-transformation calls neither pay for the main agent's tier
            nor inherit its tool-oriented instructions.
        serve_ui: When ``True`` (default), serve the bundled browser chat
            UI at ``GET /`` so the UI and ``/chat`` share one origin.
        idle_timeout_minutes: Minutes of no user activity before the UI
            auto-restarts the conversation; ``0`` disables.
        max_images_per_message: Maximum number of images a client may attach
            to a single ``POST /chat`` request.  Default ``8``.
        max_image_bytes: Maximum decoded size (bytes) of a single attached
            image.  Default ``5_242_880`` (5 MiB).
        allowed_image_media_types: Media types accepted for image
            attachments.  Default ``["image/png", "image/jpeg", "image/gif",
            "image/webp"]``.
        cors_allow_origins: Origins permitted to call ``/chat`` cross-origin
            (e.g. when the UI is hosted separately). ``None`` (default)
            adds no CORS headers; ``["*"]`` allows any origin.
        correlation_id_header: HTTP header name for the correlation /
            request-id. Default ``X-Request-ID``.
        conversation_store: Tracks per-client multi-turn conversation history
            and trace sessions. ``None`` (default) builds one with default
            settings.
        event_bus: Per-client SSE notification bus for ``GET /events``.
            When ``None`` (default), a fresh :class:`EventBus` is created.
            Pass the same instance given to the ``SubsessionRegistry`` so
            lifecycle frames published by the registry reach the SSE
            subscribers.
        run_serializer: Per-owner ``RunSerializer`` that prevents
            overlapping agent runs for the same owner.  When ``None``
            (default), a fresh ``RunSerializer`` is created.  Pass the
            same instance to the ``ParentDelivery`` so subsession summary
            writes and user-initiated ``/chat`` requests are serialized.
        msg_id_store: Per-session message idempotency store that ensures
            duplicate messages return the cached reply.  When ``None``
            (default), a fresh :class:`MessageIdempotencyStore` is created.
        message_coalescer: Per-session message coalescer that batches
            rapid-fire user messages into a single agent run.  When
            ``None`` (default), a fresh :class:`MessageCoalescer` is
            created with *message_coalesce_seconds*.
        message_coalesce_seconds: Debounce window (seconds) that the
            coalescer waits before draining the pending-message batch.
            Default ``0.3``.
        subsession_registry: Shared
            :class:`~robotsix_chat.subsessions.SubsessionRegistry` for the
            unified subsession system.  Leave ``None`` when subsessions are
            not wired — the ``/subsessions`` routes then return 503.
        subsession_delivery: The
            :class:`~robotsix_chat.subsessions.ParentDelivery` used by the
            ``/subsessions/{id}/close`` route to deliver the summary of an
            externally-closed subsession.  Required together with
            *subsession_registry* for full functionality.
        feedback_runner: Optional
            :class:`~robotsix_chat.feedback.FeedbackRunner` that schedules
            feedback analysis runs at compaction and session-end boundaries.
            When ``None`` (default), feedback runs are disabled.
        periodic_definitions: Enabled
            :class:`~robotsix_chat.config.periodic_models.PeriodicSessionDefinition`
            presets. When ``None``/empty, no periodic scheduler is created.
        periodic_agent_factory: Callable mapping a preset's ``model_level``
            (``None`` for the global default) to the agent that runs its
            turns. When ``None``, the main *agent* runs every periodic turn.
        periodic_state_path: Override for the scheduler's firing-state file
            (tests); defaults to the standard /data location.
        on_startup: Optional callable invoked during application startup
            (the Starlette lifespan ``startup`` phase).  Pass a closure
            that e.g. resumes persisted subsessions.
        on_startup_async: Optional async callable invoked after *on_startup*
            during application startup.  Pass a coroutine function that
            e.g. starts the component-agent responder.
        on_shutdown: Optional async callable invoked during application
            shutdown (after ``yield``).  Pass a coroutine function that
            e.g. stops the component-agent responder.
        direct_repo_settings: GitHub App credentials (app id, private key,
            installation id) used by the
            ``PATCH /chat/github/repos/{owner}/{repo}/settings`` endpoint.
            When ``None``, the endpoint returns 503.
        central_deploy_settings: Canonical deploy-plane settings (URL and
            API key) used by the GitHub security/actions endpoints for
            inbound ``X-API-Key`` matching.  When ``None``, those
            endpoints return 503.
        github_security_settings: GitHub security-feature toggle config
            (org, deploy API key) used by the
            ``PATCH /chat/github/repos/{owner}/{repo}/settings`` endpoint.
            When ``None``, the endpoint returns 503.
        github_actions_settings: GitHub Actions config (org, deploy API key)
            used by the Actions secrets and workflow dispatch endpoints.
            When ``None``, the endpoints return 503.
        mobile_auth: Mobile SSO authentication settings.  When ``None``
            or disabled, the auth endpoints return 404.
        config_path: Path to the config JSON file, used by the
            ``GET /config`` and ``PUT /config`` endpoints.  When ``None``
            (default), the path is resolved from the
            ``ROBOTSIX_CONFIG_FILE`` environment variable or the default
            ``config/config.json``.
        draft_store_dir: Path to the session-drafts directory, used by
            the ``GET /sessions/{session_id}/draft`` and
            ``PUT /sessions/{session_id}/draft`` endpoints.  Each session
            gets its own ``{session_id}.json`` file inside this directory.
            When ``None`` (default), the directory ``/data/session_drafts``
            is used.
        diagnostic_store: Shared :class:`~robotsix_chat.diagnostics.DiagnosticStore`
            instance, used by the ``POST /diagnostics/events`` and
            ``GET /diagnostics/events`` endpoints.  When ``None`` (default),
            the diagnostic endpoints return 503.
        knowledge_store: Shared :class:`~robotsix_chat.knowledge.KnowledgeStore`
            instance used for session carryover persistence.  When ``None``
            (default), carryover is disabled.
        health_settings: Optional
            :class:`~robotsix_chat.config.models.HealthSettings` controlling
            the periodic health-check scheduler.  When ``None`` (default),
            the default settings are used (enabled, 300 s interval).
        evergoing_settings: Optional
            :class:`~robotsix_chat.config.models.EvergoingSettings` controlling
            the periodic summarising compaction scheduler (interval, runs
            kept verbatim).  When ``None`` (default), the default settings
            are used.
        memory_component_settings: Optional
            :class:`~robotsix_chat.config.models.MemoryComponentSettings` —
            summary pushes to the robotsix-memory component.
        continuation_store: Shared
            :class:`~robotsix_chat.continuation.store.ContinuationStore`
            instance for pending post-restart continuations.  When
            ``None`` (default), the chat endpoint does not reset the
            consecutive-continuation guardrail counter on operator messages.

    """
    routes: list[Route | Mount] = []
    for path, endpoint, methods, _summary, versioned in _API_ROUTE_SPECS:
        routes.append(Route(path, endpoint, methods=list(methods)))
        # Stable, versioned alias under /api/v1.  The historical root path
        # stays registered so existing un-versioned callers keep working
        # during the transition (only ops probes are root-only).
        if versioned:
            routes.append(Route(f"/api/v1{path}", endpoint, methods=list(methods)))

    # OpenAPI contract endpoints.  The whole app (including these two paths)
    # sits behind the central-deploy gateway's auth layer.
    routes.append(Route("/openapi.json", openapi_json_endpoint, methods=["GET"]))
    routes.append(Route("/docs", docs_endpoint, methods=["GET"]))

    # Chat-skill descriptor — served through a Starlette-native endpoint (see
    # routes/chat_skill.py) because the shared robotsix-http factory
    # (robotsix_http.fastapi.create_chat_skill_router) is FastAPI-only by
    # design: it mints a FastAPI APIRouter that a plain Starlette app cannot
    # host, so migrating /chat-skill to the factory is infeasible for this
    # server.  Frontmatter validity and route parity are still enforced
    # against the factory by the chat_skill_route_parity test.  It
    # intentionally lives outside _API_ROUTE_SPECS: no /api/v1 alias, and no
    # entry in the OpenAPI schema assembled above.
    routes.append(Route("/chat-skill", chat_skill_endpoint, methods=["GET"]))

    if serve_ui:
        routes.append(Route("/", ui_endpoint, methods=["GET"]))
        static_dir = str(resources.files("robotsix_chat") / "ui" / "static")
        routes.append(
            Mount(
                "/static",
                app=StaticFiles(directory=static_dir),
            )
        )

    # CorrelationIdMiddleware is outermost so every request (and its log lines)
    # carries a request id. Authentication is centralized at the
    # central-deploy gateway — the app adds no auth layer of its own.
    middleware = [
        Middleware(CorrelationIdMiddleware, header_name=correlation_id_header),
        Middleware(StructlogContextMiddleware),
    ]
    if cors_allow_origins:
        middleware.append(
            Middleware(
                CORSMiddleware,
                allow_origins=cors_allow_origins,
                allow_methods=["GET", "POST", "OPTIONS"],
                allow_headers=["Content-Type"],
            )
        )

    # Security headers (http-security-headers standard), registered exactly
    # once here. Appended last so it sits innermost and decorates every
    # response the routes / exception handlers produce.
    middleware.append(Middleware(SecureASGIMiddleware, secure=build_secure_headers()))

    app = Starlette(
        routes=routes,
        middleware=middleware,
        exception_handlers={
            HTTPException: http_exception_handler,
            404: not_found_handler,
            500: server_error_handler,
            Exception: unhandled_exception_handler,
        },
        lifespan=lambda _app: _make_lifespan(
            on_startup,
            on_startup_async=on_startup_async,
            on_shutdown=on_shutdown,
            app=_app,
        ),
    )
    app.state.agent = agent
    # The main agent's memory backend, surfaced for GET /health so a frozen
    # store is externally visible (``None`` for agents with no memory).
    app.state.memory = getattr(agent, "memory", None)
    app.state.summary_agent = summary_agent if summary_agent is not None else agent
    app.state.conversation_store = conversation_store or ConversationStore()
    # Configured chat level — the baseline a session runs at until the agent
    # escalates it. Read from the agent so create_app needs no new parameter.
    app.state.chat_model_level = getattr(agent, "model_level", None)
    app.state.llmio_tier_overrides = getattr(agent, "tier_overrides", None)
    # Whether keyed (OpenRouter) model levels are usable — surfaced to the UI
    # model selector so it can mark levels that need an absent API key as
    # unavailable. Read from the agent so create_app needs no new parameter.
    app.state.chat_api_key_available = bool(getattr(agent, "has_api_key", False))
    app.state.idle_timeout_minutes = idle_timeout_minutes
    app.state.max_images_per_message = max_images_per_message
    app.state.max_image_bytes = max_image_bytes
    app.state.allowed_image_media_types = (
        allowed_image_media_types
        if allowed_image_media_types is not None
        else list(DEFAULT_ALLOWED_IMAGE_MEDIA_TYPES)
    )
    app.state.event_bus = event_bus or EventBus()
    app.state.run_serializer = run_serializer or RunSerializer()
    app.state.msg_id_store = msg_id_store or MessageIdempotencyStore()
    app.state.message_coalescer = message_coalescer or MessageCoalescer(
        debounce_seconds=message_coalesce_seconds
    )
    app.state.subsession_registry = subsession_registry  # may be None
    app.state.subsession_delivery = subsession_delivery  # may be None
    app.state.direct_repo_settings = direct_repo_settings
    app.state.central_deploy_settings = central_deploy_settings
    app.state.github_security_settings = github_security_settings
    app.state.github_actions_settings = github_actions_settings
    app.state.mobile_auth = mobile_auth
    app.state.feedback_runner = feedback_runner  # may be None
    _register_inflight_probes(app.state.message_coalescer, subsession_registry)
    if periodic_definitions:
        from robotsix_chat.periodic import (
            PERIODIC_OWNER,
            PERIODIC_SCHEDULER_PERSIST_PATH,
            PeriodicScheduler,
            format_failsafe_partial_report,
            prune_closed_periodic_sessions,
        )
        from robotsix_chat.subsessions import SubsessionKind

        _p_coalescer = app.state.message_coalescer
        _p_store = app.state.conversation_store

        async def _periodic_submit_turn(
            session_id: str, message: str, model_level: int | None
        ) -> None:
            """Run one periodic turn through the normal chat submit path."""
            turn_agent = (
                periodic_agent_factory(model_level)
                if periodic_agent_factory is not None
                else app.state.agent
            )
            queue = await _p_coalescer.submit(
                session_id,
                message,
                None,
                None,
                agent=turn_agent,
                store=_p_store,
                run_serializer=app.state.run_serializer,
                msg_id_store=app.state.msg_id_store,
                lock_key=session_id,
                owner_id=PERIODIC_OWNER,
                had_session=True,
                summary_agent=app.state.summary_agent,
                event_bus=app.state.event_bus,
            )
            # Drain to completion so the scheduler's task tracks the whole
            # turn (there is no SSE client on a scheduled firing).
            from .routes.constants import SSE_DONE_TYPE, SSE_ERROR_TYPE

            while True:
                frame_type, payload = await queue.get()
                if frame_type == SSE_DONE_TYPE:
                    break
                if frame_type == SSE_ERROR_TYPE:
                    # A turn-level error is fanned out as an SSE_ERROR frame
                    # rather than raised by submit() (the coalescer spawns a
                    # background processor task that never re-raises), so
                    # distinguish it here. Raising makes the scheduler treat
                    # this run as failed — it is NOT completion-closed, and
                    # is left for the supersede-close safety net.
                    err_msg = (
                        payload.get("message") if isinstance(payload, dict) else None
                    )
                    raise RuntimeError(err_msg or "periodic turn failed")

        async def _periodic_close_previous(session_id: str) -> None:
            """Close a superseded periodic run through the UI close path."""
            from .routes.sessions import close_session_fully

            await close_session_fully(app, PERIODIC_OWNER, session_id)

        async def _periodic_close_completed(session_id: str) -> None:
            """Close a periodic run once its turn completes, via the UI close path."""
            from .routes.sessions import close_session_fully

            await close_session_fully(app, PERIODIC_OWNER, session_id)

        def _periodic_has_live_subsessions(session_id: str) -> bool:
            """Return True when a session still has a working subsession."""
            registry = app.state.subsession_registry
            if registry is None:
                return False
            # ``is_active`` is a @property (status in ACTIVE_STATUSES), not a
            # method — calling it would raise ``TypeError: 'bool' object is
            # not callable`` and leak an unhandled task exception, and the
            # completion-close gate would break for any session that ever
            # spawned a subsession.
            return any(sub.is_active for sub in registry.list_for_owner(session_id))

        async def _periodic_report_partial_result(
            session_id: str, error_message: str
        ) -> None:
            """Record a partial-failure report into a crashed run's transcript.

            When a periodic turn raises before completing, the normal submit
            path never records the exchange, leaving the session with no
            visible failure state. Appending the error here means future runs
            resume with full context of what was attempted and where it
            failed.
            """
            _p_store.record(
                session_id,
                PERIODIC_OWNER,
                "(periodic turn error)",
                error_message,
            )

        async def _periodic_ensure_partial_report(session_id: str) -> None:
            """Append a failsafe PARTIAL REPORT when a turn ended without one.

            A periodic turn can finish WITHOUT raising yet leave no report —
            token exhaustion or a provider cutoff can end the turn cleanly
            before the agent summarises its work. Conservative detection (low
            false-positive): append only when the transcript is empty or the
            final assistant reply is empty/whitespace-only. A healthy run ends
            with a non-empty assistant reply and is left untouched, so this
            never double-appends on a normal firing.
            """
            turns = _p_store.history(session_id)
            if turns and turns[-1][1].strip():
                return
            _p_store.record(
                session_id,
                PERIODIC_OWNER,
                "(periodic failsafe)",
                format_failsafe_partial_report(),
            )

        async def _periodic_carry_over(
            previous_session_id: str, session_id: str
        ) -> int:
            """Hand the previous run's live user_chat panels to the new run.

            Without this the supersede-close kills every decision panel the
            operator has not answered yet, and the new run — finding no open
            panel — spawns the same question again, every firing.
            """
            registry = app.state.subsession_registry
            if registry is None:
                return 0
            return int(
                registry.reassign_live_user_chats(previous_session_id, session_id)
            )

        async def _periodic_prune_closed(keep: set[str]) -> int:
            """Delete closed periodic runs outside the retention window."""
            return prune_closed_periodic_sessions(
                _p_store, keep, registry=app.state.subsession_registry
            )

        async def _periodic_report_pending_subsessions(session_id: str) -> None:
            """Surface OPEN user_chat panels when a periodic turn crashed.

            The agent normally surfaces open ``user_chat`` decision panels as
            its first operation, but a turn that fails before the agent runs
            never performs that check, so pending operator decisions stay
            invisible in the transcript. This fallback — invoked ONLY on the
            exception path — lists the run's live ``user_chat`` subsessions and
            records them directly, making the escalations visible independently
            of the main task succeeding. No-op when there are none open, so the
            transcript is not cluttered when nothing is pending.
            """
            registry = app.state.subsession_registry
            if registry is None:
                return
            pending = [
                sub
                for sub in registry.list_for_owner(session_id)
                if sub.kind is SubsessionKind.USER_CHAT and sub.is_active
            ]
            if not pending:
                return
            lines = [
                "PENDING OPERATOR DECISIONS (surfaced after a failed periodic "
                + "turn)",
                "",
                "The scheduled task failed before completing, but the "
                "following open user_chat decision panels are still awaiting an "
                "operator reply. They are live decisions, not deferred work:",
                "",
            ]
            for sub in pending:
                lines.append(f"- {sub.title} ({sub.id}) — status: {sub.status.value}")
                prompt = (sub.prompt or "").strip()
                if prompt:
                    lines.append(f"    Decision needed: {prompt}")
            _p_store.record(
                session_id,
                PERIODIC_OWNER,
                "(periodic pending subsessions)",
                "\n".join(lines),
            )

        app.state.periodic_scheduler = PeriodicScheduler(
            definitions=periodic_definitions,
            conversation_store=_p_store,
            submit_turn=_periodic_submit_turn,
            is_busy=_p_coalescer.is_busy,
            persist_path=periodic_state_path or PERIODIC_SCHEDULER_PERSIST_PATH,
            close_previous=_periodic_close_previous,
            close_completed=_periodic_close_completed,
            has_live_subsessions=_periodic_has_live_subsessions,
            report_partial_result=_periodic_report_partial_result,
            ensure_partial_report_on_interruption=_periodic_ensure_partial_report,
            report_pending_subsessions=_periodic_report_pending_subsessions,
            carry_over_subsessions=_periodic_carry_over,
            prune_closed_runs=_periodic_prune_closed,
        )
    else:
        app.state.periodic_scheduler = None
    app.state.diagnostic_store = diagnostic_store  # may be None
    app.state.knowledge_store = knowledge_store  # may be None
    # Health-check scheduler — created here so it has access to the fully
    # populated app.state, then started during the lifespan async phase.
    _hs = health_settings or HealthSettings()
    app.state.health_settings = _hs
    if _hs.enabled:
        from robotsix_chat.health import HealthScheduler

        app.state.health_scheduler = HealthScheduler(
            interval_seconds=_hs.check_interval_seconds,
            state=app.state,
        )
    else:
        app.state.health_scheduler = None
    app.state.health_status = None  # populated after first check cycle
    # The periodic summary scheduler is the single context-reduction
    # mechanism for ALL sessions (idle compaction removed); started during
    # the lifespan async phase.
    _eg = evergoing_settings or EvergoingSettings()
    if app.state.summary_agent is not None:
        from robotsix_chat.evergoing import EvergoingSummaryScheduler
        from robotsix_chat.memory.push import MemoryPush

        _mc = memory_component_settings or MemoryComponentSettings()
        memory_push = (
            MemoryPush(_mc.url, timeout_seconds=_mc.timeout_seconds)
            if _mc.enabled
            else None
        )
        app.state.evergoing_scheduler = EvergoingSummaryScheduler(
            interval_seconds=_eg.trim_interval_seconds,
            store=app.state.conversation_store,
            agent=app.state.summary_agent,
            keep_recent_runs=_eg.keep_recent_runs,
            memory_push=memory_push,
        )
    else:
        app.state.evergoing_scheduler = None
    app.state.continuation_store = continuation_store  # may be None

    if config_path is not None:
        app.state.config_path = config_path
    if draft_store_dir is not None:
        app.state.draft_store_dir = draft_store_dir
    return app

run_server(agent, *, summary_agent=None, host='0.0.0.0', port=8000, serve_ui=True, idle_timeout_minutes=30, max_images_per_message=8, max_image_bytes=5242880, allowed_image_media_types=None, cors_allow_origins=None, correlation_id_header='X-Request-ID', conversation_store=None, event_bus=None, run_serializer=None, subsession_registry=None, subsession_delivery=None, feedback_runner=None, periodic_definitions=None, periodic_agent_factory=None, periodic_state_path=None, on_startup=None, on_startup_async=None, on_shutdown=None, direct_repo_settings=None, central_deploy_settings=None, github_security_settings=None, github_actions_settings=None, mobile_auth=None, config_path=None, diagnostic_store=None, knowledge_store=None, health_settings=None, evergoing_settings=None, memory_component_settings=None, continuation_store=None)

Start the chat SSE server on host:port.

Blocks until the process is interrupted (uvicorn handles SIGINT / SIGTERM).

Source code in src/robotsix_chat/chat/server/cli.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def run_server(
    agent: ChatAgent,
    *,
    summary_agent: ChatAgent | None = None,
    host: str = "0.0.0.0",  # noqa: S104  # nosec B104
    port: int = 8000,
    serve_ui: bool = True,
    idle_timeout_minutes: int = 30,
    max_images_per_message: int = 8,
    max_image_bytes: int = 5_242_880,
    allowed_image_media_types: list[str] | None = None,
    cors_allow_origins: list[str] | None = None,
    correlation_id_header: str = "X-Request-ID",
    conversation_store: ConversationStore | None = None,
    event_bus: EventBus | None = None,
    run_serializer: RunSerializer | None = None,
    subsession_registry: Any = None,
    subsession_delivery: Any = None,
    feedback_runner: Any = None,
    periodic_definitions: Any = None,
    periodic_agent_factory: Any = None,
    periodic_state_path: str | None = None,
    on_startup: Callable[[], None] | None = None,
    on_startup_async: Callable[[], Any] | None = None,
    on_shutdown: Callable[[], Any] | None = None,
    direct_repo_settings: Any = None,
    central_deploy_settings: Any = None,
    github_security_settings: Any = None,
    github_actions_settings: Any = None,
    mobile_auth: Any = None,
    config_path: str | None = None,
    diagnostic_store: Any = None,
    knowledge_store: Any = None,
    health_settings: Any = None,
    evergoing_settings: Any = None,
    memory_component_settings: Any = None,
    continuation_store: Any = None,
) -> None:
    """Start the chat SSE server on ``host:port``.

    Blocks until the process is interrupted (uvicorn handles
    ``SIGINT`` / ``SIGTERM``).
    """
    import uvicorn

    app = create_app(
        agent,
        summary_agent=summary_agent,
        serve_ui=serve_ui,
        idle_timeout_minutes=idle_timeout_minutes,
        max_images_per_message=max_images_per_message,
        max_image_bytes=max_image_bytes,
        allowed_image_media_types=allowed_image_media_types,
        cors_allow_origins=cors_allow_origins,
        correlation_id_header=correlation_id_header,
        conversation_store=conversation_store,
        event_bus=event_bus,
        run_serializer=run_serializer,
        subsession_registry=subsession_registry,
        subsession_delivery=subsession_delivery,
        feedback_runner=feedback_runner,
        periodic_definitions=periodic_definitions,
        periodic_agent_factory=periodic_agent_factory,
        periodic_state_path=periodic_state_path,
        on_startup=on_startup,
        on_startup_async=on_startup_async,
        on_shutdown=on_shutdown,
        direct_repo_settings=direct_repo_settings,
        central_deploy_settings=central_deploy_settings,
        github_security_settings=github_security_settings,
        github_actions_settings=github_actions_settings,
        mobile_auth=mobile_auth,
        config_path=config_path,
        diagnostic_store=diagnostic_store,
        knowledge_store=knowledge_store,
        health_settings=health_settings,
        evergoing_settings=evergoing_settings,
        memory_component_settings=memory_component_settings,
        continuation_store=continuation_store,
    )
    uvicorn.run(app, host=host, port=port)

run_server_from_config(agent=None)

Start the chat SSE server using Settings.load() for configuration.

Resolves settings through the full cascade (pydantic defaults → YAML config file → environment, with .env support), configures Python logging, builds a default :class:LlmioChatAgent when agent is None (using agent_instruction from config), and delegates to :func:run_server. (Authentication is centralized at the central-deploy gateway — the server itself is unauthenticated.)

Source code in src/robotsix_chat/chat/server/cli.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def run_server_from_config(agent: ChatAgent | None = None) -> None:
    """Start the chat SSE server using ``Settings.load()`` for configuration.

    Resolves settings through the full cascade (pydantic defaults → YAML
    config file → environment, with ``.env`` support), configures Python
    logging, builds a default :class:`LlmioChatAgent` when *agent* is
    ``None`` (using ``agent_instruction`` from config), and delegates to
    :func:`run_server`. (Authentication is centralized at the central-deploy
    gateway — the server itself is unauthenticated.)
    """
    # Lazy import so tests can patch ``robotsix_chat.chat.server.run_server``
    # and the patch is visible through the package re-export.
    from . import run_server as _run_server

    settings = Settings.load()

    _configure_logging(settings)

    # -- tracing / observability (graceful no-op when deps or creds absent) --
    _export_langfuse_env(settings)
    _setup_observability()

    # -- llmio provider-failover configuration ----------------------------
    # Adopt the configured failover window up front so status reads show the
    # right policy before the first turn (each agent's tier config re-adopts
    # it per call as well).
    from robotsix_llmio.config.tier import FailoverConfig
    from robotsix_llmio.core.failover import get_failover_tracker

    get_failover_tracker().configure(
        FailoverConfig(window_seconds=settings.llmio_failover_window_seconds)
    )
    logger.info(
        "llmio provider-failover window configured: %.0f seconds",
        settings.llmio_failover_window_seconds,
    )
    if not settings.openrouter_api_key.get_secret_value():
        logger.warning(
            "no llmio.api_key configured — provider failover to the keyed "
            "OpenRouter slot is unavailable; turns fail if the Claude "
            "subscription is exhausted or degraded"
        )

    # -- unified subsession system -----------------------------------------
    # One registry owns every subsession (task / periodic / user_chat, all
    # nesting depths).  Lifecycle frames go to the EventBus → GET /events →
    # browser; terminal summaries go through ParentDelivery → either the
    # owning chat session's history (parent = main chat) or the parent
    # subsession's inbox (nested).
    from robotsix_chat.subsessions import (
        CloseState,
        ParentDelivery,
        SubsessionContext,
        SubsessionEnv,
        SubsessionRegistry,
        resume_subsessions,
    )
    from robotsix_chat.subsessions.worker import attach_slot_budget

    event_bus = EventBus()

    persist_path_str = settings.conversation.persist_path
    conversation_store = ConversationStore(
        persist_path=Path(persist_path_str) if persist_path_str else None,
    )

    # Per-owner run serializer — shared between /chat requests and
    # subsession summary writes so they never overlap for the same owner.
    run_serializer = RunSerializer()

    # Shared diagnostic store — created once so agent tools and the HTTP
    # endpoint share the same in-memory instance.  Events posted via the API
    # are immediately visible to agent tools without a restart.
    diagnostic_store = DiagnosticStore(settings.diagnostics.store_path)

    # Shared knowledge store — created once so the agent tools and the
    # session-lifecycle handlers (carryover persistence) use the same instance.
    knowledge_store = KnowledgeStore(settings.knowledge.path)

    # Continuation store — shared instance so the startup hook and the
    # agent tool read/write the same pending-continuation state.
    continuation_store = ContinuationStore(
        max_consecutive=settings.continuation.max_consecutive,
    )

    subsession_registry = SubsessionRegistry(
        event_sink=event_bus,
        store_path=Path(settings.subsessions.store_path),
        transcript_max_entries=settings.subsessions.transcript_max_entries,
    )
    delivery = ParentDelivery(
        conversation_store=conversation_store,
        registry=subsession_registry,
        run_serializer=run_serializer,
        event_sink=event_bus,
    )

    # Subsession agent factory: same full tool suite as the main agent,
    # plus the depth-aware subsession tools bound to the worker's context.
    # `env` is created right after (late binding through the closure).
    def _subsession_agent_factory(
        s: Settings,
        model_level: int,
        ctx: SubsessionContext,
        close_state: CloseState,
    ) -> LlmioChatAgent:
        return create_agent_from_settings(
            settings=s,
            conversation_store=conversation_store,
            model_level=model_level,
            subsession_env=env,
            subsession_ctx=ctx,
            subsession_close_state=close_state,
            # Background subsession workers run unattended; they get
            # read-only component recall via the gated path in
            # create_agent_from_settings, never the full backend.
            memory_enabled=False,
            diagnostic_store=diagnostic_store,
            knowledge_store=knowledge_store,
        )

    env = SubsessionEnv(
        settings=settings,
        registry=subsession_registry,
        delivery=delivery,
        conversation_store=conversation_store,
        agent_factory=_subsession_agent_factory,
        event_sink=event_bus,
    )

    # Per-conversation slot-budget manager: governs how new monitors are
    # admitted when a conversation's monitor pool is at capacity (reuse a
    # paused slot, else queue — never evict a live monitor).  No-op when
    # disabled by config (monitor_slot_budget <= 0).
    attach_slot_budget(env)

    # -- periodic session agents -------------------------------------------
    # Periodic sessions run the exact same instruction and code path as an
    # operator session; the only per-preset knob is the model level. Agents
    # are cached per level so repeated firings reuse them. Full long-term
    # memory stays gated (memory.periodic_enabled) — these turns are
    # unattended and would otherwise cognify around the clock.
    _periodic_agents: dict[int | None, LlmioChatAgent] = {}

    def _periodic_agent_factory(model_level: int | None = None) -> LlmioChatAgent:
        if model_level not in _periodic_agents:
            _periodic_agents[model_level] = create_agent_from_settings(
                settings=settings,
                conversation_store=conversation_store,
                model_level=model_level
                if model_level is not None
                else settings.chat_default_model_level,
                subsession_env=env,
                event_sink=event_bus,
                # Periodic agents get read-only component recall via the
                # gated path in create_agent_from_settings.
                memory_enabled=False,
                # Unattended: no operator-instruction-only tools (repo
                # creation / forks).
                operator_attended=False,
                diagnostic_store=diagnostic_store,
                knowledge_store=knowledge_store,
            )
        return _periodic_agents[model_level]

    # Surface shipped-template presets that never reach the live config.
    check_shipped_presets(settings.periodic.sessions)
    periodic_definitions = [d for d in settings.periodic.sessions if d.enabled]
    logger.info(
        "Periodic scheduler configured (%d enabled preset(s))",
        len(periodic_definitions),
    )

    if agent is None:
        agent = create_agent_from_settings(
            settings=settings,
            conversation_store=conversation_store,
            model_level=settings.chat_default_model_level,
            subsession_env=env,
            event_sink=event_bus,
            diagnostic_store=diagnostic_store,
            knowledge_store=knowledge_store,
            continuation_store=continuation_store,
        )
    # Wire the main agent into ParentDelivery now that both exist (see
    # ParentDelivery.set_agent for why this can't happen at construction
    # time) — main-chat-parent subsession outcomes then get a real reaction
    # turn instead of a passive history record.
    delivery.set_agent(agent)

    # -- memory write-failure operator alert -------------------------------
    # robotsix-memory retains asynchronously, so a dead write path (e.g. the
    # extraction LLM's balance exhausted) never surfaces on recall and
    # POST /remember still answers 201. The periodic health run reads
    # GET /health/hindsight (ComponentMemory.refresh_write_health) and, when
    # the retain path is failing, opens ONE operator panel naming the cause
    # so the operator learns without a model needing to notice; it closes
    # automatically when writes recover.
    from robotsix_chat.memory.component import ComponentMemory

    _app_memory = getattr(agent, "memory", None)
    if isinstance(_app_memory, ComponentMemory):
        from robotsix_chat.subsessions import SubsessionKind
        from robotsix_chat.subsessions.worker import spawn_subsession

        memory_alert_session = "system-memory-health"
        memory_alert_dedup = "memory-writes-failing"

        async def _open_memory_write_panel(last_error: str) -> None:
            prompt = (
                "The long-term memory component's write (retain) path is "
                "failing, so new memories are not being persisted.\n\n"
                f"Engine error: {last_error}\n\n"
                "Detected from the component's GET /health/hindsight "
                "(retain.status=failing). Recall still works; writes do not. "
                "Likely causes include an exhausted extraction-LLM balance or "
                "a misconfigured memory backend. Investigate and tell the "
                "operator what to do. This panel closes automatically when "
                "writes recover."
            )
            try:
                spawn_subsession(
                    env=env,
                    kind=SubsessionKind.USER_CHAT,
                    owner_session_id=memory_alert_session,
                    parent_id=None,
                    depth=1,
                    title=f"Memory writes failing: {last_error}"[:200],
                    prompt=prompt,
                    model_level=settings.chat_default_model_level,
                    dedup_key=memory_alert_dedup,
                )
            except Exception:
                logger.warning("failed to open memory-write alert panel", exc_info=True)

        async def _close_memory_write_panel() -> None:
            try:
                sub_id = subsession_registry.is_dedup_key_active(memory_alert_dedup)
                if sub_id is not None:
                    subsession_registry.cancel_and_close(
                        sub_id,
                        reason="memory_writes_recovered",
                        closed_by="system",
                        summary=(
                            "Memory writes recovered — the retain path is "
                            "healthy again."
                        ),
                    )
            except Exception:
                logger.warning(
                    "failed to close memory-write alert panel", exc_info=True
                )

        _app_memory.set_write_alert_callbacks(
            on_failing=_open_memory_write_panel,
            on_recovered=_close_memory_write_panel,
        )

    # Dedicated summariser agent for the idle-timeout compaction summary,
    # the carryover summary and conversation titles (bounded text
    # transformation, not open-ended reasoning).  It runs on its own
    # capability level and — crucially — its OWN system prompt: handed the
    # chat agent's prompt it behaved as the assistant and "continued" the
    # conversation (the 2026-08-30 compaction run echoed the last reply
    # verbatim: 65k chars in, 142 tokens out).  Every level is served by
    # the keyless default slot, so no key check is needed here.  bare=True:
    # a summary is a single bounded call over an explicit transcript — it
    # has no business paying for cross-session memory recall or agentic
    # tool access (ChatMemory.recall() alone was observed taking 90+
    # seconds in production, dwarfing the actual model call).
    summary_model_level = settings.summary_model_level
    summary_agent = create_agent_from_settings(
        instruction=SUMMARY_SYSTEM_PROMPT,
        settings=settings,
        conversation_store=conversation_store,
        model_level=summary_model_level,
        bare=True,
        diagnostic_store=diagnostic_store,
        knowledge_store=knowledge_store,
    )

    # -- feedback runner ---------------------------------------------------
    feedback_runner = None
    if settings.feedback.enabled:
        if not settings.feedback.board_url:
            logger.warning(
                "Feedback runner enabled but feedback.board_url is empty — "
                "all feedback runs will be skipped until a board URL is configured"
            )
        feedback_model_level = settings.feedback.model_level
        from robotsix_chat.feedback import FEEDBACK_SYSTEM_PROMPT, FeedbackRunner

        feedback_agent = create_agent_from_settings(
            instruction=FEEDBACK_SYSTEM_PROMPT,
            settings=settings,
            conversation_store=conversation_store,
            model_level=feedback_model_level,
            bare=True,
            diagnostic_store=diagnostic_store,
            knowledge_store=knowledge_store,
        )

        # When the board rejects a feedback finding with its admission policy
        # (investigation tickets retired), the runner routes the finding to a
        # one-shot chat subsession agent that investigates/acts on it instead.
        from robotsix_chat.subsessions import SubsessionKind
        from robotsix_chat.subsessions.worker import spawn_subsession

        _feedback_subsession_level = settings.feedback.model_level

        def _spawn_feedback_investigation(
            *,
            owner_session_id: str,
            title: str,
            prompt: str,
            kind: str = "user_chat",
            dedup_key: str | None = None,
        ) -> str | None:
            # ``kind`` is a string; map it to the enum.  Feedback findings now
            # always become an operator approval panel ("user_chat"): the
            # panel investigates read-only and only opens a PR once the
            # operator approves.  ``dedup_key`` collapses the same finding
            # across runs onto the existing panel instead of a new one.
            return spawn_subsession(
                env=env,
                kind=SubsessionKind(kind),
                owner_session_id=owner_session_id,
                parent_id=None,
                depth=1,
                title=title,
                prompt=prompt,
                model_level=_feedback_subsession_level,
                dedup_key=dedup_key,
            )

        feedback_runner = FeedbackRunner(
            settings.feedback,
            feedback_agent,
            subsession_registry=subsession_registry,
            subsession_spawner=_spawn_feedback_investigation,
            conversation_store=conversation_store,
            knowledge_store=knowledge_store,
            deploy_base_url=settings.central_deploy.url,
            deploy_api_key=settings.central_deploy.deploy_api_key.get_secret_value(),
        )
        logger.info("Feedback runner enabled (model_level=%d)", feedback_model_level)
    else:
        logger.info("Feedback runner disabled (feedback.enabled=false)")

    # -- resume persisted subsessions after redeploy -----------------------
    def _resume() -> None:
        """Resume periodic subsessions; report interrupted one-shot work."""
        resume_subsessions(env)

    # -- background watcher for paused monitors ---------------------------
    async def _start_watcher() -> None:
        """Launch the paused-monitor watcher as a background task."""
        from robotsix_chat.subsessions import watch_paused_monitors

        task = asyncio.create_task(watch_paused_monitors(env))
        env._tasks.add(task)
        task.add_done_callback(env._tasks.discard)
        logger.info("Paused-monitor watcher started.")

    # -- background watcher for central-deploy caretaker findings ----------
    async def _start_caretaker_watcher() -> None:
        """Launch the model-free caretaker-findings watcher, if enabled."""
        if not settings.caretaker.enabled:
            return
        from robotsix_chat.caretaker import watch_caretaker_findings

        task = asyncio.create_task(watch_caretaker_findings(env))
        env._tasks.add(task)
        task.add_done_callback(env._tasks.discard)
        logger.info("Caretaker-findings watcher started.")

    # -- warm the memory backend off the request path ----------------------
    def _start_memory_warmup() -> None:
        """Fire the memory backend's cold start, if the backend wants one.

        Deliberately not awaited: warming may open stores and block
        tables, which takes tens of seconds, and blocking here would delay
        readiness. Backends without a ``warm`` hook (NullMemory, ReadOnlyMemory
        over one) are simply skipped.
        """
        # Both hops are probed: ``ChatAgent`` does not declare ``memory``, and
        # not every backend behind it offers a warm-up.
        warm = getattr(getattr(agent, "memory", None), "warm", None)
        if warm is None:
            return
        task = asyncio.create_task(warm())
        env._tasks.add(task)
        task.add_done_callback(env._tasks.discard)
        logger.info("Memory warm-up started in the background.")

        # Kick off periodic LanceDB compaction/pruning (startup + interval).
        # Skipped cleanly by backends without the hook (NullMemory, ReadOnly).
        start_maintenance = getattr(
            getattr(agent, "memory", None), "start_maintenance", None
        )
        if start_maintenance is not None:
            try:
                start_maintenance()
            except Exception:
                logger.exception("Memory maintenance start failed — continuing")

    # -- async startup ------------------------------------------------------
    async def _startup_async() -> None:
        """Run the connectivity check, memory warm-up, watcher, continuation."""
        await check_component_connectivity(settings.central_deploy)
        _start_memory_warmup()
        # Start the paused-monitor watcher.
        await _start_watcher()
        # Start the caretaker-findings watcher (model-free operator escalation).
        await _start_caretaker_watcher()
        # Fire any pending post-restart continuation.
        await _fire_continuation()

    async def _fire_continuation() -> None:
        """Check for a pending continuation and fire it if present.

        The continuation is one-shot (consumed on use) and guarded by
        ``max_consecutive``.  When a continuation fires, the stored prompt
        is injected into the target session as if the operator had sent it,
        and the agent's reply is recorded in the conversation history.

        Failures are logged but never crash startup — a continuation that
        cannot fire (e.g. the session was deleted) is silently dropped.
        """
        if not settings.continuation.enabled:
            return

        sid, prompt = continuation_store.consume_pending()
        if sid is None:
            return

        logger.info(
            "Firing continuation: session_id=%s prompt_preview=%r",
            sid,
            prompt[:80] if prompt else "",
        )

        # Fire as a background task so it does not block startup readiness.
        async def _run() -> None:
            try:
                # Ensure the session exists in the store and resolve its owner.
                store_session = conversation_store.get_session(sid)
                if store_session is None:
                    logger.warning(
                        "Continuation target session %s not found — dropping",
                        sid,
                    )
                    return
                owner_id = conversation_store.owner_for_session(sid) or "operator"
                # prompt is guaranteed non-None when sid is non-None.
                if prompt is None:
                    logger.warning("Continuation prompt is None — dropping")
                    return
                async with run_serializer.for_owner(owner_id):
                    reply_parts: list[str] = []
                    async for token in agent.stream(
                        prompt,
                        history=[],
                        session_id=sid,
                        client_id=sid,
                        trace_name="continuation",
                    ):
                        reply_parts.append(token)
                    full_reply = "".join(reply_parts)
                    conversation_store.record(sid, owner_id, prompt, full_reply)
                    logger.info(
                        "Continuation fired successfully: session_id=%s reply_chars=%d",
                        sid,
                        len(full_reply),
                    )
            except asyncio.CancelledError:
                logger.debug("Continuation task cancelled for session %s", sid)
            except Exception:
                logger.exception("Continuation failed for session %s — dropping", sid)

        task = asyncio.create_task(_run())
        env._tasks.add(task)
        task.add_done_callback(env._tasks.discard)

    # -- flush pending traces on shutdown ----------------------------------
    async def _flush_traces() -> None:
        """Force-flush any buffered Langfuse spans before the process exits.

        The OTel batch span processor exports on a timer (default ~30 s);
        pending spans are lost when the process exits before the next tick.
        This hook drains the buffer so interactive traces (including the
        agent's observation tree) are captured even when the server stops
        soon after a trace completes.
        """
        stop_maintenance = getattr(
            getattr(agent, "memory", None), "stop_maintenance", None
        )
        if stop_maintenance is not None:
            try:
                await stop_maintenance()
            except Exception:
                logger.exception("Memory maintenance stop failed — continuing")
        # Checkpoint and close the ladybug graph store so an interrupted WAL
        # write (a suspected corruption trigger across deploys) is avoided.
        shutdown_memory = getattr(getattr(agent, "memory", None), "shutdown", None)
        if shutdown_memory is not None:
            try:
                await shutdown_memory()
            except Exception:
                logger.exception("Memory graph-store shutdown failed — continuing")
        try:
            from robotsix_llmio.core.tracing import flush_tracing
        except ImportError:
            return
        flush_tracing()

    logger.info(
        "Resolved persistence paths: conversation=%s, knowledge=%s, "
        "diagnostics=%s, subsessions=%s",
        settings.conversation.persist_path,
        settings.knowledge.path,
        settings.diagnostics.store_path,
        settings.subsessions.store_path,
    )

    _run_server(
        agent,
        summary_agent=summary_agent,
        host=settings.server_host,
        port=settings.server_port,
        idle_timeout_minutes=settings.idle_timeout_minutes,
        max_images_per_message=settings.max_images_per_message,
        max_image_bytes=settings.max_image_bytes,
        allowed_image_media_types=settings.allowed_image_media_types,
        cors_allow_origins=settings.cors_allow_origins,
        correlation_id_header=settings.correlation_id_header,
        conversation_store=conversation_store,
        event_bus=event_bus,
        run_serializer=run_serializer,
        subsession_registry=subsession_registry,
        subsession_delivery=delivery,
        feedback_runner=feedback_runner,
        periodic_definitions=periodic_definitions,
        periodic_agent_factory=_periodic_agent_factory,
        on_startup=_resume,
        on_startup_async=_startup_async,
        on_shutdown=_flush_traces,
        direct_repo_settings=settings.direct_repo,
        central_deploy_settings=settings.central_deploy,
        github_security_settings=settings.github_security,
        github_actions_settings=settings.github_actions,
        mobile_auth=settings.mobile_auth,
        diagnostic_store=diagnostic_store,
        knowledge_store=knowledge_store,
        health_settings=settings.health,
        evergoing_settings=settings.evergoing,
        memory_component_settings=settings.memory_component,
        continuation_store=continuation_store,
    )