iobroker.assistant 1.4.12 → 1.4.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.
package/README.md CHANGED
@@ -237,6 +237,14 @@ train it twice.
237
237
  Placeholder for the next version (at the beginning of the line):
238
238
  ### **WORK IN PROGRESS**
239
239
  -->
240
+ ### 1.4.13 (2026-11-07)
241
+ * (@GermanBluefox) If fullcalendar is installed, it must be 3.1.0 or later (the version with the event API that commands for later use)
242
+ * (@GermanBluefox) Devices renamed in the device list keep their room, type and all their states again (`@iobroker/mcp-server` 1.9.2): before, such a device lost its room, so "the light in the kitchen" was not understood, and a light lost the switch next to its level
243
+ * (@GermanBluefox) Devices in a room hidden from the smart home (iot, `smartName: false`) are no longer listed without a room
244
+ * (@GermanBluefox) The AI sees what each state of a device is (switch, level, read-only) and that the level alone does not switch a device on
245
+ * (@GermanBluefox) The AI (cloud model and pi-agent) is told to answer in the language of the question
246
+ * (@GermanBluefox) Videos: `ask` also takes `video: { url }` with an `iobdisk://` URL - the video stays on the disk of the sender's host (js-controller 8.0+) and can be read from any host. `{ adapter, path }` of the file storage still works. Telegram sends the URL
247
+
240
248
  ### 1.4.12 (2026-11-05)
241
249
  * (@GermanBluefox) ESPHome satellites: dialog mode — "ioBroker, Dialogmodus an" and the satellite listens again after every answer without the wake word (pauses are fine, nothing understood just listens on), "Dialogmodus aus" or a stop ends it, after 5 minutes without a request it ends by itself; state `satellites.<id>.dialog` shows and switches it
242
250
 
@@ -308,7 +316,7 @@ train it twice.
308
316
  * (@GermanBluefox) Chat: opens at the newest entry, and a new request scrolls into view again. Before, the tab often opened at the oldest entries
309
317
 
310
318
  ### 1.3.0 (2026-10-28)
311
- * (@GermanBluefox) Commands for later: "turn off the light in 2 hours" or "blinds to 50 % at 10 pm" becomes an event in the calendar (fullcalendar adapter) instead of running now; the AI can plan, list and cancel events. Before, the rule engine switched such commands at once. Needs a fullcalendar version with the new event API (after 3.0.5)
319
+ * (@GermanBluefox) Commands for later: "turn off the light in 2 hours" or "blinds to 50 % at 10 pm" becomes an event in the calendar (fullcalendar adapter) instead of running now; the AI can plan, list and cancel events. Before, the rule engine switched such commands at once. Needs a fullcalendar version with the new event API (>= 3.1.0)
312
320
  * (@GermanBluefox) Settings: the state of a presence row is picked with the object browser, the kind of a presence row or announcement target is a dropdown
313
321
  * (@GermanBluefox) New provider "System-wide AI settings (admin)", the default for new instances: provider, model and key come from the AI settings of the admin system settings, a change there restarts the instance. An instance without a key of its own takes them too
314
322
  * (@GermanBluefox) New provider OpenRouter
@@ -3,14 +3,16 @@
3
3
  * Pictures and videos that come with a question (`ask` with `images` / `video`, e.g. from Telegram).
4
4
  *
5
5
  * Pictures go to the cloud model as they are (base64, the vendors take JPEG/PNG/GIF/WebP). Videos are not looked at
6
- * yet: the sender keeps them in the ioBroker file storage and only says where, so a video never travels through the
7
- * message bus as base64.
6
+ * yet: the sender keeps them and only says where, so a video never travels through the message bus as base64 - on its
7
+ * disk as an `iobdisk://` URL (js-controller 8.0+, read with `adapter.readDiskFile(url)` from any host), or in the
8
+ * ioBroker file storage as `{ adapter, path }`.
8
9
  */
9
10
  Object.defineProperty(exports, "__esModule", { value: true });
10
11
  exports.MAX_IMAGE_BASE64 = exports.MAX_IMAGES = void 0;
11
12
  exports.sniffImageType = sniffImageType;
12
13
  exports.parseAskImages = parseAskImages;
13
14
  exports.parseAskVideo = parseAskVideo;
15
+ exports.videoLocation = videoLocation;
14
16
  exports.isVideoError = isVideoError;
15
17
  exports.redactImages = redactImages;
16
18
  exports.imageOnlyQuestion = imageOnlyQuestion;
@@ -81,7 +83,8 @@ function parseAskImages(raw) {
81
83
  return { images };
82
84
  }
