@agentkit-js/kernel-pyodide 0.2.0
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 +186 -0
- package/README.md +32 -0
- package/dist/PyodideKernel.d.ts +25 -0
- package/dist/PyodideKernel.d.ts.map +1 -0
- package/dist/PyodideKernel.js +235 -0
- package/dist/PyodideKernel.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
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 made available under
|
|
36
|
+
the License, as indicated by a copyright notice that is included in
|
|
37
|
+
or attached to the work (an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
43
|
+
of this License, Derivative Works shall not include works that remain
|
|
44
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
45
|
+
the Work and Derivative Works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean, as defined by the copyright owner,
|
|
48
|
+
any work of authorship, including the original version of the Work and
|
|
49
|
+
any modifications or additions to that Work or Derivative Works of the
|
|
50
|
+
Work, that is intentionally submitted to the Licensor for inclusion in
|
|
51
|
+
the Work by the copyright owner or by an individual or Legal Entity
|
|
52
|
+
authorized to submit on behalf of the copyright owner. For the purposes
|
|
53
|
+
of this definition, "submitted" means any form of electronic, verbal,
|
|
54
|
+
or written communication sent to the Licensor or its representatives,
|
|
55
|
+
including but not limited to communication on electronic mailing lists,
|
|
56
|
+
source code control systems, and issue tracking systems that are
|
|
57
|
+
managed by, or on behalf of, the Licensor for the purpose of
|
|
58
|
+
discussing and improving the Work, but excluding communication that is
|
|
59
|
+
conspicuously marked or otherwise designated in writing by the copyright
|
|
60
|
+
owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
63
|
+
whom a Contribution has been received by the Licensor and included
|
|
64
|
+
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 the 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 cross-claim
|
|
83
|
+
or counterclaim in a lawsuit) alleging that the Work or any
|
|
84
|
+
Contribution embodied within the Work constitutes patent or
|
|
85
|
+
contributory patent infringement, then any patent licenses granted
|
|
86
|
+
to You under this License for that Work shall terminate as of the date
|
|
87
|
+
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 Derivative
|
|
95
|
+
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, You must include a readable copy of the
|
|
108
|
+
attribution notices contained within such NOTICE file, in
|
|
109
|
+
at least one of the following places: within a NOTICE text
|
|
110
|
+
file distributed as part of the Derivative Works; within
|
|
111
|
+
the Source form or documentation, if provided along with the
|
|
112
|
+
Derivative Works; or, within a display generated by the
|
|
113
|
+
Derivative Works, if and wherever such third-party notices
|
|
114
|
+
normally appear. The contents of the NOTICE file are for
|
|
115
|
+
informational purposes only and do not modify the License.
|
|
116
|
+
You may add Your own attribution notices within Derivative
|
|
117
|
+
Works that You distribute, alongside or as an addendum to
|
|
118
|
+
the NOTICE text from the Work, provided that such additional
|
|
119
|
+
attribution notices cannot be construed as modifying the License.
|
|
120
|
+
|
|
121
|
+
You may add Your own license statement for Your modifications and
|
|
122
|
+
may provide additional grant of rights to use, copy, modify, merge,
|
|
123
|
+
publish, distribute, sublicense, and/or sell copies of the
|
|
124
|
+
Contribution, either alone or in combination with the Work.
|
|
125
|
+
|
|
126
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
127
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
128
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
129
|
+
this License, without any additional terms or conditions.
|
|
130
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
131
|
+
the terms of any separate license agreement you may have executed
|
|
132
|
+
with Licensor regarding such Contributions.
|
|
133
|
+
|
|
134
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
135
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
136
|
+
except as required for reasonable and customary use in describing the
|
|
137
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
138
|
+
|
|
139
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
140
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
141
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
142
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
143
|
+
implied, including, without limitation, any conditions of
|
|
144
|
+
TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
145
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
146
|
+
appropriateness of using or reproducing the Work and assume any
|
|
147
|
+
risks associated with Your exercise of permissions under this License.
|
|
148
|
+
|
|
149
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
150
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
151
|
+
unless required by applicable law (such as deliberate and grossly
|
|
152
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
153
|
+
liable to You for damages, including any direct, indirect, special,
|
|
154
|
+
incidental, or exemplary damages of any character arising as a
|
|
155
|
+
result of this License or out of the use or inability to use the
|
|
156
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
157
|
+
work stoppage, computer failure or malfunction, or all other
|
|
158
|
+
commercial damages or losses), even if such Contributor has been
|
|
159
|
+
advised of the possibility of such damages.
|
|
160
|
+
|
|
161
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
162
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
163
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
164
|
+
or other liability obligations and/or rights consistent with this
|
|
165
|
+
License. However, in accepting such obligations, You may act only
|
|
166
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
167
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
168
|
+
defend, and hold each Contributor harmless for any liability
|
|
169
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
170
|
+
of your accepting any such warranty or additional liability.
|
|
171
|
+
|
|
172
|
+
END OF TERMS AND CONDITIONS
|
|
173
|
+
|
|
174
|
+
Copyright 2026 agentkit-js contributors
|
|
175
|
+
|
|
176
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
177
|
+
you may not use this file except in compliance with the License.
|
|
178
|
+
You may obtain a copy of the License at
|
|
179
|
+
|
|
180
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
181
|
+
|
|
182
|
+
Unless required by applicable law or agreed to in writing, software
|
|
183
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
184
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
185
|
+
See the License for the specific language governing permissions and
|
|
186
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# @agentkit-js/kernel-pyodide
|
|
2
|
+
|
|
3
|
+
CPython-in-WASM kernel (Pyodide) — run real Python code from agents on Node, Bun, and CF Workers.
|
|
4
|
+
|
|
5
|
+
> Part of [agentkit-js](https://github.com/telleroutlook/agentkit-js) — a TypeScript + WASM agent runtime.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @agentkit-js/kernel-pyodide @agentkit-js/core pyodide
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { PyodideKernel } from "@agentkit-js/kernel-pyodide";
|
|
17
|
+
|
|
18
|
+
const kernel = new PyodideKernel();
|
|
19
|
+
const result = await kernel.run(`import math; print(math.gcd(2024, 56))`);
|
|
20
|
+
console.log(result.logs); // ["8"]
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
> ⚠️ **Memory budget on edge runtimes** — Pyodide's WASM image and Python heap together are
|
|
24
|
+
> ~50–80 MB resident. Cloudflare Workers' free tier (~128 MB) leaves only thin headroom for
|
|
25
|
+
> user code; for memory-heavy workloads use [`kernel-wasmtime`](../kernel-wasmtime) or
|
|
26
|
+
> [`kernel-remote`](../kernel-remote) microVMs.
|
|
27
|
+
|
|
28
|
+
See the [kernel decision tree](https://github.com/telleroutlook/agentkit-js/blob/main/docs/kernels/comparison.md).
|
|
29
|
+
|
|
30
|
+
## License
|
|
31
|
+
|
|
32
|
+
[Apache-2.0](./LICENSE) — © agentkit-js contributors
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { CapabilityManifest, KernelResult, WasmKernel } from "@agentkit-js/core/executor";
|
|
2
|
+
/**
|
|
3
|
+
* PyodideKernel — runs Python code in a Pyodide (CPython-in-WASM) sandbox (A4).
|
|
4
|
+
*
|
|
5
|
+
* Uses the `pyodide` npm package (pure JS/WASM, no native binaries required).
|
|
6
|
+
* A4 target from the spec: full CPython semantics, numpy/scipy/pandas available
|
|
7
|
+
* via pyodide.loadPackage().
|
|
8
|
+
*
|
|
9
|
+
* State model mirrors JsKernel:
|
|
10
|
+
* - Python globals persist across run() calls (stateful kernel).
|
|
11
|
+
* - __final_answer__ sentinel signals the agent's final answer.
|
|
12
|
+
* - reset() clears all Python globals and re-initialises the namespace.
|
|
13
|
+
* - snapshot()/restore() serialise via JSON (functions not preserved).
|
|
14
|
+
*
|
|
15
|
+
* Pyodide is loaded lazily on the first run() call (~500ms first-use overhead).
|
|
16
|
+
*/
|
|
17
|
+
export declare class PyodideKernel implements WasmKernel {
|
|
18
|
+
#private;
|
|
19
|
+
run(code: string, capabilities?: Partial<CapabilityManifest>): Promise<KernelResult>;
|
|
20
|
+
reset(): Promise<void>;
|
|
21
|
+
snapshot(): Promise<Uint8Array>;
|
|
22
|
+
restore(snapshot: Uint8Array): Promise<void>;
|
|
23
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=PyodideKernel.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PyodideKernel.d.ts","sourceRoot":"","sources":["../src/PyodideKernel.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAW/F;;;;;;;;;;;;;;GAcG;AACH,qBAAa,aAAc,YAAW,UAAU;;IA8CxC,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,OAAO,CAAC,YAAY,CAAC;IA2IpF,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAetB,QAAQ,IAAI,OAAO,CAAC,UAAU,CAAC;IAoB/B,OAAO,CAAC,QAAQ,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ5C,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC;CAK7C"}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PyodideKernel — runs Python code in a Pyodide (CPython-in-WASM) sandbox (A4).
|
|
3
|
+
*
|
|
4
|
+
* Uses the `pyodide` npm package (pure JS/WASM, no native binaries required).
|
|
5
|
+
* A4 target from the spec: full CPython semantics, numpy/scipy/pandas available
|
|
6
|
+
* via pyodide.loadPackage().
|
|
7
|
+
*
|
|
8
|
+
* State model mirrors JsKernel:
|
|
9
|
+
* - Python globals persist across run() calls (stateful kernel).
|
|
10
|
+
* - __final_answer__ sentinel signals the agent's final answer.
|
|
11
|
+
* - reset() clears all Python globals and re-initialises the namespace.
|
|
12
|
+
* - snapshot()/restore() serialise via JSON (functions not preserved).
|
|
13
|
+
*
|
|
14
|
+
* Pyodide is loaded lazily on the first run() call (~500ms first-use overhead).
|
|
15
|
+
*/
|
|
16
|
+
export class PyodideKernel {
|
|
17
|
+
#py = null;
|
|
18
|
+
#logs = [];
|
|
19
|
+
#initPromise = null;
|
|
20
|
+
async #ensurePyodide() {
|
|
21
|
+
if (this.#py)
|
|
22
|
+
return this.#py;
|
|
23
|
+
if (this.#initPromise)
|
|
24
|
+
return this.#initPromise;
|
|
25
|
+
this.#initPromise = (async () => {
|
|
26
|
+
const { loadPyodide } = await import("pyodide");
|
|
27
|
+
// Resolve the pyodide package directory so its WASM assets can be found
|
|
28
|
+
// regardless of the module resolution root (monorepo, pnpm hoisting, etc.).
|
|
29
|
+
// Use a plain POSIX path (no file:// prefix) — Pyodide handles both forms
|
|
30
|
+
// but the file:// form breaks under vitest's module resolver.
|
|
31
|
+
const { createRequire } = await import("node:module");
|
|
32
|
+
const { dirname } = await import("node:path");
|
|
33
|
+
const pkgRequire = createRequire(import.meta.url);
|
|
34
|
+
const pkgJsonPath = pkgRequire.resolve("pyodide/package.json");
|
|
35
|
+
const indexURL = `${dirname(pkgJsonPath)}/`;
|
|
36
|
+
const py = (await loadPyodide({ indexURL }));
|
|
37
|
+
// Initialise both sentinel spellings (Q5: dual alias for cross-kernel compatibility).
|
|
38
|
+
py.runPython("__final_answer__ = None; __finalAnswer__ = None");
|
|
39
|
+
// Q9: install capability infrastructure (urllib patch, check helpers) once.
|
|
40
|
+
// Per-call capability data is updated cheaply by #applyCapabilities.
|
|
41
|
+
this.#installCapabilityInfrastructure(py);
|
|
42
|
+
this.#py = py;
|
|
43
|
+
return py;
|
|
44
|
+
})();
|
|
45
|
+
return this.#initPromise;
|
|
46
|
+
}
|
|
47
|
+
#attachCapture(py) {
|
|
48
|
+
py.setStdout({
|
|
49
|
+
batched: (s) => {
|
|
50
|
+
this.#logs.push(s);
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
py.setStderr({
|
|
54
|
+
batched: (s) => {
|
|
55
|
+
this.#logs.push(`[stderr] ${s}`);
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
async run(code, capabilities) {
|
|
60
|
+
const py = await this.#ensurePyodide();
|
|
61
|
+
this.#logs = [];
|
|
62
|
+
this.#attachCapture(py);
|
|
63
|
+
// Reset the sentinel before each run.
|
|
64
|
+
py.globals.set("__final_answer__", null);
|
|
65
|
+
py.globals.set("__finalAnswer__", null);
|
|
66
|
+
// A2: inject/revoke capability globals per call.
|
|
67
|
+
this.#applyCapabilities(py, capabilities);
|
|
68
|
+
let output;
|
|
69
|
+
try {
|
|
70
|
+
output = py.runPython(code);
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
throw new Error(`PyodideKernelError: ${err instanceof Error ? err.message : String(err)}`);
|
|
74
|
+
}
|
|
75
|
+
// Q5: check both sentinel spellings for cross-kernel compatibility.
|
|
76
|
+
const finalAnswerSnake = py.globals.get("__final_answer__");
|
|
77
|
+
const finalAnswerCamel = py.globals.get("__finalAnswer__");
|
|
78
|
+
const finalAnswer = finalAnswerSnake !== null && finalAnswerSnake !== undefined
|
|
79
|
+
? finalAnswerSnake
|
|
80
|
+
: finalAnswerCamel;
|
|
81
|
+
const isFinalAnswer = finalAnswer !== null && finalAnswer !== undefined;
|
|
82
|
+
return {
|
|
83
|
+
output: isFinalAnswer ? finalAnswer : output,
|
|
84
|
+
logs: [...this.#logs],
|
|
85
|
+
isFinalAnswer,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Enforce capability constraints (A2) for the current run call.
|
|
90
|
+
*
|
|
91
|
+
* Network enforcement (allowedHosts):
|
|
92
|
+
* The urllib monkey-patch is installed ONCE at context init time (in #ensurePyodide).
|
|
93
|
+
* Per-call, we only update the _allowed_hosts data variable that the patch reads.
|
|
94
|
+
* This prevents the nesting bug where re-patching every step caused _original_urlopen
|
|
95
|
+
* to capture the previous _checked_urlopen, forming a deeper call chain each step.
|
|
96
|
+
*
|
|
97
|
+
* File-system (allowedReadPaths / allowedWritePaths): Pyodide runs on Emscripten MEMFS
|
|
98
|
+
* (in-memory, isolated from real disk unless NODEFS is mounted — which we never do).
|
|
99
|
+
* Advisory __check_path__ helpers are installed once at init; data updated per-call.
|
|
100
|
+
*/
|
|
101
|
+
#applyCapabilities(py, capabilities) {
|
|
102
|
+
const allowedHosts = capabilities?.allowedHosts ?? [];
|
|
103
|
+
const readPaths = capabilities?.allowedReadPaths ?? [];
|
|
104
|
+
const writePaths = capabilities?.allowedWritePaths ?? [];
|
|
105
|
+
const extraCaps = capabilities?.extraCapabilities ?? [];
|
|
106
|
+
// Only update the data variables — functions were defined once at init time.
|
|
107
|
+
const hostsJson = JSON.stringify(JSON.stringify(allowedHosts));
|
|
108
|
+
const readJson = JSON.stringify(JSON.stringify(readPaths));
|
|
109
|
+
const writeJson = JSON.stringify(JSON.stringify(writePaths));
|
|
110
|
+
const extraJson = JSON.stringify(JSON.stringify(extraCaps));
|
|
111
|
+
py.runPython(`
|
|
112
|
+
import json as _j
|
|
113
|
+
_allowed_hosts = _j.loads(${hostsJson})
|
|
114
|
+
__allowed_read_paths__ = _j.loads(${readJson})
|
|
115
|
+
__allowed_write_paths__ = _j.loads(${writeJson})
|
|
116
|
+
__extra_capabilities__ = _j.loads(${extraJson})
|
|
117
|
+
del _j
|
|
118
|
+
`);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Install capability enforcement infrastructure once at context initialisation.
|
|
122
|
+
*
|
|
123
|
+
* Q9: The urllib monkey-patch is applied here (once) rather than in #applyCapabilities
|
|
124
|
+
* (which runs every step). Re-patching every step caused _original_urlopen to
|
|
125
|
+
* capture the previous _checked_urlopen on the second call, forming a call chain
|
|
126
|
+
* that grew one layer deeper per step. Using a sentinel (_agentkit_original_urlopen)
|
|
127
|
+
* ensures the true original is only captured once, no matter how many times the
|
|
128
|
+
* data variables (_allowed_hosts) are updated.
|
|
129
|
+
*/
|
|
130
|
+
#installCapabilityInfrastructure(py) {
|
|
131
|
+
py.runPython(`
|
|
132
|
+
import urllib.request as _urllib_req, urllib.parse as _urllib_parse
|
|
133
|
+
|
|
134
|
+
# Q9: capture the true original once using a sentinel — prevents nesting if called again.
|
|
135
|
+
if not hasattr(_urllib_req, "_agentkit_original_urlopen"):
|
|
136
|
+
_urllib_req._agentkit_original_urlopen = _urllib_req.urlopen
|
|
137
|
+
|
|
138
|
+
_original_urlopen = _urllib_req._agentkit_original_urlopen
|
|
139
|
+
|
|
140
|
+
# Seed data variables with deny-all defaults; updated per-call by #applyCapabilities.
|
|
141
|
+
_allowed_hosts = []
|
|
142
|
+
__allowed_read_paths__ = []
|
|
143
|
+
__allowed_write_paths__ = []
|
|
144
|
+
__extra_capabilities__ = []
|
|
145
|
+
|
|
146
|
+
def _checked_urlopen(url, *args, **kwargs):
|
|
147
|
+
raw = url.full_url if isinstance(url, _urllib_req.Request) else str(url)
|
|
148
|
+
hostname = _urllib_parse.urlparse(raw).hostname or ""
|
|
149
|
+
if not _allowed_hosts:
|
|
150
|
+
raise PermissionError(
|
|
151
|
+
f"CapabilityDenied: network access to '{hostname}' is denied "
|
|
152
|
+
f"(allowedHosts is empty)"
|
|
153
|
+
)
|
|
154
|
+
def _matches(host, pattern):
|
|
155
|
+
if pattern.startswith("*."):
|
|
156
|
+
return host.endswith(pattern[1:]) or host == pattern[2:]
|
|
157
|
+
return host == pattern
|
|
158
|
+
if not any(_matches(hostname, h) for h in _allowed_hosts):
|
|
159
|
+
raise PermissionError(
|
|
160
|
+
f"CapabilityDenied: '{hostname}' is not in allowedHosts {_allowed_hosts}"
|
|
161
|
+
)
|
|
162
|
+
return _original_urlopen(url, *args, **kwargs)
|
|
163
|
+
|
|
164
|
+
_urllib_req.urlopen = _checked_urlopen
|
|
165
|
+
|
|
166
|
+
# Advisory path-check helpers (FS already sandboxed by Emscripten MEMFS).
|
|
167
|
+
def __check_host__(host):
|
|
168
|
+
if not _allowed_hosts:
|
|
169
|
+
raise PermissionError(f"CapabilityDenied: network to '{host}' denied")
|
|
170
|
+
if not any((lambda p: host == p or host.endswith('.' + p.lstrip('*').lstrip('.')))(h) for h in _allowed_hosts):
|
|
171
|
+
raise PermissionError(f"CapabilityDenied: '{host}' not in allowedHosts")
|
|
172
|
+
|
|
173
|
+
def __check_read_path__(path):
|
|
174
|
+
if not __allowed_read_paths__:
|
|
175
|
+
raise PermissionError(f"CapabilityDenied: read '{path}' denied (no paths allowed)")
|
|
176
|
+
if not any(path.startswith(p) for p in __allowed_read_paths__):
|
|
177
|
+
raise PermissionError(f"CapabilityDenied: read '{path}' not in allowedReadPaths")
|
|
178
|
+
|
|
179
|
+
def __check_write_path__(path):
|
|
180
|
+
if not __allowed_write_paths__:
|
|
181
|
+
raise PermissionError(f"CapabilityDenied: write '{path}' denied (no paths allowed)")
|
|
182
|
+
if not any(path.startswith(p) for p in __allowed_write_paths__):
|
|
183
|
+
raise PermissionError(f"CapabilityDenied: write '{path}' not in allowedWritePaths")
|
|
184
|
+
|
|
185
|
+
del _urllib_parse
|
|
186
|
+
`);
|
|
187
|
+
}
|
|
188
|
+
async reset() {
|
|
189
|
+
if (!this.#py)
|
|
190
|
+
return;
|
|
191
|
+
// Clear all user-defined globals and re-seed both sentinel spellings.
|
|
192
|
+
this.#py.runPython(`
|
|
193
|
+
import sys
|
|
194
|
+
# Remove all user-defined names, keep builtins.
|
|
195
|
+
for _k in list(globals().keys()):
|
|
196
|
+
if not _k.startswith('__'):
|
|
197
|
+
del globals()[_k]
|
|
198
|
+
__final_answer__ = None
|
|
199
|
+
__finalAnswer__ = None
|
|
200
|
+
`);
|
|
201
|
+
this.#logs = [];
|
|
202
|
+
}
|
|
203
|
+
async snapshot() {
|
|
204
|
+
const py = await this.#ensurePyodide();
|
|
205
|
+
// Serialise all serialisable globals to JSON.
|
|
206
|
+
// Non-serialisable values (functions, modules) are skipped.
|
|
207
|
+
const state = py.runPython(`
|
|
208
|
+
import json
|
|
209
|
+
_snap = {}
|
|
210
|
+
for _k, _v in list(globals().items()):
|
|
211
|
+
if _k.startswith('_') and _k != '__final_answer__':
|
|
212
|
+
continue
|
|
213
|
+
try:
|
|
214
|
+
json.dumps(_v)
|
|
215
|
+
_snap[_k] = _v
|
|
216
|
+
except Exception:
|
|
217
|
+
pass
|
|
218
|
+
json.dumps(_snap)
|
|
219
|
+
`);
|
|
220
|
+
return new TextEncoder().encode(state);
|
|
221
|
+
}
|
|
222
|
+
async restore(snapshot) {
|
|
223
|
+
const py = await this.#ensurePyodide();
|
|
224
|
+
const obj = JSON.parse(new TextDecoder().decode(snapshot));
|
|
225
|
+
py.globals.set("_snap", py.toPy(obj));
|
|
226
|
+
py.runPython(`globals().update(_snap); del _snap`);
|
|
227
|
+
this.#logs = [];
|
|
228
|
+
}
|
|
229
|
+
async [Symbol.asyncDispose]() {
|
|
230
|
+
await this.reset();
|
|
231
|
+
this.#py = null;
|
|
232
|
+
this.#initPromise = null;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
//# sourceMappingURL=PyodideKernel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PyodideKernel.js","sourceRoot":"","sources":["../src/PyodideKernel.ts"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;GAcG;AACH,MAAM,OAAO,aAAa;IACxB,GAAG,GAA4B,IAAI,CAAC;IACpC,KAAK,GAAa,EAAE,CAAC;IACrB,YAAY,GAAqC,IAAI,CAAC;IAEtD,KAAK,CAAC,cAAc;QAClB,IAAI,IAAI,CAAC,GAAG;YAAE,OAAO,IAAI,CAAC,GAAG,CAAC;QAC9B,IAAI,IAAI,CAAC,YAAY;YAAE,OAAO,IAAI,CAAC,YAAY,CAAC;QAEhD,IAAI,CAAC,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YAC9B,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC;YAChD,wEAAwE;YACxE,4EAA4E;YAC5E,0EAA0E;YAC1E,8DAA8D;YAC9D,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC;YACtD,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC;YAC9C,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAClD,MAAM,WAAW,GAAG,UAAU,CAAC,OAAO,CAAC,sBAAsB,CAAC,CAAC;YAC/D,MAAM,QAAQ,GAAG,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC;YAE5C,MAAM,EAAE,GAAG,CAAC,MAAM,WAAW,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAgC,CAAC;YAC5E,sFAAsF;YACtF,EAAE,CAAC,SA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,GAAG,CAAC,CAAC,CAAC;QACtC,EAAE,CAAC,SAAS,CAAC,oCAAoC,CAAC,CAAC;QACnD,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC;QACzB,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;QACnB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC;QAChB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;IAC3B,CAAC;CACF"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@agentkit-js/kernel-pyodide",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "PyodideKernel — CPython-in-WASM kernel for agentkit-js",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "tsc -p tsconfig.json",
|
|
16
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
17
|
+
"test": "vitest run",
|
|
18
|
+
"clean": "rm -rf dist .turbo"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@agentkit-js/core": "workspace:*"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"pyodide": ">=0.26.0"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"pyodide": "0.29.4",
|
|
28
|
+
"typescript": "^5.7.0",
|
|
29
|
+
"vitest": "^2.1.0"
|
|
30
|
+
},
|
|
31
|
+
"license": "Apache-2.0",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/telleroutlook/agentkit-js.git",
|
|
35
|
+
"directory": "packages/kernel-pyodide"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://github.com/telleroutlook/agentkit-js/tree/main/packages/kernel-pyodide#readme",
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/telleroutlook/agentkit-js/issues"
|
|
40
|
+
},
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=20.0.0"
|
|
43
|
+
},
|
|
44
|
+
"keywords": [
|
|
45
|
+
"agentkit",
|
|
46
|
+
"agent",
|
|
47
|
+
"ai",
|
|
48
|
+
"llm"
|
|
49
|
+
],
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
},
|
|
53
|
+
"files": [
|
|
54
|
+
"dist",
|
|
55
|
+
"LICENSE",
|
|
56
|
+
"README.md"
|
|
57
|
+
],
|
|
58
|
+
"author": "agentkit-js contributors"
|
|
59
|
+
}
|