Files
Kigi-CLI/crates/codegen/kigi-sampler/src/handle.rs
T
ZacharyZhang-NY d6c20fc13f M0: compilable skeleton — Kigi 0.1.0 fork surgery
Hard fork of xai-org/grok-build (Apache-2.0) re-targeted as Kigi, an
unofficial Kimi Code CLI community build.

Rename & identity
- 72 xai-*/xai-grok-* crates -> kigi-* (explicit: xai-grok-pager-bin ->
  kigi-bin [binary `kigi`], xai-grok-pager -> kigi-tui; rest mechanical);
  ptyctl, ptyctl-cli, third_party/ unchanged; proto package
  xai.grok.tools.v1 -> kigi.tools.v1
- Config home ~/.kigi (KIGI_SHARE_DIR override), env prefix GROK_* ->
  KIGI_*, `kigi --version` carries the unofficial-community-build notice
- clap identity, help text, startup banner, prompt templates rebranded
  (templates re-encrypted)

Deletions (PRD removal list #5/#6/#7/#9/#10)
- voice input (xai-grok-voice) and all TUI wiring
- telemetry: Mixpanel client, external OTel stream, Sentry, OTLP layers,
  trace/GCS/S3 upload queues (kigi-file-utils halved), workspace upload
  module & dc_log, heap-profile uploader, auth-diagnostics uploader,
  session-analytics halves of feedback; local zero-egress observability
  preserved in new kigi-log crate (unified log, --debug firehose,
  subsystem file logs, opt-in instrumentation)
- announcements (crate, remote-settings fields, TUI surfaces)
- plugin marketplace (crate, sources/browse/CTA/extensions-modal tab);
  direct plugin install/uninstall/update via kigi-agent git_install kept
- relay/gateway/assets endpoints and features (agent relay, headless
  relay transport, gateway bridge, LeaderEnvUrls); leader IPC socket now
  ~/.kigi/leader.sock + KIGI_LEADER_SOCKET, no ws-url derivation
- functional types rehomed instead of deleted: PermissionMode ->
  kigi-config-types, McpInitStrategy -> kigi-mcp, PrCreationSource ->
  session signals, TerminalDiagnostics -> kigi-pager-render, agent_id ->
  shell util

Endpoints
- kigi-env rewritten: single production KigiEndpoints {coding_api_base_url
  https://api.kimi.com/coding/v1 (KIGI_CODE_BASE_URL), oauth_host
  https://auth.kimi.com (KIGI_OAUTH_HOST), update_base_url (GitHub
  Releases API), upgrade_page_url}; GrokBuildEnvironment enum deleted

Toolchain & workspace hygiene
- Rust 1.97.0 pinned; edition 2024; full cargo update; git2 hoisted to
  workspace at 0.21 (Option->Result API migration), quick-xml 0.41
- Root Cargo.toml hand-maintained (PRD §8.1): version 0.1.0 inherited by
  all members, members sorted, unused deps pruned
- cargo-deny advisories gate (deny.toml with documented transitive
  exceptions); CI workflow (check/clippy/fmt/deny/test, macOS+Linux)
- cross-crate test seams re-gated behind `test-support` cargo feature;
  insta snapshot baselines renamed to the kigi_tui prefix
- clippy --workspace --all-targets: zero warnings; fmt clean

Fixes surfaced by the port
- updater probe/installer divergence (bin/kigi vs bin/grok symlink set)
- idle model-metadata refresh dead under KIGI_CODE_BASE_URL override
  (new is_effective_coding_endpoint_url, loopback+override aware)
- macOS symlinked-TMPDIR fixture canonicalization (foreign_sessions,
  fast-worktree); RSS measurement tests serialized via serial_test

Docs & legal (Apache §4)
- NOTICE added (upstream attribution + change statement); THIRD-PARTY
  notices sustained; kigi-tools ported-code notices extended; README,
  CONTRIBUTING, SECURITY, AGENTS.md rewritten

Out of scope for M0 (tracked): Kimi auth/inference (M1), search/fetch,
command parity, config import (M2), Computer Hub excision & final
brand-token sweep (M2), distribution & self-update rewrite (M3).
2026-07-17 05:31:01 -04:00

158 lines
5.6 KiB
Rust