83
85
  /**
84
- * Check the `video` of an `ask`: only a reference into the ioBroker file storage, never the content.
86
+ * Check the `video` of an `ask`: only a reference - an `iobdisk://` URL or a file of the ioBroker file storage -,
87
+ * never the content.
85
88
  *
86
89
  * @param raw the `video` field
87
90
  * @returns the reference, `null` without one, or the reason it is refused (e.g. base64 content)
@@ -91,27 +94,40 @@ function parseAskVideo(raw) {
91
94
  return null;
92
95
  }
93
96
  if (typeof raw !== 'object' || Array.isArray(raw)) {
94
- return { error: 'video must be { adapter, path } of the ioBroker file storage' };
97
+ return { error: 'video must be { url } (iobdisk://) or { adapter, path } of the ioBroker file storage' };
95
98
  }
96
99
  const v = raw;
97
100
  if ('data' in v) {
98
- return { error: 'a video is not sent as content - store it and send { adapter, path }' };
101
+ return { error: 'a video is not sent as content - store it and send { url } or { adapter, path }' };
99
102
  }
100
103
  const str = (x) => (typeof x === 'string' ? x.trim() : '');
101
104
  const num = (x) => typeof x === 'number' && Number.isFinite(x) && x >= 0 ? x : undefined;
105
+ const url = str(v.url);
106
+ if (url && !/^iobdisk:\/\/[^/]+\/[^/]+\/.+/.test(url)) {
107
+ return { error: 'video url must be iobdisk://<host>/<namespace>/<path>' };
108
+ }
102
109
  const ref = {
103
- adapter: str(v.adapter),
104
- path: str(v.path).replace(/^\/+/, ''),
110
+ url: url || undefined,
111
+ adapter: url ? '' : str(v.adapter),
112
+ path: url ? '' : str(v.path).replace(/^\/+/, ''),
105
113
  mimeType: str(v.mimeType) || undefined,
106
114
  durationSec: num(v.durationSec),
107
115
  size: num(v.size),
108
116
  error: str(v.error) || undefined,
109
117
  };
110
- if ((!ref.adapter || !ref.path) && !ref.error) {
111
- return { error: 'video without adapter and path' };
118
+ if (!ref.url && (!ref.adapter || !ref.path) && !ref.error) {
119
+ return { error: 'video without url or adapter and path' };
112
120
  }
113
121
  return ref;
114
122
  }
123
+ /**
124
+ * Where a video is, for the log, the journal and the trace: the `iobdisk://` URL or `adapter/path`.
125
+ *
126
+ * @param video the reference
127
+ */
128
+ function videoLocation(video) {
129
+ return video.url || (video.adapter ? `${video.adapter}/${video.path}` : `not stored: ${video.error || 'unknown'}`);
130
+ }
115
131
  /** Whether {@link parseAskVideo} refused the video */
