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:
@@ -0,0 +1,225 @@
|
||||
//! `x.ai/auth/*` and legacy `x.ai/{get,set}ApiKey` extension handlers.
|
||||
//!
|
||||
//! These methods let the client read/write the API key via the agent and
|
||||
//! drive the OAuth login flow. The agent is the single source of truth for
|
||||
//! `auth.json`.
|
||||
|
||||
use agent_client_protocol as acp;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{ExtResult, parse_params, to_raw_response};
|
||||
use crate::agent::MvpAgent;
|
||||
use crate::session::ExtMethodResult;
|
||||
|
||||
#[tracing::instrument(skip_all, fields(method = %args.method))]
|
||||
pub async fn handle(agent: &MvpAgent, args: &acp::ExtRequest) -> ExtResult {
|
||||
match args.method.as_ref() {
|
||||
"x.ai/auth/getBearerToken" => handle_get_bearer_token(agent).await,
|
||||
"x.ai/getApiKey" => handle_get_api_key(),
|
||||
"x.ai/setApiKey" => handle_set_api_key(args),
|
||||
"x.ai/auth/submit_code" => handle_submit_code(agent, args),
|
||||
"x.ai/auth/get_url" => handle_get_url(agent).await,
|
||||
"x.ai/auth/logout" => handle_logout(agent, args).await,
|
||||
"x.ai/auth/info" => handle_info(agent),
|
||||
"x.ai/auth/check_subscription" => handle_check_subscription(agent).await,
|
||||
_ => Err(acp::Error::method_not_found()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_get_bearer_token(agent: &MvpAgent) -> ExtResult {
|
||||
let token = match agent.auth_manager.get_valid_token().await {
|
||||
Ok(token) => Some(token),
|
||||
Err(_) => agent
|
||||
.sampling_config
|
||||
.borrow()
|
||||
.api_key
|
||||
.clone()
|
||||
.or_else(|| agent.auth_manager.current().map(|a| a.key)),
|
||||
};
|
||||
ExtMethodResult::success(serde_json::json!({ "token": token }))
|
||||
.to_ext_response()
|
||||
.map_err(|e| acp::Error::internal_error().data(e.to_string()))
|
||||
}
|
||||
|
||||
fn handle_get_api_key() -> ExtResult {
|
||||
let key = crate::agent::auth_method::read_xai_api_key_env().ok();
|
||||
ExtMethodResult::success(serde_json::json!({ "key": key }))
|
||||
.to_ext_response()
|
||||
.map_err(|e| acp::Error::internal_error().data(e.to_string()))
|
||||
}
|
||||
|
||||
fn handle_set_api_key(args: &acp::ExtRequest) -> ExtResult {
|
||||
let params: serde_json::Value = parse_params(args)?;
|
||||
let key = params.get("key").and_then(|v| v.as_str());
|
||||
let kigi_home = crate::util::kigi_home::kigi_home();
|
||||
if let Some(k) = key {
|
||||
if k.is_empty() {
|
||||
crate::auth::clear_api_key(&kigi_home)
|
||||
.map_err(|e| acp::Error::internal_error().data(e.to_string()))?;
|
||||
// SAFETY: ext_method is single-threaded per agent
|
||||
unsafe { std::env::remove_var("XAI_API_KEY") };
|
||||
} else {
|
||||
crate::auth::store_api_key(&kigi_home, k)
|
||||
.map_err(|e| acp::Error::internal_error().data(e.to_string()))?;
|
||||
// SAFETY: ext_method is single-threaded per agent
|
||||
unsafe { std::env::set_var("XAI_API_KEY", k) };
|
||||
}
|
||||
} else {
|
||||
crate::auth::clear_api_key(&kigi_home)
|
||||
.map_err(|e| acp::Error::internal_error().data(e.to_string()))?;
|
||||
// SAFETY: ext_method is single-threaded per agent
|
||||
unsafe { std::env::remove_var("XAI_API_KEY") };
|
||||
}
|
||||
ExtMethodResult::success(serde_json::json!({ "ok": true }))
|
||||
.to_ext_response()
|
||||
.map_err(|e| acp::Error::internal_error().data(e.to_string()))
|
||||
}
|
||||
|
||||
/// Handle auth code submission from TUI.
|
||||
fn handle_submit_code(agent: &MvpAgent, args: &acp::ExtRequest) -> ExtResult {
|
||||
#[derive(Deserialize)]
|
||||
struct SubmitCodeParams {
|
||||
code: String,
|
||||
}
|
||||
|
||||
let params: SubmitCodeParams = serde_json::from_str(args.params.get())
|
||||
.map_err(|e| acp::Error::invalid_params().data(format!("invalid params: {e}")))?;
|
||||
|
||||
let auth_code_tx = agent.auth_code_tx.borrow();
|
||||
if let Some(ref tx) = *auth_code_tx {
|
||||
tx.try_send(params.code).map_err(|e| {
|
||||
acp::Error::internal_error().data(format!("failed to submit auth code: {e}"))
|
||||
})?;
|
||||
to_raw_response(&serde_json::json!({ "submitted": true }))
|
||||
} else {
|
||||
Err(acp::Error::invalid_params().data("no pending auth session"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Awaits the auth URL from the oneshot channel (blocks until ready).
|
||||
async fn handle_get_url(agent: &MvpAgent) -> ExtResult {
|
||||
let rx = agent.auth_url_rx.borrow_mut().take();
|
||||
// `None` when no URL was sent (cached creds, early error, second poll):
|
||||
// report mode as `null` rather than mislabeling it `loopback`.
|
||||
let (auth_url, mode) = match rx {
|
||||
Some(rx) => match rx.await {
|
||||
Ok(info) => (Some(info.url), Some(info.mode)),
|
||||
Err(_) => (None, None),
|
||||
},
|
||||
None => (None, None),
|
||||
};
|
||||
to_raw_response(&serde_json::json!({
|
||||
"auth_url": auth_url,
|
||||
// `external_provider` kept for older clients; `mode` is authoritative.
|
||||
"external_provider": mode.is_some_and(|m| m.is_external_provider()),
|
||||
"mode": mode.map(|m| m.as_wire_str()),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn handle_logout(agent: &MvpAgent, args: &acp::ExtRequest) -> ExtResult {
|
||||
#[derive(Deserialize)]
|
||||
struct LogoutParams {
|
||||
scope: Option<String>,
|
||||
}
|
||||
|
||||
let params: LogoutParams = serde_json::from_str(args.params.get())
|
||||
.map_err(|e| acp::Error::invalid_params().data(format!("invalid params: {e}")))?;
|
||||
|
||||
let result = crate::auth::perform_logout(&agent.auth_manager, params.scope.as_deref())
|
||||
.map_err(|e| acp::Error::internal_error().data(format!("failed to logout: {e}")))?;
|
||||
// `auth.lifecycle` (not `auth`) avoids colliding with the pre-existing
|
||||
// per-request `AuthManager::auth()` `#[instrument]` span.
|
||||
tracing::info_span!("auth.lifecycle", action = "logout", success = true).in_scope(|| {});
|
||||
|
||||
agent.models_manager.on_auth_changed().await;
|
||||
|
||||
to_raw_response(&serde_json::json!({
|
||||
"ok": true,
|
||||
"was_logged_in": result.was_logged_in,
|
||||
"email": result.email,
|
||||
"api_key_still_set": result.api_key_still_set,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Single-shot subscription re-check (retry button on paywall screen).
|
||||
///
|
||||
/// Calls `retry_subscription_check()`, then returns the updated auth
|
||||
/// response with gate info so the pager can refresh the gate state.
|
||||
async fn handle_check_subscription(agent: &MvpAgent) -> ExtResult {
|
||||
agent.retry_subscription_check().await;
|
||||
let response = agent.auth_response_with_meta();
|
||||
to_raw_response(&serde_json::json!({
|
||||
"authenticated": response.meta.is_some(),
|
||||
"meta": response.meta,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Returns current auth method ID, user profile fields, and team/principal
|
||||
/// metadata.
|
||||
fn handle_info(agent: &MvpAgent) -> ExtResult {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct AuthInfoResponse {
|
||||
method_id: Option<String>,
|
||||
email: Option<String>,
|
||||
first_name: Option<String>,
|
||||
last_name: Option<String>,
|
||||
/// `grok-asset://` URL resolved by the Electron protocol handler,
|
||||
/// or a full `http(s)://` URL passed through unchanged.
|
||||
profile_image_url: Option<String>,
|
||||
team_id: Option<String>,
|
||||
team_name: Option<String>,
|
||||
team_role: Option<String>,
|
||||
organization_id: Option<String>,
|
||||
organization_name: Option<String>,
|
||||
organization_role: Option<String>,
|
||||
principal_type: Option<String>,
|
||||
principal_id: Option<String>,
|
||||
user_blocked_reason: Option<String>,
|
||||
team_blocked_reasons: Vec<String>,
|
||||
coding_data_retention_opt_out: bool,
|
||||
}
|
||||
|
||||
let method_id = agent
|
||||
.auth_method_id
|
||||
.load()
|
||||
.as_ref()
|
||||
.map(|m| m.0.to_string());
|
||||
let auth = agent.auth_manager.current();
|
||||
let raw_asset_id = auth.as_ref().and_then(|a| a.profile_image_asset_id.clone());
|
||||
|
||||
// Return a grok-asset:// URL that the Electron renderer resolves at
|
||||
// display time via a custom protocol handler. The handler proxies
|
||||
// through cli-chat-proxy's /asset endpoint; Electron's HTTP cache
|
||||
// handles reuse. No disk-cache or network call needed here.
|
||||
let profile_image_url = match raw_asset_id.as_deref().filter(|k| !k.is_empty()) {
|
||||
Some(key) if key.starts_with("http://") || key.starts_with("https://") => {
|
||||
Some(key.to_owned())
|
||||
}
|
||||
Some(key) => Some(format!("grok-asset:///{key}")),
|
||||
None => None,
|
||||
};
|
||||
to_raw_response(&AuthInfoResponse {
|
||||
method_id,
|
||||
email: auth.as_ref().and_then(|a| a.email.clone()),
|
||||
first_name: auth.as_ref().and_then(|a| a.first_name.clone()),
|
||||
last_name: auth.as_ref().and_then(|a| a.last_name.clone()),
|
||||
profile_image_url,
|
||||
team_id: auth.as_ref().and_then(|a| a.team_id.clone()),
|
||||
team_name: auth.as_ref().and_then(|a| a.team_name.clone()),
|
||||
team_role: auth.as_ref().and_then(|a| a.team_role.clone()),
|
||||
organization_id: auth.as_ref().and_then(|a| a.organization_id.clone()),
|
||||
organization_name: auth.as_ref().and_then(|a| a.organization_name.clone()),
|
||||
organization_role: auth.as_ref().and_then(|a| a.organization_role.clone()),
|
||||
principal_type: auth.as_ref().and_then(|a| a.principal_type.clone()),
|
||||
principal_id: auth.as_ref().and_then(|a| a.principal_id.clone()),
|
||||
user_blocked_reason: auth.as_ref().and_then(|a| a.user_blocked_reason.clone()),
|
||||
team_blocked_reasons: auth
|
||||
.as_ref()
|
||||
.map(|a| a.team_blocked_reasons.clone())
|
||||
.unwrap_or_default(),
|
||||
coding_data_retention_opt_out: auth
|
||||
.as_ref()
|
||||
.is_some_and(|a| a.coding_data_retention_opt_out),
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user