@valethq/sdk 0.1.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@valethq/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Valet plugin SDK: types plus zero-dependency helpers.",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
package/src/catalog.ts CHANGED
@@ -7,6 +7,8 @@ declare module "./events" {
7
7
  interface ValetEvents {
8
8
  "project.create": { project: Project };
9
9
  "project.update": { project: Project };
10
+ // spec-gap: project.delete is not in the architecture doc's event catalog.
11
+ "project.delete": { project: Project };
10
12
  "session.create": { session: Session };
11
13
  "session.update": {
12
14
  session: Session;
package/src/index.ts CHANGED
@@ -4,10 +4,13 @@ export * from "./events";
4
4
  export * from "./http";
5
5
  export * from "./identity";
6
6
  export * from "./inference";
7
+ export * from "./mcp";
8
+ export * from "./parttypes";
7
9
  export * from "./manifest";
8
10
  export * from "./platform";
9
11
  export * from "./plugin";
10
12
  export * from "./scopes";
13
+ export * from "./settings";
11
14
  export * from "./store";
12
15
  export * from "./tools";
13
16
  export * from "./version";
package/src/inference.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ToolSpec } from "./tools";
1
+ import type { ToolResult, ToolSpec } from "./tools";
2
2
 
3
3
  export interface ModelInfo {
4
4
  id: string; // "claude-opus-5-5"
@@ -78,11 +78,32 @@ export interface AgentOpenOptions {
78
78
  cwd: string;
79
79
  model: string;
80
80
  resumeId?: string;
81
- /** MCP servers the remote agent should connect to (valet's tools; see 6.2). */
82
- mcpServers: { name: string; url: string; headers?: Record<string, string> }[];
81
+ /** Valet's tools for this session (see 6.2). The provider decides how to expose them to its agent. */
82
+ tools: ToolSurface;
83
83
  signal: AbortSignal;
84
84
  }
85
85
 
86
+ /**
87
+ * Valet's tools as one provider sees them. Bound to the session: `list` and `call` follow whichever run
88
+ * is active. Valet filters the list for the run's role and exposure config, and runs the `tool.call` gate
89
+ * inside `call`, so a provider never has to enforce policy itself.
90
+ */
91
+ export interface ToolSurface {
92
+ /** Tools this run may use, as of the run's start. Empty when no run is active. */
93
+ list(): ToolSpec[];
94
+ /** Runs one call through the gate, then the tool. A denied or failed call comes back as `isError`; it never throws. */
95
+ call(name: string, input: unknown, call: { callId: string; signal: AbortSignal }): Promise<ToolResult>;
96
+ /**
97
+ * Runs the `tool.call` gate for a call the provider is about to run itself (a built-in or native tool) and
98
+ * returns the verdict. Use `input` when present: a policy hook may rewrite it. Never throws.
99
+ */
100
+ authorize(
101
+ name: string,
102
+ input: unknown,
103
+ call: { callId: string },
104
+ ): Promise<{ input: unknown } | { denied: string }>;
105
+ }
106
+
86
107
  export interface AgentSession {
87
108
  /** Persisted on the session so it can be reopened after a restart. */
88
109
  readonly resumeId: string;
package/src/manifest.ts CHANGED
@@ -7,6 +7,8 @@ export interface PluginManifest {
7
7
  name: string;
8
8
  version: string; // semver
9
9
  description?: string;
10
+ /** Where the plugin's source lives, e.g. "https://github.com/valethq/valet-exec". Shown next to its part types. */
11
+ repository?: string;
10
12
  /** Semver range of the core plugin API this targets, e.g. "^0.1.0". */
11
13
  valet: string;
12
14
  /** Entry module, relative to the manifest. Bun loads .ts directly. */
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
+ }
package/src/scopes.ts CHANGED
@@ -4,6 +4,7 @@ import type { IdentityProvider } from "./identity";
4
4
  import type { InferenceProvider } from "./inference";
5
5
  import type { MessagePlatform } from "./platform";
6
6
  import type { Disposable } from "./plugin";
7
+ import type { SettingsPanel } from "./settings";
7
8
  import type { ToolProvider } from "./tools";
8
9
 
9
10
  export interface ValetScopes {
@@ -12,6 +13,7 @@ export interface ValetScopes {
12
13
  platform: MessagePlatform;
13
14
  identity: IdentityProvider;
14
15
  context: ContextManager; // defined and provided by valet-contextmanager
16
+ settings: SettingsPanel; // defined by valet-ui
15
17
  }
16
18
  export type ScopeName = Extract<keyof ValetScopes, string>;
17
19
 
@@ -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
+ }
package/src/store.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Denial } from "./events";
2
+ import type { PartTypes } from "./parttypes";
2
3
  import type { ChannelBinding } from "./platform";
3
4
  import type { Role, ToolResult } from "./tools";
4
5
 
@@ -22,6 +23,8 @@ export interface Session {
22
23
  createdAt: number;
23
24
  updatedAt: number;
24
25
  lastMessageAt: number | null;
26
+ /** When the model last answered (latest assistant message); null until it has. */
27
+ lastResponseAt: number | null;
25
28
  }
26
29
  export interface SessionSettings {
27
30
  model?: { provider: string; model: string; fallbacks?: { provider: string; model: string }[] };
@@ -94,7 +97,9 @@ export type PartData =
94
97
  coversThroughSeq: number;
95
98
  summary?: string;
96
99
  error?: string;
97
- };
100
+ }
101
+ // kind: a registered part type id (9.4). title is the collapsed header, text what the model sees.
102
+ | { type: "custom"; kind: string; title: string; text: string; data: unknown };
98
103
 
99
104
  export type CancelledResult = { cancelled: true; cancelReason?: string; denied?: Denial };
100
105
  export interface ActorRef {
@@ -110,10 +115,13 @@ export interface Store {
110
115
  create(
111
116
  p: Pick<Project, "name" | "workspaceDir"> & { settings?: Project["settings"] },
112
117
  ): Promise<Project | CancelledResult>;
118
+ // spec-gap: workspaceDir is patchable (relocate) and delete exists; the doc's Store lists neither.
113
119
  update(
114
120
  id: string,
115
- patch: Partial<Pick<Project, "name" | "settings">>,
121
+ patch: Partial<Pick<Project, "name" | "workspaceDir" | "settings">>,
116
122
  ): Promise<Project | CancelledResult>;
123
+ /** Unregisters the project; refuses while it still has sessions. Never touches the directory. */
124
+ delete(id: string): Promise<Project | CancelledResult>;
117
125
  };
118
126
  sessions: {
119
127
  get(id: string): Session | undefined;
@@ -169,6 +177,8 @@ export interface Store {
169
177
  link(principalId: string, platform: string, externalId: string): Promise<void>;
170
178
  setRole(principalId: string, role: Role): Promise<void>;
171
179
  };
180
+ /** Plugin-defined part types (9.4). */
181
+ partTypes: PartTypes;
172
182
  blobs: {
173
183
  put(bytes: Uint8Array | Blob, meta: { mime?: string; name?: string }): Promise<{ id: string }>;
174
184
  path(id: string): string;