116
132
  function isVideoError(v) {
117
133
  return !!v && !('adapter' in v);
@@ -1 +1 @@
1
- {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telegram).\n *\n * Pictures go to the cloud model as they are (base64, the vendors take JPEG/PNG/GIF/WebP). Videos are not looked at\n * yet: the sender keeps them in the ioBroker file storage and only says where, so a video never travels through the\n * message bus as base64.\n */\n\n/** A picture for the model: base64 without a `data:` prefix and its type. */\nexport interface ImageInput {\n data: string;\n mimeType: string;\n}\n\n/** Where the sender stored a video (ioBroker file storage), with what it knows about it. */\nexport interface VideoRef {\n /** File storage namespace, e.g. `telegram.0` */\n adapter: string;\n /** Path in it, e.g. `assistant/video_2026-11-04_10-00-00.mp4` */\n path: string;\n mimeType?: string;\n durationSec?: number;\n size?: number;\n /** Set when the sender could not store it (e.g. too big to download) */\n error?: string;\n}\n\n/** At most this many pictures per question (an album of Telegram has up to 10) */\nexport const MAX_IMAGES = 4;\n\n/** Largest picture as base64 text: Anthropic refuses images over 5 MB */\nexport const MAX_IMAGE_BASE64 = 5 * 1024 * 1024;\n\nconst IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/gif', 'image/webp']);\n\n/**\n * The type of a picture from its first bytes, `null` if it is none of the four the vendors take.\n *\n * @param buf the start of the file (16 bytes are enough)\n */\nexport function sniffImageType(buf: Buffer): string | null {\n if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {\n return 'image/jpeg';\n }\n if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) {\n return 'image/png';\n }\n if (buf.length >= 6 && /^GIF8[79]a$/.test(buf.subarray(0, 6).toString('latin1'))) {\n return 'image/gif';\n }\n if (buf.length >= 12 && buf.toString('latin1', 0, 4) === 'RIFF' && buf.toString('latin1', 8, 12) === 'WEBP') {\n return 'image/webp';\n }\n return null;\n}\n\n/**\n * Check the `images` of an `ask`: base64 of JPEG/PNG/GIF/WebP, at most {@link MAX_IMAGES} and\n * {@link MAX_IMAGE_BASE64} each. The type is taken from the content, not from what the sender says.\n *\n * @param raw the `images` field: a list of `{ data, mimeType? }` (one object or a bare base64 string work too)\n * @returns the pictures, or the reason they are refused\n */\nexport function parseAskImages(raw: unknown): { images: ImageInput[]; error?: string } {\n if (raw === undefined || raw === null || raw === '') {\n return { images: [] };\n }\n const list = Array.isArray(raw) ? raw : [raw];\n if (list.length > MAX_IMAGES) {\n return { images: [], error: `too many pictures (${list.length}, at most ${MAX_IMAGES})` };\n }\n const images: ImageInput[] = [];\n for (const item of list) {\n const data = typeof item === 'string' ? item : (item as { data?: unknown } | null)?.data;\n if (typeof data !== 'string' || !data) {\n return { images: [], error: 'a picture without data' };\n }\n // a data URL is fine as well\n const base64 = data.replace(/^data:[^;,]*;base64,/, '').replace(/\\s+/g, '');\n if (base64.length > MAX_IMAGE_BASE64) {\n return {\n images: [],\n error: `picture too big (${Math.round((base64.length * 3) / 4 / 1024)} KB, at most ${(MAX_IMAGE_BASE64 * 3) / 4 / 1024} KB)`,\n };\n }\n const mimeType = sniffImageType(Buffer.from(base64.slice(0, 32), 'base64'));\n if (!mimeType || !IMAGE_TYPES.has(mimeType)) {\n return { images: [], error: 'not a JPEG, PNG, GIF or WebP picture' };\n }\n images.push({ data: base64, mimeType });\n }\n return { images };\n}\n\n/**\n * Check the `video` of an `ask`: only a reference into the ioBroker file storage, never the content.\n *\n * @param raw the `video` field\n * @returns the reference, `null` without one, or the reason it is refused (e.g. base64 content)\n */\nexport function parseAskVideo(raw: unknown): VideoRef | null | { error: string } {\n if (raw === undefined || raw === null || raw === '') {\n return null;\n }\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n return { error: 'video must be { adapter, path } of the ioBroker file storage' };\n }\n const v = raw as Record<string, unknown>;\n if ('data' in v) {\n return { error: 'a video is not sent as content - store it and send { adapter, path }' };\n }\n const str = (x: unknown): string => (typeof x === 'string' ? x.trim() : '');\n const num = (x: unknown): number | undefined =>\n typeof x === 'number' && Number.isFinite(x) && x >= 0 ? x : undefined;\n const ref: VideoRef = {\n adapter: str(v.adapter),\n path: str(v.path).replace(/^\\/+/, ''),\n mimeType: str(v.mimeType) || undefined,\n durationSec: num(v.durationSec),\n size: num(v.size),\n error: str(v.error) || undefined,\n };\n if ((!ref.adapter || !ref.path) && !ref.error) {\n return { error: 'video without adapter and path' };\n }\n return ref;\n}\n\n/** Whether {@link parseAskVideo} refused the video */\nexport function isVideoError(v: VideoRef | null | { error: string }): v is { error: string } {\n return !!v && !('adapter' in v);\n}\n\n/**\n * Copy of a request / message list with the pictures replaced by a short note — for the trace and the debug log,\n * where hundreds of KB of base64 per round help nobody. Understands the OpenAI (`image_url` with a data URL) and the\n * Anthropic form (`image` with a base64 `source`).\n *\n * @param value what to copy\n */\nexport function redactImages<T>(value: T): T {\n const walk = (v: unknown): unknown => {\n if (Array.isArray(v)) {\n return v.map(walk);\n }\n if (!v || typeof v !== 'object') {\n return v;\n }\n const o = v as Record<string, any>;\n if (o.type === 'image_url' && typeof o.image_url?.url === 'string' && o.image_url.url.startsWith('data:')) {\n return { ...o, image_url: { ...o.image_url, url: imageNote(o.image_url.url) } };\n }\n if (o.type === 'image' && o.source?.type === 'base64' && typeof o.source.data === 'string') {\n return { ...o, source: { ...o.source, data: imageNote(o.source.data, o.source.media_type) } };\n }\n const out: Record<string, unknown> = {};\n for (const [k, x] of Object.entries(o)) {\n out[k] = walk(x);\n }\n return out;\n };\n return walk(value) as T;\n}\n\nfunction imageNote(data: string, mimeType?: string): string {\n const m = /^data:([^;,]+)/.exec(data);\n const base64 = data.replace(/^data:[^,]*,/, '');\n return `<${mimeType || m?.[1] || 'image'}, ${Math.round((base64.length * 3) / 4 / 1024)} KB>`;\n}\n\n/** Language of the texts below: de, ru, else en */\ntype Lang = string;\n\n/**\n * The question for pictures that came without one (a photo without caption).\n *\n * @param lang language of the answer\n * @param count number of pictures\n */\nexport function imageOnlyQuestion(lang: Lang, count = 1): string {\n if (lang === 'ru') {\n return count > 1 ? 'Что на этих картинках?' : 'Что на этой картинке?';\n }\n if (lang === 'de') {\n return count > 1 ? 'Was ist auf diesen Bildern?' : 'Was ist auf diesem Bild?';\n }\n return count > 1 ? 'What is in these pictures?' : 'What is in this picture?';\n}\n\n/**\n * The answer to a video that came without a question.\n *\n * @param lang language of the answer\n */\nexport function videoNotSupportedText(lang: Lang): string {\n if (lang === 'ru') {\n return 'Видео я пока смотреть не умею.';\n }\n if (lang === 'de') {\n return 'Videos kann ich mir noch nicht ansehen.';\n }\n return \"I can't watch videos yet.\";\n}\n\n/**\n * The answer to pictures when there is no cloud model to look at them.\n *\n * @param lang language of the answer\n */\nexport function noVisionText(lang: Lang): string {\n if (lang === 'ru') {\n return 'Картинки я могу посмотреть только с облачной моделью.';\n }\n if (lang === 'de') {\n return 'Bilder kann ich mir nur mit einem Cloud-Modell ansehen.';\n }\n return 'I can only look at pictures with a cloud model.';\n}\n\n/**\n * Note for the model in the user turn: what came along besides the text. A model that does not get the pictures\n * (an older pi-agent) at least knows that there were some.\n *\n * @param images number of pictures attached\n * @param video whether a video came along\n */\nexport function attachmentNote(images: number, video: boolean): string {\n const parts: string[] = [];\n if (images) {\n parts.push(images > 1 ? `${images} pictures are attached.` : 'A picture is attached.');\n }\n if (video) {\n parts.push('The user also sent a video, which you cannot watch yet - say so if the question is about it.');\n }\n return parts.length ? `(${parts.join(' ')})` : '';\n}\n\n/**\n * How the question is kept in the conversation history: the pictures are not repeated in later turns, a marker says\n * there were some.\n *\n * @param question the question\n * @param images number of pictures\n * @param video whether a video came along\n */\nexport function historyText(question: string, images: number, video: boolean): string {\n const marks = [images ? `[${images > 1 ? `${images} pictures` : 'picture'}]` : '', video ? '[video]' : ''];\n return [...marks, question].filter(Boolean).join(' ');\n}\n"]}
1
+ {"version":3,"file":"media.js","sourceRoot":"","sources":["../../src/lib/media.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAuCH,wCAcC;AASD,wCA6BC;AASD,sCA+BC;AAOD,sCAEC;AAGD,oCAEC;AASD,oCAsBC;AAiBD,8CAQC;AAOD,sDAQC;AAOD,oCAQC;A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MAAc,EAAE,KAAc;IACxE,MAAM,KAAK,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,WAAW,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC3G,OAAO,CAAC,GAAG,KAAK,EAAE,QAAQ,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * Pictures and videos that come with a question (`ask` with `images` / `video`, e.g. from Telegram).\n *\n * Pictures go to the cloud model as they are (base64, the vendors take JPEG/PNG/GIF/WebP). Videos are not looked at\n * yet: the sender keeps them and only says where, so a video never travels through the message bus as base64 - on its\n * disk as an `iobdisk://` URL (js-controller 8.0+, read with `adapter.readDiskFile(url)` from any host), or in the\n * ioBroker file storage as `{ adapter, path }`.\n */\n\n/** A picture for the model: base64 without a `data:` prefix and its type. */\nexport interface ImageInput {\n data: string;\n mimeType: string;\n}\n\n/** Where the sender stored a video, with what it knows about it. */\nexport interface VideoRef {\n /**\n * The file on the disk of the sender's host, e.g. `iobdisk://pi4/telegram.0/assistant/video_1.mp4`\n * (js-controller 8.0+: `adapter.readDiskFile(url)` reads it from any host). Empty `adapter` and `path` then.\n */\n url?: string;\n /** File storage namespace, e.g. `telegram.0` (empty with `url`) */\n adapter: string;\n /** Path in it, e.g. `assistant/video_2026-11-04_10-00-00.mp4` (empty with `url`) */\n path: string;\n mimeType?: string;\n durationSec?: number;\n size?: number;\n /** Set when the sender could not store it (e.g. too big to download) */\n error?: string;\n}\n\n/** At most this many pictures per question (an album of Telegram has up to 10) */\nexport const MAX_IMAGES = 4;\n\n/** Largest picture as base64 text: Anthropic refuses images over 5 MB */\nexport const MAX_IMAGE_BASE64 = 5 * 1024 * 1024;\n\nconst IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/gif', 'image/webp']);\n\n/**\n * The type of a picture from its first bytes, `null` if it is none of the four the vendors take.\n *\n * @param buf the start of the file (16 bytes are enough)\n */\nexport function sniffImageType(buf: Buffer): string | null {\n if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {\n return 'image/jpeg';\n }\n if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) {\n return 'image/png';\n }\n if (buf.length >= 6 && /^GIF8[79]a$/.test(buf.subarray(0, 6).toString('latin1'))) {\n return 'image/gif';\n }\n if (buf.length >= 12 && buf.toString('latin1', 0, 4) === 'RIFF' && buf.toString('latin1', 8, 12) === 'WEBP') {\n return 'image/webp';\n }\n return null;\n}\n\n/**\n * Check the `images` of an `ask`: base64 of JPEG/PNG/GIF/WebP, at most {@link MAX_IMAGES} and\n * {@link MAX_IMAGE_BASE64} each. The type is taken from the content, not from what the sender says.\n *\n * @param raw the `images` field: a list of `{ data, mimeType? }` (one object or a bare base64 string work too)\n * @returns the pictures, or the reason they are refused\n */\nexport function parseAskImages(raw: unknown): { images: ImageInput[]; error?: string } {\n if (raw === undefined || raw === null || raw === '') {\n return { images: [] };\n }\n const list = Array.isArray(raw) ? raw : [raw];\n if (list.length > MAX_IMAGES) {\n return { images: [], error: `too many pictures (${list.length}, at most ${MAX_IMAGES})` };\n }\n const images: ImageInput[] = [];\n for (const item of list) {\n const data = typeof item === 'string' ? item : (item as { data?: unknown } | null)?.data;\n if (typeof data !== 'string' || !data) {\n return { images: [], error: 'a picture without data' };\n }\n // a data URL is fine as well\n const base64 = data.replace(/^data:[^;,]*;base64,/, '').replace(/\\s+/g, '');\n if (base64.length > MAX_IMAGE_BASE64) {\n return {\n images: [],\n error: `picture too big (${Math.round((base64.length * 3) / 4 / 1024)} KB, at most ${(MAX_IMAGE_BASE64 * 3) / 4 / 1024} KB)`,\n };\n }\n const mimeType = sniffImageType(Buffer.from(base64.slice(0, 32), 'base64'));\n if (!mimeType || !IMAGE_TYPES.has(mimeType)) {\n return { images: [], error: 'not a JPEG, PNG, GIF or WebP picture' };\n }\n images.push({ data: base64, mimeType });\n }\n return { images };\n}\n\n/**\n * Check the `video` of an `ask`: only a reference - an `iobdisk://` URL or a file of the ioBroker file storage -,\n * never the content.\n *\n * @param raw the `video` field\n * @returns the reference, `null` without one, or the reason it is refused (e.g. base64 content)\n */\nexport function parseAskVideo(raw: unknown): VideoRef | null | { error: string } {\n if (raw === undefined || raw === null || raw === '') {\n return null;\n }\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n return { error: 'video must be { url } (iobdisk://) or { adapter, path } of the ioBroker file storage' };\n }\n const v = raw as Record<string, unknown>;\n if ('data' in v) {\n return { error: 'a video is not sent as content - store it and send { url } or { adapter, path }' };\n }\n const str = (x: unknown): string => (typeof x === 'string' ? x.trim() : '');\n const num = (x: unknown): number | undefined =>\n typeof x === 'number' && Number.isFinite(x) && x >= 0 ? x : undefined;\n const url = str(v.url);\n if (url && !/^iobdisk:\\/\\/[^/]+\\/[^/]+\\/.+/.test(url)) {\n return { error: 'video url must be iobdisk://<host>/<namespace>/<path>' };\n }\n const ref: VideoRef = {\n url: url || undefined,\n adapter: url ? '' : str(v.adapter),\n path: url ? '' : str(v.path).replace(/^\\/+/, ''),\n mimeType: str(v.mimeType) || undefined,\n durationSec: num(v.durationSec),\n size: num(v.size),\n error: str(v.error) || undefined,\n };\n if (!ref.url && (!ref.adapter || !ref.path) && !ref.error) {\n return { error: 'video without url or adapter and path' };\n }\n return ref;\n}\n\n/**\n * Where a video is, for the log, the journal and the trace: the `iobdisk://` URL or `adapter/path`.\n *\n * @param video the reference\n */\nexport function videoLocation(video: VideoRef): string {\n return video.url || (video.adapter ? `${video.adapter}/${video.path}` : `not stored: ${video.error || 'unknown'}`);\n}\n\n/** Whether {@link parseAskVideo} refused the video */\nexport function isVideoError(v: VideoRef | null | { error: string }): v is { error: string } {\n return !!v && !('adapter' in v);\n}\n\n/**\n * Copy of a request / message list with the pictures replaced by a short note — for the trace and the debug log,\n * where hundreds of KB of base64 per round help nobody. Understands the OpenAI (`image_url` with a data URL) and the\n * Anthropic form (`image` with a base64 `source`).\n *\n * @param value what to copy\n */\nexport function redactImages<T>(value: T): T {\n const walk = (v: unknown): unknown => {\n if (Array.isArray(v)) {\n return v.map(walk);\n }\n if (!v || typeof v !== 'object') {\n return v;\n }\n const o = v as Record<string, any>;\n if (o.type === 'image_url' && typeof o.image_url?.url === 'string' && o.image_url.url.startsWith('data:')) {\n return { ...o, image_url: { ...o.image_url, url: imageNote(o.image_url.url) } };\n }\n if (o.type === 'image' && o.source?.type === 'base64' && typeof o.source.data === 'string') {\n return { ...o, source: { ...o.source, data: imageNote(o.source.data, o.source.media_type) } };\n }\n const out: Record<string, unknown> = {};\n for (const [k, x] of Object.entries(o)) {\n out[k] = walk(x);\n }\n return out;\n };\n return walk(value) as T;\n}\n\nfunction imageNote(data: string, mimeType?: string): string {\n const m = /^data:([^;,]+)/.exec(data);\n const base64 = data.replace(/^data:[^,]*,/, '');\n return `<${mimeType || m?.[1] || 'image'}, ${Math.round((base64.length * 3) / 4 / 1024)} KB>`;\n}\n\n/** Language of the texts below: de, ru, else en */\ntype Lang = string;\n\n/**\n * The question for pictures that came without one (a photo without caption).\n *\n * @param lang language of the answer\n * @param count number of pictures\n */\nexport function imageOnlyQuestion(lang: Lang, count = 1): string {\n if (lang === 'ru') {\n return count > 1 ? 'Что на этих картинках?' : 'Что на этой картинке?';\n }\n if (lang === 'de') {\n return count > 1 ? 'Was ist auf diesen Bildern?' : 'Was ist auf diesem Bild?';\n }\n return count > 1 ? 'What is in these pictures?' : 'What is in this picture?';\n}\n\n/**\n * The answer to a video that came without a question.\n *\n * @param lang language of the answer\n */\nexport function videoNotSupportedText(lang: Lang): string {\n if (lang === 'ru') {\n return 'Видео я пока смотреть не умею.';\n }\n if (lang === 'de') {\n return 'Videos kann ich mir noch nicht ansehen.';\n }\n return \"I can't watch videos yet.\";\n}\n\n/**\n * The answer to pictures when there is no cloud model to look at them.\n *\n * @param lang language of the answer\n */\nexport function noVisionText(lang: Lang): string {\n if (lang === 'ru') {\n return 'Картинки я могу посмотреть только с облачной моделью.';\n }\n if (lang === 'de') {\n return 'Bilder kann ich mir nur mit einem Cloud-Modell ansehen.';\n }\n return 'I can only look at pictures with a cloud model.';\n}\n\n/**\n * Note for the model in the user turn: what came along besides the text. A model that does not get the pictures\n * (an older pi-agent) at least knows that there were some.\n *\n * @param images number of pictures attached\n * @param video whether a video came along\n */\nexport function attachmentNote(images: number, video: boolean): string {\n const parts: string[] = [];\n if (images) {\n parts.push(images > 1 ? `${images} pictures are attached.` : 'A picture is attached.');\n }\n if (video) {\n parts.push('The user also sent a video, which you cannot watch yet - say so if the question is about it.');\n }\n return parts.length ? `(${parts.join(' ')})` : '';\n}\n\n/**\n * How the question is kept in the conversation history: the pictures are not repeated in later turns, a marker says\n * there were some.\n *\n * @param question the question\n * @param images number of pictures\n * @param video whether a video came along\n */\nexport function historyText(question: string, images: number, video: boolean): string {\n const marks = [images ? `[${images > 1 ? `${images} pictures` : 'picture'}]` : '', video ? '[video]' : ''];\n return [...marks, question].filter(Boolean).join(' ');\n}\n"]}
package/build/main.js CHANGED
@@ -3357,7 +3357,7 @@ class Assistant extends adapter_core_1.Adapter {
3357
3357
  return;
3358
3358
  }
