@jini-ai/http-kit 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/active-context.d.ts +99 -0
  3. package/dist/active-context.js +77 -0
  4. package/dist/agents.d.ts +64 -0
  5. package/dist/agents.js +23 -0
  6. package/dist/attachments.d.ts +534 -0
  7. package/dist/attachments.js +1032 -0
  8. package/dist/cancel-owned-runs.d.ts +44 -0
  9. package/dist/cancel-owned-runs.js +35 -0
  10. package/dist/component-catalog.d.ts +74 -0
  11. package/dist/component-catalog.js +74 -0
  12. package/dist/connectors.d.ts +165 -0
  13. package/dist/connectors.js +474 -0
  14. package/dist/daemon-status.d.ts +72 -0
  15. package/dist/daemon-status.js +60 -0
  16. package/dist/db-ops.d.ts +116 -0
  17. package/dist/db-ops.js +191 -0
  18. package/dist/delegated-tools.d.ts +146 -0
  19. package/dist/delegated-tools.js +286 -0
  20. package/dist/frontend-control.d.ts +131 -0
  21. package/dist/frontend-control.js +77 -0
  22. package/dist/frontend-sessions.d.ts +100 -0
  23. package/dist/frontend-sessions.js +180 -0
  24. package/dist/health.d.ts +91 -0
  25. package/dist/health.js +53 -0
  26. package/dist/host-tools.d.ts +174 -0
  27. package/dist/host-tools.js +338 -0
  28. package/dist/media.d.ts +131 -0
  29. package/dist/media.js +352 -0
  30. package/dist/memory.d.ts +230 -0
  31. package/dist/memory.js +331 -0
  32. package/dist/model-proxy.d.ts +45 -0
  33. package/dist/model-proxy.js +619 -0
  34. package/dist/origin-validation.d.ts +64 -0
  35. package/dist/origin-validation.js +226 -0
  36. package/dist/read-only-tools.d.ts +67 -0
  37. package/dist/read-only-tools.js +59 -0
  38. package/dist/remote-run-events.d.ts +66 -0
  39. package/dist/remote-run-events.js +230 -0
  40. package/dist/research.d.ts +42 -0
  41. package/dist/research.js +316 -0
  42. package/dist/route-manifest.d.ts +31 -0
  43. package/dist/route-manifest.js +103 -0
  44. package/dist/routines.d.ts +114 -0
  45. package/dist/routines.js +320 -0
  46. package/dist/runs.d.ts +79 -0
  47. package/dist/runs.js +232 -0
  48. package/dist/terminals.d.ts +125 -0
  49. package/dist/terminals.js +349 -0
  50. package/dist/tool-catalog.d.ts +68 -0
  51. package/dist/tool-catalog.js +68 -0
  52. package/dist/workspace-root.d.ts +69 -0
  53. package/dist/workspace-root.js +63 -0
  54. package/dist/xai.d.ts +86 -0
  55. package/dist/xai.js +668 -0
  56. package/package.json +7 -7
