@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/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@valethq/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Valet plugin SDK: types plus zero-dependency helpers.",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "license": "AGPL-3.0-only",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/valethq/valet-core.git",
15
+ "directory": "packages/sdk"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "LICENSE"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ }
24
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,55 @@
1
+ import type { HookPhase } from "./events";
2
+ import type { Message, Part, Principal, Project, Run, Session } from "./store";
3
+ import type { Role } from "./tools";
4
+
5
+ // Section 7.3: the core event catalog, declaration-merged into the open maps.
6
+ declare module "./events" {
7
+ interface ValetEvents {
8
+ "project.create": { project: Project };
9
+ "project.update": { project: Project };
10
+ // spec-gap: project.delete is not in the architecture doc's event catalog.
11
+ "project.delete": { project: Project };
12
+ "session.create": { session: Session };
13
+ "session.update": {
14
+ session: Session;
15
+ patch: Partial<Pick<Session, "title" | "color" | "status" | "settings">>;
16
+ };
17
+ "session.delete": { session: Session };
18
+ "message.create": { message: Message; parts: Part[] };
19
+ "message.complete": { message: Message };
20
+ "run.start": { run: Run };
21
+ "run.update": { run: Run };
22
+ "run.end": { run: Run };
23
+ "run.cancel": { runId: string; by: string };
24
+ "run.interrupted": { run: Run };
25
+ "tool.call": { runId: string; callId: string; name: string; input: unknown; role: Role };
26
+ "principal.link": { principal: Principal; identity: { platform: string; externalId: string } };
27
+ "control.request": {
28
+ kind: "http" | "ws.sub" | "ws.call";
29
+ method: string;
30
+ path: string;
31
+ /** The plugin that owns the matched route or topic prefix, when there is one. */
32
+ plugin?: string;
33
+ };
34
+ "identity.changed": { principalId?: string };
35
+ "core.ready": Record<string, never>;
36
+ "core.shutdown": Record<string, never>;
37
+ }
38
+
39
+ interface ValetSignals {
40
+ "message.delta": {
41
+ sessionId: string;
42
+ messageId: string;
43
+ partId: string;
44
+ kind: "text" | "reasoning" | "tool-output";
45
+ delta: string;
46
+ /** Length of the part's text/output before this delta was appended; dedupe or refetch on overlap. */
47
+ offset: number;
48
+ };
49
+ /** A part was opened, replaced or closed; carries the whole part so a client can update it in place. */
50
+ "part.update": { sessionId: string; messageId: string; part: unknown };
51
+ "run.status": { sessionId: string; runId: string; status: string };
52
+ "core.config.changed": { changed: string[]; restartRequired: string[] };
53
+ "core.hook.error": { eventName: string; phase: HookPhase; plugin: string | undefined; error: unknown };
54
+ }
55
+ }
package/src/context.ts ADDED
@@ -0,0 +1,51 @@
1
+ import type { ModelInfo, ModelMessage } from "./inference";
2
+ import type { Role } from "./tools";
3
+
4
+ export interface PersonaFile {
5
+ path: string;
6
+ role: "agents" | "user" | "memory" | "soul" | "identity" | "daily" | "other";
7
+ content: string;
8
+ }
9
+
10
+ export interface BuiltContext {
11
+ system: string;
12
+ messages: ModelMessage[];
13
+ estimatedTokens: number;
14
+ files: PersonaFile[];
15
+ }
16
+
17
+ /** The `context@1` scope: persona files, prompt building and compaction state for a session. */
18
+ export interface ContextManager {
19
+ /** model-kind: full prompt within budget (persona files, compaction summary, recent history). */
20
+ build(req: { sessionId: string; runId: string; model: ModelInfo; role: Role }): Promise<BuiltContext>;
21
+ /** agent-kind: persona/memory preamble for a new or reseeded remote session. */
22
+ preamble(req: {
23
+ sessionId: string;
24
+ role: Role;
25
+ model?: { id: string; contextWindow?: number };
26
+ }): Promise<string>;
27
+ shouldCompact(req: {
28
+ sessionId: string;
29
+ model: ModelInfo;
30
+ lastUsage: { inputTokens?: number; contextTokens?: number };
31
+ }): Promise<boolean>;
32
+ /** Opens a compaction part in the chat (status in_progress), in the same session, never a new one. */
33
+ compactionStart(req: { sessionId: string; by: string }): Promise<{ compactionId: string }>;
34
+ /** Closes the compaction part that compactionStart opened. A summary only counts when completed. */
35
+ compactionEnd(req: {
36
+ sessionId: string;
37
+ compactionId: string;
38
+ status: "completed" | "failed" | "cancelled";
39
+ summary?: string;
40
+ error?: string;
41
+ }): Promise<void>;
42
+ /**
43
+ * valet compacts the chat: opens a part, summarizes everything since the last valet summary with
44
+ * `summarize`, then closes the part. The summary replaces older turns in valet's history.
45
+ */
46
+ compact(req: {
47
+ sessionId: string;
48
+ reason: "auto" | "manual";
49
+ summarize(transcript: string): Promise<string>;
50
+ }): Promise<void>;
51
+ }
package/src/events.ts ADDED
@@ -0,0 +1,103 @@
1
+ import type { Disposable } from "./plugin";
2
+ import type { Role } from "./tools";
3
+
4
+ export type HookPhase = "before" | "after";
5
+ export interface HookOptions {
6
+ priority?: number;
7
+ once?: boolean;
8
+ }
9
+ export interface Subscription {
10
+ readonly active: boolean;
11
+ disconnect(): void;
12
+ }
13
+
14
+ /** Who caused an event, a store write or a scope call. Core fills it in; plugins cannot set `plugin`. */
15
+ export interface Caller {
16
+ /** The emitting, writing or calling plugin's id, or "core" (boot recovery, control-plane requests). */
17
+ readonly plugin: string;
18
+ /**
19
+ * The principal this is on behalf of, if any. Inside a run, `role` is the run's effective role (section 8.3).
20
+ * A plugin claims it (via `store.as()` or a message author), or an identity provider proves it. Hooks decide whether to believe it.
21
+ */
22
+ readonly actor?: { readonly principalId: string; readonly role: Role };
23
+ /** Control-plane requests only: the identity@1 provider that authenticated the request. */
24
+ readonly authenticatedBy?: string;
25
+ /** Set on re-entrant emits: the event whose hook caused this one. */
26
+ readonly cause?: { readonly event: string; readonly plugin: string };
27
+ }
28
+ export interface Denial {
29
+ readonly by: string;
30
+ readonly reason: string;
31
+ }
32
+
33
+ export interface BeforeEvent<N extends string, P> {
34
+ readonly name: N;
35
+ readonly phase: "before";
36
+ readonly caller: Caller;
37
+ payload: P;
38
+ readonly cancelled: boolean;
39
+ readonly cancelReason: string | undefined;
40
+ readonly denied: Denial | undefined;
41
+ cancel(reason?: string): void;
42
+ /** Refuse service to this caller. Like cancel(), it skips the remaining before hooks. Core sets `by` to this hook's plugin. */
43
+ deny(reason: string): void;
44
+ }
45
+ export interface AfterEvent<N extends string, P> {
46
+ readonly name: N;
47
+ readonly phase: "after";
48
+ readonly caller: Caller;
49
+ readonly payload: P;
50
+ readonly cancelled: boolean;
51
+ readonly cancelReason: string | undefined;
52
+ readonly denied: Denial | undefined;
53
+ }
54
+ export interface EmitResult<P> {
55
+ readonly payload: P;
56
+ readonly cancelled: boolean;
57
+ readonly cancelReason?: string;
58
+ readonly denied?: Denial;
59
+ }
60
+
61
+ /** Extended by declaration merging; plugin events are named "<namespace>.<rest>". */
62
+ // biome-ignore lint/suspicious/noEmptyInterface: spec: open interface extended by declaration merging
63
+ export interface ValetEvents {}
64
+ /** High-frequency, after-only signals. */
65
+ // biome-ignore lint/suspicious/noEmptyInterface: spec: open interface extended by declaration merging
66
+ export interface ValetSignals {}
67
+
68
+ type EvName = Extract<keyof ValetEvents, string>;
69
+ type SigName = Extract<keyof ValetSignals, string>;
70
+
71
+ export interface PluginEventBus {
72
+ before<N extends EvName>(
73
+ name: N,
74
+ fn: (e: BeforeEvent<N, ValetEvents[N]>) => void | Promise<void>,
75
+ opts?: HookOptions,
76
+ ): Subscription;
77
+ after<N extends EvName>(
78
+ name: N,
79
+ fn: (e: AfterEvent<N, ValetEvents[N]>) => void | Promise<void>,
80
+ opts?: HookOptions,
81
+ ): Subscription;
82
+ /** Only for events in this plugin's namespace; core events are emitted by core actions. */
83
+ emit<N extends EvName>(name: N, payload: ValetEvents[N]): Promise<EmitResult<ValetEvents[N]>>;
84
+ onSignal<N extends SigName>(name: N, fn: (payload: ValetSignals[N], caller: Caller) => void): Subscription;
85
+ signal<N extends SigName>(name: N, payload: ValetSignals[N]): void;
86
+ /** Decide which plugins may hook or observe this plugin's namespace. Checked when a hook subscribes. */
87
+ restrict(fn: (subscriber: string, name: string) => boolean): Disposable;
88
+ }
89
+
90
+ /** spec-gap: `cause` is the thrown error, or the literal string "timeout" | "depth" for bus limits. */
91
+ export class EventHookError extends Error {
92
+ constructor(
93
+ readonly eventName: string,
94
+ readonly phase: HookPhase,
95
+ readonly plugin: string | undefined,
96
+ readonly cause: unknown,
97
+ ) {
98
+ super(`Hook${plugin ? ` from "${plugin}"` : ""} failed during ${phase} phase of "${eventName}"`, {
99
+ cause,
100
+ });
101
+ this.name = "EventHookError";
102
+ }
103
+ }
package/src/http.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { Caller } from "./events";
2
+ import type { Disposable } from "./plugin";
3
+ import type { Principal } from "./store";
4
+
5
+ export type RouteHandler = (req: Request, ctx: RequestContext) => Response | Promise<Response>;
6
+ export interface RequestContext {
7
+ caller: Caller;
8
+ principal: Principal | undefined;
9
+ params: Record<string, string>;
10
+ url: URL;
11
+ }
12
+
13
+ export interface HttpHost {
14
+ /** Path is relative to /plugins/<id>; ":param" segments are supported. Non-public routes need an identified principal; beyond that, serving is the handler's call. */
15
+ route(
16
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
17
+ path: string,
18
+ handler: RouteHandler,
19
+ opts?: { public?: boolean },
20
+ ): Disposable;
21
+ /** Absolute URL of a mounted path, for MCP endpoints and webhooks. */
22
+ url(path: string): string;
23
+ }
@@ -0,0 +1,8 @@
1
+ export interface AuthResult {
2
+ principalId: string;
3
+ /** Revocable credential, e.g. a device or token id. */
4
+ credentialId?: string;
5
+ }
6
+ export interface IdentityProvider {
7
+ authenticate(req: Request): AuthResult | undefined | Promise<AuthResult | undefined>;
8
+ }
package/src/index.ts ADDED
@@ -0,0 +1,17 @@
1
+ export * from "./catalog";
2
+ export * from "./context";
3
+ export * from "./events";
4
+ export * from "./http";
5
+ export * from "./identity";
6
+ export * from "./inference";
7
+ export * from "./mcp";
8
+ export * from "./parttypes";
9
+ export * from "./manifest";
10
+ export * from "./platform";
11
+ export * from "./plugin";
12
+ export * from "./scopes";
13
+ export * from "./settings";
14
+ export * from "./store";
15
+ export * from "./tools";
16
+ export * from "./version";
17
+ export * from "./ws";
@@ -0,0 +1,142 @@
1
+ import type { ToolResult, ToolSpec } from "./tools";
2
+
3
+ export interface ModelInfo {
4
+ id: string; // "claude-opus-5-5"
5
+ name: string; // "Claude Opus 5.5"
6
+ contextWindow: number;
7
+ maxOutputTokens: number;
8
+ input: ("text" | "image")[];
9
+ reasoning: boolean;
10
+ cost?: { input: number; output: number; cacheRead?: number }; // per 1M tokens
11
+ }
12
+
13
+ export type InferenceProvider = ModelProvider | AgentProvider;
14
+
15
+ interface ProviderBase {
16
+ readonly id: string; // "devin-cli"; also the scope key
17
+ readonly label: string;
18
+ listModels(): Promise<ModelInfo[]>;
19
+ /** The provider's Utility model: a cheap, fast model for small side jobs such as naming a session. */
20
+ readonly utility?: UtilityModel;
21
+ }
22
+
23
+ export interface UtilityRequest {
24
+ system: string;
25
+ prompt: string;
26
+ maxOutputTokens?: number;
27
+ }
28
+
29
+ export interface UtilityModel {
30
+ /** Id of the model side jobs run on, or undefined when the provider has none to offer. */
31
+ model(): string | undefined;
32
+ /** One short, tool-free completion on `model()`. Rejects when the call fails. */
33
+ complete(req: UtilityRequest, signal: AbortSignal): Promise<string>;
34
+ }
35
+
36
+ // ---- kind: "model" ----
37
+ export interface ModelProvider extends ProviderBase {
38
+ readonly kind: "model";
39
+ stream(req: InferenceRequest, signal: AbortSignal): AsyncIterable<InferenceChunk>;
40
+ }
41
+
42
+ export interface InferenceRequest {
43
+ model: string;
44
+ system: string;
45
+ messages: ModelMessage[];
46
+ tools: ToolSpec[];
47
+ maxOutputTokens?: number;
48
+ reasoning?: "off" | "low" | "medium" | "high";
49
+ meta: { sessionId: string; runId: string };
50
+ }
51
+
52
+ export type ModelMessage =
53
+ | { role: "user"; content: ModelContent[] }
54
+ | { role: "assistant"; content: ModelContent[] }
55
+ | { role: "tool"; callId: string; content: ModelContent[]; isError?: boolean };
56
+
57
+ export type ModelContent =
58
+ | { type: "text"; text: string }
59
+ | { type: "image"; mime: string; blobId: string }
60
+ | { type: "tool-call"; callId: string; name: string; input: unknown };
61
+
62
+ export type InferenceChunk =
63
+ | { type: "text-delta"; text: string }
64
+ | { type: "reasoning-delta"; text: string }
65
+ | { type: "tool-call"; callId: string; name: string; input: unknown }
66
+ | { type: "usage"; inputTokens: number; outputTokens: number; cacheReadTokens?: number }
67
+ | { type: "finish"; reason: "stop" | "tool-calls" | "length" | "cancelled" | "error"; error?: string };
68
+
69
+ // ---- kind: "agent" ----
70
+ export interface AgentProvider extends ProviderBase {
71
+ readonly kind: "agent";
72
+ /** Opens a new remote session, or reopens one when `resumeId` (from Session.providerState) is given. */
73
+ open(opts: AgentOpenOptions): Promise<AgentSession>;
74
+ }
75
+
76
+ export interface AgentOpenOptions {
77
+ sessionId: string;
78
+ cwd: string;
79
+ model: string;
80
+ resumeId?: 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
+ signal: AbortSignal;
84
+ }
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
+
107
+ export interface AgentSession {
108
+ /** Persisted on the session so it can be reopened after a restart. */
109
+ readonly resumeId: string;
110
+ prompt(
111
+ input: { content: ModelContent[]; preamble?: string },
112
+ signal: AbortSignal,
113
+ ): AsyncIterable<AgentEvent>;
114
+ setModel?(model: string): Promise<void>;
115
+ /**
116
+ * Asks the harness to compact now (Claude Code `/compact`, Devin `/compact`). Yields the same
117
+ * compaction-start/end events as an automatic compaction, then finish.
118
+ */
119
+ compact?(instructions: string | undefined, signal: AbortSignal): AsyncIterable<AgentEvent>;
120
+ close(): Promise<void>;
121
+ }
122
+
123
+ export type AgentEvent =
124
+ | { type: "text-delta"; text: string }
125
+ | { type: "reasoning-delta"; text: string }
126
+ | { type: "tool-start"; callId: string; name: string; title?: string; input?: unknown }
127
+ | { type: "tool-update"; callId: string; outputDelta?: string; status?: "running" | "done" | "error" }
128
+ | {
129
+ type: "tool-end";
130
+ callId: string;
131
+ status: "done" | "error" | "cancelled";
132
+ output?: string;
133
+ exitCode?: number;
134
+ }
135
+ | { type: "permission"; request: { callId: string; title: string }; respond(allow: boolean): void }
136
+ | { type: "usage"; contextTokens?: number; inputTokens?: number; outputTokens?: number }
137
+ | { type: "notice"; level: "info" | "warning" | "error"; text: string }
138
+ /** The harness started compacting its own context; valet opens a compaction part and never compacts it. */
139
+ | { type: "compaction-start" }
140
+ /** The harness finished compacting; closes the open compaction part. */
141
+ | { type: "compaction-end"; status: "completed" | "failed" | "cancelled"; error?: string }
142
+ | { type: "finish"; reason: "stop" | "cancelled" | "length" | "error"; error?: string };
@@ -0,0 +1,32 @@
1
+ export interface PluginManifest {
2
+ /** Manifest format version. */
3
+ schema: 1;
4
+ /** Globally unique; matches the repo name, e.g. "valet-discord". */
5
+ id: string;
6
+ /** Friendly display name shown in UIs, e.g. "Claude Code" for "valet-claudecode". */
7
+ name: string;
8
+ version: string; // semver
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;
12
+ /** Semver range of the core plugin API this targets, e.g. "^0.1.0". */
13
+ valet: string;
14
+ /** Entry module, relative to the manifest. Bun loads .ts directly. */
15
+ main: string;
16
+ /** Hard plugin dependencies: id -> semver range. Loaded first; if one is missing or fails, this plugin does not load. */
17
+ dependencies?: Record<string, string>;
18
+ /** Soft plugin dependencies: loaded first when present; absence is fine. */
19
+ optionalDependencies?: Record<string, string>;
20
+ /** Scopes this plugin implements, as "name@major", e.g. ["inference@1"]. */
21
+ provides?: string[];
22
+ /** Scopes this plugin needs at activation, as "name@major". Every provider of a required scope loads first. */
23
+ requires?: string[];
24
+ /** Like `requires`, but the plugin works without them. */
25
+ optionalRequires?: string[];
26
+ /** Event namespace this plugin may emit under. Defaults to the id without the "valet-" prefix. */
27
+ events?: { namespace?: string };
28
+ /** JSON Schema for this plugin's config block; core validates it before activate(). */
29
+ configSchema?: Record<string, unknown>;
30
+ /** Reserved for post-v1 permissions. Ignored in v1 (plugins are fully trusted). */
31
+ permissions?: string[];
32
+ }