@namzu/sandbox 14.0.0 → 16.0.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.
Files changed (100) hide show
  1. package/CHANGELOG.md +924 -0
  2. package/README.md +369 -14
  3. package/dist/backends/aci-standby-pool/index.d.ts.map +1 -1
  4. package/dist/backends/aci-standby-pool/index.js +13 -1
  5. package/dist/backends/aci-standby-pool/index.js.map +1 -1
  6. package/dist/backends/docker/index.d.ts +169 -6
  7. package/dist/backends/docker/index.d.ts.map +1 -1
  8. package/dist/backends/docker/index.js +499 -85
  9. package/dist/backends/docker/index.js.map +1 -1
  10. package/dist/backends/firecracker/index.d.ts.map +1 -1
  11. package/dist/backends/firecracker/index.js +12 -2
  12. package/dist/backends/firecracker/index.js.map +1 -1
  13. package/dist/backends/firecracker/protocol.d.ts +459 -8
  14. package/dist/backends/firecracker/protocol.d.ts.map +1 -1
  15. package/dist/backends/firecracker/protocol.js +136 -0
  16. package/dist/backends/firecracker/protocol.js.map +1 -1
  17. package/dist/backends/firecracker/transport.d.ts +539 -6
  18. package/dist/backends/firecracker/transport.d.ts.map +1 -1
  19. package/dist/backends/firecracker/transport.js +1171 -24
  20. package/dist/backends/firecracker/transport.js.map +1 -1
  21. package/dist/backends/kubernetes/egress-policy.d.ts +1181 -13
  22. package/dist/backends/kubernetes/egress-policy.d.ts.map +1 -1
  23. package/dist/backends/kubernetes/egress-policy.js +2350 -31
  24. package/dist/backends/kubernetes/egress-policy.js.map +1 -1
  25. package/dist/backends/kubernetes/identity.d.ts +193 -0
  26. package/dist/backends/kubernetes/identity.d.ts.map +1 -0
  27. package/dist/backends/kubernetes/identity.js +147 -0
  28. package/dist/backends/kubernetes/identity.js.map +1 -0
  29. package/dist/backends/kubernetes/index.d.ts +678 -33
  30. package/dist/backends/kubernetes/index.d.ts.map +1 -1
  31. package/dist/backends/kubernetes/index.js +1180 -95
  32. package/dist/backends/kubernetes/index.js.map +1 -1
  33. package/dist/backends/kubernetes/ingress-policy.d.ts +375 -0
  34. package/dist/backends/kubernetes/ingress-policy.d.ts.map +1 -0
  35. package/dist/backends/kubernetes/ingress-policy.js +1050 -0
  36. package/dist/backends/kubernetes/ingress-policy.js.map +1 -0
  37. package/dist/backends/kubernetes/k8s-client.d.ts +213 -4
  38. package/dist/backends/kubernetes/k8s-client.d.ts.map +1 -1
  39. package/dist/backends/kubernetes/k8s-client.js +359 -52
  40. package/dist/backends/kubernetes/k8s-client.js.map +1 -1
  41. package/dist/backends/kubernetes/lease.d.ts +40 -14
  42. package/dist/backends/kubernetes/lease.d.ts.map +1 -1
  43. package/dist/backends/kubernetes/lease.js +68 -18
  44. package/dist/backends/kubernetes/lease.js.map +1 -1
  45. package/dist/backends/kubernetes/objects.d.ts +423 -3
  46. package/dist/backends/kubernetes/objects.d.ts.map +1 -1
  47. package/dist/backends/kubernetes/objects.js +364 -2
  48. package/dist/backends/kubernetes/objects.js.map +1 -1
  49. package/dist/backends/kubernetes/per-sandbox-policy.d.ts +219 -0
  50. package/dist/backends/kubernetes/per-sandbox-policy.d.ts.map +1 -0
  51. package/dist/backends/kubernetes/per-sandbox-policy.js +375 -0
  52. package/dist/backends/kubernetes/per-sandbox-policy.js.map +1 -0
  53. package/dist/backends/kubernetes/rbac.d.ts +153 -0
  54. package/dist/backends/kubernetes/rbac.d.ts.map +1 -0
  55. package/dist/backends/kubernetes/rbac.js +177 -0
  56. package/dist/backends/kubernetes/rbac.js.map +1 -0
  57. package/dist/backends/kubernetes/sandbox.d.ts +81 -14
  58. package/dist/backends/kubernetes/sandbox.d.ts.map +1 -1
  59. package/dist/backends/kubernetes/sandbox.js +149 -15
  60. package/dist/backends/kubernetes/sandbox.js.map +1 -1
  61. package/dist/backends/kubernetes/transport.d.ts +935 -9
  62. package/dist/backends/kubernetes/transport.d.ts.map +1 -1
  63. package/dist/backends/kubernetes/transport.js +1958 -62
  64. package/dist/backends/kubernetes/transport.js.map +1 -1
  65. package/dist/backends/kubernetes/workspace.d.ts +1149 -18
  66. package/dist/backends/kubernetes/workspace.d.ts.map +1 -1
  67. package/dist/backends/kubernetes/workspace.js +2825 -186
  68. package/dist/backends/kubernetes/workspace.js.map +1 -1
  69. package/dist/backends/remote-execution-controller.d.ts +14 -0
  70. package/dist/backends/remote-execution-controller.d.ts.map +1 -1
  71. package/dist/backends/remote-execution-controller.js.map +1 -1
  72. package/dist/index.d.ts +294 -18
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +280 -10
  75. package/dist/index.js.map +1 -1
  76. package/dist/testing/sandbox-conformance.d.ts +39 -5
  77. package/dist/testing/sandbox-conformance.d.ts.map +1 -1
  78. package/dist/testing/sandbox-conformance.js +436 -5
  79. package/dist/testing/sandbox-conformance.js.map +1 -1
  80. package/package.json +3 -3
  81. package/src/backends/aci-standby-pool/index.ts +16 -1
  82. package/src/backends/docker/index.ts +617 -100
  83. package/src/backends/firecracker/index.ts +14 -2
  84. package/src/backends/firecracker/protocol.ts +514 -6
  85. package/src/backends/firecracker/transport.ts +1492 -40
  86. package/src/backends/kubernetes/egress-policy.ts +3334 -55
  87. package/src/backends/kubernetes/identity.ts +261 -0
  88. package/src/backends/kubernetes/index.ts +1785 -127
  89. package/src/backends/kubernetes/ingress-policy.ts +1344 -0
  90. package/src/backends/kubernetes/k8s-client.ts +444 -54
  91. package/src/backends/kubernetes/lease.ts +75 -19
  92. package/src/backends/kubernetes/objects.ts +626 -6
  93. package/src/backends/kubernetes/per-sandbox-policy.ts +497 -0
  94. package/src/backends/kubernetes/rbac.ts +192 -0
  95. package/src/backends/kubernetes/sandbox.ts +218 -20
  96. package/src/backends/kubernetes/transport.ts +2733 -124
  97. package/src/backends/kubernetes/workspace.ts +4476 -222
  98. package/src/backends/remote-execution-controller.ts +14 -0
  99. package/src/index.ts +668 -19
  100. package/src/testing/sandbox-conformance.ts +540 -5