@@ -0,0 +1,230 @@
1
+ /**
2
+ * @module remote-run-events
3
+ *
4
+ * `POST /api/runs/:runId/tool-use` and `POST /api/runs/:runId/tool-result` — lets a tool call that
5
+ * executed in a DIFFERENT OS process from the one holding this run's `RunLifecycle` report its
6
+ * outcome back into the run's own event log, so SSE subscribers (a chat UI, a reattaching client)
7
+ * see it exactly as they would a locally-executed delegated tool call.
8
+ *
9
+ * This exists to relax `@jini-ai/daemon`'s co-location requirement (`RunLifecycle`/`ToolExecutor`
10
+ * previously had to live in one process per run, because `DelegatedToolBridge.execute()` calls
11
+ * `lifecycle.emit()` in-process with no remote reporting path).
12
+ * It does not remove any authorization: whatever executed the tool remotely already ran it through
13
+ * its OWN `ToolExecutor`/`ToolPolicy` gate before calling here. This route only lets that outcome
14
+ * be recorded into a run it does not own the process of.
15
+ *
16
+ * **Deliberately a separate trust boundary from `registerApiBearerAuthMiddleware`'s general API
17
+ * token** (`api-security-middleware.ts`): that token may reach browser-adjacent callers depending
18
+ * on deployment. This route is meant only for a host's own trusted backend-to-backend delegation
19
+ * (e.g. a sidecar tool-execution process reporting back to the process that owns the run), so its
20
+ * token has no "disabled" escape hatch and does not exempt loopback peers the way the general
21
+ * bearer gate does — a loopback bind is exactly the shape a same-machine but lower-trust process
22
+ * would also present, and this route grants direct run-event-injection, a materially different
23
+ * capability from what the general API token was designed to gate.
24
+ */
25
+ import { randomUUID } from 'node:crypto';
26
+ import { createApiError, isTerminalRunState } from '@jini-ai/protocol';
27
+ import { defineJsonRoute, mountJsonRoute } from './adapter.js';
28
+ import { bearerTokenFromHeader, timingSafeTokenMatch } from './api-security-middleware.js';
29
+ import { validationError } from './request.js';
30
+ import { sendApiError, statusForError } from './response.js';
31
+ import { err, ok } from './types.js';
32
+ function defaultInternalErrorSink(context) {
33
+ // eslint-disable-next-line no-console
34
+ console.error(`[@jini-ai/http-kit] internal error (remote-run-events/${context.source}, correlationId=${context.correlationId})`, context.error);
35
+ }
36
+ const DEFAULT_TOKEN_ENV_VAR = 'JINI_REMOTE_TOOL_BRIDGE_TOKEN';
37
+ /**
38
+ * Gates both remote-run-event routes behind a dedicated shared secret. Unlike
39
+ * `registerApiBearerAuthMiddleware`, there is no "unset means open" or "disabled" mode: a route
40
+ * that lets a caller inject events into someone else's run must never silently run unauthenticated
41
+ * just because a host forgot to configure the token. If the token isn't configured, the route
42
+ * fails closed with 503, not 200.
43
+ *
44
+ * Kept as its own middleware rather than folded into `api-security-middleware.ts`'s
45
+ * `requireStrictBearerToken` (which has the identical fail-closed/no-loopback-exemption posture)
46
+ * because these two routes own their own error codes — `REMOTE_TOOL_BRIDGE_*`, distinct from the
47
+ * general API token's, so an operator can tell which secret is missing from the response alone.
48
+ * The *decision* logic is shared: header parsing and the constant-time comparison both come from
49
+ * that module, so the two gates cannot drift on what counts as a well-formed header or on
50
+ * comparison safety.
51
+ */
52
+ export function requireRemoteToolBridgeToken(deps) {
53
+ const tokenEnvVar = deps.tokenConfig?.tokenEnvVar ?? DEFAULT_TOKEN_ENV_VAR;
54
+ const env = deps.env ?? process.env;
55
+ return (req, res, next) => {
56
+ const token = env[tokenEnvVar];
57
+ if (!token) {
58
+ const error = createApiError('REMOTE_TOOL_BRIDGE_NOT_CONFIGURED', `${tokenEnvVar} is not set — remote run-event ingestion is disabled`);
59
+ sendApiError(res, statusForError(error), error);
60
+ return;
61
+ }
62
+ const presented = bearerTokenFromHeader(req.get('authorization'));
63
+ if (presented === null || !timingSafeTokenMatch(presented, token)) {
64
+ const error = createApiError('REMOTE_TOOL_BRIDGE_TOKEN_REQUIRED', `Authorization: Bearer <${tokenEnvVar}> required`);
65
+ sendApiError(res, statusForError(error), error);
66
+ return;
67
+ }
68
+ next();
69
+ };
70
+ }
71
+ function isRecord(value) {
72
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
73
+ }
74
+ function requireNonEmptyString(body, key) {
75
+ const value = body[key];
76
+ return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
77
+ }
78
+ /**
79
+ * Like {@link requireNonEmptyString} but accepts `''`, for the one field where empty is a real
80
+ * value rather than a missing one: a tool's result `content`.
81
+ *
82
+ * The local path already produces empty content legitimately — `serializeDelegatedToolOutput`
83
+ * (`@jini-ai/daemon`'s `delegated-tool-bridge.ts`) maps a handler returning `undefined` to `''`,
84
+ * and `DelegatedToolBridge.execute()` emits that verbatim as the `tool_result` event's `content`.
85
+ * Rejecting `''` here would mean a tool that legitimately produces no output can be reported
86
+ * in-process but **not** remotely — a silent semantic divergence between the two paths that would
87
+ * surface as a 400 on the one tool call a host least expects to fail. Identifiers (`runId`,
88
+ * `toolUseId`, `toolId`) keep the non-empty check: for those, empty really is missing.
89
+ */
90
+ function requireString(body, key) {
91
+ const value = body[key];
92
+ return typeof value === 'string' ? value : undefined;
93
+ }
94
+ function parseRunId(input) {
95
+ const runId = input.params.runId;
96
+ return typeof runId === 'string' && runId.length > 0
97
+ ? ok(runId)
98
+ : err(validationError('runId must be a non-empty path parameter'));
99
+ }
100
+ function parseRemoteToolUse(input) {
101
+ const parsedRunId = parseRunId(input);
102
+ if (!parsedRunId.ok)
103
+ return parsedRunId;
104
+ if (!isRecord(input.body))
105
+ return err(validationError('body must be a JSON object'));
106
+ const toolUseId = requireNonEmptyString(input.body, 'toolUseId');
107
+ if (toolUseId === undefined) {
108
+ return err(validationError('toolUseId must be a non-empty string', [{ path: 'toolUseId', message: 'required non-empty string' }]));
109
+ }
110
+ const toolId = requireNonEmptyString(input.body, 'toolId');
111
+ if (toolId === undefined) {
112
+ return err(validationError('toolId must be a non-empty string', [{ path: 'toolId', message: 'required non-empty string' }]));
113
+ }
114
+ return ok({ runId: parsedRunId.value, toolUseId, toolId, input: input.body.input });
115
+ }
116
+ function parseRemoteToolResult(input) {
117
+ const parsedRunId = parseRunId(input);
118
+ if (!parsedRunId.ok)
119
+ return parsedRunId;
120
+ if (!isRecord(input.body))
121
+ return err(validationError('body must be a JSON object'));
122
+ const toolUseId = requireNonEmptyString(input.body, 'toolUseId');
123
+ if (toolUseId === undefined) {
124
+ return err(validationError('toolUseId must be a non-empty string', [{ path: 'toolUseId', message: 'required non-empty string' }]));
125
+ }
126
+ // Empty is allowed here, deliberately — see `requireString`'s own doc for the local-path parity
127
+ // this preserves. Only a non-string (or absent) `content` is a validation failure.
128
+ const content = requireString(input.body, 'content');
129
+ if (content === undefined) {
130
+ return err(validationError('content must be a string', [{ path: 'content', message: 'required string' }]));
131
+ }
132
+ const isError = input.body.isError;
133
+ if (isError !== undefined && typeof isError !== 'boolean') {
134
+ return err(validationError('isError must be a boolean when provided', [{ path: 'isError', message: 'boolean when provided' }]));
135
+ }
136
+ return ok({ runId: parsedRunId.value, toolUseId, content, ...(isError === undefined ? {} : { isError }) });
137
+ }
138
+ /**
139
+ * Records a caught `recordToolUse`/`recordToolResult` throw as the right HTTP outcome.
140
+ *
141
+ * `RunLifecycle.emit()` throws for two documented reasons (see `run-lifecycle.ts`'s own `emit`) —
142
+ * unknown `runId` and "already terminal" — but the recorder call it sits behind can also fail for
143
+ * reasons that are nobody's business but the operator's: an event-log write hitting a full disk, a
144
+ * SQLite error naming its own file path, a driver fault carrying a credential in its message.
145
+ *
146
+ * This previously reported *every* one of those as `CONFLICT` carrying `error.message` verbatim,
147
+ * which turned any such fault into an unauthenticated-adjacent information leak and mislabelled a
148
+ * server fault as a client-resolvable conflict. So the outcome is now decided by the run's actual
149
+ * state rather than by whatever the exception happened to say:
150
+ *
151
+ * - run is gone -> `NOT_FOUND` (it was there for the pre-check; it isn't now).
152
+ * - run is terminal -> `CONFLICT`, the one legitimate business conflict. The message is
153
+ * *constructed here* from data this module already owns rather than forwarded from the
154
+ * exception, so even a misattributed error cannot smuggle its text out through this branch.
155
+ * - anything else -> SEC-005: a generic `INTERNAL_ERROR` plus a correlation id, with the real
156
+ * error handed to the host's sink so it is diagnosable server-side but never echoed.
157
+ *
158
+ * Residual, deliberately accepted: a genuine storage fault that happens to coincide with an
159
+ * already-terminal run is reported as `CONFLICT` rather than `INTERNAL_ERROR`. Distinguishing those
160
+ * would require matching on `emit`'s message text, trading a rare wrong status code for a check
161
+ * that breaks silently the next time that string is reworded. Either way nothing leaks, which is
162
+ * the property that mattered.
163
+ */
164
+ async function toRemoteEventError(error, runId, deps, source) {
165
+ const status = await deps.lifecycle.get(runId).catch(() => undefined);
166
+ if (status === undefined) {
167
+ return createApiError('NOT_FOUND', `run "${runId}" was not found`);
168
+ }
169
+ if (isTerminalRunState(status.state)) {
170
+ return createApiError('CONFLICT', `run "${runId}" is already terminal — no further events can be recorded`, {
171
+ details: { runId },
172
+ });
173
+ }
174
+ const correlationId = randomUUID();
175
+ const sink = deps.onInternalError ?? defaultInternalErrorSink;
176
+ sink({ source, correlationId, error });
177
+ return createApiError('INTERNAL_ERROR', 'an internal error occurred', { requestId: correlationId });
178
+ }
179
+ export const remoteToolUseRoute = defineJsonRoute({
180
+ method: 'post',
181
+ path: '/api/runs/:runId/tool-use',
182
+ parse: parseRemoteToolUse,
183
+ handle: async (input, deps) => {
184
+ const run = await deps.lifecycle.get(input.runId);
185
+ if (run === undefined)
186
+ return err(createApiError('NOT_FOUND', `run "${input.runId}" was not found`));
187
+ try {
188
+ await deps.recorder.recordToolUse(input.runId, { toolUseId: input.toolUseId, toolId: input.toolId, input: input.input });
189
+ return ok({ recorded: true });
190
+ }
191
+ catch (error) {
192
+ return err(await toRemoteEventError(error, input.runId, deps, 'tool-use'));
193
+ }
194
+ },
195
+ });
196
+ export const remoteToolResultRoute = defineJsonRoute({
197
+ method: 'post',
198
+ path: '/api/runs/:runId/tool-result',
199
+ parse: parseRemoteToolResult,
200
+ handle: async (input, deps) => {
201
+ const run = await deps.lifecycle.get(input.runId);
202
+ if (run === undefined)
203
+ return err(createApiError('NOT_FOUND', `run "${input.runId}" was not found`));
204
+ try {
205
+ await deps.recorder.recordToolResult(input.runId, {
206
+ toolUseId: input.toolUseId,
207
+ content: input.content,
208
+ ...(input.isError === undefined ? {} : { isError: input.isError }),
209
+ });
210
+ return ok({ recorded: true });
211
+ }
212
+ catch (error) {
213
+ return err(await toRemoteEventError(error, input.runId, deps, 'tool-result'));
214
+ }
215
+ },
216
+ });
217
+ /**
218
+ * Mounts both remote-run-event routes on `app`, gated by {@link requireRemoteToolBridgeToken}.
219
+ * Unlike `registerRunRoutes`/`registerDelegatedToolRoutes`, these routes do not use
220
+ * `requireSameOrigin` — they are not meant to be called from a browser at all, only from a host's
221
+ * own trusted backend process, so the dedicated bearer token above is the sole gate.
222
+ */
223
+ export function registerRemoteRunEventRoutes(app, deps, adapter) {
224
+ const gate = requireRemoteToolBridgeToken(deps);
225
+ app.use('/api/runs/:runId/tool-use', gate);
226
+ app.use('/api/runs/:runId/tool-result', gate);
227
+ mountJsonRoute(app, remoteToolUseRoute, deps, adapter);
228
+ mountJsonRoute(app, remoteToolResultRoute, deps, adapter);
229
+ }
230
+ //# sourceMappingURL=remote-run-events.js.map
@@ -0,0 +1,42 @@
1
+ import type { Express } from 'express';
2
+ import { type AdapterContext } from './adapter.js';
3
+ export interface ResearchSource {
4
+ readonly title: string;
5
+ readonly url: string;
6
+ readonly snippet: string;
7
+ readonly publishedAt?: string;
8
+ readonly provider: string;
9
+ }
10
+ /** Matches OD's real `@open-design/contracts/api/research.ts` `ResearchFindings` shape — see module doc. */
11
+ export interface ResearchSearchResponse {
12
+ readonly query: string;
13
+ readonly summary: string;
14
+ readonly sources: readonly ResearchSource[];
15
+ readonly provider: string;
16
+ readonly depth: 'shallow';
17
+ readonly fetchedAt: number;
18
+ }
19
+ export interface ResearchInternalErrorContext {
20
+ readonly correlationId: string;
21
+ readonly error: unknown;
22
+ }
23
+ export interface ResearchProviderCredentials {
24
+ readonly apiKey?: string;
25
+ readonly baseUrl?: string;
26
+ readonly model?: string;
27
+ }
28
+ export interface ResearchHttpDeps {
29
+ /** Resolves per-provider credentials. Defaults to `TAVILY_API_KEY` for the built-in Tavily transport. */
30
+ readonly resolveCredentials?: (providerId: string) => Promise<ResearchProviderCredentials>;
31
+ /** Host-owned sink for the real exception behind a generic `INTERNAL_ERROR` response (SEC-005). Defaults to `console.error`. */
32
+ readonly onInternalError?: (context: ResearchInternalErrorContext) => void;
33
+ }
34
+ interface ResearchSearchRequest {
35
+ readonly query: string;
36
+ readonly maxSources?: number;
37
+ }
38
+ export declare const researchSearchRoute: import("./types.js").JsonRouteSpec<ResearchSearchRequest, ResearchSearchResponse, ResearchHttpDeps>;
39
+ /** Mounts `POST /api/research/search` on `app`. A pack's `http(app, services)` calls this directly. */
40
+ export declare function registerResearchRoutes(app: Express, deps: ResearchHttpDeps, adapter: AdapterContext): void;
41
+ export {};
42
+ //# sourceMappingURL=research.d.ts.map
@@ -0,0 +1,316 @@
1
+ /**
2
+ * @module research
3
+ *
4
+ * `POST /api/research/search` — a thin route wrapper over Tavily's real Search API
5
+ * (`POST {baseUrl}/search`), ported from OD's `apps/daemon/src/research/tavily.ts` (the low-level
6
+ * Tavily client) **and** `apps/daemon/src/research/index.ts#searchResearch` (the findings-assembly
7
+ * wrapper the real `/api/research/search` route in `apps/daemon/src/routes/media.ts` actually
8
+ * calls). Verified against a **live** boot of OD's real daemon (`apps/daemon/bin/od.mjs`, from the
9
+ * sibling `/Users/la/Desktop/Programming/OSS-Repos/open-design` checkout on this machine) hitting
10
+ * the real route with a mock Tavily backend, not just static reading — see the field-by-field notes
11
+ * below for what that live diff actually found. The request/response shape and defaults are ported
12
+ * (`search_depth: 'basic'`, `include_answer: true`, `include_raw_content: false`, a 20-result hard
13
+ * cap, the `results[]` -> `ResearchSource[]` mapping, the 1000-char query cap, the
14
+ * `Math.floor`+clamp-to-`[1,20]` `maxSources` normalization, and the `NO_RESEARCH_SOURCES`-style
15
+ * "zero sources is a failure, not an empty success" behavior) — OD's own `TavilyError`/
16
+ * `ResearchError` classes and `requestInit.dispatcher` passthrough are not carried over; this route
17
+ * pack's own SEC-005 error-handling convention (a generic `INTERNAL_ERROR` + correlation id,
18
+ * matching every other route pack in this package) replaces the origin's thrown-error shape for
19
+ * genuinely unexpected failures. OD's `AbortController`-based 30s timeout **is** carried over
20
+ * (added after an external audit flagged its absence — a stalled/malicious upstream could otherwise
21
+ * hold a request indefinitely, since bare `fetch` has no default timeout): `tavilySearch` aborts
22
+ * the request after `DEFAULT_TAVILY_TIMEOUT_MS` and clears the timer in a `finally` regardless of
23
+ * outcome. No other request-level knobs (connection pooling, `dispatcher`) are exposed yet — a
24
+ * future pass can add them the same way `media.ts#MediaGenerationRequestInit` optionally threads a
25
+ * `dispatcher` through, if a real need for one shows up.
26
+ *
27
+ * **`ResearchSource` field names match OD's real `@open-design/contracts/api/research.ts`
28
+ * `ResearchSource` shape** (`title`/`url`/`snippet`/`publishedAt?`/`provider`). **`ResearchSearchResponse`
29
+ * matches that same contract file's `ResearchFindings` shape** (`query`/`summary`/`sources`/
30
+ * `provider`/`depth`/`fetchedAt`) — an earlier version of this port conflated the *raw Tavily
31
+ * client's* return shape (`tavily.ts`'s `{ answer, sources }`) with the *route's actual HTTP
32
+ * response* shape (`research/index.ts#searchResearch`'s `ResearchFindings`), which the live daemon
33
+ * diff caught: hitting the real `/api/research/search` with a mock Tavily backend returned
34
+ * `{"query":"...","summary":"...","sources":[...],"provider":"tavily","depth":"shallow",
35
+ * "fetchedAt":<ms>}`, never `{answer, sources}`. `depth` is hardcoded to the `'shallow'` literal
36
+ * (rather than OD's full `'shallow' | 'medium' | 'deep'` `ResearchDepth` union) since this port, like
37
+ * OD's real Phase-1 `searchResearch`, only ever produces `'shallow'` — there is no depth-selection
38
+ * request field on either side yet.
39
+ *
40
+ * **`providers` request field**: OD's real route accepts an optional `providers: string[]` and only
41
+ * inspects `providers[0]` (defaulting to `'tavily'` when absent/empty); a non-array value is treated
42
+ * as absent (not rejected), and a first element other than `'tavily'` is rejected with a 400 before
43
+ * credentials are even resolved (`UNSUPPORTED_RESEARCH_PROVIDER` in OD; this port's own generic
44
+ * `BAD_REQUEST` validation-error convention here, same as every other `parse`-time rejection in this
45
+ * file). Confirmed live: `providers: ["bing"]` 400s on the real daemon, `providers: ["tavily"]`
46
+ * succeeds identically to omitting the field.
47
+ *
48
+ * **Credential resolution**: `resolveCredentials` defaults to this transport's narrow
49
+ * `TAVILY_API_KEY` environment seam. A host with its own secrets layer supplies its own resolver
50
+ * instead; `@jini-ai/http-kit` deliberately does not depend on the incubating media implementation
51
+ * package. Note OD's real env-var precedence is
52
+ * `['OD_TAVILY_API_KEY', 'TAVILY_API_KEY']` (checked live via `apps/daemon/tests/research.test.ts`'s
53
+ * `TAVILY_ENV_KEYS`) — this package's own `@jini-ai/media#PROVIDER_CREDENTIAL_ENV_VARS.tavily` only
54
+ * lists `['TAVILY_API_KEY']`, deliberately dropping the `OD_`-prefixed variant: this repo's own
55
+ * `AGENTS.md` boundary rule bans product-identity strings (including the `OD_` prefix) inside
56
+ * `packages/@jini-ai/**`, so that omission is a hard constraint, not a port gap.
57
+ *
58
+ * **Missing credentials is a clean `NOT_CONFIGURED` (503), not an `INTERNAL_ERROR`.** No API key
59
+ * configured is an expected, non-exceptional state (matching `connectors.ts`'s "capability exists,
60
+ * reachable, inert until configured" shape) — it never reaches the SEC-005 sink, since there is no
61
+ * real exception or secret to hide, just an honest "not set up yet" answer. OD's real behavior here
62
+ * (confirmed live) is a 400 `TAVILY_API_KEY_MISSING`, not a 503 — this is a deliberate, documented
63
+ * divergence from OD (this package's own generic-error-code convention, applied consistently across
64
+ * every route pack) rather than an oversight, so it is intentionally **not** changed to match OD's
65
+ * 400.
66
+ *
67
+ * **Zero sources is a `NOT_FOUND` (404), not a `200` with an empty array.** OD's real
68
+ * `searchResearch` throws `ResearchError('no sources found', 404, 'NO_RESEARCH_SOURCES')` when
69
+ * Tavily's `results[]` maps to zero usable sources (confirmed live against a mock Tavily backend
70
+ * that returns `results: []`) — this port matches that with the package's own generic `NOT_FOUND`
71
+ * code (mapped to 404 by `response.ts#ERROR_STATUS_BY_CODE`) rather than inventing a
72
+ * research-specific code, same rationale as the `NOT_CONFIGURED` choice above.
73
+ *
74
+ * **Query normalization**: OD's real `searchResearch` trims the query and caps it at 1000 characters
75
+ * before ever calling Tavily (`(input.query?.trim() || '').slice(0, 1000)`) — confirmed live by
76
+ * sending a padded, 1112-char query and observing the daemon forward exactly 1000 trimmed
77
+ * characters to the mock Tavily backend. This port replicates both the trim and the cap in
78
+ * `parseResearchSearch`.
79
+ *
80
+ * **`maxSources` normalization**: OD's real `clampMaxSources` is `Math.max(1, Math.min(Math.floor(value),
81
+ * 20))` — confirmed live by sending `maxSources: 2.7` and observing `max_results: 2` (not `2.7`) on
82
+ * the wire to the mock Tavily backend. An earlier version of this port only clamped the range
83
+ * (`Math.max(0, Math.min(value, 20))`) without flooring, which could forward a fractional
84
+ * `max_results` straight to Tavily's real API for any non-integer input (e.g. `maxSources: 0.5`
85
+ * would have clamped to `0.5`, not `1`); this port now floors first, matching OD.
86
+ *
87
+ * **SEC-005 for everything else**: a genuine Tavily request/response failure is caught, reported
88
+ * through `onInternalError` (defaults to `console.error`, matching every other route pack), and
89
+ * surfaced to the caller as a generic `INTERNAL_ERROR` — the raw error message (which can echo
90
+ * request details) is never sent to the HTTP caller directly. `redactSecrets` (reused from
91
+ * `@jini-ai/agent-runtime`'s `connection-guard.ts`, already reachable via this package's existing
92
+ * `@jini-ai/agent-runtime` dependency — the same "shared primitive, one implementation" reuse this
93
+ * task's agent-runtime work applied to `sse-decode.ts`/`turn-end-guard.ts`) strips the bearer
94
+ * token out of any upstream error text before it is even logged, belt-and-braces alongside the
95
+ * generic-message substitution.
96
+ */
97
+ import { randomUUID } from 'node:crypto';
98
+ import { redactSecrets, validateBaseUrl } from '@jini-ai/agent-runtime';
99
+ import { createApiError } from '@jini-ai/protocol';
100
+ import { defineJsonRoute, mountJsonRoute } from './adapter.js';
101
+ import { validationError } from './request.js';
102
+ import { err, ok } from './types.js';
103
+ const DEFAULT_TAVILY_BASE_URL = 'https://api.tavily.com';
104
+ /** Tavily's own documented cap on `max_results` (see OD's `tavily.ts#TAVILY_MAX_RESULTS_LIMIT`). */
105
+ const TAVILY_MAX_RESULTS_LIMIT = 20;
106
+ const DEFAULT_MAX_SOURCES = 5;
107
+ /** Matches OD's own `tavily.ts` timeout — see module doc. */
108
+ const DEFAULT_TAVILY_TIMEOUT_MS = 30_000;
109
+ /** Matches OD's real `research/index.ts#searchResearch` query cap — see module doc. */
110
+ const MAX_QUERY_LENGTH = 1000;
111
+ function defaultInternalErrorSink(context) {
112
+ // eslint-disable-next-line no-console
113
+ console.error(`[@jini-ai/http-kit] internal error (research/search, correlationId=${context.correlationId})`, context.error);
114
+ }
115
+ /**
116
+ * Default `ResearchHttpDeps.resolveCredentials`: reads `TAVILY_API_KEY` from the environment.
117
+ *
118
+ * Takes no `providerId` even though the `resolveCredentials` dep type supplies one (a function of
119
+ * fewer parameters is assignable, so this still satisfies the interface). It used to accept one and
120
+ * return `{}` for anything other than `'tavily'`, but that arm was unreachable twice over: the only
121
+ * call site below passes the literal `'tavily'`, and `validateRequestedProvider` already rejects any
122
+ * other provider name at parse time. A host that supports a second provider injects its own
123
+ * `resolveCredentials` rather than reaching this function with a different id.
124
+ */
125
+ async function defaultResolveCredentials() {
126
+ const apiKey = process.env.TAVILY_API_KEY?.trim();
127
+ return apiKey ? { apiKey } : {};
128
+ }
129
+ function isRecord(value) {
130
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
131
+ }
132
+ function nonEmptyString(value) {
133
+ return typeof value === 'string' && value.trim().length > 0 ? value : null;
134
+ }
135
+ /**
136
+ * Only `'tavily'` is a supported provider (matches OD's real Phase-1 `searchResearch` — see module
137
+ * doc). OD only inspects `providers[0]` and treats a non-array `providers` value as absent rather
138
+ * than rejecting it; this mirrors both.
139
+ */
140
+ function validateRequestedProvider(rawProviders) {
141
+ if (!Array.isArray(rawProviders))
142
+ return ok(null);
143
+ const filtered = rawProviders.filter((p) => typeof p === 'string' && p.length > 0);
144
+ const requested = filtered[0];
145
+ if (requested !== undefined && requested !== 'tavily') {
146
+ return err(validationError(`provider "${requested}" is not supported — only "tavily" is available`));
147
+ }
148
+ return ok(null);
149
+ }
150
+ function parseResearchSearch(input) {
151
+ if (!isRecord(input.body))
152
+ return err(validationError('body must be a JSON object'));
153
+ const rawQuery = nonEmptyString(input.body.query);
154
+ if (!rawQuery)
155
+ return err(validationError('query must be a non-empty string', [{ path: 'query', message: 'required non-empty string' }]));
156
+ const query = rawQuery.trim().slice(0, MAX_QUERY_LENGTH);
157
+ const maxSources = input.body.maxSources;
158
+ if (maxSources !== undefined && (typeof maxSources !== 'number' || !Number.isFinite(maxSources) || maxSources <= 0)) {
159
+ return err(validationError('maxSources must be a positive number when provided'));
160
+ }
161
+ const providerCheck = validateRequestedProvider(input.body.providers);
162
+ if (!providerCheck.ok)
163
+ return providerCheck;
164
+ return ok({ query, ...(maxSources !== undefined ? { maxSources: maxSources } : {}) });
165
+ }
166
+ /**
167
+ * Calls Tavily's real `POST /search` endpoint directly — see module doc for the port's exact
168
+ * scope/provenance. Throws (never a `Result`) on any failure; the route handler below is the one
169
+ * place that converts a thrown error into the package's SEC-005 response shape.
170
+ *
171
+ * `apiKey` is a separate, non-optional parameter rather than being read off `credentials`, so the
172
+ * "credential is present" invariant is carried by the type system instead of by a runtime guard.
173
+ * This function used to take only `credentials` and re-check `credentials.apiKey` itself, but the
174
+ * sole caller below already returns `NOT_CONFIGURED` before it ever gets here — the check was
175
+ * unreachable by construction, so it is now expressed as a required argument instead of dead code.
176
+ * `credentials` is still passed for its optional transport config (`baseUrl`).
177
+ */
178
+ async function tavilySearch(apiKey, credentials, request) {
179
+ const baseUrl = credentials.baseUrl ?? DEFAULT_TAVILY_BASE_URL;
180
+ const baseUrlCheck = validateBaseUrl(baseUrl);
181
+ if (baseUrlCheck.error) {
182
+ throw new Error(baseUrlCheck.error);
183
+ }
184
+ const base = baseUrl.replace(/\/+$/, '');
185
+ // Floor before clamping, matching OD's real `clampMaxSources` — see module doc. Without the
186
+ // floor, a fractional `maxSources` (e.g. `2.7`, or `0.5` before the `Math.max(1, ...)` floor
187
+ // below) would forward a non-integer `max_results` straight to Tavily's real API.
188
+ const maxResults = Math.max(1, Math.min(Math.floor(request.maxSources ?? DEFAULT_MAX_SOURCES), TAVILY_MAX_RESULTS_LIMIT));
189
+ const body = {
190
+ query: request.query,
191
+ search_depth: 'basic',
192
+ max_results: maxResults,
193
+ include_answer: true,
194
+ include_raw_content: false,
195
+ };
196
+ // The timeout must stay armed for the full operation, not just until `fetch` resolves —
197
+ // `fetch` resolves as soon as response headers arrive, before the body is read. A round-2
198
+ // external audit caught (and locally reproduced) an earlier version of this fix that cleared
199
+ // the timer right after `fetch` resolved, leaving `response.text()`/`response.json()` below
200
+ // completely unbounded against a server that sends headers promptly and then stalls the body.
201
+ //
202
+ // `TavilyHttpError` marks an error already redacted and formatted by the `!response.ok` branch
203
+ // below, so the outer catch can rethrow it verbatim instead of wrapping it a second time (which
204
+ // would otherwise produce a "Tavily request failed: Tavily 429: ..." double-prefixed message).
205
+ class TavilyHttpError extends Error {
206
+ }
207
+ const timeoutController = new AbortController();
208
+ const timeoutHandle = setTimeout(() => timeoutController.abort(), DEFAULT_TAVILY_TIMEOUT_MS);
209
+ // Assigned in the `try` and returned *after* the `finally`, rather than returned from inside the
210
+ // `try`. Both forms behave identically, but a return-through-`finally` compiles to three copies of
211
+ // the `finally` body (normal completion, return, throw) and one of those is unreachable here — the
212
+ // `try` cannot fall off its end and the `catch` always throws. Falling through to a single return
213
+ // keeps the cleanup path honestly measurable instead of permanently one-third uncovered.
214
+ let output;
215
+ try {
216
+ const response = await fetch(`${base}/search`, {
217
+ method: 'POST',
218
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },
219
+ body: JSON.stringify(body),
220
+ signal: timeoutController.signal,
221
+ });
222
+ if (!response.ok) {
223
+ const text = await response.text().catch(() => '');
224
+ throw new TavilyHttpError(redactSecrets(`Tavily ${response.status}: ${text.slice(0, 200) || 'no body'}`, [apiKey]));
225
+ }
226
+ const json = (await response.json());
227
+ const answer = typeof json.answer === 'string' ? json.answer : '';
228
+ const rawResults = Array.isArray(json.results) ? json.results : [];
229
+ const sources = [];
230
+ for (const raw of rawResults) {
231
+ const url = typeof raw.url === 'string' ? raw.url : '';
232
+ if (!url)
233
+ continue;
234
+ const publishedAt = typeof raw.published_date === 'string' && raw.published_date.trim() ? raw.published_date.trim() : undefined;
235
+ sources.push({
236
+ title: typeof raw.title === 'string' && raw.title.trim() ? raw.title.trim() : url,
237
+ url,
238
+ snippet: typeof raw.content === 'string' ? raw.content.trim().slice(0, 800) : '',
239
+ provider: 'tavily',
240
+ ...(publishedAt ? { publishedAt } : {}),
241
+ });
242
+ }
243
+ output = { answer, sources };
244
+ }
245
+ catch (error) {
246
+ if (!timeoutController.signal.aborted && error instanceof TavilyHttpError) {
247
+ throw error;
248
+ }
249
+ const message = error instanceof Error ? error.message : String(error);
250
+ throw new Error(redactSecrets(timeoutController.signal.aborted
251
+ ? `Tavily request timed out after ${DEFAULT_TAVILY_TIMEOUT_MS}ms`
252
+ : `Tavily request failed: ${message}`, [apiKey]));
253
+ }
254
+ finally {
255
+ clearTimeout(timeoutHandle);
256
+ }
257
+ return output;
258
+ }
259
+ /** Ported verbatim from OD's real `research/index.ts#synthesizeFallbackSummary` — see module doc. Used when Tavily returns no `answer` text so the caller still gets a usable `summary`. */
260
+ function synthesizeFallbackSummary(sources) {
261
+ const lead = sources
262
+ .slice(0, 5)
263
+ .map((s, i) => `- [${i + 1}] ${s.title}: ${s.snippet.slice(0, 200)}`)
264
+ .join('\n');
265
+ return `(No provider summary; top snippets follow.)\n${lead}`;
266
+ }
267
+ export const researchSearchRoute = defineJsonRoute({
268
+ method: 'post',
269
+ path: '/api/research/search',
270
+ requireSameOrigin: true,
271
+ parse: parseResearchSearch,
272
+ handle: async (request, deps) => {
273
+ const resolveCredentials = deps.resolveCredentials ?? defaultResolveCredentials;
274
+ const onInternalError = deps.onInternalError ?? defaultInternalErrorSink;
275
+ let credentials;
276
+ try {
277
+ credentials = await resolveCredentials('tavily');
278
+ }
279
+ catch (error) {
280
+ const correlationId = randomUUID();
281
+ onInternalError({ correlationId, error });
282
+ return err(createApiError('INTERNAL_ERROR', 'an internal error occurred', { requestId: correlationId }));
283
+ }
284
+ const apiKey = credentials.apiKey;
285
+ if (!apiKey) {
286
+ return err(createApiError('NOT_CONFIGURED', 'tavily provider not configured'));
287
+ }
288
+ try {
289
+ const raw = await tavilySearch(apiKey, credentials, request);
290
+ // Matches OD's real `NO_RESEARCH_SOURCES` (404) — see module doc. Zero usable sources is a
291
+ // failure, not an empty success, even when the upstream Tavily call itself succeeded.
292
+ if (raw.sources.length === 0) {
293
+ return err(createApiError('NOT_FOUND', 'no sources found'));
294
+ }
295
+ const result = {
296
+ query: request.query,
297
+ summary: raw.answer || synthesizeFallbackSummary(raw.sources),
298
+ sources: raw.sources,
299
+ provider: 'tavily',
300
+ depth: 'shallow',
301
+ fetchedAt: Date.now(),
302
+ };
303
+ return ok(result);
304
+ }
305
+ catch (error) {
306
+ const correlationId = randomUUID();
307
+ onInternalError({ correlationId, error });
308
+ return err(createApiError('INTERNAL_ERROR', 'an internal error occurred', { requestId: correlationId }));
309
+ }
310
+ },
311
+ });
312
+ /** Mounts `POST /api/research/search` on `app`. A pack's `http(app, services)` calls this directly. */
313
+ export function registerResearchRoutes(app, deps, adapter) {
314
+ mountJsonRoute(app, researchSearchRoute, deps, adapter);
315
+ }
316
+ //# sourceMappingURL=research.js.map
@@ -0,0 +1,31 @@
1
+ import type { RouteRegistration } from './route-registration-guard.js';
2
+ /**
3
+ * Route families described by this manifest, keyed by the same feature id `@jini-ai/server`'s built-in
4
+ * feature catalog uses — so a host that enables features by name can look routes up by that same name.
5
+ */
6
+ export declare const JINI_ROUTE_MANIFEST: Readonly<Record<string, readonly RouteRegistration[]>>;
7
+ /**
8
+ * The routes one family mounts.
9
+ *
10
+ * @param family - A feature id, e.g. `'runs'`.
11
+ * @returns That family's registrations, or `undefined` when the family is not described by this
12
+ * manifest. The distinction matters: a caller building a proxy allow-list must treat `undefined` as
13
+ * "look it up yourself", never as "this family has no routes" — see this module's scope note.
14
+ * @complexity O(1).
15
+ * @overallScore 100/100
16
+ */
17
+ export declare function routeFamilyManifest(family: string): readonly RouteRegistration[] | undefined;
18
+ /**
19
+ * Every route across every family this manifest describes, de-duplicated.
20
+ *
21
+ * De-duplication is real rather than defensive: `health` intentionally mounts both `/health` and
22
+ * `/api/health` as separate routes, and a future family could legitimately share a path with another.
23
+ *
24
+ * @param families - Family ids to include. Unknown ids contribute nothing (rather than throwing), so a
25
+ * caller can pass its enabled-feature list verbatim without pre-filtering it.
26
+ * @returns One entry per distinct `METHOD PATH`, in first-seen order.
27
+ * @complexity O(n) in the total routes across the named families.
28
+ * @overallScore 100/100
29
+ */
30
+ export declare function manifestRoutesForFamilies(families: readonly string[]): readonly RouteRegistration[];
31
+ //# sourceMappingURL=route-manifest.d.ts.map