@jini-ai/http-kit 0.7.2 → 0.7.3-next.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 (124) hide show
  1. package/CHANGELOG.md +2 -10
  2. package/README.md +6 -6
  3. package/dist/adapter.d.ts +7 -50
  4. package/dist/adapter.js +12 -54
  5. package/dist/api-security-middleware.d.ts +0 -16
  6. package/dist/api-security-middleware.js +2 -18
  7. package/dist/index.d.ts +10 -15
  8. package/dist/index.js +7 -10
  9. package/dist/internal-error.d.ts +42 -0
  10. package/dist/internal-error.js +48 -0
  11. package/dist/local-daemon-request.d.ts +11 -4
  12. package/dist/local-daemon-request.js +1 -28
  13. package/dist/middleware.d.ts +1 -0
  14. package/dist/middleware.js +1 -0
  15. package/dist/node-bridge.d.ts +108 -0
  16. package/dist/node-bridge.js +356 -0
  17. package/dist/observability.d.ts +3 -14
  18. package/dist/origin.d.ts +13 -30
  19. package/dist/origin.js +13 -13
  20. package/dist/range.d.ts +53 -0
  21. package/dist/range.js +93 -0
  22. package/dist/rate-limit.d.ts +1 -13
  23. package/dist/rate-limit.js +5 -2
  24. package/dist/request.d.ts +2 -13
  25. package/dist/request.js +0 -13
  26. package/dist/response.d.ts +8 -7
  27. package/dist/response.js +0 -36
  28. package/dist/route-registration-guard.d.ts +14 -0
  29. package/dist/route-registration-guard.js +17 -0
  30. package/dist/run-credentials.d.ts +73 -0
  31. package/dist/run-credentials.js +71 -0
  32. package/dist/settings/contracts.d.ts +49 -0
  33. package/dist/settings/contracts.js +2 -0
  34. package/dist/settings/http-request.d.ts +36 -0
  35. package/dist/settings/http-request.js +50 -0
  36. package/dist/settings/http.d.ts +10 -0
  37. package/dist/settings/http.js +216 -0
  38. package/dist/settings/index.d.ts +4 -0
  39. package/dist/settings/index.js +3 -0
  40. package/dist/settings/shared.d.ts +16 -0
  41. package/dist/settings/shared.js +16 -0
  42. package/dist/settings/stream.d.ts +25 -0
  43. package/dist/settings/stream.js +180 -0
  44. package/dist/sse.d.ts +1 -15
  45. package/dist/sse.js +77 -72
  46. package/dist/trust-proxy.d.ts +36 -0
  47. package/dist/trust-proxy.js +45 -0
  48. package/dist/types.d.ts +4 -52
  49. package/dist/types.js +1 -4
  50. package/package.json +24 -14
  51. package/dist/active-context.d.ts +0 -99
  52. package/dist/active-context.js +0 -77
  53. package/dist/agents.d.ts +0 -64
  54. package/dist/agents.js +0 -23
  55. package/dist/attachments.d.ts +0 -534
  56. package/dist/attachments.js +0 -1032
  57. package/dist/cancel-owned-runs.d.ts +0 -44
  58. package/dist/cancel-owned-runs.js +0 -35
  59. package/dist/component-catalog.d.ts +0 -74
  60. package/dist/component-catalog.js +0 -74
  61. package/dist/connectors.d.ts +0 -165
  62. package/dist/connectors.js +0 -474
  63. package/dist/daemon-status.d.ts +0 -72
  64. package/dist/daemon-status.js +0 -60
  65. package/dist/db-ops.d.ts +0 -116
  66. package/dist/db-ops.js +0 -191
  67. package/dist/delegated-tools.d.ts +0 -146
  68. package/dist/delegated-tools.js +0 -286
  69. package/dist/frontend-control.d.ts +0 -131
  70. package/dist/frontend-control.js +0 -77
  71. package/dist/frontend-sessions.d.ts +0 -100
  72. package/dist/frontend-sessions.js +0 -180
  73. package/dist/health.d.ts +0 -91
  74. package/dist/health.js +0 -53
  75. package/dist/host-tools.d.ts +0 -174
  76. package/dist/host-tools.js +0 -338
  77. package/dist/media.d.ts +0 -131
  78. package/dist/media.js +0 -352
  79. package/dist/memory.d.ts +0 -230
  80. package/dist/memory.js +0 -331
  81. package/dist/model-proxy.d.ts +0 -45
  82. package/dist/model-proxy.js +0 -619
  83. package/dist/origin-validation.d.ts +0 -64
  84. package/dist/origin-validation.js +0 -226
  85. package/dist/raw-sse.d.ts +0 -49
  86. package/dist/raw-sse.js +0 -92
  87. package/dist/read-only-tools.d.ts +0 -67
  88. package/dist/read-only-tools.js +0 -59
  89. package/dist/remote-run-events.d.ts +0 -66
  90. package/dist/remote-run-events.js +0 -230
  91. package/dist/research.d.ts +0 -42
  92. package/dist/research.js +0 -316
  93. package/dist/route-manifest.d.ts +0 -31
  94. package/dist/route-manifest.js +0 -103
  95. package/dist/routines.d.ts +0 -114
  96. package/dist/routines.js +0 -320
  97. package/dist/runs.d.ts +0 -79
  98. package/dist/runs.js +0 -232
  99. package/dist/terminals.d.ts +0 -125
  100. package/dist/terminals.js +0 -349
  101. package/dist/tool-catalog.d.ts +0 -68
  102. package/dist/tool-catalog.js +0 -68
  103. package/dist/verified-origin/configured-origin.d.ts +0 -37
  104. package/dist/verified-origin/configured-origin.js +0 -99
  105. package/dist/verified-origin/index.d.ts +0 -7
  106. package/dist/verified-origin/index.js +0 -6
  107. package/dist/verified-origin/loopback-host.d.ts +0 -9
  108. package/dist/verified-origin/loopback-host.js +0 -17
  109. package/dist/verified-origin/origin.d.ts +0 -64
  110. package/dist/verified-origin/origin.js +0 -162
  111. package/dist/verified-origin/ports.d.ts +0 -38
  112. package/dist/verified-origin/ports.js +0 -2
  113. package/dist/verified-origin/repo.memory.d.ts +0 -32
  114. package/dist/verified-origin/repo.memory.js +0 -34
  115. package/dist/verified-origin/site-path.d.ts +0 -113
  116. package/dist/verified-origin/site-path.js +0 -188
  117. package/dist/verified-origin/types.d.ts +0 -33
  118. package/dist/verified-origin/types.js +0 -30
  119. package/dist/verified-origin.d.ts +0 -2
  120. package/dist/verified-origin.js +0 -2
  121. package/dist/workspace-root.d.ts +0 -69
  122. package/dist/workspace-root.js +0 -63
  123. package/dist/xai.d.ts +0 -86
  124. package/dist/xai.js +0 -668
