typeclaw 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +3 -2
  2. package/auth.schema.json +57 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +57 -0
  5. package/src/agent/index.ts +10 -6
  6. package/src/agent/multimodal/look-at.ts +87 -0
  7. package/src/agent/session-origin.ts +1 -0
  8. package/src/agent/tools/channel-history-render.ts +21 -0
  9. package/src/agent/tools/channel-history.ts +2 -17
  10. package/src/agent/tools/channel-read.ts +206 -0
  11. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +26 -2
  12. package/src/bundled-plugins/github-cli-auth/index.ts +25 -6
  13. package/src/bundled-plugins/memory/index.ts +10 -11
  14. package/src/bundled-plugins/memory/vector/hybrid.ts +73 -6
  15. package/src/bundled-plugins/memory/vector/index-on-write.ts +25 -20
  16. package/src/bundled-plugins/memory/vector/passages.ts +2 -24
  17. package/src/bundled-plugins/memory/vector/reference-index-on-write.ts +28 -23
  18. package/src/bundled-plugins/memory/vector/store.ts +2 -0
  19. package/src/bundled-plugins/memory/vector/truncation.ts +28 -0
  20. package/src/bundled-plugins/planner/planner.ts +4 -2
  21. package/src/bundled-plugins/reviewer/reviewer.ts +9 -1
  22. package/src/bundled-plugins/tool-result-cap/README.md +10 -1
  23. package/src/bundled-plugins/tool-result-cap/cap-result.ts +8 -0
  24. package/src/channels/adapters/discord-bot.ts +112 -0
  25. package/src/channels/adapters/instagram-channel-resolver.ts +113 -0
  26. package/src/channels/adapters/instagram-classify.ts +69 -0
  27. package/src/channels/adapters/instagram-format.ts +8 -0
  28. package/src/channels/adapters/instagram.ts +346 -0
  29. package/src/channels/adapters/kakaotalk-classify.ts +31 -6
  30. package/src/channels/adapters/kakaotalk.ts +1 -1
  31. package/src/channels/adapters/slack-bot.ts +147 -0
  32. package/src/channels/manager.ts +60 -2
  33. package/src/channels/router.ts +64 -0
  34. package/src/channels/schema.ts +5 -0
  35. package/src/channels/types.ts +46 -0
  36. package/src/cli/channel.ts +76 -1
  37. package/src/cli/init.ts +1 -0
  38. package/src/cli/status.ts +37 -14
  39. package/src/config/channels-mutation.ts +2 -1
  40. package/src/doctor/channel-checks.ts +28 -0
  41. package/src/hostd/daemon.ts +59 -19
  42. package/src/hostd/kakao-renewal-manager.ts +35 -10
  43. package/src/hostd/protocol.ts +2 -0
  44. package/src/hostd/tailscale.ts +41 -5
  45. package/src/hostd/webex-renewal-manager.ts +13 -4
  46. package/src/init/index.ts +50 -1
  47. package/src/init/instagram-auth.ts +134 -0
  48. package/src/init/run-owner-claim.ts +1 -0
  49. package/src/permissions/match-rule.ts +1 -1
  50. package/src/permissions/resolve.ts +1 -0
  51. package/src/plugin/index.ts +1 -0
  52. package/src/plugin/manager.ts +14 -0
  53. package/src/plugin/registry.ts +12 -0
  54. package/src/plugin/types.ts +4 -0
  55. package/src/role-claim/match-rule.ts +2 -1
  56. package/src/run/index.ts +46 -20
  57. package/src/secrets/instagram-store.ts +112 -0
  58. package/src/secrets/schema.ts +18 -0
  59. package/src/skills/typeclaw-channel-instagram/SKILL.md +30 -0
  60. package/src/test-helpers/rm-temp-dir.ts +24 -0
  61. package/typeclaw.schema.json +161 -1
@@ -19,11 +19,18 @@ import type { ChannelRouter } from '@/channels/router'
19
19
  import type { ChannelAdapterConfig } from '@/channels/schema'
