@animalabs/agent-framework 0.6.10 → 0.7.0
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/dist/src/agent.d.ts +2 -0
- package/dist/src/agent.d.ts.map +1 -1
- package/dist/src/agent.js +3 -0
- package/dist/src/agent.js.map +1 -1
- package/dist/src/framework.d.ts +115 -15
- package/dist/src/framework.d.ts.map +1 -1
- package/dist/src/framework.js +820 -104
- package/dist/src/framework.js.map +1 -1
- package/dist/src/mcpl/channel-registry.d.ts +87 -7
- package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
- package/dist/src/mcpl/channel-registry.js +329 -49
- package/dist/src/mcpl/channel-registry.js.map +1 -1
- package/dist/src/modules/workspace/index.d.ts.map +1 -1
- package/dist/src/modules/workspace/index.js +13 -4
- package/dist/src/modules/workspace/index.js.map +1 -1
- package/dist/src/types/agent.d.ts +17 -0
- package/dist/src/types/agent.d.ts.map +1 -1
- package/dist/src/types/trace.d.ts +32 -0
- package/dist/src/types/trace.d.ts.map +1 -1
- package/dist/test/channel-registry-routing.test.js +186 -10
- package/dist/test/channel-registry-routing.test.js.map +1 -1
- package/dist/test/explicit-prose-routing.test.d.ts +11 -0
- package/dist/test/explicit-prose-routing.test.d.ts.map +1 -0
- package/dist/test/explicit-prose-routing.test.js +247 -0
- package/dist/test/explicit-prose-routing.test.js.map +1 -0
- package/dist/test/present-while-acting.test.js +85 -8
- package/dist/test/present-while-acting.test.js.map +1 -1
- package/dist/test/trunk-channel-routing.test.js +2 -2
- package/dist/test/trunk-channel-routing.test.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +4 -4
- package/src/agent.ts +3 -0
- package/src/framework.ts +881 -107
- package/src/mcpl/channel-registry.ts +401 -54
- package/src/modules/workspace/index.ts +13 -4
- package/src/types/agent.ts +18 -0
- package/src/types/trace.ts +47 -1
package/dist/src/framework.js
CHANGED
|
@@ -57,6 +57,119 @@ function sniffImageMediaType(data) {
|
|
|
57
57
|
const SILENCING_TOOLS = new Set([
|
|
58
58
|
'skip_reply', 'channel_publish', 'send_message', 'reply_message', 'send_dm',
|
|
59
59
|
]);
|
|
60
|
+
/**
|
|
61
|
+
* True when an injected message is real conversational input — something the
|
|
62
|
+
* agent might actually be replying to — rather than ambient machinery.
|
|
63
|
+
* System markers (`system: true` — send-failed notices, routing notices) and
|
|
64
|
+
* reactions (`chat:reaction` tag, MCPL RFC-001) don't count: they must not
|
|
65
|
+
* clear explicit-send suppression, and they never influence routing.
|
|
66
|
+
*/
|
|
67
|
+
const isConversationalInjection = (metadata) => {
|
|
68
|
+
if (!metadata)
|
|
69
|
+
return true;
|
|
70
|
+
const m = metadata;
|
|
71
|
+
if (m.system === true)
|
|
72
|
+
return false;
|
|
73
|
+
if (Array.isArray(m.tags) && m.tags.includes('chat:reaction'))
|
|
74
|
+
return false;
|
|
75
|
+
return true;
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Explicit delivery tools whose successful use into a closed channel OPENS
|
|
79
|
+
* it (send implies engagement — see openIfClosedForSend). Bare tool names,
|
|
80
|
+
* matched after stripping the MCPL server prefix.
|
|
81
|
+
*/
|
|
82
|
+
const SEND_ENGAGEMENT_TOOLS = new Set([
|
|
83
|
+
'send_message', 'reply_message', 'send_dm', 'send_file', 'send_files',
|
|
84
|
+
]);
|
|
85
|
+
/**
|
|
86
|
+
* Best-effort extraction of the delivered channel id from an MCPL send-tool
|
|
87
|
+
* result (the discord-mcpl send tools return JSON like
|
|
88
|
+
* `{"messageId":"…","channelId":"…"}` as a text block). Returns undefined on
|
|
89
|
+
* any shape mismatch — the caller falls back to the tool's input args.
|
|
90
|
+
*/
|
|
91
|
+
function extractChannelIdFromToolResult(content) {
|
|
92
|
+
const text = content?.find((c) => c.type === 'text' && c.text)?.text;
|
|
93
|
+
if (!text)
|
|
94
|
+
return undefined;
|
|
95
|
+
try {
|
|
96
|
+
const parsed = JSON.parse(text);
|
|
97
|
+
return typeof parsed.channelId === 'string' && parsed.channelId.length > 0
|
|
98
|
+
? parsed.channelId
|
|
99
|
+
: undefined;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* True when an incoming channel message explicitly addressed the agent.
|
|
107
|
+
* Primary signal is the MCPL RFC-001 `chat:addressed` tag (mention / reply /
|
|
108
|
+
* DM, as classified by the server); the metadata booleans are the fallback
|
|
109
|
+
* for servers that predate tags. Addressed messages outrank ambient chatter
|
|
110
|
+
* when picking a turn's frozen speech locus.
|
|
111
|
+
*/
|
|
112
|
+
const isAddressedMessage = (tags, _metadata) => Array.isArray(tags) && tags.includes('chat:addressed');
|
|
113
|
+
/**
|
|
114
|
+
* Parse a prose segment's routing prefix (explicit prose routing —
|
|
115
|
+
* docs/explicit-prose-routing.md). The FIRST line may be:
|
|
116
|
+
* `>>target [!] [body…]` — target = channel spec or `private`
|
|
117
|
+
* The ` !` continuation modifier must immediately follow the target,
|
|
118
|
+
* whitespace-separated. Body may start on the same line or the next.
|
|
119
|
+
*/
|
|
120
|
+
function parseProsePrefix(text) {
|
|
121
|
+
const m = /^>>(\S+)([ \t]+!)?[ \t]*\n?/.exec(text);
|
|
122
|
+
if (!m)
|
|
123
|
+
return { kind: 'none', continueTurn: false, body: text };
|
|
124
|
+
const target = m[1];
|
|
125
|
+
const continueTurn = m[2] !== undefined;
|
|
126
|
+
const body = text.slice(m[0].length);
|
|
127
|
+
// `skip_reply` mirrors the tool the model already knows: text stays in
|
|
128
|
+
// context, nothing is delivered. (Deliberately NOT called "private"/"note" —
|
|
129
|
+
// that vocabulary sat adjacent to signed thinking in a live window and drew
|
|
130
|
+
// a reasoning_extraction classifier hit, 2026-07-24 Fable.)
|
|
131
|
+
if (target === 'skip_reply') {
|
|
132
|
+
return { kind: 'private', continueTurn, body };
|
|
133
|
+
}
|
|
134
|
+
return { kind: 'target', target, continueTurn, body };
|
|
135
|
+
}
|
|
136
|
+
/** One-time primer appended when an agent's proseRouting mode changes. */
|
|
137
|
+
function proseModePrimer(mode) {
|
|
138
|
+
if (mode === 'locus') {
|
|
139
|
+
return '[prose-routing] Mode change: your plain text auto-routes to the ' +
|
|
140
|
+
'conversational locus again. `>>` destination prefixes are no longer needed.';
|
|
141
|
+
}
|
|
142
|
+
// Deliberately terse: a short event-style notice is classifier-safe from
|
|
143
|
+
// the user role (ablation D, 2026-07-24), while the full grammar as a user
|
|
144
|
+
// message drew a deterministic reasoning_extraction refusal (ablation A/B).
|
|
145
|
+
// The grammar is TAUGHT BY BOUNCE: the first undelivered text produces a
|
|
146
|
+
// notice with the exact resend syntax, and the full reference is available
|
|
147
|
+
// on demand via the prose_help tool (a tool RESULT is model-requested
|
|
148
|
+
// content — the safest role there is). Nothing is injected into the system
|
|
149
|
+
// prompt: those bytes belong to the recipe, and the deepest KV prefix must
|
|
150
|
+
// not vary with framework code.
|
|
151
|
+
return ('[prose-routing] Output mode changed: plain text is delivered only with a ' +
|
|
152
|
+
'destination prefix line, e.g. ">>#channel-name your text". ' +
|
|
153
|
+
'The prose_help tool shows the full syntax.');
|
|
154
|
+
}
|
|
155
|
+
/** Full `>>` routing reference, served as the prose_help TOOL RESULT (never
|
|
156
|
+
* injected ambiently — see proseModePrimer note). */
|
|
157
|
+
const PROSE_ROUTING_HELP = 'Plain-text output routing (explicit mode):\n' +
|
|
158
|
+
' >>#channel-name … or >>@person … (DM) or >>service:guild:id …\n' +
|
|
159
|
+
' One message may hold several sections: each line starting with ">>" begins\n' +
|
|
160
|
+
' a new envelope, routed to its own destination independently.\n' +
|
|
161
|
+
' The first destination in a turn applies to the rest of that turn.\n' +
|
|
162
|
+
' Append " !" after the destination (e.g. ">>#ops !") to start your next turn\n' +
|
|
163
|
+
' immediately when this one ends, instead of pausing until the next event.\n' +
|
|
164
|
+
' >>skip_reply — text stays in your context only, like the skip_reply tool.\n' +
|
|
165
|
+
'Text without a destination is not delivered: it is retained, and a notice will\n' +
|
|
166
|
+
'prompt you to resend — reply e.g. ">>#channel {{unsent}}" to deliver the retained\n' +
|
|
167
|
+
'text unchanged. Send tools (send_message, send_dm, …) are unaffected.';
|
|
168
|
+
const PROSE_HELP_TOOL = {
|
|
169
|
+
name: 'prose_help',
|
|
170
|
+
description: 'Show the plain-text output routing syntax (destination prefixes, resend token, skip).',
|
|
171
|
+
inputSchema: { type: 'object', properties: {} },
|
|
172
|
+
};
|
|
60
173
|
/** Strip the `server--` MCPL prefix from a tool name. */
|
|
61
174
|
const bareToolName = (n) => n.split('--').pop();
|
|
62
175
|
import { CheckpointManager } from './mcpl/checkpoint-manager.js';
|
|
@@ -209,20 +322,37 @@ export class AgentFramework {
|
|
|
209
322
|
processLoggingPersist;
|
|
210
323
|
processLoggingBroadcast;
|
|
211
324
|
activeStreams = new Map();
|
|
212
|
-
/** Per-agent output locus
|
|
213
|
-
*
|
|
214
|
-
*
|
|
215
|
-
*
|
|
216
|
-
*
|
|
217
|
-
*
|
|
218
|
-
*
|
|
325
|
+
/** Per-agent output locus FROZEN for the CURRENT logical turn. Resolved
|
|
326
|
+
* eagerly in startAgentStream (home → addressed trigger → global default)
|
|
327
|
+
* and never moved until the next turn: mid-turn injected messages — ambient
|
|
328
|
+
* chatter, reactions, system markers — must not hijack where the agent's
|
|
329
|
+
* plain prose lands (2026-07-21 Cairn lounge misroute). Lives here — not in
|
|
330
|
+
* driveStream locals — so the pin survives a context-budget stream restart,
|
|
331
|
+
* which continues the same logical turn in a fresh driveStream. Cleared or
|
|
332
|
+
* re-set at the start of every non-restart turn. */
|
|
219
333
|
turnLocusPins = new Map();
|
|
220
|
-
/** A tool boundary injected fresh
|
|
221
|
-
*
|
|
222
|
-
* explicit-send suppression before handling
|
|
223
|
-
*
|
|
224
|
-
|
|
225
|
-
|
|
334
|
+
/** A tool boundary injected fresh CONVERSATIONAL input (a real message —
|
|
335
|
+
* not a reaction or a system marker) into the live stream. Tells
|
|
336
|
+
* driveStream to clear sticky explicit-send suppression before handling
|
|
337
|
+
* the next model round. Never affects routing: the turn locus is frozen. */
|
|
338
|
+
midTurnInputSignals = new Set();
|
|
339
|
+
/** Last outbound locus announced to each agent as a durable `[routing]`
|
|
340
|
+
* window message. Announce-on-change only: steady state emits nothing
|
|
341
|
+
* (KV-safe, no per-turn chatter). In-memory — after a process restart the
|
|
342
|
+
* first turn's locus is announced once to re-establish the baseline. */
|
|
343
|
+
lastAnnouncedLocus = new Map();
|
|
344
|
+
// ---- Explicit prose routing (docs/explicit-prose-routing.md) ----------
|
|
345
|
+
/** Latest bounced (undelivered) prose per agent — the `{{unsent}}` source. */
|
|
346
|
+
proseClipboards = new Map();
|
|
347
|
+
/** Sticky per-TURN delivery target set by the turn's first `>>` prefix.
|
|
348
|
+
* Cleared at every non-restart turn start; survives context restarts. */
|
|
349
|
+
proseTargetPins = new Map();
|
|
350
|
+
/** Agents whose current turn requested `!` continuation — re-woken when the
|
|
351
|
+
* turn completes instead of pausing until the next external event. */
|
|
352
|
+
proseContinuations = new Set();
|
|
353
|
+
/** Consecutive bounce-wakes per agent; capped so an agent that keeps
|
|
354
|
+
* emitting unprefixed prose can't wake-loop (notices still append). */
|
|
355
|
+
proseBounceStreaks = new Map();
|
|
226
356
|
pendingAssistantBlocks = new Map();
|
|
227
357
|
/** Streams the FRAMEWORK cancelled for non-terminal reasons, keyed
|
|
228
358
|
* `${agentName}:${streamId}`: an endTurn tool result or a context-budget
|
|
@@ -988,20 +1118,48 @@ export class AgentFramework {
|
|
|
988
1118
|
throw new Error(`Unknown agent: ${agentName}`);
|
|
989
1119
|
return agent.getRuntimeSettings();
|
|
990
1120
|
}
|
|
991
|
-
|
|
1121
|
+
/**
|
|
1122
|
+
* Apply runtime settings.
|
|
1123
|
+
*
|
|
1124
|
+
* `opts.persist: false` makes the change EPHEMERAL: it takes effect live but
|
|
1125
|
+
* is not written to the `framework/state` slot, so a restart reverts it. That
|
|
1126
|
+
* is the mode for operator experiments ("change it, watch, revert") — the
|
|
1127
|
+
* default persists, because a durable operational change should survive a
|
|
1128
|
+
* bounce like every other override.
|
|
1129
|
+
*
|
|
1130
|
+
* Nothing here notifies the agent. Discovery is deliberately PULL: the agent
|
|
1131
|
+
* can read current settings any time via the `agent_settings` tool's `get`
|
|
1132
|
+
* action, which costs no context perturbation. Pushing a notice injects text
|
|
1133
|
+
* into the very context being tuned — it invalidates the KV prefix and can
|
|
1134
|
+
* itself trip a classifier — so callers opt into that explicitly rather than
|
|
1135
|
+
* getting it by default.
|
|
1136
|
+
*
|
|
1137
|
+
* KNOWN LIMITATION of `persist: false`: the change still lands in the agent's
|
|
1138
|
+
* in-memory override map, and `persistAgentRuntimeSettings` writes that whole
|
|
1139
|
+
* map. So a LATER persisting call promotes any still-live ephemeral change to
|
|
1140
|
+
* durable as a side effect. Ephemeral means "not written by THIS call", not
|
|
1141
|
+
* "can never be written". Reset the ephemeral key before persisting something
|
|
1142
|
+
* else if that matters. Making it airtight needs per-key ephemeral tracking
|
|
1143
|
+
* inside Agent.
|
|
1144
|
+
*/
|
|
1145
|
+
updateAgentRuntimeSettings(agentName, patch, opts) {
|
|
992
1146
|
const agent = this.agents.get(agentName);
|
|
993
1147
|
if (!agent)
|
|
994
1148
|
throw new Error(`Unknown agent: ${agentName}`);
|
|
995
1149
|
const result = agent.updateRuntimeSettings(patch);
|
|
996
|
-
|
|
1150
|
+
if (opts?.persist !== false) {
|
|
1151
|
+
this.persistAgentRuntimeSettings(agentName, agent.getRuntimeSettingsOverrides());
|
|
1152
|
+
}
|
|
997
1153
|
return result;
|
|
998
1154
|
}
|
|
999
|
-
resetAgentRuntimeSettings(agentName, keys) {
|
|
1155
|
+
resetAgentRuntimeSettings(agentName, keys, opts) {
|
|
1000
1156
|
const agent = this.agents.get(agentName);
|
|
1001
1157
|
if (!agent)
|
|
1002
1158
|
throw new Error(`Unknown agent: ${agentName}`);
|
|
1003
1159
|
const result = agent.resetRuntimeSettings(keys);
|
|
1004
|
-
|
|
1160
|
+
if (opts?.persist !== false) {
|
|
1161
|
+
this.persistAgentRuntimeSettings(agentName, agent.getRuntimeSettingsOverrides());
|
|
1162
|
+
}
|
|
1005
1163
|
return result;
|
|
1006
1164
|
}
|
|
1007
1165
|
cancelAgentRuntimeSettingsTransition(agentName) {
|
|
@@ -1064,10 +1222,14 @@ export class AgentFramework {
|
|
|
1064
1222
|
throw new Error(`Agent not found: ${agentName}`);
|
|
1065
1223
|
}
|
|
1066
1224
|
const tools = this.getToolsForAgent(agentName).filter((t) => agent.canUseTool(t.name));
|
|
1225
|
+
// An explicit budget compiles against a HYPOTHETICAL window instead of the
|
|
1226
|
+
// agent's live one. That also suppresses transition-settling in
|
|
1227
|
+
// compileWithInjections (which only settles when no budget is passed), so
|
|
1228
|
+
// previewing a smaller window cannot advance a converging descent.
|
|
1067
1229
|
// Default: no dynamic injection gathering → fully transparent (no
|
|
1068
1230
|
// inference, no Chronicle writes, no external RPC). Opt in explicitly.
|
|
1069
1231
|
if (!opts?.injections) {
|
|
1070
|
-
return agent.buildActivationRequest(tools, undefined);
|
|
1232
|
+
return agent.buildActivationRequest(tools, undefined, opts?.budget);
|
|
1071
1233
|
}
|
|
1072
1234
|
// Full-fidelity path: mirrors startAgentStream's injection gathering.
|
|
1073
1235
|
// NOT transparent — see the doc comment above.
|
|
@@ -1097,7 +1259,31 @@ export class AgentFramework {
|
|
|
1097
1259
|
console.error('beforeInference hook error (preview):', error);
|
|
1098
1260
|
}
|
|
1099
1261
|
}
|
|
1100
|
-
return agent.buildActivationRequest(tools, injections);
|
|
1262
|
+
return agent.buildActivationRequest(tools, injections, opts?.budget);
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* Non-committing preview of the FOLD PLAN at a hypothetical budget and/or
|
|
1266
|
+
* context settings — the numbers behind an operator's "what happens if I set
|
|
1267
|
+
* the budget to X" before they apply it.
|
|
1268
|
+
*
|
|
1269
|
+
* Unlike `previewActivation` (which renders a request), this returns the
|
|
1270
|
+
* picker's plan: resulting tokens, whether it fits, how many summaries would
|
|
1271
|
+
* have to be produced first, and the per-chunk fold levels. Commits nothing:
|
|
1272
|
+
* no resolution persistence, no compression enqueue, no transition
|
|
1273
|
+
* bookkeeping — see `AutobiographicalStrategy.previewContext`.
|
|
1274
|
+
*
|
|
1275
|
+
* Returns null when the agent's strategy has no fold plan (non-adaptive).
|
|
1276
|
+
*/
|
|
1277
|
+
previewContextSettings(agentName, budgetTokens, overrides) {
|
|
1278
|
+
const agent = this.agents.get(agentName);
|
|
1279
|
+
if (!agent)
|
|
1280
|
+
throw new Error(`Unknown agent: ${agentName}`);
|
|
1281
|
+
const cm = agent.getContextManager();
|
|
1282
|
+
if (typeof cm.previewContext !== 'function')
|
|
1283
|
+
return null;
|
|
1284
|
+
// reserveForResponse mirrors the live compile so the previewed middle is
|
|
1285
|
+
// comparable to what the agent actually gets.
|
|
1286
|
+
return cm.previewContext({ maxTokens: budgetTokens, reserveForResponse: agent.maxTokens }, overrides);
|
|
1101
1287
|
}
|
|
1102
1288
|
/**
|
|
1103
1289
|
* Check if process logging is enabled.
|
|
@@ -2691,20 +2877,17 @@ export class AgentFramework {
|
|
|
2691
2877
|
}
|
|
2692
2878
|
}
|
|
2693
2879
|
}
|
|
2694
|
-
// A newly injected message begins a new
|
|
2695
|
-
// the same provider inference. Remember
|
|
2696
|
-
// driveStream: an explicit send in the preceding
|
|
2697
|
-
// silence the reply
|
|
2698
|
-
//
|
|
2699
|
-
//
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
: latest;
|
|
2706
|
-
}, null);
|
|
2707
|
-
this.midTurnRoutingResets.set(agent.name, injectedChannelId);
|
|
2880
|
+
// A newly injected CONVERSATIONAL message begins a new
|
|
2881
|
+
// conversational round inside the same provider inference. Remember
|
|
2882
|
+
// that boundary for driveStream: an explicit send in the preceding
|
|
2883
|
+
// round must not silence the reply. Routing is deliberately NOT
|
|
2884
|
+
// affected — the turn locus is frozen at turn start, so ambient
|
|
2885
|
+
// chatter, reactions, and system markers injected mid-turn can no
|
|
2886
|
+
// longer hijack where the agent's prose lands. Non-conversational
|
|
2887
|
+
// injections (reactions, `system: true` markers) don't even clear
|
|
2888
|
+
// the send suppression: nothing new was said to the agent.
|
|
2889
|
+
if (midTurnInjections.some((inj) => isConversationalInjection(inj.metadata))) {
|
|
2890
|
+
this.midTurnInputSignals.add(agent.name);
|
|
2708
2891
|
}
|
|
2709
2892
|
// Check if any tool result requested endTurn
|
|
2710
2893
|
const shouldEndTurn = currentState.toolResults.some(tc => tc.result.endTurn);
|
|
@@ -2890,6 +3073,8 @@ export class AgentFramework {
|
|
|
2890
3073
|
};
|
|
2891
3074
|
if (event.threadId)
|
|
2892
3075
|
metadata.threadId = event.threadId;
|
|
3076
|
+
if (event.tags)
|
|
3077
|
+
metadata.tags = event.tags;
|
|
2893
3078
|
// Per-channel conversation routing: messages go to the channel's fork
|
|
2894
3079
|
// agent (spawned from the template on first qualifying message), never
|
|
2895
3080
|
// to the primary conversation.
|
|
@@ -2900,6 +3085,7 @@ export class AgentFramework {
|
|
|
2900
3085
|
const id = this.addMessage('user', event.content, metadata);
|
|
2901
3086
|
this.emitTrace({ type: 'message:added', messageId: id, source: 'mcpl:channel-incoming' });
|
|
2902
3087
|
if (event.triggerInference) {
|
|
3088
|
+
const addressed = isAddressedMessage(event.tags, event.metadata);
|
|
2903
3089
|
for (const agentName of this.agents.keys()) {
|
|
2904
3090
|
this.pendingRequests.push({
|
|
2905
3091
|
agentName,
|
|
@@ -2909,6 +3095,9 @@ export class AgentFramework {
|
|
|
2909
3095
|
// Route this turn's auto-published speech back to THIS channel, not
|
|
2910
3096
|
// the global most-recent-inbound locus (item-3 redux, trunk agents).
|
|
2911
3097
|
channelId: event.channelId,
|
|
3098
|
+
// Addressed messages outrank ambient chatter when a batched wake
|
|
3099
|
+
// picks the turn's frozen speech locus.
|
|
3100
|
+
addressed,
|
|
2912
3101
|
});
|
|
2913
3102
|
}
|
|
2914
3103
|
}
|
|
@@ -2990,6 +3179,7 @@ export class AgentFramework {
|
|
|
2990
3179
|
// A fork's home channel wins in routeSpeech regardless, but carry the
|
|
2991
3180
|
// triggering channel too so the trunk/active path stays consistent.
|
|
2992
3181
|
channelId: event.channelId,
|
|
3182
|
+
addressed: isAddressedMessage(event.tags, event.metadata),
|
|
2993
3183
|
});
|
|
2994
3184
|
}
|
|
2995
3185
|
}
|
|
@@ -3145,7 +3335,7 @@ export class AgentFramework {
|
|
|
3145
3335
|
handleMcplPushEvent(event) {
|
|
3146
3336
|
const triggerChannel = this.derivePushEventChannel(event.origin);
|
|
3147
3337
|
if (triggerChannel && this.channelRegistry) {
|
|
3148
|
-
this.channelRegistry.ensureChannelRegistered(event.serverId, triggerChannel.channelId, triggerChannel.label);
|
|
3338
|
+
this.channelRegistry.ensureChannelRegistered(event.serverId, triggerChannel.channelId, triggerChannel.label, triggerChannel.metadata);
|
|
3149
3339
|
}
|
|
3150
3340
|
const metadata = {
|
|
3151
3341
|
...event.origin,
|
|
@@ -3153,7 +3343,17 @@ export class AgentFramework {
|
|
|
3153
3343
|
featureSet: event.featureSet,
|
|
3154
3344
|
eventId: event.eventId,
|
|
3155
3345
|
triggered: event.triggerInference ?? false,
|
|
3346
|
+
...(event.tags ? { tags: event.tags } : {}),
|
|
3156
3347
|
};
|
|
3348
|
+
// `origin.channelId` is the server-internal raw id (a bare Discord
|
|
3349
|
+
// snowflake) — unroutable as a locus and unresolvable by the agent. Store
|
|
3350
|
+
// the composite MCPL id instead wherever we can derive it, so anything
|
|
3351
|
+
// downstream that reads `metadata.channelId` (routing, provenance, the
|
|
3352
|
+
// agent itself) sees the qualified form. The raw value stays available on
|
|
3353
|
+
// servers that also send `rawChannelId`-style origin fields.
|
|
3354
|
+
if (triggerChannel) {
|
|
3355
|
+
metadata.channelId = triggerChannel.channelId;
|
|
3356
|
+
}
|
|
3157
3357
|
const content = [...event.content];
|
|
3158
3358
|
const addressedWhileClosed = triggerChannel &&
|
|
3159
3359
|
event.tags?.includes('chat:addressed') &&
|
|
@@ -3207,6 +3407,10 @@ export class AgentFramework {
|
|
|
3207
3407
|
source: event.serverId,
|
|
3208
3408
|
timestamp: Date.now(),
|
|
3209
3409
|
channelId: triggerChannel?.channelId,
|
|
3410
|
+
// DMs and addressed-while-closed messages arrive as push events;
|
|
3411
|
+
// they must outrank ambient chatter in a batched wake's locus
|
|
3412
|
+
// selection just like their channels/incoming counterparts.
|
|
3413
|
+
addressed: isAddressedMessage(event.tags, event.origin),
|
|
3210
3414
|
});
|
|
3211
3415
|
}
|
|
3212
3416
|
}
|
|
@@ -3230,16 +3434,35 @@ export class AgentFramework {
|
|
|
3230
3434
|
derivePushEventChannel(origin) {
|
|
3231
3435
|
if (!origin)
|
|
3232
3436
|
return undefined;
|
|
3233
|
-
|
|
3437
|
+
let label = typeof origin.channelName === 'string' && origin.channelName ? origin.channelName : undefined;
|
|
3438
|
+
let metadata;
|
|
3439
|
+
// A DM has no channelName — label it by the PERSON and carry their
|
|
3440
|
+
// identity, so DM registrations are people-first (`DM: antra`, matchable
|
|
3441
|
+
// by `>>@name` / `<@id>` mention tokens) instead of bare snowflakes.
|
|
3442
|
+
const isDM = origin.isDM === true || origin.guildId === null;
|
|
3443
|
+
if (isDM && typeof origin.authorName === 'string' && origin.authorName) {
|
|
3444
|
+
label = label ?? `DM: ${origin.authorName}`;
|
|
3445
|
+
metadata = {
|
|
3446
|
+
channelType: 'dm',
|
|
3447
|
+
recipientName: origin.authorName,
|
|
3448
|
+
...(typeof origin.authorId === 'string' && origin.authorId
|
|
3449
|
+
? { recipientId: origin.authorId }
|
|
3450
|
+
: {}),
|
|
3451
|
+
};
|
|
3452
|
+
}
|
|
3234
3453
|
const explicit = origin.mcplChannelId;
|
|
3235
3454
|
if (typeof explicit === 'string' && explicit) {
|
|
3236
|
-
return { channelId: explicit, label };
|
|
3455
|
+
return { channelId: explicit, ...(label ? { label } : {}), ...(metadata ? { metadata } : {}) };
|
|
3237
3456
|
}
|
|
3238
3457
|
// Discord fallback: reconstruct the composite from origin parts. `guildId`
|
|
3239
3458
|
// is null for a DM (→ 'dm'); a real guild id for a non-open guild channel.
|
|
3240
3459
|
if (origin.source === 'discord' && typeof origin.channelId === 'string' && origin.channelId) {
|
|
3241
3460
|
const guild = typeof origin.guildId === 'string' && origin.guildId ? origin.guildId : 'dm';
|
|
3242
|
-
return {
|
|
3461
|
+
return {
|
|
3462
|
+
channelId: `discord:${guild}:${origin.channelId}`,
|
|
3463
|
+
...(label ? { label } : {}),
|
|
3464
|
+
...(metadata ? { metadata } : {}),
|
|
3465
|
+
};
|
|
3243
3466
|
}
|
|
3244
3467
|
return undefined;
|
|
3245
3468
|
}
|
|
@@ -3312,14 +3535,287 @@ export class AgentFramework {
|
|
|
3312
3535
|
const trigger = requests[0];
|
|
3313
3536
|
// Route this turn's auto-published speech to the channel that triggered
|
|
3314
3537
|
// it (item-3 redux). A batched wake may carry several triggering channels
|
|
3315
|
-
// (messages arrived in >1 channel while the agent was busy/idle)
|
|
3316
|
-
//
|
|
3317
|
-
//
|
|
3318
|
-
//
|
|
3319
|
-
//
|
|
3320
|
-
//
|
|
3321
|
-
|
|
3322
|
-
|
|
3538
|
+
// (messages arrived in >1 channel while the agent was busy/idle):
|
|
3539
|
+
// 1. the most recent ADDRESSED channel wins (mention / reply / DM —
|
|
3540
|
+
// someone explicitly spoke TO the agent);
|
|
3541
|
+
// 2. else the most recent channel-bearing request (ambient message in
|
|
3542
|
+
// an open channel — legacy last-inbound semantics).
|
|
3543
|
+
// Ambient chatter must not outrank an addressed message just by being
|
|
3544
|
+
// newest (2026-07-21 Cairn lounge misroute, turn-start variant).
|
|
3545
|
+
// Non-channel wakes (heartbeats, module events, reactions — which never
|
|
3546
|
+
// carry channelId) leave both undefined → global fallback.
|
|
3547
|
+
let ambientChannel;
|
|
3548
|
+
let addressedChannel;
|
|
3549
|
+
for (const r of requests) {
|
|
3550
|
+
if (!r.channelId)
|
|
3551
|
+
continue;
|
|
3552
|
+
ambientChannel = r.channelId;
|
|
3553
|
+
if (r.addressed)
|
|
3554
|
+
addressedChannel = r.channelId;
|
|
3555
|
+
}
|
|
3556
|
+
const triggerChannel = addressedChannel ?? ambientChannel;
|
|
3557
|
+
const triggerAddressed = addressedChannel !== undefined;
|
|
3558
|
+
await this.startAgentStream(agent, {
|
|
3559
|
+
...trigger,
|
|
3560
|
+
channelId: triggerChannel,
|
|
3561
|
+
addressed: triggerAddressed,
|
|
3562
|
+
});
|
|
3563
|
+
}
|
|
3564
|
+
}
|
|
3565
|
+
/**
|
|
3566
|
+
* Announce-on-change locus notice (turn-frozen routing). Appends a durable
|
|
3567
|
+
* `[routing]` window message when the turn's effective outbound locus
|
|
3568
|
+
* differs from the last one announced — the agent must never have to guess
|
|
3569
|
+
* where its plain prose lands. Durable append (never retracted) keeps the
|
|
3570
|
+
* KV prefix stable; change-only keeps it out of steady-state turns. The
|
|
3571
|
+
* first resolution after boot announces only a non-null locus ("prose has
|
|
3572
|
+
* no destination" is the unremarkable boot default). Never triggers
|
|
3573
|
+
* inference; never locus-eligible itself (system + no channel metadata).
|
|
3574
|
+
*/
|
|
3575
|
+
announceLocusIfChanged(agentName, locus) {
|
|
3576
|
+
const hasBaseline = this.lastAnnouncedLocus.has(agentName);
|
|
3577
|
+
const prev = this.lastAnnouncedLocus.get(agentName) ?? null;
|
|
3578
|
+
if (hasBaseline ? prev === locus : locus === null) {
|
|
3579
|
+
if (!hasBaseline)
|
|
3580
|
+
this.lastAnnouncedLocus.set(agentName, locus);
|
|
3581
|
+
return;
|
|
3582
|
+
}
|
|
3583
|
+
this.lastAnnouncedLocus.set(agentName, locus);
|
|
3584
|
+
const agent = this.agents.get(agentName);
|
|
3585
|
+
if (!agent)
|
|
3586
|
+
return;
|
|
3587
|
+
let text;
|
|
3588
|
+
if (locus === null) {
|
|
3589
|
+
text =
|
|
3590
|
+
'[routing] Your plain speech currently has no channel — it stays in ' +
|
|
3591
|
+
'your archive. Use an explicit send tool to reach a channel.';
|
|
3592
|
+
}
|
|
3593
|
+
else {
|
|
3594
|
+
const label = this.channelRegistry?.getDescriptor(locus)?.label;
|
|
3595
|
+
const shown = label && label !== locus
|
|
3596
|
+
? `${label.startsWith('#') ? label : `#${label}`} (${locus})`
|
|
3597
|
+
: locus;
|
|
3598
|
+
text =
|
|
3599
|
+
`[routing] Your plain speech now lands in ${shown}. ` +
|
|
3600
|
+
'Other channels need an explicit send tool.';
|
|
3601
|
+
}
|
|
3602
|
+
try {
|
|
3603
|
+
const id = agent.getContextManager().addMessage('user', [{ type: 'text', text }], { system: true, kind: 'routing-notice' });
|
|
3604
|
+
this.emitTrace({ type: 'message:added', messageId: id, source: 'routing-notice' });
|
|
3605
|
+
console.error(`[routing] ${agentName}: locus ${prev ?? '(none)'} -> ${locus ?? '(none)'} (announced in window)`);
|
|
3606
|
+
}
|
|
3607
|
+
catch (err) {
|
|
3608
|
+
console.error('announceLocusIfChanged: failed to record routing notice:', err);
|
|
3609
|
+
}
|
|
3610
|
+
}
|
|
3611
|
+
/**
|
|
3612
|
+
* Durable window notice for a channel the agent did not ask to open —
|
|
3613
|
+
* subscription-policy admission, or an open forced by the agent's own
|
|
3614
|
+
* delivery into a closed channel. The agent must always learn that new
|
|
3615
|
+
* traffic will start flowing, and that `channel_close` opts out (their
|
|
3616
|
+
* decision outranks policy). System message: never triggers inference,
|
|
3617
|
+
* never conversational, never locus-eligible.
|
|
3618
|
+
*/
|
|
3619
|
+
recordChannelAutoOpenNotice(agentName, channels, cause) {
|
|
3620
|
+
if (channels.length === 0)
|
|
3621
|
+
return;
|
|
3622
|
+
const shown = channels
|
|
3623
|
+
.map((c) => (c.label && c.label !== c.channelId ? `${c.label} (${c.channelId})` : c.channelId))
|
|
3624
|
+
.join(', ');
|
|
3625
|
+
const plural = channels.length > 1;
|
|
3626
|
+
const causeText = cause === 'subscription-policy'
|
|
3627
|
+
? 'your subscription policy just admitted ' + (plural ? 'them' : 'it')
|
|
3628
|
+
: 'your own message into the closed channel engaged it';
|
|
3629
|
+
const text = `[channels] Now open: ${shown} — ${causeText}. Ongoing traffic from ` +
|
|
3630
|
+
(plural ? 'these channels' : 'this channel') +
|
|
3631
|
+
` will reach you. If you don't want ${plural ? 'one of them' : 'it'}, use channel_close — ` +
|
|
3632
|
+
'your choice sticks; neither policy nor a later send will silently reopen it.';
|
|
3633
|
+
try {
|
|
3634
|
+
// Through framework.addMessage for mid-turn safety (deferral +
|
|
3635
|
+
// hear-while-acting injection) — a delivery-forced open happens inside
|
|
3636
|
+
// a live turn, and a direct context-manager append there would store
|
|
3637
|
+
// the notice out of order. Targets the primary agent; connectome-host
|
|
3638
|
+
// runs trunk-only, so this is the delivering agent in practice.
|
|
3639
|
+
this.addMessage('user', [{ type: 'text', text }], { system: true, kind: 'channel-notice' });
|
|
3640
|
+
console.error(`[channel] auto-open notice (${cause}) -> ${agentName ?? 'primary'}: ${shown}`);
|
|
3641
|
+
}
|
|
3642
|
+
catch (err) {
|
|
3643
|
+
console.error('recordChannelAutoOpenNotice failed:', err);
|
|
3644
|
+
}
|
|
3645
|
+
}
|
|
3646
|
+
/**
|
|
3647
|
+
* Explicit-prose-routing delivery gateway (docs/explicit-prose-routing.md).
|
|
3648
|
+
* Every prose segment of an `explicit`-mode agent flows through here:
|
|
3649
|
+
* parse the `>>` prefix, resolve the target, deliver — or bounce to the
|
|
3650
|
+
* clipboard with a resend notice. Misdelivery is structurally impossible:
|
|
3651
|
+
* nothing is ever sent to a destination the model did not name (directly
|
|
3652
|
+
* or via the turn's sticky target).
|
|
3653
|
+
*/
|
|
3654
|
+
async deliverProse(agent, rawText) {
|
|
3655
|
+
// Multi-envelope: a single prose block may address SEVERAL destinations —
|
|
3656
|
+
// every line beginning with `>>` opens a new envelope, routed
|
|
3657
|
+
// independently (first live use: Tilde 2026-07-24, one block carrying a
|
|
3658
|
+
// letter to #tilde-mythos AND a `>>#tilde` aside; the single-envelope
|
|
3659
|
+
// parser delivered the aside literally into the first destination —
|
|
3660
|
+
// exactly the leak class this mode exists to kill). Text before the
|
|
3661
|
+
// first `>>` is its own unprefixed envelope (sticky/bounce as usual).
|
|
3662
|
+
const lines = rawText.split('\n');
|
|
3663
|
+
const envelopes = [];
|
|
3664
|
+
let current = [];
|
|
3665
|
+
for (const line of lines) {
|
|
3666
|
+
// Only a REAL prefix line opens an envelope: `>>` immediately followed
|
|
3667
|
+
// by a target token. A quoted `>> arrow` (space after) stays body text.
|
|
3668
|
+
if (/^>>\S/.test(line.trimStart()) && current.length > 0) {
|
|
3669
|
+
envelopes.push(current.join('\n'));
|
|
3670
|
+
current = [];
|
|
3671
|
+
}
|
|
3672
|
+
current.push(line);
|
|
3673
|
+
}
|
|
3674
|
+
if (current.length > 0)
|
|
3675
|
+
envelopes.push(current.join('\n'));
|
|
3676
|
+
for (const envelope of envelopes) {
|
|
3677
|
+
if (!envelope.trim())
|
|
3678
|
+
continue;
|
|
3679
|
+
await this.deliverProseEnvelope(agent, envelope.replace(/^\s+(?=>>)/, ''));
|
|
3680
|
+
}
|
|
3681
|
+
}
|
|
3682
|
+
async deliverProseEnvelope(agent, rawText) {
|
|
3683
|
+
const name = agent.name;
|
|
3684
|
+
const parsed = parseProsePrefix(rawText);
|
|
3685
|
+
if (parsed.continueTurn)
|
|
3686
|
+
this.proseContinuations.add(name);
|
|
3687
|
+
if (parsed.kind === 'private') {
|
|
3688
|
+
// The text already lives in the assistant message (window/chronicle);
|
|
3689
|
+
// "delivery" is deliberately a no-op. Consumes the retained text if the
|
|
3690
|
+
// segment embedded it.
|
|
3691
|
+
if (parsed.body.includes('{{unsent}}'))
|
|
3692
|
+
this.proseClipboards.delete(name);
|
|
3693
|
+
console.error(`[prose] ${name}: >>skip_reply — ${parsed.body.length} chars kept in context (not sent)`);
|
|
3694
|
+
return;
|
|
3695
|
+
}
|
|
3696
|
+
let targetChannel;
|
|
3697
|
+
let body;
|
|
3698
|
+
if (parsed.kind === 'target') {
|
|
3699
|
+
const res = this.channelRegistry.resolveProseTarget(parsed.target);
|
|
3700
|
+
if ('error' in res) {
|
|
3701
|
+
this.bounceProse(agent, parsed.body, res.error, res.candidates);
|
|
3702
|
+
return;
|
|
3703
|
+
}
|
|
3704
|
+
targetChannel = res.channelId;
|
|
3705
|
+
// Sticky within the turn: later unprefixed segments follow this target.
|
|
3706
|
+
this.proseTargetPins.set(name, targetChannel);
|
|
3707
|
+
body = parsed.body;
|
|
3708
|
+
}
|
|
3709
|
+
else {
|
|
3710
|
+
const sticky = this.proseTargetPins.get(name);
|
|
3711
|
+
if (!sticky) {
|
|
3712
|
+
this.bounceProse(agent, rawText, 'no destination prefix and no destination set yet this turn');
|
|
3713
|
+
return;
|
|
3714
|
+
}
|
|
3715
|
+
targetChannel = sticky;
|
|
3716
|
+
body = rawText;
|
|
3717
|
+
}
|
|
3718
|
+
const usedClipboard = body.includes('{{unsent}}');
|
|
3719
|
+
if (usedClipboard) {
|
|
3720
|
+
body = body.replaceAll('{{unsent}}', this.proseClipboards.get(name) ?? '');
|
|
3721
|
+
}
|
|
3722
|
+
if (!body.trim()) {
|
|
3723
|
+
console.error(`[prose] ${name}: empty body after prefix/substitution — nothing to send`);
|
|
3724
|
+
return;
|
|
3725
|
+
}
|
|
3726
|
+
try {
|
|
3727
|
+
const result = await this.channelRegistry.routeSpeech(name, body, targetChannel);
|
|
3728
|
+
if (result?.delivered) {
|
|
3729
|
+
this.proseBounceStreaks.delete(name);
|
|
3730
|
+
if (usedClipboard)
|
|
3731
|
+
this.proseClipboards.delete(name);
|
|
3732
|
+
}
|
|
3733
|
+
}
|
|
3734
|
+
catch (err) {
|
|
3735
|
+
console.error(`[prose] ${name}: delivery to ${targetChannel} failed:`, err);
|
|
3736
|
+
}
|
|
3737
|
+
}
|
|
3738
|
+
/** Cap on consecutive bounce-triggered wakes (notices still append after). */
|
|
3739
|
+
static PROSE_BOUNCE_WAKE_CAP = 2;
|
|
3740
|
+
bounceProse(agent, text, reason, candidates) {
|
|
3741
|
+
const name = agent.name;
|
|
3742
|
+
this.proseClipboards.set(name, text);
|
|
3743
|
+
const streak = (this.proseBounceStreaks.get(name) ?? 0) + 1;
|
|
3744
|
+
this.proseBounceStreaks.set(name, streak);
|
|
3745
|
+
const cand = candidates?.length ? ` Known channels it could mean: ${candidates.join(', ')}.` : '';
|
|
3746
|
+
const notice = `[prose-routing] Your text (${text.length} chars) was not delivered — ${reason}.${cand} ` +
|
|
3747
|
+
'The text is retained; nothing is lost. To deliver it unchanged, reply with a ' +
|
|
3748
|
+
'destination plus the token {{unsent}}, e.g. ">>#channel {{unsent}}" or ">>@person {{unsent}}". ' +
|
|
3749
|
+
'">>skip_reply {{unsent}}" keeps it in context only. The prose_help tool shows the full syntax.';
|
|
3750
|
+
try {
|
|
3751
|
+
// Through framework.addMessage, NOT the context manager directly: while
|
|
3752
|
+
// the turn is still streaming this defers the notice to the next tool
|
|
3753
|
+
// boundary, where it is BOTH stored in order and injected into the live
|
|
3754
|
+
// stream (hear-while-acting) — the model sees the error and can correct
|
|
3755
|
+
// the prefix within the same turn. A direct append here would land the
|
|
3756
|
+
// notice before the turn's assistant blocks (cache bust, invisible
|
|
3757
|
+
// until the next compile).
|
|
3758
|
+
const id = this.addMessage('user', [{ type: 'text', text: notice }], { system: true, kind: 'prose-bounce' });
|
|
3759
|
+
if (id)
|
|
3760
|
+
this.emitTrace({ type: 'message:added', messageId: id, source: 'prose-bounce' });
|
|
3761
|
+
else
|
|
3762
|
+
this.emitTrace({ type: 'message:added', messageId: 'deferred', source: 'prose-bounce' });
|
|
3763
|
+
}
|
|
3764
|
+
catch (err) {
|
|
3765
|
+
console.error('bounceProse: failed to record bounce notice:', err);
|
|
3766
|
+
}
|
|
3767
|
+
const capped = streak > AgentFramework.PROSE_BOUNCE_WAKE_CAP;
|
|
3768
|
+
console.error(`[prose] ${name}: BOUNCED ${text.length} chars — ${reason}` +
|
|
3769
|
+
(capped ? ' (bounce-wake cap reached; notice appended without wake)' : ''));
|
|
3770
|
+
if (!capped) {
|
|
3771
|
+
// Wake so the resend can happen immediately — an unsent DM reply must
|
|
3772
|
+
// not sit invisible until the next unrelated event.
|
|
3773
|
+
this.pendingRequests.push({
|
|
3774
|
+
agentName: name,
|
|
3775
|
+
reason: 'prose-bounce',
|
|
3776
|
+
source: 'framework',
|
|
3777
|
+
timestamp: Date.now(),
|
|
3778
|
+
});
|
|
3779
|
+
}
|
|
3780
|
+
}
|
|
3781
|
+
/**
|
|
3782
|
+
* One-time mode primer (docs/explicit-prose-routing.md): when an agent's
|
|
3783
|
+
* configured proseRouting differs from the last mode we primed them for,
|
|
3784
|
+
* append the teaching notice and persist the new mode. A brand-new agent
|
|
3785
|
+
* in default locus mode is recorded silently — no primer for the status quo.
|
|
3786
|
+
*/
|
|
3787
|
+
maybePrimeProseMode(agent) {
|
|
3788
|
+
const mode = agent.proseRouting;
|
|
3789
|
+
try {
|
|
3790
|
+
const data = this.store.getStateJson(FRAMEWORK_STATE_ID);
|
|
3791
|
+
const state = (data && typeof data === 'object' ? data : {});
|
|
3792
|
+
const primed = { ...(state.proseRoutingPrimed ?? {}) };
|
|
3793
|
+
const stored = primed[agent.name];
|
|
3794
|
+
if (stored === mode)
|
|
3795
|
+
return;
|
|
3796
|
+
// Absence means "always default (locus)": a locus-mode agent that was
|
|
3797
|
+
// never explicit needs no entry and no primer — and skipping the write
|
|
3798
|
+
// keeps framework/state from growing a record per agent (scaling gate).
|
|
3799
|
+
if (mode === 'locus' && stored === undefined)
|
|
3800
|
+
return;
|
|
3801
|
+
if (mode === 'locus')
|
|
3802
|
+
delete primed[agent.name];
|
|
3803
|
+
else
|
|
3804
|
+
primed[agent.name] = mode;
|
|
3805
|
+
state.proseRoutingPrimed = primed;
|
|
3806
|
+
this.store.setStateJson(FRAMEWORK_STATE_ID, state);
|
|
3807
|
+
}
|
|
3808
|
+
catch (err) {
|
|
3809
|
+
console.error('maybePrimeProseMode: state read/write failed:', err);
|
|
3810
|
+
return;
|
|
3811
|
+
}
|
|
3812
|
+
try {
|
|
3813
|
+
const id = agent.getContextManager().addMessage('user', [{ type: 'text', text: proseModePrimer(mode) }], { system: true, kind: 'prose-routing-primer' });
|
|
3814
|
+
this.emitTrace({ type: 'message:added', messageId: id, source: 'prose-routing-primer' });
|
|
3815
|
+
console.error(`[prose] ${agent.name}: mode primer appended (${mode})`);
|
|
3816
|
+
}
|
|
3817
|
+
catch (err) {
|
|
3818
|
+
console.error('maybePrimeProseMode: failed to append primer:', err);
|
|
3323
3819
|
}
|
|
3324
3820
|
}
|
|
3325
3821
|
async startAgentStream(agent, trigger, attempt = 0) {
|
|
@@ -3334,20 +3830,74 @@ export class AgentFramework {
|
|
|
3334
3830
|
// instead falls back to the global default. A given agent runs one turn at a
|
|
3335
3831
|
// time, so a set here is only read during THIS turn's routeSpeech /
|
|
3336
3832
|
// buildChannelContext; retries re-run with the same trigger, re-setting it.
|
|
3337
|
-
|
|
3338
|
-
|
|
3833
|
+
// A context-budget restart continues the SAME logical turn in a fresh
|
|
3834
|
+
// stream — its trigger carries no channelId, and deleting the trigger
|
|
3835
|
+
// channel here mid-logical-turn is exactly the hole that sent Sol's DM
|
|
3836
|
+
// reply to a stale guild channel (2026-07-22): any live locus resolution
|
|
3837
|
+
// after the restart fell through to the hours-old defaultPublishChannel.
|
|
3838
|
+
// Keep the turn's trigger channel across restarts; only real new turns
|
|
3839
|
+
// reset it.
|
|
3840
|
+
if (trigger?.reason !== 'context_budget_restart') {
|
|
3841
|
+
if (trigger?.channelId) {
|
|
3842
|
+
this.activeTriggerChannels.set(agent.name, trigger.channelId);
|
|
3843
|
+
}
|
|
3844
|
+
else {
|
|
3845
|
+
this.activeTriggerChannels.delete(agent.name);
|
|
3846
|
+
}
|
|
3339
3847
|
}
|
|
3340
|
-
|
|
3341
|
-
|
|
3848
|
+
// FREEZE this turn's outbound locus now (turn-frozen routing). Resolved
|
|
3849
|
+
// once — home channel for forks, else the triggering channel, else the
|
|
3850
|
+
// global default — and never moved for the rest of the turn: mid-turn
|
|
3851
|
+
// injections must not redirect the agent's plain prose (ambient chatter /
|
|
3852
|
+
// reactions hijacked it before, 2026-07-21). A context-budget restart
|
|
3853
|
+
// continues the same logical turn, so it keeps the existing pin. The
|
|
3854
|
+
// eager snapshot also protects heartbeat turns from a moving
|
|
3855
|
+
// defaultPublishChannel mid-turn. If the effective locus differs from the
|
|
3856
|
+
// last one announced, drop a durable `[routing]` notice into the window
|
|
3857
|
+
// BEFORE this turn compiles, so the agent always knows where its voice
|
|
3858
|
+
// goes (announce-on-change only — no per-turn chatter, append-only for
|
|
3859
|
+
// KV stability).
|
|
3860
|
+
if (trigger?.reason !== 'context_budget_restart') {
|
|
3861
|
+
if (attempt === 0)
|
|
3862
|
+
this.maybePrimeProseMode(agent);
|
|
3863
|
+
if (agent.proseRouting === 'explicit') {
|
|
3864
|
+
// Explicit prose routing: there is no locus. The model names every
|
|
3865
|
+
// destination in-band (`>>` prefixes); the only turn state is the
|
|
3866
|
+
// sticky target, reset for each fresh turn. No freeze, no announce.
|
|
3867
|
+
this.proseTargetPins.delete(agent.name);
|
|
3868
|
+
this.proseContinuations.delete(agent.name);
|
|
3869
|
+
this.midTurnInputSignals.delete(agent.name);
|
|
3870
|
+
this.turnLocusPins.delete(agent.name);
|
|
3871
|
+
}
|
|
3872
|
+
else {
|
|
3873
|
+
const locus = this.channelRegistry?.resolveLocus(agent.name) ?? null;
|
|
3874
|
+
if (locus !== null)
|
|
3875
|
+
this.turnLocusPins.set(agent.name, locus);
|
|
3876
|
+
else
|
|
3877
|
+
this.turnLocusPins.delete(agent.name);
|
|
3878
|
+
this.midTurnInputSignals.delete(agent.name);
|
|
3879
|
+
if (attempt === 0)
|
|
3880
|
+
this.announceLocusIfChanged(agent.name, locus);
|
|
3881
|
+
}
|
|
3342
3882
|
}
|
|
3343
3883
|
this.touchEphemeralRun(agent.name, true);
|
|
3344
|
-
this.emitTrace({
|
|
3884
|
+
this.emitTrace({
|
|
3885
|
+
type: 'inference:started',
|
|
3886
|
+
agentName: agent.name,
|
|
3887
|
+
// The turn-frozen locus was pinned just above (kept across a
|
|
3888
|
+
// context-budget restart, which skips the re-pin but re-emits this).
|
|
3889
|
+
channelId: this.turnLocusPins.get(agent.name),
|
|
3890
|
+
});
|
|
3345
3891
|
this.eventGate?.onInferenceStarted(agent.name);
|
|
3346
3892
|
this.lastInferenceAt.set(agent.name, { ...this.lastInferenceAt.get(agent.name), startedAt: Date.now() });
|
|
3347
3893
|
try {
|
|
3348
3894
|
const requestSnapshot = this.captureInferenceToolSnapshot(agent);
|
|
3349
3895
|
const allTools = this.getToolsForAgent(agent.name, requestSnapshot);
|
|
3350
3896
|
const tools = allTools.filter((t) => agent.canUseTool(t.name));
|
|
3897
|
+
// Explicit-mode agents get the on-demand routing reference (teach-by-
|
|
3898
|
+
// bounce: the grammar is never injected, only served when asked).
|
|
3899
|
+
if (agent.proseRouting === 'explicit')
|
|
3900
|
+
tools.push(PROSE_HELP_TOOL);
|
|
3351
3901
|
// Gather context from modules (pull-based) and MCPL hooks (push-based)
|
|
3352
3902
|
// Both produce ContextInjection[] that get merged before inference.
|
|
3353
3903
|
let injections;
|
|
@@ -3428,25 +3978,14 @@ export class AgentFramework {
|
|
|
3428
3978
|
const myStreamId = agent.streamId;
|
|
3429
3979
|
let hadToolCalls = false;
|
|
3430
3980
|
// ---- Present-while-acting turn state ---------------------------------
|
|
3431
|
-
// Output locus for the
|
|
3432
|
-
//
|
|
3433
|
-
//
|
|
3434
|
-
//
|
|
3435
|
-
//
|
|
3436
|
-
//
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
this.midTurnRoutingResets.delete(agent.name);
|
|
3440
|
-
}
|
|
3441
|
-
const resolveTurnLocus = () => {
|
|
3442
|
-
let locus = this.turnLocusPins.get(agent.name) ?? null;
|
|
3443
|
-
if (locus === null && this.channelRegistry) {
|
|
3444
|
-
locus = this.channelRegistry.resolveLocus(agent.name);
|
|
3445
|
-
if (locus !== null)
|
|
3446
|
-
this.turnLocusPins.set(agent.name, locus);
|
|
3447
|
-
}
|
|
3448
|
-
return locus;
|
|
3449
|
-
};
|
|
3981
|
+
// Output locus for the WHOLE logical turn: frozen in startAgentStream
|
|
3982
|
+
// (home → addressed trigger → global default) before this stream began,
|
|
3983
|
+
// and never moved until the next turn. Mid-turn injections do not touch
|
|
3984
|
+
// it — an ambient message or a reaction arriving at a tool boundary must
|
|
3985
|
+
// not redirect the agent's task narration (2026-07-21 Cairn misroute).
|
|
3986
|
+
// The pin lives in `turnLocusPins` so a context-budget restart (same
|
|
3987
|
+
// logical turn, fresh driveStream) keeps it.
|
|
3988
|
+
const resolveTurnLocus = () => this.turnLocusPins.get(agent.name) ?? null;
|
|
3450
3989
|
// Ordered delivery chain for live-routed prose. Links are enqueued
|
|
3451
3990
|
// WITHOUT awaiting in the stream-event loop — an awaited network post
|
|
3452
3991
|
// here would stall consumption of the next round's events by
|
|
@@ -3475,32 +4014,29 @@ export class AgentFramework {
|
|
|
3475
4014
|
// historical whole-turn routing so fallback-mode prose is still
|
|
3476
4015
|
// delivered exactly once, at turn end.
|
|
3477
4016
|
let liveProseRouting = false;
|
|
3478
|
-
// Typing indicator: show "<agent> is typing…"
|
|
3479
|
-
//
|
|
3480
|
-
//
|
|
3481
|
-
//
|
|
3482
|
-
|
|
3483
|
-
|
|
3484
|
-
|
|
4017
|
+
// Typing indicator: show "<agent> is typing…" for the whole duration of
|
|
4018
|
+
// this turn. Started here (paired with the finally below, so it can never
|
|
4019
|
+
// leak) and refreshed on a 7s interval by the ChannelRegistry until
|
|
4020
|
+
// stopped on any exit path. Never moves mid-turn.
|
|
4021
|
+
// - locus mode: the frozen routing pin (where bare prose will land).
|
|
4022
|
+
// - explicit mode: there is no locus — indicate on the TRIGGER channel
|
|
4023
|
+
// (where the wake came from). Typing is presence, not delivery, so
|
|
4024
|
+
// this doesn't violate never-guess: it says "attending to what you
|
|
4025
|
+
// sent here", which is true regardless of where the reply goes.
|
|
4026
|
+
// Heartbeat/no-trigger explicit turns show no indicator.
|
|
4027
|
+
const typingChannel = agent.proseRouting === 'explicit'
|
|
4028
|
+
? trigger?.channelId ?? null
|
|
4029
|
+
: resolveTurnLocus();
|
|
3485
4030
|
if (typingChannel)
|
|
3486
4031
|
this.channelRegistry.startTyping(typingChannel);
|
|
3487
4032
|
const adoptInjectedRound = () => {
|
|
3488
|
-
if (!this.
|
|
4033
|
+
if (!this.midTurnInputSignals.has(agent.name))
|
|
3489
4034
|
return;
|
|
3490
|
-
|
|
3491
|
-
|
|
3492
|
-
//
|
|
3493
|
-
//
|
|
4035
|
+
this.midTurnInputSignals.delete(agent.name);
|
|
4036
|
+
// A new conversational message, not merely a tool result, means any
|
|
4037
|
+
// earlier explicit delivery has completed its conversational job.
|
|
4038
|
+
// Routing is NOT touched: the turn locus stays frozen.
|
|
3494
4039
|
turnSilenced = false;
|
|
3495
|
-
if (nextLocus) {
|
|
3496
|
-
this.turnLocusPins.set(agent.name, nextLocus);
|
|
3497
|
-
if (typingChannel !== nextLocus) {
|
|
3498
|
-
if (typingChannel)
|
|
3499
|
-
this.channelRegistry?.stopTyping(typingChannel);
|
|
3500
|
-
typingChannel = nextLocus;
|
|
3501
|
-
this.channelRegistry?.startTyping(nextLocus);
|
|
3502
|
-
}
|
|
3503
|
-
}
|
|
3504
4040
|
};
|
|
3505
4041
|
try {
|
|
3506
4042
|
for await (const event of stream) {
|
|
@@ -3513,6 +4049,10 @@ export class AgentFramework {
|
|
|
3513
4049
|
content: event.content,
|
|
3514
4050
|
blockType: event.meta.type,
|
|
3515
4051
|
blockIndex: event.meta.blockIndex,
|
|
4052
|
+
// Turn-frozen locus (same value as the typing indicator above):
|
|
4053
|
+
// lets trace consumers tag every chunk with the channel this
|
|
4054
|
+
// turn's prose is bound for, without re-deriving routing.
|
|
4055
|
+
channelId: typingChannel ?? undefined,
|
|
3516
4056
|
});
|
|
3517
4057
|
break;
|
|
3518
4058
|
case 'block': {
|
|
@@ -3523,6 +4063,7 @@ export class AgentFramework {
|
|
|
3523
4063
|
phase,
|
|
3524
4064
|
blockType: block.type,
|
|
3525
4065
|
blockIndex: index,
|
|
4066
|
+
channelId: typingChannel ?? undefined,
|
|
3526
4067
|
});
|
|
3527
4068
|
break;
|
|
3528
4069
|
}
|
|
@@ -3547,13 +4088,30 @@ export class AgentFramework {
|
|
|
3547
4088
|
assistantBlocks = roundContent.filter((b) => b.type !== 'tool_result');
|
|
3548
4089
|
}
|
|
3549
4090
|
else {
|
|
3550
|
-
// Fallback (older membrane / XML tool mode): preamble + calls
|
|
4091
|
+
// Fallback (older membrane / XML tool mode): preamble + calls.
|
|
4092
|
+
// XML mode: persist the verbatim generation on each tool_use
|
|
4093
|
+
// (membrane#36 round-trip fidelity). context.rawText is the
|
|
4094
|
+
// parser's fullMatch — the exact <function_calls> block the
|
|
4095
|
+
// model wrote (plus the harness-appended close tag), shared by
|
|
4096
|
+
// every call in the round; the anthropic-xml formatter replays
|
|
4097
|
+
// it byte-identically instead of reconstructing. Guarded by
|
|
4098
|
+
// shape so a native-path fallback can never attach non-XML.
|
|
4099
|
+
const rawText = event.context.rawText;
|
|
4100
|
+
const rawXml = rawText && /^<(antml:)?function_calls>/.test(rawText)
|
|
4101
|
+
? rawText
|
|
4102
|
+
: undefined;
|
|
3551
4103
|
assistantBlocks = [];
|
|
3552
4104
|
if (event.context.preamble) {
|
|
3553
4105
|
assistantBlocks.push({ type: 'text', text: event.context.preamble });
|
|
3554
4106
|
}
|
|
3555
4107
|
for (const c of event.calls) {
|
|
3556
|
-
assistantBlocks.push({
|
|
4108
|
+
assistantBlocks.push({
|
|
4109
|
+
type: 'tool_use',
|
|
4110
|
+
id: c.id,
|
|
4111
|
+
name: c.name,
|
|
4112
|
+
input: c.input,
|
|
4113
|
+
...(rawXml ? { rawXml } : {}),
|
|
4114
|
+
});
|
|
3557
4115
|
}
|
|
3558
4116
|
}
|
|
3559
4117
|
this.pendingAssistantBlocks.set(agent.name, assistantBlocks);
|
|
@@ -3588,7 +4146,20 @@ export class AgentFramework {
|
|
|
3588
4146
|
liveProseRouting = true;
|
|
3589
4147
|
const roundSegments = splitProseSegments(assistantBlocks);
|
|
3590
4148
|
if (roundSegments.length > 0) {
|
|
3591
|
-
if (
|
|
4149
|
+
if (agent.proseRouting === 'explicit') {
|
|
4150
|
+
// Explicit mode: every segment through the prose gateway.
|
|
4151
|
+
// Silencing does not apply — unprefixed prose bounces and
|
|
4152
|
+
// prefixed prose is deliberate; think-privacy still holds.
|
|
4153
|
+
if (!hasSameRoundPrivateThink) {
|
|
4154
|
+
console.error(`[prose] ${agent.name}: mid-turn round [${roundToolNames.join(', ')}] -> ${roundSegments.length} segment(s) via prose gateway`);
|
|
4155
|
+
for (const seg of roundSegments) {
|
|
4156
|
+
turnSpeechChain = turnSpeechChain
|
|
4157
|
+
.then(() => this.deliverProse(agent, seg))
|
|
4158
|
+
.catch((err) => console.error('mid-turn prose delivery failed:', err));
|
|
4159
|
+
}
|
|
4160
|
+
}
|
|
4161
|
+
}
|
|
4162
|
+
else if (turnSilenced) {
|
|
3592
4163
|
console.error(`[routing] ${agent.name}: mid-turn round [${roundToolNames.join(', ')}] -> prose NOT routed (turn silenced)`);
|
|
3593
4164
|
}
|
|
3594
4165
|
else if (hasSameRoundPrivateThink) {
|
|
@@ -3867,11 +4438,30 @@ export class AgentFramework {
|
|
|
3867
4438
|
.join('\n')
|
|
3868
4439
|
.trim();
|
|
3869
4440
|
if (speechText) {
|
|
3870
|
-
|
|
3871
|
-
|
|
4441
|
+
if (agent.proseRouting === 'explicit') {
|
|
4442
|
+
console.error(`[prose] ${agent.name}: text-only turn -> prose gateway`);
|
|
4443
|
+
try {
|
|
4444
|
+
await this.deliverProse(agent, speechText);
|
|
4445
|
+
}
|
|
4446
|
+
catch (err) {
|
|
4447
|
+
console.error('text-only prose delivery failed:', err);
|
|
4448
|
+
}
|
|
3872
4449
|
}
|
|
3873
|
-
|
|
3874
|
-
|
|
4450
|
+
else {
|
|
4451
|
+
// Route to the TURN-FROZEN locus, like every other speech
|
|
4452
|
+
// path. This dispatch runs AFTER the agent is idle, so a live
|
|
4453
|
+
// resolution here can read the NEXT turn's trigger state (or
|
|
4454
|
+
// a post-restart cleared one) and land the reply in a stale
|
|
4455
|
+
// channel — the 2026-07-22 Sol DM-to-guild misroute. The
|
|
4456
|
+
// frozen pin is immune to both races.
|
|
4457
|
+
const locus = resolveTurnLocus();
|
|
4458
|
+
console.error(`[routing] ${agent.name}: text-only turn -> routing speech -> ${locus ?? '(none)'}`);
|
|
4459
|
+
try {
|
|
4460
|
+
await this.channelRegistry.routeSpeech(agent.name, speechText, locus);
|
|
4461
|
+
}
|
|
4462
|
+
catch (err) {
|
|
4463
|
+
console.error('speech routing failed:', err);
|
|
4464
|
+
}
|
|
3875
4465
|
}
|
|
3876
4466
|
}
|
|
3877
4467
|
}
|
|
@@ -3902,7 +4492,20 @@ export class AgentFramework {
|
|
|
3902
4492
|
// land before the trailing prose. Awaited even when silenced —
|
|
3903
4493
|
// the chain may still be flushing earlier rounds' posts.
|
|
3904
4494
|
await turnSpeechChain;
|
|
3905
|
-
if (
|
|
4495
|
+
if (agent.proseRouting === 'explicit') {
|
|
4496
|
+
if (segments.length > 0) {
|
|
4497
|
+
console.error(`[prose] ${agent.name}: tool-call turn [${toolNames.join(', ')}] -> ${segments.length} trailing segment(s) via prose gateway`);
|
|
4498
|
+
for (const seg of segments) {
|
|
4499
|
+
try {
|
|
4500
|
+
await this.deliverProse(agent, seg);
|
|
4501
|
+
}
|
|
4502
|
+
catch (err) {
|
|
4503
|
+
console.error('trailing prose delivery failed:', err);
|
|
4504
|
+
}
|
|
4505
|
+
}
|
|
4506
|
+
}
|
|
4507
|
+
}
|
|
4508
|
+
else if (silenced || segments.length === 0) {
|
|
3906
4509
|
console.error(`[routing] ${agent.name}: tool-call turn [${toolNames.join(', ') || 'none'}] -> trailing prose NOT routed ` +
|
|
3907
4510
|
`(${silenced ? 'silencing tool / explicit send' : 'no trailing prose'})`);
|
|
3908
4511
|
}
|
|
@@ -3930,6 +4533,20 @@ export class AgentFramework {
|
|
|
3930
4533
|
// NOTE: agent.reset() + onInferenceEnded() already ran above,
|
|
3931
4534
|
// BEFORE dispatchSpeech. Locus routing is speech dispatch and
|
|
3932
4535
|
// doesn't depend on the status field, so it correctly runs after.
|
|
4536
|
+
// Explicit-prose `!` continuation: a prose segment this turn asked
|
|
4537
|
+
// to keep going (`>>#x !` / `>>private !`) — start another turn
|
|
4538
|
+
// now instead of pausing until the next external event. This gives
|
|
4539
|
+
// prose the same continuation ability tool rounds have (wanted for
|
|
4540
|
+
// robotics-style loops where an end-of-turn pause is harmful).
|
|
4541
|
+
if (this.proseContinuations.delete(agent.name)) {
|
|
4542
|
+
console.error(`[prose] ${agent.name}: '!' continuation — requesting immediate next turn`);
|
|
4543
|
+
this.pendingRequests.push({
|
|
4544
|
+
agentName: agent.name,
|
|
4545
|
+
reason: 'prose-continuation',
|
|
4546
|
+
source: 'framework',
|
|
4547
|
+
timestamp: Date.now(),
|
|
4548
|
+
});
|
|
4549
|
+
}
|
|
3933
4550
|
break;
|
|
3934
4551
|
}
|
|
3935
4552
|
case 'error': {
|
|
@@ -4401,6 +5018,20 @@ export class AgentFramework {
|
|
|
4401
5018
|
this.dispatchChannelToolCall(agentName, enrichedCall);
|
|
4402
5019
|
return;
|
|
4403
5020
|
}
|
|
5021
|
+
// prose_help: on-demand routing reference for explicit-prose agents.
|
|
5022
|
+
// Answered inline — the grammar is a tool RESULT (model-requested), never
|
|
5023
|
+
// ambient context (see PROSE_ROUTING_HELP / teach-by-bounce).
|
|
5024
|
+
if (enrichedCall.name === 'prose_help') {
|
|
5025
|
+
this.emitTrace({ type: 'tool:completed', module: 'framework', tool: 'prose_help', callId: enrichedCall.id, durationMs: 0 });
|
|
5026
|
+
this.pushEvent({
|
|
5027
|
+
type: 'tool-result',
|
|
5028
|
+
callId: enrichedCall.id,
|
|
5029
|
+
agentName,
|
|
5030
|
+
moduleName: 'framework',
|
|
5031
|
+
result: { success: true, data: PROSE_ROUTING_HELP },
|
|
5032
|
+
});
|
|
5033
|
+
return;
|
|
5034
|
+
}
|
|
4404
5035
|
const sepIndex = enrichedCall.name.indexOf('--');
|
|
4405
5036
|
const moduleName = sepIndex >= 0 ? enrichedCall.name.substring(0, sepIndex) : 'unknown';
|
|
4406
5037
|
const toolName = sepIndex >= 0 ? call.name.substring(sepIndex + 2) : call.name;
|
|
@@ -4723,6 +5354,13 @@ export class AgentFramework {
|
|
|
4723
5354
|
if (err.name === 'OverBudgetError') {
|
|
4724
5355
|
return { errorType: 'over_budget' };
|
|
4725
5356
|
}
|
|
5357
|
+
// context-manager's fatal coverage invariant (fix/coverage-invariant-fatal,
|
|
5358
|
+
// 2026-07-26): a compile REFUSES rather than shipping a context with
|
|
5359
|
+
// silently-dropped messages. Recovery is identical to over_budget — kick
|
|
5360
|
+
// the compression drain so summaries cover the un-represented span.
|
|
5361
|
+
if (err.name === 'UncoveredDropError') {
|
|
5362
|
+
return { errorType: 'context_refusal' };
|
|
5363
|
+
}
|
|
4726
5364
|
return {};
|
|
4727
5365
|
}
|
|
4728
5366
|
/**
|
|
@@ -4777,7 +5415,19 @@ export class AgentFramework {
|
|
|
4777
5415
|
// (e.g. a reason string that crossed a serialization boundary). It matches
|
|
4778
5416
|
// CM's current OverBudgetError wording and MAY rot if CM rewords it — the
|
|
4779
5417
|
// errorType gate is the one that's load-bearing.
|
|
4780
|
-
const overBudget = errorType === 'over_budget' ||
|
|
5418
|
+
const overBudget = errorType === 'over_budget' ||
|
|
5419
|
+
errorType === 'context_refusal' ||
|
|
5420
|
+
/exceed hard budget|no summary covers/i.test(reason);
|
|
5421
|
+
// Observability: a refused compile means the agent cannot think AT ALL
|
|
5422
|
+
// this turn — surface it on the ops-alert pipeline (ops:alert trace +
|
|
5423
|
+
// webhook → fleet-watch) immediately, not only at the hard-down streak.
|
|
5424
|
+
// The per-(agent,kind) cooldown throttles repeats; failures.log already
|
|
5425
|
+
// has the per-exhaustion record from logFailure above.
|
|
5426
|
+
if (overBudget) {
|
|
5427
|
+
this.opsAlert('context-refusal', agentName, `compile refused (${errorType ?? 'unclassified'}): ${reason.slice(0, 300)} — ` +
|
|
5428
|
+
`drain breaker ${agent ? 'kicking' : 'unavailable (no agent handle)'}; ` +
|
|
5429
|
+
`if this persists, raise contextBudgetTokens or overBudgetGraceRatio.`, { skipLog: true });
|
|
5430
|
+
}
|
|
4781
5431
|
if (agent && overBudget && !this.overBudgetDrainInFlight.has(agentName)) {
|
|
4782
5432
|
this.overBudgetDrainInFlight.add(agentName);
|
|
4783
5433
|
void (async () => {
|
|
@@ -4924,15 +5574,35 @@ export class AgentFramework {
|
|
|
4924
5574
|
// yes, wake no).
|
|
4925
5575
|
onRouteFailure: ({ channelId, reason, textLen }) => {
|
|
4926
5576
|
try {
|
|
5577
|
+
// Render a human-readable channel name when we can — a bare
|
|
5578
|
+
// snowflake in the marker is unresolvable for the agent (the
|
|
5579
|
+
// 2026-07-21 incident read as "a stale artifact", not a live
|
|
5580
|
+
// failure). The marker is `system: true`, so it is never
|
|
5581
|
+
// conversational and never influences routing.
|
|
5582
|
+
const label = channelId
|
|
5583
|
+
? this.channelRegistry?.getDescriptor(channelId)?.label
|
|
5584
|
+
: undefined;
|
|
5585
|
+
const where = channelId
|
|
5586
|
+
? label && label !== channelId
|
|
5587
|
+
? `${label.startsWith('#') ? label : `#${label}`} (${channelId})`
|
|
5588
|
+
: channelId
|
|
5589
|
+
: 'the channel';
|
|
4927
5590
|
this.addMessage('user', [{
|
|
4928
5591
|
type: 'text',
|
|
4929
|
-
text: `[discord-send-failed] Your previous reply (${textLen} chars) could not be delivered to ${
|
|
5592
|
+
text: `[discord-send-failed] Your previous reply (${textLen} chars) could not be delivered to ${where} (${reason}). It was saved to your archive but the human did not receive it.`,
|
|
4930
5593
|
}], { system: true, kind: 'discord-send-failed', channelId: channelId ?? '', reason });
|
|
4931
5594
|
}
|
|
4932
5595
|
catch (err) {
|
|
4933
5596
|
console.error('onRouteFailure: failed to record send-failure marker:', err);
|
|
4934
5597
|
}
|
|
4935
5598
|
},
|
|
5599
|
+
// A channel opened without the agent asking (policy admission or an
|
|
5600
|
+
// open forced by delivery) must be announced in the window, with the
|
|
5601
|
+
// opt-out named. Routed here so registry-driven opens and framework-
|
|
5602
|
+
// driven opens produce the same durable notice.
|
|
5603
|
+
onChannelAutoOpened: ({ conversationId, source, channels }) => {
|
|
5604
|
+
this.recordChannelAutoOpenNotice(conversationId, channels, source);
|
|
5605
|
+
},
|
|
4936
5606
|
});
|
|
4937
5607
|
// Host capabilities advertised during the MCP handshake — stored so
|
|
4938
5608
|
// servers can also be connected later at runtime (connectMcplServer).
|
|
@@ -5785,6 +6455,33 @@ export class AgentFramework {
|
|
|
5785
6455
|
this.checkpointManager.recordCheckpoint(serverId, fs, result.state);
|
|
5786
6456
|
}
|
|
5787
6457
|
}
|
|
6458
|
+
// INVARIANT: engaging a channel opens it. A successful explicit send
|
|
6459
|
+
// into a channel the registry knows as closed drives the same open
|
|
6460
|
+
// flow as channel_open (durable desired state, server subscribe), so
|
|
6461
|
+
// there is no such thing as posting into a channel that stays
|
|
6462
|
+
// half-alive (no typing, no reactions, no inbound forwarding).
|
|
6463
|
+
// Fire-and-forget: the send already succeeded; the open must not
|
|
6464
|
+
// delay or fail the tool result.
|
|
6465
|
+
if (this.channelRegistry &&
|
|
6466
|
+
SEND_ENGAGEMENT_TOOLS.has(toolName) &&
|
|
6467
|
+
result.isError !== true) {
|
|
6468
|
+
const target = extractChannelIdFromToolResult(result.content) ??
|
|
6469
|
+
(typeof args.channelId === 'string' ? args.channelId : undefined);
|
|
6470
|
+
if (target) {
|
|
6471
|
+
this.channelRegistry
|
|
6472
|
+
.openIfClosedForSend(target, serverId)
|
|
6473
|
+
.then(({ status, channelId, label }) => {
|
|
6474
|
+
if (status === 'opened') {
|
|
6475
|
+
console.error(`[channel] ${agentName}: explicit ${toolName} into closed channel ${target} — opened (send implies engagement)`);
|
|
6476
|
+
this.recordChannelAutoOpenNotice(agentName, [{ channelId: channelId ?? target, label }], 'opened-by-reply');
|
|
6477
|
+
}
|
|
6478
|
+
else if (status === 'open-failed') {
|
|
6479
|
+
console.error(`[channel] ${agentName}: ${toolName} delivered to ${target} but the open-on-send failed — channel remains half-alive, will reconcile`);
|
|
6480
|
+
}
|
|
6481
|
+
})
|
|
6482
|
+
.catch((err) => console.error('[channel] open-on-send error:', err));
|
|
6483
|
+
}
|
|
6484
|
+
}
|
|
5788
6485
|
// Convert MCP tool result to framework ToolResult.
|
|
5789
6486
|
// When the result contains non-text blocks (e.g. images from an MCP
|
|
5790
6487
|
// tool like zulip-mcp's fetch_attachment), pass the full content array
|
|
@@ -6014,12 +6711,31 @@ export class AgentFramework {
|
|
|
6014
6711
|
const human = seconds >= 3600 ? `${(seconds / 3600).toFixed(1)}h`
|
|
6015
6712
|
: seconds >= 60 ? `${Math.round(seconds / 60)}m`
|
|
6016
6713
|
: `${Math.round(seconds)}s`;
|
|
6017
|
-
// Announce in the
|
|
6714
|
+
// Announce in the TURN's frozen locus (best-effort; never blocks the
|
|
6715
|
+
// result). The sleep tool runs mid-turn, so the pin is live — same
|
|
6716
|
+
// authority as every other speech path, no live re-resolution.
|
|
6018
6717
|
if (announce && this.channelRegistry) {
|
|
6019
6718
|
const text = input.message ?? `💤 Going quiet for ${human}. I'll still see messages, but won't respond until I wake.`;
|
|
6020
|
-
this.
|
|
6021
|
-
|
|
6022
|
-
|
|
6719
|
+
const agent = this.agents.get(agentName);
|
|
6720
|
+
if (agent?.proseRouting === 'explicit') {
|
|
6721
|
+
// Explicit mode: announce to the turn's sticky prose target if the
|
|
6722
|
+
// model has set one; otherwise stay quiet — never guess a channel.
|
|
6723
|
+
const target = this.proseTargetPins.get(agentName);
|
|
6724
|
+
if (target) {
|
|
6725
|
+
this.channelRegistry.routeSpeech(agentName, text, target).catch((err) => {
|
|
6726
|
+
console.error('[sleep] announce failed:', err instanceof Error ? err.message : err);
|
|
6727
|
+
});
|
|
6728
|
+
}
|
|
6729
|
+
else {
|
|
6730
|
+
console.error(`[sleep] ${agentName}: no prose target this turn — sleep announcement not posted (explicit mode never guesses)`);
|
|
6731
|
+
}
|
|
6732
|
+
}
|
|
6733
|
+
else {
|
|
6734
|
+
const locus = this.turnLocusPins.get(agentName) ?? null;
|
|
6735
|
+
this.channelRegistry.routeSpeech(agentName, text, locus).catch((err) => {
|
|
6736
|
+
console.error('[sleep] announce failed:', err instanceof Error ? err.message : err);
|
|
6737
|
+
});
|
|
6738
|
+
}
|
|
6023
6739
|
}
|
|
6024
6740
|
console.error(`[sleep] agent=${agentName} seconds=${seconds} announce=${announce} until=${new Date(until).toISOString()}`);
|
|
6025
6741
|
// endTurn: the agent stops here and goes idle for the duration.
|