@jini-ai/http-kit 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/adapter.js +56 -47
  3. package/dist/local-daemon-request.js +11 -5
  4. package/dist/observability.d.ts +18 -0
  5. package/dist/observability.js +19 -0
  6. package/dist/verified-origin/site-path.js +5 -1
  7. package/package.json +7 -7
  8. package/dist/active-context.d.ts +0 -99
  9. package/dist/active-context.js +0 -77
  10. package/dist/agents.d.ts +0 -64
  11. package/dist/agents.js +0 -23
  12. package/dist/attachments.d.ts +0 -534
  13. package/dist/attachments.js +0 -1032
  14. package/dist/cancel-owned-runs.d.ts +0 -44
  15. package/dist/cancel-owned-runs.js +0 -35
  16. package/dist/component-catalog.d.ts +0 -74
  17. package/dist/component-catalog.js +0 -74
  18. package/dist/connectors.d.ts +0 -165
  19. package/dist/connectors.js +0 -474
  20. package/dist/daemon-status.d.ts +0 -72
  21. package/dist/daemon-status.js +0 -60
  22. package/dist/db-ops.d.ts +0 -116
  23. package/dist/db-ops.js +0 -191
  24. package/dist/delegated-tools.d.ts +0 -146
  25. package/dist/delegated-tools.js +0 -286
  26. package/dist/frontend-control.d.ts +0 -131
  27. package/dist/frontend-control.js +0 -77
  28. package/dist/frontend-sessions.d.ts +0 -100
  29. package/dist/frontend-sessions.js +0 -180
  30. package/dist/health.d.ts +0 -91
  31. package/dist/health.js +0 -53
  32. package/dist/host-tools.d.ts +0 -174
  33. package/dist/host-tools.js +0 -338
  34. package/dist/media.d.ts +0 -131
  35. package/dist/media.js +0 -352
  36. package/dist/memory.d.ts +0 -230
  37. package/dist/memory.js +0 -331
  38. package/dist/model-proxy.d.ts +0 -45
  39. package/dist/model-proxy.js +0 -619
  40. package/dist/origin-validation.d.ts +0 -64
  41. package/dist/origin-validation.js +0 -226
  42. package/dist/read-only-tools.d.ts +0 -67
  43. package/dist/read-only-tools.js +0 -59
  44. package/dist/remote-run-events.d.ts +0 -66
  45. package/dist/remote-run-events.js +0 -230
  46. package/dist/research.d.ts +0 -42
  47. package/dist/research.js +0 -316
  48. package/dist/route-manifest.d.ts +0 -31
  49. package/dist/route-manifest.js +0 -103
  50. package/dist/routines.d.ts +0 -114
  51. package/dist/routines.js +0 -320
  52. package/dist/runs.d.ts +0 -79
  53. package/dist/runs.js +0 -232
  54. package/dist/terminals.d.ts +0 -125
  55. package/dist/terminals.js +0 -349
  56. package/dist/tool-catalog.d.ts +0 -68
  57. package/dist/tool-catalog.js +0 -68
  58. package/dist/workspace-root.d.ts +0 -69
  59. package/dist/workspace-root.js +0 -63
  60. package/dist/xai.d.ts +0 -86
  61. package/dist/xai.js +0 -668
@@ -1,180 +0,0 @@
1
- /**
2
- * @module frontend-sessions
3
- *
4
- * The transport half of `@jini-ai/daemon`'s `FrontendSessionRegistry`: how a browser surface reaches
5
- * the daemon, and how the daemon reaches back into it.
6
- *
7
- * Two routes, because the connection *is* the session:
8
- *
9
- * - `GET /api/frontend-sessions/stream` opens an SSE channel. The daemon mints the session id,
10
- * attaches the surface, sends `{type:'attached', sessionId}` as the first event, and pushes one
11
- * `{type:'invocation', ...}` per capability call. When the connection closes for any reason —
12
- * navigation, a crashed tab, a pulled network cable — the surface is detached and every
13
- * invocation still awaiting it is failed.
14
- * - `POST /api/frontend-sessions/:sessionId/responses` carries the surface's answer back.
15
- *
16
- * There is deliberately **no separate register/unregister pair**. A surface whose lifetime is a
17
- * `POST` to create and a `DELETE` to destroy leaks a session every time a tab dies without running
18
- * its unload handler, and those leaked sessions keep claiming capabilities they can no longer
19
- * serve. Tying the lifetime to the stream makes the failure mode impossible instead of unlikely.
20
- *
21
- * **The response route does not execute anything.** It settles a promise that a `ToolHandler` is
22
- * already awaiting, so the call it answers has already passed `ToolExecutor`'s authorization,
23
- * confirmation, timeout, cancellation, truncation, and audit. An answer for an unknown or
24
- * already-settled invocation is reported as `{settled:false}` rather than being an error: a stream
25
- * reconnect or a retried POST is expected, not exceptional.
26
- *
27
- * Binding a run to a session is NOT exposed here. Which surface owns a run is a decision only the
28
- * composition root can make (it is the thing that starts runs), so it calls `registry.bindRun`
29
- * directly — see `@jini-ai/daemon`'s own module doc for why attach and bind are separate.
30
- */
31
- import { randomUUID } from 'node:crypto';
32
- import { createApiError } from '@jini-ai/protocol';
33
- import { defineJsonRoute, mountJsonRoute } from './adapter.js';
34
- import { guardSameOrigin } from './origin.js';
35
- import { createSseResponse } from './raw-sse.js';
36
- import { validationError } from './request.js';
37
- import { sendApiError, statusForError } from './response.js';
38
- import { err, ok } from './types.js';
39
- export const FRONTEND_SESSION_STREAM_ROUTE_PATH = '/api/frontend-sessions/stream';
40
- export const FRONTEND_SESSION_RESPONSE_ROUTE_PATH = '/api/frontend-sessions/:sessionId/responses';
41
- function reportInternalError(deps, source, error) {
42
- try {
43
- if (deps.onInternalError)
44
- deps.onInternalError({ source, error });
45
- // eslint-disable-next-line no-console
46
- else
47
- console.error(`[@jini-ai/http-kit] internal error (frontend-sessions:${source})`, error);
48
- }
49
- catch (sinkError) {
50
- // A diagnostic sink must never turn a contained failure into an unhandled rejection of its own.
51
- // eslint-disable-next-line no-console
52
- console.error(`[@jini-ai/http-kit] internal error sink failed (frontend-sessions:${source})`, sinkError);
53
- }
54
- }
55
- /**
56
- * Reads the repeatable `?capability=` query parameter.
57
- *
58
- * Express gives a single value as a string and repeats as an array; anything else (a nested object
59
- * from a bracketed query string) is rejected rather than coerced.
60
- */
61
- export function parseCapabilityQuery(raw) {
62
- const values = raw === undefined ? [] : (Array.isArray(raw) ? raw : [raw]);
63
- const capabilities = [];
64
- for (const value of values) {
65
- if (typeof value !== 'string' || value.trim().length === 0)
66
- return null;
67
- capabilities.push(value);
68
- }
69
- return capabilities;
70
- }
71
- /**
72
- * Handles one surface's stream from open to close.
73
- *
74
- * SSE commits `text/event-stream` headers before anything else can be known, so a bad request is
75
- * reported as one `{type:'error'}` data event and then closed — there is no status-code channel
76
- * left. Same precedent as `run-stream.ts`.
77
- */
78
- export function handleFrontendSessionStream(req, res, deps) {
79
- const capabilities = parseCapabilityQuery(req.query['capability']);
80
- // Assigned below, after the connection exists — `attach` needs something to deliver through, and
81
- // `onClose` has to be armed before then so a connection that dies during setup still detaches.
82
- let handle;
83
- const connection = createSseResponse(req, res, {
84
- // Detach on close rather than on an explicit teardown call: this fires for a closed tab and a
85
- // dropped connection too, which an unregister route would not.
86
- onClose: () => handle?.detach(),
87
- });
88
- if (capabilities === null) {
89
- connection.send({
90
- type: 'error',
91
- message: 'each "capability" query parameter must be a non-empty string',
92
- });
93
- connection.close();
94
- return;
95
- }
96
- const sessionId = (deps.newSessionId ?? randomUUID)();
97
- handle = deps.registry.attach({ sessionId, capabilities }, (invocation) => connection.send({ type: 'invocation', ...invocation }));
98
- connection.send({
99
- type: 'attached',
100
- sessionId,
101
- bindToken: handle.bindToken,
102
- });
103
- }
104
- function isRecord(value) {
105
- return typeof value === 'object' && value !== null && !Array.isArray(value);
106
- }
107
- function parseFrontendSessionResponse(input) {
108
- const sessionId = input.params['sessionId'];
109
- if (typeof sessionId !== 'string' || sessionId.length === 0) {
110
- return err(validationError('sessionId must be a non-empty string', [{ path: 'sessionId', message: 'required non-empty string' }]));
111
- }
112
- if (!isRecord(input.body))
113
- return err(validationError('body must be a JSON object'));
114
- const invocationId = input.body['invocationId'];
115
- if (typeof invocationId !== 'string' || invocationId.trim().length === 0) {
116
- return err(validationError('invocationId must be a non-empty string', [{ path: 'invocationId', message: 'required non-empty string' }]));
117
- }
118
- const okFlag = input.body['ok'];
119
- if (typeof okFlag !== 'boolean') {
120
- return err(validationError('ok must be a boolean', [{ path: 'ok', message: 'required boolean' }]));
121
- }
122
- if (!okFlag) {
123
- const message = input.body['message'];
124
- if (typeof message !== 'string' || message.trim().length === 0) {
125
- // A failure with no reason gives the agent nothing to act on, which is how a caller ends up
126
- // retrying the same refusal forever.
127
- return err(validationError('message must be a non-empty string when ok is false', [{ path: 'message', message: 'required when ok is false' }]));
128
- }
129
- return ok({ sessionId, invocationId, ok: false, message });
130
- }
131
- return ok({ sessionId, invocationId, ok: true, output: input.body['output'] });
132
- }
133
- /**
134
- * `POST /api/frontend-sessions/:sessionId/responses` — delivers a surface's answer to the tool
135
- * handler awaiting it. Always `200`; `{settled:false}` reports a duplicate or unknown answer,
136
- * which is an expected outcome rather than a transport error.
137
- */
138
- export const frontendSessionResponseRoute = defineJsonRoute({
139
- method: 'post',
140
- path: FRONTEND_SESSION_RESPONSE_ROUTE_PATH,
141
- requireSameOrigin: true,
142
- parse: parseFrontendSessionResponse,
143
- handle: (input, deps) => {
144
- const settled = deps.registry.settle(input.sessionId, input.invocationId, input.ok
145
- ? { ok: true, output: input.output }
146
- : { ok: false, message: input.message });
147
- return ok({ settled });
148
- },
149
- });
150
- /**
151
- * Mounts both frontend-session routes on `app`.
152
- *
153
- * The stream route bypasses `mountJsonRoute` (raw `app.get`, for the SSE response shape), so it
154
- * does not get `requireSameOrigin` for free the way `frontendSessionResponseRoute` does — the
155
- * guard is applied here directly, before the SSE channel is opened, so a cross-origin request
156
- * never gets a stream (and, notably, never mints a session id or `bindToken` either).
157
- */
158
- export function registerFrontendSessionRoutes(app, deps, adapter) {
159
- app.get(FRONTEND_SESSION_STREAM_ROUTE_PATH, (req, res) => {
160
- const origin = guardSameOrigin(req, adapter);
161
- if (!origin.ok) {
162
- sendApiError(res, statusForError(origin.error), origin.error);
163
- return;
164
- }
165
- try {
166
- handleFrontendSessionStream(req, res, deps);
167
- }
168
- catch (error) {
169
- reportInternalError(deps, 'stream', error);
170
- if (!res.headersSent) {
171
- res.status(500).json({ error: createApiError('INTERNAL_ERROR', 'an internal error occurred') });
172
- }
173
- else if (!res.writableEnded) {
174
- res.end();
175
- }
176
- }
177
- });
178
- mountJsonRoute(app, frontendSessionResponseRoute, deps, adapter);
179
- }
180
- //# sourceMappingURL=frontend-sessions.js.map
package/dist/health.d.ts DELETED
@@ -1,91 +0,0 @@
1
- /**
2
- * @module health
3
- *
4
- * `GET /health`, `GET /api/health` (plain liveness — always `200 {ok: true, version}` once the
5
- * process is up, no dependency checks), `GET /ready`, `GET /api/ready` (real readiness —
6
- * delegates to an injected `checkReadiness`, `503` when it reports `ok: false`), and `GET
7
- * /version`, `GET /api/version` (echoes the running build's version). Both the mount-relative
8
- * and `/api`-prefixed form of each probe are registered because `api-security-middleware.ts`'s
9
- * `OPEN_PROBE_PATHS` already anticipated exactly these six paths as always-open (no bearer token,
10
- * no origin check) — this module is what finally makes that anticipated set of paths real routes
11
- * instead of an open gate over nothing.
12
- *
13
- * **Mount before `express.json()`/the bearer-auth/origin-guard middleware** (see
14
- * `@jini-ai/server`'s `create-local-node-daemon.ts` wiring): these are simple parameterless GETs
15
- * with no request body, so nothing here needs JSON body-parsing, and a monitoring probe should
16
- * never need a bearer token or same-origin `Origin` header just to confirm the process is up —
17
- * the same reasoning `api-security-middleware.ts`'s own doc already gives for exempting these
18
- * paths.
19
- *
20
- * **`daemon-status.ts#daemonStatusRoute`'s own doc previously called `GET /api/daemon/status` "a
21
- * health-check" — this module is the real, purpose-built answer to that now.** `/api/daemon/status`
22
- * still exists and still reports version/host/port/data-dir/shutdown state (useful operator
23
- * detail), but a liveness/readiness monitor should poll `/health`/`/ready` instead: those are
24
- * unauthenticated by design (see above), `/api/daemon/status` is not gated same-origin either
25
- * today, but was never *documented* as the liveness contract — see that module's updated doc
26
- * comment.
27
- *
28
- * **OD-parity, verified live 2026-07-22** by booting a real Open Design daemon (`apps/daemon/bin/
29
- * od.mjs --no-open`, from a full clone of `nexu-io/open-design`) and curling its real
30
- * `/api/health`, `/api/ready`, `/api/version` handlers (`apps/daemon/src/server.ts:2624-2642`).
31
- * Live responses observed: `GET /api/health` → `200 {"ok":true,"version":"0.15.1"}`; `GET
32
- * /api/ready` → `200 {"ok":true,"ready":true,"version":"0.15.1"}` (the handler's readiness check
33
- * is a single `!daemonShuttingDown` boolean, not a pluggable checks map — `server.ts:2629-2637`);
34
- * `GET /api/version` → `200 {"version":{"version":"0.15.1","channel":"development",
35
- * "packaged":false,"platform":"darwin","arch":"x64"}}` (the full `AppVersionInfo` shape from
36
- * `app-version.ts:12-18`, nested under the `version` key — not a bare string). Confirmed OD
37
- * registers no bare (non-`/api`-prefixed) `/health`/`/ready`/`/version` routes at all (`GET
38
- * /health` 404s live) — this module's mount-relative variants are a deliberate Jini generalization
39
- * for hosts that don't prefix their API under `/api`, not an OD-observed route. Also confirmed no
40
- * origin/CORS headers appear on any of the three live OD responses — `requireLocalDaemonRequest`
41
- * (`http/local-daemon-request.ts`), which is what stamps `Vary: Origin`/`Access-Control-*`
42
- * headers on other `/api/daemon/*` routes like shutdown, is never applied to health/ready/version,
43
- * matching this module's `requireSameOrigin`-unset routes.
44
- *
45
- * Two real gaps that live comparison caught and this module now fixes: `livenessRoute` and
46
- * `readinessRoute` used to omit `version` entirely, and `readinessRoute`'s success body had no
47
- * `ready` field — both now present, sourced from the same `deps.getVersion()` already wired for
48
- * `/version`. One gap intentionally left open: `/version`'s response here stays a flat `{version:
49
- * string}` (via the same string-returning `getVersion` convention `daemon-status.ts` already
50
- * uses) rather than OD's nested `AppVersionInfo` object — the channel/packaged/platform/arch
51
- * fields aren't wired anywhere in Jini today (`@jini-ai/server`'s `create-local-node-daemon.ts`
52
- * only ever supplies a plain version string), and inventing that plumbing is a host-level decision
53
- * out of this file's scope, not something to paper over with an unused type change here.
54
- */
55
- import type { Express } from 'express';
56
- import { type AdapterContext } from './adapter.js';
57
- export interface HealthReadinessResult {
58
- readonly ok: boolean;
59
- readonly checks: Record<string, boolean>;
60
- }
61
- export interface HealthHttpDeps {
62
- /** Resolves the running build's version string. May be sync or async, matching `daemon-status.ts#DaemonStatusDeps.getVersion`. */
63
- readonly getVersion: () => Promise<string> | string;
64
- /** Host-owned readiness probe (e.g. "is the sqlite handle healthy and is the process not mid-shutdown"). Defaults to always-ready (`{ok: true, checks: {}}`) — a host with nothing worth checking gets a working route with no wiring required. */
65
- readonly checkReadiness?: () => Promise<HealthReadinessResult>;
66
- }
67
- export interface LivenessResponse {
68
- readonly ok: true;
69
- /** The running build's version string. Matches OD's real `/api/health` — see module doc. */
70
- readonly version: string;
71
- }
72
- export interface ReadinessResponse {
73
- readonly ok: true;
74
- /** Mirrors `ok` — OD's real `/api/ready` carries both fields; see module doc. */
75
- readonly ready: true;
76
- /** The running build's version string. Matches OD's real `/api/ready` — see module doc. */
77
- readonly version: string;
78
- readonly checks: Record<string, boolean>;
79
- }
80
- export interface VersionResponse {
81
- readonly version: string;
82
- }
83
- export declare const healthRoute: import("./types.js").JsonRouteSpec<void, LivenessResponse, HealthHttpDeps>;
84
- export declare const apiHealthRoute: import("./types.js").JsonRouteSpec<void, LivenessResponse, HealthHttpDeps>;
85
- export declare const readyRoute: import("./types.js").JsonRouteSpec<void, ReadinessResponse, HealthHttpDeps>;
86
- export declare const apiReadyRoute: import("./types.js").JsonRouteSpec<void, ReadinessResponse, HealthHttpDeps>;
87
- export declare const versionInfoRoute: import("./types.js").JsonRouteSpec<void, VersionResponse, HealthHttpDeps>;
88
- export declare const apiVersionInfoRoute: import("./types.js").JsonRouteSpec<void, VersionResponse, HealthHttpDeps>;
89
- /** Mounts all six health/readiness/version routes on `app`. Call this before installing `express.json()`/the bearer-auth/origin-guard middleware — see module doc. */
90
- export declare function registerHealthRoutes(app: Express, deps: HealthHttpDeps, adapter: AdapterContext): void;
91
- //# sourceMappingURL=health.d.ts.map
package/dist/health.js DELETED
@@ -1,53 +0,0 @@
1
- import { createApiError } from '@jini-ai/protocol';
2
- import { defineJsonRoute, mountJsonRoute } from './adapter.js';
3
- import { err, ok } from './types.js';
4
- async function defaultCheckReadiness() {
5
- return { ok: true, checks: {} };
6
- }
7
- function livenessRoute(path) {
8
- return defineJsonRoute({
9
- method: 'get',
10
- path,
11
- parse: () => ok(undefined),
12
- handle: async (_input, deps) => ok({ ok: true, version: await deps.getVersion() }),
13
- });
14
- }
15
- function readinessRoute(path) {
16
- return defineJsonRoute({
17
- method: 'get',
18
- path,
19
- parse: () => ok(undefined),
20
- handle: async (_input, deps) => {
21
- const checkReadiness = deps.checkReadiness ?? defaultCheckReadiness;
22
- const [result, version] = await Promise.all([checkReadiness(), deps.getVersion()]);
23
- if (!result.ok) {
24
- return err(createApiError('SERVICE_UNAVAILABLE', 'service not ready', { details: { checks: result.checks } }));
25
- }
26
- return ok({ ok: true, ready: true, version, checks: result.checks });
27
- },
28
- });
29
- }
30
- function versionRoute(path) {
31
- return defineJsonRoute({
32
- method: 'get',
33
- path,
34
- parse: () => ok(undefined),
35
- handle: async (_input, deps) => ok({ version: await deps.getVersion() }),
36
- });
37
- }
38
- export const healthRoute = livenessRoute('/health');
39
- export const apiHealthRoute = livenessRoute('/api/health');
40
- export const readyRoute = readinessRoute('/ready');
41
- export const apiReadyRoute = readinessRoute('/api/ready');
42
- export const versionInfoRoute = versionRoute('/version');
43
- export const apiVersionInfoRoute = versionRoute('/api/version');
44
- /** Mounts all six health/readiness/version routes on `app`. Call this before installing `express.json()`/the bearer-auth/origin-guard middleware — see module doc. */
45
- export function registerHealthRoutes(app, deps, adapter) {
46
- mountJsonRoute(app, healthRoute, deps, adapter);
47
- mountJsonRoute(app, apiHealthRoute, deps, adapter);
48
- mountJsonRoute(app, readyRoute, deps, adapter);
49
- mountJsonRoute(app, apiReadyRoute, deps, adapter);
50
- mountJsonRoute(app, versionInfoRoute, deps, adapter);
51
- mountJsonRoute(app, apiVersionInfoRoute, deps, adapter);
52
- }
53
- //# sourceMappingURL=health.js.map
@@ -1,174 +0,0 @@
1
- /**
2
- * @module host-tools
3
- *
4
- * Generic "open a working directory in a local host tool" surface, ported
5
- * from the routes-classification table's `host-tools.ts` MIXED row (see
6
- * `source-map.md`): the editor catalogue, `$PATH`/mac-bundle probing, and
7
- * guarded detached-spawn machinery have zero OD dependency and are ported
8
- * here in full. `GET /api/editors` (which uses solely this machinery) was
9
- * mounted first; `POST /api/resources/:resourceRef/open-in` (OD's `POST
10
- * /api/projects/:id/open-in`) is now ported too, now that a generic
11
- * workspace-root port exists (`workspace-root.ts`) to stand in for OD's
12
- * `projectStore.getProject`/`projectFiles.resolveProjectDir` — see that
13
- * route's own doc below for the exact mapping.
14
- *
15
- * The probing functions take an injectable `HostToolProbeEnv` (filesystem
16
- * `access`, `env`, `platform`) rather than reading `process.env`/`fs`
17
- * directly, so every platform/found/missing branch is exercisable from a
18
- * single-OS test runner without touching the real filesystem.
19
- */
20
- import { spawn as nodeSpawn } from 'node:child_process';
21
- import type { Express } from 'express';
22
- import { type AdapterContext } from './adapter.js';
23
- import { type WorkspaceRootResolver } from './workspace-root.js';
24
- export type RealPlatform = 'darwin' | 'win32' | 'linux';
25
- export type Platform = RealPlatform | 'unknown';
26
- export interface CatalogueEntry {
27
- readonly id: string;
28
- readonly label: string;
29
- readonly icon: string;
30
- /** CLI shim name to probe on `$PATH`. Mutually exclusive in practice with `macOpenBundle`, though both may be set as a fallback pair. */
31
- readonly command?: string;
32
- readonly commandArgs?: (workingDir: string) => string[];
33
- /** macOS-only fallback: when the CLI shim is missing, look for an app bundle by name and launch it via `open -a "<name>"`. */
34
- readonly macOpenBundle?: string | readonly string[];
35
- readonly macOpenArgs?: (bundleName: string, workingDir: string) => string[];
36
- readonly platforms?: readonly RealPlatform[];
37
- readonly excludedPlatforms?: readonly RealPlatform[];
38
- }
39
- /** The cross-platform-staple + macOS-bundle editor/tool catalogue, unchanged from the origin. */
40
- export declare const CATALOGUE: readonly CatalogueEntry[];
41
- /** Maps Node's `process.platform` to this module's tri-state `Platform`; anything else (aix, freebsd, sunos, ...) is `'unknown'`. */
42
- export declare function currentPlatform(nodePlatform?: NodeJS.Platform): Platform;
43
- export declare function applicableForPlatform(entry: CatalogueEntry, platform: Platform): boolean;
44
- /**
45
- * Everything the probing functions below need from the outside world, gathered into one
46
- * injectable value. Production code gets {@link defaultProbeEnv}; tests inject a fake `access`
47
- * (so "found"/"missing" is a table, not a real filesystem) and any `platform`/`env` they want to
48
- * exercise, independent of the OS actually running the test.
49
- */
50
- export interface HostToolProbeEnv {
51
- readonly access: (path: string, mode: number) => Promise<void>;
52
- readonly env: Readonly<Record<string, string | undefined>>;
53
- readonly platform: Platform;
54
- }
55
- export declare function defaultProbeEnv(): HostToolProbeEnv;
56
- /**
57
- * `$PATH` directories to probe, plus the common macOS/Linux locations a login shell would have
58
- * that a GUI-launched daemon's thin inherited `PATH` often lacks (no `/usr/local/bin`, no
59
- * `/opt/homebrew/bin`) — without these, CLI shims installed via an editor's "Install command"
60
- * action are invisible to a daemon launched by double-clicking an app bundle.
61
- */
62
- export declare function pathDirs(probeEnv: HostToolProbeEnv): string[];
63
- export declare function probeCommandOnPath(command: string, probeEnv: HostToolProbeEnv): Promise<string | null>;
64
- export declare function probeMacBundle(name: string | readonly string[], probeEnv: HostToolProbeEnv): Promise<{
65
- name: string;
66
- path: string;
67
- } | null>;
68
- /**
69
- * A discriminated union rather than one shape with optional fields: `resolvedPath`/`launch` are
70
- * only ever set together (both "found" branches below set the pair; the "not found" branch sets
71
- * neither), so the type says that directly instead of leaving `resolvedPath` reachable-but-absent
72
- * when `available` is `false`.
73
- */
74
- type ResolvedEntry = {
75
- readonly available: true;
76
- readonly resolvedPath: string;
77
- readonly launch: {
78
- readonly command: string;
79
- readonly argsForDir: (workingDir: string) => string[];
80
- };
81
- } | {
82
- readonly available: false;
83
- };
84
- export declare function resolveEntry(entry: CatalogueEntry, probeEnv?: HostToolProbeEnv): Promise<ResolvedEntry>;
85
- export interface HostToolLaunchPlan {
86
- readonly available: boolean;
87
- readonly resolvedPath?: string;
88
- readonly command?: string;
89
- readonly args?: string[];
90
- }
91
- /** Resolves the concrete `{command, args}` a caller would spawn to open `workingDir` in `editorId`, or `available: false` if that tool isn't installed/known. */
92
- export declare function resolveHostToolLaunchPlan(editorId: string, workingDir: string, probeEnv?: HostToolProbeEnv): Promise<HostToolLaunchPlan>;
93
- export type LaunchHostToolResult = {
94
- readonly ok: true;
95
- } | {
96
- readonly ok: false;
97
- readonly error: string;
98
- };
99
- /**
100
- * Spawns a detached host-tool launch and waits for the OS to confirm it actually started. Node
101
- * emits `'spawn'` once the child is running and `'error'` when the launch is refused (missing
102
- * binary, quarantine, EACCES) — `'error'` arrives on a later tick, so this must be awaited before
103
- * a caller replies, otherwise a launch the OS rejected would be reported as success (origin's
104
- * #3871).
105
- *
106
- * Deliberately never passes `shell: true`: on Windows that would route the launch through
107
- * `cmd.exe`, which shell-interprets args — and one of them is a caller-supplied directory path,
108
- * so a path containing `&`/`|`/`^`/`>` etc. would inject commands. `command` is already resolved
109
- * to an absolute path (including `.exe`/`.cmd`), so it's routed through `createCommandInvocation`
110
- * (`@jini-ai/platform`), which runs a `.cmd`/`.bat` via `cmd.exe` with
111
- * `CommandLineToArgvW`-safe verbatim args and everything else directly — no shell, no
112
- * metacharacter interpretation.
113
- */
114
- export declare function launchHostTool(command: string, args: string[], spawnImpl?: typeof nodeSpawn): Promise<LaunchHostToolResult>;
115
- export interface HostEditor {
116
- readonly id: string;
117
- readonly label: string;
118
- readonly icon: string;
119
- readonly available: boolean;
120
- readonly resolvedPath?: string;
121
- readonly platforms?: readonly RealPlatform[];
122
- }
123
- export interface HostEditorsResponse {
124
- readonly editors: readonly HostEditor[];
125
- readonly platform: Platform;
126
- }
127
- /** Probes every catalogue entry applicable to the current platform and reports which are actually installed. */
128
- export declare function listAvailableEditors(probeEnv?: HostToolProbeEnv): Promise<HostEditorsResponse>;
129
- /** `GET /api/editors` — lists the host-tool catalogue applicable to this platform with live availability. */
130
- export declare const hostEditorsRoute: import("./types.js").JsonRouteSpec<void, HostEditorsResponse, Record<string, never>>;
131
- export interface OpenResourceInEditorRequest {
132
- readonly resourceRef: string;
133
- readonly editorId: string;
134
- readonly detail?: string;
135
- }
136
- export interface OpenResourceInEditorResponse {
137
- readonly ok: true;
138
- readonly editorId: string;
139
- readonly path: string;
140
- }
141
- /** Everything `POST /api/resources/:resourceRef/open-in` needs from the host. */
142
- export interface HostToolsOpenInDeps {
143
- /** Resolves a resource reference to a filesystem working directory. Defaults to {@link denyAllWorkspaceRoots} — a host that never wires a real resolver gets a 404 on every call, never a guessed path (see `workspace-root.ts`). */
144
- readonly resolveRoot?: WorkspaceRootResolver;
145
- readonly probeEnv?: HostToolProbeEnv;
146
- readonly spawnImpl?: typeof nodeSpawn;
147
- }
148
- /**
149
- * `POST /api/resources/:resourceRef/open-in` — launches `editorId` (from
150
- * {@link CATALOGUE}) rooted at the working directory `deps.resolveRoot`
151
- * resolves for `resourceRef`. Ported from OD's `POST
152
- * /api/projects/:id/open-in`: `projectId` generalizes to the opaque
153
- * `resourceRef` this package already uses (`active-context.ts`,
154
- * `cancel-owned-runs.ts`), and `getProject`/`resolveProjectDir` generalize
155
- * to the injected {@link WorkspaceRootResolver}. `PROJECT_NOT_FOUND` (an
156
- * OD-product-only code with no `@jini-ai/protocol` equivalent — see
157
- * `response.ts`'s file-map note) becomes a generic `NOT_FOUND` when the
158
- * resolver denies. `EDITOR_NOT_AVAILABLE` (OD's 409 for "installed catalogue
159
- * entry, but not found on this machine") becomes `CONFLICT`, which already
160
- * maps to 409 in this package's `ERROR_STATUS_BY_CODE`.
161
- *
162
- * The launch-failure message is returned to the caller verbatim (unlike
163
- * `runs.ts`'s SEC-005 redaction of internal agent-run errors): this is a
164
- * same-origin, explicitly-consented, single local action the caller just
165
- * asked for (open the tool it named, at the directory it's authorized to
166
- * open) — the underlying spawn error (e.g. a quarantined/missing binary) is
167
- * operationally useful to the caller and does not cross a trust boundary
168
- * the way an internal agent-run exception can.
169
- */
170
- export declare const openResourceInEditorRoute: import("./types.js").JsonRouteSpec<OpenResourceInEditorRequest, OpenResourceInEditorResponse, HostToolsOpenInDeps>;
171
- /** Mounts `GET /api/editors` and `POST /api/resources/:resourceRef/open-in` on `app`. A pack's `http(app, services)` calls this directly. */
172
- export declare function registerHostToolsRoutes(app: Express, adapter: AdapterContext, openInDeps?: HostToolsOpenInDeps): void;
173
- export {};
174
- //# sourceMappingURL=host-tools.d.ts.map