@artinet/fleet 0.1.1 → 0.1.7

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 (38) hide show
  1. package/README.md +109 -230
  2. package/dist/default.d.ts +1 -0
  3. package/dist/default.js +1 -0
  4. package/dist/routes/create/index.d.ts +51 -50
  5. package/dist/routes/create/index.js +1 -1
  6. package/dist/routes/request/implementation/load.d.ts +1 -1
  7. package/dist/routes/request/implementation/load.js +17 -20
  8. package/dist/routes/request/types/definitions.d.ts +59 -57
  9. package/dist/routes/request/types/definitions.js +5 -7
  10. package/dist/server/express/agent-request.d.ts +6 -15
  11. package/dist/server/express/agent-request.js +33 -27
  12. package/dist/server/express/deploy-request.d.ts +6 -14
  13. package/dist/server/express/deploy-request.js +18 -18
  14. package/dist/server/express/server.d.ts +73 -13
  15. package/dist/server/express/server.js +57 -49
  16. package/dist/server/express/test-request.d.ts +16 -14
  17. package/dist/server/express/test-request.js +25 -25
  18. package/dist/server/express/types.d.ts +10 -0
  19. package/dist/server/express/types.js +5 -0
  20. package/dist/server/hono/agent-request.d.ts +6 -14
  21. package/dist/server/hono/agent-request.js +25 -21
  22. package/dist/server/hono/deploy-request.d.ts +6 -13
  23. package/dist/server/hono/deploy-request.js +14 -13
  24. package/dist/server/hono/rpc.d.ts +9 -11
  25. package/dist/server/hono/rpc.js +19 -20
  26. package/dist/server/hono/server.d.ts +82 -13
  27. package/dist/server/hono/server.js +63 -44
  28. package/dist/server/hono/test-request.d.ts +6 -13
  29. package/dist/server/hono/test-request.js +26 -26
  30. package/dist/server/hono/types.d.ts +9 -0
  31. package/dist/server/hono/types.js +5 -0
  32. package/dist/settings.d.ts +22 -1
  33. package/dist/ship.d.ts +45 -1
  34. package/dist/ship.js +46 -1
  35. package/dist/types.d.ts +37 -0
  36. package/dist/utils.d.ts +11 -0
  37. package/dist/utils.js +13 -0
  38. package/package.json +108 -108
@@ -2,25 +2,21 @@
2
2
  * Copyright 2025 The Artinet Project
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import * as sdk from "@artinet/sdk";
6
- import express from "express";
7
- import { DEFAULTS } from "../../default.js";
8
- import * as agent from "./agent-request.js";
9
- import * as testing from "./test-request.js";
10
- import * as deployment from "./deploy-request.js";
11
- import { AGENT_FIELD_NAME } from "./agent-request.js";
5
+ import * as sdk from '@artinet/sdk';
6
+ import express from 'express';
7
+ import { DEFAULTS } from '../../default.js';
8
+ import * as agent from './agent-request.js';
9
+ import * as testing from './test-request.js';
10
+ import * as deployment from './deploy-request.js';
11
+ import { AGENT_FIELD_NAME } from '../../default.js';
12
12
  const createContext = (settings) => {
13
13
  const _settings = {
14
14
  ...DEFAULTS,
15
15
  ...settings,
16
- retrieve: agent.factory(settings.get ?? DEFAULTS.get,
17
- /**Middleware addons are currently only supported on the agent request route */
18
- settings.middleware?.build() ?? []),
19
- deploy: deployment.factory(settings.set ?? DEFAULTS.set),
20
- evaluate: testing.factory(settings.test ?? DEFAULTS.test),
21
- user: settings.user
22
- ? settings.user
23
- : (_req) => Promise.resolve(settings.userId ?? "default"),
16
+ retrieve: agent.factory({ implementation: settings.get ?? DEFAULTS.get }),
17
+ deploy: deployment.factory({ implementation: settings.set ?? DEFAULTS.set }),
18
+ evaluate: testing.factory({ implementation: settings.test ?? DEFAULTS.test }),
19
+ user: settings.user ? settings.user : (_session) => Promise.resolve(settings.userId ?? 'default'),
24
20
  };
25
21
  return _settings;
26
22
  };
@@ -40,9 +36,43 @@ const createRequestContext = (context) => {
40
36
  timestamp: undefined,
41
37
  };
42
38
  };
43
- export function fleet(settings = DEFAULTS, { app = express(), authOnRetrieve = false, enableTesting = true, } = {}) {
39
+ /**
40
+ * Creates and configures a Fleet server instance using Express.
41
+ *
42
+ * This function implements the **Factory Pattern** combined with **Dependency Injection**
43
+ * to provide a flexible, testable, and configurable server setup. The pattern allows
44
+ * consumers to override defaults while maintaining sensible out-of-the-box behavior.
45
+ *
46
+ * @param settings - Partial configuration merged with defaults. Supports custom
47
+ * handlers for `get`, `set`, `test`, and middleware composition.
48
+ * @param options - Server instantiation options
49
+ * @param options.app - Pre-configured Express application instance. Useful for
50
+ * adding custom middleware or integrating with existing servers.
51
+ * @param options.authOnRetrieve - When `true`, applies auth middleware to agent
52
+ * retrieval routes. Defaults to `false` for development convenience.
53
+ * @param options.enableTesting - When `true`, exposes the test endpoint for
54
+ * agent evaluation. Disable in production if not needed.
55
+ *
56
+ * @returns Object containing:
57
+ * - `app`: The configured Express application
58
+ * - `launch`: Function to start the HTTP server on a specified port
59
+ * - `ship`: Async function to deploy agents and return a launchable server
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * // Basic usage with defaults
64
+ * const { app, launch } = fleet();
65
+ * launch(3000);
66
+ *
67
+ * // With custom configuration
68
+ * const { ship } = fleet({ userId: 'admin' }, { authOnRetrieve: true });
69
+ * const server = await ship([agentConfig]);
70
+ * server.launch(8080);
71
+ * ```
72
+ */
73
+ export function fleet(settings = DEFAULTS, { app = express(), authOnRetrieve = false, enableTesting = true } = {}) {
44
74
  const context = createContext(settings);
45
- const { basePath, agentPath, fallbackPath, deploymentPath, testPath, auth, user, evaluate, deploy, retrieve, set, } = context;
75
+ const { basePath, agentPath, fallbackPath, deploymentPath, testPath, auth, user, evaluate, deploy, retrieve, set } = context;
46
76
  const router = express.Router();
47
77
  router.use(express.json());
48
78
  if (auth) {
@@ -54,38 +84,32 @@ export function fleet(settings = DEFAULTS, { app = express(), authOnRetrieve = f
54
84
  }
55
85
  }
56
86
  if (enableTesting === true && evaluate !== undefined) {
57
- router.post(testPath, async (req, res, next) => await testing.request({
58
- request: req,
59
- response: res,
60
- next,
87
+ router.post(testPath, async (request, response, next) => await testing.request({
88
+ session: { request, response, next },
61
89
  context: createRequestContext(context),
62
90
  handler: evaluate,
63
91
  user,
64
92
  }), sdk.errorHandler);
65
93
  }
66
- router.post(deploymentPath, async (req, res, next) => await deployment.request({
67
- request: req,
68
- response: res,
69
- next,
94
+ router.post(deploymentPath, async (request, response, next) => await deployment.request({
95
+ session: { request, response, next },
70
96
  context: createRequestContext(context),
71
97
  handler: deploy,
72
98
  user,
73
99
  }));
74
- router.use(`${agentPath}/:${AGENT_FIELD_NAME}`, async (req, res, next) => await agent.request({
75
- request: req,
76
- response: res,
77
- next,
100
+ router.use(`${agentPath}/:${AGENT_FIELD_NAME}`, async (request, response, next) => await agent.request({
101
+ session: { request, response, next },
78
102
  context: createRequestContext(context),
79
103
  handler: retrieve,
80
104
  user,
105
+ intercepts: settings.middleware?.build() ?? [],
81
106
  }), sdk.errorHandler);
82
- router.use(`${fallbackPath}/:${AGENT_FIELD_NAME}`, async (req, res, next) => await agent.request({
83
- request: req,
84
- response: res,
85
- next,
107
+ router.use(`${fallbackPath}/:${AGENT_FIELD_NAME}`, async (request, response, next) => await agent.request({
108
+ session: { request, response, next },
86
109
  context: createRequestContext(context),
87
110
  handler: retrieve,
88
111
  user,
112
+ intercepts: settings.middleware?.build() ?? [],
89
113
  }), sdk.errorHandler);
90
114
  app.use(basePath, router);
91
115
  const launch = (port = 3000) => {
@@ -107,19 +131,3 @@ export function fleet(settings = DEFAULTS, { app = express(), authOnRetrieve = f
107
131
  };
108
132
  return { app, launch, ship };
109
133
  }
110
- // const swarm = await fleet().ship([
111
- // {
112
- // config: {
113
- // uri: "my-agent",
114
- // name: "my-agent",
115
- // description: "A helpful assistant",
116
- // modelId: "gpt-4",
117
- // instructions: "You are a helpful assistant.",
118
- // version: "1.0.0",
119
- // skills: [],
120
- // capabilities: {},
121
- // services: [],
122
- // },
123
- // },
124
- // ]);
125
- // swarm.launch(3000);
@@ -2,17 +2,19 @@
2
2
  * Copyright 2025 The Artinet Project
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import express from "express";
6
- import { TestAgentRoute } from "../../routes/request/index.js";
7
- export type handler = (req: express.Request, res: express.Response, next: express.NextFunction, context: TestAgentRoute["context"], test?: TestAgentRoute["implementation"]) => Promise<void>;
8
- export declare function handle(req: express.Request, res: express.Response, _next: express.NextFunction, context: TestAgentRoute["context"], test?: TestAgentRoute["implementation"]): Promise<void>;
9
- export declare const factory: (test?: TestAgentRoute["implementation"]) => handler;
10
- export interface Params {
11
- request: express.Request;
12
- response: express.Response;
13
- next: express.NextFunction;
14
- context: Omit<TestAgentRoute["context"], "agentId">;
15
- handler: handler;
16
- user: (request: express.Request) => Promise<string>;
17
- }
18
- export declare function request({ request: req, response: res, next, context, handler, user, }: Params): Promise<void>;
5
+ import { TestAgentMount } from '../../routes/request/index.js';
6
+ import { Session } from './types.js';
7
+ /**
8
+ * Handler utilities for agent test/evaluation requests.
9
+ *
10
+ * Exports a reusable handler function for routing test/evaluation requests to agent instances,
11
+ * validating the request body, and returning the result as a JSON-RPC response.
12
+ *
13
+ * Used by the deployment server to provide a standard agent test/evaluation endpoint interface.
14
+ *
15
+ * @module server/handlers/test
16
+ */
17
+ export type Mount = TestAgentMount<Session>;
18
+ export declare const factory: Mount['factory'];
19
+ export declare const handle: Mount['handler'];
20
+ export declare const request: Mount['request'];
@@ -2,25 +2,13 @@
2
2
  * Copyright 2025 The Artinet Project
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import * as sdk from "@artinet/sdk";
6
- import { TestAgent, TestRequestSchema, } from "../../routes/request/index.js";
7
- import { v4 as uuidv4 } from "uuid";
8
- import { handleJSONRPCResponse } from "./rpc.js";
9
- import { generateRequestId } from "./utils.js";
10
- export async function handle(req, res, _next, context, test = TestAgent) {
11
- let parsed = await sdk.validateSchema(TestRequestSchema, req?.body ?? {});
12
- let id = parsed.id ?? uuidv4();
13
- parsed.id = id;
14
- let request = parsed;
15
- context.target = parsed.config;
16
- request.method = "test/invoke";
17
- request.params = null;
18
- const response = await test(request, context);
19
- await handleJSONRPCResponse(res, String(id), request.method, response);
20
- }
21
- export const factory = (test = TestAgent) => async (req, res, next, context) => await handle(req, res, next, context, test);
5
+ import * as sdk from '@artinet/sdk';
6
+ import { TestAgent, TestRequestSchema, } from '../../routes/request/index.js';
7
+ import { v4 as uuidv4 } from 'uuid';
8
+ import { handleJSONRPCResponse } from './rpc.js';
9
+ import { generateRequestId } from './utils.js';
22
10
  const MAX_TEST_ID_ATTEMPTS = 10;
23
- const getTestId = async (context) => {
11
+ const generateTestId = async (context) => {
24
12
  let testId = uuidv4();
25
13
  let free = false;
26
14
  for (let i = 0; i < MAX_TEST_ID_ATTEMPTS; i++) {
@@ -40,12 +28,24 @@ const getTestId = async (context) => {
40
28
  }
41
29
  return testId;
42
30
  };
43
- export async function request({ request: req, response: res, next, context, handler = handle, user, }) {
44
- const requestContext = {
31
+ export const factory = ({ implementation = TestAgent }) => async (params) => await handle(params, implementation);
32
+ export const handle = async ({ session: { request, response }, context }, implementation = TestAgent) => {
33
+ let parsed = await sdk.validateSchema(TestRequestSchema, request?.body ?? {});
34
+ let id = parsed.id ?? uuidv4();
35
+ parsed.id = id;
36
+ let req = parsed;
37
+ context.target = parsed.config;
38
+ req.method = 'test/invoke';
39
+ req.params = null;
40
+ const res = await implementation(req, context);
41
+ return await handleJSONRPCResponse(response, String(id), req.method, res);
42
+ };
43
+ export const request = async ({ session, context, handler = handle, user, intercepts }, implementation = TestAgent) => {
44
+ const _context = {
45
45
  ...context,
46
- agentId: await getTestId(context),
47
- requestId: generateRequestId(context, req),
48
- userId: await user?.(req),
46
+ agentId: await generateTestId(context),
47
+ requestId: generateRequestId(context, session.request),
48
+ userId: await user?.(session),
49
49
  };
50
- return await handler(req, res, next, requestContext);
51
- }
50
+ return await handler({ session, context: _context, intercepts }, implementation);
51
+ };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Copyright 2025 The Artinet Project
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+ import express from 'express';
6
+ export type Session = {
7
+ request: express.Request;
8
+ response: express.Response;
9
+ next: express.NextFunction;
10
+ };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Copyright 2025 The Artinet Project
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+ export {};
@@ -2,12 +2,8 @@
2
2
  * Copyright 2025 The Artinet Project
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import * as hono from "hono";
6
- import { RequestAgentRoute, RequestContext } from "../../routes/request/index.js";
7
- export declare const AGENT_FIELD_NAME = "agentId";
8
- export type handler = (ctx: hono.Context, next: hono.Next, context: RequestContext, request?: RequestAgentRoute["implementation"], intercepts?: RequestAgentRoute["intercept"][]) => Promise<void>;
9
- export declare function handle(ctx: hono.Context, _next: hono.Next, context: RequestContext, request?: RequestAgentRoute["implementation"], intercepts?: RequestAgentRoute["intercept"][]): Promise<void>;
10
- export declare const factory: (request?: RequestAgentRoute["implementation"], intercepts?: RequestAgentRoute["intercept"][]) => handler;
5
+ import { RequestAgentMount } from '../../routes/request/index.js';
6
+ import { Session } from './types.js';
11
7
  /**
12
8
  * Handler utilities for agent HTTP requests.
13
9
  *
@@ -19,11 +15,7 @@ export declare const factory: (request?: RequestAgentRoute["implementation"], in
19
15
  *
20
16
  * @module server/handlers/agent
21
17
  */
22
- export interface Params {
23
- ctx: hono.Context;
24
- next: hono.Next;
25
- context: Omit<RequestContext, "agentId">;
26
- handler: handler;
27
- user: (ctx: hono.Context) => Promise<string>;
28
- }
29
- export declare function request({ ctx, next, context, handler, user, }: Params): Promise<void>;
18
+ export type Mount = RequestAgentMount<Session>;
19
+ export declare const handle: Mount['handler'];
20
+ export declare const factory: Mount['factory'];
21
+ export declare const request: Mount['request'];
@@ -2,23 +2,22 @@
2
2
  * Copyright 2025 The Artinet Project
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import { INVALID_REQUEST } from "@artinet/sdk";
6
- import { RequestAgent, } from "../../routes/request/index.js";
7
- import * as sdk from "@artinet/sdk";
8
- import { handleJSONRPCResponse } from "./rpc.js";
9
- import { generateRequestId } from "./utils.js";
10
- export const AGENT_FIELD_NAME = "agentId";
11
- export async function handle(ctx, _next, context, request = RequestAgent, intercepts) {
5
+ import { INVALID_REQUEST } from '@artinet/sdk';
6
+ import { RequestAgent } from '../../routes/request/index.js';
7
+ import * as sdk from '@artinet/sdk';
8
+ import { handleJSONRPCResponse } from './rpc.js';
9
+ import { generateRequestId } from './utils.js';
10
+ import { AGENT_FIELD_NAME } from '../../default.js';
11
+ export const handle = async ({ session: { ctx }, context, intercepts }, implementation = RequestAgent) => {
12
12
  /* hono.Context.req uses a raw JSON.parse() so we prefer to use the text() and our own safeParse() */
13
13
  const body = sdk.safeParse(await ctx.req.text());
14
- const requestId = generateRequestId(context, ctx.req.header("x-request-id") ?? body?.id);
14
+ const requestId = generateRequestId(context, ctx.req.header('x-request-id') ?? body?.id);
15
15
  let parsed;
16
- if (ctx.req.path.endsWith("agent-card.json") ||
17
- ctx.req.path.endsWith("agent.json")) {
16
+ if (ctx.req.path.endsWith('agent-card.json') || ctx.req.path.endsWith('agent.json')) {
18
17
  parsed = {
19
- jsonrpc: "2.0",
18
+ jsonrpc: '2.0',
20
19
  id: requestId,
21
- method: "agentcard/get",
20
+ method: 'agentcard/get',
22
21
  params: null,
23
22
  };
24
23
  }
@@ -31,23 +30,28 @@ export async function handle(ctx, _next, context, request = RequestAgent, interc
31
30
  params: params,
32
31
  };
33
32
  sdk.logger.info(`handle agent request received:${parsed.method}:params:${sdk.formatJson(agentRequest)}`);
34
- const response = await request(agentRequest, context, intercepts);
33
+ const response = await implementation(agentRequest, context, intercepts);
35
34
  sdk.logger.info(`handle agent request completed:${parsed.method}:response:${sdk.formatJson(response)}`);
36
35
  await handleJSONRPCResponse(ctx, requestId, parsed.method, response);
37
- }
38
- export const factory = (request = RequestAgent, intercepts) => async (ctx, next, context) => await handle(ctx, next, context, request, intercepts);
39
- export async function request({ ctx, next, context, handler = handle, user, }) {
36
+ };
37
+ export const factory = ({ implementation = RequestAgent, }) => {
38
+ return async (params) => {
39
+ return await handle(params, implementation);
40
+ };
41
+ };
42
+ export const request = async ({ session, context, handler = handle, user, intercepts }, implementation = RequestAgent) => {
43
+ const { ctx } = session;
40
44
  const agentId = ctx.req.param(AGENT_FIELD_NAME);
41
45
  if (!agentId) {
42
46
  throw INVALID_REQUEST({ message: `${AGENT_FIELD_NAME} is required` });
43
47
  }
44
- /* hono.Context.req uses a raw JSON.parse() so we prefer to use the text() and our own safeParse() */
45
- const reqId = ctx.req.header("x-request-id") ?? sdk.safeParse(await ctx.req.text())?.id;
48
+ /* hono.Context.req uses a raw JSON.parse() so we prefer to use text() and our own safeParse() */
49
+ const reqId = ctx.req.header('x-request-id') ?? sdk.safeParse(await ctx.req.text())?.id;
46
50
  const requestContext = {
47
51
  ...context,
48
52
  agentId,
49
53
  requestId: generateRequestId(context, reqId),
50
- userId: await user?.(ctx),
54
+ userId: await user?.(session),
51
55
  };
52
- await handler(ctx, next, requestContext);
53
- }
56
+ return await handler({ session, context: requestContext, intercepts }, implementation);
57
+ };
@@ -2,16 +2,9 @@
2
2
  * Copyright 2025 The Artinet Project
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import * as hono from "hono";
6
- import { CreateAgentRoute } from "../../routes/create/index.js";
7
- export type handler = (ctx: hono.Context, next: hono.Next, context: CreateAgentRoute["context"], deploy?: CreateAgentRoute["implementation"]) => Promise<void>;
8
- export declare function handle(ctx: hono.Context, _next: hono.Next, context: CreateAgentRoute["context"], deploy?: CreateAgentRoute["implementation"]): Promise<void>;
9
- export declare const factory: (deploy?: CreateAgentRoute["implementation"]) => handler;
10
- export interface Params {
11
- ctx: hono.Context;
12
- next: hono.Next;
13
- context: CreateAgentRoute["context"];
14
- handler: handler;
15
- user: (ctx: hono.Context) => Promise<string>;
16
- }
17
- export declare function request({ ctx, next, context, handler, user, }: Params): Promise<void>;
5
+ import { CreateAgentMount } from '../../routes/create/index.js';
6
+ import { Session } from './types.js';
7
+ export type Mount = CreateAgentMount<Session>;
8
+ export declare const factory: Mount['factory'];
9
+ export declare const handle: Mount['handler'];
10
+ export declare const request: Mount['request'];
@@ -2,26 +2,27 @@
2
2
  * Copyright 2025 The Artinet Project
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import * as sdk from "@artinet/sdk";
6
- import { CreateAgent, CreateAgentRequestSchema, } from "../../routes/create/index.js";
7
- import { generateRequestId, generateRegistrationId } from "./utils.js";
8
- export async function handle(ctx, _next, context, deploy = CreateAgent) {
5
+ import * as sdk from '@artinet/sdk';
6
+ import { CreateAgent, CreateAgentRequestSchema, } from '../../routes/create/index.js';
7
+ import { generateRequestId, generateRegistrationId } from './utils.js';
8
+ export const factory = ({ implementation = CreateAgent }) => async (params) => await handle(params, implementation);
9
+ export const handle = async ({ session: { ctx }, context, intercepts }, implementation = CreateAgent) => {
9
10
  /* hono.Context.req uses a raw JSON.parse() so we prefer to use the text() and our own safeParse() */
10
11
  const req = sdk.safeParse(await ctx.req.text());
11
12
  const request = await sdk.validateSchema(CreateAgentRequestSchema, req);
12
13
  sdk.logger.info(`deploying agent: ${request.config.name}`);
13
14
  sdk.logger.debug(`deploying agent: ${sdk.formatJson(request)}`);
14
15
  context.registrationId = generateRegistrationId(request.config.uri);
15
- const result = await deploy(request, context);
16
+ const result = await implementation(request, context, intercepts);
16
17
  ctx.res = ctx.json(result);
17
- }
18
- export const factory = (deploy = CreateAgent) => async (ctx, next, context) => await handle(ctx, next, context, deploy);
19
- export async function request({ ctx, next, context, handler = handle, user, }) {
20
- const reqId = ctx.req.header("x-request-id") ?? sdk.safeParse(await ctx.req.text())?.id;
21
- const requestContext = {
18
+ };
19
+ export const request = async ({ session, context, handler = handle, user, intercepts }, implementation = CreateAgent) => {
20
+ const { ctx } = session;
21
+ const reqId = ctx.req.header('x-request-id') ?? sdk.safeParse(await ctx.req.text())?.id;
22
+ const _context = {
22
23
  ...context,
23
24
  requestId: generateRequestId(context, reqId),
24
- userId: await user?.(ctx),
25
+ userId: await user?.(session),
25
26
  };
26
- await handler(ctx, next, requestContext);
27
- }
27
+ await handler({ session, context: _context, intercepts }, implementation);
28
+ };
@@ -2,15 +2,13 @@
2
2
  * Copyright 2025 The Artinet Project
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import * as hono from "hono";
6
- import { ResultOrError } from "../../types.js";
7
- export declare function toJSONRPCResponse(id: string, result_or_error: ResultOrError): {
8
- jsonrpc: "2.0";
9
- id: string;
10
- result: unknown;
11
- } | {
12
- jsonrpc: "2.0";
13
- id: string;
14
- error: unknown;
15
- };
5
+ import * as hono from 'hono';
6
+ import { ResultOrError } from '../../types.js';
7
+ /**
8
+ * Handle JSON-RPC response for Hono.
9
+ *
10
+ * Used by the deployment server to provide a standard agent endpoint interface.
11
+ *
12
+ * @module server/handlers/rpc
13
+ */
16
14
  export declare function handleJSONRPCResponse(ctx: hono.Context, id: string, method: string, response: ResultOrError): Promise<void>;
@@ -2,48 +2,47 @@
2
2
  * Copyright 2025 The Artinet Project
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import * as sdk from "@artinet/sdk";
6
- import { streamSSE } from "hono/streaming";
7
- export function toJSONRPCResponse(id, result_or_error) {
8
- if (result_or_error.type === "success") {
9
- return { jsonrpc: "2.0", id, result: result_or_error.result };
10
- }
11
- if (result_or_error.type === "error") {
12
- return { jsonrpc: "2.0", id, error: result_or_error.error };
13
- }
14
- throw new Error("Invalid response type");
15
- }
5
+ import * as sdk from '@artinet/sdk';
6
+ import { streamSSE } from 'hono/streaming';
7
+ import { toJSONRPCResponse } from '../../utils.js';
8
+ /**
9
+ * Handle JSON-RPC response for Hono.
10
+ *
11
+ * Used by the deployment server to provide a standard agent endpoint interface.
12
+ *
13
+ * @module server/handlers/rpc
14
+ */
16
15
  export async function handleJSONRPCResponse(ctx, id, method, response) {
17
- if (response.type === "success" && method === "agentcard/get") {
16
+ if (response.type === 'success' && method === 'agentcard/get') {
18
17
  ctx.status(200);
19
18
  ctx.res = ctx.json(response.result);
20
19
  return;
21
20
  }
22
- if (response.type === "success") {
21
+ if (response.type === 'success') {
23
22
  ctx.status(200);
24
23
  ctx.res = ctx.json(toJSONRPCResponse(String(id), response));
25
24
  return;
26
25
  }
27
- if (response.type === "error") {
26
+ if (response.type === 'error') {
28
27
  ctx.status(500);
29
28
  ctx.res = ctx.json(toJSONRPCResponse(String(id), response));
30
29
  return;
31
30
  }
32
- if (response.type === "stream") {
31
+ if (response.type === 'stream') {
33
32
  const stream = response.stream;
34
33
  ctx.res = streamSSE(ctx, async (responseStream) => {
35
34
  for await (const data of stream) {
36
35
  responseStream.writeSSE({
37
- data: JSON.stringify({ jsonrpc: "2.0", id, result: data }),
36
+ data: JSON.stringify({ jsonrpc: '2.0', id, result: data }),
38
37
  });
39
38
  }
40
39
  responseStream.close();
41
40
  });
42
41
  ctx.status(200);
43
- ctx.res.headers.set("Content-Type", "text/event-stream");
44
- ctx.res.headers.set("Cache-Control", "no-cache");
45
- ctx.res.headers.set("Connection", "keep-alive");
42
+ ctx.res.headers.set('Content-Type', 'text/event-stream');
43
+ ctx.res.headers.set('Cache-Control', 'no-cache');
44
+ ctx.res.headers.set('Connection', 'keep-alive');
46
45
  return;
47
46
  }
48
- throw sdk.INTERNAL_ERROR({ message: "Unknown response type" });
47
+ throw sdk.INTERNAL_ERROR({ message: 'Unknown response type' });
49
48
  }