@jini-ai/http-kit 0.7.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/active-context.d.ts +99 -0
- package/dist/active-context.js +77 -0
- package/dist/agents.d.ts +64 -0
- package/dist/agents.js +23 -0
- package/dist/attachments.d.ts +534 -0
- package/dist/attachments.js +1032 -0
- package/dist/cancel-owned-runs.d.ts +44 -0
- package/dist/cancel-owned-runs.js +35 -0
- package/dist/component-catalog.d.ts +74 -0
- package/dist/component-catalog.js +74 -0
- package/dist/connectors.d.ts +165 -0
- package/dist/connectors.js +474 -0
- package/dist/daemon-status.d.ts +72 -0
- package/dist/daemon-status.js +60 -0
- package/dist/db-ops.d.ts +116 -0
- package/dist/db-ops.js +191 -0
- package/dist/delegated-tools.d.ts +146 -0
- package/dist/delegated-tools.js +286 -0
- package/dist/frontend-control.d.ts +131 -0
- package/dist/frontend-control.js +77 -0
- package/dist/frontend-sessions.d.ts +100 -0
- package/dist/frontend-sessions.js +180 -0
- package/dist/health.d.ts +91 -0
- package/dist/health.js +53 -0
- package/dist/host-tools.d.ts +174 -0
- package/dist/host-tools.js +338 -0
- package/dist/media.d.ts +131 -0
- package/dist/media.js +352 -0
- package/dist/memory.d.ts +230 -0
- package/dist/memory.js +331 -0
- package/dist/model-proxy.d.ts +45 -0
- package/dist/model-proxy.js +619 -0
- package/dist/origin-validation.d.ts +64 -0
- package/dist/origin-validation.js +226 -0
- package/dist/read-only-tools.d.ts +67 -0
- package/dist/read-only-tools.js +59 -0
- package/dist/remote-run-events.d.ts +66 -0
- package/dist/remote-run-events.js +230 -0
- package/dist/research.d.ts +42 -0
- package/dist/research.js +316 -0
- package/dist/route-manifest.d.ts +31 -0
- package/dist/route-manifest.js +103 -0
- package/dist/routines.d.ts +114 -0
- package/dist/routines.js +320 -0
- package/dist/runs.d.ts +79 -0
- package/dist/runs.js +232 -0
- package/dist/terminals.d.ts +125 -0
- package/dist/terminals.js +349 -0
- package/dist/tool-catalog.d.ts +68 -0
- package/dist/tool-catalog.js +68 -0
- package/dist/workspace-root.d.ts +69 -0
- package/dist/workspace-root.js +63 -0
- package/dist/xai.d.ts +86 -0
- package/dist/xai.js +668 -0
- package/package.json +7 -7
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module delegated-tools
|
|
3
|
+
*
|
|
4
|
+
* `POST /api/delegated-tool-calls` — the daemon-side half of gap 3's MCP-callback continuation
|
|
5
|
+
* transport spike (see `packages/daemon/source-map.md`'s "run/chat orchestration gap 3, part 1"
|
|
6
|
+
* addition and this package's own dated section in `source-map.md`). The swarm-consensus Final
|
|
7
|
+
* Recommendation asked for exactly this round trip: "inject the already-shipped MCP host into
|
|
8
|
+
* one MCP-capable CLI's launch config, prove a tool round-trip through the existing
|
|
9
|
+
* `delegated-tool-bridge.ts`." This route is that round trip's daemon-side half — an MCP server
|
|
10
|
+
* subprocess spawned alongside a `claude` run (`packages/mcp/src/bin/serve.ts`, injected via
|
|
11
|
+
* `packages/daemon/src/agent-executor.ts`'s optional `mcpJsonInjection` config) calls back into
|
|
12
|
+
* the daemon over loopback HTTP (`packages/mcp/src/server/daemon-client.ts`) with
|
|
13
|
+
* `{runId, toolUseId, toolId, input}`; this route decodes that request and calls the
|
|
14
|
+
* already-shipped, already-tested `createDelegatedToolBridge`
|
|
15
|
+
* (`packages/daemon/src/delegated-tool-bridge.ts`), which is the ONLY execution path from here:
|
|
16
|
+
* every injected byte still routes through `ToolExecutor`'s deny-by-default gate — no parallel
|
|
17
|
+
* authorization mechanism is introduced by this route.
|
|
18
|
+
*
|
|
19
|
+
* `resolvePrincipal` is host-owned and has no default (mirrors gap 3's own resolved
|
|
20
|
+
* human-in-the-loop answer — an explicit host-supplied allowlist/policy, never an invented
|
|
21
|
+
* mechanism): whatever `Principal` a host resolves for a given delegated-tool-call request is
|
|
22
|
+
* exactly what flows into `ToolExecutor.execute`'s own `ToolPolicy.authorize`/
|
|
23
|
+
* `ExecutionDelegate` gates. This route does not itself decide who is allowed to do what — it
|
|
24
|
+
* only decides *which run* a request may act against (an unknown or not-yet-started `runId` is
|
|
25
|
+
* rejected with `404` before the bridge is ever invoked, same precedent as `runs.ts`'s
|
|
26
|
+
* `runCancelRoute`).
|
|
27
|
+
*/
|
|
28
|
+
import { randomUUID } from 'node:crypto';
|
|
29
|
+
import { createApiError } from '@jini-ai/protocol';
|
|
30
|
+
import { createDelegatedToolBridge } from '@jini-ai/daemon';
|
|
31
|
+
import { defineJsonRoute, mountJsonRoute } from './adapter.js';
|
|
32
|
+
import { validationError } from './request.js';
|
|
33
|
+
import { err, ok } from './types.js';
|
|
34
|
+
import * as readOnlyTools from './read-only-tools.js';
|
|
35
|
+
/**
|
|
36
|
+
* Refusal text for a `requireReadOnly` call naming a tool that is not registered read-only —
|
|
37
|
+
* including one that is not registered at all, which is the same answer for the same reason
|
|
38
|
+
* (nothing corroborates that it only reads).
|
|
39
|
+
*
|
|
40
|
+
* Names the tool and the remedy, because the caller is a model choosing between two gateways and
|
|
41
|
+
* "denied" alone would leave it guessing which one to try. `describe_tool` already discloses
|
|
42
|
+
* whether an id exists, so distinguishing "unknown" from "writes" here would buy the caller nothing
|
|
43
|
+
* and cost a second message to keep in step.
|
|
44
|
+
*/
|
|
45
|
+
export function readOnlyRefusalMessage(toolId) {
|
|
46
|
+
return readOnlyTools.readOnlyToolRefusalMessage({ toolId, messages: legacyReadOnlyMessages });
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Refusal text for a `requireReadOnly` call this host has no way to check, because it mounted the
|
|
50
|
+
* route without {@link DelegatedToolsHttpDeps.toolRegistry}.
|
|
51
|
+
*
|
|
52
|
+
* Refusing is the only safe answer: the alternative — running the call because the constraint could
|
|
53
|
+
* not be evaluated — would let a write through a caller that annotated itself read-only, which is
|
|
54
|
+
* strictly worse than having no read-only gateway at all. The message names the missing dep so the
|
|
55
|
+
* fix is one line in the host's own wiring rather than an investigation.
|
|
56
|
+
*/
|
|
57
|
+
export const READ_ONLY_UNVERIFIABLE_MESSAGE = 'this host cannot verify read-only tools — POST /api/delegated-tool-calls was mounted without DelegatedToolsHttpDeps.toolRegistry, so a requireReadOnly call cannot be checked and is refused';
|
|
58
|
+
/** Exact existing gateway wording belongs to this compatibility adapter. */
|
|
59
|
+
const legacyReadOnlyMessages = {
|
|
60
|
+
unverifiableMessage: READ_ONLY_UNVERIFIABLE_MESSAGE,
|
|
61
|
+
toolRefusalMessage: ({ toolId }) => `tool "${toolId}" is not registered as read-only — this gateway executes only tools whose registration declares readOnly; call it through execute_delegated_tool instead`,
|
|
62
|
+
};
|
|
63
|
+
/** Compatibility wrapper; new object-shaped API lives at ./read-only-tools. */
|
|
64
|
+
export function constrainPrincipalToReadOnlyTools(principal) {
|
|
65
|
+
return readOnlyTools.constrainPrincipalToReadOnlyTools({ principal });
|
|
66
|
+
}
|
|
67
|
+
/** Compatibility wrapper preserving the existing principal argument. */
|
|
68
|
+
export function principalIsReadOnlyConstrained(principal) {
|
|
69
|
+
return readOnlyTools.principalIsReadOnlyConstrained({ principal });
|
|
70
|
+
}
|
|
71
|
+
/** Compatibility wrapper using the shared fail-closed dispatch decision. */
|
|
72
|
+
export function refuseNonReadOnlyDispatch(options) {
|
|
73
|
+
return readOnlyTools.refuseNonReadOnlyDispatch({ ...options, messages: legacyReadOnlyMessages });
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Compatibility wrapper. Compose innermost, directly around the bare executor,
|
|
77
|
+
* so nested calls by outer decorators still pass through the shared gate.
|
|
78
|
+
*/
|
|
79
|
+
export function withReadOnlyToolConstraint(inner, deps) {
|
|
80
|
+
return readOnlyTools.withReadOnlyToolConstraint({
|
|
81
|
+
inner,
|
|
82
|
+
registry: deps.registry,
|
|
83
|
+
messages: legacyReadOnlyMessages,
|
|
84
|
+
idGenerator: { newId: randomUUID },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/** Route preflight shares the same registration decision as nested dispatch. */
|
|
88
|
+
function checkReadOnlyConstraint(deps, input) {
|
|
89
|
+
if (input.requireReadOnly !== true)
|
|
90
|
+
return null;
|
|
91
|
+
const refusal = readOnlyTools.checkReadOnlyTool({
|
|
92
|
+
toolId: input.toolId, registry: deps.toolRegistry, messages: legacyReadOnlyMessages,
|
|
93
|
+
});
|
|
94
|
+
if (refusal === null)
|
|
95
|
+
return null;
|
|
96
|
+
return createApiError('TOOL_OPERATION_DENIED', refusal);
|
|
97
|
+
}
|
|
98
|
+
/** Logs the real failure server-side and returns the generic, correlation-id-bearing public error (SEC-005: never the raw exception). */
|
|
99
|
+
function defaultInternalErrorSink(context) {
|
|
100
|
+
// eslint-disable-next-line no-console
|
|
101
|
+
console.error(`[@jini-ai/http-kit] internal error (${context.source}, correlationId=${context.correlationId})`, context.error);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The host's {@link DelegatedToolsHttpDeps.describeInternalError} text for `context`, or `undefined`
|
|
105
|
+
* when there is no describer, it declines (`undefined`/`''`), or it throws.
|
|
106
|
+
*
|
|
107
|
+
* @complexity O(1) plus the describer's own cost.
|
|
108
|
+
*/
|
|
109
|
+
function describeSafely(deps, context) {
|
|
110
|
+
if (deps.describeInternalError === undefined)
|
|
111
|
+
return undefined;
|
|
112
|
+
try {
|
|
113
|
+
const text = deps.describeInternalError(context);
|
|
114
|
+
return typeof text === 'string' && text.length > 0 ? text : undefined;
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
// eslint-disable-next-line no-console
|
|
118
|
+
console.error(`[@jini-ai/http-kit] describeInternalError threw (correlationId=${context.correlationId})`, error);
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function reportInternalError(deps, source, error, runId, toolId, status) {
|
|
123
|
+
const correlationId = randomUUID();
|
|
124
|
+
const context = {
|
|
125
|
+
source,
|
|
126
|
+
runId,
|
|
127
|
+
toolId,
|
|
128
|
+
correlationId,
|
|
129
|
+
error,
|
|
130
|
+
...(status === undefined ? {} : { status }),
|
|
131
|
+
};
|
|
132
|
+
const sink = deps.onInternalError ?? defaultInternalErrorSink;
|
|
133
|
+
sink(context);
|
|
134
|
+
const message = describeSafely(deps, context) ?? 'an internal error occurred';
|
|
135
|
+
return createApiError('INTERNAL_ERROR', message, { requestId: correlationId });
|
|
136
|
+
}
|
|
137
|
+
function isRecord(value) {
|
|
138
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
139
|
+
}
|
|
140
|
+
function requireNonEmptyString(body, key) {
|
|
141
|
+
const value = body[key];
|
|
142
|
+
return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
|
|
143
|
+
}
|
|
144
|
+
function parseDelegatedToolExecute(input) {
|
|
145
|
+
if (!isRecord(input.body))
|
|
146
|
+
return err(validationError('body must be a JSON object'));
|
|
147
|
+
const runId = requireNonEmptyString(input.body, 'runId');
|
|
148
|
+
if (runId === undefined) {
|
|
149
|
+
return err(validationError('runId must be a non-empty string', [{ path: 'runId', message: 'required non-empty string' }]));
|
|
150
|
+
}
|
|
151
|
+
const toolUseId = requireNonEmptyString(input.body, 'toolUseId');
|
|
152
|
+
if (toolUseId === undefined) {
|
|
153
|
+
return err(validationError('toolUseId must be a non-empty string', [{ path: 'toolUseId', message: 'required non-empty string' }]));
|
|
154
|
+
}
|
|
155
|
+
const toolId = requireNonEmptyString(input.body, 'toolId');
|
|
156
|
+
if (toolId === undefined) {
|
|
157
|
+
return err(validationError('toolId must be a non-empty string', [{ path: 'toolId', message: 'required non-empty string' }]));
|
|
158
|
+
}
|
|
159
|
+
// Spread-in rather than always-present so an unconstrained body parses to exactly the object it
|
|
160
|
+
// parsed to before this field existed — the existing gateway's request shape is byte-identical,
|
|
161
|
+
// which is what the "additive only" constraint means at the wire.
|
|
162
|
+
//
|
|
163
|
+
// Only a literal `true` arms the constraint. Anything else (absent, `false`, a truthy string) is
|
|
164
|
+
// "unconstrained", never a parse error: this field can only ever TIGHTEN a call, so a malformed
|
|
165
|
+
// value that fell through to the normal gateway is the same outcome as not sending it at all.
|
|
166
|
+
const requireReadOnly = input.body['requireReadOnly'] === true ? { requireReadOnly: true } : {};
|
|
167
|
+
return ok({ runId, toolUseId, toolId, input: input.body.input, ...requireReadOnly });
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Maps a settled `ToolExecutionResult` to the wire `Result` — the same status mapping
|
|
171
|
+
* `db-ops.ts`'s `toolResultToApiResult` establishes for this identical `ToolExecutionResult`
|
|
172
|
+
* union, kept consistent here rather than reinvented: `completed` → `200 {result}`,
|
|
173
|
+
* `denied`/`confirmation-denied` → `403 TOOL_OPERATION_DENIED`, `timed-out`/`cancelled` → a
|
|
174
|
+
* SEC-005-redacted `500 INTERNAL_ERROR` (the real status/error goes to `onInternalError`, never the
|
|
175
|
+
* wire — unless the host supplies `deps.describeInternalError`, whose text then replaces the generic
|
|
176
|
+
* message on every redacted 500 below).
|
|
177
|
+
*
|
|
178
|
+
* `failed` splits in two, on `result.errorKind` (`@jini-ai/daemon`'s `ToolExecutor` sets it from
|
|
179
|
+
* whether the handler threw `@jini-ai/core`'s `ToolInputError`): `'validation'` means the CALLER's
|
|
180
|
+
* input was the problem — a wrong/missing/malformed field name, a `themeId` that doesn't exist, a
|
|
181
|
+
* path escaping its theme — so it is reported as a real `400 BAD_REQUEST` carrying the handler's own
|
|
182
|
+
* actionable message (the same one a model reads to retry correctly), not redacted. Everything else
|
|
183
|
+
* (`'internal'`, or no `errorKind` at all — e.g. an older `ToolExecutor` build) stays the SEC-005
|
|
184
|
+
* redacted 500 path, because a handler that threw for a reason OTHER than "your input was bad" can
|
|
185
|
+
* embed exactly the kind of internal detail that path exists to keep off the wire — unless the host
|
|
186
|
+
* vouches for this exact result via `deps.isModelSafeToolFailure` (it has already redacted the text
|
|
187
|
+
* itself), in which case it is a `422 TOOL_EXECUTION_FAILED` carrying the host's text verbatim.
|
|
188
|
+
*/
|
|
189
|
+
function toolExecutionResultToApiResult(deps, runId, toolId, result) {
|
|
190
|
+
switch (result.status) {
|
|
191
|
+
case 'completed':
|
|
192
|
+
return ok({ result });
|
|
193
|
+
case 'denied':
|
|
194
|
+
return err(createApiError('TOOL_OPERATION_DENIED', 'this operation was denied by policy'));
|
|
195
|
+
case 'confirmation-denied':
|
|
196
|
+
return err(createApiError('TOOL_OPERATION_DENIED', 'this operation was denied during confirmation'));
|
|
197
|
+
case 'timed-out':
|
|
198
|
+
case 'cancelled':
|
|
199
|
+
return err(reportInternalError(deps, 'delegated-tool-execute', result.status, runId, toolId, result.status));
|
|
200
|
+
case 'failed':
|
|
201
|
+
if (result.errorKind === 'validation') {
|
|
202
|
+
return err(createApiError('BAD_REQUEST', result.error ?? 'invalid tool input'));
|
|
203
|
+
}
|
|
204
|
+
if (result.error && deps.isModelSafeToolFailure?.(result) === true) {
|
|
205
|
+
return err(createApiError('TOOL_EXECUTION_FAILED', result.error));
|
|
206
|
+
}
|
|
207
|
+
return err(reportInternalError(deps, 'delegated-tool-execute', result.error ?? result.status, runId, toolId, 'failed'));
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* `POST /api/delegated-tool-calls` — executes one delegated tool call against an already-started
|
|
212
|
+
* run. Maps `ToolExecutionResult.status` to the HTTP response via `toolExecutionResultToApiResult`
|
|
213
|
+
* above — mirroring `db-ops.ts`'s precedent for the identical status union rather than treating
|
|
214
|
+
* every business outcome as a `200`. A genuinely unexpected throw (an unregistered `toolId` — a
|
|
215
|
+
* routing/programming error per `ToolExecutor.execute`'s own contract — or a race where the run
|
|
216
|
+
* became terminal between this route's existence check and the bridge's first emitted event)
|
|
217
|
+
* reaches the same SEC-005 redaction path.
|
|
218
|
+
*/
|
|
219
|
+
export const delegatedToolExecuteRoute = defineJsonRoute({
|
|
220
|
+
method: 'post',
|
|
221
|
+
path: '/api/delegated-tool-calls',
|
|
222
|
+
requireSameOrigin: true,
|
|
223
|
+
parse: parseDelegatedToolExecute,
|
|
224
|
+
handle: async (input, deps, signal) => {
|
|
225
|
+
const run = await deps.lifecycle.get(input.runId);
|
|
226
|
+
if (run === undefined) {
|
|
227
|
+
return err(createApiError('NOT_FOUND', `run "${input.runId}" was not found`));
|
|
228
|
+
}
|
|
229
|
+
// Before `resolvePrincipal`, and long before the bridge: a refused call must cost nothing
|
|
230
|
+
// downstream and must leave no trace of an execution that was never going to happen. It sits
|
|
231
|
+
// after the run-existence check only so that a bad `runId` still answers 404 the way it always
|
|
232
|
+
// did, regardless of the constraint.
|
|
233
|
+
const readOnlyRefusal = checkReadOnlyConstraint(deps, input);
|
|
234
|
+
if (readOnlyRefusal !== null)
|
|
235
|
+
return err(readOnlyRefusal);
|
|
236
|
+
let principal;
|
|
237
|
+
try {
|
|
238
|
+
principal = await deps.resolvePrincipal(input);
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
return err(reportInternalError(deps, 'resolve-principal', error, input.runId, input.toolId));
|
|
242
|
+
}
|
|
243
|
+
// Attenuates the resolved principal itself for a `requireReadOnly` call, so the constraint
|
|
244
|
+
// survives past this route: a consumer's own `ToolExecutor` composition may dispatch a tool id
|
|
245
|
+
// one or more hops past the one checked above (a nested/recovery dispatch using this same
|
|
246
|
+
// principal), and only the principal — not this request's `requireReadOnly` flag, which dies
|
|
247
|
+
// at this function's return — reaches that far. See `constrainPrincipalToReadOnlyTools`'s own
|
|
248
|
+
// doc. A no-op for every existing unconstrained caller.
|
|
249
|
+
if (input.requireReadOnly === true) {
|
|
250
|
+
principal = constrainPrincipalToReadOnlyTools(principal);
|
|
251
|
+
}
|
|
252
|
+
// Composes the SAME enforcement decorator this package exports for a host's own use, here,
|
|
253
|
+
// around whatever `ToolExecutor` the host supplied — a second, independent check of the OUTER
|
|
254
|
+
// `toolId` `checkReadOnlyConstraint` already ran (never a WEAKER outcome than that check, only
|
|
255
|
+
// ever redundant with it; see `withReadOnlyToolConstraint`'s own doc for why this alone cannot
|
|
256
|
+
// close a nested dispatch a host's own inner decorator issues). Skipped entirely for an
|
|
257
|
+
// unconstrained call so the pre-existing gateway's executor reference is untouched.
|
|
258
|
+
const toolExecutor = input.requireReadOnly === true
|
|
259
|
+
? withReadOnlyToolConstraint(deps.toolExecutor, { registry: deps.toolRegistry })
|
|
260
|
+
: deps.toolExecutor;
|
|
261
|
+
const bridge = createDelegatedToolBridge({ lifecycle: deps.lifecycle, toolExecutor });
|
|
262
|
+
try {
|
|
263
|
+
// `signal` carries the caller's HTTP connection dropping — see `mountJsonRoute`
|
|
264
|
+
// (`adapter.ts`). The bridge already combines it with the run's own cancellation
|
|
265
|
+
// (`DelegatedToolInvocation.signal`'s doc); this is the wire that was missing, not new
|
|
266
|
+
// behaviour in the bridge or `ToolExecutor`.
|
|
267
|
+
const result = await bridge.execute({
|
|
268
|
+
runId: input.runId,
|
|
269
|
+
toolUseId: input.toolUseId,
|
|
270
|
+
toolId: input.toolId,
|
|
271
|
+
principal,
|
|
272
|
+
input: input.input,
|
|
273
|
+
...(signal !== undefined ? { signal } : {}),
|
|
274
|
+
});
|
|
275
|
+
return toolExecutionResultToApiResult(deps, input.runId, input.toolId, result);
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
return err(reportInternalError(deps, 'delegated-tool-execute', error, input.runId, input.toolId));
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
});
|
|
282
|
+
/** Mounts `POST /api/delegated-tool-calls` on `app`. A pack's `http(app, services)` calls this directly. */
|
|
283
|
+
export function registerDelegatedToolRoutes(app, deps, adapter) {
|
|
284
|
+
mountJsonRoute(app, delegatedToolExecuteRoute, deps, adapter);
|
|
285
|
+
}
|
|
286
|
+
//# sourceMappingURL=delegated-tools.js.map
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module frontend-control
|
|
3
|
+
*
|
|
4
|
+
* Assembles the three halves of agent-driven frontend control into one thing a host can wire up as
|
|
5
|
+
* a config entry rather than a checklist.
|
|
6
|
+
*
|
|
7
|
+
* The parts already existed and none of them composed: `@jini-ai/daemon`'s `FrontendSessionRegistry`
|
|
8
|
+
* addresses a run to a surface, this package's own frontend-session routes carry invocations to a
|
|
9
|
+
* browser and answers back, and `createFrontendCapabilityRegistrations` projects a manifest into
|
|
10
|
+
* gated tools. A host had to construct all three, keep them consistent, and remember to bind a run
|
|
11
|
+
* when it started. Every one of those is a chance to get it subtly wrong, and one of them —
|
|
12
|
+
* binding — is a security decision.
|
|
13
|
+
*
|
|
14
|
+
* **Moved here from `@jini-ai/server` (2026-07-31).** It never needed that package: its real
|
|
15
|
+
* dependencies are `core`, `daemon`, `express` and this module's own siblings, all of which
|
|
16
|
+
* `http-kit` already has. The only thing pinning it there was a *type-only* import of
|
|
17
|
+
* `LocalNodeHttpExtension` — so a helper any Express host could use sat behind a package that also
|
|
18
|
+
* pulls in `@jini-ai/sidecar` and `better-sqlite3`. The reference implementation hit exactly this
|
|
19
|
+
* and hand-reimplemented the composition instead. `@jini-ai/server` re-exports it, so existing
|
|
20
|
+
* imports keep working.
|
|
21
|
+
*
|
|
22
|
+
* **This facade never returns the registry**, and that is its most important property. The
|
|
23
|
+
* registry's `invoke` executes a capability on a real user's screen with no policy check, no
|
|
24
|
+
* confirmation, no timeout, and no audit record — it is safe only because the sole thing that can
|
|
25
|
+
* reach it is a `ToolHandler` that `ToolExecutor` already gated. Handing a host the registry so it
|
|
26
|
+
* could "wire something custom" would hand it a bypass, and a bypass that exists gets used. The
|
|
27
|
+
* host gets an HTTP extension, a set of registrations, and a bind hook; none of them can execute a
|
|
28
|
+
* capability directly.
|
|
29
|
+
*
|
|
30
|
+
* **The bind token is not a field on the run DTO.** A run is a neutral kernel noun and a browser
|
|
31
|
+
* surface is not; putting `frontendBindToken` on `RunCreateRequest` would push a browser concept
|
|
32
|
+
* into a protocol every consumer shares, to serve one transport. Instead the host supplies
|
|
33
|
+
* {@link CreateFrontendControlOptions.resolveBindToken}, which reads the token out of whatever
|
|
34
|
+
* envelope that host already uses — `contextRef` is an opaque host blob precisely so hosts can put
|
|
35
|
+
* their own metadata in it. The engine stays neutral and the host keeps one place to look.
|
|
36
|
+
*/
|
|
37
|
+
import type { Express } from 'express';
|
|
38
|
+
import type { ToolPolicy, ToolRegistration } from '@jini-ai/core';
|
|
39
|
+
import { type FrontendCapabilitySpec } from '@jini-ai/daemon';
|
|
40
|
+
import type { AdapterContext } from './adapter.js';
|
|
41
|
+
import type { RunCreateRequest, RunStartHandler } from './runs.js';
|
|
42
|
+
/**
|
|
43
|
+
* The context {@link FrontendControl.httpExtension} actually reads — just the adapter.
|
|
44
|
+
*
|
|
45
|
+
* Declared structurally here rather than importing `@jini-ai/server`'s `LocalNodeHttpExtension`,
|
|
46
|
+
* which is what used to keep this module in that package. A function taking this narrower context
|
|
47
|
+
* stays assignable to one taking the wider `{adapter, lifecycle, dataDir}`, so passing the result
|
|
48
|
+
* to `createLocalNodeDaemon`'s `httpExtensions` still typechecks — while a host that builds its own
|
|
49
|
+
* Express app (and so has no `dataDir` or `LocalNodeHttpExtensionContext` to hand over) can now use
|
|
50
|
+
* this facade too, instead of reimplementing it. The reference implementation had to do exactly
|
|
51
|
+
* that.
|
|
52
|
+
*/
|
|
53
|
+
export type FrontendHttpExtension = (app: Express, context: {
|
|
54
|
+
readonly adapter: AdapterContext;
|
|
55
|
+
}) => void;
|
|
56
|
+
export interface FrontendBindErrorContext {
|
|
57
|
+
readonly runId: string;
|
|
58
|
+
readonly error: unknown;
|
|
59
|
+
}
|
|
60
|
+
export interface CreateFrontendControlOptions {
|
|
61
|
+
/**
|
|
62
|
+
* The capabilities to expose. `@jini-ai/agentic`'s `PAGE_CAPABILITIES` and `@jini-ai/chat/core`'s
|
|
63
|
+
* `CHAT_CAPABILITIES` satisfy this structurally — the engine never imports that vocabulary
|
|
64
|
+
* (see `frontend-capability-tools.ts`'s module doc for why the edge points one way).
|
|
65
|
+
*/
|
|
66
|
+
readonly capabilities: readonly FrontendCapabilitySpec[];
|
|
67
|
+
/**
|
|
68
|
+
* Reads this run's bind token out of the host's own run request, or returns `undefined` when the
|
|
69
|
+
* run has no originating surface.
|
|
70
|
+
*
|
|
71
|
+
* Required, and deliberately not defaulted. A default would have to guess where a host keeps the
|
|
72
|
+
* token, and guessing wrong fails *open* in the confusing direction: the run starts, the agent
|
|
73
|
+
* gets its tools, and every page call fails later with "no frontend is bound" — a symptom that
|
|
74
|
+
* looks like a browser problem and is actually a config one.
|
|
75
|
+
*
|
|
76
|
+
* Returning `undefined` is normal, not an error. A run started from a CLI has no surface, and
|
|
77
|
+
* capabilities whose `surface` is `'server'` do not need one.
|
|
78
|
+
*/
|
|
79
|
+
readonly resolveBindToken: (request: RunCreateRequest) => string | undefined;
|
|
80
|
+
/** @default `@jini-ai/daemon`'s `denyAllFrontendCapabilityPolicy` — a host grants access explicitly. */
|
|
81
|
+
readonly policy?: ToolPolicy;
|
|
82
|
+
/** @default `@jini-ai/daemon`'s `DEFAULT_FRONTEND_CAPABILITY_TIMEOUT_MS`. */
|
|
83
|
+
readonly timeoutMs?: number;
|
|
84
|
+
/** Applied to every registration. Frontend output is untrusted page text; bound it. */
|
|
85
|
+
readonly maxOutputBytes?: number;
|
|
86
|
+
/**
|
|
87
|
+
* Host-owned sink for a bind failure. Defaults to `console.error`.
|
|
88
|
+
*
|
|
89
|
+
* A failed bind does not fail the run. The run is still legitimate — the agent simply cannot
|
|
90
|
+
* drive the page, and every capability call it makes will say so by name. Killing a run because
|
|
91
|
+
* one optional channel could not be established would turn a degraded session into no session.
|
|
92
|
+
*/
|
|
93
|
+
readonly onBindError?: (context: FrontendBindErrorContext) => void;
|
|
94
|
+
}
|
|
95
|
+
export interface FrontendControl {
|
|
96
|
+
/**
|
|
97
|
+
* Mounts the frontend-session stream and response routes. Pass in `createLocalNodeDaemon`'s
|
|
98
|
+
* `httpExtensions`, or call it directly with `(app, { adapter })` from a host that owns its own
|
|
99
|
+
* Express app — see {@link FrontendHttpExtension}.
|
|
100
|
+
*/
|
|
101
|
+
readonly httpExtension: FrontendHttpExtension;
|
|
102
|
+
/** One gated tool per capability. Pass in `toolRegistrations`. */
|
|
103
|
+
readonly toolRegistrations: readonly ToolRegistration[];
|
|
104
|
+
/**
|
|
105
|
+
* Binds each starting run to the surface that originated it, and releases the binding when the
|
|
106
|
+
* run reaches a terminal state so a long-lived tab does not accumulate dead bindings.
|
|
107
|
+
*
|
|
108
|
+
* Compose it with whatever the host already does on run start — this hook only binds, it never
|
|
109
|
+
* executes anything:
|
|
110
|
+
*
|
|
111
|
+
* ```ts
|
|
112
|
+
* onRunStarted: (context) => {
|
|
113
|
+
* frontend.bindOnStarted(context);
|
|
114
|
+
* void startMyAgent(context);
|
|
115
|
+
* }
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
readonly bindOnStarted: RunStartHandler;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Builds the frontend-control bundle.
|
|
122
|
+
*
|
|
123
|
+
* @param options - Capabilities to expose, how to find the bind token, and the gate to apply.
|
|
124
|
+
* @returns An HTTP extension, tool registrations, and a run-start bind hook — never the registry.
|
|
125
|
+
* @throws Never at construction. A duplicate capability id throws later, when the registrations are
|
|
126
|
+
* registered, naming the id (`ToolRegistry.register`'s own error).
|
|
127
|
+
*
|
|
128
|
+
* @complexity O(n) in `capabilities`.
|
|
129
|
+
*/
|
|
130
|
+
export declare function createFrontendControl(options: CreateFrontendControlOptions): FrontendControl;
|
|
131
|
+
//# sourceMappingURL=frontend-control.d.ts.map
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createFrontendCapabilityRegistrations, createFrontendSessionRegistry, } from '@jini-ai/daemon';
|
|
2
|
+
import { registerFrontendSessionRoutes } from './frontend-sessions.js';
|
|
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,100 @@
|
|
|
1
|
+
import type { Express, Request, Response } from 'express';
|
|
2
|
+
import type { FrontendSessionRegistry } from '@jini-ai/daemon';
|
|
3
|
+
import { type AdapterContext } from './adapter.js';
|
|
4
|
+
export declare const FRONTEND_SESSION_STREAM_ROUTE_PATH = "/api/frontend-sessions/stream";
|
|
5
|
+
export declare const FRONTEND_SESSION_RESPONSE_ROUTE_PATH = "/api/frontend-sessions/:sessionId/responses";
|
|
6
|
+
/** First event on the stream, telling the surface the id it must answer under. */
|
|
7
|
+
export interface FrontendSessionAttachedEvent {
|
|
8
|
+
readonly type: 'attached';
|
|
9
|
+
readonly sessionId: string;
|
|
10
|
+
/**
|
|
11
|
+
* Secret this surface presents to bind a run to itself. Delivered here and nowhere else: this
|
|
12
|
+
* stream is the one channel already proven to belong to the surface that opened it.
|
|
13
|
+
*
|
|
14
|
+
* Never put this in a URL, a query string, or a log. It is separate from `sessionId` precisely
|
|
15
|
+
* because that id already travels in a request path (`…/:sessionId/responses`) and therefore
|
|
16
|
+
* leaks into access logs and proxies by design — see `@jini-ai/daemon`'s `FrontendSessionHandle`.
|
|
17
|
+
*/
|
|
18
|
+
readonly bindToken: string;
|
|
19
|
+
}
|
|
20
|
+
/** One capability call for the surface to execute. */
|
|
21
|
+
export interface FrontendSessionInvocationEvent {
|
|
22
|
+
readonly type: 'invocation';
|
|
23
|
+
readonly invocationId: string;
|
|
24
|
+
readonly capabilityId: string;
|
|
25
|
+
readonly input: Record<string, unknown>;
|
|
26
|
+
}
|
|
27
|
+
/** Sent instead of `attached` when the request itself was unusable; the stream then closes. */
|
|
28
|
+
export interface FrontendSessionErrorEvent {
|
|
29
|
+
readonly type: 'error';
|
|
30
|
+
readonly message: string;
|
|
31
|
+
}
|
|
32
|
+
export type FrontendSessionStreamEvent = FrontendSessionAttachedEvent | FrontendSessionInvocationEvent | FrontendSessionErrorEvent;
|
|
33
|
+
/**
|
|
34
|
+
* A surface's answer, as a discriminated union rather than a flat record with two optional fields.
|
|
35
|
+
*
|
|
36
|
+
* The parser already refuses a failure with no message, so `message?: string` alongside
|
|
37
|
+
* `ok: boolean` would let the type describe a state the parser guarantees cannot exist — and force
|
|
38
|
+
* a `?? 'no message'` fallback at the use site that no input could ever reach. Encoding the
|
|
39
|
+
* guarantee here removes the branch instead of leaving it to be covered by a test that would have
|
|
40
|
+
* to fabricate an impossible input.
|
|
41
|
+
*/
|
|
42
|
+
export type FrontendSessionResponseRequest = {
|
|
43
|
+
readonly sessionId: string;
|
|
44
|
+
readonly invocationId: string;
|
|
45
|
+
readonly ok: true;
|
|
46
|
+
readonly output?: unknown;
|
|
47
|
+
} | {
|
|
48
|
+
readonly sessionId: string;
|
|
49
|
+
readonly invocationId: string;
|
|
50
|
+
readonly ok: false;
|
|
51
|
+
readonly message: string;
|
|
52
|
+
};
|
|
53
|
+
export interface FrontendSessionResponseBody {
|
|
54
|
+
/** `false` when the invocation was unknown or already settled — a duplicate answer, not an error. */
|
|
55
|
+
readonly settled: boolean;
|
|
56
|
+
}
|
|
57
|
+
export interface FrontendSessionsHttpDeps {
|
|
58
|
+
readonly registry: FrontendSessionRegistry;
|
|
59
|
+
/**
|
|
60
|
+
* Mints session ids. Defaults to `randomUUID`. A surface never supplies its own: an id the
|
|
61
|
+
* caller chose could collide with, or deliberately impersonate, a session already attached.
|
|
62
|
+
*/
|
|
63
|
+
readonly newSessionId?: () => string;
|
|
64
|
+
/** Host-owned sink for failures that must not escape an async Express handler. Defaults to `console.error`. */
|
|
65
|
+
readonly onInternalError?: (context: {
|
|
66
|
+
readonly source: string;
|
|
67
|
+
readonly error: unknown;
|
|
68
|
+
}) => void;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Reads the repeatable `?capability=` query parameter.
|
|
72
|
+
*
|
|
73
|
+
* Express gives a single value as a string and repeats as an array; anything else (a nested object
|
|
74
|
+
* from a bracketed query string) is rejected rather than coerced.
|
|
75
|
+
*/
|
|
76
|
+
export declare function parseCapabilityQuery(raw: unknown): readonly string[] | null;
|
|
77
|
+
/**
|
|
78
|
+
* Handles one surface's stream from open to close.
|
|
79
|
+
*
|
|
80
|
+
* SSE commits `text/event-stream` headers before anything else can be known, so a bad request is
|
|
81
|
+
* reported as one `{type:'error'}` data event and then closed — there is no status-code channel
|
|
82
|
+
* left. Same precedent as `run-stream.ts`.
|
|
83
|
+
*/
|
|
84
|
+
export declare function handleFrontendSessionStream(req: Request, res: Response, deps: FrontendSessionsHttpDeps): void;
|
|
85
|
+
/**
|
|
86
|
+
* `POST /api/frontend-sessions/:sessionId/responses` — delivers a surface's answer to the tool
|
|
87
|
+
* handler awaiting it. Always `200`; `{settled:false}` reports a duplicate or unknown answer,
|
|
88
|
+
* which is an expected outcome rather than a transport error.
|
|
89
|
+
*/
|
|
90
|
+
export declare const frontendSessionResponseRoute: import("./types.js").JsonRouteSpec<FrontendSessionResponseRequest, FrontendSessionResponseBody, FrontendSessionsHttpDeps>;
|
|
91
|
+
/**
|
|
92
|
+
* Mounts both frontend-session routes on `app`.
|
|
93
|
+
*
|
|
94
|
+
* The stream route bypasses `mountJsonRoute` (raw `app.get`, for the SSE response shape), so it
|
|
95
|
+
* does not get `requireSameOrigin` for free the way `frontendSessionResponseRoute` does — the
|
|
96
|
+
* guard is applied here directly, before the SSE channel is opened, so a cross-origin request
|
|
97
|
+
* never gets a stream (and, notably, never mints a session id or `bindToken` either).
|
|
98
|
+
*/
|
|
99
|
+
export declare function registerFrontendSessionRoutes(app: Express, deps: FrontendSessionsHttpDeps, adapter: AdapterContext): void;
|
|
100
|
+
//# sourceMappingURL=frontend-sessions.d.ts.map
|