@botcord/daemon 0.2.78 → 0.2.79
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/attention-policy-fetcher.d.ts +14 -0
- package/dist/attention-policy-fetcher.js +59 -0
- package/dist/cloud-daemon.js +8 -0
- package/dist/cloud-gateway-runtime.d.ts +29 -0
- package/dist/cloud-gateway-runtime.js +122 -0
- package/dist/daemon.js +21 -6
- package/dist/gateway/channels/botcord.js +29 -9
- package/dist/gateway/channels/login-session.d.ts +12 -0
- package/dist/gateway/channels/login-session.js +20 -2
- package/dist/gateway/channels/sanitize.d.ts +5 -18
- package/dist/gateway/channels/sanitize.js +5 -54
- package/dist/gateway/channels/text-split.d.ts +5 -11
- package/dist/gateway/channels/text-split.js +5 -31
- package/dist/gateway/dispatcher.d.ts +7 -1
- package/dist/gateway/dispatcher.js +88 -8
- package/dist/gateway/gateway.d.ts +16 -1
- package/dist/gateway/gateway.js +21 -0
- package/dist/gateway/policy-resolver.js +17 -9
- package/dist/gateway/runtimes/deepseek-tui.js +31 -12
- package/dist/gateway/types.d.ts +12 -57
- package/dist/gateway-control.js +18 -9
- package/dist/provision.d.ts +7 -3
- package/dist/provision.js +115 -8
- package/dist/room-recovery-context.d.ts +11 -0
- package/dist/room-recovery-context.js +97 -0
- package/package.json +2 -2
- package/src/__tests__/attention-policy-fetcher.test.ts +67 -0
- package/src/__tests__/cloud-gateway-runtime.test.ts +127 -0
- package/src/__tests__/gateway-control.test.ts +136 -0
- package/src/__tests__/policy-resolver.test.ts +20 -0
- package/src/__tests__/provision.test.ts +65 -0
- package/src/attention-policy-fetcher.ts +87 -0
- package/src/cloud-daemon.ts +8 -0
- package/src/cloud-gateway-runtime.ts +171 -0
- package/src/daemon.ts +23 -6
- package/src/gateway/__tests__/botcord-channel.test.ts +97 -0
- package/src/gateway/__tests__/deepseek-tui-adapter.test.ts +177 -0
- package/src/gateway/__tests__/dispatcher.test.ts +56 -0
- package/src/gateway/channels/botcord.ts +32 -8
- package/src/gateway/channels/login-session.ts +20 -2
- package/src/gateway/channels/sanitize.ts +8 -66
- package/src/gateway/channels/text-split.ts +5 -27
- package/src/gateway/dispatcher.ts +123 -27
- package/src/gateway/gateway.ts +29 -0
- package/src/gateway/policy-resolver.ts +20 -9
- package/src/gateway/runtimes/deepseek-tui.ts +37 -12
- package/src/gateway/types.ts +31 -59
- package/src/gateway-control.ts +21 -9
- package/src/provision.ts +133 -7
- package/src/room-recovery-context.ts +131 -0
|
@@ -124,6 +124,25 @@ function extractCloudRunBudget(msg) {
|
|
|
124
124
|
}
|
|
125
125
|
return out.maxWallTimeMs !== undefined || out.maxToolCalls !== undefined ? out : undefined;
|
|
126
126
|
}
|
|
127
|
+
function looksLikeRecoverableSessionFailure(error) {
|
|
128
|
+
return /compact|compaction|context|token limit|maximum context|too many tokens|conversation found|session .*not found|resume/i
|
|
129
|
+
.test(error);
|
|
130
|
+
}
|
|
131
|
+
function buildRuntimeRecoveryPrompt(args) {
|
|
132
|
+
return [
|
|
133
|
+
"[BotCord Runtime Recovery Notice]",
|
|
134
|
+
"The previous Codex runtime session for this room became unrecoverable while resuming or compacting context.",
|
|
135
|
+
`Previous runtime error: ${truncate(args.error, 1000)}`,
|
|
136
|
+
"You are now running in a fresh Codex session.",
|
|
137
|
+
"Use the recent room messages below, current filesystem state, and available BotCord memory/context tools to reconstruct the active task.",
|
|
138
|
+
"Continue the original user request without asking the user to repeat information unless it is missing from those sources.",
|
|
139
|
+
"",
|
|
140
|
+
args.recoveryContext?.trim() || "[Recent Room Messages]\n(unavailable)",
|
|
141
|
+
"",
|
|
142
|
+
"[Current User Turn]",
|
|
143
|
+
args.userTurn,
|
|
144
|
+
].join("\n");
|
|
145
|
+
}
|
|
127
146
|
/**
|
|
128
147
|
* Reason carried on `AbortController.abort()` when a cancel-previous wave
|
|
129
148
|
* is taking over the slot. Distinguishing this from a timeout abort lets
|
|
@@ -164,6 +183,7 @@ export class Dispatcher {
|
|
|
164
183
|
runtimeAuthFailureCooldownMs;
|
|
165
184
|
buildSystemContext;
|
|
166
185
|
buildMemoryContext;
|
|
186
|
+
buildRuntimeRecoveryContext;
|
|
167
187
|
onInbound;
|
|
168
188
|
onOutbound;
|
|
169
189
|
onTurnComplete;
|
|
@@ -195,6 +215,7 @@ export class Dispatcher {
|
|
|
195
215
|
opts.runtimeAuthFailureCooldownMs ?? DEFAULT_RUNTIME_AUTH_FAILURE_COOLDOWN_MS;
|
|
196
216
|
this.buildSystemContext = opts.buildSystemContext;
|
|
197
217
|
this.buildMemoryContext = opts.buildMemoryContext;
|
|
218
|
+
this.buildRuntimeRecoveryContext = opts.buildRuntimeRecoveryContext;
|
|
198
219
|
this.onInbound = opts.onInbound;
|
|
199
220
|
this.onOutbound = opts.onOutbound;
|
|
200
221
|
this.onTurnComplete = opts.onTurnComplete;
|
|
@@ -1269,12 +1290,13 @@ export class Dispatcher {
|
|
|
1269
1290
|
const runtime = this.runtimeFactory(route.runtime, route.extraArgs);
|
|
1270
1291
|
let result;
|
|
1271
1292
|
let threw;
|
|
1293
|
+
let activeSessionId = sessionId;
|
|
1272
1294
|
const turnStartedAt = Date.now();
|
|
1273
1295
|
try {
|
|
1274
1296
|
try {
|
|
1275
|
-
|
|
1276
|
-
text:
|
|
1277
|
-
sessionId,
|
|
1297
|
+
const runRuntime = (textForRun, sessionIdForRun) => runtime.run({
|
|
1298
|
+
text: textForRun,
|
|
1299
|
+
sessionId: sessionIdForRun,
|
|
1278
1300
|
cwd: route.cwd,
|
|
1279
1301
|
accountId: msg.accountId,
|
|
1280
1302
|
hubUrl: this.resolveHubUrl?.(msg.accountId),
|
|
@@ -1296,6 +1318,64 @@ export class Dispatcher {
|
|
|
1296
1318
|
gateway: route.gateway,
|
|
1297
1319
|
...(route.hermesProfile ? { hermesProfile: route.hermesProfile } : {}),
|
|
1298
1320
|
});
|
|
1321
|
+
result = await runRuntime(runtimeText, sessionId);
|
|
1322
|
+
const firstError = result.error ?? "";
|
|
1323
|
+
const firstReply = (result.text || "").trim();
|
|
1324
|
+
const shouldRetryFresh = route.runtime === "codex" &&
|
|
1325
|
+
!!sessionId &&
|
|
1326
|
+
!!firstError &&
|
|
1327
|
+
!firstReply &&
|
|
1328
|
+
!looksLikeRuntimeAuthFailure(firstError) &&
|
|
1329
|
+
looksLikeRecoverableSessionFailure(firstError) &&
|
|
1330
|
+
!controller.signal.aborted &&
|
|
1331
|
+
!slot.timedOut &&
|
|
1332
|
+
!slot.budgetExceeded;
|
|
1333
|
+
if (shouldRetryFresh) {
|
|
1334
|
+
try {
|
|
1335
|
+
await this.sessionStore.delete(key);
|
|
1336
|
+
this.log.info("dispatcher: dropped unrecoverable runtime session before fresh retry", {
|
|
1337
|
+
key,
|
|
1338
|
+
prevRuntimeSessionId: sessionId,
|
|
1339
|
+
runtime: route.runtime,
|
|
1340
|
+
error: firstError,
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
catch (err) {
|
|
1344
|
+
this.log.warn("dispatcher: session-store.delete failed before fresh retry", {
|
|
1345
|
+
key,
|
|
1346
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
let recoveryContext;
|
|
1350
|
+
if (this.buildRuntimeRecoveryContext) {
|
|
1351
|
+
try {
|
|
1352
|
+
recoveryContext = await this.buildRuntimeRecoveryContext(msg);
|
|
1353
|
+
}
|
|
1354
|
+
catch (err) {
|
|
1355
|
+
this.log.warn("dispatcher: buildRuntimeRecoveryContext threw — retrying without recent room context", {
|
|
1356
|
+
agentId: msg.accountId,
|
|
1357
|
+
roomId: msg.conversation.id,
|
|
1358
|
+
topicId: msg.conversation.threadId ?? null,
|
|
1359
|
+
turnId,
|
|
1360
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1361
|
+
});
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
activeSessionId = null;
|
|
1365
|
+
runtimeText = buildRuntimeRecoveryPrompt({
|
|
1366
|
+
userTurn: text,
|
|
1367
|
+
error: firstError,
|
|
1368
|
+
recoveryContext,
|
|
1369
|
+
});
|
|
1370
|
+
this.log.info("dispatcher: retrying codex turn in a fresh session with recovery context", {
|
|
1371
|
+
agentId: msg.accountId,
|
|
1372
|
+
roomId: msg.conversation.id,
|
|
1373
|
+
topicId: msg.conversation.threadId ?? null,
|
|
1374
|
+
turnId,
|
|
1375
|
+
queueKey,
|
|
1376
|
+
});
|
|
1377
|
+
result = await runRuntime(runtimeText, null);
|
|
1378
|
+
}
|
|
1299
1379
|
}
|
|
1300
1380
|
catch (err) {
|
|
1301
1381
|
threw = err;
|
|
@@ -1477,12 +1557,12 @@ export class Dispatcher {
|
|
|
1477
1557
|
// even when the adapter echoes that id back
|
|
1478
1558
|
// result.newSessionId truthy → upsert the entry
|
|
1479
1559
|
// otherwise → no-op (e.g. codex intentionally never persists)
|
|
1480
|
-
if (
|
|
1560
|
+
if (activeSessionId && effectiveError && !replyText) {
|
|
1481
1561
|
try {
|
|
1482
1562
|
await this.sessionStore.delete(key);
|
|
1483
1563
|
this.log.info("dispatcher: dropped stale runtime session", {
|
|
1484
1564
|
key,
|
|
1485
|
-
prevRuntimeSessionId:
|
|
1565
|
+
prevRuntimeSessionId: activeSessionId,
|
|
1486
1566
|
nextRuntimeSessionId: result.newSessionId || null,
|
|
1487
1567
|
error: effectiveError,
|
|
1488
1568
|
});
|
|
@@ -1509,7 +1589,7 @@ export class Dispatcher {
|
|
|
1509
1589
|
updatedAt: Date.now(),
|
|
1510
1590
|
};
|
|
1511
1591
|
try {
|
|
1512
|
-
const prevRuntimeSessionId =
|
|
1592
|
+
const prevRuntimeSessionId = activeSessionId;
|
|
1513
1593
|
await this.sessionStore.set(session);
|
|
1514
1594
|
this.log.debug("dispatcher: persisted runtime session", {
|
|
1515
1595
|
key,
|
|
@@ -1524,12 +1604,12 @@ export class Dispatcher {
|
|
|
1524
1604
|
});
|
|
1525
1605
|
}
|
|
1526
1606
|
}
|
|
1527
|
-
else if (
|
|
1607
|
+
else if (activeSessionId && effectiveError) {
|
|
1528
1608
|
try {
|
|
1529
1609
|
await this.sessionStore.delete(key);
|
|
1530
1610
|
this.log.info("dispatcher: dropped stale runtime session", {
|
|
1531
1611
|
key,
|
|
1532
|
-
prevRuntimeSessionId:
|
|
1612
|
+
prevRuntimeSessionId: activeSessionId,
|
|
1533
1613
|
error: effectiveError,
|
|
1534
1614
|
});
|
|
1535
1615
|
}
|
|
@@ -2,7 +2,7 @@ import { type ChannelBackoffOptions } from "./channel-manager.js";
|
|
|
2
2
|
import { type DispatcherOptions, type RuntimeFactory } from "./dispatcher.js";
|
|
3
3
|
import { type GatewayLogger } from "./log.js";
|
|
4
4
|
import { type TranscriptWriter } from "./transcript.js";
|
|
5
|
-
import type { ChannelAdapter, GatewayChannelConfig, GatewayConfig, GatewayInboundMessage, GatewayOutboundMessage, GatewayRoute, GatewayRuntimeSnapshot, InboundObserver, MemoryContextBuilder, OutboundObserver, SystemContextBuilder, UserTurnBuilder } from "./types.js";
|
|
5
|
+
import type { ChannelAdapter, GatewayChannelConfig, GatewayConfig, GatewayInboundMessage, GatewayOutboundMessage, GatewayRoute, GatewayRuntimeSnapshot, InboundObserver, MemoryContextBuilder, OutboundObserver, RuntimeRecoveryContextBuilder, SystemContextBuilder, UserTurnBuilder } from "./types.js";
|
|
6
6
|
/** Constructor options for `Gateway`. */
|
|
7
7
|
export interface GatewayBootOptions {
|
|
8
8
|
config: GatewayConfig;
|
|
@@ -25,6 +25,11 @@ export interface GatewayBootOptions {
|
|
|
25
25
|
* resumed runtime sessions get an explicit prompt when memory changes.
|
|
26
26
|
*/
|
|
27
27
|
buildMemoryContext?: MemoryContextBuilder;
|
|
28
|
+
/**
|
|
29
|
+
* Recent room context provider used by dispatcher when it must discard a
|
|
30
|
+
* broken runtime session and retry the same turn in a fresh session.
|
|
31
|
+
*/
|
|
32
|
+
buildRuntimeRecoveryContext?: RuntimeRecoveryContextBuilder;
|
|
28
33
|
/**
|
|
29
34
|
* Observer called after the dispatcher acks each inbound message. Useful
|
|
30
35
|
* for activity tracking or metrics. Errors are logged and swallowed.
|
|
@@ -137,6 +142,16 @@ export declare class Gateway {
|
|
|
137
142
|
* routing, queueing, transcript, and runtime behavior as channel messages.
|
|
138
143
|
*/
|
|
139
144
|
injectInbound(message: GatewayInboundMessage): Promise<void>;
|
|
145
|
+
/**
|
|
146
|
+
* Inject an inbound message while routing replies through a caller-owned
|
|
147
|
+
* channel adapter. Cloud gateway runtime sessions use this to execute a
|
|
148
|
+
* provider message without loading provider credentials inside the sandbox:
|
|
149
|
+
* the temporary adapter captures the runtime's final reply and the always-on
|
|
150
|
+
* ingress service performs the provider send.
|
|
151
|
+
*/
|
|
152
|
+
injectInboundThrough(message: GatewayInboundMessage, channel: ChannelAdapter, ack?: {
|
|
153
|
+
accept: () => Promise<void>;
|
|
154
|
+
}): Promise<void>;
|
|
140
155
|
/**
|
|
141
156
|
* Send a daemon-control initiated outbound message through a registered
|
|
142
157
|
* channel. Used by proactive third-party gateway sends where the runtime
|
package/dist/gateway/gateway.js
CHANGED
|
@@ -69,6 +69,7 @@ export class Gateway {
|
|
|
69
69
|
turnTimeoutMs: opts.turnTimeoutMs,
|
|
70
70
|
buildSystemContext: opts.buildSystemContext,
|
|
71
71
|
buildMemoryContext: opts.buildMemoryContext,
|
|
72
|
+
buildRuntimeRecoveryContext: opts.buildRuntimeRecoveryContext,
|
|
72
73
|
onInbound: opts.onInbound,
|
|
73
74
|
composeUserTurn: opts.composeUserTurn,
|
|
74
75
|
onOutbound: opts.onOutbound,
|
|
@@ -178,6 +179,26 @@ export class Gateway {
|
|
|
178
179
|
async injectInbound(message) {
|
|
179
180
|
await this.dispatcher.handle({ message });
|
|
180
181
|
}
|
|
182
|
+
/**
|
|
183
|
+
* Inject an inbound message while routing replies through a caller-owned
|
|
184
|
+
* channel adapter. Cloud gateway runtime sessions use this to execute a
|
|
185
|
+
* provider message without loading provider credentials inside the sandbox:
|
|
186
|
+
* the temporary adapter captures the runtime's final reply and the always-on
|
|
187
|
+
* ingress service performs the provider send.
|
|
188
|
+
*/
|
|
189
|
+
async injectInboundThrough(message, channel, ack) {
|
|
190
|
+
const previous = this.channelMap.get(channel.id);
|
|
191
|
+
this.channelMap.set(channel.id, channel);
|
|
192
|
+
try {
|
|
193
|
+
await this.dispatcher.handle({ message, ...(ack ? { ack } : {}) });
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
if (previous)
|
|
197
|
+
this.channelMap.set(channel.id, previous);
|
|
198
|
+
else
|
|
199
|
+
this.channelMap.delete(channel.id);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
181
202
|
/**
|
|
182
203
|
* Send a daemon-control initiated outbound message through a registered
|
|
183
204
|
* channel. Used by proactive third-party gateway sends where the runtime
|
|
@@ -24,16 +24,24 @@
|
|
|
24
24
|
const DEFAULT_TTL_MS = 5 * 60 * 1000;
|
|
25
25
|
const FETCH_FAILED = Symbol("fetch_failed");
|
|
26
26
|
/**
|
|
27
|
-
* Force
|
|
27
|
+
* Force direct conversations to `mode: "always"` per design §4.2 — UI never
|
|
28
28
|
* lets the user mute a DM, but a stale cache from before a UX bug is cheap
|
|
29
|
-
* to defend against here.
|
|
29
|
+
* to defend against here. Third-party 1:1 gateway chats have the same
|
|
30
|
+
* expectation: they do not carry BotCord mention metadata, so applying a
|
|
31
|
+
* global mention-only policy would silently drop ordinary direct messages.
|
|
30
32
|
*/
|
|
31
|
-
function
|
|
32
|
-
if (roomId && roomId
|
|
33
|
+
function maybeForceDirectConversation(roomId, policy) {
|
|
34
|
+
if (roomId && isDirectConversation(roomId) && policy.mode !== "always") {
|
|
33
35
|
return { ...policy, mode: "always" };
|
|
34
36
|
}
|
|
35
37
|
return policy;
|
|
36
38
|
}
|
|
39
|
+
function isDirectConversation(roomId) {
|
|
40
|
+
return (roomId.startsWith("rm_dm_") ||
|
|
41
|
+
roomId.startsWith("telegram:user:") ||
|
|
42
|
+
roomId.startsWith("wechat:user:") ||
|
|
43
|
+
roomId.startsWith("feishu:user:"));
|
|
44
|
+
}
|
|
37
45
|
function defaultPolicy() {
|
|
38
46
|
return { mode: "always", keywords: [] };
|
|
39
47
|
}
|
|
@@ -65,10 +73,10 @@ export class PolicyResolver {
|
|
|
65
73
|
return defaultPolicy();
|
|
66
74
|
const policy = fetched ?? defaultPolicy();
|
|
67
75
|
this.cache.set(cacheKey(agentId, roomId), {
|
|
68
|
-
policy:
|
|
76
|
+
policy: maybeForceDirectConversation(roomId, policy),
|
|
69
77
|
expiresAt: now + this.ttlMs,
|
|
70
78
|
});
|
|
71
|
-
return
|
|
79
|
+
return maybeForceDirectConversation(roomId, policy);
|
|
72
80
|
}
|
|
73
81
|
// 3. No room override known — inherit from the cached agent-wide global.
|
|
74
82
|
// Without this layer, group messages collapsed to mode=always whenever
|
|
@@ -77,7 +85,7 @@ export class PolicyResolver {
|
|
|
77
85
|
const globalKey = cacheKey(agentId, null);
|
|
78
86
|
const globalHit = this.cache.get(globalKey);
|
|
79
87
|
if (globalHit && globalHit.expiresAt > now) {
|
|
80
|
-
return
|
|
88
|
+
return maybeForceDirectConversation(roomId, globalHit.policy);
|
|
81
89
|
}
|
|
82
90
|
// 4. Cold start for global.
|
|
83
91
|
const fetched = await this.safeFetch(() => this.fetchGlobal(agentId));
|
|
@@ -85,7 +93,7 @@ export class PolicyResolver {
|
|
|
85
93
|
return defaultPolicy();
|
|
86
94
|
const policy = fetched ?? defaultPolicy();
|
|
87
95
|
this.cache.set(globalKey, { policy, expiresAt: now + this.ttlMs });
|
|
88
|
-
return
|
|
96
|
+
return maybeForceDirectConversation(roomId, policy);
|
|
89
97
|
}
|
|
90
98
|
async safeFetch(fn) {
|
|
91
99
|
try {
|
|
@@ -113,7 +121,7 @@ export class PolicyResolver {
|
|
|
113
121
|
put(agentId, roomId, policy) {
|
|
114
122
|
const key = cacheKey(agentId, roomId);
|
|
115
123
|
this.cache.set(key, {
|
|
116
|
-
policy:
|
|
124
|
+
policy: maybeForceDirectConversation(roomId, policy),
|
|
117
125
|
expiresAt: Date.now() + this.ttlMs,
|
|
118
126
|
});
|
|
119
127
|
}
|
|
@@ -316,14 +316,17 @@ export class DeepseekTuiAdapter {
|
|
|
316
316
|
if (eventName === "message.delta") {
|
|
317
317
|
append(stringField(payload, "content") ?? "");
|
|
318
318
|
}
|
|
319
|
-
else if (eventName === "item.delta" && payload
|
|
320
|
-
append(
|
|
319
|
+
else if (eventName === "item.delta" && isAgentMessageDelta(payload)) {
|
|
320
|
+
append(extractDeepseekDelta(payload));
|
|
321
321
|
}
|
|
322
322
|
if (eventName === "turn.started" || embeddedDeepseekEvent(payload) === "turn.started") {
|
|
323
323
|
opts.onStatus?.({ kind: "thinking", phase: "started", label: "Thinking" });
|
|
324
324
|
}
|
|
325
|
-
else if (eventName === "tool.started" || isToolStarted(payload)) {
|
|
326
|
-
const label = stringField(payload, "name") ??
|
|
325
|
+
else if (eventName === "tool.started" || isToolStarted(eventName, payload)) {
|
|
326
|
+
const label = stringField(payload, "name") ??
|
|
327
|
+
stringField(payload?.tool, "name") ??
|
|
328
|
+
stringField(payload?.payload?.tool, "name") ??
|
|
329
|
+
"tool";
|
|
327
330
|
opts.onStatus?.({ kind: "thinking", phase: "updated", label });
|
|
328
331
|
}
|
|
329
332
|
else if (isDeepseekTerminalEvent(eventName, payload)) {
|
|
@@ -385,15 +388,18 @@ function normalizeDeepseekEvent(eventName, payload, seq) {
|
|
|
385
388
|
if (eventName === "message.delta") {
|
|
386
389
|
return { raw: { event: eventName, payload }, kind: "assistant_text", seq };
|
|
387
390
|
}
|
|
388
|
-
if (eventName === "tool.started" || isToolStarted(payload)) {
|
|
391
|
+
if (eventName === "tool.started" || isToolStarted(eventName, payload)) {
|
|
389
392
|
return { raw: { event: eventName, payload }, kind: "tool_use", seq };
|
|
390
393
|
}
|
|
391
|
-
if (eventName === "tool.completed" || isToolCompleted(payload)) {
|
|
394
|
+
if (eventName === "tool.completed" || isToolCompleted(eventName, payload)) {
|
|
392
395
|
return { raw: { event: eventName, payload }, kind: "tool_result", seq };
|
|
393
396
|
}
|
|
394
|
-
if (eventName === "item.delta" && payload
|
|
397
|
+
if (eventName === "item.delta" && isAgentMessageDelta(payload)) {
|
|
395
398
|
return { raw: { event: eventName, payload }, kind: "assistant_text", seq };
|
|
396
399
|
}
|
|
400
|
+
if (eventName === "item.completed" && isAgentReasoningItem(payload)) {
|
|
401
|
+
return { raw: { event: eventName, payload }, kind: "thinking", seq };
|
|
402
|
+
}
|
|
397
403
|
if (eventName === "turn.started" || eventName === "status" || embeddedDeepseekEvent(payload) === "turn.started") {
|
|
398
404
|
return { raw: { event: eventName, payload }, kind: "system", seq };
|
|
399
405
|
}
|
|
@@ -416,14 +422,27 @@ function isDeepseekTerminalEvent(eventName, payload) {
|
|
|
416
422
|
embedded === "turn.done" ||
|
|
417
423
|
embedded === "done");
|
|
418
424
|
}
|
|
419
|
-
function isToolStarted(payload) {
|
|
420
|
-
return
|
|
425
|
+
function isToolStarted(eventName, payload) {
|
|
426
|
+
return ((eventName === "item.started" && (!!payload?.tool || payload?.item?.kind === "tool_call")) ||
|
|
427
|
+
(payload?.event === "item.started" && !!payload?.payload?.tool));
|
|
421
428
|
}
|
|
422
|
-
function isToolCompleted(payload) {
|
|
423
|
-
const kind = payload?.payload?.item?.kind;
|
|
424
|
-
return ((
|
|
429
|
+
function isToolCompleted(eventName, payload) {
|
|
430
|
+
const kind = payload?.payload?.item?.kind ?? payload?.item?.kind;
|
|
431
|
+
return ((eventName === "item.completed" ||
|
|
432
|
+
eventName === "item.failed" ||
|
|
433
|
+
payload?.event === "item.completed" ||
|
|
434
|
+
payload?.event === "item.failed") &&
|
|
425
435
|
(kind === "tool_call" || kind === "file_change" || kind === "command_execution"));
|
|
426
436
|
}
|
|
437
|
+
function isAgentMessageDelta(payload) {
|
|
438
|
+
return payload?.kind === "agent_message" || payload?.payload?.kind === "agent_message";
|
|
439
|
+
}
|
|
440
|
+
function isAgentReasoningItem(payload) {
|
|
441
|
+
return payload?.item?.kind === "agent_reasoning" || payload?.payload?.item?.kind === "agent_reasoning";
|
|
442
|
+
}
|
|
443
|
+
function extractDeepseekDelta(payload) {
|
|
444
|
+
return stringField(payload, "delta") ?? stringField(payload?.payload, "delta") ?? "";
|
|
445
|
+
}
|
|
427
446
|
function extractDeepseekError(eventName, payload) {
|
|
428
447
|
if (eventName === "error") {
|
|
429
448
|
return (stringField(payload, "message") ??
|
package/dist/gateway/types.d.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import type { GatewayLogger } from "./log.js";
|
|
2
|
+
import type { GatewayInboundEnvelope as CanonicalGatewayInboundEnvelope, GatewayInboundMessage as CanonicalGatewayInboundMessage, GatewayOutboundAttachment as CanonicalGatewayOutboundAttachment, GatewayOutboundMessage as CanonicalGatewayOutboundMessage, RuntimeGatewayProvider } from "@botcord/protocol-core";
|
|
3
|
+
export type GatewayInboundMessage = CanonicalGatewayInboundMessage;
|
|
4
|
+
export type GatewayInboundEnvelope = CanonicalGatewayInboundEnvelope;
|
|
5
|
+
export type GatewayOutboundAttachment = CanonicalGatewayOutboundAttachment;
|
|
6
|
+
export type GatewayOutboundMessage = CanonicalGatewayOutboundMessage;
|
|
2
7
|
/** Set of predicates matched against a normalized inbound message to pick a route. */
|
|
3
8
|
export interface RouteMatch {
|
|
4
9
|
channel?: string;
|
|
@@ -69,41 +74,6 @@ export interface GatewayConfig {
|
|
|
69
74
|
managedRoutes?: GatewayRoute[];
|
|
70
75
|
streamBlocks?: boolean;
|
|
71
76
|
}
|
|
72
|
-
/** Normalized inbound message produced by a channel adapter for the dispatcher. */
|
|
73
|
-
export interface GatewayInboundMessage {
|
|
74
|
-
id: string;
|
|
75
|
-
/** Channel adapter id (`ChannelAdapter.id`), not channel type. */
|
|
76
|
-
channel: string;
|
|
77
|
-
accountId: string;
|
|
78
|
-
conversation: {
|
|
79
|
-
id: string;
|
|
80
|
-
kind: "direct" | "group";
|
|
81
|
-
title?: string;
|
|
82
|
-
threadId?: string | null;
|
|
83
|
-
};
|
|
84
|
-
sender: {
|
|
85
|
-
id: string;
|
|
86
|
-
name?: string;
|
|
87
|
-
kind: "user" | "agent" | "system";
|
|
88
|
-
};
|
|
89
|
-
text?: string;
|
|
90
|
-
raw: unknown;
|
|
91
|
-
replyTo?: string | null;
|
|
92
|
-
mentioned?: boolean;
|
|
93
|
-
receivedAt: number;
|
|
94
|
-
trace?: {
|
|
95
|
-
id: string;
|
|
96
|
-
streamable?: boolean;
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
/** Inbound envelope wrapping a normalized message with optional upstream ack callbacks. */
|
|
100
|
-
export interface GatewayInboundEnvelope {
|
|
101
|
-
message: GatewayInboundMessage;
|
|
102
|
-
ack?: {
|
|
103
|
-
accept(): Promise<void>;
|
|
104
|
-
reject?(reason: string): Promise<void>;
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
77
|
/**
|
|
108
78
|
* Channel-agnostic hook that produces a system-context string for a turn.
|
|
109
79
|
* Called before every `runtime.run(...)`; returned value is passed through
|
|
@@ -137,33 +107,18 @@ export interface MemoryContextSnapshot {
|
|
|
137
107
|
version: string;
|
|
138
108
|
}
|
|
139
109
|
export type MemoryContextBuilder = (message: GatewayInboundMessage) => Promise<MemoryContextSnapshot | null | undefined> | MemoryContextSnapshot | null | undefined;
|
|
110
|
+
/**
|
|
111
|
+
* Optional hook used after a runtime session is discarded and retried fresh.
|
|
112
|
+
* The daemon implementation can pull recent room messages from Hub; gateway
|
|
113
|
+
* core treats the returned string as opaque recovery context.
|
|
114
|
+
*/
|
|
115
|
+
export type RuntimeRecoveryContextBuilder = (message: GatewayInboundMessage) => Promise<string | null | undefined> | string | null | undefined;
|
|
140
116
|
/**
|
|
141
117
|
* Optional hook fired after the dispatcher dispatches a reply to a channel.
|
|
142
118
|
* Intended for outbound bookkeeping (loop-risk tracking, metrics). Errors
|
|
143
119
|
* are caught and logged so observer failures never break the turn.
|
|
144
120
|
*/
|
|
145
121
|
export type OutboundObserver = (message: GatewayOutboundMessage) => Promise<void> | void;
|
|
146
|
-
/** Outbound reply payload passed to `ChannelAdapter.send()`. */
|
|
147
|
-
export interface GatewayOutboundAttachment {
|
|
148
|
-
/** Local daemon-readable file path. */
|
|
149
|
-
filePath?: string;
|
|
150
|
-
/** In-memory bytes, primarily for tests and in-process tool callers. */
|
|
151
|
-
data?: Uint8Array;
|
|
152
|
-
filename?: string;
|
|
153
|
-
contentType?: string;
|
|
154
|
-
kind?: "image" | "file" | "video";
|
|
155
|
-
}
|
|
156
|
-
export interface GatewayOutboundMessage {
|
|
157
|
-
channel: string;
|
|
158
|
-
accountId: string;
|
|
159
|
-
conversationId: string;
|
|
160
|
-
threadId?: string | null;
|
|
161
|
-
type?: "message" | "error";
|
|
162
|
-
text: string;
|
|
163
|
-
attachments?: GatewayOutboundAttachment[];
|
|
164
|
-
replyTo?: string | null;
|
|
165
|
-
traceId?: string | null;
|
|
166
|
-
}
|
|
167
122
|
/** Per-channel status snapshot exposed for `status`/`doctor` style output. */
|
|
168
123
|
export interface ChannelStatusSnapshot {
|
|
169
124
|
channel: string;
|
|
@@ -176,7 +131,7 @@ export interface ChannelStatusSnapshot {
|
|
|
176
131
|
lastStopAt?: number;
|
|
177
132
|
lastError?: string | null;
|
|
178
133
|
/** Third-party provider id when this channel is not the built-in BotCord. */
|
|
179
|
-
provider?:
|
|
134
|
+
provider?: RuntimeGatewayProvider;
|
|
180
135
|
/** Last time the adapter polled the upstream provider (ms epoch). */
|
|
181
136
|
lastPollAt?: number;
|
|
182
137
|
/** Last time the adapter accepted an inbound message (ms epoch). */
|
package/dist/gateway-control.js
CHANGED
|
@@ -108,13 +108,16 @@ export function createGatewayControl(ctx) {
|
|
|
108
108
|
if (!loginId) {
|
|
109
109
|
return badParams("upsert_gateway: wechat requires loginId");
|
|
110
110
|
}
|
|
111
|
-
const
|
|
112
|
-
if (
|
|
111
|
+
const resolved = sessions.resolve(loginId);
|
|
112
|
+
if (resolved.state !== "live") {
|
|
113
113
|
return {
|
|
114
114
|
ok: false,
|
|
115
|
-
error:
|
|
115
|
+
error: resolved.state === "missing"
|
|
116
|
+
? { code: "login_missing", message: `wechat login session "${loginId}" not found` }
|
|
117
|
+
: { code: "login_expired", message: `wechat login session "${loginId}" expired` },
|
|
116
118
|
};
|
|
117
119
|
}
|
|
120
|
+
const session = resolved.session;
|
|
118
121
|
if (session.provider !== "wechat") {
|
|
119
122
|
return badParams(`upsert_gateway: login session provider "${session.provider}" != "wechat"`);
|
|
120
123
|
}
|
|
@@ -143,13 +146,16 @@ export function createGatewayControl(ctx) {
|
|
|
143
146
|
if (!loginId) {
|
|
144
147
|
return badParams("upsert_gateway: feishu requires loginId");
|
|
145
148
|
}
|
|
146
|
-
const
|
|
147
|
-
if (
|
|
149
|
+
const resolved = sessions.resolve(loginId);
|
|
150
|
+
if (resolved.state !== "live") {
|
|
148
151
|
return {
|
|
149
152
|
ok: false,
|
|
150
|
-
error:
|
|
153
|
+
error: resolved.state === "missing"
|
|
154
|
+
? { code: "login_missing", message: `feishu login session "${loginId}" not found` }
|
|
155
|
+
: { code: "login_expired", message: `feishu login session "${loginId}" expired` },
|
|
151
156
|
};
|
|
152
157
|
}
|
|
158
|
+
const session = resolved.session;
|
|
153
159
|
if (session.provider !== "feishu") {
|
|
154
160
|
return badParams(`upsert_gateway: login session provider "${session.provider}" != "feishu"`);
|
|
155
161
|
}
|
|
@@ -659,13 +665,16 @@ export function createGatewayControl(ctx) {
|
|
|
659
665
|
if (!params.accountId || typeof params.accountId !== "string") {
|
|
660
666
|
return badParams("gateway_recent_senders: accountId is required");
|
|
661
667
|
}
|
|
662
|
-
const
|
|
663
|
-
if (
|
|
668
|
+
const resolved = sessions.resolve(params.loginId);
|
|
669
|
+
if (resolved.state !== "live") {
|
|
664
670
|
return {
|
|
665
671
|
ok: false,
|
|
666
|
-
error:
|
|
672
|
+
error: resolved.state === "missing"
|
|
673
|
+
? { code: "login_missing", message: `wechat login session "${params.loginId}" not found` }
|
|
674
|
+
: { code: "login_expired", message: `wechat login session "${params.loginId}" expired` },
|
|
667
675
|
};
|
|
668
676
|
}
|
|
677
|
+
const session = resolved.session;
|
|
669
678
|
if (session.provider !== "wechat") {
|
|
670
679
|
return badParams("gateway_recent_senders: provider does not match login session");
|
|
671
680
|
}
|
package/dist/provision.d.ts
CHANGED
|
@@ -182,10 +182,14 @@ interface HelloIdentityResult {
|
|
|
182
182
|
updated: number;
|
|
183
183
|
skipped: number;
|
|
184
184
|
}
|
|
185
|
+
interface RuntimeSnapshotCtx {
|
|
186
|
+
gateway?: Gateway;
|
|
187
|
+
}
|
|
185
188
|
/**
|
|
186
189
|
* Reconcile every agent identity carried by the `hello.agents` snapshot
|
|
187
|
-
* against the on-disk `identity.md
|
|
188
|
-
* file-system error for one agent never
|
|
190
|
+
* against the on-disk `identity.md` and credentials runtime selectors.
|
|
191
|
+
* Best-effort: a malformed entry or a file-system error for one agent never
|
|
192
|
+
* aborts the rest.
|
|
189
193
|
*
|
|
190
194
|
* Identity-snapshot semantics intentionally only touch the metadata
|
|
191
195
|
* line + Bio body — Role/Boundaries paragraphs the user authored locally
|
|
@@ -193,7 +197,7 @@ interface HelloIdentityResult {
|
|
|
193
197
|
* (agent provisioned on a different daemon, or workspace cleared) are
|
|
194
198
|
* silently skipped.
|
|
195
199
|
*/
|
|
196
|
-
export declare function applyHelloIdentitySnapshot(snapshot: AgentIdentitySnapshot[] | undefined): HelloIdentityResult;
|
|
200
|
+
export declare function applyHelloIdentitySnapshot(snapshot: AgentIdentitySnapshot[] | undefined, ctx?: RuntimeSnapshotCtx): HelloIdentityResult;
|
|
197
201
|
interface ReloadResult {
|
|
198
202
|
reloaded: true;
|
|
199
203
|
added: string[];
|