werkmeister-core 0.91.2 → 0.91.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # sandbox-core
2
2
 
3
+ ## 0.91.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 348a734: SDK reference rewritten for people building on `werkmeister-core/sdk`. The 45 longest-standing exports now say what they do, what they return and throw, and whether they need the daemon, each with an example that imports from `werkmeister-core/sdk`. A test type-checks every example against the built SDK. The exports added for SDK parity get the same treatment in a follow-up. No API change.
8
+
3
9
  ## 0.91.2
4
10
 
5
11
  ### Patch Changes
@@ -132,7 +132,22 @@ export interface Notice {
132
132
  }
133
133
  export declare function readNotices(root: string): Record<string, Notice>;
134
134
  export declare function raiseNotice(root: string, id: string, n: Omit<Notice, "at">, now?: Date): void;
135
- /** Removes notice *id* from workspace *root*'s notices; a missing id is a no-op. */
135
+ /**
136
+ * Removes one notice from a workspace's notices (the alerts werkmeister raises for a person,
137
+ * such as a PR auto-fix that needs attention). Runs in-process: it rewrites the workspace's
138
+ * notices file. A missing id does nothing.
139
+ *
140
+ * @param root - The workspace folder's absolute path.
141
+ * @param id - The notice's id.
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * import { clearNotice, resolveWorkspaceDir } from "werkmeister-core/sdk";
146
+ *
147
+ * const root = await resolveWorkspaceDir("my-workspace");
148
+ * clearNotice(root, "autofix-werkmeister");
149
+ * ```
150
+ */
136
151
  export declare function clearNotice(root: string, id: string): void;
137
152
  /** `<dot-dir>/wake-nudge-<session>.json` (SW-418): a `pr watch` wake held for that open session. */
138
153
  export declare const wakeNudgePath: (root: string, session: string) => string;
@@ -485,7 +485,22 @@ export function raiseNotice(root, id, n, now = new Date()) {
485
485
  return;
486
486
  writeAtomic(noticesPath(root), { ...all, [id]: { ...n, at: now.toISOString() } });
487
487
  }
