| 1 | # @codewhale/runtime-sdk |
| 2 | |
| 3 | Small JavaScript helpers and TypeScript declarations for Codewhale's local |
| 4 | Runtime API. The package is intentionally transport-only: it never bypasses the |
| 5 | Rust runtime, sandbox, approvals, provider configuration, or Runtime execution |
| 6 | ledger. |
| 7 | |
| 8 | Version 0.10.3 wraps Fleet operations, read-only thread event streaming and |
| 9 | client-executed dynamic-tool result delivery. |
| 10 | It does **not** provide thread creation/resume, turn start/steer/interrupt, |
| 11 | approval, clarification or model discovery helpers. Those operations already |
| 12 | exist on the full Engine HTTP API; use the recipe below. This package is |
| 13 | distinct from the hosted model/Responses API SDK, `codewhale-sdk`. |
| 14 | |
| 15 | Start the full API with `codewhale app-server --http`. Bare `app-server`, |
| 16 | `--stdio` and `--socket` are smaller compatibility interfaces. Their turns |
| 17 | require explicit `allowed_tools: []` and cannot run interactive tools or start |
| 18 | background goals. |
| 19 | Require `tool_free_turns: true` in capabilities before relying on that restriction; |
| 20 | older compatibility servers may ignore the allowlist field. |
| 21 | The supervisor supplies `CODEWHALE_RUNTIME_TOKEN`; a generated Runtime token |
| 22 | is not printed for discovery. Send the supplied token as a bearer credential. |
| 23 | |
| 24 | ```js |
| 25 | import { createRuntimeClient } from "@codewhale/runtime-sdk"; |
| 26 | |
| 27 | const client = createRuntimeClient({ |
| 28 | baseUrl: "http://127.0.0.1:7878", |
| 29 | token: process.env.CODEWHALE_RUNTIME_TOKEN, |
| 30 | }); |
| 31 | |
| 32 | const created = await client.createFleetRun({ |
| 33 | target: "this_computer", |
| 34 | roles: [{ name: "reviewer" }, { name: "verifier" }], |
| 35 | workflow: { |
| 36 | id: "release-check", |
| 37 | kind: "parallel", |
| 38 | tasks: [ |
| 39 | { id: "review", name: "Review", instructions: "Review locally.", worker: { role: "reviewer" } }, |
| 40 | { id: "verify", name: "Verify", instructions: "Verify locally.", worker: { role: "verifier" } }, |
| 41 | ], |
| 42 | }, |
| 43 | }); |
| 44 | |
| 45 | // Creation is durable but does not launch work. Launch remains explicit. |
| 46 | await client.startFleetRun(created.run.id); |
| 47 | |
| 48 | let cursor; |
| 49 | for await (const event of client.fleetEvents(created.run.id, { after: cursor })) { |
| 50 | if (event.cursor) cursor = event.cursor; // persist durable cursors only |
| 51 | if (event.event === "fleet.replay.cursor_unavailable") { |
| 52 | // Reload getFleetRun(created.run.id), then reconnect without the old cursor. |
| 53 | } |
| 54 | } |
| 55 | ``` |
| 56 | |
| 57 | ## Shared Runtime contracts |
| 58 | |
| 59 | The existing thread-event declaration consumes the Runtime envelope generated |
| 60 | from `crates/app-server-protocol`. Image, capability and dynamic-tool types are |
| 61 | exported from the same generated file; the SDK does not maintain another copy. |
| 62 | Generate the JSON Schema and TypeScript package outputs with |
| 63 | `cargo run -p codewhale-app-server-protocol --features schema --bin codewhale-app-server-schema -- --write`. |
| 64 | Use `--check` to verify the committed schema and both TypeScript destinations. |
| 65 | The SDK result helper consumes these generated dynamic-tool contracts. This |
| 66 | does not add Codex RPC methods or turn-start helpers. |
| 67 | |
| 68 | Input defaults remain optional in DynamicToolSpec and DynamicToolCallResult. |
| 69 | DynamicToolSpecOutput describes the serialized spec published in thread metadata; |
| 70 | Runtime event/capability fields describe the server's emitted representation. |
| 71 | Generated Json admits omitted undefined object members, while its root and array |
| 72 | values exclude undefined. The Native host generator keeps its existing format. |
| 73 | |
| 74 | ## Deliver a dynamic-tool result |
| 75 | |
| 76 | Pass the exact pending call from `snapshot.pending_dynamic_tool_calls` or a |
| 77 | validated `tool_call.requested` journal payload, together with the result from |
| 78 | your registered client-side tool: |
| 79 | |
| 80 | ```js |
| 81 | await client.deliverDynamicToolResult(call, { |
| 82 | success: true, |
| 83 | content: [{ type: "input_text", text: output }], |
| 84 | }, { signal }); |
| 85 | ``` |
| 86 | |
| 87 | The generated `DynamicToolCallParams` supplies all three Runtime identifiers; |
| 88 | the helper encodes each path segment and submits once to the existing result |
| 89 | endpoint. It resolves with no value after the empty HTTP 202 acknowledgement. |
| 90 | That confirms result acceptance, not turn completion. Continue reading the |
| 91 | Runtime journal or thread snapshot for the terminal outcome. Unknown, expired |
| 92 | or already settled calls remain `RuntimeApiError` responses with their actual |
| 93 | HTTP status; a 404 is not inferred to mean that the endpoint is unsupported. |
| 94 | |
| 95 | The helper neither executes tools nor invents results. An aborted request or |
| 96 | lost response leaves acceptance uncertain and does not cancel Engine work; |
| 97 | reload the canonical pending calls and journal before deciding what to do. |
| 98 | It never automatically retries a mutation. Authenticated requests and this |
| 99 | mutation refuse redirects, including unauthenticated use of the helper. |
| 100 | |
| 101 | ## Fleet Helpers |
| 102 | |
| 103 | - `listFleetRuns()` |
| 104 | - `getFleetRun(runId)` |
| 105 | - `listFleetWorkers(runId)` |
| 106 | - `getFleetWorker(workerId)` |
| 107 | - `interruptWorker(workerId)` |
| 108 | - `stopWorker(workerId)` |
| 109 | - `restartWorker(workerId)` |
| 110 | - `stopFleetRun(runId)` |
| 111 | - `startFleetRun(runId)` |
| 112 | - `replayFleetEvents(runId, { after, limit })` |
| 113 | - `fleetEvents(runId, { after, limit })` |
| 114 | - `createFleetRun(spec)` |
| 115 | |
| 116 | The Runtime implements the local managed-Fleet path. Fleet |
| 117 | names the roster and selected member; the Runtime owns launch authority, |
| 118 | durable run/worker/event state, replay, and execution. A creation request must |
| 119 | name its roles, define a `parallel` Workflow, and select the explicit |
| 120 | `this_computer` target. `another_computer` and `cloud` are contract values but |
| 121 | fail closed until those targets are implemented. Event cursors are opaque and |
| 122 | durable across Runtime restarts; if Runtime ledger compaction removes an old |
| 123 | cursor, replay returns a conflict so the client can reload the run projection. |
| 124 | Local worker IDs are generated per run; managed creation does not yet accept |
| 125 | caller-assigned `worker_specs` because worker controls address IDs globally. |
| 126 | |
| 127 | Older runtimes that do not expose one of these endpoints produce a |
| 128 | `RuntimeCapabilityError` with a stable capability string instead of a generic |
| 129 | fetch failure. |
| 130 | |
| 131 | ## Full Engine API |
| 132 | |
| 133 | The existing HTTP API supplies the controls missing from this package. This |
| 134 | example uses Node's built-in `fetch` and the same token as the client above; |
| 135 | it does not add a second session store, turn loop or approval authority. |
| 136 | |
| 137 | ```js |
| 138 | import { randomUUID } from "node:crypto"; |
| 139 | |
| 140 | const baseUrl = "http://127.0.0.1:7878"; |
| 141 | const token = process.env.CODEWHALE_RUNTIME_TOKEN; |
| 142 | if (!token) throw new Error("The supervisor must supply CODEWHALE_RUNTIME_TOKEN"); |
| 143 | |
| 144 | async function runtime(path, { method = "GET", body, signal } = {}) { |
| 145 | const url = new URL(path, baseUrl); |
| 146 | if (url.origin !== new URL(baseUrl).origin || url.username || url.password) { |
| 147 | throw new Error("Runtime requests must stay on the configured origin"); |
| 148 | } |
| 149 | const response = await fetch(url, { |
| 150 | method, signal, redirect: "error", |
| 151 | headers: { |
| 152 | authorization: `Bearer ${token}`, |
| 153 | accept: "application/json", |
| 154 | ...(body === undefined ? {} : { "content-type": "application/json" }), |
| 155 | }, |
| 156 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), |
| 157 | }); |
| 158 | if (!response.ok) throw new Error(`Runtime HTTP ${response.status}: ${await response.text()}`); |
| 159 | return response.status === 204 ? null : response.json(); |
| 160 | } |
| 161 | |
| 162 | const info = await runtime("/v1/runtime/info"); |
| 163 | if (!info.capabilities.thread_create_idempotency || |
| 164 | !info.capabilities.turn_operation_idempotency || |
| 165 | !info.capabilities.turn_operation_lookup) { |
| 166 | throw new Error("This client requires Runtime operation-key recovery support"); |
| 167 | } |
| 168 | const providers = await runtime("/v1/providers"); |
| 169 | const createIntent = { operation_key: randomUUID(), workspace: process.cwd(), mode: "agent" }; |
| 170 | const thread = await runtime("/v1/threads", { method: "POST", body: createIntent }); |
| 171 | const threadPath = `/v1/threads/${encodeURIComponent(thread.id)}`; |
| 172 | const snapshot = await runtime(threadPath); |
| 173 | ``` |
| 174 | |
| 175 | Persist `createIntent` before sending it. Recover an uncertain creation with |
| 176 | the same operation key and original body; never mint a new key just because a |
| 177 | response was lost. A turn likewise uses a persisted `operation_key`; inspect |
| 178 | `GET /v1/threads/{id}/turn-operations/{operation_key}` after an uncertain turn |
| 179 | response. HTTP acceptance is not terminal completion. Read the canonical |
| 180 | snapshot, turn status, effective route metadata and events before reporting |
| 181 | the outcome. An aborted fetch closes the request; it does not cancel Engine |
| 182 | work. Use the explicit interrupt endpoint for that. |
| 183 | |
| 184 | | Control | Authenticated HTTP request | |
| 185 | | --- | --- | |
| 186 | | Discover capabilities | `GET /v1/runtime/info` | |
| 187 | | Discover models | `GET /v1/providers`, then `GET /v1/providers/{provider}/models?limit=250`; retain `model_provider_id` for configured routes and follow `nextCursor` | |
| 188 | | Create/read a thread | `POST /v1/threads` / `GET /v1/threads/{id}` | |
| 189 | | Resume | `POST /v1/threads/{id}/resume` | |
| 190 | | Start a turn | `POST /v1/threads/{id}/turns` with `{ "prompt": "…", "operation_key": "…" }` | |
| 191 | | Steer active work | `POST /v1/threads/{id}/turns/{turn_id}/steer` with `{ "prompt": "…" }` | |
| 192 | | Interrupt | `POST /v1/threads/{id}/turns/{turn_id}/interrupt` | |
| 193 | | Decide an approval | `POST /v1/approvals/{approval_id}` with `{ "decision": "allow" }` or `{ "decision": "deny" }`; `remember` defaults to false | |
| 194 | | Answer clarification | `POST /v1/user-input/{id}/{request_id}` with `{ "answers": [{ "id": "question-id", "label": "selected option", "value": "answer" }] }` | |
| 195 | |
| 196 | Encode each path identifier separately with `encodeURIComponent`. Decisions |
| 197 | must come from the user and target the exact pending request from that thread's |
| 198 | canonical `pending_approvals` or `pending_user_inputs`, including its turn/tool |
| 199 | identity. Submit them while work is active; do not queue them behind completion. |
| 200 | Expired or already answered IDs fail rather than settling another waiter. |
| 201 | Use the existing `threadEvents()` helper for SSE and its cursor/end rules below. |
| 202 | The snapshot's `latest_seq` is the initial subscription cursor; recover a |
| 203 | replay gap by reloading the snapshot, without replaying a mutation. |
| 204 | |
| 205 | This table is the core client journey, not an exhaustive schema or a claim |
| 206 | that every planned capability is enabled. Honor `info.capabilities` and the |
| 207 | [Runtime API contract](../../docs/RUNTIME_API.md), including permission, |
| 208 | operation-key recovery and authenticated stream handling. |
| 209 | |
| 210 | ## Read a thread journal |
| 211 | |
| 212 | `threadEvents(threadId, { sinceSeq, replayLimit, signal })` reads the existing |
| 213 | `GET /v1/threads/{id}/events` SSE endpoint. It never creates a thread or starts |
| 214 | a turn. Pass an `AbortSignal` to close the subscription. Redirects are refused, |
| 215 | and incomplete or oversized frames fail instead of producing partial records. |
| 216 | |
| 217 | The returned `seq` and `previous_seq` belong to Runtime. Keep the last accepted |
| 218 | `seq` for reconnects; sequence numbers need not be consecutive. Consumers should |
| 219 | validate the selected thread and predecessor cursor before advancing their own |
| 220 | read position. Authentication uses the client constructor's existing `token` |
| 221 | option and stays in the Authorization header. |
| 222 | |
| 223 | |
| 224 | Consumers that present **current** activity can pass `includeProgress: true`. |
| 225 | The same endpoint adds `progress=true` and advertises support with |
| 226 | `x-codewhale-event-progress: 1`. A Runtime without that capability fails |
| 227 | explicitly; a historical event is not a readiness signal. |
| 228 | |
| 229 | Opt-in streams include `{ event: "stream.progress", thread_id, seq, state }`, |
| 230 | where `state` is `replaying` or `live`. These are transport frames at the existing |
| 231 | journal cursor, not journal events or new sequence numbers. Initial replay and |
| 232 | broadcast-lag recovery are `replaying`. The stream becomes `live` only after |
| 233 | both durable history and the already queued live tail have been drained. A |
| 234 | request answered during replay therefore settles before readiness is reported. |
| 235 | Later lag can return the same connection to `replaying`. Consumers should stop |
| 236 | extending activity while replaying or disconnected and validate the thread and |
| 237 | cursor. Default streams retain the original event-only contract, plus the |
| 238 | final frame below. |
| 239 | |
| 240 | ### Stream end |
| 241 | |
| 242 | Whenever the Runtime ends a thread stream on purpose, the last item is |
| 243 | `{ event: "stream.end", thread_id, reason, last_seq, retryable }`. It is not a |
| 244 | journal event and has no `seq`. When `retryable` is true, call `threadEvents` |
| 245 | again with `sinceSeq: last_seq`; otherwise stop and reload the thread snapshot. |
| 246 | Runtimes that send it advertise `x-codewhale-stream-end: 1`. If the iterator |
| 247 | ends without it, the connection was lost: resume from the last `seq` you |
| 248 | accepted. The full client rule is in |
| 249 | [`docs/RUNTIME_API.md`](../../docs/RUNTIME_API.md#ending-and-resuming-a-thread-stream). |
| 250 | |
| 251 | Use `isThreadStreamEnd` to narrow iterator items in TypeScript. Journal event |
| 252 | names remain open-ended, so checking `event === "stream.end"` alone cannot |
| 253 | narrow the union: |
| 254 | |
| 255 | ```ts |
| 256 | import { isThreadStreamEnd } from "@codewhale/runtime-sdk"; |
| 257 | |
| 258 | for await (const item of client.threadEvents(threadId)) { |
| 259 | if (isThreadStreamEnd(item)) { |
| 260 | console.log(item.reason, item.last_seq, item.retryable); |
| 261 | } else { |
| 262 | console.log(item.seq, item.payload); |
| 263 | } |
| 264 | } |
| 265 | ``` |
| 266 |