codenib.agent
¶
Agent package consolidating agent utilities and implementations.
Modules:
| Name | Description |
|---|---|
agent_types |
Data types for the agent runner. |
boundary |
Agent-boundary line-numbering conversion (issue #153). |
compile |
Agent compile: query-time skill selection. |
extract_agent |
Keyword extraction agent for problem statements. |
harness |
Declarative agent harness configuration. |
history |
Token-budgeted chat history for the agent loop (issue #109, phase 4). |
lsp_graph |
Graph-backed LSP-shaped navigation helpers. |
lsp_provider |
LSP-compatible providers over CodeNib static indexes. |
rerank_agent |
Rerank agent for ranking code nodes based on relevance to a query. |
resource_guard |
Manifest-aware resource checking for the agent. |
route_context |
Initial static-graph route context for agent runs. |
runner |
Lightweight agent runner using LLM tool calling. |
runtime |
Runtime support types for agent execution. |
skills |
Declarative skill definitions for CodeNib agents. |
tool_schema |
Convert skills and tools to OpenAI function-calling tool schemas. |
tools |
Always-on default tool primitives for the agent. |
Classes:
| Name | Description |
|---|---|
AgentResult |
Outcome of |
ToolCallRecord |
Record of a single tool invocation during an agent run. |
KeywordExtraction |
Model for keyword extraction output. |
KeywordExtractor |
Agent for extracting keywords from problem statements. |
AgentHarnessSpec |
Stable runner-facing harness contract. |
AgentRunAccumulator |
Accumulate usage and turn counts across related agent runs. |
PlainChatHistory |
Unbounded chat history with the same interface as the budgeted one. |
TokenBudgetedChatHistory |
Chat-history container that caps total context tokens. |
LSPProviderMetadata |
Trace-safe metadata describing how an LSP-shaped call was served. |
LSPProviderNodes |
List-compatible LSP result carrying provider metadata for traces. |
StaticLSPProvider |
LSP-shaped provider backed by a loaded CodeNib symbol graph. |
RerankAgent |
Agent for reranking code nodes based on query relevance using LLM APIs. |
RerankResult |
Model for reranking output. |
LSPRouteContext |
Rendered startup context produced by the static graph route. |
AgentRunner |
LLM-driven agent loop over the CodeNib skill registry. |
CodeNibAgentOptions |
Configuration for a single |
AgentRunTrace |
Durable event log for one |
AgentTraceEvent |
A replay-oriented event emitted by an agent run. |
ContextLedger |
Append-only collection of context ledger entries for one agent run. |
ContextLedgerEntry |
Bounded summary of context produced, retained, or consumed by a run. |
RepositoryContextExplorer |
Plan and execute repository search over manifest-backed CodeNib views. |
RepositoryEvidence |
One ranked source span in CodeNib's 0-based coordinate system. |
RepositoryExplorePreparation |
A deterministic query plan with all selected views loaded. |
RepositoryExplorerCapabilityError |
The selected exploration policy cannot run over the manifest. |
RepositoryExploreResult |
Ranked repository evidence and the plan that produced it. |
RepositoryExploreTrace |
Planner and execution provenance for one exploration request. |
Functions:
| Name | Description |
|---|---|
extract_keywords_from_statement |
Extract keywords from a problem statement. |
agent_working_directory |
Temporarily run agent default tools relative to cwd. |
run_agent_in_directory |
Run an |
count_message_tokens |
Best-effort token count for a list of chat messages. |
lsp_result_metadata |
Return provider metadata from a list-compatible LSP result. |
rerank_nodes_with_query |
Convenience function to rerank nodes with a query. |
build_lsp_route_context |
Run an |
canonical_lsp_route_args |
Return the canonical argument shape for a static LSP route call. |
extract_lsp_symbol_seeds |
Extract explicit symbol-like seeds from task text. |
filter_lsp_symbol_seeds |
Apply a route startup seed policy while preserving seed order. |
fingerprint_lsp_route_nodes |
Return a stable fingerprint for an ordered route-node result. |
is_specific_lsp_symbol_seed |
Return whether seed is specific enough for gated startup routing. |
normalize_lsp_route_seed_policy |
Normalize and validate the startup route seed policy. |
render_lsp_route_context |
Render route nodes as compact, unverified prompt context. |
compile_repo |
Compile indexes for repo_path ahead of time and return the manifest. |
has_localization_contract |
Return true when an answer carries the localization output contract. |
query |
Run one agent turn over a repo and return the result. |
normalize_repository_explorer_policy |
Return the canonical repository-explorer policy name. |
repository_explorer_build_views |
Return the deterministic materialization set for a benchmark policy. |
registry_to_tools |
Convert all skills in the registry to OpenAI tool schemas. |
skill_to_tool_schema |
Convert a single |
AgentResult
dataclass
¶
AgentResult(
answer: str,
tool_calls: list[ToolCallRecord] = list(),
messages: list[dict[str, Any]] = list(),
total_turns: int = 0,
total_duration_ms: float = 0.0,
usage: TokenUsage | None = None,
usage_records: list[UsageRecord] = list(),
trace: AgentRunTrace | None = None,
)
Outcome of AgentRunner.run().
ToolCallRecord
dataclass
¶
ToolCallRecord(
tool_call_id: str,
skill_id: str,
arguments: dict[str, Any],
resolved_arguments: dict[str, Any] | None = None,
result: Any = None,
duration_ms: float = 0.0,
error: str | None = None,
)
Record of a single tool invocation during an agent run.
KeywordExtraction
¶
Bases: BaseModel
Model for keyword extraction output.
KeywordExtractor
¶
KeywordExtractor(llm: LiteLLMChat)
Agent for extracting keywords from problem statements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
LiteLLMChat
|
A configured LiteLLMChat instance. |
required |
Methods:
| Name | Description |
|---|---|
extract_keywords |
Extract keywords from a problem statement. |
Source code in codenib/agent/extract_agent.py
extract_keywords
¶
extract_keywords(problem_statement: str) -> KeywordExtraction
Extract keywords from a problem statement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem_statement
|
str
|
The problem statement to extract keywords from |
required |
Returns:
| Name | Type | Description |
|---|---|---|
KeywordExtraction |
KeywordExtraction
|
Structured output with extracted keywords |
Source code in codenib/agent/extract_agent.py
AgentHarnessSpec
dataclass
¶
AgentHarnessSpec(
max_turns: int = 10,
max_context_tokens: int | None = None,
allow_skills: Collection[str] | None = None,
exclude_skills: Collection[str] | None = None,
include_default_tools: bool = True,
default_tool_ids: Collection[str] | None = None,
system_prompt: str | None = None,
first_turn_tool_choice: str | None = None,
force_first_turn_only: bool = False,
force_localization_contract: bool = False,
compact_after_read: bool = False,
compact_keep_reads: int = 0,
enable_lsp_route_context: bool = False,
lsp_route_seed_limit: int = 8,
lsp_route_seed_policy: str = "all",
lsp_route_query_fallback: bool = False,
lsp_route_top_k: int = 12,
lsp_route_include_neighbors: bool = True,
)
Stable runner-facing harness contract.
This deliberately mirrors generic :class:AgentRunner controls only. It
does not encode benchmark arms, scorer fields, model names, or dataset
identifiers, so experiments can compare policies without leaking those
policies into the core runtime API.
Methods:
| Name | Description |
|---|---|
with_overrides |
Return a copy with selected fields replaced and revalidated. |
to_runner_kwargs |
Return |
create_runner |
Build an |
with_overrides
¶
Return a copy with selected fields replaced and revalidated.
Source code in codenib/agent/harness.py
to_runner_kwargs
¶
to_runner_kwargs(
*,
session_ctx: Any | None = None,
manifest: Any | None = None,
compile_table: Any | None = None,
extra: Mapping[str, Any] | None = None
) -> dict[str, Any]
Return AgentRunner keyword arguments for this harness.
Collection fields are copied into mutable sets because AgentRunner
treats them as constructor inputs and may derive internal sets from
them. The spec remains immutable and reusable across cells/subagents.
Source code in codenib/agent/harness.py
create_runner
¶
create_runner(
*,
llm: Any | None = None,
model: str | None = None,
registry: Any | None = None,
session_ctx: Any | None = None,
manifest: Any | None = None,
compile_table: Any | None = None,
**overrides: Any
) -> Any
Build an AgentRunner using this harness.
overrides are one-off runner keyword overrides for cases like
subagents with a shorter turn budget. They do not mutate the spec.
Source code in codenib/agent/harness.py
AgentRunAccumulator
dataclass
¶
AgentRunAccumulator(
_usage_values: dict[str, list[float]] = (
lambda: {key: [] for key in USAGE_TOTAL_KEYS}
)(),
_turns: list[int] = list(),
)
Accumulate usage and turn counts across related agent runs.
A harness may charge one logical cell for several LLM interactions: routing gates, isolated subagents, verify retries, or a final convergence run. This helper keeps that accounting generic so experiment scripts do not each reimplement token/turn summation.
Methods:
| Name | Description |
|---|---|
add_usage |
Add a |
add_turns |
Add one run's turn count when it is known. |
add_result |
Add accounting fields from an |
usage_sum |
Return the sum for one usage field, or |
usage_totals |
Return flat totals with |
total_turns |
Return summed turns, or |
add_usage
¶
Add a TokenUsage or mapping with flat/nested token fields.
Source code in codenib/agent/harness.py
add_turns
¶
add_result
¶
Add accounting fields from an AgentResult-like object.
usage_sum
¶
Return the sum for one usage field, or None if never recorded.
Source code in codenib/agent/harness.py
usage_totals
¶
total_turns
¶
Return summed turns, or fallback when no turn count was added.
PlainChatHistory
¶
Unbounded chat history with the same interface as the budgeted one.
Lets :class:~codenib.agent.runner.AgentRunner use a single code path
whether or not a token budget is configured. Behaviour is identical to a
bare list of message dicts — nothing is ever evicted.
Source code in codenib/agent/history.py
TokenBudgetedChatHistory
¶
Chat-history container that caps total context tokens.
Pinned system messages are always retained. When appending a message
would push the estimated token total above max_tokens, the oldest
non-system messages are evicted one at a time (oldest first) until the
history fits again, so the system prompt plus the most recent turns are
preserved.
keep_last guards the tail: the most recent keep_last non-system
messages are never evicted even under budget pressure, so the model
always sees the immediate context it needs to act. A single message that
on its own exceeds the budget is kept (we never drop the message just
added) and a warning is logged.
The container is intentionally minimal — add_message /
get_messages / clear / __len__ / __iter__ — so the runner
can use it in place of a bare list.
Methods:
| Name | Description |
|---|---|
get_messages |
Return the live message list (the object the LLM is called with). |
clear |
Drop all messages. |
add_message |
Append message, then evict oldest non-system messages if over budget. |
extend |
Append several messages, enforcing the budget after each one. |
total_tokens |
Estimated token total of the current history. |
Source code in codenib/agent/history.py
LSPProviderMetadata
dataclass
¶
LSPProviderMetadata(
provider: str,
capability: str,
status: str,
lsp_method: str,
backend: str | None = None,
index_snapshot: str | None = None,
fallback_reason: str | None = None,
behavior_contract: str = _GRAPH_BEHAVIOR_CONTRACT,
position_granularity: str = "line",
position_encoding: str | None = None,
)
Trace-safe metadata describing how an LSP-shaped call was served.
LSPProviderNodes
¶
LSPProviderNodes(nodes: Iterable[Any] = (), *, metadata: LSPProviderMetadata)
StaticLSPProvider
¶
StaticLSPProvider(
graph: Any,
*,
snapshot_id: str | None = None,
occurrence_index: Any | None = None,
backend: str | None = None,
fallback_reason: str | None = None
)
LSP-shaped provider backed by a loaded CodeNib symbol graph.
Methods:
| Name | Description |
|---|---|
can_serve |
Return a non-throwing fast-path decision for one capability. |
definition |
Serve |
references |
Serve |
route |
Serve CodeNib's LSP-shaped route extension from the static graph. |
Source code in codenib/agent/lsp_provider.py
can_serve
¶
can_serve(capability: str) -> LSPProviderMetadata
Return a non-throwing fast-path decision for one capability.
Source code in codenib/agent/lsp_provider.py
definition
¶
definition(
*,
file_path: str | None = None,
line: int | None = None,
character: int | None = None,
symbol: str | None = None,
top_k: int = 8
) -> LSPProviderNodes
Serve textDocument/definition from the static graph.
Source code in codenib/agent/lsp_provider.py
references
¶
references(
*,
file_path: str | None = None,
line: int | None = None,
character: int | None = None,
symbol: str | None = None,
include_declaration: bool = True,
top_k: int = 40
) -> LSPProviderNodes
Serve textDocument/references from the static graph.
Source code in codenib/agent/lsp_provider.py
route
¶
route(
*,
symbols: Sequence[str],
query: str | None = None,
top_k: int = 12,
include_neighbors: bool = True
) -> LSPProviderNodes
Serve CodeNib's LSP-shaped route extension from the static graph.
Source code in codenib/agent/lsp_provider.py
RerankAgent
¶
RerankAgent(
llm: LiteLLMChat, listwise_format: Literal["structured", "rankgpt"] = "structured"
)
Agent for reranking code nodes based on query relevance using LLM APIs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
LiteLLMChat
|
A configured LiteLLMChat instance. |
required |
listwise_format
|
Literal['structured', 'rankgpt']
|
How to ask the LLM to format the ranking.
|
'structured'
|
Methods:
| Name | Description |
|---|---|
rerank_nodes |
Rerank nodes based on their relevance to the query. |
Source code in codenib/agent/rerank_agent.py
rerank_nodes
¶
rerank_nodes(
query: str,
nodes: list[NodeInfo],
top_k: int | None = None,
window_size: int | None = None,
window_step: int | None = None,
include_content: bool = False,
) -> list[QueriedNode]
Rerank nodes based on their relevance to the query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The query to rank nodes against |
required |
nodes
|
list[NodeInfo]
|
List of nodes with content to rank |
required |
top_k
|
int | None
|
Maximum number of results to return (None for all) |
None
|
window_size
|
int | None
|
Number of nodes per rerank window. None -> all nodes. |
None
|
window_step
|
int | None
|
Step size between sliding windows. Defaults to window_size. |
None
|
include_content
|
bool
|
Whether to include node content in the result objects. |
False
|
Returns:
| Type | Description |
|---|---|
list[QueriedNode]
|
List[QueriedNode]: Ranked nodes with relevance scores (optionally with content) |
Notes
When a sliding window is configured, each window is reranked independently and the averaged scores across all windows determine the final ordering.
Source code in codenib/agent/rerank_agent.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | |
RerankResult
¶
Bases: BaseModel
Model for reranking output.
LSPRouteContext
dataclass
¶
LSPRouteContext(
seeds: tuple[str, ...],
nodes: tuple[Any, ...],
text: str = "",
arguments: Mapping[str, Any] | None = None,
route_fingerprint: str | None = None,
)
Rendered startup context produced by the static graph route.
AgentRunner
¶
AgentRunner(
llm: LiteLLMChat | None = None,
registry: SkillRegistry | None = None,
*,
model: str | None = None,
temperature: float = 0.0,
max_tokens: int = 512,
system_prompt: str | None = None,
max_turns: int = 10,
max_context_tokens: int | None = None,
allow_skills: set[str] | None = None,
exclude_skills: set[str] | None = None,
manifest: Any | None = None,
session_ctx: Any | None = None,
compile_table: Any | None = None,
include_default_tools: bool = True,
default_tool_ids: set[str] | None = None,
sandbox: "SandboxSession" | None = None,
retry: RetryConfig | None = None,
force_localization_contract: bool = False,
force_final_answer: bool = False,
review_final_answer: bool = False,
first_turn_tool_choice: str | None = None,
force_first_turn_only: bool = False,
compact_after_read: bool = False,
compact_keep_reads: int = 0,
enable_lsp_route_context: bool = False,
lsp_route_seed_limit: int = 8,
lsp_route_seed_policy: str = "all",
lsp_route_query_fallback: bool = False,
lsp_route_top_k: int = 12,
lsp_route_include_neighbors: bool = True
)
LLM-driven agent loop over the CodeNib skill registry.
Usage::
from codenib.agent.skills.registry import SkillRegistry
runner = AgentRunner(model="gpt-4o", registry=SkillRegistry())
result = runner.run("How does authentication work in this repo?")
print(result.answer)
Methods:
| Name | Description |
|---|---|
run |
Execute the agent loop and return the result. |
Source code in codenib/agent/runner.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | |
run
¶
run(
query: str,
*,
max_turns: int | None = None,
chat_history: list[dict[str, str]] | None = None
) -> AgentResult
Execute the agent loop and return the result.
chat_history seeds prior conversation turns (text-only
{"role": "user"|"assistant", "content": ...} dicts, no tool
messages) between the system prompt and query, so follow-up
questions can reference earlier answers.
Source code in codenib/agent/runner.py
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 | |
CodeNibAgentOptions
dataclass
¶
CodeNibAgentOptions(
repo_path: str | None = None,
contexts: dict[str, Any] | None = None,
manifest: "RepoManifest" | str | Path | None = None,
languages: Sequence[str] = ("python",),
primary_language: str | None = None,
repo_size: int | None = None,
index_cache_dir: str | None = None,
embedding_model: str = DEFAULT_EMBEDDING_MODEL,
embedding_dimension: int = DEFAULT_EMBEDDING_DIMENSION,
default_top_k: int = 10,
default_level: str = "l2",
rebuild_indexes: bool = False,
skills_dir: str | None = None,
native_index_authorization: "NativeIndexAuthorization" | None = None,
native_index_authorization_resolver: (
Callable[["IndexEntry"], "NativeIndexAuthorization" | None] | None
) = None,
allowed_skills: list[str] | None = None,
excluded_skills: list[str] | None = None,
compile_table: CompileTableInput | None = None,
skill_params: dict[str, dict[str, Any]] | None = None,
llm: LiteLLMChat | None = None,
model: str | None = None,
temperature: float = 0.0,
max_tokens: int = 512,
system_prompt: str | None = None,
max_turns: int = 10,
max_context_tokens: int | None = None,
enable_lsp_route_context: bool = False,
lsp_route_seed_limit: int = 8,
lsp_route_seed_policy: str = "all",
lsp_route_query_fallback: bool = False,
lsp_route_top_k: int = 12,
lsp_route_include_neighbors: bool = True,
retry: RetryConfig | None = None,
sandbox: "SandboxSession" | None = None,
session_extras: dict[str, Any] = dict(),
)
Configuration for a single query() invocation.
Exactly one of repo_path, contexts, or manifest must
be set — these are the three mutually-exclusive ways to tell
query() where its indexes come from:
repo_path→query()calls :func:~codenib.compiler.build_skill_contextsitself and caches indexes underindex_cache_dir(or<repo>/.codenib_cache). The "build once at first query" path.contexts→ caller pre-built the contexts dict (advanced; see :func:~codenib.compiler.build_skill_contexts/ :func:~codenib.compiler.load_contexts_from_manifestfor what shape to pass).manifest→ caller compiled indexes ahead of time via :func:~codenib.agent.compile_repo(or :class:~codenib.compiler.IndexCompilerdirectly) and passes either a loaded :class:~codenib.compiler.RepoManifestor a path string torepo_manifest.json. The AoT (ahead-of-time) path:query()loads the artifacts named in the manifest and threads the manifest itself intoAgentRunnerso :class:~codenib.agent.resource_guard.ResourceGuardcan run freshness checks. No inline build happens.
Skill selection forms a three-layer funnel::
registry ⊇ allowed_skills ⊇ compile_table[scenario]
compile_table narrows allowed_skills per query but never
broadens it (see :func:codenib.agent.compile.agent_compile).
compile_table also operates at the index-build stage (for
repo_path mode only): when set, only indexes for skills it ever
names are compiled. Formally::
index_skills = allowed_skills ∩ union(compile_table.values())
A vector index isn't built if every scenario in the table maps to
bm25-only, even when embedding_search is in allowed_skills —
CAR couldn't route to it at runtime anyway. (In manifest mode
this rule is moot — the manifest dictates what exists.)
Native vector parsers are fail-closed. Pass either an already-bound
native_index_authorization or a
native_index_authorization_resolver that receives the exact manifest
IndexEntry about to be loaded. The two options are mutually exclusive;
neither can be derived from manifest fields by the agent runtime.
AgentRunTrace
dataclass
¶
AgentRunTrace(
events: list[AgentTraceEvent] = list(),
context: ContextLedger = ContextLedger(),
start_monotonic: float = monotonic(),
)
Durable event log for one AgentRunner.run() invocation.
AgentTraceEvent
dataclass
¶
AgentTraceEvent(
kind: str,
turn: int,
data: dict[str, Any] = dict(),
timestamp_ms: float | None = None,
)
A replay-oriented event emitted by an agent run.
The trace is intentionally descriptive, not prescriptive: events explain what happened during runtime without encoding benchmark scoring or promotion policy.
ContextLedger
¶
ContextLedger(entries: Sequence[ContextLedgerEntry] | None = None)
ContextLedgerEntry
dataclass
¶
ContextLedgerEntry(
source: str,
state: str,
turn: int,
summary: str = "",
path: str | None = None,
tool_call_id: str | None = None,
entry_id: str | None = None,
provenance: dict[str, Any] = dict(),
freshness: str | None = None,
token_estimate: int | None = None,
cost_estimate: float | None = None,
consumed_by: list[str] = list(),
consumed_turn: int | None = None,
metadata: dict[str, Any] = dict(),
)
Bounded summary of context produced, retained, or consumed by a run.
Methods:
| Name | Description |
|---|---|
mark_consumed |
Record that this context entry was consumed by a later runtime step. |
mark_expired |
Record that this context entry left the active working set. |
mark_consumed
¶
Record that this context entry was consumed by a later runtime step.
Source code in codenib/agent/runtime/context.py
mark_expired
¶
Record that this context entry left the active working set.
Source code in codenib/agent/runtime/context.py
RepositoryContextExplorer
¶
RepositoryContextExplorer(
context: Any,
*,
policy: str = "auto",
budget: BudgetInput = "balanced",
level: str = "l2",
_owns_context: bool = False
)
Plan and execute repository search over manifest-backed CodeNib views.
auto plans against manifest-advertised capabilities and loads only the
selected query path. Explicit policies provide stable ablation arms. The
class never materializes indexes; callers build views separately.
Methods:
| Name | Description |
|---|---|
from_manifest |
Bind to a manifest without eagerly loading retrieval views. |
from_repository |
Resolve the manifest bound to one checkout and create an explorer. |
close |
Release resources loaded by a manifest-constructed explorer. |
explore |
Return bounded, source-validated evidence for one context request. |
prepare |
Plan a query and load only the views selected for that plan. |
Source code in codenib/agent/runtime/explorer.py
from_manifest
classmethod
¶
from_manifest(
manifest_path: str | Path,
*,
policy: str = "auto",
budget: BudgetInput = "balanced",
level: str = "l2"
) -> RepositoryContextExplorer
Bind to a manifest without eagerly loading retrieval views.
Source code in codenib/agent/runtime/explorer.py
from_repository
classmethod
¶
from_repository(
repo_path: str | Path,
*,
manifest_path: str | Path | None = None,
policy: str = "auto",
budget: BudgetInput = "balanced",
level: str = "l2"
) -> RepositoryContextExplorer
Resolve the manifest bound to one checkout and create an explorer.
Source code in codenib/agent/runtime/explorer.py
close
¶
Release resources loaded by a manifest-constructed explorer.
explore
¶
explore(
query: str,
*,
top_k: int = 10,
include_content: bool = False,
budget: BudgetInput | None = None
) -> RepositoryExploreResult
Return bounded, source-validated evidence for one context request.
Source code in codenib/agent/runtime/explorer.py
prepare
¶
prepare(
query: str, *, budget: BudgetInput | None = None
) -> RepositoryExplorePreparation
Plan a query and load only the views selected for that plan.
Source code in codenib/agent/runtime/explorer.py
RepositoryEvidence
dataclass
¶
RepositoryEvidence(
path: str,
start_line: int,
end_line: int,
score: float,
node_name: str = "",
node_type: str = "",
node_id: str | None = None,
content: str | None = None,
)
One ranked source span in CodeNib's 0-based coordinate system.
RepositoryExplorePreparation
dataclass
¶
RepositoryExplorePreparation(
query: str,
plan: RetrievalPathPlan,
signals: QuerySignals,
budget: RetrievalBudget,
capabilities: RetrievalCapabilities,
)
A deterministic query plan with all selected views loaded.
RepositoryExplorerCapabilityError
¶
Bases: RuntimeError
The selected exploration policy cannot run over the manifest.
RepositoryExploreResult
dataclass
¶
RepositoryExploreResult(
evidence: tuple[RepositoryEvidence, ...], trace: RepositoryExploreTrace | None
)
Ranked repository evidence and the plan that produced it.
RepositoryExploreTrace
dataclass
¶
RepositoryExploreTrace(
policy: str,
plan: RetrievalPathPlan,
signals: QuerySignals,
budget: RetrievalBudget,
capabilities: RetrievalCapabilities,
advertised_views: tuple[str, ...],
loaded_views: tuple[str, ...],
stage_candidate_counts: tuple[tuple[str, int], ...],
retrieved_candidates: int,
returned_evidence: int,
)
Planner and execution provenance for one exploration request.
extract_keywords_from_statement
¶
extract_keywords_from_statement(
problem_statement: str, llm: LiteLLMChat
) -> KeywordExtraction
Extract keywords from a problem statement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem_statement
|
str
|
The problem statement to extract keywords from. |
required |
llm
|
LiteLLMChat
|
A configured LiteLLMChat instance. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
KeywordExtraction |
KeywordExtraction
|
Structured output with extracted keywords |
Source code in codenib/agent/extract_agent.py
agent_working_directory
¶
Temporarily run agent default tools relative to cwd.
The built-in read/grep/glob tools intentionally accept repo-relative paths. Harnesses that run against many repos should scope the process cwd around each runner invocation and always restore it afterwards.
Source code in codenib/agent/harness.py
run_agent_in_directory
¶
Run an AgentRunner-like object with repo-relative default tools.
count_message_tokens
¶
Best-effort token count for a list of chat messages.
Uses litellm.token_counter (which understands the model's real
tokenizer and per-message role overhead) when a model is supplied
and litellm is importable. Falls back to a chars / 4 heuristic
otherwise, so this never raises and stays usable in offline tests.
Source code in codenib/agent/history.py
lsp_result_metadata
¶
Return provider metadata from a list-compatible LSP result.
Source code in codenib/agent/lsp_provider.py
rerank_nodes_with_query
¶
rerank_nodes_with_query(
query: str,
nodes: list[NodeInfo],
llm: LiteLLMChat,
top_k: int | None = None,
window_size: int | None = None,
window_step: int | None = None,
include_content: bool = False,
) -> list[QueriedNode]
Convenience function to rerank nodes with a query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The query to rank nodes against. |
required |
nodes
|
list[NodeInfo]
|
List of nodes with content to rank. |
required |
llm
|
LiteLLMChat
|
A configured LiteLLMChat instance. |
required |
top_k
|
int | None
|
Maximum number of results to return (None for all). |
None
|
window_size
|
int | None
|
Optional sliding window size for reranking. |
None
|
window_step
|
int | None
|
Optional stride between sliding windows. |
None
|
include_content
|
bool
|
Whether to include node content in the result objects. |
False
|
Returns:
| Type | Description |
|---|---|
list[QueriedNode]
|
List[QueriedNode]: Ranked nodes with relevance scores |
Source code in codenib/agent/rerank_agent.py
build_lsp_route_context
¶
build_lsp_route_context(
executor: Any,
query: str,
*,
explicit_seeds: Any = None,
seed_limit: int = 8,
seed_policy: str | None = "all",
query_fallback: bool = False,
top_k: int = 12,
include_neighbors: bool = True
) -> LSPRouteContext
Run an lsp_route executor and render startup context.
Source code in codenib/agent/route_context.py
canonical_lsp_route_args
¶
canonical_lsp_route_args(
*,
symbols: Iterable[Any],
query: Any = None,
top_k: Any = 12,
include_neighbors: Any = True
) -> dict[str, Any]
Return the canonical argument shape for a static LSP route call.
Source code in codenib/agent/route_context.py
extract_lsp_symbol_seeds
¶
Extract explicit symbol-like seeds from task text.
The extractor is intentionally conservative. It keeps user-supplied explicit seeds first, then adds backtick-delimited code names and code-like tokens from the task text. It does not inspect repository contents or benchmark labels.
Source code in codenib/agent/route_context.py
filter_lsp_symbol_seeds
¶
Apply a route startup seed policy while preserving seed order.
Source code in codenib/agent/route_context.py
fingerprint_lsp_route_nodes
¶
Return a stable fingerprint for an ordered route-node result.
Source code in codenib/agent/route_context.py
is_specific_lsp_symbol_seed
¶
Return whether seed is specific enough for gated startup routing.
Source code in codenib/agent/route_context.py
normalize_lsp_route_seed_policy
¶
Normalize and validate the startup route seed policy.
Source code in codenib/agent/route_context.py
render_lsp_route_context
¶
render_lsp_route_context(
seeds: Sequence[str], nodes: Sequence[Any], *, max_nodes: int | None = None
) -> str
Render route nodes as compact, unverified prompt context.
Source code in codenib/agent/route_context.py
compile_repo
¶
compile_repo(
repo_path: str,
*,
index_types: Sequence[str] = ("bm25",),
languages: Sequence[str] = ("python",),
cache_dir: str | None = None,
embedding_model: str = DEFAULT_EMBEDDING_MODEL,
embedding_dimension: int = DEFAULT_EMBEDDING_DIMENSION,
source_selection: RepositorySourceSelection | None = None
) -> "RepoManifest"
Compile indexes for repo_path ahead of time and return the manifest.
Thin convenience wrapper over :class:~codenib.compiler.IndexCompiler
that registers the default index builders for the requested
languages and writes <cache_dir>/repo_manifest.json.
Pair with :func:query to run the agent against the result without
re-indexing on every call::
manifest = compile_repo(
"/path/to/repo",
index_types=("bm25", "vector"),
languages=("python",),
)
result = query(
"where is auth wired up?",
options=CodeNibAgentOptions(
manifest=manifest,
allowed_skills=["bm25_search", "embedding_search"],
),
)
For advanced cases — custom builder registries, partial rebuilds —
use :class:~codenib.compiler.IndexCompiler directly.
Source code in codenib/agent/runner.py
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 | |
has_localization_contract
¶
Return true when an answer carries the localization output contract.
Source code in codenib/agent/runner.py
query
¶
query(prompt: str, *, options: CodeNibAgentOptions | None = None) -> AgentResult
Run one agent turn over a repo and return the result.
See :class:CodeNibAgentOptions for the full options surface,
including the three mutually-exclusive index-source modes
(repo_path, contexts, manifest).
Raises:
| Type | Description |
|---|---|
ValueError
|
if not exactly one of |
Source code in codenib/agent/runner.py
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 | |
normalize_repository_explorer_policy
¶
Return the canonical repository-explorer policy name.
Source code in codenib/agent/runtime/explorer.py
repository_explorer_build_views
¶
Return the deterministic materialization set for a benchmark policy.
Source code in codenib/agent/runtime/explorer.py
registry_to_tools
¶
registry_to_tools(
registry: SkillRegistry | None = None,
*,
allow: set[str] | None = None,
exclude: set[str] | None = None
) -> list[dict[str, Any]]
Convert all skills in the registry to OpenAI tool schemas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
SkillRegistry | None
|
Registry to read from; defaults to the singleton. |
None
|
allow
|
set[str] | None
|
If provided, only skills in this set are included (allowlist,
applied first). If |
None
|
exclude
|
set[str] | None
|
Skill IDs to skip (denylist, applied after |
None
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of tool dicts ready for |
Source code in codenib/agent/tool_schema.py
skill_to_tool_schema
¶
skill_to_tool_schema(meta: SkillMetadata) -> dict[str, Any]
Convert a single SkillMetadata to an OpenAI function tool dict.