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. |
utils |
|
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. |
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. |
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,
index_snapshot: str | None = None,
fallback_reason: str | None = None,
behavior_contract: str = _GRAPH_BEHAVIOR_CONTRACT,
position_granularity: str = "line",
)
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: SCIPOccurrenceIndex | 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
75 76 77 78 79 80 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 | |
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,
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
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 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 | |
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
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 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 | |
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,
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,
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.)
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
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
) -> "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
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 | |
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
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 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 | |
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.