typeclaw 0.43.0 → 0.43.1
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/package.json +2 -2
- package/src/agent/index.ts +9 -2
- package/src/agent/system-prompt.ts +36 -0
- package/src/channels/adapters/discord-bot.ts +76 -3
- package/src/channels/adapters/discord.ts +15 -2
- package/src/channels/manager.ts +9 -1
- package/src/channels/router.ts +366 -77
- package/src/channels/schema.ts +24 -0
- package/src/channels/types.ts +8 -5
- package/src/cli/channel.ts +40 -13
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "typeclaw",
|
|
3
|
-
"version": "0.43.
|
|
3
|
+
"version": "0.43.1",
|
|
4
4
|
"homepage": "https://github.com/typeclaw/typeclaw#readme",
|
|
5
5
|
"bugs": {
|
|
6
6
|
"url": "https://github.com/typeclaw/typeclaw/issues"
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"@mariozechner/pi-tui": "^0.73.1",
|
|
51
51
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
52
52
|
"@mozilla/readability": "^0.6.0",
|
|
53
|
-
"agent-messenger": "^2.
|
|
53
|
+
"agent-messenger": "^2.29.0",
|
|
54
54
|
"cheerio": "^1.2.0",
|
|
55
55
|
"citty": "^0.2.2",
|
|
56
56
|
"cron-parser": "^5.5.0",
|
package/src/agent/index.ts
CHANGED
|
@@ -66,6 +66,8 @@ import {
|
|
|
66
66
|
buildSlimSystemPrompt,
|
|
67
67
|
DEFAULT_SUBAGENT_ROSTER,
|
|
68
68
|
renderRuntimeBlock,
|
|
69
|
+
renderRuntimeNondisclosureRule,
|
|
70
|
+
stripRuntimeIdentityProse,
|
|
69
71
|
} from './system-prompt'
|
|
70
72
|
import { attachToolNotFoundNudge } from './tool-not-found-nudge'
|
|
71
73
|
import { createBudgetState, type ToolResultBudget, wrapToolDefinitionWithBudget } from './tool-result-budget'
|
|
@@ -914,10 +916,12 @@ export async function createOverrideResourceLoader(
|
|
|
914
916
|
permissions?: PermissionService,
|
|
915
917
|
runtimeVersion?: string,
|
|
916
918
|
): Promise<DefaultResourceLoader> {
|
|
917
|
-
const
|
|
918
|
-
|
|
919
|
+
const branding = getConfig().branding
|
|
920
|
+
const withRuntime = branding
|
|
921
|
+
? runtimeVersion !== undefined
|
|
919
922
|
? `${systemPrompt}\n\n${renderRuntimeBlock(runtimeVersion)}`
|
|
920
923
|
: systemPrompt
|
|
924
|
+
: `${stripRuntimeIdentityProse(systemPrompt)}\n\n${renderRuntimeNondisclosureRule()}`
|
|
921
925
|
const finalPrompt = withOrigin(withRuntime, origin, permissions)
|
|
922
926
|
const loader = new DefaultResourceLoader({
|
|
923
927
|
cwd: process.cwd(),
|
|
@@ -1051,6 +1055,9 @@ export function composeSystemPrompt(parts: SystemPromptComposition): string {
|
|
|
1051
1055
|
if (branding && parts.runtimeVersion !== undefined) {
|
|
1052
1056
|
prompt = `${prompt}\n\n${renderRuntimeBlock(parts.runtimeVersion)}`
|
|
1053
1057
|
}
|
|
1058
|
+
if (!branding) {
|
|
1059
|
+
prompt = `${prompt}\n\n${renderRuntimeNondisclosureRule()}`
|
|
1060
|
+
}
|
|
1054
1061
|
if (parts.origin !== undefined) {
|
|
1055
1062
|
prompt = `${prompt}\n\n${renderSessionOrigin(parts.origin, Date.now(), parts.roleContext)}`
|
|
1056
1063
|
}
|
|
@@ -184,6 +184,42 @@ export function renderRuntimeBlock(version: string): string {
|
|
|
184
184
|
TypeClaw runtime version: ${version}.`
|
|
185
185
|
}
|
|
186
186
|
|
|
187
|
+
// Appended to the system prompt ONLY when `config.branding` is false. Branding
|
|
188
|
+
// off rephrases the opening and drops the version block, but the literal
|
|
189
|
+
// "typeclaw" still reaches the model through functional tokens it can't lose
|
|
190
|
+
// without breaking: bundled skill names (`typeclaw-render-pdf` etc.), the
|
|
191
|
+
// operator CLI (`typeclaw logs -f`), and `typeclaw.json`. Aliasing every one
|
|
192
|
+
// would break skill/tool resolution, so instead of hiding the tokens we tell
|
|
193
|
+
// the model not to surface them as its identity. English-authored on purpose:
|
|
194
|
+
// this is an instruction TO the model (applied in any reply language), not
|
|
195
|
+
// user-text pattern matching, so AGENTS.md's multi-language matching rule does
|
|
196
|
+
// not apply.
|
|
197
|
+
export function renderRuntimeNondisclosureRule(): string {
|
|
198
|
+
return `## Runtime disclosure
|
|
199
|
+
|
|
200
|
+
The operator set \`branding: false\`. Never reveal, name, or hint at the runtime,
|
|
201
|
+
platform, framework, or vendor hosting you — in any language. You are the agent
|
|
202
|
+
defined by IDENTITY.md and SOUL.md; if asked what you run on, who built you, or
|
|
203
|
+
your stack/model/provider, decline briefly and stay in character.
|
|
204
|
+
|
|
205
|
+
Internal tokens you use for real work (skill names, the operator CLI, config
|
|
206
|
+
filenames) are implementation details, not your identity — use them, but never
|
|
207
|
+
surface them as the answer to "what are you running on?"`
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Bundled subagent prompts (scout/operator/reviewer/planner/researcher/explorer)
|
|
211
|
+
// open with hardcoded identity prose — "running inside TypeClaw" and, in the
|
|
212
|
+
// planner, "TypeClaw ships a `reviewer`". The nondisclosure rule tells the model
|
|
213
|
+
// not to volunteer the runtime, but that prose STATES it outright, so a
|
|
214
|
+
// branding-off subagent still reads its own name in the first sentence. This
|
|
215
|
+
// strips exactly those two identity phrases (not functional `typeclaw.json`-style
|
|
216
|
+
// tokens) from an override prompt when branding is off, so the rule is not
|
|
217
|
+
// fighting the prose. Kept as exact-literal replacements rather than a broad
|
|
218
|
+
// /typeclaw/i regex precisely so functional tokens survive untouched.
|
|
219
|
+
export function stripRuntimeIdentityProse(prompt: string): string {
|
|
220
|
+
return prompt.replaceAll(' running inside TypeClaw', '').replaceAll('TypeClaw ships a', 'The runtime ships a')
|
|
221
|
+
}
|
|
222
|
+
|
|
187
223
|
// Wall-clock anchor injected into the **user turn**, not the system prompt.
|
|
188
224
|
//
|
|
189
225
|
// Why per-turn instead of session-creation: long-lived channel sessions can
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
|
+
|
|
1
3
|
import { DiscordBotClient, DiscordBotListener } from 'agent-messenger/discordbot'
|
|
2
4
|
import {
|
|
3
5
|
DiscordIntent,
|
|
@@ -742,13 +744,26 @@ function clampLimit(requested: number, max: number): number {
|
|
|
742
744
|
// the upload error (the file the agent wanted to share is the load-bearing
|
|
743
745
|
// part of the message). The text post is best-effort and only attempted
|
|
744
746
|
// after every upload succeeds.
|
|
747
|
+
//
|
|
748
|
+
// Native reply on an attachment-only send: the SDK's `uploadFile` cannot carry
|
|
749
|
+
// a `message_reference`, so a reply-arrow on a pure-attachment reply is
|
|
750
|
+
// impossible through it. When `msg.replyTo` is set AND there is no text send to
|
|
751
|
+
// carry the reference, the FIRST file upload goes through a raw multipart POST
|
|
752
|
+
// with a `payload_json.message_reference` instead (uploadFirstFileWithReply) so
|
|
753
|
+
// the file message itself is the native reply. Only the first file carries it —
|
|
754
|
+
// otherwise Discord renders one reply-arrow per attachment. Remaining files, and
|
|
755
|
+
// every upload on a send that also has text (the text send carries the
|
|
756
|
+
// reference), stay on the SDK path.
|
|
745
757
|
export function createOutboundCallback(deps: {
|
|
746
758
|
client: Pick<DiscordBotClient, 'sendMessage' | 'uploadFile'>
|
|
747
759
|
logger: DiscordBotAdapterLogger
|
|
748
760
|
formatChannelTag: (workspace: string, chat: string) => Promise<string>
|
|
761
|
+
token: string
|
|
749
762
|
resolvePath?: (path: string) => string
|
|
763
|
+
fetchImpl?: typeof fetch
|
|
750
764
|
}): OutboundCallback {
|
|
751
|
-
const { client, logger, formatChannelTag, resolvePath } = deps
|
|
765
|
+
const { client, logger, formatChannelTag, token, resolvePath } = deps
|
|
766
|
+
const fetchImpl = deps.fetchImpl ?? fetch
|
|
752
767
|
return async (msg: OutboundMessage): Promise<SendResult> => {
|
|
753
768
|
if (msg.adapter !== 'discord-bot') {
|
|
754
769
|
return { ok: false, error: `unknown adapter: ${msg.adapter}` }
|
|
@@ -763,10 +778,25 @@ export function createOutboundCallback(deps: {
|
|
|
763
778
|
`[discord-bot] outbound ${tag} text_len=${text.length} attachments=${attachments.length}${msg.thread ? ` thread=${msg.thread}` : ''}`,
|
|
764
779
|
)
|
|
765
780
|
|
|
766
|
-
|
|
781
|
+
// Only a textless send lets a file carry the native reply: when text is
|
|
782
|
+
// present, the reference rides on the text send instead (below), so files
|
|
783
|
+
// must NOT also reference the parent or Discord shows two reply-arrows.
|
|
784
|
+
const replyOnFirstFile = text === '' ? msg.replyTo?.externalMessageId : undefined
|
|
785
|
+
|
|
786
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
767
787
|
const path = resolvePath ? resolvePath(attachment.path) : attachment.path
|
|
788
|
+
const referenceThisFile = index === 0 ? replyOnFirstFile : undefined
|
|
768
789
|
try {
|
|
769
|
-
const file =
|
|
790
|
+
const file =
|
|
791
|
+
referenceThisFile !== undefined
|
|
792
|
+
? await uploadFirstFileWithReply({
|
|
793
|
+
channelId: msg.chat,
|
|
794
|
+
path,
|
|
795
|
+
replyToId: referenceThisFile,
|
|
796
|
+
token,
|
|
797
|
+
fetchImpl,
|
|
798
|
+
})
|
|
799
|
+
: await client.uploadFile(msg.chat, path)
|
|
770
800
|
logger.info(`[discord-bot] uploaded id=${file.id} filename=${file.filename} size=${file.size} ${tag}`)
|
|
771
801
|
if (msg.thread) {
|
|
772
802
|
logger.warn(
|
|
@@ -804,6 +834,47 @@ export function createOutboundCallback(deps: {
|
|
|
804
834
|
}
|
|
805
835
|
}
|
|
806
836
|
|
|
837
|
+
type DiscordCreateMessageWithAttachments = {
|
|
838
|
+
attachments?: DiscordFile[]
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// Raw multipart create-message so a pure-attachment reply carries a native
|
|
842
|
+
// `message_reference`. Mirrors the SDK's `uploadFile` wire shape (`files[0]`)
|
|
843
|
+
// and adds a `payload_json` field — Discord merges JSON body fields from
|
|
844
|
+
// `payload_json` with the multipart file parts, which is the only documented
|
|
845
|
+
// way to attach `message_reference` to a file upload. Returns the created
|
|
846
|
+
// message's first attachment as a `DiscordFile`, matching `client.uploadFile`
|
|
847
|
+
// so the caller's logging/typing is identical on both paths.
|
|
848
|
+
async function uploadFirstFileWithReply(args: {
|
|
849
|
+
channelId: string
|
|
850
|
+
path: string
|
|
851
|
+
replyToId: string
|
|
852
|
+
token: string
|
|
853
|
+
fetchImpl: typeof fetch
|
|
854
|
+
}): Promise<DiscordFile> {
|
|
855
|
+
const fileBuffer = await readFile(args.path)
|
|
856
|
+
const filename = args.path.split('/').pop() ?? 'file'
|
|
857
|
+
const form = new FormData()
|
|
858
|
+
form.append('payload_json', JSON.stringify({ message_reference: { message_id: args.replyToId } }))
|
|
859
|
+
form.append('files[0]', new Blob([new Uint8Array(fileBuffer)]), filename)
|
|
860
|
+
|
|
861
|
+
const response = await args.fetchImpl(`${DISCORD_API_BASE}/channels/${args.channelId}/messages`, {
|
|
862
|
+
method: 'POST',
|
|
863
|
+
headers: { Authorization: `Bot ${args.token}` },
|
|
864
|
+
body: form,
|
|
865
|
+
})
|
|
866
|
+
if (!response.ok) {
|
|
867
|
+
const body = await response.text().catch(() => '')
|
|
868
|
+
throw new Error(`http ${response.status}${body ? `: ${body.slice(0, 200)}` : ''}`)
|
|
869
|
+
}
|
|
870
|
+
const message = (await response.json()) as DiscordCreateMessageWithAttachments
|
|
871
|
+
const first = message.attachments?.[0]
|
|
872
|
+
if (first === undefined) {
|
|
873
|
+
throw new Error('upload succeeded but no attachments returned')
|
|
874
|
+
}
|
|
875
|
+
return first
|
|
876
|
+
}
|
|
877
|
+
|
|
807
878
|
// Discord CDN URLs (`cdn.discordapp.com/attachments/...`) are signed and
|
|
808
879
|
// expire (~24h). Sending the bot token alongside makes no difference for
|
|
809
880
|
// public CDN URLs (Discord ignores it), but is required for the rare
|
|
@@ -999,6 +1070,8 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
|
|
|
999
1070
|
client,
|
|
1000
1071
|
logger,
|
|
1001
1072
|
formatChannelTag,
|
|
1073
|
+
token: options.token,
|
|
1074
|
+
fetchImpl,
|
|
1002
1075
|
})
|
|
1003
1076
|
|
|
1004
1077
|
const fetchAttachmentCallback = createFetchAttachmentCallback({ token: options.token, logger })
|
|
@@ -75,13 +75,26 @@ export function createDiscordOutboundCallback(deps: {
|
|
|
75
75
|
if (text === '' && attachments.length === 0) return { ok: false, error: 'message has neither text nor attachments' }
|
|
76
76
|
const tag = await deps.formatChannelTag(msg.chat)
|
|
77
77
|
deps.logger.info(`[discord] outbound ${tag} text_len=${text.length} attachments=${attachments.length}`)
|
|
78
|
+
|
|
79
|
+
// The native reply reference rides on exactly ONE message so Discord shows a
|
|
80
|
+
// single reply-arrow: the first text chunk when there is text, otherwise the
|
|
81
|
+
// first file upload. Every later chunk/file posts bare.
|
|
82
|
+
const replyTo = msg.replyTo?.externalMessageId
|
|
83
|
+
const replyOnFirstFile = text === '' ? replyTo : undefined
|
|
84
|
+
const replyOption = (reference: string | undefined): { reply_to: string } | undefined =>
|
|
85
|
+
reference !== undefined ? { reply_to: reference } : undefined
|
|
78
86
|
try {
|
|
79
87
|
// Attachments first, then text — Discord's upstream uploadFile takes no
|
|
80
88
|
// content body, so a failed upload must not leave a text-only message
|
|
81
89
|
// already posted (see OutboundMessage.attachments contract).
|
|
82
|
-
for (const attachment of attachments
|
|
90
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
91
|
+
await deps.client.uploadFile(msg.chat, attachment.path, replyOption(index === 0 ? replyOnFirstFile : undefined))
|
|
92
|
+
}
|
|
83
93
|
if (text !== '') {
|
|
84
|
-
|
|
94
|
+
const chunks = chunkMarkdown(text, 2_000)
|
|
95
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
96
|
+
await deps.client.sendMessage(msg.chat, chunk, replyOption(index === 0 ? replyTo : undefined))
|
|
97
|
+
}
|
|
85
98
|
}
|
|
86
99
|
return { ok: true }
|
|
87
100
|
} catch (err) {
|
package/src/channels/manager.ts
CHANGED
|
@@ -482,7 +482,13 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
482
482
|
// the sum of each adapter's connect latency instead of just the slowest.
|
|
483
483
|
const starts = ADAPTER_IDS.flatMap((name) => {
|
|
484
484
|
const adapterCfg = cfg[name]
|
|
485
|
-
|
|
485
|
+
if (adapterCfg === undefined) return []
|
|
486
|
+
// Mark configured up front, regardless of start outcome: a failed start
|
|
487
|
+
// (e.g. expired token) never registers a history callback, and the router
|
|
488
|
+
// uses this flag to answer "configured but unavailable" instead of the
|
|
489
|
+
// misleading "not supported".
|
|
490
|
+
router.setAdapterConfigured(name, adapterCfg.enabled !== false)
|
|
491
|
+
return [runSerially(name, () => startAdapter(name, adapterCfg))]
|
|
486
492
|
})
|
|
487
493
|
// Await every launched start to settle BEFORE surfacing a failure.
|
|
488
494
|
// `startAdapter` converts expected per-adapter failures to `false`, so a
|
|
@@ -528,11 +534,13 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
528
534
|
const desired = cfg[name]
|
|
529
535
|
const current = live.get(name)
|
|
530
536
|
if (desired === undefined || desired.enabled === false) {
|
|
537
|
+
router.setAdapterConfigured(name, false)
|
|
531
538
|
if (current) {
|
|
532
539
|
await runSerially(name, () => stopAdapter(name))
|
|
533
540
|
stopped.push(name)
|
|
534
541
|
}
|
|
535
542
|
} else if (!current) {
|
|
543
|
+
router.setAdapterConfigured(name, true)
|
|
536
544
|
const ok = await runSerially(name, () => startAdapter(name, desired))
|
|
537
545
|
if (ok) started.push(name)
|
|
538
546
|
} else {
|
package/src/channels/router.ts
CHANGED
|
@@ -62,7 +62,13 @@ import {
|
|
|
62
62
|
saveChannelSessions,
|
|
63
63
|
type ChannelSessionRecord,
|
|
64
64
|
} from './persistence'
|
|
65
|
-
import {
|
|
65
|
+
import {
|
|
66
|
+
ADAPTER_READ_CAPABILITIES,
|
|
67
|
+
QUOTED_REPLY_EXCERPT_MAX_CHARS,
|
|
68
|
+
type AdapterId,
|
|
69
|
+
type ChannelAdapterConfig,
|
|
70
|
+
type ReadCapability,
|
|
71
|
+
} from './schema'
|
|
66
72
|
import type {
|
|
67
73
|
ChannelHistoryMessage,
|
|
68
74
|
ChannelKey,
|
|
@@ -179,6 +185,8 @@ export function disengageReactionEmojiFor(adapter: AdapterId): string {
|
|
|
179
185
|
return DISENGAGE_REACTION_EMOJI_OVERRIDES[adapter] ?? DISENGAGE_REACTION_EMOJI
|
|
180
186
|
}
|
|
181
187
|
|
|
188
|
+
type SilentAckReason = 'skip_response' | 'no_reply' | 'skip_response_text_leak'
|
|
189
|
+
|
|
182
190
|
// Wake nudge pushed into a resumed channel session at boot so drain() has a
|
|
183
191
|
// non-empty batch and fires a turn. The substantive instruction the model acts
|
|
184
192
|
// on is the `typeclaw.restart-self` entry already in the reopened JSONL (pi
|
|
@@ -251,6 +259,35 @@ export const CHANNEL_EMPTY_TURN_RETRY_MAX_OUTPUT_TOKENS = 16384
|
|
|
251
259
|
// thrashed the send path, so a re-prompt would just re-thrash; they skip
|
|
252
260
|
// straight to the fallback. See validateChannelTurn's candidate===null branch.
|
|
253
261
|
export const MAX_EMPTY_TURN_RETRIES = 2
|
|
262
|
+
|
|
263
|
+
// Separate, tiny budget for the tool-call-leak self-correction retry. Kept
|
|
264
|
+
// apart from MAX_EMPTY_TURN_RETRIES so a persistently-leaking model cannot
|
|
265
|
+
// consume the empty-turn budget (or vice versa) and so it can't livelock: one
|
|
266
|
+
// nudged retry, then on a second leak we suppress and stay silent. A leaked
|
|
267
|
+
// call is a clean protocol miss, not budget exhaustion — one reminder is
|
|
268
|
+
// usually enough, and silence is safer than an unbounded re-prompt loop.
|
|
269
|
+
export const MAX_TOOL_LEAK_RETRIES = 1
|
|
270
|
+
// Reminder-only nudge injected before a tool-call-leak retry. The model wrote a
|
|
271
|
+
// tool call as its visible message text instead of actually calling the tool,
|
|
272
|
+
// so we suppressed the plumbing and ask it to redo the turn properly. Same
|
|
273
|
+
// SYSTEM MESSAGE framing as the other reminder-only nudges.
|
|
274
|
+
export const TOOL_CALL_LEAK_NUDGE = [
|
|
275
|
+
'---',
|
|
276
|
+
'**[SYSTEM MESSAGE — not from a human]**',
|
|
277
|
+
'',
|
|
278
|
+
'Your previous turn wrote a tool call (e.g. `channel_reply(...)`,',
|
|
279
|
+
'`channel_react(...)`, `skip_response(...)`) as plain message TEXT instead of',
|
|
280
|
+
'actually invoking the tool. That text was suppressed — it was NOT sent to the',
|
|
281
|
+
'channel — because raw tool-call syntax must never be posted as a message. This',
|
|
282
|
+
'is an automated signal from the channel router, not a message from anyone in',
|
|
283
|
+
'the chat. **Do not acknowledge or reply to this notice itself.**',
|
|
284
|
+
'',
|
|
285
|
+
'Redo the turn correctly: to reply, call your channel reply tool; to react or',
|
|
286
|
+
'disengage, call that tool; to stay silent, call `skip_response({ reason })`.',
|
|
287
|
+
'Emit a real tool call — do not type its syntax as your answer.',
|
|
288
|
+
'',
|
|
289
|
+
'---',
|
|
290
|
+
].join('\n')
|
|
254
291
|
// Reminder-only nudge injected before an empty-turn retry. Uses the repo's
|
|
255
292
|
// SYSTEM MESSAGE framing (see composeTurnPrompt) so persona-rich models do not
|
|
256
293
|
// reply to the notice itself. Names the actual failure (the prior turn ran out
|
|
@@ -711,6 +748,13 @@ type LiveSession = {
|
|
|
711
748
|
typingStartedAt: number
|
|
712
749
|
typingTimedOut: boolean
|
|
713
750
|
typingStopPromise: Promise<void> | null
|
|
751
|
+
// Monotonic heartbeat generation. Captured when a heartbeat starts and
|
|
752
|
+
// bumped when it stops. `clearInterval` cannot cancel a timer callback that
|
|
753
|
+
// already came due, so a stale 'tick' can still run AFTER stopTypingHeartbeat
|
|
754
|
+
// enqueued its clear — on Slack that re-sets "is typing..." after the empty-
|
|
755
|
+
// string clear and strands the indicator (Slack's status has no auto-expiry).
|
|
756
|
+
// A 'tick' fired with a stale epoch is dropped before it reaches the adapter.
|
|
757
|
+
typingEpoch: number
|
|
714
758
|
// True only while `live.session.prompt()` is actively running. Gates the
|
|
715
759
|
// deferred typing revival: a revival queued behind an in-flight cap-trip
|
|
716
760
|
// 'stop' must NOT re-arm the heartbeat once the prompt has finished, or it
|
|
@@ -746,6 +790,17 @@ type LiveSession = {
|
|
|
746
790
|
// discarded on silence (skip_response / empty / errored turns) so the bot never
|
|
747
791
|
// leaves a reaction on a message it merely looked at (e.g. cron lookaround).
|
|
748
792
|
pendingTurnReactions: ReactionRequest[]
|
|
793
|
+
// Armed by `validateChannelTurn` on a DELIBERATE silent turn (skip_response or
|
|
794
|
+
// an explicit NO_REPLY), stamped with `turnSeq` so a stale flag from a crashed
|
|
795
|
+
// turn cannot leak into the next one. Read in drain's per-turn finally — AFTER
|
|
796
|
+
// the transient engage :eyes: is dropped — to leave a PERSISTENT :eyes: on the
|
|
797
|
+
// triggering message: "I saw this and intentionally chose not to reply." Null
|
|
798
|
+
// on every non-deliberate outcome (a real reply, a model malfunction, a
|
|
799
|
+
// plumbing leak, a retry, a synthetic turn). Firing after the engage-drop is
|
|
800
|
+
// load-bearing: adapters that collapse a same-actor same-emoji reaction into
|
|
801
|
+
// one toggle would otherwise have the engage-drop remove the only visible
|
|
802
|
+
// :eyes:. See `reactOnSilentAck`.
|
|
803
|
+
silentAckTurn: { turnSeq: number; reason: SilentAckReason } | null
|
|
749
804
|
lastTurnAuthorIds: Set<string>
|
|
750
805
|
// Mirror of currentTurnAuthorId at end-of-turn (the LAST speaker of the
|
|
751
806
|
// prior batch), preserved across the drain finally-block which resets
|
|
@@ -840,6 +895,11 @@ type LiveSession = {
|
|
|
840
895
|
// increments it before injecting EMPTY_TURN_RETRY_NUDGE and reads it to decide
|
|
841
896
|
// retry-vs-fallback. See the candidate===null branch.
|
|
842
897
|
emptyTurnRetries: number
|
|
898
|
+
// Count of tool-call-leak self-correction re-prompts spent this logical turn,
|
|
899
|
+
// bounded by MAX_TOOL_LEAK_RETRIES. Separate from emptyTurnRetries so the two
|
|
900
|
+
// failure modes can't drain each other's budget. Reset with the rest on a
|
|
901
|
+
// fresh user batch.
|
|
902
|
+
toolLeakRetries: number
|
|
843
903
|
// Latches once a bare-empty `stop` has been classified as empty-stop-after-tool-work
|
|
844
904
|
// this logical turn. The recovery nudge tells the model NOT to re-run its tools, so
|
|
845
905
|
// a compliant retry is expected to land another bare-empty `stop` with NO new tool
|
|
@@ -1056,6 +1116,17 @@ export type ChannelRouter = {
|
|
|
1056
1116
|
// the wrong signal. autoReactOnEngage reads this to post :eyes: only as a
|
|
1057
1117
|
// fallback when no visible typing exists. Unset defaults to false.
|
|
1058
1118
|
setTypingCapability: (adapter: ChannelKey['adapter'], supported: boolean) => void
|
|
1119
|
+
// Set by the manager for every adapter present in typeclaw.json#channels,
|
|
1120
|
+
// independent of whether the adapter's start() succeeded (a failed login never
|
|
1121
|
+
// registers callbacks). Combined with the adapter's static read-capability set
|
|
1122
|
+
// (ADAPTER_READ_CAPABILITIES), fetchHistory/getMessage/listChannels tell three
|
|
1123
|
+
// cases apart for a missing callback: not configured → *-not-supported;
|
|
1124
|
+
// configured but the capability isn't one this adapter implements →
|
|
1125
|
+
// *-not-supported; configured AND the adapter should implement it but no
|
|
1126
|
+
// callback is live (e.g. auth failure at startup) → *-adapter-unavailable. So
|
|
1127
|
+
// the agent only sees the actionable error when re-auth would actually help.
|
|
1128
|
+
// Unset defaults to not-configured.
|
|
1129
|
+
setAdapterConfigured: (adapter: ChannelKey['adapter'], configured: boolean) => void
|
|
1059
1130
|
registerChannelNameResolver: (adapter: ChannelKey['adapter'], resolver: ChannelNameResolver) => void
|
|
1060
1131
|
unregisterChannelNameResolver: (adapter: ChannelKey['adapter'], resolver: ChannelNameResolver) => void
|
|
1061
1132
|
// Self-identity is a per-adapter singleton (one bot account per adapter),
|
|
@@ -1209,6 +1280,8 @@ export type ChannelRouter = {
|
|
|
1209
1280
|
flushDebounce: (key: ChannelKey) => Promise<void>
|
|
1210
1281
|
fireTypingHeartbeat: (key: ChannelKey, phase?: 'tick' | 'stop') => Promise<void>
|
|
1211
1282
|
fireTypingInterval: (key: ChannelKey) => Promise<void>
|
|
1283
|
+
fireTypingTick: (key: ChannelKey, epoch: number) => Promise<void>
|
|
1284
|
+
typingEpoch: (key: ChannelKey) => number | undefined
|
|
1212
1285
|
isTypingActive: (key: ChannelKey) => boolean
|
|
1213
1286
|
stopTyping: (key: ChannelKey) => Promise<void>
|
|
1214
1287
|
runIdleGc: () => Promise<void>
|
|
@@ -1411,6 +1484,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1411
1484
|
const removeReactionCallbacks = new Map<ChannelKey['adapter'], Set<RemoveReactionCallback>>()
|
|
1412
1485
|
const typingCallbacks = new Map<ChannelKey['adapter'], Set<TypingCallback>>()
|
|
1413
1486
|
const typingCapableAdapters = new Set<ChannelKey['adapter']>()
|
|
1487
|
+
const configuredAdapters = new Set<ChannelKey['adapter']>()
|
|
1414
1488
|
const channelNameResolvers = new Map<ChannelKey['adapter'], Set<ChannelNameResolver>>()
|
|
1415
1489
|
const membershipResolvers = new Map<ChannelKey['adapter'], Set<MembershipResolver>>()
|
|
1416
1490
|
const selfIdentityResolvers = new Map<ChannelKey['adapter'], ChannelSelfIdentityResolver>()
|
|
@@ -1923,6 +1997,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1923
1997
|
typingStartedAt: 0,
|
|
1924
1998
|
typingTimedOut: false,
|
|
1925
1999
|
typingStopPromise: null,
|
|
2000
|
+
typingEpoch: 0,
|
|
1926
2001
|
promptInFlight: false,
|
|
1927
2002
|
lastInboundAt: now(),
|
|
1928
2003
|
baseContextBytes: 0,
|
|
@@ -1933,6 +2008,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1933
2008
|
currentTurnTypingThread: null,
|
|
1934
2009
|
currentTurnEngageReactions: [],
|
|
1935
2010
|
pendingTurnReactions: [],
|
|
2011
|
+
silentAckTurn: null,
|
|
1936
2012
|
// `lastTurnAuthorId` (string, used for `lastInboundAuthorId` in
|
|
1937
2013
|
// origin) and `lastTurnAuthorIds` (Set, used by
|
|
1938
2014
|
// `grantStickyForReplyTargets` as the fallback when
|
|
@@ -1956,6 +2032,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1956
2032
|
inFlightToolSends: new Map(),
|
|
1957
2033
|
policyDeniedToolSendsThisTurn: new Map(),
|
|
1958
2034
|
emptyTurnRetries: 0,
|
|
2035
|
+
toolLeakRetries: 0,
|
|
1959
2036
|
emptyStopAfterToolWorkArmed: false,
|
|
1960
2037
|
willingnessNudges: 0,
|
|
1961
2038
|
lastTerminalReplyAbort: null,
|
|
@@ -2188,7 +2265,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2188
2265
|
await persist()
|
|
2189
2266
|
}
|
|
2190
2267
|
|
|
2191
|
-
const fireTyping = async (live: LiveSession, phase: 'tick' | 'stop'): Promise<void> => {
|
|
2268
|
+
const fireTyping = async (live: LiveSession, phase: 'tick' | 'stop', epoch?: number): Promise<void> => {
|
|
2269
|
+
// Drop a stale 'tick' that a since-cancelled interval still dispatched:
|
|
2270
|
+
// once the heartbeat stopped (or a new one started) the captured epoch no
|
|
2271
|
+
// longer matches, and forwarding it would re-set the indicator after the
|
|
2272
|
+
// stop clear. 'stop' is never epoch-gated — it must always clear.
|
|
2273
|
+
if (phase === 'tick' && epoch !== undefined && epoch !== live.typingEpoch) return
|
|
2192
2274
|
const callbacks = typingCallbacks.get(live.key.adapter)
|
|
2193
2275
|
if (!callbacks || callbacks.size === 0) return
|
|
2194
2276
|
// Snapshot before iterating: a callback could unregister mid-call.
|
|
@@ -2354,11 +2436,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2354
2436
|
bumpTypingActivity(live)
|
|
2355
2437
|
return
|
|
2356
2438
|
}
|
|
2439
|
+
const epoch = ++live.typingEpoch
|
|
2357
2440
|
live.typingStartedAt = now()
|
|
2358
2441
|
// Fire immediately so the indicator appears on the very first inbound,
|
|
2359
2442
|
// not 8 seconds later.
|
|
2360
|
-
void fireTyping(live, 'tick')
|
|
2443
|
+
void fireTyping(live, 'tick', epoch)
|
|
2361
2444
|
live.typingTimer = setInterval(() => {
|
|
2445
|
+
// A due callback can run one last time after stopTypingHeartbeat's
|
|
2446
|
+
// clearInterval; the epoch mismatch makes fireTyping drop the tick so it
|
|
2447
|
+
// can't re-set the indicator after the stop clear.
|
|
2448
|
+
if (epoch !== live.typingEpoch) return
|
|
2362
2449
|
if (live.destroyed) {
|
|
2363
2450
|
void stopTypingHeartbeat(live)
|
|
2364
2451
|
return
|
|
@@ -2371,11 +2458,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2371
2458
|
void stopTypingHeartbeat(live)
|
|
2372
2459
|
return
|
|
2373
2460
|
}
|
|
2374
|
-
void fireTyping(live, 'tick')
|
|
2461
|
+
void fireTyping(live, 'tick', epoch)
|
|
2375
2462
|
}, TYPING_HEARTBEAT_MS)
|
|
2376
2463
|
}
|
|
2377
2464
|
|
|
2378
2465
|
const stopTypingHeartbeat = async (live: LiveSession): Promise<void> => {
|
|
2466
|
+
// Bump first, before any early return: a stop must invalidate the current
|
|
2467
|
+
// generation so a due-but-not-yet-run interval tick is dropped by
|
|
2468
|
+
// fireTyping's epoch guard even if the timer was already cleared.
|
|
2469
|
+
live.typingEpoch++
|
|
2379
2470
|
if (!live.typingTimer) {
|
|
2380
2471
|
await live.typingStopPromise
|
|
2381
2472
|
return
|
|
@@ -2623,6 +2714,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2623
2714
|
// iterations the retry itself queues do not refill the budget and loop
|
|
2624
2715
|
// forever (and the raised cap stays scoped to the turn that set it).
|
|
2625
2716
|
live.emptyTurnRetries = 0
|
|
2717
|
+
live.toolLeakRetries = 0
|
|
2626
2718
|
live.emptyStopAfterToolWorkArmed = false
|
|
2627
2719
|
live.willingnessNudges = 0
|
|
2628
2720
|
live.abortReasonThisTurn = null
|
|
@@ -2672,6 +2764,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2672
2764
|
const promptStart = now()
|
|
2673
2765
|
const successfulSendsBeforePrompt = live.successfulChannelSends
|
|
2674
2766
|
const emptyTurnRetriesBeforePrompt = live.emptyTurnRetries
|
|
2767
|
+
const toolLeakRetriesBeforePrompt = live.toolLeakRetries
|
|
2675
2768
|
const engageAddPromises = live.currentTurnEngageReactions
|
|
2676
2769
|
live.turnSeq++
|
|
2677
2770
|
live.successfulSendsAtTurnStart = successfulSendsBeforePrompt
|
|
@@ -2721,14 +2814,19 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2721
2814
|
// usable assistant reply (real model prose the user saw) seeds the next
|
|
2722
2815
|
// turn's escalation. Every other terminal outcome CLEARS lastQuestionSignal
|
|
2723
2816
|
// so an older question can't leak across the failed/silent turn:
|
|
2724
|
-
// - retry queued (`length`/`aborted`, budget left
|
|
2725
|
-
//
|
|
2817
|
+
// - retry queued (`length`/`aborted`, budget left, OR a tool-call
|
|
2818
|
+
// leak nudged a self-correction retry): turn still in flight →
|
|
2819
|
+
// leave both for the reminder-only iteration that ends it.
|
|
2726
2820
|
// - usable reply → commit the pending signal.
|
|
2727
2821
|
// - provider error / empty-turn fallback / NO_REPLY / skip (no usable
|
|
2728
2822
|
// reply) → clear BOTH (pending and lastQuestionSignal).
|
|
2729
2823
|
// A fallback sends via source:'system', which also bumps
|
|
2730
|
-
// successfulChannelSends, so it must be excluded explicitly.
|
|
2731
|
-
|
|
2824
|
+
// successfulChannelSends, so it must be excluded explicitly. Both retry
|
|
2825
|
+
// budgets keep the logical turn open, so both must count here — a
|
|
2826
|
+
// tool-leak retry that later replies must commit the signal AT the
|
|
2827
|
+
// successful retry, not clear it after the first suppressed attempt.
|
|
2828
|
+
const retryQueuedThisTurn =
|
|
2829
|
+
live.emptyTurnRetries > emptyTurnRetriesBeforePrompt || live.toolLeakRetries > toolLeakRetriesBeforePrompt
|
|
2732
2830
|
const providerErrorThisTurn = assistantLeafStopReason(live.session) === 'error'
|
|
2733
2831
|
const fallbackPostedThisTurn = live.emptyTurnFallbackTurn === live.turnSeq
|
|
2734
2832
|
const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
|
|
@@ -2759,7 +2857,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2759
2857
|
} finally {
|
|
2760
2858
|
live.promptInFlight = false
|
|
2761
2859
|
const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
|
|
2762
|
-
|
|
2860
|
+
// The eager :eyes: ack is a "looking at this" signal, not a "replied"
|
|
2861
|
+
// one, so it comes off at turn end no matter the outcome — a reply, but
|
|
2862
|
+
// also silence, skip_response, an empty turn, or a provider error
|
|
2863
|
+
// (observe-after-engage). Leaving it only on the reply path stranded the
|
|
2864
|
+
// ack permanently on messages the agent looked at but never answered.
|
|
2865
|
+
const dropDone = dropEngageReactions(live, engageAddPromises)
|
|
2866
|
+
// A DELIBERATE silent turn (skip_response / NO_REPLY) leaves a
|
|
2867
|
+
// PERSISTENT :eyes: acking "seen, intentionally not replying". On a
|
|
2868
|
+
// typing-less adapter it reuses the same message/emoji/actor as the
|
|
2869
|
+
// transient engage :eyes:, and adapters that collapse that into one
|
|
2870
|
+
// toggle would let a still-in-flight engage removal strip the ack — so
|
|
2871
|
+
// the silent path AWAITS every engage removal reaching the adapter
|
|
2872
|
+
// before adding the persistent one. Only silent turns pay that wait:
|
|
2873
|
+
// normal/reply turns keep the engage drop fire-and-forget (`void`), so
|
|
2874
|
+
// turn-end never blocks on the reaction API off the silent path.
|
|
2875
|
+
if (live.silentAckTurn?.turnSeq === live.turnSeq) await dropDone
|
|
2876
|
+
else void dropDone
|
|
2877
|
+
reactOnSilentAck(live)
|
|
2763
2878
|
// Held channel_react reactions apply only when the agent posted a
|
|
2764
2879
|
// genuine reply this turn — NOT an empty-turn fallback or provider-
|
|
2765
2880
|
// error notice, both of which send via source:'system' and bump
|
|
@@ -2773,8 +2888,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2773
2888
|
assistantLeafStopReason(live.session) !== 'error'
|
|
2774
2889
|
if (usableReplyThisTurn) flushPendingReactions(live)
|
|
2775
2890
|
else live.pendingTurnReactions = []
|
|
2776
|
-
|
|
2777
|
-
|
|
2891
|
+
// Either retry budget keeps the turn in flight, so a deferred provider
|
|
2892
|
+
// error must wait for the reminder-only iteration that actually ends it.
|
|
2893
|
+
const retryQueuedThisTurn =
|
|
2894
|
+
live.emptyTurnRetries > emptyTurnRetriesBeforePrompt || live.toolLeakRetries > toolLeakRetriesBeforePrompt
|
|
2895
|
+
await maybePostDeferredProviderError(live, sentReplyThisTurn, retryQueuedThisTurn)
|
|
2778
2896
|
await fireSessionTurnEnd(live)
|
|
2779
2897
|
}
|
|
2780
2898
|
await fireSessionIdle(live)
|
|
@@ -3364,8 +3482,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3364
3482
|
return addReactionRef
|
|
3365
3483
|
}
|
|
3366
3484
|
|
|
3367
|
-
|
|
3368
|
-
|
|
3485
|
+
// Returns a promise that settles only once every engage removal has REACHED
|
|
3486
|
+
// the adapter, not merely been scheduled. The silent-ack path awaits this so
|
|
3487
|
+
// its persistent :eyes: is added strictly AFTER the transient one is removed
|
|
3488
|
+
// (see reactOnSilentAck). Fire-and-forget callers just `void` the result.
|
|
3489
|
+
const dropEngageReactions = (live: LiveSession, addPromises: Array<Promise<ReactionRef | null>>): Promise<void> => {
|
|
3490
|
+
return Promise.all(addPromises.map((addPromise) => dropOneEngageReaction(live, addPromise))).then(() => undefined)
|
|
3369
3491
|
}
|
|
3370
3492
|
|
|
3371
3493
|
// Only the LAST engaging inbound of a coalesced batch should carry the eager
|
|
@@ -3377,11 +3499,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3377
3499
|
const addPromises = live.promptQueue.flatMap((m) => (m.engageReaction !== undefined ? [m.engageReaction] : []))
|
|
3378
3500
|
if (addPromises.length === 0) return
|
|
3379
3501
|
for (const item of live.promptQueue) delete item.engageReaction
|
|
3380
|
-
dropEngageReactions(live, addPromises)
|
|
3502
|
+
void dropEngageReactions(live, addPromises)
|
|
3381
3503
|
}
|
|
3382
3504
|
|
|
3383
|
-
const dropOneEngageReaction = (live: LiveSession, addPromise: Promise<ReactionRef | null>): void => {
|
|
3384
|
-
|
|
3505
|
+
const dropOneEngageReaction = (live: LiveSession, addPromise: Promise<ReactionRef | null>): Promise<void> => {
|
|
3506
|
+
return addPromise
|
|
3385
3507
|
.then((reactionRef) => {
|
|
3386
3508
|
if (reactionRef === null) return undefined
|
|
3387
3509
|
return removeReaction({
|
|
@@ -3428,6 +3550,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3428
3550
|
else typingCapableAdapters.delete(adapter)
|
|
3429
3551
|
}
|
|
3430
3552
|
|
|
3553
|
+
const setAdapterConfigured = (adapter: ChannelKey['adapter'], configured: boolean): void => {
|
|
3554
|
+
if (configured) configuredAdapters.add(adapter)
|
|
3555
|
+
else configuredAdapters.delete(adapter)
|
|
3556
|
+
}
|
|
3557
|
+
|
|
3431
3558
|
const registerChannelNameResolver = (adapter: ChannelKey['adapter'], resolver: ChannelNameResolver): void => {
|
|
3432
3559
|
let set = channelNameResolvers.get(adapter)
|
|
3433
3560
|
if (!set) {
|
|
@@ -3492,10 +3619,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3492
3619
|
historyCallbacks.get(adapter)?.delete(cb)
|
|
3493
3620
|
}
|
|
3494
3621
|
|
|
3622
|
+
const isReadCapabilityUnavailable = (adapter: ChannelKey['adapter'], capability: ReadCapability): boolean =>
|
|
3623
|
+
configuredAdapters.has(adapter) && ADAPTER_READ_CAPABILITIES[adapter].includes(capability)
|
|
3624
|
+
|
|
3625
|
+
const missingCallbackError = (adapter: ChannelKey['adapter'], capability: ReadCapability): string =>
|
|
3626
|
+
isReadCapabilityUnavailable(adapter, capability)
|
|
3627
|
+
? `${capability}-adapter-unavailable: the "${adapter}" adapter is configured but not currently running (it likely failed to start, e.g. an expired token or auth error — check the container logs and re-authenticate)`
|
|
3628
|
+
: `${capability}-not-supported`
|
|
3629
|
+
|
|
3495
3630
|
const fetchHistory = async (adapter: ChannelKey['adapter'], args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
3496
3631
|
const callbacks = historyCallbacks.get(adapter)
|
|
3497
3632
|
if (!callbacks || callbacks.size === 0) {
|
|
3498
|
-
return { ok: false, error: 'history
|
|
3633
|
+
return { ok: false, error: missingCallbackError(adapter, 'history') }
|
|
3499
3634
|
}
|
|
3500
3635
|
// Snapshot before iterating, mirroring `send`: a callback that mutates
|
|
3501
3636
|
// the set (e.g. unregisters mid-call) must not skip siblings.
|
|
@@ -3524,7 +3659,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3524
3659
|
|
|
3525
3660
|
const getMessage = async (adapter: ChannelKey['adapter'], args: GetMessageArgs): Promise<GetMessageResult> => {
|
|
3526
3661
|
const cb = messageGetCallbacks.get(adapter)
|
|
3527
|
-
if (cb === undefined)
|
|
3662
|
+
if (cb === undefined)
|
|
3663
|
+
return isReadCapabilityUnavailable(adapter, 'message-get')
|
|
3664
|
+
? { ok: false, error: missingCallbackError(adapter, 'message-get'), code: 'adapter-unavailable' }
|
|
3665
|
+
: { ok: false, error: 'message-get-not-supported', code: 'not-supported' }
|
|
3528
3666
|
try {
|
|
3529
3667
|
return await raceWithTimeout(cb(args), fetchHistoryTimeoutMs, `[channels] ${adapter} message get`)
|
|
3530
3668
|
} catch (err) {
|
|
@@ -3543,7 +3681,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3543
3681
|
|
|
3544
3682
|
const listChannels = async (adapter: ChannelKey['adapter'], args: ListChannelsArgs): Promise<ListChannelsResult> => {
|
|
3545
3683
|
const cb = listCallbacks.get(adapter)
|
|
3546
|
-
if (cb === undefined)
|
|
3684
|
+
if (cb === undefined)
|
|
3685
|
+
return isReadCapabilityUnavailable(adapter, 'list')
|
|
3686
|
+
? { ok: false, error: missingCallbackError(adapter, 'list'), code: 'adapter-unavailable' }
|
|
3687
|
+
: { ok: false, error: 'list-not-supported', code: 'not-supported' }
|
|
3547
3688
|
try {
|
|
3548
3689
|
return await raceWithTimeout(cb(args), fetchHistoryTimeoutMs, `[channels] ${adapter} list channels`)
|
|
3549
3690
|
} catch (err) {
|
|
@@ -3978,6 +4119,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3978
4119
|
const { reason } = live.skippedTurn
|
|
3979
4120
|
live.skippedTurn = null
|
|
3980
4121
|
logger.info(`[channels] ${live.keyId} skipped_by_tool reason=${JSON.stringify(reason)}`)
|
|
4122
|
+
armSilentTurnAck(live, 'skip_response')
|
|
3981
4123
|
return
|
|
3982
4124
|
}
|
|
3983
4125
|
if (live.skippedTurn !== null && live.skippedTurn.turnSeq === live.turnSeq) {
|
|
@@ -4003,6 +4145,27 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4003
4145
|
}
|
|
4004
4146
|
}
|
|
4005
4147
|
|
|
4148
|
+
// Suppress a leaked tool call (never post the plumbing) and, while budget
|
|
4149
|
+
// remains, push a self-correction reminder so the same logical turn
|
|
4150
|
+
// re-prompts and the model can redo it with a real tool call. On exhaustion
|
|
4151
|
+
// we stay silent — a persistently-leaking model must not livelock, and
|
|
4152
|
+
// silence is safer than posting a fallback the user didn't ask for.
|
|
4153
|
+
const suppressToolLeakAndNudge = (live: LiveSession, leakedText: string): void => {
|
|
4154
|
+
if (live.toolLeakRetries < MAX_TOOL_LEAK_RETRIES) {
|
|
4155
|
+
live.toolLeakRetries++
|
|
4156
|
+
logger.warn(
|
|
4157
|
+
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (nudge ` +
|
|
4158
|
+
`attempt=${live.toolLeakRetries}/${MAX_TOOL_LEAK_RETRIES}) text_len=${leakedText.length}`,
|
|
4159
|
+
)
|
|
4160
|
+
live.pendingSystemReminders.push(TOOL_CALL_LEAK_NUDGE)
|
|
4161
|
+
return
|
|
4162
|
+
}
|
|
4163
|
+
logger.warn(
|
|
4164
|
+
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (retries exhausted, silent) ` +
|
|
4165
|
+
`text_len=${leakedText.length}`,
|
|
4166
|
+
)
|
|
4167
|
+
}
|
|
4168
|
+
|
|
4006
4169
|
// A send landed this turn, but the model may have posted a `continue: true`
|
|
4007
4170
|
// progress reply, kept working, then ENDED with its final answer as plain
|
|
4008
4171
|
// prose — never calling a channel tool again. The terminal-reply abort fires
|
|
@@ -4276,6 +4439,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4276
4439
|
}
|
|
4277
4440
|
const leakedReasoning = !isNoReplySignal(assistantText)
|
|
4278
4441
|
logger.info(`[channels] ${live.keyId} no_reply${leakedReasoning ? ' (with_leaked_reasoning)' : ''}`)
|
|
4442
|
+
armSilentTurnAck(live, 'no_reply')
|
|
4279
4443
|
return
|
|
4280
4444
|
}
|
|
4281
4445
|
|
|
@@ -4291,28 +4455,34 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4291
4455
|
return
|
|
4292
4456
|
}
|
|
4293
4457
|
|
|
4294
|
-
// Plain-text tool-call leak: the model serialized a
|
|
4295
|
-
//
|
|
4296
|
-
//
|
|
4297
|
-
//
|
|
4298
|
-
//
|
|
4299
|
-
//
|
|
4300
|
-
//
|
|
4458
|
+
// Plain-text tool-call leak: the model serialized a tool call as ordinary
|
|
4459
|
+
// message text instead of producing a real tool call. Default is SUPPRESS —
|
|
4460
|
+
// that raw plumbing must never reach the channel. The two exceptions are
|
|
4461
|
+
// `channel_reply` / `channel_send`, whose leaked form carries a salvageable
|
|
4462
|
+
// user message: extract the `text` arg and recover the actual reply.
|
|
4463
|
+
// `suppress-silent` (skip_response) drops without a nudge because the model
|
|
4464
|
+
// already got the silence it asked for; `suppress-warn` (every other leaked
|
|
4465
|
+
// call) drops AND re-prompts the model to redo the turn with a real tool
|
|
4466
|
+
// call, bounded by MAX_TOOL_LEAK_RETRIES so it can't livelock.
|
|
4301
4467
|
const plainTextToolCallKind = getPlainTextChannelToolCallKind(assistantText)
|
|
4302
|
-
if (plainTextToolCallKind === '
|
|
4468
|
+
if (plainTextToolCallKind === 'suppress-silent') {
|
|
4303
4469
|
logger.warn(
|
|
4304
|
-
`[channels] ${live.keyId}: suppressed
|
|
4470
|
+
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (silent) text_len=${assistantText.length}`,
|
|
4305
4471
|
)
|
|
4472
|
+
armSilentTurnAck(live, 'skip_response_text_leak')
|
|
4473
|
+
return
|
|
4474
|
+
}
|
|
4475
|
+
if (plainTextToolCallKind === 'suppress-warn') {
|
|
4476
|
+
suppressToolLeakAndNudge(live, assistantText)
|
|
4306
4477
|
return
|
|
4307
4478
|
}
|
|
4308
4479
|
if (plainTextToolCallKind !== null) {
|
|
4309
4480
|
const extracted = extractPlainTextChannelToolCallText(assistantText)
|
|
4310
|
-
//
|
|
4311
|
-
//
|
|
4481
|
+
// A reply/send leak with no recoverable `text` (missing arg, empty value,
|
|
4482
|
+
// or fully-truncated) still owes the user a real message — treat it as a
|
|
4483
|
+
// warn-worthy leak, not a silent drop, so the model retries properly.
|
|
4312
4484
|
if (extracted === null) {
|
|
4313
|
-
|
|
4314
|
-
`[channels] ${live.keyId}: suppressed unextractable_plain_text_channel_tool_call text_len=${assistantText.length}`,
|
|
4315
|
-
)
|
|
4485
|
+
suppressToolLeakAndNudge(live, assistantText)
|
|
4316
4486
|
return
|
|
4317
4487
|
}
|
|
4318
4488
|
// The extracted value is still untrusted model output: if it is itself a
|
|
@@ -4957,6 +5127,38 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4957
5127
|
})
|
|
4958
5128
|
}
|
|
4959
5129
|
|
|
5130
|
+
const armSilentTurnAck = (live: LiveSession, reason: SilentAckReason): void => {
|
|
5131
|
+
live.silentAckTurn = { turnSeq: live.turnSeq, reason }
|
|
5132
|
+
}
|
|
5133
|
+
|
|
5134
|
+
const reactOnSilentAck = (live: LiveSession): void => {
|
|
5135
|
+
if (live.silentAckTurn?.turnSeq !== live.turnSeq) return
|
|
5136
|
+
const { reason } = live.silentAckTurn
|
|
5137
|
+
live.silentAckTurn = null
|
|
5138
|
+
const reactionRef = live.currentTurnReactionRef
|
|
5139
|
+
if (reactionRef === null) return
|
|
5140
|
+
void react({
|
|
5141
|
+
adapter: live.key.adapter,
|
|
5142
|
+
workspace: live.key.workspace,
|
|
5143
|
+
chat: live.key.chat,
|
|
5144
|
+
thread: live.key.thread,
|
|
5145
|
+
reactionRef,
|
|
5146
|
+
emoji: ENGAGE_REACTION_EMOJI,
|
|
5147
|
+
})
|
|
5148
|
+
.then((result) => {
|
|
5149
|
+
if (!result.ok && result.code !== 'unsupported') {
|
|
5150
|
+
logger.info(
|
|
5151
|
+
`[channels] silent-ack-react failed reason=${reason} adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
|
|
5152
|
+
)
|
|
5153
|
+
}
|
|
5154
|
+
})
|
|
5155
|
+
.catch((err) => {
|
|
5156
|
+
logger.info(
|
|
5157
|
+
`[channels] silent-ack-react threw reason=${reason} adapter=${live.key.adapter} chat=${live.key.chat}: ${describe(err)}`,
|
|
5158
|
+
)
|
|
5159
|
+
})
|
|
5160
|
+
}
|
|
5161
|
+
|
|
4960
5162
|
return {
|
|
4961
5163
|
route,
|
|
4962
5164
|
send,
|
|
@@ -4974,6 +5176,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4974
5176
|
registerTyping,
|
|
4975
5177
|
unregisterTyping,
|
|
4976
5178
|
setTypingCapability,
|
|
5179
|
+
setAdapterConfigured,
|
|
4977
5180
|
registerChannelNameResolver,
|
|
4978
5181
|
unregisterChannelNameResolver,
|
|
4979
5182
|
registerSelfIdentity,
|
|
@@ -5051,6 +5254,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5051
5254
|
}
|
|
5052
5255
|
await fireTyping(live, 'tick')
|
|
5053
5256
|
},
|
|
5257
|
+
fireTypingTick: async (key: ChannelKey, epoch: number) => {
|
|
5258
|
+
const live = liveSessions.get(channelKeyId(key))
|
|
5259
|
+
if (!live) return
|
|
5260
|
+
await fireTyping(live, 'tick', epoch)
|
|
5261
|
+
},
|
|
5262
|
+
typingEpoch: (key: ChannelKey) => liveSessions.get(channelKeyId(key))?.typingEpoch,
|
|
5054
5263
|
isTypingActive: (key: ChannelKey) => {
|
|
5055
5264
|
const live = liveSessions.get(channelKeyId(key))
|
|
5056
5265
|
return live?.typingTimer !== null && live?.typingTimer !== undefined
|
|
@@ -5547,20 +5756,23 @@ export type ReplyRenderMode = 'native' | 'quote'
|
|
|
5547
5756
|
// because native support is not uniform within an adapter — Telegram's
|
|
5548
5757
|
// `sendMessage` accepts `reply_to_message_id` but `sendDocument` does not, so
|
|
5549
5758
|
// an attachment-only Telegram reply must quote; the same text-only restriction
|
|
5550
|
-
// holds for
|
|
5551
|
-
// land bare) and KakaoTalk. Slack's primitive is `thread`, not a per-message
|
|
5759
|
+
// holds for KakaoTalk. Slack's primitive is `thread`, not a per-message
|
|
5552
5760
|
// reply, so it stays quote; GitHub's PR-review reply already rides on `thread`.
|
|
5553
5761
|
//
|
|
5554
5762
|
// KakaoTalk is `native` here even though its reply payload can fail to resolve
|
|
5555
5763
|
// at send time — the adapter degrades to the blockquote fallback itself using
|
|
5556
5764
|
// `replyTo.source`, so the router still routes it down the native branch.
|
|
5557
|
-
const NATIVE_REPLY_TEXT_ADAPTERS = new Set<AdapterId>(['telegram-bot', '
|
|
5765
|
+
const NATIVE_REPLY_TEXT_ADAPTERS = new Set<AdapterId>(['telegram-bot', 'kakaotalk'])
|
|
5558
5766
|
|
|
5559
5767
|
// Webex's `parentId` rides on both `sendMessage` and `uploadFile`, so a reply is
|
|
5560
5768
|
// native for every shape — including attachment-only, which the text-gated set
|
|
5561
|
-
// above cannot express.
|
|
5562
|
-
// `
|
|
5563
|
-
|
|
5769
|
+
// above cannot express. Both Discord adapters join this set because each carries
|
|
5770
|
+
// `message_reference` on BOTH the text send (`sendMessage`) and the attachment
|
|
5771
|
+
// send (`payload_json` on the first file upload), so an attachment-only Discord
|
|
5772
|
+
// reply is a native reply-arrow, not a bare blockquote. Special-cased before the
|
|
5773
|
+
// text gate so the router sets `replyTo` (not a blockquote) even when the reply
|
|
5774
|
+
// carries no text.
|
|
5775
|
+
const NATIVE_REPLY_EVERY_SHAPE_ADAPTERS = new Set<AdapterId>(['webex', 'webex-bot', 'discord-bot', 'discord'])
|
|
5564
5776
|
|
|
5565
5777
|
export function resolveReplyRenderMode(msg: OutboundMessage): ReplyRenderMode {
|
|
5566
5778
|
if (NATIVE_REPLY_EVERY_SHAPE_ADAPTERS.has(msg.adapter)) return 'native'
|
|
@@ -5953,15 +6165,27 @@ function attemptMadeToolCall(session: AgentSession): boolean {
|
|
|
5953
6165
|
return false
|
|
5954
6166
|
}
|
|
5955
6167
|
|
|
6168
|
+
// Peels a single symmetric markdown-emphasis wrapper off a token: bold/italic
|
|
6169
|
+
// asterisks (`*`, `**`, `***`), underscores (`_`, `__`), or inline-code
|
|
6170
|
+
// backticks. Only strips when the SAME run brackets both ends, so `**NO_REPLY**`
|
|
6171
|
+
// → `NO_REPLY` while an asymmetric `*NO_REPLY` or a non-wrapping `NO_REPLY_MODE`
|
|
6172
|
+
// is returned unchanged. Not recursive — one layer is enough for the observed
|
|
6173
|
+
// `**...**` / `` `...` `` "loud" drift; anything more nested is not a real form.
|
|
6174
|
+
function stripEmphasisWrapper(token: string): string {
|
|
6175
|
+
const match = /^([*_`]{1,3})([^*_`].*?[^*_`]|[^*_`])\1$/.exec(token)
|
|
6176
|
+
return match ? match[2]! : token
|
|
6177
|
+
}
|
|
6178
|
+
|
|
5956
6179
|
// Lenient on purpose: distilled / smaller models routinely drift off the
|
|
5957
6180
|
// documented `NO_REPLY` form. We additionally accept `(NO_REPLY)` (Claude-style
|
|
5958
|
-
// hedging)
|
|
5959
|
-
//
|
|
5960
|
-
//
|
|
6181
|
+
// hedging), markdown-emphasized "loud" forms (`**NO_REPLY**`, `` `NO_REPLY` ``,
|
|
6182
|
+
// `*NO_REPLY*`), and empty visible text (e.g. Kimi-distilled models that emit
|
|
6183
|
+
// only a thinking block and end the turn) — without the empty case we'd recover
|
|
6184
|
+
// an empty string into the chat. The prompt contract still teaches the strict
|
|
5961
6185
|
// literal; this just widens what we accept. Shared with channel_send /
|
|
5962
6186
|
// channel_reply so all three call sites stay in lockstep.
|
|
5963
6187
|
export function isNoReplySignal(text: string): boolean {
|
|
5964
|
-
const trimmed = text.trim()
|
|
6188
|
+
const trimmed = stripEmphasisWrapper(text.trim())
|
|
5965
6189
|
if (trimmed === '') return true
|
|
5966
6190
|
if (trimmed === 'NO_REPLY') return true
|
|
5967
6191
|
if (trimmed === '(NO_REPLY)') return true
|
|
@@ -5990,21 +6214,31 @@ export function isNoReplySignal(text: string): boolean {
|
|
|
5990
6214
|
// "... end with NO_REPLY." (+ sentence punctuation)
|
|
5991
6215
|
// "... end with NO_REPLY.NO_REPLY" (model-doubled terminator, glued)
|
|
5992
6216
|
// "... and stop. (NO_REPLY)" (parenthesized at end)
|
|
6217
|
+
// "... nothing to add. **NO_REPLY**"(markdown-emphasized "loud" form)
|
|
6218
|
+
// "... nothing here. `NO_REPLY`" (inline-code "loud" form)
|
|
5993
6219
|
// Does not match (returns false):
|
|
5994
6220
|
// "NO_REPLY means do nothing" (token at start, prose after)
|
|
5995
6221
|
// "the env var is NO_REPLY_MODE" (substring, not whole token)
|
|
6222
|
+
// "the flag is FOO_NO_REPLY" (identifier — `_` is not a token boundary)
|
|
6223
|
+
// "the **NO_REPLY** token is how..."(emphasized but mid-sentence, prose after)
|
|
5996
6224
|
// "no reply needed" (case-sensitive on purpose)
|
|
5997
6225
|
export function endsWithNoReplySignal(text: string): boolean {
|
|
5998
6226
|
if (isNoReplySignal(text)) return true
|
|
5999
6227
|
const trimmed = text.trim()
|
|
6000
6228
|
if (trimmed === '') return false
|
|
6001
|
-
//
|
|
6002
|
-
//
|
|
6003
|
-
//
|
|
6004
|
-
//
|
|
6005
|
-
//
|
|
6229
|
+
// Isolate the final token, then defer to isNoReplySignal (which strips a
|
|
6230
|
+
// symmetric emphasis wrapper). Boundaries are whitespace / sentence
|
|
6231
|
+
// punctuation / opening bracket only — `.NO_REPLY` splits off the preceding
|
|
6232
|
+
// sentence (covering the model-doubled `...NO_REPLY.NO_REPLY` shape), while
|
|
6233
|
+
// `_` is deliberately NOT a boundary so an identifier like `FOO_NO_REPLY`
|
|
6234
|
+
// stays one token and reads as prose, not a signal.
|
|
6006
6235
|
const tail = trimmed.replace(/[.!?)\]\s]+$/, '')
|
|
6007
|
-
|
|
6236
|
+
const lastToken = tail.split(/[\s.!?([]/).pop() ?? ''
|
|
6237
|
+
// An empty final token means the text ended on an opening bracket (e.g. a
|
|
6238
|
+
// leaked `skip_response()` call), not a signal — don't hand it to
|
|
6239
|
+
// isNoReplySignal, whose empty-string case reads as deliberate silence.
|
|
6240
|
+
if (lastToken === '') return false
|
|
6241
|
+
return isNoReplySignal(lastToken)
|
|
6008
6242
|
}
|
|
6009
6243
|
|
|
6010
6244
|
// Detects the upstream "empty response" debug sentinel: when the LLM ends a
|
|
@@ -6110,44 +6344,99 @@ export function isLikelyKimiChannelToolLeak(text: string): boolean {
|
|
|
6110
6344
|
// posts its own "I'm staying silent" plumbing to the channel, the exact
|
|
6111
6345
|
// opposite of the intended no-op. It is never a legitimate user-facing reply.
|
|
6112
6346
|
//
|
|
6113
|
-
//
|
|
6114
|
-
//
|
|
6115
|
-
//
|
|
6116
|
-
//
|
|
6117
|
-
//
|
|
6118
|
-
//
|
|
6119
|
-
//
|
|
6120
|
-
//
|
|
6121
|
-
//
|
|
6122
|
-
//
|
|
6123
|
-
// the
|
|
6347
|
+
// Detection is a SINGLE whole-message boundary for every tool, then a per-name
|
|
6348
|
+
// disposition. reply/send RECOVER (their leaked form holds a salvageable user
|
|
6349
|
+
// message the extractor re-posts); everything else SUPPRESSES.
|
|
6350
|
+
//
|
|
6351
|
+
// SUPPRESS is the default and is detected by SHAPE, not a curated name list — a
|
|
6352
|
+
// `toolname(...)` that is the model's ENTIRE turn output is always a protocol
|
|
6353
|
+
// malfunction (the model narrated a call instead of emitting it), and that raw
|
|
6354
|
+
// plumbing must never reach the channel. No allowlist to keep in sync as tools
|
|
6355
|
+
// are added.
|
|
6356
|
+
//
|
|
6357
|
+
// The false-positive boundary is "the WHOLE trimmed message is a single call
|
|
6358
|
+
// expression" — NOT "starts with a call". A developer-facing reply like
|
|
6359
|
+
// `read({ ... }) lets you load a file` has text after the closing paren, so it
|
|
6360
|
+
// is prose and reaches the user. Only a message that is *nothing but* the call
|
|
6361
|
+
// (`skip_response({ ... })`, `channel_react({ emoji: "eyes" })`, bare
|
|
6362
|
+
// `channel_disengage()`) is a leak. This is what lets the rule cover every tool
|
|
6363
|
+
// — including future ones and generic tools like `bash(...)` — without risking
|
|
6364
|
+
// legitimate replies, because a real reply is never *only* a bare tool call.
|
|
6124
6365
|
//
|
|
6125
|
-
//
|
|
6126
|
-
//
|
|
6127
|
-
//
|
|
6128
|
-
|
|
6366
|
+
// `isWholeMessageToolCall` (below) is the bracket-aware parser; it returns the
|
|
6367
|
+
// called tool's name so the caller can apply the one intrinsic distinction that
|
|
6368
|
+
// survives: `skip_response` suppresses SILENTLY (the model wanted silence, and
|
|
6369
|
+
// suppression already delivered it — warning would be noise), while every other
|
|
6370
|
+
// suppressed leak pushes a self-correction reminder so the model retries with a
|
|
6371
|
+
// real tool call or a real reply.
|
|
6372
|
+
const SKIP_RESPONSE_TOOL_NAME = 'skip_response'
|
|
6129
6373
|
|
|
6130
|
-
export type PlainTextChannelToolCallKind = 'reply' | 'send' | '
|
|
6374
|
+
export type PlainTextChannelToolCallKind = 'reply' | 'send' | 'suppress-silent' | 'suppress-warn'
|
|
6131
6375
|
|
|
6132
6376
|
export function getPlainTextChannelToolCallKind(text: string): PlainTextChannelToolCallKind | null {
|
|
6133
|
-
|
|
6134
|
-
|
|
6135
|
-
|
|
6136
|
-
|
|
6137
|
-
|
|
6138
|
-
|
|
6139
|
-
|
|
6140
|
-
|
|
6141
|
-
|
|
6142
|
-
|
|
6143
|
-
|
|
6144
|
-
|
|
6377
|
+
// Everything routes through the SAME whole-message boundary, including
|
|
6378
|
+
// reply/send recovery — a prefix match there would false-positive prose like
|
|
6379
|
+
// `channel_reply({"text":"hi"}) is the serialized form`, recovering `hi` and
|
|
6380
|
+
// dropping the explanation. `isWholeMessageToolCall` returns the tool name
|
|
6381
|
+
// only when the entire trimmed message is the call (or a truncated one), so a
|
|
6382
|
+
// reply/send leak still recovers while a mention-with-trailing-prose falls
|
|
6383
|
+
// through to the user.
|
|
6384
|
+
const toolName = isWholeMessageToolCall(text)
|
|
6385
|
+
if (toolName === null) return null
|
|
6386
|
+
if (toolName === 'channel_reply') return 'reply'
|
|
6387
|
+
if (toolName === 'channel_send') return 'send'
|
|
6388
|
+
// `skip_response` already got what it wanted once suppressed (silence), so
|
|
6389
|
+
// warning would be noise. Every other leaked call dropped a real action or
|
|
6390
|
+
// reply, so nudge the model to redo it properly.
|
|
6391
|
+
return toolName === SKIP_RESPONSE_TOOL_NAME ? 'suppress-silent' : 'suppress-warn'
|
|
6145
6392
|
}
|
|
6146
6393
|
|
|
6147
6394
|
export function isLikelyPlainTextChannelToolCall(text: string): boolean {
|
|
6148
6395
|
return getPlainTextChannelToolCallKind(text) !== null
|
|
6149
6396
|
}
|
|
6150
6397
|
|
|
6398
|
+
// Bracket-aware parser: returns the called tool's name when the ENTIRE trimmed
|
|
6399
|
+
// text is a single call expression `identifier(...)` — empty args `()` or a
|
|
6400
|
+
// single object-literal `({ ... })` — with nothing but optional whitespace and
|
|
6401
|
+
// a trailing `;` after the closing paren. Returns null for anything else, which
|
|
6402
|
+
// is what keeps prose safe: `read({...}) loads a file` has trailing text, and
|
|
6403
|
+
// `bash` alone (no parens) is a bare word, so neither is a call. A naive
|
|
6404
|
+
// `^ident\(.*\)$` regex can't tell the closing paren of the arg object from a
|
|
6405
|
+
// paren inside a quoted string, so this walks the string honoring quotes and
|
|
6406
|
+
// brace/bracket/paren depth.
|
|
6407
|
+
export function isWholeMessageToolCall(text: string): string | null {
|
|
6408
|
+
const trimmed = text.trim()
|
|
6409
|
+
const nameMatch = /^([A-Za-z_][A-Za-z0-9_]*)\s*\(/.exec(trimmed)
|
|
6410
|
+
if (nameMatch === null) return null
|
|
6411
|
+
const name = nameMatch[1]!
|
|
6412
|
+
|
|
6413
|
+
let i = nameMatch[0].length - 1
|
|
6414
|
+
let depth = 0
|
|
6415
|
+
for (; i < trimmed.length; i++) {
|
|
6416
|
+
const ch = trimmed[i]!
|
|
6417
|
+
if (ch === '"' || ch === "'" || ch === '`') {
|
|
6418
|
+
i = skipStringLiteral(trimmed, i, ch)
|
|
6419
|
+
continue
|
|
6420
|
+
}
|
|
6421
|
+
if (ch === '(' || ch === '{' || ch === '[') {
|
|
6422
|
+
depth++
|
|
6423
|
+
continue
|
|
6424
|
+
}
|
|
6425
|
+
if (ch === ')' || ch === '}' || ch === ']') {
|
|
6426
|
+
depth--
|
|
6427
|
+
if (depth === 0) break
|
|
6428
|
+
continue
|
|
6429
|
+
}
|
|
6430
|
+
}
|
|
6431
|
+
|
|
6432
|
+
// Unbalanced (truncated mid-serialization) — still a leaked call, not prose.
|
|
6433
|
+
if (depth !== 0) return name
|
|
6434
|
+
|
|
6435
|
+
const rest = trimmed.slice(i + 1).trim()
|
|
6436
|
+
if (rest === '' || rest === ';') return name
|
|
6437
|
+
return null
|
|
6438
|
+
}
|
|
6439
|
+
|
|
6151
6440
|
// Tolerant single-purpose scanner that pulls the `text` argument out of a
|
|
6152
6441
|
// plain-text-serialized `channel_reply(...)` / `channel_send(...)` leak. A
|
|
6153
6442
|
// single regex covering every shape (double/single/unquoted keys, escaped
|
package/src/channels/schema.ts
CHANGED
|
@@ -16,6 +16,30 @@ export const ADAPTER_IDS = [
|
|
|
16
16
|
|
|
17
17
|
export type AdapterId = (typeof ADAPTER_IDS)[number]
|
|
18
18
|
|
|
19
|
+
export type ReadCapability = 'history' | 'message-get' | 'list'
|
|
20
|
+
|
|
21
|
+
// Which arbitrary-read callbacks each adapter registers when it starts healthy.
|
|
22
|
+
// A missing callback means "adapter-unavailable" (failed to start) ONLY for a
|
|
23
|
+
// capability listed here; capabilities an adapter never implements stay
|
|
24
|
+
// "not-supported" even when the adapter is configured and running. Kept as a
|
|
25
|
+
// static table because the distinction must survive a failed start() (which
|
|
26
|
+
// registers nothing), so it can't be derived from the live callback registry.
|
|
27
|
+
// The guard test in schema.test.ts asserts this matches what each adapter's
|
|
28
|
+
// start() actually registers — update both together or CI fails.
|
|
29
|
+
export const ADAPTER_READ_CAPABILITIES: Record<AdapterId, readonly ReadCapability[]> = {
|
|
30
|
+
discord: ['history'],
|
|
31
|
+
'discord-bot': ['history', 'message-get', 'list'],
|
|
32
|
+
github: ['history'],
|
|
33
|
+
instagram: ['history'],
|
|
34
|
+
line: ['history'],
|
|
35
|
+
kakaotalk: ['history'],
|
|
36
|
+
slack: ['history'],
|
|
37
|
+
'slack-bot': ['history', 'message-get', 'list'],
|
|
38
|
+
'telegram-bot': [],
|
|
39
|
+
webex: ['history'],
|
|
40
|
+
'webex-bot': ['history'],
|
|
41
|
+
}
|
|
42
|
+
|
|
19
43
|
const engagementTriggerSchema = z.enum(['mention', 'reply', 'dm'])
|
|
20
44
|
|
|
21
45
|
const stickinessSchema = z.union([
|
package/src/channels/types.ts
CHANGED
|
@@ -365,7 +365,8 @@ export type FetchHistoryResult =
|
|
|
365
365
|
// Registered per-adapter on the ChannelRouter alongside outbound/typing
|
|
366
366
|
// callbacks. Adapters that cannot fetch history (e.g. webhook-only future
|
|
367
367
|
// adapters) simply do not register one; the router answers
|
|
368
|
-
// 'history-not-supported' for those
|
|
368
|
+
// 'history-not-supported' for those, or 'history-adapter-unavailable' when the
|
|
369
|
+
// adapter is configured but failed to start (see setAdapterConfigured).
|
|
369
370
|
export type HistoryCallback = (args: FetchHistoryArgs) => Promise<FetchHistoryResult>
|
|
370
371
|
|
|
371
372
|
// Fetch a single message by its platform id from an arbitrary chat. Backs the
|
|
@@ -383,9 +384,11 @@ export type GetMessageArgs = {
|
|
|
383
384
|
export type GetMessageResult =
|
|
384
385
|
| { ok: true; message: ChannelHistoryMessage }
|
|
385
386
|
// `code: 'not-found'` is an expected miss (deleted/wrong id) the tool surfaces
|
|
386
|
-
// as a soft error; `code: 'not-supported'` means
|
|
387
|
-
//
|
|
388
|
-
|
|
387
|
+
// as a soft error; `code: 'not-supported'` means the adapter is not configured
|
|
388
|
+
// at all; `code: 'adapter-unavailable'` means it IS configured but currently
|
|
389
|
+
// has no live callback (e.g. failed to start), mirroring `fetchHistory`'s
|
|
390
|
+
// 'message-get-adapter-unavailable' string contract.
|
|
391
|
+
| { ok: false; error: string; code?: 'not-found' | 'not-supported' | 'adapter-unavailable' }
|
|
389
392
|
|
|
390
393
|
export type MessageGetCallback = (args: GetMessageArgs) => Promise<GetMessageResult>
|
|
391
394
|
|
|
@@ -408,7 +411,7 @@ export type ListChannelsArgs = {
|
|
|
408
411
|
|
|
409
412
|
export type ListChannelsResult =
|
|
410
413
|
| { ok: true; entries: ChannelListEntry[]; nextCursor?: string }
|
|
411
|
-
| { ok: false; error: string; code?: 'not-supported' }
|
|
414
|
+
| { ok: false; error: string; code?: 'not-supported' | 'adapter-unavailable' }
|
|
412
415
|
|
|
413
416
|
// Backs the `channel_read` tool's `mode: "list"`. Opt-in per adapter like
|
|
414
417
|
// history; the router answers 'list-not-supported' when none is registered.
|
package/src/cli/channel.ts
CHANGED
|
@@ -183,7 +183,11 @@ const setSub = defineCommand({
|
|
|
183
183
|
},
|
|
184
184
|
})
|
|
185
185
|
|
|
186
|
-
|
|
186
|
+
// Adapters that re-authenticate through a full interactive login replay rather
|
|
187
|
+
// than a token-field rotation (`channel set`). Discord (User) belongs here — its
|
|
188
|
+
// unofficial QR session expires and is refreshed by replaying the QR login, the
|
|
189
|
+
// same shape as LINE's QR flow. `discord-bot` stays in SETTABLE_ADAPTERS.
|
|
190
|
+
const REAUTHABLE_ADAPTERS = ['line', 'instagram', 'kakaotalk', 'webex', 'discord'] as const
|
|
187
191
|
type ReauthableAdapter = (typeof REAUTHABLE_ADAPTERS)[number]
|
|
188
192
|
|
|
189
193
|
const reauthSub = defineCommand({
|
|
@@ -405,9 +409,7 @@ async function resolveReauthableAdapter(
|
|
|
405
409
|
): Promise<ReauthableAdapter> {
|
|
406
410
|
if (requested !== undefined) {
|
|
407
411
|
if (!isReauthableAdapter(requested)) {
|
|
408
|
-
console.error(
|
|
409
|
-
errorLine(`Adapter "${requested}" does not support reauth. Supported: ${REAUTHABLE_ADAPTERS.join(', ')}.`),
|
|
410
|
-
)
|
|
412
|
+
console.error(errorLine(reauthAdapterRejectionMessage(requested)))
|
|
411
413
|
process.exit(1)
|
|
412
414
|
}
|
|
413
415
|
if (!configured.has(requested)) {
|
|
@@ -448,6 +450,14 @@ function isReauthableAdapter(value: string): value is ReauthableAdapter {
|
|
|
448
450
|
return (REAUTHABLE_ADAPTERS as ReadonlyArray<string>).includes(value)
|
|
449
451
|
}
|
|
450
452
|
|
|
453
|
+
// Returns the string (rather than exiting inline) so the routing stays testable.
|
|
454
|
+
export function reauthAdapterRejectionMessage(adapter: string): string {
|
|
455
|
+
if (isSettableAdapter(adapter)) {
|
|
456
|
+
return `Adapter "${adapter}" does not support reauth. Use \`typeclaw channel set ${adapter}\` to rotate its credentials.`
|
|
457
|
+
}
|
|
458
|
+
return `Adapter "${adapter}" does not support reauth. Supported: ${REAUTHABLE_ADAPTERS.join(', ')}.`
|
|
459
|
+
}
|
|
460
|
+
|
|
451
461
|
async function runReauth(cwd: string, adapter: ReauthableAdapter): Promise<void> {
|
|
452
462
|
switch (adapter) {
|
|
453
463
|
case 'line':
|
|
@@ -462,6 +472,9 @@ async function runReauth(cwd: string, adapter: ReauthableAdapter): Promise<void>
|
|
|
462
472
|
case 'webex':
|
|
463
473
|
await runWebexReauth(cwd)
|
|
464
474
|
return
|
|
475
|
+
case 'discord':
|
|
476
|
+
await runDiscordReauth(cwd)
|
|
477
|
+
return
|
|
465
478
|
}
|
|
466
479
|
}
|
|
467
480
|
|
|
@@ -540,6 +553,17 @@ async function runWebexReauth(cwd: string): Promise<void> {
|
|
|
540
553
|
await maybePromptReauthRefresh(cwd, 'webex')
|
|
541
554
|
}
|
|
542
555
|
|
|
556
|
+
async function runDiscordReauth(cwd: string): Promise<void> {
|
|
557
|
+
const result = await runDiscordBootstrap({ agentDir: cwd, onQrUrl: renderDiscordQrToTerminal })
|
|
558
|
+
if (!result.ok) {
|
|
559
|
+
console.error(errorLine(`Discord login failed: ${result.reason}`))
|
|
560
|
+
process.exit(1)
|
|
561
|
+
}
|
|
562
|
+
process.stdout.write(`${successLine('Discord credentials refreshed in secrets.json.')}\n`)
|
|
563
|
+
|
|
564
|
+
await maybePromptReauthRefresh(cwd, 'discord')
|
|
565
|
+
}
|
|
566
|
+
|
|
543
567
|
async function readExistingKakaotalkEmail(cwd: string): Promise<string | undefined> {
|
|
544
568
|
try {
|
|
545
569
|
const store = new SecretsKakaoCredentialStore({ mode: 'host', secretsPath: `${cwd}/secrets.json` })
|
|
@@ -771,17 +795,20 @@ function isSettableAdapter(value: string): value is SettableAdapter {
|
|
|
771
795
|
return (SETTABLE_ADAPTERS as ReadonlyArray<string>).includes(value)
|
|
772
796
|
}
|
|
773
797
|
|
|
798
|
+
// Returns the string (rather than exiting inline) so the routing stays testable.
|
|
799
|
+
export function setAdapterRejectionMessage(adapter: string): string {
|
|
800
|
+
if (isReauthableAdapter(adapter)) {
|
|
801
|
+
return `Adapter "${adapter}" does not support \`channel set\`. Use \`typeclaw channel reauth ${adapter}\` instead.`
|
|
802
|
+
}
|
|
803
|
+
if (isChannelKind(adapter)) {
|
|
804
|
+
return `Adapter "${adapter}" does not support \`channel set\`. Rotate its credentials by removing and re-adding it: \`typeclaw channel remove ${adapter} && typeclaw channel add ${adapter}\`.`
|
|
805
|
+
}
|
|
806
|
+
return `Unknown adapter "${adapter}". Expected one of: ${SETTABLE_ADAPTERS.join(', ')}.`
|
|
807
|
+
}
|
|
808
|
+
|
|
774
809
|
function validateSetAdapterArg(adapter: string, configured: Set<ChannelKind>): SettableAdapter {
|
|
775
810
|
if (!isSettableAdapter(adapter)) {
|
|
776
|
-
|
|
777
|
-
console.error(
|
|
778
|
-
errorLine(
|
|
779
|
-
`Adapter "${adapter}" does not support \`channel set\`. Use \`typeclaw channel reauth ${adapter}\` instead.`,
|
|
780
|
-
),
|
|
781
|
-
)
|
|
782
|
-
} else {
|
|
783
|
-
console.error(errorLine(`Unknown adapter "${adapter}". Expected one of: ${SETTABLE_ADAPTERS.join(', ')}.`))
|
|
784
|
-
}
|
|
811
|
+
console.error(errorLine(setAdapterRejectionMessage(adapter)))
|
|
785
812
|
process.exit(1)
|
|
786
813
|
}
|
|
787
814
|
if (!configured.has(adapter)) {
|