@vellumai/assistant 0.10.10-dev.202607202225.8cbddff → 0.10.10-dev.202607202325.d24b0a4

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.
package/Dockerfile CHANGED
@@ -98,6 +98,7 @@ RUN apt-get update && apt-get install -y \
98
98
  openssl \
99
99
  procps \
100
100
  python3 \
101
+ python3-pip \
101
102
  sqlite3 \
102
103
  sudo \
103
104
  util-linux \
@@ -232,6 +233,30 @@ RUN printf '%s\n' \
232
233
  > /usr/local/bin/dpkg && \
233
234
  chmod +x /usr/local/bin/dpkg
234
235
 
236
+ # pip must persist like apt: on Kata-family runtimes the wrapper routes root
237
+ # installs into the persistent apt chroot.
238
+ RUN ln -s /app/assistant/docker-kata-pip.sh /usr/local/bin/pip && \
239
+ ln -s /app/assistant/docker-kata-pip.sh /usr/local/bin/pip3
240
+
241
+ # .pth files (pip install -e) are only processed for site directories, not
242
+ # PYTHONPATH entries — register the persistent chroot dirs as site dirs.
243
+ RUN cp /app/assistant/docker-sitecustomize.py /usr/lib/python3/dist-packages/sitecustomize.py
244
+
245
+ # Reword Debian's stock externally-managed refusal (shipped with python3, so
246
+ # this refusal exists on every runtime regardless): `python3 -m pip install`
247
+ # bypasses the pip wrappers, so its error must steer users to paths that
248
+ # actually work. Venv advice is correct everywhere; the bare `pip install`
249
+ # route only persists on kata-family machines, so it is worded conditionally.
250
+ RUN printf '%s\n' \
251
+ '[externally-managed]' \
252
+ 'Error=This Python environment is part of the container image and does not' \
253
+ ' persist. Create a virtualenv under a persistent directory instead, e.g.' \
254
+ ' `python3 -m venv /workspace/.venv`. On managed machines with a' \
255
+ ' persistent system root, `sudo pip install <pkg>` (not `python3 -m pip`)' \
256
+ ' also persists. Passing --break-system-packages installs into the image' \
257
+ ' rootfs and will NOT survive a machine save or container restart.' \
258
+ > "/usr/lib/python$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')/EXTERNALLY-MANAGED"
259
+
235
260
  # Ensure the CES bootstrap socket volume is writable by the non-root CES user.
236
261
  RUN mkdir -p /run/ces-bootstrap && chmod 777 /run/ces-bootstrap
237
262
 
@@ -248,6 +273,8 @@ RUN chmod +x \
248
273
  /app/assistant/docker-entrypoint.sh \
249
274
  /app/assistant/docker-init-apt-root.sh \
250
275
  /app/assistant/docker-kata-apt-env.sh \
276
+ /app/assistant/docker-kata-pip.sh \
277
+ /app/assistant/docker-kata-pip-chroot.sh \
251
278
  /app/assistant/docker-kata-runtime-family.sh \
252
279
  /usr/local/bin/vellum-block-volume-common.sh \
253
280
  /usr/local/bin/vellum-block-volume-init.sh \
@@ -15,6 +15,20 @@ _vellum_kata_append_path() {
15
15
  esac
16
16
  }
17
17
 
18
+ _vellum_kata_prepend_path() {
19
+ case ":${PATH:-}:" in
20
+ *":$1:"*) ;;
21
+ *) PATH="$1${PATH:+:${PATH}}" ;;
22
+ esac
23
+ }
24
+
25
+ _vellum_kata_append_pythonpath() {
26
+ case ":${PYTHONPATH:-}:" in
27
+ *":$1:"*) ;;
28
+ *) PYTHONPATH="${PYTHONPATH:+${PYTHONPATH}:}$1" ;;
29
+ esac
30
+ }
31
+
18
32
  _vellum_kata_prepend_library_path() {
19
33
  case ":${LD_LIBRARY_PATH:-}:" in
20
34
  *":$1:"*) ;;
