@vellumai/assistant 0.10.10-dev.202607202225.8cbddff → 0.10.10-dev.202607210046.e71ae24

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.202607210046.e71ae24",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -205,6 +205,15 @@ describe("AnthropicProvider — semantic reason stamping", () => {
205
205
  ),
206
206
  reason: "insufficient_credits",
207
207
  },
208
+ {
209
+ name: "daily-limit body code → daily_limit_reached (before insufficient_credits)",
210
+ error: new FakeAPIError(
211
+ 402,
212
+ '{"code":"daily_limit_reached","detail":"Daily credit limit reached"}',
213
+ anthropicBody("invalid_request_error"),
214
+ ),
215
+ reason: "daily_limit_reached",
216
+ },
208
217
  {
209
218
  name: "5xx → server_error",
210
219
  error: new FakeAPIError(503, "internal", anthropicBody("api_error")),
@@ -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
  });
@@ -1015,6 +1015,59 @@ describe("classifyConversationError", () => {
1015
1015
  expect(result.errorCategory).toBe("context_too_large");
1016
1016
  });
1017
1017
 
1018
+ it("routes reason=daily_limit_reached to PROVIDER_BILLING/daily_limit_reached under managed-proxy", () => {
1019
+ providerRoutingSources["vercel-ai-gateway"] = "managed-proxy";
1020
+ const err = new ProviderError(
1021
+ 'Vercel AI Gateway API error (402): {"code":"daily_limit_reached","detail":"Daily credit limit reached"}',
1022
+ "vercel-ai-gateway",
1023
+ 402,
1024
+ { reason: "daily_limit_reached" },
1025
+ );
1026
+
1027
+ const result = classifyConversationError(err, baseCtx);
1028
+
1029
+ expect(result.code).toBe("PROVIDER_BILLING");
1030
+ expect(result.errorCategory).toBe("daily_limit_reached");
1031
+ expect(result.retryable).toBe(false);
1032
+ expect(result.userMessage).toContain("daily credit limit");
1033
+ expect(result.userMessage).toContain("Billing settings");
1034
+ });
1035
+
1036
+ it("classifies reason=daily_limit_reached as daily_limit_reached even when the routing map says user-key", () => {
1037
+ // Per-connection platform-auth routes can leave the global routing map
1038
+ // at user-key; the stamped reason comes only from the platform proxy's
1039
+ // body code, so it must win regardless of the map.
1040
+ providerRoutingSources.openai = "user-key";
1041
+ const err = new ProviderError(
1042
+ 'OpenAI API error (402): {"code":"daily_limit_reached","detail":"Daily credit limit reached"}',
1043
+ "openai",
1044
+ 402,
1045
+ { reason: "daily_limit_reached" },
1046
+ );
1047
+
1048
+ const result = classifyConversationError(err, baseCtx);
1049
+
1050
+ expect(result.code).toBe("PROVIDER_BILLING");
1051
+ expect(result.errorCategory).toBe("daily_limit_reached");
1052
+ expect(result.retryable).toBe(false);
1053
+ });
1054
+
1055
+ it("keeps a plain managed-proxy 402 without the daily-limit code as credits_exhausted", () => {
1056
+ providerRoutingSources.openrouter = "managed-proxy";
1057
+ const err = new ProviderError(
1058
+ "OpenRouter API error (402): Payment Required",
1059
+ "openrouter",
1060
+ 402,
1061
+ { reason: "insufficient_credits" },
1062
+ );
1063
+
1064
+ const result = classifyConversationError(err, baseCtx);
1065
+
1066
+ expect(result.code).toBe("PROVIDER_BILLING");
1067
+ expect(result.errorCategory).toBe("credits_exhausted");
1068
+ expect(result.retryable).toBe(false);
1069
+ });
1070
+
1018
1071
  it("honors a stamped reason on a statusless ProviderError (no HTTP status)", () => {
1019
1072
  // SDK streaming failures throw with statusCode undefined but can still
1020
1073
  // carry a reason; it must classify semantically, not fall to the fallback.
@@ -1457,6 +1457,15 @@ describe("GeminiProvider", () => {
1457
1457
  }
1458
1458
  });
1459
1459
 
1460
+ test("maps a daily-limit 402 body code to daily_limit_reached", async () => {
1461
+ expect(
1462
+ await reasonForApiError(
1463
+ 402,
1464
+ '{"code":"daily_limit_reached","detail":"Daily credit limit reached"}',
1465
+ ),
1466
+ ).toBe("daily_limit_reached");
1467
+ });
1468
+
1460
1469
  test("maps 404 / NOT_FOUND to model_not_found", async () => {
1461
1470
  expect(
1462
1471
  await reasonForApiError(404, "NOT_FOUND: model does not exist"),
@@ -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();
@@ -562,6 +562,12 @@ function reasonToClassification(
562
562
  return managed
563
563
  ? managedBalanceClassification()
564
564
  : providerBillingClassification();
565
+ case "daily_limit_reached":
566
+ // The reason is stamped only from the platform proxy's
567
+ // `"code":"daily_limit_reached"` body, so it is authoritative on its
568
+ // own — the global routing map can lag per-connection platform-auth
569
+ // routes and must not downgrade this to the generic billing surface.
570
+ return dailyLimitClassification();
565
571
  case "overloaded":
566
572
  return providerOverloadedClassification();
567
573
  case "server_error":
@@ -698,6 +704,19 @@ function providerBillingClassification(): Omit<
698
704
  };
699
705
  }
700
706
 
707
+ function dailyLimitClassification(): Omit<
708
+ ClassifiedConversationError,
709
+ "debugDetails"
710
+ > {
711
+ return {
712
+ code: "PROVIDER_BILLING",
713
+ userMessage:
714
+ "You've hit your daily credit limit. Raise the limit in Billing settings to keep going today.",
715
+ retryable: false,
716
+ errorCategory: "daily_limit_reached",
717
+ };
718
+ }
719
+
701
720
  // Shared classification producers — single source of `code`+`errorCategory`
702
721
  // for both the reason short-circuit and the reason-less fallback.
703
722
 
@@ -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,
@@ -4,7 +4,10 @@ import { SYSTEM_PROMPT_CACHE_BOUNDARY } from "../../prompts/cache-boundary.js";
4
4
  import { isAbortReason } from "../../util/abort-reasons.js";
5
5
  import { ProviderError, type ProviderErrorReason } from "../../util/errors.js";
6
6
  import { getLogger } from "../../util/logger.js";
7
- import { INSUFFICIENT_CREDITS_PATTERNS } from "../../util/provider-error-patterns.js";
7
+ import {
8
+ DAILY_LIMIT_PATTERNS,
9
+ INSUFFICIENT_CREDITS_PATTERNS,
10
+ } from "../../util/provider-error-patterns.js";
8
11
  import { extractRetryAfterMs } from "../../util/retry.js";
9
12
  import { stripOrphanedSurrogatesDeep } from "../../util/unicode.js";
10
13
  import { base64Source, resolveMediaReferences } from "../media-resolve.js";
@@ -116,6 +119,11 @@ export function deriveAnthropicReason(
116
119
  const status = error.status;
117
120
  const haystack = `${apiType ?? ""} ${error.message ?? ""}`;
118
121
 
122
+ // The managed proxy's daily-limit 402 shares the status with generic credit
123
+ // exhaustion; match its specific body code first so it isn't swallowed.
124
+ if (DAILY_LIMIT_PATTERNS.some((re) => re.test(haystack))) {
125
+ return "daily_limit_reached";
126
+ }
119
127
  if (
120
128
  status === 402 ||
121
129
  INSUFFICIENT_CREDITS_PATTERNS.some((re) => re.test(haystack)) ||
@@ -9,6 +9,7 @@ import { SYSTEM_PROMPT_CACHE_BOUNDARY } from "../../prompts/cache-boundary.js";
9
9
  import { isAbortReason } from "../../util/abort-reasons.js";
10
10
  import { ProviderError, type ProviderErrorReason } from "../../util/errors.js";
11
11
  import { getLogger } from "../../util/logger.js";
12
+ import { DAILY_LIMIT_PATTERNS } from "../../util/provider-error-patterns.js";
12
13
  import { base64Source, resolveMediaReferences } from "../media-resolve.js";
13
14
  import { PROVIDER_CATALOG } from "../model-catalog.js";
14
15
  import { createStreamTimeout } from "../stream-timeout.js";
@@ -241,6 +242,11 @@ export function deriveGeminiReason(error: ApiError): ProviderErrorReason {
241
242
  const upper = message.toUpperCase();
242
243
  const hasName = (name: string) => upper.includes(name);
243
244
 
245
+ // The managed proxy's daily-limit 402 body carries a specific code; match it
246
+ // before the status branches so it isn't classified as a generic 4xx.
247
+ if (DAILY_LIMIT_PATTERNS.some((re) => re.test(message))) {
248
+ return "daily_limit_reached";
249
+ }
244
250
  if (status === 401 || hasName("UNAUTHENTICATED")) {
245
251
  return "invalid_credentials";
246
252
  }
@@ -560,9 +566,7 @@ export class GeminiProvider implements Provider {
560
566
  error.status,
561
567
  // Skip reason on caller-abort: abortReason already carries the intent
562
568
  // and short-circuits classification/retry (mirrors the Anthropic client).
563
- abortReason
564
- ? { abortReason }
565
- : { reason: deriveGeminiReason(error) },
569
+ abortReason ? { abortReason } : { reason: deriveGeminiReason(error) },
566
570
  );
567
571
  }
568
572
  throw new ProviderError(
@@ -375,6 +375,17 @@ describe("deriveReason", () => {
375
375
  expect(deriveReason(n(), 402)).toBe("insufficient_credits");
376
376
  });
377
377
 
378
+ test("daily-limit body code → daily_limit_reached (before insufficient_credits)", () => {
379
+ // Both are 402s from the managed proxy; the specific daily-limit code must
380
+ // win over the generic status-402 → insufficient_credits mapping.
381
+ expect(
382
+ deriveReason(
383
+ n({ rawBody: '{"code":"daily_limit_reached","detail":"limit"}' }),
384
+ 402,
385
+ ),
386
+ ).toBe("daily_limit_reached");
387
+ });
388
+
378
389
  test("billing prose → insufficient_credits", () => {
379
390
  expect(
380
391
  deriveReason(n({ message: "Your credit balance is too low" }), 400),
@@ -2,6 +2,7 @@ import type OpenAI from "openai";
2
2
 
3
3
  import type { ProviderErrorReason } from "../../util/errors.js";
4
4
  import {
5
+ DAILY_LIMIT_PATTERNS,
5
6
  INSUFFICIENT_CREDITS_PATTERNS,
6
7
  VISION_NOT_SUPPORTED_PATTERNS,
7
8
  } from "../../util/provider-error-patterns.js";
@@ -80,6 +81,12 @@ export function deriveReason(
80
81
  return "vision_unsupported";
81
82
  }
82
83
 
84
+ // The managed proxy's daily-limit 402 shares the status with generic credit
85
+ // exhaustion; match its specific body code first so it isn't swallowed.
86
+ if (DAILY_LIMIT_PATTERNS.some((re) => re.test(haystack))) {
87
+ return "daily_limit_reached";
88
+ }
89
+
83
90
  if (
84
91
  status === 402 ||
85
92
  INSUFFICIENT_CREDITS_PATTERNS.some((re) => re.test(haystack))
@@ -10,6 +10,7 @@
10
10
 
11
11
  import { beforeEach, describe, expect, mock, test } from "bun:test";
12
12
 
13
+ import { LLMSchema } from "../../../config/schemas/llm.js";
13
14
  import type { ConfiguredProviderOptions } from "../../../providers/provider-send-message.js";
14
15
  import type {
15
16
  ProviderResponse,
@@ -48,7 +49,16 @@ mock.module("../../../providers/provider-send-message.js", () => ({
48
49
  }),
49
50
  }));
50
51
 
52
+ // The route reads `llm` for the profile checks only; drive it from the test so
53
+ // a case can present an unusable profile without touching the workspace config.
54
+ let configuredLlm = LLMSchema.parse({});
55
+ mock.module("../../../config/loader.js", () => ({
56
+ getConfigReadOnly: () => ({ llm: configuredLlm }),
57
+ getConfig: () => ({ llm: configuredLlm }),
58
+ }));
59
+
51
60
  const { ROUTES } = await import("../inference-send-routes.js");
61
+ const { BadRequestError } = await import("../errors.js");
52
62
 
53
63
  function inferenceSendHandler() {
54
64
  const route = ROUTES.find((r) => r.operationId === "inference_send");
@@ -69,6 +79,7 @@ function baseResponse(overrides: Partial<ProviderResponse>): ProviderResponse {
69
79
  }
70
80
 
71
81
  beforeEach(() => {
82
+ configuredLlm = LLMSchema.parse({});
72
83
  nextResponse = baseResponse({});
73
84
  getConfiguredProviderOptions = undefined;
74
85
  sendMessageOptions = undefined;
@@ -133,3 +144,43 @@ describe("inference_send evidence", () => {
133
144
  expect(result.evidence).toBeUndefined();
134
145
  });
135
146
  });
147
+
148
+ // ---------------------------------------------------------------------------
149
+ // Existence in `llm.profiles` is weaker than usability: the resolver also
150
+ // requires the entry to be enabled and to carry its own provider + model, and
151
+ // silently falls through to this call site's `cost-optimized` default when it
152
+ // does not. The route must reject rather than answer from that other model.
153
+ // ---------------------------------------------------------------------------
154
+
155
+ describe("inference_send profile usability", () => {
156
+ const hermes = {
157
+ provider: "openrouter",
158
+ model: "nousresearch/hermes-3-llama-3.1-405b",
159
+ source: "user",
160
+ };
161
+
162
+ function rejection(entry: Record<string, unknown>): Promise<Error> {
163
+ configuredLlm = LLMSchema.parse({ profiles: { "hermes-405b": entry } });
164
+ return Promise.resolve(
165
+ inferenceSendHandler()({
166
+ body: { message: "hi", profile: "hermes-405b" },
167
+ }),
168
+ ).then(
169
+ () => new Error("expected the request to be rejected"),
170
+ (err: Error) => err,
171
+ );
172
+ }
173
+
174
+ test("rejects a disabled profile instead of running the managed default", async () => {
175
+ const err = await rejection({ ...hermes, status: "disabled" });
176
+ expect(err).toBeInstanceOf(BadRequestError);
177
+ expect(err.message).toContain("disabled");
178
+ expect(err.message).toContain("deepseek-v4-flash");
179
+ });
180
+
181
+ test("rejects a profile that lost its provider", async () => {
182
+ const err = await rejection({ model: hermes.model, source: "user" });
183
+ expect(err).toBeInstanceOf(BadRequestError);
184
+ expect(err.message).toContain("incomplete");
185
+ });
186
+ });
@@ -8,6 +8,8 @@
8
8
  import { z } from "zod";
9
9
 
10
10
  import { getEffectiveProfiles } from "../../config/default-profile-catalog.js";
11
+ import type { ResolutionFallbackReason } from "../../config/llm-resolver.js";
12
+ import { selectWinningProfile } from "../../config/llm-resolver.js";
11
13
  import { getConfigReadOnly } from "../../config/loader.js";
12
14
  import {
13
15
  extractAllText,
@@ -33,6 +35,8 @@ async function handleInferenceSend({ body = {} }: RouteHandlerArgs) {
33
35
  const profile = body.profile as string | undefined;
34
36
  const maxTokens = body.maxTokens as number | undefined;
35
37
 
38
+ const selectionSeed = crypto.randomUUID();
39
+
36
40
  // Validate --profile against the configured profile catalog.
37
41
  if (profile !== undefined) {
38
42
  const profiles = getEffectiveProfiles(getConfigReadOnly().llm?.profiles);
@@ -46,9 +50,34 @@ async function handleInferenceSend({ body = {} }: RouteHandlerArgs) {
46
50
  `Profile "${profile}" is not defined in llm.profiles.${hint}`,
47
51
  );
48
52
  }
53
+ // Existence is weaker than usability: the resolver additionally requires
54
+ // the entry to be enabled and to carry its own provider + model, and
55
+ // silently falls through to this call site's default (`cost-optimized`)
56
+ // when it does not. Ask the resolver itself so the check cannot drift from
57
+ // dispatch, and report the reason it gives rather than answering from a
58
+ // different — managed, billed — model than the caller named.
59
+ let reason: ResolutionFallbackReason | undefined;
60
+ const winner = selectWinningProfile("inference", getConfigReadOnly().llm, {
61
+ overrideProfile: profile,
62
+ selectionSeed,
63
+ onResolutionFallback: (info) => {
64
+ if (info.requested === profile) {
65
+ reason = info.reason;
66
+ }
67
+ },
68
+ });
69
+ if (winner.profileName !== profile) {
70
+ const target = winner.entry
71
+ ? `${winner.entry.provider}/${winner.entry.model}`
72
+ : "the code default";
73
+ throw new BadRequestError(
74
+ `Profile "${profile}" is ${reason ?? "unusable"} — the request would silently run on ` +
75
+ `${winner.profileName ?? "the call-site default"} (${target}) instead. ` +
76
+ `Fix the profile or omit it.`,
77
+ );
78
+ }
49
79
  }
50
80
 
51
- const selectionSeed = crypto.randomUUID();
52
81
  const provider = await getConfiguredProvider("inference", {
53
82
  overrideProfile: profile,
54
83
  selectionSeed,
@@ -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();
@@ -113,6 +113,7 @@ export type ProviderErrorReason =
113
113
  | "model_restricted"
114
114
  | "model_not_found"
115
115
  | "insufficient_credits"
116
+ | "daily_limit_reached"
116
117
  | "rate_limited"
117
118
  | "overloaded"
118
119
  | "context_overflow"
@@ -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
  /**
@@ -36,3 +36,9 @@ export const INSUFFICIENT_CREDITS_PATTERNS = [
36
36
  /insufficient.*credits?/i,
37
37
  /key limit (?:has been )?(?:exceeded|reached)/i,
38
38
  ];
39
+
40
+ // Managed-proxy daily-credit-limit rejection: the platform emits a 402 whose
41
+ // body carries `"code": "daily_limit_reached"`. More specific than the generic
42
+ // credit-exhaustion prose above — both are 402s from the same proxy — so
43
+ // classification sites must test this before INSUFFICIENT_CREDITS_PATTERNS.
44
+ export const DAILY_LIMIT_PATTERNS = [/"code"\s*:\s*"daily_limit_reached"/i];