@jini-ai/http-kit 0.3.8 → 0.4.1

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 (60) hide show
  1. package/CHANGELOG.md +177 -0
  2. package/README.md +71 -98
  3. package/dist/adapter.d.ts +21 -6
  4. package/dist/adapter.js +47 -17
  5. package/dist/api-security-middleware.d.ts +27 -17
  6. package/dist/api-security-middleware.js +27 -36
  7. package/dist/compat.d.ts +12 -17
  8. package/dist/compat.js +4 -12
  9. package/dist/db-ops.d.ts +3 -3
  10. package/dist/db-ops.js +3 -3
  11. package/dist/delegated-tools.d.ts +9 -78
  12. package/dist/delegated-tools.js +27 -95
  13. package/dist/index.d.ts +21 -70
  14. package/dist/index.js +12 -32
  15. package/dist/local-daemon-request.d.ts +18 -8
  16. package/dist/local-daemon-request.js +23 -32
  17. package/dist/memory.d.ts +1 -1
  18. package/dist/middleware.d.ts +20 -0
  19. package/dist/middleware.js +21 -0
  20. package/dist/observability.d.ts +29 -0
  21. package/dist/observability.js +22 -0
  22. package/dist/origin.d.ts +8 -6
  23. package/dist/origin.js +8 -5
  24. package/dist/pack-http.d.ts +12 -8
  25. package/dist/pack-http.js +3 -3
  26. package/dist/rate-limit.d.ts +97 -0
  27. package/dist/rate-limit.js +94 -0
  28. package/dist/raw-sse.d.ts +7 -2
  29. package/dist/raw-sse.js +6 -7
  30. package/dist/read-only-tools.d.ts +67 -0
  31. package/dist/read-only-tools.js +59 -0
  32. package/dist/remote-run-events.js +1 -1
  33. package/dist/request.d.ts +8 -2
  34. package/dist/request.js +4 -4
  35. package/dist/response.d.ts +16 -4
  36. package/dist/response.js +7 -5
  37. package/dist/route-registration-guard.d.ts +13 -5
  38. package/dist/route-registration-guard.js +6 -6
  39. package/dist/sse.d.ts +25 -9
  40. package/dist/sse.js +10 -10
  41. package/dist/tool-catalog.d.ts +3 -3
  42. package/dist/types.d.ts +52 -15
  43. package/dist/types.js +2 -2
  44. package/dist/verified-origin/configured-origin.d.ts +37 -0
  45. package/dist/verified-origin/configured-origin.js +112 -0
  46. package/dist/verified-origin/index.d.ts +7 -0
  47. package/dist/verified-origin/index.js +6 -0
  48. package/dist/verified-origin/origin.d.ts +65 -0
  49. package/dist/verified-origin/origin.js +151 -0
  50. package/dist/verified-origin/ports.d.ts +40 -0
  51. package/dist/verified-origin/ports.js +2 -0
  52. package/dist/verified-origin/repo.memory.d.ts +34 -0
  53. package/dist/verified-origin/repo.memory.js +34 -0
  54. package/dist/verified-origin/site-path.d.ts +113 -0
  55. package/dist/verified-origin/site-path.js +179 -0
  56. package/dist/verified-origin/types.d.ts +33 -0
  57. package/dist/verified-origin/types.js +23 -0
  58. package/dist/verified-origin.d.ts +2 -0
  59. package/dist/verified-origin.js +2 -0
  60. package/package.json +52 -11
@@ -0,0 +1,97 @@
1
+ /** Fixed-window counting over a host-owned clock and counter store. */
2
+ import type { Clock } from '@jini-ai/core/primitives';
3
+ export type { Clock } from '@jini-ai/core/primitives';
4
+ /** Host-selected window and request budget; no product profiles live here. */
5
+ export interface RateLimitProfile {
6
+ readonly windowSeconds: number;
7
+ readonly max: number;
8
+ readonly burst: number;
9
+ }
10
+ export type RateLimitResult = {
11
+ allowed: true;
12
+ } | {
13
+ allowed: false;
14
+ retryAfterSeconds: number;
15
+ };
16
+ export interface CounterWindow {
17
+ readonly windowStartMs: number;
18
+ readonly count: number;
19
+ }
20
+ /**
21
+ * Async storage port. Dedicate one store to one limiter; checks are serialized
22
+ * within that limiter. Sharing a store across processes requires a different,
23
+ * atomic distributed algorithm. Stored values are replaced, never mutated.
24
+ */
25
+ export interface CounterStore {
26
+ get(required: {
27
+ key: string;
28
+ }): Promise<CounterWindow | undefined>;
29
+ set(required: {
30
+ key: string;
31
+ state: CounterWindow;
32
+ }): Promise<void>;
33
+ delete(required: {
34
+ key: string;
35
+ }): Promise<void>;
36
+ entries(required: Record<string, never>): Promise<Iterable<readonly [string, CounterWindow]>>;
37
+ size(required: Record<string, never>): Promise<number>;
38
+ }
39
+ export interface RateLimiter {
40
+ /** Resolves the budget decision; rejects missing, non-string or empty keys with TypeError. */
41
+ check(required: {
42
+ key: string;
43
+ }): Promise<RateLimitResult>;
44
+ size(required: Record<string, never>): Promise<number>;
45
+ }
46
+ /**
47
+ * Creates an isolated in-memory CounterStore adapter.
48
+ * @param _required - No required configuration for this adapter.
49
+ * @returns A new store; construct one for each limiter.
50
+ */
51
+ export declare function createMemoryCounterStore(_required: Record<string, never>, _optional?: Record<string, never>): CounterStore;
52
+ /**
53
+ * Builds a fixed-window limiter, preserving max+burst and ceil-to-second retry
54
+ * delays. Counter updates and periodic eviction run in arrival order across
55
+ * storage awaits. Rejected checks do not consume more of the budget.
56
+ * @param required - Host profile, clock and dedicated counter store.
57
+ * @returns An async limiter. Storage failures reject the caller's check.
58
+ * Invalid keys reject with TypeError before storage or queue state is touched.
59
+ * @example const result = await limiter.check({ key: clientIp });
60
+ */
61
+ export declare function createRateLimiter({ profile, clock, store }: {
62
+ profile: RateLimitProfile;
63
+ clock: Clock;
64
+ store: CounterStore;
65
+ }, _optional?: Record<string, never>): RateLimiter;
66
+ /** Structural request shape; transport/framework trust configuration stays outside. */
67
+ export interface ClientIpSource {
68
+ readonly socket: {
69
+ readonly remoteAddress?: string;
70
+ };
71
+ readonly headers: Record<string, string | string[] | undefined>;
72
+ readonly ip?: string;
73
+ }
74
+ /**
75
+ * Host trust policy. A fallback may use framework-resolved `source.ip` only
76
+ * when the host has configured that framework's proxy trust appropriately.
77
+ */
78
+ export interface ClientIpPolicy {
79
+ readonly unknownAddress: string;
80
+ isTrustedProxy(required: {
81
+ address: string;
82
+ }): boolean;
83
+ fallbackAddress(required: {
84
+ source: ClientIpSource;
85
+ socketPeer: string;
86
+ }): string;
87
+ }
88
+ /**
89
+ * Reads the first forwarded hop only when the immediate peer is trusted.
90
+ * @param required - Request source and explicit host trust/fallback policy.
91
+ * @returns The forwarded IP for a trusted peer, or the policy's fallback.
92
+ */
93
+ export declare function resolveClientIp({ source, policy }: {
94
+ source: ClientIpSource;
95
+ policy: ClientIpPolicy;
96
+ }, _optional?: Record<string, never>): string;
97
+ //# sourceMappingURL=rate-limit.d.ts.map
@@ -0,0 +1,94 @@
1
+ /** Fixed-window counting over a host-owned clock and counter store. */
2
+ /**
3
+ * Creates an isolated in-memory CounterStore adapter.
4
+ * @param _required - No required configuration for this adapter.
5
+ * @returns A new store; construct one for each limiter.
6
+ */
7
+ export function createMemoryCounterStore(_required, _optional = {}) {
8
+ const windows = new Map();
9
+ return {
10
+ get: async ({ key }) => windows.get(key),
11
+ set: async ({ key, state }) => { windows.set(key, { ...state }); },
12
+ delete: async ({ key }) => { windows.delete(key); },
13
+ entries: async () => windows.entries(),
14
+ size: async () => windows.size,
15
+ };
16
+ }
17
+ // An injected clock makes window boundaries deterministic without real-time sleeps; a fresh
18
+ // dedicated store keeps limiter instances isolated instead of sharing module-global counters.
19
+ /**
20
+ * Builds a fixed-window limiter, preserving max+burst and ceil-to-second retry
21
+ * delays. Counter updates and periodic eviction run in arrival order across
22
+ * storage awaits. Rejected checks do not consume more of the budget.
23
+ * @param required - Host profile, clock and dedicated counter store.
24
+ * @returns An async limiter. Storage failures reject the caller's check.
25
+ * Invalid keys reject with TypeError before storage or queue state is touched.
26
+ * @example const result = await limiter.check({ key: clientIp });
27
+ */
28
+ export function createRateLimiter({ profile, clock, store }, _optional = {}) {
29
+ const windowMs = profile.windowSeconds * 1000;
30
+ const effectiveMax = profile.max + profile.burst;
31
+ let lastSweepMs = null;
32
+ let pending = Promise.resolve();
33
+ // Expiry sweeps prevent attacker-controlled keys (for example rotating anonymous source IPs)
34
+ // from accumulating forever. Work is O(tracked keys) only once per window; per-request full
35
+ // scans would replace a memory-exhaustion risk with linear request latency. Active key volume
36
+ // still determines memory use, and separate in-memory processes each retain their own budget.
37
+ async function consume(key) {
38
+ const nowMs = clock.nowMs();
39
+ if (lastSweepMs === null) {
40
+ lastSweepMs = nowMs;
41
+ }
42
+ else if (nowMs - lastSweepMs >= windowMs) {
43
+ // One scan per window, rather than one per request. Sweep cost is linear
44
+ // in tracked keys; expired entries behave exactly like missing entries.
45
+ for (const [expiredKey, state] of await store.entries({})) {
46
+ if (nowMs - state.windowStartMs >= windowMs)
47
+ await store.delete({ key: expiredKey });
48
+ }
49
+ lastSweepMs = nowMs;
50
+ }
51
+ const existing = await store.get({ key });
52
+ if (!existing || nowMs - existing.windowStartMs >= windowMs) {
53
+ await store.set({ key, state: { windowStartMs: nowMs, count: 1 } });
54
+ return { allowed: true };
55
+ }
56
+ if (existing.count < effectiveMax) {
57
+ await store.set({ key, state: { ...existing, count: existing.count + 1 } });
58
+ return { allowed: true };
59
+ }
60
+ const retryAfterSeconds = Math.max(1, Math.ceil((existing.windowStartMs + windowMs - nowMs) / 1000));
61
+ return { allowed: false, retryAfterSeconds };
62
+ }
63
+ return {
64
+ check: async (required) => {
65
+ const key = required?.key;
66
+ // Positional or missing keys must never merge unrelated clients into an undefined bucket.
67
+ if (typeof key !== "string" || key === "")
68
+ throw new TypeError("rate limit key must be a non-empty string");
69
+ const result = pending.then(() => consume(key));
70
+ // Only the queue's tail contains the failure. The caller still receives
71
+ // the rejection, and later checks can try the adapter again.
72
+ pending = result.then(() => undefined, () => undefined);
73
+ return result;
74
+ },
75
+ size: () => pending.then(() => store.size({})),
76
+ };
77
+ }
78
+ /**
79
+ * Reads the first forwarded hop only when the immediate peer is trusted.
80
+ * @param required - Request source and explicit host trust/fallback policy.
81
+ * @returns The forwarded IP for a trusted peer, or the policy's fallback.
82
+ */
83
+ export function resolveClientIp({ source, policy }, _optional = {}) {
84
+ const socketPeer = source.socket?.remoteAddress ?? policy.unknownAddress;
85
+ if (policy.isTrustedProxy({ address: socketPeer })) {
86
+ const header = source.headers['x-forwarded-for'];
87
+ const value = Array.isArray(header) ? header[0] : header;
88
+ const firstHop = value?.split(',')[0]?.trim();
89
+ if (firstHop)
90
+ return firstHop;
91
+ }
92
+ return policy.fallbackAddress({ source, socketPeer });
93
+ }
94
+ //# sourceMappingURL=rate-limit.js.map
package/dist/raw-sse.d.ts CHANGED
@@ -24,7 +24,9 @@ export interface CreateSseResponseOptions {
24
24
  }
25
25
  export interface SseConnection {
26
26
  /** Writes one SSE `data:` event, JSON-serializing `data`. A no-op once the connection has closed. */
27
- send(data: unknown): void;
27
+ send({ data }: {
28
+ readonly data: unknown;
29
+ }, _optional?: Record<string, never>): void;
28
30
  /** Closes the connection: stops the keepalive interval and ends the response. Idempotent — safe to call more than once, or after the client has already disconnected. */
29
31
  close(): void;
30
32
  /** `true` once this connection has closed, whether via an explicit `close()` call or the client disconnecting. */
@@ -40,5 +42,8 @@ export interface SseConnection {
40
42
  * @complexity O(1) to open; `send` is O(1) plus `JSON.stringify`'s cost in the payload's size.
41
43
  * @overallScore 100/100
42
44
  */
43
- export declare function createSseResponse(req: IncomingMessage, res: ServerResponse, options?: CreateSseResponseOptions): SseConnection;
45
+ export declare function createSseResponse({ req, res }: {
46
+ readonly req: IncomingMessage;
47
+ readonly res: ServerResponse;
48
+ }, options?: CreateSseResponseOptions): SseConnection;
44
49
  //# sourceMappingURL=raw-sse.d.ts.map
package/dist/raw-sse.js CHANGED
@@ -15,7 +15,7 @@ export const DEFAULT_MAX_QUEUED_SSE_MESSAGES = 1000;
15
15
  * @complexity O(1) to open; `send` is O(1) plus `JSON.stringify`'s cost in the payload's size.
16
16
  * @overallScore 100/100
17
17
  */
18
- export function createSseResponse(req, res, options = {}) {
18
+ export function createSseResponse({ req, res }, options = {}) {
19
19
  let closed = false;
20
20
  const maxQueuedMessages = options.maxQueuedMessages ?? DEFAULT_MAX_QUEUED_SSE_MESSAGES;
21
21
  // Frames held back because the socket reported backpressure, flushed on `'drain'`. Every write
@@ -75,13 +75,12 @@ export function createSseResponse(req, res, options = {}) {
75
75
  writable = true;
76
76
  pump();
77
77
  });
78
- // `IncomingMessage`'s `'close'` fires when the request/response cycle ends or the connection
79
- // drops — not when a bodyless request merely finishes arriving — so this is the client-disconnect
80
- // signal it reads as. `raw-sse.test.ts` pins that against a real socket rather than a fake
81
- // emitter, because it is the kind of contract a mock will happily agree with either way.
82
- req.on('close', close);
78
+ // A request's `'close'` can fire when a POST body finishes arriving while its response is still
79
+ // streaming. Observe the response instead so request completion cannot tear down a live stream.
80
+ // `raw-sse.test.ts` pins both lifecycles; its real-socket cases also verify client disconnects.
81
+ res.on('close', close);
83
82
  return {
84
- send(data) {
83
+ send({ data }) {
85
84
  enqueue(`data: ${JSON.stringify(data)}\n\n`);
86
85
  },
87
86
  close,
@@ -0,0 +1,67 @@
1
+ import { type Principal, type ToolRegistry } from '@jini-ai/core';
2
+ import type { ToolExecutor } from '@jini-ai/daemon';
3
+ export interface ReadOnlyConstrainedPrincipal extends Principal {
4
+ readonly toolAccess: 'read-only';
5
+ }
6
+ /** Required host wording; absent metadata is always a refusal. */
7
+ export interface ReadOnlyToolMessages {
8
+ readonly unverifiableMessage: string;
9
+ toolRefusalMessage(required: {
10
+ toolId: string;
11
+ }): string;
12
+ }
13
+ export interface IdGenerator {
14
+ newId(): string;
15
+ }
16
+ export interface ReadOnlyToolCheckRequired {
17
+ readonly toolId: string;
18
+ readonly registry: Pick<ToolRegistry, 'list'> | undefined;
19
+ readonly messages: ReadOnlyToolMessages;
20
+ }
21
+ export interface ReadOnlyToolConstraintRequired {
22
+ readonly inner: ToolExecutor;
23
+ readonly registry: Pick<ToolRegistry, 'list'> | undefined;
24
+ readonly idGenerator: IdGenerator;
25
+ readonly messages: ReadOnlyToolMessages;
26
+ }
27
+ /** @returns A copied, attenuated principal; its roles are unchanged. */
28
+ export declare function constrainPrincipalToReadOnlyTools({ principal }: {
29
+ principal: Principal;
30
+ }, _optional?: Record<string, never>): ReadOnlyConstrainedPrincipal;
31
+ /** @returns Whether attenuation survived the executor/decorator boundary. */
32
+ export declare function principalIsReadOnlyConstrained({ principal }: {
33
+ principal: Principal;
34
+ }, _optional?: Record<string, never>): boolean;
35
+ /** @returns Required host wording for an unknown or non-read-only tool. */
36
+ export declare function readOnlyToolRefusalMessage({ toolId, messages }: {
37
+ toolId: string;
38
+ messages: ReadOnlyToolMessages;
39
+ }, _optional?: Record<string, never>): string;
40
+ /**
41
+ * Single read-only registration decision, shared by routes and inner dispatch.
42
+ * @returns Null for an explicitly read-only registration, otherwise host refusal text.
43
+ */
44
+ export declare function checkReadOnlyTool({ toolId, registry, messages }: ReadOnlyToolCheckRequired, _optional?: Record<string, never>): string | null;
45
+ /**
46
+ * Preflight for every dispatch, including a recovery tool the caller never named.
47
+ * @returns Null for unconstrained principals or safe reads; otherwise refusal text.
48
+ */
49
+ export declare function refuseNonReadOnlyDispatch(required: ReadOnlyToolCheckRequired & {
50
+ readonly principal: Principal;
51
+ }, _optional?: Record<string, never>): string | null;
52
+ /** @returns Caller-formatted recovery refusal, preserving the original refusal verbatim as input. */
53
+ export declare function readOnlyRemedyRefusalMessage({ refusal, formatMessage }: {
54
+ refusal: string;
55
+ formatMessage: (required: {
56
+ refusal: string;
57
+ }) => string;
58
+ }, _optional?: Record<string, never>): string;
59
+ /**
60
+ * Gate every dispatch before its handler runs. Compose directly around the bare
61
+ * executor, beneath all decorators that can issue nested/recovery dispatches.
62
+ * Wrapping only a fully composed stack cannot intercept its inner references.
63
+ * @param required - Executor, registry, denial ID source and required host wording.
64
+ * @returns An executor using the existing kernel port's positional methods.
65
+ */
66
+ export declare function withReadOnlyToolConstraint({ inner, registry, idGenerator, messages }: ReadOnlyToolConstraintRequired, _optional?: Record<string, never>): ToolExecutor;
67
+ //# sourceMappingURL=read-only-tools.d.ts.map
@@ -0,0 +1,59 @@
1
+ import { isReadOnlyTool } from '@jini-ai/core';
2
+ /** @returns A copied, attenuated principal; its roles are unchanged. */
3
+ export function constrainPrincipalToReadOnlyTools({ principal }, _optional = {}) {
4
+ return { ...principal, toolAccess: 'read-only' };
5
+ }
6
+ /** @returns Whether attenuation survived the executor/decorator boundary. */
7
+ export function principalIsReadOnlyConstrained({ principal }, _optional = {}) {
8
+ return principal.toolAccess === 'read-only';
9
+ }
10
+ /** @returns Required host wording for an unknown or non-read-only tool. */
11
+ export function readOnlyToolRefusalMessage({ toolId, messages }, _optional = {}) {
12
+ return messages.toolRefusalMessage({ toolId });
13
+ }
14
+ /**
15
+ * Single read-only registration decision, shared by routes and inner dispatch.
16
+ * @returns Null for an explicitly read-only registration, otherwise host refusal text.
17
+ */
18
+ export function checkReadOnlyTool({ toolId, registry, messages }, _optional = {}) {
19
+ if (registry === undefined)
20
+ return messages.unverifiableMessage;
21
+ const descriptor = registry.list().find((candidate) => candidate.id === toolId);
22
+ if (isReadOnlyTool(descriptor))
23
+ return null;
24
+ return readOnlyToolRefusalMessage({ toolId, messages });
25
+ }
26
+ /**
27
+ * Preflight for every dispatch, including a recovery tool the caller never named.
28
+ * @returns Null for unconstrained principals or safe reads; otherwise refusal text.
29
+ */
30
+ export function refuseNonReadOnlyDispatch(required, _optional = {}) {
31
+ if (!principalIsReadOnlyConstrained({ principal: required.principal }))
32
+ return null;
33
+ return checkReadOnlyTool(required);
34
+ }
35
+ /** @returns Caller-formatted recovery refusal, preserving the original refusal verbatim as input. */
36
+ export function readOnlyRemedyRefusalMessage({ refusal, formatMessage }, _optional = {}) {
37
+ return formatMessage({ refusal });
38
+ }
39
+ /**
40
+ * Gate every dispatch before its handler runs. Compose directly around the bare
41
+ * executor, beneath all decorators that can issue nested/recovery dispatches.
42
+ * Wrapping only a fully composed stack cannot intercept its inner references.
43
+ * @param required - Executor, registry, denial ID source and required host wording.
44
+ * @returns An executor using the existing kernel port's positional methods.
45
+ */
46
+ export function withReadOnlyToolConstraint({ inner, registry, idGenerator, messages }, _optional = {}) {
47
+ return {
48
+ execute: async (principal, run, toolId, input, signal, emitSurface) => {
49
+ const refusal = refuseNonReadOnlyDispatch({ principal, toolId, registry, messages });
50
+ if (refusal !== null)
51
+ return { executionId: idGenerator.newId(), status: 'denied', error: refusal };
52
+ return inner.execute(principal, run, toolId, input, signal, emitSurface);
53
+ },
54
+ resumeConfirmation: (executionId, decision) => inner.resumeConfirmation(executionId, decision),
55
+ cancel: (executionId) => inner.cancel(executionId),
56
+ getAuditRecord: (executionId) => inner.getAuditRecord(executionId),
57
+ };
58
+ }
59
+ //# sourceMappingURL=read-only-tools.js.map
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * This exists to relax `@jini-ai/daemon`'s co-location requirement (`RunLifecycle`/`ToolExecutor`
10
10
  * previously had to live in one process per run, because `DelegatedToolBridge.execute()` calls
11
- * `lifecycle.emit()` in-process with no remote path — see this repo's own `tovu-learnings.md` §1a).
11
+ * `lifecycle.emit()` in-process with no remote reporting path).
12
12
  * It does not remove any authorization: whatever executed the tool remotely already ran it through
13
13
  * its OWN `ToolExecutor`/`ToolPolicy` gate before calling here. This route only lets that outcome
14
14
  * be recorded into a run it does not own the process of.
package/dist/request.d.ts CHANGED
@@ -10,10 +10,16 @@ import type { RouteInputContext } from './types.js';
10
10
  * Extracts `body`/`query`/`params` from an Express `Request` into a `RouteInputContext`, so a
11
11
  * route's `parse` function can be unit-tested without constructing a real `Request`.
12
12
  */
13
- export declare function rawInput(req: Request): RouteInputContext;
13
+ export declare function rawInput({ req }: {
14
+ readonly req: Request;
15
+ }, _optional?: Record<string, never>): RouteInputContext;
14
16
  /**
15
17
  * Builds a `BAD_REQUEST` `ApiError` for a failed parse. When `issues` is non-empty, attaches
16
18
  * them as structured validation details so clients can render per-field errors.
17
19
  */
18
- export declare function validationError(message: string, issues?: Pick<ApiValidationIssue, 'path' | 'message'>[]): ApiError;
20
+ export declare function validationError({ message }: {
21
+ readonly message: string;
22
+ }, { issues }?: {
23
+ readonly issues?: Pick<ApiValidationIssue, 'path' | 'message'>[] | undefined;
24
+ }): ApiError;
19
25
  //# sourceMappingURL=request.d.ts.map
package/dist/request.js CHANGED
@@ -3,7 +3,7 @@ import { createApiError } from '@jini-ai/protocol';
3
3
  * Extracts `body`/`query`/`params` from an Express `Request` into a `RouteInputContext`, so a
4
4
  * route's `parse` function can be unit-tested without constructing a real `Request`.
5
5
  */
6
- export function rawInput(req) {
6
+ export function rawInput({ req }, _optional = {}) {
7
7
  return {
8
8
  body: req.body,
9
9
  query: (req.query ?? {}),
@@ -14,11 +14,11 @@ export function rawInput(req) {
14
14
  * Builds a `BAD_REQUEST` `ApiError` for a failed parse. When `issues` is non-empty, attaches
15
15
  * them as structured validation details so clients can render per-field errors.
16
16
  */
17
- export function validationError(message, issues = []) {
17
+ export function validationError({ message }, { issues = [] } = {}) {
18
18
  if (issues.length === 0) {
19
- return createApiError('BAD_REQUEST', message);
19
+ return createApiError({ code: 'BAD_REQUEST', message: message });
20
20
  }
21
- return createApiError('BAD_REQUEST', message, {
21
+ return createApiError({ code: 'BAD_REQUEST', message: message }, {
22
22
  details: { kind: 'validation', issues },
23
23
  });
24
24
  }
@@ -6,9 +6,21 @@
6
6
  import type { Response } from 'express';
7
7
  import { type ApiError } from '@jini-ai/protocol';
8
8
  /** Writes `body` as JSON with the given status code. */
9
- export declare function sendJson(res: Response, status: number, body: unknown): void;
10
- /** Writes an `ApiError`, wrapped in the standard `{ error }` envelope, with the given status code. */
11
- export declare function sendApiError(res: Response, status: number, error: ApiError): void;
9
+ export declare function sendJson({ res, status, body }: {
10
+ readonly res: Response;
11
+ readonly status: number;
12
+ readonly body: unknown;
13
+ }, _optional?: Record<string, never>): void;
14
+ /** Writes an `ApiError`, wrapped in the standard `{ error }` envelope, with the given status code.
15
+ * Older hand-mounted routes supplied code/message and metadata separately; construct their
16
+ * ApiError first so both generations now share one serialization and envelope policy. */
17
+ export declare function sendApiError({ res, status, error }: {
18
+ readonly res: Response;
19
+ readonly status: number;
20
+ readonly error: ApiError;
21
+ }, _optional?: Record<string, never>): void;
12
22
  /** Resolves the HTTP status to send for an `ApiError`, defaulting to 500 for unmapped codes. */
13
- export declare function statusForError(error: ApiError): number;
23
+ export declare function statusForError({ error }: {
24
+ readonly error: ApiError;
25
+ }, _optional?: Record<string, never>): number;
14
26
  //# sourceMappingURL=response.d.ts.map
package/dist/response.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { createApiErrorResponse } from '@jini-ai/protocol';
2
2
  /** Writes `body` as JSON with the given status code. */
3
- export function sendJson(res, status, body) {
3
+ export function sendJson({ res, status, body }, _optional = {}) {
4
4
  res.status(status).json(body);
5
5
  }
6
- /** Writes an `ApiError`, wrapped in the standard `{ error }` envelope, with the given status code. */
7
- export function sendApiError(res, status, error) {
8
- res.status(status).json(createApiErrorResponse(error));
6
+ /** Writes an `ApiError`, wrapped in the standard `{ error }` envelope, with the given status code.
7
+ * Older hand-mounted routes supplied code/message and metadata separately; construct their
8
+ * ApiError first so both generations now share one serialization and envelope policy. */
9
+ export function sendApiError({ res, status, error }, _optional = {}) {
10
+ res.status(status).json(createApiErrorResponse({ error: error }));
9
11
  }
10
12
  /**
11
13
  * @internal
@@ -40,7 +42,7 @@ const ERROR_STATUS_BY_CODE = {
40
42
  OAUTH_FLOW_IN_PROGRESS: 409,
41
43
  };
42
44
  /** Resolves the HTTP status to send for an `ApiError`, defaulting to 500 for unmapped codes. */
43
- export function statusForError(error) {
45
+ export function statusForError({ error }, _optional = {}) {
44
46
  return ERROR_STATUS_BY_CODE[error.code] ?? 500;
45
47
  }
46
48
  //# sourceMappingURL=response.js.map
@@ -7,7 +7,7 @@
7
7
  * registration — e.g. two packs each mounting `POST /api/runs` would otherwise silently shadow
8
8
  * one another instead of failing loudly at composition time.
9
9
  *
10
- * Genericized from an origin daemon's route-registration guard — see `source-map.md`. The
10
+ * Genericized from an origin daemon's route-registration guard — see `archived provenance ledger`. The
11
11
  * origin hardcoded a fixed two-route guarded set (product routes with no meaning in the generic
12
12
  * engine); here the guarded set is an injectable `ReadonlySet<string>` that defaults to empty, so
13
13
  * installing this guard with no options is a pure inventory tap with no enforcement.
@@ -31,7 +31,11 @@ export interface RouteRegistration {
31
31
  * @complexity O(1) — a single `Set` lookup.
32
32
  * @overallScore 100/100
33
33
  */
34
- export declare function guardedRouteKey(method: string, path: unknown, guardedRouteKeys: ReadonlySet<string>): string | null;
34
+ export declare function guardedRouteKey({ method, path, guardedRouteKeys }: {
35
+ readonly method: string;
36
+ readonly path: unknown;
37
+ readonly guardedRouteKeys: ReadonlySet<string>;
38
+ }, _optional?: Record<string, never>): string | null;
35
39
  export interface InstallRouteRegistrationGuardOptions {
36
40
  /** `METHOD PATH` keys (e.g. `'POST /api/runs'`) that must be registered at most once on `app`. Defaults to none — installing the guard with no options only builds the inventory, it enforces nothing. */
37
41
  guardedRouteKeys?: ReadonlySet<string>;
@@ -51,15 +55,19 @@ export interface InstallRouteRegistrationGuardOptions {
51
55
  * @complexity O(1) setup (patches 8 fixed methods); each wrapped call is O(1) beyond the wrapped original.
52
56
  * @overallScore 100/100
53
57
  */
54
- export declare function installRouteRegistrationGuard(app: Express, options?: InstallRouteRegistrationGuardOptions): void;
58
+ export declare function installRouteRegistrationGuard({ app }: {
59
+ readonly app: Express;
60
+ }, options?: InstallRouteRegistrationGuardOptions): void;
55
61
  /**
56
62
  * Reads back every route {@link installRouteRegistrationGuard} recorded for `app`.
57
63
  *
58
64
  * @param app - An app the guard was installed on. Safe to call on an app with no guard installed
59
65
  * (returns an empty array rather than throwing).
60
- * @returns A fresh array copy each call — the caller can never mutate the guard's own internal inventory through the returned reference.
66
+ * @returns A fresh array with copied entries each call — the caller can never mutate the guard's own internal inventory through the returned reference.
61
67
  * @complexity O(n) in the number of routes registered so far.
62
68
  * @overallScore 100/100
63
69
  */
64
- export declare function getRouteRegistrationInventory(app: Express): RouteRegistration[];
70
+ export declare function getRouteRegistrationInventory({ app }: {
71
+ readonly app: Express;
72
+ }, _optional?: Record<string, never>): RouteRegistration[];
65
73
  //# sourceMappingURL=route-registration-guard.d.ts.map
@@ -13,7 +13,7 @@ const GUARDED_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'options', 'al
13
13
  * @complexity O(1) — a single `Set` lookup.
14
14
  * @overallScore 100/100
15
15
  */
16
- export function guardedRouteKey(method, path, guardedRouteKeys) {
16
+ export function guardedRouteKey({ method, path, guardedRouteKeys }, _optional = {}) {
17
17
  if (typeof path !== 'string')
18
18
  return null;
19
19
  const key = `${method.toUpperCase()} ${path}`;
@@ -34,7 +34,7 @@ export function guardedRouteKey(method, path, guardedRouteKeys) {
34
34
  * @complexity O(1) setup (patches 8 fixed methods); each wrapped call is O(1) beyond the wrapped original.
35
35
  * @overallScore 100/100
36
36
  */
37
- export function installRouteRegistrationGuard(app, options = {}) {
37
+ export function installRouteRegistrationGuard({ app }, options = {}) {
38
38
  const guardedRouteKeys = options.guardedRouteKeys ?? new Set();
39
39
  const seen = new Set();
40
40
  const inventory = [];
@@ -45,7 +45,7 @@ export function installRouteRegistrationGuard(app, options = {}) {
45
45
  if (typeof path === 'string') {
46
46
  inventory.push({ method: method.toUpperCase(), path });
47
47
  }
48
- const key = guardedRouteKey(method, path, guardedRouteKeys);
48
+ const key = guardedRouteKey({ method, path, guardedRouteKeys });
49
49
  if (key) {
50
50
  if (seen.has(key)) {
51
51
  throw new Error(`duplicate guarded route registration: ${key}`);
@@ -61,11 +61,11 @@ export function installRouteRegistrationGuard(app, options = {}) {
61
61
  *
62
62
  * @param app - An app the guard was installed on. Safe to call on an app with no guard installed
63
63
  * (returns an empty array rather than throwing).
64
- * @returns A fresh array copy each call — the caller can never mutate the guard's own internal inventory through the returned reference.
64
+ * @returns A fresh array with copied entries each call — the caller can never mutate the guard's own internal inventory through the returned reference.
65
65
  * @complexity O(n) in the number of routes registered so far.
66
66
  * @overallScore 100/100
67
67
  */
68
- export function getRouteRegistrationInventory(app) {
69
- return [...(app[routeInventorySymbol] ?? [])];
68
+ export function getRouteRegistrationInventory({ app }, _optional = {}) {
69
+ return (app[routeInventorySymbol] ?? []).map((entry) => ({ ...entry }));
70
70
  }
71
71
  //# sourceMappingURL=route-registration-guard.js.map
package/dist/sse.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * Before this file, the only SSE machinery in this package was inlined
5
5
  * directly inside `runs.ts`'s `registerRunEventStream` (a bounded-queue,
6
6
  * backpressure-aware `res.write`/`'drain'` state machine with Last-Event-ID
7
- * replay support) — see `source-map.md`'s 2026-07-19 "generic lifecycle SSE
7
+ * replay support) — see `archived provenance ledger`'s 2026-07-19 "generic lifecycle SSE
8
8
  * projection" note and the many "requires SSE (deferred)" verdicts against
9
9
  * `chat.ts`/`memory.ts`/`terminal.ts` in the routes-classification table.
10
10
  * `createSseChannel` below is that same state machine, generalized over any
@@ -41,11 +41,17 @@ export interface CreateSseChannelOptions<E extends SseEvent> {
41
41
  /** Queued-event ceiling before the connection is dropped. Defaults to {@link DEFAULT_MAX_QUEUED_SSE_EVENTS}. */
42
42
  readonly maxQueuedEvents?: number;
43
43
  /** When true for a given event, the channel ends the stream immediately after writing it (matches `runs.ts`'s `'end'`-kind auto-close). Omit for a channel that only ends on client disconnect/overflow/explicit `end()`. */
44
- readonly isEndEvent?: (event: E) => boolean;
44
+ readonly isEndEvent?: ({ event }: {
45
+ event: E;
46
+ }) => boolean;
45
47
  /** Overrides the wire format. Defaults to {@link defaultFormatEvent}. */
46
- readonly formatEvent?: (event: E) => string;
48
+ readonly formatEvent?: ({ event }: {
49
+ event: E;
50
+ }) => string;
47
51
  /** Invoked once, synchronously, if `res.write` throws mid-flush — lets a caller log the real error without it crossing back into whatever produced the event (mirrors `runs.ts`'s `RunHttpDeps.onInternalError` seam, but this primitive itself stays logging-free: silent by default, matching a transport channel's "never throw back through the producer" contract). */
48
- readonly onWriteError?: (error: unknown) => void;
52
+ readonly onWriteError?: ({ error }: {
53
+ error: unknown;
54
+ }) => void;
49
55
  }
50
56
  export interface SseChannel<E extends SseEvent> {
51
57
  /**
@@ -55,7 +61,9 @@ export interface SseChannel<E extends SseEvent> {
55
61
  * replay history before opening the stream — the client's very first
56
62
  * flush then already contains that backlog.
57
63
  */
58
- readonly enqueue: (event: E) => void;
64
+ readonly enqueue: ({ event }: {
65
+ readonly event: E;
66
+ }, _optional?: Record<string, never>) => void;
59
67
  /**
60
68
  * Writes SSE headers (`200`, `text/event-stream`, `Cache-Control: no-cache,
61
69
  * no-transform`, `Connection: keep-alive`) and starts draining the queue.
@@ -93,7 +101,9 @@ export interface SseChannel<E extends SseEvent> {
93
101
  * overflow/write failure). Safe to call after the channel is already
94
102
  * closed — the callback then runs immediately, synchronously.
95
103
  */
96
- readonly onClose: (callback: () => void) => void;
104
+ readonly onClose: ({ callback }: {
105
+ readonly callback: () => void;
106
+ }, _optional?: Record<string, never>) => void;
97
107
  }
98
108
  /**
99
109
  * Builds a bounded, backpressure-aware SSE channel over an Express `Response`.
@@ -122,7 +132,9 @@ export interface SseChannel<E extends SseEvent> {
122
132
  * @complexity `enqueue`/`open`/`end` are O(1) amortized; a full queue drain is O(events written).
123
133
  * @overallScore 100/100
124
134
  */
125
- export declare function createSseChannel<E extends SseEvent>(res: ServerResponse, options?: CreateSseChannelOptions<E>): SseChannel<E>;
135
+ export declare function createSseChannel<E extends SseEvent>({ res }: {
136
+ readonly res: ServerResponse;
137
+ }, options?: CreateSseChannelOptions<E>): SseChannel<E>;
126
138
  /** Reads a reconnect cursor from the standard `Last-Event-ID` header, falling back to an `afterCursor` query parameter. Shared by any SSE route that supports reconnect replay (the header takes precedence since it is what browsers set automatically on `EventSource` reconnect). */
127
139
  export declare function requestedAfterCursor(req: {
128
140
  get(name: string): string | undefined;
@@ -132,8 +144,12 @@ export declare function requestedAfterCursor(req: {
132
144
  * Writes an `ApiError`, wrapped in the standard `{ error }` envelope, directly onto a raw
133
145
  * `ServerResponse` — for the narrow window before an `SseChannel` has opened (so Express's own
134
146
  * `res.json()` response wrapper isn't safe to use yet). Produces the identical
135
- * `createApiErrorResponse(error)` envelope shape `response.ts`'s `sendApiError`/`sendJson` do —
147
+ * `createApiErrorResponse({ error: error })` envelope shape `response.ts`'s `sendApiError`/`sendJson` do —
136
148
  * this just writes that same shape without going through Express's response helper.
137
149
  */
138
- export declare function sendRawApiError(res: ServerResponse, status: number, error: ApiError): void;
150
+ export declare function sendRawApiError({ res, status, error }: {
151
+ readonly res: ServerResponse;
152
+ readonly status: number;
153
+ readonly error: ApiError;
154
+ }, _optional?: Record<string, never>): void;
139
155
  //# sourceMappingURL=sse.d.ts.map