typeclaw 0.42.1 → 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/auth.schema.json +16 -0
- package/package.json +2 -2
- package/secrets.schema.json +16 -0
- package/src/agent/index.ts +9 -2
- package/src/agent/live-subagents.ts +4 -4
- package/src/agent/plugin-tools.ts +8 -2
- package/src/agent/session-origin.ts +6 -3
- package/src/agent/system-prompt.ts +41 -3
- package/src/agent/tools/channel-react.ts +5 -4
- package/src/agent/tools/spawn-subagent.ts +80 -24
- package/src/bundled-plugins/planner/planner.ts +1 -1
- package/src/bundled-plugins/researcher/researcher.ts +2 -2
- package/src/bundled-plugins/reviewer/reviewer.ts +1 -1
- package/src/channels/adapters/discord-bot-thread-room.ts +73 -0
- package/src/channels/adapters/discord-bot.ts +85 -4
- package/src/channels/adapters/discord.ts +15 -2
- package/src/channels/adapters/slack-bot-classify.ts +1 -0
- package/src/channels/adapters/slack-classify.ts +1 -0
- package/src/channels/engagement.ts +33 -0
- package/src/channels/manager.ts +9 -1
- package/src/channels/router.ts +500 -91
- package/src/channels/schema.ts +24 -0
- package/src/channels/types.ts +18 -5
- package/src/cli/channel.ts +40 -13
- package/src/cli/command-meta.ts +2 -0
- package/src/cli/index.ts +1 -0
- package/src/cli/mcp.ts +233 -0
- package/src/hostd/daemon.ts +28 -9
- package/src/hostd/protocol.ts +12 -9
- package/src/mcp/client.ts +15 -5
- package/src/mcp/index.ts +12 -0
- package/src/mcp/manager.ts +9 -4
- package/src/mcp/oauth.ts +212 -0
- package/src/run/index.ts +15 -2
- package/src/sandbox/hidden-paths.ts +59 -0
- package/src/sandbox/index.ts +1 -1
- package/src/secrets/index.ts +1 -1
- package/src/secrets/schema.ts +13 -0
- package/src/secrets/secrets-provider.ts +2 -2
- package/src/secrets/storage.ts +108 -1
- package/src/skills/typeclaw-channel-github/SKILL.md +2 -2
- package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
|
@@ -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,
|
|
@@ -55,6 +57,7 @@ import {
|
|
|
55
57
|
registerCommands,
|
|
56
58
|
type DiscordCommandDeclaration,
|
|
57
59
|
} from './discord-bot-slash-commands'
|
|
60
|
+
import { createDiscordThreadRoomResolver } from './discord-bot-thread-room'
|
|
58
61
|
import { addDiscordMentionHints, type DiscordMentionUser } from './mention-hints'
|
|
59
62
|
|
|
60
63
|
// One declared slash command per logical agent gesture. /stop maps to the
|
|
@@ -741,13 +744,26 @@ function clampLimit(requested: number, max: number): number {
|
|
|
741
744
|
// the upload error (the file the agent wanted to share is the load-bearing
|
|
742
745
|
// part of the message). The text post is best-effort and only attempted
|
|
743
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.
|
|
744
757
|
export function createOutboundCallback(deps: {
|
|
745
758
|
client: Pick<DiscordBotClient, 'sendMessage' | 'uploadFile'>
|
|
746
759
|
logger: DiscordBotAdapterLogger
|
|
747
760
|
formatChannelTag: (workspace: string, chat: string) => Promise<string>
|
|
761
|
+
token: string
|
|
748
762
|
resolvePath?: (path: string) => string
|
|
763
|
+
fetchImpl?: typeof fetch
|
|
749
764
|
}): OutboundCallback {
|
|
750
|
-
const { client, logger, formatChannelTag, resolvePath } = deps
|
|
765
|
+
const { client, logger, formatChannelTag, token, resolvePath } = deps
|
|
766
|
+
const fetchImpl = deps.fetchImpl ?? fetch
|
|
751
767
|
return async (msg: OutboundMessage): Promise<SendResult> => {
|
|
752
768
|
if (msg.adapter !== 'discord-bot') {
|
|
753
769
|
return { ok: false, error: `unknown adapter: ${msg.adapter}` }
|
|
@@ -762,10 +778,25 @@ export function createOutboundCallback(deps: {
|
|
|
762
778
|
`[discord-bot] outbound ${tag} text_len=${text.length} attachments=${attachments.length}${msg.thread ? ` thread=${msg.thread}` : ''}`,
|
|
763
779
|
)
|
|
764
780
|
|
|
765
|
-
|
|
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()) {
|
|
766
787
|
const path = resolvePath ? resolvePath(attachment.path) : attachment.path
|
|
788
|
+
const referenceThisFile = index === 0 ? replyOnFirstFile : undefined
|
|
767
789
|
try {
|
|
768
|
-
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)
|
|
769
800
|
logger.info(`[discord-bot] uploaded id=${file.id} filename=${file.filename} size=${file.size} ${tag}`)
|
|
770
801
|
if (msg.thread) {
|
|
771
802
|
logger.warn(
|
|
@@ -803,6 +834,47 @@ export function createOutboundCallback(deps: {
|
|
|
803
834
|
}
|
|
804
835
|
}
|
|
805
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
|
+
|
|
806
878
|
// Discord CDN URLs (`cdn.discordapp.com/attachments/...`) are signed and
|
|
807
879
|
// expire (~24h). Sending the bot token alongside makes no difference for
|
|
808
880
|
// public CDN URLs (Discord ignores it), but is required for the rare
|
|
@@ -954,6 +1026,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
|
|
|
954
1026
|
let stopWaiters: Array<() => void> = []
|
|
955
1027
|
|
|
956
1028
|
const channelResolver = createDiscordChannelResolver({ token: options.token })
|
|
1029
|
+
const threadRoomResolver = createDiscordThreadRoomResolver({ token: options.token, fetchImpl })
|
|
957
1030
|
|
|
958
1031
|
// Discord mentions by snowflake id (`<@id>`/`<@!id>`), so no username form.
|
|
959
1032
|
const selfIdentityResolver: ChannelSelfIdentityResolver = () => (botUserId !== null ? { id: botUserId } : null)
|
|
@@ -997,6 +1070,8 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
|
|
|
997
1070
|
client,
|
|
998
1071
|
logger,
|
|
999
1072
|
formatChannelTag,
|
|
1073
|
+
token: options.token,
|
|
1074
|
+
fetchImpl,
|
|
1000
1075
|
})
|
|
1001
1076
|
|
|
1002
1077
|
const fetchAttachmentCallback = createFetchAttachmentCallback({ token: options.token, logger })
|
|
@@ -1061,10 +1136,16 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
|
|
|
1061
1136
|
}
|
|
1062
1137
|
},
|
|
1063
1138
|
})
|
|
1064
|
-
|
|
1139
|
+
// Discord threads are their own channels (`chat = thread id`, `thread`
|
|
1140
|
+
// stays null), so the engagement gate cannot see "this is a thread" from
|
|
1141
|
+
// the payload alone. Resolve the channel's type/parent and stamp the
|
|
1142
|
+
// structural `room` signal for guild inbounds; DMs are never thread rooms.
|
|
1143
|
+
const room = event.guild_id !== undefined ? await threadRoomResolver(event.channel_id) : undefined
|
|
1144
|
+
const basePayload =
|
|
1065
1145
|
referenceResult.referenceContext === undefined
|
|
1066
1146
|
? { ...verdict.payload, text: hintedText }
|
|
1067
1147
|
: { ...verdict.payload, text: hintedText, referenceContext: referenceResult.referenceContext }
|
|
1148
|
+
const payload = room !== undefined ? { ...basePayload, room } : basePayload
|
|
1068
1149
|
|
|
1069
1150
|
const routedTag = await formatChannelTag(payload.workspace, payload.chat)
|
|
1070
1151
|
logger.info(
|
|
@@ -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) {
|
|
@@ -143,6 +143,7 @@ export function classifyInbound(
|
|
|
143
143
|
workspace,
|
|
144
144
|
chat: event.channel,
|
|
145
145
|
thread,
|
|
146
|
+
...(thread !== null ? { room: { kind: 'thread' as const } } : {}),
|
|
146
147
|
...(typingThread !== undefined ? { typingThread } : {}),
|
|
147
148
|
text,
|
|
148
149
|
...(attachments.length > 0 ? { attachments } : {}),
|
|
@@ -49,6 +49,7 @@ export function classifyInbound(
|
|
|
49
49
|
workspace,
|
|
50
50
|
chat: event.channel,
|
|
51
51
|
thread,
|
|
52
|
+
...(thread !== null ? { room: { kind: 'thread' as const } } : {}),
|
|
52
53
|
text: rawText,
|
|
53
54
|
externalMessageId: event.ts,
|
|
54
55
|
reactionRef: encodeSlackReactionRef({ channel: event.channel, ts: event.ts }),
|
|
@@ -216,11 +216,44 @@ export function decideEngagement(input: EngagementInput): EngagementDecision {
|
|
|
216
216
|
// fallback fix.
|
|
217
217
|
if (targetsSomeoneElse(message, participants, botInThread)) return 'observe'
|
|
218
218
|
|
|
219
|
+
// Thread solo-fallback fail-closed gate. A thread is a SEPARATE live session
|
|
220
|
+
// from its parent channel (the participant/membership key carries the thread
|
|
221
|
+
// suffix — see `channelKeyId`), so a freshly-opened thread starts with one
|
|
222
|
+
// known speaker and a cold membership cache. That collapses `effectiveHumans`
|
|
223
|
+
// to ≤1 and would trip the solo-human fallback below, making the bot butt
|
|
224
|
+
// into a thread it was never part of in a busy multi-human channel. Membership
|
|
225
|
+
// is a room property, not a thread property, so a thread may ride the fallback
|
|
226
|
+
// ONLY on a fresh, complete membership read that itself proves ≤1 human; null
|
|
227
|
+
// / truncated / stale reads fail closed to `observe`. Exemptions: DMs (solo by
|
|
228
|
+
// construction) and threads the bot ALREADY participates in (`botInThread` —
|
|
229
|
+
// an established conversation, not an un-addressed intrusion; this is the same
|
|
230
|
+
// escape hatch the `replyToOtherMessageId` suppressor uses). Non-thread solo
|
|
231
|
+
// channels keep the legacy answer-everything fallback untouched.
|
|
232
|
+
//
|
|
233
|
+
// `isThreadRoom` reads the structural `room` signal FIRST so this fires for
|
|
234
|
+
// Discord threads too (their `thread` is null — the thread id lives in
|
|
235
|
+
// `chat`), falling back to `thread !== null` for Slack-shaped inbounds.
|
|
236
|
+
if (isThreadRoom(message) && !botInThread && !isFreshCompleteSoloRoom(input.membership, now)) {
|
|
237
|
+
return 'observe'
|
|
238
|
+
}
|
|
239
|
+
|
|
219
240
|
if (effectiveHumans <= 1 && !message.authorIsBot) return 'engage'
|
|
220
241
|
|
|
221
242
|
return 'observe'
|
|
222
243
|
}
|
|
223
244
|
|
|
245
|
+
function isThreadRoom(message: InboundMessage): boolean {
|
|
246
|
+
if (message.isDm) return false
|
|
247
|
+
return message.room?.kind === 'thread' || message.thread !== null
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function isFreshCompleteSoloRoom(membership: MembershipCount | null, now: number): boolean {
|
|
251
|
+
if (membership === null) return false
|
|
252
|
+
if (membership.truncated) return false
|
|
253
|
+
if (now - membership.fetchedAt >= MEMBERSHIP_FRESHNESS_MS) return false
|
|
254
|
+
return membership.humans <= 1
|
|
255
|
+
}
|
|
256
|
+
|
|
224
257
|
// Structural "this message is addressed to someone other than us" test. Pure
|
|
225
258
|
// over adapter-classified booleans + observed peer names — no semantic text
|
|
226
259
|
// interpretation, so it is safe for the content-blind engagement gate. Shared
|
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 {
|