Open History to see the last commit
1/**
2 * Compound sandbox identity. We never key a resumable sandbox on `threadId`
3 * alone — that would resume the WRONG environment when the provider,
4 * workspace, image, or tenant changes. The key folds all of those in, so any
5 * change busts the sandbox and forces a fresh create+bootstrap (safe default).
6 */
7import type { WorkspaceDefinition } from './workspace'
8
9/** Inputs that, together, identify one resumable sandbox instance. */
10export interface SandboxKeyInput {
11 threadId: string
12 sandboxId: string
13 providerName: string
14 workspace?: WorkspaceDefinition
15 /** Optional tenant scoping pulled from runtimeContext. */
16 tenant?: { userId?: string; orgId?: string }
17}
18
19/** Deterministic, dependency-free 64-bit FNV-1a hash → hex string. */
20function fnv1a(input: string): string {
21 // Two 32-bit lanes to approximate 64-bit without BigInt overhead concerns.
22 let h1 = 0x811c9dc5
23 let h2 = 0x811c9dc5
24 for (let i = 0; i < input.length; i++) {
25 const c = input.charCodeAt(i)
26 h1 ^= c & 0xff
27 h1 = Math.imul(h1, 0x01000193)
28 h2 ^= (c >> 8) & 0xff
29 h2 = Math.imul(h2, 0x01000193)
30 }
31 const hex = (n: number): string => (n >>> 0).toString(16).padStart(8, '0')
32 return hex(h1) + hex(h2)
33}
34
35/** Canonical, key-sorted JSON so logically-equal inputs hash identically. */
36function canonical(value: unknown): string {
37 if (value === null || typeof value !== 'object') return JSON.stringify(value)
38 if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
39 const keys = Object.keys(value).sort()
40 return `{${keys
41 .map(
42 (k) =>
43 `${JSON.stringify(k)}:${canonical((value as Record<string, unknown>)[k])}`,
44 )
45 .join(',')}}`
46}
47
48/**
49 * Hash of the parts of a workspace that change what the agent sees. Secrets are
50 * intentionally excluded (rotating a token must not orphan the sandbox).
51 */
52export function computeWorkspaceHash(
53 workspace: WorkspaceDefinition | undefined,
54): string {
55 if (!workspace) return fnv1a('no-workspace')
56 const { secrets: _secrets, ...rest } = workspace
57 const { source } = rest
58 if (source.type === 'git' && source.auth) {
59 const { token: _token, ...auth } = source.auth
60 return fnv1a(canonical({ ...rest, source: { ...source, auth } }))
61 }
62 return fnv1a(canonical(rest))
63}
64
65/** Compute the compound sandbox instance key. */
66export function computeSandboxKey(input: SandboxKeyInput): string {
67 const material = canonical({
68 threadId: input.threadId,
69 sandboxId: input.sandboxId,
70 providerName: input.providerName,
71 workspaceHash: computeWorkspaceHash(input.workspace),
72 tenant: input.tenant ?? null,
73 })
74 return fnv1a(material)
75}