@ggui-ai/agent-runtime 0.1.0-rc.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 describing the origin of the Work and
141
+ 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 Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
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 2026 Loqu, Inc. (Guuey)
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
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # @ggui-ai/agent-runtime
2
+
3
+ Pluggable adapter seam for "the thing that runs an agent."
4
+
5
+ Part of the **ggui protocol** toolchain, this package defines a small contract —
6
+ `AgentRuntimeAdapter` — for supervising whatever actually executes an agent: the
7
+ Claude Agent SDK, OpenAI Agents, the Vercel AI SDK, a plain subprocess, or anything
8
+ else. A host consumes this seam so no agent framework is hardcoded into its dev loop;
9
+ swapping runtimes never touches host code.
10
+
11
+ This package exposes the contract types plus an in-memory stub adapter
12
+ (`createStubAgentRuntime`) for tests and local development. Framework-specific
13
+ adapters live in their own packages so consumers opt into the dependency weight.
14
+
15
+ ## Exports
16
+
17
+ | Import | Contents |
18
+ | -------------------------------- | ---------------------------------------------------------- |
19
+ | `@ggui-ai/agent-runtime` | The `AgentRuntimeAdapter` contract and the in-memory stub. |
20
+ | `@ggui-ai/agent-runtime/process` | A subprocess-backed adapter. |
21
+
22
+ ## License
23
+
24
+ Apache-2.0
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `@ggui-ai/agent-runtime` — pluggable adapter seam for "the thing
3
+ * that runs an agent," consumed by the open dev engine
4
+ * (`@ggui-ai/dev-stack`) and any future non-dev host (bench
5
+ * runners, remote supervisors).
6
+ *
7
+ * This barrel exposes the contract + an in-memory stub adapter.
8
+ * Framework-specific adapters (Claude Agent SDK, OpenAI Agents,
9
+ * Vercel AI SDK, a plain subprocess) live in their own packages so
10
+ * consumers opt into the dependency weight.
11
+ *
12
+ * Design rule: the agent framework is NEVER hardcoded into the dev
13
+ * engine. This adapter seam carries every framework, so a host can
14
+ * swap runtimes without touching engine code.
15
+ */
16
+ export type { AgentRuntimeAdapter, AgentRuntimeCapabilities, AgentRuntimeEvent, AgentRuntimeHandle, AgentRuntimeListener, AgentRuntimeProjectIdentity, AgentRuntimeStartInput, AgentRuntimeStatus, } from './types.js';
17
+ export { createStubAgentRuntime, type StubAgentRuntimeController, type StubAgentRuntimeOptions, } from './stub.js';
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,YAAY,EACV,mBAAmB,EACnB,wBAAwB,EACxB,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,2BAA2B,EAC3B,sBAAsB,EACtB,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,sBAAsB,EACtB,KAAK,0BAA0B,EAC/B,KAAK,uBAAuB,GAC7B,MAAM,WAAW,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { createStubAgentRuntime, } from './stub.js';
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Node subprocess reference adapter — the first real
3
+ * implementation of {@link AgentRuntimeAdapter}.
4
+ *
5
+ * Supervises a local agent that runs as a child process: spawns
6
+ * with an explicit `command` + `args`, streams stdout/stderr into
7
+ * the event channel, and maps process lifecycle signals onto the
8
+ * adapter's status machine (`starting` → `ready` → `stopped` |
9
+ * `crashed`).
10
+ *
11
+ * Reference only — deliberately NOT the architecture:
12
+ *
13
+ * - `command` + `args` are REQUIRED. The factory does not assume
14
+ * `npx tsx watch src/index.ts` (the `ggui dev` default) or
15
+ * any framework-specific entrypoint. A CLI wanting `.ts` input
16
+ * wraps its own `node --import=tsx` shape and passes it
17
+ * through; the adapter itself knows only how to spawn.
18
+ * - No framework detection. Claude / OpenAI / Vercel AI / LangGraph
19
+ * adapters live in their own packages and translate their own
20
+ * idioms onto this same seam.
21
+ * - No service-discovery assumptions. Optional `readyCheck` lets
22
+ * callers promote `starting → ready` on an HTTP probe; if
23
+ * omitted the adapter considers the child "ready" as soon as
24
+ * the spawn completes.
25
+ *
26
+ * Lives under `@ggui-ai/agent-runtime/process` so consumers that
27
+ * don't spawn subprocesses (browser-side hubs, future test
28
+ * runners) never pull the `node:child_process` dep by loading the
29
+ * root barrel.
30
+ */
31
+ import { type ChildProcess } from 'node:child_process';
32
+ import type { AgentRuntimeAdapter } from './types.js';
33
+ /**
34
+ * Optional HTTP-probe readiness gate. The adapter polls
35
+ * `http://127.0.0.1:<port>/<path>` and emits `status: 'ready'` on
36
+ * the first successful response. Before that the handle stays in
37
+ * `starting`.
38
+ *
39
+ * Kept narrow — no redirect following, no body inspection, no
40
+ * non-HTTP probes. Hosts wanting richer semantics (gRPC health,
41
+ * stdout-match) fork the adapter or post a specific probe layer
42
+ * on top. Keeps the reference impl honest.
43
+ */
44
+ export interface HttpReadyCheck {
45
+ readonly type: 'http';
46
+ /** Port to probe on 127.0.0.1. Required — we don't scan. */
47
+ readonly port: number;
48
+ /** Path to probe. Defaults to `'/'`. */
49
+ readonly path?: string;
50
+ /** Milliseconds between polls. Defaults to 250. */
51
+ readonly intervalMs?: number;
52
+ /** Overall timeout budget. Defaults to 30s. */
53
+ readonly timeoutMs?: number;
54
+ }
55
+ export type ReadyCheck = HttpReadyCheck;
56
+ export interface NodeProcessAgentRuntimeOptions {
57
+ /**
58
+ * Adapter name surfaced via `adapter.name`. Defaults to
59
+ * `'node-process'`. Override for clearer logs when multiple
60
+ * adapters coexist.
61
+ */
62
+ readonly name?: string;
63
+ /**
64
+ * Executable to run. Required — the factory takes NO default to
65
+ * avoid pinning a framework. The CLI or host decides whether
66
+ * this is `'node'`, `process.execPath`, or something else.
67
+ */
68
+ readonly command: string;
69
+ /** Args forwarded to the child. Required; pass `[]` for no args. */
70
+ readonly args: readonly string[];
71
+ /**
72
+ * Working directory for the child process. When omitted the
73
+ * adapter uses {@link AgentRuntimeStartInput.projectRoot} (or the
74
+ * parent's cwd as a last resort). Absolute paths only.
75
+ */
76
+ readonly cwd?: string;
77
+ /**
78
+ * Extra env vars forwarded into the child. MERGED with
79
+ * `startInput.env` (startInput wins on collision) and then with
80
+ * `process.env` (child inherits the rest of the parent env).
81
+ * Adapter never leaks env keys the caller didn't opt into by
82
+ * either source.
83
+ */
84
+ readonly env?: Readonly<Record<string, string>>;
85
+ /**
86
+ * Optional readiness probe. When omitted the adapter emits
87
+ * `status: 'ready'` immediately after spawn succeeds.
88
+ */
89
+ readonly readyCheck?: ReadyCheck;
90
+ /**
91
+ * Signal to send on `stop()`. Defaults to `'SIGTERM'`. After
92
+ * {@link shutdownTimeoutMs} the adapter escalates to `SIGKILL`.
93
+ */
94
+ readonly shutdownSignal?: NodeJS.Signals;
95
+ /** Grace period before SIGKILL. Defaults to {@link DEFAULT_SHUTDOWN_TIMEOUT_MS}. */
96
+ readonly shutdownTimeoutMs?: number;
97
+ /**
98
+ * Maximum bytes to buffer from a single log line before truncation.
99
+ * Useful for runaway stack traces — defaults to 16 KiB.
100
+ */
101
+ readonly maxLineBytes?: number;
102
+ /**
103
+ * Test seam — inject a spawner to exercise the adapter without
104
+ * touching the filesystem. Production code leaves this unset.
105
+ */
106
+ readonly spawner?: Spawner;
107
+ }
108
+ /**
109
+ * Minimal spawner contract — `spawn()` from `node:child_process`
110
+ * satisfies this. Broken out so tests can substitute a fake that
111
+ * emits crafted stdout / stderr / exit events.
112
+ */
113
+ export type Spawner = (command: string, args: readonly string[], options: {
114
+ cwd?: string;
115
+ env?: NodeJS.ProcessEnv;
116
+ }) => ChildProcess;
117
+ /**
118
+ * Construct a framework-neutral subprocess adapter. The returned
119
+ * adapter carries no framework-specific behaviour; callers pin the
120
+ * framework by choosing `command` + `args`.
121
+ */
122
+ export declare function createNodeProcessAgentRuntime(options: NodeProcessAgentRuntimeOptions): AgentRuntimeAdapter;
123
+ //# sourceMappingURL=process.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process.d.ts","sourceRoot":"","sources":["../src/process.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,OAAO,EAAS,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,KAAK,EACV,mBAAmB,EAMpB,MAAM,YAAY,CAAC;AASpB;;;;;;;;;;GAUG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,4DAA4D;IAC5D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,wCAAwC;IACxC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,mDAAmD;IACnD,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,+CAA+C;IAC/C,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,MAAM,UAAU,GAAG,cAAc,CAAC;AAExC,MAAM,WAAW,8BAA8B;IAC7C;;;;OAIG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;;OAMG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAChD;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;IACjC;;;OAGG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC;IACzC,oFAAoF;IACpF,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC;;;OAGG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED;;;;GAIG;AACH,MAAM,MAAM,OAAO,GAAG,CACpB,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,OAAO,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAA;CAAE,KAC/C,YAAY,CAAC;AAElB;;;;GAIG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,8BAA8B,GACtC,mBAAmB,CAoDrB"}
@@ -0,0 +1,349 @@
1
+ /**
2
+ * Node subprocess reference adapter — the first real
3
+ * implementation of {@link AgentRuntimeAdapter}.
4
+ *
5
+ * Supervises a local agent that runs as a child process: spawns
6
+ * with an explicit `command` + `args`, streams stdout/stderr into
7
+ * the event channel, and maps process lifecycle signals onto the
8
+ * adapter's status machine (`starting` → `ready` → `stopped` |
9
+ * `crashed`).
10
+ *
11
+ * Reference only — deliberately NOT the architecture:
12
+ *
13
+ * - `command` + `args` are REQUIRED. The factory does not assume
14
+ * `npx tsx watch src/index.ts` (the `ggui dev` default) or
15
+ * any framework-specific entrypoint. A CLI wanting `.ts` input
16
+ * wraps its own `node --import=tsx` shape and passes it
17
+ * through; the adapter itself knows only how to spawn.
18
+ * - No framework detection. Claude / OpenAI / Vercel AI / LangGraph
19
+ * adapters live in their own packages and translate their own
20
+ * idioms onto this same seam.
21
+ * - No service-discovery assumptions. Optional `readyCheck` lets
22
+ * callers promote `starting → ready` on an HTTP probe; if
23
+ * omitted the adapter considers the child "ready" as soon as
24
+ * the spawn completes.
25
+ *
26
+ * Lives under `@ggui-ai/agent-runtime/process` so consumers that
27
+ * don't spawn subprocesses (browser-side hubs, future test
28
+ * runners) never pull the `node:child_process` dep by loading the
29
+ * root barrel.
30
+ */
31
+ import { spawn } from 'node:child_process';
32
+ /** Default graceful-shutdown window before escalating to SIGKILL. */
33
+ const DEFAULT_SHUTDOWN_TIMEOUT_MS = 5_000;
34
+ /** Default readyCheck polling cadence. */
35
+ const DEFAULT_READY_INTERVAL_MS = 250;
36
+ /** Default readyCheck overall budget. */
37
+ const DEFAULT_READY_TIMEOUT_MS = 30_000;
38
+ /**
39
+ * Construct a framework-neutral subprocess adapter. The returned
40
+ * adapter carries no framework-specific behaviour; callers pin the
41
+ * framework by choosing `command` + `args`.
42
+ */
43
+ export function createNodeProcessAgentRuntime(options) {
44
+ if (!options.command || options.command.length === 0) {
45
+ throw new TypeError('createNodeProcessAgentRuntime: `command` is required');
46
+ }
47
+ const name = options.name ?? 'node-process';
48
+ const spawnImpl = options.spawner ??
49
+ ((cmd, args, opts) => spawn(cmd, args, { ...opts, stdio: ['ignore', 'pipe', 'pipe'] }));
50
+ return {
51
+ name,
52
+ capabilities: {
53
+ observable: true,
54
+ restartable: false,
55
+ },
56
+ async start(input) {
57
+ const cwd = options.cwd ?? input.projectRoot;
58
+ const env = {
59
+ ...process.env,
60
+ ...options.env,
61
+ ...input.env,
62
+ };
63
+ const child = spawnImpl(options.command, options.args, { cwd, env });
64
+ const handle = new NodeProcessHandle({
65
+ child,
66
+ runId: `node-process-${child.pid ?? 'nopid'}-${Date.now()}`,
67
+ shutdownSignal: options.shutdownSignal ?? 'SIGTERM',
68
+ shutdownTimeoutMs: options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS,
69
+ maxLineBytes: options.maxLineBytes ?? 16_384,
70
+ });
71
+ if (input.signal) {
72
+ const onAbort = () => {
73
+ void handle.stop();
74
+ };
75
+ if (input.signal.aborted) {
76
+ queueMicrotask(onAbort);
77
+ }
78
+ else {
79
+ input.signal.addEventListener('abort', onAbort, { once: true });
80
+ }
81
+ }
82
+ if (options.readyCheck) {
83
+ handle.runReadyCheck(options.readyCheck);
84
+ }
85
+ else {
86
+ handle.markReadyOnNextTick();
87
+ }
88
+ return handle;
89
+ },
90
+ };
91
+ }
92
+ /**
93
+ * Concrete handle wrapping a `ChildProcess`. Owns the lifecycle
94
+ * transitions and the stdout/stderr line fanout.
95
+ */
96
+ class NodeProcessHandle {
97
+ runId;
98
+ _status = 'starting';
99
+ listeners = new Set();
100
+ child;
101
+ shutdownSignal;
102
+ shutdownTimeoutMs;
103
+ maxLineBytes;
104
+ stopping = false;
105
+ readyAbort = null;
106
+ stdoutBuffer = '';
107
+ stderrBuffer = '';
108
+ constructor(options) {
109
+ this.runId = options.runId;
110
+ this.child = options.child;
111
+ this.shutdownSignal = options.shutdownSignal;
112
+ this.shutdownTimeoutMs = options.shutdownTimeoutMs;
113
+ this.maxLineBytes = options.maxLineBytes;
114
+ this.child.stdout?.setEncoding('utf-8');
115
+ this.child.stderr?.setEncoding('utf-8');
116
+ this.child.stdout?.on('data', (chunk) => this.onChunk('stdout', chunk));
117
+ this.child.stderr?.on('data', (chunk) => this.onChunk('stderr', chunk));
118
+ this.child.on('error', (err) => {
119
+ this.emit({
120
+ type: 'error',
121
+ message: err instanceof Error ? err.message : String(err),
122
+ timestamp: Date.now(),
123
+ });
124
+ });
125
+ this.child.on('exit', (code, signal) => this.onExit(code, signal));
126
+ }
127
+ get status() {
128
+ return this._status;
129
+ }
130
+ subscribe(listener) {
131
+ this.listeners.add(listener);
132
+ return () => {
133
+ this.listeners.delete(listener);
134
+ };
135
+ }
136
+ async stop() {
137
+ if (this._status === 'stopped' || this._status === 'crashed')
138
+ return;
139
+ if (this.stopping)
140
+ return;
141
+ this.stopping = true;
142
+ this.cancelReadyCheck();
143
+ if (this.child.exitCode !== null || this.child.signalCode !== null) {
144
+ // Already gone.
145
+ this.transitionTo('stopped');
146
+ return;
147
+ }
148
+ // Graceful request first.
149
+ this.child.kill(this.shutdownSignal);
150
+ // Escalate to SIGKILL if the child doesn't exit in time. We
151
+ // only escalate — the `exit` handler owns the final status
152
+ // transition once the kernel reports the process gone.
153
+ await new Promise((resolve) => {
154
+ const killTimer = setTimeout(() => {
155
+ try {
156
+ this.child.kill('SIGKILL');
157
+ }
158
+ catch {
159
+ // Already exited between checks.
160
+ }
161
+ }, this.shutdownTimeoutMs).unref?.();
162
+ this.child.once('exit', () => {
163
+ if (killTimer !== undefined)
164
+ clearTimeout(killTimer);
165
+ resolve();
166
+ });
167
+ });
168
+ }
169
+ /**
170
+ * Schedule a ready transition on a macrotask. Called when
171
+ * there's no readyCheck configured — the adapter considers the
172
+ * child "ready" as soon as it exists. A `setTimeout(…, 0)`
173
+ * macrotask is deliberate: subscribers attached synchronously
174
+ * after `await adapter.start()` must land BEFORE the emit fires
175
+ * (microtasks would race with the `async` resolution). Guarded
176
+ * so an immediate stop() or crash doesn't raise `ready` over a
177
+ * terminal state.
178
+ */
179
+ markReadyOnNextTick() {
180
+ const timer = setTimeout(() => {
181
+ if (this._status === 'starting') {
182
+ this.transitionTo('ready');
183
+ }
184
+ }, 0);
185
+ timer.unref?.();
186
+ }
187
+ runReadyCheck(check) {
188
+ const abort = new AbortController();
189
+ this.readyAbort = abort;
190
+ void runHttpReadyCheck(check, abort.signal).then((result) => {
191
+ if (abort.signal.aborted)
192
+ return;
193
+ if (this._status !== 'starting')
194
+ return;
195
+ if (result.ok) {
196
+ this.transitionTo('ready');
197
+ }
198
+ else {
199
+ this.emit({
200
+ type: 'error',
201
+ message: `readyCheck failed: ${result.reason}`,
202
+ timestamp: Date.now(),
203
+ });
204
+ }
205
+ }, (err) => {
206
+ if (abort.signal.aborted)
207
+ return;
208
+ const message = err instanceof Error ? err.message : String(err);
209
+ this.emit({ type: 'error', message, timestamp: Date.now() });
210
+ });
211
+ }
212
+ cancelReadyCheck() {
213
+ this.readyAbort?.abort();
214
+ this.readyAbort = null;
215
+ }
216
+ onChunk(stream, chunk) {
217
+ const buffer = stream === 'stdout' ? 'stdoutBuffer' : 'stderrBuffer';
218
+ let remaining = (this[buffer] + chunk);
219
+ let lineEnd = remaining.indexOf('\n');
220
+ while (lineEnd !== -1) {
221
+ const raw = remaining.slice(0, lineEnd).replace(/\r$/, '');
222
+ const line = raw.length > this.maxLineBytes ? `${raw.slice(0, this.maxLineBytes)}…` : raw;
223
+ this.emit({
224
+ type: 'log',
225
+ stream,
226
+ line,
227
+ timestamp: Date.now(),
228
+ });
229
+ remaining = remaining.slice(lineEnd + 1);
230
+ lineEnd = remaining.indexOf('\n');
231
+ }
232
+ this[buffer] = remaining;
233
+ }
234
+ onExit(code, signal) {
235
+ // Flush any tail-buffered output as a final line each.
236
+ for (const stream of ['stdout', 'stderr']) {
237
+ const key = stream === 'stdout' ? 'stdoutBuffer' : 'stderrBuffer';
238
+ const tail = this[key];
239
+ if (tail.length > 0) {
240
+ this.emit({
241
+ type: 'log',
242
+ stream,
243
+ line: tail.replace(/\r$/, ''),
244
+ timestamp: Date.now(),
245
+ });
246
+ this[key] = '';
247
+ }
248
+ }
249
+ this.cancelReadyCheck();
250
+ // Crashed vs stopped:
251
+ // - `stop()` was called → stopping=true, we requested the exit.
252
+ // - external signal we asked for (`shutdownSignal`) → stopped.
253
+ // - non-zero exit code WITHOUT our request → crashed.
254
+ // - zero exit code WITHOUT our request → stopped (graceful self-exit).
255
+ if (this.stopping) {
256
+ this.transitionTo('stopped');
257
+ return;
258
+ }
259
+ if (signal !== null) {
260
+ // Unexpected signal the dev-stack didn't send → crashed.
261
+ this.emit({
262
+ type: 'error',
263
+ message: `process terminated by signal ${signal}`,
264
+ timestamp: Date.now(),
265
+ });
266
+ this.transitionTo('crashed');
267
+ return;
268
+ }
269
+ if (code === 0) {
270
+ this.transitionTo('stopped');
271
+ }
272
+ else {
273
+ this.emit({
274
+ type: 'error',
275
+ message: `process exited with code ${code ?? 'null'}`,
276
+ timestamp: Date.now(),
277
+ });
278
+ this.transitionTo('crashed');
279
+ }
280
+ }
281
+ transitionTo(status) {
282
+ if (this._status === status)
283
+ return;
284
+ this.emit({ type: 'status', status, timestamp: Date.now() });
285
+ }
286
+ emit(event) {
287
+ if (event.type === 'status') {
288
+ this._status = event.status;
289
+ }
290
+ const snapshot = Array.from(this.listeners);
291
+ for (const listener of snapshot) {
292
+ try {
293
+ listener(event);
294
+ }
295
+ catch {
296
+ // A bad listener MUST NOT break fanout. Adapter-level
297
+ // errors surface through `error` events; a listener that
298
+ // throws is a consumer bug.
299
+ }
300
+ }
301
+ }
302
+ }
303
+ /**
304
+ * HTTP readiness probe. Polls `http://127.0.0.1:port<path>` at the
305
+ * configured interval until it gets a 2xx, the caller aborts, or
306
+ * the overall budget expires.
307
+ *
308
+ * Uses the built-in `fetch` with its own `AbortController` per
309
+ * request so a slow connect doesn't block the poll cadence. The
310
+ * outer `signal` cancels the whole loop on caller abort (handle
311
+ * shutdown).
312
+ */
313
+ async function runHttpReadyCheck(check, signal) {
314
+ const interval = check.intervalMs ?? DEFAULT_READY_INTERVAL_MS;
315
+ const budget = check.timeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
316
+ const path = check.path ?? '/';
317
+ const url = `http://127.0.0.1:${check.port}${path.startsWith('/') ? path : `/${path}`}`;
318
+ const start = Date.now();
319
+ while (!signal.aborted) {
320
+ if (Date.now() - start > budget) {
321
+ return { ok: false, reason: `timeout after ${budget}ms probing ${url}` };
322
+ }
323
+ const perRequest = AbortSignal.timeout
324
+ ? AbortSignal.timeout(Math.max(interval, 100))
325
+ : undefined;
326
+ try {
327
+ const res = await fetch(url, { signal: perRequest });
328
+ if (res.ok)
329
+ return { ok: true };
330
+ }
331
+ catch {
332
+ // Not reachable yet — fall through to the sleep.
333
+ }
334
+ if (signal.aborted)
335
+ return { ok: false, reason: 'aborted' };
336
+ await sleep(interval, signal);
337
+ }
338
+ return { ok: false, reason: 'aborted' };
339
+ }
340
+ function sleep(ms, signal) {
341
+ return new Promise((resolve) => {
342
+ const timer = setTimeout(resolve, ms);
343
+ timer.unref?.();
344
+ signal.addEventListener('abort', () => {
345
+ clearTimeout(timer);
346
+ resolve();
347
+ }, { once: true });
348
+ });
349
+ }
package/dist/stub.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * In-memory stub adapter — a reference implementation that
3
+ * `@ggui-ai/dev-stack` tests, the hub's dev fixtures, and contract
4
+ * tests in this package use to exercise the seam without spawning
5
+ * real processes.
6
+ *
7
+ * The stub's behaviour is deterministic and fully controlled by
8
+ * the caller:
9
+ *
10
+ * - `start()` immediately transitions `starting → ready` via a
11
+ * status event, unless `manualReady` is set (in which case the
12
+ * caller drives the transition through the returned controller).
13
+ * - `stop()` transitions whatever-the-current-state is →
14
+ * `stopped` and resolves after all pending listeners have seen
15
+ * the event.
16
+ * - The returned controller lets tests emit arbitrary log / error
17
+ * events, flip status programmatically, and assert against
18
+ * whatever timing shape they care about.
19
+ *
20
+ * The stub is the shape new adapter implementations should imitate
21
+ * for their own event-loop plumbing: fanout set, single `status`
22
+ * field, idempotent stop, no global state.
23
+ */
24
+ import type { AgentRuntimeAdapter, AgentRuntimeHandle, AgentRuntimeStartInput, AgentRuntimeStatus } from './types.js';
25
+ export interface StubAgentRuntimeOptions {
26
+ /** Identifier surfaced via `adapter.name`. Defaults to `'stub'`. */
27
+ readonly name?: string;
28
+ /**
29
+ * When `true`, `start()` returns a handle in `starting` without
30
+ * emitting `ready`. Tests drive the transition via
31
+ * {@link StubAgentRuntimeController.emitStatus}.
32
+ */
33
+ readonly manualReady?: boolean;
34
+ }
35
+ /**
36
+ * Side-channel controller returned from
37
+ * {@link createStubAgentRuntime}. Production code should never hold
38
+ * one of these; they exist so tests can simulate arbitrary adapter
39
+ * behaviour.
40
+ */
41
+ export interface StubAgentRuntimeController {
42
+ /** Inputs the last `start()` call received. `null` before start. */
43
+ lastInput(): AgentRuntimeStartInput | null;
44
+ /** All handles ever produced (one per `start()`). */
45
+ handles(): readonly AgentRuntimeHandle[];
46
+ /**
47
+ * Inject a status event on the latest handle. Updates the handle's
48
+ * declarative `status` too.
49
+ */
50
+ emitStatus(status: AgentRuntimeStatus): void;
51
+ /** Inject a log event on the latest handle. */
52
+ emitLog(stream: 'stdout' | 'stderr', line: string): void;
53
+ /** Inject an error event on the latest handle. */
54
+ emitError(message: string): void;
55
+ /** Fail the next `start()` call with the given error. */
56
+ failNextStart(error: Error): void;
57
+ }
58
+ /**
59
+ * Construct a stub adapter + controller pair.
60
+ *
61
+ * const { adapter, controller } = createStubAgentRuntime();
62
+ * const handle = await adapter.start({ … });
63
+ * controller.emitLog('stderr', 'boot fail');
64
+ * await handle.stop();
65
+ */
66
+ export declare function createStubAgentRuntime(options?: StubAgentRuntimeOptions): {
67
+ adapter: AgentRuntimeAdapter;
68
+ controller: StubAgentRuntimeController;
69
+ };
70
+ //# sourceMappingURL=stub.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stub.d.ts","sourceRoot":"","sources":["../src/stub.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,KAAK,EACV,mBAAmB,EAEnB,kBAAkB,EAElB,sBAAsB,EACtB,kBAAkB,EACnB,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,uBAAuB;IACtC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAEvB;;;;OAIG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;CAChC;AAED;;;;;GAKG;AACH,MAAM,WAAW,0BAA0B;IACzC,oEAAoE;IACpE,SAAS,IAAI,sBAAsB,GAAG,IAAI,CAAC;IAC3C,qDAAqD;IACrD,OAAO,IAAI,SAAS,kBAAkB,EAAE,CAAC;IACzC;;;OAGG;IACH,UAAU,CAAC,MAAM,EAAE,kBAAkB,GAAG,IAAI,CAAC;IAC7C,+CAA+C;IAC/C,OAAO,CAAC,MAAM,EAAE,QAAQ,GAAG,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACzD,kDAAkD;IAClD,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,yDAAyD;IACzD,aAAa,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;CACnC;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,GAAE,uBAA4B,GACpC;IACD,OAAO,EAAE,mBAAmB,CAAC;IAC7B,UAAU,EAAE,0BAA0B,CAAC;CACxC,CA8EA"}
package/dist/stub.js ADDED
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Construct a stub adapter + controller pair.
3
+ *
4
+ * const { adapter, controller } = createStubAgentRuntime();
5
+ * const handle = await adapter.start({ … });
6
+ * controller.emitLog('stderr', 'boot fail');
7
+ * await handle.stop();
8
+ */
9
+ export function createStubAgentRuntime(options = {}) {
10
+ const name = options.name ?? 'stub';
11
+ const manualReady = options.manualReady ?? false;
12
+ const handles = [];
13
+ let lastInput = null;
14
+ let nextStartError = null;
15
+ const adapter = {
16
+ name,
17
+ capabilities: {
18
+ observable: true,
19
+ restartable: false,
20
+ },
21
+ async start(input) {
22
+ lastInput = input;
23
+ if (nextStartError) {
24
+ const err = nextStartError;
25
+ nextStartError = null;
26
+ throw err;
27
+ }
28
+ const handle = new StubHandle(`stub-run-${handles.length + 1}`, {
29
+ signal: input.signal,
30
+ });
31
+ handles.push(handle);
32
+ // Emit ready asynchronously unless the caller wants to drive it.
33
+ // A `setTimeout(…, 0)` macrotask guarantees the emit lands AFTER
34
+ // the caller's sync code post-`await adapter.start()` has run —
35
+ // so `handle.subscribe(…)` attached right after the await still
36
+ // catches the ready event. `queueMicrotask` would fire before the
37
+ // subscriber was registered because `async` resolution is also a
38
+ // microtask.
39
+ if (!manualReady) {
40
+ const timer = setTimeout(() => {
41
+ handle.emitIfStarting({
42
+ type: 'status',
43
+ status: 'ready',
44
+ timestamp: Date.now(),
45
+ });
46
+ }, 0);
47
+ timer.unref?.();
48
+ }
49
+ return handle;
50
+ },
51
+ };
52
+ const controller = {
53
+ lastInput: () => lastInput,
54
+ handles: () => handles,
55
+ emitStatus(status) {
56
+ currentHandle(handles).emit({
57
+ type: 'status',
58
+ status,
59
+ timestamp: Date.now(),
60
+ });
61
+ },
62
+ emitLog(stream, line) {
63
+ currentHandle(handles).emit({
64
+ type: 'log',
65
+ stream,
66
+ line,
67
+ timestamp: Date.now(),
68
+ });
69
+ },
70
+ emitError(message) {
71
+ currentHandle(handles).emit({
72
+ type: 'error',
73
+ message,
74
+ timestamp: Date.now(),
75
+ });
76
+ },
77
+ failNextStart(error) {
78
+ nextStartError = error;
79
+ },
80
+ };
81
+ return { adapter, controller };
82
+ }
83
+ function currentHandle(handles) {
84
+ const latest = handles.at(-1);
85
+ if (!latest) {
86
+ throw new Error('stub adapter has no active handle — call start() first');
87
+ }
88
+ return latest;
89
+ }
90
+ /**
91
+ * Concrete handle implementation. Extracted so the stub adapter +
92
+ * future in-package adapters can share the same event fanout
93
+ * plumbing without depending on Node internals.
94
+ */
95
+ class StubHandle {
96
+ runId;
97
+ _status = 'starting';
98
+ listeners = new Set();
99
+ stopped = false;
100
+ constructor(runId, options = {}) {
101
+ this.runId = runId;
102
+ if (options.signal) {
103
+ const onAbort = () => {
104
+ void this.stop();
105
+ };
106
+ if (options.signal.aborted) {
107
+ queueMicrotask(onAbort);
108
+ }
109
+ else {
110
+ options.signal.addEventListener('abort', onAbort, { once: true });
111
+ }
112
+ }
113
+ }
114
+ get status() {
115
+ return this._status;
116
+ }
117
+ subscribe(listener) {
118
+ this.listeners.add(listener);
119
+ return () => {
120
+ this.listeners.delete(listener);
121
+ };
122
+ }
123
+ emit(event) {
124
+ if (event.type === 'status') {
125
+ this._status = event.status;
126
+ }
127
+ // Snapshot first so a listener that unsubscribes mid-fanout
128
+ // doesn't skip another listener in the same tick.
129
+ const snapshot = Array.from(this.listeners);
130
+ for (const listener of snapshot) {
131
+ try {
132
+ listener(event);
133
+ }
134
+ catch {
135
+ // A bad listener MUST NOT break fanout to its peers.
136
+ // Adapter-level errors surface through `error` events; a
137
+ // listener that throws is a consumer bug.
138
+ }
139
+ }
140
+ }
141
+ /**
142
+ * Emit iff the handle is still in `starting`. Used by the
143
+ * deferred auto-ready path so an aborted / explicitly-stopped
144
+ * handle doesn't reawaken as `ready` when the timer fires.
145
+ */
146
+ emitIfStarting(event) {
147
+ if (this._status !== 'starting')
148
+ return;
149
+ this.emit(event);
150
+ }
151
+ async stop() {
152
+ if (this.stopped)
153
+ return;
154
+ this.stopped = true;
155
+ this.emit({ type: 'status', status: 'stopped', timestamp: Date.now() });
156
+ // A real adapter awaits subprocess exit here. The stub has
157
+ // nothing to wait on — but the microtask-synchronous emit
158
+ // keeps timing predictable for tests.
159
+ }
160
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Agent runtime adapter seam — the one public contract for
3
+ * "something that runs an agent and can be supervised by
4
+ * `@ggui-ai/dev-stack` or any other host."
5
+ *
6
+ * Design rules (locked 2026-04-18):
7
+ *
8
+ * 1. **Framework-neutral.** No Claude / OpenAI / Vercel-AI / LangGraph
9
+ * assumption leaks into this interface. Adapter authors translate
10
+ * their framework's idioms into this shape, not the other way
11
+ * around. `tsx watch src/index.ts` is a reference adapter — not
12
+ * the architecture.
13
+ *
14
+ * 2. **Node-free.** These types MUST NOT import from `node:*`. A
15
+ * browser-side host (the local dev hub, a cloud control plane,
16
+ * a test runner) needs to consume the adapter's events without
17
+ * pulling subprocess / fs APIs in. Reference adapters that DO
18
+ * spawn subprocesses live behind secondary subpaths (`./process`,
19
+ * `./stub`) so consumers opt in.
20
+ *
21
+ * 3. **Events are the runtime truth.** A handle exposes a declarative
22
+ * `status` for one-shot queries, but the authoritative state lives
23
+ * in the event stream (`status` → `log` → `error`). Consumers that
24
+ * care about liveness subscribe; those that only need a
25
+ * point-in-time probe read `status`.
26
+ *
27
+ * 4. **Capabilities are data, not duck typing.** Hosts inspect
28
+ * `capabilities.restartable` / `.observable` before calling
29
+ * methods that might not exist. Keeps the seam declarative even
30
+ * when adapters grow feature flags.
31
+ *
32
+ * 5. **Dependency direction.** `dev-stack` → `agent-runtime` only.
33
+ * Never the reverse. This lets future non-dev hosts (bench
34
+ * runners, remote supervisors) consume the same adapters without
35
+ * pulling the dev server in.
36
+ */
37
+ /**
38
+ * Point-in-time status of a running adapter.
39
+ *
40
+ * - `starting` — `start()` has been called; the adapter is
41
+ * bootstrapping. The handle is already returned; status events
42
+ * will surface progress.
43
+ * - `ready` — the underlying agent process / worker / service is
44
+ * healthy and accepting work.
45
+ * - `stopped` — `stop()` was called and completed, or the adapter
46
+ * shut itself down cleanly (graceful exit).
47
+ * - `crashed` — the adapter terminated without a request. Hosts
48
+ * decide whether to restart; adapters MAY self-restart only when
49
+ * `capabilities.restartable === true`.
50
+ */
51
+ export type AgentRuntimeStatus = 'starting' | 'ready' | 'stopped' | 'crashed';
52
+ /**
53
+ * Event the adapter emits through the handle's subscription.
54
+ *
55
+ * Delivery is at-least-once — consumers dedupe where it matters.
56
+ * Ordering is preserved per-adapter; cross-adapter ordering is not.
57
+ */
58
+ export type AgentRuntimeEvent = {
59
+ type: 'status';
60
+ status: AgentRuntimeStatus;
61
+ timestamp: number;
62
+ } | {
63
+ type: 'log';
64
+ stream: 'stdout' | 'stderr';
65
+ line: string;
66
+ timestamp: number;
67
+ } | {
68
+ type: 'error';
69
+ message: string;
70
+ timestamp: number;
71
+ };
72
+ /** Listener shape — hosts register one of these via `handle.subscribe`. */
73
+ export type AgentRuntimeListener = (event: AgentRuntimeEvent) => void;
74
+ /**
75
+ * Capability probe. Callers branch the UI / supervision policy on
76
+ * these instead of poking at optional methods at runtime.
77
+ */
78
+ export interface AgentRuntimeCapabilities {
79
+ /**
80
+ * `true` if the adapter emits a non-empty event stream during its
81
+ * run (at minimum, a `status: 'ready'` event after boot). `false`
82
+ * for adapters that only support start/stop/status polling.
83
+ */
84
+ readonly observable: boolean;
85
+ /**
86
+ * `true` if the adapter's `restart()` is safe to call on an active
87
+ * handle. Adapters that need a full stop-then-start cycle leave
88
+ * this `false` and hosts compose their own restart.
89
+ */
90
+ readonly restartable: boolean;
91
+ }
92
+ /**
93
+ * Minimal identity of the ggui project the adapter is being asked
94
+ * to run. The adapter MAY use `slug` / `name` in logs or in the
95
+ * process title; it MUST NOT assume anything beyond these fields
96
+ * are present.
97
+ *
98
+ * `protocol` carries the ggui protocol version (e.g. `'1.1'`) so
99
+ * adapters that generate boilerplate / pass protocol headers to
100
+ * their framework can stay in lockstep with the manifest.
101
+ */
102
+ export interface AgentRuntimeProjectIdentity {
103
+ readonly slug: string;
104
+ readonly name: string;
105
+ readonly protocol: string;
106
+ }
107
+ /**
108
+ * Input passed to {@link AgentRuntimeAdapter.start}. Intentionally
109
+ * narrow — adapters accept extra configuration through their own
110
+ * factory functions; this shape is the common subset every adapter
111
+ * MUST handle.
112
+ */
113
+ export interface AgentRuntimeStartInput {
114
+ /**
115
+ * Absolute project root (directory that contains `ggui.json`).
116
+ * Adapters resolve entry files / env files relative to this.
117
+ */
118
+ readonly projectRoot: string;
119
+ /** The loaded project identity (see above). */
120
+ readonly project: AgentRuntimeProjectIdentity;
121
+ /**
122
+ * Optional entry hint. Adapter-specific interpretation — a
123
+ * subprocess adapter might treat this as the script path; a worker
124
+ * adapter might treat it as a module name. `undefined` lets the
125
+ * adapter fall back to its own default.
126
+ */
127
+ readonly entry?: string;
128
+ /**
129
+ * Environment variables to forward into the runtime. Adapter MUST
130
+ * NOT leak `process.env` keys that aren't in this record — hosts
131
+ * explicitly opt into what crosses the boundary.
132
+ */
133
+ readonly env?: Readonly<Record<string, string>>;
134
+ /**
135
+ * Port hint. Adapters that bind a socket SHOULD honour it when
136
+ * available, or pick the next free port and surface the chosen
137
+ * value via a status event.
138
+ */
139
+ readonly portHint?: number;
140
+ /**
141
+ * Abort signal. Aborting is equivalent to calling
142
+ * {@link AgentRuntimeHandle.stop} on the returned handle — hosts
143
+ * that want fire-and-forget cleanup pass a signal instead of
144
+ * holding the handle.
145
+ */
146
+ readonly signal?: AbortSignal;
147
+ }
148
+ /**
149
+ * Running-instance handle returned from {@link AgentRuntimeAdapter.start}.
150
+ *
151
+ * Every method is idempotent when called on an already-terminal
152
+ * state: `stop()` on a stopped handle is a no-op; a second
153
+ * `subscribe()` after `stop()` is allowed (returns an unsubscribe
154
+ * that does nothing) but MAY be rejected with a clear error by the
155
+ * adapter if desired.
156
+ */
157
+ export interface AgentRuntimeHandle {
158
+ /** Opaque id unique per run. Adapter decides the format. */
159
+ readonly runId: string;
160
+ /**
161
+ * Declarative snapshot. Reflects the last status event the adapter
162
+ * emitted; consumers that need real-time progress should
163
+ * `subscribe` instead.
164
+ */
165
+ readonly status: AgentRuntimeStatus;
166
+ /**
167
+ * Subscribe to events. Returns an unsubscribe function.
168
+ * At-least-once delivery; listeners MUST be idempotent.
169
+ */
170
+ subscribe(listener: AgentRuntimeListener): () => void;
171
+ /**
172
+ * Stop the runtime. Resolves after the adapter has completed its
173
+ * teardown (process exit, worker termination, server close —
174
+ * adapter-specific).
175
+ */
176
+ stop(): Promise<void>;
177
+ }
178
+ /**
179
+ * The adapter interface. Implementations translate a specific agent
180
+ * framework / process model into the seam's shape.
181
+ *
182
+ * Minimal reference adapters live in this package under secondary
183
+ * subpaths (`./stub` for tests, `./process` for subprocess-based
184
+ * runtimes). Framework-specific adapters (Claude Agent SDK, OpenAI
185
+ * Agents, Vercel AI SDK) belong in their own packages so pulling
186
+ * the seam in doesn't drag an SDK's dependency graph along.
187
+ */
188
+ export interface AgentRuntimeAdapter {
189
+ /** Human-readable identifier — used in logs and the hub UI. */
190
+ readonly name: string;
191
+ /** Capability probe — see {@link AgentRuntimeCapabilities}. */
192
+ readonly capabilities: AgentRuntimeCapabilities;
193
+ /**
194
+ * Boot the runtime. Resolves once the handle is safe to return —
195
+ * the agent may still be `starting`; `status: 'ready'` surfaces
196
+ * via the event stream.
197
+ *
198
+ * Throws only on permanent start-time errors (missing entry,
199
+ * malformed config). Runtime crashes after boot travel through
200
+ * the event stream + `handle.status === 'crashed'`.
201
+ */
202
+ start(input: AgentRuntimeStartInput): Promise<AgentRuntimeHandle>;
203
+ }
204
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,kBAAkB,GAAG,UAAU,GAAG,OAAO,GAAG,SAAS,GAAG,SAAS,CAAC;AAE9E;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,kBAAkB,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACjE;IACE,IAAI,EAAE,KAAK,CAAC;IACZ,MAAM,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CACnB,GACD;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC;AAE1D,2EAA2E;AAC3E,MAAM,MAAM,oBAAoB,GAAG,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;AAEtE;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC;;;;OAIG;IACH,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;IAE7B;;;;OAIG;IACH,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC;CAC/B;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;GAKG;AACH,MAAM,WAAW,sBAAsB;IACrC;;;OAGG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAE7B,+CAA+C;IAC/C,QAAQ,CAAC,OAAO,EAAE,2BAA2B,CAAC;IAE9C;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAExB;;;;OAIG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAEhD;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED;;;;;;;;GAQG;AACH,MAAM,WAAW,kBAAkB;IACjC,4DAA4D;IAC5D,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAEvB;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,kBAAkB,CAAC;IAEpC;;;OAGG;IACH,SAAS,CAAC,QAAQ,EAAE,oBAAoB,GAAG,MAAM,IAAI,CAAC;IAEtD;;;;OAIG;IACH,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,mBAAmB;IAClC,+DAA+D;IAC/D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,+DAA+D;IAC/D,QAAQ,CAAC,YAAY,EAAE,wBAAwB,CAAC;IAEhD;;;;;;;;OAQG;IACH,KAAK,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;CACnE"}
package/dist/types.js ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Agent runtime adapter seam — the one public contract for
3
+ * "something that runs an agent and can be supervised by
4
+ * `@ggui-ai/dev-stack` or any other host."
5
+ *
6
+ * Design rules (locked 2026-04-18):
7
+ *
8
+ * 1. **Framework-neutral.** No Claude / OpenAI / Vercel-AI / LangGraph
9
+ * assumption leaks into this interface. Adapter authors translate
10
+ * their framework's idioms into this shape, not the other way
11
+ * around. `tsx watch src/index.ts` is a reference adapter — not
12
+ * the architecture.
13
+ *
14
+ * 2. **Node-free.** These types MUST NOT import from `node:*`. A
15
+ * browser-side host (the local dev hub, a cloud control plane,
16
+ * a test runner) needs to consume the adapter's events without
17
+ * pulling subprocess / fs APIs in. Reference adapters that DO
18
+ * spawn subprocesses live behind secondary subpaths (`./process`,
19
+ * `./stub`) so consumers opt in.
20
+ *
21
+ * 3. **Events are the runtime truth.** A handle exposes a declarative
22
+ * `status` for one-shot queries, but the authoritative state lives
23
+ * in the event stream (`status` → `log` → `error`). Consumers that
24
+ * care about liveness subscribe; those that only need a
25
+ * point-in-time probe read `status`.
26
+ *
27
+ * 4. **Capabilities are data, not duck typing.** Hosts inspect
28
+ * `capabilities.restartable` / `.observable` before calling
29
+ * methods that might not exist. Keeps the seam declarative even
30
+ * when adapters grow feature flags.
31
+ *
32
+ * 5. **Dependency direction.** `dev-stack` → `agent-runtime` only.
33
+ * Never the reverse. This lets future non-dev hosts (bench
34
+ * runners, remote supervisors) consume the same adapters without
35
+ * pulling the dev server in.
36
+ */
37
+ export {};
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@ggui-ai/agent-runtime",
3
+ "version": "0.1.0-rc.1",
4
+ "description": "Pluggable adapter seam for supervising whatever actually runs an agent — the Claude Agent SDK, OpenAI Agents, the Vercel AI SDK, a plain subprocess, and more. Lets a host swap agent runtimes without hardcoding any framework into its dev loop.",
5
+ "keywords": [
6
+ "ggui",
7
+ "agent",
8
+ "agent-runtime",
9
+ "adapter",
10
+ "claude-agent-sdk"
11
+ ],
12
+ "license": "Apache-2.0",
13
+ "type": "module",
14
+ "main": "dist/index.js",
15
+ "types": "dist/index.d.ts",
16
+ "files": [
17
+ "dist",
18
+ "README.md"
19
+ ],
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js",
24
+ "default": "./dist/index.js"
25
+ },
26
+ "./process": {
27
+ "types": "./dist/process.d.ts",
28
+ "import": "./dist/process.js",
29
+ "default": "./dist/process.js"
30
+ }
31
+ },
32
+ "dependencies": {},
33
+ "devDependencies": {
34
+ "@types/node": "^24.0.0",
35
+ "typescript": "^5.0.0",
36
+ "vitest": "^3.0.0"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "https://github.com/ggui-ai/ggui.git",
41
+ "directory": "packages/agent-runtime"
42
+ },
43
+ "homepage": "https://github.com/ggui-ai/ggui/tree/main/packages/agent-runtime",
44
+ "bugs": {
45
+ "url": "https://github.com/ggui-ai/ggui/issues"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "engines": {
51
+ "node": ">=20.0.0"
52
+ },
53
+ "author": "ggui contributors <hello@ggui.ai>",
54
+ "scripts": {
55
+ "build": "tsc -p tsconfig.build.json",
56
+ "dev": "tsc --watch",
57
+ "typecheck": "tsc --noEmit",
58
+ "test": "vitest run",
59
+ "test:watch": "vitest"
60
+ }
61
+ }