Files
Kigi-CLI/crates/codegen/kigi-shell/src/util/config/resolve/system_prompt.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

167 lines
5.2 KiB
Rust

pub const ENV_SYSTEM_PROMPT_LABEL: &str = "KIGI_SYSTEM_PROMPT_LABEL";
pub const DEFAULT_SYSTEM_PROMPT_LABEL: &str = kigi_agent::DEFAULT_SYSTEM_PROMPT_LABEL;
/// Resolve system-prompt identity label.
/// Precedence: env → config per-model → `[agent]` → GB per-model → GB global →
/// `"Grok"`. Empty/whitespace falls through.
///
/// Per-model TOML is looked up by session catalog id, then routing slug
/// (`ModelInfo.model`). Do not use CLI `-m` alone — it may outlive a mid-session
/// model switch.
pub fn resolve_system_prompt_label(
cfg: &crate::agent::config::Config,
model_id: &str,
model: Option<&crate::agent::config::ModelInfo>,
) -> String {
let label_for = |key: &str| {
cfg.config_models
.get(key)
.and_then(|m| m.system_prompt_label.clone())
};
let user_per_model =
label_for(model_id).or_else(|| model.map(|m| m.model.as_str()).and_then(label_for));
resolve_system_prompt_label_from_tiers(
user_per_model,
cfg.agent.system_prompt_label.clone(),
model.and_then(|m| m.system_prompt_label.clone()),
cfg.remote_settings
.as_ref()
.and_then(|r| r.system_prompt_label.clone()),
)
}
pub fn resolve_system_prompt_label_from_tiers(
user_per_model: Option<String>,
user_global: Option<String>,
gb_per_model: Option<String>,
gb_global: Option<String>,
) -> String {
let non_empty = |s: Option<String>| {
s.and_then(|v| {
let t = v.trim();
(!t.is_empty()).then(|| t.to_string())
})
};
std::env::var(ENV_SYSTEM_PROMPT_LABEL)
.ok()
.and_then(|s| non_empty(Some(s)))
.or_else(|| non_empty(user_per_model))
.or_else(|| non_empty(user_global))
.or_else(|| non_empty(gb_per_model))
.or_else(|| non_empty(gb_global))
.unwrap_or_else(|| DEFAULT_SYSTEM_PROMPT_LABEL.to_string())
}
#[cfg(test)]
mod system_prompt_label_tests {
use super::{
DEFAULT_SYSTEM_PROMPT_LABEL, ENV_SYSTEM_PROMPT_LABEL,
resolve_system_prompt_label_from_tiers,
};
/// Serialize access to `KIGI_SYSTEM_PROMPT_LABEL` and clear it for tier tests.
/// `env_wins_over_all_tiers` mutates the env; without this lock, parallel tests
/// that expect the var unset (e.g. `gb_per_model_beats_gb_global`) flake.
fn with_env_cleared<R>(f: impl FnOnce() -> R) -> R {
let _guard = ENV_LOCK.lock().unwrap();
let prev = std::env::var(ENV_SYSTEM_PROMPT_LABEL).ok();
// Safety: test-only, locked.
unsafe { std::env::remove_var(ENV_SYSTEM_PROMPT_LABEL) };
let r = f();
match prev {
Some(v) => unsafe { std::env::set_var(ENV_SYSTEM_PROMPT_LABEL, v) },
None => unsafe { std::env::remove_var(ENV_SYSTEM_PROMPT_LABEL) },
}
r
}
#[test]
fn default_when_all_unset() {
with_env_cleared(|| {
assert_eq!(
resolve_system_prompt_label_from_tiers(None, None, None, None),
DEFAULT_SYSTEM_PROMPT_LABEL
);
});
}
#[test]
fn per_model_beats_global_and_gb() {
with_env_cleared(|| {
assert_eq!(
resolve_system_prompt_label_from_tiers(
Some("PerModel".into()),
Some("Global".into()),
Some("GbPer".into()),
Some("GbGlobal".into()),
),
"PerModel"
);
});
}
#[test]
fn global_beats_gb() {
with_env_cleared(|| {
assert_eq!(
resolve_system_prompt_label_from_tiers(
None,
Some("Global".into()),
Some("GbPer".into()),
Some("GbGlobal".into()),
),
"Global"
);
});
}
#[test]
fn gb_per_model_beats_gb_global() {
with_env_cleared(|| {
assert_eq!(
resolve_system_prompt_label_from_tiers(
None,
None,
Some("GbPer".into()),
Some("GbGlobal".into()),
),
"GbPer"
);
});
}
#[test]
fn empty_and_whitespace_fall_through() {
with_env_cleared(|| {
assert_eq!(
resolve_system_prompt_label_from_tiers(
Some(" ".into()),
Some("".into()),
None,
Some("GbGlobal".into()),
),
"GbGlobal"
);
});
}
#[test]
fn env_wins_over_all_tiers() {
let _guard = ENV_LOCK.lock().unwrap();
// Safety: test-only, locked.
unsafe { std::env::set_var(ENV_SYSTEM_PROMPT_LABEL, "FromEnv") };
let got = resolve_system_prompt_label_from_tiers(
Some("PerModel".into()),
Some("Global".into()),
Some("GbPer".into()),
Some("GbGlobal".into()),
);
unsafe { std::env::remove_var(ENV_SYSTEM_PROMPT_LABEL) };
assert_eq!(got, "FromEnv");
}
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
}