//! Public handle for talking to the sampler actor.
use tokio::sync::{mpsc, oneshot};
use kigi_sampling_types::{ConversationRequest, ConversationResponse, SamplingError};
use crate::commands::SamplerCommand;
use crate::config::SamplerConfig;
use crate::metrics::InferenceLatencyStats;
use crate::types::RequestId;
/// Cheaply-cloneable handle to the sampler actor.
///
/// Internally just an `mpsc::UnboundedSender<SamplerCommand>`. All
/// methods are non-blocking (fire-and-forget) except for the
/// `*_async` queries which return a future awaiting an
/// `oneshot::Receiver`.
#[derive(Clone)]
pub struct SamplerHandle {
cmd_tx: mpsc::UnboundedSender<SamplerCommand>,
}
impl SamplerHandle {
/// Construct a handle from a command sender. `pub(crate)` because
/// only [`SamplerActor::spawn`](crate::actor::SamplerActor::spawn)
/// produces one of these.
pub(crate) fn new(cmd_tx: mpsc::UnboundedSender<SamplerCommand>) -> Self {
Self { cmd_tx }
}
/// Create a no-op handle that discards all commands.
///
/// Useful for tests and callers that need a `SamplerHandle` field
/// before the actor is wired up. Mirrors
/// [`HunkTrackerHandle::noop`](https://docs.rs/kigi-hunk-tracker).
pub fn noop() -> Self {
let (cmd_tx, _cmd_rx) = mpsc::unbounded_channel();
// Receiver is dropped immediately; sends will fail but every
// send-site uses `let _ = ...` so that is fine.
Self { cmd_tx }
}
/// Submit a sampling request. Fire-and-forget -- results arrive
/// via the shared event channel.
pub fn submit(&self, request_id: RequestId, request: ConversationRequest) {
let _ = self.cmd_tx.send(SamplerCommand::Submit {
request_id,
request: Box::new(request),
config: None,
completion_tx: None,
});
}
/// Submit a sampling request with an explicit per-request config
/// override (e.g., a different model than the actor's default).
pub fn submit_with_config(
&self,
request_id: RequestId,
request: ConversationRequest,
config: SamplerConfig,
) {
let _ = self.cmd_tx.send(SamplerCommand::Submit {
request_id,
request: Box::new(request),
config: Some(Box::new(config)),
completion_tx: None,
});
}
/// Cancel an in-flight request. No-op if the request id is
/// unknown (already finished or never submitted).
pub fn cancel(&self, request_id: RequestId) {
let _ = self.cmd_tx.send(SamplerCommand::Cancel { request_id });
}
/// Update the default sampling config (e.g., after model switch
/// or auth refresh). The next request submitted without an
/// override will use it.
pub fn update_config(&self, config: SamplerConfig) {
let _ = self.cmd_tx.send(SamplerCommand::UpdateConfig {
config: Box::new(config),
});
}
/// Query whether a request is still in flight. Returns `false`
/// for unknown / finished / cancelled ids.
pub async fn is_active(&self, request_id: RequestId) -> bool {
let (reply_tx, reply_rx) = oneshot::channel();
let _ = self.cmd_tx.send(SamplerCommand::IsActive {
request_id,
reply: reply_tx,
});
reply_rx.await.unwrap_or(false)
}
/// Query the number of in-flight requests. Returns 0 if the
/// actor has been shut down.
pub async fn active_count(&self) -> usize {
let (reply_tx, reply_rx) = oneshot::channel();
let _ = self
.cmd_tx
.send(SamplerCommand::ActiveCount { reply: reply_tx });
reply_rx.await.unwrap_or(0)
}
/// Submit a request and await its completion. Events still flow
/// to the shared channel for live UI updates -- this method just
/// additionally awaits the per-request completion oneshot so the
/// caller gets a clean `Result` without filtering events.
///
/// Used by sequential callers like compaction / summary /
/// `/btw` side questions.
pub async fn submit_and_collect(
&self,
request_id: RequestId,
request: ConversationRequest,
) -> Result<(ConversationResponse, InferenceLatencyStats), SamplingError> {
// RAII guard: when this future is dropped (cancel, panic, or normal return),
// tell the sampler actor to cancel the in-flight request_id. No-op if the
// actor already finished and removed it from its active set.
struct CancelOnDrop {
cmd_tx: mpsc::UnboundedSender<SamplerCommand>,
request_id: RequestId,
}
impl Drop for CancelOnDrop {
fn drop(&mut self) {
// fire-and-forget the send.
let _ = self.cmd_tx.send(SamplerCommand::Cancel {
request_id: self.request_id.clone(),
});
}
}
let (completion_tx, completion_rx) = oneshot::channel();
let cancel_id = request_id.clone();
// Only arm the guard if Submit actually reached the actor.
let _guard = self
.cmd_tx
.send(SamplerCommand::Submit {
request_id,
request: Box::new(request),
config: None,
completion_tx: Some(completion_tx),
})
.ok()
.map(|_| CancelOnDrop {
cmd_tx: self.cmd_tx.clone(),
request_id: cancel_id,
});
completion_rx.await.unwrap_or_else(|_| {
Err(SamplingError::Auth(
"sampler actor dropped before completion".to_string(),
))
})
}
}