@flowy-agent-store/sdk 0.1.0-beta.2
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 +201 -0
- package/README.md +20 -0
- package/dist/index.cjs +268 -0
- package/dist/index.d.cts +67 -0
- package/dist/index.d.mts +67 -0
- package/dist/index.mjs +264 -0
- package/package.json +40 -0
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 2025-2026 Flowy (nomifun.com)
|
|
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
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# `@flowy-agent-store/sdk`
|
|
2
|
+
|
|
3
|
+
Node.js host for the Agent Store runtime (`docs/agent-store/12-sdk-packaging.md P1-3`): spawn `agent-store`, wait for its stdout readiness line, connect over loopback with `@flowy-agent-store/client`.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { launchClient } from "@flowy-agent-store/sdk";
|
|
7
|
+
|
|
8
|
+
const session = await launchClient({
|
|
9
|
+
client: { name: "my-app", version: "0.1.0" },
|
|
10
|
+
});
|
|
11
|
+
const store = await session.client.listStore();
|
|
12
|
+
await session.close();
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
规则(P0 实测结论):
|
|
16
|
+
|
|
17
|
+
- 子进程固定 `--host 127.0.0.1 --no-open`;非回环一律拒绝(`isLoopbackUrl`)。
|
|
18
|
+
- 默认自带临时 `--data-dir` 并在 `close()` 删除;传自己的目录即表示独占——后端单实例锁会 fail-fast。
|
|
19
|
+
- 二进制定位:`bin` 参数 → `AGENT_STORE_BIN` → `PATH`;找不到直接报错(不下载,见 P2)。
|
|
20
|
+
- 就绪行 `protocol_version` 与 SDK 不一致时杀掉子进程并报错(含两端版本)。
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _flowy_agent_store_client = require("@flowy-agent-store/client");
|
|
3
|
+
let node_fs = require("node:fs");
|
|
4
|
+
let node_module = require("node:module");
|
|
5
|
+
let node_path = require("node:path");
|
|
6
|
+
let node_child_process = require("node:child_process");
|
|
7
|
+
let node_fs_promises = require("node:fs/promises");
|
|
8
|
+
let node_os = require("node:os");
|
|
9
|
+
let node_readline = require("node:readline");
|
|
10
|
+
let _flowy_agent_store_protocol = require("@flowy-agent-store/protocol");
|
|
11
|
+
//#region src/bin.ts
|
|
12
|
+
/**
|
|
13
|
+
* Locate the `agent-store` runtime binary.
|
|
14
|
+
*
|
|
15
|
+
* Order (docs/agent-store/12 §6):
|
|
16
|
+
* 1. explicit `bin` argument (skips every other lookup)
|
|
17
|
+
* 2. `AGENT_STORE_BIN` environment variable
|
|
18
|
+
* 3. platform runtime package (`@flowy-agent-store/runtime-<platform>-<arch>`,
|
|
19
|
+
* an optionalDependency of `@flowy-agent-store/sdk`) resolved via
|
|
20
|
+
* `createRequire(import.meta.url).resolve` — the binary ships inside the
|
|
21
|
+
* package (`vendor/agent-store[.exe]`)
|
|
22
|
+
* 4. `agent-store[.exe]` on `PATH`
|
|
23
|
+
*
|
|
24
|
+
* Anything else is a hard error — the SDK never downloads or guesses.
|
|
25
|
+
*/
|
|
26
|
+
const VENDOR_DIR = "vendor";
|
|
27
|
+
const BIN_NAMES = ["agent-store", "agent-store.exe"];
|
|
28
|
+
function resolveAppServerBin(explicit) {
|
|
29
|
+
if (explicit && (0, node_fs.existsSync)(explicit)) return explicit;
|
|
30
|
+
const candidates = [];
|
|
31
|
+
if (explicit) candidates.push(explicit);
|
|
32
|
+
const fromEnv = process.env["AGENT_STORE_BIN"];
|
|
33
|
+
if (fromEnv) candidates.push(fromEnv);
|
|
34
|
+
const fromRuntimePackage = findInRuntimePackage();
|
|
35
|
+
if (fromRuntimePackage) candidates.push(fromRuntimePackage);
|
|
36
|
+
for (const name of BIN_NAMES) {
|
|
37
|
+
const found = findOnPath(name);
|
|
38
|
+
if (found) candidates.push(found);
|
|
39
|
+
}
|
|
40
|
+
const hit = candidates.find((candidate) => (0, node_fs.existsSync)(candidate));
|
|
41
|
+
if (!hit) throw new Error(`cannot find the agent-store runtime binary: pass \`bin\`, set AGENT_STORE_BIN, install @flowy-agent-store/runtime-${process.platform}-${process.arch} alongside @flowy-agent-store/sdk, or put agent-store[.exe] on PATH`);
|
|
42
|
+
return hit;
|
|
43
|
+
}
|
|
44
|
+
/** Probe the platform runtime package for a vendored binary (optional dep). */
|
|
45
|
+
function findInRuntimePackage() {
|
|
46
|
+
const pkg = `@flowy-agent-store/runtime-${process.platform}-${process.arch}`;
|
|
47
|
+
try {
|
|
48
|
+
const pkgRoot = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href).resolve(`${pkg}/package.json`).slice(0, -12);
|
|
49
|
+
for (const name of BIN_NAMES) {
|
|
50
|
+
const candidate = (0, node_path.join)(pkgRoot, VENDOR_DIR, name);
|
|
51
|
+
if ((0, node_fs.existsSync)(candidate)) return candidate;
|
|
52
|
+
}
|
|
53
|
+
return;
|
|
54
|
+
} catch {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function findOnPath(name) {
|
|
59
|
+
const pathEnv = process.env["PATH"] ?? process.env["Path"] ?? "";
|
|
60
|
+
for (const dir of pathEnv.split(node_path.delimiter)) {
|
|
61
|
+
if (!dir) continue;
|
|
62
|
+
const full = (0, node_path.join)(dir, name);
|
|
63
|
+
try {
|
|
64
|
+
if ((0, node_fs.existsSync)(full)) return full;
|
|
65
|
+
} catch {}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region src/readiness.ts
|
|
70
|
+
/** Parse one stdout line; `null` when it is not the readiness line. */
|
|
71
|
+
function parseReadinessLine(line) {
|
|
72
|
+
let parsed;
|
|
73
|
+
try {
|
|
74
|
+
parsed = JSON.parse(line);
|
|
75
|
+
} catch {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
if (typeof parsed !== "object" || parsed === null) return null;
|
|
79
|
+
const record = parsed;
|
|
80
|
+
if (record["agent_store"] !== "listening") return null;
|
|
81
|
+
const { host, port, url, protocol_version, version, auth } = record;
|
|
82
|
+
if (typeof host !== "string" || typeof port !== "number" || typeof url !== "string" || typeof protocol_version !== "string" || typeof version !== "string" || typeof auth !== "string") return null;
|
|
83
|
+
return {
|
|
84
|
+
host,
|
|
85
|
+
port,
|
|
86
|
+
url,
|
|
87
|
+
protocol_version,
|
|
88
|
+
version,
|
|
89
|
+
auth
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/spawn.ts
|
|
94
|
+
/**
|
|
95
|
+
* Spawn the `agent-store` runtime as a child process and wait for its
|
|
96
|
+
* readiness line (docs/agent-store/12 P0-1 / P1-3).
|
|
97
|
+
*
|
|
98
|
+
* The child is always loopback-only (`--host 127.0.0.1 --no-open`) with its
|
|
99
|
+
* own data directory (SDK独占, P0-3): a fresh temp dir by default, or an
|
|
100
|
+
* explicit one the caller owns. A server-side single-instance lock fails the
|
|
101
|
+
* spawn fast when the directory is already held — that error propagates.
|
|
102
|
+
*/
|
|
103
|
+
const DEFAULT_READY_TIMEOUT_MS = 12e4;
|
|
104
|
+
const STDERR_TAIL_LINES = 50;
|
|
105
|
+
const KILL_GRACE_MS = 2e3;
|
|
106
|
+
/** Fail when the runtime speaks a different wire protocol (§7 acceptance). */
|
|
107
|
+
function assertProtocolCompatible(runtimeVersion) {
|
|
108
|
+
if (runtimeVersion !== _flowy_agent_store_protocol.APP_SERVER_PROTOCOL_VERSION) throw new Error(`protocol version mismatch: runtime speaks ${runtimeVersion}, SDK expects ${_flowy_agent_store_protocol.APP_SERVER_PROTOCOL_VERSION}`);
|
|
109
|
+
}
|
|
110
|
+
async function spawnAppServer(options = {}) {
|
|
111
|
+
const bin = resolveAppServerBin(options.bin);
|
|
112
|
+
const ownedDir = options.dataDir === void 0;
|
|
113
|
+
const dataDir = ownedDir ? await (0, node_fs_promises.mkdtemp)((0, node_path.join)((0, node_os.tmpdir)(), "agent-store-sdk-")) : options.dataDir;
|
|
114
|
+
const port = options.port ?? 0;
|
|
115
|
+
const child = (0, node_child_process.spawn)(bin, [
|
|
116
|
+
"--host",
|
|
117
|
+
"127.0.0.1",
|
|
118
|
+
"--port",
|
|
119
|
+
String(port),
|
|
120
|
+
"--data-dir",
|
|
121
|
+
dataDir,
|
|
122
|
+
"--no-open",
|
|
123
|
+
...options.extraArgs ?? []
|
|
124
|
+
], {
|
|
125
|
+
stdio: [
|
|
126
|
+
"ignore",
|
|
127
|
+
"pipe",
|
|
128
|
+
"pipe"
|
|
129
|
+
],
|
|
130
|
+
windowsHide: true
|
|
131
|
+
});
|
|
132
|
+
const stderrTail = [];
|
|
133
|
+
child.stderr?.on("data", (chunk) => {
|
|
134
|
+
for (const line of String(chunk).split(/\r?\n/)) {
|
|
135
|
+
if (line.length === 0) continue;
|
|
136
|
+
stderrTail.push(line);
|
|
137
|
+
if (stderrTail.length > STDERR_TAIL_LINES) stderrTail.shift();
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
const stopChild = async () => {
|
|
141
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
142
|
+
child.kill();
|
|
143
|
+
if (!await new Promise((resolve) => {
|
|
144
|
+
const timer = setTimeout(() => resolve(false), KILL_GRACE_MS);
|
|
145
|
+
child.once("exit", () => {
|
|
146
|
+
clearTimeout(timer);
|
|
147
|
+
resolve(true);
|
|
148
|
+
});
|
|
149
|
+
})) child.kill("SIGKILL");
|
|
150
|
+
};
|
|
151
|
+
const fail = async (message) => {
|
|
152
|
+
await stopChild();
|
|
153
|
+
if (ownedDir) await (0, node_fs_promises.rm)(dataDir, {
|
|
154
|
+
recursive: true,
|
|
155
|
+
force: true
|
|
156
|
+
}).catch(() => void 0);
|
|
157
|
+
const tail = stderrTail.length > 0 ? `\nstderr tail:\n${stderrTail.join("\n")}` : "";
|
|
158
|
+
throw new Error(`${message}${tail}`);
|
|
159
|
+
};
|
|
160
|
+
try {
|
|
161
|
+
const readiness = await waitForReadiness(child, options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS);
|
|
162
|
+
try {
|
|
163
|
+
assertProtocolCompatible(readiness.protocol_version);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
await fail(error.message);
|
|
166
|
+
}
|
|
167
|
+
let closed = false;
|
|
168
|
+
return {
|
|
169
|
+
readiness,
|
|
170
|
+
dataDir,
|
|
171
|
+
close: async () => {
|
|
172
|
+
if (closed) return;
|
|
173
|
+
closed = true;
|
|
174
|
+
await stopChild();
|
|
175
|
+
if (ownedDir) await (0, node_fs_promises.rm)(dataDir, {
|
|
176
|
+
recursive: true,
|
|
177
|
+
force: true
|
|
178
|
+
}).catch(() => void 0);
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
} catch (error) {
|
|
182
|
+
await stopChild();
|
|
183
|
+
if (ownedDir) await (0, node_fs_promises.rm)(dataDir, {
|
|
184
|
+
recursive: true,
|
|
185
|
+
force: true
|
|
186
|
+
}).catch(() => void 0);
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
function waitForReadiness(child, timeoutMs) {
|
|
191
|
+
return new Promise((resolve, reject) => {
|
|
192
|
+
if (!child.stdout) {
|
|
193
|
+
reject(/* @__PURE__ */ new Error("spawned runtime has no stdout pipe"));
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const lines = (0, node_readline.createInterface)({ input: child.stdout });
|
|
197
|
+
const timer = setTimeout(() => {
|
|
198
|
+
lines.close();
|
|
199
|
+
reject(/* @__PURE__ */ new Error(`timed out after ${timeoutMs}ms waiting for the runtime readiness line`));
|
|
200
|
+
}, timeoutMs);
|
|
201
|
+
const done = (fn) => {
|
|
202
|
+
clearTimeout(timer);
|
|
203
|
+
lines.close();
|
|
204
|
+
fn();
|
|
205
|
+
};
|
|
206
|
+
lines.on("line", (line) => {
|
|
207
|
+
const readiness = parseReadinessLine(line);
|
|
208
|
+
if (readiness) done(() => resolve(readiness));
|
|
209
|
+
});
|
|
210
|
+
child.once("error", (error) => {
|
|
211
|
+
done(() => reject(/* @__PURE__ */ new Error(`failed to spawn the runtime: ${error.message}`)));
|
|
212
|
+
});
|
|
213
|
+
child.once("exit", (code) => {
|
|
214
|
+
done(() => reject(/* @__PURE__ */ new Error(`runtime exited before reporting readiness (code ${code})`)));
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
//#endregion
|
|
219
|
+
//#region src/index.ts
|
|
220
|
+
/**
|
|
221
|
+
* `@flowy-agent-store/sdk` — spawn the runtime, connect over loopback, hand back
|
|
222
|
+
* a ready `AppServerClient`.
|
|
223
|
+
*/
|
|
224
|
+
/**
|
|
225
|
+
* Spawn a loopback runtime with its own data dir and return a connected,
|
|
226
|
+
* initialized client. Rejects non-loopback contact outright (P0-4): this
|
|
227
|
+
* entry point only ever dials the process it just spawned.
|
|
228
|
+
*/
|
|
229
|
+
async function launchClient(options) {
|
|
230
|
+
const server = await spawnAppServer(options);
|
|
231
|
+
const wsUrl = `ws://${server.readiness.host}:${server.readiness.port}/api/app-server/ws`;
|
|
232
|
+
if (!(0, _flowy_agent_store_client.isLoopbackUrl)(wsUrl)) {
|
|
233
|
+
await server.close();
|
|
234
|
+
throw new Error(`refusing to connect outside loopback: ${wsUrl}`);
|
|
235
|
+
}
|
|
236
|
+
const client = new _flowy_agent_store_client.AppServerClient({
|
|
237
|
+
transport: new _flowy_agent_store_client.WebSocketTransport(wsUrl, {
|
|
238
|
+
requestTimeoutMs: options.requestTimeoutMs,
|
|
239
|
+
token: options.token
|
|
240
|
+
}),
|
|
241
|
+
client: options.client,
|
|
242
|
+
capabilities: options.capabilities
|
|
243
|
+
});
|
|
244
|
+
try {
|
|
245
|
+
const initializeResult = await client.connect();
|
|
246
|
+
let closed = false;
|
|
247
|
+
return {
|
|
248
|
+
server,
|
|
249
|
+
client,
|
|
250
|
+
initializeResult,
|
|
251
|
+
close: async () => {
|
|
252
|
+
if (closed) return;
|
|
253
|
+
closed = true;
|
|
254
|
+
client.close();
|
|
255
|
+
await server.close();
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
} catch (error) {
|
|
259
|
+
client.close();
|
|
260
|
+
await server.close();
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
265
|
+
exports.launchClient = launchClient;
|
|
266
|
+
exports.parseReadinessLine = parseReadinessLine;
|
|
267
|
+
exports.resolveAppServerBin = resolveAppServerBin;
|
|
268
|
+
exports.spawnAppServer = spawnAppServer;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { AppServerClient } from "@flowy-agent-store/client";
|
|
2
|
+
import { ClientCapabilities, ClientInfo, InitializeResult } from "@flowy-agent-store/protocol";
|
|
3
|
+
//#region src/bin.d.ts
|
|
4
|
+
export declare function resolveAppServerBin(explicit?: string): string;
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region src/readiness.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* Readiness protocol (docs/agent-store/12 P0-1).
|
|
9
|
+
*
|
|
10
|
+
* The runtime prints exactly one machine-readable line on stdout after the
|
|
11
|
+
* socket is bound. Tracing logs share stdout, so the host scans lines for a
|
|
12
|
+
* JSON object with `"agent_store": "listening"` and ignores everything else.
|
|
13
|
+
*/
|
|
14
|
+
interface ReadinessInfo {
|
|
15
|
+
host: string;
|
|
16
|
+
port: number;
|
|
17
|
+
url: string;
|
|
18
|
+
protocol_version: string;
|
|
19
|
+
version: string;
|
|
20
|
+
auth: string;
|
|
21
|
+
}
|
|
22
|
+
/** Parse one stdout line; `null` when it is not the readiness line. */
|
|
23
|
+
export declare function parseReadinessLine(line: string): ReadinessInfo | null;
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/spawn.d.ts
|
|
26
|
+
interface SpawnOptions {
|
|
27
|
+
/** Explicit binary path (overrides `AGENT_STORE_BIN` / `PATH`). */
|
|
28
|
+
bin?: string;
|
|
29
|
+
/** Data directory the child owns. Defaults to a fresh temp dir (removed on `close`). */
|
|
30
|
+
dataDir?: string;
|
|
31
|
+
/** Port to bind. Defaults to `0` (OS-assigned, reported by the readiness line). */
|
|
32
|
+
port?: number;
|
|
33
|
+
/** Extra CLI args appended after the managed ones. */
|
|
34
|
+
extraArgs?: string[];
|
|
35
|
+
/** How long to wait for the readiness line. Defaults to 120s (cold DB init). */
|
|
36
|
+
readyTimeoutMs?: number;
|
|
37
|
+
}
|
|
38
|
+
interface SpawnedServer {
|
|
39
|
+
readonly readiness: ReadinessInfo;
|
|
40
|
+
readonly dataDir: string;
|
|
41
|
+
/** Terminate the child and remove the data dir when it was auto-created. */
|
|
42
|
+
close(): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
export declare function spawnAppServer(options?: SpawnOptions): Promise<SpawnedServer>;
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/index.d.ts
|
|
47
|
+
export interface LaunchOptions extends SpawnOptions {
|
|
48
|
+
client: ClientInfo;
|
|
49
|
+
capabilities?: ClientCapabilities;
|
|
50
|
+
token?: string;
|
|
51
|
+
requestTimeoutMs?: number;
|
|
52
|
+
}
|
|
53
|
+
export interface LaunchedClient {
|
|
54
|
+
server: SpawnedServer;
|
|
55
|
+
client: AppServerClient;
|
|
56
|
+
initializeResult: InitializeResult;
|
|
57
|
+
/** Disconnect and terminate the spawned runtime. */
|
|
58
|
+
close(): Promise<void>;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Spawn a loopback runtime with its own data dir and return a connected,
|
|
62
|
+
* initialized client. Rejects non-loopback contact outright (P0-4): this
|
|
63
|
+
* entry point only ever dials the process it just spawned.
|
|
64
|
+
*/
|
|
65
|
+
export declare function launchClient(options: LaunchOptions): Promise<LaunchedClient>;
|
|
66
|
+
//#endregion
|
|
67
|
+
export type { ReadinessInfo, SpawnOptions, SpawnedServer };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { AppServerClient } from "@flowy-agent-store/client";
|
|
2
|
+
import { ClientCapabilities, ClientInfo, InitializeResult } from "@flowy-agent-store/protocol";
|
|
3
|
+
//#region src/bin.d.ts
|
|
4
|
+
export declare function resolveAppServerBin(explicit?: string): string;
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region src/readiness.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* Readiness protocol (docs/agent-store/12 P0-1).
|
|
9
|
+
*
|
|
10
|
+
* The runtime prints exactly one machine-readable line on stdout after the
|
|
11
|
+
* socket is bound. Tracing logs share stdout, so the host scans lines for a
|
|
12
|
+
* JSON object with `"agent_store": "listening"` and ignores everything else.
|
|
13
|
+
*/
|
|
14
|
+
interface ReadinessInfo {
|
|
15
|
+
host: string;
|
|
16
|
+
port: number;
|
|
17
|
+
url: string;
|
|
18
|
+
protocol_version: string;
|
|
19
|
+
version: string;
|
|
20
|
+
auth: string;
|
|
21
|
+
}
|
|
22
|
+
/** Parse one stdout line; `null` when it is not the readiness line. */
|
|
23
|
+
export declare function parseReadinessLine(line: string): ReadinessInfo | null;
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/spawn.d.ts
|
|
26
|
+
interface SpawnOptions {
|
|
27
|
+
/** Explicit binary path (overrides `AGENT_STORE_BIN` / `PATH`). */
|
|
28
|
+
bin?: string;
|
|
29
|
+
/** Data directory the child owns. Defaults to a fresh temp dir (removed on `close`). */
|
|
30
|
+
dataDir?: string;
|
|
31
|
+
/** Port to bind. Defaults to `0` (OS-assigned, reported by the readiness line). */
|
|
32
|
+
port?: number;
|
|
33
|
+
/** Extra CLI args appended after the managed ones. */
|
|
34
|
+
extraArgs?: string[];
|
|
35
|
+
/** How long to wait for the readiness line. Defaults to 120s (cold DB init). */
|
|
36
|
+
readyTimeoutMs?: number;
|
|
37
|
+
}
|
|
38
|
+
interface SpawnedServer {
|
|
39
|
+
readonly readiness: ReadinessInfo;
|
|
40
|
+
readonly dataDir: string;
|
|
41
|
+
/** Terminate the child and remove the data dir when it was auto-created. */
|
|
42
|
+
close(): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
export declare function spawnAppServer(options?: SpawnOptions): Promise<SpawnedServer>;
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/index.d.ts
|
|
47
|
+
export interface LaunchOptions extends SpawnOptions {
|
|
48
|
+
client: ClientInfo;
|
|
49
|
+
capabilities?: ClientCapabilities;
|
|
50
|
+
token?: string;
|
|
51
|
+
requestTimeoutMs?: number;
|
|
52
|
+
}
|
|
53
|
+
export interface LaunchedClient {
|
|
54
|
+
server: SpawnedServer;
|
|
55
|
+
client: AppServerClient;
|
|
56
|
+
initializeResult: InitializeResult;
|
|
57
|
+
/** Disconnect and terminate the spawned runtime. */
|
|
58
|
+
close(): Promise<void>;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Spawn a loopback runtime with its own data dir and return a connected,
|
|
62
|
+
* initialized client. Rejects non-loopback contact outright (P0-4): this
|
|
63
|
+
* entry point only ever dials the process it just spawned.
|
|
64
|
+
*/
|
|
65
|
+
export declare function launchClient(options: LaunchOptions): Promise<LaunchedClient>;
|
|
66
|
+
//#endregion
|
|
67
|
+
export type { ReadinessInfo, SpawnOptions, SpawnedServer };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { AppServerClient, WebSocketTransport, isLoopbackUrl } from "@flowy-agent-store/client";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { delimiter, join } from "node:path";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { createInterface } from "node:readline";
|
|
9
|
+
import { APP_SERVER_PROTOCOL_VERSION } from "@flowy-agent-store/protocol";
|
|
10
|
+
//#region src/bin.ts
|
|
11
|
+
/**
|
|
12
|
+
* Locate the `agent-store` runtime binary.
|
|
13
|
+
*
|
|
14
|
+
* Order (docs/agent-store/12 §6):
|
|
15
|
+
* 1. explicit `bin` argument (skips every other lookup)
|
|
16
|
+
* 2. `AGENT_STORE_BIN` environment variable
|
|
17
|
+
* 3. platform runtime package (`@flowy-agent-store/runtime-<platform>-<arch>`,
|
|
18
|
+
* an optionalDependency of `@flowy-agent-store/sdk`) resolved via
|
|
19
|
+
* `createRequire(import.meta.url).resolve` — the binary ships inside the
|
|
20
|
+
* package (`vendor/agent-store[.exe]`)
|
|
21
|
+
* 4. `agent-store[.exe]` on `PATH`
|
|
22
|
+
*
|
|
23
|
+
* Anything else is a hard error — the SDK never downloads or guesses.
|
|
24
|
+
*/
|
|
25
|
+
const VENDOR_DIR = "vendor";
|
|
26
|
+
const BIN_NAMES = ["agent-store", "agent-store.exe"];
|
|
27
|
+
function resolveAppServerBin(explicit) {
|
|
28
|
+
if (explicit && existsSync(explicit)) return explicit;
|
|
29
|
+
const candidates = [];
|
|
30
|
+
if (explicit) candidates.push(explicit);
|
|
31
|
+
const fromEnv = process.env["AGENT_STORE_BIN"];
|
|
32
|
+
if (fromEnv) candidates.push(fromEnv);
|
|
33
|
+
const fromRuntimePackage = findInRuntimePackage();
|
|
34
|
+
if (fromRuntimePackage) candidates.push(fromRuntimePackage);
|
|
35
|
+
for (const name of BIN_NAMES) {
|
|
36
|
+
const found = findOnPath(name);
|
|
37
|
+
if (found) candidates.push(found);
|
|
38
|
+
}
|
|
39
|
+
const hit = candidates.find((candidate) => existsSync(candidate));
|
|
40
|
+
if (!hit) throw new Error(`cannot find the agent-store runtime binary: pass \`bin\`, set AGENT_STORE_BIN, install @flowy-agent-store/runtime-${process.platform}-${process.arch} alongside @flowy-agent-store/sdk, or put agent-store[.exe] on PATH`);
|
|
41
|
+
return hit;
|
|
42
|
+
}
|
|
43
|
+
/** Probe the platform runtime package for a vendored binary (optional dep). */
|
|
44
|
+
function findInRuntimePackage() {
|
|
45
|
+
const pkg = `@flowy-agent-store/runtime-${process.platform}-${process.arch}`;
|
|
46
|
+
try {
|
|
47
|
+
const pkgRoot = createRequire(import.meta.url).resolve(`${pkg}/package.json`).slice(0, -12);
|
|
48
|
+
for (const name of BIN_NAMES) {
|
|
49
|
+
const candidate = join(pkgRoot, VENDOR_DIR, name);
|
|
50
|
+
if (existsSync(candidate)) return candidate;
|
|
51
|
+
}
|
|
52
|
+
return;
|
|
53
|
+
} catch {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function findOnPath(name) {
|
|
58
|
+
const pathEnv = process.env["PATH"] ?? process.env["Path"] ?? "";
|
|
59
|
+
for (const dir of pathEnv.split(delimiter)) {
|
|
60
|
+
if (!dir) continue;
|
|
61
|
+
const full = join(dir, name);
|
|
62
|
+
try {
|
|
63
|
+
if (existsSync(full)) return full;
|
|
64
|
+
} catch {}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
//#endregion
|
|
68
|
+
//#region src/readiness.ts
|
|
69
|
+
/** Parse one stdout line; `null` when it is not the readiness line. */
|
|
70
|
+
function parseReadinessLine(line) {
|
|
71
|
+
let parsed;
|
|
72
|
+
try {
|
|
73
|
+
parsed = JSON.parse(line);
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
if (typeof parsed !== "object" || parsed === null) return null;
|
|
78
|
+
const record = parsed;
|
|
79
|
+
if (record["agent_store"] !== "listening") return null;
|
|
80
|
+
const { host, port, url, protocol_version, version, auth } = record;
|
|
81
|
+
if (typeof host !== "string" || typeof port !== "number" || typeof url !== "string" || typeof protocol_version !== "string" || typeof version !== "string" || typeof auth !== "string") return null;
|
|
82
|
+
return {
|
|
83
|
+
host,
|
|
84
|
+
port,
|
|
85
|
+
url,
|
|
86
|
+
protocol_version,
|
|
87
|
+
version,
|
|
88
|
+
auth
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
//#endregion
|
|
92
|
+
//#region src/spawn.ts
|
|
93
|
+
/**
|
|
94
|
+
* Spawn the `agent-store` runtime as a child process and wait for its
|
|
95
|
+
* readiness line (docs/agent-store/12 P0-1 / P1-3).
|
|
96
|
+
*
|
|
97
|
+
* The child is always loopback-only (`--host 127.0.0.1 --no-open`) with its
|
|
98
|
+
* own data directory (SDK独占, P0-3): a fresh temp dir by default, or an
|
|
99
|
+
* explicit one the caller owns. A server-side single-instance lock fails the
|
|
100
|
+
* spawn fast when the directory is already held — that error propagates.
|
|
101
|
+
*/
|
|
102
|
+
const DEFAULT_READY_TIMEOUT_MS = 12e4;
|
|
103
|
+
const STDERR_TAIL_LINES = 50;
|
|
104
|
+
const KILL_GRACE_MS = 2e3;
|
|
105
|
+
/** Fail when the runtime speaks a different wire protocol (§7 acceptance). */
|
|
106
|
+
function assertProtocolCompatible(runtimeVersion) {
|
|
107
|
+
if (runtimeVersion !== APP_SERVER_PROTOCOL_VERSION) throw new Error(`protocol version mismatch: runtime speaks ${runtimeVersion}, SDK expects ${APP_SERVER_PROTOCOL_VERSION}`);
|
|
108
|
+
}
|
|
109
|
+
async function spawnAppServer(options = {}) {
|
|
110
|
+
const bin = resolveAppServerBin(options.bin);
|
|
111
|
+
const ownedDir = options.dataDir === void 0;
|
|
112
|
+
const dataDir = ownedDir ? await mkdtemp(join(tmpdir(), "agent-store-sdk-")) : options.dataDir;
|
|
113
|
+
const port = options.port ?? 0;
|
|
114
|
+
const child = spawn(bin, [
|
|
115
|
+
"--host",
|
|
116
|
+
"127.0.0.1",
|
|
117
|
+
"--port",
|
|
118
|
+
String(port),
|
|
119
|
+
"--data-dir",
|
|
120
|
+
dataDir,
|
|
121
|
+
"--no-open",
|
|
122
|
+
...options.extraArgs ?? []
|
|
123
|
+
], {
|
|
124
|
+
stdio: [
|
|
125
|
+
"ignore",
|
|
126
|
+
"pipe",
|
|
127
|
+
"pipe"
|
|
128
|
+
],
|
|
129
|
+
windowsHide: true
|
|
130
|
+
});
|
|
131
|
+
const stderrTail = [];
|
|
132
|
+
child.stderr?.on("data", (chunk) => {
|
|
133
|
+
for (const line of String(chunk).split(/\r?\n/)) {
|
|
134
|
+
if (line.length === 0) continue;
|
|
135
|
+
stderrTail.push(line);
|
|
136
|
+
if (stderrTail.length > STDERR_TAIL_LINES) stderrTail.shift();
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
const stopChild = async () => {
|
|
140
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
141
|
+
child.kill();
|
|
142
|
+
if (!await new Promise((resolve) => {
|
|
143
|
+
const timer = setTimeout(() => resolve(false), KILL_GRACE_MS);
|
|
144
|
+
child.once("exit", () => {
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
resolve(true);
|
|
147
|
+
});
|
|
148
|
+
})) child.kill("SIGKILL");
|
|
149
|
+
};
|
|
150
|
+
const fail = async (message) => {
|
|
151
|
+
await stopChild();
|
|
152
|
+
if (ownedDir) await rm(dataDir, {
|
|
153
|
+
recursive: true,
|
|
154
|
+
force: true
|
|
155
|
+
}).catch(() => void 0);
|
|
156
|
+
const tail = stderrTail.length > 0 ? `\nstderr tail:\n${stderrTail.join("\n")}` : "";
|
|
157
|
+
throw new Error(`${message}${tail}`);
|
|
158
|
+
};
|
|
159
|
+
try {
|
|
160
|
+
const readiness = await waitForReadiness(child, options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS);
|
|
161
|
+
try {
|
|
162
|
+
assertProtocolCompatible(readiness.protocol_version);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
await fail(error.message);
|
|
165
|
+
}
|
|
166
|
+
let closed = false;
|
|
167
|
+
return {
|
|
168
|
+
readiness,
|
|
169
|
+
dataDir,
|
|
170
|
+
close: async () => {
|
|
171
|
+
if (closed) return;
|
|
172
|
+
closed = true;
|
|
173
|
+
await stopChild();
|
|
174
|
+
if (ownedDir) await rm(dataDir, {
|
|
175
|
+
recursive: true,
|
|
176
|
+
force: true
|
|
177
|
+
}).catch(() => void 0);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
} catch (error) {
|
|
181
|
+
await stopChild();
|
|
182
|
+
if (ownedDir) await rm(dataDir, {
|
|
183
|
+
recursive: true,
|
|
184
|
+
force: true
|
|
185
|
+
}).catch(() => void 0);
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
function waitForReadiness(child, timeoutMs) {
|
|
190
|
+
return new Promise((resolve, reject) => {
|
|
191
|
+
if (!child.stdout) {
|
|
192
|
+
reject(/* @__PURE__ */ new Error("spawned runtime has no stdout pipe"));
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const lines = createInterface({ input: child.stdout });
|
|
196
|
+
const timer = setTimeout(() => {
|
|
197
|
+
lines.close();
|
|
198
|
+
reject(/* @__PURE__ */ new Error(`timed out after ${timeoutMs}ms waiting for the runtime readiness line`));
|
|
199
|
+
}, timeoutMs);
|
|
200
|
+
const done = (fn) => {
|
|
201
|
+
clearTimeout(timer);
|
|
202
|
+
lines.close();
|
|
203
|
+
fn();
|
|
204
|
+
};
|
|
205
|
+
lines.on("line", (line) => {
|
|
206
|
+
const readiness = parseReadinessLine(line);
|
|
207
|
+
if (readiness) done(() => resolve(readiness));
|
|
208
|
+
});
|
|
209
|
+
child.once("error", (error) => {
|
|
210
|
+
done(() => reject(/* @__PURE__ */ new Error(`failed to spawn the runtime: ${error.message}`)));
|
|
211
|
+
});
|
|
212
|
+
child.once("exit", (code) => {
|
|
213
|
+
done(() => reject(/* @__PURE__ */ new Error(`runtime exited before reporting readiness (code ${code})`)));
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region src/index.ts
|
|
219
|
+
/**
|
|
220
|
+
* `@flowy-agent-store/sdk` — spawn the runtime, connect over loopback, hand back
|
|
221
|
+
* a ready `AppServerClient`.
|
|
222
|
+
*/
|
|
223
|
+
/**
|
|
224
|
+
* Spawn a loopback runtime with its own data dir and return a connected,
|
|
225
|
+
* initialized client. Rejects non-loopback contact outright (P0-4): this
|
|
226
|
+
* entry point only ever dials the process it just spawned.
|
|
227
|
+
*/
|
|
228
|
+
async function launchClient(options) {
|
|
229
|
+
const server = await spawnAppServer(options);
|
|
230
|
+
const wsUrl = `ws://${server.readiness.host}:${server.readiness.port}/api/app-server/ws`;
|
|
231
|
+
if (!isLoopbackUrl(wsUrl)) {
|
|
232
|
+
await server.close();
|
|
233
|
+
throw new Error(`refusing to connect outside loopback: ${wsUrl}`);
|
|
234
|
+
}
|
|
235
|
+
const client = new AppServerClient({
|
|
236
|
+
transport: new WebSocketTransport(wsUrl, {
|
|
237
|
+
requestTimeoutMs: options.requestTimeoutMs,
|
|
238
|
+
token: options.token
|
|
239
|
+
}),
|
|
240
|
+
client: options.client,
|
|
241
|
+
capabilities: options.capabilities
|
|
242
|
+
});
|
|
243
|
+
try {
|
|
244
|
+
const initializeResult = await client.connect();
|
|
245
|
+
let closed = false;
|
|
246
|
+
return {
|
|
247
|
+
server,
|
|
248
|
+
client,
|
|
249
|
+
initializeResult,
|
|
250
|
+
close: async () => {
|
|
251
|
+
if (closed) return;
|
|
252
|
+
closed = true;
|
|
253
|
+
client.close();
|
|
254
|
+
await server.close();
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
} catch (error) {
|
|
258
|
+
client.close();
|
|
259
|
+
await server.close();
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
//#endregion
|
|
264
|
+
export { launchClient, parseReadinessLine, resolveAppServerBin, spawnAppServer };
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@flowy-agent-store/sdk",
|
|
3
|
+
"version": "0.1.0-beta.2",
|
|
4
|
+
"description": "Node.js host for the Agent Store App Server: spawn the runtime binary and connect over loopback (docs/agent-store/12 P1-3)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.mts",
|
|
10
|
+
"import": "./dist/index.mjs",
|
|
11
|
+
"require": "./dist/index.cjs"
|
|
12
|
+
},
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@flowy-agent-store/client": "0.1.0-beta.2",
|
|
20
|
+
"@flowy-agent-store/protocol": "0.1.0-beta.2"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsdown",
|
|
24
|
+
"prepack": "tsdown"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public",
|
|
28
|
+
"registry": "https://registry.npmjs.org/"
|
|
29
|
+
},
|
|
30
|
+
"main": "./dist/index.cjs",
|
|
31
|
+
"module": "./dist/index.mjs",
|
|
32
|
+
"types": "./dist/index.d.mts",
|
|
33
|
+
"optionalDependencies": {
|
|
34
|
+
"@flowy-agent-store/runtime-win32-x64": "0.1.0-beta.2",
|
|
35
|
+
"@flowy-agent-store/runtime-linux-x64": "0.1.0-beta.2",
|
|
36
|
+
"@flowy-agent-store/runtime-linux-arm64": "0.1.0-beta.2",
|
|
37
|
+
"@flowy-agent-store/runtime-darwin-x64": "0.1.0-beta.2",
|
|
38
|
+
"@flowy-agent-store/runtime-darwin-arm64": "0.1.0-beta.2"
|
|
39
|
+
}
|
|
40
|
+
}
|