20
20
  import type {
21
21
  ChannelHistoryMessage,
22
+ ChannelListEntry,
22
23
  ChannelSelfIdentityResolver,
23
24
  FetchAttachmentCallback,
24
25
  FetchHistoryArgs,
25
26
  FetchHistoryResult,
27
+ GetMessageArgs,
28
+ GetMessageResult,
26
29
  HistoryCallback,
30
+ ListCallback,
31
+ ListChannelsArgs,
32
+ ListChannelsResult,
33
+ MessageGetCallback,
27
34
  OutboundCallback,
28
35
  OutboundMessage,
29
36
  ResolvedChannelNames,
@@ -185,6 +192,12 @@ type DiscordChannelObject = {
185
192
  permission_overwrites?: DiscordPermissionOverwrite[]
186
193
  }
187
194
 
195
+ type DiscordListChannel = {
196
+ id?: string
197
+ name?: string
198
+ type?: number
199
+ }
200
+
188
201
  type DiscordRole = {
189
202
  id?: string
190
203
  permissions?: string
@@ -578,6 +591,91 @@ export function createDiscordHistoryCallback(deps: {
578
591
  }
579
592
  }
580
593
 
594
+ // Fetch one message via GET /channels/{id}/messages/{message_id}. Reuses
595
+ // mapDiscordMessage so a single message renders identically to a history entry.
596
+ // A 404 from Discord (deleted/unknown id) maps to a soft not-found.
597
+ export function createDiscordMessageGetCallback(deps: {
598
+ token: string
599
+ logger: DiscordBotAdapterLogger
600
+ botUserIdRef: () => string | null
601
+ fetchImpl?: typeof fetch
602
+ }): MessageGetCallback {
603
+ const { token, logger, botUserIdRef } = deps
604
+ const fetchFn = deps.fetchImpl ?? fetch
605
+ return async (args: GetMessageArgs): Promise<GetMessageResult> => {
606
+ const channelId = args.thread ?? args.chat
607
+ let response: Response
608
+ try {
609
+ response = await fetchFn(`${DISCORD_API_BASE}/channels/${channelId}/messages/${args.messageId}`, {
610
+ method: 'GET',
611
+ headers: { Authorization: `Bot ${token}` },
612
+ })
613
+ } catch (err) {
614
+ const message = err instanceof Error ? err.message : String(err)
615
+ logger.warn(`[discord-bot] message get failed: ${message}`)
616
+ return { ok: false, error: message }
617
+ }
618
+ if (response.status === 404) return { ok: false, error: 'message not found', code: 'not-found' }
619
+ if (!response.ok) return { ok: false, error: `http ${response.status}` }
620
+ let raw: DiscordRawHistoryMessage
621
+ try {
622
+ raw = (await response.json()) as DiscordRawHistoryMessage
623
+ } catch (err) {
624
+ const message = err instanceof Error ? err.message : String(err)
625
+ return { ok: false, error: `parse failed: ${message}` }
626
+ }
627
+ return { ok: true, message: mapDiscordMessage(raw, botUserIdRef()) }
628
+ }
629
+ }
630
+
631
+ // List a guild's channels via GET /guilds/{guild}/channels. Only message-
632
+ // readable types are surfaced (text 0, announcement 5, forum 15, media 16, and
633
+ // thread types 10/11/12); non-message channels the agent cannot channel_read —
634
+ // category 4, voice 2, stage 13 — are dropped so they never appear as readable
635
+ // chats. Membership is not reported by this endpoint, so isMember is omitted.
636
+ export function createDiscordListCallback(deps: {
637
+ token: string
638
+ logger: DiscordBotAdapterLogger
639
+ fetchImpl?: typeof fetch
640
+ }): ListCallback {
641
+ const { token, logger } = deps
642
+ const fetchFn = deps.fetchImpl ?? fetch
643
+ return async (args: ListChannelsArgs): Promise<ListChannelsResult> => {
644
+ let response: Response
645
+ try {
646
+ response = await fetchFn(`${DISCORD_API_BASE}/guilds/${args.workspace}/channels`, {
647
+ method: 'GET',
648
+ headers: { Authorization: `Bot ${token}` },
649
+ })
650
+ } catch (err) {
651
+ const message = err instanceof Error ? err.message : String(err)
652
+ logger.warn(`[discord-bot] channel list failed: ${message}`)
653
+ return { ok: false, error: message }
654
+ }
655
+ if (!response.ok) return { ok: false, error: `http ${response.status}` }
656
+ let raw: DiscordListChannel[]
657
+ try {
658
+ raw = (await response.json()) as DiscordListChannel[]
659
+ } catch (err) {
660
+ const message = err instanceof Error ? err.message : String(err)
661
+ return { ok: false, error: `parse failed: ${message}` }
662
+ }
663
+ const entries = raw
664
+ .filter((c) => c.id !== undefined && c.type !== undefined && DISCORD_READABLE_CHANNEL_TYPES.has(c.type))
665
+ .map((c) => mapDiscordListChannel(c))
666
+ return { ok: true, entries: entries.slice(0, clampLimit(args.limit, DISCORD_HISTORY_LIMIT_MAX)) }
667
+ }
668
+ }
669
+
670
+ const DISCORD_THREAD_TYPES = new Set([10, 11, 12])
671
+ const DISCORD_READABLE_CHANNEL_TYPES = new Set([0, 5, 15, 16, 10, 11, 12])
672
+
673
+ function mapDiscordListChannel(c: DiscordListChannel): ChannelListEntry {
674
+ const kind: ChannelListEntry['kind'] = c.type !== undefined && DISCORD_THREAD_TYPES.has(c.type) ? 'thread' : 'channel'
675
+ const name = c.name !== undefined && c.name !== '' ? `#${c.name}` : (c.id ?? 'unknown')
676
+ return { chat: c.id ?? 'unknown', name, kind }
677
+ }
678
+
581
679
  function mapDiscordMessage(msg: DiscordRawHistoryMessage, botUserId: string | null): ChannelHistoryMessage {
582
680
  // A thread started from an existing message exposes that opener only as the
583
681
  // type-21 starter's `referenced_message` — the starter itself has empty
@@ -881,6 +979,14 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
881
979
  botUserIdRef: () => botUserId,
882
980
  })
883
981
 
982
+ const messageGetCallback = createDiscordMessageGetCallback({
983
+ token: options.token,
984
+ logger,
985
+ botUserIdRef: () => botUserId,
986
+ })
987
+
988
+ const listCallback = createDiscordListCallback({ token: options.token, logger })
989
+
884
990
  const membershipResolver = createDiscordMembershipResolver({
885
991
  token: options.token,
886
992
  logger,
@@ -1042,6 +1148,8 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1042
1148
  options.router.registerChannelNameResolver('discord-bot', channelResolver)
1043
1149
  options.router.registerSelfIdentity('discord-bot', selfIdentityResolver)
1044
1150
  options.router.registerHistory('discord-bot', historyCallback)
1151
+ options.router.registerMessageGet('discord-bot', messageGetCallback)
1152
+ options.router.registerList('discord-bot', listCallback)
1045
1153
  options.router.registerFetchAttachment('discord-bot', fetchAttachmentCallback)
1046
1154
  options.router.registerMembership('discord-bot', membershipResolver)
1047
1155
 
@@ -1060,6 +1168,8 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1060
1168
  options.router.unregisterChannelNameResolver('discord-bot', channelResolver)
1061
1169
  options.router.unregisterSelfIdentity('discord-bot', selfIdentityResolver)
1062
1170
  options.router.unregisterHistory('discord-bot', historyCallback)
1171
+ options.router.unregisterMessageGet('discord-bot', messageGetCallback)
1172
+ options.router.unregisterList('discord-bot', listCallback)
1063
1173
  options.router.unregisterFetchAttachment('discord-bot', fetchAttachmentCallback)
1064
1174
  options.router.unregisterMembership('discord-bot', membershipResolver)
1065
1175
  listener = null
@@ -1081,6 +1191,8 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1081
1191
  options.router.unregisterChannelNameResolver('discord-bot', channelResolver)
1082
1192
  options.router.unregisterSelfIdentity('discord-bot', selfIdentityResolver)
1083
1193
  options.router.unregisterHistory('discord-bot', historyCallback)
1194
+ options.router.unregisterMessageGet('discord-bot', messageGetCallback)
1195
+ options.router.unregisterList('discord-bot', listCallback)
1084
1196
  options.router.unregisterFetchAttachment('discord-bot', fetchAttachmentCallback)
1085
1197
  options.router.unregisterMembership('discord-bot', membershipResolver)
1086
1198
  if (inflightInbounds > 0) {
@@ -0,0 +1,113 @@
1
+ import type { InstagramChatSummary } from 'agent-messenger/instagram'
2
+
3
+ import type { ChannelKey, ChannelNameResolver, ResolvedChannelNames } from '@/channels/types'
4
+
5
+ const DEFAULT_TTL_MS = 5 * 60 * 1000
6
+ const CHAT_FETCH_LIMIT = 500
7
+
8
+ export type InstagramWorkspace = '@instagram-dm' | '@instagram-group'
9
+
10
+ export function instagramWorkspaceForChat(chat: Pick<InstagramChatSummary, 'type' | 'is_group'>): InstagramWorkspace {
11
+ return chat.type === 'private' && !chat.is_group ? '@instagram-dm' : '@instagram-group'
12
+ }
13
+
14
+ export type InstagramChatLookupValue = {
15
+ workspace: InstagramWorkspace
16
+ isDm: boolean
17
+ }
18
+
19
+ export type InstagramChannelResolver = {
20
+ resolve: ChannelNameResolver
21
+ lookupChat: (chatId: string) => InstagramChatLookupValue | null
22
+ refresh: () => Promise<void>
23
+ // Inbound events can arrive before listChats() surfaces the thread. Default
24
+ // provisional entries to the stricter group bucket until a real refresh can
25
+ // prove the chat is a DM.
26
+ ingestProvisional: (chatId: string) => void
27
+ }
28
+
29
+ export type InstagramChannelResolverOptions = {
30
+ client: { listChats(limit?: number): Promise<InstagramChatSummary[]> }
31
+ now?: () => number
32
+ ttlMs?: number
33
+ logger?: { warn: (msg: string) => void }
34
+ }
35
+
36
+ type Entry = {
37
+ workspace: InstagramWorkspace
38
+ isDm: boolean
39
+ chatName: string | null
40
+ expiresAt: number
41
+ }
42
+
43
+ export function createInstagramChannelResolver(options: InstagramChannelResolverOptions): InstagramChannelResolver {
44
+ const now = options.now ?? Date.now
45
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
46
+ const cache = new Map<string, Entry>()
47
+ let inflight: Promise<void> | null = null
48
+
49
+ const refresh = async (): Promise<void> => {
50
+ if (inflight !== null) {
51
+ await inflight
52
+ return
53
+ }
54
+ const promise = loadAll().finally(() => {
55
+ inflight = null
56
+ })
57
+ inflight = promise
58
+ await promise
59
+ }
60
+
61
+ const loadAll = async (): Promise<void> => {
62
+ try {
63
+ const chats = await options.client.listChats(CHAT_FETCH_LIMIT)
64
+ const expiresAt = now() + ttlMs
65
+ for (const chat of chats) ingest(chat, expiresAt)
66
+ } catch (err) {
67
+ options.logger?.warn(`[instagram] channel resolver refresh failed: ${describe(err)}`)
68
+ }
69
+ }
70
+
71
+ const ingest = (chat: InstagramChatSummary, expiresAt: number): void => {
72
+ const workspace = instagramWorkspaceForChat(chat)
73
+ cache.set(chat.id, {
74
+ workspace,
75
+ isDm: workspace === '@instagram-dm',
76
+ chatName: chat.name === '' ? null : chat.name,
77
+ expiresAt,
78
+ })
79
+ }
80
+
81
+ const resolve: ChannelNameResolver = async (key: ChannelKey): Promise<ResolvedChannelNames> => {
82
+ const entry = cache.get(key.chat)
83
+ if (entry === undefined || entry.expiresAt <= now()) await refresh()
84
+ const fresh = cache.get(key.chat)
85
+ if (fresh === undefined) return {}
86
+ const result: ResolvedChannelNames = {}
87
+ if (fresh.chatName !== null && fresh.chatName !== '') result.chatName = fresh.chatName
88
+ return result
89
+ }
90
+
91
+ const lookupChat = (chatId: string): InstagramChatLookupValue | null => {
92
+ const entry = cache.get(chatId)
93
+ if (entry === undefined || entry.expiresAt <= now()) return null
94
+ return { workspace: entry.workspace, isDm: entry.isDm }
95
+ }
96
+
97
+ const ingestProvisional = (chatId: string): void => {
98
+ const existing = cache.get(chatId)
99
+ if (existing !== undefined && existing.expiresAt > now()) return
100
+ cache.set(chatId, {
101
+ workspace: '@instagram-group',
102
+ isDm: false,
103
+ chatName: null,
104
+ expiresAt: now() + ttlMs,
105
+ })
106
+ }
107
+
108
+ return { resolve, lookupChat, refresh, ingestProvisional }
109
+ }
110
+
111
+ function describe(err: unknown): string {
112
+ return err instanceof Error ? err.message : String(err)
113
+ }
@@ -0,0 +1,69 @@
1
+ import type { InstagramMessageSummary } from 'agent-messenger/instagram'
2
+
3
+ import { matchesAnyAlias } from '@/channels/engagement'
4
+ import type { ChannelAdapterConfig } from '@/channels/schema'
5
+ import type { InboundMessage } from '@/channels/types'
6
+
7
+ import type { InstagramChatLookupValue } from './instagram-channel-resolver'
8
+
9
+ export type InboundDropReason = 'self_author' | 'empty_text' | 'unknown_chat' | 'pre_connect'
10
+
11
+ export type InboundClassification =
12
+ | { kind: 'drop'; reason: InboundDropReason }
13
+ | { kind: 'route'; payload: InboundMessage }
14
+
15
+ export type InstagramChatLookup = (chatId: string) => InstagramChatLookupValue | null
16
+
17
+ export type InstagramInboundContext = {
18
+ selfUserId: string | null
19
+ lookupChat: InstagramChatLookup
20
+ selfAliases?: readonly string[]
21
+ }
22
+
23
+ export function classifyInbound(
24
+ message: InstagramMessageSummary,
25
+ _config: ChannelAdapterConfig,
26
+ context: InstagramInboundContext,
27
+ ): InboundClassification {
28
+ if (context.selfUserId === null) return { kind: 'drop', reason: 'pre_connect' }
29
+ if (message.is_outgoing || message.from === context.selfUserId) return { kind: 'drop', reason: 'self_author' }
30
+
31
+ const rawText = message.text ?? ''
32
+ if (rawText === '' && message.media_url === undefined) return { kind: 'drop', reason: 'empty_text' }
33
+ const text = rawText === '' ? instagramMediaPlaceholder(message.type) : rawText
34
+
35
+ const chatInfo = context.lookupChat(message.thread_id)
36
+ if (chatInfo === null) return { kind: 'drop', reason: 'unknown_chat' }
37
+
38
+ // Instagram summaries expose no native @-mention metadata. Group engagement
39
+ // is therefore plain-text alias matching only; DMs engage every message.
40
+ const aliasMatched = matchesAnyAlias(text, context.selfAliases ?? [])
41
+ const parsed = Date.parse(message.timestamp)
42
+
43
+ return {
44
+ kind: 'route',
45
+ payload: {
46
+ adapter: 'instagram',
47
+ workspace: chatInfo.workspace,
48
+ chat: message.thread_id,
49
+ thread: null,
50
+ text,
51
+ externalMessageId: message.id,
52
+ authorId: message.from,
53
+ authorName: message.from_name ?? message.from,
54
+ authorIsBot: false,
55
+ isBotMention: aliasMatched,
56
+ replyToBotMessageId: null,
57
+ mentionsOthers: false,
58
+ replyToOtherMessageId: null,
59
+ isDm: chatInfo.isDm,
60
+ ts: Number.isNaN(parsed) ? 0 : parsed,
61
+ },
62
+ }
63
+ }
64
+
65
+ function instagramMediaPlaceholder(type: string): string {
66
+ const normalized = type.trim()
67
+ if (normalized === '' || normalized === 'text') return '[Instagram media]'
68
+ return `[Instagram ${normalized}]`
69
+ }
@@ -0,0 +1,8 @@
1
+ import { toKakaoPlainText } from './kakaotalk-format'
2
+
3
+ // Instagram DMs render plain text like KakaoTalk and LINE: markdown markers are
4
+ // visible to recipients, so reuse the existing plain-text stripper until the SDK
5
+ // exposes a platform-specific rich-text surface.
6
+ export function toInstagramPlainText(input: string): string {
7
+ return toKakaoPlainText(input)
8
+ }