@ouro.bot/cli 0.1.0-alpha.1101 → 0.1.0-alpha.1103

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.
@@ -1,37 +1,4 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
3
  exports.BlueBubblesSendError = void 0;
37
4
  exports.createBlueBubblesClient = createBlueBubblesClient;
@@ -40,8 +7,7 @@ const config_1 = require("../../heart/config");
40
7
  const identity_1 = require("../../heart/identity");
41
8
  const bluebubbles_health_diagnostics_1 = require("../../heart/daemon/bluebubbles-health-diagnostics");
42
9
  const runtime_1 = require("../../nerves/runtime");
43
- const minimax_1 = require("../../heart/providers/minimax");
44
- const minimax_vlm_1 = require("../../heart/providers/minimax-vlm");
10
+ const understand_1 = require("../../heart/attachments/understand");
45
11
  const model_1 = require("./model");
46
12
  const media_1 = require("./media");
47
13
  const host_account_verifier_1 = require("./host-account-verifier");
@@ -701,28 +667,7 @@ function createBlueBubblesClient(config = (0, config_1.getBlueBubblesConfig)(),
701
667
  const agentConfig = (0, identity_1.loadAgentConfig)();
702
668
  const chatModel = agentConfig.humanFacing.model;
703
669
  const chatProvider = agentConfig.humanFacing.provider;
704
- const vlmDescribe = async (params) => {
705
- if (chatProvider !== "minimax") {
706
- throw new Error("VLM fallback requires a minimax credential for this agent — " +
707
- "configure one or switch to a vision-capable chat model");
708
- }
709
- const { readProviderCredentialRecord } = await Promise.resolve().then(() => __importStar(require("../../heart/provider-credentials")));
710
- const credential = await readProviderCredentialRecord((0, identity_1.getAgentName)(), "minimax");
711
- const apiKey = credential.ok ? credential.record.credentials.apiKey : undefined;
712
- if (!apiKey) {
713
- throw new Error("VLM fallback: minimax API key not found in the agent vault — " +
714
- "run `ouro auth --agent <agent> --provider minimax`");
715
- }
716
- return (0, minimax_vlm_1.minimaxVlmDescribe)({
717
- apiKey: String(apiKey),
718
- prompt: params.prompt,
719
- imageDataUrl: params.imageDataUrl,
720
- baseURL: minimax_1.MINIMAX_PROVIDER_BASE_URL,
721
- attachmentGuid: params.attachmentGuid,
722
- mimeType: params.mimeType,
723
- chatModel: params.chatModel,
724
- });
725
- };
670
+ const vlmDescribe = (params) => (0, understand_1.describeImage)((0, identity_1.getAgentName)(), params);
726
671
  // VLM prompt context wants the user's raw inbound text — NOT
727
672
  // the agent-facing rendering, which now carries the attachment
728
673
  // marker after the B2 fix. Pull it from the source payload.
@@ -35,28 +35,19 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.downloadBlueBubblesAttachment = exports.VLM_TEXT_WRAPPERS = void 0;
37
37
  exports.hydrateBlueBubblesAttachments = hydrateBlueBubblesAttachments;
38
- const node_child_process_1 = require("node:child_process");
39
38
  const fs = __importStar(require("node:fs/promises"));
40
39
  const os = __importStar(require("node:os"));
41
40
  const path = __importStar(require("node:path"));
42
41
  const runtime_1 = require("../../nerves/runtime");
43
42
  const identity_1 = require("../../heart/identity");
43
+ const transcribe_audio_1 = require("../../heart/attachments/transcribe-audio");
44
+ const understand_1 = require("../../heart/attachments/understand");
44
45
  const model_capabilities_1 = require("../../heart/model-capabilities");
45
46
  const image_normalize_1 = require("../../heart/attachments/image-normalize");
46
47
  const store_1 = require("../../heart/attachments/store");
47
48
  const bluebubbles_1 = require("../../heart/attachments/sources/bluebubbles");
48
49
  const attachment_download_1 = require("./attachment-download");
49
- // Pin the exact wrapper strings so tests and code read from one source.
50
- exports.VLM_TEXT_WRAPPERS = {
51
- description: (desc) => `[image description: ${desc}]`,
52
- failure: (reason) => `[image description failed: ${reason}]`,
53
- };
54
- // D3 prompt template. Included here (not templated out) because the contract
55
- // is load-bearing — see planning doc section D3 and AX-4.
56
- function buildVlmPrompt(userText) {
57
- const body = userText ?? "";
58
- return `User message: "${body}"\n\nDescribe this image in detail, focusing on anything relevant to what the user said above.\nInclude any text visible in the image verbatim.`;
59
- }
50
+ exports.VLM_TEXT_WRAPPERS = understand_1.IMAGE_DESCRIPTION_TEXT;
60
51
  const AUDIO_EXTENSIONS = new Set([".mp3", ".wav", ".m4a", ".caf", ".ogg"]);
61
52
  const AUDIO_EXTENSION_BY_CONTENT_TYPE = {
62
53
  "audio/wav": ".wav",
@@ -78,19 +69,6 @@ const AUDIO_INPUT_FORMAT_BY_EXTENSION = {
78
69
  ".wav": "wav",
79
70
  ".mp3": "mp3",
80
71
  };
81
- const WHISPER_CPP_FORMULA = "whisper-cpp";
82
- const WHISPER_CPP_MODEL_NAME = "ggml-base.en.bin";
83
- const WHISPER_CPP_MODEL_URL = `https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${WHISPER_CPP_MODEL_NAME}`;
84
- // Lazy — getAgentToolsRoot() requires identity to be resolved, which isn't
85
- // true at module-load time in most unit test contexts. Tests that only touch
86
- // the image/VLM path shouldn't break because the audio path asked for a
87
- // tools root they don't need.
88
- function whisperCppPaths() {
89
- const toolsDir = path.join((0, identity_1.getAgentToolsRoot)(), "whisper-cpp");
90
- const modelsDir = path.join(toolsDir, "models");
91
- const modelPath = path.join(modelsDir, WHISPER_CPP_MODEL_NAME);
92
- return { toolsDir, modelsDir, modelPath };
93
- }
94
72
  function describeAttachment(attachment) {
95
73
  return attachment.transferName?.trim() || attachment.guid?.trim() || "attachment";
96
74
  }
@@ -117,124 +95,13 @@ function audioFormatForInput(contentType, attachment) {
117
95
  const extension = path.extname(attachment?.transferName ?? "").toLowerCase();
118
96
  return AUDIO_INPUT_FORMAT_BY_CONTENT_TYPE[contentType ?? ""] ?? AUDIO_INPUT_FORMAT_BY_EXTENSION[extension];
119
97
  }
120
- async function execFileText(file, args, timeout) {
121
- return await new Promise((resolve, reject) => {
122
- (0, node_child_process_1.execFile)(file, args, { timeout }, (error, stdout = "", stderr = "") => {
123
- if (error) {
124
- const detail = stderr.trim() || stdout.trim() || error.message;
125
- reject(new Error(detail));
126
- return;
127
- }
128
- resolve(stdout);
129
- });
130
- });
131
- }
132
- async function pathExists(targetPath) {
133
- try {
134
- await fs.access(targetPath);
135
- return true;
136
- }
137
- catch {
138
- return false;
139
- }
140
- }
141
- async function resolveWhisperCppBinary(timeoutMs) {
142
- try {
143
- const existing = (await execFileText("which", ["whisper-cli"], timeoutMs)).trim();
144
- if (existing) {
145
- return existing;
146
- }
147
- }
148
- catch {
149
- // fall through to managed install
150
- }
151
- let prefix = "";
152
- try {
153
- prefix = (await execFileText("brew", ["--prefix", WHISPER_CPP_FORMULA], timeoutMs)).trim();
154
- if (prefix) {
155
- const candidate = path.join(prefix, "bin", "whisper-cli");
156
- if (await pathExists(candidate)) {
157
- return candidate;
158
- }
159
- }
160
- }
161
- catch {
162
- // fall through to managed install
163
- }
164
- await execFileText("brew", ["install", WHISPER_CPP_FORMULA], Math.max(timeoutMs, 300_000));
165
- prefix = (await execFileText("brew", ["--prefix", WHISPER_CPP_FORMULA], timeoutMs)).trim();
166
- if (!prefix) {
167
- throw new Error("whisper.cpp installed but brew did not return a usable prefix");
168
- }
169
- const candidate = path.join(prefix, "bin", "whisper-cli");
170
- if (!await pathExists(candidate)) {
171
- throw new Error("whisper.cpp installed but whisper-cli binary is missing");
172
- }
173
- return candidate;
174
- }
175
- async function ensureWhisperCppModel(timeoutMs, fetchImpl) {
176
- const { modelsDir, modelPath } = whisperCppPaths();
177
- try {
178
- await fs.access(modelPath);
179
- return modelPath;
180
- }
181
- catch {
182
- await fs.mkdir(modelsDir, { recursive: true });
183
- const response = await fetchImpl(WHISPER_CPP_MODEL_URL, {
184
- method: "GET",
185
- signal: AbortSignal.timeout(Math.max(timeoutMs, 300_000)),
186
- });
187
- if (!response.ok) {
188
- throw new Error(`failed to download whisper.cpp model: HTTP ${response.status}`);
189
- }
190
- await fs.writeFile(modelPath, Buffer.from(await response.arrayBuffer()));
191
- return modelPath;
192
- }
193
- }
194
- async function convertAudioForWhisperCpp(sourcePath, outputPath, timeoutMs) {
195
- try {
196
- await execFileText("ffmpeg", ["-y", "-i", sourcePath, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", outputPath], Math.max(timeoutMs, 120_000));
197
- return;
198
- }
199
- catch (ffmpegError) {
200
- try {
201
- await execFileText("afconvert", ["-f", "WAVE", "-d", "LEI16@16000", "-c", "1", sourcePath, outputPath], Math.max(timeoutMs, 120_000));
202
- return;
203
- }
204
- catch (afconvertError) {
205
- const ffmpegReason = ffmpegError.message;
206
- const afconvertReason = afconvertError.message;
207
- throw new Error(`failed to prepare audio for whisper.cpp (ffmpeg: ${ffmpegReason}; afconvert: ${afconvertReason})`);
208
- }
209
- }
210
- }
211
98
  async function transcribeAudioWithWhisperCpp(params, modelFetchImpl = fetch) {
212
99
  const workDir = await fs.mkdtemp(path.join(os.tmpdir(), "ouro-bb-audio-"));
213
100
  const filename = sanitizeFilename(describeAttachment(params.attachment));
214
- const extension = fileExtensionForAudio(params.attachment, params.contentType);
215
- const audioPath = path.join(workDir, `${path.parse(filename).name}${extension}`);
216
- const wavPath = path.join(workDir, `${path.parse(audioPath).name}.wav`);
217
- const outputBase = path.join(workDir, path.parse(audioPath).name);
101
+ const audioPath = path.join(workDir, `${path.parse(filename).name}${fileExtensionForAudio(params.attachment, params.contentType)}`);
218
102
  try {
219
103
  await fs.writeFile(audioPath, params.buffer);
220
- const whisperCliPath = await resolveWhisperCppBinary(params.timeoutMs);
221
- const modelPath = await ensureWhisperCppModel(params.timeoutMs, modelFetchImpl);
222
- await convertAudioForWhisperCpp(audioPath, wavPath, params.timeoutMs);
223
- await execFileText(whisperCliPath, ["-m", modelPath, "-f", wavPath, "-oj", "-of", outputBase], Math.max(params.timeoutMs, 120_000));
224
- const transcriptPath = `${outputBase}.json`;
225
- const raw = await fs.readFile(transcriptPath, "utf8");
226
- const parsed = JSON.parse(raw);
227
- if (typeof parsed.text === "string") {
228
- return parsed.text.trim();
229
- }
230
- if (Array.isArray(parsed.transcription)) {
231
- return parsed.transcription
232
- .map((entry) => (typeof entry?.text === "string" ? entry.text.trim() : ""))
233
- .filter(Boolean)
234
- .join(" ")
235
- .trim();
236
- }
237
- return "";
104
+ return await (0, transcribe_audio_1.transcribeAudioFile)(audioPath, { timeoutMs: params.timeoutMs, fetchImpl: modelFetchImpl });
238
105
  }
239
106
  finally {
240
107
  await fs.rm(workDir, { recursive: true, force: true }).catch(() => undefined);
@@ -311,7 +178,7 @@ async function hydrateBlueBubblesAttachments(attachments, config, channelConfig,
311
178
  const normalizedMime = normalized.mimeType ?? persistedRecord.mimeType ?? "image/jpeg";
312
179
  const dataUrl = `data:${normalizedMime};base64,${normalizedBuffer.toString("base64")}`;
313
180
  const description = await deps.vlmDescribe({
314
- prompt: buildVlmPrompt(deps.userText),
181
+ prompt: (0, understand_1.imageDescriptionPrompt)(deps.userText),
315
182
  imageDataUrl: dataUrl,
316
183
  attachmentGuid: attachment.guid,
317
184
  mimeType: normalizedMime,
@@ -365,7 +232,7 @@ async function hydrateBlueBubblesAttachments(attachments, config, channelConfig,
365
232
  notices.push(`attachment hydration failed for ${name}: empty audio transcript`);
366
233
  continue;
367
234
  }
368
- transcriptAdditions.push(`voice note transcript: ${transcript}`);
235
+ transcriptAdditions.push(`${transcribe_audio_1.VOICE_NOTE_TRANSCRIPT_PREFIX}${transcript}`);
369
236
  continue;
370
237
  }
371
238
  inputParts.push({
@@ -41,6 +41,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
41
41
  exports.emitObligationTransitionEpisodes = emitObligationTransitionEpisodes;
42
42
  exports.selectCheckpointCurrentAsk = selectCheckpointCurrentAsk;
43
43
  exports.startPostTurnSync = startPostTurnSync;
44
+ exports.erroredTurnReply = erroredTurnReply;
44
45
  exports.handleInboundTurn = handleInboundTurn;
45
46
  const fs = __importStar(require("fs"));
46
47
  const path = __importStar(require("path"));
@@ -532,6 +533,17 @@ function startPostTurnSync(agentRoot, config) {
532
533
  });
533
534
  });
534
535
  }
536
+ /**
537
+ * What every outward sense says when a turn errors and provider failover has nothing to say.
538
+ * Such turns used to end in silence: the owner saw no reply, prodded, and later got
539
+ * the late answer followed by a greeting to a prod (D-004); the step-limit stop was the
540
+ * observed cause (D-007). The engine still refuses to answer without evidence.
541
+ */
542
+ function erroredTurnReply(errorMessage) {
543
+ return /iteration limit exhausted/u.test(errorMessage ?? "")
544
+ ? "I hit my step limit in the middle of that job and couldn't finish it. Tell me to continue and I'll pick up from where I stopped."
545
+ : "I couldn't finish that one: something went wrong before I had an answer. Ask me again and I'll retry.";
546
+ }
535
547
  async function handleInboundTurn(input) {
536
548
  return (0, turn_execution_lease_1.withTurnExecutionLease)(() => handleInboundTurnExclusive(input));
537
549
  }
@@ -1283,6 +1295,8 @@ async function handleInboundTurnExclusive(input) {
1283
1295
  messages: sessionMessages,
1284
1296
  drainedPending: pending,
1285
1297
  ...(input.switchedProvider ? { switchedProvider: input.switchedProvider } : {}),
1298
+ // Every chat sense answers an errored turn. The inner channel stays silent, and the CLI keeps showing its operator the raw error.
1299
+ ...(result.outcome === "errored" && input.channel !== "inner" && input.channel !== "cli" ? { failoverMessage: erroredTurnReply(result.error?.message) } : {}),
1286
1300
  };
1287
1301
  }
1288
1302
  finally {
@@ -39,10 +39,10 @@ var __importStar = (this && this.__importStar) || (function () {
39
39
  };
40
40
  })();
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.erroredTurnReply = void 0;
42
43
  exports.stripThinkBlocks = stripThinkBlocks;
43
44
  exports.extractOutwardSenseDeliveryText = extractOutwardSenseDeliveryText;
44
45
  exports.getSenseSessionPath = getSenseSessionPath;
45
- exports.erroredTurnReply = erroredTurnReply;
46
46
  exports.runSenseTurn = runSenseTurn;
47
47
  const os = __importStar(require("os"));
48
48
  const path = __importStar(require("path"));
@@ -59,6 +59,7 @@ const pending_1 = require("../mind/pending");
59
59
  const context_2 = require("../mind/context");
60
60
  const trust_gate_1 = require("./trust-gate");
61
61
  const pipeline_1 = require("./pipeline");
62
+ Object.defineProperty(exports, "erroredTurnReply", { enumerable: true, get: function () { return pipeline_1.erroredTurnReply; } });
62
63
  const mcp_manager_1 = require("../repertoire/mcp-manager");
63
64
  const runtime_1 = require("../nerves/runtime");
64
65
  const session_transaction_1 = require("../mind/session-transaction");
@@ -353,17 +354,6 @@ function getSenseSessionPath(agentName, friendId, channel, sessionKey, agentRoot
353
354
  * Caller provides channel, session key, friend, and message;
354
355
  * this function handles all pipeline wiring.
355
356
  */
356
- /**
357
- * What an outward sense says when a turn errors and provider failover has nothing to say.
358
- * Such turns used to end in silence: the owner saw no reply, prodded, and later got
359
- * the late answer followed by a greeting to a prod (D-004); the step-limit stop was the
360
- * observed cause (D-007). The engine still refuses to answer without evidence.
361
- */
362
- function erroredTurnReply(errorMessage) {
363
- return /iteration limit exhausted/u.test(errorMessage ?? "")
364
- ? "I hit my step limit in the middle of that job and couldn't finish it. Tell me to continue and I'll pick up from where I stopped."
365
- : "I couldn't finish that one: something went wrong before I had an answer. Ask me again and I'll retry.";
366
- }
367
357
  async function runSenseTurn(options) {
368
358
  options = { ...options, ...(options.shepherdSession ? { shepherdSession: Object.freeze({ ...options.shepherdSession }) } : {}) };
369
359
  return (0, turn_execution_lease_1.withTurnExecutionLease)(async () => {
@@ -720,7 +710,7 @@ async function runSenseTurnExclusive(options, owner) {
720
710
  let finalDeliveryKind = terminalDeliveryKind;
721
711
  const acceptedTerminalOutcome = turnResult.turnOutcome === "settled" || turnResult.turnOutcome === "blocked";
722
712
  const failoverText = turnResult.turnOutcome === "errored"
723
- ? turnResult.failoverMessage?.trim() || (channel === "inner" ? undefined : erroredTurnReply(terminalErrorMessage))
713
+ ? turnResult.failoverMessage?.trim() || (channel === "inner" ? undefined : (0, pipeline_1.erroredTurnReply)(terminalErrorMessage))
724
714
  : undefined;
725
715
  const expectsOutwardResponse = acceptedTerminalOutcome || turnResult.turnOutcome === "command" || Boolean(failoverText);
726
716
  let finalCausalCoordinate;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_TEAMS_ATTACHMENT_BYTES = void 0;
4
+ exports.ingestTeamsAttachments = ingestTeamsAttachments;
5
+ exports.teamsInboundText = teamsInboundText;
6
+ const node_crypto_1 = require("node:crypto");
7
+ const downloaded_store_1 = require("../heart/attachments/downloaded-store");
8
+ const understand_1 = require("../heart/attachments/understand");
9
+ const runtime_1 = require("../nerves/runtime");
10
+ // Files, pictures and voice clips someone sends the agent in Teams, kept and put into words like every other sense.
11
+ exports.MAX_TEAMS_ATTACHMENT_BYTES = 20_000_000;
12
+ const MAX_TEAMS_ATTACHMENTS_PER_MESSAGE = 8;
13
+ const FILE_DOWNLOAD_INFO = "application/vnd.microsoft.teams.file.download.info";
14
+ // The bot token only goes to Microsoft's own Bot Framework media hosts, never to an arbitrary contentUrl.
15
+ const BOT_MEDIA_HOST = /(^|\.)(botframework\.com|trafficmanager\.net|teams\.microsoft\.com|skype\.com)$/u;
16
+ function downloadFor(attachment) {
17
+ const contentType = attachment.contentType ?? "";
18
+ if (contentType === FILE_DOWNLOAD_INFO) {
19
+ const downloadUrl = attachment.content?.downloadUrl;
20
+ return typeof downloadUrl === "string" ? { url: downloadUrl, displayName: attachment.name || "file", needsBotToken: false } : null;
21
+ }
22
+ if (!/^(image|audio|video)\//u.test(contentType) || typeof attachment.contentUrl !== "string")
23
+ return null;
24
+ return { url: attachment.contentUrl, displayName: attachment.name || contentType.replace("/", "."), mimeType: contentType, needsBotToken: true };
25
+ }
26
+ async function ingestTeamsAttachments(input) {
27
+ const fetchImpl = input.fetch ?? globalThis.fetch;
28
+ const attachments = [];
29
+ const notices = [];
30
+ const downloads = (input.attachments ?? []).map(downloadFor).filter((download) => download !== null);
31
+ for (const download of downloads.slice(0, MAX_TEAMS_ATTACHMENTS_PER_MESSAGE)) {
32
+ try {
33
+ const url = new URL(download.url);
34
+ if (url.protocol !== "https:")
35
+ throw new Error("attachment URL is not https");
36
+ const headers = {};
37
+ if (download.needsBotToken && BOT_MEDIA_HOST.test(url.hostname)) {
38
+ const token = await input.getBotToken();
39
+ if (token)
40
+ headers.authorization = `Bearer ${token}`;
41
+ }
42
+ const response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(30_000) });
43
+ if (!response.ok)
44
+ throw new Error(`download failed with HTTP ${response.status}`);
45
+ const buffer = await (0, downloaded_store_1.readBoundedResponse)(response, exports.MAX_TEAMS_ATTACHMENT_BYTES);
46
+ attachments.push(await (0, downloaded_store_1.storeDownloadedAttachment)({
47
+ agentName: input.agentName,
48
+ agentRoot: input.agentRoot,
49
+ source: "teams",
50
+ sourceId: (0, node_crypto_1.createHash)("sha256").update(download.url).digest("hex").slice(0, 32),
51
+ displayName: download.displayName,
52
+ mimeType: download.mimeType ?? response.headers.get("content-type") ?? undefined,
53
+ buffer,
54
+ }));
55
+ }
56
+ catch (error) {
57
+ notices.push(`attachment unavailable: ${download.displayName} (${error instanceof Error ? error.message : String(error)})`);
58
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.teams_attachment_ingest_error", message: "Teams attachment ingestion failed", meta: { reason: error instanceof Error ? error.message : String(error) } });
59
+ }
60
+ }
61
+ return { attachments, notices };
62
+ }
63
+ /** The text the agent sees for a Teams message: what was typed, then its attachments in words. */
64
+ async function teamsInboundText(text, input) {
65
+ const ingested = await ingestTeamsAttachments(input);
66
+ const lines = await (0, understand_1.attachmentTurnLines)(ingested.attachments, { agentName: input.agentName, agentRoot: input.agentRoot, userText: text, timeoutMs: understand_1.ATTACHMENT_WORDS_TIMEOUT_MS });
67
+ return [text, ...lines, ...ingested.notices].filter(Boolean).join("\n");
68
+ }
@@ -71,6 +71,7 @@ const runtime_1 = require("../nerves/runtime");
71
71
  const proactive_content_guard_1 = require("./proactive-content-guard");
72
72
  const turn_coordinator_1 = require("../heart/turn-coordinator");
73
73
  const identity_1 = require("../heart/identity");
74
+ const teams_attachments_1 = require("./teams-attachments");
74
75
  const mcp_manager_1 = require("../repertoire/mcp-manager");
75
76
  const progress_story_1 = require("../heart/progress-story");
76
77
  const tool_activity_callbacks_1 = require("../heart/tool-activity-callbacks");
@@ -1536,7 +1537,15 @@ function registerBotHandlers(app, label) {
1536
1537
  botApi: app.id && api ? { id: app.id, conversations: api.conversations } : undefined,
1537
1538
  teamsSendImage: (0, teams_image_1.createTeamsImageSender)((message) => ctx.send(message), activity.id, aiLabelEntities()),
1538
1539
  };
1539
- await handleTeamsMessage(text, stream, convId, teamsContext, sendText);
1540
+ const agentName = (0, identity_1.getAgentName)();
1541
+ const inboundText = await (0, teams_attachments_1.teamsInboundText)(text, {
1542
+ agentName,
1543
+ agentRoot: (0, identity_1.getAgentRoot)(agentName),
1544
+ attachments: activity.attachments,
1545
+ /* v8 ignore next -- live SDK token manager; ingestTeamsAttachments tests cover the token use @preserve */
1546
+ getBotToken: async () => (await app.tokenManager.getBotToken())?.toString(),
1547
+ });
1548
+ await handleTeamsMessage(inboundText, stream, convId, teamsContext, sendText);
1540
1549
  }
1541
1550
  catch (err) {
1542
1551
  reportTeamsRequest("failed", convId, requestContext, { reason: "handler_failed" });
@@ -37,67 +37,16 @@ exports.MAX_TELEGRAM_ATTACHMENT_BYTES = void 0;
37
37
  exports.ingestTelegramAttachments = ingestTelegramAttachments;
38
38
  const fs = __importStar(require("node:fs/promises"));
39
39
  const path = __importStar(require("node:path"));
40
- const node_crypto_1 = require("node:crypto");
40
+ const downloaded_store_1 = require("../heart/attachments/downloaded-store");
41
41
  const store_1 = require("../heart/attachments/store");
42
42
  const store_2 = require("../heart/attachments/store");
43
43
  const originals_1 = require("../heart/attachments/originals");
44
44
  const originals_2 = require("../heart/attachments/originals");
45
- const telegram_1 = require("../heart/attachments/sources/telegram");
45
+ const downloaded_1 = require("../heart/attachments/sources/downloaded");
46
46
  const runtime_1 = require("../nerves/runtime");
47
47
  exports.MAX_TELEGRAM_ATTACHMENT_BYTES = 20_000_000;
48
48
  const MAX_TELEGRAM_ATTACHMENTS_PER_MESSAGE = 8;
49
49
  const SAFE_FILE_PATH = /^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[A-Za-z0-9._/-]{1,512}$/u;
50
- async function readBounded(response, limit) {
51
- const advertised = Number(response.headers.get("content-length"));
52
- if (Number.isFinite(advertised) && advertised > limit)
53
- throw new Error("advertised size exceeds limit");
54
- if (!response.body)
55
- throw new Error("empty response body");
56
- const chunks = [];
57
- let total = 0;
58
- const reader = response.body.getReader();
59
- try {
60
- for (;;) {
61
- const { done, value } = await reader.read();
62
- if (done)
63
- break;
64
- total += value.byteLength;
65
- if (total > limit)
66
- throw new Error("download exceeds limit");
67
- chunks.push(value);
68
- }
69
- }
70
- finally {
71
- await reader.cancel().catch(() => undefined);
72
- }
73
- return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)), total);
74
- }
75
- async function atomicWrite(filePath, buffer) {
76
- const directory = path.dirname(filePath);
77
- await fs.mkdir(directory, { recursive: true, mode: 0o700 });
78
- const temporary = `${filePath}.${(0, node_crypto_1.randomUUID)()}.tmp`;
79
- let handle;
80
- try {
81
- handle = await fs.open(temporary, "wx", 0o600);
82
- await handle.writeFile(buffer);
83
- await handle.sync();
84
- await handle.close();
85
- handle = undefined;
86
- await fs.rename(temporary, filePath);
87
- const directoryHandle = await fs.open(directory, "r");
88
- try {
89
- await directoryHandle.sync();
90
- }
91
- finally {
92
- await directoryHandle.close();
93
- }
94
- }
95
- finally {
96
- await handle?.close().catch(() => undefined);
97
- await fs.unlink(temporary).catch((error) => { if (error.code !== "ENOENT")
98
- throw error; });
99
- }
100
- }
101
50
  async function ingestTelegramAttachments(input) {
102
51
  const fetchImpl = input.fetch ?? globalThis.fetch;
103
52
  const unique = [...new Map(input.attachments.map((attachment) => [attachment.fileId, attachment])).values()]
@@ -119,8 +68,8 @@ async function ingestTelegramAttachments(input) {
119
68
  continue;
120
69
  }
121
70
  }
122
- const recoverable = (0, telegram_1.buildTelegramAttachmentRecord)({
123
- fileId: candidate.fileId,
71
+ const recoverable = (0, downloaded_1.buildDownloadedAttachmentRecord)("telegram", {
72
+ sourceId: candidate.fileId,
124
73
  displayName: candidate.displayName,
125
74
  mimeType: candidate.mimeType,
126
75
  byteCount: candidate.byteCount,
@@ -131,8 +80,8 @@ async function ingestTelegramAttachments(input) {
131
80
  const stat = await fs.lstat(recoverablePath);
132
81
  if (!stat.isFile() || stat.size > exports.MAX_TELEGRAM_ATTACHMENT_BYTES)
133
82
  throw new Error("persisted attachment is invalid");
134
- const recovered = (0, store_1.cacheRecentAttachment)(input.agentName, (0, telegram_1.buildTelegramAttachmentRecord)({
135
- fileId: candidate.fileId,
83
+ const recovered = (0, store_1.cacheRecentAttachment)(input.agentName, (0, downloaded_1.buildDownloadedAttachmentRecord)("telegram", {
84
+ sourceId: candidate.fileId,
136
85
  displayName: candidate.displayName,
137
86
  mimeType: candidate.mimeType,
138
87
  byteCount: stat.size,
@@ -157,23 +106,16 @@ async function ingestTelegramAttachments(input) {
157
106
  : (() => { throw new Error("attachment transport is unavailable"); })();
158
107
  if (!response.ok)
159
108
  throw new Error(`download failed with HTTP ${response.status}`);
160
- const buffer = await readBounded(response, exports.MAX_TELEGRAM_ATTACHMENT_BYTES);
161
- const provisional = (0, telegram_1.buildTelegramAttachmentRecord)({
162
- fileId: candidate.fileId,
109
+ const buffer = await (0, downloaded_store_1.readBoundedResponse)(response, exports.MAX_TELEGRAM_ATTACHMENT_BYTES);
110
+ const record = await (0, downloaded_store_1.storeDownloadedAttachment)({
111
+ agentName: input.agentName,
112
+ agentRoot: input.agentRoot,
113
+ source: "telegram",
114
+ sourceId: candidate.fileId,
163
115
  displayName: candidate.displayName,
164
116
  mimeType: candidate.mimeType ?? response.headers.get("content-type") ?? undefined,
165
- byteCount: buffer.length,
166
- localPath: path.resolve(input.agentRoot, "state", "attachments", ".pending", candidate.fileId),
117
+ buffer,
167
118
  });
168
- const localPath = (0, originals_1.originalStoragePath)(input.agentRoot, provisional, provisional.mimeType);
169
- await atomicWrite(localPath, buffer);
170
- const record = (0, store_1.cacheRecentAttachment)(input.agentName, (0, telegram_1.buildTelegramAttachmentRecord)({
171
- fileId: candidate.fileId,
172
- displayName: candidate.displayName,
173
- mimeType: provisional.mimeType,
174
- byteCount: buffer.length,
175
- localPath,
176
- }), input.agentRoot);
177
119
  attachments.push(record);
178
120
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_attachment_ingested", message: "Telegram attachment entered the shared attachment store", meta: { kind: record.kind, byteCount: buffer.length } });
179
121
  }
@@ -98,8 +98,8 @@ const approval_store_1 = require("../heart/approval-store");
98
98
  const tools_awaiting_1 = require("../repertoire/tools-awaiting");
99
99
  const obligations_1 = require("../arc/obligations");
100
100
  const orientation_frame_1 = require("../heart/orientation-frame");
101
- const render_1 = require("../heart/attachments/render");
102
101
  const telegram_attachments_1 = require("./telegram-attachments");
102
+ const understand_1 = require("../heart/attachments/understand");
103
103
  const pending_1 = require("../mind/pending");
104
104
  const relationship_authorization_1 = require("../repertoire/relationship-authorization");
105
105
  const telegram_admission_1 = require("./telegram-admission");
@@ -1429,8 +1429,9 @@ function createTelegramSenseApp(options) {
1429
1429
  attachments: message.attachments ?? [],
1430
1430
  });
1431
1431
  const attachmentIds = ingested.attachments.map((attachment) => attachment.id);
1432
+ const attachmentLines = await (0, understand_1.attachmentTurnLines)(ingested.attachments, { agentName: options.agentName, agentRoot, userText: message.text, timeoutMs: understand_1.ATTACHMENT_WORDS_TIMEOUT_MS });
1432
1433
  return {
1433
- text: (0, delegated_command_1.shieldDelegatedBanner)([message.text, (0, render_1.renderAttachmentBlock)(ingested.attachments), ...(message.attachmentNotices ?? []), ...ingested.notices].filter(Boolean).join("\n")),
1434
+ text: (0, delegated_command_1.shieldDelegatedBanner)([message.text, ...attachmentLines, ...(message.attachmentNotices ?? []), ...ingested.notices].filter(Boolean).join("\n")),
1434
1435
  attachmentIds,
1435
1436
  };
1436
1437
  };
@@ -41,24 +41,16 @@ const os = __importStar(require("os"));
41
41
  const path = __importStar(require("path"));
42
42
  const child_process_1 = require("child_process");
43
43
  const runtime_1 = require("../../nerves/runtime");
44
+ const transcribe_audio_1 = require("../../heart/attachments/transcribe-audio");
44
45
  const transcript_1 = require("./transcript");
45
46
  function parseWhisperCppTranscriptJson(raw) {
46
- let parsed;
47
+ let text;
47
48
  try {
48
- parsed = JSON.parse(raw);
49
+ text = (0, transcribe_audio_1.whisperCppTranscriptText)(raw);
49
50
  }
50
51
  catch (error) {
51
52
  throw new Error(`invalid whisper.cpp JSON: ${String(error)}`);
52
53
  }
53
- const text = typeof parsed.text === "string"
54
- ? parsed.text.trim()
55
- : Array.isArray(parsed.transcription)
56
- ? parsed.transcription
57
- .map((entry) => typeof entry.text === "string" ? entry.text.trim() : "")
58
- .filter(Boolean)
59
- .join(" ")
60
- .trim()
61
- : "";
62
54
  if (!text) {
63
55
  throw new Error("empty whisper.cpp transcript");
64
56
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1101",
3
+ "version": "0.1.0-alpha.1103",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1101",
9
+ "version": "0.1.0-alpha.1103",
10
10
  "dependencies": {
11
11
  "@anthropic-ai/sdk": "^0.78.0",
12
12
  "@ouro.bot/friends": "0.1.0-alpha.18",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1101",
3
+ "version": "0.1.0-alpha.1103",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },