@feltdb/feltkit 0.5.1 → 0.5.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.
@@ -1,6 +1,8 @@
1
+ import { type KeyObject } from "node:crypto";
1
2
  import { type IncomingMessage, type ServerResponse } from "node:http";
2
3
  import { type EveAgentDeclaration, type FunctionDefinition } from "../app.js";
3
4
  import type { Principal } from "../runtime/authority.js";
5
+ import type { AgentSessionOrigin } from "../runtime/context.js";
4
6
  import type { Logger } from "../runtime/context.js";
5
7
  import type { FeltKitRuntime } from "../runtime/runtime.js";
6
8
  export declare const EVE_SESSIONS_COLLECTION = "_feltkit_eve_sessions";
@@ -37,19 +39,59 @@ export interface EveSessionRecord {
37
39
  at: number;
38
40
  reason?: string;
39
41
  };
42
+ /**
43
+ * A session started under a standing delegation (`ctx.agent.startSession`): the work grant, the person who issued it
44
+ * (`createdBy`), the application principal that started it, and where the request came from.
45
+ */
46
+ delegated?: {
47
+ grant: string;
48
+ startedBy: string;
49
+ origin: AgentSessionOrigin;
50
+ key?: string;
51
+ };
40
52
  }
41
53
  /** A tool name (eve: the tool file's name) for a capability: dots become underscores. */
42
54
  export declare function eveToolName(capability: string): string;
43
55
  export declare function signEveToken(secret: string, claims: Record<string, unknown>, now?: number): string;
