iobroker.assistant 1.4.12 → 1.4.14

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,17 @@ 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.14 (2026-11-07)
241
+ * (@GermanBluefox) ESPHome satellites, dialog mode: a satellite that does not listen again after an answer (it stopped the answer itself — stop word, tap) ends the mode instead of leaving it on while nobody listens; the log says how much of the answer was played
242
+
243
+ ### 1.4.13 (2026-11-07)
244
+ * (@GermanBluefox) If fullcalendar is installed, it must be 3.1.0 or later (the version with the event API that commands for later use)
245
+ * (@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
246
+ * (@GermanBluefox) Devices in a room hidden from the smart home (iot, `smartName: false`) are no longer listed without a room
247
+ * (@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
248
+ * (@GermanBluefox) The AI (cloud model and pi-agent) is told to answer in the language of the question
249
+ * (@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
250
+
240
251
  ### 1.4.12 (2026-11-05)
241
252
  * (@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
253
 
@@ -308,7 +319,7 @@ train it twice.
308
319
  * (@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
320
 
310
321
  ### 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)
322
+ * (@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
323
  * (@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
324
  * (@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
325
  * (@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
- {"version":3,"file":"media.js","sourceRoot":"","sources":["../../src/lib/media.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAkCH,wCAcC;AASD,wCA6BC;AAQD,sCA0BC;AAGD,oCAEC;AASD,oCAsBC;AAiBD,8CAQC;AAOD,sDAQC;AAOD,oCAQC;AASD,wCASC;AAUD,kCAGC;AA7ND,kFAAkF;AACrE,QAAA,UAAU,GAAG,CAAC,CAAC;AAE5B,yEAAyE;AAC5D,QAAA,gBAAgB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAEhD,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,YAAY,CAAC,CAAC,CAAC;AAEpF;;;;GAIG;AACH,SAAgB,cAAc,CAAC,GAAW;IACtC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QAC3E,OAAO,YAAY,CAAC;IACxB,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9G,OAAO,WAAW,CAAC;IACvB,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,aAAa,CAAC,IAAI,C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AQ,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 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":";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AAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;AACtD,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,WAAW,CAAC,QAAgB,EAAE,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"]}
@@ -220,6 +220,14 @@ const DIALOG_CHECK_MS = 5000;
220
220
  * open its microphone again — an ESPHome device does that only after a reply has played.
221
221
  */
222
222
  const DIALOG_PAUSE_MS = 250;
223
+ /**
224
+ * Dialog mode: once its reply has played, the device opens the microphone again by itself (ThirdReality after its
225
+ * "continue conversation delay", 0.5 s by default). Nothing within this time: it does not listen, and the mode goes off
226
+ * — its stop word or a tap ended the reply, or it lost the flag.
227
+ */
228
+ const DIALOG_REOPEN_MS = 6000;
229
+ /** A reply that ended this much earlier than its length was cut on the device. */
230
+ const REPLY_CUT_MS = 500;
223
231
  /** "Yes" and "no" as a button answer is passed on: the words of the satellite's language, which pi-agent also takes. */
224
232
  const YES_NO = {
225
233
  en: ['Yes', 'No'],
@@ -495,6 +503,11 @@ class EsphomeConnection {
495
503
  /** Dialog mode: when something was last recognised (or the mode was switched on). */
496
504
  dialogHeardAt = 0;
497
505
  dialogTimer = null;
506
+ /** Dialog mode: when the last reply went out (0 = none pending) and how long it is. */
507
+ dialogReplyAt = 0;
508
+ dialogReplyMs = 0;
509
+ /** Dialog mode: waits for the device to listen again after its reply, see {@link onReplyPlayed}. */
510
+ dialogReopenTimer = null;
498
511
  constructor(device, opts) {
499
512
  this.opts = opts;
500
513
  this.host = device.ip.trim();
@@ -598,6 +611,7 @@ class EsphomeConnection {
598
611
  clearInterval(this.dialogTimer);
599
612
  this.dialogTimer = null;
600
613
  }
614
+ this.cancelDialogReopen();
601
615
  }
602
616
  setOffline() {
603
617
  if (this.online) {
@@ -743,6 +757,7 @@ class EsphomeConnection {
743
757
  }
744
758
  this.opts.log.debug(`ESPHome ${this.deviceName}: playback finished (success=${message.getSuccess()})`);
745
759
  this.status('idle');
760
+ this.onReplyPlayed();
746
761
  return;
747
762
  case 'PingRequest':
748
763
  this.send(new esphomeProto_1.pb.PingResponse());
@@ -930,6 +945,7 @@ class EsphomeConnection {
930
945
  this.opts.log.debug(`ESPHome ${this.deviceName}: pipeline already running — ignoring wake`);
931
946
  return;
932
947
  }
948
+ this.cancelDialogReopen();
933
949
  const phrase = request.getWakeWordPhrase();
934
950
  if (Date.now() < this.ignoreFollowUpUntil) {
935
951
  // The microphone for the question a button already answered: close it at once. In this state the device
@@ -1031,6 +1047,8 @@ class EsphomeConnection {
1031
1047
  }
1032
1048
  this.dialogOn = on;
1033
1049
  this.dialogHeardAt = Date.now();
1050
+ this.dialogReplyAt = 0;
1051
+ this.cancelDialogReopen();
1034
1052
  if (this.dialogTimer) {
1035
1053
  clearInterval(this.dialogTimer);
1036
1054
  this.dialogTimer = null;
@@ -1039,17 +1057,20 @@ class EsphomeConnection {
1039
1057
  ? ` (nothing said for ${exports.DIALOG_IDLE_MS / 60_000} min)`
1040
1058
  : reason === 'stop'
1041
1059
  ? ' (the device was stopped)'
1042
- : reason === 'offline'
1043
- ? ' (offline)'
1044
- : reason === 'error'
1045
- ? ' (the voice pipeline failed)'
1046
- : '';
1060
+ : reason === 'no-listen'
1061
+ ? ' (the device did not listen again after the reply)'
1062
+ : reason === 'offline'
1063
+ ? ' (offline)'
1064
+ : reason === 'error'
1065
+ ? ' (the voice pipeline failed)'
1066
+ : '';
1047
1067
  this.opts.log.info(`ESPHome ${this.deviceName}: dialog mode ${on ? 'on' : 'off'}${why}`);
1048
1068
  this.opts.onDialog?.(this.deviceName, this.room, on, reason);
1049
1069
  if (on) {
1050
1070
  this.dialogTimer = setInterval(() => this.checkDialogIdle(), DIALOG_CHECK_MS);
1051
1071
  this.dialogTimer.unref();
1052
1072
  if (open && this.online && !this.capture && !this.runOpen) {
1073
+ this.noteDialogReply((open.pcm.length / 2 / open.sampleRate) * 1000);
1053
1074
  void this.announce(open.pcm, open.sampleRate, true, '', false).catch(e => this.opts.log.warn(`ESPHome ${this.deviceName}: opening the microphone failed — ${e.message}`));
1054
1075
  }
1055
1076
  return;
@@ -1073,6 +1094,46 @@ class EsphomeConnection {
1073
1094
  }
1074
1095
  this.setDialog(false, 'idle');
1075
1096
  }
1097
+ /** Dialog mode: a reply went out after which the device should listen again. */
1098
+ noteDialogReply(ms) {
1099
+ if (this.dialogOn) {
1100
+ this.dialogReplyAt = Date.now();
1101
+ this.dialogReplyMs = ms;
1102
+ }
1103
+ }
1104
+ /**
1105
+ * Dialog mode: the device reports that its reply has played (or was stopped). It should open the microphone again
1106
+ * now; one that does not — its stop word or a tap ended the reply, or it dropped the conversation flag — would
1107
+ * leave the mode on while nobody listens. A wake word during the reply starts a new run in time and keeps it.
1108
+ */
1109
+ onReplyPlayed() {
1110
+ if (!this.dialogOn || !this.dialogReplyAt || this.capture) {
1111
+ return;
1112
+ }
1113
+ const playedMs = Date.now() - this.dialogReplyAt;
1114
+ const replyMs = this.dialogReplyMs;
1115
+ this.dialogReplyAt = 0;
1116
+ this.cancelDialogReopen();
1117
+ this.dialogReopenTimer = setTimeout(() => {
1118
+ this.dialogReopenTimer = null;
1119
+ if (!this.dialogOn || this.capture || this.runOpen) {
1120
+ return;
1121
+ }
1122
+ const s = (ms) => (ms / 1000).toFixed(1);
1123
+ this.opts.log.info(playedMs + REPLY_CUT_MS < replyMs
1124
+ ? `ESPHome ${this.deviceName}: the device stopped the reply after ${s(playedMs)} of ${s(replyMs)} s ` +
1125
+ `(its stop word, a tap or its wake word) and does not listen again`
1126
+ : `ESPHome ${this.deviceName}: the device played the reply but did not open its microphone again`);
1127
+ this.setDialog(false, 'no-listen');
1128
+ }, DIALOG_REOPEN_MS);
1129
+ this.dialogReopenTimer.unref();
1130
+ }
1131
+ cancelDialogReopen() {
1132
+ if (this.dialogReopenTimer) {
1133
+ clearTimeout(this.dialogReopenTimer);
1134
+ this.dialogReopenTimer = null;
1135
+ }
1136
+ }
1076
1137
  /**
1077
1138
  * The device asks to end the conversation (`VoiceAssistantRequest{start:false}`): a button, or the wake word
1078
1139
  * said again while a request is running — that is how ESPHome's voice_assistant stops. While it waits for an
@@ -1337,6 +1398,7 @@ class EsphomeConnection {
1337
1398
  this.event(EVENT.TTS_END, { url });
1338
1399
  // linux-voice-assistant reads the flag here (ignoring "0"), ESPHome at INTENT_END
1339
1400
  this.event(EVENT.RUN_END, conversation);
1401
+ this.noteDialogReply((ttsPcm.length / 2 / sampleRate) * 1000);
1340
1402
  this.questionUntil = followUp ? Date.now() + (ttsPcm.length / 2 / sampleRate) * 1000 + QUESTION_OPEN_MS : 0;
1341
1403
  this.armPlaybackTimeout();
1342
1404
  }
@@ -1369,6 +1431,7 @@ class EsphomeConnection {
1369
1431
  this.event(EVENT.TTS_START, { text: '' });
1370
1432
  this.event(EVENT.TTS_END, { url });
1371
1433
  this.event(EVENT.RUN_END, { continue_conversation: '1' });
1434
+ this.noteDialogReply((clip.length / 2 / sampleRate) * 1000);
1372
1435
  this.armPlaybackTimeout();
1373
1436
  }
1374
1437
  catch (e) {