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).
This commit is contained in:
2026-07-17 05:31:01 -04:00
commit d6c20fc13f
2612 changed files with 1353757 additions and 0 deletions
+126
View File
@@ -0,0 +1,126 @@
//! Agent spawning — creates the agent process and ACP channels.
//!
//! Simplified to only support GrokShell (in-process) mode.
//! Subprocess and remote modes can be added later if needed.
use std::rc::Rc;
use std::thread;
use anyhow::Result;
use tokio_util::sync::CancellationToken;
use kigi_acp_lib::{
AcpAgentChannel, AcpClientChannel, AcpClientTx, AcpGatewayReceiver, AcpGatewaySender,
acp_channels,
};
use kigi_shell::{
agent::{MvpAgent, config::Config as AgentConfig, models::RefreshStrategy},
auth::AuthManager,
util::kigi_home::kigi_home,
};
/// Result of spawning a child agent.
pub struct SpawnedAgent {
/// Kept alive so the thread isn't detached. Will be used for graceful shutdown.
pub _thread_handle: thread::JoinHandle<Result<()>>,
pub channel: AcpClientChannel,
pub cancel: CancellationToken,
/// The agent's `AuthManager`, shared so pager-side consumers
/// channel) resolve the same refreshing bearer as chat traffic.
pub auth_manager: std::sync::Arc<AuthManager>,
}
/// Spawn a GrokShell agent in a background thread.
///
/// Returns the ACP client channel for communication and a cancellation token.
pub async fn spawn_grok_shell(
agent_config: AgentConfig,
cancel: &CancellationToken,
memory_config: Option<kigi_shell::config::MemoryConfig>,
) -> Result<SpawnedAgent> {
let auth_manager = std::sync::Arc::new(AuthManager::new(
&kigi_home(),
agent_config.grok_com_config.clone(),
));
auth_manager.configure_refresher(agent_config.grok_com_config.auth_provider_command.clone());
// Pause token refreshes across system sleep so an OIDC refresh can't
// straddle a suspend (which can revoke the refresh token and force
// re-login). No-op where the OS listener is unavailable.
auth_manager.start_system_power_listener();
// Best-effort refresh of managed policy before bootstrap reads it (repairs a wrong-identity/missing
// cache). Never errors — the OS-protected system/MDM layers still apply.
kigi_shell::managed_config::ensure_managed_policy_present(&auth_manager).await;
// Run the full bootstrap sequence: config resolution, process-level
// singletons (including `extract_bundled_files` which writes compiled-in
// skills to ~/.kigi/skills/), and model catalog construction.
let (agent_config, models_manager) =
kigi_shell::agent::init::bootstrap(&agent_config, &auth_manager, None)
.map_err(|e| anyhow::anyhow!(e))?;
models_manager
.list_models(RefreshStrategy::OnlineIfUncached)
.await;
let agent_cancel = cancel.child_token();
let (acp_client, acp_agent) = acp_channels();
// Clone before `auth_manager` is moved into the agent closure below, so the
// pager can share the same refreshing bearer.
let auth_manager_for_pager = auth_manager.clone();
let spawn_fn: Box<dyn FnOnce(AcpClientTx) -> Result<Rc<MvpAgent>> + Send + 'static> = {
Box::new(move |client_tx| {
let gateway = AcpGatewaySender::new(client_tx);
let mut agent =
MvpAgent::with_models(gateway, &agent_config, auth_manager, models_manager);
if let Some(mc) = memory_config {
agent.set_memory_config(mc);
}
Ok(Rc::new(agent))
})
};
// Spawn the agent thread with direct dispatch
let handle = spawn_agent_thread_direct(spawn_fn, acp_agent, agent_cancel.clone())?;
Ok(SpawnedAgent {
_thread_handle: handle,
channel: acp_client,
cancel: agent_cancel,
auth_manager: auth_manager_for_pager,
})
}
/// Spawn an agent in a dedicated thread with direct RPC dispatch.
///
/// The agent runs on a single-threaded tokio LocalSet runtime.
/// RPC requests go directly to the agent via Rc, bypassing simplex pipes.
fn spawn_agent_thread_direct(
spawn_agent: Box<dyn FnOnce(AcpClientTx) -> Result<Rc<MvpAgent>> + Send + 'static>,
channel: AcpAgentChannel,
cancel: CancellationToken,
) -> Result<thread::JoinHandle<Result<()>>> {
Ok(thread::Builder::new()
.name("acp-agent-worker".into())
.spawn(move || -> Result<()> {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
let local = tokio::task::LocalSet::new();
local.block_on(&rt, async move {
let client_tx = channel.tx.clone();
let agent_rc = spawn_agent(client_tx)?;
// Direct dispatch: RPC requests go straight to the agent
let gw_rx = AcpGatewayReceiver::new(channel.rx, agent_rc).with_tracing(true);
tokio::task::spawn_local(gw_rx.run());
tokio::task::yield_now().await;
// Keep running until cancelled
cancel.cancelled().await;
anyhow::Result::Ok(())
})
})?)
}