Skip to content

Commit e0162ab

Browse files
.NET: Canonicalize Hyperlight sandbox fingerprints (#8295)
Co-authored-by: Copilot App <[email protected]> Copilot-Session: b9da797e-a9ff-492f-b5c1-8e9c7af1d8dc
1 parent 119c795 commit e0162ab

5 files changed

Lines changed: 453 additions & 50 deletions

File tree

‎dotnet/src/Microsoft.Agents.AI.Hyperlight/HyperlightCodeActProvider.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ public sealed class HyperlightCodeActProvider : AIContextProvider, IDisposable
7575
public HyperlightCodeActProvider(HyperlightCodeActProviderOptions? options = null)
7676
{
7777
this._options = options ?? new HyperlightCodeActProviderOptions();
78-
this._executor = new SandboxExecutor(this._options);
78+
this._executor = new SandboxExecutor();
7979

8080
if (this._options.Tools is not null)
8181
{
@@ -280,7 +280,7 @@ protected override ValueTask<AIContext> ProvideAIContextAsync(InvokingContext co
280280
this._tools.Values.ToList(),
281281
this._fileMounts.Values.ToList(),
282282
this._allowedDomains.Values.ToList(),
283-
this._options.HostInputDirectory,
283+
this._options,
284284
this._toolRegistryVersion);
285285
}
286286

‎dotnet/src/Microsoft.Agents.AI.Hyperlight/HyperlightExecuteCodeFunction.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ public sealed class HyperlightExecuteCodeFunction : AIFunction, IDisposable
6565
public HyperlightExecuteCodeFunction(HyperlightCodeActProviderOptions? options = null)
6666
{
6767
var effective = options ?? new HyperlightCodeActProviderOptions();
68-
this._executor = new SandboxExecutor(effective);
68+
this._executor = new SandboxExecutor();
6969

7070
var tools = (effective.Tools?.Where(t => t is not null) ?? []).ToList();
7171
var fileMounts = (effective.FileMounts?.Where(m => m is not null) ?? []).ToList();
@@ -75,7 +75,7 @@ public HyperlightExecuteCodeFunction(HyperlightCodeActProviderOptions? options =
7575
tools,
7676
fileMounts,
7777
allowedDomains,
78-
effective.HostInputDirectory,
78+
effective,
7979
toolRegistryVersion: Guid.Empty);
8080

8181
this._description = InstructionBuilder.BuildExecuteCodeDescription(

‎dotnet/src/Microsoft.Agents.AI.Hyperlight/Internal/SandboxExecutor.cs‎

Lines changed: 137 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
// Copyright (c) Microsoft. All rights reserved.
22

33
using System;
4+
using System.Buffers;
45
using System.Collections.Generic;
5-
using System.Globalization;
66
using System.Linq;
7-
using System.Text;
7+
using System.Security.Cryptography;
88
using System.Text.Json;
99
using System.Threading;
1010
using System.Threading.Tasks;
@@ -21,19 +21,13 @@ namespace Microsoft.Agents.AI.Hyperlight.Internal;
2121
/// </summary>
2222
internal sealed class SandboxExecutor : IDisposable
2323
{
24-
private readonly HyperlightCodeActProviderOptions _options;
2524
private readonly SemaphoreSlim _executionLock = new(1, 1);
2625

2726
private Sandbox? _sandbox;
2827
private SandboxSnapshot? _warmSnapshot;
2928
private string? _lastConfigFingerprint;
3029
private bool _disposed;
3130

32-
public SandboxExecutor(HyperlightCodeActProviderOptions options)
33-
{
34-
this._options = options;
35-
}
36-
3731
/// <summary>
3832
/// Immutable snapshot of provider state at the start of a run.
3933
/// Used to build a run-scoped <c>execute_code</c> function that is
@@ -45,20 +39,30 @@ public RunSnapshot(
4539
IReadOnlyList<AIFunction> tools,
4640
IReadOnlyList<FileMount> fileMounts,
4741
IReadOnlyList<AllowedDomain> allowedDomains,
48-
string? hostInputDirectory,
42+
HyperlightCodeActProviderOptions options,
4943
Guid toolRegistryVersion = default)
5044
{
51-
this.Tools = tools;
52-
this.FileMounts = fileMounts;
53-
this.AllowedDomains = allowedDomains;
54-
this.HostInputDirectory = hostInputDirectory;
45+
this.Tools = tools.ToList();
46+
this.FileMounts = fileMounts.ToList();
47+
this.AllowedDomains = allowedDomains
48+
.Select(domain => new AllowedDomain(domain.Target, domain.Methods?.ToArray()))
49+
.ToList();
50+
this.Backend = options.Backend;
51+
this.ModulePath = options.ModulePath;
52+
this.HeapSize = options.HeapSize;
53+
this.StackSize = options.StackSize;
54+
this.HostInputDirectory = options.HostInputDirectory;
5555
this.ToolRegistryVersion = toolRegistryVersion;
5656
this.ConfigFingerprint = ComputeFingerprint(
57-
tools,
58-
fileMounts,
59-
allowedDomains,
60-
hostInputDirectory,
61-
toolRegistryVersion);
57+
this.Tools,
58+
this.FileMounts,
59+
this.AllowedDomains,
60+
this.HostInputDirectory,
61+
toolRegistryVersion,
62+
this.Backend,
63+
this.ModulePath,
64+
this.HeapSize,
65+
this.StackSize);
6266
}
6367

6468
public IReadOnlyList<AIFunction> Tools { get; }
@@ -67,6 +71,14 @@ public RunSnapshot(
6771

6872
public IReadOnlyList<AllowedDomain> AllowedDomains { get; }
6973

74+
public SandboxBackend Backend { get; }
75+
76+
public string? ModulePath { get; }
77+
78+
public string? HeapSize { get; }
79+
80+
public string? StackSize { get; }
81+
7082
public string? HostInputDirectory { get; }
7183

7284
public Guid ToolRegistryVersion { get; }
@@ -75,7 +87,7 @@ public RunSnapshot(
7587
/// Stable fingerprint of the configuration that materially affects how
7688
/// the sandbox must be built. Used by <see cref="SandboxExecutor"/> to
7789
/// decide whether a previously-built sandbox can be reused or must be
78-
/// rebuilt because tools / mounts / allow-list entries have changed.
90+
/// rebuilt because its capabilities or runtime options have changed.
7991
/// </summary>
8092
public string ConfigFingerprint { get; }
8193

@@ -84,35 +96,114 @@ internal static string ComputeFingerprint(
8496
IReadOnlyList<FileMount> fileMounts,
8597
IReadOnlyList<AllowedDomain> allowedDomains,
8698
string? hostInputDirectory,
87-
Guid toolRegistryVersion = default)
99+
Guid toolRegistryVersion = default,
100+
SandboxBackend backend = SandboxBackend.JavaScript,
101+
string? modulePath = null,
102+
string? heapSize = null,
103+
string? stackSize = null)
88104
{
89-
var sb = new StringBuilder();
90-
sb.Append("tools=");
91-
foreach (var name in tools.Select(t => t.Name).OrderBy(n => n, StringComparer.Ordinal))
105+
var buffer = new ArrayBufferWriter<byte>();
106+
using (var writer = new Utf8JsonWriter(buffer))
92107
{
93-
sb.Append(name).Append('|');
108+
writer.WriteStartObject();
109+
writer.WriteNumber("backend", (int)backend);
110+
writer.WriteString("modulePath", modulePath);
111+
writer.WriteString("heapSize", heapSize);
112+
writer.WriteString("stackSize", stackSize);
113+
writer.WriteString("hostInputDirectory", hostInputDirectory);
114+
writer.WriteString("toolRegistryVersion", toolRegistryVersion);
115+
116+
writer.WritePropertyName("tools");
117+
writer.WriteStartArray();
118+
foreach (var name in tools.Select(tool => tool.Name).OrderBy(name => name, StringComparer.Ordinal))
119+
{
120+
writer.WriteStringValue(name);
121+
}
122+
123+
writer.WriteEndArray();
124+
125+
writer.WritePropertyName("fileMounts");
126+
writer.WriteStartArray();
127+
foreach (var mount in fileMounts
128+
.OrderBy(mount => mount.MountPath, StringComparer.Ordinal)
129+
.ThenBy(mount => mount.HostPath, StringComparer.Ordinal))
130+
{
131+
writer.WriteStartObject();
132+
writer.WriteString("mountPath", mount.MountPath);
133+
writer.WriteString("hostPath", mount.HostPath);
134+
writer.WriteEndObject();
135+
}
136+
137+
writer.WriteEndArray();
138+
139+
var domains = allowedDomains
140+
.Select(domain => (
141+
domain.Target,
142+
Methods: domain.Methods?.OrderBy(method => method, StringComparer.Ordinal).ToArray()))
143+
.ToList();
144+
domains.Sort(static (left, right) =>
145+
{
146+
var targetComparison = StringComparer.Ordinal.Compare(left.Target, right.Target);
147+
return targetComparison != 0
148+
? targetComparison
149+
: CompareStringArrays(left.Methods, right.Methods);
150+
});
151+
152+
writer.WritePropertyName("allowedDomains");
153+
writer.WriteStartArray();
154+
foreach (var domain in domains)
155+
{
156+
writer.WriteStartObject();
157+
writer.WriteString("target", domain.Target);
158+
writer.WritePropertyName("methods");
159+
if (domain.Methods is null)
160+
{
161+
writer.WriteNullValue();
162+
}
163+
else
164+
{
165+
writer.WriteStartArray();
166+
foreach (var method in domain.Methods)
167+
{
168+
writer.WriteStringValue(method);
169+
}
170+
171+
writer.WriteEndArray();
172+
}
173+
174+
writer.WriteEndObject();
175+
}
176+
177+
writer.WriteEndArray();
178+
writer.WriteEndObject();
94179
}
95180

96-
sb.Append(";toolVersion=").Append(toolRegistryVersion.ToString("D", CultureInfo.InvariantCulture));
181+
return Convert.ToHexString(SHA256.HashData(buffer.WrittenSpan));
182+
}
183+
184+
private static int CompareStringArrays(string[]? left, string[]? right)
185+
{
186+
if (left is null)
187+
{
188+
return right is null ? 0 : -1;
189+
}
97190

98-
sb.Append(";mounts=");
99-
foreach (var m in fileMounts
100-
.Select(m => m.MountPath + "->" + m.HostPath)
101-
.OrderBy(s => s, StringComparer.Ordinal))
191+
if (right is null)
102192
{
103-
sb.Append(m).Append('|');
193+
return 1;
104194
}
105195

106-
sb.Append(";allow=");
107-
foreach (var d in allowedDomains
108-
.Select(d => d.Target + "/" + (d.Methods is null ? "*" : string.Join(",", d.Methods)))
109-
.OrderBy(s => s, StringComparer.Ordinal))
196+
var sharedLength = Math.Min(left.Length, right.Length);
197+
for (var index = 0; index < sharedLength; index++)
110198
{
111-
sb.Append(d).Append('|');
199+
var comparison = StringComparer.Ordinal.Compare(left[index], right[index]);
200+
if (comparison != 0)
201+
{
202+
return comparison;
203+
}
112204
}
113205

114-
sb.Append(";input=").Append(hostInputDirectory ?? string.Empty);
115-
return sb.ToString();
206+
return left.Length.CompareTo(right.Length);
116207
}
117208
}
118209

@@ -162,7 +253,7 @@ private void EnsureInitialized(RunSnapshot snapshot)
162253
}
163254

164255
// Configuration changed (or first run) — dispose the previous sandbox
165-
// so the new one picks up the new tool/mount/allow-list set.
256+
// so the new one picks up the current capabilities and runtime options.
166257
this._warmSnapshot?.Dispose();
167258
this._sandbox?.Dispose();
168259
this._warmSnapshot = null;
@@ -174,21 +265,21 @@ private void EnsureInitialized(RunSnapshot snapshot)
174265
private void BuildAndWarmUp(RunSnapshot snapshot)
175266
{
176267
var builder = new SandboxBuilder()
177-
.WithBackend(this._options.Backend);
268+
.WithBackend(snapshot.Backend);
178269

179-
if (!string.IsNullOrEmpty(this._options.ModulePath))
270+
if (!string.IsNullOrEmpty(snapshot.ModulePath))
180271
{
181-
builder = builder.WithModulePath(this._options.ModulePath!);
272+
builder = builder.WithModulePath(snapshot.ModulePath!);
182273
}
183274

184-
if (!string.IsNullOrEmpty(this._options.HeapSize))
275+
if (!string.IsNullOrEmpty(snapshot.HeapSize))
185276
{
186-
builder = builder.WithHeapSize(this._options.HeapSize!);
277+
builder = builder.WithHeapSize(snapshot.HeapSize!);
187278
}
188279

189-
if (!string.IsNullOrEmpty(this._options.StackSize))
280+
if (!string.IsNullOrEmpty(snapshot.StackSize))
190281
{
191-
builder = builder.WithStackSize(this._options.StackSize!);
282+
builder = builder.WithStackSize(snapshot.StackSize!);
192283
}
193284

194285
var hostInput = snapshot.HostInputDirectory;
@@ -221,7 +312,7 @@ private void BuildAndWarmUp(RunSnapshot snapshot)
221312
// Backend-specific no-op used to trigger lazy guest runtime initialization
222313
// before the warm snapshot is captured. Matches the values used by the
223314
// upstream HyperlightSandbox.Extensions.AI CodeExecutionTool reference.
224-
_ = sandbox.Run(this._options.Backend == SandboxBackend.JavaScript ? "void 0;" : "None");
315+
_ = sandbox.Run(snapshot.Backend == SandboxBackend.JavaScript ? "void 0;" : "None");
225316
this._warmSnapshot = sandbox.Snapshot();
226317
this._sandbox = sandbox;
227318
this._lastConfigFingerprint = snapshot.ConfigFingerprint;

0 commit comments

Comments
 (0)