diff --git a/docs/modules/pkl-core/pages/index.adoc b/docs/modules/pkl-core/pages/index.adoc
index 1d09e4f82f..0ce9dd7e7d 100644
--- a/docs/modules/pkl-core/pages/index.adoc
+++ b/docs/modules/pkl-core/pages/index.adoc
@@ -131,3 +131,174 @@ Module loaders can be configured and customized using {uri-pkl-core-ModuleKeyFac
== Further Information
Refer to the Javadoc and sources published with the library, or browse the library's {uri-pkl-core-main-sources}[main] and {uri-pkl-core-test-sources}[test] sources.
+
+== Experimental polyglot object and function access
+
+Pkl can be evaluated in a GraalVM polyglot context alongside other Truffle languages.
+The result is a read-only view of the Pkl module, with lazy access to its properties.
+For example, with compatible Pkl and GraalJS dependencies on the classpath:
+
+[source,java]
+----
+try (var context = org.graalvm.polyglot.Context.newBuilder("js", "pkl")
+ .allowPolyglotAccess(org.graalvm.polyglot.PolyglotAccess.ALL)
+ .build()) {
+ var result = context.eval("js", """
+ const config = Polyglot.eval('pkl', `
+ name = "birds"
+ ports = List(8080, 8081)
+ `);
+ config.name + ':' + config.ports[0];
+ """);
+ System.out.println(result.asString()); // birds:8080
+}
+----
+
+A Java host can also call `context.eval("pkl", source)` and use the returned
+`org.graalvm.polyglot.Value` directly.
+JavaScript uses GraalJS here; this does not add Pkl support to arbitrary Node.js or browser runtimes.
+
+[cols="1,2"]
+|===
+|Pkl value |Interop representation
+
+|Boolean, String, Int, Float
+|Native interop primitives. Int remains a signed 64-bit integer; a consuming language's numeric conversion rules still apply.
+
+|Null
+|Interop null.
+
+|Module, Typed, Dynamic
+|Readable public properties. Local and hidden properties are excluded, including from direct lookup.
+
+|List, Listing, Bytes
+|Read-only arrays and iterables. Bytes expose unsigned integer elements.
+
+|Map, Mapping
+|Read-only hash entries and entry iterators. Keys retain their types rather than being converted to strings.
+
+|Dynamic elements and entries
+|Array (when elements are present) and hash protocols, respectively, in addition to named properties.
+
+|Set
+|An iterable in Pkl iteration order.
+
+|Pair
+|Readable `first` and `second` properties.
+
+|Duration, DataSize
+|Readable `value` and `unit` properties, preserving the original unit.
+
+|Function-valued properties
+|Executable closures. Arguments may be primitives or Pkl values belonging to the same context.
+
+|Other Pkl values
+|Opaque Pkl values. Named Pkl method declarations and class instantiation are not yet exposed.
+|===
+
+Numeric hash-key lookup first tries the supplied numeric type. If no key matches, it tries the
+other Pkl numeric type only when conversion is lossless. This accommodates languages such as
+JavaScript whose numeric representations do not distinguish Pkl Int and Float reliably.
+
+Member enumeration does not evaluate property values.
+Reading a property or element performs normal Pkl evaluation and type checking, and caches the result
+according to Pkl's existing rules. Errors in unread properties remain deferred.
+Object identity is preserved across repeated reads, including cyclic references; values are not
+recursively copied or serialized. Debugger display strings do not force lazy values.
+All views and iterators belong to their originating context and must be used before it is closed.
+
+The standalone polyglot entry point accepts supplied source text and standard-library imports.
+It does not configure filesystem, network, package, environment, or external-property readers,
+even when the host grants the polyglot context I/O access.
+The existing `Evaluator` API retains its own configuration and behavior.
+Each evaluation creates a new root module; source caching does not share root module values.
+
+=== Calling Pkl functions
+
+Function-valued properties can be read and executed, or invoked directly from a guest language.
+For example, JavaScript in the context above can use:
+
+[source,javascript]
+----
+const functions = Polyglot.eval('pkl', `
+ greeting = (name: String) -> "Hello, " + name
+ describe = (data: Dynamic) -> data.name + ":" + data.port.toString()
+`);
+functions.greeting('Sam'); // "Hello, Sam"
+----
+
+A Java host uses `module.getMember("greeting").execute("Sam")`.
+Calls use Pkl's normal call targets, preserving parameter constraints and declared return checks.
+Arity errors and unsupported argument types are reported through the interop protocol;
+Pkl evaluation errors retain their formatted diagnostics.
+Returned objects remain lazy, read-only Pkl views.
+Function-type annotations have the same semantics as within Pkl; interop does not strengthen them.
+
+Foreign objects and callbacks are rejected as direct arguments. Pkl objects and closures can be
+passed back to functions in their owning context, but cannot be passed directly to a function in
+a different context, even when both contexts share an engine.
+
+Capability queries do not evaluate properties. An unread property advertises deferred invocation
+because its value might be a function. Calling it evaluates the property and reports a type error
+if the value is not callable. Once the value is cached, invocation capability reflects its type.
+This preserves lazy evaluation while allowing ordinary JavaScript method-call syntax.
+
+=== Explicit snapshots of foreign data
+
+Use `PolyglotContext.snapshot(context, foreignValue)` from Java to copy foreign data into
+immutable Pkl values. The operation is also available as
+`context.getBindings("pkl").getMember("snapshot")`.
+To expose it to JavaScript, bind the Pkl scope once:
+
+[source,java]
+----
+context.getBindings("js").putMember("Pkl", context.getBindings("pkl"));
+----
+
+[source,javascript]
+----
+const source = {name: 'api', port: 8080};
+const saved = Pkl.snapshot(source);
+source.port = 9999;
+functions.describe(saved); // "api:8080"
+----
+
+Snapshots use the following mappings, in this order:
+
+* Null-like values, booleans, strings, and losslessly representable numbers become Pkl primitives.
+ Numbers fitting Int are represented as Int; other exactly representable numbers become Float.
+ GraalJS `undefined`, including readable sparse-array holes, becomes Pkl `null`.
+* Arrays become List; additional named properties are not copied.
+* Hash entries become Map, preserving key types and rejecting keys that collapse to the same Pkl key.
+* Other iterables, including foreign sets, become List in iteration order.
+* Objects with readable members become Dynamic using the enumerated member names.
+
+Repeated references within a snapshot preserve identity. Cycles are rejected with a path to the
+cycle, as are foreign functions, constructors, known side-effecting accessors, unreadable values,
+and numbers that cannot be represented without loss. Collection sizes and visited values are
+limited to 100,000, and nesting depth to 256. A failed snapshot publishes no partial graph and does
+not affect subsequent copies. Pkl values already belonging to the target context are reused
+without forcing or copying.
+
+The source must remain stable while copying: a snapshot is not an atomic transaction over
+concurrent mutations. Foreign iteration and proxy operations can execute guest code during the
+explicit copy. After a successful copy, foreign mutation cannot change the captured data, and no
+foreign object or callback is retained in that data.
+
+=== Independent engines and lifecycle
+
+Ordinary `Context.newBuilder(...)` and caller-supplied `Engine` instances are supported.
+`PolyglotContext.newBuilder(...)` is a convenience alias for the ordinary builder.
+Each Truffle language instance owns its standard-library modules, built-in classes, and factory
+call targets. Contexts on compatible sharing layers of one engine reuse that state; independent
+engines do not retain each other's executable nodes or prototypes.
+
+Contexts on different engines may use different host-access policies. Contexts sharing an engine
+must still obey GraalVM's engine-sharing requirements. Closing one engine does not invalidate
+values in another. A value, function, snapshot, or iterator must be used before its own context
+is closed.
+
+The existing `Evaluator` API continues to use its internal shared engine. Standard-library
+bootstrap uses fixed inputs and isolated type-checking state, without capturing the embedding
+context's environment or external properties. Foreign mutation remains outside Pkl evaluation;
+there is no implicit live import of objects or callbacks.
diff --git a/pkl-core/pkl-core.gradle.kts b/pkl-core/pkl-core.gradle.kts
index b9784263f9..62a8c62c66 100644
--- a/pkl-core/pkl-core.gradle.kts
+++ b/pkl-core/pkl-core.gradle.kts
@@ -64,7 +64,7 @@ dependencies {
implementation(projects.pklFormatter)
implementation(libs.msgpack)
implementation(libs.truffleApi)
- implementation(libs.graalSdk)
+ api(libs.graalSdk)
implementation(libs.paguro) { exclude(group = "org.jetbrains", module = "annotations") }
@@ -72,6 +72,7 @@ dependencies {
testImplementation(projects.pklCommonsTest)
testImplementation(libs.wiremock)
+ testRuntimeOnly(libs.graalJs)
add("generatorImplementation", libs.javaPoet)
add("generatorImplementation", libs.truffleApi)
diff --git a/pkl-core/src/main/java/org/pkl/core/PolyglotContext.java b/pkl-core/src/main/java/org/pkl/core/PolyglotContext.java
new file mode 100644
index 0000000000..18820ac0a1
--- /dev/null
+++ b/pkl-core/src/main/java/org/pkl/core/PolyglotContext.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.pkl.core;
+
+import org.graalvm.polyglot.Context;
+import org.graalvm.polyglot.Value;
+
+/** Convenience entry point for independent polyglot contexts supporting Pkl. */
+public final class PolyglotContext {
+ private PolyglotContext() {}
+
+ /**
+ * Returns a standard polyglot context builder. Callers may supply their own engine and host
+ * access policy. An empty language list permits all installed languages. Cross-language
+ * evaluation additionally requires the builder's polyglot-access permission.
+ */
+ public static Context.Builder newBuilder(String... permittedLanguages) {
+ return Context.newBuilder(permittedLanguages);
+ }
+
+ /**
+ * Explicitly copies foreign data into immutable Pkl values owned by {@code context}. Objects
+ * become Dynamic, arrays/iterables become List, and hash entries become Map. Repeated references
+ * are preserved; cycles, foreign functions, known side-effecting accessors, lossy numbers, and
+ * graphs exceeding the snapshot limits are rejected.
+ *
+ *
The source must remain stable while copying. This is not an atomic transaction over a
+ * concurrently changing guest object. No foreign object is retained by a successful snapshot. Pkl
+ * values already belonging to the target context are returned without forcing or copying.
+ */
+ public static Value snapshot(Context context, Object value) {
+ return context.getBindings("pkl").getMember("snapshot").execute(value);
+ }
+}
diff --git a/pkl-core/src/main/java/org/pkl/core/runtime/VmContext.java b/pkl-core/src/main/java/org/pkl/core/runtime/VmContext.java
index d0824f41f3..64f901b4f7 100644
--- a/pkl-core/src/main/java/org/pkl/core/runtime/VmContext.java
+++ b/pkl-core/src/main/java/org/pkl/core/runtime/VmContext.java
@@ -19,12 +19,14 @@
import com.oracle.truffle.api.TruffleLanguage.Env;
import com.oracle.truffle.api.instrumentation.Instrumenter;
import com.oracle.truffle.api.nodes.Node;
+import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
+import java.util.regex.Pattern;
import org.jspecify.annotations.Nullable;
import org.pkl.core.Logger;
import org.pkl.core.Loggers;
@@ -43,8 +45,11 @@ public final class VmContext {
private static final ContextReference REFERENCE =
ContextReference.create(VmLanguage.class);
private final VmValueTrackerFactory valueTrackerFactory;
+ private final Env env;
+ final VmPolyglotScope polyglotScope = new VmPolyglotScope(this);
public VmContext(VmLanguage vmLanguage, Env env) {
+ this.env = env;
this.valueTrackerFactory =
new VmValueTrackerFactory(env.lookup(Instrumenter.class), vmLanguage);
}
@@ -119,6 +124,32 @@ public void initialize(Holder holder) {
this.holder = holder;
}
+ /** Initializes standalone polyglot evaluation without ambient I/O capabilities. */
+ void initializeForPolyglot() {
+ // The embedding Evaluator supplies its own holder before evaluating any source.
+ //noinspection ConstantValue
+ if (holder != null) return;
+ var securityManager =
+ SecurityManagers.standard(
+ List.of(Pattern.compile(".*")), List.of(), SecurityManagers.defaultTrustLevels, null);
+ initialize(
+ new Holder(
+ StackFrameTransformers.empty,
+ securityManager,
+ HttpClient.dummyClient(),
+ new ModuleResolver(List.of(ModuleKeyFactories.standardLibrary)),
+ new ResourceManager(securityManager, List.of()),
+ Loggers.writer(new PrintWriter(env.err(), true)),
+ Map.of(),
+ Map.of(),
+ null,
+ null,
+ null,
+ null,
+ TraceMode.COMPACT,
+ false));
+ }
+
private Holder getHolder() {
return Objects.requireNonNull(holder, "Pkl context is not initialized");
}
diff --git a/pkl-core/src/main/java/org/pkl/core/runtime/VmForeignSnapshot.java b/pkl-core/src/main/java/org/pkl/core/runtime/VmForeignSnapshot.java
new file mode 100644
index 0000000000..5f6ed3aee5
--- /dev/null
+++ b/pkl-core/src/main/java/org/pkl/core/runtime/VmForeignSnapshot.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.pkl.core.runtime;
+
+import com.oracle.truffle.api.interop.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import org.jspecify.annotations.Nullable;
+
+/** One explicit, bounded copy operation. No foreign objects survive in the resulting graph. */
+final class VmForeignSnapshot {
+ private static final int MAX_DEPTH = 256;
+ private static final int MAX_VALUES = 100_000;
+ private final VmContext owner;
+ private final InteropLibrary interop = InteropLibrary.getUncached();
+ private final Map> seen = new HashMap<>();
+ private int values;
+
+ VmForeignSnapshot(VmContext owner) {
+ this.owner = owner;
+ }
+
+ static @Nullable Object primitive(Object value) {
+ var interop = InteropLibrary.getUncached();
+ try {
+ if (interop.isNull(value)) return VmNull.withoutDefault();
+ if (interop.isBoolean(value)) return interop.asBoolean(value);
+ if (interop.isString(value)) return interop.asString(value);
+ if (interop.fitsInLong(value)) return interop.asLong(value);
+ if (interop.fitsInDouble(value)) return interop.asDouble(value);
+ } catch (UnsupportedMessageException e) {
+ return null;
+ }
+ return null;
+ }
+
+ Object copy(Object value) throws UnsupportedTypeException {
+ return copy(value, "$", 0);
+ }
+
+ private Object copy(Object value, String path, int depth) throws UnsupportedTypeException {
+ if (++values > MAX_VALUES || depth > MAX_DEPTH) {
+ throw error(value, path, "Snapshot exceeds the depth (256) or value-count (100000) limit.");
+ }
+ if (value instanceof VmPolyglotValue wrapper) {
+ if (wrapper.owner != owner) throw error(value, path, "Pkl values belong to another context.");
+ return wrapper.value;
+ }
+ var primitive = primitive(value);
+ if (primitive != null) return primitive;
+ if (interop.isNumber(value))
+ throw error(value, path, "Number cannot be represented losslessly by Pkl Int or Float.");
+ if (interop.isExecutable(value) || interop.isInstantiable(value)) {
+ throw error(value, path, "Functions and constructors cannot be snapshotted.");
+ }
+ try {
+ int hash =
+ interop.hasIdentity(value)
+ ? interop.identityHashCode(value)
+ : System.identityHashCode(value);
+ var bucket = seen.computeIfAbsent(hash, ignored -> new ArrayList<>());
+ for (var memo : bucket) {
+ if (value == memo.original || interop.isIdentical(value, memo.original, interop)) {
+ if (memo.result == null) throw error(value, path, "Cycle refers to " + memo.path + ".");
+ return memo.result;
+ }
+ }
+ var memo = new Memo(value, path);
+ bucket.add(memo);
+ Object result;
+ if (interop.hasArrayElements(value)) {
+ long size = interop.getArraySize(value);
+ checkSize(value, path, size);
+ var elements = new Object[(int) size];
+ for (int i = 0; i < size; i++) {
+ if (!interop.isArrayElementReadable(value, i))
+ throw error(value, path + "[" + i + "]", "Sparse or unreadable array element.");
+ elements[i] = copy(interop.readArrayElement(value, i), path + "[" + i + "]", depth + 1);
+ }
+ result = VmList.create(elements);
+ } else if (interop.hasHashEntries(value)) {
+ checkSize(value, path, interop.getHashSize(value));
+ var entries = interop.getHashEntriesIterator(value);
+ var builder = VmMap.builder();
+ var keys = new HashSet