lastlight-core 0.21.11 → 0.21.13

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 (150) hide show
  1. package/deploy/k8s/README.md +111 -34
  2. package/deploy/k8s/architecture.md +199 -0
  3. package/deploy/k8s/configmap.yaml +14 -3
  4. package/deploy/k8s/harness-deployment.yaml +111 -0
  5. package/deploy/k8s/kustomization.yaml +10 -8
  6. package/deploy/k8s/sandbox-namespace.yaml +14 -0
  7. package/deploy/k8s/sandbox-quota.yaml +37 -0
  8. package/deploy/k8s/sandbox-rbac.yaml +60 -0
  9. package/dist/admin/routes.js +66 -10
  10. package/dist/admin/routes.js.map +1 -1
  11. package/dist/config/config.d.ts +36 -0
  12. package/dist/config/config.js +101 -3
  13. package/dist/config/config.js.map +1 -1
  14. package/dist/cron/review-discovery.d.ts +54 -0
  15. package/dist/cron/review-discovery.js +70 -0
  16. package/dist/cron/review-discovery.js.map +1 -0
  17. package/dist/engine/executors/orchestrator.js +124 -58
  18. package/dist/engine/executors/orchestrator.js.map +1 -1
  19. package/dist/engine/github/github.d.ts +8 -0
  20. package/dist/engine/github/github.js +14 -0
  21. package/dist/engine/github/github.js.map +1 -1
  22. package/dist/engine/github/profiles.d.ts +12 -1
  23. package/dist/engine/github/profiles.js +33 -1
  24. package/dist/engine/github/profiles.js.map +1 -1
  25. package/dist/index.js +55 -14
  26. package/dist/index.js.map +1 -1
  27. package/dist/sandbox/artifact-backend.d.ts +40 -0
  28. package/dist/sandbox/artifact-backend.js +67 -0
  29. package/dist/sandbox/artifact-backend.js.map +1 -0
  30. package/dist/sandbox/artifact-store.d.ts +55 -0
  31. package/dist/sandbox/artifact-store.js +203 -0
  32. package/dist/sandbox/artifact-store.js.map +1 -0
  33. package/dist/sandbox/docker.d.ts +2 -1
  34. package/dist/sandbox/docker.js +3 -3
  35. package/dist/sandbox/docker.js.map +1 -1
  36. package/dist/sandbox/k8s/agent-context-registry.d.ts +25 -0
  37. package/dist/sandbox/k8s/agent-context-registry.js +45 -0
  38. package/dist/sandbox/k8s/agent-context-registry.js.map +1 -0
  39. package/dist/sandbox/k8s/agent-context-route.d.ts +13 -0
  40. package/dist/sandbox/k8s/agent-context-route.js +21 -0
  41. package/dist/sandbox/k8s/agent-context-route.js.map +1 -0
  42. package/dist/sandbox/k8s/artifact-upload-route.d.ts +12 -0
  43. package/dist/sandbox/k8s/artifact-upload-route.js +40 -0
  44. package/dist/sandbox/k8s/artifact-upload-route.js.map +1 -0
  45. package/dist/sandbox/k8s/client.d.ts +22 -0
  46. package/dist/sandbox/k8s/client.js +35 -0
  47. package/dist/sandbox/k8s/client.js.map +1 -0
  48. package/dist/sandbox/k8s/egress-apply.d.ts +14 -0
  49. package/dist/sandbox/k8s/egress-apply.js +44 -0
  50. package/dist/sandbox/k8s/egress-apply.js.map +1 -0
  51. package/dist/sandbox/k8s/egress-ensurer.d.ts +37 -0
  52. package/dist/sandbox/k8s/egress-ensurer.js +54 -0
  53. package/dist/sandbox/k8s/egress-ensurer.js.map +1 -0
  54. package/dist/sandbox/k8s/egress-policy.d.ts +112 -0
  55. package/dist/sandbox/k8s/egress-policy.js +118 -0
  56. package/dist/sandbox/k8s/egress-policy.js.map +1 -0
  57. package/dist/sandbox/k8s/init-agent-context.d.ts +20 -0
  58. package/dist/sandbox/k8s/init-agent-context.js +35 -0
  59. package/dist/sandbox/k8s/init-agent-context.js.map +1 -0
  60. package/dist/sandbox/k8s/init-clone.d.ts +53 -0
  61. package/dist/sandbox/k8s/init-clone.js +114 -0
  62. package/dist/sandbox/k8s/init-clone.js.map +1 -0
  63. package/dist/sandbox/k8s/init-skills.d.ts +13 -0
  64. package/dist/sandbox/k8s/init-skills.js +28 -0
  65. package/dist/sandbox/k8s/init-skills.js.map +1 -0
  66. package/dist/sandbox/k8s/kubernetes-sandbox.d.ts +179 -0
  67. package/dist/sandbox/k8s/kubernetes-sandbox.js +418 -0
  68. package/dist/sandbox/k8s/kubernetes-sandbox.js.map +1 -0
  69. package/dist/sandbox/k8s/log-stream.d.ts +4 -0
  70. package/dist/sandbox/k8s/log-stream.js +43 -0
  71. package/dist/sandbox/k8s/log-stream.js.map +1 -0
  72. package/dist/sandbox/k8s/naming.d.ts +19 -0
  73. package/dist/sandbox/k8s/naming.js +35 -0
  74. package/dist/sandbox/k8s/naming.js.map +1 -0
  75. package/dist/sandbox/k8s/pod-lifecycle.d.ts +40 -0
  76. package/dist/sandbox/k8s/pod-lifecycle.js +151 -0
  77. package/dist/sandbox/k8s/pod-lifecycle.js.map +1 -0
  78. package/dist/sandbox/k8s/pod-status.d.ts +46 -0
  79. package/dist/sandbox/k8s/pod-status.js +83 -0
  80. package/dist/sandbox/k8s/pod-status.js.map +1 -0
  81. package/dist/sandbox/k8s/pod.d.ts +79 -0
  82. package/dist/sandbox/k8s/pod.js +115 -0
  83. package/dist/sandbox/k8s/pod.js.map +1 -0
  84. package/dist/sandbox/k8s/pvc.d.ts +20 -0
  85. package/dist/sandbox/k8s/pvc.js +26 -0
  86. package/dist/sandbox/k8s/pvc.js.map +1 -0
  87. package/dist/sandbox/k8s/quota.d.ts +34 -0
  88. package/dist/sandbox/k8s/quota.js +52 -0
  89. package/dist/sandbox/k8s/quota.js.map +1 -0
  90. package/dist/sandbox/k8s/reclaim.d.ts +50 -0
  91. package/dist/sandbox/k8s/reclaim.js +141 -0
  92. package/dist/sandbox/k8s/reclaim.js.map +1 -0
  93. package/dist/sandbox/k8s/resource-name.d.ts +33 -0
  94. package/dist/sandbox/k8s/resource-name.js +49 -0
  95. package/dist/sandbox/k8s/resource-name.js.map +1 -0
  96. package/dist/sandbox/k8s/run-agent-script.d.ts +60 -0
  97. package/dist/sandbox/k8s/run-agent-script.js +48 -0
  98. package/dist/sandbox/k8s/run-agent-script.js.map +1 -0
  99. package/dist/sandbox/k8s/run-id.d.ts +23 -0
  100. package/dist/sandbox/k8s/run-id.js +32 -0
  101. package/dist/sandbox/k8s/run-id.js.map +1 -0
  102. package/dist/sandbox/k8s/run-secrets.d.ts +75 -0
  103. package/dist/sandbox/k8s/run-secrets.js +115 -0
  104. package/dist/sandbox/k8s/run-secrets.js.map +1 -0
  105. package/dist/sandbox/k8s/secret.d.ts +20 -0
  106. package/dist/sandbox/k8s/secret.js +38 -0
  107. package/dist/sandbox/k8s/secret.js.map +1 -0
  108. package/dist/sandbox/k8s/skill-bundle-route.d.ts +10 -0
  109. package/dist/sandbox/k8s/skill-bundle-route.js +18 -0
  110. package/dist/sandbox/k8s/skill-bundle-route.js.map +1 -0
  111. package/dist/sandbox/k8s/skill-bundle.d.ts +36 -0
  112. package/dist/sandbox/k8s/skill-bundle.js +85 -0
  113. package/dist/sandbox/k8s/skill-bundle.js.map +1 -0
  114. package/dist/sandbox/k8s/sweep.d.ts +47 -0
  115. package/dist/sandbox/k8s/sweep.js +29 -0
  116. package/dist/sandbox/k8s/sweep.js.map +1 -0
  117. package/dist/sandbox/k8s/workspace-provisioner.d.ts +51 -0
  118. package/dist/sandbox/k8s/workspace-provisioner.js +64 -0
  119. package/dist/sandbox/k8s/workspace-provisioner.js.map +1 -0
  120. package/dist/sandbox/sandbox.d.ts +20 -1
  121. package/dist/sandbox/sandbox.js +22 -1
  122. package/dist/sandbox/sandbox.js.map +1 -1
  123. package/dist/state/workflow-run-store.d.ts +11 -0
  124. package/dist/state/workflow-run-store.js +19 -0
  125. package/dist/state/workflow-run-store.js.map +1 -1
  126. package/dist/workflows/admission.d.ts +19 -0
  127. package/dist/workflows/admission.js +81 -13
  128. package/dist/workflows/admission.js.map +1 -1
  129. package/dist/workflows/handlers/post-review.d.ts +21 -0
  130. package/dist/workflows/handlers/post-review.js +56 -13
  131. package/dist/workflows/handlers/post-review.js.map +1 -1
  132. package/dist/workflows/resume.js +6 -0
  133. package/dist/workflows/resume.js.map +1 -1
  134. package/dist/workflows/runner.d.ts +11 -2
  135. package/dist/workflows/runner.js +73 -15
  136. package/dist/workflows/runner.js.map +1 -1
  137. package/dist/workflows/simple.d.ts +13 -1
  138. package/dist/workflows/simple.js +46 -4
  139. package/dist/workflows/simple.js.map +1 -1
  140. package/package.json +21 -20
  141. package/skills/issue-triage/SKILL.md +17 -0
  142. package/workflows/cron-review.yaml +14 -1
  143. package/workflows/dependabot-pr-merge.yaml +14 -9
  144. package/workflows/issue-triage.yaml +6 -0
  145. package/workflows/prompts/dependabot-pr-merge.md +53 -11
  146. package/deploy/k8s/deployment.yaml +0 -63
  147. package/deploy/k8s/generic-device-plugin.yaml +0 -63
  148. package/deploy/k8s/namespace.yaml +0 -10
  149. package/deploy/k8s/pvc.yaml +0 -13
  150. package/deploy/k8s/service.yaml +0 -12