488
- /** Removes notice *id* from workspace *root*'s notices; a missing id is a no-op. */
488
+ /**
489
+ * Removes one notice from a workspace's notices (the alerts werkmeister raises for a person,
490
+ * such as a PR auto-fix that needs attention). Runs in-process: it rewrites the workspace's
491
+ * notices file. A missing id does nothing.
492
+ *
493
+ * @param root - The workspace folder's absolute path.
494
+ * @param id - The notice's id.
495
+ *
496
+ * @example
497
+ * ```ts
498
+ * import { clearNotice, resolveWorkspaceDir } from "werkmeister-core/sdk";
499
+ *
500
+ * const root = await resolveWorkspaceDir("my-workspace");
501
+ * clearNotice(root, "autofix-werkmeister");
502
+ * ```
503
+ */
489
504
  export function clearNotice(root, id) {
490
505
  const all = readNotices(root);
491
506
  if (!(id in all))
package/dist/compose.d.ts CHANGED
@@ -139,7 +139,19 @@ export interface ComposeLogsOptions {
139
139
  * told *why* a tail produced nothing.
140
140
  */
141
141
  export declare function composeLogs(feature: string, service?: string | null, { follow, tail, signal }?: ComposeLogsOptions): Promise<void>;
142
- /** A running tail: `stop()` closes every container stream; `done` settles once they are closed. */
142
+ /**
143
+ * A running log tail, as `streamLogs` returns it. `stop()` closes every container stream;
144
+ * `done` settles once they are closed.
145
+ *
146
+ * @example
147
+ * ```ts
148
+ * import { streamLogs, type LogTail } from "werkmeister-core/sdk";
149
+ *
150
+ * const tail: LogTail = streamLogs("my-workspace", "api", (chunk) => process.stdout.write(chunk));
151
+ * setTimeout(() => tail.stop(), 5_000);
152
+ * await tail.done;
153
+ * ```
154
+ */
143
155
  export interface LogTail {
144
156
  /** Closes every container stream. */
145
157
  stop(): void;
@@ -8,12 +8,44 @@ import type { LogTail } from "./compose.js";
8
8
  import { SandboxError } from "./errors.js";
9
9
  export declare const DEFAULT_DAEMON_PORT = 3002;
10
10
  export declare function daemonPort(): number;
11
- /** `WERKMEISTER_HOST` (proposal §2.4; e.g. http://host.docker.internal:3002), else loopback. */
11
+ /**
12
+ * The base URL of the werkmeister daemon, with no trailing slash. Runs in-process and makes no
13
+ * network call.
14
+ *
15
+ * @returns `WERKMEISTER_HOST` when it is set (e.g. `http://host.docker.internal:3002`), else the
16
+ * loopback address `http://127.0.0.1:<port>`, where the port is `WERKMEISTER_MCP_PORT`, the
17
+ * machine config's `mcp_port` override, or 3002.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { daemonUrl } from "werkmeister-core/sdk";
22
+ *
23
+ * const res = await fetch(`${daemonUrl()}/api/status`);
24
+ * console.log(res.status);
25
+ * ```
26
+ */
12
27
  export declare function daemonUrl(): string;
13
28
  /** WERKMEISTER_MCP_TOKEN, else the workspace's own token, else the machine token. */
14
29
  export declare function daemonToken(workspaceRoot?: string): string | null;
15
- /** The daemon is not listening, or something else holds its port: the caller may fall back. */
30
+ /**
31
+ * Thrown when the werkmeister daemon is not reachable: nothing is listening at {@link daemonUrl},
32
+ * or something other than the daemon holds its port. The daemon never saw the call, so it is safe
33
+ * to run the work another way. Its `code` is `DAEMON_DOWN`, and it extends `SandboxError`.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * import { callTool, DaemonUnavailable } from "werkmeister-core/sdk";
38
+ *
39
+ * try {
40
+ * await callTool("status");
41
+ * } catch (e) {
42
+ * if (e instanceof DaemonUnavailable) console.log(e.code, e.message); // "DAEMON_DOWN"
43
+ * else throw e;
44
+ * }
45
+ * ```
46
+ */
16
47
  export declare class DaemonUnavailable extends SandboxError {
48
+ /** @param detail - Why the daemon could not be reached; it goes into the message. */
17
49
  constructor(detail: string);
18
50
  }
19
51
  /** The daemon took the call but did not answer in time: it may still be running it, so never run it again here. */
@@ -41,7 +73,18 @@ export declare const CLIENT_UI_HEADER = "x-werkmeister-client-ui";
41
73
  export declare function buildOf(entry: string | undefined): string | null;
42
74
  /** Send *get*'s build with each call and warn once when the daemon loaded another. */
43
75
  export declare function expectDaemonBuild(get: () => string | null): void;
44
- /** What the daemon's `GET /api/status` reports about itself. */
76
+ /**
77
+ * What the werkmeister daemon reports about itself: its process, which build it runs and how
78
+ * busy it is. {@link daemonStatus} returns it.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * import { daemonStatus, type DaemonStatus } from "werkmeister-core/sdk";
83
+ *
84
+ * const status: DaemonStatus | null = await daemonStatus();
85
+ * if (status?.stale) console.log(`daemon ${status.pid} runs ${status.loaded}, disk has ${status.onDisk}`);
86
+ * ```
87
+ */
45
88
  export interface DaemonStatus {
46
89
  /** The daemon's process id. */
47
90
  pid: number;
@@ -58,9 +101,36 @@ export interface DaemonStatus {
58
101
  /** True when the daemon is stale and will restart itself once idle. */
59
102
  restartPending: boolean;
60
103
  }
61
- /** The daemon's own `GET /api/status`, or null when it is down or refuses. */
104
+ /**
105
+ * Asks the werkmeister daemon for its status. Needs the daemon, but never throws: it waits at
106
+ * most 5 seconds and does not retry.
107
+ *
108
+ * @returns The daemon's {@link DaemonStatus}, or null when the daemon is down, does not answer
109
+ * within 5 seconds, or refuses the request (for example a bad token).
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * import { daemonStatus } from "werkmeister-core/sdk";
114
+ *
115
+ * const status = await daemonStatus();
116
+ * if (!status) console.log("daemon is down: run the work in-process instead");
117
+ * else console.log(`${status.inFlight} calls running, ${status.queued} queued`);
118
+ * ```
119
+ */
62
120
  export declare function daemonStatus(): Promise<DaemonStatus | null>;
63
- /** A daemon tool's answer. */
121
+ /**
122
+ * A daemon tool's answer, as {@link callTool} returns it: the structured result and the text an
123
+ * MCP client would show.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * import { callTool, type ToolResult } from "werkmeister-core/sdk";
128
+ *
129
+ * type Listing = { workspaces: unknown[] };
130
+ * const result: ToolResult<Listing> = await callTool<Listing>("list-workspaces");
131
+ * console.log(result.text);
132
+ * ```
133
+ */
64
134
  export interface ToolResult<T> {
65
135
  /** The tool's structured result; `T` is the caller's assertion, not checked. */
66
136
  data: T;
@@ -68,9 +138,37 @@ export interface ToolResult<T> {
68
138
  text: string;
69
139
  }
70
140
  /**
71
- * Run daemon tool *name* with *args* over `POST /api/tool` (default timeout 120 s).
72
- * Throws `DaemonUnavailable` when the daemon is down, `DaemonTimeout` when it took the call but
73
- * did not answer in time, and `SandboxError` when the tool fails.
141
+ * Runs one werkmeister tool (the same tools the MCP server offers) in the werkmeister daemon and
142
+ * returns its answer. Needs the daemon. If the daemon refuses or resets the connection, it waits
143
+ * up to 15 seconds for a restarting daemon before giving up. Once a wait has given up, later calls
144
+ * in the same process do not wait again until one gets through.
145
+ *
146
+ * @param name - The tool name, e.g. `"status"` or `"list-workspaces"`.
147
+ * @param args - The tool's arguments. Defaults to none.
148
+ * @param opts - `token`: the bearer token to send; by default `WERKMEISTER_MCP_TOKEN`, else the
149
+ * machine token; `null` sends none. `signal`: aborts the call. `timeoutMs`: how long to wait for
150
+ * the answer, in milliseconds; defaults to 120000.
151
+ * @returns The tool's {@link ToolResult}. `T` is your assertion about `data`; it is not checked.
152
+ * @throws {@link DaemonUnavailable} when the daemon is not running or something else holds its
153
+ * port: the daemon never ran the tool, so you may run the work another way. Also when *signal*
154
+ * aborts the call before any answer came back; the daemon may already be running the tool then.
155
+ * @throws `SandboxError` when the daemon took the call but did not answer in time
156
+ * (`code` `DAEMON_TIMEOUT`): it may still be running the tool, so do not run it again. Also when
157
+ * the tool fails (the tool's own `code`, or `HTTP_<status>`), and when the daemon runs older code
158
+ * that has no such tool (`DAEMON_STALE`).
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * import { callTool, DaemonUnavailable } from "werkmeister-core/sdk";
163
+ *
164
+ * try {
165
+ * const { text } = await callTool("status", {}, { timeoutMs: 30_000 });
166
+ * console.log(text);
167
+ * } catch (e) {
168
+ * if (!(e instanceof DaemonUnavailable)) throw e;
169
+ * console.log(e.message); // says how to start the daemon on this platform
170
+ * }
171
+ * ```
74
172
  */
75
173
  export declare function callTool<T = unknown>(name: string, args?: Record<string, unknown>, opts?: {
76
174
  token?: string | null;
@@ -78,8 +176,30 @@ export declare function callTool<T = unknown>(name: string, args?: Record<string
78
176
  timeoutMs?: number;
79
177
  }): Promise<ToolResult<T>>;
80
178
  /**
81
- * Follow a workspace's logs over the daemon's SSE endpoint, in the same
82
- * {@link LogTail} shape as core's in-process `composeLogsStream`.
179
+ * Follows a workspace's container logs and passes each chunk to *onData* as it arrives. Needs the
180
+ * daemon. It returns at once; failures, including a daemon that is down, reject the returned
181
+ * `done` promise instead of throwing.
182
+ *
183
+ * @param workspace - The workspace's name.
184
+ * @param service - One service to follow, or null for all of the workspace's services.
185
+ * @param onData - Called with each chunk of log text.
186
+ * @param opts - `token`: the bearer token to send; by default `WERKMEISTER_MCP_TOKEN`, else the
187
+ * machine token; `null` sends none.
188
+ * @returns A {@link LogTail}. `done` resolves when the stream ends or you call `stop()`. It
189
+ * rejects with {@link DaemonUnavailable} when the daemon is down, and with `SandboxError`
190
+ * when the daemon refuses the stream or the logs fail.
191
+ *
192
+ * @example
193
+ * ```ts
194
+ * import { DaemonUnavailable, streamLogs } from "werkmeister-core/sdk";
195
+ *
196
+ * const tail = streamLogs("my-workspace", null, (chunk) => process.stdout.write(chunk));
197
+ * setTimeout(() => tail.stop(), 10_000);
198
+ * await tail.done.catch((e) => {
199
+ * if (e instanceof DaemonUnavailable) console.log("daemon is down: try `werkmeister feature logs`");
200
+ * else throw e;
201
+ * });
202
+ * ```
83
203
  */
84
204
  export declare function streamLogs(workspace: string, service: string | null, onData: (chunk: string) => void, opts?: {
85
205
  token?: string | null;
@@ -19,7 +19,22 @@ export function daemonPort() {
19
19
  const port = Number(raw);
20
20
  return Number.isInteger(port) && port > 0 ? port : DEFAULT_DAEMON_PORT;
21
21
  }
22
- /** `WERKMEISTER_HOST` (proposal §2.4; e.g. http://host.docker.internal:3002), else loopback. */
22
+ /**
23
+ * The base URL of the werkmeister daemon, with no trailing slash. Runs in-process and makes no
24
+ * network call.
25
+ *
26
+ * @returns `WERKMEISTER_HOST` when it is set (e.g. `http://host.docker.internal:3002`), else the
27
+ * loopback address `http://127.0.0.1:<port>`, where the port is `WERKMEISTER_MCP_PORT`, the
28
+ * machine config's `mcp_port` override, or 3002.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { daemonUrl } from "werkmeister-core/sdk";
33
+ *
34
+ * const res = await fetch(`${daemonUrl()}/api/status`);
35
+ * console.log(res.status);
36
+ * ```
37
+ */
23
38
  export function daemonUrl() {
24
39
  return (envVar("HOST") || `http://127.0.0.1:${daemonPort()}`).replace(/\/+$/, "");
25
40
  }
@@ -37,8 +52,25 @@ export function daemonToken(workspaceRoot) {
37
52
  (workspaceRoot ? readToken(workspaceTokenFile(workspaceRoot)) : null) ||
38
53
  readToken(path.join(dotDir(os.homedir()), "mcp-token")));
39
54
  }
40
- /** The daemon is not listening, or something else holds its port: the caller may fall back. */
55
+ /**
56
+ * Thrown when the werkmeister daemon is not reachable: nothing is listening at {@link daemonUrl},
57
+ * or something other than the daemon holds its port. The daemon never saw the call, so it is safe
58
+ * to run the work another way. Its `code` is `DAEMON_DOWN`, and it extends `SandboxError`.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * import { callTool, DaemonUnavailable } from "werkmeister-core/sdk";
63
+ *
64
+ * try {
65
+ * await callTool("status");
66
+ * } catch (e) {
67
+ * if (e instanceof DaemonUnavailable) console.log(e.code, e.message); // "DAEMON_DOWN"
68
+ * else throw e;
69
+ * }
70
+ * ```
71
+ */
41
72
  export class DaemonUnavailable extends SandboxError {
73
+ /** @param detail - Why the daemon could not be reached; it goes into the message. */
42
74
  constructor(detail) {
43
75
  super(`werkmeister daemon not reachable at ${daemonUrl()} (${detail}). ` +
44
76
  "Run `werkmeister machine setup` (macOS) or `werkmeister infra connect`.", "DAEMON_DOWN");
@@ -150,7 +182,22 @@ function checkBuild(onDisk, res) {
150
182
  warn(`The werkmeister daemon runs an older build (loaded ${loaded}, on disk ${onDisk}); ` +
151
183
  "it restarts by itself once idle, or run `werkmeister daemon restart`.");
152
184
  }
153
- /** The daemon's own `GET /api/status`, or null when it is down or refuses. */
185
+ /**
186
+ * Asks the werkmeister daemon for its status. Needs the daemon, but never throws: it waits at
187
+ * most 5 seconds and does not retry.
188
+ *
189
+ * @returns The daemon's {@link DaemonStatus}, or null when the daemon is down, does not answer
190
+ * within 5 seconds, or refuses the request (for example a bad token).
191
+ *
192
+ * @example
193
+ * ```ts
194
+ * import { daemonStatus } from "werkmeister-core/sdk";
195
+ *
196
+ * const status = await daemonStatus();
197
+ * if (!status) console.log("daemon is down: run the work in-process instead");
198
+ * else console.log(`${status.inFlight} calls running, ${status.queued} queued`);
199
+ * ```
200
+ */
154
201
  export async function daemonStatus() {
155
202
  try {
156
203
  const res = await send(`${daemonUrl()}/api/status`, { headers: headers(undefined), signal: AbortSignal.timeout(5000) }, false);
@@ -161,9 +208,37 @@ export async function daemonStatus() {
161
208
  }
162
209
  }
163
210
  /**
164
- * Run daemon tool *name* with *args* over `POST /api/tool` (default timeout 120 s).
165
- * Throws `DaemonUnavailable` when the daemon is down, `DaemonTimeout` when it took the call but
166
- * did not answer in time, and `SandboxError` when the tool fails.
211
+ * Runs one werkmeister tool (the same tools the MCP server offers) in the werkmeister daemon and
212
+ * returns its answer. Needs the daemon. If the daemon refuses or resets the connection, it waits
213
+ * up to 15 seconds for a restarting daemon before giving up. Once a wait has given up, later calls
214
+ * in the same process do not wait again until one gets through.
215
+ *
216
+ * @param name - The tool name, e.g. `"status"` or `"list-workspaces"`.
217
+ * @param args - The tool's arguments. Defaults to none.
218
+ * @param opts - `token`: the bearer token to send; by default `WERKMEISTER_MCP_TOKEN`, else the
219
+ * machine token; `null` sends none. `signal`: aborts the call. `timeoutMs`: how long to wait for
220
+ * the answer, in milliseconds; defaults to 120000.
221
+ * @returns The tool's {@link ToolResult}. `T` is your assertion about `data`; it is not checked.
222
+ * @throws {@link DaemonUnavailable} when the daemon is not running or something else holds its
223
+ * port: the daemon never ran the tool, so you may run the work another way. Also when *signal*
224
+ * aborts the call before any answer came back; the daemon may already be running the tool then.
225
+ * @throws `SandboxError` when the daemon took the call but did not answer in time
226
+ * (`code` `DAEMON_TIMEOUT`): it may still be running the tool, so do not run it again. Also when
227
+ * the tool fails (the tool's own `code`, or `HTTP_<status>`), and when the daemon runs older code
228
+ * that has no such tool (`DAEMON_STALE`).
229
+ *
230
+ * @example
231
+ * ```ts
232
+ * import { callTool, DaemonUnavailable } from "werkmeister-core/sdk";
233
+ *
234
+ * try {
235
+ * const { text } = await callTool("status", {}, { timeoutMs: 30_000 });
236
+ * console.log(text);
237
+ * } catch (e) {
238
+ * if (!(e instanceof DaemonUnavailable)) throw e;
239
+ * console.log(e.message); // says how to start the daemon on this platform
240
+ * }
241
+ * ```
167
242
  */
168
243
  export async function callTool(name, args = {}, opts = {}) {
169
244
  const timeout = AbortSignal.timeout(opts.timeoutMs ?? 120_000);
@@ -205,8 +280,30 @@ export async function callTool(name, args = {}, opts = {}) {
205
280
  return { data: body.structuredContent, text: body.text ?? "" };
206
281
  }
207
282
  /**
208
- * Follow a workspace's logs over the daemon's SSE endpoint, in the same
209
- * {@link LogTail} shape as core's in-process `composeLogsStream`.
283
+ * Follows a workspace's container logs and passes each chunk to *onData* as it arrives. Needs the
284
+ * daemon. It returns at once; failures, including a daemon that is down, reject the returned
285
+ * `done` promise instead of throwing.
286
+ *
287
+ * @param workspace - The workspace's name.
288
+ * @param service - One service to follow, or null for all of the workspace's services.
289
+ * @param onData - Called with each chunk of log text.
290
+ * @param opts - `token`: the bearer token to send; by default `WERKMEISTER_MCP_TOKEN`, else the
291
+ * machine token; `null` sends none.
292
+ * @returns A {@link LogTail}. `done` resolves when the stream ends or you call `stop()`. It
293
+ * rejects with {@link DaemonUnavailable} when the daemon is down, and with `SandboxError`
294
+ * when the daemon refuses the stream or the logs fail.
295
+ *
296
+ * @example
297
+ * ```ts
298
+ * import { DaemonUnavailable, streamLogs } from "werkmeister-core/sdk";
299
+ *
300
+ * const tail = streamLogs("my-workspace", null, (chunk) => process.stdout.write(chunk));
301
+ * setTimeout(() => tail.stop(), 10_000);
302
+ * await tail.done.catch((e) => {
303
+ * if (e instanceof DaemonUnavailable) console.log("daemon is down: try `werkmeister feature logs`");
304
+ * else throw e;
305
+ * });
306
+ * ```
210
307
  */
211
308
  export function streamLogs(workspace, service, onData, opts = {}) {
212
309
  const abort = new AbortController();
package/dist/errors.d.ts CHANGED
@@ -5,31 +5,52 @@
5
5
  */
6
6
  export declare const WORKSPACE_ERROR_CODE = "WORKSPACE";
7
7
  /**
8
- * A user-facing failure carrying a machine-readable *code*.
8
+ * The base class of every error the SDK throws on purpose. Its `message` is written for a person
9
+ * to read; its `code` names the kind of failure, so your code can branch on it without parsing
10
+ * the message. {@link WorkspaceError} and `DaemonUnavailable` extend it.
9
11
  *
10
- * This is what lets a library function fail without ending the process. The six
11
- * command sequences (`up`/`down`/`stop`/`restart`/`connect`/`status`) exit(1)
12
- * today, which a long-lived caller — the dashboard, an MCP server — cannot
13
- * survive; they throw this instead, and the CLI's top-level handler in
14
- * `main.ts` turns it back into the same `[err]` line and exit status.
12
+ * @example
13
+ * ```ts
14
+ * import { callTool, SandboxError } from "werkmeister-core/sdk";
15
15
  *
16
- * *code* exists for the in-process caller to branch on, not for the CLI: every
17
- * code maps to exit 1.
16
+ * try {
17
+ * await callTool("status");
18
+ * } catch (e) {
19
+ * if (e instanceof SandboxError && e.code === "DAEMON_TIMEOUT") console.log("still running: don't retry");
20
+ * else throw e;
21
+ * }
22
+ * ```
18
23
  */
19
24
  export declare class SandboxError extends Error {
20
25
  /** Machine-readable failure kind, e.g. `WORKSPACE`, `DAEMON_DOWN`. */
21
26
  readonly code: string;
27
+ /**
28
+ * @param message - What went wrong, for a person to read.
29
+ * @param code - The failure kind.
30
+ */
22
31
  constructor(message: string,
23
32
  /** Machine-readable failure kind, e.g. `WORKSPACE`, `DAEMON_DOWN`. */
24
33
  code: string);
25
34
  }
26
35
  /**
27
- * A user-facing failure with a clean message (CLI not found, create failed, …).
36
+ * The error most SDK functions throw: a workspace that does not exist, a bad name, a command
37
+ * that is not installed, a create or action that failed. Its `message` says what went wrong in
38
+ * words a person can act on, and its `code` is always `WORKSPACE`. It extends
39
+ * {@link SandboxError}.
28
40
  *
29
- * One code for all ~45 throw sites: they predate `SandboxError` and none of
30
- * their callers branches on anything finer than the class. Giving them
31
- * distinct codes is a separate change nothing has asked for yet.
41
+ * @example
42
+ * ```ts
43
+ * import { resolveWorkspaceDir, WorkspaceError } from "werkmeister-core/sdk";
44
+ *
45
+ * try {
46
+ * console.log(await resolveWorkspaceDir("no-such-workspace"));
47
+ * } catch (e) {
48
+ * if (e instanceof WorkspaceError) console.log(e.code, e.message); // "WORKSPACE"
49
+ * else throw e;
50
+ * }
51
+ * ```
32
52
  */
33
53
  export declare class WorkspaceError extends SandboxError {
54
+ /** @param message - What went wrong, for a person to read. */
34
55
  constructor(message: string);
35
56
  }
package/dist/errors.js CHANGED
@@ -4,20 +4,33 @@
4
4
  * two drift silently — the CLI would just start formatting them differently.
5
5
  */
6
6
  export const WORKSPACE_ERROR_CODE = "WORKSPACE";
7
+ // Lets a library function fail without ending the process: the command sequences
8
+ // (`up`/`down`/`stop`/`restart`/`connect`/`status`) throw this instead of exit(1), and the
9
+ // CLI's top-level handler in `main.ts` turns it back into the same `[err]` line and exit
10
+ // status. Every code maps to exit 1.
7
11
  /**
8
- * A user-facing failure carrying a machine-readable *code*.
12
+ * The base class of every error the SDK throws on purpose. Its `message` is written for a person
13
+ * to read; its `code` names the kind of failure, so your code can branch on it without parsing
14
+ * the message. {@link WorkspaceError} and `DaemonUnavailable` extend it.
9
15
  *
10
- * This is what lets a library function fail without ending the process. The six
11
- * command sequences (`up`/`down`/`stop`/`restart`/`connect`/`status`) exit(1)
12
- * today, which a long-lived caller — the dashboard, an MCP server — cannot
13
- * survive; they throw this instead, and the CLI's top-level handler in
14
- * `main.ts` turns it back into the same `[err]` line and exit status.
16
+ * @example
17
+ * ```ts
18
+ * import { callTool, SandboxError } from "werkmeister-core/sdk";
15
19
  *
16
- * *code* exists for the in-process caller to branch on, not for the CLI: every
17
- * code maps to exit 1.
20
+ * try {
21
+ * await callTool("status");
22
+ * } catch (e) {
23
+ * if (e instanceof SandboxError && e.code === "DAEMON_TIMEOUT") console.log("still running: don't retry");
24
+ * else throw e;
25
+ * }
26
+ * ```
18
27
  */
19
28
  export class SandboxError extends Error {
20
29
  code;
30
+ /**
31
+ * @param message - What went wrong, for a person to read.
32
+ * @param code - The failure kind.
33
+ */
21
34
  constructor(message,
22
35
  /** Machine-readable failure kind, e.g. `WORKSPACE`, `DAEMON_DOWN`. */
23
36
  code) {
@@ -26,14 +39,29 @@ export class SandboxError extends Error {
26
39
  this.name = "SandboxError";
27
40
  }
28
41
  }
42
+ // One code for all ~45 throw sites: they predate `SandboxError` and none of their callers
43
+ // branches on anything finer than the class. Giving them distinct codes is a separate change
44
+ // nothing has asked for yet.
29
45
  /**
30
- * A user-facing failure with a clean message (CLI not found, create failed, …).
46
+ * The error most SDK functions throw: a workspace that does not exist, a bad name, a command
47
+ * that is not installed, a create or action that failed. Its `message` says what went wrong in
48
+ * words a person can act on, and its `code` is always `WORKSPACE`. It extends
49
+ * {@link SandboxError}.
31
50
  *
32
- * One code for all ~45 throw sites: they predate `SandboxError` and none of
33
- * their callers branches on anything finer than the class. Giving them
34
- * distinct codes is a separate change nothing has asked for yet.
51
+ * @example
52
+ * ```ts
53
+ * import { resolveWorkspaceDir, WorkspaceError } from "werkmeister-core/sdk";
54
+ *
55
+ * try {
56
+ * console.log(await resolveWorkspaceDir("no-such-workspace"));
57
+ * } catch (e) {
58
+ * if (e instanceof WorkspaceError) console.log(e.code, e.message); // "WORKSPACE"
59
+ * else throw e;
60
+ * }
61
+ * ```
35
62
  */
36
63
  export class WorkspaceError extends SandboxError {
64
+ /** @param message - What went wrong, for a person to read. */
37
65
  constructor(message) {
38
66
  super(message, WORKSPACE_ERROR_CODE);
39
67
  this.name = "WorkspaceError";
@@ -106,15 +106,50 @@ export declare function buildFormSchema(spec: PromptSpecJson, title?: string | n
106
106
  /** A workspace needs at least one repo: a selected service or an explicit repo. The message, or null when satisfied. */
107
107
  export declare function repoSelectionError(formData: Record<string, unknown>): string | null;
108
108
  /**
109
- * Field key → why `formData` can't be submitted against a `buildFormSchema` bundle: required, pattern and choices,
110
- * plus `repoSelectionError` (under `services`). Empty when it can. For renderers without a JSON Schema validator
111
- * (the /workspaces pane); the browser form's AJV covers the schema part and calls `repoSelectionError` itself.
109
+ * Checks new-workspace form data against the form's schema, without a JSON
110
+ * Schema validator. It checks required fields, allowed choices and patterns,
111
+ * and that at least one service or repo is picked. Runs in-process.
112
+ *
113
+ * @param bundle - The form schema; only `schema.properties` and
114
+ * `schema.required` are read.
115
+ * @param formData - The field values to check.
116
+ * @returns Field key → why that field can't be submitted (the repo check is
117
+ * reported under `services`). Empty when the data can be submitted.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * import { validateFormData } from "werkmeister-core/sdk";
122
+ *
123
+ * const errors = validateFormData(
124
+ * { schema: { properties: { feature: { type: "string", pattern: "^[a-z-]+$" } }, required: ["feature"] } },
125
+ * { feature: "Login Page", services: ["api"] },
126
+ * );
127
+ * console.log(errors); // { feature: '"Login Page" doesn\'t match the expected format' }
128
+ * ```
112
129
  */
113
130
  export declare function validateFormData(bundle: {
114
131
  schema: Pick<FormBundle["schema"], "properties" | "required">;
115
132
  }, formData: Record<string, unknown>): Record<string, string>;
116
133
  /**
117
- * Fill-empty merge of an issue's fields into form data: a field already filled is never clobbered, so re-fetching
118
- * is safe. `issue_id` is the exception — the lookup normalizes it (`api#7` → `acme/api#7`), so the canonical ref wins.
134
+ * Merges fields fetched from an issue into new-workspace form data, filling only
135
+ * empty fields, so a field the person already filled is never overwritten and
136
+ * fetching again is safe. `issue_id` is the exception: the fetched one always
137
+ * wins, because the lookup returns the canonical ref (`api#7` becomes
138
+ * `acme/api#7`). Runs in-process and returns a new object.
139
+ *
140
+ * @param current - The form data as it is now.
141
+ * @param incoming - The fields fetched from the issue.
142
+ * @returns A copy of `current` with the empty fields filled from `incoming`.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * import { mergeFormData } from "werkmeister-core/sdk";
147
+ *
148
+ * const merged = mergeFormData(
149
+ * { feature: "login", description: "" },
150
+ * { feature: "sign-in", description: "Add SSO", issue_id: "PROJ-42" },
151
+ * );
152
+ * console.log(merged); // { feature: "login", description: "Add SSO", issue_id: "PROJ-42" }
153
+ * ```
119
154
  */
120
155
  export declare function mergeFormData(current: Record<string, unknown>, incoming: Record<string, unknown>): Record<string, unknown>;