@ouro.bot/cli 0.1.0-alpha.1124 → 0.1.0-alpha.1126

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/changelog.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1126",
6
+ "changes": [
7
+ "The agent can send a file from its machine into the chat with one send_file tool on iMessage, Telegram and Teams; it replaces teams_send_image."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1125",
12
+ "changes": [
13
+ "Wake runners hold a wake while the last one sent to the same session has not reached it, so the app's own queue never fills with hours-old wakes that arrive one per turn; the command offers the news again on its next run."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1124",
6
18
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1124",
2
+ "runtimeVersion": "0.1.0-alpha.1126",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -2,7 +2,7 @@
2
2
  "version": 2,
3
3
  "profiles": {
4
4
  "sanctuary-owner": {
5
- "version": 21,
5
+ "version": 22,
6
6
  "contextScopes": [
7
7
  "household.status",
8
8
  "household.policy",
@@ -87,7 +87,8 @@
87
87
  "media_release_profile",
88
88
  "media_fill_missing",
89
89
  "react",
90
- "set_reply_target"
90
+ "set_reply_target",
91
+ "send_file"
91
92
  ],
92
93
  "effectScopes": [
93
94
  "telegram.proactive",
@@ -157,7 +158,7 @@
157
158
  ]
158
159
  },
159
160
  "sanctuary-agent-peer": {
160
- "version": 11,
161
+ "version": 12,
161
162
  "toolNames": [
162
163
  "external_event_disposition",
163
164
  "query_active_work",
@@ -230,7 +231,8 @@
230
231
  "media_release_profile",
231
232
  "media_fill_missing",
232
233
  "react",
233
- "set_reply_target"
234
+ "set_reply_target",
235
+ "send_file"
234
236
  ],
235
237
  "contextScopes": [
236
238
  "household.status",
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1124</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1126</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -60,7 +60,7 @@ function exactSanctuaryContainmentProfileBoundaries(value) {
60
60
  if (!value || typeof value !== "object" || Array.isArray(value))
61
61
  return false;
62
62
  const boundaries = value;
63
- const versions = { "sanctuary-owner": 21, "sanctuary-household": 6, "sanctuary-event": 4 };
63
+ const versions = { "sanctuary-owner": 22, "sanctuary-household": 6, "sanctuary-event": 4 };
64
64
  if (!(0, node_util_1.isDeepStrictEqual)(Object.keys(boundaries).sort(), Object.keys(versions).sort()))
65
65
  return false;
66
66
  const packageRoot = path.resolve(__dirname, "../../../deploy/unraid/sanctuary.ouro");
@@ -44,7 +44,8 @@ const frontend_socket_client_1 = require("../frontend-socket-client");
44
44
  const sanctuary_authority_codec_1 = require("./sanctuary-authority-codec");
45
45
  const runtime_1 = require("../../nerves/runtime");
46
46
  const PROTOCOL_VERSION = 1;
47
- const DEFAULT_MAX_REQUEST_BYTES = 256 * 1024;
47
+ // Room for one file upload (MAX_TELEGRAM_UPLOAD_BYTES, base64) plus its envelope.
48
+ const DEFAULT_MAX_REQUEST_BYTES = 14 * 1024 * 1024;
48
49
  const DEFAULT_CONNECTION_TIMEOUT_MS = 65_000;
49
50
  const MAX_TELEGRAM_ATTACHMENT_BYTES = 20_000_000;
50
51
  const SAFE_TELEGRAM_FILE_PATH = /^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[A-Za-z0-9._/-]{1,512}$/u;
@@ -69,6 +70,21 @@ function exactBody(value, required, optional = []) {
69
70
  function boundedText(value, maxLength) {
70
71
  return typeof value === "string" && value.length > 0 && value.length <= maxLength;
71
72
  }
73
+ // A reply names only the message it answers, so it cannot carry content of its own.
74
+ function validReplyParameters(value) {
75
+ return value === undefined || (isObject(value) && exactKeys(value, ["message_id"])
76
+ && Number.isSafeInteger(value.message_id) && value.message_id > 0);
77
+ }
78
+ /** Rebuilds a file the agent sent as base64; anything else is refused. */
79
+ function decodeUpload(value) {
80
+ if (!isObject(value) || !exactKeys(value, ["kind", "name", "contentType", "bodyBase64"]) || value.kind !== "telegram_input_file"
81
+ || !boundedText(value.name, 256) || !boundedText(value.contentType, 256) || typeof value.bodyBase64 !== "string")
82
+ return null;
83
+ const bytes = Buffer.from(value.bodyBase64, "base64");
84
+ if (bytes.length === 0 || bytes.length > telegram_client_1.MAX_TELEGRAM_UPLOAD_BYTES || bytes.toString("base64") !== value.bodyBase64)
85
+ return null;
86
+ return { kind: "telegram_input_file", name: value.name, contentType: value.contentType, bytes };
87
+ }
72
88
  // After a gateway restart, Telegram keeps the previous getUpdates long-poll
73
89
  // alive server-side and answers 409 Conflict to the new poller until that
74
90
  // session expires (about the previous poll's timeout). Retry through that
@@ -90,7 +106,7 @@ class SanctuaryTelegramAuthorityService {
90
106
  #hostMaintenanceFailures = new Map();
91
107
  constructor(options) {
92
108
  this.#api = {
93
- request: (method, body) => options.api.request(method, body, AbortSignal.timeout(method === "getUpdates" ? 60_000 : 15_000)),
109
+ request: (method, body) => options.api.request(method, body, AbortSignal.timeout(method === "getUpdates" || method === "sendPhoto" || method === "sendDocument" ? 60_000 : 15_000)),
94
110
  };
95
111
  this.#gateway = options.gateway;
96
112
  this.#hostAuthority = options.hostAuthority;
@@ -204,6 +220,7 @@ class SanctuaryTelegramAuthorityService {
204
220
  const requestMethod = params.method;
205
221
  const body = params.body;
206
222
  const ownerChatId = this.#gateway.identity().ownerChatId;
223
+ let upload;
207
224
  if (requestMethod === "getMe") {
208
225
  if (!emptyParams(body))
209
226
  throw new Error("Sanctuary Telegram getMe body is invalid");
@@ -215,9 +232,7 @@ class SanctuaryTelegramAuthorityService {
215
232
  if (!boundedText(body.text, 4_096)
216
233
  || (body.parse_mode !== undefined && body.parse_mode !== "HTML")
217
234
  || (body.reply_markup !== undefined && !isObject(body.reply_markup))
218
- // A reply names only the message it answers, so it cannot carry content of its own.
219
- || (body.reply_parameters !== undefined && !(isObject(body.reply_parameters) && exactKeys(body.reply_parameters, ["message_id"])
220
- && Number.isSafeInteger(body.reply_parameters.message_id) && body.reply_parameters.message_id > 0))) {
235
+ || !validReplyParameters(body.reply_parameters)) {
221
236
  throw new Error("Sanctuary Telegram send body is invalid");
222
237
  }
223
238
  const chatId = String(body.chat_id);
@@ -288,6 +303,21 @@ class SanctuaryTelegramAuthorityService {
288
303
  throw new Error("Sanctuary Telegram chat action target is invalid");
289
304
  }
290
305
  }
306
+ else if (requestMethod === "sendPhoto" || requestMethod === "sendDocument") {
307
+ const field = requestMethod === "sendPhoto" ? "photo" : "document";
308
+ if (!exactBody(body, ["chat_id", field], ["caption", "reply_parameters"])
309
+ || (body.caption !== undefined && !boundedText(body.caption, 1_024))
310
+ || !validReplyParameters(body.reply_parameters)) {
311
+ throw new Error("Sanctuary Telegram file send body is invalid");
312
+ }
313
+ const file = decodeUpload(body[field]);
314
+ if (!file)
315
+ throw new Error("Sanctuary Telegram file upload is invalid");
316
+ const chatId = String(body.chat_id);
317
+ if (chatId !== ownerChatId && !this.#gateway.isAuthorizedChat(chatId))
318
+ throw new Error("Sanctuary Telegram send target is invalid");
319
+ upload = { ...body, [field]: file };
320
+ }
291
321
  else if (requestMethod === "setMessageReaction") {
292
322
  // A reaction is one emoji on a message in a chat the agent may already message; nothing else rides along.
293
323
  if (!exactBody(body, ["chat_id", "message_id", "reaction"]))
@@ -315,7 +345,7 @@ class SanctuaryTelegramAuthorityService {
315
345
  else {
316
346
  throw new Error("Sanctuary Telegram request method is not available");
317
347
  }
318
- const result = await this.#api.request(requestMethod, body);
348
+ const result = await this.#api.request(requestMethod, upload ?? body);
319
349
  if (requestMethod === "getFile") {
320
350
  if (!isObject(result)
321
351
  || typeof result.file_path !== "string"
@@ -1159,8 +1159,8 @@ function checkFirstClassMcpTrust(context) {
1159
1159
  return allow;
1160
1160
  }
1161
1161
  function checkTrustLevelGuardrails(toolName, args, context) {
1162
- if (toolName === "teams_send_image" && context.trustLevel !== "family") {
1163
- return deny("sending local images in Teams requires family trust.");
1162
+ if (toolName === "send_file" && context.trustLevel !== "family") {
1163
+ return deny("sending files from this machine requires family trust.");
1164
1164
  }
1165
1165
  const cacheSyncResult = mailCacheSyncShellGuardrail(toolName, args, context);
1166
1166
  if (!cacheSyncResult.allowed)
@@ -1246,6 +1246,9 @@ function guardInvocation(toolName, args, context) {
1246
1246
  // Read-only tools skip the structural and trust guardrails; only the sync key's directory is closed to them.
1247
1247
  if (READ_ONLY_TOOLS.has(toolName))
1248
1248
  return syncSecretReadRefused(toolName, args, context.agentRoot) ? deny(REASONS.unreadablePath) : allow;
1249
+ // send_file reads the file it sends, so the sync key's directory is closed to it the same way.
1250
+ if (toolName === "send_file" && syncSecretReadRefused("read_file", args, context.agentRoot))
1251
+ return deny(REASONS.unreadablePath);
1249
1252
  // Layer 1: structural guardrails (always on)
1250
1253
  const structuralResult = checkStructuralGuardrails(toolName, args, context);
1251
1254
  if (!structuralResult.allowed)
@@ -1,22 +1,29 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.chatToolDefinitions = exports.CHAT_ACTION_CHANNELS = exports.CHAT_ACTION_TOOL_NAMES = void 0;
3
+ exports.chatToolDefinitions = exports.CHAT_ACTION_TOOL_CHANNELS = void 0;
4
4
  exports.chatActionsForTurn = chatActionsForTurn;
5
5
  exports.offTurnRefusal = offTurnRefusal;
6
6
  const runtime_1 = require("../nerves/runtime");
7
- // Every chat app lets you react to a message and reply to a specific one. These tools are the same on every
8
- // sense; each sense binds `ctx.chatActions` to its own app, and a missing action means the app can't do it.
9
- /** Tools that act in the chat the turn came from; offered only on chat senses and only when the turn may send. */
10
- exports.CHAT_ACTION_TOOL_NAMES = new Set(["react", "set_reply_target"]);
11
- /** Senses whose turns bind `chatActions`. */
12
- exports.CHAT_ACTION_CHANNELS = new Set(["bluebubbles", "telegram"]);
7
+ // Every chat app lets you react to a message, reply to a specific one and send a file. These tools are the same on
8
+ // every sense; each sense binds `ctx.chatActions` to its own app, and a missing action means the app can't do it.
9
+ const MESSAGING_APPS = new Set(["bluebubbles", "telegram"]);
10
+ /**
11
+ * Tools that act in the chat the turn came from, and the senses whose turns bind them. They are offered only there,
12
+ * and only when the turn may send. Teams can't add reactions and already replies to the activity, but it takes files.
13
+ */
14
+ exports.CHAT_ACTION_TOOL_CHANNELS = new Map([
15
+ ["react", MESSAGING_APPS],
16
+ ["set_reply_target", MESSAGING_APPS],
17
+ ["send_file", new Set([...MESSAGING_APPS, "teams"])],
18
+ ]);
13
19
  /**
14
20
  * Binds a sense's chat actions to the turn: a left-out message id means the message that started it. The id stays
15
21
  * inside these closures, so it never sits in the tool context as data.
16
22
  */
17
23
  function chatActionsForTurn(actions, inboundMessageId) {
18
- const { react, setReplyTarget } = actions;
24
+ const { react, setReplyTarget, sendFile } = actions;
19
25
  return {
26
+ ...(sendFile ? { sendFile } : {}),
20
27
  ...(react ? {
21
28
  react: async (emoji, messageId) => {
22
29
  const id = messageId ?? inboundMessageId;
@@ -124,4 +131,36 @@ exports.chatToolDefinitions = [
124
131
  summaryKeys: ["target", "message_id"],
125
132
  riskProfile: { mutates: "external_side_effect", risk: "high", reason: "changes where the reply in the current chat lands" },
126
133
  },
134
+ {
135
+ tool: {
136
+ type: "function",
137
+ function: {
138
+ name: "send_file",
139
+ description: "send a file from this machine into this chat, with an optional caption. images show inline; other files arrive as documents where the app takes them.",
140
+ parameters: {
141
+ type: "object",
142
+ properties: {
143
+ path: { type: "string", description: "absolute path to the file." },
144
+ caption: { type: "string", description: "optional text sent with the file." },
145
+ },
146
+ required: ["path"],
147
+ },
148
+ },
149
+ },
150
+ // A file that didn't go through throws, so the turn records the send as failed rather than done.
151
+ handler: async (args, ctx) => {
152
+ const refusal = offTurnRefusal(ctx);
153
+ if (refusal)
154
+ throw new Error(refusal);
155
+ const filePath = argText(args.path);
156
+ if (!filePath.startsWith("/"))
157
+ throw new Error("path must be an absolute path to a file.");
158
+ const actions = ctx?.chatActions;
159
+ if (!actions?.sendFile)
160
+ throw new Error("this chat doesn't take files from me.");
161
+ return actions.sendFile(filePath, typeof args.caption === "string" ? args.caption : "");
162
+ },
163
+ summaryKeys: ["path"],
164
+ riskProfile: { mutates: "external_side_effect", risk: "high", reason: "sends a local file into the current chat" },
165
+ },
127
166
  ];
@@ -10,7 +10,6 @@ const ado_client_1 = require("./ado-client");
10
10
  const graph_endpoints_json_1 = __importDefault(require("./data/graph-endpoints.json"));
11
11
  const ado_endpoints_json_1 = __importDefault(require("./data/ado-endpoints.json"));
12
12
  const runtime_1 = require("../nerves/runtime");
13
- const teams_image_1 = require("../senses/teams-image");
14
13
  const MUTATE_METHODS = ["POST", "PATCH", "DELETE"];
15
14
  const DEFAULT_ADO_QUERY = "SELECT [System.Id], [System.Title], [System.State], [System.AssignedTo] FROM WorkItems WHERE [System.AssignedTo] = @Me AND [System.State] <> 'Closed' ORDER BY [System.ChangedDate] DESC";
16
15
  exports.teamsToolDefinitions = [
@@ -285,43 +284,6 @@ exports.teamsToolDefinitions = [
285
284
  integration: "ado",
286
285
  summaryKeys: ["query"],
287
286
  },
288
- {
289
- tool: {
290
- type: "function",
291
- function: {
292
- name: "teams_send_image",
293
- description: "Send a local PNG or JPEG image into the current Teams conversation, without publishing it or using OneDrive. Requires family trust. Images are resized/compressed for inline delivery. An activity receipt confirms Teams acceptance, not client rendering.",
294
- parameters: {
295
- type: "object",
296
- properties: {
297
- path: { type: "string", description: "Absolute path to a local PNG or JPEG image" },
298
- caption: { type: "string", maxLength: teams_image_1.MAX_TEAMS_IMAGE_CAPTION_LENGTH, description: "Optional short caption (up to 1024 characters)" },
299
- },
300
- required: ["path"],
301
- additionalProperties: false,
302
- },
303
- },
304
- },
305
- handler: async (args, ctx) => {
306
- if (ctx?.noSend || ctx?.habitSession || ctx?.autonomousTurnKind) {
307
- throw new Error("Teams image sending is unavailable in no-send or autonomous turns");
308
- }
309
- if (ctx?.context?.friend.trustLevel !== "family" || ctx.context.channel.channel !== "teams") {
310
- throw new Error("Sending local images in Teams requires a family-trusted Teams conversation");
311
- }
312
- if (!ctx.teamsSendImage || !ctx.agentName || !ctx.agentRoot) {
313
- throw new Error("Teams image sending requires an authenticated current-conversation sender and agent owner");
314
- }
315
- const caption = args.caption ?? "";
316
- if (caption.length > teams_image_1.MAX_TEAMS_IMAGE_CAPTION_LENGTH)
317
- throw new Error("Teams image caption exceeds 1024 characters");
318
- const attachment = await (0, teams_image_1.prepareTeamsImage)({ path: args.path, agentName: ctx.agentName, agentRoot: ctx.agentRoot });
319
- const activityId = await ctx.teamsSendImage(attachment, caption);
320
- return `image accepted by Teams in the current conversation (activity ${activityId}); client rendering is not verified`;
321
- },
322
- summaryKeys: ["path"],
323
- riskProfile: { mutates: "external_side_effect", risk: "high", reason: "sends local image bytes to the current Teams conversation" },
324
- },
325
287
  ];
326
288
  function searchEndpoints(entries, query) {
327
289
  (0, runtime_1.emitNervesEvent)({
@@ -171,7 +171,7 @@ function selectToolsForChannel(capabilities, toolPreferences, _context, provider
171
171
  else {
172
172
  const available = new Set(capabilities?.availableIntegrations ?? []);
173
173
  const integrations = [...tools_teams_1.teamsToolDefinitions, ...ado_semantic_1.adoSemanticToolDefinitions, ...tools_github_1.githubToolDefinitions]
174
- .filter((definition) => available.size > 0 || definition.tool.function.name === "teams_send_image")
174
+ .filter(() => available.size > 0)
175
175
  .filter((definition) => definition.integration ? available.has(definition.integration) : capabilities?.channel === "teams")
176
176
  .map((definition) => {
177
177
  const preference = definition.integration ? toolPreferences?.[definition.integration] : undefined;
@@ -206,10 +206,10 @@ function selectToolsForChannel(capabilities, toolPreferences, _context, provider
206
206
  ordinary.push(tools_surface_1.surfaceToolDefinition);
207
207
  }
208
208
  }
209
- ordinary = ordinary.filter((definition) => (definition.tool.function.name !== "teams_send_image" || (!context?.noSend && !context?.habitSession && !context?.autonomousTurnKind))
210
- // Reacting and choosing a reply target act in the chat the turn came from, so they need a chat sense and a turn that may send.
211
- && (!tools_chat_1.CHAT_ACTION_TOOL_NAMES.has(definition.tool.function.name)
212
- || (tools_chat_1.CHAT_ACTION_CHANNELS.has(capabilities?.channel ?? "") && !context?.noSend && !context?.habitSession && !context?.autonomousTurnKind))
209
+ ordinary = ordinary.filter((definition) =>
210
+ // Chat actions act in the chat the turn came from, so they need a sense that binds them and a turn that may send.
211
+ (!tools_chat_1.CHAT_ACTION_TOOL_CHANNELS.has(definition.tool.function.name)
212
+ || (tools_chat_1.CHAT_ACTION_TOOL_CHANNELS.get(definition.tool.function.name).has(capabilities?.channel ?? "") && !context?.noSend && !context?.habitSession && !context?.autonomousTurnKind))
213
213
  &&
214
214
  (!relationship || relationship.advertisedToolNames.includes(definition.tool.function.name))
215
215
  && (!definition.requiredCapability || providerCapabilities?.has(definition.requiredCapability) === true));
@@ -42,6 +42,7 @@ exports.assertSessionId = assertSessionId;
42
42
  exports.eventLogPath = eventLogPath;
43
43
  exports.readEventLog = readEventLog;
44
44
  exports.parseEventLines = parseEventLines;
45
+ exports.messageDelivered = messageDelivered;
45
46
  exports.describePermission = describePermission;
46
47
  exports.tailFacts = tailFacts;
47
48
  exports.classify = classify;
@@ -195,6 +196,20 @@ function parseEventLines(text) {
195
196
  function tailEvents(stateDir, id, bytes) {
196
197
  return parseEventLines(readEventLog(id, { stateDir, maxBytes: bytes }).text);
197
198
  }
199
+ const DELIVERY_TAIL_BYTES = 4 * 1024 * 1024;
200
+ const DELIVERY_CLOCK_SLACK_MS = 60_000;
201
+ const squash = (text) => text.replace(/\s+/g, " ").trim();
202
+ /**
203
+ * Whether a message sent at `sinceMs` has reached the session: its log holds a user message that starts with the same
204
+ * text. A message the app accepted but still holds in its own queue is not in the log yet.
205
+ */
206
+ function messageDelivered(id, text, sinceMs, options = {}) {
207
+ const probe = squash(text).slice(0, 160);
208
+ return parseEventLines(readEventLog(id, { ...options, maxBytes: DELIVERY_TAIL_BYTES }).text).some(event => {
209
+ const data = isRecord(event.data) ? event.data : {};
210
+ return event.type === "user.message" && Date.parse(str(event.timestamp) ?? "") >= sinceMs - DELIVERY_CLOCK_SLACK_MS && squash(str(data.content) ?? "").includes(probe);
211
+ });
212
+ }
198
213
  const PERMISSION_WHAT = {
199
214
  shell: "run a shell command",
200
215
  write: "change a file",
@@ -200,7 +200,7 @@ function startAppSessionsSense(options) {
200
200
  const runnerTick = () => {
201
201
  if (stopped)
202
202
  return;
203
- runnerPoll = checkWakeRunners(options.agentName, agentRoot, { run: options.runCommand ?? wake_runner_1.runCommand, send: options.sendWake ?? (0, wake_runner_1.sendWake)(client), now: now() }, due).then(ms => {
203
+ runnerPoll = checkWakeRunners(options.agentName, agentRoot, { run: options.runCommand ?? wake_runner_1.runCommand, send: options.sendWake ?? (0, wake_runner_1.sendWake)(client), delivered: options.wasDelivered ?? (0, wake_runner_1.wasDelivered)(client), now: now() }, due).then(ms => {
204
204
  if (!stopped)
205
205
  cancelRunners = schedule(runnerTick, ms);
206
206
  });
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.sendWake = exports.runCommand = exports.WAKE_RUNNER_TIMEOUT_MS = exports.WAKE_RUNNER_DEFAULT_SECONDS = void 0;
36
+ exports.sendWake = exports.wasDelivered = exports.runCommand = exports.WAKE_HOLD_MS = exports.WAKE_RUNNER_TIMEOUT_MS = exports.WAKE_RUNNER_DEFAULT_SECONDS = void 0;
37
37
  exports.parseWakeOutput = parseWakeOutput;
38
38
  exports.runWakeRunner = runWakeRunner;
39
39
  exports.runWakeRunners = runWakeRunners;
@@ -56,9 +56,15 @@ const wake_runner_state_1 = require("./wake-runner-state");
56
56
  * A wake is delivered "immediate" by default: the app admits it at the session's next turn boundary. A session that works for
57
57
  * hours in one run never goes idle, so a message queued behind that run ("enqueue") waits until the run ends, however old the
58
58
  * news in it. A runner can ask for "enqueue" when a wake should never interrupt.
59
+ *
60
+ * The app holds an accepted message in its own queue until the session reaches a turn boundary, and it cannot be taken back.
61
+ * So a session gets one wake at a time: while the last wake sent to it has not shown up in its log, the next wake is held
62
+ * and reported undelivered, and the command, which re-derives its state every run, offers it again. A wake still missing
63
+ * after `WAKE_HOLD_MS` is taken as lost. Held wakes never pile up in the app as hours-old news.
59
64
  */
60
65
  exports.WAKE_RUNNER_DEFAULT_SECONDS = 300;
61
66
  exports.WAKE_RUNNER_TIMEOUT_MS = 2 * 60_000;
67
+ exports.WAKE_HOLD_MS = 30 * 60_000;
62
68
  const MAX_STATUS_LINES = 20;
63
69
  const MAX_LINE = 300;
64
70
  const MAX_OUTPUT = 10 * 1024 * 1024;
@@ -100,14 +106,19 @@ const runCommand = (argv, timeoutMs) => new Promise(resolve => {
100
106
  });
101
107
  });
102
108
  exports.runCommand = runCommand;
109
+ const wasDelivered = (client) => (session, message, sinceMs) => (0, client_1.messageDelivered)(session, message, sinceMs, client);
110
+ exports.wasDelivered = wasDelivered;
103
111
  const sendWake = (client) => async (session, message, delivery) => {
104
112
  const result = await (0, client_1.sendToAppSession)(session, message, { ...client, delivery });
105
113
  return { ok: result.ok, error: result.error };
106
114
  };
107
115
  exports.sendWake = sendWake;
108
116
  /** Run one runner's command, deliver its wakes and report each one back. Returns the runner's new state. */
109
- async function runWakeRunner(runner, deps) {
117
+ async function runWakeRunner(runner, deps, previous = {}) {
110
118
  const state = { lastRunAt: new Date(deps.now).toISOString() };
119
+ const open = openWakes(previous, deps);
120
+ if (Object.keys(open).length)
121
+ state.open = open;
111
122
  const ran = await deps.run(runner.command, exports.WAKE_RUNNER_TIMEOUT_MS);
112
123
  if (!ran.ok)
113
124
  return fail(runner, state, ran.error ?? "the command failed");
@@ -124,9 +135,14 @@ async function runWakeRunner(runner, deps) {
124
135
  const problems = [];
125
136
  for (const wake of output.wakes) {
126
137
  const session = wake.session ?? runner.session;
127
- const sent = session
128
- ? await deps.send(session, wake.message, runner.delivery ?? "immediate").catch((error) => ({ ok: false, error: error.message }))
129
- : { ok: false, error: "the wake names no session and the runner has none" };
138
+ const holding = session ? state.open?.[session] : undefined;
139
+ const sent = !session
140
+ ? { ok: false, error: "the wake names no session and the runner has none" }
141
+ : holding
142
+ ? { ok: false, error: `held: the wake sent ${ageLabel(deps.now - Date.parse(holding.at))} ago has not reached the session yet` }
143
+ : await deps.send(session, wake.message, runner.delivery ?? "immediate").catch((error) => ({ ok: false, error: error.message }));
144
+ if (session && sent.ok)
145
+ (state.open ??= {})[session] = { at: new Date(deps.now).toISOString(), message: wake.message };
130
146
  const reason = sent.ok ? null : sent.error ?? "the app refused the message";
131
147
  if (!reason)
132
148
  state.lastDelivered += 1;
@@ -143,6 +159,14 @@ async function runWakeRunner(runner, deps) {
143
159
  (0, runtime_1.emitNervesEvent)({ level: problems.length ? "warn" : "info", component: "senses", event: "senses.wake_runner_run", message: "ran a wake runner and delivered its wakes", meta: { runner: runner.name, wakes: state.lastWakes, delivered: state.lastDelivered, problems: problems.length } });
144
160
  return state;
145
161
  }
162
+ const ageLabel = (ms) => `${Math.max(1, Math.round(ms / 60_000))} min`;
163
+ /** The wakes sent earlier that are still in the app's queue, by session: the ones the session's log does not show and that are younger than the hold. */
164
+ function openWakes(previous, deps) {
165
+ return Object.fromEntries(Object.entries(previous.open ?? {}).filter(([session, wake]) => {
166
+ const sentAt = Date.parse(wake.at);
167
+ return deps.now - sentAt < exports.WAKE_HOLD_MS && !deps.delivered(session, wake.message, sentAt);
168
+ }));
169
+ }
146
170
  function fail(runner, state, reason) {
147
171
  state.lastError = reason;
148
172
  (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.wake_runner_error", message: "a wake runner's command did not give wakes; nothing was delivered", meta: { runner: runner.name, error: reason } });
@@ -154,6 +178,6 @@ async function runWakeRunners(agentRoot, runners, deps, only) {
154
178
  const states = Object.fromEntries(runners.map(runner => [runner.name, stored[runner.name] ?? {}]));
155
179
  for (const runner of runners)
156
180
  if (!only || only.has(runner.name))
157
- states[runner.name] = await runWakeRunner(runner, deps);
181
+ states[runner.name] = await runWakeRunner(runner, deps, stored[runner.name]);
158
182
  (0, store_1.writeJson)((0, wake_runner_state_1.wakeRunnerStateFile)(agentRoot), states);
159
183
  }
@@ -412,6 +412,24 @@ function createBlueBubblesClient(config = (0, config_1.getBlueBubblesConfig)(),
412
412
  throw new Error(`BlueBubbles reaction failed (${response.status}): ${errorText || "unknown"}`);
413
413
  }
414
414
  },
415
+ async sendAttachment(params) {
416
+ await assertHostAccount();
417
+ const chatGuid = await resolveChatGuid(params.chat, config, channelConfig);
418
+ if (!chatGuid)
419
+ throw new Error("BlueBubbles could not find this chat.");
420
+ const form = new FormData();
421
+ form.append("chatGuid", chatGuid);
422
+ form.append("tempGuid", (0, node_crypto_1.randomUUID)());
423
+ form.append("name", params.file.name);
424
+ form.append("attachment", new Blob([new Uint8Array(params.file.bytes)], { type: params.file.contentType }), params.file.name);
425
+ const url = buildBlueBubblesApiUrl(config.serverUrl, "/api/v1/message/attachment", config.password);
426
+ // An upload takes longer than a text send; give it a minute on top of the usual timeout.
427
+ const response = await fetch(url, { method: "POST", body: form, signal: AbortSignal.timeout(channelConfig.requestTimeoutMs + 60_000) });
428
+ if (!response.ok) {
429
+ const errorText = await response.text().catch(() => "");
430
+ throw new Error(`BlueBubbles attachment failed (${response.status}): ${errorText || "unknown"}`);
431
+ }
432
+ },
415
433
  async editMessage(params) {
416
434
  await assertHostAccount();
417
435
  const messageGuid = params.messageGuid.trim();
@@ -81,6 +81,7 @@ const bluebubbles_meta_guard_1 = require("../bluebubbles-meta-guard");
81
81
  const model_1 = require("./model");
82
82
  const client_1 = require("./client");
83
83
  const reactions_1 = require("./reactions");
84
+ const send_file_1 = require("./send-file");
84
85
  const tools_chat_1 = require("../../repertoire/tools-chat");
85
86
  const host_account_verifier_1 = require("./host-account-verifier");
86
87
  const webhook_registration_1 = require("./webhook-registration");
@@ -1895,6 +1896,7 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1895
1896
  chatActions: (0, tools_chat_1.chatActionsForTurn)({
1896
1897
  setReplyTarget: (selection) => replyTarget.setSelection(selection),
1897
1898
  react: (emoji, messageId) => (0, reactions_1.reactInBlueBubbles)(client, event.chat, emoji, messageId),
1899
+ sendFile: (filePath, caption) => (0, send_file_1.sendFileInBlueBubbles)(client, event.chat, filePath, caption),
1898
1900
  }, event.messageGuid),
1899
1901
  },
1900
1902
  });
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_IMESSAGE_FILE_BYTES = void 0;
4
+ exports.sendFileInBlueBubbles = sendFileInBlueBubbles;
5
+ const runtime_1 = require("../../nerves/runtime");
6
+ const chat_file_1 = require("../chat-file");
7
+ /** iMessage itself carries files far larger than this; the cap keeps one upload from tying up the turn. */
8
+ exports.MAX_IMESSAGE_FILE_BYTES = 100_000_000;
9
+ /** The shared send_file action on iMessage: the file, then its caption as a message of its own. */
10
+ async function sendFileInBlueBubbles(client, chat, filePath, caption) {
11
+ if (!client.sendAttachment)
12
+ throw new Error("this iMessage connection can't send files.");
13
+ const file = await (0, chat_file_1.readChatFile)(filePath, exports.MAX_IMESSAGE_FILE_BYTES);
14
+ await client.sendAttachment({ chat, file });
15
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.bluebubbles_file_sent", message: "sent a file over iMessage", meta: { contentType: file.contentType } });
16
+ const text = caption.trim();
17
+ if (text)
18
+ await client.sendText({ chat, text });
19
+ return `sent ${file.name}`;
20
+ }
@@ -0,0 +1,75 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.readChatFile = readChatFile;
37
+ const fs = __importStar(require("node:fs/promises"));
38
+ const path = __importStar(require("node:path"));
39
+ const runtime_1 = require("../nerves/runtime");
40
+ // The file a chat sense sends for the shared send_file tool. Each app takes files differently, but they all start here.
41
+ const CONTENT_TYPES = {
42
+ ".jpg": "image/jpeg",
43
+ ".jpeg": "image/jpeg",
44
+ ".png": "image/png",
45
+ ".gif": "image/gif",
46
+ ".webp": "image/webp",
47
+ ".heic": "image/heic",
48
+ ".pdf": "application/pdf",
49
+ ".txt": "text/plain",
50
+ ".md": "text/markdown",
51
+ ".csv": "text/csv",
52
+ ".json": "application/json",
53
+ ".zip": "application/zip",
54
+ ".epub": "application/epub+zip",
55
+ ".mp3": "audio/mpeg",
56
+ ".m4a": "audio/mp4",
57
+ ".mp4": "video/mp4",
58
+ ".mov": "video/quicktime",
59
+ };
60
+ function megabytes(bytes) {
61
+ return `${(bytes / 1_000_000).toFixed(1)} MB`;
62
+ }
63
+ /** Reads a local file to send into a chat, refusing one the app won't take. */
64
+ async function readChatFile(filePath, maxBytes) {
65
+ const stat = await fs.stat(filePath);
66
+ if (!stat.isFile())
67
+ throw new Error(`${filePath} is not a file`);
68
+ if (stat.size === 0)
69
+ throw new Error(`${filePath} is empty`);
70
+ if (stat.size > maxBytes)
71
+ throw new Error(`${path.basename(filePath)} is ${megabytes(stat.size)}; this chat takes files up to ${megabytes(maxBytes)}`);
72
+ const contentType = CONTENT_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream";
73
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.chat_file_read", message: "read a file to send into a chat", meta: { contentType, bytes: stat.size } });
74
+ return { name: path.basename(filePath), contentType, bytes: await fs.readFile(filePath) };
75
+ }
@@ -35,6 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.MAX_TEAMS_IMAGE_CAPTION_LENGTH = exports.MAX_TEAMS_INLINE_IMAGE_BYTES = void 0;
37
37
  exports.prepareTeamsImage = prepareTeamsImage;
38
+ exports.teamsImageFileSender = teamsImageFileSender;
38
39
  exports.createTeamsImageSender = createTeamsImageSender;
39
40
  const fs = __importStar(require("node:fs/promises"));
40
41
  const path = __importStar(require("node:path"));
@@ -93,6 +94,14 @@ async function prepareTeamsImage(input) {
93
94
  name: `${path.basename(input.path, path.extname(input.path)).slice(0, 100)}${contentType === "image/png" ? ".png" : ".jpg"}`,
94
95
  };
95
96
  }
97
+ /** Binds the shared send_file action to this Teams conversation: Teams takes PNG and JPEG images inline. */
98
+ function teamsImageFileSender(send, agentName, agentRoot) {
99
+ return async (filePath, caption) => {
100
+ const attachment = await prepareTeamsImage({ path: filePath, agentName, agentRoot });
101
+ const activityId = await send(attachment, caption);
102
+ return `sent the image; Teams accepted it (activity ${activityId})`;
103
+ };
104
+ }
96
105
  function createTeamsImageSender(send, replyToId, entities = []) {
97
106
  return async (attachment, caption) => {
98
107
  if (caption.length > exports.MAX_TEAMS_IMAGE_CAPTION_LENGTH)
@@ -989,7 +989,7 @@ async function handleTeamsMessage(text, stream, conversationId, teamsContext, se
989
989
  summarize: (0, core_1.createSummarize)("human"),
990
990
  tenantId: teamsContext.tenantId,
991
991
  botApi: teamsContext.botApi,
992
- teamsSendImage: teamsContext.teamsSendImage,
992
+ ...(teamsContext.teamsSendImage ? { chatActions: { sendFile: (0, teams_image_1.teamsImageFileSender)(teamsContext.teamsSendImage, agentName, owner.agentRoot) } } : {}),
993
993
  } : {}) };
994
994
  let currentText = text;
995
995
  const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)(owner) ?? undefined;
@@ -126,7 +126,10 @@ function createSanctuaryTelegramAuthorityTransport(client, verification) {
126
126
  if (method !== "getUpdates") {
127
127
  return await client.request("telegram.request", {
128
128
  method,
129
- body,
129
+ // A file crosses to the root as base64; the root rebuilds it and sends the upload itself.
130
+ body: Object.fromEntries(Object.entries(body).map(([key, value]) => [key, (0, telegram_client_1.isTelegramInputFile)(value)
131
+ ? { kind: value.kind, name: value.name, contentType: value.contentType, bodyBase64: value.bytes.toString("base64") }
132
+ : value])),
130
133
  ...(currentObservation ? {
131
134
  observation: {
132
135
  updateId: currentObservation.payload.updateId,
@@ -3,6 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createTelegramChatActions = createTelegramChatActions;
4
4
  const runtime_1 = require("../nerves/runtime");
5
5
  const tools_chat_1 = require("../repertoire/tools-chat");
6
+ const telegram_client_1 = require("./telegram-client");
7
+ const chat_file_1 = require("./chat-file");
8
+ const TELEGRAM_PHOTO_TYPES = new Set(["image/jpeg", "image/png", "image/webp"]);
6
9
  function telegramMessageId(value) {
7
10
  return /^[1-9][0-9]*$/u.test(value) && Number.isSafeInteger(Number(value)) ? Number(value) : undefined;
8
11
  }
@@ -12,6 +15,7 @@ function telegramMessageId(value) {
12
15
  */
13
16
  function createTelegramChatActions(api, chatId, inboundMessageId) {
14
17
  let selection = { target: "current_lane" };
18
+ const replyToMessageId = () => selection.target === "thread" ? telegramMessageId(selection.messageId) : undefined;
15
19
  return {
16
20
  actions: (0, tools_chat_1.chatActionsForTurn)({
17
21
  react: async (emoji, messageId) => {
@@ -28,7 +32,23 @@ function createTelegramChatActions(api, chatId, inboundMessageId) {
28
32
  selection = next;
29
33
  return next.target === "thread" ? `my reply will answer message ${next.messageId}` : "my reply will post plainly in the chat";
30
34
  },
35
+ // Photos show inline; anything else arrives as a document. The file follows the reply target, like text does.
36
+ sendFile: async (filePath, caption) => {
37
+ const text = caption.trim();
38
+ if (text.length > 1_024)
39
+ throw new Error("a Telegram caption can be up to 1,024 characters");
40
+ const file = await (0, chat_file_1.readChatFile)(filePath, telegram_client_1.MAX_TELEGRAM_UPLOAD_BYTES);
41
+ const field = TELEGRAM_PHOTO_TYPES.has(file.contentType) ? "photo" : "document";
42
+ const replyTo = replyToMessageId();
43
+ await api.request(field === "photo" ? "sendPhoto" : "sendDocument", {
44
+ chat_id: chatId,
45
+ [field]: { kind: "telegram_input_file", ...file },
46
+ ...(text ? { caption: text } : {}),
47
+ ...(replyTo ? { reply_parameters: { message_id: replyTo } } : {}),
48
+ });
49
+ return `sent ${file.name}`;
50
+ },
31
51
  }, inboundMessageId),
32
- replyToMessageId: () => selection.target === "thread" ? telegramMessageId(selection.messageId) : undefined,
52
+ replyToMessageId,
33
53
  };
34
54
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TELEGRAM_APPROVAL_TOMBSTONE_TTL_MS = exports.TELEGRAM_APPROVAL_TERMINAL_EDIT_TIMEOUT_MS = exports.TELEGRAM_APPROVAL_EXPIRED_TEXT = exports.TELEGRAM_APPROVAL_TTL_MS = exports.FileTelegramPendingApprovalStore = exports.FileTelegramUpdateInboxStore = exports.TELEGRAM_ALLOWED_UPDATES = exports.FileTelegramOffsetStore = exports.TelegramApiError = void 0;
3
+ exports.TELEGRAM_APPROVAL_TOMBSTONE_TTL_MS = exports.TELEGRAM_APPROVAL_TERMINAL_EDIT_TIMEOUT_MS = exports.TELEGRAM_APPROVAL_EXPIRED_TEXT = exports.TELEGRAM_APPROVAL_TTL_MS = exports.FileTelegramPendingApprovalStore = exports.FileTelegramUpdateInboxStore = exports.TELEGRAM_ALLOWED_UPDATES = exports.FileTelegramOffsetStore = exports.MAX_TELEGRAM_UPLOAD_BYTES = exports.TelegramApiError = void 0;
4
+ exports.isTelegramInputFile = isTelegramInputFile;
4
5
  exports.telegramUpdateMessageCoordinates = telegramUpdateMessageCoordinates;
5
6
  exports.createTelegramLongPoll = createTelegramLongPoll;
6
7
  exports.classifyTelegramPersistedApprovalState = classifyTelegramPersistedApprovalState;
@@ -27,6 +28,23 @@ class TelegramApiError extends Error {
27
28
  }
28
29
  }
29
30
  exports.TelegramApiError = TelegramApiError;
31
+ /** The largest file the agent uploads to Telegram; the Bot API takes photos up to 10 MB. */
32
+ exports.MAX_TELEGRAM_UPLOAD_BYTES = 10_000_000;
33
+ function isTelegramInputFile(value) {
34
+ return typeof value === "object" && value !== null && value.kind === "telegram_input_file";
35
+ }
36
+ function telegramRequestInit(body) {
37
+ if (!Object.values(body).some(isTelegramInputFile))
38
+ return { headers: { "content-type": "application/json" }, body: JSON.stringify(body) };
39
+ const form = new FormData();
40
+ for (const [key, value] of Object.entries(body)) {
41
+ if (isTelegramInputFile(value))
42
+ form.append(key, new Blob([new Uint8Array(value.bytes)], { type: value.contentType }), value.name);
43
+ else
44
+ form.append(key, typeof value === "string" ? value : JSON.stringify(value));
45
+ }
46
+ return { body: form };
47
+ }
30
48
  const durableAtomicWrite = (filePath, contents) => (0, atomic_file_1.writeFileAtomicSync)(filePath, contents);
31
49
  class FileTelegramOffsetStore {
32
50
  path;
@@ -1717,8 +1735,7 @@ function createTelegramBotApi(options) {
1717
1735
  try {
1718
1736
  const response = await fetchImpl(`${baseUrl}/${method}`, {
1719
1737
  method: "POST",
1720
- headers: { "content-type": "application/json" },
1721
- body: JSON.stringify(body),
1738
+ ...telegramRequestInit(body),
1722
1739
  signal: requestSignal,
1723
1740
  });
1724
1741
  const envelope = parseEnvelope(await response.text(), response.status, options.token);
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1124",
3
+ "version": "0.1.0-alpha.1126",
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.1124",
9
+ "version": "0.1.0-alpha.1126",
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.1124",
3
+ "version": "0.1.0-alpha.1126",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },