@jini-ai/server 0.0.0-stage → 0.5.0

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.
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The runtime half of {@link CapabilityId}.
3
+ *
4
+ * Declared as a `Record<CapabilityId, true>` rather than a plain array so drift is a compile error
5
+ * in **both** directions: a union member missing here fails the `Record`'s exhaustiveness, and a
6
+ * key here that is not in the union fails the object literal's excess-property check. A validation
7
+ * list that can silently fall behind the type it validates is worse than none, because it reads as
8
+ * closed while quietly admitting whatever was added last.
9
+ */
10
+ const CAPABILITY_ID_SET = Object.freeze({
11
+ 'run:transport': true,
12
+ 'run:inject': true,
13
+ 'agent:discovery': true,
14
+ 'tool:delegated': true,
15
+ 'tool:catalog': true,
16
+ 'host:read': true,
17
+ 'host:exec': true,
18
+ 'db:admin': true,
19
+ 'net:egress': true,
20
+ 'daemon:control': true,
21
+ 'memory:store': true,
22
+ 'routines:schedule': true,
23
+ 'media:generate': true,
24
+ 'ui:session': true,
25
+ });
26
+ /** Every capability this vocabulary declares, for error messages and for exhaustive iteration. */
27
+ export const CAPABILITY_IDS = Object.freeze(Object.keys(CAPABILITY_ID_SET));
28
+ /** Whether `value` names a capability this vocabulary actually declares. */
29
+ export function isCapabilityId(required) {
30
+ return Object.prototype.hasOwnProperty.call(CAPABILITY_ID_SET, required.value);
31
+ }
32
+ /**
33
+ * The capabilities a feature may default to *on* under the `core-only` activation policy — the
34
+ * run transport, installed-agent discovery and the delegated-tool gateway. These are the frozen
35
+ * embedding contract; adding host execution or network egress would expand the security ceiling.
36
+ *
37
+ * A feature qualifies only if **every** capability it provides is in here, so a feature that mixes
38
+ * a core capability with a non-core one (say `run:transport` plus `host:exec`) does not sneak in on
39
+ * the strength of its safe half.
40
+ */
41
+ export const CORE_CAPABILITIES = Object.freeze([
42
+ 'run:transport',
43
+ 'agent:discovery',
44
+ 'tool:delegated',
45
+ ]);
46
+ /** Identity helper that pins a feature's shape at the definition site. */
47
+ export function defineJiniFeature(feature) {
48
+ return feature;
49
+ }
50
+ /**
51
+ * The shipped profiles. **Versioned and immutable**: a future capability must never silently join
52
+ * an existing profile's grant set, because a consumer pinned to `local-daemon-v1` chose the
53
+ * authority surface it had on the day it pinned. A new set is a new id (`-v2`), not an edit.
54
+ *
55
+ * Both name a *capability grant*, never a hand-listed feature array — so the active feature list is
56
+ * always computed from capability semantics and cannot drift away from them when a feature is
57
+ * added, renamed, or reclassified.
58
+ */
59
+ export const JINI_PROFILES = Object.freeze({
60
+ /**
61
+ * The conservative embedding default: run transport, agent discovery and delegated tools.
62
+ * Everything that adds host execution, network egress, database administration or daemon control
63
+ * is outside the grant, so it can be
64
+ * neither defaulted on nor explicitly enabled without the host first raising the ceiling.
65
+ */
66
+ 'agent-core-v1': Object.freeze({
67
+ id: 'agent-core-v1',
68
+ grants: Object.freeze(['run:transport', 'agent:discovery', 'tool:delegated']),
69
+ activation: 'core-only',
70
+ }),
71
+ /**
72
+ * `createLocalNodeDaemon`'s historical surface, frozen as a compatibility profile: exactly the
73
+ * capabilities the standalone daemon has always mounted. `run:inject`, `memory:store`,
74
+ * `routines:schedule`, `media:generate` and `ui:session` are **absent by design** — those route
75
+ * families were never wired by that preset, and granting them here would silently expand a
76
+ * shipped daemon's surface.
77
+ */
78
+ 'local-daemon-v1': Object.freeze({
79
+ id: 'local-daemon-v1',
80
+ grants: Object.freeze([
81
+ 'run:transport',
82
+ 'agent:discovery',
83
+ 'tool:delegated',
84
+ 'tool:catalog',
85
+ 'host:read',
86
+ 'host:exec',
87
+ 'db:admin',
88
+ 'net:egress',
89
+ 'daemon:control',
90
+ ]),
91
+ activation: 'all-permitted',
92
+ }),
93
+ });
94
+ //# sourceMappingURL=feature.js.map
@@ -0,0 +1,76 @@
1
+ import type { ToolPolicy, ToolRegistration } from '@jini-ai/core';
2
+ import { type FrontendCapabilitySpec } from '@jini-ai/daemon';
3
+ import { type RunCreateRequest, type RunStartHandler } from '@jini-ai/http-kit';
4
+ import type { LocalNodeHttpExtension } from './create-local-node-daemon.js';
5
+ export interface FrontendBindErrorContext {
6
+ readonly runId: string;
7
+ readonly error: unknown;
8
+ }
9
+ export interface CreateFrontendControlOptions {
10
+ /**
11
+ * The capabilities to expose. `@jini-ai/agentic`'s `PAGE_CAPABILITIES` and `@jini-ai/chat-core`'s
12
+ * `CHAT_CAPABILITIES` satisfy this structurally — the engine never imports that vocabulary
13
+ * (see `frontend-capability-tools.ts`'s module doc for why the edge points one way).
14
+ */
15
+ readonly capabilities: readonly FrontendCapabilitySpec[];
16
+ /**
17
+ * Reads this run's bind token out of the host's own run request, or returns `undefined` when the
18
+ * run has no originating surface.
19
+ *
20
+ * Required, and deliberately not defaulted. A default would have to guess where a host keeps the
21
+ * token, and guessing wrong fails *open* in the confusing direction: the run starts, the agent
22
+ * gets its tools, and every page call fails later with "no frontend is bound" — a symptom that
23
+ * looks like a browser problem and is actually a config one.
24
+ *
25
+ * Returning `undefined` is normal, not an error. A run started from a CLI has no surface, and
26
+ * capabilities whose `surface` is `'server'` do not need one.
27
+ */
28
+ readonly resolveBindToken: (request: RunCreateRequest) => string | undefined;
29
+ /** @default `@jini-ai/daemon`'s `denyAllFrontendCapabilityPolicy` — a host grants access explicitly. */
30
+ readonly policy?: ToolPolicy;
31
+ /** @default `@jini-ai/daemon`'s `DEFAULT_FRONTEND_CAPABILITY_TIMEOUT_MS`. */
32
+ readonly timeoutMs?: number;
33
+ /** Applied to every registration. Frontend output is untrusted page text; bound it. */
34
+ readonly maxOutputBytes?: number;
35
+ /**
36
+ * Host-owned sink for a bind failure. Defaults to `console.error`.
37
+ *
38
+ * A failed bind does not fail the run. The run is still legitimate — the agent simply cannot
39
+ * drive the page, and every capability call it makes will say so by name. Killing a run because
40
+ * one optional channel could not be established would turn a degraded session into no session.
41
+ */
42
+ readonly onBindError?: (context: FrontendBindErrorContext) => void;
43
+ }
44
+ export interface FrontendControl {
45
+ /** Mounts the frontend-session stream and response routes. Pass in `httpExtensions`. */
46
+ readonly httpExtension: LocalNodeHttpExtension;
47
+ /** One gated tool per capability. Pass in `toolRegistrations`. */
48
+ readonly toolRegistrations: readonly ToolRegistration[];
49
+ /**
50
+ * Binds each starting run to the surface that originated it, and releases the binding when the
51
+ * run reaches a terminal state so a long-lived tab does not accumulate dead bindings.
52
+ *
53
+ * Compose it with whatever the host already does on run start — this hook only binds, it never
54
+ * executes anything:
55
+ *
56
+ * ```ts
57
+ * onRunStarted: (context) => {
58
+ * frontend.bindOnStarted(context);
59
+ * void startMyAgent(context);
60
+ * }
61
+ * ```
62
+ */
63
+ readonly bindOnStarted: RunStartHandler;
64
+ }
65
+ /**
66
+ * Builds the frontend-control bundle.
67
+ *
68
+ * @param options - Capabilities to expose, how to find the bind token, and the gate to apply.
69
+ * @returns An HTTP extension, tool registrations, and a run-start bind hook — never the registry.
70
+ * @throws Never at construction. A duplicate capability id throws later, when the registrations are
71
+ * registered, naming the id (`ToolRegistry.register`'s own error).
72
+ *
73
+ * @complexity O(n) in `capabilities`.
74
+ */
75
+ export declare function createFrontendControl(options: CreateFrontendControlOptions): FrontendControl;
76
+ //# sourceMappingURL=frontend-control.d.ts.map
@@ -0,0 +1,77 @@
1
+ import { createFrontendCapabilityRegistrations, createFrontendSessionRegistry, } from '@jini-ai/daemon';
2
+ import { registerFrontendSessionRoutes, } from '@jini-ai/http-kit';
3
+ function defaultBindErrorSink(context) {
4
+ // eslint-disable-next-line no-console
5
+ console.error(`[@jini-ai/server] could not bind run "${context.runId}" to a frontend surface`, context.error);
6
+ }
7
+ /**
8
+ * Builds the frontend-control bundle.
9
+ *
10
+ * @param options - Capabilities to expose, how to find the bind token, and the gate to apply.
11
+ * @returns An HTTP extension, tool registrations, and a run-start bind hook — never the registry.
12
+ * @throws Never at construction. A duplicate capability id throws later, when the registrations are
13
+ * registered, naming the id (`ToolRegistry.register`'s own error).
14
+ *
15
+ * @complexity O(n) in `capabilities`.
16
+ */
17
+ export function createFrontendControl(options) {
18
+ // Closed over, never exposed. See the module doc: reaching this is reaching an ungated `invoke`.
19
+ const registry = createFrontendSessionRegistry();
20
+ const onBindError = options.onBindError ?? defaultBindErrorSink;
21
+ const toolRegistrations = createFrontendCapabilityRegistrations({
22
+ registry,
23
+ capabilities: options.capabilities,
24
+ ...(options.policy !== undefined ? { policy: options.policy } : {}),
25
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
26
+ ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
27
+ });
28
+ const httpExtension = (app, context) => {
29
+ registerFrontendSessionRoutes(app, { registry }, context.adapter);
30
+ };
31
+ /**
32
+ * The error boundary the `onBindError` contract actually needs. A `RunStartHandler` throwing is
33
+ * not a no-op: `@jini-ai/http-kit`'s run-start route catches it, marks the run `failed` and answers
34
+ * 500 — so anything inside this hook that can throw can produce exactly the killed run that
35
+ * contract promises never to cause. `resolveBindToken` is host-supplied and reads an opaque host
36
+ * blob (a `JSON.parse` away from throwing), and the sink itself is host-supplied too. A sink that
37
+ * throws leaves nowhere left to report, so that one is swallowed rather than escalated.
38
+ */
39
+ const reportBindError = (context) => {
40
+ try {
41
+ onBindError(context);
42
+ }
43
+ catch {
44
+ // Deliberately terminal: the reporting channel is what failed.
45
+ }
46
+ };
47
+ const bindOnStarted = ({ request, run, lifecycle }) => {
48
+ let bindToken;
49
+ try {
50
+ bindToken = options.resolveBindToken(request);
51
+ }
52
+ catch (error) {
53
+ reportBindError({ runId: run.id, error });
54
+ return;
55
+ }
56
+ if (bindToken === undefined)
57
+ return;
58
+ let release;
59
+ try {
60
+ release = registry.bindRunByToken(run.id, bindToken);
61
+ }
62
+ catch (error) {
63
+ reportBindError({ runId: run.id, error });
64
+ return;
65
+ }
66
+ // Release on terminal so a tab that outlives many runs does not accumulate bindings for runs
67
+ // that ended. `waitForTerminal` rejecting is itself a reason to release, not to keep waiting,
68
+ // so both paths run it — and the whole chain is swallowed, because a bookkeeping failure must
69
+ // never surface as an unhandled rejection that takes the process down.
70
+ void lifecycle
71
+ .waitForTerminal(run.id)
72
+ .then(release, release)
73
+ .catch(() => undefined);
74
+ };
75
+ return { httpExtension, toolRegistrations, bindOnStarted };
76
+ }
77
+ //# sourceMappingURL=frontend-control.js.map
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @module host-bootstrap
3
+ *
4
+ * Generic host-lifecycle primitives ported from an origin daemon's CLI-startup module — see
5
+ * `archived provenance ledger`. Only the two functions with no CLI-flag-parsing or env-var-reading inside their
6
+ * own bodies are ported here: `parseDaemonCliStartupArgs` (argv/env parsing for a `od <cmd>`-style
7
+ * CLI) and the higher-level `startDaemonRuntime`/`runDaemonCliStartup` wrappers belong to a future
8
+ * `@jini-ai/cli` task, not this one — this module is deliberately CLI-shape-agnostic.
9
+ */
10
+ import type { Server } from 'node:http';
11
+ export declare const DEFAULT_DAEMON_BIND_HOST = "127.0.0.1";
12
+ /**
13
+ * Trims `input` to a usable bind-host string, falling back to the loopback default for
14
+ * blank/nullish input.
15
+ *
16
+ * @param input - A caller-supplied host value of unknown shape (typically `string | undefined`
17
+ * from an options object, hence the deliberately loose `unknown` parameter type).
18
+ * @returns The trimmed stringification of `input`, or {@link DEFAULT_DAEMON_BIND_HOST} when
19
+ * `input` is nullish or its stringification trims to empty. Nonstrings deliberately retain the
20
+ * historical coercion, so a supplied number is not silently replaced with the loopback host.
21
+ * @complexity O(1).
22
+ * @overallScore 100/100
23
+ */
24
+ export declare function normalizeDaemonBindHost(input: unknown): string;
25
+ export interface CloseHttpServerOptions {
26
+ /** Hard ceiling before force-closing every remaining socket. Defaults to 5000ms. */
27
+ closeTimeoutMs?: number;
28
+ /** Delay before closing idle (non-active) connections, capped by `closeTimeoutMs`. Defaults to 1000ms. */
29
+ idleCloseMs?: number;
30
+ }
31
+ /**
32
+ * Gracefully closes `server`: after a short `idleCloseMs` grace period it closes idle
33
+ * connections, then force-closes any connection still open once `closeTimeoutMs` elapses. Resolves
34
+ * immediately, without touching any socket, if `server` is not currently listening.
35
+ *
36
+ * @param server - The `node:http` server to close.
37
+ * @param options.closeTimeoutMs - See {@link CloseHttpServerOptions}.
38
+ * @param options.idleCloseMs - See {@link CloseHttpServerOptions}.
39
+ * @returns Resolves once `server.close()`'s callback fires with no error, or once the hard timeout
40
+ * force-closes connections, whichever happens first. The deadline deliberately bounds shutdown
41
+ * even if the callback never arrives; any later callback is ignored after settlement.
42
+ * @throws Rejects with whatever error `server.close()`'s callback reports (e.g. calling `close()`
43
+ * on a server that was never listening in the first place — guarded against above by the early
44
+ * return). Errors received before settlement propagate; callbacks after the hard deadline do not
45
+ * replace its already-settled result.
46
+ * @complexity O(1) scheduling; the actual wait is bounded by `closeTimeoutMs`.
47
+ * @overallScore 100/100
48
+ */
49
+ export declare function closeHttpServer(server: Server, options?: CloseHttpServerOptions): Promise<void>;
50
+ export interface GracefulShutdownOptions {
51
+ /** Host signal/exit adapter. The default preserves Node's process-global signal handling. */
52
+ process?: ShutdownProcessPort;
53
+ /** Node timer ABI, injectable so a host controls shutdown scheduling. */
54
+ timers?: Pick<typeof globalThis, 'setTimeout' | 'clearTimeout'>;
55
+ /** Node console ABI; timeout and failure messages retain their historical arguments. */
56
+ logger?: Pick<Console, 'error'>;
57
+ /** OS signals to listen for. Defaults to `['SIGTERM', 'SIGINT']` — the two a container runtime,
58
+ * process manager, or an operator's `kill`/Ctrl-C ordinarily send to stop a long-lived daemon. */
59
+ signals?: readonly NodeJS.Signals[];
60
+ /** Hard ceiling, from the first signal, before forcing exit even if `stop()` never settles — a
61
+ * wedged shutdown must not block the process from ever exiting. Defaults to 10000ms (Docker's own
62
+ * default grace period before it escalates to `SIGKILL`). */
63
+ timeoutMs?: number;
64
+ /** Called exactly once, with `0` if `stop()` resolved or `1` if it rejected or the timeout fired
65
+ * first. Defaults to the supplied process port's exit (Node process.exit by default). Override to observe or customize the final step (tests always
66
+ * do this — calling the real `process.exit` from a unit test would kill the test runner). */
67
+ onExit?: (code: number) => void;
68
+ }
69
+ /** Minimal Node signal ABI; embedders can supply their own process without seizing global listeners. */
70
+ export interface ShutdownProcessPort {
71
+ on(signal: NodeJS.Signals, listener: (signal: NodeJS.Signals) => void): unknown;
72
+ off(signal: NodeJS.Signals, listener: (signal: NodeJS.Signals) => void): unknown;
73
+ exit(code: number): unknown;
74
+ }
75
+ export interface GracefulShutdownHandle {
76
+ /** Removes the installed signal listeners. A later signal is then a plain no-op — Node's own
77
+ * default behavior applies again, exactly as if this had never been called. */
78
+ uninstall(): void;
79
+ }
80
+ /**
81
+ * Wires `stop` to the process's OS shutdown signals so a container stop, process-manager restart, or
82
+ * operator `kill`/Ctrl-C runs the caller's graceful teardown instead of Node's default immediate
83
+ * termination. Deliberately opt-in rather than something `createLocalNodeDaemon` installs on every
84
+ * caller's behalf: a library that unilaterally seizes process-global signal handling can surprise an
85
+ * embedding host that manages its own process lifecycle (an Electron shell, for one, already owns
86
+ * its own fatal-exception handling and — per `desktop-host`'s own sidecar shutdown path — asks a
87
+ * spawned daemon child to stop over HTTP and falls back to `SIGKILL`, never `SIGTERM`, so it neither
88
+ * needs nor should double up on this). One line at the host's own entrypoint —
89
+ * `installGracefulShutdown({ stop: daemon.stop })` — is the whole integration.
90
+ *
91
+ * Idempotent and re-entrant: a second signal that arrives while a shutdown from the first is still
92
+ * in flight is ignored outright (not queued, not a second `stop()` call) — the in-flight shutdown
93
+ * (or, past `timeoutMs`, the forced exit) is left to finish on its own.
94
+ *
95
+ * @param stop - The caller's own graceful-shutdown function, e.g. a `LocalNodeDaemon.stop`.
96
+ * @param options - See {@link GracefulShutdownOptions}.
97
+ * @returns A handle whose `uninstall()` removes the installed listeners.
98
+ * @complexity O(1) to install; the signal handler itself is O(1) plus whatever `stop` costs.
99
+ */
100
+ export declare function installGracefulShutdown({ stop }: {
101
+ stop: () => Promise<void>;
102
+ }, options?: GracefulShutdownOptions): GracefulShutdownHandle;
103
+ //# sourceMappingURL=host-bootstrap.d.ts.map
@@ -0,0 +1,146 @@
1
+ export const DEFAULT_DAEMON_BIND_HOST = '127.0.0.1';
2
+ /**
3
+ * Trims `input` to a usable bind-host string, falling back to the loopback default for
4
+ * blank/nullish input.
5
+ *
6
+ * @param input - A caller-supplied host value of unknown shape (typically `string | undefined`
7
+ * from an options object, hence the deliberately loose `unknown` parameter type).
8
+ * @returns The trimmed stringification of `input`, or {@link DEFAULT_DAEMON_BIND_HOST} when
9
+ * `input` is nullish or its stringification trims to empty. Nonstrings deliberately retain the
10
+ * historical coercion, so a supplied number is not silently replaced with the loopback host.
11
+ * @complexity O(1).
12
+ * @overallScore 100/100
13
+ */
14
+ export function normalizeDaemonBindHost(input) {
15
+ const host = String(input ?? '').trim();
16
+ return host || DEFAULT_DAEMON_BIND_HOST;
17
+ }
18
+ /**
19
+ * Gracefully closes `server`: after a short `idleCloseMs` grace period it closes idle
20
+ * connections, then force-closes any connection still open once `closeTimeoutMs` elapses. Resolves
21
+ * immediately, without touching any socket, if `server` is not currently listening.
22
+ *
23
+ * @param server - The `node:http` server to close.
24
+ * @param options.closeTimeoutMs - See {@link CloseHttpServerOptions}.
25
+ * @param options.idleCloseMs - See {@link CloseHttpServerOptions}.
26
+ * @returns Resolves once `server.close()`'s callback fires with no error, or once the hard timeout
27
+ * force-closes connections, whichever happens first. The deadline deliberately bounds shutdown
28
+ * even if the callback never arrives; any later callback is ignored after settlement.
29
+ * @throws Rejects with whatever error `server.close()`'s callback reports (e.g. calling `close()`
30
+ * on a server that was never listening in the first place — guarded against above by the early
31
+ * return). Errors received before settlement propagate; callbacks after the hard deadline do not
32
+ * replace its already-settled result.
33
+ * @complexity O(1) scheduling; the actual wait is bounded by `closeTimeoutMs`.
34
+ * @overallScore 100/100
35
+ */
36
+ export async function closeHttpServer(server, options = {}) {
37
+ const { closeTimeoutMs = 5_000, idleCloseMs = 1_000 } = options;
38
+ if (!server.listening)
39
+ return;
40
+ await new Promise((resolveClose, rejectClose) => {
41
+ let resolved = false;
42
+ const resolveOnce = () => {
43
+ if (resolved)
44
+ return;
45
+ resolved = true;
46
+ clearTimeout(idleTimer);
47
+ clearTimeout(hardTimer);
48
+ resolveClose();
49
+ };
50
+ const rejectOnce = (error) => {
51
+ if (resolved)
52
+ return;
53
+ resolved = true;
54
+ clearTimeout(idleTimer);
55
+ clearTimeout(hardTimer);
56
+ rejectClose(error);
57
+ };
58
+ const idleTimer = setTimeout(() => {
59
+ server.closeIdleConnections?.();
60
+ }, Math.min(idleCloseMs, closeTimeoutMs));
61
+ const hardTimer = setTimeout(() => {
62
+ server.closeAllConnections?.();
63
+ resolveOnce();
64
+ }, closeTimeoutMs);
65
+ idleTimer.unref?.();
66
+ hardTimer.unref?.();
67
+ server.close((error) => (error == null ? resolveOnce() : rejectOnce(error)));
68
+ }).finally(() => {
69
+ server.closeIdleConnections?.();
70
+ });
71
+ }
72
+ /**
73
+ * Wires `stop` to the process's OS shutdown signals so a container stop, process-manager restart, or
74
+ * operator `kill`/Ctrl-C runs the caller's graceful teardown instead of Node's default immediate
75
+ * termination. Deliberately opt-in rather than something `createLocalNodeDaemon` installs on every
76
+ * caller's behalf: a library that unilaterally seizes process-global signal handling can surprise an
77
+ * embedding host that manages its own process lifecycle (an Electron shell, for one, already owns
78
+ * its own fatal-exception handling and — per `desktop-host`'s own sidecar shutdown path — asks a
79
+ * spawned daemon child to stop over HTTP and falls back to `SIGKILL`, never `SIGTERM`, so it neither
80
+ * needs nor should double up on this). One line at the host's own entrypoint —
81
+ * `installGracefulShutdown({ stop: daemon.stop })` — is the whole integration.
82
+ *
83
+ * Idempotent and re-entrant: a second signal that arrives while a shutdown from the first is still
84
+ * in flight is ignored outright (not queued, not a second `stop()` call) — the in-flight shutdown
85
+ * (or, past `timeoutMs`, the forced exit) is left to finish on its own.
86
+ *
87
+ * @param stop - The caller's own graceful-shutdown function, e.g. a `LocalNodeDaemon.stop`.
88
+ * @param options - See {@link GracefulShutdownOptions}.
89
+ * @returns A handle whose `uninstall()` removes the installed listeners.
90
+ * @complexity O(1) to install; the signal handler itself is O(1) plus whatever `stop` costs.
91
+ */
92
+ export function installGracefulShutdown({ stop }, options = {}) {
93
+ const signalProcess = options.process ?? process;
94
+ const timers = options.timers ?? globalThis;
95
+ const logger = options.logger ?? console;
96
+ const signals = options.signals ?? ['SIGTERM', 'SIGINT'];
97
+ const timeoutMs = options.timeoutMs ?? 10_000;
98
+ const onExit = options.onExit ?? ((code) => { signalProcess.exit(code); });
99
+ let shuttingDown = false;
100
+ const handleSignal = (signal) => {
101
+ // A second signal while a shutdown is already in flight must not re-run `stop()` or restart the
102
+ // timeout — the first attempt (or its forced-exit fallback below) already owns getting the
103
+ // process to exit.
104
+ if (shuttingDown)
105
+ return;
106
+ shuttingDown = true;
107
+ let timedOut = false;
108
+ const timer = timers.setTimeout(() => {
109
+ timedOut = true;
110
+ // eslint-disable-next-line no-console
111
+ logger.error(`[@jini-ai/server] graceful shutdown did not complete within ${timeoutMs}ms after ${signal}; forcing exit`);
112
+ onExit(1);
113
+ }, timeoutMs);
114
+ timer.unref?.();
115
+ void stop()
116
+ .catch((error) => {
117
+ // eslint-disable-next-line no-console
118
+ logger.error(`[@jini-ai/server] graceful shutdown failed after ${signal}`, error);
119
+ // Re-thrown so the `.finally` below still distinguishes success from failure via rejection
120
+ // state rather than a second flag.
121
+ throw error;
122
+ })
123
+ .then(() => {
124
+ if (timedOut)
125
+ return;
126
+ timers.clearTimeout(timer);
127
+ onExit(0);
128
+ }, () => {
129
+ if (timedOut)
130
+ return;
131
+ timers.clearTimeout(timer);
132
+ onExit(1);
133
+ });
134
+ };
135
+ for (const signal of signals) {
136
+ signalProcess.on(signal, handleSignal);
137
+ }
138
+ return {
139
+ uninstall() {
140
+ for (const signal of signals) {
141
+ signalProcess.off(signal, handleSignal);
142
+ }
143
+ },
144
+ };
145
+ }
146
+ //# sourceMappingURL=host-bootstrap.js.map
@@ -0,0 +1,156 @@
1
+ /**
2
+ * @module @jini-ai/server
3
+ *
4
+ * The Node.js host preset (extraction-plan.md §2.4): `createLocalNodeDaemon`, the piece that
5
+ * assembles `@jini-ai/core`/`@jini-ai/daemon`/concern-owned storage adapters/`@jini-ai/http-kit` into an actually-runnable
6
+ * daemon process, plus the generic host-lifecycle primitives it's built on. See `archived provenance ledger`
7
+ * for full provenance and scope-decision notes.
8
+
9
+ * Archived provenance rationale:
10
+ * ## Design decisions
11
+ *
12
+ * **1. Two function overloads instead of one generic signature with a defaulted `BoundIds`.** The
13
+ * task brief's literal shown signature was
14
+ * `createLocalNodeDaemon<const Packs, BoundIds extends string = KernelBoundIds>(config: ...)`.
15
+ * Empirically verified against this repo's TypeScript (5.9.3, `strict`) that this shape does not
16
+ * actually preserve `createDaemon`'s compile-time "missing binding" gate: when a type parameter both
17
+ * has a default *and* is referenced inside a conditional type in the same position where it also
18
+ * needs inference from a nested callback's return type, TypeScript resolves it to the default
19
+ * instead of inferring from the callback — silently defeating the gate on exactly the call shape
20
+ * (`bindings` customizer provided) where it matters most. Fixed by splitting into two overloads — one
21
+ * where `bindings` is absent and `BoundIds` is the concrete `KernelBoundIds`, one where `bindings` is
22
+ * required and `BoundIds` is inferred fresh with no default — which sidesteps the inference conflict
23
+ * entirely. Both directions (and an under-binding customizer, and a satisfied customizer) are proven
24
+ * in `create-local-node-daemon.typecheck.ts`. Documented in full inline on the exported function.
25
+ *
26
+ * **2. `resolveBoundPort`/`resolveReportHost` extracted as small pure, exported helpers.** The
27
+ * origin's `.listen()` tail inlined both the "is `server.address()` actually usable" check and the
28
+ * "substitute 127.0.0.1 for an all-interfaces bind host" substitution directly in the `'listening'`
29
+ * callback. Pulling them out makes two genuinely-defensive branches (a `server.address()` that is
30
+ * `null`/a Unix-socket-path string/a non-positive port — provably unreachable via any real TCP
31
+ * listener once `'listening'` has fired, per the origin's own "belt-and-braces" framing) directly
32
+ * unit-testable without mocking Express or the underlying socket at all.
33
+ *
34
+ * **3. `@jini/core/internal`'s `AnyPack`/`RequiredTokenIds`/`MissingTokenIds` re-export.** Needed so
35
+ * this package could re-derive `createDaemon`'s exact compile-time gate rather than duplicate the
36
+ * type-level logic. See `packages/core/src/internal.ts`'s own module doc and
37
+ * `packages/core/src/daemon.ts` — these three types are now `export`ed there (previously
38
+ * module-private) but deliberately *not* re-exported from `@jini/core`'s public `index.ts` (which
39
+ * switched from a `daemon.js` wildcard re-export to an explicit named list for exactly this reason).
40
+ *
41
+ * **4. `createDaemon`'s own compile-time gate is bypassed (via a cast) inside
42
+ * `createLocalNodeDaemon`'s implementation body**, the same way
43
+ * `packages/core/src/__tests__/index.test.ts`'s `createDaemonUnsafe` reaches `createDaemon`'s runtime
44
+ * path directly: `Packs`/`BoundIds` are still abstract, unresolved type parameters inside a generic
45
+ * function body, so `createDaemon`'s own conditional gate can never collapse to a definite branch
46
+ * there regardless of which overload the real call site matched. Safety was already established by
47
+ * this function's own equivalent gate (present on both exported overloads) at the real call site.
48
+ *
49
+ * **5. `stop()` always closes the durable `EventLog`, even when the caller's `onShutdown` hook
50
+ * rejects** — `try { await config.onShutdown?.() } finally { await eventLog.close() }` — so a
51
+ * caller-supplied hook failing can never leak an open sqlite file handle; the original rejection
52
+ * still propagates to whoever awaited `stop()`.
53
+ *
54
+ * **6. `env[JINI_BIND_HOST]` is set before serving any request — a documented, only-partially-fixable
55
+ * wrinkle.** `@jini/http`'s own `guardSameOrigin` (used by `registerDaemonStatusRoutes`' shutdown
56
+ * route) resolves `bindHost` purely from real `process.env.JINI_BIND_HOST`, with **no parameter path**
57
+ * of its own — unlike most of that module's other functions, it never accepts an injected `env`.
58
+ * `createLocalNodeDaemon` sets `env[JINI_BIND_HOST] = host` (where `env` is `config.env ??
59
+ * process.env`) before returning, which correctly fixes the common case (no `env` override — the
60
+ * default, real `process.env` gets the right value). When a caller *does* inject a distinct `env`
61
+ * object for full test isolation, this line cannot make `guardSameOrigin`'s hardwired real-`process.env`
62
+ * read reflect it — a pre-existing `@jini/http` limitation this call cannot reach around without
63
+ * editing `origin.ts` itself (out of scope here, same reasoning as the origin-validation duplication
64
+ * flagged in `packages/http/archived provenance ledger`).
65
+ *
66
+ * ## 2026-07-29 — post-merge audit fixes (six teardown/config/URL defects)
67
+ *
68
+ * Independent review of the `feat/agentic-capability-layer` merge (OpenAI Codex `gpt-5.6-sol` as peer
69
+ * reviewer, then re-verified against source here) surfaced six real defects in this package. Each was
70
+ * reproduced with a failing test before any fix landed.
71
+ *
72
+ * **1. Caller packs were never disposed.** `composeJiniKernel` calls `createDaemon` on `config.packs`,
73
+ * so it — not the caller — builds their services; but neither the failure-cleanup path nor `close()`
74
+ * ever ran their `dispose`. A caller pack whose `services()` opened a socket, timer or database handle
75
+ * leaked it past `createLocalNodeDaemon().stop()`, and the wrapper exposes no caller daemon for the
76
+ * host to tear down itself. Added `JiniKernel.disposeCallerPacks()` — memoized, best-effort, symmetric
77
+ * with `disposeFeatures()` — called by `close()`, by the composition-failure `catch`, and by the
78
+ * daemon's `stop()`. Disposal order is reverse of construction: features first (they were composed
79
+ * against an already-built caller daemon), caller packs second.
80
+ *
81
+ * **2. `journal.db` opened outside the cleanup block.** `createJiniKernelBase` opened `events.db`, then
82
+ * `journal.db`, and only *then* entered the `try` whose `catch` closed them. `journal.db` failing (a
83
+ * corrupt file, or a directory sitting where a database was expected) left the `events.db` handle open
84
+ * in a process that has no kernel. Every acquisition now happens inside the one block, tracked in an
85
+ * `opened` array the cleanup drains — the shape the module's own comment already claimed.
86
+ *
87
+ * **3. Capability keys were not runtime-validated.** Feature ids in `config.features` threw on a typo;
88
+ * capability ids in `config.capabilities` did not. `{'host:exce': false}` deleted a grant nobody held,
89
+ * so `host:exec` survived and `terminal`/`hostTools` stayed mounted — a security switch that fails
90
+ * *open* on a typo, in the direction that reads as applied. `feature.ts` now carries the runtime half
91
+ * of `CapabilityId` as a `Record<CapabilityId, true>` (drift is a compile error in both directions, so
92
+ * the list cannot silently fall behind the union it validates) plus `CAPABILITY_IDS`/`isCapabilityId`;
93
+ * `resolveFeatureActivation` validates the keys next to where it validates feature ids.
94
+ *
95
+ * **4. An injected `config.env` never reached the per-route same-origin guard.** `env[JINI_BIND_HOST] =
96
+ * host` writes into the caller's object when one is supplied, and `@jini-ai/http-kit`'s `guardSameOrigin`
97
+ * read real `process.env`. The origin-guard *middleware* was already handed the injected `env`, so the
98
+ * two halves of one decision read two different environments: the middleware admitted an origin the
99
+ * host configured through `config.env` and the route then rejected it. Fixed at the seam —
100
+ * `OriginContext` (and so `AdapterContext`) grew an optional `env`, defaulting to `process.env`, and
101
+ * this preset sets it. That covers `JINI_BIND_HOST`, `JINI_ALLOWED_ORIGINS` and `JINI_WEB_PORT` alike.
102
+ *
103
+ * **5. Shutdown could skip its own teardown, or crash the process.** `closeHttpServer` rejecting (which
104
+ * its own contract documents) skipped feature disposal, discovery-record removal, `onShutdown` and the
105
+ * sqlite close — leaving a half-torn-down daemon, strictly worse than the failure that caused it. It is
106
+ * a `try`/`finally` now; the original rejection still propagates once teardown finishes. Separately,
107
+ * `requestShutdown` dropped `stop()`'s promise with a bare `void`, so a failing shutdown became an
108
+ * unhandled rejection — which on Node's default policy terminates the process this was gracefully
109
+ * shutting down. It is reported through `console.error` now; the rejection stays on `stopPromise` so an
110
+ * explicit `stop()` caller still observes it.
111
+ *
112
+ * **6. `resolveReportHost` produced an unparseable URL for an IPv6 bind host.** `'::1'` passed through
113
+ * unchanged, so the reported base URL was `http://::1:54321` — which `new URL()` and `fetch` both
114
+ * reject, and which was written verbatim into the discovery record. It now returns the bracketed
115
+ * authority form (RFC 3986 §3.2.2), idempotently.
116
+ *
117
+ * Two lower-severity items from the same review, also fixed:
118
+ *
119
+ * - **`agents`' scan cache was not keyed by promise identity.** A slow scan that failed *after* `POST
120
+ * /api/agents/rescan` had already replaced it with a successful one cleared the newer entry, forcing
121
+ * a duplicate probe of every agent CLI on the machine. The `catch` now clears only its own entry.
122
+ * - **`createFrontendControl`'s bind boundary did not cover `resolveBindToken` or its own error sink.**
123
+ * A `RunStartHandler` throwing is not a no-op — `@jini-ai/http-kit`'s run-start route marks the run
124
+ * `failed` and answers 500 — so a host-supplied `resolveBindToken` throwing (it parses an opaque host
125
+ * blob) produced exactly the killed run the `onBindError` doc promises never to cause. Both are inside
126
+ * the boundary now; a throwing sink is swallowed, because the reporting channel is what failed.
127
+ *
128
+ * **One pre-existing gap closed while here.** The package's committed 100% function-coverage gate was
129
+ * already failing on `main` (99.09%): `sidecar-strict`'s origin-guard `getResolvedPort` closure had no
130
+ * end-to-end coverage, because both of that mode's gates are request-time middleware. Added six real
131
+ * `security: sidecar-strict` tests (unauthenticated 401, authenticated 201, cross-origin 403 with a
132
+ * valid token, unset-token 503, probe routes reachable tokenless, `exemptPaths`) — the one block in
133
+ * `compose-jini-kernel.test.ts` that opens a socket, and only because it has to.
134
+ *
135
+ * **Verified, personally, this session**: `packages/server` **231/231 passing** across 8 files (was
136
+ * 215 before the sidecar-strict block), **100/100/100/100 coverage**; `packages/http-kit` 1245/1245 and
137
+ * 100% ; `packages/chat-core` 261/261; `packages/chat-react` 610/610 and 100%;
138
+ * `examples/reference-web` 41/41. Repo-wide `pnpm typecheck` and `pnpm guard` clean.
139
+ */
140
+ export type { CreateLocalNodeDaemonConfig, KernelBoundIds, LocalNodeDaemon, LocalNodeHttpExtension, LocalNodeHttpExtensionContext, } from './create-local-node-daemon.js';
141
+ export { buildDaemonDbOperations, classifyRunFailureForRetry, createLocalNodeDaemon, projectDetectedAgent, resolveBoundPort, resolveReportHost, } from './create-local-node-daemon.js';
142
+ export type { ComposeJiniKernelConfig, JiniKernel, JiniKernelSecurity } from './compose-jini-kernel.js';
143
+ export { composeJiniKernel, defaultServerMessages } from './compose-jini-kernel.js';
144
+ export type { AnyPack, CapabilityId, FeatureBuildContext, FeatureComposition, FeaturePhase, JiniFeature, JiniProfile, JiniProfileId, ProfileActivation, } from './feature.js';
145
+ export { CAPABILITY_IDS, CORE_CAPABILITIES, defineJiniFeature, isCapabilityId, JINI_PROFILES } from './feature.js';
146
+ export type { ActivationReason, ActiveFeatureRecord, DeactivationReason, FeatureActivationInput, FeatureActivationPlan, InactiveFeatureRecord, } from './feature-activation.js';
147
+ export { resolveFeatureActivation } from './feature-activation.js';
148
+ export type { BuiltInFeatureOptions } from './builtin-features.js';
149
+ export { ANONYMOUS_DELEGATED_PRINCIPAL, createBuiltInFeatures, LOCAL_DAEMON_PRINCIPAL, } from './builtin-features.js';
150
+ export type { CreateJiniKernelBaseOptions, JiniKernelBase, JiniKernelStorage, KernelSqliteAccess, } from './kernel-base.js';
151
+ export { createJiniKernelBase } from './kernel-base.js';
152
+ export { createFrontendControl } from '@jini-ai/daemon/http';
153
+ export type { CreateFrontendControlOptions, FrontendBindErrorContext, FrontendControl, FrontendHttpExtension } from '@jini-ai/daemon/http';
154
+ export type { CloseHttpServerOptions, GracefulShutdownHandle, GracefulShutdownOptions } from './host-bootstrap.js';
155
+ export { DEFAULT_DAEMON_BIND_HOST, closeHttpServer, installGracefulShutdown, normalizeDaemonBindHost, } from './host-bootstrap.js';
156
+ //# sourceMappingURL=index.d.ts.map