@ouro.bot/cli 0.1.0-alpha.1361 → 0.1.0-alpha.1364

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.1364",
6
+ "changes": [
7
+ "The Butler can send the messages it starts itself (house notices, external events, unprompted messages) to the owner's primary agent over A2A instead of to Telegram, set by senses.telegram.ownerNoticesTo in agent.json; replies stay on Telegram, and while the peer can't be reached only urgent messages go to Telegram, marked as a fallback."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1363",
12
+ "changes": [
13
+ "File tools (read_file, write_file, edit_file, grep) and shell take an optional cwd that relative paths start from, and a path that names nothing says which absolute path was tried."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1361",
6
18
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1361",
2
+ "runtimeVersion": "0.1.0-alpha.1364",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -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.1361</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1364</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -224,6 +224,27 @@ function normalizeAppSessionsConfig(rawSense, configFile) {
224
224
  result.digest = normalizeDigest(rawSense.digest, fail);
225
225
  return result;
226
226
  }
227
+ function normalizeOwnerNoticesTo(value, configFile) {
228
+ const fail = (message) => {
229
+ (0, runtime_1.emitNervesEvent)({ level: "error", event: "config_identity.error", component: "config/identity", message: "agent config has an invalid Telegram owner route", meta: { path: configFile } });
230
+ throw new Error(`agent.json at ${configFile}: ${message}`);
231
+ };
232
+ if (!value || typeof value !== "object" || Array.isArray(value))
233
+ return fail("senses.telegram.ownerNoticesTo must be { cardUrl, did }.");
234
+ const { cardUrl, did } = value;
235
+ let protocol = "";
236
+ try {
237
+ protocol = typeof cardUrl === "string" ? new URL(cardUrl).protocol : "";
238
+ }
239
+ catch {
240
+ protocol = "";
241
+ }
242
+ if (protocol !== "http:" && protocol !== "https:")
243
+ return fail("senses.telegram.ownerNoticesTo.cardUrl must be an http or https URL.");
244
+ if (typeof did !== "string" || !did.startsWith("did:key:"))
245
+ return fail("senses.telegram.ownerNoticesTo.did must be a did:key.");
246
+ return { cardUrl: cardUrl, did };
247
+ }
227
248
  function normalizeSenses(value, configFile) {
228
249
  const defaults = {
229
250
  cli: { ...exports.DEFAULT_AGENT_SENSES.cli },
@@ -318,6 +339,11 @@ function normalizeSenses(value, configFile) {
318
339
  defaults[senseName] = { enabled, ...normalizeAppSessionsConfig(rawSense, configFile) };
319
340
  continue;
320
341
  }
342
+ const ownerNoticesTo = rawSense.ownerNoticesTo;
343
+ if (senseName === "telegram" && ownerNoticesTo !== undefined) {
344
+ defaults[senseName] = { enabled, ownerNoticesTo: normalizeOwnerNoticesTo(ownerNoticesTo, configFile) };
345
+ continue;
346
+ }
321
347
  defaults[senseName] = { enabled };
322
348
  }
323
349
  return defaults;
@@ -39,6 +39,7 @@ exports.insideAgentFolder = insideAgentFolder;
39
39
  exports.psycheFileClass = psycheFileClass;
40
40
  exports.psycheWriteAllowed = psycheWriteAllowed;
41
41
  exports.psycheEditNote = psycheEditNote;
42
+ exports.fileToolPath = fileToolPath;
42
43
  exports.guardInvocation = guardInvocation;
43
44
  const fs = __importStar(require("node:fs"));
44
45
  const path = __importStar(require("node:path"));
@@ -56,6 +57,7 @@ const REASONS = {
56
57
  readBeforeEdit: "i need to read that file first before i can edit it.",
57
58
  readBeforeOverwrite: "i need to read that file first before i can overwrite it.",
58
59
  protectedPath: "that path is protected — i can read it but not modify it.",
60
+ unresolvedCwd: "this call names a cwd, but no home is known to resolve it from; pass an absolute path instead.",
59
61
  unreadablePath: "that path is protected — i can't read it.",
60
62
  destructiveCommand: "that command is too dangerous to run — it could cause irreversible damage.",
61
63
  // Trust reasons (vary by relationship)
@@ -1244,13 +1246,37 @@ function syncSecretShellRefused(command) {
1244
1246
  return command.includes(path.resolve((0, sync_1.syncSecretDir)()));
1245
1247
  }
1246
1248
  // --- main entry point ---
1247
- function guardInvocation(toolName, args, context) {
1249
+ /** The file tools whose path may start from a cwd the call names. */
1250
+ const CWD_FILE_TOOLS = new Set(["read_file", "write_file", "edit_file", "grep"]);
1251
+ /**
1252
+ * Where a file tool's path lands: an absolute path as given; a relative one from `cwd` when the call names one (itself
1253
+ * relative to home unless absolute), else from home. The guard and the tool both use this, so they check the same file.
1254
+ */
1255
+ function fileToolPath(target, cwd, home) {
1256
+ if (path.isAbsolute(target))
1257
+ return target;
1258
+ const base = cwd ? path.resolve(home, cwd) : home;
1259
+ return path.resolve(base, target);
1260
+ }
1261
+ /** The call with its path made absolute from cwd, so every check below sees the file the tool will touch; null if it can't be. */
1262
+ function withCwdResolved(toolName, args, home) {
1263
+ if (!CWD_FILE_TOOLS.has(toolName) || typeof args.cwd !== "string" || args.cwd === "")
1264
+ return args;
1265
+ if (!home)
1266
+ return null;
1267
+ const target = args.path || (toolName === "grep" ? "." : "");
1268
+ return target ? { ...args, path: fileToolPath(target, args.cwd, home) } : args;
1269
+ }
1270
+ function guardInvocation(toolName, rawArgs, context) {
1248
1271
  (0, runtime_1.emitNervesEvent)({
1249
1272
  component: "tools",
1250
1273
  event: "tools.guard_check",
1251
1274
  message: "guardrail check",
1252
1275
  meta: { toolName },
1253
1276
  });
1277
+ const args = withCwdResolved(toolName, rawArgs, context.agentRoot);
1278
+ if (!args)
1279
+ return deny(REASONS.unresolvedCwd);
1254
1280
  // Read-only tools skip the structural and trust guardrails; only the sync key's directory is closed to them.
1255
1281
  if (READ_ONLY_TOOLS.has(toolName))
1256
1282
  return syncSecretReadRefused(toolName, args, context.agentRoot) ? deny(REASONS.unreadablePath) : allow;
@@ -11,10 +11,11 @@ const crypto_1 = require("crypto");
11
11
  const runtime_1 = require("../nerves/runtime");
12
12
  const sessions = new Map();
13
13
  const MAX_OUTPUT_LINES = 200;
14
- function spawnBackgroundShell(command, owner) {
14
+ /** Runs in `cwd` when given, else in the owner's home. */
15
+ function spawnBackgroundShell(command, owner, cwd) {
15
16
  const id = (0, crypto_1.randomUUID)();
16
17
  const proc = (0, child_process_1.spawn)("sh", ["-c", command], {
17
- cwd: owner.agentRoot,
18
+ cwd: cwd ?? owner.agentRoot,
18
19
  stdio: ["pipe", "pipe", "pipe"],
19
20
  });
20
21
  const session = {
@@ -42,6 +42,7 @@ const file_state_1 = require("../mind/file-state");
42
42
  const scrutiny_1 = require("../mind/scrutiny");
43
43
  const tools_base_1 = require("./tools-base");
44
44
  const guardrails_1 = require("./guardrails");
45
+ const runtime_1 = require("../nerves/runtime");
45
46
  const tool_limits_1 = require("./tool-limits");
46
47
  /** The profile of a file tool that only reads, so a card can say `read`; it is the dispatcher's own default. */
47
48
  const READS_ONLY = { mutates: "none", risk: "low" };
@@ -63,13 +64,17 @@ function psycheNoteFor(resolvedPath, ctx) {
63
64
  return "";
64
65
  }
65
66
  }
66
- /** Relative paths start in the agent's home (its bundle); absolute paths are used as given. */
67
- function resolveLocalToolPath(targetPath, ctx) {
68
- if (!path.isAbsolute(targetPath)) {
69
- return path.resolve(ctx?.agentRoot ?? (0, identity_1.getAgentRoot)(), targetPath);
70
- }
71
- return targetPath;
67
+ /** Relative paths start in the agent's home (its bundle), or in `cwd` when the call names one; absolute paths are used as given. */
68
+ function resolveLocalToolPath(targetPath, ctx, cwd) {
69
+ return path.isAbsolute(targetPath) ? targetPath : (0, guardrails_1.fileToolPath)(targetPath, cwd || undefined, ctx?.agentRoot ?? (0, identity_1.getAgentRoot)());
70
+ }
71
+ const CWD_PARAMETER = { type: "string", description: "folder a relative path starts from (defaults to your home)" };
72
+ /** A result for a path that names nothing, with the absolute path tried, so a wrong starting folder shows in the result. */
73
+ function notFound(tool, given, tried, what) {
74
+ (0, runtime_1.emitNervesEvent)({ component: "tools", event: "tools.file_not_found", message: "a file tool's path named nothing", meta: { tool, relative: !path.isAbsolute(given) } });
75
+ return (0, tools_base_1.withCode)(`error: no ${what} at ${tried}${path.isAbsolute(given) ? "" : ` (from the relative path ${given})`}`, "not-found");
72
76
  }
77
+ const isMissing = (error) => error?.code === "ENOENT";
73
78
  function homeOf(ctx) {
74
79
  return ctx?.agentRoot ?? (0, identity_1.getAgentRoot)();
75
80
  }
@@ -119,6 +124,7 @@ exports.fileToolDefinitions = [
119
124
  type: "object",
120
125
  properties: {
121
126
  path: { type: "string" },
127
+ cwd: CWD_PARAMETER,
122
128
  offset: { type: "number", description: "1-based line number to start reading from" },
123
129
  limit: { type: "number", description: "maximum number of lines to return" },
124
130
  char_offset: { type: "number", description: "1-based character to start from within the first line shown, to read on through a line over 30,000 characters" },
@@ -128,8 +134,16 @@ exports.fileToolDefinitions = [
128
134
  },
129
135
  },
130
136
  handler: (a, ctx) => {
131
- const resolvedPath = resolveLocalToolPath(a.path, ctx);
132
- const raw = asBuffer(fs.readFileSync(resolvedPath));
137
+ const resolvedPath = resolveLocalToolPath(a.path, ctx, a.cwd);
138
+ let raw;
139
+ try {
140
+ raw = asBuffer(fs.readFileSync(resolvedPath));
141
+ }
142
+ catch (error) {
143
+ if (isMissing(error))
144
+ return notFound("read_file", a.path, resolvedPath, "file");
145
+ throw error;
146
+ }
133
147
  if ((0, tool_limits_1.looksBinary)(raw))
134
148
  return `[binary file, ${raw.length} bytes; not shown]`;
135
149
  const full = raw.toString("utf-8");
@@ -171,8 +185,9 @@ exports.fileToolDefinitions = [
171
185
  summaryKeys: ["path"],
172
186
  riskProfile: READS_ONLY,
173
187
  ax: { id: "tool:read_file", eager: true, group: "turn-files", when: "Pick this to see a file's exact text before you quote or change it; to find which file holds something, grep or glob first.", effect: "read", idempotent: true, errors: [
188
+ { code: "not-found", means: "Nothing is at the path; the result names the absolute path tried, so a relative path that started in the wrong folder shows there.", fix: "Pass cwd for the folder the path is relative to, or an absolute path." },
174
189
  { code: "guardrail-blocked", means: "The path is inside the folder holding the sync key, which no tool may read, or the path can't be resolved (a link loop or a folder you can't open).", fix: "Read a file outside that folder; for a path that won't resolve, check it with ls first." },
175
- { code: "invalid-arguments", means: "path is missing, or offset, limit or char_offset isn't a number.", fix: "Call read_file again with path as text and offset, limit and char_offset as numbers." },
190
+ { code: "invalid-arguments", means: "path is missing, cwd isn't text, or offset, limit or char_offset isn't a number.", fix: "Call read_file again with path and cwd as text and offset, limit and char_offset as numbers." },
176
191
  ] },
177
192
  },
178
193
  {
@@ -183,13 +198,13 @@ exports.fileToolDefinitions = [
183
198
  description: "Create a file, or replace one whole. It writes what you send and nothing of what was there, so read an existing file first when you mean to keep any of it. Prefer edit_file for a change to part of a file -- it only sends the diff.",
184
199
  parameters: {
185
200
  type: "object",
186
- properties: { path: { type: "string" }, content: { type: "string" } },
201
+ properties: { path: { type: "string" }, cwd: CWD_PARAMETER, content: { type: "string" } },
187
202
  required: ["path", "content"],
188
203
  },
189
204
  },
190
205
  },
191
206
  handler: (a, ctx) => {
192
- const resolvedPath = resolveLocalToolPath(a.path, ctx);
207
+ const resolvedPath = resolveLocalToolPath(a.path, ctx, a.cwd);
193
208
  fs.mkdirSync(path.dirname(resolvedPath), { recursive: true });
194
209
  fs.writeFileSync(resolvedPath, a.content, "utf-8");
195
210
  (0, scrutiny_1.trackModifiedFile)(resolvedPath);
@@ -216,6 +231,7 @@ exports.fileToolDefinitions = [
216
231
  type: "object",
217
232
  properties: {
218
233
  path: { type: "string" },
234
+ cwd: CWD_PARAMETER,
219
235
  old_string: { type: "string" },
220
236
  new_string: { type: "string" },
221
237
  },
@@ -224,7 +240,9 @@ exports.fileToolDefinitions = [
224
240
  },
225
241
  },
226
242
  handler: (a, ctx) => {
227
- const resolvedPath = resolveLocalToolPath(a.path, ctx);
243
+ const resolvedPath = resolveLocalToolPath(a.path, ctx, a.cwd);
244
+ if (!fs.existsSync(resolvedPath))
245
+ return notFound("edit_file", a.path, resolvedPath, "file");
228
246
  if (!tools_base_1.editFileReadTracker.has(resolvedPath)) {
229
247
  return (0, tools_base_1.withCode)(`error: you must read the file with read_file before editing it. call read_file on ${a.path} first.`, "read-first");
230
248
  }
@@ -289,6 +307,7 @@ exports.fileToolDefinitions = [
289
307
  summaryKeys: ["path"],
290
308
  riskProfile: { mutates: "durable_state_write", risk: "high", reason: "edits file contents" },
291
309
  ax: { id: "tool:edit_file", eager: true, group: "turn-files", when: "Pick this to change one exact passage of a file you have read, including psyche/TACIT.md, where what you've learned about how things work here lives; write_file is for new files and full rewrites.", effect: "write", errors: [
310
+ { code: "not-found", means: "Nothing is at the path; the result names the absolute path tried, so a relative path that started in the wrong folder shows there.", fix: "Pass cwd for the folder the path is relative to, or an absolute path." },
292
311
  { code: "read-first", means: "You haven't read this file with read_file yet, so the edit was refused.", fix: "Call read_file on the same path, then send the edit again." },
293
312
  { code: "no-match", means: "old_string appears nowhere in the file, often because whitespace or an earlier edit differs.", fix: "Read the file again and copy old_string from it exactly, indentation included." },
294
313
  { code: "ambiguous-match", means: "old_string appears more than once, so the edit can't tell which place you mean.", fix: "Add surrounding lines to old_string until it matches one place only." },
@@ -341,6 +360,8 @@ exports.fileToolDefinitions = [
341
360
  },
342
361
  handler: (a, ctx) => {
343
362
  const cwd = a.cwd ? resolveLocalToolPath(a.cwd, ctx) : homeOf(ctx);
363
+ if (!fs.statSync(cwd, { throwIfNoEntry: false })?.isDirectory())
364
+ return notFound("glob", a.cwd ?? cwd, cwd, "folder");
344
365
  // A cwd the caller chose is searched as asked; only the default (the whole home) leaves state/ out.
345
366
  const skipsState = !a.cwd && searchesWholeHome(cwd, cwd);
346
367
  const ignore = [...tool_limits_1.SKIP_DIRS.map((d) => `**/${d}/**`), ...(skipsState ? [`${RUNTIME_DATA_DIR}/**`] : [])];
@@ -353,6 +374,7 @@ exports.fileToolDefinitions = [
353
374
  summaryKeys: ["pattern", "cwd"],
354
375
  riskProfile: READS_ONLY,
355
376
  ax: { id: "tool:glob", group: "turn-files", when: "Pick this to find files by name pattern, such as every Markdown file under notes; to search inside files, use grep.", effect: "read", idempotent: true, errors: [
377
+ { code: "not-found", means: "Nothing is at the path; the result names the absolute path tried, so a relative path that started in the wrong folder shows there.", fix: "Pass cwd for the folder the path is relative to, or an absolute path." },
356
378
  { code: "guardrail-blocked", means: "The pattern or cwd reaches into the folder holding the sync key, or cwd can't be resolved.", fix: "Narrow cwd or the pattern so the search stays out of that folder." },
357
379
  { code: "invalid-arguments", means: "pattern is missing, or cwd isn't text.", fix: "Call glob again with pattern set, such as **/*.md, and cwd as a folder name if you want one." },
358
380
  ] },
@@ -367,7 +389,8 @@ exports.fileToolDefinitions = [
367
389
  type: "object",
368
390
  properties: {
369
391
  pattern: { type: "string", description: "regex pattern to search for" },
370
- path: { type: "string", description: "file or directory to search (defaults to your home)" },
392
+ path: { type: "string", description: "file or directory to search (defaults to cwd, else your home)" },
393
+ cwd: CWD_PARAMETER,
371
394
  context_lines: { type: "number", description: "number of surrounding context lines (default 0)" },
372
395
  include: { type: "string", description: "glob filter to limit searched files (e.g. *.md)" },
373
396
  ignore_case: { type: "boolean", description: "match without regard to case" },
@@ -378,7 +401,7 @@ exports.fileToolDefinitions = [
378
401
  },
379
402
  },
380
403
  handler: (a, ctx) => {
381
- const targetPath = a.path ? resolveLocalToolPath(a.path, ctx) : homeOf(ctx);
404
+ const targetPath = a.path || a.cwd ? resolveLocalToolPath(a.path || ".", ctx, a.cwd) : homeOf(ctx);
382
405
  const regex = new RegExp(a.pattern, a.ignore_case ? "i" : "");
383
406
  const contextLines = parseInt(a.context_lines || "0", 10);
384
407
  const includeGlob = a.include || undefined;
@@ -470,7 +493,7 @@ exports.fileToolDefinitions = [
470
493
  }
471
494
  const stat = fs.statSync(targetPath, { throwIfNoEntry: false });
472
495
  if (!stat)
473
- return "";
496
+ return notFound("grep", a.path || a.cwd || targetPath, targetPath, "file or folder");
474
497
  let files = [targetPath];
475
498
  if (!stat.isFile()) {
476
499
  files = collectFiles(targetPath);
@@ -490,6 +513,7 @@ exports.fileToolDefinitions = [
490
513
  summaryKeys: ["pattern", "path", "include"],
491
514
  riskProfile: READS_ONLY,
492
515
  ax: { id: "tool:grep", eager: true, group: "turn-files", when: "Pick this to learn which files and lines contain some text or regex; then read_file shows a match in full.", effect: "read", idempotent: true, errors: [
516
+ { code: "not-found", means: "Nothing is at the path; the result names the absolute path tried, so a relative path that started in the wrong folder shows there.", fix: "Pass cwd for the folder the path is relative to, or an absolute path." },
493
517
  { code: "guardrail-blocked", means: "The search path is, or contains, the folder holding the sync key, or it can't be resolved.", fix: "Pass a narrower path that leaves that folder out." },
494
518
  { code: "invalid-arguments", means: "pattern is missing, or context_lines, ignore_case or files_only has the wrong type.", fix: "Call grep again with pattern as text, context_lines as a number and the flags as true or false." },
495
519
  ] },
@@ -104,11 +104,12 @@ exports.shellToolDefinitions = [
104
104
  type: "function",
105
105
  function: {
106
106
  name: "shell",
107
- description: "Run a shell command in your home; cd does not persist between calls, and a failed command comes back with how it ended, its stdout and its stderr. Keeps the last 2000 lines or 30,000 characters of output and saves the full output to a file it names when it cuts.",
107
+ description: "Run a shell command in your home, or in cwd when you pass one; cd does not persist between calls, and a failed command comes back with how it ended, its stdout and its stderr. Keeps the last 2000 lines or 30,000 characters of output and saves the full output to a file it names when it cuts.",
108
108
  parameters: {
109
109
  type: "object",
110
110
  properties: {
111
111
  command: { type: "string" },
112
+ cwd: { type: "string", description: "folder to run the command in, relative to your home or absolute (defaults to your home)" },
112
113
  timeout_ms: {
113
114
  type: "number",
114
115
  description: "Timeout in milliseconds. Default: 30000. Max: 600000.",
@@ -148,9 +149,15 @@ exports.shellToolDefinitions = [
148
149
  meta: { command: a.command, patterns: destructivePatterns },
149
150
  });
150
151
  }
152
+ // A cwd starts from home when relative, the way the file tools' paths do; a folder that isn't there is said plainly.
153
+ const runIn = a.cwd ? path.resolve(shellHome(ctx), a.cwd) : undefined;
154
+ if (runIn !== undefined && !fs.statSync(runIn, { throwIfNoEntry: false })?.isDirectory()) {
155
+ (0, runtime_1.emitNervesEvent)({ component: "tools", event: "tool.shell_cwd_missing", message: "a shell call named a cwd that is not a folder", meta: { relative: !path.isAbsolute(a.cwd) } });
156
+ return (0, tool_error_code_1.withCode)(`error: no folder at ${runIn}${path.isAbsolute(a.cwd) ? "" : ` (from the relative cwd ${a.cwd})`}`, "not-found");
157
+ }
151
158
  // Background mode: spawn and return immediately
152
159
  if (a.background === true) {
153
- const session = (0, shell_sessions_1.spawnBackgroundShell)(a.command, shellOwner(ctx));
160
+ const session = (0, shell_sessions_1.spawnBackgroundShell)(a.command, shellOwner(ctx), runIn);
154
161
  return JSON.stringify({ id: session.id, command: session.command, status: session.status });
155
162
  }
156
163
  const MAX_TIMEOUT = 600000;
@@ -173,7 +180,7 @@ exports.shellToolDefinitions = [
173
180
  const timeout = Math.min(baseTimeout, MAX_TIMEOUT);
174
181
  const home = shellHome(ctx);
175
182
  const raw = await new Promise((resolve, reject) => {
176
- const child = (0, child_process_1.exec)(a.command, { encoding: "utf-8", timeout, cwd: home, maxBuffer: MAX_BUFFER }, (error, stdout, stderr) => {
183
+ const child = (0, child_process_1.exec)(a.command, { encoding: "utf-8", timeout, cwd: runIn ?? home, maxBuffer: MAX_BUFFER }, (error, stdout, stderr) => {
177
184
  if (error) {
178
185
  // A failing command's output gets the same tail cap and saved file, and the agent sees all of it: how it ended,
179
186
  // what it printed and what it complained about. Node's own message keeps only stderr.
@@ -198,6 +205,7 @@ exports.shellToolDefinitions = [
198
205
  ax: { id: "tool:shell", eager: true, group: "turn-shell", when: "Pick this to run a program or script in your home; for plain file reads and searches, read_file, grep and glob are safer.", effect: "consequential", confirm: "Approve shell with exact arguments <the call's arguments as JSON>?", errors: [
199
206
  { code: "command-failed", means: "The command ran and exited non-zero; its stdout and stderr follow the first line.", fix: "Read stderr, fix the command or its input, and run it again." },
200
207
  { code: "command-timed-out", means: "The command ran past its timeout and was stopped; whatever it printed follows.", fix: "Run it again with a larger timeout_ms, at most 600000, or with background: true and watch it with shell_status." },
208
+ { code: "not-found", means: "cwd names no folder; the result gives the absolute path tried.", fix: "Pass cwd as a folder that exists, relative to your home or absolute." },
201
209
  { code: "command-not-started", means: "The shell couldn't start the command at all, so nothing ran.", fix: "Check the program's name and that it is installed, then run it again." },
202
210
  { code: "guardrail-blocked", means: "The line writes to a protected path, names the sync key's folder, or runs a command this person isn't trusted for.", fix: "Change the command so it stays off protected paths, or run it from a chat with your owner." },
203
211
  { code: "orientation-hold", means: "This turn is on a correction hold and the command changes things, so it waits.", fix: "Call orientation_get, settle what the person meant, then run the command if it is still right." },
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OWNER_ROUTE_FALLBACK_PREFIX = void 0;
4
+ exports.ownerRouteUrgency = ownerRouteUrgency;
5
+ exports.ownerRouteDedupeKey = ownerRouteDedupeKey;
6
+ exports.ownerRouteItem = ownerRouteItem;
7
+ exports.formatOwnerRouteMessage = formatOwnerRouteMessage;
8
+ exports.createA2AOwnerRoute = createA2AOwnerRoute;
9
+ exports.ownerRouteForAgent = ownerRouteForAgent;
10
+ const node_crypto_1 = require("node:crypto");
11
+ const client_1 = require("../a2a/client");
12
+ const identity_1 = require("../a2a/identity");
13
+ const identity_2 = require("../heart/identity");
14
+ const runtime_1 = require("../nerves/runtime");
15
+ exports.OWNER_ROUTE_FALLBACK_PREFIX = "Slugger can't be reached, so this comes to you directly.";
16
+ function ownerRouteUrgency(key, critical) {
17
+ if (critical)
18
+ return "now";
19
+ if (key.startsWith("owner-notice:house-sweep:"))
20
+ return "batch";
21
+ return "today";
22
+ }
23
+ const slug = (value) => value.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "");
24
+ function ownerRouteDedupeKey(key, text) {
25
+ const [kind, ...rest] = key.split(":");
26
+ const tail = rest.join(":");
27
+ let condition;
28
+ if (kind === "external-event") {
29
+ // The generation counts re-fires of one event; the condition is its source and id.
30
+ let identity;
31
+ try {
32
+ identity = JSON.parse(tail);
33
+ }
34
+ catch {
35
+ identity = null;
36
+ }
37
+ condition = Array.isArray(identity) && identity.length >= 2 ? `${identity[0]}-${identity[1]}` : key;
38
+ }
39
+ else if (kind === "proactive") {
40
+ // A proactive key is a fresh UUID each time, so the same words name the same condition.
41
+ condition = `proactive-${(0, node_crypto_1.createHash)("sha256").update(text).digest("hex").slice(0, 12)}`;
42
+ }
43
+ else {
44
+ condition = kind === "owner-notice" ? tail : key;
45
+ }
46
+ return `butler-${slug(condition)}`.slice(0, 120);
47
+ }
48
+ function ownerRouteItem(key, text, critical) {
49
+ return { key, text, urgency: ownerRouteUrgency(key, critical), dedupeKey: ownerRouteDedupeKey(key, text) };
50
+ }
51
+ function formatOwnerRouteMessage(item) {
52
+ const firstLine = item.text.trim().split("\n")[0].trim();
53
+ const ask = firstLine.length > 200 ? `${firstLine.slice(0, 199)}…` : firstLine;
54
+ return [
55
+ "from: the Butler (sanctuary, Ari's house server)",
56
+ `urgency: ${item.urgency}`,
57
+ `ask: ${ask}`,
58
+ "why only Ari: it is about his house, and the Butler reports to him",
59
+ `steps: ${item.text}`,
60
+ "deadline: none",
61
+ `dedupe key: ${item.dedupeKey}`,
62
+ ].join("\n");
63
+ }
64
+ const reason = (error) => error instanceof Error ? error.message : String(error);
65
+ function createA2AOwnerRoute(options) {
66
+ const fetchCard = options.fetchCard ?? client_1.fetchA2AAgentCard;
67
+ const send = options.send ?? client_1.sendSealedA2AChat;
68
+ return async (item) => {
69
+ try {
70
+ const served = (0, client_1.cardDid)(await fetchCard(options.cardUrl));
71
+ if (served !== options.did) {
72
+ const detail = `the card at ${options.cardUrl} serves ${served}, not the pinned ${options.did}`;
73
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.telegram_owner_route_pin_mismatch", message: "the owner route's peer card serves another DID", meta: { cardUrl: options.cardUrl, served: served ?? null, pinned: options.did } });
74
+ return { status: "unreachable", detail };
75
+ }
76
+ await send({ cardUrl: options.cardUrl, text: formatOwnerRouteMessage(item), identity: await options.loadIdentity() });
77
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_owner_route_delivered", message: "sent a self-started Butler message to the owner's primary agent", meta: { urgency: item.urgency, dedupeKey: item.dedupeKey } });
78
+ return { status: "delivered" };
79
+ }
80
+ catch (error) {
81
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.telegram_owner_route_unreachable", message: "the owner's primary agent could not be reached", meta: { urgency: item.urgency, dedupeKey: item.dedupeKey, error: reason(error) } });
82
+ return { status: "unreachable", detail: reason(error) };
83
+ }
84
+ };
85
+ }
86
+ /** The owner route `agent.json` names (`senses.telegram.ownerNoticesTo`), signing as this agent's A2A identity; none when unset. */
87
+ function ownerRouteForAgent(agentName, agentRoot) {
88
+ const peer = (0, identity_2.loadAgentConfig)({ agentName, agentRoot }).senses?.telegram.ownerNoticesTo;
89
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_owner_route_configured", message: "read the Telegram owner route", meta: { agentName, cardUrl: peer?.cardUrl ?? null } });
90
+ if (!peer)
91
+ return undefined;
92
+ return createA2AOwnerRoute({ cardUrl: peer.cardUrl, did: peer.did, loadIdentity: () => (0, identity_1.loadSelfA2AIdentity)({ agentName }) });
93
+ }
@@ -91,6 +91,7 @@ const sanctuary_grounding_1 = require("./sanctuary-grounding");
91
91
  const telegram_approval_runtime_1 = require("./telegram-approval-runtime");
92
92
  const telegram_audit_ledger_1 = require("./telegram-audit-ledger");
93
93
  const session_events_1 = require("../heart/session-events");
94
+ const telegram_owner_route_1 = require("./telegram-owner-route");
94
95
  const telegram_handoff_1 = require("./telegram-handoff");
95
96
  const router_1 = require("../heart/external-events/router");
96
97
  const session_transaction_1 = require("../mind/session-transaction");
@@ -1054,12 +1055,59 @@ function createTelegramSenseApp(options) {
1054
1055
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_notice_held_for_pacing", message: "held a house notice for quiet hours or the daily message cap", meta: { agentName: options.agentName, reason: pacingReason } });
1055
1056
  return true;
1056
1057
  };
1058
+ // Keys the owner's primary agent accepted, so a retry is already sent (as with the effect journal for Telegram).
1059
+ const routedKeysPath = path.join(agentRoot, "state", "telegram", "routed-owner-notices.json");
1060
+ const fallbackText = (text) => `${telegram_owner_route_1.OWNER_ROUTE_FALLBACK_PREFIX}\n\n${text}`;
1061
+ /**
1062
+ * Offers a self-started message to the owner route. Returns null when it is handled (the peer has it, or it waits in the
1063
+ * held file for the peer), or the text Telegram should send: the message itself with no route, or, for an urgent message
1064
+ * the peer can't take, the message marked as a fallback.
1065
+ */
1066
+ const routeSelfStarted = async (text, key, critical = (0, telegram_handoff_1.isCriticalNoticeKey)(key), signal) => {
1067
+ if (!options.ownerRoute)
1068
+ return text;
1069
+ // Older held notices go first, so the peer hears them in order.
1070
+ await releaseHeldNotices(signal);
1071
+ const item = (0, telegram_owner_route_1.ownerRouteItem)(key, text, critical);
1072
+ const outcome = await options.ownerRoute(item);
1073
+ if (outcome.status === "delivered") {
1074
+ (0, telegram_handoff_1.recordReleasedHeldKeys)(routedKeysPath, [key]);
1075
+ return null;
1076
+ }
1077
+ if (item.urgency === "now") {
1078
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.telegram_owner_route_fallback", message: "the owner's primary agent can't be reached; an urgent message goes to Telegram", meta: { agentName: options.agentName, dedupeKey: item.dedupeKey, detail: outcome.detail } });
1079
+ return fallbackText(text);
1080
+ }
1081
+ const held = (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath);
1082
+ if (!held.some((notice) => notice.key === key))
1083
+ (0, telegram_handoff_1.writeHeldNotices)(heldNoticesPath, [...held, { key, text }]);
1084
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_notice_held_for_owner_route", message: "held a house notice until the owner's primary agent can be reached", meta: { agentName: options.agentName, dedupeKey: item.dedupeKey } });
1085
+ return null;
1086
+ };
1087
+ /** With an owner route, held notices go to the peer one by one; a critical one it can't take goes to Telegram as a fallback. */
1088
+ const releaseHeldNoticesToRoute = async (route, signal) => {
1089
+ const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
1090
+ for (const notice of (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath)) {
1091
+ const critical = (0, telegram_handoff_1.isCriticalNoticeKey)(notice.key);
1092
+ const outcome = await route((0, telegram_owner_route_1.ownerRouteItem)(notice.key, notice.text, critical));
1093
+ if (outcome.status !== "delivered" && !critical)
1094
+ continue;
1095
+ (0, telegram_handoff_1.writeHeldNotices)(heldNoticesPath, (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath).filter((entry) => entry.key !== notice.key));
1096
+ if (outcome.status === "delivered") {
1097
+ (0, telegram_handoff_1.recordReleasedHeldKeys)(routedKeysPath, [notice.key]);
1098
+ continue;
1099
+ }
1100
+ await recordAcceptedEffects(sessionPath, [await deliverButlerEffect(fallbackText(notice.text), notice.key, signal)]);
1101
+ }
1102
+ };
1057
1103
  let heldNoticeRelease = Promise.resolve();
1058
1104
  const releaseHeldNotices = async (signal) => {
1059
1105
  // Nearly always nothing is held: return without queueing, so ordinary turns and the reconcile tick pay nothing.
1060
1106
  if ((0, telegram_handoff_1.readHeldNotices)(heldNoticesPath).length === 0)
1061
1107
  return;
1062
1108
  const release = heldNoticeRelease.then(async () => {
1109
+ if (options.ownerRoute)
1110
+ return releaseHeldNoticesToRoute(options.ownerRoute, signal);
1063
1111
  const held = (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath);
1064
1112
  if (ownerChatIsHandedOff())
1065
1113
  return;
@@ -1881,10 +1929,13 @@ function createTelegramSenseApp(options) {
1881
1929
  return;
1882
1930
  }
1883
1931
  const key = `proactive:${(0, node_crypto_1.randomUUID)()}`;
1884
- if (holdNoticeDuringHandoff(proactiveText, key))
1932
+ const telegramText = await routeSelfStarted(proactiveText, key, undefined, signal);
1933
+ if (telegramText === null)
1934
+ return;
1935
+ if (holdNoticeDuringHandoff(telegramText, key))
1885
1936
  return;
1886
1937
  await releaseHeldNotices(signal);
1887
- const effect = await deliverButlerEffect(proactiveText, key, signal);
1938
+ const effect = await deliverButlerEffect(telegramText, key, signal);
1888
1939
  countProactiveSend();
1889
1940
  const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
1890
1941
  await recordAcceptedEffects(sessionPath, [effect]);
@@ -1905,8 +1956,10 @@ function createTelegramSenseApp(options) {
1905
1956
  const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
1906
1957
  const held = (0, telegram_handoff_1.readHeldNotices)(heldNoticesPath);
1907
1958
  const releasedKeys = (0, telegram_handoff_1.readReleasedHeldKeys)(releasedHeldKeysPath);
1959
+ const routedKeys = (0, telegram_handoff_1.readReleasedHeldKeys)(routedKeysPath);
1908
1960
  const ownerMessageExists = (candidate) => held.some((notice) => notice.key === candidate)
1909
1961
  || releasedKeys.includes(candidate)
1962
+ || routedKeys.includes(candidate)
1910
1963
  || getEffectJournal().readByIdempotencyKey(candidate) !== null;
1911
1964
  if (ownerMessageExists(key)) {
1912
1965
  // A retry after the message went out (or was held): finish the original send, never send a reworded second one.
@@ -1930,10 +1983,14 @@ function createTelegramSenseApp(options) {
1930
1983
  });
1931
1984
  return { status: "covered", effectKey: coveredBy };
1932
1985
  }
1933
- if (holdNoticeDuringHandoff(text, key, [key, ...relatedKeys].some(telegram_handoff_1.isCriticalNoticeKey)))
1986
+ const critical = [key, ...relatedKeys].some(telegram_handoff_1.isCriticalNoticeKey);
1987
+ const telegramText = await routeSelfStarted(text, key, critical, input.signal);
1988
+ if (telegramText === null)
1989
+ return { status: "sent", effectKey: key };
1990
+ if (holdNoticeDuringHandoff(telegramText, key, critical))
1934
1991
  return { status: "sent", effectKey: key };
1935
1992
  await releaseHeldNotices(input.signal);
1936
- const effect = await deliverButlerEffect(text, key, input.signal);
1993
+ const effect = await deliverButlerEffect(telegramText, key, input.signal);
1937
1994
  countProactiveSend();
1938
1995
  await recordAcceptedEffects(sessionPath, [effect]);
1939
1996
  return { status: "sent", effectKey: key };
@@ -1948,10 +2005,13 @@ function createTelegramSenseApp(options) {
1948
2005
  throw new Error("Telegram owner notice id is invalid");
1949
2006
  await runWithAcceptanceAuditOwner(async () => {
1950
2007
  const text = requiredText(input.text, "owner notice");
1951
- if (holdNoticeDuringHandoff(text, `owner-notice:${noticeId}`))
2008
+ const telegramText = await routeSelfStarted(text, `owner-notice:${noticeId}`, undefined, input.signal);
2009
+ if (telegramText === null)
2010
+ return;
2011
+ if (holdNoticeDuringHandoff(telegramText, `owner-notice:${noticeId}`))
1952
2012
  return;
1953
2013
  await releaseHeldNotices(input.signal);
1954
- const effect = await deliverButlerEffect(text, `owner-notice:${noticeId}`, input.signal);
2014
+ const effect = await deliverButlerEffect(telegramText, `owner-notice:${noticeId}`, input.signal);
1955
2015
  countProactiveSend();
1956
2016
  const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
1957
2017
  await recordAcceptedEffects(sessionPath, [effect]);
@@ -2266,6 +2326,7 @@ async function startTelegramSenseApp(agentName, waitForAuthority = false) {
2266
2326
  authorityTransport,
2267
2327
  // The owner is in Los Angeles; a container without TZ would otherwise run quiet hours on UTC.
2268
2328
  proactivePacing: { timeZone: process.env.TZ || "America/Los_Angeles" },
2329
+ ...(() => { const ownerRoute = (0, telegram_owner_route_1.ownerRouteForAgent)(agentName, (0, identity_1.getAgentRoot)(agentName)); return ownerRoute ? { ownerRoute } : {}; })(),
2269
2330
  ...(await createProductionTelegramRelationshipComposition(agentName, credentials, undefined, authorityTransport)),
2270
2331
  ...(agentName === "sanctuary" ? { privilegedFailsafe: {
2271
2332
  eventRoot: (0, router_1.getExternalEventRoot)(),
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1361",
3
+ "version": "0.1.0-alpha.1364",
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.1361",
9
+ "version": "0.1.0-alpha.1364",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1361",
3
+ "version": "0.1.0-alpha.1364",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {