typeclaw 0.41.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.
- package/README.md +3 -2
- package/auth.schema.json +57 -0
- package/package.json +2 -2
- package/secrets.schema.json +57 -0
- package/src/agent/index.ts +10 -6
- package/src/agent/session-origin.ts +1 -0
- package/src/agent/tools/channel-history-render.ts +21 -0
- package/src/agent/tools/channel-history.ts +2 -17
- package/src/agent/tools/channel-read.ts +206 -0
- package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +26 -2
- package/src/bundled-plugins/github-cli-auth/index.ts +25 -6
- package/src/bundled-plugins/memory/vector/hybrid.ts +73 -6
- package/src/bundled-plugins/memory/vector/passages.ts +2 -24
- package/src/bundled-plugins/memory/vector/truncation.ts +28 -0
- package/src/bundled-plugins/tool-result-cap/README.md +10 -1
- package/src/bundled-plugins/tool-result-cap/cap-result.ts +8 -0
- package/src/channels/adapters/discord-bot.ts +112 -0
- package/src/channels/adapters/instagram-channel-resolver.ts +113 -0
- package/src/channels/adapters/instagram-classify.ts +69 -0
- package/src/channels/adapters/instagram-format.ts +8 -0
- package/src/channels/adapters/instagram.ts +346 -0
- package/src/channels/adapters/slack-bot.ts +147 -0
- package/src/channels/manager.ts +60 -2
- package/src/channels/router.ts +64 -0
- package/src/channels/schema.ts +5 -0
- package/src/channels/types.ts +46 -0
- package/src/cli/channel.ts +76 -1
- package/src/cli/init.ts +1 -0
- package/src/cli/status.ts +37 -14
- package/src/config/channels-mutation.ts +2 -1
- package/src/doctor/channel-checks.ts +28 -0
- package/src/hostd/daemon.ts +11 -7
- package/src/hostd/protocol.ts +2 -0
- package/src/init/index.ts +50 -1
- package/src/init/instagram-auth.ts +134 -0
- package/src/init/run-owner-claim.ts +1 -0
- package/src/permissions/match-rule.ts +1 -1
- package/src/permissions/resolve.ts +1 -0
- package/src/role-claim/match-rule.ts +2 -1
- package/src/secrets/instagram-store.ts +112 -0
- package/src/secrets/schema.ts +18 -0
- package/src/skills/typeclaw-channel-instagram/SKILL.md +30 -0
- package/typeclaw.schema.json +161 -1
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
import * as instagramModule from 'agent-messenger/instagram'
|
|
2
|
+
import {
|
|
3
|
+
InstagramClient as RealInstagramClient,
|
|
4
|
+
InstagramCredentialManager,
|
|
5
|
+
InstagramListener as RealInstagramListener,
|
|
6
|
+
} from 'agent-messenger/instagram'
|
|
7
|
+
import type { InstagramChatSummary, InstagramMessageSummary } from 'agent-messenger/instagram'
|
|
8
|
+
|
|
9
|
+
import type { ChannelRouter } from '@/channels/router'
|
|
10
|
+
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
11
|
+
import type {
|
|
12
|
+
ChannelHistoryMessage,
|
|
13
|
+
FetchHistoryArgs,
|
|
14
|
+
FetchHistoryResult,
|
|
15
|
+
HistoryCallback,
|
|
16
|
+
OutboundCallback,
|
|
17
|
+
OutboundMessage,
|
|
18
|
+
ResolvedChannelNames,
|
|
19
|
+
SendResult,
|
|
20
|
+
} from '@/channels/types'
|
|
21
|
+
|
|
22
|
+
import { describeError } from './describe-error'
|
|
23
|
+
import { createInstagramChannelResolver } from './instagram-channel-resolver'
|
|
24
|
+
import { classifyInbound } from './instagram-classify'
|
|
25
|
+
import { toInstagramPlainText } from './instagram-format'
|
|
26
|
+
|
|
27
|
+
export interface InstagramClientShape {
|
|
28
|
+
login(credentials?: { username: string; password: string }, accountId?: string): Promise<this>
|
|
29
|
+
getProfile(): Promise<{ user_id: string; username: string; full_name: string | null; profile_pic_url: string | null }>
|
|
30
|
+
listChats(limit?: number): Promise<InstagramChatSummary[]>
|
|
31
|
+
getMessages(threadId: string, limit?: number): Promise<InstagramMessageSummary[]>
|
|
32
|
+
sendMessage(threadId: string, text: string): Promise<InstagramMessageSummary>
|
|
33
|
+
getUserId(): string | null
|
|
34
|
+
fetchIrisBootstrap?: () => Promise<unknown>
|
|
35
|
+
getSessionState?: () => unknown
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type ConnectedPayload = { userId: string; transport?: 'realtime' | 'polling' }
|
|
39
|
+
|
|
40
|
+
export interface InstagramListenerShape {
|
|
41
|
+
start(): Promise<void> | void
|
|
42
|
+
stop(): void
|
|
43
|
+
on(event: 'connected', handler: (payload: ConnectedPayload) => void): this
|
|
44
|
+
on(event: 'message', handler: (message: InstagramMessageSummary) => void): this
|
|
45
|
+
on(event: 'error', handler: (error: Error) => void): this
|
|
46
|
+
on(event: 'disconnected', handler: () => void): this
|
|
47
|
+
off(event: 'connected', handler: (payload: ConnectedPayload) => void): this
|
|
48
|
+
off(event: 'message', handler: (message: InstagramMessageSummary) => void): this
|
|
49
|
+
off(event: 'error', handler: (error: Error) => void): this
|
|
50
|
+
off(event: 'disconnected', handler: () => void): this
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const InstagramClient = RealInstagramClient as unknown as new (
|
|
54
|
+
credManager?: InstagramCredentialManager,
|
|
55
|
+
) => InstagramClientShape
|
|
56
|
+
|
|
57
|
+
export type InstagramListenerCtor = new (
|
|
58
|
+
client: InstagramClientShape,
|
|
59
|
+
options?: {
|
|
60
|
+
pollInterval?: number
|
|
61
|
+
realtimeRetryBaseMs?: number
|
|
62
|
+
realtimeRetryMaxMs?: number
|
|
63
|
+
disableRealtime?: boolean
|
|
64
|
+
connackTimeoutMs?: number
|
|
65
|
+
},
|
|
66
|
+
) => InstagramListenerShape
|
|
67
|
+
|
|
68
|
+
export function resolveInstagramListenerCtor(): { ctor: InstagramListenerCtor; transport: 'hybrid' | 'polling' } {
|
|
69
|
+
const maybeHybrid = (instagramModule as Record<string, unknown>).InstagramHybridListener
|
|
70
|
+
if (typeof maybeHybrid === 'function')
|
|
71
|
+
return { ctor: maybeHybrid as unknown as InstagramListenerCtor, transport: 'hybrid' }
|
|
72
|
+
return { ctor: RealInstagramListener as unknown as InstagramListenerCtor, transport: 'polling' }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export type InstagramCredentialStore = {
|
|
76
|
+
getAccount(id?: string): Promise<{ account_id: string } | null>
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type InstagramAdapterLogger = {
|
|
80
|
+
info: (msg: string) => void
|
|
81
|
+
warn: (msg: string) => void
|
|
82
|
+
error: (msg: string) => void
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const consoleLogger: InstagramAdapterLogger = {
|
|
86
|
+
info: (m) => console.log(m),
|
|
87
|
+
warn: (m) => console.warn(m),
|
|
88
|
+
error: (m) => console.error(m),
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export type InstagramAdapterOptions = {
|
|
92
|
+
router: ChannelRouter
|
|
93
|
+
configRef: () => ChannelAdapterConfig
|
|
94
|
+
logger?: InstagramAdapterLogger
|
|
95
|
+
selfAliasesRef?: () => readonly string[]
|
|
96
|
+
credentialsStore?: InstagramCredentialStore
|
|
97
|
+
client?: InstagramClientShape
|
|
98
|
+
clientFactory?: (credManager?: InstagramCredentialManager) => InstagramClientShape
|
|
99
|
+
listenerCtorResolver?: () => { ctor: InstagramListenerCtor; transport: 'hybrid' | 'polling' }
|
|
100
|
+
now?: () => number
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export type InstagramAdapter = {
|
|
104
|
+
start: () => Promise<void>
|
|
105
|
+
stop: () => Promise<void>
|
|
106
|
+
isConnected: () => boolean
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export const INSTAGRAM_HISTORY_LIMIT_MAX = 200
|
|
110
|
+
|
|
111
|
+
export function createOutboundCallback(deps: {
|
|
112
|
+
client: Pick<InstagramClientShape, 'sendMessage'>
|
|
113
|
+
logger: InstagramAdapterLogger
|
|
114
|
+
formatChannelTag: (workspace: string, chat: string) => Promise<string>
|
|
115
|
+
}): OutboundCallback {
|
|
116
|
+
const { client, logger, formatChannelTag } = deps
|
|
117
|
+
return async (msg: OutboundMessage): Promise<SendResult> => {
|
|
118
|
+
if (msg.adapter !== 'instagram') return { ok: false, error: `unknown adapter: ${msg.adapter}` }
|
|
119
|
+
if (msg.attachments !== undefined && msg.attachments.length > 0) {
|
|
120
|
+
return { ok: false, error: 'instagram adapter does not support outbound attachments' }
|
|
121
|
+
}
|
|
122
|
+
const text = toInstagramPlainText(msg.text ?? '')
|
|
123
|
+
if (text === '') return { ok: false, error: 'message has no text' }
|
|
124
|
+
const tag = await formatChannelTag(msg.workspace, msg.chat)
|
|
125
|
+
logger.info(`[instagram] outbound ${tag} text_len=${text.length}`)
|
|
126
|
+
try {
|
|
127
|
+
const result = await client.sendMessage(msg.chat, text)
|
|
128
|
+
logger.info(`[instagram] sent message_id=${result.id} ${tag}`)
|
|
129
|
+
return { ok: true, messageId: result.id, messageIds: [result.id] }
|
|
130
|
+
} catch (err) {
|
|
131
|
+
const message = describeError(err)
|
|
132
|
+
logger.error(`[instagram] sendMessage failed: ${message}`)
|
|
133
|
+
return { ok: false, error: message }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function createInstagramHistoryCallback(deps: {
|
|
139
|
+
client: Pick<InstagramClientShape, 'getMessages'>
|
|
140
|
+
logger: InstagramAdapterLogger
|
|
141
|
+
selfUserIdRef: () => string | null
|
|
142
|
+
}): HistoryCallback {
|
|
143
|
+
const { client, logger, selfUserIdRef } = deps
|
|
144
|
+
return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
145
|
+
const limit = clampLimit(args.limit, INSTAGRAM_HISTORY_LIMIT_MAX)
|
|
146
|
+
try {
|
|
147
|
+
const messages = await client.getMessages(args.chat, limit)
|
|
148
|
+
const selfId = selfUserIdRef()
|
|
149
|
+
const mapped: ChannelHistoryMessage[] = messages.map((m) => {
|
|
150
|
+
const parsed = Date.parse(m.timestamp)
|
|
151
|
+
return {
|
|
152
|
+
externalMessageId: m.id,
|
|
153
|
+
authorId: m.from,
|
|
154
|
+
authorName: m.from_name ?? m.from,
|
|
155
|
+
text: m.text ?? '',
|
|
156
|
+
ts: Number.isNaN(parsed) ? 0 : parsed,
|
|
157
|
+
isBot: selfId !== null && (m.from === selfId || m.is_outgoing),
|
|
158
|
+
replyToBotMessageId: null,
|
|
159
|
+
}
|
|
160
|
+
})
|
|
161
|
+
return { ok: true, messages: mapped }
|
|
162
|
+
} catch (err) {
|
|
163
|
+
const message = describeError(err)
|
|
164
|
+
logger.warn(`[instagram] history fetch failed: ${message}`)
|
|
165
|
+
return { ok: false, error: message }
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function createInstagramAdapter(options: InstagramAdapterOptions): InstagramAdapter {
|
|
171
|
+
const logger = options.logger ?? consoleLogger
|
|
172
|
+
const buildClient = options.clientFactory ?? ((cm?: InstagramCredentialManager) => new InstagramClient(cm))
|
|
173
|
+
const client = options.client ?? buildClient(new InstagramCredentialManager())
|
|
174
|
+
let listener: InstagramListenerShape | null = null
|
|
175
|
+
let selfUserId: string | null = null
|
|
176
|
+
let connected = false
|
|
177
|
+
let started = false
|
|
178
|
+
let inflightInbounds = 0
|
|
179
|
+
let stopWaiters: Array<() => void> = []
|
|
180
|
+
|
|
181
|
+
const channelResolver = createInstagramChannelResolver({ client, logger })
|
|
182
|
+
|
|
183
|
+
const formatChannelTag = async (workspace: string, chat: string): Promise<string> => {
|
|
184
|
+
const names = await channelResolver
|
|
185
|
+
.resolve({ adapter: 'instagram', workspace, chat, thread: null })
|
|
186
|
+
.catch(() => ({}) as ResolvedChannelNames)
|
|
187
|
+
return `bucket=${workspace} chat=${formatLabel(names.chatName, chat)}`
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const historyCallback = createInstagramHistoryCallback({ client, logger, selfUserIdRef: () => selfUserId })
|
|
191
|
+
const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
|
|
192
|
+
|
|
193
|
+
const processInbound = async (message: InstagramMessageSummary): Promise<void> => {
|
|
194
|
+
inflightInbounds++
|
|
195
|
+
try {
|
|
196
|
+
if (channelResolver.lookupChat(message.thread_id) === null) {
|
|
197
|
+
await channelResolver.refresh()
|
|
198
|
+
if (channelResolver.lookupChat(message.thread_id) === null) {
|
|
199
|
+
channelResolver.ingestProvisional(message.thread_id)
|
|
200
|
+
logger.warn(
|
|
201
|
+
`[instagram] provisional chat=${message.thread_id} message_id=${message.id} bucket=@instagram-group reason=not_in_listChats`,
|
|
202
|
+
)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const bucket = channelResolver.lookupChat(message.thread_id)?.workspace ?? '@instagram-group'
|
|
207
|
+
const inboundTag = await formatChannelTag(bucket, message.thread_id)
|
|
208
|
+
logger.info(
|
|
209
|
+
`[instagram] inbound message_id=${message.id} author=${message.from} ${inboundTag} type=${message.type} text_len=${(message.text ?? '').length}`,
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
const verdict = classifyInbound(message, options.configRef(), {
|
|
213
|
+
selfUserId,
|
|
214
|
+
lookupChat: (id) => channelResolver.lookupChat(id),
|
|
215
|
+
...(options.selfAliasesRef ? { selfAliases: options.selfAliasesRef() } : {}),
|
|
216
|
+
})
|
|
217
|
+
if (verdict.kind === 'drop') {
|
|
218
|
+
logger.info(`[instagram] dropped message_id=${message.id} reason=${verdict.reason}`)
|
|
219
|
+
return
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
logger.info(
|
|
223
|
+
`[instagram] routed message_id=${message.id} ${inboundTag} mention=${verdict.payload.isBotMention} dm=${verdict.payload.isDm}`,
|
|
224
|
+
)
|
|
225
|
+
await options.router.route(verdict.payload)
|
|
226
|
+
} catch (err) {
|
|
227
|
+
logger.error(`[instagram] handleInbound failed: ${describeError(err)}`)
|
|
228
|
+
} finally {
|
|
229
|
+
inflightInbounds--
|
|
230
|
+
if (inflightInbounds === 0 && stopWaiters.length > 0) {
|
|
231
|
+
const waiters = stopWaiters
|
|
232
|
+
stopWaiters = []
|
|
233
|
+
for (const w of waiters) w()
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return {
|
|
239
|
+
async start(): Promise<void> {
|
|
240
|
+
if (started) return
|
|
241
|
+
started = true
|
|
242
|
+
|
|
243
|
+
try {
|
|
244
|
+
const credentialStore = options.credentialsStore ?? null
|
|
245
|
+
if (credentialStore !== null) {
|
|
246
|
+
const account = await credentialStore.getAccount()
|
|
247
|
+
if (account === null) {
|
|
248
|
+
throw new Error(
|
|
249
|
+
'no Instagram account in secrets.json#channels.instagram (run typeclaw channel add instagram)',
|
|
250
|
+
)
|
|
251
|
+
}
|
|
252
|
+
await client.login(undefined, account.account_id)
|
|
253
|
+
} else {
|
|
254
|
+
await client.login()
|
|
255
|
+
}
|
|
256
|
+
} catch (err) {
|
|
257
|
+
started = false
|
|
258
|
+
logger.error(`[instagram] login failed: ${describeError(err)}`)
|
|
259
|
+
throw err
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
try {
|
|
263
|
+
const profile = await client.getProfile()
|
|
264
|
+
selfUserId = profile.user_id
|
|
265
|
+
logger.info(`[instagram] authenticated as ${profile.username} (${profile.user_id})`)
|
|
266
|
+
} catch (err) {
|
|
267
|
+
started = false
|
|
268
|
+
logger.error(`[instagram] getProfile failed: ${describeError(err)}`)
|
|
269
|
+
throw err
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
try {
|
|
273
|
+
await channelResolver.refresh()
|
|
274
|
+
} catch (err) {
|
|
275
|
+
logger.warn(`[instagram] initial chat list fetch failed: ${describeError(err)}`)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const resolved = (options.listenerCtorResolver ?? resolveInstagramListenerCtor)()
|
|
279
|
+
listener = new resolved.ctor(client, { pollInterval: 5_000 })
|
|
280
|
+
logger.info(`[instagram] listener transport=${resolved.transport}`)
|
|
281
|
+
listener.on('connected', ({ userId, transport = 'polling' }) => {
|
|
282
|
+
connected = true
|
|
283
|
+
logger.info(`[instagram] connected (user_id=${userId}, transport=${transport})`)
|
|
284
|
+
})
|
|
285
|
+
listener.on('disconnected', () => {
|
|
286
|
+
connected = false
|
|
287
|
+
logger.warn('[instagram] disconnected; SDK will reconnect with backoff')
|
|
288
|
+
})
|
|
289
|
+
listener.on('error', (err) => {
|
|
290
|
+
logger.error(`[instagram] listener error: ${describeError(err)}`)
|
|
291
|
+
})
|
|
292
|
+
listener.on('message', (message) => {
|
|
293
|
+
void processInbound(message)
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
try {
|
|
297
|
+
await listener.start()
|
|
298
|
+
} catch (err) {
|
|
299
|
+
try {
|
|
300
|
+
listener.stop()
|
|
301
|
+
} catch {
|
|
302
|
+
// best-effort cleanup; the start failure is what we surface
|
|
303
|
+
}
|
|
304
|
+
listener = null
|
|
305
|
+
started = false
|
|
306
|
+
logger.error(`[instagram] listener start failed: ${describeError(err)}`)
|
|
307
|
+
throw err
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
options.router.registerOutbound('instagram', outboundCallback)
|
|
311
|
+
options.router.registerChannelNameResolver('instagram', channelResolver.resolve)
|
|
312
|
+
options.router.registerHistory('instagram', historyCallback)
|
|
313
|
+
},
|
|
314
|
+
|
|
315
|
+
async stop(): Promise<void> {
|
|
316
|
+
if (!started) return
|
|
317
|
+
started = false
|
|
318
|
+
options.router.unregisterOutbound('instagram', outboundCallback)
|
|
319
|
+
options.router.unregisterChannelNameResolver('instagram', channelResolver.resolve)
|
|
320
|
+
options.router.unregisterHistory('instagram', historyCallback)
|
|
321
|
+
if (inflightInbounds > 0) {
|
|
322
|
+
await new Promise<void>((resolve) => {
|
|
323
|
+
stopWaiters.push(resolve)
|
|
324
|
+
})
|
|
325
|
+
}
|
|
326
|
+
listener?.stop()
|
|
327
|
+
listener = null
|
|
328
|
+
selfUserId = null
|
|
329
|
+
connected = false
|
|
330
|
+
},
|
|
331
|
+
|
|
332
|
+
isConnected(): boolean {
|
|
333
|
+
return connected && selfUserId !== null
|
|
334
|
+
},
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function clampLimit(requested: number, max: number): number {
|
|
339
|
+
if (!Number.isFinite(requested) || requested <= 0) return max
|
|
340
|
+
return Math.min(Math.floor(requested), max)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function formatLabel(name: string | undefined, id: string): string {
|
|
344
|
+
if (name === undefined || name === '' || name === id) return id
|
|
345
|
+
return `${name}(${id})`
|
|
346
|
+
}
|
|
@@ -18,11 +18,18 @@ import type { ChannelRouter } from '@/channels/router'
|
|
|
18
18
|
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
19
19
|
import type {
|
|
20
20
|
ChannelHistoryMessage,
|
|
21
|
+
ChannelListEntry,
|
|
21
22
|
ChannelSelfIdentityResolver,
|
|
22
23
|
FetchAttachmentCallback,
|
|
23
24
|
FetchHistoryArgs,
|
|
24
25
|
FetchHistoryResult,
|
|
26
|
+
GetMessageArgs,
|
|
27
|
+
GetMessageResult,
|
|
25
28
|
HistoryCallback,
|
|
29
|
+
ListCallback,
|
|
30
|
+
ListChannelsArgs,
|
|
31
|
+
ListChannelsResult,
|
|
32
|
+
MessageGetCallback,
|
|
26
33
|
OutboundCallback,
|
|
27
34
|
OutboundMessage,
|
|
28
35
|
ResolvedChannelNames,
|
|
@@ -414,6 +421,21 @@ type SlackConversationInfoResponse = {
|
|
|
414
421
|
channel?: { num_members?: number }
|
|
415
422
|
}
|
|
416
423
|
|
|
424
|
+
type SlackConversationsListChannel = {
|
|
425
|
+
id?: string
|
|
426
|
+
name?: string
|
|
427
|
+
is_im?: boolean
|
|
428
|
+
is_mpim?: boolean
|
|
429
|
+
is_member?: boolean
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
type SlackConversationsListResponse = {
|
|
433
|
+
ok: boolean
|
|
434
|
+
error?: string
|
|
435
|
+
channels?: SlackConversationsListChannel[]
|
|
436
|
+
response_metadata?: { next_cursor?: string }
|
|
437
|
+
}
|
|
438
|
+
|
|
417
439
|
type SlackConversationMembersResponse = {
|
|
418
440
|
ok: boolean
|
|
419
441
|
error?: string
|
|
@@ -729,6 +751,116 @@ export function createSlackHistoryCallback(deps: {
|
|
|
729
751
|
}
|
|
730
752
|
}
|
|
731
753
|
|
|
754
|
+
// Fetch one message by ts. Slack has no by-id endpoint, so we window
|
|
755
|
+
// conversations.history (channel root) or conversations.replies (thread) to a
|
|
756
|
+
// single ts via oldest=latest=messageId, inclusive=true, limit=1 — without the
|
|
757
|
+
// window, a long thread is cursor-paginated and a reply past the first page
|
|
758
|
+
// would be wrongly reported not-found. conversations.replies still needs `ts`
|
|
759
|
+
// set to the thread ROOT to identify the thread. Reuses mapSlackMessage so a
|
|
760
|
+
// single message renders identically to a history entry.
|
|
761
|
+
export function createSlackMessageGetCallback(deps: {
|
|
762
|
+
token: string
|
|
763
|
+
logger: SlackBotAdapterLogger
|
|
764
|
+
botUserIdRef: () => string | null
|
|
765
|
+
authorResolver?: SlackAuthorResolver
|
|
766
|
+
fetchImpl?: typeof fetch
|
|
767
|
+
}): MessageGetCallback {
|
|
768
|
+
const { token, logger, botUserIdRef, authorResolver } = deps
|
|
769
|
+
const fetchFn = deps.fetchImpl ?? fetch
|
|
770
|
+
return async (args: GetMessageArgs): Promise<GetMessageResult> => {
|
|
771
|
+
const body = new URLSearchParams()
|
|
772
|
+
body.set('channel', args.chat)
|
|
773
|
+
if (args.thread !== null) body.set('ts', args.thread)
|
|
774
|
+
body.set('oldest', args.messageId)
|
|
775
|
+
body.set('latest', args.messageId)
|
|
776
|
+
body.set('inclusive', 'true')
|
|
777
|
+
body.set('limit', '1')
|
|
778
|
+
const endpoint = args.thread === null ? 'conversations.history' : 'conversations.replies'
|
|
779
|
+
|
|
780
|
+
let raw: SlackHistoryResponse
|
|
781
|
+
try {
|
|
782
|
+
const response = await fetchFn(`${SLACK_API_BASE}/${endpoint}`, {
|
|
783
|
+
method: 'POST',
|
|
784
|
+
headers: {
|
|
785
|
+
Authorization: `Bearer ${token}`,
|
|
786
|
+
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
|
|
787
|
+
},
|
|
788
|
+
body: body.toString(),
|
|
789
|
+
})
|
|
790
|
+
raw = (await response.json()) as SlackHistoryResponse
|
|
791
|
+
} catch (err) {
|
|
792
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
793
|
+
logger.warn(`[slack-bot] message get failed: ${message}`)
|
|
794
|
+
return { ok: false, error: message }
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
if (!raw.ok) return { ok: false, error: raw.error ?? 'unknown slack error' }
|
|
798
|
+
|
|
799
|
+
const botUserId = botUserIdRef()
|
|
800
|
+
const found = (raw.messages ?? []).find((m) => m.ts === args.messageId)
|
|
801
|
+
if (found === undefined) return { ok: false, error: 'message not found', code: 'not-found' }
|
|
802
|
+
|
|
803
|
+
const message = mapSlackMessage(found, botUserId)
|
|
804
|
+
if (authorResolver !== undefined && found.user !== undefined && found.user !== '') {
|
|
805
|
+
message.text = await addSlackMentionHints(message.text, authorResolver.resolve, { botUserId })
|
|
806
|
+
message.authorName = await authorResolver.resolve(found.user)
|
|
807
|
+
}
|
|
808
|
+
return { ok: true, message }
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// List channels the bot can see via conversations.list. Maps Slack channel
|
|
813
|
+
// types to ChannelListEntry.kind; `is_member` from the API populates isMember.
|
|
814
|
+
export function createSlackListCallback(deps: {
|
|
815
|
+
token: string
|
|
816
|
+
logger: SlackBotAdapterLogger
|
|
817
|
+
fetchImpl?: typeof fetch
|
|
818
|
+
}): ListCallback {
|
|
819
|
+
const { token, logger } = deps
|
|
820
|
+
const fetchFn = deps.fetchImpl ?? fetch
|
|
821
|
+
return async (args: ListChannelsArgs): Promise<ListChannelsResult> => {
|
|
822
|
+
const body = new URLSearchParams()
|
|
823
|
+
body.set('limit', String(clampLimit(args.limit, 200)))
|
|
824
|
+
body.set('types', 'public_channel,private_channel,mpim,im')
|
|
825
|
+
if (args.cursor !== undefined && args.cursor !== '') body.set('cursor', args.cursor)
|
|
826
|
+
|
|
827
|
+
let raw: SlackConversationsListResponse
|
|
828
|
+
try {
|
|
829
|
+
const response = await fetchFn(`${SLACK_API_BASE}/conversations.list`, {
|
|
830
|
+
method: 'POST',
|
|
831
|
+
headers: {
|
|
832
|
+
Authorization: `Bearer ${token}`,
|
|
833
|
+
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
|
|
834
|
+
},
|
|
835
|
+
body: body.toString(),
|
|
836
|
+
})
|
|
837
|
+
raw = (await response.json()) as SlackConversationsListResponse
|
|
838
|
+
} catch (err) {
|
|
839
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
840
|
+
logger.warn(`[slack-bot] channel list failed: ${message}`)
|
|
841
|
+
return { ok: false, error: message }
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
if (!raw.ok) return { ok: false, error: raw.error ?? 'unknown slack error' }
|
|
845
|
+
|
|
846
|
+
const entries = (raw.channels ?? []).map((c) => mapSlackChannelEntry(c))
|
|
847
|
+
const nextCursor = raw.response_metadata?.next_cursor
|
|
848
|
+
if (nextCursor !== undefined && nextCursor !== '') return { ok: true, entries, nextCursor }
|
|
849
|
+
return { ok: true, entries }
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
function mapSlackChannelEntry(c: SlackConversationsListChannel): ChannelListEntry {
|
|
854
|
+
const kind: ChannelListEntry['kind'] = c.is_im === true ? 'dm' : c.is_mpim === true ? 'group' : 'channel'
|
|
855
|
+
const name = c.name !== undefined && c.name !== '' ? `#${c.name}` : (c.id ?? 'unknown')
|
|
856
|
+
return {
|
|
857
|
+
chat: c.id ?? 'unknown',
|
|
858
|
+
name,
|
|
859
|
+
kind,
|
|
860
|
+
...(c.is_member !== undefined ? { isMember: c.is_member } : {}),
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
|
|
732
864
|
function mapSlackMessage(msg: SlackRawHistoryMessage, botUserId: string | null): ChannelHistoryMessage {
|
|
733
865
|
const isBot =
|
|
734
866
|
msg.subtype === 'bot_message' ||
|
|
@@ -1022,6 +1154,15 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
|
|
|
1022
1154
|
authorResolver,
|
|
1023
1155
|
})
|
|
1024
1156
|
|
|
1157
|
+
const messageGetCallback = createSlackMessageGetCallback({
|
|
1158
|
+
token: options.token,
|
|
1159
|
+
logger,
|
|
1160
|
+
botUserIdRef: () => botUserId,
|
|
1161
|
+
authorResolver,
|
|
1162
|
+
})
|
|
1163
|
+
|
|
1164
|
+
const listCallback = createSlackListCallback({ token: options.token, logger })
|
|
1165
|
+
|
|
1025
1166
|
const membershipResolver = createSlackMembershipResolver({
|
|
1026
1167
|
token: options.token,
|
|
1027
1168
|
logger,
|
|
@@ -1257,6 +1398,8 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
|
|
|
1257
1398
|
options.router.registerChannelNameResolver('slack-bot', channelResolver)
|
|
1258
1399
|
options.router.registerSelfIdentity('slack-bot', selfIdentityResolver)
|
|
1259
1400
|
options.router.registerHistory('slack-bot', historyCallback)
|
|
1401
|
+
options.router.registerMessageGet('slack-bot', messageGetCallback)
|
|
1402
|
+
options.router.registerList('slack-bot', listCallback)
|
|
1260
1403
|
options.router.registerFetchAttachment('slack-bot', fetchAttachmentCallback)
|
|
1261
1404
|
options.router.registerMembership('slack-bot', membershipResolver)
|
|
1262
1405
|
|
|
@@ -1275,6 +1418,8 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
|
|
|
1275
1418
|
options.router.unregisterChannelNameResolver('slack-bot', channelResolver)
|
|
1276
1419
|
options.router.unregisterSelfIdentity('slack-bot', selfIdentityResolver)
|
|
1277
1420
|
options.router.unregisterHistory('slack-bot', historyCallback)
|
|
1421
|
+
options.router.unregisterMessageGet('slack-bot', messageGetCallback)
|
|
1422
|
+
options.router.unregisterList('slack-bot', listCallback)
|
|
1278
1423
|
options.router.unregisterFetchAttachment('slack-bot', fetchAttachmentCallback)
|
|
1279
1424
|
options.router.unregisterMembership('slack-bot', membershipResolver)
|
|
1280
1425
|
listener = null
|
|
@@ -1297,6 +1442,8 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
|
|
|
1297
1442
|
options.router.unregisterChannelNameResolver('slack-bot', channelResolver)
|
|
1298
1443
|
options.router.unregisterSelfIdentity('slack-bot', selfIdentityResolver)
|
|
1299
1444
|
options.router.unregisterHistory('slack-bot', historyCallback)
|
|
1445
|
+
options.router.unregisterMessageGet('slack-bot', messageGetCallback)
|
|
1446
|
+
options.router.unregisterList('slack-bot', listCallback)
|
|
1300
1447
|
options.router.unregisterFetchAttachment('slack-bot', fetchAttachmentCallback)
|
|
1301
1448
|
options.router.unregisterMembership('slack-bot', membershipResolver)
|
|
1302
1449
|
if (inflightInbounds > 0) {
|
package/src/channels/manager.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { join } from 'node:path'
|
|
|
4
4
|
import type { PermissionService } from '@/permissions'
|
|
5
5
|
import type { GithubSecretsBlock } from '@/secrets'
|
|
6
6
|
import { SecretsDiscordCredentialStore } from '@/secrets/discord-store'
|
|
7
|
+
import { SecretsInstagramCredentialStore } from '@/secrets/instagram-store'
|
|
7
8
|
import { SecretsKakaoCredentialStore } from '@/secrets/kakao-store'
|
|
8
9
|
import { SecretsLineCredentialStore } from '@/secrets/line-store'
|
|
9
10
|
import { SecretsSlackCredentialStore } from '@/secrets/slack-store'
|
|
@@ -14,6 +15,7 @@ import type { Stream } from '@/stream'
|
|
|
14
15
|
import { createDiscordAdapter, type DiscordAdapter } from './adapters/discord'
|
|
15
16
|
import { createDiscordBotAdapter, type DiscordBotAdapter } from './adapters/discord-bot'
|
|
16
17
|
import { createGithubAdapter, type GithubAdapter } from './adapters/github'
|
|
18
|
+
import { createInstagramAdapter, type InstagramAdapter } from './adapters/instagram'
|
|
17
19
|
import { createKakaotalkAdapter, type KakaotalkAdapter } from './adapters/kakaotalk'
|
|
18
20
|
import { createLineAdapter, type LineAdapter } from './adapters/line'
|
|
19
21
|
import { createSlackAdapter, type SlackAdapter } from './adapters/slack'
|
|
@@ -75,6 +77,7 @@ export type ChannelManagerOptions = {
|
|
|
75
77
|
createDiscordAdapter?: typeof createDiscordBotAdapter
|
|
76
78
|
createDiscordUserAdapter?: typeof createDiscordAdapter
|
|
77
79
|
createGithubAdapter?: typeof createGithubAdapter
|
|
80
|
+
createInstagramAdapter?: typeof createInstagramAdapter
|
|
78
81
|
createKakaotalkAdapter?: typeof createKakaotalkAdapter
|
|
79
82
|
createLineAdapter?: typeof createLineAdapter
|
|
80
83
|
createSlackAdapter?: typeof createSlackBotAdapter
|
|
@@ -145,6 +148,7 @@ type AnyAdapter =
|
|
|
145
148
|
| DiscordAdapter
|
|
146
149
|
| DiscordBotAdapter
|
|
147
150
|
| GithubAdapter
|
|
151
|
+
| InstagramAdapter
|
|
148
152
|
| LineAdapter
|
|
149
153
|
| KakaotalkAdapter
|
|
150
154
|
| SlackAdapter
|
|
@@ -188,6 +192,7 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
188
192
|
const createDiscordBot = options.createDiscordAdapter ?? createDiscordBotAdapter
|
|
189
193
|
const createDiscordUser = options.createDiscordUserAdapter ?? createDiscordAdapter
|
|
190
194
|
const createGithub = options.createGithubAdapter ?? createGithubAdapter
|
|
195
|
+
const createInstagram = options.createInstagramAdapter ?? createInstagramAdapter
|
|
191
196
|
const createKakaotalk = options.createKakaotalkAdapter ?? createKakaotalkAdapter
|
|
192
197
|
const createLine = options.createLineAdapter ?? createLineAdapter
|
|
193
198
|
const createSlackBot = options.createSlackAdapter ?? createSlackBotAdapter
|
|
@@ -219,6 +224,7 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
219
224
|
|
|
220
225
|
const buildCredentialSignature = (name: AdapterId): { signature: string; missing: string[] } => {
|
|
221
226
|
if (name === 'line') return buildLineSignature(options.agentDir)
|
|
227
|
+
if (name === 'instagram') return buildInstagramSignature(options.agentDir)
|
|
222
228
|
if (name === 'kakaotalk') return buildKakaotalkSignature(options.agentDir)
|
|
223
229
|
if (name === 'webex') return buildWebexSignature(options.agentDir)
|
|
224
230
|
if (name === 'slack') return buildSlackSignature(options.agentDir)
|
|
@@ -271,6 +277,17 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
271
277
|
credentialsStore,
|
|
272
278
|
})
|
|
273
279
|
}
|
|
280
|
+
if (name === 'instagram') {
|
|
281
|
+
const credentialsStore = createContainerInstagramCredentialStore(options.agentDir, env)
|
|
282
|
+
if (credentialsStore === null) return null
|
|
283
|
+
return createInstagram({
|
|
284
|
+
router,
|
|
285
|
+
configRef: () => options.channelsConfigRef()[name] ?? cfg,
|
|
286
|
+
logger,
|
|
287
|
+
selfAliasesRef: () => router.getSelfAliases(),
|
|
288
|
+
credentialsStore,
|
|
289
|
+
})
|
|
290
|
+
}
|
|
274
291
|
if (name === 'kakaotalk') {
|
|
275
292
|
const credentialsStore = createContainerKakaoCredentialStore(options.agentDir, env)
|
|
276
293
|
if (credentialsStore === null) return null
|
|
@@ -522,7 +539,12 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
522
539
|
stopped.push(name)
|
|
523
540
|
} else if (signature !== current.credentialSignature) {
|
|
524
541
|
const reason =
|
|
525
|
-
name === 'kakaotalk' ||
|
|
542
|
+
name === 'kakaotalk' ||
|
|
543
|
+
name === 'line' ||
|
|
544
|
+
name === 'instagram' ||
|
|
545
|
+
name === 'webex' ||
|
|
546
|
+
name === 'slack' ||
|
|
547
|
+
name === 'discord'
|
|
526
548
|
? 'credential rotation'
|
|
527
549
|
: 'token rotation'
|
|
528
550
|
restartRequired.push(`${name} (${reason})`)
|
|
@@ -539,7 +561,7 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
|
|
|
539
561
|
// secrets.json#channels.<adapter>, not in env, so they go through
|
|
540
562
|
// structured-block signatures instead.
|
|
541
563
|
const TOKEN_ENV: Record<
|
|
542
|
-
Exclude<AdapterId, 'kakaotalk' | 'line' | 'github' | 'webex' | 'slack' | 'discord'>,
|
|
564
|
+
Exclude<AdapterId, 'kakaotalk' | 'line' | 'instagram' | 'github' | 'webex' | 'slack' | 'discord'>,
|
|
543
565
|
readonly string[]
|
|
544
566
|
> = {
|
|
545
567
|
'discord-bot': ['DISCORD_BOT_TOKEN'],
|
|
@@ -700,6 +722,33 @@ function buildLineSignature(agentDir: string): { signature: string; missing: str
|
|
|
700
722
|
}
|
|
701
723
|
}
|
|
702
724
|
|
|
725
|
+
function createContainerInstagramCredentialStore(
|
|
726
|
+
agentDir: string,
|
|
727
|
+
env: NodeJS.ProcessEnv,
|
|
728
|
+
): SecretsInstagramCredentialStore | null {
|
|
729
|
+
const creds = resolveHostdContainerCredentials(env)
|
|
730
|
+
if (creds === null) return null
|
|
731
|
+
return new SecretsInstagramCredentialStore({
|
|
732
|
+
mode: 'container',
|
|
733
|
+
secretsPath: join(agentDir, 'secrets.json'),
|
|
734
|
+
...creds,
|
|
735
|
+
})
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
function buildInstagramSignature(agentDir: string): { signature: string; missing: string[] } {
|
|
739
|
+
const path = join(agentDir, 'secrets.json')
|
|
740
|
+
try {
|
|
741
|
+
const block = new SecretsBackend(path).tryReadChannelsSync()?.instagram
|
|
742
|
+
if (!isInstagramCredentialBlock(block)) {
|
|
743
|
+
return { signature: '', missing: ['secrets.json#channels.instagram'] }
|
|
744
|
+
}
|
|
745
|
+
const digest = createHash('sha256').update(JSON.stringify(block)).digest('hex')
|
|
746
|
+
return { signature: `secrets.json#channels.instagram@sha256:${digest}`, missing: [] }
|
|
747
|
+
} catch (err) {
|
|
748
|
+
return { signature: '', missing: [`secrets.json#channels.instagram (${describe(err)})`] }
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
703
752
|
function buildGithubSignature(agentDir: string): { signature: string; missing: string[] } {
|
|
704
753
|
const block = readGithubSecrets(agentDir)
|
|
705
754
|
if (block === null) return { signature: '', missing: ['secrets.json#channels.github'] }
|
|
@@ -744,6 +793,15 @@ function isLineCredentialBlock(value: unknown): value is { accounts: Record<stri
|
|
|
744
793
|
)
|
|
745
794
|
}
|
|
746
795
|
|
|
796
|
+
function isInstagramCredentialBlock(value: unknown): value is { accounts: Record<string, unknown> } {
|
|
797
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
|
|
798
|
+
if (!('accounts' in value)) return false
|
|
799
|
+
const accounts = value.accounts
|
|
800
|
+
return (
|
|
801
|
+
typeof accounts === 'object' && accounts !== null && !Array.isArray(accounts) && Object.keys(accounts).length > 0
|
|
802
|
+
)
|
|
803
|
+
}
|
|
804
|
+
|
|
747
805
|
function isSlackCredentialBlock(value: unknown): value is { accounts: Record<string, unknown> } {
|
|
748
806
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
|
|
749
807
|
if (!('accounts' in value)) return false
|