@ouro.bot/cli 0.1.0-alpha.1370 → 0.1.0-alpha.1372

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.1372",
6
+ "changes": [
7
+ "ouro hook post-tool-use no longer loads the whole CLI: it sends from a small module, skips subagents, and sends at most one note per Claude Code session every five minutes. Measured on a stand-in agent with no daemon, the hook's node process went from a median 178 ms, 0.20 s of CPU and 80 MB to 86 ms, 0.07 s and 44 MB (bare node is 67 ms)."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1371",
12
+ "changes": [
13
+ "iMessage: a message whose reply never went out (the process died or the turn ended early) is now answered on recovery instead of being marked handled, and recovery finds messages saved by older builds."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1370",
6
18
  "changes": [
@@ -10,7 +22,8 @@
10
22
  {
11
23
  "version": "0.1.0-alpha.1369",
12
24
  "changes": [
13
- "iMessage no longer stops replying in a chat after runtime sync re-reads a message that already has an outcome; that message used to hold every later reply in the chat forever."
25
+ "iMessage no longer stops replying in a chat after runtime sync re-reads a message that already has an outcome; that message used to hold every later reply in the chat forever.",
26
+ "Update the Ouro UI files to Ouro UI core v1.12.0 and Ouro UI v1.3.454."
14
27
  ]
15
28
  },
16
29
  {
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1370",
2
+ "runtimeVersion": "0.1.0-alpha.1372",
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.1370</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1372</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -0,0 +1,149 @@
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.POST_TOOL_USE_SEND_TIMEOUT_MS = exports.POST_TOOL_USE_QUIET_MS = void 0;
37
+ exports.isPostToolUseHook = isPostToolUseHook;
38
+ exports.runPostToolUseHook = runPostToolUseHook;
39
+ exports.defaultPostToolUseDeps = defaultPostToolUseDeps;
40
+ /**
41
+ * `ouro hook post-tool-use --agent <agent>`, without loading the CLI.
42
+ *
43
+ * Claude Code runs this after every Bash, Edit and Write call in every session (`ouro setup`'s PostToolUse hook), so
44
+ * with 20 sessions open it runs many times a minute. Through the full CLI each call took about 340 ms of wall time and
45
+ * 0.3 s of CPU (measured 2026-11-22 on alpha.1354, recorded in the PR), almost all of it loading modules to send one
46
+ * message. The entry point sends it here instead, importing only node modules and the socket client, and sends at most
47
+ * one note per session in each quiet window: the note says only that the session used a tool, which the agent already
48
+ * knows from the first one, and the hook never wakes the agent.
49
+ *
50
+ * It skips without a send when the hook fires inside a subagent (Claude Code puts `agent_id` on the event), when the
51
+ * session already sent within the quiet window, or when the daemon's socket is missing. It always answers
52
+ * `{"continue":true}`, so a slow or absent daemon never holds up the tool call.
53
+ */
54
+ const crypto = __importStar(require("crypto"));
55
+ const fs = __importStar(require("fs"));
56
+ const os = __importStar(require("os"));
57
+ const path = __importStar(require("path"));
58
+ const socket_client_1 = require("./socket-client");
59
+ const runtime_1 = require("../../nerves/runtime");
60
+ /** How long a session's tool use stays news: one note per session in each window. */
61
+ exports.POST_TOOL_USE_QUIET_MS = 5 * 60 * 1000;
62
+ /** The hook's whole budget for the send; Claude Code's own timeout is 5 s. */
63
+ exports.POST_TOOL_USE_SEND_TIMEOUT_MS = 2_000;
64
+ /** True for exactly `hook post-tool-use --agent <agent>`, the argv the entry point hands this module. */
65
+ function isPostToolUseHook(argv) {
66
+ return argv.length === 4 && argv[0] === "hook" && argv[1] === "post-tool-use" && argv[2] === "--agent" && /^[A-Za-z0-9._-]+$/.test(argv[3]);
67
+ }
68
+ function stampPath(dir, agent, sessionId) {
69
+ return path.join(dir, `${agent}-${crypto.createHash("sha256").update(sessionId).digest("hex").slice(0, 32)}`);
70
+ }
71
+ /** Within the quiet window since this session's last send. A missing or unreadable stamp is not. */
72
+ function quiet(file, now) {
73
+ try {
74
+ return now - fs.statSync(file).mtimeMs < exports.POST_TOOL_USE_QUIET_MS;
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ function stamp(dir, file, now) {
81
+ try {
82
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
83
+ fs.writeFileSync(file, "");
84
+ fs.utimesSync(file, now / 1000, now / 1000);
85
+ }
86
+ catch {
87
+ // An unwritable stamp only means the next call sends again.
88
+ }
89
+ }
90
+ async function runPostToolUseHook(agent, deps) {
91
+ const outcome = await decide(agent, deps);
92
+ // Nothing configures a log sink in this process, so this costs only the runtime's import (about 10 ms).
93
+ (0, runtime_1.emitNervesEvent)({ event: "daemon.hook_post_tool_use", component: "daemon", message: `post-tool-use hook: ${outcome}`, meta: { agent, outcome } });
94
+ return outcome;
95
+ }
96
+ async function decide(agent, deps) {
97
+ try {
98
+ let event = {};
99
+ try {
100
+ const parsed = JSON.parse(deps.readStdin());
101
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
102
+ event = parsed;
103
+ }
104
+ catch {
105
+ // Malformed or missing input still answers continue, as the CLI did.
106
+ }
107
+ if (typeof event.agent_id === "string" && event.agent_id !== "")
108
+ return "subagent";
109
+ const sessionId = typeof event.session_id === "string" && event.session_id !== "" ? event.session_id : "unknown";
110
+ const toolName = typeof event.tool_name === "string" ? event.tool_name : "";
111
+ const file = stampPath(deps.stampDir, agent, sessionId);
112
+ const now = deps.now();
113
+ if (quiet(file, now))
114
+ return "quiet";
115
+ if (!fs.existsSync(deps.socketPath))
116
+ return "no-daemon";
117
+ stamp(deps.stampDir, file, now);
118
+ try {
119
+ await deps.send(deps.socketPath, {
120
+ kind: "message.send", from: `claude-code:${sessionId}`, to: agent,
121
+ content: `[Claude Code used ${toolName} in session ${sessionId}]`,
122
+ }, { timeoutMs: exports.POST_TOOL_USE_SEND_TIMEOUT_MS });
123
+ return "sent";
124
+ }
125
+ catch {
126
+ return "send-failed";
127
+ }
128
+ }
129
+ finally {
130
+ deps.writeStdout(JSON.stringify({ continue: true }));
131
+ }
132
+ }
133
+ /* v8 ignore start -- the real process's stdin, stdout and socket @preserve */
134
+ function defaultPostToolUseDeps() {
135
+ return {
136
+ readStdin: () => { try {
137
+ return fs.readFileSync(0, "utf-8");
138
+ }
139
+ catch {
140
+ return "";
141
+ } },
142
+ writeStdout: (text) => { process.stdout.write(text); },
143
+ socketPath: socket_client_1.DEFAULT_DAEMON_SOCKET_PATH,
144
+ stampDir: path.join(os.tmpdir(), "ouro-hook-post-tool-use"),
145
+ now: () => Date.now(),
146
+ send: (socketPath, command, options) => (0, socket_client_1.sendDaemonCommand)(socketPath, command, options),
147
+ };
148
+ }
149
+ /* v8 ignore stop */
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runOuroEntry = runOuroEntry;
4
+ // The ouro CLI, which ouro-entry.ts loads and runs for every command but the per-tool hook.
5
+ const compile_cache_1 = require("./compile-cache");
6
+ const runtime_1 = require("../../nerves/runtime");
7
+ const cli_arg_redaction_1 = require("./cli-arg-redaction");
8
+ const daemon_cli_1 = require("./daemon-cli");
9
+ const cli_gate_1 = require("./cli-gate");
10
+ const runtime_logging_1 = require("./runtime-logging");
11
+ const portable_git_1 = require("./portable-git");
12
+ /** Runs the CLI on the arguments after `ouro`. */
13
+ function runOuroEntry(args) {
14
+ if (args[0] === "shepherd" && args[1] !== "chat")
15
+ (0, runtime_logging_1.configureDaemonRuntimeLogger)("ouro", { machine: true });
16
+ else
17
+ (0, runtime_logging_1.configureDaemonRuntimeLogger)("ouro");
18
+ (0, portable_git_1.activatePortableGit)();
19
+ (0, runtime_1.emitNervesEvent)({
20
+ component: "daemon",
21
+ event: "daemon.cli_entry_start",
22
+ message: "starting ouro CLI entrypoint",
23
+ meta: { args: (0, cli_arg_redaction_1.redactCliArgs)(args), compileCache: compile_cache_1.ouroCompileCacheDirectory },
24
+ });
25
+ const gate = (0, cli_gate_1.gateCommandArgs)(args);
26
+ // A failure ends with the code its Ouro AX card names (see `ouro help --json`), so an agent can look up the fix.
27
+ const withCode = (message, code) => (typeof code === "string" ? `${message}\ncode: ${code}\n` : `${message}\n`);
28
+ if (gate.kind === "refuse") {
29
+ process.stderr.write(withCode(gate.message, gate.code));
30
+ process.exitCode = 1;
31
+ }
32
+ else if (gate.kind === "preview" || gate.kind === "help") {
33
+ process.stdout.write(`${gate.text}\n`);
34
+ }
35
+ else {
36
+ void (0, daemon_cli_1.runOuroCli)(gate.args).catch((error) => {
37
+ const message = error instanceof Error ? error.message : String(error);
38
+ const code = error instanceof Error ? error.code : undefined;
39
+ process.stderr.write(withCode(message, code));
40
+ (0, runtime_1.emitNervesEvent)({
41
+ level: "error",
42
+ component: "daemon",
43
+ event: "daemon.cli_entry_error",
44
+ message: "ouro CLI entrypoint failed",
45
+ meta: typeof code === "string" ? { error: message, code } : { error: message },
46
+ });
47
+ process.exit(1);
48
+ });
49
+ }
50
+ }
@@ -1,47 +1,46 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
3
36
  Object.defineProperty(exports, "__esModule", { value: true });
4
37
  // First, so every later module can come from the compile cache.
5
- const compile_cache_1 = require("./compile-cache");
6
- const runtime_1 = require("../../nerves/runtime");
7
- const cli_arg_redaction_1 = require("./cli-arg-redaction");
8
- const daemon_cli_1 = require("./daemon-cli");
9
- const cli_gate_1 = require("./cli-gate");
10
- const runtime_logging_1 = require("./runtime-logging");
11
- const portable_git_1 = require("./portable-git");
12
- if (process.argv[2] === "shepherd" && process.argv[3] !== "chat")
13
- (0, runtime_logging_1.configureDaemonRuntimeLogger)("ouro", { machine: true });
38
+ require("./compile-cache");
39
+ const hook_post_tool_use_1 = require("./hook-post-tool-use");
40
+ // Claude Code runs `ouro hook post-tool-use` after every tool call in every session, so it skips loading the CLI
41
+ // (hook-post-tool-use.ts). Every other command loads it.
42
+ const argv = process.argv.slice(2);
43
+ if ((0, hook_post_tool_use_1.isPostToolUseHook)(argv))
44
+ void (0, hook_post_tool_use_1.runPostToolUseHook)(argv[3], (0, hook_post_tool_use_1.defaultPostToolUseDeps)());
14
45
  else
15
- (0, runtime_logging_1.configureDaemonRuntimeLogger)("ouro");
16
- (0, portable_git_1.activatePortableGit)();
17
- (0, runtime_1.emitNervesEvent)({
18
- component: "daemon",
19
- event: "daemon.cli_entry_start",
20
- message: "starting ouro CLI entrypoint",
21
- meta: { args: (0, cli_arg_redaction_1.redactCliArgs)(process.argv.slice(2)), compileCache: compile_cache_1.ouroCompileCacheDirectory },
22
- });
23
- const gate = (0, cli_gate_1.gateCommandArgs)(process.argv.slice(2));
24
- // A failure ends with the code its Ouro AX card names (see `ouro help --json`), so an agent can look up the fix.
25
- const withCode = (message, code) => (typeof code === "string" ? `${message}\ncode: ${code}\n` : `${message}\n`);
26
- if (gate.kind === "refuse") {
27
- process.stderr.write(withCode(gate.message, gate.code));
28
- process.exitCode = 1;
29
- }
30
- else if (gate.kind === "preview" || gate.kind === "help") {
31
- process.stdout.write(`${gate.text}\n`);
32
- }
33
- else {
34
- void (0, daemon_cli_1.runOuroCli)(gate.args).catch((error) => {
35
- const message = error instanceof Error ? error.message : String(error);
36
- const code = error instanceof Error ? error.code : undefined;
37
- process.stderr.write(withCode(message, code));
38
- (0, runtime_1.emitNervesEvent)({
39
- level: "error",
40
- component: "daemon",
41
- event: "daemon.cli_entry_error",
42
- message: "ouro CLI entrypoint failed",
43
- meta: typeof code === "string" ? { error: message, code } : { error: message },
44
- });
45
- process.exit(1);
46
- });
47
- }
46
+ void Promise.resolve().then(() => __importStar(require("./ouro-cli-main"))).then(({ runOuroEntry }) => runOuroEntry(argv));
@@ -34,6 +34,8 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.OUTBOUND_ORIGIN_LABELS = void 0;
37
+ exports.recordedOutboundText = recordedOutboundText;
38
+ exports.isRecordedOutboundText = isRecordedOutboundText;
37
39
  exports.drainOutboundRecords = drainOutboundRecords;
38
40
  exports.recordOutboundInSession = recordOutboundInSession;
39
41
  const crypto_1 = require("crypto");
@@ -55,8 +57,14 @@ function deferredDir(agentRoot, friendId, channel, key) {
55
57
  function deferredFileName(deliveryId) {
56
58
  return `${(0, crypto_1.createHash)("sha256").update(deliveryId).digest("hex").slice(0, 32)}.json`;
57
59
  }
58
- function recordedText(record) {
59
- return `[you sent this via ${record.originLabel}] ${record.content}`;
60
+ const RECORDED_OUTBOUND_PREFIX = "[you sent this via ";
61
+ /** The assistant text a delivered proactive send leaves in the friend's session. */
62
+ function recordedOutboundText(record) {
63
+ return `${RECORDED_OUTBOUND_PREFIX}${record.originLabel}] ${record.content}`;
64
+ }
65
+ /** True for a session message written by recordedOutboundText, not by a turn answering the friend. */
66
+ function isRecordedOutboundText(text) {
67
+ return text.startsWith(RECORDED_OUTBOUND_PREFIX);
60
68
  }
61
69
  function recordError(message, meta) {
62
70
  (0, runtime_1.emitNervesEvent)({ level: "warn", component: "mind", event: "mind.outbound_record_error", message, meta });
@@ -120,7 +128,7 @@ function drainUnderLease(agentRoot, friendId, channel, key, lease) {
120
128
  if (!record) {
121
129
  recordError("skipped an unreadable deferred outbound record", { friendId, channel, file: name });
122
130
  }
123
- else if ((0, context_1.appendSyntheticAssistantMessage)(lease.sessionPath, recordedText(record), lease, { outbound: { origin: record.origin, deliveryId: record.deliveryId }, createIfMissing: true, sentAt: record.recordedAt })) {
131
+ else if ((0, context_1.appendSyntheticAssistantMessage)(lease.sessionPath, recordedOutboundText(record), lease, { outbound: { origin: record.origin, deliveryId: record.deliveryId }, createIfMissing: true, sentAt: record.recordedAt })) {
124
132
  count += 1;
125
133
  }
126
134
  else {
@@ -141,7 +149,7 @@ function recordOutboundInSession(input) {
141
149
  try {
142
150
  return (0, session_transaction_1.withImmediateSessionTurnLease)(sessionPath, (lease) => {
143
151
  drainOutboundRecords(agentRoot, friendId, channel, key, lease);
144
- const appended = (0, context_1.appendSyntheticAssistantMessage)(sessionPath, recordedText(input), lease, { outbound: { origin, deliveryId }, createIfMissing: true });
152
+ const appended = (0, context_1.appendSyntheticAssistantMessage)(sessionPath, recordedOutboundText(input), lease, { outbound: { origin, deliveryId }, createIfMissing: true });
145
153
  if (appended)
146
154
  return "recorded";
147
155
  recordError("could not append an outbound record to its session", { friendId, channel, deliveryId });
@@ -176,6 +176,9 @@ const DISPATCH_EXEMPT_PATTERNS = [
176
176
  // Loaded first by the CLI entry points, before any project module, so it cannot import nerves; the entry's own
177
177
  // start event reports the compile cache directory it chose.
178
178
  "daemon/compile-cache",
179
+ // The CLI's entry point only picks a module: the per-tool hook (which emits daemon.hook_post_tool_use) or the CLI
180
+ // (ouro-cli-main.ts, which emits the entry's start events). It stays this small so the hook loads nothing else.
181
+ "heart/daemon/ouro-entry.ts",
179
182
  ];
180
183
  function isDispatchExempt(filePath) {
181
184
  return DISPATCH_EXEMPT_PATTERNS.some((pattern) => filePath.includes(pattern));
@@ -163,7 +163,12 @@ async function routeSurfaceToFriend(agentName, friendId, content, queueItem, hin
163
163
  content,
164
164
  timestamp: Date.now(),
165
165
  });
166
- return { status: "queued", detail };
166
+ // A BlueBubbles return deliberately waits for the friend's next iMessage
167
+ // instead of live-sending one. Say so, so the agent never reads "queued"
168
+ // as "sent", and name the tool that texts them now when that is the intent.
169
+ return target.channel === "bluebubbles"
170
+ ? { status: "queued", detail: `${detail}; it waits for their next iMessage. To text them now, use send_message with channel="bluebubbles"` }
171
+ : { status: "queued", detail };
167
172
  };
168
173
  const deliverTelegramOrQueue = async (target, detail) => {
169
174
  const telegramKey = (0, config_1.canonicalizeTelegramSessionKey)(target.key);
@@ -645,12 +645,18 @@ function createBlueBubblesClient(config = (0, config_1.getBlueBubblesConfig)(),
645
645
  },
646
646
  });
647
647
  await assertHostAccount();
648
- const url = buildRepairUrl(config.serverUrl, event.messageGuid, config.password);
648
+ const fetchRepair = (messageGuid) => fetch(buildRepairUrl(config.serverUrl, messageGuid, config.password), {
649
+ method: "GET",
650
+ signal: AbortSignal.timeout(channelConfig.requestTimeoutMs),
651
+ });
649
652
  try {
650
- const response = await fetch(url, {
651
- method: "GET",
652
- signal: AbortSignal.timeout(channelConfig.requestTimeoutMs),
653
- });
653
+ let response = await fetchRepair(event.messageGuid);
654
+ // BlueBubbles GUIDs are upper case and looked up exactly. Captures from
655
+ // older builds stored them lower-cased, so retry once with the provider spelling.
656
+ const providerGuid = event.messageGuid.toUpperCase();
657
+ if (response.status === 404 && providerGuid !== event.messageGuid) {
658
+ response = await fetchRepair(providerGuid);
659
+ }
654
660
  if (!response.ok) {
655
661
  const errorText = await response.text().catch(() => "");
656
662
  const repaired = applyRepairNotice(event, `BlueBubbles repair failed: ${errorText || `HTTP ${response.status}`}`);
@@ -611,15 +611,26 @@ function buildInboundContent(event) {
611
611
  ...event.inputPartsForAgent,
612
612
  ];
613
613
  }
614
- function sessionLikelyContainsMessage(event, existingMessages) {
614
+ function sessionUserMessageIndex(event, existingMessages) {
615
615
  const fragment = event.textForAgent.trim();
616
616
  if (!fragment)
617
- return false;
618
- return existingMessages.some((message) => {
619
- if (message.role !== "user")
620
- return false;
621
- return extractMessageText(message.content).includes(fragment);
622
- });
617
+ return -1;
618
+ return existingMessages.findLastIndex((message) => (message.role === "user" && extractMessageText(message.content).includes(fragment)));
619
+ }
620
+ /**
621
+ * A turn saves the friend's message before the model runs, so the text alone
622
+ * does not prove the message was answered. Only a later assistant reply does;
623
+ * a proactive send recorded in the session afterwards does not count.
624
+ */
625
+ function sessionAlreadyAnsweredMessage(event, existingMessages) {
626
+ const index = sessionUserMessageIndex(event, existingMessages);
627
+ return index >= 0 && existingMessages.slice(index + 1).some((message) => (message.role === "assistant" && !(0, outbound_record_1.isRecordedOutboundText)(extractMessageText(message.content))));
628
+ }
629
+ /** Drop the unanswered copy a dead turn left at the tail, so the replay adds the message once. */
630
+ function withoutUnansweredTail(event, messages) {
631
+ return sessionUserMessageIndex(event, messages) === messages.length - 1
632
+ ? messages.slice(0, -1)
633
+ : messages;
623
634
  }
624
635
  function getBlueBubblesContinuityIngressTexts(event) {
625
636
  const text = event.textForAgent.trim();
@@ -1566,13 +1577,13 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1566
1577
  // Pre-load session inside the canonical turn lock so same-chat
1567
1578
  // deliveries cannot race on stale trunk state.
1568
1579
  const existing = resolvedDeps.loadSession(sessPath);
1580
+ const replaying = options.semanticRecovery || source !== "webhook";
1569
1581
  const sessionMessages = existing?.messages && existing.messages.length > 0
1570
- ? structuredClone(existing.messages)
1582
+ ? structuredClone(replaying ? withoutUnansweredTail(event, existing.messages) : existing.messages)
1571
1583
  : [{ role: "system", content: (0, prompt_1.flattenSystemPrompt)(await resolvedDeps.buildSystem("bluebubbles", {}, context)) }];
1572
1584
  // Record EARLY for audit and crash recovery. This is capture truth, not
1573
1585
  // a claim that the agent turn completed successfully.
1574
- const inboundSource = (options.semanticRecovery || source !== "webhook")
1575
- && sessionLikelyContainsMessage(event, existing?.messages ?? sessionMessages)
1586
+ const inboundSource = replaying && sessionAlreadyAnsweredMessage(event, existing?.messages ?? sessionMessages)
1576
1587
  ? "recovery-bootstrap"
1577
1588
  : source;
1578
1589
  (0, inbound_log_1.recordBlueBubblesInbound)(agentName, event, inboundSource);
@@ -437,9 +437,12 @@ function buildBlueBubblesSemanticCapture(input) {
437
437
  if (observationClock === false)
438
438
  return null;
439
439
  const kind = input.event.kind === "message" ? "message" : input.event.mutationType;
440
- const eventGuid = requiredIdentifier(input.event.messageGuid);
440
+ // BlueBubbles looks messages up by exact GUID. The identity key folds case so
441
+ // spellings deduplicate, but the capture keeps the provider's spelling so
442
+ // recovery can fetch the message again.
443
+ const eventGuid = providerGuid(input.event.messageGuid);
441
444
  const targetGuid = input.event.kind === "mutation"
442
- ? requiredIdentifier(input.event.targetMessageGuid)
445
+ ? providerGuid(input.event.targetMessageGuid)
443
446
  ?? (input.event.mutationType === "unsend" ? eventGuid : null)
444
447
  : null;
445
448
  const reaction = input.event.kind === "mutation" ? input.event.reaction : undefined;
@@ -975,13 +978,13 @@ function blueBubblesSemanticCaptureHash(capture) {
975
978
  event: {
976
979
  provider: capture.event.provider,
977
980
  kind: capture.event.kind,
978
- eventGuid: capture.event.eventGuid,
981
+ eventGuid: caseFoldedGuid(capture.event.eventGuid),
979
982
  fromMe: capture.event.fromMe,
980
983
  actor: capture.event.actor,
981
984
  participants: capture.event.participants,
982
985
  text: capture.event.text,
983
986
  textSha256: capture.event.textSha256,
984
- targetGuid: capture.event.targetGuid,
987
+ targetGuid: caseFoldedGuid(capture.event.targetGuid),
985
988
  targetAuthorship: capture.event.targetAuthorship,
986
989
  canonicalAction: capture.event.canonicalAction,
987
990
  canonicalValue: capture.event.canonicalValue,
@@ -1899,6 +1902,15 @@ function requiredIdentifier(value) {
1899
1902
  const normalized = normalizeIngressIdentifier(value);
1900
1903
  return normalized || null;
1901
1904
  }
1905
+ function providerGuid(value) {
1906
+ if (typeof value !== "string")
1907
+ return requiredIdentifier(value);
1908
+ return value.trim() || null;
1909
+ }
1910
+ /** Captures from older builds stored lower-case GUIDs; compare them case-insensitively. */
1911
+ function caseFoldedGuid(value) {
1912
+ return value === null ? null : value.toLowerCase();
1913
+ }
1902
1914
  function normalizeProviderNamespace(value) {
1903
1915
  const normalized = requiredIdentifier(value);
1904
1916
  return normalized && UUID_V4_PATTERN.test(normalized) ? normalized : null;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1370",
3
+ "version": "0.1.0-alpha.1372",
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.1370",
9
+ "version": "0.1.0-alpha.1372",
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.1370",
3
+ "version": "0.1.0-alpha.1372",
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": {