diff --git a/.changes/agent-tool-composition.fixed.md b/.changes/agent-tool-composition.fixed.md new file mode 100644 index 00000000..c6f0c953 --- /dev/null +++ b/.changes/agent-tool-composition.fixed.md @@ -0,0 +1 @@ +SDK 默认提供核心 Agent 工具。服务在启动扩展前显式注册 Agent Query 的交付工具,工具目录不再依赖模块导入顺序。 diff --git a/app/business/sink/agent_query.py b/app/business/sink/agent_query.py index 31b2ac46..adfc10bf 100644 --- a/app/business/sink/agent_query.py +++ b/app/business/sink/agent_query.py @@ -71,14 +71,17 @@ class AgentQueryResultMissingError(RuntimeError): """A normal Agent Turn ended without delivering its required result.""" -@AgentManager.tool( - SUBMIT_QUERY_RESULT_TOOL, - description="Submit the answer to this information need and its supporting entities.", -) async def submit_query_result(input: AgentQueryResult) -> JSONValue: return typing.cast(JSONValue, input.model_dump(mode="json")) +def register_agent_query_tool() -> None: + AgentManager.tool( + SUBMIT_QUERY_RESULT_TOOL, + description="Submit the answer to this information need and its supporting entities.", + )(submit_query_result) + + class AgentQuerySink( SinkBase[AgentQueryConfig], sink_type=AGENT_QUERY_SINK_TYPE, diff --git a/docs/30-unit-tdd/agent-query-sink.md b/docs/30-unit-tdd/agent-query-sink.md index 8ab1fd19..7856ade1 100644 --- a/docs/30-unit-tdd/agent-query-sink.md +++ b/docs/30-unit-tdd/agent-query-sink.md @@ -67,8 +67,8 @@ The generic read tools are controllers beside their semantic owners. They adapt domain services; they do not move retrieval, Resolver, or graph behavior into Agent Query. `submit_query_result` alone is Sink-owned because delivery is the Sink's behavior. -`submit_query_result` participates in the explicit `register_core_agent_tools()` bootstrap. It is available before any -Sink instance is enabled, and registration does not depend on importing Sink REST routes. +The service registers `submit_query_result` in runtime bootstrap before loading extensions or enabling Sink instances. +The SDK's built-in Tool catalog contains only core-owned Tools. The first version reads text/JSON and already-derived media text. It does not invoke raw multimodal interpretation, create a second query/result store, persist Thread history, or add a new Peer capability. diff --git a/inkcre_core/business/agent/AGENTS.md b/inkcre_core/business/agent/AGENTS.md index cee9ab90..b550fbae 100644 --- a/inkcre_core/business/agent/AGENTS.md +++ b/inkcre_core/business/agent/AGENTS.md @@ -12,8 +12,9 @@ transport policy. ToolCall message together with its complete ToolResult message in one backend append. - Runtime validates Tool inputs once with the bound Pydantic model. Use Pydantic's validation detail directly. Tool return shape is a static type-checking contract, not a second runtime schema. -- Tool registration is decorator-owned. Exact persisted Tool IDs have set semantics and are bound once per new Thread; - later registry changes do not rewrite existing Thread schemas or handlers. +- Tool owners export value definitions for the SDK catalog. Application-owned tools register during runtime startup. + Exact persisted Tool IDs have set semantics and are bound once per new Thread. Later registry changes do not rewrite + existing Thread schemas or handlers. - Tool handlers are owner-local controllers: they own Agent input/result projection and call ordinary domain services. Do not move domain behavior into this subtree or create a central `agent_tools` business package. The durable boundary is documented in `docs/30-unit-tdd/business-pipeline-and-authority.md`. diff --git a/inkcre_core/business/agent/bootstrap.py b/inkcre_core/business/agent/bootstrap.py index 0f69e4e4..c8f5cdf0 100644 --- a/inkcre_core/business/agent/bootstrap.py +++ b/inkcre_core/business/agent/bootstrap.py @@ -1,16 +1,30 @@ -"""Explicit registration entrypoint for core-owned Agent Tool controllers.""" +"""Compose the SDK catalog from owner-local Agent Tool definitions.""" +from collections.abc import Mapping +from functools import cache +from types import MappingProxyType -def register_core_agent_tools() -> None: - """Import every core Tool owner, independent of HTTP Sink delivery. +from .contracts import AgentToolRegistration, DuplicateAgentToolRegistrationError + + +@cache +def core_agent_tools() -> Mapping[str, AgentToolRegistration]: + from inkcre_core.business.graph_navigation_retrieval import tools as graph + from inkcre_core.business.info_base import tools as info_base + from inkcre_core.business.info_base.resolver import tools as resolver + from inkcre_core.business.organization import tools as organization - Decorators register Tools when their modules load; Python's import cache makes - repeated bootstrap calls harmless. Entry points must call this explicitly, - rather than rely on routes or package re-exports importing the owners first. - """ - from inkcre_core.business.graph_navigation_retrieval import tools as _graph_tools - from inkcre_core.business.info_base import tools as _info_base_tools - from inkcre_core.business.info_base.resolver import tools as _resolver_tools - from inkcre_core.business.organization import tools as _organization_tools + catalog: dict[str, AgentToolRegistration] = {} + for owner in (graph, info_base, resolver, organization): + for tool in owner.AGENT_TOOLS: + if tool.tool_id in catalog: + raise DuplicateAgentToolRegistrationError( + f"Core Agent Tool {tool.tool_id!r} is defined more than once" + ) + catalog[tool.tool_id] = tool + return MappingProxyType(catalog) - del _graph_tools, _info_base_tools, _resolver_tools, _organization_tools + +def register_core_agent_tools() -> None: + """Warm the SDK catalog for callers of the legacy bootstrap API.""" + core_agent_tools() diff --git a/inkcre_core/business/agent/contracts.py b/inkcre_core/business/agent/contracts.py index 5e5e05e5..d6b03142 100644 --- a/inkcre_core/business/agent/contracts.py +++ b/inkcre_core/business/agent/contracts.py @@ -4,6 +4,7 @@ from collections.abc import Awaitable, Callable from dataclasses import dataclass +import inspect import typing import pydantic @@ -57,3 +58,65 @@ class BoundAgentTool: definition: FunctionTool input_model: type[pydantic.BaseModel] handler: AgentToolHandler + + +@dataclass(frozen=True) +class AgentToolRegistration: + """An exact Tool definition owned by the module that implements it.""" + + tool_id: str + handler: AgentToolHandler + description: str + input_model: type[pydantic.BaseModel] + input_model_factory: AgentToolInputModelFactory | None + + @classmethod + def from_handler( + cls, + handler: typing.Callable[..., object], + tool_id: str, + *, + description: str, + input_model_factory: AgentToolInputModelFactory | None = None, + ) -> AgentToolRegistration: + if not tool_id: + raise AgentToolBindingError("Agent Tool ID must not be empty") + signature = inspect.signature(handler) + parameters = tuple(signature.parameters.values()) + if len(parameters) != 1: + raise AgentToolBindingError( + f"Agent Tool {tool_id!r} handler must accept exactly one input model" + ) + hints = typing.get_type_hints(handler) + annotation = hints.get(parameters[0].name) + if not isinstance(annotation, type) or not issubclass(annotation, pydantic.BaseModel): + raise AgentToolBindingError( + f"Agent Tool {tool_id!r} input must be annotated with a Pydantic model" + ) + return cls( + tool_id=tool_id, + handler=typing.cast(AgentToolHandler, handler), + description=description, + input_model=annotation, + input_model_factory=input_model_factory, + ) + + def bind(self) -> BoundAgentTool: + input_model = ( + self.input_model_factory() + if self.input_model_factory is not None + else self.input_model + ) + if not isinstance(input_model, type) or not issubclass(input_model, pydantic.BaseModel): + raise AgentToolBindingError( + f"Agent Tool {self.tool_id!r} did not produce a Pydantic input model" + ) + return BoundAgentTool( + definition=FunctionTool( + id=self.tool_id, + description=self.description, + input_schema=input_model.model_json_schema(), + ), + input_model=input_model, + handler=self.handler, + ) diff --git a/inkcre_core/business/agent/main.py b/inkcre_core/business/agent/main.py index 5a6a776c..4fdeb7f8 100644 --- a/inkcre_core/business/agent/main.py +++ b/inkcre_core/business/agent/main.py @@ -2,12 +2,8 @@ from __future__ import annotations -from dataclasses import dataclass -import inspect import typing -import pydantic - from inkcre_core.business.ai import AIExecutionRequirement, AIManager from inkcre_core.schemas import AgentDefinitionModel from inkcre_core.schemas.agent import AgentID, AgentForm, AgentUpdateForm @@ -15,11 +11,12 @@ from inkcre_core.persistence.agent.uow import agent_uow +from .bootstrap import core_agent_tools from .contracts import ( AgentNotFoundError, AgentToolBindingError, - AgentToolHandler, AgentToolInputModelFactory, + AgentToolRegistration, BoundAgentTool, DuplicateAgentToolRegistrationError, MissingAgentToolError, @@ -36,39 +33,10 @@ HandlerT = typing.TypeVar("HandlerT", bound=typing.Callable[..., typing.Any]) -@dataclass(frozen=True) -class _ToolRegistration: - handler: AgentToolHandler - original_handler: typing.Callable[..., typing.Any] - description: str - input_model: type[pydantic.BaseModel] - input_model_factory: AgentToolInputModelFactory | None - - def bind(self, tool_id: str) -> BoundAgentTool: - input_model = ( - self.input_model_factory() - if self.input_model_factory is not None - else self.input_model - ) - if not isinstance(input_model, type) or not issubclass(input_model, pydantic.BaseModel): - raise AgentToolBindingError( - f"Agent Tool {tool_id!r} did not produce a Pydantic input model" - ) - return BoundAgentTool( - definition=FunctionTool( - id=tool_id, - description=self.description, - input_schema=input_model.model_json_schema(), - ), - input_model=input_model, - handler=self.handler, - ) - - class AgentManager: """Agent-definition execution and peer-local exact Tool registry.""" - _TOOLS: dict[str, _ToolRegistration] = {} + _TOOLS: dict[str, AgentToolRegistration] = {} _persistence: ThreadPersistenceBackend = InMemoryThreadPersistenceBackend() @classmethod @@ -119,19 +87,20 @@ async def delete_definition(cls, agent_id: AgentID) -> bool: def list_tools( cls, *, limit: int | None = None, cursor: str | None = None ) -> tuple[list[dict[str, str]], str | None]: - ids = sorted(key for key in cls._TOOLS if cursor is None or key > cursor) + catalog = {**core_agent_tools(), **cls._TOOLS} + ids = sorted(key for key in catalog if cursor is None or key > cursor) more = limit is not None and len(ids) > limit ids = ids[:limit] - return [{"id": key, "description": cls._TOOLS[key].description} for key in ids], ids[ + return [{"id": key, "description": catalog[key].description} for key in ids], ids[ -1 ] if more else None @classmethod def get_tool(cls, tool_id: str) -> FunctionTool: - registration = cls._TOOLS.get(tool_id) + registration = cls._tool_registration(tool_id) if registration is None: raise MissingAgentToolError(f"Agent Tool {tool_id!r} is not registered") - return registration.bind(tool_id).definition + return registration.bind().definition @classmethod async def can_execute(cls, agent_id: AgentID, input_modality: str) -> bool: @@ -168,23 +137,13 @@ def tool( raise AgentToolBindingError("Agent Tool ID must not be empty") def decorator(handler: HandlerT) -> HandlerT: - signature = inspect.signature(handler) - parameters = tuple(signature.parameters.values()) - if len(parameters) != 1: - raise AgentToolBindingError( - f"Agent Tool {tool_id!r} handler must accept exactly one input model" - ) - hints = typing.get_type_hints(handler) - annotation = hints.get(parameters[0].name) - if not isinstance(annotation, type) or not issubclass(annotation, pydantic.BaseModel): - raise AgentToolBindingError( - f"Agent Tool {tool_id!r} input must be annotated with a Pydantic model" - ) - - existing = cls._TOOLS.get(tool_id) + registration = AgentToolRegistration.from_handler( + handler, tool_id, description=description, input_model_factory=input_model_factory + ) + existing = cls._tool_registration(tool_id) if existing is not None: if ( - existing.original_handler is handler + existing.handler is handler and existing.description == description and existing.input_model_factory is input_model_factory ): @@ -193,13 +152,7 @@ def decorator(handler: HandlerT) -> HandlerT: f"Agent Tool {tool_id!r} is already registered" ) - cls._TOOLS[tool_id] = _ToolRegistration( - handler=typing.cast(AgentToolHandler, handler), - original_handler=handler, - description=description, - input_model=annotation, - input_model_factory=input_model_factory, - ) + cls._TOOLS[tool_id] = registration return handler return decorator @@ -231,14 +184,18 @@ async def run(cls, agent_id: AgentID, initial_message: UserMessage) -> Thread: thread.start_turn(initial_message) return thread + @classmethod + def _tool_registration(cls, tool_id: str) -> AgentToolRegistration | None: + return cls._TOOLS.get(tool_id) or core_agent_tools().get(tool_id) + @classmethod def _bind_tools(cls, tool_ids: tuple[str, ...]) -> tuple[BoundAgentTool, ...]: bound: list[BoundAgentTool] = [] for tool_id in tool_ids: - registration = cls._TOOLS.get(tool_id) + registration = cls._tool_registration(tool_id) if registration is None: raise MissingAgentToolError( f"Agent definition references unavailable Tool {tool_id!r}" ) - bound.append(registration.bind(tool_id)) + bound.append(registration.bind()) return tuple(bound) diff --git a/inkcre_core/business/graph_navigation_retrieval/tools.py b/inkcre_core/business/graph_navigation_retrieval/tools.py index 837bab78..a3494ad3 100644 --- a/inkcre_core/business/graph_navigation_retrieval/tools.py +++ b/inkcre_core/business/graph_navigation_retrieval/tools.py @@ -4,7 +4,8 @@ import pydantic -from inkcre_core.business.agent import AgentManager, ToolExecutionError +from inkcre_core.business.agent import ToolExecutionError +from inkcre_core.business.agent.contracts import AgentToolRegistration from inkcre_core.business.agent.projection import project_json from inkcre_core.schemas.ai import JSONValue from inkcre_core.schemas.graph_navigation_retrieval import ( @@ -89,13 +90,6 @@ class ConnectedComponentsInput(pydantic.BaseModel): max_explored_relations: int = pydantic.Field(default=DEFAULT_MAX_EXPLORED_RELATIONS, ge=1) -@AgentManager.tool( - GET_ENTITY_NEIGHBORHOOD_TOOL, - description=( - "Read a Block's direct neighborhood or a Relation with its endpoints. " - "Null may indicate an incorrect entity type." - ), -) async def get_entity_neighborhood(input: EntityNeighborhoodInput) -> JSONValue: request = input.root if request.entity_type == "block": @@ -113,10 +107,6 @@ async def get_entity_neighborhood(input: EntityNeighborhoodInput) -> JSONValue: return project_json(result) -@AgentManager.tool( - FIND_PATH_TOOL, - description="Find a bounded graph path; an exploration limit is not proof of absence.", -) async def find_path(input: FindPathInput) -> JSONValue: return project_json( await GraphNavigationRetrievalManager.find_path( @@ -130,12 +120,6 @@ async def find_path(input: FindPathInput) -> JSONValue: ) -@AgentManager.tool( - GET_CONNECTED_COMPONENTS_TOOL, - description=( - "Partition seeds by bounded undirected reachability through exact Relation contents." - ), -) async def get_connected_components(input: ConnectedComponentsInput) -> JSONValue: try: result = await GraphNavigationRetrievalManager.get_connected_components( @@ -146,3 +130,27 @@ async def get_connected_components(input: ConnectedComponentsInput) -> JSONValue {"error": type(error).__name__, "message": str(error)} ) from error return project_json(result) + + +AGENT_TOOLS = ( + AgentToolRegistration.from_handler( + get_entity_neighborhood, + GET_ENTITY_NEIGHBORHOOD_TOOL, + description=( + "Read a Block's direct neighborhood or a Relation with its endpoints. " + "Null may indicate an incorrect entity type." + ), + ), + AgentToolRegistration.from_handler( + find_path, + FIND_PATH_TOOL, + description="Find a bounded graph path; an exploration limit is not proof of absence.", + ), + AgentToolRegistration.from_handler( + get_connected_components, + GET_CONNECTED_COMPONENTS_TOOL, + description=( + "Partition seeds by bounded undirected reachability through exact Relation contents." + ), + ), +) diff --git a/inkcre_core/business/info_base/resolver/tools.py b/inkcre_core/business/info_base/resolver/tools.py index 84c2fb96..2017b1e0 100644 --- a/inkcre_core/business/info_base/resolver/tools.py +++ b/inkcre_core/business/info_base/resolver/tools.py @@ -4,7 +4,7 @@ import pydantic -from inkcre_core.business.agent import AgentManager +from inkcre_core.business.agent.contracts import AgentToolRegistration from inkcre_core.business.agent.projection import project_json from inkcre_core.business.info_base.services import BlockService from inkcre_core.schemas.ai import JSONValue @@ -143,11 +143,6 @@ def model_json_schema(cls, *args, **kwargs) -> dict[str, typing.Any]: return BoundResolverInput -@AgentManager.tool( - RESOLVER_TOOL, - input_model_factory=_resolver_input_model, - description="Describe or invoke public typed read methods on exact Block Resolvers.", -) async def resolver(input: ResolverMetaToolInput) -> JSONValue: request = input.root if request.action == "describe": @@ -275,3 +270,13 @@ async def resolver(input: ResolverMetaToolInput) -> JSONValue: } ) return typing.cast(JSONValue, {"results": results}) + + +AGENT_TOOLS = ( + AgentToolRegistration.from_handler( + resolver, + RESOLVER_TOOL, + input_model_factory=_resolver_input_model, + description="Describe or invoke public typed read methods on exact Block Resolvers.", + ), +) diff --git a/inkcre_core/business/info_base/tools.py b/inkcre_core/business/info_base/tools.py index 08fe5d14..693d849f 100644 --- a/inkcre_core/business/info_base/tools.py +++ b/inkcre_core/business/info_base/tools.py @@ -4,7 +4,7 @@ import pydantic -from inkcre_core.business.agent import AgentManager +from inkcre_core.business.agent.contracts import AgentToolRegistration from inkcre_core.business.agent.projection import project_json from inkcre_core.schemas.ai import JSONValue from inkcre_core.schemas.info_base.block import BlockModel @@ -55,10 +55,6 @@ def validate_selection(self) -> typing.Self: return self -@AgentManager.tool( - RETRIEVE_TOOL, - description="Retrieve lexical, semantic, or separate hybrid results for one query.", -) async def retrieve(input: RetrieveInput) -> JSONValue: branches = await InfoBaseManager.retrieve(input.query, input.mode, input.limit) payload: dict[str, JSONValue] = {} @@ -120,13 +116,6 @@ async def retrieve(input: RetrieveInput) -> JSONValue: return payload -@AgentManager.tool( - GET_ENTITIES_TOOL, - description=( - "Read persisted Blocks or Relations without resolving content. " - "Null may indicate an incorrect entity type." - ), -) async def get_entities(input: GetEntitiesInput) -> JSONValue: result = await InfoBaseManager.get_entities( tuple((reference.type, reference.id) for reference in input.entities), @@ -150,3 +139,20 @@ async def get_entities(input: GetEntitiesInput) -> JSONValue: }, ) return project_json(result) + + +AGENT_TOOLS = ( + AgentToolRegistration.from_handler( + retrieve, + RETRIEVE_TOOL, + description="Retrieve lexical, semantic, or separate hybrid results for one query.", + ), + AgentToolRegistration.from_handler( + get_entities, + GET_ENTITIES_TOOL, + description=( + "Read persisted Blocks or Relations without resolving content. " + "Null may indicate an incorrect entity type." + ), + ), +) diff --git a/inkcre_core/business/organization/tools.py b/inkcre_core/business/organization/tools.py index ad24740a..cc4de421 100644 --- a/inkcre_core/business/organization/tools.py +++ b/inkcre_core/business/organization/tools.py @@ -6,7 +6,8 @@ import pydantic -from inkcre_core.business.agent import AgentManager, ToolExecutionError +from inkcre_core.business.agent import ToolExecutionError +from inkcre_core.business.agent.contracts import AgentToolRegistration from inkcre_core.business.info_base import InfoBaseManager from inkcre_core.business.info_base.commands import submit_graph as persist_submitted_graph from inkcre_core.business.info_base.resolver import ( @@ -128,11 +129,6 @@ def validate_resolver_input(self) -> typing.Self: return BoundDraftGraphInput -@AgentManager.tool( - GET_DRAFT_GRAPH_SCHEMA_TOOL, - description="Describe graph-drafting inputs for selected Resolver types.", - input_model_factory=_schema_discovery_input_model, -) async def get_draft_graph_schema(input: GetDraftGraphSchemaInput) -> JSONValue: snapshot = _draft_capability_snapshot() return { @@ -150,11 +146,6 @@ async def get_draft_graph_schema(input: GetDraftGraphSchemaInput) -> JSONValue: } -@AgentManager.tool( - DRAFT_GRAPH_TOOL, - description="Draft one rooted GraphForm through an exact Resolver without persistence.", - input_model_factory=_draft_graph_input_model, -) async def draft_graph(input: DraftGraphInput) -> JSONValue: capability = ResolverManager.get_draft_capability(input.resolver_type) resolver_input = typing.cast(pydantic.BaseModel, getattr(input, "_resolver_input")) @@ -163,10 +154,6 @@ async def draft_graph(input: DraftGraphInput) -> JSONValue: return typing.cast(JSONValue, graph.model_dump(mode="json")) -@AgentManager.tool( - SUBMIT_GRAPH_TOOL, - description="Persist one complete GraphForm and return local-to-persisted Block IDs.", -) async def submit_graph(input: SubmitGraphInput) -> JSONValue: result = await persist_submitted_graph(input.graph) return typing.cast(JSONValue, result.model_dump(mode="json")) @@ -217,13 +204,6 @@ async def _exact_result(operation: typing.Awaitable[pydantic.BaseModel]) -> JSON return typing.cast(JSONValue, result.model_dump(mode="json")) -@AgentManager.tool( - RECORD_SUPERSESSION_TOOL, - description=( - f"Record {SUPERSEDES_RELATION!r}: the successor is authorized to replace " - "the predecessor across its entire scope on the same subject." - ), -) async def record_supersession(input: SupersessionProposal) -> JSONValue: return await _exact_result( SupersessionBehaviorResolver.record_supersession( @@ -233,14 +213,6 @@ async def record_supersession(input: SupersessionProposal) -> JSONValue: ) -@AgentManager.tool( - RECORD_REFINEMENT_TOOL, - description=( - f"Record {REFINES_RELATION!r}: new compatible detail at equal or narrower scope " - "on the same subject, not mere extraction or rewording. The predecessor " - "remains independently usable as a coarser description." - ), -) async def record_refinement(input: RefinementProposal) -> JSONValue: return await _exact_result( RefinementBehaviorResolver.record_refinement( @@ -250,17 +222,6 @@ async def record_refinement(input: RefinementProposal) -> JSONValue: ) -@AgentManager.tool( - RECORD_EVIDENCE_STANCE_TOOL, - description=( - "Record attributable evidence supporting or challenging a whole " - "assertion in comparable scope, without declaring it true or false. " - "Merely establishing that derived content faithfully restates its source is " - "not evidence stance, regardless of source authority. Shared provenance is " - "allowed when observation or reasoning " - "contributes reasons beyond restatement." - ), -) async def record_evidence_stance(input: EvidenceStanceProposal) -> JSONValue: return await _exact_result( EvidenceStanceBehaviorResolver.record_evidence_stance( @@ -271,14 +232,6 @@ async def record_evidence_stance(input: EvidenceStanceProposal) -> JSONValue: ) -@AgentManager.tool( - CREATE_SYNTHESIS_TOOL, - description=( - "Create reusable multi-source information preserving provenance, " - "disagreement, uncertainty and speaker attribution; copies do not " - "multiply corroboration." - ), -) async def create_synthesis(input: SynthesisProposal) -> JSONValue: return await _exact_result( SynthesisBehaviorResolver.create_synthesis( @@ -289,13 +242,6 @@ async def create_synthesis(input: SynthesisProposal) -> JSONValue: ) -@AgentManager.tool( - ANCHOR_EXISTING_REFERENT_TOOL, - description=( - "Link a source's referring fragment to an existing identity-bearing " - "referent, without creating a new referent." - ), -) async def anchor_existing_referent( input: ExistingReferentAnchorProposal, ) -> JSONValue: @@ -308,15 +254,6 @@ async def anchor_existing_referent( ) -@AgentManager.tool( - RECORD_DUPLICATE_ASSERTION_TOOL, - description=( - f"Record {DUPLICATES_ASSERTION_RELATION!r}: whole assertions from the same " - "provenance occurrence with no " - "independent evidence, reasoning, decision or material gain; matching " - "words alone are insufficient." - ), -) async def record_duplicate_assertion(input: DuplicateAssertionProposal) -> JSONValue: return await _exact_result( DuplicateAssertionBehaviorResolver.record_duplicate_assertion( @@ -326,11 +263,6 @@ async def record_duplicate_assertion(input: DuplicateAssertionProposal) -> JSONV ) -@AgentManager.tool( - RECORD_ORGANIZATION_CANDIDATE_TOOL, - description="Mark an organization candidate without executing the behavior.", - input_model_factory=_candidate_input_model, -) async def record_organization_candidate( input: RecordOrganizationCandidateInput, ) -> JSONValue: @@ -340,3 +272,86 @@ async def record_organization_candidate( return await _exact_result( typing.cast(typing.Any, behavior).record_candidate(input.block_id) ) + + +AGENT_TOOLS = ( + AgentToolRegistration.from_handler( + get_draft_graph_schema, + GET_DRAFT_GRAPH_SCHEMA_TOOL, + description="Describe graph-drafting inputs for selected Resolver types.", + input_model_factory=_schema_discovery_input_model, + ), + AgentToolRegistration.from_handler( + draft_graph, + DRAFT_GRAPH_TOOL, + description="Draft one rooted GraphForm through an exact Resolver without persistence.", + input_model_factory=_draft_graph_input_model, + ), + AgentToolRegistration.from_handler( + submit_graph, + SUBMIT_GRAPH_TOOL, + description="Persist one complete GraphForm and return local-to-persisted Block IDs.", + ), + AgentToolRegistration.from_handler( + record_supersession, + RECORD_SUPERSESSION_TOOL, + description=( + f"Record {SUPERSEDES_RELATION!r}: the successor is authorized to replace " + "the predecessor across its entire scope on the same subject." + ), + ), + AgentToolRegistration.from_handler( + record_refinement, + RECORD_REFINEMENT_TOOL, + description=( + f"Record {REFINES_RELATION!r}: new compatible detail at equal or narrower scope " + "on the same subject, not mere extraction or rewording. The predecessor " + "remains independently usable as a coarser description." + ), + ), + AgentToolRegistration.from_handler( + record_evidence_stance, + RECORD_EVIDENCE_STANCE_TOOL, + description=( + "Record attributable evidence supporting or challenging a whole " + "assertion in comparable scope, without declaring it true or false. " + "Merely establishing that derived content faithfully restates its source is " + "not evidence stance, regardless of source authority. Shared provenance is " + "allowed when observation or reasoning " + "contributes reasons beyond restatement." + ), + ), + AgentToolRegistration.from_handler( + create_synthesis, + CREATE_SYNTHESIS_TOOL, + description=( + "Create reusable multi-source information preserving provenance, " + "disagreement, uncertainty and speaker attribution; copies do not " + "multiply corroboration." + ), + ), + AgentToolRegistration.from_handler( + anchor_existing_referent, + ANCHOR_EXISTING_REFERENT_TOOL, + description=( + "Link a source's referring fragment to an existing identity-bearing " + "referent, without creating a new referent." + ), + ), + AgentToolRegistration.from_handler( + record_duplicate_assertion, + RECORD_DUPLICATE_ASSERTION_TOOL, + description=( + f"Record {DUPLICATES_ASSERTION_RELATION!r}: whole assertions from the same " + "provenance occurrence with no " + "independent evidence, reasoning, decision or material gain; matching " + "words alone are insufficient." + ), + ), + AgentToolRegistration.from_handler( + record_organization_candidate, + RECORD_ORGANIZATION_CANDIDATE_TOOL, + description="Mark an organization candidate without executing the behavior.", + input_model_factory=_candidate_input_model, + ), +) diff --git a/run.py b/run.py index f429d530..e4c4db90 100644 --- a/run.py +++ b/run.py @@ -143,7 +143,7 @@ def bootstrap_step(step: str): async def bootstrap_runtime(app: fastapi.FastAPI) -> None: """Initialize database-backed runtime services after migrations are ready.""" from inkcre_core.business.info_base.resolver import register_core_resolvers - from inkcre_core.business.agent import register_core_agent_tools + from app.business.sink.agent_query import register_agent_query_tool from inkcre_core.business.organization import register_core_organization_behaviors from inkcre_core.business.info_base.storage import StorageManager @@ -163,7 +163,7 @@ async def bootstrap_runtime(app: fastapi.FastAPI) -> None: with bootstrap_step("core_registration"): register_core_resolvers() register_core_organization_behaviors() - register_core_agent_tools() + register_agent_query_tool() # Setup built-in storage instances with bootstrap_step("storages"): diff --git a/scripts/check_core_package.py b/scripts/check_core_package.py index ef3c1103..d445c1e8 100644 --- a/scripts/check_core_package.py +++ b/scripts/check_core_package.py @@ -22,11 +22,18 @@ def find_spec(self, fullname, path=None, target=None): sys.meta_path.insert(0, NoApplication()) from inkcre_core import Core +from inkcre_core.business.agent import AgentManager from inkcre_core.business.info_base import BlockService, submit_graph from inkcre_core.schemas.info_base.main import GraphForm from inkcre_core.business.peer import PeerManager from inkcre_core.business.job import JobManager +tools, _ = AgentManager.list_tools() +tool_ids = {tool['id'] for tool in tools} +assert {'retrieve', 'resolver', 'find_path', 'draft_graph'} <= tool_ids +assert 'submit_query_result' not in tool_ids +assert AgentManager.get_tool('retrieve').id == 'retrieve' + async def main(): core = Core('postgresql+psycopg://unused:x@127.0.0.1:1/unused') with core.bind(): diff --git a/tests/agent/test_tool_composition.py b/tests/agent/test_tool_composition.py new file mode 100644 index 00000000..425d70ce --- /dev/null +++ b/tests/agent/test_tool_composition.py @@ -0,0 +1,125 @@ +"""Agent Tool visibility follows the SDK and service composition boundaries.""" + +import subprocess +import sys + + +def test_tool_catalog_and_service_registration_in_fresh_process(): + probe = """ +from fastapi import FastAPI +from fastapi.testclient import TestClient +import pydantic + +from app.business.sink.agent_query import register_agent_query_tool +from app.routes.agent import ROUTER +from inkcre_core.business.agent import ( + AgentManager, + DuplicateAgentToolRegistrationError, + register_core_agent_tools, +) + +app = FastAPI() +app.include_router(ROUTER) +with TestClient(app) as client: + # Importing Sink and route modules must not register the delivery Tool. + before = {row["id"] for row in client.get("/agent-tools").json()["tools"]} + assert {"retrieve", "resolver", "find_path", "draft_graph"} <= before + assert client.get("/agent-tools/submit_query_result").status_code == 404 + + register_core_agent_tools() # Compatibility call may occur after the first SDK lookup. + register_agent_query_tool() + register_agent_query_tool() + + class Input(pydantic.BaseModel): + value: int + + def custom(input: Input): + return input.value + + register = AgentManager.tool("extension.test", description="Extension probe") + assert register(custom) is custom + assert register(custom) is custom + try: + AgentManager.tool("retrieve", description="Conflicting Tool")(custom) + except DuplicateAgentToolRegistrationError: + pass + else: + raise AssertionError("custom registration replaced a built-in Tool") + + response = client.get("/agent-tools") + assert response.status_code == 200 + assert {row["id"] for row in response.json()["tools"]} == before | { + "submit_query_result", "extension.test" + } + schema = client.get("/agent-tools/submit_query_result").json() + assert schema["id"] == "submit_query_result" + assert schema["input_schema"]["required"] == ["answer"] +""" + subprocess.run([sys.executable, "-c", probe], check=True) # noqa: S603 + + +def test_runtime_bootstrap_exposes_delivery_tool_to_query_execution( + monkeypatch, async_runner +): + from unittest.mock import AsyncMock, Mock + + import pytest + + import run + from app.business.sink.agent_query import AgentQuerySink + from inkcre_core.business.agent import AgentManager, InMemoryThreadPersistenceBackend + from inkcre_core.business.info_base.storage import StorageManager + from inkcre_core.schemas.agent import AgentDefinitionModel + from inkcre_core.schemas.ai import AssistantMessage, ToolCall + from inkcre_core.schemas.job import JobModel + from inkcre_core.schemas.sink import SinkModel + + class StopBeforeDatabaseSetup(Exception): + pass + + monkeypatch.setattr(AgentManager, "_TOOLS", {}) + monkeypatch.setattr(AgentManager, "_persistence", InMemoryThreadPersistenceBackend()) + monkeypatch.setattr(run.PeerManager, "register_self", AsyncMock()) + monkeypatch.setattr(run.PeerManager, "setup_builtin_outbounds", Mock()) + monkeypatch.setattr(run.PeerManager, "register_inbound", Mock()) + monkeypatch.setattr(run, "initialize_telemetry", AsyncMock()) + monkeypatch.setattr( + StorageManager, + "setup_builtin_storages_async", + AsyncMock(side_effect=StopBeforeDatabaseSetup), + ) + + result = {"answer": "Observed answer", "references": [{"type": "block", "id": 42}]} + monkeypatch.setattr( + AgentManager, + "get_definition", + AsyncMock( + return_value=AgentDefinitionModel( + id=7, + name="Query Agent", + model=1, + system_prompt="Answer the query.", + tools=("submit_query_result",), + max_model_calls_per_turn=2, + ) + ), + ) + monkeypatch.setattr( + run.AIManager, + "chat", + AsyncMock( + side_effect=[ + AssistantMessage( + tool_calls=(ToolCall(id="submit", tool="submit_query_result", arguments=result),) + ), + AssistantMessage(content="Done"), + ] + ), + ) + + sink = AgentQuerySink(SinkModel(id=1, type="core.agent-query.v1", config={"agent": 7})) + job = JobModel(id=1, type="core.sink.agent-query.v1") + with pytest.raises(StopBeforeDatabaseSetup): + async_runner.run(run.bootstrap_runtime(run.api_app)) + async_runner.run(sink.execute(job, "Read the evidence")) + assert job.state == {"result": result, "termination": "completed"}