The Open Framework for Building Agents
feat(selfmod): search the eve registry for integrations (#2480)
prha05a53cd18f0c
diff --git a/.changeset/selfmod-search-registry.md b/.changeset/selfmod-search-registry.mdnew file mode 100644index 000000000..88222226d--- /dev/null+++ b/.changeset/selfmod-search-registry.md@@ -0,0 +1,12 @@+---+"@eve/self-modification": patch+---++The self-modification subagent can now search the eve registry. A new+`selfmod__search_registry` tool reports the channels, MCP connections,+extensions, and observability integrations a project can add — each with its+item address, whether the authored tree already holds it, and the eve version it+requires — so the subagent recommends `eve add channel/slack` instead of+hand-writing an integration the registry already ships. Search is read-only and+installs nothing. Results include pagination metadata so every match can be+retrieved, and bundle searches include their component names and metadata.diff --git a/packages/eve-self-modification/README.md b/packages/eve-self-modification/README.mdindex 48c0a7447..d519debaf 100644--- a/packages/eve-self-modification/README.md+++ b/packages/eve-self-modification/README.md@@ -33,4 +33,4 @@ export { default } from "@eve/self-modification/sandbox";export { default } from "@eve/self-modification";```-Set `model` in the agent definition to choose the self-modification subagent's model; it defaults to `anthropic/claude-sonnet-5`. The sandbox mounts the application's authored `agent/` directory read-write at `/source` and the installed eve package's version-matched documentation read-only at `/eve-docs`. The extension contributes the official eve authoring skill, adapted to use that documentation mount, and `selfmod__edit_file` for one or more exact targeted edits to an existing file without rewriting it. Its instructions direct independent discovery calls to run concurrently and reserve `write_file` for new files or complete rewrites.+Set `model` in the agent definition to choose the self-modification subagent's model; it defaults to `anthropic/claude-sonnet-5`. The sandbox mounts the application's authored `agent/` directory read-write at `/source` and the installed eve package's version-matched documentation read-only at `/eve-docs`. The extension contributes the `selfmod__edit_file` for one or more exact targeted edits to an existing file without rewriting it. Its instructions direct independent discovery calls to run concurrently and reserve `write_file` for new files or complete rewrites. The extension also contains `selfmod__search_registry` to search the eve registry for channels, connections, extensions, and other integrations the project can add. Registry search is read-only: it reports each item's address, whether the authored tree already holds it, and the eve version it requires, so the subagent recommends the user add the registry item (e.g. `eve add channel/slack`) instead of hand-writing an integration the registry already ships.diff --git a/packages/eve-self-modification/extension/instructions.ts b/packages/eve-self-modification/extension/instructions.tsindex 4fd45abe8..4dd67e788 100644--- a/packages/eve-self-modification/extension/instructions.ts+++ b/packages/eve-self-modification/extension/instructions.ts@@ -7,6 +7,8 @@ The source code of the eve agent is mounted read-write at /source. Use bash onlyUse selfmod__edit_file for precise changes to existing files; every edits[].oldText must match exactly. When changing multiple separate locations in one file, use one call with multiple entries in edits[]. Each oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits; merge nearby changes into one edit. Keep oldText as small as possible while still being unique. Use write_file only for new files or complete rewrites.+When the developer asks what this agent can integrate with, or asks for a capability an existing integration may already provide, call selfmod__search_registry before writing anything by hand. Prefer a registry item: report its address and tell the developer to install it with the /add command in this eve dev session, and say when the project already has it. Write an integration yourself only when the registry has nothing that fits, or the developer asks for a custom implementation.+Group independent calls, including bash and reads, in one response.The eve framework documentation is mounted read-only at /eve-docs. Read the eve guide directly relevant to an unfamiliar public API. Prefer an existing local implementation pattern over broad documentation research.diff --git a/packages/eve-self-modification/extension/tools/search_registry.ts b/packages/eve-self-modification/extension/tools/search_registry.tsnew file mode 100644index 000000000..eac88c967--- /dev/null+++ b/packages/eve-self-modification/extension/tools/search_registry.ts@@ -0,0 +1,512 @@+import { defineTool, type ToolContext } from "eve/tools";++/** Registry categories an integration search can be narrowed to. */+const CATEGORIES = ["channel", "connection", "extension", "instrumentation"] as const;++type Category = (typeof CATEGORIES)[number];++const DEFAULT_REGISTRY_BASE = "https://eve.dev/r";+const INDEX_PATH = "/registry.json";+const DEFAULT_LIMIT = 10;+const MAX_LIMIT = 25;+const FETCH_TIMEOUT_MS = 10_000;+/**+ * The catalog changes when eve releases, not between turns, so one fetch can+ * serve a whole conversation. A stale-tolerant read is correct here.+ */+const CACHE_TTL_MS = 5 * 60_000;+/** The sandbox mounts the authored `agent/` directory here in development. */+const AUTHORED_SOURCE_MOUNT = "/source";+const AUTHORED_PREFIX = "agent/";++const inputSchema = {+ type: "object",+ additionalProperties: false,+ properties: {+ query: {+ type: "string",+ maxLength: 200,+ description: "Free-text match against integration names, titles, and descriptions.",+ },+ category: {+ type: "string",+ enum: [...CATEGORIES],+ description: "Restrict results to one registry category.",+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: MAX_LIMIT,+ description: `Maximum number of items to return (default ${DEFAULT_LIMIT}, maximum ${MAX_LIMIT}).`,+ },+ offset: {+ type: "integer",+ minimum: 0,+ description:+ "Number of matching items to skip. Use nextOffset from a prior result to retrieve the next page.",+ },+ },+} as const;++const outputSchema = {+ type: "object",+ additionalProperties: false,+ properties: {+ items: {+ type: "array",+ items: {+ type: "object",+ additionalProperties: false,+ properties: {+ address: { type: "string" },+ title: { type: "string" },+ description: { type: "string" },+ category: { type: "string" },+ components: { type: "array", items: { type: "string" } },+ requires: { type: "string" },+ installed: { type: "boolean" },+ },+ required: ["address", "title"],+ },+ },+ errors: {+ type: "array",+ items: {+ type: "object",+ additionalProperties: false,+ properties: {+ registry: { type: "string" },+ message: { type: "string" },+ },+ required: ["registry", "message"],+ },+ },+ total: { type: "integer" },+ hasMore: { type: "boolean" },+ nextOffset: { type: "integer" },+ },+ required: ["items", "errors", "total", "hasMore"],+} as const;++/** One catalog entry, narrowed from the published registry index. */+export interface CatalogEntry {+ readonly address: string;+ readonly title: string;+ readonly description?: string;+ readonly category?: Category;+ readonly components?: readonly string[];+ /** Component addresses, labels, and descriptions used to search bundles. */+ readonly componentSearchTerms?: readonly string[];+ readonly requires?: string;+ /** Authored path this item installs, used to detect an existing install. */+ readonly authoredTarget?: string;+}++/** One row returned to the model. */+export interface FoundIntegration {+ readonly address: string;+ readonly title: string;+ readonly description?: string;+ readonly category?: Category;+ readonly components?: readonly string[];+ readonly requires?: string;+ readonly installed?: boolean;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function optionalString(value: unknown): string | undefined {+ return typeof value === "string" && value.length > 0 ? value : undefined;+}++function isCategory(value: string): value is Category {+ return (CATEGORIES as readonly string[]).includes(value);+}++/**+ * Derives the category from the item address.+ *+ * eve registry addresses carry their category as the leading path segment.+ * Bundles (`linear`) and package-scoped items (`experimental/self-modification`)+ * have none, so the field stays absent rather than being guessed.+ */+function categoryOf(address: string): Category | undefined {+ const segment = address.split("/")[0];+ return segment !== undefined && address.includes("/") && isCategory(segment)+ ? segment+ : undefined;+}++/**+ * Falls back to a readable title for an item that publishes none, matching how+ * the eve CLI labels catalog rows.+ */+function titleFromAddress(address: string): string {+ const slug = address.split("/").at(-1) ?? address;+ return slug+ .split("-")+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))+ .join(" ");+}++/**+ * Reads the eve-owned metadata block from one index entry.+ *+ * `meta.eve` is eve's own registry contract, described by the schemas in the+ * CLI's `registry-metadata.ts`. This reads the two fields the subagent needs+ * and ignores the rest, so an added field degrades to an absent value here+ * instead of a parse failure.+ */+function eveMetadata(entry: Record<string, unknown>): Record<string, unknown> {+ const meta = entry.meta;+ if (!isRecord(meta)) return {};+ const eve = meta.eve;+ return isRecord(eve) ? eve : {};+}++/** Metadata for bundle components, used both for display and free-text search. */+function componentMetadata(+ eve: Record<string, unknown>,+): { readonly addresses: readonly string[]; readonly searchTerms: readonly string[] } | undefined {+ const components = eve.components;+ if (!Array.isArray(components)) return undefined;++ const addresses: string[] = [];+ const searchTerms: string[] = [];+ for (const component of components) {+ if (!isRecord(component)) continue;+ const address = optionalString(component.item);+ if (address === undefined) continue;+ addresses.push(address);+ searchTerms.push(address);+ const label = optionalString(component.label);+ if (label !== undefined) searchTerms.push(label);+ const description = optionalString(component.description);+ if (description !== undefined) searchTerms.push(description);+ }+ return addresses.length > 0 ? { addresses, searchTerms } : undefined;+}++/** First authored file the item installs; identifies an existing install. */+function authoredTargetOf(entry: Record<string, unknown>): string | undefined {+ const files = entry.files;+ if (!Array.isArray(files)) return undefined;+ for (const file of files) {+ if (!isRecord(file)) continue;+ const target = optionalString(file.target);+ if (target?.startsWith(AUTHORED_PREFIX) === true) return target;+ }+ return undefined;+}++/**+ * Narrows the published registry index into catalog entries.+ *+ * Unreadable entries are skipped rather than failing the whole search: the+ * index is owned by the registry and may carry fields this version predates.+ */+export function parseRegistryIndex(value: unknown): readonly CatalogEntry[] {+ if (!isRecord(value) || !Array.isArray(value.items)) return [];+ const entries: CatalogEntry[] = [];++ for (const item of value.items) {+ if (!isRecord(item)) continue;+ const address = optionalString(item.name);+ if (address === undefined) continue;+ const eve = eveMetadata(item);++ const entry: {+ address: string;+ authoredTarget?: string;+ category?: Category;+ componentSearchTerms?: readonly string[];+ components?: readonly string[];+ description?: string;+ requires?: string;+ title: string;+ } = { address, title: optionalString(item.title) ?? titleFromAddress(address) };++ const category = categoryOf(address);+ if (category !== undefined) entry.category = category;+ const description = optionalString(item.description);+ if (description !== undefined) entry.description = description;+ const components = componentMetadata(eve);+ if (components !== undefined) {+ entry.components = components.addresses;+ entry.componentSearchTerms = components.searchTerms;+ }+ const requires = optionalString(eve.requires);+ if (requires !== undefined) entry.requires = requires;+ const authoredTarget = authoredTargetOf(item);+ if (authoredTarget !== undefined) entry.authoredTarget = authoredTarget;++ entries.push(entry);+ }++ return entries;+}++/**+ * Filters and bounds catalog entries for one search.+ *+ * A bundle matches when one of its components matches the requested category,+ * so asking for channels still surfaces `linear` (which installs a channel)+ * instead of hiding it behind its uncategorized address.+ */+export function selectIntegrations(input: {+ readonly category?: Category;+ readonly entries: readonly CatalogEntry[];+ readonly limit?: number;+ readonly query?: string;+}): readonly FoundIntegration[] {+ return selectIntegrationPage(input).items;+}++export function selectIntegrationPage(input: {+ readonly category?: Category;+ readonly entries: readonly CatalogEntry[];+ readonly limit?: number;+ readonly offset?: number;+ readonly query?: string;+}): {+ readonly hasMore: boolean;+ readonly items: readonly FoundIntegration[];+ readonly nextOffset?: number;+ readonly total: number;+} {+ const limit = Math.min(Math.max(input.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);+ const offset = Math.max(input.offset ?? 0, 0);+ const terms = (input.query ?? "")+ .toLowerCase()+ .split(/\s+/u)+ .filter((term) => term.length > 0);++ const matches = input.entries.filter((entry) => {+ if (input.category !== undefined && !matchesCategory(entry, input.category)) return false;+ if (terms.length === 0) return true;+ const haystack = [+ entry.address,+ entry.title,+ entry.description ?? "",+ ...(entry.componentSearchTerms ?? entry.components ?? []),+ ]+ .join(" ")+ .toLowerCase();+ return terms.every((term) => haystack.includes(term));+ });++ const items = matches.slice(offset, offset + limit).map((entry) => {+ const row: {+ address: string;+ category?: Category;+ components?: readonly string[];+ description?: string;+ requires?: string;+ title: string;+ } = { address: entry.address, title: entry.title };+ if (entry.category !== undefined) row.category = entry.category;+ if (entry.components !== undefined) row.components = entry.components;+ if (entry.description !== undefined) row.description = entry.description;+ if (entry.requires !== undefined) row.requires = entry.requires;+ return row;+ });+ const nextOffset = offset + items.length;+ const result: {+ hasMore: boolean;+ items: readonly FoundIntegration[];+ nextOffset?: number;+ total: number;+ } = {+ hasMore: nextOffset < matches.length,+ items,+ total: matches.length,+ };+ if (nextOffset < matches.length) result.nextOffset = nextOffset;+ return result;+}++function matchesCategory(entry: CatalogEntry, category: Category): boolean {+ if (entry.category === category) return true;+ return entry.components?.some((component) => categoryOf(component) === category) === true;+}++/**+ * Resolves the registry index URL, honoring the same development override the+ * eve CLI reads.+ *+ * The override decides which registry the agent trusts, so it enforces the same+ * rules as `resolveOfficialRegistryUrl` in eve's registry command: HTTP(S) only,+ * no embedded credentials, no query or fragment. The rules are restated here+ * rather than imported because that module reaches the registry client, which+ * has no place in an agent runtime.+ */+export function resolveRegistryIndexUrl(configured = process.env.EVE_DEV_OFFICIAL_REGISTRY_URL) {+ if (configured === undefined) return `${DEFAULT_REGISTRY_BASE}${INDEX_PATH}`;++ let url: URL;+ try {+ url = new URL(configured);+ } catch {+ throw new Error("EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.");+ }+ if (url.protocol !== "http:" && url.protocol !== "https:") {+ throw new Error("EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.");+ }+ if (url.username !== "" || url.password !== "") {+ throw new Error("EVE_DEV_OFFICIAL_REGISTRY_URL must not include credentials.");+ }+ if (url.search !== "" || url.hash !== "") {+ throw new Error("EVE_DEV_OFFICIAL_REGISTRY_URL must not include a query or fragment.");+ }++ url.pathname = `${url.pathname.replace(/\/+$/u, "")}${INDEX_PATH}`;+ return url.toString();+}++interface CachedIndex {+ readonly entries: readonly CatalogEntry[];+ readonly fetchedAtMs: number;+ readonly url: string;+}++let cache: CachedIndex | undefined;++/** Clears the module-level index cache. Test seam. */+export function clearRegistryIndexCache(): void {+ cache = undefined;+}++async function loadRegistryIndex(input: {+ readonly nowMs: number;+ readonly signal?: AbortSignal;+ readonly url: string;+}): Promise<readonly CatalogEntry[]> {+ if (+ cache !== undefined &&+ cache.url === input.url &&+ input.nowMs - cache.fetchedAtMs < CACHE_TTL_MS+ ) {+ return cache.entries;+ }++ const response = await fetch(input.url, {+ headers: { accept: "application/json" },+ signal: AbortSignal.any(+ input.signal === undefined+ ? [AbortSignal.timeout(FETCH_TIMEOUT_MS)]+ : [input.signal, AbortSignal.timeout(FETCH_TIMEOUT_MS)],+ ),+ });+ if (!response.ok) {+ throw new Error(`Could not read the eve registry (${response.status}).`);+ }+ const entries = parseRegistryIndex(await response.json());+ cache = { entries, fetchedAtMs: input.nowMs, url: input.url };+ return entries;+}++/**+ * Annotates each row with whether the authored tree already holds its file.+ *+ * Development mounts the authored `agent/` directory at `/source`, so+ * `agent/channels/slack.ts` is `/source/channels/slack.ts`. eve derives every+ * integration name from its path, so a present file is an exact answer rather+ * than a heuristic. The field is left absent — never `false` — when the source+ * cannot be read, so "unknown" is not reported as "not installed".+ */+async function annotateInstalled(input: {+ readonly ctx: Pick<ToolContext, "getSandbox">;+ readonly entries: readonly CatalogEntry[];+ readonly rows: readonly FoundIntegration[];+}): Promise<readonly FoundIntegration[]> {+ const targets = new Map(+ input.entries.flatMap((entry) =>+ entry.authoredTarget === undefined ? [] : [[entry.address, entry.authoredTarget] as const],+ ),+ );+ if (input.rows.every((row) => targets.get(row.address) === undefined)) return input.rows;++ let sandbox: Awaited<ReturnType<ToolContext["getSandbox"]>>;+ try {+ sandbox = await input.ctx.getSandbox();+ } catch {+ return input.rows;+ }++ return await Promise.all(+ input.rows.map(async (row) => {+ const target = targets.get(row.address);+ if (target === undefined) return row;+ const path = `${AUTHORED_SOURCE_MOUNT}/${target.slice(AUTHORED_PREFIX.length)}`;+ try {+ const content = await sandbox.readTextFile({ path });+ return { ...row, installed: content !== null };+ } catch {+ return row;+ }+ }),+ );+}++export default defineTool({+ description:+ "Search the eve registry for integrations this project can add: channels, MCP connections, extensions, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, and report the item address (for example `channel/slack`) so the developer can install it with `/add`.",+ inputSchema,+ outputSchema,+ async execute(input, ctx) {+ const errors: { message: string; registry: string }[] = [];+ let url: string;+ try {+ url = resolveRegistryIndexUrl();+ } catch (error) {+ return {+ errors: [{ message: errorMessage(error), registry: "eve" }],+ hasMore: false,+ items: [],+ total: 0,+ };+ }++ let entries: readonly CatalogEntry[] = [];+ try {+ entries = await loadRegistryIndex({ nowMs: Date.now(), signal: ctx.abortSignal, url });+ } catch (error) {+ errors.push({ message: errorMessage(error), registry: url });+ }++ const selection: {+ category?: Category;+ entries: readonly CatalogEntry[];+ limit?: number;+ offset?: number;+ query?: string;+ } = { entries };+ const category = typeof input.category === "string" ? input.category : undefined;+ if (category !== undefined && isCategory(category)) selection.category = category;+ if (typeof input.limit === "number") selection.limit = input.limit;+ if (typeof input.offset === "number") selection.offset = input.offset;+ if (typeof input.query === "string") selection.query = input.query;+ const page = selectIntegrationPage(selection);++ const result: {+ errors: { message: string; registry: string }[];+ hasMore: boolean;+ items: readonly FoundIntegration[];+ nextOffset?: number;+ total: number;+ } = {+ errors,+ hasMore: page.hasMore,+ items: await annotateInstalled({ ctx, entries, rows: page.items }),+ total: page.total,+ };+ if (page.nextOffset !== undefined) result.nextOffset = page.nextOffset;+ return result;+ },+});++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}diff --git a/packages/eve-self-modification/src/agent.ts b/packages/eve-self-modification/src/agent.tsindex 8efb05b08..af3aa09bf 100644--- a/packages/eve-self-modification/src/agent.ts+++ b/packages/eve-self-modification/src/agent.ts@@ -28,6 +28,7 @@ export function defineSelfModificationAgent(options: SelfModificationAgentOption"Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the developer does not mention files or source code. " +"Infer persistence from the request and conversation rather than waiting for phrases such as “modify your source.” " +"For example, asking the agent to stop always doing something, add a capability, or change future responses calls for inspecting and editing the authored source instead of providing a one-turn workaround. " ++ "Also delegate questions about which integrations, channels, connections, or capabilities are available to add: the subagent searches the eve registry and reports exact item addresses instead of guessing them. " +"Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. " +"Source edits do not affect the caller’s current turn. After this subagent reports changes, do not invoke edited tools or attempt runtime verification until a new user turn. " +"If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.",diff --git a/packages/eve-self-modification/src/search-registry.test.ts b/packages/eve-self-modification/src/search-registry.test.tsnew file mode 100644index 000000000..5afab507d--- /dev/null+++ b/packages/eve-self-modification/src/search-registry.test.ts@@ -0,0 +1,328 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import searchRegistry, {+ clearRegistryIndexCache,+ parseRegistryIndex,+ resolveRegistryIndexUrl,+ selectIntegrationPage,+ selectIntegrations,+ type CatalogEntry,+} from "../extension/tools/search_registry.js";++const INDEX = {+ items: [+ {+ name: "channel/slack",+ title: "Slack",+ description: "Talk to the agent from Slack.",+ files: [{ target: "agent/channels/slack.ts" }],+ meta: { eve: { requires: ">=0.30.0" } },+ },+ {+ name: "channel/discord",+ title: "Discord",+ description: "Talk to the agent from Discord.",+ files: [{ target: "agent/channels/discord.ts" }],+ },+ {+ name: "connection/notion",+ title: "Notion",+ description: "Read and write Notion pages.",+ files: [{ target: "agent/connections/notion.ts" }],+ },+ {+ name: "linear",+ title: "Linear",+ description: "Receive delegated Linear work.",+ meta: {+ eve: {+ components: [+ {+ item: "channel/linear-agent",+ label: "Linear agent",+ description: "Delegate Linear work to an agent.",+ },+ { item: "connection/linear", label: "Linear connection" },+ ],+ },+ },+ },+ { name: "instrumentation/langfuse-tracing", files: [{ target: "agent/instrumentation.ts" }] },+ { name: 42 },+ ],+};++function catalog(): readonly CatalogEntry[] {+ return parseRegistryIndex(INDEX);+}++afterEach(() => {+ clearRegistryIndexCache();+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+});++describe("parseRegistryIndex", () => {+ it("narrows published entries and skips unreadable ones", () => {+ const entries = catalog();++ expect(entries.map((entry) => entry.address)).toEqual([+ "channel/slack",+ "channel/discord",+ "connection/notion",+ "linear",+ "instrumentation/langfuse-tracing",+ ]);+ expect(entries[0]).toEqual({+ address: "channel/slack",+ authoredTarget: "agent/channels/slack.ts",+ category: "channel",+ description: "Talk to the agent from Slack.",+ requires: ">=0.30.0",+ title: "Slack",+ });+ });++ it("keeps a bundle's components and leaves its category absent", () => {+ const bundle = catalog().find((entry) => entry.address === "linear");++ expect(bundle?.category).toBeUndefined();+ expect(bundle?.components).toEqual(["channel/linear-agent", "connection/linear"]);+ });++ it("labels an item that publishes no title", () => {+ const entry = catalog().find((row) => row.address === "instrumentation/langfuse-tracing");++ expect(entry?.title).toBe("Langfuse Tracing");+ });++ it("returns nothing for a malformed index", () => {+ expect(parseRegistryIndex(null)).toEqual([]);+ expect(parseRegistryIndex({ items: "nope" })).toEqual([]);+ });+});++describe("selectIntegrations", () => {+ it("matches every query term across address, title, and description", () => {+ expect(+ selectIntegrations({ entries: catalog(), query: "notion pages" }).map((row) => row.address),+ ).toEqual(["connection/notion"]);+ expect(selectIntegrations({ entries: catalog(), query: "slack" })).toHaveLength(1);+ expect(+ selectIntegrations({ entries: catalog(), query: "linear agent" }).map((row) => row.address),+ ).toEqual(["linear"]);+ expect(selectIntegrations({ entries: catalog(), query: "nothing here" })).toEqual([]);+ });++ it("includes a bundle whose components match the requested category", () => {+ expect(+ selectIntegrations({ category: "channel", entries: catalog() }).map((row) => row.address),+ ).toEqual(["channel/slack", "channel/discord", "linear"]);+ });++ it("bounds the result count", () => {+ expect(selectIntegrations({ entries: catalog(), limit: 2 })).toHaveLength(2);+ expect(selectIntegrations({ entries: catalog(), limit: 500 })).toHaveLength(5);+ });++ it("reports totals and provides an offset for the next page", () => {+ expect(selectIntegrationPage({ entries: catalog(), limit: 2 })).toEqual({+ hasMore: true,+ items: [+ {+ address: "channel/slack",+ category: "channel",+ description: "Talk to the agent from Slack.",+ requires: ">=0.30.0",+ title: "Slack",+ },+ {+ address: "channel/discord",+ category: "channel",+ description: "Talk to the agent from Discord.",+ title: "Discord",+ },+ ],+ nextOffset: 2,+ total: 5,+ });+ expect(selectIntegrationPage({ entries: catalog(), limit: 2, offset: 4 })).toMatchObject({+ hasMore: false,+ items: [{ address: "instrumentation/langfuse-tracing", title: "Langfuse Tracing" }],+ total: 5,+ });+ });++ it("returns presentation fields only", () => {+ const [row] = selectIntegrations({ entries: catalog(), query: "slack" });++ expect(row).toEqual({+ address: "channel/slack",+ category: "channel",+ description: "Talk to the agent from Slack.",+ requires: ">=0.30.0",+ title: "Slack",+ });+ });+});++describe("resolveRegistryIndexUrl", () => {+ it("defaults to the official registry index", () => {+ expect(resolveRegistryIndexUrl(undefined)).toBe("https://eve.dev/r/registry.json");+ });++ it("honors an HTTP(S) override, trailing slash included", () => {+ expect(resolveRegistryIndexUrl("http://localhost:4000/r")).toBe(+ "http://localhost:4000/r/registry.json",+ );+ expect(resolveRegistryIndexUrl("http://localhost:4000/r/")).toBe(+ "http://localhost:4000/r/registry.json",+ );+ });++ it("rejects an override that is not a plain HTTP(S) location", () => {+ expect(() => resolveRegistryIndexUrl("file:///tmp/r")).toThrow("HTTP(S) URL");+ expect(() => resolveRegistryIndexUrl("https://user:[email protected]/r")).toThrow(+ "must not include credentials",+ );+ expect(() => resolveRegistryIndexUrl("https://example.com/r?token=abc")).toThrow(+ "query or fragment",+ );+ });+});++describe("selfmod__search_registry", () => {+ function stubFetch(response: { ok: boolean; status?: number; body?: unknown }) {+ const fetchMock = vi.fn().mockResolvedValue({+ json: async () => response.body,+ ok: response.ok,+ status: response.status ?? 200,+ });+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+ }++ /** Narrows the tool's promise-or-stream return to its resolved object. */+ async function run(input: Record<string, unknown>, context: never) {+ const result = await searchRegistry.execute(input, context);+ if (Symbol.asyncIterator in result) {+ throw new TypeError("search_registry must not stream its result.");+ }+ return result;+ }++ function ctx(files: Record<string, string> = {}) {+ return {+ getSandbox: async () => ({+ readTextFile: async ({ path }: { path: string }) => files[path] ?? null,+ }),+ } as never;+ }++ it("returns catalog rows with installed state from the source mount", async () => {+ stubFetch({ body: INDEX, ok: true });++ const result = await run(+ { category: "channel" },+ ctx({ "/source/channels/slack.ts": "export default {}" }),+ );++ expect(result).toEqual({+ errors: [],+ hasMore: false,+ items: [+ {+ address: "channel/slack",+ category: "channel",+ description: "Talk to the agent from Slack.",+ installed: true,+ requires: ">=0.30.0",+ title: "Slack",+ },+ {+ address: "channel/discord",+ category: "channel",+ description: "Talk to the agent from Discord.",+ installed: false,+ title: "Discord",+ },+ {+ address: "linear",+ components: ["channel/linear-agent", "connection/linear"],+ description: "Receive delegated Linear work.",+ title: "Linear",+ },+ ],+ total: 3,+ });+ });++ it("leaves installed absent when the source cannot be read", async () => {+ stubFetch({ body: INDEX, ok: true });++ const result = await run({ query: "slack" }, {+ getSandbox: async () => {+ throw new Error("no sandbox");+ },+ } as never);++ expect(result).toMatchObject({+ hasMore: false,+ items: [+ {+ address: "channel/slack",+ category: "channel",+ description: "Talk to the agent from Slack.",+ requires: ">=0.30.0",+ title: "Slack",+ },+ ],+ total: 1,+ });+ });++ it("reports a catalog failure instead of throwing", async () => {+ stubFetch({ ok: false, status: 503 });++ const result = await run({}, ctx());++ expect(result).toEqual({+ errors: [+ {+ message: "Could not read the eve registry (503).",+ registry: "https://eve.dev/r/registry.json",+ },+ ],+ hasMore: false,+ items: [],+ total: 0,+ });+ });++ it("combines the turn abort signal with the registry timeout", async () => {+ const fetchMock = stubFetch({ body: INDEX, ok: true });+ const controller = new AbortController();++ await run({}, {+ abortSignal: controller.signal,+ getSandbox: async () => ({+ readTextFile: async () => null,+ }),+ } as never);++ const options = fetchMock.mock.calls[0]?.[1] as { signal: AbortSignal };+ expect(options.signal).not.toBe(controller.signal);+ expect(options.signal.aborted).toBe(false);+ controller.abort();+ expect(options.signal.aborted).toBe(true);+ });++ it("serves repeat searches from one fetch", async () => {+ const fetchMock = stubFetch({ body: INDEX, ok: true });++ await run({ query: "slack" }, ctx());+ await run({ query: "notion" }, ctx());++ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});