@@ -0,0 +1,43 @@
1
+ import { PassThrough } from "node:stream";
2
+ /** Stream a pod's stdout (follow) and forward complete lines. Resolves when the
3
+ * log stream closes (pod terminated). Mirrors the docker adapter's line buffer. */
4
+ export function streamPodLog(log, namespace, pod, container, onLine) {
5
+ return new Promise((resolve, reject) => {
6
+ const stream = new PassThrough();
7
+ let buf = "";
8
+ stream.setEncoding("utf-8");
9
+ stream.on("data", (chunk) => {
10
+ buf += chunk;
11
+ let nl;
12
+ while ((nl = buf.indexOf("\n")) >= 0) {
13
+ const line = buf.slice(0, nl);
14
+ buf = buf.slice(nl + 1);
15
+ if (line.length > 0) {
16
+ try {
17
+ onLine(line);
18
+ }
19
+ catch {
20
+ /* swallow listener errors */
21
+ }
22
+ }
23
+ }
24
+ });
25
+ stream.on("end", () => {
26
+ if (buf.length > 0) {
27
+ try {
28
+ onLine(buf);
29
+ }
30
+ catch {
31
+ /* swallow listener errors */
32
+ }
33
+ }
34
+ resolve();
35
+ });
36
+ stream.on("error", reject);
37
+ // follow: stream until the container terminates. log() resolves with an
38
+ // AbortController once the request is established; we don't need it here
39
+ // since resolution/rejection is driven by the stream's own end/error events.
40
+ log.log(namespace, pod, container, stream, { follow: true, pretty: false }).catch(reject);
41
+ });
42
+ }
43
+ //# sourceMappingURL=log-stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"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C;YACD,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC3B,wEAAwE;QACxE,yEAAyE;QACzE,6EAA6E;QAC7E,GAAG,CAAC,GAAG,CAAC,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAC5F,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { Rfc1123Label } from "./resource-name.js";
2
+ /** RFC-1123 label: lowercase alnum + '-', ≤63 chars, starts/ends alnum.
3
+ * We slug the taskId and append a short stable hash to guarantee uniqueness
4
+ * after truncation. Budget also reserves room for the creds/prompt Secret
5
+ * name suffix (see `SECRET_SUFFIX_BUDGET`), so the derived Secret name stays
6
+ * a valid RFC-1123 label too. Returns the `Rfc1123Label` itself, not a bare
7
+ * string: `secretNameFor` (secret.ts) takes exactly this type, so "a Secret
8
+ * name is only ever derived from a pod name" is a compile-time fact (F6),
9
+ * not a comment callers can route around with an arbitrary string. Callers
10
+ * that need the raw pod name (manifests, log-stream calls, …) read
11
+ * `.value`. */
12
+ export declare function podNameFor(taskId: string, phaseSuffix?: string): Rfc1123Label;
13
+ /** RFC-1123 label VALUE: `[a-zA-Z0-9._-]`, ≤63 chars. Unlike `podNameFor`'s
14
+ * label NAME rules this allows uppercase and `.` — but we lowercase anyway so
15
+ * the pod and PVC (and later the reclaim run-selector) compare byte-for-byte
16
+ * regardless of the source runId's casing. Its character class differs from
17
+ * {@link Rfc1123Label}'s NAME rules (dots/underscores stay), so it keeps its
18
+ * own sanitizer rather than routing through the shared slug. */
19
+ export declare function sanitizeLabelValue(v: string): string;
@@ -0,0 +1,35 @@
1
+ import { createHash } from "node:crypto";
2
+ import { Rfc1123Label } from "./resource-name.js";
3
+ /** Longest suffix `secretNameFor` (secret.ts) appends to a pod name:
4
+ * "-prompt" (7 chars). Reserve room for it (+1 margin) so a pod name at the
5
+ * cap never produces an invalid (>63-char) Secret name. `secretNameFor`'s
6
+ * `Rfc1123Label.withSuffix` call (F6) is the runtime backstop if this
7
+ * budget is ever wrong — it throws instead of silently emitting a >63-char
8
+ * Secret name. */
9
+ const SECRET_SUFFIX_BUDGET = 8;
10
+ /** RFC-1123 label: lowercase alnum + '-', ≤63 chars, starts/ends alnum.
11
+ * We slug the taskId and append a short stable hash to guarantee uniqueness
12
+ * after truncation. Budget also reserves room for the creds/prompt Secret
13
+ * name suffix (see `SECRET_SUFFIX_BUDGET`), so the derived Secret name stays
14
+ * a valid RFC-1123 label too. Returns the `Rfc1123Label` itself, not a bare
15
+ * string: `secretNameFor` (secret.ts) takes exactly this type, so "a Secret
16
+ * name is only ever derived from a pod name" is a compile-time fact (F6),
17
+ * not a comment callers can route around with an arbitrary string. Callers
18
+ * that need the raw pod name (manifests, log-stream calls, …) read
19
+ * `.value`. */
20
+ export function podNameFor(taskId, phaseSuffix = "run") {
21
+ const hash = createHash("sha1").update(`${taskId}/${phaseSuffix}`).digest("hex").slice(0, 8);
22
+ const maxLength = Rfc1123Label.MAX_LENGTH - 1 - hash.length - SECRET_SUFFIX_BUDGET;
23
+ const base = Rfc1123Label.slug(`${taskId}-${phaseSuffix}`, { prefix: "ll-", maxLength });
24
+ return base.withSuffix(hash);
25
+ }
26
+ /** RFC-1123 label VALUE: `[a-zA-Z0-9._-]`, ≤63 chars. Unlike `podNameFor`'s
27
+ * label NAME rules this allows uppercase and `.` — but we lowercase anyway so
28
+ * the pod and PVC (and later the reclaim run-selector) compare byte-for-byte
29
+ * regardless of the source runId's casing. Its character class differs from
30
+ * {@link Rfc1123Label}'s NAME rules (dots/underscores stay), so it keeps its
31
+ * own sanitizer rather than routing through the shared slug. */
32
+ export function sanitizeLabelValue(v) {
33
+ return v.toLowerCase().replace(/[^a-z0-9._-]/g, "-").slice(0, Rfc1123Label.MAX_LENGTH);
34
+ }
35
+ //# sourceMappingURL=naming.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"naming.js","sourceRoot":"","sources":["../../../src/sandbox/k8s/naming.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD;;;;;mBAKmB;AACnB,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B;;;;;;;;;gBASgB;AAChB,MAAM,UAAU,UAAU,CAAC,MAAc,EAAE,WAAW,GAAG,KAAK;IAC5D,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,GAAG,MAAM,IAAI,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAC7F,MAAM,SAAS,GAAG,YAAY,CAAC,UAAU,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,oBAAoB,CAAC;IACnF,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC,GAAG,MAAM,IAAI,WAAW,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;IACzF,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAC/B,CAAC;AAED;;;;;iEAKiE;AACjE,MAAM,UAAU,kBAAkB,CAAC,CAAS;IAC1C,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,eAAe,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,YAAY,CAAC,UAAU,CAAC,CAAC;AACzF,CAAC"}
@@ -0,0 +1,40 @@
1
+ import type { CoreV1Api } from "@kubernetes/client-node";
2
+ /**
3
+ * Resolve a finished pod to its real exit code + deadline flag. The log
4
+ * stream closing does not guarantee the API-visible status has left
5
+ * `Running` (kubelet status-sync lag), so we poll `readNamespacedPodStatus`
6
+ * until the pod is terminal (see {@link terminalResult}), then read the
7
+ * container's `terminated.exitCode`. The loop is bounded (~15 × 500ms ≈ 8s)
8
+ * so a stuck status never hangs the command; on exhaustion we fall back to
9
+ * the coarse phase-based result.
10
+ */
11
+ export declare function awaitPodResult(core: CoreV1Api, ns: string, name: string): Promise<{
12
+ exitCode: number;
13
+ timedOut: boolean;
14
+ }>;
15
+ /**
16
+ * Wait until the pod's container has started so the kubelet log endpoint is
17
+ * available. `Log.log(follow)` returns HTTP 400 while the container is still
18
+ * `waiting` (Pending / ContainerCreating / image pull), so streaming
19
+ * immediately after create races the scheduler. See {@link containerStartState}
20
+ * for what counts as "started" vs a fatal `waiting` reason — a terminal
21
+ * image/config error fails fast with its real reason rather than waiting out
22
+ * the budget, so the failure is debuggable instead of a cryptic 400. A failed
23
+ * clone initContainer is checked on every poll too (see
24
+ * {@link checkInitContainerFailure}) — otherwise the main container just sits
25
+ * at `PodInitializing` for the whole budget while the real `git clone`
26
+ * failure sits unreported in `initContainerStatuses`.
27
+ */
28
+ export declare function waitForContainerStart(core: CoreV1Api, ns: string, name: string): Promise<void>;
29
+ /**
30
+ * Poll after a successful pod delete until the API 404s it, so the RWO PVC
31
+ * (an RWO block/local StorageClass such as the cluster default allows only
32
+ * one attached node) is actually released before `dispose` returns — a
33
+ * sequential next-phase pod reusing the same PVC on a different node would
34
+ * otherwise race the still-attaching volume and hit Multi-Attach. A 404 on
35
+ * the very first poll (pod already gone)
36
+ * succeeds immediately. Best-effort like the delete above: any non-404
37
+ * read error is treated as "not yet confirmed gone" and just retried
38
+ * within the budget, never failing the caller's `dispose()`.
39
+ */
40
+ export declare function waitForPodGone(core: CoreV1Api, ns: string, name: string): Promise<void>;
@@ -0,0 +1,151 @@
1
+ import { ApiException } from "@kubernetes/client-node";
2
+ import { containerStartState, initContainerFailure, terminalResult } from "./pod-status.js";
3
+ /** Bound on the post-stream status poll: ~15 × 500ms ≈ 8s before the coarse
4
+ * phase-based fallback, so a lagging kubelet status never hangs a command. */
5
+ const POD_STATUS_POLL_ATTEMPTS = 15;
6
+ const POD_STATUS_POLL_INTERVAL_MS = 500;
7
+ /** Bound on the pre-stream "container started" poll. A cold node pulling the
8
+ * ~400 MB sandbox image straight from GHCR takes ~30s, and a burst of reviews
9
+ * lands pods on several cold nodes at once (plus scheduling + iSCSI attach) —
10
+ * 60s wasn't enough and pods were reaped mid-pull. ~180 × 1s ≈ 180s absorbs a
11
+ * cold first-node pull; a terminal pull/config error still fails fast within it
12
+ * (see FATAL_WAITING_REASONS in `pod-status.ts`), so the extra budget only
13
+ * helps a progressing pull. A cluster image mirror (Spegel) makes subsequent
14
+ * nodes pull from a LAN peer, so this budget is the fallback for the one node
15
+ * that pulls from GHCR. */
16
+ const POD_START_POLL_ATTEMPTS = 180;
17
+ const POD_START_POLL_INTERVAL_MS = 1000;
18
+ /** Bound on the post-delete "pod actually gone" poll (RWO Multi-Attach fix):
19
+ * a Pod deleted via the API isn't detached from its RWO PVC until it's
20
+ * truly gone, so a sequential next-phase pod on the same PVC (possibly a
21
+ * different node) can hit Multi-Attach if `dispose` returns too early.
22
+ * Budget ~30 × 1s ≈ 30s; on exhaustion `waitForPodGone` warns and returns
23
+ * anyway — never hang the run (the reclaim sweep, Plan 4, is the backstop). */
24
+ const POD_DELETE_POLL_ATTEMPTS = 30;
25
+ const POD_DELETE_POLL_INTERVAL_MS = 1000;
26
+ /** Promise-based delay — the one place the pod-lifecycle poll loops below wait
27
+ * between attempts, replacing four hand-rolled `new Promise((r) =>
28
+ * setTimeout(r, ms))` calls. */
29
+ function sleep(ms) {
30
+ return new Promise((resolve) => setTimeout(resolve, ms));
31
+ }
32
+ /**
33
+ * Resolve a finished pod to its real exit code + deadline flag. The log
34
+ * stream closing does not guarantee the API-visible status has left
35
+ * `Running` (kubelet status-sync lag), so we poll `readNamespacedPodStatus`
36
+ * until the pod is terminal (see {@link terminalResult}), then read the
37
+ * container's `terminated.exitCode`. The loop is bounded (~15 × 500ms ≈ 8s)
38
+ * so a stuck status never hangs the command; on exhaustion we fall back to
39
+ * the coarse phase-based result.
40
+ */
41
+ export async function awaitPodResult(core, ns, name) {
42
+ for (let attempt = 0; attempt < POD_STATUS_POLL_ATTEMPTS; attempt++) {
43
+ const pod = await core.readNamespacedPodStatus({ name, namespace: ns });
44
+ const result = terminalResult(pod.status);
45
+ if (result)
46
+ return result;
47
+ await sleep(POD_STATUS_POLL_INTERVAL_MS);
48
+ }
49
+ // Status never went terminal within the budget — coarse phase fallback.
50
+ const pod = await core.readNamespacedPodStatus({ name, namespace: ns });
51
+ return { exitCode: pod.status?.phase === "Succeeded" ? 0 : 1, timedOut: false };
52
+ }
53
+ /**
54
+ * Wait until the pod's container has started so the kubelet log endpoint is
55
+ * available. `Log.log(follow)` returns HTTP 400 while the container is still
56
+ * `waiting` (Pending / ContainerCreating / image pull), so streaming
57
+ * immediately after create races the scheduler. See {@link containerStartState}
58
+ * for what counts as "started" vs a fatal `waiting` reason — a terminal
59
+ * image/config error fails fast with its real reason rather than waiting out
60
+ * the budget, so the failure is debuggable instead of a cryptic 400. A failed
61
+ * clone initContainer is checked on every poll too (see
62
+ * {@link checkInitContainerFailure}) — otherwise the main container just sits
63
+ * at `PodInitializing` for the whole budget while the real `git clone`
64
+ * failure sits unreported in `initContainerStatuses`.
65
+ */
66
+ export async function waitForContainerStart(core, ns, name) {
67
+ let lastReason = "";
68
+ for (let attempt = 0; attempt < POD_START_POLL_ATTEMPTS; attempt++) {
69
+ const pod = await core.readNamespacedPodStatus({ name, namespace: ns });
70
+ await checkInitContainerFailure(core, ns, name, pod.status?.initContainerStatuses);
71
+ const state = containerStartState(pod.status);
72
+ // container has started (or already finished) — logs are available
73
+ if (state === "started")
74
+ return;
75
+ if (state !== "waiting") {
76
+ throw new Error(`k8s sandbox pod ${name} cannot start: ${state.fatal}` +
77
+ (state.message ? ` — ${state.message}` : ""));
78
+ }
79
+ const waiting = pod.status?.containerStatuses?.[0]?.state?.waiting;
80
+ lastReason = waiting?.reason ?? pod.status?.phase ?? "";
81
+ await sleep(POD_START_POLL_INTERVAL_MS);
82
+ }
83
+ const budgetSeconds = (POD_START_POLL_ATTEMPTS * POD_START_POLL_INTERVAL_MS) / 1000;
84
+ throw new Error(`k8s sandbox pod ${name} container did not start within ${budgetSeconds}s ` +
85
+ `(last state: ${lastReason || "unknown"})`);
86
+ }
87
+ /**
88
+ * Fail fast when the clone initContainer has failed or is stuck on a fatal
89
+ * pull/config error, instead of leaving the caller to wait out the full
90
+ * `waitForContainerStart` budget while the main container reports the
91
+ * uninformative `PodInitializing` (which is the NORMAL state while an
92
+ * initContainer is still running — not itself a failure). Delegates the
93
+ * decision to the pure {@link initContainerFailure}; only the terminated
94
+ * (non-zero exit) case fetches a log tail — a `waiting` container has no logs
95
+ * to show yet.
96
+ */
97
+ async function checkInitContainerFailure(core, ns, podName, initStatuses) {
98
+ const failure = initContainerFailure(initStatuses);
99
+ if (!failure)
100
+ return;
101
+ const failing = initStatuses?.find((init) => init.name === failure.name);
102
+ const logs = failing?.state?.terminated
103
+ ? await initContainerLogs(core, ns, podName, failure.name)
104
+ : "";
105
+ throw new Error(`k8s sandbox pod ${podName} init container "${failure.name}" ${failure.message}` +
106
+ (logs ? `\n--- ${failure.name} logs (tail) ---\n${logs}` : ""));
107
+ }
108
+ /**
109
+ * Best-effort tail of a terminated init container's logs, appended to the
110
+ * thrown error so the REAL failure (a git clone error — DNS, egress, PVC
111
+ * permission, auth) is visible instead of a bare `exit 128`. Never throws:
112
+ * a log-fetch failure just yields no extra detail.
113
+ */
114
+ async function initContainerLogs(core, ns, podName, container) {
115
+ try {
116
+ const raw = await core.readNamespacedPodLog({ name: podName, namespace: ns, container });
117
+ const text = typeof raw === "string" ? raw.trim() : "";
118
+ const MAX = 2000;
119
+ return text.length > MAX ? `…${text.slice(-MAX)}` : text;
120
+ }
121
+ catch {
122
+ return "";
123
+ }
124
+ }
125
+ /**
126
+ * Poll after a successful pod delete until the API 404s it, so the RWO PVC
127
+ * (an RWO block/local StorageClass such as the cluster default allows only
128
+ * one attached node) is actually released before `dispose` returns — a
129
+ * sequential next-phase pod reusing the same PVC on a different node would
130
+ * otherwise race the still-attaching volume and hit Multi-Attach. A 404 on
131
+ * the very first poll (pod already gone)
132
+ * succeeds immediately. Best-effort like the delete above: any non-404
133
+ * read error is treated as "not yet confirmed gone" and just retried
134
+ * within the budget, never failing the caller's `dispose()`.
135
+ */
136
+ export async function waitForPodGone(core, ns, name) {
137
+ for (let attempt = 0; attempt < POD_DELETE_POLL_ATTEMPTS; attempt++) {
138
+ try {
139
+ await core.readNamespacedPodStatus({ name, namespace: ns });
140
+ }
141
+ catch (err) {
142
+ if (err instanceof ApiException && err.code === 404)
143
+ return; // gone
144
+ }
145
+ await sleep(POD_DELETE_POLL_INTERVAL_MS);
146
+ }
147
+ const budgetSeconds = (POD_DELETE_POLL_ATTEMPTS * POD_DELETE_POLL_INTERVAL_MS) / 1000;
148
+ console.warn(`[k8s] pod ${name} still present ${budgetSeconds}s after delete — proceeding anyway ` +
149
+ `(a sequential pod on the same PVC may race the volume release).`);
150
+ }
151
+ //# sourceMappingURL=pod-lifecycle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pod-lifecycle.js","sourceRoot":"","sources":["../../../src/sandbox/k8s/pod-lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAEvD,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE5F;+EAC+E;AAC/E,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,2BAA2B,GAAG,GAAG,CAAC;AAExC;;;;;;;;4BAQ4B;AAC5B,MAAM,uBAAuB,GAAG,GAAG,CAAC;AACpC,MAAM,0BAA0B,GAAG,IAAI,CAAC;AAExC;;;;;gFAKgF;AAChF,MAAM,wBAAwB,GAAG,EAAE,CAAC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C5E,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,wBAAwB,EAAE,OAAO,EAAE,EAAE,CAAC;QACpE,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,uBAAuB,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,CAAC;QAC9D,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,GAAG,YAAY,YAAY,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG;gBAAE,OAAO,CAAC,OAAO;QACtE,CAAC;QACD,MAAM,KAAK,CAAC,2BAA2B,CAAC,CAAC;IAC3C,CAAC;IACD,MAAM,aAAa,GAAG,CAAC,wBAAwB,GAAG,2BAA2B,CAAC,GAAG,IAAI,CAAC;IACtF,OAAO,CAAC,IAAI,CACV,aAAa,IAAI,kBAAkB,aAAa,qCAAqC;QACnF,iEAAiE,CACpE,CAAC;AACJ,CAAC"}
@@ -0,0 +1,46 @@
1
+ import type { V1ContainerStatus, V1PodStatus } from "@kubernetes/client-node";
2
+ /** Container `waiting.reason`s that will never resolve on their own — fail fast
3
+ * with the reason instead of waiting out the whole start budget. */
4
+ export declare const FATAL_WAITING_REASONS: Set<string>;
5
+ /**
6
+ * Pure classifier for {@link awaitPodResult} (`pod-lifecycle.ts`): resolve a
7
+ * pod's status to its real exit code + deadline flag once it has gone
8
+ * terminal, or `undefined` while it's still running. "Terminal" means either
9
+ * the first container status reports `terminated`, or the pod phase itself is
10
+ * `Succeeded`/`Failed` (some terminal pods never populate `containerStatuses`).
11
+ * `timedOut` is true when either the pod-level or container-level reason is
12
+ * `DeadlineExceeded` (an `activeDeadlineSeconds` kill).
13
+ */
14
+ export declare function terminalResult(status?: V1PodStatus): {
15
+ exitCode: number;
16
+ timedOut: boolean;
17
+ } | undefined;
18
+ /**
19
+ * Pure classifier for {@link waitForContainerStart} (`pod-lifecycle.ts`):
20
+ * "started" means the container is `running`/`terminated` OR the pod already
21
+ * reached a terminal phase (a fast command can finish before the first poll)
22
+ * — the kubelet log endpoint is available either way. A `waiting` state whose
23
+ * reason is in {@link FATAL_WAITING_REASONS} (an image/config error that will
24
+ * never resolve on its own) classifies as fatal instead of "waiting", so the
25
+ * caller can fail fast with the real reason rather than waiting out the whole
26
+ * start budget.
27
+ */
28
+ export declare function containerStartState(status?: V1PodStatus): "started" | "waiting" | {
29
+ fatal: string;
30
+ message?: string;
31
+ };
32
+ /**
33
+ * Pure classifier for {@link checkInitContainerFailure} (`pod-lifecycle.ts`):
34
+ * the first init container that has either terminated non-zero or is stuck on
35
+ * a fatal `waiting.reason` (see {@link FATAL_WAITING_REASONS}) — `undefined`
36
+ * while every init container is still progressing normally (the NORMAL
37
+ * `PodInitializing` state is not itself a failure). `message` already reads
38
+ * as a complete clause ("failed (exit N): reason — detail" or "cannot start:
39
+ * reason — detail"); the caller prefixes it with the pod/container identity
40
+ * and — for the terminated case only — appends a best-effort log tail (a
41
+ * pure function can't fetch logs, so that I/O stays in the caller).
42
+ */
43
+ export declare function initContainerFailure(inits?: V1ContainerStatus[]): {
44
+ name: string;
45
+ message: string;
46
+ } | undefined;
@@ -0,0 +1,83 @@
1
+ /** Container `waiting.reason`s that will never resolve on their own — fail fast
2
+ * with the reason instead of waiting out the whole start budget. */
3
+ export const FATAL_WAITING_REASONS = new Set([
4
+ "ImagePullBackOff",
5
+ "ErrImagePull",
6
+ "InvalidImageName",
7
+ "CreateContainerConfigError",
8
+ "CreateContainerError",
9
+ ]);
10
+ /**
11
+ * Pure classifier for {@link awaitPodResult} (`pod-lifecycle.ts`): resolve a
12
+ * pod's status to its real exit code + deadline flag once it has gone
13
+ * terminal, or `undefined` while it's still running. "Terminal" means either
14
+ * the first container status reports `terminated`, or the pod phase itself is
15
+ * `Succeeded`/`Failed` (some terminal pods never populate `containerStatuses`).
16
+ * `timedOut` is true when either the pod-level or container-level reason is
17
+ * `DeadlineExceeded` (an `activeDeadlineSeconds` kill).
18
+ */
19
+ export function terminalResult(status) {
20
+ const terminated = status?.containerStatuses?.[0]?.state?.terminated;
21
+ const phase = status?.phase;
22
+ const isTerminal = terminated !== undefined || phase === "Succeeded" || phase === "Failed";
23
+ if (!isTerminal)
24
+ return undefined;
25
+ const timedOut = status?.reason === "DeadlineExceeded" || terminated?.reason === "DeadlineExceeded";
26
+ const exitCode = terminated ? terminated.exitCode : phase === "Succeeded" ? 0 : 1;
27
+ return { exitCode, timedOut };
28
+ }
29
+ /**
30
+ * Pure classifier for {@link waitForContainerStart} (`pod-lifecycle.ts`):
31
+ * "started" means the container is `running`/`terminated` OR the pod already
32
+ * reached a terminal phase (a fast command can finish before the first poll)
33
+ * — the kubelet log endpoint is available either way. A `waiting` state whose
34
+ * reason is in {@link FATAL_WAITING_REASONS} (an image/config error that will
35
+ * never resolve on its own) classifies as fatal instead of "waiting", so the
36
+ * caller can fail fast with the real reason rather than waiting out the whole
37
+ * start budget.
38
+ */
39
+ export function containerStartState(status) {
40
+ const state = status?.containerStatuses?.[0]?.state;
41
+ const phase = status?.phase;
42
+ if (state?.running || state?.terminated || phase === "Succeeded" || phase === "Failed") {
43
+ return "started";
44
+ }
45
+ const waiting = state?.waiting;
46
+ if (waiting?.reason && FATAL_WAITING_REASONS.has(waiting.reason)) {
47
+ return { fatal: waiting.reason, message: waiting.message };
48
+ }
49
+ return "waiting";
50
+ }
51
+ /**
52
+ * Pure classifier for {@link checkInitContainerFailure} (`pod-lifecycle.ts`):
53
+ * the first init container that has either terminated non-zero or is stuck on
54
+ * a fatal `waiting.reason` (see {@link FATAL_WAITING_REASONS}) — `undefined`
55
+ * while every init container is still progressing normally (the NORMAL
56
+ * `PodInitializing` state is not itself a failure). `message` already reads
57
+ * as a complete clause ("failed (exit N): reason — detail" or "cannot start:
58
+ * reason — detail"); the caller prefixes it with the pod/container identity
59
+ * and — for the terminated case only — appends a best-effort log tail (a
60
+ * pure function can't fetch logs, so that I/O stays in the caller).
61
+ */
62
+ export function initContainerFailure(inits) {
63
+ for (const init of inits ?? []) {
64
+ const name = init.name;
65
+ const terminated = init.state?.terminated;
66
+ if (terminated && terminated.exitCode !== 0) {
67
+ return {
68
+ name,
69
+ message: `failed (exit ${terminated.exitCode}): ${terminated.reason ?? "unknown"}` +
70
+ (terminated.message ? ` — ${terminated.message}` : ""),
71
+ };
72
+ }
73
+ const waiting = init.state?.waiting;
74
+ if (waiting?.reason && FATAL_WAITING_REASONS.has(waiting.reason)) {
75
+ return {
76
+ name,
77
+ message: `cannot start: ${waiting.reason}` + (waiting.message ? ` — ${waiting.message}` : ""),
78
+ };
79
+ }
80
+ }
81
+ return undefined;
82
+ }
83
+ //# sourceMappingURL=pod-status.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pod-status.js","sourceRoot":"","sources":["../../../src/sandbox/k8s/pod-status.ts"],"names":[],"mappings":"AAEA;qEACqE;AACrE,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC;IAC3C,kBAAkB;IAClB,cAAc;IACd,kBAAkB;IAClB,4BAA4B;IAC5B,sBAAsB;CACvB,CAAC,CAAC;AAEH;;;;;;;;GAQG;AACH,MAAM,UAAU,cAAc,CAC5B,MAAoB;IAEpB,MAAM,UAAU,GAAG,MAAM,EAAE,iBAAiB,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,UAAU,CAAC;IACrE,MAAM,KAAK,GAAG,MAAM,EAAE,KAAK,CAAC;IAC5B,MAAM,UAAU,GAAG,UAAU,KAAK,SAAS,IAAI,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,QAAQ,CAAC;IAC3F,IAAI,CAAC,UAAU;QAAE,OAAO,SAAS,CAAC;IAClC,MAAM,QAAQ,GACZ,MAAM,EAAE,MAAM,KAAK,kBAAkB,IAAI,UAAU,EAAE,MAAM,KAAK,kBAAkB,CAAC;IACrF,MAAM,QAAQ,GAAG,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,KAAK,WAAW,CAAC,CAAC,CAA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AAC,CAAC,CAAC,EAAE,CAAC;aACzD,CAAC;QACJ,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,EAAE,OAAO,CAAC;QACpC,IAAI,OAAO,EAAE,MAAM,IAAI,qBAAqB,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YACjE,OAAO;gBACL,IAAI;gBACJ,OAAO,EACL,iBAAiB,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACvF,CAAC;QACJ,CAAC;IACH,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC"}
@@ -0,0 +1,79 @@
1
+ import type { V1Container, V1Pod } from "@kubernetes/client-node";
2
+ import { type EgressMode } from "./egress-policy.js";
3
+ import type { RunId } from "./run-id.js";
4
+ export declare const PROMPT_MOUNT_DIR = "/lastlight";
5
+ export declare const PROMPT_FILE = "/lastlight/prompt";
6
+ /**
7
+ * Resource *requests* (no limits) stamped on every sandbox container so the pod
8
+ * declares a footprint the scheduler can bin-pack and a compute `ResourceQuota`
9
+ * (`requests.cpu` / `requests.memory`) can meter. Requests only — deliberately
10
+ * no limits, so a heavy clone/build isn't CPU-throttled or OOM-killed. The
11
+ * per-namespace concurrency ceiling stays the `ResourceQuota`'s job (see the
12
+ * Concurrency section of `spec/09-sandbox.md`), not a per-pod cap.
13
+ *
14
+ * The `agent` container carries the real workload; init containers (clone /
15
+ * skills) are short and light. Under quota accounting a pod's effective request
16
+ * per resource is `max(largest init container, sum of app containers)`, so the
17
+ * smaller init requests never inflate the pod's metered cost above the agent's.
18
+ */
19
+ export declare const SANDBOX_AGENT_REQUESTS: {
20
+ readonly cpu: "250m";
21
+ readonly memory: "512Mi";
22
+ };
23
+ export declare const SANDBOX_INIT_REQUESTS: {
24
+ readonly cpu: "100m";
25
+ readonly memory: "128Mi";
26
+ };
27
+ /** Label stamping a sandbox Pod/PVC with the run that owns it — the selector
28
+ * `reclaimSandbox` (Plan 5) matches on to find a run's objects. `pvc.ts`
29
+ * reuses this same constant so both objects carry an identical key. */
30
+ export declare const RUN_ID_LABEL = "lastlight.io/run-id";
31
+ /** Fixed in-pod mount root for the "workspace" volume — always the PVC/emptyDir
32
+ * ROOT, independent of `cwd` (which may be a `<root>/<repo>` subdir once a
33
+ * pre-clone init container has populated it). The clone initContainer mounts
34
+ * the same volume at this same path (see `kubernetes-sandbox.ts`), so the
35
+ * checkout it writes at `<WORKSPACE_DIR>/<repo>` lands exactly where the main
36
+ * container's `workingDir` expects it — mounting the volume at `cwd` instead
37
+ * would nest the checkout one level too deep. */
38
+ export declare const WORKSPACE_DIR = "/home/agent/workspace";
39
+ export interface PodSpecInput {
40
+ name: string;
41
+ namespace: string;
42
+ image: string;
43
+ command: string[];
44
+ /** Name of the per-run creds Secret (see `secret.ts`); env arrives via
45
+ * `envFrom`, never inline (inline env is `kubectl get pod -o yaml`-visible). */
46
+ envFromSecret: string;
47
+ cwd: string;
48
+ activeDeadlineSeconds: number;
49
+ runAsUser: number;
50
+ /** Name of the per-run prompt Secret; when set, mounts its `prompt` key as a file at
51
+ * `PROMPT_FILE` so the entrypoint can pipe it into stdin (Task 6). */
52
+ promptSecret?: string;
53
+ /** PVC-backed (per-(repo,PR), pre-cloned by an initContainer) or emptyDir
54
+ * (ephemeral, no pre-clone) workspace. */
55
+ workspace: {
56
+ kind: "pvc";
57
+ claimName: string;
58
+ } | {
59
+ kind: "emptyDir";
60
+ };
61
+ /** Runs before the "agent" container — currently just the minimal git clone
62
+ * (Task 5). Each gets the creds Secret's `envFrom` attached here so it
63
+ * shares the main container's `GIT_CONFIG_*` git auth. */
64
+ initContainers?: V1Container[];
65
+ /** Selects which CiliumNetworkPolicy governs this pod's egress — `strict`
66
+ * (the allowlist) or `open` (an `unrestricted_egress` phase). Stamped as the
67
+ * `egress-policy` label the policy's endpointSelector matches. */
68
+ egressPolicy: EgressMode;
69
+ /** When set, add a `skills` emptyDir shared with the skills initContainer and
70
+ * mount it at SKILLS_MOUNT_DIR in the agent container (the initContainer,
71
+ * passed in `initContainers`, unpacks the fetched bundle into it). */
72
+ skillsMount?: boolean;
73
+ /** Run identity (see `run-id.ts`); when set, its `matchLabels()` is stamped
74
+ * onto the Pod so `reclaimSandbox` (Plan 5) can select it back by the same
75
+ * label (F7 — stamp/select symmetry, enforced by `RunId` rather than by
76
+ * convention). */
77
+ runId?: RunId;
78
+ }
79
+ export declare function buildPodManifest(i: PodSpecInput): V1Pod;
@@ -0,0 +1,115 @@
1
+ import { EGRESS_POLICY_LABEL } from "./egress-policy.js";
2
+ import { SKILLS_MOUNT_DIR } from "./skill-bundle.js";
3
+ export const PROMPT_MOUNT_DIR = "/lastlight";
4
+ export const PROMPT_FILE = `${PROMPT_MOUNT_DIR}/prompt`;
5
+ /**
6
+ * Resource *requests* (no limits) stamped on every sandbox container so the pod
7
+ * declares a footprint the scheduler can bin-pack and a compute `ResourceQuota`
8
+ * (`requests.cpu` / `requests.memory`) can meter. Requests only — deliberately
9
+ * no limits, so a heavy clone/build isn't CPU-throttled or OOM-killed. The
10
+ * per-namespace concurrency ceiling stays the `ResourceQuota`'s job (see the
11
+ * Concurrency section of `spec/09-sandbox.md`), not a per-pod cap.
12
+ *
13
+ * The `agent` container carries the real workload; init containers (clone /
14
+ * skills) are short and light. Under quota accounting a pod's effective request
15
+ * per resource is `max(largest init container, sum of app containers)`, so the
16
+ * smaller init requests never inflate the pod's metered cost above the agent's.
17
+ */
18
+ export const SANDBOX_AGENT_REQUESTS = { cpu: "250m", memory: "512Mi" };
19
+ export const SANDBOX_INIT_REQUESTS = { cpu: "100m", memory: "128Mi" };
20
+ /** Label stamping a sandbox Pod/PVC with the run that owns it — the selector
21
+ * `reclaimSandbox` (Plan 5) matches on to find a run's objects. `pvc.ts`
22
+ * reuses this same constant so both objects carry an identical key. */
23
+ export const RUN_ID_LABEL = "lastlight.io/run-id";
24
+ /** Fixed in-pod mount root for the "workspace" volume — always the PVC/emptyDir
25
+ * ROOT, independent of `cwd` (which may be a `<root>/<repo>` subdir once a
26
+ * pre-clone init container has populated it). The clone initContainer mounts
27
+ * the same volume at this same path (see `kubernetes-sandbox.ts`), so the
28
+ * checkout it writes at `<WORKSPACE_DIR>/<repo>` lands exactly where the main
29
+ * container's `workingDir` expects it — mounting the volume at `cwd` instead
30
+ * would nest the checkout one level too deep. */
31
+ export const WORKSPACE_DIR = "/home/agent/workspace";
32
+ export function buildPodManifest(i) {
33
+ return {
34
+ apiVersion: "v1",
35
+ kind: "Pod",
36
+ metadata: {
37
+ name: i.name,
38
+ namespace: i.namespace,
39
+ labels: {
40
+ "app.kubernetes.io/managed-by": "lastlight",
41
+ "lastlight.io/component": "sandbox",
42
+ [EGRESS_POLICY_LABEL]: i.egressPolicy,
43
+ ...(i.runId ? i.runId.matchLabels() : {}),
44
+ },
45
+ },
46
+ spec: {
47
+ restartPolicy: "Never",
48
+ activeDeadlineSeconds: i.activeDeadlineSeconds,
49
+ automountServiceAccountToken: false, // an agent needs no k8s API access
50
+ securityContext: {
51
+ runAsNonRoot: true,
52
+ runAsUser: i.runAsUser,
53
+ // Chown mounted volumes to this group and add the process to it, so a
54
+ // non-root process can write the RWO PVC — which mounts root-owned, so
55
+ // without this the clone initContainer fails to create the checkout dir
56
+ // ("could not create work tree dir: Permission denied"). Reuses the
57
+ // runAsUser value as the group id (a standard non-root idiom).
58
+ fsGroup: i.runAsUser,
59
+ // Skip the recursive chown when the volume's group already matches —
60
+ // matters on a REUSED PVC (Plan 2 deferral): without it every run pays
61
+ // a slow recursive chown over the whole checkout just to re-confirm
62
+ // ownership it already has.
63
+ fsGroupChangePolicy: "OnRootMismatch",
64
+ seccompProfile: { type: "RuntimeDefault" },
65
+ },
66
+ volumes: [
67
+ i.workspace.kind === "pvc"
68
+ ? { name: "workspace", persistentVolumeClaim: { claimName: i.workspace.claimName } }
69
+ : { name: "workspace", emptyDir: {} },
70
+ ...(i.promptSecret
71
+ ? [
72
+ {
73
+ name: "prompt",
74
+ secret: {
75
+ secretName: i.promptSecret,
76
+ items: [{ key: "prompt", path: "prompt" }],
77
+ },
78
+ },
79
+ ]
80
+ : []),
81
+ ...(i.skillsMount ? [{ name: "skills", emptyDir: {} }] : []),
82
+ ],
83
+ ...(i.initContainers && i.initContainers.length
84
+ ? {
85
+ initContainers: i.initContainers.map((c) => ({
86
+ ...c,
87
+ envFrom: [{ secretRef: { name: i.envFromSecret } }],
88
+ resources: { requests: { ...SANDBOX_INIT_REQUESTS } },
89
+ })),
90
+ }
91
+ : {}),
92
+ containers: [
93
+ {
94
+ name: "agent",
95
+ image: i.image,
96
+ command: i.command,
97
+ workingDir: i.cwd,
98
+ resources: { requests: { ...SANDBOX_AGENT_REQUESTS } },
99
+ // env now arrives from the per-run creds Secret — never inline (kubectl-visible).
100
+ envFrom: [{ secretRef: { name: i.envFromSecret } }],
101
+ volumeMounts: [
102
+ { name: "workspace", mountPath: WORKSPACE_DIR },
103
+ ...(i.promptSecret ? [{ name: "prompt", mountPath: PROMPT_MOUNT_DIR, readOnly: true }] : []),
104
+ ...(i.skillsMount ? [{ name: "skills", mountPath: SKILLS_MOUNT_DIR }] : []),
105
+ ],
106
+ securityContext: {
107
+ allowPrivilegeEscalation: false,
108
+ capabilities: { drop: ["ALL"] },
109
+ },
110
+ },
111
+ ],
112
+ },
113
+ };
114
+ }
115
+ //# sourceMappingURL=pod.js.map