@@ -38,4 +52,29 @@ _vellum_kata_prepend_library_path "${VELLUM_APT_DATA_ROOT}/usr/lib"
38
52
  _vellum_kata_prepend_library_path "${VELLUM_APT_DATA_ROOT}/usr/local/lib"
39
53
  export LD_LIBRARY_PATH
40
54
 
41
- unset -f _vellum_kata_append_path _vellum_kata_prepend_library_path
55
+ # Make python packages installed into the chroot importable by the image
56
+ # python: apt packages land in the unversioned dist-packages dir, chroot pip
57
+ # installs in the versioned /usr/local one. The chroot suite matches the image
58
+ # suite, so the image python's version selects the right pip dir. The pip dir
59
+ # must precede the apt dir, mirroring Debian's sys.path order, so a
60
+ # pip-upgraded package wins over an older apt one.
61
+ _vellum_kata_python_version="$(/usr/bin/python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || true)"
62
+ if [ -n "${_vellum_kata_python_version}" ]; then
63
+ _vellum_kata_append_pythonpath "${VELLUM_APT_DATA_ROOT}/usr/local/lib/python${_vellum_kata_python_version}/dist-packages"
64
+ fi
65
+ _vellum_kata_append_pythonpath "${VELLUM_APT_DATA_ROOT}/usr/lib/python3/dist-packages"
66
+ unset _vellum_kata_python_version
67
+ export PYTHONPATH
68
+
69
+ # The image bakes these under /home/assistant, which is ephemeral rootfs; on
70
+ # kata pods $HOME is the persistent data volume, so user-level installs there
71
+ # survive machine saves.
72
+ if [ -n "${HOME:-}" ]; then
73
+ export PYTHONUSERBASE="${HOME}/.python"
74
+ export BUN_INSTALL="${HOME}/.bun"
75
+ _vellum_kata_prepend_path "${BUN_INSTALL}/bin"
76
+ _vellum_kata_prepend_path "${PYTHONUSERBASE}/bin"
77
+ fi
78
+ export PATH
79
+
80
+ unset -f _vellum_kata_append_path _vellum_kata_prepend_path _vellum_kata_append_pythonpath _vellum_kata_prepend_library_path
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env sh
2
+ # Runs pip inside the persistent apt chroot. Must be invoked under `unshare -m`
3
+ # (see docker-kata-pip.sh): the bind mounts below live in a private mount
4
+ # namespace so they disappear with the pip process and are never visible to
5
+ # other processes — a lingering /data bind inside the chroot would create a
6
+ # path cycle (/data/system/data/system/...) for anything walking /data.
7
+ set -eu
8
+
9
+ DATA_ROOT="$1"
10
+ CALLER_CWD="$2"
11
+ PIP_BIN="$3"
12
+ shift 3
13
+
14
+ for dir in /workspace /data /tmp /var/tmp; do
15
+ [ -d "${dir}" ] || continue
16
+ mkdir -p "${DATA_ROOT}${dir}"
17
+ mount --bind "${dir}" "${DATA_ROOT}${dir}" 2>/dev/null || true
18
+ done
19
+
20
+ # chroot(1) always chdirs to /; restore the caller's cwd when it exists inside
21
+ # the chroot so relative paths keep working.
22
+ exec chroot "${DATA_ROOT}" /bin/sh -c 'cd "$1" 2>/dev/null || cd /; shift; exec "$@"' sh "${CALLER_CWD}" "${PIP_BIN}" "$@"
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env sh
2
+ # pip/pip3 wrapper (symlinked from /usr/local/bin). On Kata-family runtimes,
3
+ # root pip installs are routed into the persistent apt chroot — like the
4
+ # apt/apt-get/dpkg wrappers — so they survive machine saves; the image rootfs
5
+ # is discarded on every save. Non-root invocations fall through to the image
6
+ # pip, where PIP_BREAK_SYSTEM_PACKAGES makes pip default to a user install
7
+ # under the persistent PYTHONUSERBASE.
8
+ set -eu
9
+
10
+ PIP_NAME="$(basename "$0")"
11
+ case "${PIP_NAME}" in
12
+ pip | pip3) ;;
13
+ *) PIP_NAME="pip3" ;;
14
+ esac
15
+
16
+ . /app/assistant/docker-kata-runtime-family.sh
17
+
18
+ if ! vellum_is_kata_family_runtime; then
19
+ exec "/usr/bin/${PIP_NAME}" "$@"
20
+ fi
21
+
22
+ export PIP_BREAK_SYSTEM_PACKAGES=1
23
+ DATA_ROOT="${VELLUM_APT_DATA_ROOT:-/data/system}"
24
+
25
+ if [ "$(id -u)" = "0" ]; then
26
+ /app/assistant/docker-init-apt-root.sh
27
+ if [ -x "${DATA_ROOT}/bin/sh" ] && [ -f "${DATA_ROOT}/.rootfs-initialized" ] && ! grep -qs " ${DATA_ROOT} .*noexec" /proc/mounts; then
28
+ if [ ! -x "${DATA_ROOT}/usr/bin/${PIP_NAME}" ]; then
29
+ echo "Installing pip into the persistent system root (one-time setup)..." >&2
30
+ chroot "${DATA_ROOT}" sh -c "apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq python3-pip" >&2 || true
31
+ fi
32
+ if [ -x "${DATA_ROOT}/usr/bin/${PIP_NAME}" ]; then
33
+ # The helper bind-mounts caller-visible source dirs into the chroot
34
+ # (inside a private mount namespace) and restores the caller's cwd, so
35
+ # path-based installs (pip install ., -r requirements.txt) and --user
36
+ # installs into $PYTHONUSERBASE resolve to the same files as outside.
37
+ # Platform kata pods are privileged inside their per-assistant VM, so
38
+ # unshare -m works there; if this environment can't create a mount
39
+ # namespace, fall back to a bare chroot — index installs still persist,
40
+ # only caller-path installs lose visibility.
41
+ if unshare -m true 2>/dev/null; then
42
+ exec unshare -m /app/assistant/docker-kata-pip-chroot.sh "${DATA_ROOT}" "${PWD}" "/usr/bin/${PIP_NAME}" "$@"
43
+ fi
44
+ exec chroot "${DATA_ROOT}" /bin/sh -c 'cd "$1" 2>/dev/null || cd /; shift; exec "$@"' sh "${PWD}" "/usr/bin/${PIP_NAME}" "$@"
45
+ fi
46
+ fi
47
+ echo "Warning: persistent pip root unavailable; falling back to the image pip (installs will not survive a save)" >&2
48
+ fi
49
+
50
+ exec "/usr/bin/${PIP_NAME}" "$@"
@@ -0,0 +1,29 @@
1
+ """Vellum: expose the persistent apt/pip chroot as site directories.
2
+
3
+ Installed at /usr/lib/python3/dist-packages/sitecustomize.py in the assistant
4
+ image. PYTHONPATH (set by docker-kata-apt-env.sh and buildSanitizedEnv) makes
5
+ plain modules importable, but .pth files (e.g. from `pip install -e`) are only
6
+ processed for site directories, so the chroot dirs must also be registered
7
+ here. Virtualenvs without --system-site-packages never import this module,
8
+ which is intended — venvs are self-contained.
9
+ """
10
+
11
+ import os
12
+
13
+ if os.environ.get("VELLUM_SANDBOX_RUNTIME") in (
14
+ "kata",
15
+ "firecracker",
16
+ "cloud-hypervisor",
17
+ ):
18
+ import site
19
+ import sys
20
+
21
+ _root = os.environ.get("VELLUM_APT_DATA_ROOT", "/data/system")
22
+ _version = "%d.%d" % sys.version_info[:2]
23
+ # pip dir before apt dir, matching the PYTHONPATH precedence.
24
+ for _dir in (
25
+ "%s/usr/local/lib/python%s/dist-packages" % (_root, _version),
26
+ "%s/usr/lib/python3/dist-packages" % _root,
27
+ ):
28
+ if os.path.isdir(_dir):
29
+ site.addsitedir(_dir)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.10-dev.202607202225.8cbddff",
3
+ "version": "0.10.10-dev.202607202325.d24b0a4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -18,10 +18,21 @@ mock.module("../config/env.js", () => ({
18
18
 
19
19
  const FAKE_JPEG = Buffer.from("fake-jpeg-master-bytes");
20
20
  const FAKE_JPEG_B64 = FAKE_JPEG.toString("base64");
21
+ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
21
22
 
22
23
  mock.module("../util/image-conversion.js", () => ({
23
24
  convertImageToJpeg: () => FAKE_JPEG,
24
25
  isHeifImage: (bytes: Uint8Array) => bytes.length >= 12,
26
+ // Minimal stand-in for the real on-disk sniff (covered in
27
+ // image-conversion.test.ts) — only PNG, which is all these wiring cases need.
28
+ sniffImageFileMimeType: (path: string) => {
29
+ try {
30
+ const head = readFileSync(path).subarray(0, 4);
31
+ return head.equals(PNG_MAGIC) ? "image/png" : null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ },
25
36
  jpegFilenameFor: (filename: string) =>
26
37
  `${filename.replace(/\.[^./\\]+$/, "")}.jpg`,
27
38
  normalizeImageBytes: (mimeType: string, bytes: Uint8Array) =>
@@ -65,7 +76,7 @@ import {
65
76
  } from "../runtime/routes/attachment-routes.js";
66
77
  import type { RouteHandlerArgs } from "../runtime/routes/types.js";
67
78
  import { getWorkspaceDir } from "../util/platform.js";
68
- import { fakeHeifHeaderBytes } from "./heic-fixture.js";
79
+ import { fakeHeifHeaderBytes, PNG_1PX_BYTES } from "./heic-fixture.js";
69
80
 
70
81
  const uploadRoute = ROUTES.find((r) => r.operationId === "attachment_upload")!;
71
82
  const registerRoute = ROUTES.find(
@@ -227,4 +238,26 @@ describe("HEIC upload normalization wiring", () => {
227
238
  expect(existsSync(registeredPath)).toBe(true);
228
239
  expect(readFileSync(registeredPath).equals(HEIC_BYTES)).toBe(true);
229
240
  });
241
+
242
+ test("attachment register corrects a mislabeled image MIME", async () => {
243
+ // A PNG named .jpg — callers hand this path an extension-derived MIME, and
244
+ // the stored value becomes the media_type on every replay of the message.
245
+ const registerDir = join(getWorkspaceDir(), "register-fixtures");
246
+ mkdirSync(registerDir, { recursive: true });
247
+ const registeredPath = join(registerDir, "renamed.jpg");
248
+ writeFileSync(registeredPath, PNG_1PX_BYTES);
249
+
250
+ const result = (await registerRoute.handler(
251
+ jsonUploadArgs({
252
+ path: registeredPath,
253
+ mimeType: "image/jpeg",
254
+ filename: "renamed.jpg",
255
+ }),
256
+ )) as { id: string; mimeType: string };
257
+
258
+ expect(result.mimeType).toBe("image/png");
259
+ expect(getAttachmentById(result.id)?.mimeType).toBe("image/png");
260
+ // Only the label is corrected — the registered file is left in place.
261
+ expect(readFileSync(registeredPath).equals(PNG_1PX_BYTES)).toBe(true);
262
+ });
230
263
  });
@@ -6,6 +6,9 @@
6
6
  * gated on darwin.
7
7
  */
8
8
 
9
+ import { mkdtempSync, writeFileSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
9
12
  import { beforeAll, describe, expect, test } from "bun:test";
10
13
 
11
14
  import {
@@ -15,6 +18,7 @@ import {
15
18
  normalizeImageBase64,
16
19
  normalizeImageBytes,
17
20
  sniffBase64ImageMimeType,
21
+ sniffImageFileMimeType,
18
22
  sniffImageMimeType,
19
23
  } from "../util/image-conversion.js";
20
24
  import {
@@ -111,6 +115,20 @@ describe("sniffImageMimeType", () => {
111
115
  sniffBase64ImageMimeType(Buffer.from("not an image").toString("base64")),
112
116
  ).toBeNull();
113
117
  });
118
+
119
+ test("file variant sniffs from the on-disk head", () => {
120
+ const dir = mkdtempSync(join(tmpdir(), "vellum-sniff-file-"));
121
+ // A PNG named .jpg — what arrives when the MIME is extension-derived.
122
+ const pngPath = join(dir, "photo.jpg");
123
+ writeFileSync(pngPath, PNG_1PX_BYTES);
124
+ expect(sniffImageFileMimeType(pngPath)).toBe("image/png");
125
+
126
+ const textPath = join(dir, "notes.txt");
127
+ writeFileSync(textPath, "plain text content");
128
+ expect(sniffImageFileMimeType(textPath)).toBeNull();
129
+
130
+ expect(sniffImageFileMimeType(join(dir, "missing.png"))).toBeNull();
131
+ });
114
132
  });
115
133
 
116
134
  describe("normalizeImageBytes passthrough", () => {
@@ -123,12 +123,17 @@ describe("buildSanitizedEnv", () => {
123
123
  test("only includes Kata apt variables for Kata-family sandbox runtimes", () => {
124
124
  process.env.VELLUM_SANDBOX_RUNTIME = "gvisor";
125
125
  process.env.PATH = "/usr/bin";
126
+ process.env.HOME = "/data";
126
127
  process.env.VELLUM_APT_DATA_ROOT = "/data/system";
127
128
  process.env.LD_LIBRARY_PATH = "/host/lib";
129
+ process.env.PYTHONPATH = "/host/python";
128
130
 
129
131
  let env = buildSanitizedEnv();
130
132
  expect(env.VELLUM_APT_DATA_ROOT).toBeUndefined();
131
133
  expect(env.LD_LIBRARY_PATH).toBeUndefined();
134
+ expect(env.PYTHONPATH).toBeUndefined();
135
+ expect(env.PYTHONUSERBASE).toBeUndefined();
136
+ expect(env.BUN_INSTALL).toBeUndefined();
132
137
  expect(env.PATH.split(":")).not.toContain("/data/system/usr/bin");
133
138
 
134
139
  process.env.VELLUM_SANDBOX_RUNTIME = "kata";
@@ -141,6 +146,14 @@ describe("buildSanitizedEnv", () => {
141
146
  "/data/system/usr/local/lib",
142
147
  );
143
148
  expect(env.LD_LIBRARY_PATH.split(":")).not.toContain("/host/lib");
149
+ expect(env.PYTHONPATH.split(":")).toContain(
150
+ "/data/system/usr/lib/python3/dist-packages",
151
+ );
152
+ expect(env.PYTHONPATH.split(":")).not.toContain("/host/python");
153
+ expect(env.PYTHONUSERBASE).toBe("/data/.python");
154
+ expect(env.BUN_INSTALL).toBe("/data/.bun");
155
+ expect(env.PATH.split(":")).toContain("/data/.python/bin");
156
+ expect(env.PATH.split(":")).toContain("/data/.bun/bin");
144
157
 
145
158
  process.env.VELLUM_SANDBOX_RUNTIME = "cloud-hypervisor";
146
159
  env = buildSanitizedEnv();
@@ -24,6 +24,7 @@ import {
24
24
  jpegFilenameFor,
25
25
  normalizeImageBase64,
26
26
  normalizeImageBytes,
27
+ sniffImageFileMimeType,
27
28
  } from "../util/image-conversion.js";
28
29
  import { getLogger } from "../util/logger.js";
29
30
  import { getWorkspaceDir } from "../util/platform.js";
@@ -612,6 +613,13 @@ export function uploadAttachmentFromBytes(
612
613
  *
613
614
  * The file stays on disk; the attachment row stores an empty dataBase64 and
614
615
  * records the on-disk path in the `file_path` column.
616
+ *
617
+ * A declared image MIME that disagrees with the file's magic bytes is
618
+ * corrected before the row is written. Callers here pass a MIME they were
619
+ * handed (a signal's attachment metadata, a tool's `mimeType` argument), which
620
+ * is ultimately extension-derived — and the stored value becomes the
621
+ * `media_type` on every replay of the message, so a wrong one makes the
622
+ * provider reject the conversation on every later turn.
615
623
  */
616
624
  export function uploadFileBackedAttachment(
617
625
  filename: string,
@@ -620,7 +628,9 @@ export function uploadFileBackedAttachment(
620
628
  sizeBytes: number,
621
629
  ): StoredAttachment & { filePath: string } {
622
630
  const now = Date.now();
623
- const kind = classifyKind(mimeType);
631
+ const sniffed = sniffImageFileMimeType(filePath);
632
+ const storedMimeType = sniffed && sniffed !== mimeType ? sniffed : mimeType;
633
+ const kind = classifyKind(storedMimeType);
624
634
  const id = uuid();
625
635
  const db = getDb();
626
636
 
@@ -628,7 +638,7 @@ export function uploadFileBackedAttachment(
628
638
  .values({
629
639
  id,
630
640
  originalFilename: filename,
631
- mimeType,
641
+ mimeType: storedMimeType,
632
642
  sizeBytes,
633
643
  kind,
634
644
  dataBase64: "",
@@ -647,7 +657,7 @@ export function uploadFileBackedAttachment(
647
657
  return {
648
658
  id,
649
659
  originalFilename: filename,
650
- mimeType,
660
+ mimeType: storedMimeType,
651
661
  sizeBytes,
652
662
  kind,
653
663
  thumbnailBase64: null,
@@ -95,7 +95,10 @@ async function dispatchUserMessage(params: {
95
95
  resolvedAttachments.push({
96
96
  id: stored.id,
97
97
  filename: a.filename,
98
- mimeType: a.mimeType,
98
+ // The stored MIME, not the declared one: the store corrects a
99
+ // declared type that disagrees with the file's magic bytes, and the
100
+ // queued turn must send what the persisted row says.
101
+ mimeType: stored.mimeType,
99
102
  data: "",
100
103
  filePath: a.path,
101
104
  });
@@ -5,6 +5,8 @@
5
5
  *
6
6
  * Shared by the sandbox bash tool and skill sandbox runner.
7
7
  */
8
+ import { readdirSync } from "node:fs";
9
+
8
10
  import { getGatewayInternalBaseUrl } from "../../config/env.js";
9
11
  import { getDataDir, getWorkspaceDir } from "../../util/platform.js";
10
12
 
@@ -80,7 +82,12 @@ export const KATA_SAFE_ENV_VARS = [
80
82
  "VELLUM_APT_DATA_MIRROR",
81
83
  ] as const;
82
84
 
83
- export const KATA_INJECTED_ENV_VARS = ["LD_LIBRARY_PATH"] as const;
85
+ export const KATA_INJECTED_ENV_VARS = [
86
+ "LD_LIBRARY_PATH",
87
+ "PYTHONPATH",
88
+ "PYTHONUSERBASE",
89
+ "BUN_INSTALL",
90
+ ] as const;
84
91
 
85
92
  const KATA_APT_DATA_ROOT = "/data/system";
86
93
  const KATA_FAMILY_SANDBOX_RUNTIMES = new Set([
@@ -115,6 +122,35 @@ function kataAptLibraryPaths(dataRoot: string): string[] {
115
122
  ];
116
123
  }
117
124
 
125
+ // Python packages installed into the chroot: apt packages land in the
126
+ // unversioned dist-packages dir, chroot pip installs in versioned
127
+ // /usr/local/lib/python3.X dirs. Versions come from the image's /usr/lib
128
+ // (present before any install, so the path works within the same tool call
129
+ // that first runs pip) plus the chroot's /usr/local/lib as a fallback for
130
+ // any version drift between image and chroot.
131
+ function kataPythonPaths(dataRoot: string): string[] {
132
+ const versions = new Set<string>();
133
+ for (const libDir of ["/usr/lib", `${dataRoot}/usr/local/lib`]) {
134
+ try {
135
+ for (const entry of readdirSync(libDir)) {
136
+ if (/^python3\.\d+$/.test(entry)) {
137
+ versions.add(entry);
138
+ }
139
+ }
140
+ } catch {
141
+ // Directory missing (e.g. chroot not bootstrapped yet) — skip.
142
+ }
143
+ }
144
+ // pip's /usr/local dirs must precede the apt dir, mirroring Debian's
145
+ // sys.path order, so a pip-upgraded package wins over an older apt one.
146
+ return [
147
+ ...[...versions].map(
148
+ (version) => `${dataRoot}/usr/local/lib/${version}/dist-packages`,
149
+ ),
150
+ `${dataRoot}/usr/lib/python3/dist-packages`,
151
+ ];
152
+ }
153
+
118
154
  /**
119
155
  * Keys that buildSanitizedEnv always injects into the returned env,
120
156
  * independent of what is present in process.env.
@@ -159,6 +195,21 @@ export function buildSanitizedEnv(): Record<string, string> {
159
195
  undefined,
160
196
  kataAptLibraryPaths(kataAptDataRoot),
161
197
  );
198
+ env.PYTHONPATH = appendUniquePathEntries(
199
+ undefined,
200
+ kataPythonPaths(kataAptDataRoot),
201
+ );
202
+ // The image bakes these under ephemeral /home/assistant; $HOME is the
203
+ // persistent data volume on kata pods, so user-level installs survive
204
+ // machine saves.
205
+ if (env.HOME) {
206
+ env.PYTHONUSERBASE = `${env.HOME}/.python`;
207
+ env.BUN_INSTALL = `${env.HOME}/.bun`;
208
+ env.PATH = appendUniquePathEntries(
209
+ `${env.PYTHONUSERBASE}/bin:${env.BUN_INSTALL}/bin`,
210
+ env.PATH.split(":").filter(Boolean),
211
+ );
212
+ }
162
213
  }
163
214
  // Always inject an internal gateway base for local control-plane/API calls.
164
215
  const internalGatewayBase = getGatewayInternalBaseUrl();
@@ -16,10 +16,13 @@
16
16
  import { execFileSync } from "node:child_process";
17
17
  import { createHash } from "node:crypto";
18
18
  import {
19
+ closeSync,
19
20
  existsSync,
20
21
  mkdirSync,
22
+ openSync,
21
23
  readdirSync,
22
24
  readFileSync,
25
+ readSync,
23
26
  statSync,
24
27
  unlinkSync,
25
28
  writeFileSync,
@@ -273,6 +276,30 @@ export function sniffBase64ImageMimeType(dataBase64: string): string | null {
273
276
  return sniffImageMimeType(Buffer.from(dataBase64.slice(0, 16), "base64"));
274
277
  }
275
278
 
279
+ /**
280
+ * On-disk variant of {@link sniffImageMimeType}, for file-backed attachments
281
+ * that are never read into memory (recordings can exceed the upload limit).
282
+ * Reads only the 12-byte head. Returns null when the file is unreadable or the
283
+ * format is unrecognized, so callers keep the declared MIME.
284
+ */
285
+ export function sniffImageFileMimeType(filePath: string): string | null {
286
+ let fd: number;
287
+ try {
288
+ fd = openSync(filePath, "r");
289
+ } catch {
290
+ return null;
291
+ }
292
+ try {
293
+ const head = Buffer.alloc(12);
294
+ const bytesRead = readSync(fd, head, 0, 12, 0);
295
+ return sniffImageMimeType(head.subarray(0, bytesRead));
296
+ } catch {
297
+ return null;
298
+ } finally {
299
+ closeSync(fd);
300
+ }
301
+ }
302
+
276
303
  const HEIF_FILENAME_RE = /\.(heic|heif)$/i;
277
304
 
278
305
  /**