@jini-ai/http-kit 0.4.1 → 0.4.3

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 (61) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/adapter.js +56 -47
  3. package/dist/local-daemon-request.js +11 -5
  4. package/dist/observability.d.ts +18 -0
  5. package/dist/observability.js +19 -0
  6. package/dist/verified-origin/site-path.js +5 -1
  7. package/package.json +7 -7
  8. package/dist/active-context.d.ts +0 -99
  9. package/dist/active-context.js +0 -77
  10. package/dist/agents.d.ts +0 -64
  11. package/dist/agents.js +0 -23
  12. package/dist/attachments.d.ts +0 -534
  13. package/dist/attachments.js +0 -1032
  14. package/dist/cancel-owned-runs.d.ts +0 -44
  15. package/dist/cancel-owned-runs.js +0 -35
  16. package/dist/component-catalog.d.ts +0 -74
  17. package/dist/component-catalog.js +0 -74
  18. package/dist/connectors.d.ts +0 -165
  19. package/dist/connectors.js +0 -474
  20. package/dist/daemon-status.d.ts +0 -72
  21. package/dist/daemon-status.js +0 -60
  22. package/dist/db-ops.d.ts +0 -116
  23. package/dist/db-ops.js +0 -191
  24. package/dist/delegated-tools.d.ts +0 -146
  25. package/dist/delegated-tools.js +0 -286
  26. package/dist/frontend-control.d.ts +0 -131
  27. package/dist/frontend-control.js +0 -77
  28. package/dist/frontend-sessions.d.ts +0 -100
  29. package/dist/frontend-sessions.js +0 -180
  30. package/dist/health.d.ts +0 -91
  31. package/dist/health.js +0 -53
  32. package/dist/host-tools.d.ts +0 -174
  33. package/dist/host-tools.js +0 -338
  34. package/dist/media.d.ts +0 -131
  35. package/dist/media.js +0 -352
  36. package/dist/memory.d.ts +0 -230
  37. package/dist/memory.js +0 -331
  38. package/dist/model-proxy.d.ts +0 -45
  39. package/dist/model-proxy.js +0 -619
  40. package/dist/origin-validation.d.ts +0 -64
  41. package/dist/origin-validation.js +0 -226
  42. package/dist/read-only-tools.d.ts +0 -67
  43. package/dist/read-only-tools.js +0 -59
  44. package/dist/remote-run-events.d.ts +0 -66
  45. package/dist/remote-run-events.js +0 -230
  46. package/dist/research.d.ts +0 -42
  47. package/dist/research.js +0 -316
  48. package/dist/route-manifest.d.ts +0 -31
  49. package/dist/route-manifest.js +0 -103
  50. package/dist/routines.d.ts +0 -114
  51. package/dist/routines.js +0 -320
  52. package/dist/runs.d.ts +0 -79
  53. package/dist/runs.js +0 -232
  54. package/dist/terminals.d.ts +0 -125
  55. package/dist/terminals.js +0 -349
  56. package/dist/tool-catalog.d.ts +0 -68
  57. package/dist/tool-catalog.js +0 -68
  58. package/dist/workspace-root.d.ts +0 -69
  59. package/dist/workspace-root.js +0 -63
  60. package/dist/xai.d.ts +0 -86
  61. package/dist/xai.js +0 -668
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @jini-ai/http-kit
2
2
 
3
+ ## 0.4.3 — 2026-10-22
4
+
5
+ - 2026-10-22: Completed-request logging off by default (one compact line when enabled), coverage.
6
+
7
+ ## 0.4.2 — 2026-10-14
8
+
9
+ - Express 5 accepted: the optional `express` peer is now `^4.21.0 || ^5.0.0` (1442d875), so an Express 5 host no longer hits ERESOLVE.
10
+
3
11
  ## 0.4.1
4
12
 
5
13
  ### Patch Changes
