@steerable/agent-runtime 0.0.0-stage → 0.9.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,141 @@
1
- # Temporary Holding Version
1
+ # @steerable/agent-runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official TypeScript production runtime for the Steerable framework.
4
+
5
+ Python is the only production implementation of the framework's harness and
6
+ CoreLoop. This package is how a pure-TypeScript product runs it in
7
+ production: it owns the embedded Python sidecar process (spawn, ready
8
+ handshake, health ping, bounded auto-restart, graceful drain) and exposes
9
+ the CoreLoop-level API over the sidecar's JSON-RPC surface. You never write
10
+ subprocess management, and because the TS runtime drives the same Python
11
+ CoreLoop the server uses, there is no second implementation to drift.
12
+
13
+ ## Install & prerequisites
14
+
15
+ ```sh
16
+ npm install @steerable/agent-runtime
17
+ ```
18
+
19
+ npm also installs one `@steerable/runtime-<target>` package for your platform,
20
+ as an optional dependency of this package. It carries the Python sidecar, the
21
+ `run_code` interpreter and the egress proxy, so nothing else has to be
22
+ installed.
23
+
24
+ The interpreter resolves in this order:
25
+
26
+ 1. the `python` option, then `STEERABLE_SIDECAR_PYTHON`
27
+ 2. the platform package installed above
28
+ 3. a framework checkout's `.venv` (so an example inside the repo runs from
29
+ source)
30
+ 4. `STEERABLE_PYTHON`, then `python3` on `PATH`
31
+
32
+ Point at a specific interpreter with the `python` option when you ship your own
33
+ runtime. `resolveRuntimePython()` exposes the same resolution if you need to
34
+ report it.
35
+
36
+ Each platform package carries a `runtime.json` with SHA-256 digests for its
37
+ files; the interpreter and proxy are verified the first time they are used, and
38
+ a mismatch refuses to start rather than running a modified binary.
39
+
40
+ ## Upgrading from 0.8
41
+
42
+ - The interpreter now comes from the platform package instead of
43
+ `STEERABLE_PYTHON` or the system `python3`. Existing overrides still win.
44
+ - `engines.node` is `>=22.19.0`; the package no longer requires Node 26.
45
+ - This package is published to npm, so remove any `link:` specifier pointing at
46
+ a framework checkout.
47
+
48
+ ## Quick start
49
+
50
+ ```ts
51
+ import { AgentRuntime } from '@steerable/agent-runtime';
52
+
53
+ const runtime = new AgentRuntime({
54
+ tools: {
55
+ // Host tools the CoreLoop may call back over the reverse channel.
56
+ read_file: async ({ path }) => ({ success: true, result: await readFile(String(path), 'utf8') }),
57
+ },
58
+ });
59
+ await runtime.start();
60
+
61
+ const session = await runtime.createSession({ chatId: 'chat-1', userId: 'me' });
62
+ const turn = await runtime.chatStream({
63
+ provider: 'openai_compat',
64
+ model: 'deepseek-chat',
65
+ baseUrl: process.env.LLM_BASE_URL,
66
+ apiKey: process.env.LLM_API_KEY,
67
+ messages: [{ role: 'user', content: 'hello' }],
68
+ });
69
+
70
+ for await (const event of turn.events) {
71
+ // content | tool_call | tool_result | usage | orchestration | done | error
72
+ }
73
+ const { status, cancelled } = await turn.done;
74
+
75
+ await runtime.close();
76
+ ```
77
+
78
+ ## API map
79
+
80
+ | Runtime API | Sidecar RPC |
81
+ | --- | --- |
82
+ | `start()` / `close()` | process lifecycle + `system.shutdown` |
83
+ | `ping()` | `system.ping` |
84
+ | `createSession` / `resumeSession` / `listSessions` | `agent.session.*` |
85
+ | `forkSession` / `sessionBranches` | `agent.session.fork` / `agent.session.branches` |
86
+ | `sessionMessages` | `agent.session.messages` |
87
+ | `chatStream` / `cancelChat` / `steerChat` / `forkChat` | `agent.chat.*` |
88
+ | `listTools` / `invokeTool` | `tool.list` / `tool.invoke` |
89
+ | `listSkills` | `skills.list` |
90
+ | `applyEdits` | `workspace.apply_edits` |
91
+ | `fetchTrace` / `exportTrace` / `exportMetrics` | `trace.fetch` / `trace.export` / `metrics.export` |
92
+ | `getConfig` / `setConfig` | `config.get` / `config.set` |
93
+
94
+ The full wire contract is [docs/spec/sidecar.md](../../../docs/spec/sidecar.md).
95
+ A CI gate (`test/surface.test.ts`) asserts this surface matches the methods
96
+ the Python sidecar registers — the two cannot drift.
97
+
98
+ `chatStream` defaults `useCoreLoop: true` on the request: the runtime's
99
+ API (cooperative cancel, steer, orchestration) only exists on the sidecar's
100
+ CoreLoop path. Pass `useCoreLoop: false` to opt into the legacy
101
+ direct-stream path explicitly.
102
+
103
+ ## Testing
104
+
105
+ Unit tests run against `test/fake-sidecar.mjs` (a Node script speaking the
106
+ wire protocol). `test/e2e-real-sidecar.test.ts` is a true end-to-end gate:
107
+ it spawns the **real** Python sidecar from the repo's uv venv and drives a
108
+ full tool-calling turn — CoreLoop → OpenAI-compatible HTTP → local mock
109
+ server → reverse-channel `tool.invoke` → second LLM round — plus a
110
+ cooperative-cancel run. It self-skips when `.venv` cannot import
111
+ `steerable_sidecar` (run `uv sync` at the repo root to enable).
112
+
113
+ ## React UI
114
+
115
+ `@steerable/agent-ui` hooks consume the runtime directly:
116
+
117
+ ```tsx
118
+ import { createChatStreamTransport, createSessionTransport } from '@steerable/agent-runtime';
119
+ import { useChatStream, useAgentSession } from '@steerable/agent-ui';
120
+
121
+ const sessionTransport = createSessionTransport(runtime);
122
+ const chatTransport = createChatStreamTransport(runtime, {
123
+ sessionId: () => currentSessionId,
124
+ params: { provider: 'openai_compat', model: 'deepseek-chat' },
125
+ });
126
+ ```
127
+
128
+ ## Lifecycle semantics
129
+
130
+ - **Ready handshake** — `start()` resolves only after `lifecycle.ready` and a
131
+ `system.ping` round-trip; a half-booted process never answers requests.
132
+ - **Auto-restart** — an unexpected exit of a *fully booted* process triggers
133
+ up to `maxRestarts` restarts with exponential backoff; boot failures are
134
+ not retried (they are almost always deterministic). Requests made while
135
+ down reject fast with `SidecarNotReadyError`.
136
+ - **Graceful close** — `close()` sends `system.shutdown`, waits, then
137
+ escalates SIGTERM → SIGKILL. A close during a restart cycle suppresses the
138
+ pending restart.
139
+ - **Cancellation** — `cancelChat(streamId)` is cooperative: the CoreLoop
140
+ winds down at the next safe point and the terminal `done` event still
141
+ arrives with `status: 'cancelled'`.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@steerable/agent-runtime` — the official TypeScript production runtime
3
+ * for the Steerable framework. Owns the embedded Python sidecar lifecycle
4
+ * and exposes the CoreLoop-level API; see `docs/spec/architecture.md`
5
+ * ("Official TS production entry") and `docs/spec/sidecar.md`.
6
+ */
7
+ export { JsonRpcPeer, JsonRpcRemoteError, JsonRpcTransportClosedError, } from './jsonrpc.js';
8
+ export { SidecarNotReadyError, SidecarProcess, SidecarStartError, type SidecarProcessOptions, type SidecarReadyInfo, type SidecarRestartPolicy, } from './sidecar.js';
9
+ export { PLATFORM_PACKAGE_SCOPE, platformPackageName, resetPlatformRuntimeCache, resolvePlatformRuntime, supportedTargetsLine, verifyPlatformRuntimeDeep, type PlatformRuntime, type PlatformRuntimeFailure, type PlatformRuntimeFailureReason, type PlatformRuntimeManifest, type PlatformRuntimeResult, type RuntimeFile, } from './platform-runtime.js';
10
+ export { SIDECAR_METHODS, SIDECAR_NOTIFICATIONS, type SidecarMethod, type SidecarNotification, } from './methods.js';
11
+ export { AgentRuntime, type AgentRuntimeOptions, type ApplyEditsResult, type BranchFamily, type BranchPoint, type ChatStreamHandle, type ChatStreamParams, type ChatStreamStatus, type SessionMessages, type SkillInfo, type ToolDescriptor, type MetricsExportResult, type MetricsExportSample, type TraceExportResult, type TraceFetchResult, } from './runtime.js';
12
+ export { createChatStreamTransport, createSessionTransport, type AgentSessionTransport, type ChatStreamSendInput, type ChatStreamTransport, type ChatStreamTransportOptions, } from './transports.js';
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@steerable/agent-runtime` — the official TypeScript production runtime
3
+ * for the Steerable framework. Owns the embedded Python sidecar lifecycle
4
+ * and exposes the CoreLoop-level API; see `docs/spec/architecture.md`
5
+ * ("Official TS production entry") and `docs/spec/sidecar.md`.
6
+ */
7
+ export { JsonRpcPeer, JsonRpcRemoteError, JsonRpcTransportClosedError, } from './jsonrpc.js';
8
+ export { SidecarNotReadyError, SidecarProcess, SidecarStartError, } from './sidecar.js';
9
+ export { PLATFORM_PACKAGE_SCOPE, platformPackageName, resetPlatformRuntimeCache, resolvePlatformRuntime, supportedTargetsLine, verifyPlatformRuntimeDeep, } from './platform-runtime.js';
10
+ export { SIDECAR_METHODS, SIDECAR_NOTIFICATIONS, } from './methods.js';
11
+ export { AgentRuntime, } from './runtime.js';
12
+ export { createChatStreamTransport, createSessionTransport, } from './transports.js';
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Minimal line-delimited JSON-RPC 2.0 peer over a child process's
3
+ * stdin/stdout, matching the framing in `docs/spec/sidecar.md`.
4
+ *
5
+ * Three inbound frame kinds are dispatched:
6
+ * - response (`id` + `result`/`error`) → resolves the pending request
7
+ * - notification (`method`, no `id`) → `onNotification`
8
+ * - reverse request (`id` + `method`) → `onRequest`, and this client
9
+ * writes the response back (the sidecar calls host tools this way)
10
+ *
11
+ * The client owns no reconnection logic — that lives in `SidecarProcess`.
12
+ * When the transport dies every pending request rejects with
13
+ * `JsonRpcTransportClosedError` so callers fail fast instead of hanging.
14
+ */
15
+ export interface JsonRpcRequest {
16
+ jsonrpc: '2.0';
17
+ id: number | string;
18
+ method: string;
19
+ params?: unknown;
20
+ }
21
+ export interface JsonRpcNotification {
22
+ jsonrpc: '2.0';
23
+ method: string;
24
+ params?: unknown;
25
+ }
26
+ export interface JsonRpcSuccessResponse {
27
+ jsonrpc: '2.0';
28
+ id: number | string;
29
+ result: unknown;
30
+ }
31
+ export interface JsonRpcErrorResponse {
32
+ jsonrpc: '2.0';
33
+ id: number | string;
34
+ error: {
35
+ code: number;
36
+ message: string;
37
+ data?: unknown;
38
+ };
39
+ }
40
+ export type JsonRpcInbound = JsonRpcNotification | JsonRpcSuccessResponse | JsonRpcErrorResponse | (JsonRpcRequest & {
41
+ id: number | string;
42
+ });
43
+ export declare class JsonRpcRemoteError extends Error {
44
+ readonly code: number;
45
+ readonly data: unknown;
46
+ constructor(code: number, message: string, data?: unknown);
47
+ }
48
+ export declare class JsonRpcTransportClosedError extends Error {
49
+ constructor(message?: string);
50
+ }
51
+ export interface JsonRpcPeerOptions {
52
+ /** Bytes written here go to the peer (child stdin). */
53
+ write: (line: string) => void;
54
+ /** Sidecar-originated notifications (stream.chunk, lifecycle.*, …). */
55
+ onNotification?: (method: string, params: unknown) => void;
56
+ /**
57
+ * Reverse-channel requests (sidecar → host, e.g. `tool.invoke`). Return
58
+ * the result; throw to send a JSON-RPC error back. Unhandled methods
59
+ * answer `-32601 Method not found`.
60
+ */
61
+ onRequest?: (method: string, params: unknown) => Promise<unknown>;
62
+ }
63
+ export declare class JsonRpcPeer {
64
+ private readonly writeLine;
65
+ private readonly onNotification;
66
+ private readonly onRequest;
67
+ private readonly pending;
68
+ private nextId;
69
+ private buffer;
70
+ private closed;
71
+ constructor(options: JsonRpcPeerOptions);
72
+ /**
73
+ * Feed raw stdout bytes. Frames are newline-delimited JSON; partial lines
74
+ * are buffered until their terminator arrives.
75
+ */
76
+ feed(chunk: string): void;
77
+ /** Send a request and await its result. Rejects on remote error or close. */
78
+ request<TResult = unknown>(method: string, params?: unknown, options?: {
79
+ timeoutMs?: number | null;
80
+ }): Promise<TResult>;
81
+ /**
82
+ * Mark the transport dead: reject every pending request. Idempotent; the
83
+ * peer is not usable afterwards (a restarted process builds a new peer).
84
+ */
85
+ close(reason?: string): void;
86
+ private dispatch;
87
+ private answerReverse;
88
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Minimal line-delimited JSON-RPC 2.0 peer over a child process's
3
+ * stdin/stdout, matching the framing in `docs/spec/sidecar.md`.
4
+ *
5
+ * Three inbound frame kinds are dispatched:
6
+ * - response (`id` + `result`/`error`) → resolves the pending request
7
+ * - notification (`method`, no `id`) → `onNotification`
8
+ * - reverse request (`id` + `method`) → `onRequest`, and this client
9
+ * writes the response back (the sidecar calls host tools this way)
10
+ *
11
+ * The client owns no reconnection logic — that lives in `SidecarProcess`.
12
+ * When the transport dies every pending request rejects with
13
+ * `JsonRpcTransportClosedError` so callers fail fast instead of hanging.
14
+ */
15
+ export class JsonRpcRemoteError extends Error {
16
+ code;
17
+ data;
18
+ constructor(code, message, data) {
19
+ super(message);
20
+ this.name = 'JsonRpcRemoteError';
21
+ this.code = code;
22
+ this.data = data;
23
+ }
24
+ }
25
+ export class JsonRpcTransportClosedError extends Error {
26
+ constructor(message = 'json-rpc transport closed') {
27
+ super(message);
28
+ this.name = 'JsonRpcTransportClosedError';
29
+ }
30
+ }
31
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
32
+ export class JsonRpcPeer {
33
+ writeLine;
34
+ onNotification;
35
+ onRequest;
36
+ pending = new Map();
37
+ nextId = 1;
38
+ buffer = '';
39
+ closed = false;
40
+ constructor(options) {
41
+ this.writeLine = options.write;
42
+ this.onNotification = options.onNotification ?? (() => undefined);
43
+ this.onRequest = options.onRequest ?? null;
44
+ }
45
+ /**
46
+ * Feed raw stdout bytes. Frames are newline-delimited JSON; partial lines
47
+ * are buffered until their terminator arrives.
48
+ */
49
+ feed(chunk) {
50
+ this.buffer += chunk;
51
+ for (;;) {
52
+ const nl = this.buffer.indexOf('\n');
53
+ if (nl === -1)
54
+ return;
55
+ const line = this.buffer.slice(0, nl).trim();
56
+ this.buffer = this.buffer.slice(nl + 1);
57
+ if (line.length === 0)
58
+ continue;
59
+ let frame;
60
+ try {
61
+ frame = JSON.parse(line);
62
+ }
63
+ catch {
64
+ // Non-JSON stdout (a stray print inside the sidecar) must not kill
65
+ // the channel — the protocol owns stdout, so anything else is noise.
66
+ continue;
67
+ }
68
+ this.dispatch(frame);
69
+ }
70
+ }
71
+ /** Send a request and await its result. Rejects on remote error or close. */
72
+ request(method, params, options) {
73
+ if (this.closed) {
74
+ return Promise.reject(new JsonRpcTransportClosedError());
75
+ }
76
+ const id = this.nextId++;
77
+ const timeoutMs = options && options.timeoutMs !== undefined
78
+ ? options.timeoutMs
79
+ : DEFAULT_REQUEST_TIMEOUT_MS;
80
+ return new Promise((resolve, reject) => {
81
+ const timer = timeoutMs === null
82
+ ? null
83
+ : setTimeout(() => {
84
+ if (this.pending.delete(id)) {
85
+ reject(new JsonRpcTransportClosedError(`request ${method} timed out after ${timeoutMs}ms`));
86
+ }
87
+ }, timeoutMs);
88
+ this.pending.set(id, {
89
+ resolve: resolve,
90
+ reject,
91
+ timer,
92
+ });
93
+ const frame = { jsonrpc: '2.0', id, method };
94
+ if (params !== undefined)
95
+ frame.params = params;
96
+ this.writeLine(JSON.stringify(frame) + '\n');
97
+ });
98
+ }
99
+ /**
100
+ * Mark the transport dead: reject every pending request. Idempotent; the
101
+ * peer is not usable afterwards (a restarted process builds a new peer).
102
+ */
103
+ close(reason = 'json-rpc transport closed') {
104
+ if (this.closed)
105
+ return;
106
+ this.closed = true;
107
+ const err = new JsonRpcTransportClosedError(reason);
108
+ for (const [, p] of this.pending) {
109
+ if (p.timer)
110
+ clearTimeout(p.timer);
111
+ p.reject(err);
112
+ }
113
+ this.pending.clear();
114
+ }
115
+ dispatch(frame) {
116
+ const hasMethod = 'method' in frame && typeof frame.method === 'string';
117
+ const hasId = 'id' in frame && frame.id !== undefined;
118
+ if (hasMethod && hasId) {
119
+ void this.answerReverse(frame);
120
+ return;
121
+ }
122
+ if (hasMethod) {
123
+ this.onNotification(frame.method, frame.params);
124
+ return;
125
+ }
126
+ if (hasId) {
127
+ const id = frame.id;
128
+ const p = this.pending.get(id);
129
+ if (!p)
130
+ return; // late response for an already-timed-out request
131
+ this.pending.delete(id);
132
+ if (p.timer)
133
+ clearTimeout(p.timer);
134
+ if ('error' in frame && frame.error) {
135
+ p.reject(new JsonRpcRemoteError(frame.error.code, frame.error.message, frame.error.data));
136
+ }
137
+ else {
138
+ p.resolve(frame.result);
139
+ }
140
+ }
141
+ }
142
+ async answerReverse(frame) {
143
+ const respond = (body) => {
144
+ if (!this.closed) {
145
+ this.writeLine(JSON.stringify({ jsonrpc: '2.0', id: frame.id, ...body }) + '\n');
146
+ }
147
+ };
148
+ if (!this.onRequest) {
149
+ respond({
150
+ error: { code: -32601, message: 'Method not found', data: { method: frame.method } },
151
+ });
152
+ return;
153
+ }
154
+ try {
155
+ const result = await this.onRequest(frame.method, frame.params);
156
+ respond({ result: result ?? null });
157
+ }
158
+ catch (err) {
159
+ respond({
160
+ error: {
161
+ code: -32000,
162
+ message: err instanceof Error ? err.message : String(err),
163
+ },
164
+ });
165
+ }
166
+ }
167
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The sidecar JSON-RPC method surface this runtime covers, as data.
3
+ *
4
+ * This list is the TS side of the 3.2.4 conformance gate:
5
+ * `test/surface.test.ts` parses the `register("<method>", …)` lines out of
6
+ * the Python sidecar (`packages/sidecar/py/src/steerable_sidecar/sidecar.py`)
7
+ * and asserts the two sets are identical — so a method added to the sidecar
8
+ * without a runtime wrapper (or a wrapper for a method the sidecar no longer
9
+ * has) fails CI instead of drifting silently.
10
+ */
11
+ /** Every host→sidecar request method the sidecar registers. */
12
+ export declare const SIDECAR_METHODS: readonly ["system.ping", "system.shutdown", "system.shutdown_now", "agent.session.create", "agent.session.resume", "agent.session.list", "agent.session.fork", "agent.session.branches", "agent.session.messages", "agent.chat.stream", "agent.chat.cancel", "agent.chat.steer", "agent.chat.fork", "agent.chat.compact", "agent.session.tree", "tool.list", "tool.invoke", "workspace.apply_edits", "skills.list", "trace.fetch", "trace.export", "metrics.export", "config.get", "config.set", "compat.describe", "sandbox.describe", "harness.describe", "models.list", "presets.describe", "presets.resolve", "catalog.describe", "plugin.list", "plugin.enable", "plugin.disable", "plugin.reload", "plugin.tools.describe"];
13
+ export type SidecarMethod = (typeof SIDECAR_METHODS)[number];
14
+ /** Notification methods the sidecar pushes (no id, no response). */
15
+ export declare const SIDECAR_NOTIFICATIONS: readonly ["lifecycle.ready", "lifecycle.shutdown", "stream.chunk", "stream.done", "stream.error", "agent.child"];
16
+ export type SidecarNotification = (typeof SIDECAR_NOTIFICATIONS)[number];