@ouro.bot/cli 0.1.0-alpha.1394 → 0.1.0-alpha.1397
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 +12 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/heart/core.js +78 -0
- package/dist/heart/daemon/sense-manager.js +103 -9
- package/dist/heart/external-events/router.js +1 -1
- package/dist/heart/habits/habit-session.js +12 -5
- package/dist/mind/pending.js +29 -0
- package/dist/repertoire/tools-flow.js +2 -0
- package/dist/repertoire/tools-surface.js +167 -27
- package/dist/scripts/claude-code-stop-hook.js +4 -3
- package/dist/senses/bluebubbles/index.js +114 -17
- package/dist/senses/bluebubbles/runtime-state.js +17 -2
- package/dist/senses/ordinary-owner-decision.js +4 -3
- package/dist/senses/pipeline.js +10 -5
- package/dist/senses/shared-turn.js +5 -0
- package/dist/senses/teams-off-turn.js +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
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.1397",
|
|
6
|
+
"changes": [
|
|
7
|
+
"When an agent tells a person something unprompted, surface now texts them on their own iMessage, Telegram or Teams chat, or says plainly it was not sent and saves it for their next message; it never queues it into an MCP or CLI session they don't read."
|
|
8
|
+
]
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"version": "0.1.0-alpha.1396",
|
|
12
|
+
"changes": [
|
|
13
|
+
"A BlueBubbles listener that stops proving itself now reads as an error and is restarted, timed on the daemon's own clock so sleep never triggers it, and slow syncs, failed syncs and recoveries are logged."
|
|
14
|
+
]
|
|
15
|
+
},
|
|
4
16
|
{
|
|
5
17
|
"version": "0.1.0-alpha.1394",
|
|
6
18
|
"changes": [
|
|
@@ -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.
|
|
4
|
+
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1397</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
package/dist/heart/core.js
CHANGED
|
@@ -11,6 +11,8 @@ exports.createSummarize = createSummarize;
|
|
|
11
11
|
exports.getProviderDisplayLabel = getProviderDisplayLabel;
|
|
12
12
|
exports.createHabitCallbackBuffer = createHabitCallbackBuffer;
|
|
13
13
|
exports.resumeApprovalContinuation = resumeApprovalContinuation;
|
|
14
|
+
exports.unsentSurfaceResult = unsentSurfaceResult;
|
|
15
|
+
exports.surfacesReachedLater = surfacesReachedLater;
|
|
14
16
|
exports.isChatStyleChannel = isChatStyleChannel;
|
|
15
17
|
exports.buildPonderResult = buildPonderResult;
|
|
16
18
|
exports.isExternalStateQuery = isExternalStateQuery;
|
|
@@ -54,6 +56,7 @@ function validateToolCallBatchAtProductionBoundary(calls, activeTools) {
|
|
|
54
56
|
});
|
|
55
57
|
}
|
|
56
58
|
const context_1 = require("../mind/context");
|
|
59
|
+
const pending_1 = require("../mind/pending");
|
|
57
60
|
const prompt_budget_1 = require("../mind/prompt-budget");
|
|
58
61
|
const prompt_1 = require("../mind/prompt");
|
|
59
62
|
const kept_notes_1 = require("./kept-notes");
|
|
@@ -428,6 +431,58 @@ function stripThinkBlocksForViolationCheck(input) {
|
|
|
428
431
|
}
|
|
429
432
|
return out.trim();
|
|
430
433
|
}
|
|
434
|
+
/** Who a send was for: its friendId, or for a surface addressed only by delegationId, that held thought. */
|
|
435
|
+
const surfaceFriendKey = (record) => {
|
|
436
|
+
const friendId = (record.args.friendId ?? "").trim().toLowerCase();
|
|
437
|
+
return friendId || (record.args.delegationId ? `delegation:${record.args.delegationId.trim()}` : "");
|
|
438
|
+
};
|
|
439
|
+
const isUnsentSurface = (record) => record.name === "surface" && /\(code: surface-not-sent\)$/u.test(record.result);
|
|
440
|
+
/** A surface or send_message that reached the friend now, or may have (unconfirmed). */
|
|
441
|
+
const reachedSurfaceFriend = (record) => (record.name === "surface" && /^(?:delivered|forwarded|unconfirmed)\b/u.test(record.result))
|
|
442
|
+
|| (record.name === "send_message" && /^delivered now$/mu.test(record.result) && !/\(code: [a-z0-9-]+\)$/u.test(record.result));
|
|
443
|
+
/**
|
|
444
|
+
* This turn's newest surface result that came back not sent (it ends with the surface-not-sent code), among the
|
|
445
|
+
* friends no later surface or send_message reached. Rest uses it to say once that the person was not told.
|
|
446
|
+
*/
|
|
447
|
+
function unsentSurfaceResult(records) {
|
|
448
|
+
const unsent = new Map();
|
|
449
|
+
for (const record of records) {
|
|
450
|
+
const friend = surfaceFriendKey(record);
|
|
451
|
+
if (isUnsentSurface(record)) {
|
|
452
|
+
unsent.delete(friend);
|
|
453
|
+
unsent.set(friend, record.result);
|
|
454
|
+
}
|
|
455
|
+
else if (reachedSurfaceFriend(record)) {
|
|
456
|
+
unsent.delete(friend);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
return [...unsent.values()].at(-1) ?? null;
|
|
460
|
+
}
|
|
461
|
+
const sameWords = (left, right) => {
|
|
462
|
+
const words = (text) => (text ?? "").trim().replace(/\s+/gu, " ").toLowerCase();
|
|
463
|
+
return words(left) !== "" && words(left) === words(right);
|
|
464
|
+
};
|
|
465
|
+
/**
|
|
466
|
+
* When the newest record reached a friend with the same words as surfaces to that friend saved earlier this turn,
|
|
467
|
+
* those saved copies are now redundant. Different words leave the saved copy alone, since that news has not reached
|
|
468
|
+
* them. A surface addressed only by delegationId names no friend and is left alone.
|
|
469
|
+
*/
|
|
470
|
+
function surfacesReachedLater(records) {
|
|
471
|
+
const latest = records.at(-1);
|
|
472
|
+
if (!latest || !reachedSurfaceFriend(latest) || !latest.args.friendId?.trim())
|
|
473
|
+
return [];
|
|
474
|
+
const said = latest.args.content;
|
|
475
|
+
let saved = [];
|
|
476
|
+
for (const record of records.slice(0, -1)) {
|
|
477
|
+
if (surfaceFriendKey(record) !== surfaceFriendKey(latest))
|
|
478
|
+
continue;
|
|
479
|
+
if (isUnsentSurface(record) && sameWords(record.args.content, said))
|
|
480
|
+
saved.push({ friendId: record.args.friendId.trim(), content: record.args.content });
|
|
481
|
+
else if (reachedSurfaceFriend(record) && sameWords(record.args.content, said))
|
|
482
|
+
saved = [];
|
|
483
|
+
}
|
|
484
|
+
return saved;
|
|
485
|
+
}
|
|
431
486
|
function hasFreshPendingWork(options) {
|
|
432
487
|
const pendingMessages = options?.pendingMessages;
|
|
433
488
|
if (!Array.isArray(pendingMessages))
|
|
@@ -1307,6 +1362,9 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
1307
1362
|
// which doesn't update mid-turn. The agent only needs to be told once;
|
|
1308
1363
|
// after that, repeated rest attempts mean they've acknowledged.
|
|
1309
1364
|
let freshWorkGateFired = false;
|
|
1365
|
+
// Once-per-turn flag for the unsent-surface rest gate: the agent is told once
|
|
1366
|
+
// that a person it meant to tell was not reached; a second rest is its answer.
|
|
1367
|
+
let surfaceNotSentGateFired = false;
|
|
1310
1368
|
// Counter for no-tool-call violations. MiniMax reasoning models occasionally
|
|
1311
1369
|
// emit only a <think>...</think> block and stop, without any tool call — even
|
|
1312
1370
|
// when tool_choice is set to "required". Private-return requests also need
|
|
@@ -2371,6 +2429,20 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
2371
2429
|
});
|
|
2372
2430
|
continue;
|
|
2373
2431
|
}
|
|
2432
|
+
const unsentSurface = !wrappingUp && !surfaceNotSentGateFired ? unsentSurfaceResult(turnToolRecords) : null;
|
|
2433
|
+
if (unsentSurface) {
|
|
2434
|
+
surfaceNotSentGateFired = true;
|
|
2435
|
+
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs, toolSelection), false);
|
|
2436
|
+
rejectToolBatch(msg, [tools_flow_1.FLOW_TOOL_REFUSALS.restSurfaceNotSent(unsentSurface)]);
|
|
2437
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2438
|
+
level: "info",
|
|
2439
|
+
component: "engine",
|
|
2440
|
+
event: "engine.surface_not_sent_gate_fired",
|
|
2441
|
+
message: "rest deferred once because a surface this turn was not sent; agent has been notified",
|
|
2442
|
+
meta: {},
|
|
2443
|
+
});
|
|
2444
|
+
continue;
|
|
2445
|
+
}
|
|
2374
2446
|
callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs, toolSelection), true);
|
|
2375
2447
|
pushGenerated(msg);
|
|
2376
2448
|
const ack = "(resting)";
|
|
@@ -2821,6 +2893,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
2821
2893
|
if (invoked && requiredToolCallNames.includes(tc.name) && !options?.requiredToolCalls?.requireSuccessfulResults)
|
|
2822
2894
|
dispatchedRequiredToolCalls.add(tc.name);
|
|
2823
2895
|
turnToolRecords.push({ name: tc.name, args, result: toolResult });
|
|
2896
|
+
for (const saved of surfacesReachedLater(turnToolRecords)) {
|
|
2897
|
+
try {
|
|
2898
|
+
(0, pending_1.withdrawDeferredReturn)((0, identity_2.getAgentName)(), saved.friendId, saved.content);
|
|
2899
|
+
}
|
|
2900
|
+
catch { /* a stale saved copy only repeats the news */ }
|
|
2901
|
+
}
|
|
2824
2902
|
const modelResult = (0, delegated_command_1.shieldDelegatedBanner)((0, tool_output_budget_1.fitToolOutputForModel)(tc.name, (0, tool_friction_1.rewriteToolResultForModel)(tc.name, toolResult, toolFrictionLedger)));
|
|
2825
2903
|
pushGenerated({ role: "tool", tool_call_id: tc.id, content: modelResult });
|
|
2826
2904
|
providerRuntime.appendToolOutput(tc.id, modelResult);
|
|
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.DaemonSenseManager = void 0;
|
|
36
|
+
exports.DaemonSenseManager = exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS = void 0;
|
|
37
37
|
const fs = __importStar(require("fs"));
|
|
38
38
|
const bluebubbles_host_account_1 = require("../bluebubbles-host-account");
|
|
39
39
|
const os = __importStar(require("os"));
|
|
@@ -54,6 +54,14 @@ const DEFAULT_TEAMS_PORT = 3978;
|
|
|
54
54
|
const DEFAULT_BLUEBUBBLES_PORT = 18790;
|
|
55
55
|
const DEFAULT_BLUEBUBBLES_WEBHOOK_PATH = "/bluebubbles-webhook";
|
|
56
56
|
const BLUEBUBBLES_RUNTIME_FRESHNESS_WINDOW_MS = 90_000;
|
|
57
|
+
/**
|
|
58
|
+
* The listener's 30 s sync loop refreshes its proof on every tick, even while a slow pass runs, and a pass that
|
|
59
|
+
* hangs is abandoned after two minutes without progress. So a proof this daemon has watched stay unchanged this long means the loop
|
|
60
|
+
* itself has stopped. Busy turns never hold it back.
|
|
61
|
+
*/
|
|
62
|
+
exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS = 10 * 60_000;
|
|
63
|
+
/** Each restart that brings no fresh proof doubles the wait before the next, up to this many doublings. */
|
|
64
|
+
const BLUEBUBBLES_STALE_PROOF_MAX_DOUBLINGS = 3;
|
|
57
65
|
const SENSE_CONFIG_RETRY_DELAYS_MS = [1_000, 2_000, 5_000, 10_000, 30_000, 60_000];
|
|
58
66
|
const WORKBENCH_RUNTIME_INJECTION_DETAIL = "runtime-injected by Workbench app; no agent.json entry required";
|
|
59
67
|
const WORKBENCH_STALE_BUNDLE_DETAIL = "stale agent.json Workbench entry; run 'ouro connect workbench' to clean it and use runtime injection";
|
|
@@ -490,6 +498,7 @@ function readBlueBubblesRuntimeJson(runtimePath) {
|
|
|
490
498
|
? parsed.detail
|
|
491
499
|
: "startup health probe pending",
|
|
492
500
|
lastCheckedAt: typeof parsed.lastCheckedAt === "string" ? parsed.lastCheckedAt : undefined,
|
|
501
|
+
lastHeartbeatAt: typeof parsed.lastHeartbeatAt === "string" ? parsed.lastHeartbeatAt : undefined,
|
|
493
502
|
proofMethod: typeof parsed.proofMethod === "string" && parsed.proofMethod.trim()
|
|
494
503
|
? parsed.proofMethod
|
|
495
504
|
: undefined,
|
|
@@ -518,10 +527,19 @@ function readBlueBubblesRuntimeJson(runtimePath) {
|
|
|
518
527
|
/* v8 ignore start -- defensive: catch for missing/corrupt BB runtime state file @preserve */
|
|
519
528
|
}
|
|
520
529
|
catch {
|
|
521
|
-
return { upstreamStatus: "unknown", detail: "startup health probe pending", pendingRecoveryCount: 0, failedRecoveryCount: 0 };
|
|
530
|
+
return { upstreamStatus: "unknown", detail: "startup health probe pending", pendingRecoveryCount: 0, failedRecoveryCount: 0, unreadable: true };
|
|
522
531
|
}
|
|
523
532
|
/* v8 ignore stop */
|
|
524
533
|
}
|
|
534
|
+
/** The listener's latest sign of life: its last health check, or a sync heartbeat written since. */
|
|
535
|
+
function blueBubblesLatestProof(state) {
|
|
536
|
+
const checkedMs = state.lastCheckedAt ? Date.parse(state.lastCheckedAt) : Number.NaN;
|
|
537
|
+
const heartbeatMs = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : Number.NaN;
|
|
538
|
+
if (!Number.isFinite(heartbeatMs) || checkedMs >= heartbeatMs)
|
|
539
|
+
return { at: state.lastCheckedAt, method: state.proofMethod };
|
|
540
|
+
// Every write stamps a heartbeat a moment after its check, so the heartbeat is named the proof only once the check is old.
|
|
541
|
+
return { at: state.lastHeartbeatAt, method: blueBubblesRuntimeStateIsFresh(state.lastCheckedAt) ? state.proofMethod : "bluebubbles.syncHeartbeat" };
|
|
542
|
+
}
|
|
525
543
|
function readBlueBubblesRuntimeFacts(agent, bundlesRoot, snapshot) {
|
|
526
544
|
const agentRoot = path.join(bundlesRoot, `${agent}.ouro`);
|
|
527
545
|
const runtimePath = path.join(agentRoot, "state", "senses", "bluebubbles", "runtime.json");
|
|
@@ -529,11 +547,12 @@ function readBlueBubblesRuntimeFacts(agent, bundlesRoot, snapshot) {
|
|
|
529
547
|
return { runtime: snapshot?.runtime };
|
|
530
548
|
}
|
|
531
549
|
const state = readBlueBubblesRuntimeJson(runtimePath);
|
|
532
|
-
const
|
|
550
|
+
const proof = blueBubblesLatestProof(state);
|
|
551
|
+
const proofAtMs = proof.at ? Date.parse(proof.at) : Number.NaN;
|
|
533
552
|
const proofFacts = {
|
|
534
|
-
proofMethod:
|
|
535
|
-
lastProofAt:
|
|
536
|
-
proofAgeMs: Number.isFinite(
|
|
553
|
+
proofMethod: proof.method ?? "bluebubbles.checkHealth",
|
|
554
|
+
lastProofAt: proof.at,
|
|
555
|
+
proofAgeMs: Number.isFinite(proofAtMs) ? Math.max(0, Date.now() - proofAtMs) : undefined,
|
|
537
556
|
pendingRecoveryCount: state.pendingRecoveryCount,
|
|
538
557
|
failedRecoveryCount: state.failedRecoveryCount,
|
|
539
558
|
oldestPendingRecoveryAt: state.oldestPendingRecoveryAt,
|
|
@@ -543,11 +562,21 @@ function readBlueBubblesRuntimeFacts(agent, bundlesRoot, snapshot) {
|
|
|
543
562
|
oldestActiveTurnStartedAt: state.oldestActiveTurnStartedAt,
|
|
544
563
|
oldestActiveTurnAgeMs: state.oldestActiveTurnAgeMs,
|
|
545
564
|
};
|
|
546
|
-
if (!blueBubblesRuntimeStateIsFresh(
|
|
565
|
+
if (!blueBubblesRuntimeStateIsFresh(proof.at)) {
|
|
566
|
+
// A running listener that has stopped proving itself is not healthy, whatever its process state says.
|
|
567
|
+
if (proof.at && snapshot?.runtime === "running") {
|
|
568
|
+
return {
|
|
569
|
+
runtime: "error",
|
|
570
|
+
...proofFacts,
|
|
571
|
+
lastFailure: "BlueBubbles proof is stale",
|
|
572
|
+
failureLayer: "proof_freshness",
|
|
573
|
+
recoveryAction: `the daemon restarts the BlueBubbles listener once its proof has not changed for ${Math.round(exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS / 60_000)}m`,
|
|
574
|
+
};
|
|
575
|
+
}
|
|
547
576
|
return {
|
|
548
577
|
runtime: snapshot?.runtime,
|
|
549
|
-
lastFailure:
|
|
550
|
-
failureLayer:
|
|
578
|
+
lastFailure: proof.at ? "BlueBubbles proof is stale" : undefined,
|
|
579
|
+
failureLayer: proof.at ? "proof_freshness" : undefined,
|
|
551
580
|
};
|
|
552
581
|
}
|
|
553
582
|
if (snapshot?.runtime !== "running") {
|
|
@@ -617,9 +646,14 @@ class DaemonSenseManager {
|
|
|
617
646
|
presenceFlagOn;
|
|
618
647
|
/** Shared senses skipped because another machine owns them; started here when ownership arrives. */
|
|
619
648
|
notOwnerSkipped = new Set();
|
|
649
|
+
monotonicNow;
|
|
650
|
+
/** Per agent: the listener process and proof last seen, since when (monotonic), and restarts that brought no new proof. */
|
|
651
|
+
blueBubblesProofWatch = new Map();
|
|
620
652
|
constructor(options) {
|
|
621
653
|
const bundlesRoot = options.bundlesRoot ?? path.join(os.homedir(), "AgentBundles");
|
|
622
654
|
this.bundlesRoot = bundlesRoot;
|
|
655
|
+
/* v8 ignore next -- production default; tests inject the clock @preserve */
|
|
656
|
+
this.monotonicNow = options.monotonicNow ?? (() => performance.now());
|
|
623
657
|
/* v8 ignore start -- production default reads the real roster and machine identity; tests inject presenceOwner @preserve */
|
|
624
658
|
this.presenceOwner = options.presenceOwner ?? ((agent, sense) => {
|
|
625
659
|
if (!(0, presence_1.isSharedSense)(sense))
|
|
@@ -977,9 +1011,69 @@ class DaemonSenseManager {
|
|
|
977
1011
|
// something else triggers a tight respawn cycle for any reason, the
|
|
978
1012
|
// guard fires and refuses further restarts after N attempts in M
|
|
979
1013
|
// minutes, so we can never re-enter the 2026-05-11 spiral.
|
|
1014
|
+
//
|
|
1015
|
+
// What we do watch is the listener's own proof. Its sync loop rewrites
|
|
1016
|
+
// runtime.json every 30 s on a timer that turns never block, so a proof
|
|
1017
|
+
// ten minutes old means that loop has stopped, not that it is busy. The
|
|
1018
|
+
// probe only reads the file; it never calls into the listener.
|
|
1019
|
+
probes.push(this.blueBubblesProofProbe(agent));
|
|
980
1020
|
}
|
|
981
1021
|
return probes;
|
|
982
1022
|
}
|
|
1023
|
+
blueBubblesProofProbe(agent) {
|
|
1024
|
+
const managedName = `${agent}:bluebubbles`;
|
|
1025
|
+
return {
|
|
1026
|
+
name: `bluebubbles-proof:${agent}`,
|
|
1027
|
+
managedName,
|
|
1028
|
+
check: async () => {
|
|
1029
|
+
const snapshot = this.processManager.listAgentSnapshots().find((row) => row.name === managedName);
|
|
1030
|
+
if (snapshot?.status !== "running")
|
|
1031
|
+
return { ok: true };
|
|
1032
|
+
const runtimePath = path.join(this.bundlesRoot, `${agent}.ouro`, "state", "senses", "bluebubbles", "runtime.json");
|
|
1033
|
+
const state = fs.existsSync(runtimePath) ? readBlueBubblesRuntimeJson(runtimePath) : null;
|
|
1034
|
+
// A file caught mid-write says nothing either way.
|
|
1035
|
+
if (state?.unreadable)
|
|
1036
|
+
return { ok: true };
|
|
1037
|
+
const proofAt = (state && blueBubblesLatestProof(state).at) ?? null;
|
|
1038
|
+
const processKey = `${snapshot.pid ?? ""}:${snapshot.startedAt ?? ""}`;
|
|
1039
|
+
// Timed on this daemon's own clock, which stops while the machine sleeps just as the listener's timers do,
|
|
1040
|
+
// so waking from sleep or a wall-clock correction never makes a proof look stale.
|
|
1041
|
+
const now = this.monotonicNow();
|
|
1042
|
+
const watch = this.blueBubblesProofWatch.get(agent);
|
|
1043
|
+
if (!watch || watch.process !== processKey || watch.proofAt !== proofAt) {
|
|
1044
|
+
const restarts = watch && watch.proofAt === proofAt ? watch.restarts : 0;
|
|
1045
|
+
this.blueBubblesProofWatch.set(agent, { process: processKey, proofAt, sinceMs: now, restarts });
|
|
1046
|
+
return { ok: true };
|
|
1047
|
+
}
|
|
1048
|
+
const stalledMs = now - watch.sinceMs;
|
|
1049
|
+
if (stalledMs < exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS * 2 ** Math.min(watch.restarts, BLUEBUBBLES_STALE_PROOF_MAX_DOUBLINGS))
|
|
1050
|
+
return { ok: true };
|
|
1051
|
+
// If the restart brings no new proof either, wait longer before the next one.
|
|
1052
|
+
watch.restarts += 1;
|
|
1053
|
+
watch.sinceMs = now;
|
|
1054
|
+
const stalledMinutes = Math.round(stalledMs / 60_000);
|
|
1055
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1056
|
+
level: "warn",
|
|
1057
|
+
component: "daemon",
|
|
1058
|
+
event: "daemon.bluebubbles_stale_proof_restart",
|
|
1059
|
+
message: "restarting a BlueBubbles listener whose proof stopped updating",
|
|
1060
|
+
meta: {
|
|
1061
|
+
agent,
|
|
1062
|
+
stalledMs,
|
|
1063
|
+
lastProofAt: proofAt,
|
|
1064
|
+
restarts: watch.restarts,
|
|
1065
|
+
nextRestartAfterMs: exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS * 2 ** Math.min(watch.restarts, BLUEBUBBLES_STALE_PROOF_MAX_DOUBLINGS),
|
|
1066
|
+
},
|
|
1067
|
+
});
|
|
1068
|
+
return {
|
|
1069
|
+
ok: false,
|
|
1070
|
+
detail: proofAt === null
|
|
1071
|
+
? `the BlueBubbles listener has written no BlueBubbles proof in ${stalledMinutes}m; restarting it`
|
|
1072
|
+
: `BlueBubbles proof has not changed in ${stalledMinutes}m; restarting the listener`,
|
|
1073
|
+
};
|
|
1074
|
+
},
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
983
1077
|
async restartSense(managedName) {
|
|
984
1078
|
const parsed = parseSenseSnapshotName(managedName);
|
|
985
1079
|
if (parsed?.sense === "shepherd" && this.quiescedShepherdOwners.has(parsed.agent))
|
|
@@ -1303,7 +1303,7 @@ function validateDisposition(disposition) {
|
|
|
1303
1303
|
if (disposition.nextWake.kind === "at")
|
|
1304
1304
|
assertBoundedText(disposition.nextWake.at, "wake time", 64);
|
|
1305
1305
|
if (disposition.ownerMessage) {
|
|
1306
|
-
if (!["sent", "already_sent", "covered"].includes(disposition.ownerMessage.status))
|
|
1306
|
+
if (!["sent", "saved", "already_sent", "covered"].includes(disposition.ownerMessage.status))
|
|
1307
1307
|
throw new Error("External event owner message status is invalid");
|
|
1308
1308
|
if (!disposition.ownerMessage.effectKey)
|
|
1309
1309
|
throw new Error("External event owner message key is missing");
|
|
@@ -484,7 +484,7 @@ function defaultSummarySnapshot(input) {
|
|
|
484
484
|
nextLikelyStep: null,
|
|
485
485
|
};
|
|
486
486
|
}
|
|
487
|
-
const surfaced = (input.surfaceAttempts ?? []).find(
|
|
487
|
+
const surfaced = (input.surfaceAttempts ?? []).find(successfulSurfaceAttempt);
|
|
488
488
|
if (surfaced) {
|
|
489
489
|
return {
|
|
490
490
|
summary: `Habit ${input.habit.name} surfaced via ${surfaced.recipient}/${surfaced.channel}.`,
|
|
@@ -540,10 +540,17 @@ function buildHabitRunReceipt(input) {
|
|
|
540
540
|
});
|
|
541
541
|
return receipt;
|
|
542
542
|
}
|
|
543
|
+
/** A refused send: it will not reach them. */
|
|
544
|
+
function refusedSurfaceAttempt(attempt) {
|
|
545
|
+
return attempt.result === "blocked"
|
|
546
|
+
|| attempt.result === "failed"
|
|
547
|
+
|| attempt.result === "unavailable";
|
|
548
|
+
}
|
|
549
|
+
/** A send that reached the person now. Queued and deferred ones wait for their next message, so they have not surfaced yet. */
|
|
543
550
|
function successfulSurfaceAttempt(attempt) {
|
|
544
|
-
return attempt
|
|
545
|
-
&& attempt.result !== "
|
|
546
|
-
&& attempt.result !== "
|
|
551
|
+
return !refusedSurfaceAttempt(attempt)
|
|
552
|
+
&& attempt.result !== "queued"
|
|
553
|
+
&& attempt.result !== "deferred";
|
|
547
554
|
}
|
|
548
555
|
function surfaceRefsFromAttempts(attempts) {
|
|
549
556
|
return attempts
|
|
@@ -568,7 +575,7 @@ function habitOutcomeForCompletion(input) {
|
|
|
568
575
|
return { outcome: "updated_desk", producedRefs };
|
|
569
576
|
if (producedRefs.some((ref) => ref.kind === "arc" || ref.kind === "claim"))
|
|
570
577
|
return { outcome: "wrote_arc", producedRefs };
|
|
571
|
-
if (attempts.length > 0 && attempts.every(
|
|
578
|
+
if (attempts.length > 0 && attempts.every(refusedSurfaceAttempt)) {
|
|
572
579
|
return { outcome: "blocked", producedRefs };
|
|
573
580
|
}
|
|
574
581
|
return { outcome: "no_change", producedRefs };
|
package/dist/mind/pending.js
CHANGED
|
@@ -42,6 +42,7 @@ exports.queuePendingMessage = queuePendingMessage;
|
|
|
42
42
|
exports.queuePendingMessageOnce = queuePendingMessageOnce;
|
|
43
43
|
exports.enqueueDeferredReturn = enqueueDeferredReturn;
|
|
44
44
|
exports.drainDeferredReturns = drainDeferredReturns;
|
|
45
|
+
exports.withdrawDeferredReturn = withdrawDeferredReturn;
|
|
45
46
|
exports.drainPending = drainPending;
|
|
46
47
|
const fs = __importStar(require("fs"));
|
|
47
48
|
const path = __importStar(require("path"));
|
|
@@ -172,6 +173,34 @@ function drainDeferredReturns(agentName, friendId) {
|
|
|
172
173
|
});
|
|
173
174
|
return messages;
|
|
174
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Removes the saved copies of one message from a friend's deferred returns, for when the same turn
|
|
178
|
+
* reached them another way after it was saved. Returns how many it removed.
|
|
179
|
+
*/
|
|
180
|
+
function withdrawDeferredReturn(agentName, friendId, content) {
|
|
181
|
+
const queueDir = getDeferredReturnDir(agentName, friendId);
|
|
182
|
+
if (!fs.existsSync(queueDir))
|
|
183
|
+
return 0;
|
|
184
|
+
const saved = (0, session_events_1.capStructuredRecordString)(content);
|
|
185
|
+
let removed = 0;
|
|
186
|
+
for (const file of fs.readdirSync(queueDir).filter((name) => name.endsWith(".json"))) {
|
|
187
|
+
const filePath = path.join(queueDir, file);
|
|
188
|
+
try {
|
|
189
|
+
if (JSON.parse(fs.readFileSync(filePath, "utf-8")).content !== saved)
|
|
190
|
+
continue;
|
|
191
|
+
fs.unlinkSync(filePath);
|
|
192
|
+
removed += 1;
|
|
193
|
+
}
|
|
194
|
+
catch { /* unreadable or already drained: leave it */ }
|
|
195
|
+
}
|
|
196
|
+
(0, runtime_1.emitNervesEvent)({
|
|
197
|
+
event: "mind.deferred_return_withdrawn",
|
|
198
|
+
component: "mind",
|
|
199
|
+
message: "saved friend return withdrawn because the turn reached them another way",
|
|
200
|
+
meta: { friendId, queueDir, removed },
|
|
201
|
+
});
|
|
202
|
+
return removed;
|
|
203
|
+
}
|
|
175
204
|
function drainPending(pendingDir) {
|
|
176
205
|
if (!fs.existsSync(pendingDir))
|
|
177
206
|
return [];
|
|
@@ -129,6 +129,7 @@ exports.FLOW_TOOL_REFUSALS = {
|
|
|
129
129
|
settleHeldWork: (0, tool_error_code_1.withCode)("current held-work frame still has unsurfaced items — return each listed item with surface(delegationId=...) before you settle. Older transcript claims are historical; only the current held-work frame is the gate.", "held-work-unsurfaced"),
|
|
130
130
|
restHeldWork: (0, tool_error_code_1.withCode)("current held-work frame still has unsurfaced items — return each listed item with surface(delegationId=...) before you rest. Older transcript claims are historical; only the current held-work frame is the gate.", "held-work-unsurfaced"),
|
|
131
131
|
restFreshWork: (0, tool_error_code_1.withCode)("fresh work arrived for me this turn — inspect the pending messages above and take the next concrete action before you rest.", "fresh-work-pending"),
|
|
132
|
+
restSurfaceNotSent: (surfaceResult) => (0, tool_error_code_1.withCode)(`your surface this turn did not reach them: ${surfaceResult.replace(/ \(code: [a-z0-9-]+\)$/u, "").replace(/\.$/u, "")}. reach them another way now if the result names one, or rest again and it waits for their next message.`, "surface-not-sent"),
|
|
132
133
|
speakEmpty: (0, tool_error_code_1.withCode)("speak requires a non-empty `message` string.", "empty-message"),
|
|
133
134
|
speakNotDelivered: (detail) => (0, tool_error_code_1.withCode)(`speak delivery failed: ${detail}. the message did not reach your friend; do not assume they saw it.`, "speak-not-delivered"),
|
|
134
135
|
ponderCreateIncomplete: (0, tool_error_code_1.withCode)("ponder create requires kind, objective, success_criteria, and valid payload_json.", "ponder-fields-missing"),
|
|
@@ -151,6 +152,7 @@ exports.toolCards = [
|
|
|
151
152
|
{ code: "rest-alone", means: "rest came in one batch with other tool calls, so nothing in the batch ran.", fix: "Make the other calls first, read their results, then call rest on its own." },
|
|
152
153
|
{ code: "held-work-unsurfaced", means: "This private turn still holds work someone is waiting on.", fix: "Return each listed item with surface(delegationId=...), then rest." },
|
|
153
154
|
{ code: "fresh-work-pending", means: "New messages arrived during this turn, so rest waits once.", fix: "Read the pending messages and act on them, then rest." },
|
|
155
|
+
{ code: "surface-not-sent", means: "A surface this turn came back not sent (saved for the person's next message), so rest waits once.", fix: "Reach them another way if the surface result names one, or rest again and it waits for their next message." },
|
|
154
156
|
] },
|
|
155
157
|
{ id: "tool:ponder", group: "turn-flow", when: "Pick this when a question needs more thought than this turn allows, or harness friction should be worked on privately later.", effect: "write", errors: [
|
|
156
158
|
{ code: "ponder-fields-missing", means: "A field ponder needs was missing, or payload_json was not a JSON object.", fix: "Call ponder again with kind, objective, success_criteria and payload_json, plus packet_id to revise." },
|
|
@@ -33,7 +33,8 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.toolCards = exports.surfaceToolDefinition = exports.surfaceToolDef = void 0;
|
|
36
|
+
exports.toolCards = exports.surfaceToolDefinition = exports.SPONTANEOUS_OUTREACH_FRESH_DAYS = exports.surfaceToolDef = void 0;
|
|
37
|
+
exports.sendSpontaneousOutreach = sendSpontaneousOutreach;
|
|
37
38
|
exports.routeSurfaceToFriend = routeSurfaceToFriend;
|
|
38
39
|
const fs = __importStar(require("fs"));
|
|
39
40
|
const crypto_1 = require("crypto");
|
|
@@ -44,6 +45,7 @@ const obligations_1 = require("../arc/obligations");
|
|
|
44
45
|
const packets_1 = require("../arc/packets");
|
|
45
46
|
const session_activity_1 = require("../heart/session-activity");
|
|
46
47
|
const bluebubbles_meta_guard_1 = require("../senses/bluebubbles-meta-guard");
|
|
48
|
+
const proactive_content_guard_1 = require("../senses/proactive-content-guard");
|
|
47
49
|
const runtime_1 = require("../nerves/runtime");
|
|
48
50
|
const path = __importStar(require("path"));
|
|
49
51
|
const outbound_1 = require("../senses/voice/outbound");
|
|
@@ -84,7 +86,7 @@ exports.surfaceToolDef = {
|
|
|
84
86
|
type: "function",
|
|
85
87
|
function: {
|
|
86
88
|
name: "surface",
|
|
87
|
-
description: "return a ready thought to a friend or active session
|
|
89
|
+
description: "return a ready thought to a friend or active session; content carrying internal markers is refused. pass delegationId to address a held thought (see your attention queue above): it goes back to the session that asked. pass friendId for spontaneous outreach: to a person it sends now on their newest iMessage, Telegram or Teams chat active in the last 30 days, trying the next if one does not send, and skipping MCP, CLI and agent sessions, which they don't read; to an agent friend it goes to that agent's newest session. if a send fails partway it comes back unconfirmed: it may have reached them, so don't send it again. if none sends, it comes back deferred: not sent, saved for their next message, and the result says why and what else reaches them. set channel=voice only when you intentionally want a live phone call; content becomes the call reason/opening context. set channel=teams to tell a friend on Teams now (it sends at once where your Teams sense runs, otherwise waits in their Teams chat). does not end your turn.",
|
|
88
90
|
parameters: {
|
|
89
91
|
type: "object",
|
|
90
92
|
properties: {
|
|
@@ -98,7 +100,7 @@ exports.surfaceToolDef = {
|
|
|
98
100
|
},
|
|
99
101
|
friendId: {
|
|
100
102
|
type: "string",
|
|
101
|
-
description: "friend to reach out to spontaneously (when not addressing a held thought)",
|
|
103
|
+
description: "friend to reach out to spontaneously (when not addressing a held thought); sends now on their newest active iMessage, Telegram or Teams chat, otherwise comes back deferred (not sent, saved)",
|
|
102
104
|
},
|
|
103
105
|
channel: {
|
|
104
106
|
type: "string",
|
|
@@ -139,14 +141,127 @@ exports.surfaceToolDef = {
|
|
|
139
141
|
},
|
|
140
142
|
},
|
|
141
143
|
};
|
|
144
|
+
/** A chat surface sends on unprompted is used only while the friend has been active in it this recently. */
|
|
145
|
+
exports.SPONTANEOUS_OUTREACH_FRESH_DAYS = 30;
|
|
146
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
147
|
+
/** The senses surface sends on at once when it reaches out to a friend unprompted, as a person would name them. */
|
|
148
|
+
const PUSH_CHANNEL_LABELS = { bluebubbles: "iMessage", telegram: "Telegram", teams: "Teams" };
|
|
149
|
+
/**
|
|
150
|
+
* Spontaneous outreach: send now on the friend's chats that reach a person (iMessage, Telegram, Teams), newest first,
|
|
151
|
+
* skipping group chats and chats quiet for more than SPONTANEOUS_OUTREACH_FRESH_DAYS, until one sends. It never
|
|
152
|
+
* picks an MCP session (the next connecting agent would read it) or a CLI session (they see it only when they reopen
|
|
153
|
+
* it). A send that failed partway stops the search, since it may have reached them, and so does a content guard's
|
|
154
|
+
* refusal, since no other chat should carry that text. When none sends it returns the
|
|
155
|
+
* detail for a deferred return: why, and a call only if the friend takes calls.
|
|
156
|
+
*/
|
|
157
|
+
async function sendSpontaneousOutreach(friendId, sessions, senders, nowMs) {
|
|
158
|
+
const isGroup = (session) => session.channel === "bluebubbles" && session.key.includes(";+;");
|
|
159
|
+
const isPush = (session) => session.channel in PUSH_CHANNEL_LABELS && !isGroup(session);
|
|
160
|
+
const quietDays = (session) => Math.floor((nowMs - session.lastActivityMs) / DAY_MS);
|
|
161
|
+
const failures = [];
|
|
162
|
+
for (const target of sessions.filter((session) => isPush(session) && quietDays(session) < exports.SPONTANEOUS_OUTREACH_FRESH_DAYS)) {
|
|
163
|
+
let attempt;
|
|
164
|
+
try {
|
|
165
|
+
attempt = await senders[target.channel](target);
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
attempt = { status: "unsent", why: error instanceof Error ? error.message : String(error) };
|
|
169
|
+
}
|
|
170
|
+
if (attempt.status === "refused") {
|
|
171
|
+
const detail = `blocked: ${PUSH_CHANNEL_LABELS[target.channel]} refused this text as internal (${attempt.why}), so no chat sends it; rewrite it as plain words for them`;
|
|
172
|
+
return { sent: { status: "failed", detail: (0, tool_error_code_1.withCode)(detail, "delivery-blocked") } };
|
|
173
|
+
}
|
|
174
|
+
if (attempt.status !== "unsent")
|
|
175
|
+
return { sent: { status: attempt.status, detail: attempt.detail } };
|
|
176
|
+
const failure = `${PUSH_CHANNEL_LABELS[target.channel]} did not send (${attempt.why})`;
|
|
177
|
+
if (!failures.includes(failure))
|
|
178
|
+
failures.push(failure);
|
|
179
|
+
}
|
|
180
|
+
const name = sessions.find((session) => session.friendName)?.friendName ?? friendId;
|
|
181
|
+
const lead = "not sent now; saved for their next message.";
|
|
182
|
+
if (sessions.length === 0)
|
|
183
|
+
return { unsentDetail: `${lead} ${name} has no chat session with you yet.` };
|
|
184
|
+
const kind = (session) => isGroup(session) ? "group" : isPush(session) && quietDays(session) >= exports.SPONTANEOUS_OUTREACH_FRESH_DAYS ? "quiet" : "other";
|
|
185
|
+
const label = (session) => kind(session) === "group"
|
|
186
|
+
? `${session.channel} group chat (skipped)`
|
|
187
|
+
: kind(session) === "quiet" ? `${session.channel} quiet for ${quietDays(session)} days` : session.channel;
|
|
188
|
+
const theirs = sessions
|
|
189
|
+
.filter((session, index) => sessions.findIndex((other) => other.channel === session.channel && kind(other) === kind(session)) === index)
|
|
190
|
+
.map(label)
|
|
191
|
+
.join(", ");
|
|
192
|
+
const why = failures.length > 0
|
|
193
|
+
? `${failures.join("; ")}.`
|
|
194
|
+
: `${name} has no chat that surface can send on, active in the last ${exports.SPONTANEOUS_OUTREACH_FRESH_DAYS} days (their sessions: ${theirs}).`;
|
|
195
|
+
const call = sessions.some((session) => session.channel === "voice")
|
|
196
|
+
? ` Only if it is urgent: surface friendId="${friendId}" channel="voice" calls them.`
|
|
197
|
+
: "";
|
|
198
|
+
return { unsentDetail: `${lead} ${why}${call}` };
|
|
199
|
+
}
|
|
200
|
+
/** Send outcomes where a sense's guard refused the text itself, not the chat. */
|
|
201
|
+
const CONTENT_REFUSALS = new Set(["internal_content_blocked", "blocked_meta_content"]);
|
|
202
|
+
const unconfirmedDetail = (sense) => `the ${sense} send failed partway, so it may have reached them; don't resend unless they say they didn't get it`;
|
|
203
|
+
const teamsForwardedDetail = (machine) => `handed to ${machine}, which runs Teams; it sends on its next sync`;
|
|
204
|
+
/** A Teams send_error may have gone out unless Teams said it was not sent. */
|
|
205
|
+
const teamsSendMayHaveGoneOut = (sent) => sent.delivery?.state === "unknown" || (sent.reason === "send_error" && sent.delivery?.state !== "not_sent");
|
|
206
|
+
/** How each push sense sends one spontaneous message, and what its outcome means. */
|
|
207
|
+
function spontaneousOutreachSenders(agentName, agentRoot, content, queueItem) {
|
|
208
|
+
return {
|
|
209
|
+
bluebubbles: async (target) => {
|
|
210
|
+
const { sendProactiveBlueBubblesMessageToSession } = await Promise.resolve().then(() => __importStar(require("../senses/bluebubbles")));
|
|
211
|
+
const sent = await sendProactiveBlueBubblesMessageToSession({ friendId: target.friendId, sessionKey: target.key, text: content, intent: "generic_outreach", origin: "proactive" });
|
|
212
|
+
if (sent.delivered)
|
|
213
|
+
return { status: "delivered", detail: "texted them by iMessage now" };
|
|
214
|
+
if (sent.delivery?.state === "unknown")
|
|
215
|
+
return { status: "unconfirmed", detail: unconfirmedDetail("iMessage") };
|
|
216
|
+
if (sent.reason && CONTENT_REFUSALS.has(sent.reason))
|
|
217
|
+
return { status: "refused", why: sent.reason };
|
|
218
|
+
return { status: "unsent", why: sent.reason ?? "not delivered" };
|
|
219
|
+
},
|
|
220
|
+
telegram: async (target) => {
|
|
221
|
+
const telegramKey = (0, config_1.canonicalizeTelegramSessionKey)(target.key);
|
|
222
|
+
const hash = (0, crypto_1.createHash)("sha256").update(`${target.friendId}\0${telegramKey}\0${content}`).digest("hex");
|
|
223
|
+
const { sendTelegramAwaitFollowUp } = await Promise.resolve().then(() => __importStar(require("../senses/telegram")));
|
|
224
|
+
const delivered = await sendTelegramAwaitFollowUp(agentName, {
|
|
225
|
+
friendId: target.friendId,
|
|
226
|
+
channel: "telegram",
|
|
227
|
+
key: telegramKey,
|
|
228
|
+
content,
|
|
229
|
+
requestId: queueItem?.obligationId ?? `surface:${hash}`,
|
|
230
|
+
deliveryId: queueItem?.obligationId ? `surface:${queueItem.obligationId}:${hash}` : `surface:${hash}`,
|
|
231
|
+
intent: "generic_outreach",
|
|
232
|
+
});
|
|
233
|
+
if (delivered.status === "delivered_now")
|
|
234
|
+
return { status: "delivered", detail: "sent to Telegram now" };
|
|
235
|
+
if (delivered.status === "forwarded")
|
|
236
|
+
return { status: "forwarded", detail: `handed to the machine that runs Telegram: ${delivered.detail}` };
|
|
237
|
+
return { status: "unsent", why: delivered.detail ?? delivered.status };
|
|
238
|
+
},
|
|
239
|
+
teams: async (target) => {
|
|
240
|
+
const { sendTeamsOffTurn } = await Promise.resolve().then(() => __importStar(require("../senses/teams-off-turn")));
|
|
241
|
+
const sent = await sendTeamsOffTurn({ friendId: target.friendId, key: target.key, text: content, origin: "proactive", captureReceipt: true }, { agentRoot });
|
|
242
|
+
if (sent?.forwardedTo)
|
|
243
|
+
return { status: "forwarded", detail: teamsForwardedDetail(sent.forwardedTo) };
|
|
244
|
+
if (sent?.delivered)
|
|
245
|
+
return { status: "delivered", detail: "sent to Teams now" };
|
|
246
|
+
if (sent && teamsSendMayHaveGoneOut(sent))
|
|
247
|
+
return { status: "unconfirmed", detail: unconfirmedDetail("Teams") };
|
|
248
|
+
if (sent?.reason && CONTENT_REFUSALS.has(sent.reason))
|
|
249
|
+
return { status: "refused", why: sent.reason };
|
|
250
|
+
return { status: "unsent", why: sent?.reason ?? "not available here" };
|
|
251
|
+
},
|
|
252
|
+
};
|
|
253
|
+
}
|
|
142
254
|
// Surface tool handler: routes content to friend's freshest session
|
|
143
255
|
/**
|
|
144
256
|
* Delivers content to a friend the way surface does: the held-work origin or a
|
|
145
|
-
* bridge first, then the friend's
|
|
146
|
-
*
|
|
147
|
-
*
|
|
257
|
+
* bridge first, then for spontaneous outreach the friend's newest active iMessage,
|
|
258
|
+
* Telegram or Teams chat that sends (see sendSpontaneousOutreach), and otherwise
|
|
259
|
+
* a deferred return for their next message, saying it was not sent. Also used for
|
|
260
|
+
* an ordinary agent's external-event owner message.
|
|
148
261
|
*/
|
|
149
262
|
async function routeSurfaceToFriend(agentName, friendId, content, queueItem, hint) {
|
|
263
|
+
if ((0, bluebubbles_meta_guard_1.containsInternalMetaMarkers)(content))
|
|
264
|
+
return { status: "failed", detail: "blocked: contains internal meta markers" };
|
|
150
265
|
/* v8 ignore start -- routing: integration path tested via private-runtime routing tests @preserve */
|
|
151
266
|
try {
|
|
152
267
|
const agentRoot = (0, identity_1.getAgentRoot)();
|
|
@@ -163,11 +278,11 @@ async function routeSurfaceToFriend(agentName, friendId, content, queueItem, hin
|
|
|
163
278
|
content,
|
|
164
279
|
timestamp: Date.now(),
|
|
165
280
|
});
|
|
166
|
-
// A BlueBubbles return deliberately waits for the friend's next
|
|
167
|
-
// instead of live-sending one. Say so, so the agent never reads
|
|
168
|
-
// as "sent"
|
|
281
|
+
// A held BlueBubbles return deliberately waits for the friend's next
|
|
282
|
+
// iMessage instead of live-sending one. Say so, so the agent never reads
|
|
283
|
+
// "queued" as "sent".
|
|
169
284
|
return target.channel === "bluebubbles"
|
|
170
|
-
? { status: "queued", detail: `${detail}; it waits for their next iMessage
|
|
285
|
+
? { status: "queued", detail: `${detail}; it waits for their next iMessage` }
|
|
171
286
|
: { status: "queued", detail };
|
|
172
287
|
};
|
|
173
288
|
const deliverTelegramOrQueue = async (target, detail) => {
|
|
@@ -185,19 +300,24 @@ async function routeSurfaceToFriend(agentName, friendId, content, queueItem, hin
|
|
|
185
300
|
deliveryId,
|
|
186
301
|
intent: "generic_outreach",
|
|
187
302
|
});
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
303
|
+
if (delivered.status === "delivered_now")
|
|
304
|
+
return { status: "delivered", detail: "sent to Telegram now" };
|
|
305
|
+
if (delivered.status === "forwarded")
|
|
306
|
+
return { status: "forwarded", detail: `handed to the machine that runs Telegram: ${delivered.detail}` };
|
|
307
|
+
return queueToSession(target, detail);
|
|
191
308
|
};
|
|
192
309
|
const deliverTeamsOrQueue = async (target, detail) => {
|
|
193
310
|
const { sendTeamsOffTurn } = await Promise.resolve().then(() => __importStar(require("../senses/teams-off-turn")));
|
|
194
|
-
const sent = await sendTeamsOffTurn({ friendId: target.friendId, key: target.key, text: content, origin: "proactive" }, { agentRoot });
|
|
311
|
+
const sent = await sendTeamsOffTurn({ friendId: target.friendId, key: target.key, text: content, origin: "proactive", captureReceipt: true }, { agentRoot });
|
|
195
312
|
if (sent?.forwardedTo)
|
|
196
|
-
return { status: "
|
|
313
|
+
return { status: "forwarded", detail: teamsForwardedDetail(sent.forwardedTo) };
|
|
197
314
|
if (sent?.delivered)
|
|
198
315
|
return { status: "delivered", detail: "sent to Teams now" };
|
|
199
|
-
if (sent
|
|
200
|
-
return
|
|
316
|
+
if (sent && teamsSendMayHaveGoneOut(sent))
|
|
317
|
+
return { status: "unconfirmed", detail: unconfirmedDetail("Teams") };
|
|
318
|
+
if (sent?.reason && CONTENT_REFUSALS.has(sent.reason)) {
|
|
319
|
+
return { status: "failed", detail: (0, tool_error_code_1.withCode)(`blocked: Teams refused this text as internal (${sent.reason}); rewrite it as plain words for them`, "delivery-blocked") };
|
|
320
|
+
}
|
|
201
321
|
return queueToSession(target, detail);
|
|
202
322
|
};
|
|
203
323
|
const deliverOrQueue = (target, detail) => target.channel === "telegram"
|
|
@@ -265,16 +385,32 @@ async function routeSurfaceToFriend(agentName, friendId, content, queueItem, hin
|
|
|
265
385
|
const detail = `for originating ${queueItem.channel} session`;
|
|
266
386
|
return deliverOrQueue(target, detail);
|
|
267
387
|
}
|
|
268
|
-
// Priority 2: Try proactive delivery first, then queue to freshest session
|
|
269
388
|
const allFriendSessions = (0, session_activity_1.listSessionActivity)({ sessionsDir, friendsDir, agentName, activeThresholdMs: Number.MAX_SAFE_INTEGER })
|
|
270
389
|
.filter((s) => s.friendId === friendId && s.channel !== "inner");
|
|
271
|
-
// Priority
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
390
|
+
// Priority 2a: an agent friend reads its MCP or a2a session, so outreach to
|
|
391
|
+
// it still goes to its freshest session.
|
|
392
|
+
const friendKind = (() => {
|
|
393
|
+
try {
|
|
394
|
+
return JSON.parse(fs.readFileSync(path.join(friendsDir, `${friendId}.json`), "utf-8")).kind;
|
|
395
|
+
}
|
|
396
|
+
catch {
|
|
397
|
+
return undefined;
|
|
398
|
+
}
|
|
399
|
+
})();
|
|
400
|
+
if (friendKind === "agent" && allFriendSessions[0]) {
|
|
401
|
+
return deliverOrQueue(allFriendSessions[0], `for next interaction via ${allFriendSessions[0].channel}`);
|
|
402
|
+
}
|
|
403
|
+
// Priority 2b: spontaneous outreach to a person sends now where it reaches
|
|
404
|
+
// them, never into a session only agents read (MCP) or one they must reopen (CLI).
|
|
405
|
+
// Text the senses' content guard refuses goes nowhere, whichever chat is newest.
|
|
406
|
+
const contentBlock = (0, proactive_content_guard_1.getProactiveInternalContentBlockReason)(content);
|
|
407
|
+
if (contentBlock) {
|
|
408
|
+
return { status: "failed", detail: (0, tool_error_code_1.withCode)(`blocked: this reads as internal status (${contentBlock}), so no chat sends it; rewrite it as plain words for them`, "delivery-blocked") };
|
|
276
409
|
}
|
|
277
|
-
|
|
410
|
+
const outreach = await sendSpontaneousOutreach(friendId, allFriendSessions, spontaneousOutreachSenders(agentName, agentRoot, content, queueItem), Date.now());
|
|
411
|
+
if ("sent" in outreach)
|
|
412
|
+
return outreach.sent;
|
|
413
|
+
// Priority 3: Deferred — nothing sent now; their next message picks it up.
|
|
278
414
|
const { getDeferredReturnDir } = await Promise.resolve().then(() => __importStar(require("../mind/pending")));
|
|
279
415
|
const { queuePendingMessage: queueDeferred } = await Promise.resolve().then(() => __importStar(require("../mind/pending")));
|
|
280
416
|
const deferredDir = getDeferredReturnDir(agentName, friendId);
|
|
@@ -286,7 +422,7 @@ async function routeSurfaceToFriend(agentName, friendId, content, queueItem, hin
|
|
|
286
422
|
content,
|
|
287
423
|
timestamp: Date.now(),
|
|
288
424
|
});
|
|
289
|
-
return { status: "deferred", detail:
|
|
425
|
+
return { status: "deferred", detail: outreach.unsentDetail };
|
|
290
426
|
}
|
|
291
427
|
catch {
|
|
292
428
|
return { status: "failed" };
|
|
@@ -302,6 +438,7 @@ const surfaceCard = {
|
|
|
302
438
|
errors: [
|
|
303
439
|
{ code: "delivery-blocked", means: "The content carries internal meta markers, so nothing was delivered.", fix: "Rewrite the content as plain words for the person and surface it again." },
|
|
304
440
|
{ code: "orientation-hold", means: "This turn is on a correction hold, so surfacing waits.", fix: "Call orientation_get, settle what the person meant, then surface the thought if it still answers them." },
|
|
441
|
+
{ code: "surface-not-sent", means: "No chat sent the message now, so it is saved for the friend's next message; the result says why.", fix: "If it cannot wait and the result offers a call, call them; otherwise let it wait." },
|
|
305
442
|
],
|
|
306
443
|
};
|
|
307
444
|
/* v8 ignore start -- surface handler wiring: core logic tested via surface-tool.test.ts; this wires identity/routing deps @preserve */
|
|
@@ -337,7 +474,7 @@ exports.surfaceToolDefinition = {
|
|
|
337
474
|
return "unknown";
|
|
338
475
|
} })();
|
|
339
476
|
const routeToFriend = (friendId, content, queueItem, hint) => routeSurfaceToFriend(agentName, friendId, content, queueItem, hint);
|
|
340
|
-
|
|
477
|
+
const surfaced = await (0, surface_tool_1.handleSurface)({
|
|
341
478
|
content: args.content ?? "",
|
|
342
479
|
delegationId: args.delegationId,
|
|
343
480
|
friendId: args.friendId,
|
|
@@ -393,13 +530,16 @@ exports.surfaceToolDefinition = {
|
|
|
393
530
|
recipient: targetFriendId,
|
|
394
531
|
channel: queueItem?.channel ?? args.channel ?? "surface",
|
|
395
532
|
reason: result.status === "failed" ? "blocked" : "answer",
|
|
396
|
-
|
|
533
|
+
// forwarded and unconfirmed most likely reach them; deferred and queued wait for their next message.
|
|
534
|
+
result: result.status === "forwarded" || result.status === "unconfirmed" ? "sent" : result.status,
|
|
397
535
|
rawStatus: result.status,
|
|
398
536
|
...(queueItem ? { routeKind: "originator" } : {}),
|
|
399
537
|
...(result.status === "failed" ? { error: result.detail ?? "surface route failed" } : {}),
|
|
400
538
|
});
|
|
401
539
|
},
|
|
402
540
|
});
|
|
541
|
+
// A deferred surface was not sent now, so it carries the code rest checks for.
|
|
542
|
+
return surfaced.startsWith("deferred") ? (0, tool_error_code_1.withCode)(surfaced, "surface-not-sent") : surfaced;
|
|
403
543
|
},
|
|
404
544
|
summaryKeys: ["content", "delegationId", "friendId", "channel"],
|
|
405
545
|
riskProfile: {
|
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
// Claude Code stop hook — checks the agent's pending queue and returns
|
|
3
3
|
// any messages as additionalContext for injection into the next turn.
|
|
4
4
|
//
|
|
5
|
-
// This is how the agent
|
|
6
|
-
//
|
|
7
|
-
//
|
|
5
|
+
// This is how the agent answers back into a dev tool session: a held return
|
|
6
|
+
// surfaced to the MCP session that asked (or a send_message to it) lands in
|
|
7
|
+
// that session's pending queue, and the stop hook injects it as context. An
|
|
8
|
+
// unprompted surface never lands here: it goes to a chat the person reads.
|
|
8
9
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
10
|
exports.handleStopHook = handleStopHook;
|
|
10
11
|
const pending_1 = require("../mind/pending");
|
|
@@ -429,6 +429,13 @@ const defaultDeps = {
|
|
|
429
429
|
}),
|
|
430
430
|
};
|
|
431
431
|
const BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS = 30_000;
|
|
432
|
+
/** After a failed sync, the next one comes sooner than the interval: 5 s, then 10 s, then 20 s. */
|
|
433
|
+
const BLUEBUBBLES_RUNTIME_SYNC_RETRY_BASE_MS = 5_000;
|
|
434
|
+
/**
|
|
435
|
+
* A sync that makes no progress (no probe answer, catch-up page or capture) for this long is abandoned so the next
|
|
436
|
+
* one can start. Every request times out in 30 s, so only a hang gets here; a slow catch-up that keeps going finishes.
|
|
437
|
+
*/
|
|
438
|
+
const BLUEBUBBLES_RUNTIME_SYNC_STALL_MS = 2 * 60_000;
|
|
432
439
|
const BLUEBUBBLES_RECOVERY_PASS_DELAY_MS = 1_000;
|
|
433
440
|
const BLUEBUBBLES_RECOVERY_PASS_INTERVAL_MS = 30_000;
|
|
434
441
|
// A turn that is still thinking after this long is treated as hung. It is generous on purpose: a slow reply that
|
|
@@ -3082,7 +3089,8 @@ function resolveBlueBubblesCatchUpSince(previousState, nowMs = Date.now()) {
|
|
|
3082
3089
|
if (previousState.upstreamStatus === "error") {
|
|
3083
3090
|
return nowMs - BLUEBUBBLES_RECOVERY_CATCHUP_LOOKBACK_MS;
|
|
3084
3091
|
}
|
|
3085
|
-
|
|
3092
|
+
// A sync abandoned partway through catch-up has moved lastCheckedAt but not the cursor.
|
|
3093
|
+
const lastCheckedAt = parseTimestampMs(previousState.catchUpThrough ?? previousState.lastCheckedAt);
|
|
3086
3094
|
if (lastCheckedAt !== null) {
|
|
3087
3095
|
return Math.max(0, lastCheckedAt - BLUEBUBBLES_HEALTHY_CATCHUP_OVERLAP_MS);
|
|
3088
3096
|
}
|
|
@@ -3124,16 +3132,32 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
|
|
|
3124
3132
|
options.lifecycleSignal?.throwIfAborted();
|
|
3125
3133
|
const resolvedDeps = { ...defaultDeps, ...deps };
|
|
3126
3134
|
const agentName = resolvedDeps.getAgentName();
|
|
3127
|
-
// Allocate before the first health-probe await. Any live webhook accepted
|
|
3128
|
-
// while that probe is pending must remain causally newer than this pass.
|
|
3129
|
-
const catchUpObservationBatch = options.catchUpObservationBatch ?? (0, latest_turn_1.beginObservationBatch)(BLUEBUBBLES_CATCHUP_PAGE_SIZE * BLUEBUBBLES_CATCHUP_MAX_PAGES);
|
|
3130
|
-
pruneBlueBubblesSemanticObservationGenerations(Date.now(), new Set((0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName).map((capture) => capture.keyHash)));
|
|
3131
|
-
const client = resolvedDeps.createClient();
|
|
3132
3135
|
const checkedAt = new Date().toISOString();
|
|
3133
3136
|
const previousState = (0, runtime_state_1.readBlueBubblesRuntimeState)(agentName);
|
|
3137
|
+
let probeStarted = false;
|
|
3138
|
+
let probePassed = false;
|
|
3134
3139
|
try {
|
|
3140
|
+
// Setup failures land in the catch below too, so they write an error proof like any failed sync.
|
|
3141
|
+
// Allocate before the first health-probe await. Any live webhook accepted
|
|
3142
|
+
// while that probe is pending must remain causally newer than this pass.
|
|
3143
|
+
const catchUpObservationBatch = options.catchUpObservationBatch ?? (0, latest_turn_1.beginObservationBatch)(BLUEBUBBLES_CATCHUP_PAGE_SIZE * BLUEBUBBLES_CATCHUP_MAX_PAGES);
|
|
3144
|
+
pruneBlueBubblesSemanticObservationGenerations(Date.now(), new Set((0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName).map((capture) => capture.keyHash)));
|
|
3145
|
+
const client = resolvedDeps.createClient();
|
|
3146
|
+
probeStarted = true;
|
|
3135
3147
|
await client.checkHealth();
|
|
3136
3148
|
options.lifecycleSignal?.throwIfAborted();
|
|
3149
|
+
probePassed = true;
|
|
3150
|
+
options.onProgress?.();
|
|
3151
|
+
// The listener logs at warn, so a healthy pass is silent; a recovery must not be.
|
|
3152
|
+
if (previousState.upstreamStatus === "error") {
|
|
3153
|
+
(0, runtime_1.emitNervesEvent)({
|
|
3154
|
+
level: "warn",
|
|
3155
|
+
component: "senses",
|
|
3156
|
+
event: "senses.bluebubbles_upstream_recovered",
|
|
3157
|
+
message: "bluebubbles upstream answered again after a failed sync",
|
|
3158
|
+
meta: { previousDetail: previousState.detail, previousCheckedAt: previousState.lastCheckedAt },
|
|
3159
|
+
});
|
|
3160
|
+
}
|
|
3137
3161
|
const pendingBeforeCatchup = blueBubblesPendingRecoverySnapshot(agentName);
|
|
3138
3162
|
const activeBeforeCatchup = (0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS);
|
|
3139
3163
|
(0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
|
|
@@ -3150,6 +3174,7 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
|
|
|
3150
3174
|
processTurns: false,
|
|
3151
3175
|
observationBatch: catchUpObservationBatch,
|
|
3152
3176
|
lifecycleSignal: options.lifecycleSignal,
|
|
3177
|
+
onProgress: options.onProgress,
|
|
3153
3178
|
});
|
|
3154
3179
|
options.lifecycleSignal?.throwIfAborted();
|
|
3155
3180
|
const failed = catchUp.failed;
|
|
@@ -3164,6 +3189,7 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
|
|
|
3164
3189
|
upstreamStatus: "ok",
|
|
3165
3190
|
detail: formatBlueBubblesRuntimeDetail(pendingAfterCatchup, failed, activeAfterCatchup),
|
|
3166
3191
|
lastCheckedAt: checkedAt,
|
|
3192
|
+
catchUpThrough: checkedAt,
|
|
3167
3193
|
proofMethod: "bluebubbles.checkHealth",
|
|
3168
3194
|
...pendingAfterCatchup,
|
|
3169
3195
|
...activeAfterCatchup,
|
|
@@ -3172,19 +3198,32 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
|
|
|
3172
3198
|
lastRecoveredAt: previousState.lastRecoveredAt,
|
|
3173
3199
|
lastRecoveredMessageGuid: previousState.lastRecoveredMessageGuid,
|
|
3174
3200
|
});
|
|
3201
|
+
return "ok";
|
|
3175
3202
|
}
|
|
3176
3203
|
catch (error) {
|
|
3177
3204
|
if (options.lifecycleSignal?.aborted)
|
|
3178
|
-
return;
|
|
3205
|
+
return "aborted";
|
|
3206
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
3207
|
+
// A failed probe logs itself, so a streak of them adds only the line that starts it. Anything else logs here.
|
|
3208
|
+
if (!probeStarted || probePassed || previousState.upstreamStatus !== "error") {
|
|
3209
|
+
(0, runtime_1.emitNervesEvent)({
|
|
3210
|
+
level: "warn",
|
|
3211
|
+
component: "senses",
|
|
3212
|
+
event: "senses.bluebubbles_runtime_sync_failed",
|
|
3213
|
+
message: "bluebubbles runtime sync failed; recorded upstream error",
|
|
3214
|
+
meta: { reason: detail, probePassed },
|
|
3215
|
+
});
|
|
3216
|
+
}
|
|
3179
3217
|
(0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
|
|
3180
3218
|
upstreamStatus: "error",
|
|
3181
|
-
detail
|
|
3219
|
+
detail,
|
|
3182
3220
|
lastCheckedAt: checkedAt,
|
|
3183
3221
|
proofMethod: "bluebubbles.checkHealth",
|
|
3184
3222
|
...blueBubblesPendingRecoverySnapshot(agentName),
|
|
3185
3223
|
...(0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS),
|
|
3186
3224
|
failedRecoveryCount: 0,
|
|
3187
3225
|
});
|
|
3226
|
+
return "error";
|
|
3188
3227
|
}
|
|
3189
3228
|
}
|
|
3190
3229
|
async function recoverQueuedBlueBubblesMessages(deps = {}, options = {}) {
|
|
@@ -3315,6 +3354,7 @@ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousStat
|
|
|
3315
3354
|
break;
|
|
3316
3355
|
}
|
|
3317
3356
|
options.lifecycleSignal?.throwIfAborted();
|
|
3357
|
+
options.onProgress?.();
|
|
3318
3358
|
const pageMessages = pageEvents
|
|
3319
3359
|
.filter((event) => event.kind === "message")
|
|
3320
3360
|
.sort((left, right) => right.timestamp - left.timestamp);
|
|
@@ -3375,6 +3415,7 @@ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousStat
|
|
|
3375
3415
|
try {
|
|
3376
3416
|
options.lifecycleSignal?.throwIfAborted();
|
|
3377
3417
|
const captured = await captureBlueBubblesSemanticEvent(event, resolvedDeps, "upstream-catchup", observationReservation);
|
|
3418
|
+
options.onProgress?.();
|
|
3378
3419
|
if (captured.status === "audit_only") {
|
|
3379
3420
|
result.skipped++;
|
|
3380
3421
|
continue;
|
|
@@ -4008,7 +4049,9 @@ async function sendProactiveBlueBubblesMessageToSession(params, deps = {}) {
|
|
|
4008
4049
|
reason: error instanceof Error ? error.message : String(error),
|
|
4009
4050
|
},
|
|
4010
4051
|
});
|
|
4011
|
-
|
|
4052
|
+
const refused = error instanceof client_1.BlueBubblesSendError && error.httpStatus !== null && error.httpStatus >= 400 && error.httpStatus < 500 && error.httpStatus !== 408 && error.httpStatus !== 409;
|
|
4053
|
+
const mayHaveGoneOut = error instanceof client_1.BlueBubblesSendError && error.transportInvoked && !refused;
|
|
4054
|
+
return { delivered: false, reason: "send_error", ...(mayHaveGoneOut ? { delivery: { state: "unknown" } } : {}) };
|
|
4012
4055
|
}
|
|
4013
4056
|
}
|
|
4014
4057
|
function scanPendingBlueBubblesFiles(pendingRoot) {
|
|
@@ -4233,7 +4276,9 @@ function startBlueBubblesApp(deps = {}) {
|
|
|
4233
4276
|
lifecycleSignal: lifecycleController.signal,
|
|
4234
4277
|
}));
|
|
4235
4278
|
let recoveryPassRunning = false;
|
|
4236
|
-
let
|
|
4279
|
+
let runtimeSync = null;
|
|
4280
|
+
let runtimeSyncFailures = 0;
|
|
4281
|
+
let runtimeSyncRetryTimer = null;
|
|
4237
4282
|
let recoveryDelayTimer = null;
|
|
4238
4283
|
let webhookReconciler = null;
|
|
4239
4284
|
let closed = false;
|
|
@@ -4276,16 +4321,65 @@ function startBlueBubblesApp(deps = {}) {
|
|
|
4276
4321
|
triggerRecoveryPass();
|
|
4277
4322
|
}, BLUEBUBBLES_RECOVERY_PASS_DELAY_MS);
|
|
4278
4323
|
}
|
|
4324
|
+
function scheduleRuntimeSyncRetry() {
|
|
4325
|
+
runtimeSyncFailures += 1;
|
|
4326
|
+
const delayMs = BLUEBUBBLES_RUNTIME_SYNC_RETRY_BASE_MS * 2 ** (runtimeSyncFailures - 1);
|
|
4327
|
+
// From here the 30 s interval retries soon enough.
|
|
4328
|
+
if (closed || delayMs >= BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS)
|
|
4329
|
+
return;
|
|
4330
|
+
runtimeSyncRetryTimer = setTimeout(() => {
|
|
4331
|
+
runtimeSyncRetryTimer = null;
|
|
4332
|
+
triggerRuntimeSync();
|
|
4333
|
+
}, delayMs);
|
|
4334
|
+
}
|
|
4279
4335
|
function triggerRuntimeSync(catchUpObservationBatch) {
|
|
4280
|
-
|
|
4336
|
+
/* v8 ignore next -- close clears the interval and the retry timer; guard covers an already-queued host callback @preserve */
|
|
4337
|
+
if (closed)
|
|
4281
4338
|
return;
|
|
4282
|
-
|
|
4339
|
+
if (runtimeSync) {
|
|
4340
|
+
const runningMs = Date.now() - runtimeSync.startedAt;
|
|
4341
|
+
const idleMs = Date.now() - runtimeSync.lastProgressAt;
|
|
4342
|
+
if (idleMs < BLUEBUBBLES_RUNTIME_SYNC_STALL_MS) {
|
|
4343
|
+
// A slow pass is still a live loop; say so, so the daemon does not take it for a stopped one.
|
|
4344
|
+
(0, runtime_state_1.touchBlueBubblesRuntimeHeartbeat)(resolvedDeps.getAgentName());
|
|
4345
|
+
return;
|
|
4346
|
+
}
|
|
4347
|
+
// A sync that never finishes must not stop every later one, which would leave the proof to go stale.
|
|
4348
|
+
(0, runtime_1.emitNervesEvent)({
|
|
4349
|
+
level: "warn",
|
|
4350
|
+
component: "senses",
|
|
4351
|
+
event: "senses.bluebubbles_runtime_sync_timeout",
|
|
4352
|
+
message: "abandoned a bluebubbles runtime sync that did not finish",
|
|
4353
|
+
meta: { runningMs, idleMs },
|
|
4354
|
+
});
|
|
4355
|
+
runtimeSync.controller.abort(new Error("bluebubbles_runtime_sync_timeout"));
|
|
4356
|
+
runtimeSync = null;
|
|
4357
|
+
}
|
|
4358
|
+
if (runtimeSyncRetryTimer !== null) {
|
|
4359
|
+
clearTimeout(runtimeSyncRetryTimer);
|
|
4360
|
+
runtimeSyncRetryTimer = null;
|
|
4361
|
+
}
|
|
4362
|
+
const sync = { startedAt: Date.now(), lastProgressAt: Date.now(), controller: new AbortController() };
|
|
4363
|
+
runtimeSync = sync;
|
|
4283
4364
|
void syncBlueBubblesRuntime(resolvedDeps, {
|
|
4284
4365
|
...(catchUpObservationBatch ? { catchUpObservationBatch } : {}),
|
|
4285
|
-
lifecycleSignal: lifecycleController.signal,
|
|
4366
|
+
lifecycleSignal: AbortSignal.any([lifecycleController.signal, sync.controller.signal]),
|
|
4367
|
+
onProgress: () => { sync.lastProgressAt = Date.now(); },
|
|
4368
|
+
})
|
|
4369
|
+
.then((outcome) => {
|
|
4370
|
+
if (runtimeSync !== sync)
|
|
4371
|
+
return;
|
|
4372
|
+
runtimeSync = null;
|
|
4373
|
+
if (outcome === "error")
|
|
4374
|
+
scheduleRuntimeSyncRetry();
|
|
4375
|
+
else
|
|
4376
|
+
runtimeSyncFailures = 0;
|
|
4377
|
+
scheduleRecoveryPass();
|
|
4286
4378
|
})
|
|
4287
|
-
|
|
4379
|
+
/* v8 ignore start -- defensive: every failure of the sync itself is caught inside it and written as an error proof @preserve */
|
|
4288
4380
|
.catch((error) => {
|
|
4381
|
+
if (runtimeSync === sync)
|
|
4382
|
+
runtimeSync = null;
|
|
4289
4383
|
if (closed)
|
|
4290
4384
|
return;
|
|
4291
4385
|
(0, runtime_1.emitNervesEvent)({
|
|
@@ -4295,10 +4389,9 @@ function startBlueBubblesApp(deps = {}) {
|
|
|
4295
4389
|
message: "bluebubbles runtime sync failed",
|
|
4296
4390
|
meta: { reason: error instanceof Error ? error.message : String(error) },
|
|
4297
4391
|
});
|
|
4298
|
-
|
|
4299
|
-
.finally(() => {
|
|
4300
|
-
runtimeSyncRunning = false;
|
|
4392
|
+
scheduleRuntimeSyncRetry();
|
|
4301
4393
|
});
|
|
4394
|
+
/* v8 ignore stop */
|
|
4302
4395
|
}
|
|
4303
4396
|
const runtimeTimer = setInterval(() => {
|
|
4304
4397
|
/* v8 ignore next -- close clears this interval; guard covers an already-queued host callback @preserve */
|
|
@@ -4316,6 +4409,10 @@ function startBlueBubblesApp(deps = {}) {
|
|
|
4316
4409
|
lifecycleController.abort(new Error("bluebubbles_runtime_shutdown"));
|
|
4317
4410
|
clearInterval(runtimeTimer);
|
|
4318
4411
|
clearInterval(recoveryTimer);
|
|
4412
|
+
if (runtimeSyncRetryTimer !== null) {
|
|
4413
|
+
clearTimeout(runtimeSyncRetryTimer);
|
|
4414
|
+
runtimeSyncRetryTimer = null;
|
|
4415
|
+
}
|
|
4319
4416
|
if (recoveryDelayTimer !== null) {
|
|
4320
4417
|
clearTimeout(recoveryDelayTimer);
|
|
4321
4418
|
recoveryDelayTimer = null;
|
|
@@ -36,8 +36,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
36
36
|
exports.getBlueBubblesRuntimeStatePath = getBlueBubblesRuntimeStatePath;
|
|
37
37
|
exports.readBlueBubblesRuntimeState = readBlueBubblesRuntimeState;
|
|
38
38
|
exports.writeBlueBubblesRuntimeState = writeBlueBubblesRuntimeState;
|
|
39
|
+
exports.touchBlueBubblesRuntimeHeartbeat = touchBlueBubblesRuntimeHeartbeat;
|
|
39
40
|
const fs = __importStar(require("node:fs"));
|
|
40
41
|
const path = __importStar(require("node:path"));
|
|
42
|
+
const atomic_file_1 = require("../../heart/atomic-file");
|
|
41
43
|
const identity_1 = require("../../heart/identity");
|
|
42
44
|
const runtime_1 = require("../../nerves/runtime");
|
|
43
45
|
const DEFAULT_RUNTIME_STATE = {
|
|
@@ -64,6 +66,8 @@ function readBlueBubblesRuntimeState(agentName, agentRoot) {
|
|
|
64
66
|
? parsed.detail
|
|
65
67
|
: DEFAULT_RUNTIME_STATE.detail,
|
|
66
68
|
lastCheckedAt: typeof parsed.lastCheckedAt === "string" ? parsed.lastCheckedAt : undefined,
|
|
69
|
+
lastHeartbeatAt: typeof parsed.lastHeartbeatAt === "string" ? parsed.lastHeartbeatAt : undefined,
|
|
70
|
+
catchUpThrough: typeof parsed.catchUpThrough === "string" ? parsed.catchUpThrough : undefined,
|
|
67
71
|
proofMethod: typeof parsed.proofMethod === "string" && parsed.proofMethod.trim()
|
|
68
72
|
? parsed.proofMethod
|
|
69
73
|
: undefined,
|
|
@@ -102,8 +106,13 @@ function readBlueBubblesRuntimeState(agentName, agentRoot) {
|
|
|
102
106
|
function writeBlueBubblesRuntimeState(agentName, state, agentRoot) {
|
|
103
107
|
const filePath = getBlueBubblesRuntimeStatePath(agentName, agentRoot);
|
|
104
108
|
try {
|
|
105
|
-
|
|
106
|
-
|
|
109
|
+
const catchUpThrough = state.catchUpThrough ?? readBlueBubblesRuntimeState(agentName, agentRoot).catchUpThrough;
|
|
110
|
+
// Replaced whole, so the daemon reading it mid-write never sees half a file.
|
|
111
|
+
(0, atomic_file_1.writeJsonAtomicSync)(filePath, {
|
|
112
|
+
...state,
|
|
113
|
+
...(catchUpThrough === undefined ? {} : { catchUpThrough }),
|
|
114
|
+
lastHeartbeatAt: new Date(Date.now()).toISOString(),
|
|
115
|
+
});
|
|
107
116
|
}
|
|
108
117
|
catch (error) {
|
|
109
118
|
(0, runtime_1.emitNervesEvent)({
|
|
@@ -135,3 +144,9 @@ function writeBlueBubblesRuntimeState(agentName, state, agentRoot) {
|
|
|
135
144
|
});
|
|
136
145
|
return filePath;
|
|
137
146
|
}
|
|
147
|
+
/** Refresh the heartbeat of the state on disk, while a sync that has not written yet is still running. */
|
|
148
|
+
function touchBlueBubblesRuntimeHeartbeat(agentName, agentRoot) {
|
|
149
|
+
if (!fs.existsSync(getBlueBubblesRuntimeStatePath(agentName, agentRoot)))
|
|
150
|
+
return;
|
|
151
|
+
writeBlueBubblesRuntimeState(agentName, readBlueBubblesRuntimeState(agentName, agentRoot), agentRoot);
|
|
152
|
+
}
|
|
@@ -75,7 +75,7 @@ async function deliverOrdinaryOwnerDecision(deps, input) {
|
|
|
75
75
|
const ledger = readLedger(deps.agentRoot);
|
|
76
76
|
const existing = ledger[eventKey(input)];
|
|
77
77
|
if (existing)
|
|
78
|
-
return { status: existing.role === "covered" ? "covered" : "already_sent", effectKey: existing.effectKey };
|
|
78
|
+
return { status: existing.role === "covered" ? "covered" : existing.role === "saved" ? "saved" : "already_sent", effectKey: existing.effectKey };
|
|
79
79
|
const owner = resolveOrdinaryOwner(await deps.listFriends(), deps.ownerUsername === undefined ? (0, friends_1.machineOwnerUsername)() : deps.ownerUsername);
|
|
80
80
|
if (!owner)
|
|
81
81
|
throw new Error("this agent has no single owner to tell: no active family friend is this machine's user, and it has more or fewer than one family friend");
|
|
@@ -83,7 +83,8 @@ async function deliverOrdinaryOwnerDecision(deps, input) {
|
|
|
83
83
|
const routed = await deps.route(owner.id, input.text);
|
|
84
84
|
if (routed.status === "failed")
|
|
85
85
|
throw new Error(`the owner message could not be delivered${routed.detail ? `: ${routed.detail}` : ""}`);
|
|
86
|
-
|
|
86
|
+
const role = routed.status === "deferred" ? "saved" : "sent";
|
|
87
|
+
ledger[eventKey(input)] = { effectKey, role };
|
|
87
88
|
for (const related of input.relatedEvents)
|
|
88
89
|
ledger[eventKey(related)] ??= { effectKey, role: "covered" };
|
|
89
90
|
writeLedger(deps.agentRoot, ledger);
|
|
@@ -93,5 +94,5 @@ async function deliverOrdinaryOwnerDecision(deps, input) {
|
|
|
93
94
|
message: "external-event owner message sent through the agent's own senses",
|
|
94
95
|
meta: { agentName: deps.agentName, source: input.source, eventId: input.eventId, ownerId: owner.id, route: routed.status, related: input.relatedEvents.length },
|
|
95
96
|
});
|
|
96
|
-
return { status:
|
|
97
|
+
return { status: role, effectKey };
|
|
97
98
|
}
|
package/dist/senses/pipeline.js
CHANGED
|
@@ -892,11 +892,16 @@ async function handleInboundTurnExclusive(input) {
|
|
|
892
892
|
? []
|
|
893
893
|
: (input.drainDeferredReturns?.(resolvedContext.friend.id) ?? []);
|
|
894
894
|
const sessionPending = input.drainPending(input.pendingDir);
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
895
|
+
// A deferred return was saved for the friend's next message, whenever that comes, so a
|
|
896
|
+
// sense's freshness window for its own pending never drops it.
|
|
897
|
+
const pending = [
|
|
898
|
+
...deferredReturns,
|
|
899
|
+
...filterDeliverablePendingMessages({
|
|
900
|
+
pendingDir: input.pendingDir,
|
|
901
|
+
channel: input.channel,
|
|
902
|
+
messages: sessionPending,
|
|
903
|
+
}),
|
|
904
|
+
];
|
|
900
905
|
const promotedPendingUserMessages = input.channel === "inner"
|
|
901
906
|
? pending
|
|
902
907
|
.filter((message) => message.from === "ouro-cli" && message.content.trim().length > 0)
|
|
@@ -630,6 +630,11 @@ async function runSenseTurnExclusive(options, owner) {
|
|
|
630
630
|
tenantId: resolverParams.tenantId,
|
|
631
631
|
enforceTrustGate: trust_gate_1.enforceTrustGate,
|
|
632
632
|
drainPending: options.disablePersistence ? () => [] : pending_1.drainPending,
|
|
633
|
+
// A surface saved for a person's next message is picked up on their next
|
|
634
|
+
// Telegram or voice turn too; agent channels (MCP, a2a) never take it.
|
|
635
|
+
...((channel === "telegram" || channel === "voice") && !options.disablePersistence
|
|
636
|
+
? { drainDeferredReturns: (deferredFriendId) => (0, pending_1.drainDeferredReturns)(agentName, deferredFriendId) }
|
|
637
|
+
: {}),
|
|
633
638
|
runAgentOptions: {
|
|
634
639
|
mcpManager,
|
|
635
640
|
...(options.disableTools ? { tools: [], hardDisableTools: true } : {}),
|
|
@@ -187,6 +187,7 @@ async function sendTeamsOffTurn(request, deps) {
|
|
|
187
187
|
text: request.text,
|
|
188
188
|
intent: request.intent ?? "generic_outreach",
|
|
189
189
|
...(request.authorizingSession ? { authorizingSession: request.authorizingSession } : {}),
|
|
190
|
+
...(request.captureReceipt ? { captureReceipt: true } : {}),
|
|
190
191
|
deliveryId: `off-turn:${repeatKey}`,
|
|
191
192
|
origin: request.origin,
|
|
192
193
|
}, { botApi });
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ouro.bot/cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.1397",
|
|
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.
|
|
9
|
+
"version": "0.1.0-alpha.1397",
|
|
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.
|
|
3
|
+
"version": "0.1.0-alpha.1397",
|
|
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": {
|