kcode-kennedy-orchestration 0.1.0

Typed orchestration and session-control runtime for Kennedy
Documentation
# kcode-kennedy-orchestration

`kcode-kennedy-orchestration` owns Kennedy's shared typed session control and
non-transport scheduling. It composes manuals, opens/restores logical sessions,
coordinates checkpoints and stop/cancellation state, and runs browser commands,
history ingress, self-time, and audio synchronization. Telegram event, group,
delivery, rollover, and wakeup scheduling belongs to
`kcode-kennedy-telegram-runtime`, which consumes this crate's shared control.

## Re-exported session API

The crate re-exports `kcode_kennedy_sessions::AgentMode`, `RuntimeModel`,
`Session`, and `Service` under the name `SessionService`. Their fields, variants,
methods, and error contracts are unchanged; this crate adds no wrapper session
model.

## Configuration and capabilities

`Config` has five public fields:

- `system_prompts_directory`: directory containing Kennedy's required manuals.
- `user_root_node_id` and `kennedy_root_node_id`: validated canonical system
  roots, encoded as strings for session state.
- `telegram_max_media_bytes`: copied into restored Telegram channel state so
  session tools preserve the transport's object-size limit.
- `runtime_model`: selected model, reasoning effort, and context window.

`LocalServices` is the construction-only capability bundle. Its public fields
are `kmap`, `intelligence`, `history`, `audio`, `directory`, `dev_tools`, and
`telegram`, holding the corresponding in-process service handles. The app must
provide handles from the same process and persistence graph.

`ApiError` has public `code` and `message` fields and implements `Display` and
`Error`. Expected history/identity conflicts use `state_conflict`; missing data
uses `not_found`; bad input uses `invalid_request`; unexpected failures use
`internal_error`. Provider cancellation retains `operation_cancelled`.

`Api::new` binds `LocalServices` and the two configured roots into a clonable
typed façade. Its complete public method surface is:

- Kweb/model control: `kmap_node`, `user_root_node_id`,
  `kennedy_root_node_id`, and `cancel_intelligence`.
- Session History: `history_health`, `history_list`, `history_get_session`,
  `history_register`, `history_command_heads`, `history_claim_command`,
  `history_complete_command`, `history_listen_for_stop`, `history_stop_heads`,
  `history_complete_stop`, `history_checkpoint`, `history_request_ingress`,
  `history_start_ingress`, `history_complete_ingress`, `history_fail_ingress`,
  `history_complete`, and `history_release_interrupted_ingress`.
- Identity and source cleanup: `directory_user`, `directory_group`, and
  `release_managed_sources`. Release failure is logged rather than returned so
  cleanup cannot replace the owning session outcome.
- Telegram coordination: `telegram_user_lock`, `telegram_health`,
  `telegram_private_sessions`, `telegram_events`, `telegram_group_ingress`,
  `telegram_complete_group_ingress`, `telegram_group_session_updates`,
  `telegram_complete_silent_group_reset`,
  `telegram_acknowledge_group_context`, `telegram_detach_group_session`,
  `telegram_save_group_message_preparation`, `telegram_bind_event`,
  `telegram_reply_event`, `telegram_abort_event`, `telegram_interrupt_event`,
  `telegram_complete_reset`, `telegram_event_media`,
  `telegram_group_message_media`, `telegram_group_message_media_metadata`, and
  `telegram_send_object`.
- Media/application synchronization: `extract_document` and
  `synchronize_audio_ingress`.

All fallible methods return `ApiError` without exposing subsystem-internal
diagnostics where the underlying owner classifies the failure as internal.
Mutating methods preserve the owning subsystem's durable idempotency and state
transition contracts.

## Manuals

`Manuals` is a cloneable validated prompt set. `Manuals::load` reads all twelve
required files and rejects missing or blank content. `compose_conversation`
selects conversation, self-time, or wakeup instructions and layers Telegram
manuals only for Telegram channels. `compose_ingress` selects audio or history
ingress instructions and retains Telegram group context when applicable. Both
append the current runtime description and return an error when a required
section is absent.

## Shared runtime state

`SessionRuntime` is the initialized snapshot used to open sessions. Its public
fields are `model`, `user_root_node_id`, and `kennedy_root_node_id`; the validated
manuals remain private so callers cannot bypass prompt composition.

`TurnCompletion` has `Finished` and `Stopped` variants. `Stopped` means a Session
History stop listener won the turn race and the model operation was cancelled;
the caller must checkpoint the session's interruption before completing the
owning external work.

## Orchestrator

`Orchestrator::new` accepts `Config`, `Api`, and `SessionService`.
`initialize_until_ready` serializes concurrent callers and retries root,
history, prompt, and interrupted-ingress readiness exactly once until
successful. `runtime` returns the initialized snapshot or an error before
readiness. `run` initializes, then schedules browser commands,
history ingress, self-time, and audio synchronization until failure or
cancellation.

The shared control methods are:

- `api` and `writer`, which borrow the façade and global Kweb writer mutex.
- `open_session`, which composes the correct prompt and creates/restores the
  one authoritative session implementation.
- `pending_stop`, `complete_pending_stop`, `operation_is_active`,
  `register_operation`, and `remove_operation`, which coordinate externally
  visible stop state with model operation IDs.
- `run_session_turn`, which runs a pending turn with caller-supplied async
  checkpoints while racing the durable stop listener.
- `list_history`, `get_conversation`, and `get_listed_conversation`; the last
  returns `None` when a previously listed record has completed and disappeared.
- `conversation_lock`, which returns the shared per-session mutex used by every
  transport runtime.
- `session_for_record`, which restores a logical session from current history
  state and repairs compatibility defaults without changing durable state.
- `close_conversation` and `request_conversation_ingress`, which release managed
  sources and make the versioned transition into history ingress.

`build` returns an `Arc<Orchestrator>` and `run` is the equivalent free-function
lifecycle adapter used by the top-level app.

`persist_record` checkpoints a versioned `SessionRecord`; an identical state
already stored after `state_conflict` is idempotent success, while a different
state remains an error. `data_url` encodes media bytes for model input.
`telegram_caption_for` returns the exact supplied text only when its UTF-16
length and native Telegram media kind permit a caption.

## Ownership and concurrency

Session History owns durable records and commands; Telegram transport owns its
queues; Kweb Manager owns graph state. The orchestrator serializes conflicting
work per conversation, shares active-operation cancellation across runtimes,
and provides one writer mutex for all Kweb-mutating background work. Focused
runtimes may schedule outer work but must use this control rather than implement
a second session/checkpoint lifecycle.