@kana-ai/edgar-runtime 0.0.0-stage → 0.1.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 +202 -0
- package/README.md +93 -2
- package/dist/src/main.d.ts +2 -0
- package/dist/src/main.js +39 -0
- package/dist/src/server/ports.d.ts +6 -0
- package/dist/src/server/ports.js +63 -0
- package/dist/src/server/serve.d.ts +15 -0
- package/dist/src/server/serve.js +116 -0
- package/package.json +35 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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 2026 Kana.ai
|
|
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.
|
|
202
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kana-ai/edgar-runtime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The process that runs one extension's code for the EDGAR engine. The engine starts it, sends JSON-RPC 2.0 requests on stdin, one per line, and reads answers and `tool.progress` notifications on stdout. The runtime writes its log to stderr. The messages are in `@kana-ai/edgar-contracts/schemas/json/rpc.schema.json`.
|
|
4
|
+
|
|
5
|
+
You do not start this process yourself: the worker starts one runtime for each extension at the extension's first call, and stops it when the worker stops. Read this page when you debug an extension that does not start, or when you change how an extension is run. For the extension's own code, see [the SDK](/packages/sdk/README.md).
|
|
6
|
+
|
|
7
|
+
## How the engine starts it
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
node --disable-proto=throw --permission \
|
|
11
|
+
--allow-fs-read=<apps/runtime> --allow-fs-read=<packages/sdk> \
|
|
12
|
+
--allow-fs-read=<node_modules/.pnpm> --allow-fs-read=<extension folder> \
|
|
13
|
+
<entry> <extension folder>/edgar-extension.json <extension module>
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
- `<entry>` is the file that `bin` names in the runtime's `package.json`: `src/main.ts` in this repository, and `dist/src/main.js` in a packed install. `<extension module>` is the file that `exports["."]` names in the extension's `package.json`. When the field is missing, the engine uses `src/main.ts` and `src/index.ts`.
|
|
17
|
+
- The environment holds only `PATH`, `HOME` (an empty folder for each extension, `runtimes/<extension>/` in the state folder) and an empty `NODE_OPTIONS`. The process runs in its own process group, and the worker kills the group when it stops.
|
|
18
|
+
- Node 24 refuses `--experimental-permission`. The flag is `--permission`.
|
|
19
|
+
- The process reads its own package, the SDK and its `undici` copy, and the extension. In a pnpm workspace the SDK and `undici` are outside `apps/runtime`, so read access to its own package path alone is not enough: Node stops at the first import. Give read access to each of the four paths above. The runtime needs no write access, no child process, no worker and no addon.
|
|
20
|
+
- On Node 25 or later, the worker adds `--allow-net` only for an extension whose approved manifest grants a `network:<host>` capability, or whose project names hosts in `[extensions.<name>] hosts`, so an extension with no host has no network at all. `--allow-net` opens every host, because Node has no form for one host, so the runtime's own `fetch` policy limits the hosts.
|
|
21
|
+
|
|
22
|
+
## What it does
|
|
23
|
+
|
|
24
|
+
1. It reads the two arguments. With fewer, it prints `usage: edgar-runtime <edgar-extension.json> <extension module>` and exits 2.
|
|
25
|
+
1. It replaces `http.request` and `https.request` with stubs that throw, and refuses to start, with exit 1, if it cannot.
|
|
26
|
+
1. It hashes `edgar-extension.json` with SHA-256, and imports the module. A module whose default export is not made by `defineExtension` stops the start, with exit 1.
|
|
27
|
+
1. It answers `hello` with the contract and the hash. The engine compares the hash with the approved one, and refuses the extension with `manifest_drift` when they differ.
|
|
28
|
+
1. It runs one `tool.call` at a time. A second call while one runs is refused with `busy`. A call that throws is answered with `internal_error`, and the engine records `permanent_failure(tool_error)`.
|
|
29
|
+
1. It lets `fetch` reach only the hosts of each call's `network:<host>` capabilities.
|
|
30
|
+
1. It answers a `tool.cancel` within 5 seconds. A tool that has not stopped by then is answered `cancelled`, and the runtime logs `tool.call <operation id> ignored the cancel, exiting` and exits 1, so the engine starts a new process for the next call and no later call gets `busy`. It refuses a line over 4 MiB, and exits 0 after `idle_seconds` with no call, after `shutdown`, or at the end of its input. At `shutdown` and at the end of its input, it first tells the call in flight to stop, as a `tool.cancel` does, so a service does not keep the process after the engine has gone.
|
|
31
|
+
|
|
32
|
+
## Talk to it by hand
|
|
33
|
+
|
|
34
|
+
To check that an extension starts, run the runtime with the four read paths and send it lines. This session sends a call before `hello`, a `hello` with a wrong contract, a good `hello` and a `shutdown`, to the `notes` extension of [the SDK page](/packages/sdk/README.md#define-an-extension):
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
printf '%s\n' \
|
|
38
|
+
'{"jsonrpc":"2.0","id":1,"method":"tool.call","params":{}}' \
|
|
39
|
+
'{"jsonrpc":"2.0","id":2,"method":"hello","params":{"contract":2,"idle_seconds":60}}' \
|
|
40
|
+
'{"jsonrpc":"2.0","id":3,"method":"hello","params":{"contract":1,"idle_seconds":60}}' \
|
|
41
|
+
'{"jsonrpc":"2.0","id":4,"method":"shutdown","params":{}}' |
|
|
42
|
+
node --disable-proto=throw --permission \
|
|
43
|
+
--allow-fs-read="$EDGAR/apps/runtime" --allow-fs-read="$EDGAR/packages/sdk" \
|
|
44
|
+
--allow-fs-read="$EDGAR/node_modules/.pnpm" --allow-fs-read="$PWD" \
|
|
45
|
+
"$EDGAR/apps/runtime/src/main.ts" "$PWD/edgar-extension.json" "$PWD/src/index.ts"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`$EDGAR` is the folder of this repository, and the current folder is the extension's. The answers, one line each:
|
|
49
|
+
|
|
50
|
+
```text
|
|
51
|
+
{"jsonrpc":"2.0","id":1,"error":{"code":-32600,"message":"invalid_request: hello first"}}
|
|
52
|
+
{"jsonrpc":"2.0","id":2,"error":{"code":-32004,"message":"contract_mismatch: this runtime speaks 1"}}
|
|
53
|
+
{"jsonrpc":"2.0","id":3,"result":{"contract":1,"manifest_hash":"sha256:1e4b1c4f9626644f4f9e75ddfd0b33ec0d1db0d30f94f2c08c91aade6f2241a1"}}
|
|
54
|
+
{"jsonrpc":"2.0","id":4,"result":null}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The `manifest_hash` is the SHA-256 of `edgar-extension.json`, the same value that `shasum -a 256 edgar-extension.json` prints. With `"idle_seconds":1` and no `shutdown`, the runtime writes `idle for 1 s, exiting` to stderr after one second and exits 0.
|
|
58
|
+
|
|
59
|
+
## Limits and failure modes
|
|
60
|
+
|
|
61
|
+
| What you see | Cause | What to do |
|
|
62
|
+
| --------------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
|
63
|
+
| An `ERR_ACCESS_DENIED` error at the first import | A read path is missing from the command. | Give read access to each of the four paths. |
|
|
64
|
+
| `refusing to start: <module> has no default export made by defineExtension` | The module exports something else. | Export the result of `defineExtension` as the default export. |
|
|
65
|
+
| `manifest_drift` on the attempt | The manifest changed since the approval. | Build the extension, read the change, then run `edgar extensions approve <name>`. |
|
|
66
|
+
| `busy` | The engine sent a second call while one ran. | Nothing: the engine sends one call at a time to a runtime. |
|
|
67
|
+
| `runtime_crashed` on the attempt | The process stopped during a call. | Read the `runtime_log` events of the call. The next call starts a new process. |
|
|
68
|
+
| `ignored the cancel, exiting` in the log | A tool did not read `ctx.signal`. | Pass `ctx.signal` to each `fetch` and wait of the tool. The next call starts a new process. |
|
|
69
|
+
|
|
70
|
+
The runtime holds each call to the hosts of its `network:<host>` capabilities. `fetch` and `WebSocket` go through undici's global dispatcher, which refuses any other host. `http.request`, `http.get`, `https.request` and `https.get` throw. Every TCP connection goes through `Socket.connect`, which the runtime replaces before it loads the extension: `net.connect`, `net.createConnection`, `tls.connect`, `http2.connect` and an undici `Agent` of the extension's own throw `NetworkRefused` for an unlisted host. A socket to a pipe, or with a `lookup` of its own, is refused. UDP (`node:dgram`) is refused for every host. When one of these replacements does not take, the runtime refuses to start. Code that reaches Node's internal bindings is not stopped, and a DNS lookup is not checked.
|
|
71
|
+
|
|
72
|
+
## Tests
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pnpm --filter @kana-ai/edgar-runtime run test
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The tests in `tests/server/` drive the server over in-memory streams: a call that reads the sandbox with its secret, the progress throttle, `hello` and the contract check, a call before `hello`, a second call (`busy`) and the cancel, a tool that ignores the cancel (exit 1) and one that stops when told (the next call runs), a call the runtime cannot run, the 4 MiB limit, `shutdown`, the idle exit, and a call that ends only when it is told to, at `shutdown` and at the end of the input.
|
|
79
|
+
|
|
80
|
+
## Validation
|
|
81
|
+
|
|
82
|
+
These commands were run on 2026-11-10 on macOS with Node 26:
|
|
83
|
+
|
|
84
|
+
| Command | Exit code |
|
|
85
|
+
| ---------------------------------------------------------- | ------------------------- |
|
|
86
|
+
| The session above | 0, the four answers above |
|
|
87
|
+
| The same runtime with `"idle_seconds":1` and no `shutdown` | 0 after one second |
|
|
88
|
+
| `node apps/runtime/src/main.ts` with no arguments | 2 |
|
|
89
|
+
| `pnpm --filter @kana-ai/edgar-runtime run test` | 0, `pass 13` |
|
|
90
|
+
|
|
91
|
+
## Where to read next
|
|
92
|
+
|
|
93
|
+
- [`@kana-ai/edgar-contracts`](/packages/contracts/README.md): each message, as JSON Schema.
|
|
94
|
+
- [The `edgar-adapters` crate](/packages/crates/edgar-adapters/README.md#runtime-client-runtime): the engine's side of the same wire.
|
package/dist/src/main.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { isExtension } from "@kana-ai/edgar-sdk";
|
|
7
|
+
import { callables, installNetworkPolicy, guardNodeNetwork } from "@kana-ai/edgar-sdk/runtime";
|
|
8
|
+
import { serve } from "#server/serve";
|
|
9
|
+
const log = (line) => {
|
|
10
|
+
process.stderr.write(`${line}\n`);
|
|
11
|
+
};
|
|
12
|
+
const [manifestPath, modulePath] = process.argv.slice(2);
|
|
13
|
+
if (manifestPath === undefined || modulePath === undefined) {
|
|
14
|
+
log("usage: edgar-runtime <edgar-extension.json> <extension module>");
|
|
15
|
+
process.exit(2);
|
|
16
|
+
}
|
|
17
|
+
const guarded = guardNodeNetwork();
|
|
18
|
+
if (!guarded.ok) {
|
|
19
|
+
log(`refusing to start: ${guarded.error.message}`);
|
|
20
|
+
process.exit(1);
|
|
21
|
+
}
|
|
22
|
+
installNetworkPolicy(new Set());
|
|
23
|
+
const manifestHash = `sha256:${createHash("sha256")
|
|
24
|
+
.update(await readFile(manifestPath))
|
|
25
|
+
.digest("hex")}`;
|
|
26
|
+
const module = await import(pathToFileURL(resolve(modulePath)).href);
|
|
27
|
+
const extension = typeof module === "object" && module !== null && "default" in module ? module.default : undefined;
|
|
28
|
+
if (!isExtension(extension)) {
|
|
29
|
+
log(`refusing to start: ${modulePath} has no default export made by defineExtension`);
|
|
30
|
+
process.exit(1);
|
|
31
|
+
}
|
|
32
|
+
await serve({
|
|
33
|
+
input: process.stdin,
|
|
34
|
+
output: process.stdout,
|
|
35
|
+
log,
|
|
36
|
+
callables: callables(extension),
|
|
37
|
+
manifestHash,
|
|
38
|
+
exit: (code) => process.exit(code),
|
|
39
|
+
});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type Peer } from "@kana-ai/edgar-sdk/codec";
|
|
2
|
+
import type { Port } from "@kana-ai/edgar-sdk/runtime";
|
|
3
|
+
/** The engine ports of one call: requests go out by id, progress and log lines go out throttled to one `tool.progress` per `interval` ms. */
|
|
4
|
+
export declare function enginePort(rpc: Peer, operationId: string, interval: number, log: (line: string) => void): Port & {
|
|
5
|
+
flush(): void;
|
|
6
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { errorCodes, trusted, } from "@kana-ai/edgar-sdk/codec";
|
|
2
|
+
import { err, ok } from "@kana-ai/edgar-sdk/result";
|
|
3
|
+
const portErrors = new Map([
|
|
4
|
+
[errorCodes.capability_refused, "capability_refused"],
|
|
5
|
+
[errorCodes.sandbox_refused, "sandbox_refused"],
|
|
6
|
+
[errorCodes.runtime_payload_too_large, "runtime_payload_too_large"],
|
|
7
|
+
[errorCodes.unknown_id, "unknown_id"],
|
|
8
|
+
]);
|
|
9
|
+
/** The engine ports of one call: requests go out by id, progress and log lines go out throttled to one `tool.progress` per `interval` ms. */
|
|
10
|
+
export function enginePort(rpc, operationId, interval, log) {
|
|
11
|
+
const progress = throttle(interval, (params) => {
|
|
12
|
+
if (!rpc.send({ jsonrpc: "2.0", method: "tool.progress", params }))
|
|
13
|
+
log(`a tool.progress of ${operationId} is over 4 MiB and was dropped`);
|
|
14
|
+
});
|
|
15
|
+
return {
|
|
16
|
+
request: async (method, params) => portResult(await rpc.request(method, params)),
|
|
17
|
+
progress: (snapshot) => progress.push(operationId, { snapshot }),
|
|
18
|
+
log: (line) => progress.push(operationId, { line }),
|
|
19
|
+
flush: () => progress.flush(),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function portResult(answer) {
|
|
23
|
+
if (answer.ok)
|
|
24
|
+
return ok(trusted(answer.result));
|
|
25
|
+
const code = answer.code === undefined ? undefined : portErrors.get(answer.code);
|
|
26
|
+
return err({ code: code ?? "engine_error", message: answer.message });
|
|
27
|
+
}
|
|
28
|
+
function throttle(interval, send) {
|
|
29
|
+
let last = -Infinity;
|
|
30
|
+
let timer;
|
|
31
|
+
let operation = "";
|
|
32
|
+
let snapshot;
|
|
33
|
+
let lines = [];
|
|
34
|
+
const flush = () => {
|
|
35
|
+
clearTimeout(timer);
|
|
36
|
+
timer = undefined;
|
|
37
|
+
if (snapshot === undefined && lines.length === 0)
|
|
38
|
+
return;
|
|
39
|
+
send({
|
|
40
|
+
operation_id: operation,
|
|
41
|
+
...(snapshot === undefined ? {} : { snapshot }),
|
|
42
|
+
...(lines.length === 0 ? {} : { lines }),
|
|
43
|
+
});
|
|
44
|
+
last = Date.now();
|
|
45
|
+
snapshot = undefined;
|
|
46
|
+
lines = [];
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
push(operationId, item) {
|
|
50
|
+
operation = operationId;
|
|
51
|
+
if (item.snapshot !== undefined)
|
|
52
|
+
snapshot = item.snapshot;
|
|
53
|
+
if (item.line !== undefined)
|
|
54
|
+
lines.push(item.line);
|
|
55
|
+
const wait = last + interval - Date.now();
|
|
56
|
+
if (wait <= 0)
|
|
57
|
+
flush();
|
|
58
|
+
else
|
|
59
|
+
timer ??= setTimeout(flush, wait);
|
|
60
|
+
},
|
|
61
|
+
flush,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Readable, Writable } from "node:stream";
|
|
2
|
+
import { type Callable } from "@kana-ai/edgar-sdk/runtime";
|
|
3
|
+
/** What `serve` needs; streams are the process's stdin and stdout in `main.ts` and `Duplex` pairs in tests. */
|
|
4
|
+
export interface ServeOptions {
|
|
5
|
+
readonly input: Readable;
|
|
6
|
+
readonly output: Writable;
|
|
7
|
+
readonly log: (line: string) => void;
|
|
8
|
+
readonly callables: ReadonlyMap<string, Callable>;
|
|
9
|
+
readonly manifestHash: string;
|
|
10
|
+
readonly exit: (code: number) => void;
|
|
11
|
+
readonly progressIntervalMs?: number;
|
|
12
|
+
readonly cancelGraceMs?: number;
|
|
13
|
+
}
|
|
14
|
+
/** Serves JSON-RPC 2.0 lines until `shutdown`, the end of input, or `idle_seconds` without a call. A body still running when its call is answered ignored the cancel past the grace: the process exits 1, so the engine starts a clean one for the next call. */
|
|
15
|
+
export declare function serve(options: ServeOptions): Promise<void>;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { permanentFailure } from "@kana-ai/edgar-sdk";
|
|
2
|
+
import { CONTRACT, acceptHello, peer, trusted } from "@kana-ai/edgar-sdk/codec";
|
|
3
|
+
import { invoke } from "@kana-ai/edgar-sdk/runtime";
|
|
4
|
+
import { enginePort } from "#server/ports";
|
|
5
|
+
/** Serves JSON-RPC 2.0 lines until `shutdown`, the end of input, or `idle_seconds` without a call. A body still running when its call is answered ignored the cancel past the grace: the process exits 1, so the engine starts a clean one for the next call. */
|
|
6
|
+
export async function serve(options) {
|
|
7
|
+
const interval = options.progressIntervalMs ?? 250;
|
|
8
|
+
const rpc = peer(options.output, options.log);
|
|
9
|
+
let ready = false;
|
|
10
|
+
let idleSeconds = 0;
|
|
11
|
+
let idle;
|
|
12
|
+
let current;
|
|
13
|
+
let over = false;
|
|
14
|
+
const armIdle = () => {
|
|
15
|
+
clearTimeout(idle);
|
|
16
|
+
if (over)
|
|
17
|
+
return;
|
|
18
|
+
idle = setTimeout(() => {
|
|
19
|
+
options.log(`idle for ${idleSeconds} s, exiting`);
|
|
20
|
+
options.exit(0);
|
|
21
|
+
}, idleSeconds * 1000);
|
|
22
|
+
};
|
|
23
|
+
const call = (id, params) => {
|
|
24
|
+
const callable = options.callables.get(params.tool);
|
|
25
|
+
if (callable === undefined)
|
|
26
|
+
return rpc.fail(id, "invalid_params", `no tool ${params.tool}`);
|
|
27
|
+
clearTimeout(idle);
|
|
28
|
+
const controller = new AbortController();
|
|
29
|
+
const engine = enginePort(rpc, params.operation_id, interval, options.log);
|
|
30
|
+
let running = false;
|
|
31
|
+
const body = {
|
|
32
|
+
run: async (input, ctx) => {
|
|
33
|
+
running = true;
|
|
34
|
+
try {
|
|
35
|
+
return await callable.run(input, ctx);
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
running = false;
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
const answered = (async () => {
|
|
43
|
+
try {
|
|
44
|
+
const outcome = await invoke(body, params, engine, controller.signal, options.cancelGraceMs);
|
|
45
|
+
engine.flush();
|
|
46
|
+
if (!rpc.send({ jsonrpc: "2.0", id, result: outcome })) {
|
|
47
|
+
rpc.reply(id, permanentFailure("runtime_payload_too_large", "the outcome is over 4 MiB"));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
options.log(`tool.call ${params.operation_id} failed: ${String(error)}`);
|
|
52
|
+
rpc.fail(id, "internal_error", error instanceof Error ? error.message : String(error));
|
|
53
|
+
}
|
|
54
|
+
})();
|
|
55
|
+
const done = (async () => {
|
|
56
|
+
await answered;
|
|
57
|
+
if (running) {
|
|
58
|
+
options.log(`tool.call ${params.operation_id} ignored the cancel, exiting`);
|
|
59
|
+
return options.exit(1);
|
|
60
|
+
}
|
|
61
|
+
current = undefined;
|
|
62
|
+
armIdle();
|
|
63
|
+
})();
|
|
64
|
+
current = { operationId: params.operation_id, controller, answered, done };
|
|
65
|
+
};
|
|
66
|
+
const request = async (id, method, params) => {
|
|
67
|
+
switch (method) {
|
|
68
|
+
case "hello": {
|
|
69
|
+
if (!acceptHello(rpc, id, params))
|
|
70
|
+
return;
|
|
71
|
+
const seconds = params["idle_seconds"];
|
|
72
|
+
if (typeof seconds !== "number" || !Number.isInteger(seconds) || seconds < 1) {
|
|
73
|
+
return rpc.fail(id, "invalid_params", "idle_seconds must be a positive integer");
|
|
74
|
+
}
|
|
75
|
+
ready = true;
|
|
76
|
+
idleSeconds = seconds;
|
|
77
|
+
if (current === undefined)
|
|
78
|
+
armIdle();
|
|
79
|
+
return rpc.reply(id, {
|
|
80
|
+
contract: CONTRACT,
|
|
81
|
+
manifest_hash: options.manifestHash,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
case "tool.call":
|
|
85
|
+
if (!ready)
|
|
86
|
+
return rpc.fail(id, "invalid_request", "hello first");
|
|
87
|
+
if (current !== undefined)
|
|
88
|
+
return rpc.fail(id, "busy", `${current.operationId} is in flight`);
|
|
89
|
+
return call(id, trusted(params));
|
|
90
|
+
case "tool.cancel": {
|
|
91
|
+
const target = current;
|
|
92
|
+
if (target === undefined || target.operationId !== params["operation_id"]) {
|
|
93
|
+
return rpc.reply(id, { cancelled: false });
|
|
94
|
+
}
|
|
95
|
+
target.controller.abort();
|
|
96
|
+
await target.answered;
|
|
97
|
+
return rpc.reply(id, { cancelled: true });
|
|
98
|
+
}
|
|
99
|
+
case "shutdown":
|
|
100
|
+
over = true;
|
|
101
|
+
clearTimeout(idle);
|
|
102
|
+
current?.controller.abort();
|
|
103
|
+
await current?.answered;
|
|
104
|
+
rpc.reply(id, null);
|
|
105
|
+
return options.exit(0);
|
|
106
|
+
default:
|
|
107
|
+
return rpc.fail(id, "method_not_found", method);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
await rpc.listen(options.input, request);
|
|
111
|
+
current?.controller.abort();
|
|
112
|
+
await current?.answered;
|
|
113
|
+
over = true;
|
|
114
|
+
clearTimeout(idle);
|
|
115
|
+
options.exit(0);
|
|
116
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kana-ai/edgar-runtime",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "The process that runs one extension's code for the EDGAR engine, over JSON-RPC on stdio.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/kana-ai/edgar",
|
|
9
|
+
"directory": "apps/runtime"
|
|
10
|
+
},
|
|
11
|
+
"bin": {
|
|
12
|
+
"edgar-runtime": "./dist/src/main.js"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist/src"
|
|
16
|
+
],
|
|
17
|
+
"type": "module",
|
|
18
|
+
"imports": {
|
|
19
|
+
"#*": "./dist/src/*.js"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@kana-ai/edgar-contracts": "0.1.1",
|
|
23
|
+
"@kana-ai/edgar-sdk": "0.1.1"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "24.19.2",
|
|
27
|
+
"oxfmt": "0.76.0",
|
|
28
|
+
"oxlint": "1.91.0",
|
|
29
|
+
"oxlint-tsgolint": "7.0.2005",
|
|
30
|
+
"typescript": "7.0.2"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"check-types": "tsc --noEmit",
|
|
34
|
+
"lint": "oxlint --type-aware --deny-warnings",
|
|
35
|
+
"format:check": "oxfmt --check",
|
|
36
|
+
"test": "node --test"
|
|
37
|
+
}
|
|
6
38
|
}
|