@valethq/sdk 0.0.0-stage → 0.2.0

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/src/mcp.ts ADDED
@@ -0,0 +1,248 @@
1
+ import { randomUUID, timingSafeEqual } from "node:crypto";
2
+ import type { HttpHost } from "./http";
3
+ import type { ToolSurface } from "./inference";
4
+ import type { ToolResult } from "./tools";
5
+
6
+ /** The MCP server entry a harness connects to: Streamable HTTP, bearer token in the headers. */
7
+ export interface McpServerEntry {
8
+ name: string;
9
+ url: string;
10
+ headers: Record<string, string>;
11
+ }
12
+
13
+ export interface ToolEndpointOptions {
14
+ serverName: string;
15
+ version: string;
16
+ /** Reads a blob's bytes, so image results can go to the harness inline. Without it they are placeholders. */
17
+ readBlob?(blobId: string): Promise<Uint8Array>;
18
+ }
19
+
20
+ export interface ToolEndpoint {
21
+ /** Serves `surface` to one session at a token-guarded URL on the plugin's own route, and returns how to reach it. */
22
+ expose(sessionId: string, surface: ToolSurface): McpServerEntry;
23
+ /** Stops serving the session. Its token stops working. */
24
+ revoke(sessionId: string): void;
25
+ }
26
+
27
+ const PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
28
+
29
+ interface Exposure {
30
+ token: string;
31
+ surface: ToolSurface;
32
+ }
33
+
34
+ class RpcError extends Error {
35
+ constructor(
36
+ readonly code: number,
37
+ message: string,
38
+ ) {
39
+ super(message);
40
+ }
41
+ }
42
+
43
+ async function toMcpResult(result: ToolResult, readBlob: ToolEndpointOptions["readBlob"]) {
44
+ const content = await Promise.all(
45
+ result.content.map(async (c) => {
46
+ if (c.type === "text") return c;
47
+ if (!readBlob) return { type: "text", text: `[image ${c.mime} blob ${c.blobId}]` };
48
+ const bytes = await readBlob(c.blobId);
49
+ return { type: "image", data: Buffer.from(bytes).toString("base64"), mimeType: c.mime };
50
+ }),
51
+ );
52
+ return { content, ...(result.isError ? { isError: true } : {}) };
53
+ }
54
+
55
+ /**
56
+ * Serves a session's ToolSurface as an MCP server (Streamable HTTP: JSON replies, or SSE for tool calls when
57
+ * the client accepts it). Each plugin that
58
+ * talks to an MCP-speaking harness mounts one of these on its own route, so the plugin serves the tools
59
+ * itself and valet's core stays out of the transport.
60
+ */
61
+ export function toolEndpoint(http: HttpHost, opts: ToolEndpointOptions): ToolEndpoint {
62
+ const sessions = new Map<string, Exposure>();
63
+ const bearer = (token: string) => `Bearer ${token}`;
64
+
65
+ http.route(
66
+ "POST",
67
+ "/mcp/:sessionId",
68
+ (req, { params }) => serve(req, sessions.get(params.sessionId ?? "")),
69
+ { public: true },
70
+ );
71
+ http.route(
72
+ "GET",
73
+ "/mcp/:sessionId",
74
+ () => new Response(null, { status: 405, headers: { allow: "POST" } }),
75
+ {
76
+ public: true,
77
+ },
78
+ );
79
+
80
+ const serve = async (req: Request, exposure: Exposure | undefined): Promise<Response> => {
81
+ if (!exposure || !authorized(exposure.token, req.headers.get("authorization"))) {
82
+ return Response.json(
83
+ { error: { code: "unauthorized", message: "bad or missing MCP token" } },
84
+ { status: 401 },
85
+ );
86
+ }
87
+ let body: unknown;
88
+ try {
89
+ body = await req.json();
90
+ } catch {
91
+ return Response.json(
92
+ { jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } },
93
+ { status: 400 },
94
+ );
95
+ }
96
+ const batch = Array.isArray(body);
97
+ const messages: unknown[] = Array.isArray(body) ? body : [body];
98
+ const run = async () => {
99
+ const replies: unknown[] = [];
100
+ for (const msg of messages) {
101
+ const reply = await dispatch(exposure.surface, msg, req.signal);
102
+ if (reply) replies.push(reply);
103
+ }
104
+ return replies;
105
+ };
106
+ if (streams(req, messages)) return sse(run(), req.signal);
107
+ const replies = await run();
108
+ if (replies.length === 0) return new Response(null, { status: 202 });
109
+ return Response.json(batch ? replies : replies[0]);
110
+ };
111
+
112
+ const dispatch = async (surface: ToolSurface, msg: unknown, signal: AbortSignal) => {
113
+ const m = msg as {
114
+ jsonrpc?: unknown;
115
+ id?: string | number;
116
+ method?: unknown;
117
+ params?: Record<string, unknown>;
118
+ };
119
+ if (m?.jsonrpc !== "2.0" || typeof m.method !== "string") {
120
+ return { jsonrpc: "2.0", id: null, error: { code: -32600, message: "invalid request" } };
121
+ }
122
+ if (m.id === undefined) return undefined; // notification
123
+ try {
124
+ const result = await method(surface, m.method, m.params ?? {}, signal);
125
+ return { jsonrpc: "2.0", id: m.id, result };
126
+ } catch (error) {
127
+ const code = error instanceof RpcError ? error.code : -32603;
128
+ return {
129
+ jsonrpc: "2.0",
130
+ id: m.id,
131
+ error: { code, message: error instanceof Error ? error.message : String(error) },
132
+ };
133
+ }
134
+ };
135
+
136
+ const method = async (
137
+ surface: ToolSurface,
138
+ name: string,
139
+ params: Record<string, unknown>,
140
+ signal: AbortSignal,
141
+ ) => {
142
+ switch (name) {
143
+ case "initialize": {
144
+ const asked = params.protocolVersion;
145
+ return {
146
+ protocolVersion:
147
+ typeof asked === "string" && PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
148
+ capabilities: { tools: { listChanged: false } },
149
+ serverInfo: { name: opts.serverName, version: opts.version },
150
+ };
151
+ }
152
+ case "ping":
153
+ return {};
154
+ case "tools/list":
155
+ return {
156
+ tools: surface
157
+ .list()
158
+ .map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
159
+ };
160
+ case "tools/call": {
161
+ const tool = params.name;
162
+ if (typeof tool !== "string") throw new RpcError(-32602, "tools/call needs a tool name");
163
+ const result = await surface.call(tool, params.arguments ?? {}, {
164
+ callId: `mcp_${randomUUID()}`,
165
+ signal,
166
+ });
167
+ return toMcpResult(result, opts.readBlob);
168
+ }
169
+ default:
170
+ throw new RpcError(-32601, `method not found: ${name}`);
171
+ }
172
+ };
173
+
174
+ return {
175
+ expose(sessionId, surface) {
176
+ const token = randomUUID();
177
+ sessions.set(sessionId, { token, surface });
178
+ return {
179
+ name: opts.serverName,
180
+ url: http.url(`/mcp/${sessionId}`),
181
+ headers: { authorization: bearer(token) },
182
+ };
183
+ },
184
+ revoke(sessionId) {
185
+ sessions.delete(sessionId);
186
+ },
187
+ };
188
+ }
189
+
190
+ /** Tool calls can run for minutes, so they answer as SSE when the client takes it: headers go out at once. */
191
+ function streams(req: Request, messages: unknown[]): boolean {
192
+ if (!(req.headers.get("accept") ?? "").includes("text/event-stream")) return false;
193
+ return messages.some(
194
+ (m) =>
195
+ (m as { method?: unknown; id?: unknown })?.method === "tools/call" &&
196
+ (m as { id?: unknown }).id !== undefined,
197
+ );
198
+ }
199
+
200
+ /** Comment lines keep idle timeouts (Bun.serve closes a quiet connection after 10s) from closing the stream. */
201
+ export const SSE_KEEPALIVE_MS = 5_000;
202
+
203
+ function sse(replies: Promise<unknown[]>, signal: AbortSignal): Response {
204
+ const enc = new TextEncoder();
205
+ let timer: ReturnType<typeof setInterval> | undefined;
206
+ const body = new ReadableStream<Uint8Array>({
207
+ start(controller) {
208
+ const write = (s: string) => {
209
+ try {
210
+ controller.enqueue(enc.encode(s));
211
+ } catch {
212
+ clearInterval(timer);
213
+ }
214
+ };
215
+ write(": open\n\n");
216
+ timer = setInterval(() => write(": keepalive\n\n"), SSE_KEEPALIVE_MS);
217
+ signal.addEventListener("abort", () => clearInterval(timer), { once: true });
218
+ void replies.then(
219
+ (list) => {
220
+ clearInterval(timer);
221
+ for (const reply of list) write(`event: message\ndata: ${JSON.stringify(reply)}\n\n`);
222
+ try {
223
+ controller.close();
224
+ } catch {}
225
+ },
226
+ (error: unknown) => {
227
+ clearInterval(timer);
228
+ controller.error(error);
229
+ },
230
+ );
231
+ },
232
+ cancel() {
233
+ clearInterval(timer);
234
+ },
235
+ });
236
+ return new Response(body, {
237
+ headers: { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" },
238
+ });
239
+ }
240
+
241
+ function authorized(token: string, header: string | null): boolean {
242
+ if (!header) return false;
243
+ const want = Buffer.from(bearer(token));
244
+ const got = Buffer.from(header);
245
+ return want.length === got.length && timingSafeEqual(want, got);
246
+ }
247
+
248
+ const bearer = (token: string) => `Bearer ${token}`;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Plugin-defined part types (9.4). A `custom` part's `kind` names a definition in core's part type
3
+ * registry; core validates `data` against its schema. `title` and `text` are written with the part, so
4
+ * any client, and the model, can show it without knowing the type.
5
+ */
6
+ export interface PartTypeDefinition {
7
+ /** "<plugin id>/<name>@<major>", e.g. "valet-exec/job-end@1". A published version's schema never changes. */
8
+ id: string;
9
+ /** What the part means, for people and other plugins. */
10
+ description?: string;
11
+ /** JSON schema (core's validator subset) that `data` must match. */
12
+ schema: Record<string, unknown>;
13
+ /** Rendering hints for clients that have no renderer for this id. */
14
+ view?: PartTypeView;
15
+ /** A `system` message holding this part starts a run, like a user message does. */
16
+ wakes?: boolean;
17
+ }
18
+
19
+ export interface PartTypeView {
20
+ /** Shown collapsed to `title` until expanded, like reasoning and tool calls. Default true. */
21
+ collapsed?: boolean;
22
+ level?: "info" | "warn" | "error";
23
+ /** A short icon name; clients map what they know and ignore the rest. */
24
+ icon?: string;
25
+ /** Top-level `data` keys worth showing as a key/value list. */
26
+ fields?: string[];
27
+ }
28
+
29
+ /** A registry entry. Entries outlive their plugin: reinstalling it picks the same entry back up. */
30
+ export interface PartType extends PartTypeDefinition {
31
+ plugin: { id: string; version: string; repository?: string };
32
+ definedAt: number;
33
+ updatedAt: number;
34
+ }
35
+
36
+ export interface PartTypes {
37
+ /**
38
+ * Adds or updates one of this plugin's types; call it on every activate. The id must start with
39
+ * "<plugin id>/". Re-defining an id with a different schema throws: bump the major instead.
40
+ */
41
+ define(def: PartTypeDefinition): PartType;
42
+ get(id: string): PartType | undefined;
43
+ list(): PartType[];
44
+ }
45
+
46
+ /** Splits "valet-exec/job-end@1" into its parts, or undefined if it isn't one. */
47
+ export function parsePartTypeId(id: string): { plugin: string; name: string; major: number } | undefined {
48
+ const m = /^([a-z0-9][a-z0-9._-]*)\/([a-z0-9][a-z0-9._-]*)@(\d+)$/.exec(id);
49
+ if (!m) return undefined;
50
+ return { plugin: m[1] as string, name: m[2] as string, major: Number(m[3]) };
51
+ }
@@ -0,0 +1,19 @@
1
+ export interface ChannelBinding {
2
+ platform: string; // "discord"
3
+ conversationId: string; // channel, DM or thread ID
4
+ meta?: Record<string, unknown>;
5
+ }
6
+
7
+ export interface OutboundMessage {
8
+ text: string;
9
+ files?: { blobId: string; name: string }[];
10
+ replyToExternalId?: string;
11
+ }
12
+
13
+ export interface MessagePlatform {
14
+ readonly id: string;
15
+ readonly label: string;
16
+ send(binding: ChannelBinding, msg: OutboundMessage): Promise<{ externalId: string }>;
17
+ edit?(binding: ChannelBinding, externalId: string, msg: OutboundMessage): Promise<void>;
18
+ typing?(binding: ChannelBinding): Promise<void>;
19
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { PluginEventBus } from "./events";
2
+ import type { HttpHost } from "./http";
3
+ import type { PluginManifest } from "./manifest";
4
+ import type { ScopeRegistry } from "./scopes";
5
+ import type { PluginStorage, Store } from "./store";
6
+ import type { WsHost } from "./ws";
7
+
8
+ export interface ValetPlugin<Config = unknown> {
9
+ activate(ctx: PluginContext<Config>): void | Promise<void>;
10
+ deactivate?(): void | Promise<void>;
11
+ }
12
+ export function definePlugin<Config = unknown>(plugin: ValetPlugin<Config>): ValetPlugin<Config> {
13
+ return plugin;
14
+ }
15
+
16
+ export interface PluginContext<Config = unknown> {
17
+ readonly plugin: {
18
+ readonly id: string;
19
+ readonly version: string;
20
+ readonly dir: string;
21
+ readonly manifest: PluginManifest;
22
+ };
23
+ /** The plugin's current config block; reflects the latest successful reload. */
24
+ readonly config: Config;
25
+ /**
26
+ * Called after a reload changed this plugin's config block, with the validated new and previous values.
27
+ * Throw to say the change needs a restart. A plugin without a listener is reported as restart-required.
28
+ */
29
+ onConfigChange(fn: (next: Config, prev: Config) => void | Promise<void>): void;
30
+ readonly log: Logger;
31
+ readonly events: PluginEventBus;
32
+ readonly scopes: ScopeRegistry;
33
+ readonly store: Store;
34
+ readonly storage: PluginStorage;
35
+ readonly http: HttpHost;
36
+ readonly ws: WsHost;
37
+ readonly secrets: Secrets;
38
+ readonly paths: { readonly data: string; readonly cache: string; readonly valetHome: string };
39
+ /** Aborted when this plugin deactivates or core shuts down. */
40
+ readonly signal: AbortSignal;
41
+ /** Runs on deactivate, in reverse registration order. Hooks, scopes, routes and WS handlers are disposed automatically. */
42
+ onDispose(fn: () => void | Promise<void>): void;
43
+ }
44
+
45
+ export interface Logger {
46
+ debug(msg: string, data?: Record<string, unknown>): void;
47
+ info(msg: string, data?: Record<string, unknown>): void;
48
+ warn(msg: string, data?: Record<string, unknown>): void;
49
+ error(msg: string, data?: Record<string, unknown>): void;
50
+ }
51
+
52
+ export interface Secrets {
53
+ /** Resolves ~/.valet/secrets/<name> (file, mode 0600) and then the environment variable <NAME>. */
54
+ get(name: string): Promise<string | undefined>;
55
+ require(name: string): Promise<string>;
56
+ }
57
+
58
+ export interface Disposable {
59
+ dispose(): void;
60
+ }
package/src/scopes.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { ContextManager } from "./context";
2
+ import type { Caller } from "./events";
3
+ import type { IdentityProvider } from "./identity";
4
+ import type { InferenceProvider } from "./inference";
5
+ import type { MessagePlatform } from "./platform";
6
+ import type { Disposable } from "./plugin";
7
+ import type { SettingsPanel } from "./settings";
8
+ import type { ToolProvider } from "./tools";
9
+
10
+ export interface ValetScopes {
11
+ inference: InferenceProvider;
12
+ tools: ToolProvider;
13
+ platform: MessagePlatform;
14
+ identity: IdentityProvider;
15
+ context: ContextManager; // defined and provided by valet-contextmanager
16
+ settings: SettingsPanel; // defined by valet-ui
17
+ }
18
+ export type ScopeName = Extract<keyof ValetScopes, string>;
19
+
20
+ export interface ScopeDefinition {
21
+ name: string;
22
+ version: number;
23
+ cardinality: "one" | "many";
24
+ }
25
+ export function defineScope(def: ScopeDefinition): ScopeDefinition {
26
+ return def;
27
+ }
28
+
29
+ export interface ScopeProvider<K extends ScopeName> {
30
+ readonly key: string; // provider key, e.g. "devin-cli"; defaults to the plugin id
31
+ readonly plugin: string;
32
+ readonly impl: ValetScopes[K];
33
+ }
34
+
35
+ export type ScopeImpl<K extends ScopeName> = ValetScopes[K] | ((caller: Caller) => ValetScopes[K]);
36
+
37
+ export interface ScopeRegistry {
38
+ define(def: ScopeDefinition): void;
39
+ /** A factory is called once per consuming plugin with that plugin's identity, so the provider knows who is calling. */
40
+ provide<K extends ScopeName>(scope: K, impl: ScopeImpl<K>, opts?: { key?: string }): Disposable;
41
+ /** The single provider (cardinality "one") or the provider with this key. Throws ScopeMissingError. */
42
+ get<K extends ScopeName>(scope: K, key?: string): ValetScopes[K];
43
+ maybe<K extends ScopeName>(scope: K, key?: string): ValetScopes[K] | undefined;
44
+ all<K extends ScopeName>(scope: K): ScopeProvider<K>[];
45
+ /** Fires on provide and dispose, so consumers can track providers that arrive later or go away. */
46
+ watch<K extends ScopeName>(scope: K, fn: (providers: ScopeProvider<K>[]) => void): Disposable;
47
+ }
48
+
49
+ export class ServiceDeniedError extends Error {
50
+ readonly by!: string;
51
+ readonly reason: string;
52
+ constructor(reason: string) {
53
+ super(reason);
54
+ this.name = "ServiceDeniedError";
55
+ this.reason = reason;
56
+ }
57
+ }
58
+
59
+ /** spec-gap: referenced by ScopeRegistry.get but never defined in the doc. */
60
+ export class ScopeMissingError extends Error {
61
+ constructor(
62
+ readonly scope: string,
63
+ readonly key?: string,
64
+ ) {
65
+ super(`no provider for scope "${scope}"${key === undefined ? "" : ` with key "${key}"`}`);
66
+ this.name = "ScopeMissingError";
67
+ }
68
+ }
@@ -0,0 +1,55 @@
1
+ // spec-gap: the `settings` scope is defined by valet-ui and not in the architecture doc; every provider used to redeclare this type.
2
+
3
+ export type SettingsTone = "normal" | "good" | "warning" | "critical";
4
+
5
+ /** Declarative view data. The UI owns all rendering; a block carries values, never markup. */
6
+ export type SettingsBlock =
7
+ | { type: "text"; text: string; tone?: SettingsTone }
8
+ | { type: "badge"; text: string; tone?: SettingsTone }
9
+ | { type: "stat"; label: string; value: string; caption?: string }
10
+ | {
11
+ type: "meter";
12
+ label: string;
13
+ /** Filled share of the bar, 0-100. */
14
+ value: number;
15
+ /** Headline text, e.g. "44% left". */
16
+ display?: string;
17
+ /** Small line under the headline, e.g. "+56% in 2h 0m". */
18
+ caption?: string;
19
+ /** Short status at the top right, e.g. "On pace". */
20
+ status?: string;
21
+ /** Marker position on the bar, 0-100 (e.g. where a steady pace would be now). */
22
+ marker?: number;
23
+ tone?: SettingsTone;
24
+ }
25
+ | { type: "table"; columns: string[]; rows: string[][] }
26
+ | {
27
+ type: "button";
28
+ label: string;
29
+ /** Key in `SettingsPanel.actions`. */
30
+ action: string;
31
+ args?: Record<string, unknown>;
32
+ /** Ask for confirmation with this text before running. */
33
+ confirm?: string;
34
+ tone?: SettingsTone;
35
+ }
36
+ | { type: "group"; title?: string; layout?: "stack" | "row"; blocks: SettingsBlock[] };
37
+
38
+ export type SettingsAction = (args: Record<string, unknown>) => void | Promise<void>;
39
+
40
+ /** A panel on the `settings` scope: an editable form (`schema`, `get`, `set`), read-only `view` blocks, or both. The blocks render above the form. */
41
+ export interface SettingsPanel {
42
+ title: string;
43
+ description?: string;
44
+ /** JSON Schema describing the editable values; the UI renders its form from it. */
45
+ schema?: Record<string, unknown>;
46
+ get?(): Record<string, unknown> | Promise<Record<string, unknown>>;
47
+ /** Applies and persists the values. Throw to reject; the message is shown in the UI. */
48
+ set?(values: Record<string, unknown>): void | Promise<void>;
49
+ /** Called on every fetch, so the blocks can reflect current state. */
50
+ view?(): SettingsBlock[] | Promise<SettingsBlock[]>;
51
+ /** Re-fetch the panel this often (ms) while it is visible. The UI clamps this to at least 1000. */
52
+ refreshMs?: number;
53
+ /** Handlers for `button` blocks. Throw to report an error in the UI. */
54
+ actions?: Record<string, SettingsAction>;
55
+ }