alternatives method

AgentToolResult alternatives({
  1. required Map<String, Object?> args,
})

Resolves the alternatives whose price stays under maxPrice.

Implementation

AgentToolResult alternatives({required Map<String, Object?> args}) {
  final decoded = ToolIngress.validate(
    args,
    AlternativesLookupIntent.fromWire,
  );
  return decoded.fold((intent) {
    // A negative limit is an int, so `fromWire` accepts it, but `take(-1)`
    // throws a RangeError. Reject it as `/limit` field feedback before
    // querying, matching the zero-trust ingress contract; omitted, zero and
    // positive limits stay valid.
    final limit = intent.limit;
    if (limit != null && limit < 0) {
      return AgentToolResult.rejected(
        '/limit expected a non-negative int but got $limit',
      );
    }
    final descriptor = registry.resolve<T>();
    final price = _priceField(descriptor);
    final query = ZfaQuery<T>(
      where: <ZorphyFilter<T>>[
        if (price != null && intent.maxPrice != null)
          price.lessThan(intent.maxPrice!),
      ],
      orderBy: <ZorphySort<T>>[if (price != null) price.asc()],
    );
    final documents = store.backend<T>().query(query);
    final take = limit == null ? documents : documents.take(limit);
    return AgentToolResult(
      ok: true,
      facts: <AgentFact>[
        for (final document in take)
          _factOf(descriptor, document.key, document.value),
      ],
    );
  }, (error) => AgentToolResult.rejected(ToolIngress.feedback(error)));
}