3359
3359
  const shown = (0, media_1.historyText)(question, attachments.images.length, !!attachments.video);
3360
- this.log.info(`${heard ? 'Voice Q' : 'Q'} (${obj.command} from ${caller}): ${shown}${attachments.video ? ` (video ${attachments.video.adapter}/${attachments.video.path})` : ''}`);
3360
+ this.log.info(`${heard ? 'Voice Q' : 'Q'} (${obj.command} from ${caller}): ${shown}${attachments.video ? ` (video ${(0, media_1.videoLocation)(attachments.video)})` : ''}`);
3361
3361
  this.setStateAsync('text.request', { val: shown, ack: true }).catch(() => { });
3362
3362
  this.setQuerySource(source);
3363
3363
  try {
@@ -3489,7 +3489,7 @@ class Assistant extends adapter_core_1.Adapter {
3489
3489
  const kb = (base64) => Math.round((base64.length * 3) / 4 / 1024);
3490
3490
  const parts = [
3491
3491
  images.length ? `${images.length} picture(s), ${images.reduce((n, i) => n + kb(i.data), 0)} KB` : '',
3492
- video ? `video ${video.adapter}/${video.path}` : '',
3492
+ video ? `video ${(0, media_1.videoLocation)(video)}` : '',
3493
3493
  ].filter(Boolean);
3494
3494
  this.journal?.step({
3495
3495
  stage: 'request',
@@ -3593,6 +3593,20 @@ class Assistant extends adapter_core_1.Adapter {
3593
3593
  }
3594
3594
  return 'If the request was only a command to switch devices on or off or to set them to a value, and everything worked, answer with the control marker [[DONE]] alone (a short beep plays instead of a sentence). For questions, errors or when you have something to tell, answer normally.';
3595
3595
  }
3596
+ /**
3597
+ * System-prompt instruction to answer in the language of the question: the system prompt, the device names and
3598
+ * the time/weather lines are in the configured language, and the model followed them instead of the question.
3599
+ */
3600
+ languageHint() {
3601
+ const lang = String(this.config.voiceLanguage || this.language || 'en');
3602
+ if (lang === 'ru') {
3603
+ return 'Всегда отвечай на том языке, на котором задан вопрос, даже если эти инструкции, имена устройств или данные на другом языке.';
3604
+ }
3605
+ if (lang === 'de') {
3606
+ return 'Antworte immer in der Sprache, in der die Frage gestellt wurde, auch wenn diese Anweisungen, die Gerätenamen oder die Daten in einer anderen Sprache sind.';
3607
+ }
3608
+ return 'Always answer in the language the question was asked in, even if these instructions, the device names or the data are in another language.';
3609
+ }
3596
3610
  /**
3597
3611
  * Length instruction for a request that came in by voice: the answer is cut at `ttsMaxChars` before it is
3598
3612
  * spoken, so the model is asked to stay within it. Empty for text requests (chat, Telegram, scripts) and
@@ -3794,7 +3808,7 @@ class Assistant extends adapter_core_1.Adapter {
3794
3808
  const { images, video } = this.attachments();
3795
3809
  if (!question.trim() && video) {
3796
3810
  // A video without a question: nothing looks at videos yet
3797
- this.log.info(`Video from '${source}' (${video.adapter}/${video.path}) not looked at: not supported yet.`);
3811
+ this.log.info(`Video from '${source}' (${(0, media_1.videoLocation)(video)}) not looked at: not supported yet.`);
3798
3812
  this.journal?.note({ tier: 'none' });
3799
3813
  this.journal?.step({ stage: 'none', title: 'A video without a question: videos are not looked at yet' });
3800
3814
  return (0, media_1.videoNotSupportedText)(this.answerLanguage());
@@ -3916,7 +3930,7 @@ class Assistant extends adapter_core_1.Adapter {
3916
3930
  // Only ask the model to emit the follow-up marker when satellites can actually re-open the mic.
3917
3931
  const followUp = this.config.voiceEnabled ? this.followUpHint() : '';
3918
3932
  const done = this.doneHint();
3919
- const parts = [this.config.systemPrompt || '', followUp, done, mem, ctx].filter(Boolean);
3933
+ const parts = [this.config.systemPrompt || '', this.languageHint(), followUp, done, mem, ctx].filter(Boolean);
3920
3934
  const sys = parts.length ? parts.join('\n\n') : undefined;
3921
3935
  this.log.info(`Cloud LLM [${this.agent.model || 'auto'}] (source='${source}', context=${history.length} turn(s)${mem ? ', memory' : ''}${weather ? ', weather' : ''}${this.presence?.configured ? ', presence' : ''}) — running tool loop…`);
3922
3936
  // Prepend the current date/time (and the weather line, if a source is configured) to the user turn —
@@ -3949,7 +3963,7 @@ class Assistant extends adapter_core_1.Adapter {
3949
3963
  time,
3950
3964
  weather: weather || undefined,
3951
3965
  images: images.length || undefined,
3952
- video: video ? `${video.adapter}/${video.path}` : undefined,
3966
+ video: video ? (0, media_1.videoLocation)(video) : undefined,
3953
3967
  },
3954
3968
  });
3955
3969
  try {
@@ -3982,7 +3996,7 @@ class Assistant extends adapter_core_1.Adapter {
3982
3996
  const followUp = this.config.voiceEnabled ? this.followUpHint() : '';
3983
3997
  // The device list maps names to state ids, so pi-agent can act without searching first. It is the
3984
3998
  // first to go when the instructions get too long — pi-agent can still search.
3985
- const { text: instructions, dropped } = (0, piAgent_1.composeInstructions)([this.config.systemPrompt || '', followUp, this.doneHint(), this.spokenLengthHint()], [this.buildMemoryContext(), await this.buildDeviceContext()]);
3999
+ const { text: instructions, dropped } = (0, piAgent_1.composeInstructions)([this.config.systemPrompt || '', this.languageHint(), followUp, this.doneHint(), this.spokenLengthHint()], [this.buildMemoryContext(), await this.buildDeviceContext()]);
3986
4000
  if (dropped) {
3987
4001
  this.log.debug(`pi-agent: ${dropped} context block(s) left out, the instructions would be too long.`);
3988
4002
  }
@@ -4108,7 +4122,7 @@ class Assistant extends adapter_core_1.Adapter {
4108
4122
  continue; // hidden from the LLM
4109
4123
  }
4110
4124
  const room = d.room ? `${d.room}, ` : '';
4111
- lines.push(`- ${d.name} (${room}${d.type}): ${ids.join(', ')}`);
4125
+ lines.push(`- ${d.name} (${room}${d.type}): ${this.describeControls(d)}`);
4112
4126
  }
4113
4127
  const lang = String(this.config.voiceLanguage || this.language || 'en');
4114
4128
  lines.push(...this.satelliteVolumeLines(lang));
@@ -4116,12 +4130,35 @@ class Assistant extends adapter_core_1.Adapter {
4116
4130
  return '';
4117
4131
  }
4118
4132
  const header = lang === 'ru'
4119
- ? 'Известные устройства — «имя (комната, тип): stateId». Используй эти stateId напрямую с set_state/get_states; вызывай list_devices только если нужного устройства здесь нет.'
4133
+ ? 'Известные устройства — «имя (комната, тип): элемент stateId [вид]; …». Используй эти stateId напрямую с set_state/get_states; вызывай list_devices только если нужного устройства здесь нет. Если у устройства есть выключатель [on/off] и уровень [number], то «включи» — это выключатель = true (уровень — только если его назвали): один уровень устройство не включает.'
4120
4134
  : lang === 'de'
4121
- ? 'Bekannte Geräte — "Name (Raum, Typ): stateId". Nutze diese stateIds direkt mit set_state/get_states; rufe list_devices nur, wenn ein Gerät hier fehlt.'
4122
- : 'Known devices — "name (room, type): stateId". Use these stateIds directly with set_state/get_states; only call list_devices if a needed device is missing here.';
4135
+ ? 'Bekannte Geräte — "Name (Raum, Typ): Element stateId [Art]; …". Nutze diese stateIds direkt mit set_state/get_states; rufe list_devices nur, wenn ein Gerät hier fehlt. Hat ein Gerät einen Schalter [on/off] und einen Level [number], heißt "einschalten" Schalter = true (den Level nur, wenn er genannt wurde): der Level allein schaltet das Gerät nicht ein.'
4136
+ : 'Known devices — "name (room, type): element stateId [kind]; …". Use these stateIds directly with set_state/get_states; only call list_devices if a needed device is missing here. If a device has a switch [on/off] and a level [number], "turn on" means switch = true (the level only if one was asked for): the level alone does not switch the device on.';
4123
4137
  return `${header}\n${lines.join('\n')}`;
4124
4138
  }
4139
+ /**
4140
+ * The controls of a device for the LLM: element, state id and what it is. A bare list of ids did not tell the
4141
+ * level from the switch next to it, and the model set only the level of a light, so it stayed off.
4142
+ */
4143
+ describeControls(d) {
4144
+ const seen = new Set();
4145
+ const parts = [];
4146
+ for (const [key, id] of Object.entries(d.controls)) {
4147
+ if (seen.has(id)) {
4148
+ continue;
4149
+ }
4150
+ seen.add(id);
4151
+ const kind = d.writable[key] === false
4152
+ ? 'read-only'
4153
+ : d.types[key] === 'boolean'
4154
+ ? 'on/off'
4155
+ : d.types[key] === 'number'
4156
+ ? 'number'
4157
+ : '';
4158
+ parts.push(kind ? `${key} ${id} [${kind}]` : `${key} ${id}`);
4159
+ }
4160
+ return parts.join('; ');
4161
+ }
4125
4162
  /**
4126
4163
  * The playback volume of every voice satellite as a line of the device list. Without it, "Lautstärke auf 50
4127
4164
  * Prozent" that the rules miss reaches the LLM (or pi-agent) with only the media devices of the room in view, and