package/dist/adapter.js CHANGED
@@ -51,8 +51,7 @@ export class ClientFacingError extends Error {
51
51
  * @complexity O(1) time/space for the fixed spec fields.
52
52
  */
53
53
  export function defineJsonRoute(requiredArgs, optionalArgs = {}) {
54
- const spec = { ...requiredArgs, ...optionalArgs };
55
- return spec;
54
+ return { ...requiredArgs, ...optionalArgs };
56
55
  }
57
56
  /**
58
57
  * Mounts one JsonRouteSpec on an Express app. The Adapter is the only code here that knows
@@ -86,15 +85,8 @@ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
86
85
  const raw = rawInput({ req });
87
86
  if (spec.ports?.workspace)
88
87
  await spec.ports.workspace({ raw, deps });
89
- if (spec.requireSameOrigin) {
90
- if (!adapter)
91
- throw new Error('same-origin adapter context is required');
92
- const origin = guardSameOrigin({ req, origin: adapter });
93
- if (!origin.ok) {
94
- sendApiError({ res, status: statusForError({ error: origin.error }), error: origin.error });
95
- return;
96
- }
97
- }
88
+ if (!allowRouteOrigin({ req, res, spec, adapter }))
89
+ return;
98
90
  let context;
99
91
  if (spec.ports?.authenticate)
100
92
  context = await spec.ports.authenticate({ raw, res, deps });
@@ -111,48 +103,65 @@ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
111
103
  await spec.ports.authorize({ context, deps, permission, entityType });
112
104
  };
113
105
  const result = await spec.handle({ input: parsed.value, deps, context, authorize }, { signal: abortController.signal });
114
- // `abortController.signal` can only have been aborted by `onResponseClose` firing while the
115
- // `await` above was pending — nothing here runs concurrently with it — so this unambiguously
116
- // means the client was already gone before any response was sent. Writing one now would be
117
- // wasted work at best and, worse, would route a benign disconnect into the SEC-005 catch
118
- // below as a false internal error if the socket rejects the write.
119
- if (abortController.signal.aborted)
120
- return;
121
- if (!result.ok) {
122
- sendApiError({ res, status: statusForError({ error: result.error }), error: result.error });
123
- return;
124
- }
125
- sendJson({ res, status: spec.successStatus ?? 200, body: result.value });
106
+ sendRouteResult({ res, result, spec, signal: abortController.signal });
126
107
  }
127
108
  catch (e) {
128
- // An explicit host error port owns exception classification and serialization, including
129
- // its guard rejections. Hosts without it retain the SEC-005 policy below unchanged.
130
- if (spec.ports?.onError) {
131
- spec.ports.onError({ res, error: e });
132
- return;
133
- }
134
- // A route (or something it called) already classified this failure as safe to disclose —
135
- // see `ClientFacingError`'s own doc. Sent verbatim, at its own status; never routed to the
136
- // SEC-005 sink below, because nothing unanticipated happened.
137
- if (e instanceof ClientFacingError) {
138
- sendApiError({ res, status: statusForError({ error: e.apiError }), error: e.apiError });
139
- return;
140
- }
141
- // SEC-005. This catch exists for exceptions no route anticipated, which makes it precisely
142
- // the path most likely to be holding something private: a driver error naming a database
143
- // file, a connection string, a credential a provider echoed back. Serializing `e.message`
144
- // into the response handed all of that to the caller — and because `health.ts`'s probes are
145
- // mounted ahead of the security middleware and exempted from the bearer gate, an unauthorized
146
- // caller could read it too, simply by getting a readiness dependency to fail. The real error
147
- // still reaches the operator through the sink, correlated to what the caller was told.
148
- const correlationId = randomUUID();
149
- const sink = adapter?.onInternalError ?? defaultInternalErrorSink;
150
- sink({ method: spec.method, path: spec.path, correlationId, error: e });
151
- sendApiError({ res, status: 500, error: createApiError({ code: 'INTERNAL_ERROR', message: 'an internal error occurred' }, { requestId: correlationId }) });
109
+ sendRouteException({ res, spec, adapter, error: e });
152
110
  }
153
111
  finally {
154
112
  res.off?.('close', onResponseClose);
155
113
  }
156
114
  });
157
115
  }
116
+ function allowRouteOrigin({ req, res, spec, adapter }, _optional = {}) {
117
+ if (!spec.requireSameOrigin)
118
+ return true;
119
+ if (!adapter)
120
+ throw new Error('same-origin adapter context is required');
121
+ const origin = guardSameOrigin({ req, origin: adapter });
122
+ if (origin.ok)
123
+ return true;
124
+ sendApiError({ res, status: statusForError({ error: origin.error }), error: origin.error });
125
+ return false;
126
+ }
127
+ function sendRouteResult({ res, result, spec, signal }, _optional = {}) {
128
+ // `signal` can only have been aborted by `onResponseClose` firing while the
129
+ // `await spec.handle` in the request handler was pending — nothing here runs concurrently
130
+ // with it — so this unambiguously means the client was already gone before any response was
131
+ // sent. Writing one now would be wasted work at best and, worse, would route a benign
132
+ // disconnect into the SEC-005 catch as a false internal error if the socket rejects the write.
133
+ if (signal.aborted)
134
+ return;
135
+ if (!result.ok) {
136
+ sendApiError({ res, status: statusForError({ error: result.error }), error: result.error });
137
+ return;
138
+ }
139
+ sendJson({ res, status: spec.successStatus ?? 200, body: result.value });
140
+ }
141
+ function sendRouteException({ res, spec, adapter, error: e }, _optional = {}) {
142
+ // An explicit host error port owns exception classification and serialization, including
143
+ // its guard rejections. Hosts without it retain the SEC-005 policy below unchanged.
144
+ if (spec.ports?.onError) {
145
+ spec.ports.onError({ res, error: e });
146
+ return;
147
+ }
148
+ // A route (or something it called) already classified this failure as safe to disclose —
149
+ // see `ClientFacingError`'s own doc. Sent verbatim, at its own status; never routed to the
150
+ // SEC-005 sink below, because nothing unanticipated happened.
151
+ if (e instanceof ClientFacingError) {
152
+ sendApiError({ res, status: statusForError({ error: e.apiError }), error: e.apiError });
153
+ return;
154
+ }
155
+ // SEC-005. This catch exists for exceptions no route anticipated, which makes it precisely
156
+ // the path most likely to be holding something private: a driver error naming a database
157
+ // file, a connection string, a credential a provider echoed back. Serializing `e.message`
158
+ // into the response handed all of that to the caller — and because `health.ts`'s probes are
159
+ // mounted ahead of the security middleware and exempted from the bearer gate, an unauthorized
160
+ // caller could read it too, simply by getting a readiness dependency to fail. The real error
161
+ // still reaches the operator through the sink, correlated to what the caller was told.
162
+ const correlationId = randomUUID();
163
+ const sink = adapter?.onInternalError ?? defaultInternalErrorSink;
164
+ sink({ method: spec.method, path: spec.path, correlationId, error: e });
165
+ sendApiError({ res, status: 500, error: createApiError({ code: 'INTERNAL_ERROR', message: 'an internal error occurred' }, { requestId: correlationId }) });
166
+ }
158
167
  //# sourceMappingURL=adapter.js.map
@@ -53,6 +53,13 @@ export function isLoopbackPeerAddress({ address }, _optional = {}) {
53
53
  return normalized === '127.0.0.1' || normalized.startsWith('127.');
54
54
  return false;
55
55
  }
56
+ function isBareHttpOrigin({ parsed }, _optional = {}) {
57
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
58
+ return false;
59
+ if (parsed.pathname !== '/' || parsed.search || parsed.hash || parsed.username || parsed.password)
60
+ return false;
61
+ return true;
62
+ }
56
63
  /** Parses an `Origin` header value into its origin string, requiring a bare `scheme://loopback-host[:port]` with no path/query/userinfo. */
57
64
  export function localOriginFromHeader({ value }, _optional = {}) {
58
65
  if (typeof value !== 'string')
@@ -62,9 +69,7 @@ export function localOriginFromHeader({ value }, _optional = {}) {
62
69
  return null;
63
70
  try {
64
71
  const parsed = new URL(trimmed);
65
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
66
- return null;
67
- if (parsed.pathname !== '/' || parsed.search || parsed.hash || parsed.username || parsed.password)
72
+ if (!isBareHttpOrigin({ parsed }))
68
73
  return null;
69
74
  if (!isLoopbackHostname({ hostname: parsed.hostname }))
70
75
  return null;
@@ -101,14 +106,15 @@ export function validateLocalDaemonRequest({ req }, _optional = {}) {
101
106
  };
102
107
  }
103
108
  const originHeader = req.get('origin');
104
- if (originHeader !== undefined && !localOriginFromHeader({ value: originHeader })) {
109
+ const origin = localOriginFromHeader({ value: originHeader });
110
+ if (originHeader !== undefined && !origin) {
105
111
  return {
106
112
  ok: false,
107
113
  message: 'request origin must be a loopback daemon origin',
108
114
  details: { header: 'origin' },
109
115
  };
110
116
  }
111
- return { ok: true, origin: localOriginFromHeader({ value: originHeader }) };
117
+ return { ok: true, origin };
112
118
  }
113
119
  /**
114
120
  * Express middleware that rejects any non-loopback request with a 403, and
@@ -1,4 +1,22 @@
1
1
  import type { Express, RequestHandler } from 'express';
2
+ import { type Logger } from '@jini-ai/core/primitives';
3
+ /** Log request completions only when explicitly enabled, either all or above a threshold.
4
+ * Structured sinks retain correlation fields; the default console gets only the compact message.
5
+ * Missing or invalid thresholds disable slow logging; zero is supported. Duration must exceed it.
6
+ * Callers supply elapsed monotonic time and bounded route patterns, never raw request data.
7
+ * @complexity O(1) per completion, excluding the injected logger.
8
+ */
9
+ export declare function logCompletedRequest(required: {
10
+ requestId: string;
11
+ method: string;
12
+ routePattern: string;
13
+ statusCode: number;
14
+ durationMs: number;
15
+ }, { logger, logRequests, slowRequestMs }?: {
16
+ logger?: Pick<Logger, 'info'>;
17
+ logRequests?: boolean;
18
+ slowRequestMs?: number;
19
+ }): void;
2
20
  /** Structural port satisfied by diagnostics/observability, with host-owned logging and tracing. */
3
21
  export interface HttpRequestObservabilityPort {
4
22
  trackRequest(required: {
@@ -1,3 +1,22 @@
1
+ import { createConsoleLogger } from '@jini-ai/core/primitives';
2
+ /** Log request completions only when explicitly enabled, either all or above a threshold.
3
+ * Structured sinks retain correlation fields; the default console gets only the compact message.
4
+ * Missing or invalid thresholds disable slow logging; zero is supported. Duration must exceed it.
5
+ * Callers supply elapsed monotonic time and bounded route patterns, never raw request data.
6
+ * @complexity O(1) per completion, excluding the injected logger.
7
+ */
8
+ export function logCompletedRequest(required, { logger, logRequests = false, slowRequestMs } = {}) {
9
+ const logSlowRequest = slowRequestMs !== undefined && Number.isFinite(slowRequestMs)
10
+ && slowRequestMs >= 0 && required.durationMs > slowRequestMs;
11
+ if (!logRequests && !logSlowRequest)
12
+ return;
13
+ const { statusCode, method, routePattern, durationMs, requestId } = required;
14
+ const message = `http ${statusCode} ${method} ${routePattern} ${Math.round(durationMs)}ms req=${requestId}`;
15
+ if (logger)
16
+ logger.info({ message }, { meta: { ...required } });
17
+ else
18
+ createConsoleLogger({ prefix: '' }).info({ message });
19
+ }
1
20
  /** Track requests before routing and read the mount-aware route pattern at response completion.
2
21
  * Unmatched paths use a fixed label so attacker-selected paths do not become metric labels.
3
22
  * Each response completes its tracker once; hook error policy belongs to the injected adapter.
@@ -28,7 +28,9 @@
28
28
  * {@link checkSiteRelativeTarget}). Both are bare origins, so a reference resolves to the same
29
29
  * pathname against either.
30
30
  */
31
+ // eslint-disable-next-line sonarjs/no-clear-text-protocols -- Reserved .invalid probe origin used only for URL parsing; no network transport is invoked.
31
32
  const PROBE_ORIGIN = "http://reserved-path-probe.invalid";
33
+ // eslint-disable-next-line sonarjs/no-clear-text-protocols -- Reserved .invalid probe origin used only for URL parsing; no network transport is invoked.
32
34
  const SECOND_PROBE_ORIGIN = "http://reserved-path-probe-2.invalid";
33
35
  /**
34
36
  * Whether `value` contains a C0 or C1 control character.
@@ -106,7 +108,9 @@ function checkDecodedSitePathname(pathname, reservedSegments) {
106
108
  }
107
109
  if (decoded.includes("\\") || hasControlCharacter({ value: decoded }, {}))
108
110
  return { kind: "disallowed-character" };
109
- const first = (resolveDotSegments(decoded).split("/")[1] ?? "").toLowerCase();
111
+ // `resolveDotSegments` always returns a path with a leading "/", so the first segment is
112
+ // everything after it up to the next "/" — `split(..., 1)` yields exactly that one element.
113
+ const first = resolveDotSegments(decoded).slice(1).split("/", 1).join("").toLowerCase();
110
114
  if (reservedSegments.has(first))
111
115
  return { kind: "reserved", surface: first };
112
116
  return { kind: "ok" };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/http-kit",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Generic Express transport primitives, request parsing, response serialization, origin guards and route-pack mounting.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -71,17 +71,17 @@
71
71
  "@types/express": "^4.17.21",
72
72
  "@vitest/coverage-v8": "^2.1.9",
73
73
  "express": "^4.21.0",
74
- "@jini-ai/core": "0.4.2",
75
- "@jini-ai/protocol": "0.4.2",
76
- "@jini-ai/platform": "0.5.2"
74
+ "@jini-ai/core": "0.4.9",
75
+ "@jini-ai/platform": "0.5.10",
76
+ "@jini-ai/protocol": "0.4.5"
77
77
  },
78
78
  "dependencies": {
79
- "@jini-ai/core": "^0.4.2",
80
- "@jini-ai/protocol": "^0.4.2"
79
+ "@jini-ai/protocol": "^0.4.5",
80
+ "@jini-ai/core": "^0.4.9"
81
81
  },
82
82
  "peerDependencies": {
83
83
  "@jini-ai/platform": "^0.5.1",
84
- "express": "^4.21.0"
84
+ "express": "^4.21.0 || ^5.0.0"
85
85
  },
86
86
  "peerDependenciesMeta": {
87
87
  "@jini-ai/platform": {
@@ -1,99 +0,0 @@
1
- /**
2
- * @module active-context
3
- *
4
- * Generic "what resource is the caller currently focused on?" channel: an
5
- * in-memory, TTL-scoped pointer a client POSTs to record its current focus
6
- * and GETs to read back (resolved against a real display name via an
7
- * injected lookup). Ported from the routes-classification table's
8
- * `active-context.ts` MIXED row (see `source-map.md`) — the origin's only
9
- * real coupling was `handleGetActive` calling into an OD project store to
10
- * resolve a display name; the TTL store and both handlers were already
11
- * product-neutral, and all handlers are synchronous (no async risk).
12
- *
13
- * The origin's `projectId`/`fileName` fields are generalized here to a
14
- * single opaque `resourceRef` (was `projectId`) plus an optional `detail`
15
- * string (was `fileName` — a sub-locator within that resource), matching
16
- * the source-map's own "renaming to a generic resource ref" note. The
17
- * origin's `deps.getProject` lookup becomes an injected `resolveResource`
18
- * dependency, matching this branch's DI convention (see
19
- * `daemon-status.ts`/`host-tools.ts`: real collaborators supplied by the
20
- * caller rather than read from a global store).
21
- */
22
- import type { Express } from 'express';
23
- import { type AdapterContext } from './adapter.js';
24
- /** How long a recorded focus stays valid before a GET treats it as stale and clears it. */
25
- export declare const ACTIVE_CONTEXT_TTL_MS: number;
26
- interface ActiveContext {
27
- resourceRef: string;
28
- detail: string | null;
29
- ts: number;
30
- }
31
- interface ActiveContextStore {
32
- current: ActiveContext | null;
33
- }
34
- type SetActiveInput = {
35
- kind: 'clear';
36
- } | {
37
- kind: 'set';
38
- resourceRef: string;
39
- detail: string | null;
40
- };
41
- type SetActiveOutput = {
42
- active: false;
43
- } | {
44
- active: true;
45
- resourceRef: string;
46
- detail: string | null;
47
- ts: number;
48
- };
49
- type GetActiveOutput = {
50
- active: false;
51
- } | {
52
- active: true;
53
- resourceRef: string;
54
- resourceName: string | null;
55
- detail: string | null;
56
- ts: number;
57
- ageMs: number;
58
- };
59
- /** A resolved resource's display name. `resolveResource` itself may return `null`/`undefined` (not this type) when the caller has no entry at all for a given resource ref (e.g. unknown or deleted). */
60
- export interface ActiveContextResource {
61
- readonly name?: string | null;
62
- }
63
- /** What a caller must supply to mount the active-context routes. */
64
- export interface ActiveContextDeps {
65
- /**
66
- * Resolves a display name for a resource ref (was OD's project store's
67
- * `getProject`). Injected so this module has no dependency on any
68
- * particular resource store; may return `null`/`undefined` if the ref is
69
- * unknown.
70
- */
71
- resolveResource: (resourceRef: string) => ActiveContextResource | null | undefined;
72
- /** Returns the current time in epoch ms. Defaults to `Date.now` when omitted. */
73
- now?: () => number;
74
- }
75
- /**
76
- * Internal deps threaded to both handlers: the caller-supplied
77
- * {@link ActiveContextDeps} plus the shared in-memory store built once per
78
- * `registerActiveContextRoutes` call, so the two routes see the same state.
79
- */
80
- interface ActiveContextRouteDeps {
81
- store: ActiveContextStore;
82
- resolveResource: ActiveContextDeps['resolveResource'];
83
- now: () => number;
84
- }
85
- /**
86
- * `POST /api/active` — records (or, with `{active: false}`, clears) the
87
- * caller's current resource focus.
88
- */
89
- export declare const setActiveRoute: import("./types.js").JsonRouteSpec<SetActiveInput, SetActiveOutput, ActiveContextRouteDeps>;
90
- /**
91
- * `GET /api/active` — reads back the current resource focus, resolving a
92
- * display name for it, or `{active: false}` if nothing is set or the
93
- * recorded focus has aged past {@link ACTIVE_CONTEXT_TTL_MS}.
94
- */
95
- export declare const getActiveRoute: import("./types.js").JsonRouteSpec<void, GetActiveOutput, ActiveContextRouteDeps>;
96
- /** Mounts both active-context routes on `app`, sharing one in-memory store between them. A pack's `http(app, services)` calls this directly. */
97
- export declare function registerActiveContextRoutes(app: Express, deps: ActiveContextDeps, adapter: AdapterContext): void;
98
- export {};
99
- //# sourceMappingURL=active-context.d.ts.map
@@ -1,77 +0,0 @@
1
- import { createApiError } from '@jini-ai/protocol';
2
- import { defineJsonRoute, mountJsonRoute } from './adapter.js';
3
- import { err, ok } from './types.js';
4
- /** How long a recorded focus stays valid before a GET treats it as stale and clears it. */
5
- export const ACTIVE_CONTEXT_TTL_MS = 5 * 60 * 1000;
6
- function parseSetActive(raw) {
7
- const body = (raw.body ?? {});
8
- if (body.active === false) {
9
- return ok({ kind: 'clear' });
10
- }
11
- const resourceRef = typeof body.resourceRef === 'string' ? body.resourceRef : '';
12
- if (!resourceRef) {
13
- return err(createApiError('BAD_REQUEST', 'resourceRef is required'));
14
- }
15
- const detail = typeof body.detail === 'string' && body.detail.length > 0 ? body.detail : null;
16
- return ok({ kind: 'set', resourceRef, detail });
17
- }
18
- function handleSetActive(input, deps) {
19
- if (input.kind === 'clear') {
20
- deps.store.current = null;
21
- return ok({ active: false });
22
- }
23
- const next = { resourceRef: input.resourceRef, detail: input.detail, ts: deps.now() };
24
- deps.store.current = next;
25
- return ok({ active: true, ...next });
26
- }
27
- function handleGetActive(_input, deps) {
28
- const current = deps.store.current;
29
- if (!current || deps.now() - current.ts > ACTIVE_CONTEXT_TTL_MS) {
30
- deps.store.current = null;
31
- return ok({ active: false });
32
- }
33
- const resource = deps.resolveResource(current.resourceRef);
34
- return ok({
35
- active: true,
36
- resourceRef: current.resourceRef,
37
- resourceName: resource?.name ?? null,
38
- detail: current.detail,
39
- ts: current.ts,
40
- ageMs: deps.now() - current.ts,
41
- });
42
- }
43
- /**
44
- * `POST /api/active` — records (or, with `{active: false}`, clears) the
45
- * caller's current resource focus.
46
- */
47
- export const setActiveRoute = defineJsonRoute({
48
- method: 'post',
49
- path: '/api/active',
50
- requireSameOrigin: true,
51
- parse: parseSetActive,
52
- handle: handleSetActive,
53
- });
54
- /**
55
- * `GET /api/active` — reads back the current resource focus, resolving a
56
- * display name for it, or `{active: false}` if nothing is set or the
57
- * recorded focus has aged past {@link ACTIVE_CONTEXT_TTL_MS}.
58
- */
59
- export const getActiveRoute = defineJsonRoute({
60
- method: 'get',
61
- path: '/api/active',
62
- requireSameOrigin: true,
63
- parse: () => ok(undefined),
64
- handle: handleGetActive,
65
- });
66
- /** Mounts both active-context routes on `app`, sharing one in-memory store between them. A pack's `http(app, services)` calls this directly. */
67
- export function registerActiveContextRoutes(app, deps, adapter) {
68
- const store = { current: null };
69
- const routeDeps = {
70
- store,
71
- resolveResource: deps.resolveResource,
72
- now: deps.now ?? (() => Date.now()),
73
- };
74
- mountJsonRoute(app, setActiveRoute, routeDeps, adapter);
75
- mountJsonRoute(app, getActiveRoute, routeDeps, adapter);
76
- }
77
- //# sourceMappingURL=active-context.js.map
package/dist/agents.d.ts DELETED
@@ -1,64 +0,0 @@
1
- /**
2
- * @module agents
3
- *
4
- * `GET /api/agents` — lists the agents a host can expose to a client,
5
- * including host-probed availability/model metadata when supplied.
6
- * `POST /api/agents/rescan` asks the host to invalidate its discovery cache
7
- * and probe again.
8
- *
9
- * `listAgents` is injected (matching `daemon-status.ts`/`active-context.ts`'s
10
- * DI convention) rather than this module importing `@jini-ai/agent-runtime`
11
- * directly — a host typically already has that package's `AGENT_DEFS` array
12
- * in scope and just needs to project it, and this keeps `@jini-ai/http-kit` from
13
- * taking on a dependency on subprocess discovery. The host owns probing,
14
- * timeouts, caching, PATH/env policy, and the projection of spawn-only
15
- * metadata; this transport only serializes the safe summary.
16
- */
17
- import type { Express } from 'express';
18
- import { type AdapterContext } from './adapter.js';
19
- export interface AgentModelSummary {
20
- readonly id: string;
21
- readonly label: string;
22
- }
23
- /**
24
- * Client-safe agent discovery data. Optional probe fields preserve the
25
- * original static-registry contract for hosts that only expose `{id, name}`.
26
- * Spawn internals (`bin`, resolved path, argv builders, env) never cross HTTP.
27
- */
28
- export interface AgentSummary {
29
- readonly id: string;
30
- readonly name: string;
31
- readonly available?: boolean;
32
- readonly version?: string | null;
33
- readonly authStatus?: 'ok' | 'missing' | 'unknown';
34
- readonly models?: readonly AgentModelSummary[];
35
- readonly reasoningOptions?: readonly AgentModelSummary[];
36
- readonly modelsSource?: 'live' | 'fallback';
37
- readonly supportsCustomModel?: boolean;
38
- readonly diagnostic?: string;
39
- /**
40
- * Whether this runtime can receive external MCP servers (the host application's or this engine's
41
- * own tools) at all, per
42
- * `@jini-ai/agent-runtime`'s `runtimeSupportsExternalTools(def)` — the def-level source of
43
- * truth. `undefined` means the host did not populate this field (pre-existing hosts on an older
44
- * `@jini-ai/http-kit` continue to omit it); a UI gating on this should treat `undefined` the same
45
- * as `true` (no known reason to warn) rather than assuming the worst.
46
- */
47
- readonly supportsTools?: boolean;
48
- }
49
- export interface AgentsHttpDeps {
50
- /** Returns the host's cached or freshly resolved client-safe agent inventory. */
51
- readonly listAgents: () => Promise<readonly AgentSummary[]> | readonly AgentSummary[];
52
- /** Forces host-owned discovery to run again. Falls back to `listAgents` when omitted. */
53
- readonly rescanAgents?: () => Promise<readonly AgentSummary[]> | readonly AgentSummary[];
54
- }
55
- export interface AgentListResponse {
56
- readonly agents: readonly AgentSummary[];
57
- }
58
- /** `GET /api/agents` — read-only, no side effects; matches `runListRoute`/`runStatusRoute`'s posture of not requiring same-origin. */
59
- export declare const agentListRoute: import("./types.js").JsonRouteSpec<void, AgentListResponse, AgentsHttpDeps>;
60
- /** `POST /api/agents/rescan` — explicit state refresh, protected by the local same-origin gate. */
61
- export declare const agentRescanRoute: import("./types.js").JsonRouteSpec<void, AgentListResponse, AgentsHttpDeps>;
62
- /** Mounts the read and explicit-rescan agent discovery routes. */
63
- export declare function registerAgentRoutes(app: Express, deps: AgentsHttpDeps, adapter: AdapterContext): void;
64
- //# sourceMappingURL=agents.d.ts.map
package/dist/agents.js DELETED
@@ -1,23 +0,0 @@
1
- import { defineJsonRoute, mountJsonRoute } from './adapter.js';
2
- import { ok } from './types.js';
3
- /** `GET /api/agents` — read-only, no side effects; matches `runListRoute`/`runStatusRoute`'s posture of not requiring same-origin. */
4
- export const agentListRoute = defineJsonRoute({
5
- method: 'get',
6
- path: '/api/agents',
7
- parse: () => ok(undefined),
8
- handle: async (_input, deps) => ok({ agents: await deps.listAgents() }),
9
- });
10
- /** `POST /api/agents/rescan` — explicit state refresh, protected by the local same-origin gate. */
11
- export const agentRescanRoute = defineJsonRoute({
12
- method: 'post',
13
- path: '/api/agents/rescan',
14
- requireSameOrigin: true,
15
- parse: () => ok(undefined),
16
- handle: async (_input, deps) => ok({ agents: await (deps.rescanAgents ?? deps.listAgents)() }),
17
- });
18
- /** Mounts the read and explicit-rescan agent discovery routes. */
19
- export function registerAgentRoutes(app, deps, adapter) {
20
- mountJsonRoute(app, agentListRoute, deps, adapter);
21
- mountJsonRoute(app, agentRescanRoute, deps, adapter);
22
- }
23
- //# sourceMappingURL=agents.js.map