56
+ /** An ES256 JWT (a remote executor verifies it with the public key only). */
57
+ export declare function signEveTokenEs256(key: KeyObject, kid: string, claims: Record<string, unknown>, now?: number): string;
58
+ /** A P-256 key pair derived from a secret (a stable key per agent, nothing to store); null in the negligible case the scalar is out of range. */
59
+ export declare function deriveEs256(seed: Buffer): {
60
+ privateKey: KeyObject;
61
+ publicKey: KeyObject;
62
+ kid: string;
63
+ };
44
64
  export declare class EveHost {
45
65
  #private;
46
66
  constructor(runtime: FeltKitRuntime, projectDir: string, log?: Logger);
67
+ /**
68
+ * Start a session under a standing delegation, from the application's own server code (`ctx.agent.startSession`):
69
+ * work no signed-in person of this application started in their browser, such as an agent joining a meeting in
70
+ * another application. The delegation is a work grant a person issued to the agent's worker in the caller's
71
+ * workspace; it must be active, and its issuer must still hold every capability it covers. The session runs as that
72
+ * delegation exactly as one a person started: every call is authorized under the grant, consequential ones need a
73
+ * person's approval of the exact call. The caller needs feltkit.agent.delegated; the origin is recorded, never trusted.
74
+ */
75
+ startDelegated(name: string, caller: Principal | null, input: {
76
+ delegation: string;
77
+ message: string;
78
+ origin: AgentSessionOrigin;
79
+ key?: string;
80
+ }): Promise<{
81
+ sessionId: string;
82
+ created: boolean;
83
+ }>;
84
+ /** End a delegated session (`ctx.agent.endSession`): only the principal that started it, or a person of its workspace. */
85
+ endDelegated(name: string, caller: Principal | null, sessionId: string, reason?: string): Promise<{
86
+ ended: boolean;
87
+ }>;
47
88
  static declared(runtime: FeltKitRuntime): boolean;
48
89
  /**
49
90
  * The agent's view of its capabilities, generated into its project (`agent/lib/feltkit-capabilities.json`):
50
91
  * for each capability the declaration covers, its tool name, description, JSON Schema input and whether it
51
92
  * needs a person's approval. Tools are made from it (`feltkitCapability`), so the agent never restates them.
52
93
  */
94
+ static capabilityEntries(declaration: EveAgentDeclaration, functions: ReadonlyMap<string, FunctionDefinition>): Record<string, EveCapability>;
53
95
  static writeCapabilities(root: string, declaration: EveAgentDeclaration, functions: ReadonlyMap<string, FunctionDefinition>): string;
54
96
  /** `eve build` for every agent: the production server `eve start` runs. */
55
97
  /**
@@ -59,6 +101,14 @@ export declare class EveHost {
59
101
  */
60
102
  static requireControl(name: string, root: string): void;
61
103
  static build(projectDir: string, eve: Record<string, EveAgentDeclaration>, functions: ReadonlyMap<string, FunctionDefinition>, log?: (line: string) => void): Promise<void>;
104
+ /** The PEM public key a remote executor verifies people's identities with (published at /_feltkit/eve/<name>/key). */
105
+ publicKey(name: string): {
106
+ kid: string;
107
+ algorithm: "ES256";
108
+ publicKey: string;
109
+ };
110
+ /** The agent's capabilities as a remote executor reads them (the same entries a local agent gets generated into its project). */
111
+ describeCapabilities(name: string): Record<string, EveCapability>;
62
112
  /** Start every agent's server. FeltKit must be listening (the agent calls back into it). */
63
113
  start(feltkitUrl: string, options?: {
64
114
  build?: boolean;
@@ -19,13 +19,14 @@
19
19
  * capability and input, and eve resumes with the approval's reference, which the call names.
20
20
  */
21
21
  import { spawn } from "node:child_process";
22
- import { createHmac, randomUUID } from "node:crypto";
22
+ import { createECDH, createHmac, createPrivateKey, createPublicKey, randomUUID, sign as cryptoSign } from "node:crypto";
23
23
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
24
24
  import { request as httpRequest } from "node:http";
25
+ import { request as httpsRequest } from "node:https";
25
26
  import { createServer as createNetServer } from "node:net";
26
27
  import { createRequire } from "node:module";
27
28
  import { join, resolve } from "node:path";
28
- import { projectAgentsOf } from "../app.js";
29
+ import { projectAgentsOf, remoteExecutorOrThrow } from "../app.js";
29
30
  import { FeltKitError } from "../errors.js";
30
31
  import { queryPages } from "../runtime/paged-read.js";
31
32
  import { readJSON, safeEqual, sendJSON } from "./http.js";
@@ -34,6 +35,18 @@ const TOKEN_TTL_S = 300;
34
35
  const HEALTH_TIMEOUT_MS = 30_000;
35
36
  const MAX_BACKOFF_MS = 30_000;
36
37
  const STREAM_READ_LIMIT = 4 * 1024 * 1024;
38
+ function originOrThrow(origin) {
39
+ const o = origin;
40
+ const short = (v, max) => typeof v === "string" && v.length > 0 && v.length <= max;
41
+ if (!o || typeof o !== "object" || !short(o.application, 64) || !short(o.kind, 64) || !short(o.ref, 200))
42
+ throw new FeltKitError("INVALID_ARGUMENT", "origin is { application, kind, ref, requestedBy?, detail? }, each a short string.");
43
+ if (o.requestedBy !== undefined && (!short(o.requestedBy?.id, 200) || (o.requestedBy.name !== undefined && !short(o.requestedBy.name, 200))))
44
+ throw new FeltKitError("INVALID_ARGUMENT", "origin.requestedBy is { id, name? }.");
45
+ const detail = o.detail ?? {};
46
+ if (typeof detail !== "object" || Object.keys(detail).length > 20 || Object.entries(detail).some(([k, v]) => !short(k, 64) || !short(v, 500)))
47
+ throw new FeltKitError("INVALID_ARGUMENT", "origin.detail is at most 20 short string entries.");
48
+ return { application: o.application, kind: o.kind, ref: o.ref, ...(o.requestedBy ? { requestedBy: { id: o.requestedBy.id, ...(o.requestedBy.name ? { name: o.requestedBy.name } : {}) } } : {}), ...(Object.keys(detail).length ? { detail: { ...detail } } : {}) };
49
+ }
37
50
  /** A tool name (eve: the tool file's name) for a capability: dots become underscores. */
38
51
  export function eveToolName(capability) {
39
52
  return capability.replace(/\./g, "_");
@@ -44,6 +57,33 @@ export function signEveToken(secret, claims, now = Date.now()) {
44
57
  const body = `${b64({ alg: "HS256", typ: "JWT" })}.${b64({ iat, exp: iat + TOKEN_TTL_S, ...claims })}`;
45
58
  return `${body}.${createHmac("sha256", secret).update(body).digest("base64url")}`;
46
59
  }
60
+ /** An ES256 JWT (a remote executor verifies it with the public key only). */
61
+ export function signEveTokenEs256(key, kid, claims, now = Date.now()) {
62
+ const b64 = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
63
+ const iat = Math.floor(now / 1000);
64
+ const body = `${b64({ alg: "ES256", typ: "JWT", kid })}.${b64({ iat, exp: iat + TOKEN_TTL_S, ...claims })}`;
65
+ return `${body}.${cryptoSign("sha256", Buffer.from(body), { key, dsaEncoding: "ieee-p1363" }).toString("base64url")}`;
66
+ }
67
+ /** A P-256 key pair derived from a secret (a stable key per agent, nothing to store); null in the negligible case the scalar is out of range. */
68
+ export function deriveEs256(seed) {
69
+ for (let counter = 0; counter < 8; counter++) {
70
+ const d = createHmac("sha256", seed).update(`p256/${counter}`).digest();
71
+ try {
72
+ const ecdh = createECDH("prime256v1");
73
+ ecdh.setPrivateKey(d);
74
+ const point = ecdh.getPublicKey();
75
+ const jwk = { kty: "EC", crv: "P-256", d: d.toString("base64url"), x: point.subarray(1, 33).toString("base64url"), y: point.subarray(33, 65).toString("base64url") };
76
+ const privateKey = createPrivateKey({ key: jwk, format: "jwk" });
77
+ const publicKey = createPublicKey(privateKey);
78
+ const kid = createHmac("sha256", "kid").update(point).digest("base64url").slice(0, 16);
79
+ return { privateKey, publicKey, kid };
80
+ }
81
+ catch {
82
+ continue;
83
+ }
84
+ }
85
+ throw new FeltKitError("INTERNAL", "Could not derive the agent's signing key.");
86
+ }
47
87
  async function freePort() {
48
88
  return new Promise((resolvePort, reject) => {
49
89
  const server = createNetServer();
@@ -79,9 +119,85 @@ export class EveHost {
79
119
  this.#projectDir = projectDir;
80
120
  this.#log = log;
81
121
  for (const [name, declaration] of Object.entries(projectAgentsOf(runtime.app))) {
82
- this.#agents.set(name, { name, declaration, root: resolve(projectDir, declaration.root ?? "."), port: 0, state: "stopped", child: null, restarts: 0, healthySince: null });
122
+ const remote = declaration.executor ? remoteExecutorOrThrow(declaration.executor, `agent "${name}"`) : null;
123
+ this.#agents.set(name, { name, declaration, root: resolve(projectDir, declaration.root ?? "."), origin: remote, remote: Boolean(remote), port: 0, state: "stopped", child: null, restarts: 0, healthySince: null });
83
124
  }
84
125
  runtime.agent.useExternalReasoners((taskId) => this.#reasoner(taskId));
126
+ runtime.useProjectAgentSessions({ start: (name, caller, input) => this.startDelegated(name, caller, input), end: (name, caller, sessionId, reason) => this.endDelegated(name, caller, sessionId, reason) });
127
+ }
128
+ /**
129
+ * Start a session under a standing delegation, from the application's own server code (`ctx.agent.startSession`):
130
+ * work no signed-in person of this application started in their browser, such as an agent joining a meeting in
131
+ * another application. The delegation is a work grant a person issued to the agent's worker in the caller's
132
+ * workspace; it must be active, and its issuer must still hold every capability it covers. The session runs as that
133
+ * delegation exactly as one a person started: every call is authorized under the grant, consequential ones need a
134
+ * person's approval of the exact call. The caller needs feltkit.agent.delegated; the origin is recorded, never trusted.
135
+ */
136
+ async startDelegated(name, caller, input) {
137
+ const agent = this.#agentOf(name);
138
+ if (!caller || caller.guest)
139
+ throw new FeltKitError("UNAUTHORIZED", "Starting an agent session needs a signed-in caller.");
140
+ if (!this.#runtime.holds(caller, "feltkit.agent.delegated"))
141
+ throw new FeltKitError("FORBIDDEN", `${caller.id} may not start agent sessions under a delegation (needs feltkit.agent.delegated).`);
142
+ const origin = originOrThrow(input.origin);
143
+ const message = typeof input.message === "string" ? input.message.trim() : "";
144
+ if (!message || message.length > 20_000)
145
+ throw new FeltKitError("INVALID_ARGUMENT", "message is 1 to 20000 characters.");
146
+ if (input.key !== undefined && (typeof input.key !== "string" || !input.key || input.key.length > 200))
147
+ throw new FeltKitError("INVALID_ARGUMENT", "key is 1 to 200 characters.");
148
+ const tenantId = caller.tenant?.id ?? null;
149
+ const sessions = this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION);
150
+ if (input.key) {
151
+ const [existing] = (await sessions.find({ agent: name }, { limit: 1000 })).filter((r) => r.tenantId === tenantId && r.delegated?.key === input.key && r.delegated?.startedBy === caller.id);
152
+ if (existing)
153
+ return { sessionId: existing.id, created: false };
154
+ }
155
+ const workerId = `worker:${this.workerName(name, tenantId)}`;
156
+ const grant = (await this.#runtime.workers.grantsOf(workerId)).find((g) => g.ref === input.delegation);
157
+ if (!grant)
158
+ throw new FeltKitError("FORBIDDEN", "That delegation is not a work grant to this agent in your workspace.", { details: { reason: "DELEGATION_NOT_FOUND" } });
159
+ if (grant.state !== "active")
160
+ throw new FeltKitError("FORBIDDEN", `That delegation is ${grant.state}.`, { details: { reason: grant.state === "revoked" ? "DELEGATION_REVOKED" : "DELEGATION_EXPIRED" } });
161
+ const found = await this.#runtime.resolvePrincipal(grant.actor.id);
162
+ const issuer = found ? await this.#runtime.withTenant(found, tenantId ?? undefined) : null;
163
+ if (!isPerson(issuer) || (tenantId !== null && issuer.tenant?.id !== tenantId))
164
+ throw new FeltKitError("FORBIDDEN", "The person who issued that delegation is no longer a person of this workspace.", { details: { reason: "DELEGATOR_GONE" } });
165
+ const declared = this.capabilities(name);
166
+ const lapsed = grant.capabilities.filter((c) => !declared.has(c) || !this.#runtime.holds(issuer, declared.get(c).access));
167
+ if (lapsed.length)
168
+ throw new FeltKitError("FORBIDDEN", `The person who issued that delegation no longer holds what it covers: ${lapsed.join(", ")}.`, { details: { reason: "DELEGATION_EXCEEDS_DELEGATOR", capabilities: lapsed } });
169
+ if (agent.state !== "ready")
170
+ throw new FeltKitError("UNAVAILABLE", `The agent is ${agent.state}${agent.detail ? `: ${agent.detail}` : ""}.`);
171
+ const body = Buffer.from(JSON.stringify({ message }));
172
+ const answer = await this.#call(agent, "POST", "/eve/v1/session", this.#token(name, issuer, { grant: grant.ref, delegated: { startedBy: caller.id, origin } }), body, { "content-type": "application/json" });
173
+ const created = JSON.parse(answer.body.toString("utf8") || "{}");
174
+ if (answer.status >= 300 || typeof created.sessionId !== "string")
175
+ throw new FeltKitError("UNAVAILABLE", `The agent did not start the session (${answer.status}).`);
176
+ const worker = await this.#worker(name, tenantId);
177
+ const title = titleOf(body);
178
+ const task = worker ? await this.#runtime.agent.openTask({ principal: worker, objective: title, key: `session:${created.sessionId}` }) : null;
179
+ const record = { id: created.sessionId, agent: name, tenantId, createdBy: issuer.id, createdAt: Date.now(), title, ...(task ? { taskId: task.taskId } : {}), delegated: { grant: grant.ref, startedBy: caller.id, origin, ...(input.key ? { key: input.key } : {}) } };
180
+ await sessions.insert(record, created.sessionId);
181
+ this.#runtime.recordAuth("agent.session.delegated", caller, { agent: name, session: created.sessionId, grant: grant.ref, delegatedBy: issuer.id, origin: `${origin.application}:${origin.kind}:${origin.ref}` }, "success", "runtime");
182
+ return { sessionId: created.sessionId, created: true };
183
+ }
184
+ /** End a delegated session (`ctx.agent.endSession`): only the principal that started it, or a person of its workspace. */
185
+ async endDelegated(name, caller, sessionId, reason) {
186
+ this.#agentOf(name);
187
+ if (!caller || caller.guest)
188
+ throw new FeltKitError("UNAUTHORIZED", "Ending an agent session needs a signed-in caller.");
189
+ if (!this.#runtime.holds(caller, "feltkit.agent.delegated"))
190
+ throw new FeltKitError("FORBIDDEN", `${caller.id} may not end delegated agent sessions (needs feltkit.agent.delegated).`);
191
+ const record = (await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).get(sessionId));
192
+ if (!record || record.agent !== name || record.tenantId !== (caller.tenant?.id ?? null) || !record.delegated || (record.delegated.startedBy !== caller.id && !isPerson(caller)))
193
+ throw new FeltKitError("NOT_FOUND", "No such delegated session here.");
194
+ if (record.stopped)
195
+ return { ended: false };
196
+ const reasoner = record.taskId ? await this.#reasoner(record.taskId) : null;
197
+ if (!reasoner)
198
+ throw new FeltKitError("FAILED_PRECONDITION", "That session has no task to stop.");
199
+ await reasoner.stop(caller, reason ?? "ended by the application that started it");
200
+ return { ended: true };
85
201
  }
86
202
  /** The session behind an agent task, as its reasoner: in-flight work from the facts it recorded; interrupt, resume, stop. */
87
203
  async #reasoner(taskId) {
@@ -158,7 +274,7 @@ export class EveHost {
158
274
  try {
159
275
  if (!agent || agent.state !== "ready")
160
276
  throw new Error("not ready");
161
- const response = await fetch(`http://127.0.0.1:${agent.port}/eve/v1/session/${encodeURIComponent(record.id)}/stream?startIndex=0&follow=true`, { headers: { authorization: `Bearer ${this.#token(record.agent, reader, {})}`, accept: "application/x-ndjson" }, signal: stop.signal });
277
+ const response = await fetch(`${this.#origin(agent)}eve/v1/session/${encodeURIComponent(record.id)}/stream?startIndex=0&follow=true`, { headers: { authorization: `Bearer ${this.#token(record.agent, reader, {})}`, accept: "application/x-ndjson" }, signal: stop.signal });
162
278
  if (!response.ok || !response.body)
163
279
  throw new Error(`stream ${response.status}`);
164
280
  const facts = [];
@@ -237,7 +353,7 @@ export class EveHost {
237
353
  * for each capability the declaration covers, its tool name, description, JSON Schema input and whether it
238
354
  * needs a person's approval. Tools are made from it (`feltkitCapability`), so the agent never restates them.
239
355
  */
240
- static writeCapabilities(root, declaration, functions) {
356
+ static capabilityEntries(declaration, functions) {
241
357
  const capabilities = {};
242
358
  for (const fn of functions.values()) {
243
359
  const capability = fn.capability?.name;
@@ -245,9 +361,12 @@ export class EveHost {
245
361
  continue;
246
362
  capabilities[capability] = { capability, tool: eveToolName(capability), description: fn.capability?.description ?? fn.description ?? capability, inputSchema: fn.argsSchema.toJSONSchema(), approval: fn.approval === "required" ? "required" : "none" };
247
363
  }
364
+ return Object.fromEntries(Object.entries(capabilities).sort(([a], [b]) => a.localeCompare(b)));
365
+ }
366
+ static writeCapabilities(root, declaration, functions) {
248
367
  const file = join(root, "agent", "lib", "feltkit-capabilities.json");
249
368
  mkdirSync(join(root, "agent", "lib"), { recursive: true });
250
- const sorted = Object.fromEntries(Object.entries(capabilities).sort(([a], [b]) => a.localeCompare(b)));
369
+ const sorted = EveHost.capabilityEntries(declaration, functions);
251
370
  const text = `${JSON.stringify(sorted, null, 2)}\n`;
252
371
  if (!existsSync(file) || readFileSync(file, "utf8") !== text)
253
372
  writeFileSync(file, text);
@@ -280,6 +399,10 @@ export class EveHost {
280
399
  }
281
400
  static async build(projectDir, eve, functions, log) {
282
401
  for (const [name, declaration] of Object.entries(eve)) {
402
+ if (declaration.executor) {
403
+ log?.(`agent "${name}" executes remotely (${new URL(declaration.executor.url).origin}): not built here`);
404
+ continue;
405
+ }
283
406
  const root = resolve(projectDir, declaration.root ?? ".");
284
407
  EveHost.writeCapabilities(root, declaration, functions);
285
408
  const code = await new Promise((done) => {
@@ -300,8 +423,32 @@ export class EveHost {
300
423
  }
301
424
  }
302
425
  #secret(name, purpose) {
426
+ const executor = this.#agents.get(name)?.declaration.executor;
427
+ if (executor && purpose === "service")
428
+ return executor.serviceKey;
303
429
  return createHmac("sha256", this.#runtime.authSecret()).update(`feltkit/eve/${name}/${purpose}`).digest("base64url");
304
430
  }
431
+ #signing = new Map();
432
+ /** The agent's ES256 key pair, derived from the application's secret: the executor holds only the public half. */
433
+ #es256(name) {
434
+ let keys = this.#signing.get(name);
435
+ if (!keys)
436
+ this.#signing.set(name, (keys = deriveEs256(createHmac("sha256", this.#runtime.authSecret()).update(`feltkit/eve/${name}/es256`).digest())));
437
+ return keys;
438
+ }
439
+ /** The PEM public key a remote executor verifies people's identities with (published at /_feltkit/eve/<name>/key). */
440
+ publicKey(name) {
441
+ this.#agentOf(name);
442
+ const keys = this.#es256(name);
443
+ return { kid: keys.kid, algorithm: "ES256", publicKey: keys.publicKey.export({ type: "spki", format: "pem" }).toString() };
444
+ }
445
+ /** The agent's capabilities as a remote executor reads them (the same entries a local agent gets generated into its project). */
446
+ describeCapabilities(name) {
447
+ return EveHost.capabilityEntries(this.#agentOf(name).declaration, this.#runtime.project.functions);
448
+ }
449
+ #origin(agent) {
450
+ return agent.remote ? agent.origin.href : `http://127.0.0.1:${agent.port}/`;
451
+ }
305
452
  /** Start every agent's server. FeltKit must be listening (the agent calls back into it). */
306
453
  async start(feltkitUrl, options = {}) {
307
454
  this.#feltkitUrl = feltkitUrl;
@@ -326,6 +473,8 @@ export class EveHost {
326
473
  async #launch(agent) {
327
474
  if (this.#closing)
328
475
  return;
476
+ if (agent.remote)
477
+ return this.#connect(agent);
329
478
  if (!existsSync(join(agent.root, ".output", "server", "index.mjs"))) {
330
479
  agent.state = "failed";
331
480
  agent.detail = `agent "${agent.name}" is not built (${agent.root}/.output): run feltkit build.`;
@@ -379,9 +528,30 @@ export class EveHost {
379
528
  child.kill("SIGKILL");
380
529
  }
381
530
  }
531
+ /** A remote executor: ready once it answers its health check; until then retried with backoff, never started here. */
532
+ async #connect(agent) {
533
+ if (this.#closing)
534
+ return;
535
+ if (await this.#healthy(agent)) {
536
+ const was = agent.state;
537
+ agent.state = "ready";
538
+ agent.detail = undefined;
539
+ agent.healthySince = Date.now();
540
+ if (was !== "ready")
541
+ void this.#reconcile(agent.name).catch((error) => this.#log?.warn(`[agent:${agent.name}] could not follow held sessions: ${String(error)}`));
542
+ setTimeout(() => void this.#connect(agent), 15_000).unref();
543
+ return;
544
+ }
545
+ agent.restarts++;
546
+ agent.healthySince = null;
547
+ const delay = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(agent.restarts - 1, 5));
548
+ agent.state = agent.state === "ready" || agent.state === "restarting" ? "restarting" : "starting";
549
+ agent.detail = `the executor at ${agent.origin.origin} is not answering; retrying in ${delay} ms`;
550
+ setTimeout(() => void this.#connect(agent), delay).unref();
551
+ }
382
552
  async #healthy(agent) {
383
553
  try {
384
- const response = await fetch(`http://127.0.0.1:${agent.port}/eve/v1/health`, { signal: AbortSignal.timeout(2000) });
554
+ const response = await fetch(`${this.#origin(agent)}eve/v1/health`, { signal: AbortSignal.timeout(agent.remote ? 5000 : 2000) });
385
555
  return response.ok;
386
556
  }
387
557
  catch {
@@ -480,7 +650,10 @@ export class EveHost {
480
650
  return grant.ref;
481
651
  }
482
652
  #token(name, person, extra) {
483
- return signEveToken(this.#secret(name, "assertion"), {
653
+ const remote = this.#agentOf(name).remote;
654
+ const keys = remote ? this.#es256(name) : null;
655
+ const sign = (claims) => (keys ? signEveTokenEs256(keys.privateKey, keys.kid, claims) : signEveToken(this.#secret(name, "assertion"), claims));
656
+ return sign({
484
657
  iss: `feltkit:${this.#runtime.app.name}`,
485
658
  aud: `eve:${name}`,
486
659
  sub: person.id,
@@ -529,6 +702,13 @@ export class EveHost {
529
702
  * for any other path.
530
703
  */
531
704
  async handle(request, response, pathname, identify) {
705
+ const published = /^\/_feltkit\/eve\/([a-z][a-z0-9-]*)\/(key|capabilities)$/.exec(pathname);
706
+ if (published && (request.method ?? "GET") === "GET") {
707
+ if (published[2] === "key")
708
+ return void sendJSON(response, 200, { ok: true, ...this.publicKey(published[1]) }), true;
709
+ this.#authorizeBridge(published[1], request);
710
+ return void sendJSON(response, 200, { ok: true, capabilities: this.describeCapabilities(published[1]) }), true;
711
+ }
532
712
  const bridge = /^\/_feltkit\/eve\/([a-z][a-z0-9-]*)\/(invoke|control)$/.exec(pathname);
533
713
  if (bridge) {
534
714
  await (bridge[2] === "control" ? this.#control(bridge[1], request, response) : this.#bridge(bridge[1], request, response));
@@ -603,9 +783,9 @@ export class EveHost {
603
783
  return this.#proxy(agent, request, response, rest, this.#token(name, person, claims)), true;
604
784
  }
605
785
  #authorizeBridge(name, request) {
606
- this.#agentOf(name);
786
+ const agent = this.#agentOf(name);
607
787
  const remote = request.socket.remoteAddress ?? "";
608
- if (!["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(remote))
788
+ if (!agent.remote && !["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(remote))
609
789
  throw new FeltKitError("FORBIDDEN", "The agent bridge answers only this machine.");
610
790
  const key = String(request.headers.authorization ?? "").replace(/^Bearer\s+/i, "");
611
791
  if (!key || !safeEqual(key, this.#secret(name, "service")))
@@ -773,9 +953,15 @@ export class EveHost {
773
953
  const call = waiting ? (calls.get(waiting) ?? null) : null;
774
954
  return call;
775
955
  }
956
+ /** One request to the agent's executor: the child on loopback, or the remote executor (https). */
957
+ #request(agent, options, onResponse) {
958
+ const origin = new URL(this.#origin(agent));
959
+ const send = origin.protocol === "https:" ? httpsRequest : httpRequest;
960
+ return send({ ...options, protocol: origin.protocol, hostname: origin.hostname.replace(/^\[|\]$/g, ""), port: origin.port || (origin.protocol === "https:" ? 443 : 80) }, onResponse);
961
+ }
776
962
  #call(agent, method, path, token, body, headers = {}) {
777
963
  return new Promise((done, fail) => {
778
- const outgoing = httpRequest({ host: "127.0.0.1", port: agent.port, method, path, headers: { ...(headers["content-type"] ? { "content-type": headers["content-type"] } : {}), ...(headers.accept ? { accept: headers.accept } : {}), authorization: `Bearer ${token}`, ...(body ? { "content-length": body.byteLength } : {}) } }, (incoming) => {
964
+ const outgoing = this.#request(agent, { method, path, headers: { ...(headers["content-type"] ? { "content-type": headers["content-type"] } : {}), ...(headers.accept ? { accept: headers.accept } : {}), authorization: `Bearer ${token}`, ...(body ? { "content-length": body.byteLength } : {}) } }, (incoming) => {
779
965
  const chunks = [];
780
966
  let size = 0;
781
967
  incoming.on("data", (chunk) => {
@@ -805,7 +991,7 @@ export class EveHost {
805
991
  headers.authorization = `Bearer ${token}`;
806
992
  if (body)
807
993
  headers["content-length"] = body.byteLength;
808
- const outgoing = httpRequest({ host: "127.0.0.1", port: agent.port, method: request.method, path: path + search, headers }, (incoming) => {
994
+ const outgoing = this.#request(agent, { method: request.method, path: path + search, headers }, (incoming) => {
809
995
  const out = { "cache-control": "no-store" };
810
996
  for (const name of ["content-type", "x-eve-tail-index", "x-accel-buffering"]) {
811
997
  const value = incoming.headers[name];