@@ -22,6 +22,8 @@
22
22
  * sandboxclaims
23
23
  */
24
24
 
25
+ import { createHash } from 'node:crypto'
26
+
25
27
  /** Group serving the `Sandbox` kind. */
26
28
  export const SANDBOX_API_GROUP = 'agents.x-k8s.io'
27
29
  /** Group serving `SandboxTemplate`, `SandboxWarmPool` and `SandboxClaim`. */
@@ -47,6 +49,25 @@ export interface KubernetesObjectMeta {
47
49
  readonly name?: string
48
50
  readonly namespace?: string
49
51
  readonly uid?: string
52
+ /**
53
+ * RFC 3339, written by the API server on admission and never by a client.
54
+ * Read only to report how old a workspace is — see
55
+ * `workspace.ts`'s `listKubernetesWorkspaces`.
56
+ */
57
+ readonly creationTimestamp?: string
58
+ /**
59
+ * The object's version as this read saw it, written by the API server on
60
+ * every write and never by a client.
61
+ *
62
+ * It is here for exactly one use and no other: the fallback `test` clause
63
+ * of a holder-epoch patch aimed at an object that does not carry the
64
+ * annotation yet, and the `preconditions.resourceVersion` of a fenced
65
+ * DELETE — both INSIDE the one read-write pair that read it. It is never
66
+ * stored on a handle, never carried across calls and never streamed, so
67
+ * the "no watch, no informers, no resourceVersion tracking" invariant
68
+ * `k8s-client.ts` states still holds. See {@link buildHolderEpochPatch}.
69
+ */
70
+ readonly resourceVersion?: string
50
71
  /**
51
72
  * Set the moment a DELETE is accepted, long before the object goes away.
52
73
  * A pod that carries one is on its way out and must never be bound to —
@@ -109,10 +130,26 @@ export interface SandboxClaimLifecycle {
109
130
  * absent from this type: setting either forces the claim to cold-start rather
110
131
  * than adopt a warm pool sandbox, which is the one thing the warm path exists
111
132
  * to avoid. A field that cannot be named cannot be set by accident.
133
+ *
134
+ * `additionalPodMetadata` is the exception, and the reason the rule above is
135
+ * about COLD STARTS rather than about claim-time metadata in general: labels
136
+ * are merged into an adopted warm sandbox without one. Measured on
137
+ * agent-sandbox v1.0.2 — two claims out of one two-replica pool, each
138
+ * carrying a different label value, both binding a replica that already
139
+ * existed, and the controller patching the label onto the running pod and
140
+ * into the Sandbox's own podTemplate. See `egress-policy.ts`'s profile
141
+ * support.
112
142
  */
113
143
  export interface SandboxClaimResourceSpec {
114
144
  readonly warmPoolRef: { readonly name: string }
115
145
  readonly lifecycle?: SandboxClaimLifecycle
146
+ /**
147
+ * Labels (and annotations, which this backend never sets) the controller
148
+ * merges onto the pod it binds. Warm-safe — see the type comment.
149
+ */
150
+ readonly additionalPodMetadata?: {
151
+ readonly labels?: Readonly<Record<string, string>>
152
+ }
116
153
  }
117
154
 
118
155
  /**
@@ -137,6 +174,35 @@ export interface SandboxClaimResource {
137
174
  readonly status?: SandboxClaimResourceStatus
138
175
  }
139
176
 
177
+ /**
178
+ * A `GET` of the claims COLLECTION. Read by `readKubernetesTaskCapacity` (a
179
+ * count) and `releaseKubernetesTaskSandboxes` (the names to `DELETE`) — both
180
+ * in `index.ts`. Same "no watch, no `continue`" shape as
181
+ * {@link SandboxListResource}, for the same reason: this backend does no
182
+ * watch at all.
183
+ */
184
+ export interface SandboxClaimListResource {
185
+ readonly items?: readonly SandboxClaimResource[]
186
+ }
187
+
188
+ /**
189
+ * `SandboxWarmPool.spec`/`.status`, read by `readKubernetesTaskCapacity`
190
+ * alone — the first place in this backend that reads a `SandboxWarmPool`
191
+ * rather than only naming one in a claim's `warmPoolRef`. Partial in the
192
+ * same way every other shape here is: `replicas` and `readyReplicas` are the
193
+ * two fields a capacity read needs, off the exact same object
194
+ * `k8s/scripts/acquire-p50.mjs` already polls by hand.
195
+ */
196
+ export interface SandboxWarmPoolResource {
197
+ readonly metadata?: KubernetesObjectMeta
198
+ readonly spec?: {
199
+ readonly replicas?: number
200
+ }
201
+ readonly status?: {
202
+ readonly readyReplicas?: number
203
+ }
204
+ }
205
+
140
206
  /**
141
207
  * `podTemplate` on a Sandbox or a SandboxTemplate. `spec` is a core `PodSpec`,
142
208
  * carried opaquely: this backend copies one from a template into a Sandbox and
@@ -207,6 +273,17 @@ export interface SandboxResource {
207
273
  readonly status?: SandboxResourceStatus
208
274
  }
209
275
 
276
+ /**
277
+ * A `GET` of the sandboxes COLLECTION. `items` is the only field anything
278
+ * here reads: this backend does no watch, so `metadata.resourceVersion` and
279
+ * `continue` have nothing to feed — the namespace a deployment gives its
280
+ * sandboxes holds tens of objects, not the thousands that would make a page
281
+ * boundary a real answer rather than a truncated one.
282
+ */
283
+ export interface SandboxListResource {
284
+ readonly items?: readonly SandboxResource[]
285
+ }
286
+
210
287
  export interface SandboxTemplateResource {
211
288
  readonly metadata?: KubernetesObjectMeta
212
289
  readonly spec?: {
@@ -217,13 +294,62 @@ export interface SandboxTemplateResource {
217
294
  }
218
295
 
219
296
  /**
220
- * `metadata.uid` is the per-instance agent bind token; the other two fields
221
- * exist only to answer "is this the pod that uid belongs to, or the one being
222
- * deleted?" — see {@link isPodLive}.
297
+ * `metadata.uid` is the per-instance agent bind token; `deletionTimestamp`
298
+ * and `phase` exist only to answer "is this the pod that uid belongs to, or
299
+ * the one being deleted?" — see {@link isPodLive}.
300
+ *
301
+ * `podIP` is read by the `pod-ip` address mode only, and deliberately from
302
+ * the SAME object the uid comes from: an address taken from one pod and a
303
+ * token taken from another is the mismatch that reports as a flat
304
+ * `unauthorized` with nothing pointing at the pod that was replaced in
305
+ * between. Both spellings are carried because a dual-stack cluster fills
306
+ * `podIPs` and single-stack clusters have always filled `podIP`; the API
307
+ * server sets `podIP` to the first entry of `podIPs` on every cluster that
308
+ * sets either, so {@link readPodIP} prefers it and falls back.
223
309
  */
224
310
  export interface PodResource {
225
311
  readonly metadata?: KubernetesObjectMeta
226
- readonly status?: { readonly phase?: string }
312
+ readonly status?: {
313
+ readonly phase?: string
314
+ readonly podIP?: string
315
+ readonly podIPs?: readonly { readonly ip?: string }[]
316
+ /**
317
+ * `status.conditions` — read on ONE path only, and never on a healthy
318
+ * one: after an acquire has already run out of readiness budget,
319
+ * `PodScheduled=False` with reason `Unschedulable` is what separates
320
+ * "the cluster has no room" from "the sandbox is just slow". Nothing
321
+ * waits on a pod condition: `Ready` here is the kubelet's view of the
322
+ * container, and readiness on this backend is the Sandbox's own
323
+ * `Ready`, which is what {@link isConditionTrue} is called with
324
+ * everywhere else. See `index.ts`'s `diagnoseUnreadyPod`.
325
+ */
326
+ readonly conditions?: readonly KubernetesCondition[]
327
+ /**
328
+ * `status.containerStatuses` — read on the same one path, for the same
329
+ * one question. A container stuck in `waiting` with an image-pull
330
+ * reason is a permanent failure wearing the clothes of a slow start,
331
+ * and it is the only one of those this backend can name from the API.
332
+ */
333
+ readonly containerStatuses?: readonly PodContainerStatus[]
334
+ }
335
+ }
336
+
337
+ /** The single `status.containerStatuses` field the diagnosis above reads. */
338
+ export interface PodContainerStatus {
339
+ readonly name?: string
340
+ readonly state?: {
341
+ readonly waiting?: { readonly reason?: string; readonly message?: string }
342
+ }
343
+ }
344
+
345
+ /** The pod's own address, whichever of the two fields this cluster fills. */
346
+ export function readPodIP(pod: PodResource | undefined): string | undefined {
347
+ const status = pod?.status
348
+ if (typeof status?.podIP === 'string' && status.podIP !== '') return status.podIP
349
+ for (const entry of status?.podIPs ?? []) {
350
+ if (typeof entry?.ip === 'string' && entry.ip !== '') return entry.ip
351
+ }
352
+ return undefined
227
353
  }
228
354
 
229
355
  export interface PodListResource {
@@ -303,6 +429,417 @@ export function isPodStopped(pod: PodResource | undefined): boolean {
303
429
  */
304
430
  export const SANDBOX_TEMPLATE_LABEL_KEY = 'sandbox.namzu.ai/template'
305
431
 
432
+ /**
433
+ * Backend-owned annotation naming when a Sandbox's `spec.operatingMode` was
434
+ * last changed BY THIS BACKEND, RFC 3339.
435
+ *
436
+ * It exists because nothing already on the object answers the question, and
437
+ * an inventory that never wakes a workspace is the reason to ask it: a
438
+ * retention pass deleting the workspaces nobody has resumed for a month reads
439
+ * this and `metadata.creationTimestamp` and nothing else.
440
+ *
441
+ * The obvious candidate is the controller's own `Suspended` condition and its
442
+ * `lastTransitionTime`, and upstream's `sandbox_types.go` rules it out in the
443
+ * same breath it documents it: "the controller does not currently remove this
444
+ * condition when the Sandbox is resumed", so after a resume the condition is
445
+ * still True and its timestamp still names the suspend that preceded it. The
446
+ * `Ready` condition's timestamp is no better — it moves for every pod that
447
+ * comes and goes, a crash-restart included, and a workspace whose pod
448
+ * restarted has not changed operating mode at all.
449
+ *
450
+ * So the two patches that DO change the mode stamp the moment they were sent,
451
+ * and the value is exactly that: the host's clock at the moment it asked, not
452
+ * the cluster's at the moment it applied. It is an inventory column, never a
453
+ * lock or an ordering, and nothing in this backend reads it back to make a
454
+ * decision. A Sandbox whose mode has never been changed since it was created
455
+ * carries no annotation at all, and is reported without one rather than with
456
+ * a guess.
457
+ *
458
+ * Same prefix as {@link SANDBOX_TEMPLATE_LABEL_KEY}, for the same reason.
459
+ */
460
+ export const OPERATING_MODE_CHANGED_AT_ANNOTATION_KEY = 'sandbox.namzu.ai/operating-mode-changed-at'
461
+
462
+ /**
463
+ * Backend-owned annotation carrying the HOLDER EPOCH: a decimal integer the
464
+ * host raises whenever authority over this workspace moves to another
465
+ * process.
466
+ *
467
+ * A workspace id is a name, not a lock, and a host that drives one workspace
468
+ * from more than one process has to decide which of them may suspend, resume
469
+ * or delete it. Checking its own epoch and then calling `suspend()` does not
470
+ * close the race, because the write that follows is a separate request and
471
+ * the API server accepts it. So the epoch is stored HERE, on the object every
472
+ * lifecycle write targets, and every such write carries it as a condition in
473
+ * the same request — see {@link buildHolderEpochPatch}.
474
+ *
475
+ * The rule: a write carrying epoch `e` applies when the stored epoch is `<=
476
+ * e`, and sets the stored epoch to `e` in the same request. A stored epoch
477
+ * greater than `e` refuses it. An object with NO annotation reads as 0, so
478
+ * every workspace created before this existed accepts its first
479
+ * epoch-carrying write.
480
+ *
481
+ * It is the caller's number, never this backend's: nothing here invents,
482
+ * increments or persists an epoch of its own, and a call that passes none
483
+ * sends exactly the requests it always sent.
484
+ *
485
+ * Same prefix as {@link SANDBOX_TEMPLATE_LABEL_KEY} and
486
+ * {@link OPERATING_MODE_CHANGED_AT_ANNOTATION_KEY}, for the same reason.
487
+ */
488
+ export const HOLDER_EPOCH_ANNOTATION_KEY = 'sandbox.namzu.ai/holder-epoch'
489
+
490
+ /**
491
+ * Backend-owned annotation carrying a hash of the pod template a Sandbox was
492
+ * last built with.
493
+ *
494
+ * A Sandbox's `spec.podTemplate` is a COPY of the SandboxTemplate's, taken
495
+ * once, and the controller rebuilds every replacement pod from that copy
496
+ * rather than from the template — so a workspace kept for weeks runs the pod
497
+ * spec it was created with, and an edit to the template (a new image tag, a
498
+ * memory limit, a grace period, an env entry) reaches only workspaces created
499
+ * after it. Nothing on the object answers "is this copy still the template's
500
+ * current one": the two are separate objects with separate
501
+ * `resourceVersion`s, and comparing the templates field by field on every
502
+ * open would be a second, weaker copy of the overlay rules.
503
+ *
504
+ * So the value is a hash of exactly what was written: the template's
505
+ * `podTemplate` AFTER this backend's own overlays (the template label and the
506
+ * configured `runtimeClassName`), which is the object the Sandbox carries.
507
+ * Hashing before the overlays would report drift on every workspace whose
508
+ * RuntimeClass this backend chose.
509
+ *
510
+ * Written by the workspace paths only — the create POST and the refresh patch
511
+ * — and read back as `templateRevision` on a handle. A task sandbox is
512
+ * ephemeral and has nothing to drift from, so its create body is unchanged.
513
+ * A workspace created before this existed carries no annotation and reports
514
+ * `templateRevision: undefined`, which reads honestly as "unknown", never as
515
+ * "current".
516
+ *
517
+ * Same prefix as {@link SANDBOX_TEMPLATE_LABEL_KEY}, for the same reason.
518
+ */
519
+ export const POD_TEMPLATE_HASH_ANNOTATION_KEY = 'sandbox.namzu.ai/pod-template-hash'
520
+
521
+ /** Object keys in code-unit order, so the hash does not depend on a locale. */
522
+ function compareKeys(left: string, right: string): number {
523
+ if (left < right) return -1
524
+ return left > right ? 1 : 0
525
+ }
526
+
527
+ /**
528
+ * The same JSON with its object keys sorted, recursively.
529
+ *
530
+ * `JSON.stringify` preserves insertion order, and the two pod templates this
531
+ * hash has to compare never have the same one: one comes back from the API
532
+ * server's own serialisation of a stored object and the other is built here
533
+ * by spreading a template's members into a fresh object. Without this, every
534
+ * comparison would report drift that does not exist.
535
+ */
536
+ function canonicalJson(value: unknown): unknown {
537
+ if (Array.isArray(value)) return value.map(canonicalJson)
538
+ if (typeof value !== 'object' || value === null) return value
539
+ const canonical: Record<string, unknown> = {}
540
+ for (const key of Object.keys(value as Record<string, unknown>).sort(compareKeys)) {
541
+ const member = (value as Record<string, unknown>)[key]
542
+ if (member === undefined) continue
543
+ canonical[key] = canonicalJson(member)
544
+ }
545
+ return canonical
546
+ }
547
+
548
+ /**
549
+ * `sha256:<hex>` over the pod template, for
550
+ * {@link POD_TEMPLATE_HASH_ANNOTATION_KEY}.
551
+ *
552
+ * It is an identity, not a checksum of anything security-relevant: two hosts
553
+ * running the same release against the same template must compute the same
554
+ * string, and a template edit must change it. Nothing here compares it
555
+ * against a value an untrusted party chose.
556
+ */
557
+ export function podTemplateHash(podTemplate: SandboxPodTemplate): string {
558
+ const digest = createHash('sha256')
559
+ .update(JSON.stringify(canonicalJson(podTemplate)))
560
+ .digest('hex')
561
+ return `sha256:${digest}`
562
+ }
563
+
564
+ /**
565
+ * One RFC 6902 operation, in the only three shapes this backend sends.
566
+ *
567
+ * `test` is the condition, `add` is every mutation. `add` rather than
568
+ * `replace` throughout: RFC 6902 §4.1 says that on a JSON object member `add`
569
+ * creates the member when it is missing and replaces its value when it is
570
+ * present, while §4.3's `replace` fails outright on a missing one — and
571
+ * `spec.operatingMode` is absent on a Sandbox that has never been suspended,
572
+ * as is the epoch annotation on every workspace created before this release.
573
+ * A `replace` would turn both of those ordinary cases into a rejected patch.
574
+ *
575
+ * So where a design or an issue says the wire carries `replace /spec/…`, this
576
+ * is that write: on a member that is already there the two operations are the
577
+ * same write, and on one that is not, only this one lands.
578
+ */
579
+ export interface JsonPatchOperation {
580
+ readonly op: 'test' | 'add'
581
+ readonly path: string
582
+ readonly value: unknown
583
+ }
584
+
585
+ /**
586
+ * One JSON Pointer reference token (RFC 6901 §3): `~` becomes `~0` and `/`
587
+ * becomes `~1`, in that order — the reverse order would turn a literal `~1`
588
+ * into a slash.
589
+ *
590
+ * An annotation key always contains a `/` (`sandbox.namzu.ai/holder-epoch`),
591
+ * so the pointer to one is unusable without this.
592
+ */
593
+ export function escapeJsonPointerSegment(token: string): string {
594
+ return token.replace(/~/g, '~0').replace(/\//g, '~1')
595
+ }
596
+
597
+ /** Pointer to one annotation on an object's own metadata. */
598
+ export function annotationPointer(key: string): string {
599
+ return `/metadata/annotations/${escapeJsonPointerSegment(key)}`
600
+ }
601
+
602
+ /** What one read of an object saw about its holder epoch. */
603
+ export interface HolderEpochReading {
604
+ /**
605
+ * The stored epoch: the annotation parsed, or `0` when there is none.
606
+ *
607
+ * `undefined` means the annotation is PRESENT and is not a decimal
608
+ * integer, which no version of this backend writes. It is reported as
609
+ * unreadable rather than as 0 on purpose: reading a value this code does
610
+ * not understand as "nobody holds this workspace" would let a write
611
+ * overwrite a fence somebody else established, which is the one thing the
612
+ * annotation exists to prevent.
613
+ */
614
+ readonly epoch?: number
615
+ /**
616
+ * The annotation exactly as stored, and the value the `test` clause
617
+ * carries. Absent when the object has no such annotation.
618
+ */
619
+ readonly annotation?: string
620
+ /** `metadata.annotations` existed at all — decides which `add` is sent. */
621
+ readonly hasAnnotations: boolean
622
+ /** `metadata.resourceVersion`, for the fallback `test` and a fenced DELETE. */
623
+ readonly resourceVersion?: string
624
+ }
625
+
626
+ /** Decimal, no sign, no padding, no exponent — what this backend writes. */
627
+ const HOLDER_EPOCH_PATTERN = /^(?:0|[1-9][0-9]*)$/
628
+
629
+ /** Read {@link HOLDER_EPOCH_ANNOTATION_KEY} off an object's metadata. */
630
+ export function readHolderEpoch(meta: KubernetesObjectMeta | undefined): HolderEpochReading {
631
+ const annotations = meta?.annotations
632
+ const resourceVersion =
633
+ typeof meta?.resourceVersion === 'string' && meta.resourceVersion !== ''
634
+ ? meta.resourceVersion
635
+ : undefined
636
+ const stored = annotations?.[HOLDER_EPOCH_ANNOTATION_KEY]
637
+ const base = {
638
+ hasAnnotations: annotations !== undefined,
639
+ ...(resourceVersion !== undefined ? { resourceVersion } : {}),
640
+ }
641
+ if (typeof stored !== 'string') return { ...base, epoch: 0 }
642
+ if (!HOLDER_EPOCH_PATTERN.test(stored)) return { ...base, annotation: stored }
643
+ const parsed = Number(stored)
644
+ if (!Number.isSafeInteger(parsed)) return { ...base, annotation: stored }
645
+ return { ...base, epoch: parsed, annotation: stored }
646
+ }
647
+
648
+ /**
649
+ * Read {@link POD_TEMPLATE_HASH_ANNOTATION_KEY} off an object's metadata.
650
+ *
651
+ * Absent — an object created before this existed, or one an older release
652
+ * refreshed — is `undefined`, which reads as "unknown" everywhere it is
653
+ * consumed. It is deliberately never compared as an empty string: a
654
+ * revision nobody recorded is not a revision that differs.
655
+ */
656
+ export function readPodTemplateHash(meta: KubernetesObjectMeta | undefined): string | undefined {
657
+ const stored = meta?.annotations?.[POD_TEMPLATE_HASH_ANNOTATION_KEY]
658
+ return typeof stored === 'string' && stored !== '' ? stored : undefined
659
+ }
660
+
661
+ /** A stored epoch of `epoch` or lower lets a write carrying `epoch` through. */
662
+ export function holderEpochAllows(reading: HolderEpochReading, epoch: number): boolean {
663
+ return reading.epoch !== undefined && reading.epoch <= epoch
664
+ }
665
+
666
+ /** What {@link buildHolderEpochPatch} is asked to write, and under what condition. */
667
+ export interface HolderEpochPatchInput {
668
+ /** The metadata the GET returned. The condition is built from THIS read. */
669
+ readonly reading: HolderEpochReading
670
+ /**
671
+ * The epoch the write carries, and the one it stores.
672
+ *
673
+ * ABSENT is the unfenced conditional write: no epoch clause is tested and
674
+ * no epoch annotation is written, and {@link tests} then carries the whole
675
+ * condition — which is why an epoch-less call with no `tests` is refused
676
+ * below rather than sent unconditionally. A workspace refresh is the one
677
+ * caller: its condition is `spec.operatingMode`, and a host that has not
678
+ * opted into the fence must not acquire one by asking for a new pod
679
+ * template.
680
+ */
681
+ readonly epoch?: number
682
+ /**
683
+ * Further `test` clauses composed into the SAME body.
684
+ *
685
+ * This is the seam a second condition uses instead of a second request: a
686
+ * write that also has to assert, say, `spec.operatingMode` passes its
687
+ * clause here and the object is still written under one atomic patch. Two
688
+ * call sites each sending their own conditional patch would be two writes
689
+ * and two chances to lose a race between them.
690
+ */
691
+ readonly tests?: readonly JsonPatchOperation[]
692
+ /** Written to `spec.operatingMode`; omitted leaves the mode alone. */
693
+ readonly operatingMode?: 'Running' | 'Suspended'
694
+ /**
695
+ * RFC 3339 stamp for {@link OPERATING_MODE_CHANGED_AT_ANNOTATION_KEY}.
696
+ * Passed only by a write that actually CHANGES the mode — the annotation
697
+ * says when the mode last changed, and a write that merely restamps the
698
+ * epoch has not changed it.
699
+ */
700
+ readonly operatingModeChangedAt?: string
701
+ /**
702
+ * Further annotations written in the SAME body, merged with the epoch's
703
+ * and the mode stamp's rather than sent after them.
704
+ *
705
+ * {@link POD_TEMPLATE_HASH_ANNOTATION_KEY} is the only caller: the hash
706
+ * has to land with the pod template it describes, or a patch that applied
707
+ * half of the pair would leave the object claiming a revision it is not
708
+ * running.
709
+ */
710
+ readonly annotations?: Readonly<Record<string, string>>
711
+ /**
712
+ * Written to `spec.podTemplate`, replacing it WHOLE — which is the reason
713
+ * this is a JSON Patch at all. A merge patch recurses into maps, so a
714
+ * `nodeSelector` entry the template dropped would survive in the object
715
+ * and the pod would keep a constraint nobody can see in the template any
716
+ * more.
717
+ */
718
+ readonly podTemplate?: SandboxPodTemplate
719
+ }
720
+
721
+ /**
722
+ * The one conditional-write builder this backend has, and the only place a
723
+ * JSON Patch body is composed.
724
+ *
725
+ * Every clause is decided from ONE read, and the whole thing goes up as one
726
+ * request: the condition and the mutation are in the same body, so there is
727
+ * no window between checking and writing for another holder to fit into.
728
+ *
729
+ * Three shapes, decided by what that read saw:
730
+ *
731
+ * - the object carries the epoch annotation ⇒ `test` it by its exact stored
732
+ * string, then `add` the new value over it;
733
+ * - the object carries annotations but not this one ⇒ `test`
734
+ * `/metadata/resourceVersion` instead, then `add` the member;
735
+ * - the object carries no `metadata.annotations` at all ⇒ the same
736
+ * `resourceVersion` test, then `add` the map whole, because there is no
737
+ * member to add one to.
738
+ *
739
+ * The `resourceVersion` fallback is the migration case and nothing more: it
740
+ * fires once, on a workspace created before this release, and from the first
741
+ * epoch write onwards the annotation is what is tested. That matters because
742
+ * a controller status write moves `resourceVersion` without touching the
743
+ * annotation, and under the annotation test those are simply not conditions
744
+ * this write is interested in.
745
+ *
746
+ * A call carrying NO epoch skips all three: it tests only what
747
+ * {@link HolderEpochPatchInput.tests} carries and writes no epoch annotation,
748
+ * which is how a workspace refresh conditions itself on `spec.operatingMode`
749
+ * without fencing a host that never asked for a fence.
750
+ *
751
+ * Every `test` precedes every mutation, which RFC 6902 requires of a
752
+ * condition: operations apply in order, so a `test` written after an `add`
753
+ * would be testing this patch's own work. Mutations go up in a fixed order —
754
+ * annotations, then `spec.podTemplate`, then `spec.operatingMode` — so the
755
+ * body a given input produces is one body and a test can assert it.
756
+ */
757
+ export function buildHolderEpochPatch(input: HolderEpochPatchInput): readonly JsonPatchOperation[] {
758
+ const { reading, epoch } = input
759
+ const epochPointer = annotationPointer(HOLDER_EPOCH_ANNOTATION_KEY)
760
+ const tests: JsonPatchOperation[] = []
761
+ if (epoch === undefined) {
762
+ // Unfenced: the caller's own clauses are the whole condition, and an
763
+ // unconditional JSON patch is refused rather than sent. Every caller
764
+ // on this branch is conditioning on something — a refresh on
765
+ // `spec.operatingMode` — and one that passed nothing would be asking
766
+ // for a blind write in the one builder that exists to prevent them.
767
+ if ((input.tests ?? []).length === 0) {
768
+ throw new Error(
769
+ 'kubernetes: cannot build a conditional patch that carries neither a holder epoch nor a test clause — there is nothing to condition the write on.',
770
+ )
771
+ }
772
+ } else if (reading.annotation !== undefined) {
773
+ tests.push({ op: 'test', path: epochPointer, value: reading.annotation })
774
+ } else if (reading.resourceVersion !== undefined) {
775
+ tests.push({ op: 'test', path: '/metadata/resourceVersion', value: reading.resourceVersion })
776
+ } else {
777
+ // Unreachable from every call site here — each one builds from an
778
+ // object it just read, and the API server sets `resourceVersion` on
779
+ // every object it serves. It throws rather than sending an
780
+ // UNCONDITIONAL patch, because a fenced write that quietly stopped
781
+ // being fenced is the defect this whole path exists to prevent.
782
+ throw new Error(
783
+ 'kubernetes: cannot build a holder-epoch patch from an object that carries neither the holder-epoch annotation nor a metadata.resourceVersion — there is nothing to condition the write on.',
784
+ )
785
+ }
786
+ tests.push(...(input.tests ?? []))
787
+
788
+ const mutations: JsonPatchOperation[] = []
789
+ // Every annotation this body writes, in one place: the epoch when the
790
+ // write is fenced, the mode stamp when the mode moves, and whatever else
791
+ // the caller is landing atomically with them.
792
+ const annotations: Record<string, string> = {
793
+ ...(epoch !== undefined ? { [HOLDER_EPOCH_ANNOTATION_KEY]: String(epoch) } : {}),
794
+ ...(input.operatingModeChangedAt !== undefined
795
+ ? { [OPERATING_MODE_CHANGED_AT_ANNOTATION_KEY]: input.operatingModeChangedAt }
796
+ : {}),
797
+ ...input.annotations,
798
+ }
799
+ const keys = Object.keys(annotations)
800
+ if (keys.length > 0) {
801
+ if (!reading.hasAnnotations) {
802
+ // No member to add one to, so the map goes up whole — and a whole
803
+ // map REPLACES whatever is there, so this one operation is the only
804
+ // mutation in this builder that can erase another writer's work.
805
+ // The window is real: between the GET that saw no annotations and
806
+ // this patch, another process can stamp one without moving
807
+ // `spec.operatingMode` — a suspend carrying a holder epoch onto an
808
+ // already-Suspended object does exactly that — and an unconditional
809
+ // whole-map `add` would silently unfence the workspace it took.
810
+ // `resourceVersion` is what closes it. The fenced path already
811
+ // tests it on this branch (an object with no annotations has no
812
+ // epoch annotation to test); this adds the same clause for an
813
+ // UNFENCED caller, whose own clauses are about `spec` and say
814
+ // nothing about `metadata`.
815
+ if (!tests.some((test) => test.path === '/metadata/resourceVersion')) {
816
+ if (reading.resourceVersion === undefined) {
817
+ throw new Error(
818
+ 'kubernetes: cannot add a metadata.annotations map to an object that carries no metadata.resourceVersion — a whole-map write with nothing to condition it on would overwrite annotations written since the read.',
819
+ )
820
+ }
821
+ tests.push({
822
+ op: 'test',
823
+ path: '/metadata/resourceVersion',
824
+ value: reading.resourceVersion,
825
+ })
826
+ }
827
+ mutations.push({ op: 'add', path: '/metadata/annotations', value: annotations })
828
+ } else {
829
+ for (const key of keys) {
830
+ mutations.push({ op: 'add', path: annotationPointer(key), value: annotations[key] })
831
+ }
832
+ }
833
+ }
834
+ if (input.podTemplate !== undefined) {
835
+ mutations.push({ op: 'add', path: '/spec/podTemplate', value: input.podTemplate })
836
+ }
837
+ if (input.operatingMode !== undefined) {
838
+ mutations.push({ op: 'add', path: '/spec/operatingMode', value: input.operatingMode })
839
+ }
840
+ return [...tests, ...mutations]
841
+ }
842
+
306
843
  /** `{ [SANDBOX_TEMPLATE_LABEL_KEY]: sandboxTemplateName }`, as a matchLabels-ready object. */
307
844
  export function sandboxTemplateLabel(
308
845
  sandboxTemplateName: string,
@@ -334,6 +871,15 @@ export function claimPath(namespace: string, name: string): string {
334
871
  return `${claimCollectionPath(namespace)}/${segment(name)}`
335
872
  }
336
873
 
874
+ /** The claims collection, narrowed to a `labelSelector` — same shape as {@link podListPath}. */
875
+ export function claimListPath(namespace: string, labelSelector: string): string {
876
+ return `${claimCollectionPath(namespace)}?labelSelector=${encodeURIComponent(labelSelector)}`
877
+ }
878
+
879
+ export function warmPoolPath(namespace: string, name: string): string {
880
+ return `/apis/${SANDBOX_EXTENSIONS_API_GROUP}/${SANDBOX_API_VERSION}/namespaces/${segment(namespace)}/sandboxwarmpools/${segment(name)}`
881
+ }
882
+
337
883
  export function sandboxCollectionPath(namespace: string): string {
338
884
  return `/apis/${SANDBOX_API_GROUP}/${SANDBOX_API_VERSION}/namespaces/${segment(namespace)}/sandboxes`
339
885
  }
@@ -346,18 +892,92 @@ export function sandboxTemplatePath(namespace: string, name: string): string {
346
892
  return `/apis/${SANDBOX_EXTENSIONS_API_GROUP}/${SANDBOX_API_VERSION}/namespaces/${segment(namespace)}/sandboxtemplates/${segment(name)}`
347
893
  }
348
894
 
895
+ /**
896
+ * The PVC the controller creates for one `volumeClaimTemplates` entry:
897
+ * `<entry name>-<sandbox name>`, in the Sandbox's own namespace.
898
+ *
899
+ * Written out here rather than derived at each call site because it is a
900
+ * NAME the controller owns, not one this backend chooses — a release that
901
+ * changes it breaks every read of it at once, and the one place to notice
902
+ * that is a function whose whole body is the convention.
903
+ */
904
+ export function persistentVolumeClaimPath(
905
+ namespace: string,
906
+ sandboxName: string,
907
+ claimTemplateName: string,
908
+ ): string {
909
+ return `/api/v1/namespaces/${segment(namespace)}/persistentvolumeclaims/${segment(
910
+ `${claimTemplateName}-${sandboxName}`,
911
+ )}`
912
+ }
913
+
349
914
  export function podPath(namespace: string, name: string): string {
350
915
  return `/api/v1/namespaces/${segment(namespace)}/pods/${segment(name)}`
351
916
  }
352
917
 
918
+ /** The whole pods collection, unfiltered. Read by `readKubernetesTaskCapacity` alone. */
919
+ export function podCollectionPath(namespace: string): string {
920
+ return `/api/v1/namespaces/${segment(namespace)}/pods`
921
+ }
922
+
353
923
  export function podListPath(namespace: string, labelSelector: string): string {
354
924
  return `/api/v1/namespaces/${segment(namespace)}/pods?labelSelector=${encodeURIComponent(labelSelector)}`
355
925
  }
356
926
 
927
+ export function networkPolicyCollectionPath(namespace: string): string {
928
+ return `/apis/${CORE_NETWORK_POLICY_API_GROUP}/${CORE_NETWORK_POLICY_API_VERSION}/namespaces/${segment(namespace)}/networkpolicies`
929
+ }
930
+
357
931
  export function networkPolicyPath(namespace: string, name: string): string {
358
- return `/apis/${CORE_NETWORK_POLICY_API_GROUP}/${CORE_NETWORK_POLICY_API_VERSION}/namespaces/${segment(namespace)}/networkpolicies/${segment(name)}`
932
+ return `${networkPolicyCollectionPath(namespace)}/${segment(name)}`
933
+ }
934
+
935
+ export function ciliumNetworkPolicyCollectionPath(namespace: string): string {
936
+ return `/apis/${CILIUM_NETWORK_POLICY_API_GROUP}/${CILIUM_NETWORK_POLICY_API_VERSION}/namespaces/${segment(namespace)}/ciliumnetworkpolicies`
359
937
  }
360
938
 
361
939
  export function ciliumNetworkPolicyPath(namespace: string, name: string): string {
362
- return `/apis/${CILIUM_NETWORK_POLICY_API_GROUP}/${CILIUM_NETWORK_POLICY_API_VERSION}/namespaces/${segment(namespace)}/ciliumnetworkpolicies/${segment(name)}`
940
+ return `${ciliumNetworkPolicyCollectionPath(namespace)}/${segment(name)}`
941
+ }
942
+
943
+ /**
944
+ * Core Kubernetes' own admission-policy resources — `ValidatingAdmissionPolicy`
945
+ * and its binding, both CLUSTER-scoped and both stock since v1.30, so a
946
+ * cluster that serves this group needs nothing installed.
947
+ *
948
+ * Read by exactly one caller: the per-sandbox policy fence
949
+ * (`per-sandbox-policy.ts`), which refuses to write a `CiliumNetworkPolicy`
950
+ * at all unless an operator has applied the policy that bounds what this
951
+ * host may write. Never written by this backend — the fence is the operator's
952
+ * object, reviewed by whoever has cluster-admin, and a host that could create
953
+ * its own fence would not have one.
954
+ */
955
+ export const ADMISSION_REGISTRATION_API_GROUP = 'admissionregistration.k8s.io'
956
+ export const ADMISSION_REGISTRATION_API_VERSION = 'v1'
957
+
958
+ export function validatingAdmissionPolicyPath(name: string): string {
959
+ return `/apis/${ADMISSION_REGISTRATION_API_GROUP}/${ADMISSION_REGISTRATION_API_VERSION}/validatingadmissionpolicies/${segment(name)}`
960
+ }
961
+
962
+ export function validatingAdmissionPolicyBindingPath(name: string): string {
963
+ return `/apis/${ADMISSION_REGISTRATION_API_GROUP}/${ADMISSION_REGISTRATION_API_VERSION}/validatingadmissionpolicybindings/${segment(name)}`
964
+ }
965
+
966
+ /**
967
+ * An `ownerReferences` entry, as this backend writes it.
968
+ *
969
+ * `controller` and `blockOwnerDeletion` are deliberately ABSENT rather than
970
+ * written as `false`. `blockOwnerDeletion: true` would make the API server's
971
+ * `OwnerReferencesPermissionEnforcement` admission plugin demand `update` on
972
+ * the OWNER's `finalizers` subresource — a verb no Role in this repo grants
973
+ * and no host needs — so a field whose only legal value here is `false` is
974
+ * one the body is better off not carrying at all. Garbage collection does not
975
+ * need either field: a dependent whose owners are all gone is deleted, owning
976
+ * controller or not.
977
+ */
978
+ export interface KubernetesOwnerReference {
979
+ readonly apiVersion: string
980
+ readonly kind: string
981
+ readonly name: string
982
+ readonly uid: string
363
983
  }