@nebutra/agent-runtime 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -676
- package/dist/adapters/index.d.ts +24 -5
- package/dist/adapters/index.js +27 -0
- package/dist/adapters/index.js.map +1 -1
- package/dist/chunk-Q62VKHIT.js +178 -0
- package/dist/chunk-Q62VKHIT.js.map +1 -0
- package/dist/{chunk-MUF7ZZTO.js → chunk-R5HOSQUW.js} +2 -1
- package/dist/{chunk-MUF7ZZTO.js.map → chunk-R5HOSQUW.js.map} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +14 -17
- package/dist/index.js.map +1 -1
- package/dist/orchestration.d.ts +42 -1
- package/dist/orchestration.js +7 -3
- package/dist/sandbox.js +1 -1
- package/package.json +80 -30
- package/.turbo/turbo-build.log +0 -130
- package/.turbo/turbo-test.log +0 -47
- package/.turbo/turbo-typecheck.log +0 -4
- package/CHANGELOG.md +0 -250
- package/dist/chunk-MX2WL43P.js +0 -90
- package/dist/chunk-MX2WL43P.js.map +0 -1
- package/examples/pulsar-quickstart.ts +0 -35
- package/examples/resume-branch.ts +0 -45
- package/examples/subagent-fanout.ts +0 -20
- package/src/adapters/dispatcher-sse.test.ts +0 -218
- package/src/adapters/dispatcher-sse.ts +0 -222
- package/src/adapters/index.ts +0 -18
- package/src/adapters/mcp-catalog.test.ts +0 -213
- package/src/adapters/mcp-catalog.ts +0 -188
- package/src/adapters/prisma-rollout.test.ts +0 -153
- package/src/adapters/prisma-rollout.ts +0 -104
- package/src/agent-runtime.test.ts +0 -176
- package/src/artifact-stream.test.ts +0 -330
- package/src/artifact-stream.ts +0 -453
- package/src/channel-gateway.test.ts +0 -432
- package/src/channel-gateway.ts +0 -357
- package/src/cli.ts +0 -49
- package/src/code-review.test.ts +0 -501
- package/src/code-review.ts +0 -495
- package/src/command-suggestions.test.ts +0 -251
- package/src/command-suggestions.ts +0 -338
- package/src/commands.test.ts +0 -184
- package/src/commands.ts +0 -140
- package/src/commit-message.test.ts +0 -249
- package/src/commit-message.ts +0 -180
- package/src/context-compaction.test.ts +0 -522
- package/src/context-compaction.ts +0 -438
- package/src/definitions.test.ts +0 -78
- package/src/definitions.ts +0 -190
- package/src/deployment-status.test.ts +0 -215
- package/src/deployment-status.ts +0 -227
- package/src/design-context.test.ts +0 -195
- package/src/design-context.ts +0 -198
- package/src/dispatcher.test.ts +0 -234
- package/src/dispatcher.ts +0 -189
- package/src/durable-turn.test.ts +0 -209
- package/src/durable-turn.ts +0 -135
- package/src/edit-planner.test.ts +0 -204
- package/src/edit-planner.ts +0 -325
- package/src/fuzzy-match.test.ts +0 -311
- package/src/fuzzy-match.ts +0 -444
- package/src/hook-pipeline.test.ts +0 -279
- package/src/hook-pipeline.ts +0 -373
- package/src/inbound-admission.test.ts +0 -394
- package/src/inbound-admission.ts +0 -246
- package/src/index.ts +0 -49
- package/src/loop.test.ts +0 -161
- package/src/loop.ts +0 -211
- package/src/mcp-bridge.test.ts +0 -165
- package/src/mcp-bridge.ts +0 -81
- package/src/memory-provider.test.ts +0 -232
- package/src/memory-provider.ts +0 -257
- package/src/model.ts +0 -168
- package/src/orchestration.test.ts +0 -53
- package/src/orchestration.ts +0 -146
- package/src/permission-ruleset.test.ts +0 -301
- package/src/permission-ruleset.ts +0 -1
- package/src/policy.ts +0 -151
- package/src/project-repo.test.ts +0 -232
- package/src/project-repo.ts +0 -311
- package/src/protocol.ts +0 -159
- package/src/pulsar.test.ts +0 -156
- package/src/pulsar.ts +0 -322
- package/src/rollout-store-persistent.test.ts +0 -217
- package/src/rollout-store-persistent.ts +0 -166
- package/src/rollout.ts +0 -150
- package/src/sandbox.ts +0 -113
- package/src/session-share.test.ts +0 -360
- package/src/session-share.ts +0 -310
- package/src/skill-distillation.test.ts +0 -177
- package/src/skill-distillation.ts +0 -369
- package/src/skills.test.ts +0 -277
- package/src/skills.ts +0 -277
- package/src/subagents.test.ts +0 -290
- package/src/subagents.ts +0 -332
- package/src/tools.test.ts +0 -12
- package/src/tools.ts +0 -129
- package/src/workbench.test.ts +0 -0
- package/src/workbench.ts +0 -0
- package/tsconfig.json +0 -12
- package/tsup.config.ts +0 -36
|
@@ -1,218 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Web-standard transport binding tests — no server, no framework.
|
|
3
|
-
*
|
|
4
|
-
* Every test constructs a `new Request(...)` and inspects a `Response` via
|
|
5
|
-
* Web-standard APIs only (`response.text()`, `response.body!.getReader()`).
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { describe, expect, it } from "vitest";
|
|
9
|
-
import { ProtocolDispatcher } from "../dispatcher";
|
|
10
|
-
import type { ThreadEvent } from "../model";
|
|
11
|
-
import { createRpcHandler, sseResponse, subscribeNotifications } from "./dispatcher-sse.js";
|
|
12
|
-
|
|
13
|
-
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
14
|
-
|
|
15
|
-
/** A dispatcher with one echo handler bound to a real registered method. */
|
|
16
|
-
function freshDispatcher(): ProtocolDispatcher {
|
|
17
|
-
const d = new ProtocolDispatcher();
|
|
18
|
-
// `thread/start` is in the method registry; echo its params back.
|
|
19
|
-
d.register("thread/start", async (params) => ({ echoed: params }));
|
|
20
|
-
return d;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function jsonRequest(body: unknown): Request {
|
|
24
|
-
return new Request("https://edge.test/rpc", {
|
|
25
|
-
method: "POST",
|
|
26
|
-
headers: { "content-type": "application/json" },
|
|
27
|
-
body: typeof body === "string" ? body : JSON.stringify(body),
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** Drain an SSE Response body into its raw decoded text. */
|
|
32
|
-
async function drainSse(res: Response): Promise<string> {
|
|
33
|
-
if (!res.body) throw new Error("SSE response body is missing");
|
|
34
|
-
const reader = res.body.getReader();
|
|
35
|
-
const decoder = new TextDecoder();
|
|
36
|
-
let out = "";
|
|
37
|
-
for (;;) {
|
|
38
|
-
const { value, done } = await reader.read();
|
|
39
|
-
if (done) break;
|
|
40
|
-
out += decoder.decode(value, { stream: true });
|
|
41
|
-
}
|
|
42
|
-
out += decoder.decode();
|
|
43
|
-
return out;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
async function* eventsOf(...events: ThreadEvent[]): AsyncIterable<ThreadEvent> {
|
|
47
|
-
for (const e of events) yield e;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// ── createRpcHandler ─────────────────────────────────────────────────────────
|
|
51
|
-
|
|
52
|
-
describe("createRpcHandler", () => {
|
|
53
|
-
it("returns a JSON-RPC success envelope (200, application/json) on happy path", async () => {
|
|
54
|
-
const handler = createRpcHandler(freshDispatcher());
|
|
55
|
-
const res = await handler(
|
|
56
|
-
jsonRequest({
|
|
57
|
-
jsonrpc: "2.0",
|
|
58
|
-
id: 1,
|
|
59
|
-
method: "thread/start",
|
|
60
|
-
tenantId: "org_123",
|
|
61
|
-
params: { hello: "world" },
|
|
62
|
-
}),
|
|
63
|
-
);
|
|
64
|
-
|
|
65
|
-
expect(res.status).toBe(200);
|
|
66
|
-
expect(res.headers.get("content-type")).toContain("application/json");
|
|
67
|
-
const body = await res.json();
|
|
68
|
-
expect(body).toEqual({
|
|
69
|
-
jsonrpc: "2.0",
|
|
70
|
-
id: 1,
|
|
71
|
-
result: { echoed: { hello: "world" } },
|
|
72
|
-
});
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
it("returns a well-formed JSON-RPC parse error (400) on malformed JSON — never throws", async () => {
|
|
76
|
-
const handler = createRpcHandler(freshDispatcher());
|
|
77
|
-
const res = await handler(jsonRequest("{ not valid json"));
|
|
78
|
-
|
|
79
|
-
expect(res.status).toBe(400);
|
|
80
|
-
expect(res.headers.get("content-type")).toContain("application/json");
|
|
81
|
-
const body = await res.json();
|
|
82
|
-
expect(body.jsonrpc).toBe("2.0");
|
|
83
|
-
expect(body.id).toBeNull();
|
|
84
|
-
expect(body.error.code).toBe(-32700);
|
|
85
|
-
expect(typeof body.error.message).toBe("string");
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
it("fails closed on a missing-tenant envelope (200 JSON-RPC business error)", async () => {
|
|
89
|
-
const handler = createRpcHandler(freshDispatcher());
|
|
90
|
-
const res = await handler(
|
|
91
|
-
jsonRequest({ jsonrpc: "2.0", id: 7, method: "thread/start", params: {} }),
|
|
92
|
-
);
|
|
93
|
-
|
|
94
|
-
// Envelope was parseable JSON → 200, but dispatch fails closed.
|
|
95
|
-
expect(res.status).toBe(200);
|
|
96
|
-
const body = await res.json();
|
|
97
|
-
expect(body.jsonrpc).toBe("2.0");
|
|
98
|
-
expect(body.error).toBeDefined();
|
|
99
|
-
expect(body.error.code).toBe(-32600);
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
it("returns method-not-found JSON-RPC error for an unknown method", async () => {
|
|
103
|
-
const handler = createRpcHandler(freshDispatcher());
|
|
104
|
-
const res = await handler(
|
|
105
|
-
jsonRequest({ jsonrpc: "2.0", id: 9, method: "totally/unknown", tenantId: "org_1" }),
|
|
106
|
-
);
|
|
107
|
-
expect(res.status).toBe(200);
|
|
108
|
-
const body = await res.json();
|
|
109
|
-
expect(body.error.code).toBe(-32601);
|
|
110
|
-
});
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
// ── sseResponse ──────────────────────────────────────────────────────────────
|
|
114
|
-
|
|
115
|
-
describe("sseResponse", () => {
|
|
116
|
-
it("sets text/event-stream + no-cache headers", () => {
|
|
117
|
-
const res = sseResponse(eventsOf({ type: "turn.started" }));
|
|
118
|
-
expect(res.status).toBe(200);
|
|
119
|
-
expect(res.headers.get("content-type")).toContain("text/event-stream");
|
|
120
|
-
expect(res.headers.get("cache-control")).toContain("no-cache");
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
it("streams multiple events in order with correct SSE framing", async () => {
|
|
124
|
-
const stream = eventsOf(
|
|
125
|
-
{ type: "thread.started", threadId: "t1" },
|
|
126
|
-
{ type: "turn.started" },
|
|
127
|
-
{
|
|
128
|
-
type: "turn.completed",
|
|
129
|
-
usage: { inputTokens: 1, cachedInputTokens: 0, outputTokens: 2, reasoningOutputTokens: 0 },
|
|
130
|
-
},
|
|
131
|
-
);
|
|
132
|
-
const text = await drainSse(sseResponse(stream));
|
|
133
|
-
|
|
134
|
-
const frames = text.split("\n\n").filter(Boolean);
|
|
135
|
-
expect(frames).toHaveLength(3);
|
|
136
|
-
expect(frames[0]).toBe(
|
|
137
|
-
`event: thread.started\ndata: ${JSON.stringify({ type: "thread.started", threadId: "t1" })}`,
|
|
138
|
-
);
|
|
139
|
-
expect(frames[1]).toBe(
|
|
140
|
-
`event: turn.started\ndata: ${JSON.stringify({ type: "turn.started" })}`,
|
|
141
|
-
);
|
|
142
|
-
expect((frames[2] ?? "").startsWith("event: turn.completed\n")).toBe(true);
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
it("surfaces a mid-stream iterable error as a final `event: error` frame then closes", async () => {
|
|
146
|
-
async function* boom(): AsyncIterable<ThreadEvent> {
|
|
147
|
-
yield { type: "turn.started" };
|
|
148
|
-
throw new Error("upstream exploded");
|
|
149
|
-
}
|
|
150
|
-
const text = await drainSse(sseResponse(boom()));
|
|
151
|
-
const frames = text.split("\n\n").filter(Boolean);
|
|
152
|
-
|
|
153
|
-
expect(frames[0]).toBe(
|
|
154
|
-
`event: turn.started\ndata: ${JSON.stringify({ type: "turn.started" })}`,
|
|
155
|
-
);
|
|
156
|
-
const last = frames.at(-1) ?? "";
|
|
157
|
-
expect(last.startsWith("event: error\n")).toBe(true);
|
|
158
|
-
expect(last).toContain("upstream exploded");
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
it("cancels promptly when the provided AbortSignal aborts", async () => {
|
|
162
|
-
const ac = new AbortController();
|
|
163
|
-
let produced = 0;
|
|
164
|
-
async function* infinite(): AsyncIterable<ThreadEvent> {
|
|
165
|
-
for (;;) {
|
|
166
|
-
produced += 1;
|
|
167
|
-
yield { type: "turn.started" };
|
|
168
|
-
if (produced === 2) ac.abort();
|
|
169
|
-
await new Promise((r) => setTimeout(r, 1));
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
const res = sseResponse(infinite(), { signal: ac.signal });
|
|
173
|
-
const text = await drainSse(res);
|
|
174
|
-
// Stream terminated; did not run forever.
|
|
175
|
-
expect(text.length).toBeGreaterThan(0);
|
|
176
|
-
expect(produced).toBeLessThan(50);
|
|
177
|
-
});
|
|
178
|
-
|
|
179
|
-
it("does not throw when aborted before the first read", async () => {
|
|
180
|
-
const ac = new AbortController();
|
|
181
|
-
ac.abort();
|
|
182
|
-
const res = sseResponse(eventsOf({ type: "turn.started" }), { signal: ac.signal });
|
|
183
|
-
const text = await drainSse(res);
|
|
184
|
-
expect(typeof text).toBe("string");
|
|
185
|
-
});
|
|
186
|
-
});
|
|
187
|
-
|
|
188
|
-
// ── subscribeNotifications ───────────────────────────────────────────────────
|
|
189
|
-
|
|
190
|
-
describe("subscribeNotifications", () => {
|
|
191
|
-
it("bridges dispatcher notifications into an async iterable", async () => {
|
|
192
|
-
const d = new ProtocolDispatcher();
|
|
193
|
-
const iter = subscribeNotifications(d, ["turn/started", "turn/completed"]);
|
|
194
|
-
const reader = iter[Symbol.asyncIterator]();
|
|
195
|
-
|
|
196
|
-
queueMicrotask(() => {
|
|
197
|
-
d.emitNotification("turn/started", { a: 1 });
|
|
198
|
-
d.emitNotification("turn/completed", { b: 2 });
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
const first = await reader.next();
|
|
202
|
-
const second = await reader.next();
|
|
203
|
-
expect(first.value).toEqual({ name: "turn/started", payload: { a: 1 } });
|
|
204
|
-
expect(second.value).toEqual({ name: "turn/completed", payload: { b: 2 } });
|
|
205
|
-
|
|
206
|
-
await reader.return?.();
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
it("stops yielding after return() unsubscribes", async () => {
|
|
210
|
-
const d = new ProtocolDispatcher();
|
|
211
|
-
const iter = subscribeNotifications(d, ["turn/started"]);
|
|
212
|
-
const reader = iter[Symbol.asyncIterator]();
|
|
213
|
-
const done = await reader.return?.();
|
|
214
|
-
expect(done?.done).toBe(true);
|
|
215
|
-
// Emitting after teardown must not throw or buffer indefinitely.
|
|
216
|
-
expect(() => d.emitNotification("turn/started", {})).not.toThrow();
|
|
217
|
-
});
|
|
218
|
-
});
|
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Runtime-agnostic SSE / HTTP transport binding for `ProtocolDispatcher`.
|
|
3
|
-
*
|
|
4
|
-
* Built on Web-standard primitives ONLY — `Request`, `Response`,
|
|
5
|
-
* `ReadableStream`, `TextEncoder`, `AbortSignal`. There is no Hono / Express /
|
|
6
|
-
* `node:http` dependency, so the same code runs unchanged on edge runtimes,
|
|
7
|
-
* Cloudflare Workers, Deno, Bun, and Node (>=18, where these globals exist).
|
|
8
|
-
*
|
|
9
|
-
* Design goals:
|
|
10
|
-
* - Pure functions returning Web objects; nothing is mutated in place.
|
|
11
|
-
* - The dispatcher already fails closed on a missing `tenantId` (its
|
|
12
|
-
* `requestEnvelopeSchema` makes `tenantId` mandatory). This binding does
|
|
13
|
-
* not re-implement that policy — it faithfully relays the JSON-RPC error.
|
|
14
|
-
* - Never throw across the transport boundary and never leak a stack trace:
|
|
15
|
-
* a malformed body becomes a well-formed JSON-RPC parse error.
|
|
16
|
-
*
|
|
17
|
-
* Wire framing (SSE): each event is emitted as
|
|
18
|
-
* `event: <ThreadEvent.type>\n` + `data: <JSON(event)>\n\n`
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
import type { ProtocolDispatcher } from "../dispatcher";
|
|
22
|
-
import type { ThreadEvent } from "../model";
|
|
23
|
-
import type { NotificationName } from "../protocol";
|
|
24
|
-
|
|
25
|
-
// ── JSON-RPC constants ───────────────────────────────────────────────────────
|
|
26
|
-
|
|
27
|
-
/** Spec code for "Parse error" — the request body was not valid JSON. */
|
|
28
|
-
const ERR_PARSE = -32700;
|
|
29
|
-
|
|
30
|
-
const JSON_HEADERS: Readonly<Record<string, string>> = {
|
|
31
|
-
"content-type": "application/json; charset=utf-8",
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
/** A self-contained JSON-RPC failure envelope (used only for parse errors;
|
|
35
|
-
* every other failure path is produced by the dispatcher itself). */
|
|
36
|
-
function parseErrorEnvelope(message: string): {
|
|
37
|
-
readonly jsonrpc: "2.0";
|
|
38
|
-
readonly id: null;
|
|
39
|
-
readonly error: { readonly code: number; readonly message: string };
|
|
40
|
-
} {
|
|
41
|
-
return { jsonrpc: "2.0", id: null, error: { code: ERR_PARSE, message } };
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function jsonResponse(payload: unknown, status: number): Response {
|
|
45
|
-
return new Response(JSON.stringify(payload), { status, headers: { ...JSON_HEADERS } });
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// ── HTTP / JSON-RPC handler ──────────────────────────────────────────────────
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Build a Web-standard request handler bound to a dispatcher.
|
|
52
|
-
*
|
|
53
|
-
* Contract:
|
|
54
|
-
* - Unparseable body → `400` with a JSON-RPC parse-error envelope.
|
|
55
|
-
* - Any parseable body (incl. missing tenant / unknown method / handler
|
|
56
|
-
* failure) → `200` with the dispatcher's own JSON-RPC envelope. The HTTP
|
|
57
|
-
* layer stays `200` for business-level JSON-RPC errors per JSON-RPC-over-
|
|
58
|
-
* HTTP convention; the error lives in the envelope, not the status line.
|
|
59
|
-
* - The returned function never throws and never emits a 500-with-stack.
|
|
60
|
-
*/
|
|
61
|
-
export function createRpcHandler(
|
|
62
|
-
dispatcher: ProtocolDispatcher,
|
|
63
|
-
): (request: Request) => Promise<Response> {
|
|
64
|
-
return async (request: Request): Promise<Response> => {
|
|
65
|
-
let raw: unknown;
|
|
66
|
-
try {
|
|
67
|
-
raw = await request.json();
|
|
68
|
-
} catch {
|
|
69
|
-
return jsonResponse(parseErrorEnvelope("Request body is not valid JSON"), 400);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
// `dispatch` is documented to never throw; the try/catch is defence in
|
|
73
|
-
// depth so the transport boundary is total under any future change.
|
|
74
|
-
try {
|
|
75
|
-
const envelope = await dispatcher.dispatch(raw);
|
|
76
|
-
return jsonResponse(envelope, 200);
|
|
77
|
-
} catch {
|
|
78
|
-
return jsonResponse(parseErrorEnvelope("Dispatcher failure"), 400);
|
|
79
|
-
}
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// ── SSE streaming ────────────────────────────────────────────────────────────
|
|
84
|
-
|
|
85
|
-
export interface SseOptions {
|
|
86
|
-
/** Cancels the stream cleanly; closing the consumer also cancels it. */
|
|
87
|
-
readonly signal?: AbortSignal;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** Encode one `ThreadEvent` as a single SSE frame. */
|
|
91
|
-
function frame(event: ThreadEvent): string {
|
|
92
|
-
return `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** Encode a terminal transport-level error as an `event: error` SSE frame. */
|
|
96
|
-
function errorFrame(message: string): string {
|
|
97
|
-
return `event: error\ndata: ${JSON.stringify({ type: "error", message })}\n\n`;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Adapt an async `ThreadEvent` stream into a Web-standard
|
|
102
|
-
* `text/event-stream` `Response`.
|
|
103
|
-
*
|
|
104
|
-
* Guarantees:
|
|
105
|
-
* - Incremental flush: each event is enqueued as soon as it is produced.
|
|
106
|
-
* - Clean termination: the stream closes when the iterable is exhausted.
|
|
107
|
-
* - Error surfacing: an iterable error is emitted as a final
|
|
108
|
-
* `event: error` frame, then the stream closes (it never hangs).
|
|
109
|
-
* - Cancellation: an aborted `signal` (or a cancelled reader) stops
|
|
110
|
-
* pulling from the source and releases its iterator.
|
|
111
|
-
*/
|
|
112
|
-
export function sseResponse(stream: AsyncIterable<ThreadEvent>, opts?: SseOptions): Response {
|
|
113
|
-
const encoder = new TextEncoder();
|
|
114
|
-
const signal = opts?.signal;
|
|
115
|
-
|
|
116
|
-
const body = new ReadableStream<Uint8Array>({
|
|
117
|
-
async start(controller) {
|
|
118
|
-
const iterator = stream[Symbol.asyncIterator]();
|
|
119
|
-
|
|
120
|
-
const onAbort = () => {
|
|
121
|
-
void iterator.return?.(undefined);
|
|
122
|
-
};
|
|
123
|
-
if (signal) {
|
|
124
|
-
if (signal.aborted) {
|
|
125
|
-
await iterator.return?.(undefined);
|
|
126
|
-
controller.close();
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
try {
|
|
133
|
-
for (;;) {
|
|
134
|
-
if (signal?.aborted) break;
|
|
135
|
-
const next = await iterator.next();
|
|
136
|
-
if (next.done) break;
|
|
137
|
-
controller.enqueue(encoder.encode(frame(next.value)));
|
|
138
|
-
}
|
|
139
|
-
} catch (error) {
|
|
140
|
-
const message = error instanceof Error ? error.message : "Stream error";
|
|
141
|
-
controller.enqueue(encoder.encode(errorFrame(message)));
|
|
142
|
-
} finally {
|
|
143
|
-
signal?.removeEventListener("abort", onAbort);
|
|
144
|
-
controller.close();
|
|
145
|
-
}
|
|
146
|
-
},
|
|
147
|
-
cancel() {
|
|
148
|
-
// Consumer hung up: best-effort release of the upstream iterator.
|
|
149
|
-
void stream[Symbol.asyncIterator]().return?.(undefined);
|
|
150
|
-
},
|
|
151
|
-
});
|
|
152
|
-
|
|
153
|
-
return new Response(body, {
|
|
154
|
-
status: 200,
|
|
155
|
-
headers: {
|
|
156
|
-
"content-type": "text/event-stream; charset=utf-8",
|
|
157
|
-
"cache-control": "no-cache, no-transform",
|
|
158
|
-
connection: "keep-alive",
|
|
159
|
-
},
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// ── Notification → async-iterable bridge ─────────────────────────────────────
|
|
164
|
-
|
|
165
|
-
export interface NotificationFrame {
|
|
166
|
-
readonly name: NotificationName;
|
|
167
|
-
readonly payload: unknown;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/**
|
|
171
|
-
* Bridge `dispatcher.onNotification` (a push listener API) into a pull-based
|
|
172
|
-
* `AsyncIterable`. A bounded backlog buffers events that arrive between
|
|
173
|
-
* `next()` calls; pending readers are resolved immediately when an event
|
|
174
|
-
* arrives. Calling `return()` (or breaking a `for await`) unsubscribes every
|
|
175
|
-
* underlying listener — no leaks, fail-closed teardown.
|
|
176
|
-
*/
|
|
177
|
-
export function subscribeNotifications(
|
|
178
|
-
dispatcher: ProtocolDispatcher,
|
|
179
|
-
names: readonly NotificationName[],
|
|
180
|
-
): AsyncIterable<NotificationFrame> {
|
|
181
|
-
return {
|
|
182
|
-
[Symbol.asyncIterator](): AsyncIterator<NotificationFrame> {
|
|
183
|
-
const backlog: NotificationFrame[] = [];
|
|
184
|
-
const waiters: Array<(r: IteratorResult<NotificationFrame>) => void> = [];
|
|
185
|
-
let closed = false;
|
|
186
|
-
|
|
187
|
-
const unsubscribers = names.map((name) =>
|
|
188
|
-
dispatcher.onNotification(name, (payload) => {
|
|
189
|
-
if (closed) return;
|
|
190
|
-
const value: NotificationFrame = { name, payload };
|
|
191
|
-
const waiter = waiters.shift();
|
|
192
|
-
if (waiter) waiter({ value, done: false });
|
|
193
|
-
else backlog.push(value);
|
|
194
|
-
}),
|
|
195
|
-
);
|
|
196
|
-
|
|
197
|
-
const teardown = (): void => {
|
|
198
|
-
if (closed) return;
|
|
199
|
-
closed = true;
|
|
200
|
-
for (const off of unsubscribers) off();
|
|
201
|
-
let waiter = waiters.shift();
|
|
202
|
-
while (waiter) {
|
|
203
|
-
waiter({ value: undefined, done: true });
|
|
204
|
-
waiter = waiters.shift();
|
|
205
|
-
}
|
|
206
|
-
};
|
|
207
|
-
|
|
208
|
-
return {
|
|
209
|
-
next(): Promise<IteratorResult<NotificationFrame>> {
|
|
210
|
-
const buffered = backlog.shift();
|
|
211
|
-
if (buffered) return Promise.resolve({ value: buffered, done: false });
|
|
212
|
-
if (closed) return Promise.resolve({ value: undefined, done: true });
|
|
213
|
-
return new Promise((resolve) => waiters.push(resolve));
|
|
214
|
-
},
|
|
215
|
-
return(): Promise<IteratorResult<NotificationFrame>> {
|
|
216
|
-
teardown();
|
|
217
|
-
return Promise.resolve({ value: undefined, done: true });
|
|
218
|
-
},
|
|
219
|
-
};
|
|
220
|
-
},
|
|
221
|
-
};
|
|
222
|
-
}
|
package/src/adapters/index.ts
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @nebutra/agent-runtime/adapters — concrete, reusable port adapters.
|
|
3
|
-
*
|
|
4
|
-
* The root runtime keeps its pure grammar and injectable ports. These subpath
|
|
5
|
-
* exports supply concrete wirings so apps/backends reuse them instead of
|
|
6
|
-
* re-implementing glue:
|
|
7
|
-
*
|
|
8
|
-
* - `./mcp-catalog` — McpServerCatalogPort + McpClientLike over @nebutra/mcp
|
|
9
|
-
* - `./dispatcher-sse` — runtime-agnostic SSE transport for ProtocolDispatcher
|
|
10
|
-
*
|
|
11
|
-
* The durable rollout-store backend adapter is pending a governance decision
|
|
12
|
-
* (a correct system-of-record needs a fail-loud datastore; @nebutra/audit's
|
|
13
|
-
* log() swallows transient failures and is not suitable as source-of-truth).
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
export * from "./dispatcher-sse.js";
|
|
17
|
-
export * from "./mcp-catalog.js";
|
|
18
|
-
export * from "./prisma-rollout.js";
|
|
@@ -1,213 +0,0 @@
|
|
|
1
|
-
import type { MCPContext, ToolExecutionResult } from "@nebutra/mcp";
|
|
2
|
-
import { MCPServerRegistry } from "@nebutra/mcp";
|
|
3
|
-
import { describe, expect, it, vi } from "vitest";
|
|
4
|
-
import type { z } from "zod";
|
|
5
|
-
import { activateMcpTools, type McpServerCatalogPort } from "../mcp-bridge";
|
|
6
|
-
import { ToolRegistry } from "../tools";
|
|
7
|
-
|
|
8
|
-
import { createMcpClientPort, createMcpServerCatalog } from "./mcp-catalog.js";
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Build a fresh, isolated registry seeded with two servers gated by plan and
|
|
12
|
-
* tenant. No network — `local` transport with in-process handlers.
|
|
13
|
-
*/
|
|
14
|
-
function seedRegistry(): MCPServerRegistry {
|
|
15
|
-
const registry = new MCPServerRegistry();
|
|
16
|
-
|
|
17
|
-
registry.register({
|
|
18
|
-
id: "weather",
|
|
19
|
-
name: "Weather",
|
|
20
|
-
description: "Weather tools",
|
|
21
|
-
endpoint: "local://weather",
|
|
22
|
-
transport: "local",
|
|
23
|
-
tools: [
|
|
24
|
-
{
|
|
25
|
-
name: "forecast",
|
|
26
|
-
description: "Get a forecast",
|
|
27
|
-
parameters: {
|
|
28
|
-
city: { type: "string", description: "City name", required: true },
|
|
29
|
-
days: { type: "number", description: "Day count" },
|
|
30
|
-
},
|
|
31
|
-
},
|
|
32
|
-
{
|
|
33
|
-
name: "alerts",
|
|
34
|
-
description: "Severe weather alerts (pro only)",
|
|
35
|
-
allowedPlans: ["pro", "enterprise"],
|
|
36
|
-
},
|
|
37
|
-
],
|
|
38
|
-
handlers: {
|
|
39
|
-
forecast: (args) => ({ ok: true, echo: args }),
|
|
40
|
-
alerts: () => ({ ok: true, alerts: [] }),
|
|
41
|
-
},
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
registry.register({
|
|
45
|
-
id: "acme-private",
|
|
46
|
-
name: "Acme Private",
|
|
47
|
-
description: "Tenant-scoped server",
|
|
48
|
-
endpoint: "local://acme",
|
|
49
|
-
transport: "local",
|
|
50
|
-
allowedTenants: ["tenant-acme"],
|
|
51
|
-
tools: [{ name: "acme_secret", description: "Acme-only tool" }],
|
|
52
|
-
handlers: { acme_secret: () => ({ ok: true }) },
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
return registry;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
describe("createMcpServerCatalog", () => {
|
|
59
|
-
it("fails closed on empty tenantId before touching the registry", async () => {
|
|
60
|
-
const registry = new MCPServerRegistry();
|
|
61
|
-
const spy = vi.spyOn(registry, "getAccessibleTools");
|
|
62
|
-
const catalog = createMcpServerCatalog(registry);
|
|
63
|
-
|
|
64
|
-
await expect(catalog.listTools({ tenantId: "" })).rejects.toThrow();
|
|
65
|
-
await expect(catalog.listTools({ tenantId: " " })).rejects.toThrow();
|
|
66
|
-
expect(spy).not.toHaveBeenCalled();
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
it("plan-gates: a free tenant sees fewer tools than a pro tenant", async () => {
|
|
70
|
-
const catalog = createMcpServerCatalog(seedRegistry());
|
|
71
|
-
|
|
72
|
-
const free = await catalog.listTools({ tenantId: "tenant-1", plan: "free" });
|
|
73
|
-
const pro = await catalog.listTools({ tenantId: "tenant-1", plan: "pro" });
|
|
74
|
-
|
|
75
|
-
const freeNames = free.map((e) => e.definition.name).sort();
|
|
76
|
-
const proNames = pro.map((e) => e.definition.name).sort();
|
|
77
|
-
|
|
78
|
-
expect(freeNames).toEqual(["forecast"]);
|
|
79
|
-
expect(proNames).toEqual(["alerts", "forecast"]);
|
|
80
|
-
expect(pro.length).toBeGreaterThan(free.length);
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
it("isolates tenants: only the allowed tenant sees its private server", async () => {
|
|
84
|
-
const catalog = createMcpServerCatalog(seedRegistry());
|
|
85
|
-
|
|
86
|
-
const other = await catalog.listTools({ tenantId: "tenant-other", plan: "enterprise" });
|
|
87
|
-
const acme = await catalog.listTools({ tenantId: "tenant-acme", plan: "enterprise" });
|
|
88
|
-
|
|
89
|
-
expect(other.map((e) => e.definition.name)).not.toContain("acme_secret");
|
|
90
|
-
expect(acme.map((e) => e.definition.name)).toContain("acme_secret");
|
|
91
|
-
});
|
|
92
|
-
|
|
93
|
-
it("produces a usable ToolDefinition even for a schema-less MCP tool", async () => {
|
|
94
|
-
const catalog = createMcpServerCatalog(seedRegistry());
|
|
95
|
-
const pro = await catalog.listTools({ tenantId: "tenant-1", plan: "pro" });
|
|
96
|
-
|
|
97
|
-
const alerts = pro.find((e) => e.definition.name === "alerts");
|
|
98
|
-
expect(alerts).toBeDefined();
|
|
99
|
-
// No `parameters` → permissive object schema, never throws on parse.
|
|
100
|
-
expect(() => alerts?.definition.inputSchema.parse({})).not.toThrow();
|
|
101
|
-
expect(() => alerts?.definition.inputSchema.parse({ anything: 1 })).not.toThrow();
|
|
102
|
-
expect(alerts?.server).toBe("weather");
|
|
103
|
-
});
|
|
104
|
-
|
|
105
|
-
it("derives a Zod schema from MCP `parameters`", async () => {
|
|
106
|
-
const catalog = createMcpServerCatalog(seedRegistry());
|
|
107
|
-
const free = await catalog.listTools({ tenantId: "tenant-1", plan: "free" });
|
|
108
|
-
const forecast = free.find((e) => e.definition.name === "forecast");
|
|
109
|
-
|
|
110
|
-
expect(forecast).toBeDefined();
|
|
111
|
-
if (!forecast) throw new Error("forecast tool missing");
|
|
112
|
-
const schema = forecast.definition.inputSchema as z.ZodType;
|
|
113
|
-
// Required `city` enforced.
|
|
114
|
-
expect(() => schema.parse({})).toThrow();
|
|
115
|
-
expect(schema.parse({ city: "NYC" })).toMatchObject({ city: "NYC" });
|
|
116
|
-
expect(schema.parse({ city: "NYC", days: 3 })).toMatchObject({ days: 3 });
|
|
117
|
-
});
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
describe("createMcpClientPort", () => {
|
|
121
|
-
it("forwards tenantId into the MCPContext and unwraps the result envelope", async () => {
|
|
122
|
-
let seen: MCPContext | undefined;
|
|
123
|
-
const fake = {
|
|
124
|
-
async executeTool(
|
|
125
|
-
_name: string,
|
|
126
|
-
_args: Record<string, unknown>,
|
|
127
|
-
ctx: MCPContext,
|
|
128
|
-
): Promise<ToolExecutionResult> {
|
|
129
|
-
seen = ctx;
|
|
130
|
-
return { success: true, result: { value: 42 }, duration: 1 };
|
|
131
|
-
},
|
|
132
|
-
};
|
|
133
|
-
|
|
134
|
-
const port = createMcpClientPort(fake);
|
|
135
|
-
const out = await port.executeTool(
|
|
136
|
-
"forecast",
|
|
137
|
-
{ city: "NYC" },
|
|
138
|
-
{
|
|
139
|
-
requestId: "req-1",
|
|
140
|
-
tenantId: "tenant-xyz",
|
|
141
|
-
},
|
|
142
|
-
);
|
|
143
|
-
|
|
144
|
-
expect(out).toEqual({ value: 42 });
|
|
145
|
-
expect(seen?.tenantId).toBe("tenant-xyz");
|
|
146
|
-
expect(seen?.requestId).toBe("req-1");
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
it("fails closed when the MCP client reports failure", async () => {
|
|
150
|
-
const fake = {
|
|
151
|
-
async executeTool(): Promise<ToolExecutionResult> {
|
|
152
|
-
return { success: false, error: "Access denied", duration: 1 };
|
|
153
|
-
},
|
|
154
|
-
};
|
|
155
|
-
const port = createMcpClientPort(fake);
|
|
156
|
-
|
|
157
|
-
await expect(port.executeTool("x", {}, { requestId: "r", tenantId: "t" })).rejects.toThrow(
|
|
158
|
-
/Access denied/,
|
|
159
|
-
);
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
it("rejects an empty tenantId at the client boundary (fail-closed)", async () => {
|
|
163
|
-
const fake = {
|
|
164
|
-
executeTool: vi.fn(
|
|
165
|
-
async (): Promise<ToolExecutionResult> => ({
|
|
166
|
-
success: true,
|
|
167
|
-
result: null,
|
|
168
|
-
duration: 0,
|
|
169
|
-
}),
|
|
170
|
-
),
|
|
171
|
-
};
|
|
172
|
-
const port = createMcpClientPort(fake);
|
|
173
|
-
|
|
174
|
-
await expect(port.executeTool("x", {}, { requestId: "r", tenantId: "" })).rejects.toThrow();
|
|
175
|
-
expect(fake.executeTool).not.toHaveBeenCalled();
|
|
176
|
-
});
|
|
177
|
-
});
|
|
178
|
-
|
|
179
|
-
describe("composition with agent-runtime activateMcpTools", () => {
|
|
180
|
-
it("registers catalog tools into a ToolRegistry and dispatches through the client port", async () => {
|
|
181
|
-
const catalog: McpServerCatalogPort = createMcpServerCatalog(seedRegistry());
|
|
182
|
-
const calls: { name: string; ctx: MCPContext }[] = [];
|
|
183
|
-
const client = createMcpClientPort({
|
|
184
|
-
async executeTool(
|
|
185
|
-
name: string,
|
|
186
|
-
args: Record<string, unknown>,
|
|
187
|
-
ctx: MCPContext,
|
|
188
|
-
): Promise<ToolExecutionResult> {
|
|
189
|
-
calls.push({ name, ctx });
|
|
190
|
-
return { success: true, result: { echoed: args }, duration: 1 };
|
|
191
|
-
},
|
|
192
|
-
});
|
|
193
|
-
|
|
194
|
-
const registry = new ToolRegistry();
|
|
195
|
-
const result = await activateMcpTools(registry, catalog, client, {
|
|
196
|
-
tenantId: "tenant-1",
|
|
197
|
-
plan: "pro",
|
|
198
|
-
});
|
|
199
|
-
|
|
200
|
-
expect([...result.registered].sort()).toEqual(["alerts", "forecast"]);
|
|
201
|
-
expect(result.skipped).toEqual([]);
|
|
202
|
-
|
|
203
|
-
const out = await registry.dispatch(
|
|
204
|
-
"forecast",
|
|
205
|
-
{ city: "NYC" },
|
|
206
|
-
{ tenantId: "tenant-1", threadId: "thread-1" },
|
|
207
|
-
);
|
|
208
|
-
|
|
209
|
-
expect(out).toEqual({ echoed: { city: "NYC" } });
|
|
210
|
-
expect(calls).toHaveLength(1);
|
|
211
|
-
expect(calls[0]?.ctx.tenantId).toBe("tenant-1");
|
|
212
|
-
});
|
|
213
|
-
});
|