package/dist/terminals.js DELETED
@@ -1,349 +0,0 @@
1
- /**
2
- * @module terminals
3
- *
4
- * Interactive-terminal HTTP surface, mirroring OD's
5
- * `apps/daemon/src/routes/terminal.ts` (`/api/projects/:id/terminals` +
6
- * `.../:tid/{stream,stdin,resize,kill}`) generalized under `/api/terminals`.
7
- * See `ADS-memory/reports/proposals/PROP-http-route-packs-terminal-pty-2026-07-21.md`
8
- * for the design discussion and `@jini-ai/daemon`'s `terminal-session.ts` module
9
- * doc for the session-ownership/gating decisions this route pack calls into.
10
- *
11
- * This file is deliberately thin — no PTY spawning, no session registry, no
12
- * ownership logic lives here (that is `@jini-ai/daemon`'s `TerminalSessionManager`,
13
- * injected as `deps.manager`). This package only:
14
- *
15
- * - Resolves a `POST /api/terminals` request's `resourceRef` to a spawn `cwd`
16
- * via `workspace-root.ts` (the same port `host-tools.ts`'s open-in route
17
- * uses), then routes creation through `deps.toolExecutor.execute(...,
18
- * 'terminal.create', ...)` — the one call `@jini-ai/daemon`'s module gates by
19
- * policy (matching `db-ops.ts`'s tool-execution-boundary precedent).
20
- * - Routes `stdin`/`resize`/`kill`/`stream` directly to `deps.manager`'s
21
- * lighter, session-ownership-checked methods — deliberately **not** through
22
- * `ToolExecutor` again (see the daemon module's doc for why a full
23
- * authorize/confirm round-trip per keystroke would make a terminal
24
- * unusable).
25
- * - Adapts `deps.manager.attach`'s push/end sink to `sse.ts`'s generic SSE
26
- * channel, the same way `runs.ts` adapts `RunLifecycle.stream`.
27
- */
28
- import { randomUUID } from 'node:crypto';
29
- import { TERMINAL_CREATE_TOOL_ID } from '@jini-ai/daemon';
30
- import { createApiError } from '@jini-ai/protocol';
31
- import { defineJsonRoute, mountJsonRoute } from './adapter.js';
32
- import { guardSameOrigin } from './origin.js';
33
- import { validationError } from './request.js';
34
- import { sendApiError, statusForError } from './response.js';
35
- import { createSseChannel, requestedAfterCursor } from './sse.js';
36
- import { denyAllWorkspaceRoots, resolveWorkspaceRoot, WorkspaceRootDeniedError } from './workspace-root.js';
37
- import { err, ok } from './types.js';
38
- function defaultTerminalsInternalErrorSink(context) {
39
- // eslint-disable-next-line no-console
40
- console.error(`[@jini-ai/http-kit] internal error (${context.source}, correlationId=${context.correlationId})`, context.error);
41
- }
42
- function isRecord(value) {
43
- return typeof value === 'object' && value !== null && !Array.isArray(value);
44
- }
45
- /** Every one-off `terminal.create` tool call gets its own opaque `RunRef` — matching `db-ops.ts`'s `freshRun()`: these are single requests, not steps of a longer-lived agent run. */
46
- function freshRun() {
47
- return { id: randomUUID() };
48
- }
49
- function toolResultToApiResult(deps, result) {
50
- switch (result.status) {
51
- case 'completed':
52
- return ok(result.output);
53
- case 'denied':
54
- return err(createApiError('TOOL_OPERATION_DENIED', 'this operation was denied by policy'));
55
- case 'confirmation-denied':
56
- return err(createApiError('TOOL_OPERATION_DENIED', 'this operation was denied during confirmation'));
57
- case 'timed-out':
58
- case 'cancelled':
59
- case 'failed': {
60
- const correlationId = randomUUID();
61
- const sink = deps.onInternalError ?? defaultTerminalsInternalErrorSink;
62
- sink({ source: 'terminal-create', correlationId, error: result.status === 'failed' ? result.error : result.status });
63
- return err(createApiError('INTERNAL_ERROR', 'an internal error occurred', { requestId: correlationId }));
64
- }
65
- }
66
- }
67
- function parseTerminalCreate(input) {
68
- if (!isRecord(input.body))
69
- return err(validationError('body must be a JSON object'));
70
- const resourceRef = input.body.resourceRef;
71
- if (typeof resourceRef !== 'string' || resourceRef.length === 0) {
72
- return err(validationError('resourceRef is required', [{ path: 'resourceRef', message: 'required non-empty string' }]));
73
- }
74
- const detail = input.body.detail;
75
- if (detail !== undefined && (typeof detail !== 'string' || detail.length === 0)) {
76
- return err(validationError('detail must be a non-empty string when provided'));
77
- }
78
- const cols = input.body.cols;
79
- if (cols !== undefined && typeof cols !== 'number') {
80
- return err(validationError('cols must be a number when provided'));
81
- }
82
- const rows = input.body.rows;
83
- if (rows !== undefined && typeof rows !== 'number') {
84
- return err(validationError('rows must be a number when provided'));
85
- }
86
- const shell = input.body.shell;
87
- if (shell !== undefined && (typeof shell !== 'string' || shell.length === 0)) {
88
- return err(validationError('shell must be a non-empty string when provided'));
89
- }
90
- return ok({
91
- resourceRef,
92
- ...(detail === undefined ? {} : { detail }),
93
- ...(cols === undefined ? {} : { cols }),
94
- ...(rows === undefined ? {} : { rows }),
95
- ...(shell === undefined ? {} : { shell }),
96
- });
97
- }
98
- /**
99
- * `POST /api/terminals` — the one gated call (see module doc). Resolves
100
- * `resourceRef` to a working directory the same way `host-tools.ts`'s
101
- * open-in route does, then authorizes+spawns the session through
102
- * `ToolExecutor.execute(..., 'terminal.create', ...)`.
103
- */
104
- export const terminalCreateRoute = defineJsonRoute({
105
- method: 'post',
106
- path: '/api/terminals',
107
- requireSameOrigin: true,
108
- parse: parseTerminalCreate,
109
- handle: async (input, deps) => {
110
- let cwd;
111
- try {
112
- cwd = await resolveWorkspaceRoot({ resourceRef: input.resourceRef, ...(input.detail === undefined ? {} : { detail: input.detail }) }, { resolver: deps.resolveRoot ?? denyAllWorkspaceRoots });
113
- }
114
- catch (error) {
115
- if (error instanceof WorkspaceRootDeniedError) {
116
- return err(createApiError('NOT_FOUND', `resource "${input.resourceRef}" was not found`));
117
- }
118
- throw error;
119
- }
120
- const toolInput = {
121
- resourceRef: input.resourceRef,
122
- cwd,
123
- ...(input.cols === undefined ? {} : { cols: input.cols }),
124
- ...(input.rows === undefined ? {} : { rows: input.rows }),
125
- ...(input.shell === undefined ? {} : { shell: input.shell }),
126
- };
127
- const result = await deps.toolExecutor.execute(deps.principal, freshRun(), TERMINAL_CREATE_TOOL_ID, toolInput);
128
- return toolResultToApiResult(deps, result);
129
- },
130
- successStatus: 201,
131
- });
132
- function parseTerminalList(input) {
133
- const value = input.query.resourceRef;
134
- if (value === undefined)
135
- return ok({});
136
- if (typeof value !== 'string' || value.length === 0) {
137
- return err(validationError('resourceRef must be a non-empty string when provided'));
138
- }
139
- return ok({ resourceRef: value });
140
- }
141
- /** `GET /api/terminals` — sessions the calling principal owns, optionally narrowed by `resourceRef`. Never gated through `ToolExecutor` — a read scoped to the caller's own sessions, matching `runs.ts`'s `runListRoute` precedent. */
142
- export const terminalListRoute = defineJsonRoute({
143
- method: 'get',
144
- path: '/api/terminals',
145
- parse: parseTerminalList,
146
- handle: (input, deps) => ok({ terminals: deps.manager.list(deps.principal, input.resourceRef === undefined ? {} : { resourceRef: input.resourceRef }) }),
147
- });
148
- function parseTerminalId(input) {
149
- const id = input.params.id;
150
- return typeof id === 'string' && id.length > 0 ? ok(id) : err(validationError('id must be a non-empty path parameter'));
151
- }
152
- /**
153
- * Exported (not just internal) so the `result.session === null` branch — a real race
154
- * (`write`/`resize`/`kill` finding metadata for an id whose underlying session was concurrently
155
- * killed between the ownership check and the critical section, per `@jini-ai/daemon`'s
156
- * `terminal-session.ts` `currentSnapshot`) — is directly unit-testable against a synthetic
157
- * `TerminalSessionActionResult` rather than requiring a real, hard-to-deterministically-force race
158
- * through the full `TerminalSessionManager`. Matches this file's own `createDeferredEndGate`
159
- * precedent for the same "extract into a directly-testable pure function" shape.
160
- */
161
- export function actionResultToApiResult(result, notFoundMessage) {
162
- if (result.status === 'not-found')
163
- return err(createApiError('NOT_FOUND', notFoundMessage));
164
- return ok({ ok: result.ok, ...(result.session ? { terminal: result.session } : {}) });
165
- }
166
- function parseStdinInput(input) {
167
- const parsedId = parseTerminalId(input);
168
- if (!parsedId.ok)
169
- return parsedId;
170
- if (!isRecord(input.body))
171
- return err(validationError('body must be a JSON object'));
172
- const data = input.body.data;
173
- if (typeof data !== 'string') {
174
- return err(validationError('data (string) is required', [{ path: 'data', message: 'required string' }]));
175
- }
176
- return ok({ id: parsedId.value, data });
177
- }
178
- /** `POST /api/terminals/:id/stdin` — writes `data` to the session's pty. Ownership-checked by `deps.manager.write` directly, not re-gated through `ToolExecutor` (see module doc). */
179
- export const terminalStdinRoute = defineJsonRoute({
180
- method: 'post',
181
- path: '/api/terminals/:id/stdin',
182
- requireSameOrigin: true,
183
- parse: parseStdinInput,
184
- handle: async (input, deps) => {
185
- const result = await deps.manager.write(deps.principal, input.id, input.data);
186
- return actionResultToApiResult(result, `terminal "${input.id}" was not found`);
187
- },
188
- });
189
- function parseResizeInput(input) {
190
- const parsedId = parseTerminalId(input);
191
- if (!parsedId.ok)
192
- return parsedId;
193
- if (!isRecord(input.body))
194
- return err(validationError('body must be a JSON object'));
195
- const cols = Number(input.body.cols);
196
- const rows = Number(input.body.rows);
197
- if (!Number.isFinite(cols) || !Number.isFinite(rows)) {
198
- return err(validationError('cols and rows (numbers) are required'));
199
- }
200
- return ok({ id: parsedId.value, cols, rows });
201
- }
202
- /** `POST /api/terminals/:id/resize` — resizes the session's pty. */
203
- export const terminalResizeRoute = defineJsonRoute({
204
- method: 'post',
205
- path: '/api/terminals/:id/resize',
206
- requireSameOrigin: true,
207
- parse: parseResizeInput,
208
- handle: async (input, deps) => {
209
- const result = await deps.manager.resize(deps.principal, input.id, input.cols, input.rows);
210
- return actionResultToApiResult(result, `terminal "${input.id}" was not found`);
211
- },
212
- });
213
- function handleKill(id, deps) {
214
- return deps.manager.kill(deps.principal, id, 'SIGTERM').then((result) => actionResultToApiResult(result, `terminal "${id}" was not found`));
215
- }
216
- /** `POST /api/terminals/:id/kill` — sends `SIGTERM` to the session's pty. */
217
- export const terminalKillRoute = defineJsonRoute({
218
- method: 'post',
219
- path: '/api/terminals/:id/kill',
220
- requireSameOrigin: true,
221
- parse: parseTerminalId,
222
- handle: (id, deps) => handleKill(id, deps),
223
- });
224
- /** `DELETE /api/terminals/:id` — alias for `kill`, matching OD's dual `POST .../kill` / `DELETE` routes. */
225
- export const terminalDeleteRoute = defineJsonRoute({
226
- method: 'delete',
227
- path: '/api/terminals/:id',
228
- requireSameOrigin: true,
229
- parse: parseTerminalId,
230
- handle: (id, deps) => handleKill(id, deps),
231
- });
232
- /**
233
- * The `channelOpened`/`endRequestedBeforeOpen` state machine `registerTerminalEventStream`'s
234
- * `TerminalSseSink.end()` needs, extracted into its own directly-testable unit — see that
235
- * function's inline comment for *why* the deferral exists (an already-exited session's replay
236
- * path can call `end()` before `open()` has ever run).
237
- *
238
- * **On the `markOpened()`-then-`end()` ordering (opened=true when `end()` runs):** this is the
239
- * ordering every *currently reachable* production call graph in this repo takes for a live
240
- * session that exits while already streaming — but it is unreachable through that graph, not
241
- * unreachable in principle. `@jini-ai/platform`'s `TerminalService.finish()` (`packages/platform/src/
242
- * terminal.ts`) calls `sink.send('exit', ...)` immediately before `sink.end()` for every live
243
- * client; `send()` here forwards straight to `channel.enqueue()`, whose `isEndEvent: (e) => e.kind
244
- * === 'exit'` match auto-closes the channel *synchronously inside that same `enqueue()` call* —
245
- * which synchronously runs `registerTerminalEventStream`'s own `channel.onClose` callback, which
246
- * detaches this sink from `TerminalService`'s `session.clients` before `finish()`'s own, separate
247
- * `sink.end()` loop ever runs. That loop iterates `session.clients` fresh at call time (not a
248
- * snapshot taken before `emit()`), so by the time it runs, this sink has already removed itself —
249
- * `sink.end()` is consequently never invoked while `channelOpened` is `true` via any call graph
250
- * this repo's own `@jini-ai/platform` + `@jini-ai/http-kit` composition can currently produce (confirmed by
251
- * instrumenting the real call path directly, not inferred from reading the source — a synchronous
252
- * console probe in `end()` never fired across this file's full "live-exit-while-streaming" test).
253
- * That is a fact about today's specific `TerminalService`/`SseChannel` wiring, not a proof that no
254
- * future caller of `TerminalSseSink` could ever call `end()` post-open (a hypothetical non-SSE
255
- * sink, or a future `TerminalService` exit reason not preceded by a matching `send()`, would hit
256
- * exactly this branch) — so the branch stays as real, intentional defensive code, tested directly
257
- * here rather than deleted for being unreachable *today* or left silently uncovered.
258
- */
259
- export function createDeferredEndGate(channel) {
260
- let opened = false;
261
- let endRequestedBeforeOpen = false;
262
- return {
263
- markOpened() {
264
- opened = true;
265
- // Idempotent-safe even if the queued 'exit' event already auto-closed the channel via
266
- // `isEndEvent` during `open()`'s own drain (`channel.end()` is documented safe to call twice).
267
- if (endRequestedBeforeOpen)
268
- channel.end();
269
- },
270
- end() {
271
- if (opened) {
272
- channel.end();
273
- }
274
- else {
275
- endRequestedBeforeOpen = true;
276
- }
277
- },
278
- };
279
- }
280
- /**
281
- * `GET /api/terminals/:id/stream` — SSE, with `Last-Event-ID`/`afterCursor`
282
- * reconnect replay (via `sse.ts`'s `requestedAfterCursor`, the same helper
283
- * `runs.ts` uses). Adapts `deps.manager.attach`'s push/end
284
- * `TerminalSseSink` to `sse.ts`'s generic channel, mirroring
285
- * `registerRunEventStream`'s adaptation of `RunLifecycle.stream`.
286
- *
287
- * Bypasses `mountJsonRoute` (raw `app.get`, for the SSE response shape), so it does not get
288
- * `requireSameOrigin` for free the way the JSON routes above do — the guard is applied here
289
- * directly, before the SSE channel is opened, so a cross-origin request never gets a stream.
290
- */
291
- export function registerTerminalEventStream(app, deps, adapter) {
292
- app.get('/api/terminals/:id/stream', (req, res) => {
293
- const origin = guardSameOrigin(req, adapter);
294
- if (!origin.ok) {
295
- sendApiError(res, statusForError(origin.error), origin.error);
296
- return;
297
- }
298
- const id = req.params.id;
299
- if (typeof id !== 'string' || id.length === 0) {
300
- sendApiError(res, 400, createApiError('BAD_REQUEST', 'id must be a non-empty path parameter'));
301
- return;
302
- }
303
- const cursor = requestedAfterCursor(req);
304
- const lastEventId = cursor === null ? 0 : Number(cursor);
305
- const channel = createSseChannel(res, { isEndEvent: (event) => event.kind === 'exit' });
306
- // `deps.manager.attach` can call `sink.end()` synchronously, from inside the very call below
307
- // (an already-exited session's replay path) — before the channel has ever been `open()`ed. If
308
- // `end()` mapped straight to `channel.end()`, that would end the response with the queued
309
- // backlog never flushed (headers never even sent). `createDeferredEndGate` defers the actual
310
- // `channel.end()` call until after `open()` has drained whatever `send()` already queued — see
311
- // that function's own doc for the full reachability analysis of its other branch.
312
- const deferredEnd = createDeferredEndGate(channel);
313
- const sink = {
314
- send(event, data, eventId) {
315
- channel.enqueue({ opaqueCursor: String(eventId), kind: event, data });
316
- },
317
- end() {
318
- deferredEnd.end();
319
- },
320
- };
321
- let attachedSink = null;
322
- channel.onClose(() => {
323
- if (attachedSink)
324
- deps.manager.detach(id, attachedSink);
325
- });
326
- const result = deps.manager.attach(deps.principal, id, lastEventId, sink);
327
- if (result === 'not-found') {
328
- channel.abandon();
329
- sendApiError(res, 404, createApiError('NOT_FOUND', `terminal "${id}" was not found`));
330
- return;
331
- }
332
- if (result === 'attached') {
333
- attachedSink = sink;
334
- }
335
- channel.open();
336
- deferredEnd.markOpened();
337
- });
338
- }
339
- /** Mounts every terminal route (`list`/`create`/`stdin`/`resize`/`kill`/`delete`/`stream`) on `app`. A pack's `http(app, services)` calls this directly. */
340
- export function registerTerminalRoutes(app, deps, adapter) {
341
- mountJsonRoute(app, terminalListRoute, deps, adapter);
342
- mountJsonRoute(app, terminalCreateRoute, deps, adapter);
343
- mountJsonRoute(app, terminalStdinRoute, deps, adapter);
344
- mountJsonRoute(app, terminalResizeRoute, deps, adapter);
345
- mountJsonRoute(app, terminalKillRoute, deps, adapter);
346
- mountJsonRoute(app, terminalDeleteRoute, deps, adapter);
347
- registerTerminalEventStream(app, deps, adapter);
348
- }
349
- //# sourceMappingURL=terminals.js.map
@@ -1,68 +0,0 @@
1
- /**
2
- * @module tool-catalog
3
- *
4
- * `GET /api/tools/search` / `GET /api/tools/:id` — the discovery half of
5
- * `ai-control-plane.md` §29 / `PROP-tool-catalog-discovery-2026-07-26.md` §6.1's staged verbs
6
- * (`search_tools`/`describe_tool`), v0 scope: no principal scoping, no versioning, no schema
7
- * narrowing. `@jini-ai/mcp`'s `search_tools`/`describe_tool` tool defs proxy these two routes,
8
- * exactly mirroring how `run-tools.ts`'s tools proxy `runs.ts`.
9
- *
10
- * This module does not depend on `@jini-ai/sqlite-chat` or `better-sqlite3` — `ToolCatalogQuery` is a
11
- * plain injected interface, structurally compatible with `@jini-ai/sqlite-chat`'s
12
- * `searchToolCatalog`/`getToolCatalogEntry` so a caller wires those in with zero adapter code,
13
- * matching `db-ops.ts`'s established convention.
14
- *
15
- * **Deliberately not routed through `ToolExecutor`.** Unlike `db-ops.ts`'s three tools, nothing
16
- * here executes a handler or has a side effect — it is a read over a snapshot table. `PROP` §6.3:
17
- * "discovery is not permission... the catalog is never consulted for authorization." The actual
18
- * gate is still `ToolExecutor`, reached only via `execute_delegated_tool`
19
- * (`packages/daemon/src/delegated-tool-bridge.ts`) — finding a tool id here grants nothing.
20
- */
21
- import type { Express } from 'express';
22
- import { type AdapterContext } from './adapter.js';
23
- export interface ToolCatalogSearchHit {
24
- readonly id: string;
25
- readonly description: string;
26
- readonly source: string;
27
- readonly score: number;
28
- }
29
- export interface ToolCatalogEntry {
30
- readonly id: string;
31
- readonly description: string;
32
- readonly inputSchema?: unknown;
33
- readonly source: string;
34
- }
35
- /** Structurally identical to `@jini-ai/sqlite-chat`'s `searchToolCatalog`/`getToolCatalogEntry` — defined locally so this package incurs no `better-sqlite3` dependency. */
36
- export interface ToolCatalogQuery {
37
- readonly search: (query: string, limit?: number) => readonly ToolCatalogSearchHit[];
38
- readonly describe: (id: string) => ToolCatalogEntry | null;
39
- }
40
- export interface ToolCatalogHttpDeps {
41
- readonly catalog: ToolCatalogQuery;
42
- }
43
- /** `GET /api/tools/search?q=...&limit=...` — ranked candidates only, never schemas (`PROP` §6.1). */
44
- export declare const toolCatalogSearchRoute: import("./types.js").JsonRouteSpec<{
45
- query: string;
46
- limit: number;
47
- }, {
48
- hits: readonly ToolCatalogSearchHit[];
49
- }, ToolCatalogHttpDeps>;
50
- /**
51
- * `GET /api/tools/:id` — full descriptor (schema included), paid for only once a candidate survives
52
- * search.
53
- *
54
- * An unknown tool id is **404 `NOT_FOUND`**, not 400. A well-formed request naming a catalog entry
55
- * that does not exist is a missing resource, not a malformed request — and the three sibling route
56
- * families in this package that have the same "the referenced thing isn't there" case
57
- * (`memory.ts`'s `memory not found`, `routines.ts`'s `routine not found`, `media.ts`'s
58
- * `media task not found`) all already answer 404. This route answered 400 until 2026-07-29 purely
59
- * because it reached for `validationError` — the same helper its `parse` step uses, where 400 *is*
60
- * correct — so a caller could not distinguish "you sent a bad request" from "that tool is gone".
61
- * `parse` failures here (a missing `:id` segment) are still 400.
62
- */
63
- export declare const toolCatalogDescribeRoute: import("./types.js").JsonRouteSpec<{
64
- id: string;
65
- }, ToolCatalogEntry, ToolCatalogHttpDeps>;
66
- /** Mounts both tool-catalog routes on `app`. A pack's `http(app, services)` calls this directly. */
67
- export declare function registerToolCatalogRoutes(app: Express, deps: ToolCatalogHttpDeps, adapter: AdapterContext): void;
68
- //# sourceMappingURL=tool-catalog.d.ts.map
@@ -1,68 +0,0 @@
1
- import { createApiError } from '@jini-ai/protocol';
2
- import { defineJsonRoute, mountJsonRoute } from './adapter.js';
3
- import { validationError } from './request.js';
4
- import { err, ok } from './types.js';
5
- const MAX_SEARCH_LIMIT = 25;
6
- const DEFAULT_SEARCH_LIMIT = 10;
7
- function parseSearchInput(input) {
8
- const rawQuery = input.query.q;
9
- if (typeof rawQuery !== 'string' || rawQuery.trim().length === 0) {
10
- return err(validationError('q (search query) is required and must be a non-empty string'));
11
- }
12
- const rawLimit = input.query.limit;
13
- if (rawLimit === undefined)
14
- return ok({ query: rawQuery, limit: DEFAULT_SEARCH_LIMIT });
15
- if (typeof rawLimit !== 'string' || !/^[0-9]+$/.test(rawLimit)) {
16
- return err(validationError('limit must be a single positive-integer query-string value when provided'));
17
- }
18
- const parsed = Number(rawLimit);
19
- if (parsed < 1)
20
- return err(validationError('limit must be at least 1'));
21
- return ok({ query: rawQuery, limit: Math.min(parsed, MAX_SEARCH_LIMIT) });
22
- }
23
- /** `GET /api/tools/search?q=...&limit=...` — ranked candidates only, never schemas (`PROP` §6.1). */
24
- export const toolCatalogSearchRoute = defineJsonRoute({
25
- method: 'get',
26
- path: '/api/tools/search',
27
- requireSameOrigin: true,
28
- parse: parseSearchInput,
29
- handle: (input, deps) => ok({ hits: deps.catalog.search(input.query, input.limit) }),
30
- });
31
- function parseDescribeInput(input) {
32
- const id = input.params.id;
33
- if (typeof id !== 'string' || id.length === 0) {
34
- return err(validationError('id path segment is required'));
35
- }
36
- return ok({ id });
37
- }
38
- /**
39
- * `GET /api/tools/:id` — full descriptor (schema included), paid for only once a candidate survives
40
- * search.
41
- *
42
- * An unknown tool id is **404 `NOT_FOUND`**, not 400. A well-formed request naming a catalog entry
43
- * that does not exist is a missing resource, not a malformed request — and the three sibling route
44
- * families in this package that have the same "the referenced thing isn't there" case
45
- * (`memory.ts`'s `memory not found`, `routines.ts`'s `routine not found`, `media.ts`'s
46
- * `media task not found`) all already answer 404. This route answered 400 until 2026-07-29 purely
47
- * because it reached for `validationError` — the same helper its `parse` step uses, where 400 *is*
48
- * correct — so a caller could not distinguish "you sent a bad request" from "that tool is gone".
49
- * `parse` failures here (a missing `:id` segment) are still 400.
50
- */
51
- export const toolCatalogDescribeRoute = defineJsonRoute({
52
- method: 'get',
53
- path: '/api/tools/:id',
54
- requireSameOrigin: true,
55
- parse: parseDescribeInput,
56
- handle: (input, deps) => {
57
- const entry = deps.catalog.describe(input.id);
58
- if (!entry)
59
- return err(createApiError('NOT_FOUND', `no catalog entry for tool id "${input.id}"`));
60
- return ok(entry);
61
- },
62
- });
63
- /** Mounts both tool-catalog routes on `app`. A pack's `http(app, services)` calls this directly. */
64
- export function registerToolCatalogRoutes(app, deps, adapter) {
65
- mountJsonRoute(app, toolCatalogSearchRoute, deps, adapter);
66
- mountJsonRoute(app, toolCatalogDescribeRoute, deps, adapter);
67
- }
68
- //# sourceMappingURL=tool-catalog.js.map
@@ -1,37 +0,0 @@
1
- import { type VerifiedOrigin } from "./types.js";
2
- /** Operator declaration is evidence of configured trust, not DNS or ownership proof. */
3
- export interface ConfiguredOriginRequired {
4
- env: Readonly<Record<string, string | undefined>>;
5
- envVarName: string;
6
- clock: {
7
- nowIso(): string;
8
- };
9
- warn: (message: string) => void;
10
- }
11
- /** Accept a caller-named operator declaration or return undefined with a refusal warning.
12
- * No ambient environment lookup. The injected clock stamps accepted evidence only.
13
- * @complexity O(configured URL length) time/space; no network or storage effects.
14
- * @example resolveConfiguredOrigin({ env, envVarName: "APP_PUBLIC_URL", clock, warn });
15
- */
16
- export declare function resolveConfiguredOrigin(required: ConfiguredOriginRequired): VerifiedOrigin | undefined;
17
- export type OriginBootPlan = {
18
- kind: "configured";
19
- origin: VerifiedOrigin;
20
- } | {
21
- kind: "dev-seed";
22
- } | {
23
- kind: "none";
24
- };
25
- export interface OriginBootRequired extends ConfiguredOriginRequired {
26
- /** The host decides whether this runtime may seed a development capability. */
27
- allowDevSeed: () => boolean;
28
- missingOriginWarning: string;
29
- }
30
- /** Pure boot decision; registration effects and runtime selection stay in the host. */
31
- /** Choose configured evidence, an allowed development seed, or no registration.
32
- * Warnings use caller-supplied policy; registration effects remain host-owned.
33
- * @complexity O(configured URL length) time/space.
34
- * @example planOriginBoot({ env, envVarName, clock, warn, allowDevSeed, missingOriginWarning });
35
- */
36
- export declare function planOriginBoot(required: OriginBootRequired): OriginBootPlan;
37
- //# sourceMappingURL=configured-origin.d.ts.map
@@ -1,99 +0,0 @@
1
- import { trimCharsEnd } from '@jini-ai/core/primitives';
2
- import { hasForbiddenRawUrlCharacter } from "./origin.js";
3
- import { createVerifiedOrigin } from "./types.js";
4
- import { isLoopbackHost } from "./loopback-host.js";
5
- // Match candidate-origin normalization so a trailing DNS dot has one meaning across decisions.
6
- function normalizeHost(hostname) {
7
- const lowered = hostname.toLowerCase();
8
- return lowered.endsWith(".") ? lowered.slice(0, -1) : lowered;
9
- }
10
- // Reject ambiguous raw characters before parsing can erase them; use the redirect predicate
11
- // rather than introducing a second URL acceptance rule.
12
- function parseConfiguredUrl(raw) {
13
- if (hasForbiddenRawUrlCharacter({ raw }))
14
- return null;
15
- try {
16
- return new URL(raw);
17
- }
18
- catch {
19
- return null;
20
- }
21
- }
22
- // Workspace-setting evidence permits HTTPS only. Refuse HTTP before constructing evidence so
23
- // an invalid operator setting cannot make origin construction throw during boot.
24
- function refusalReason(url) {
25
- if (url.protocol !== "https:")
26
- return "its scheme must be https";
27
- if (url.username !== "" || url.password !== "")
28
- return "it carries a userinfo component";
29
- if (url.search !== "" || url.hash !== "")
30
- return "it carries a query string or fragment";
31
- const host = normalizeHost(url.hostname);
32
- if (host === "")
33
- return "its host is empty";
34
- if (isLoopbackHost({ host }))
35
- return `'${host}' is a loopback host, not a public origin`;
36
- return null;
37
- }
38
- // Omit absent port/basePath keys entirely: explicit undefined differs from an omitted optional
39
- // property under strict equality, and storage adapters preserve that distinction.
40
- function buildConfiguredOrigin(url, now) {
41
- const candidate = {
42
- scheme: "https",
43
- host: normalizeHost(url.hostname),
44
- verifiedAt: now,
45
- source: "workspace-setting",
46
- };
47
- if (url.port !== "")
48
- candidate.port = Number(url.port);
49
- const basePath = trimCharsEnd({ text: url.pathname, chars: "/" });
50
- if (basePath !== "")
51
- candidate.basePath = basePath;
52
- return createVerifiedOrigin(candidate);
53
- }
54
- // Environment authority already controls deployed code; accepting an operator declaration adds
55
- // no request-derived authority. Never feed a request-host fallback into this durable trust root.
56
- // Malformed values leave no evidence, with one diagnostic warning; unset/blank local settings stay
57
- // quiet. Use the host's boot clock so this evidence and other boot rows carry the same timestamp.
58
- /** Accept a caller-named operator declaration or return undefined with a refusal warning.
59
- * No ambient environment lookup. The injected clock stamps accepted evidence only.
60
- * @complexity O(configured URL length) time/space; no network or storage effects.
61
- * @example resolveConfiguredOrigin({ env, envVarName: "APP_PUBLIC_URL", clock, warn });
62
- */
63
- export function resolveConfiguredOrigin(required) {
64
- const { env, envVarName, clock, warn } = required;
65
- const raw = env[envVarName]?.trim();
66
- if (!raw)
67
- return undefined;
68
- const refuse = (reason) => {
69
- warn(`${envVarName} is set but was refused as this deployment's public origin (${reason}); ` +
70
- `no origin was registered from it. Value: ${raw}`);
71
- return undefined;
72
- };
73
- const url = parseConfiguredUrl(raw);
74
- if (!url)
75
- return refuse("it is not a parseable URL");
76
- const reason = refusalReason(url);
77
- if (reason)
78
- return refuse(reason);
79
- return buildConfiguredOrigin(url, clock.nowIso());
80
- }
81
- // A disallowed development seed must produce no registration: persisting localhost in a public
82
- // deployment poisons generated links, and find-or-create storage can preserve the row forever.
83
- // Avoiding new seeds does not repair old rows; registering accepted configured evidence does.
84
- /** Pure boot decision; registration effects and runtime selection stay in the host. */
85
- /** Choose configured evidence, an allowed development seed, or no registration.
86
- * Warnings use caller-supplied policy; registration effects remain host-owned.
87
- * @complexity O(configured URL length) time/space.
88
- * @example planOriginBoot({ env, envVarName, clock, warn, allowDevSeed, missingOriginWarning });
89
- */
90
- export function planOriginBoot(required) {
91
- const origin = resolveConfiguredOrigin(required);
92
- if (origin)
93
- return { kind: "configured", origin };
94
- if (required.allowDevSeed())
95
- return { kind: "dev-seed" };
96
- required.warn(required.missingOriginWarning);
97
- return { kind: "none" };
98
- }
99
- //# sourceMappingURL=configured-origin.js.map
@@ -1,7 +0,0 @@
1
- export { type OriginScheme, type OriginSource, type VerifiedOrigin, InsecureOriginSourceError, OriginNotVerifiedError, createVerifiedOrigin, } from "./types.js";
2
- export type { VerifiedOriginRequestContext, RedirectTargetContext, EgressTargetContext, OriginRegistryPort, OriginSettingRepoPort, } from "./ports.js";
3
- export { OriginRegistry, hasForbiddenRawUrlCharacter, isSameOrigin, normalizeOriginCandidate, type NormalizedTarget, type OriginRegistryDeps, } from "./origin.js";
4
- export { InMemoryOriginSettingRepo, type OriginSettingSeed } from "./repo.memory.js";
5
- export { planOriginBoot, resolveConfiguredOrigin, type ConfiguredOriginRequired, type OriginBootRequired, type OriginBootPlan, } from "./configured-origin.js";
6
- export { hasControlCharacter, checkSitePathname, checkSiteRelativeTarget, type SitePathCheck, type SiteRelativeTargetCheck, } from "./site-path.js";
7
- //# sourceMappingURL=index.d.ts.map
@@ -1,6 +0,0 @@
1
- export { InsecureOriginSourceError, OriginNotVerifiedError, createVerifiedOrigin, } from "./types.js";
2
- export { OriginRegistry, hasForbiddenRawUrlCharacter, isSameOrigin, normalizeOriginCandidate, } from "./origin.js";
3
- export { InMemoryOriginSettingRepo } from "./repo.memory.js";
4
- export { planOriginBoot, resolveConfiguredOrigin, } from "./configured-origin.js";
5
- export { hasControlCharacter, checkSitePathname, checkSiteRelativeTarget, } from "./site-path.js";
6
- //# sourceMappingURL=index.js.map
@@ -1,9 +0,0 @@
1
- /** Public identity must not name a development listener. Normalize URL spellings first so
2
- * shortened IPv4 and IPv4-mapped IPv6 cannot bypass the same rule used for localhost.
3
- * Private intranet hosts remain valid. Invalid hosts are left to the caller's URL validation.
4
- * @complexity O(host bytes), pure; parse failures return false.
5
- */
6
- export declare function isLoopbackHost({ host }: {
7
- host: string;
8
- }, _options?: {}): boolean;
9
- //# sourceMappingURL=loopback-host.d.ts.map