Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
271 changes: 271 additions & 0 deletions ARCHITECTURE.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
The most RAM efficient harness <br>
The most intelligent harness

> **Fork note:** This is a [KooshaPari](https://github.com/KooshaPari) fork of [1jehuang/jcode](https://github.com/1jehuang/jcode). Latest fork release: **v0.85.0-k1.0.0**.
> **Fork note:** This is a [KooshaPari](https://github.com/KooshaPari) fork of [1jehuang/jcode](https://github.com/1jehuang/jcode). Latest fork release: **v0.85.1-k1.1.1**.

<a href="https://trendshift.io/repositories/25042?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-25042" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/25042" alt="1jehuang/jcode | Trendshift" width="250" height="55"></a>

Expand Down Expand Up @@ -52,7 +52,7 @@ bun run --bun https://jcode.sh/install_bun.sh
```

```bash
# GitHub Packages (replace <version> with desired release, e.g. 0.85.0-k1.0.0)
# GitHub Packages (replace <version> with desired release, e.g. 0.85.1-k1.1.1)
docker pull ghcr.io/KooshaPari/jcode/jcode-linux-x86_64:<version>
```

Expand Down
44 changes: 44 additions & 0 deletions crates/jcode-app-core/examples/print_build_info.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//! Print the build manifest and current-version metadata.
//!
//! `jcode_app_core::build` re-exports the build metadata the
//! `jcode-build-support` crate computes at compile time (git hash,
//! build time, current version) and at runtime (current build
//! symlink, stable vs canary status). All of the harness / HERDR
//! code that says "this is the running binary's identity" reads
//! from this surface.
//!
//! Run with: `cargo run -p jcode-app-core --example print_build_info`
//!
//! All build-info functions take a repo dir (or none, for the
//! `current_version_file()` static path) and return `Result<_>`;
//! the example uses the current working directory as the repo dir
//! and unwraps to keep the call sites readable.

use std::path::Path;

use jcode_app_core::build::{
current_build_info, current_git_diff, current_git_hash, current_git_hash_full,
current_source_state, current_version_file, is_working_tree_dirty,
};

fn main() {
let repo = Path::new(".");

let info = current_build_info(repo).expect("current_build_info");
println!("current_build_info:");
println!(" hash: {}", info.hash);
println!(" full_hash: {}", info.full_hash);
println!(" built_at: {}", info.built_at);
println!(" commit_message: {:?}", info.commit_message);
println!(" dirty: {}", info.dirty);
println!(" version_label: {:?}", info.version_label);
println!(" source_fingerprint: {:?}", info.source_fingerprint);

println!();
println!("current_git_hash: {}", current_git_hash(repo).expect("current_git_hash"));
println!("current_git_hash_full: {}", current_git_hash_full(repo).expect("current_git_hash_full"));
println!("current_git_diff: {}", current_git_diff(repo).expect("current_git_diff"));
println!("current_source_state: {:?}", current_source_state(repo).expect("current_source_state"));
println!("is_working_tree_dirty: {}", is_working_tree_dirty(repo).expect("is_working_tree_dirty"));
println!("current_version_file: {:?}", current_version_file().expect("current_version_file"));
}
29 changes: 29 additions & 0 deletions crates/jcode-config-types/examples/round_trip_enums.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//! Round-trip the `CompactionMode` and `AgentMode` enums through JSON.
//!
//! These are the two enums the harness reads from runtime config to
//! decide *when* to compact the transcript and *what role* the agent
//! plays. They also serialize to lowercase strings so they can live in
//! the `JCODE_OPENAI_NATIVE_COMPACTION_MODE` and `JCODE_AGENT_MODE`
//! env vars (see `docs/ENVIRONMENT.md`).
//!
//! Run with: `cargo run -p jcode-config-types --example round_trip_enums`

use jcode_config_types::{AgentMode, CompactionMode};

fn main() {
for mode in [CompactionMode::Reactive, CompactionMode::Proactive] {
let s = serde_json::to_string(&mode).expect("serialize");
let back: CompactionMode = serde_json::from_str(&s).expect("deserialize");
assert_eq!(mode, back);
println!("CompactionMode::{mode:?} -> {s}");
}

println!();

for mode in [AgentMode::Execute, AgentMode::Manager] {
let s = serde_json::to_string(&mode).expect("serialize");
let back: AgentMode = serde_json::from_str(&s).expect("deserialize");
assert_eq!(mode, back);
println!("AgentMode::{mode:?} -> {s}");
}
}
35 changes: 34 additions & 1 deletion crates/jcode-config-types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,23 @@ pub use keybindings::{
keybinding_default, keybinding_defaults_report, validate_keybinding_defaults,
};

/// Compaction mode
/// Compaction mode: when and how should the agent shrink its transcript
/// into a shorter summary before sending it to the model again.
///
/// The workspace supports three policies:
/// - [`Reactive`](CompactionMode::Reactive) (default): wait until the
/// context budget is exhausted, then summarize.
/// - [`Proactive`](CompactionMode::Proactive): estimate the next-turn
/// growth rate (from the tool-definitions, message-rate, and recent
/// output size) and preemptively compact before the budget runs out.
/// - [`Semantic`](CompactionMode::Semantic): re-rank messages by
/// topic-shift and relevance scoring so that compaction keeps the
/// highest-signal turns even when many turns share a topic.
///
/// The choice is exposed at runtime via the
/// `JCODE_OPENAI_NATIVE_COMPACTION_MODE` env var
/// (see [`crates/jcode-base/src/config/env_overrides.rs`]) and
/// serialized to JSON in lowercase.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum CompactionMode {
Expand Down Expand Up @@ -43,6 +59,23 @@ impl CompactionMode {
}

/// Agent operating mode: controls what the agent is allowed to do.
///
/// Three modes gate the tool surface:
/// - [`Execute`](AgentMode::Execute) (default): autonomous implementation
/// — read, edit, build, commit, push, open PRs. Tools are unrestricted.
/// - [`Manager`](AgentMode::Manager): plans, delegates via swarm,
/// reviews worker output. Cannot write files or run build commands
/// directly (`write`, `edit`, `multiedit`, `apply_patch`, `patch`,
/// `gmail` are all blocked — see
/// [`AgentMode::is_tool_blocked`]). Used for
/// the coordinator role in [`crate::SwarmRole::Coordinator`].
/// - [`Researcher`](AgentMode::Researcher): read-only. May read, search,
/// run tests, but never modifies the workspace. Used by the web search
/// and analysis tools, and by ambient/autojudge workers.
///
/// The choice is serialized in lowercase ("execute", "manager",
/// "researcher") on the wire; `parse` accepts a few short aliases
/// ("exec", "mgr", "res", "research") for ergonomics.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum AgentMode {
Expand Down
34 changes: 34 additions & 0 deletions crates/jcode-core/examples/smoke.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//! Exercise the small utilities in `jcode_core` (the
//! dependency-light primitives crate).
//!
//! Demonstrates:
//! - `id::new_id` — generate a prefixed unique id
//! - `id::new_memorable_session_id` — generate a two-word memorable
//! session id and the round-trip `extract_session_name` helper
//! - `util::truncate_str` — byte-safe truncation
//! - `util::estimate_tokens` — rough 4-chars-per-token estimator
//!
//! Run with: `cargo run -p jcode-core --example smoke`

use jcode_core::id;
use jcode_core::util;

fn main() {
let prefixed = id::new_id("agent");
println!("id::new_id(\"agent\") = {prefixed}");

let (session_id, name) = id::new_memorable_session_id();
println!("id::new_memorable_session_id() = {session_id} (name = {name})");

let recovered = id::extract_session_name(&session_id).unwrap_or("<none>");
assert_eq!(recovered, name);
println!("id::extract_session_name round-trip: {recovered}");

let long = "a".repeat(120);
let truncated = util::truncate_str(&long, 20);
println!("util::truncate_str(120 chars, 20) -> len {} ({:?})", truncated.len(), truncated);

let sample = "the quick brown fox jumps over the lazy dog";
let est = util::estimate_tokens(sample);
println!("util::estimate_tokens(\"{sample}\") = {est} tokens (rough 4c/tok)");
}
50 changes: 50 additions & 0 deletions crates/jcode-herdr/examples/round_trip_state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//! Round-trip the `AgentState` enum and read the HERDR environment
//! snapshot the jcode pane would use.
//!
//! `jcode_herdr` is the jcode end of the HERDR cross-harness terminal
//! multiplexer. The interesting public surface for newcomers:
//!
//! - `AgentState` — the three-state lifecycle HERDR panes report:
//! `Working`, `Idle`, `Blocked`
//! - `HerdrEnv` — the parsed view of the `HERDR_*` env vars the
//! pane sets when it launches jcode
//!
//! Run with: `cargo run -p jcode-herdr --example round_trip_state`
//!
//! The env snapshot is read at construction time; if you want to
//! exercise it, run the example with the relevant vars set, e.g.:
//!
//! ```text
//! HERDR_BIN_PATH=/usr/local/bin/herdr \
//! HERDR_SOCKET_PATH=/tmp/herdr.sock \
//! HERDR_PANE_ID=pane-1 \
//! HERDR_TAB_ID=tab-1 \
//! HERDR_WORKSPACE_ID=ws-1 \
//! cargo run -p jcode-herdr --example round_trip_state
//! ```

use jcode_herdr::state::AgentState;
use jcode_herdr::HerdrEnv;

fn main() {
for state in [AgentState::Working, AgentState::Idle, AgentState::Blocked] {
let s = state.as_str();
let back = match s {
"working" => AgentState::Working,
"idle" => AgentState::Idle,
"blocked" => AgentState::Blocked,
other => panic!("unexpected AgentState str: {other}"),
};
assert_eq!(state, back);
println!("AgentState::{state:?} -> {s:?}");
}

println!();

let env = HerdrEnv::capture();
println!("HerdrEnv::capture():");
println!(" is_valid: {}", env.is_valid());
println!(" pane_id: {:?}", env.pane_id());
println!(" socket_path: {:?}", env.socket_path());
println!(" pane_id_or_empty:{:?}", env.pane_id_or_empty());
}
40 changes: 40 additions & 0 deletions crates/jcode-protocol/examples/serialize_history_message.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//! Serialize a `HistoryMessage` and round-trip it through JSON.
//!
//! Demonstrates the wire shape of the most-used DTO in
//! `jcode_protocol::HistoryMessage` and the four-value
//! `TranscriptMode` enum. The point is to be the smallest possible
//! "hello, world" for a downstream SDK that wants to talk to a
//! running jcode server over the protocol socket.
//!
//! Run with: `cargo run -p jcode-protocol --example serialize_history_message`

use jcode_protocol::{HistoryMessage, TranscriptMode};

fn main() {
let original = HistoryMessage {
role: "user".to_string(),
content: "Show me the recent session activity.".to_string(),
response_stats: None,
tool_calls: None,
tool_data: None,
};

let json = serde_json::to_string(&original).expect("serialize");
println!("serialized:");
println!(" {json}");

let parsed: HistoryMessage = serde_json::from_str(&json).expect("deserialize");
assert_eq!(parsed.role, original.role);
assert_eq!(parsed.content, original.content);
println!("round-trip: ok (role + content match)");

for mode in [
TranscriptMode::Insert,
TranscriptMode::Append,
TranscriptMode::Replace,
TranscriptMode::Send,
] {
let s = serde_json::to_string(&mode).expect("serialize enum");
println!(" TranscriptMode::{mode:?} -> {s}");
}
}
27 changes: 26 additions & 1 deletion crates/jcode-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ pub use memory_snapshots::{
MemoryStepStatusSnapshot,
};

/// How a transcript message should be merged into the running
/// conversation history.
///
/// Used by the protocol's inter-session handoff path so that a session
/// resuming from a snapshot can either
/// [`Insert`](TranscriptMode::Insert) at an arbitrary position,
/// [`Append`](TranscriptMode::Append) to the tail,
/// [`Replace`](TranscriptMode::Replace) a previous message (used for
/// stream rescans and mid-turn correction), or
/// [`Send`](TranscriptMode::Send) (default — leaves history
/// untouched and just transmits the new message). The wire form is
/// snake_case.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum TranscriptMode {
Expand All @@ -47,7 +59,20 @@ pub enum CommDeliveryMode {
Wake,
}

/// A message in conversation history (for sync)
/// A single message in a session's conversation history, used by the
/// cross-session sync surface.
///
/// Every front-end ([`jcode-tui`], [`jcode-sdk`], web clients reading
/// from `jcode-harness-api`) reads and writes sessions as a `Vec<HistoryMessage>`.
/// The fields are deliberately JSON-friendly and omit empty optionals:
/// - `role` and `content` are always present (a "role" of `""` is the
/// sentinel for a system event such as a tool-call result).
/// - `tool_calls` carries the list of tool-call names the assistant
/// invoked in this turn; absent when the message has no tool calls.
/// - `tool_data` holds the actual structured [`ToolCall`] payload when
/// needed for replay.
/// - `response_stats` is set when the provider returned token telemetry
/// for this turn; surfaces use it to render per-turn cost.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoryMessage {
#[serde(default, skip_serializing_if = "Option::is_none")]
Expand Down
50 changes: 50 additions & 0 deletions crates/jcode-provider-core/examples/smoke.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//! Smoke test the small helper APIs in `jcode_provider_core`.
//!
//! `jcode_provider_core` is the trait-and-selection layer that every
//! concrete `jcode-provider-<name>-runtime` crate implements. It also
//! exposes pure helpers that don't need a live HTTP client — useful
//! for unit tests and for callers that want to roll their own
//! transport:
//!
//! - `fingerprint::stable_hash_str` / `stable_hash_json` — stable
//! hashes for prompt-cache break detection
//! - `retry_after::retry_delay` — exponential backoff with a
//! server-supplied hint, identical to the production formula
//!
//! Run with: `cargo run -p jcode-provider-core --example smoke`

use jcode_provider_core::fingerprint::{stable_hash_json, stable_hash_str};
use jcode_provider_core::retry_after::retry_delay;
use serde_json::json;
use std::time::Duration;

fn main() {
let h1 = stable_hash_str("hello world");
let h2 = stable_hash_str("hello world");
let h3 = stable_hash_str("goodbye world");
assert_eq!(h1, h2);
assert_ne!(h1, h3);
println!("stable_hash_str h1 == h2: {h1} == {h2}");
println!("stable_hash_str h3: {h3}");

let j = json!({ "model": "claude-3", "messages": ["hi"] });
let hj = stable_hash_json(&j);
println!("stable_hash_json: {hj}");

println!();
println!("retry_delay(attempt, base=200ms, no server hint):");
for attempt in 0..6 {
let d = retry_delay(attempt, 200, None);
println!(" attempt {attempt} -> {} ms", d.as_millis());
}

println!();
println!("retry_delay(attempt, base=200ms, server hint=5s):");
for attempt in 0..6 {
let d = retry_delay(attempt, 200, Some(Duration::from_secs(5)));
println!(
" attempt {attempt} -> {} ms (server-hint-respecting)",
d.as_millis()
);
}
}
20 changes: 20 additions & 0 deletions crates/jcode-provider-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,26 @@ use std::time::Duration;
pub type EventStream = Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send>>;

/// Provider trait for LLM backends.
///
/// Every backend that can serve chat-completion requests implements this
/// trait. The harness is provider-agnostic at the call site: any code
/// that wants tokens just holds `Arc<dyn Provider>` and calls
/// [`complete`](Provider::complete) or
/// [`complete_split`](Provider::complete_split). Each implementor is
/// responsible for translating the workspace's neutral
/// [`Message`]/[`ToolDefinition`] model into whatever the upstream API
/// actually wants (Anthropic Messages, OpenAI Chat Completions,
/// Gemini generateContent, OpenAI-compat profiles, etc.).
///
/// The trait is intentionally narrow — it only covers the streaming
/// completion contract plus the small set of identity-metadata
/// accessors (`name`, `model`, `display_name`, `active_auth_method_*`)
/// that the TUI, billing, and info-widget surfaces key off. Storage,
/// retry, model selection, failover, pricing, and reasoning-effort
/// logic live in sibling modules (`selection`, `failover`, `fallback_pick`,
/// `pricing`, `reasoning`, `attempt_tracker`, `retry_after`, ...) so the
/// trait itself stays a stable contract for downstream `jcode-provider-*`
/// crates.
// async_trait adds must_use to methods returning an already must-use boxed Future.
#[allow(clippy::double_must_use)]
#[async_trait]
Expand Down
Loading
Loading