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.
Files changed (43) 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/session-origin.ts +1 -0
  7. package/src/agent/tools/channel-history-render.ts +21 -0
  8. package/src/agent/tools/channel-history.ts +2 -17
  9. package/src/agent/tools/channel-read.ts +206 -0
  10. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +26 -2
  11. package/src/bundled-plugins/github-cli-auth/index.ts +25 -6
  12. package/src/bundled-plugins/memory/vector/hybrid.ts +73 -6
  13. package/src/bundled-plugins/memory/vector/passages.ts +2 -24
  14. package/src/bundled-plugins/memory/vector/truncation.ts +28 -0
  15. package/src/bundled-plugins/tool-result-cap/README.md +10 -1
  16. package/src/bundled-plugins/tool-result-cap/cap-result.ts +8 -0
  17. package/src/channels/adapters/discord-bot.ts +112 -0
  18. package/src/channels/adapters/instagram-channel-resolver.ts +113 -0
  19. package/src/channels/adapters/instagram-classify.ts +69 -0
  20. package/src/channels/adapters/instagram-format.ts +8 -0
  21. package/src/channels/adapters/instagram.ts +346 -0
  22. package/src/channels/adapters/slack-bot.ts +147 -0
  23. package/src/channels/manager.ts +60 -2
  24. package/src/channels/router.ts +64 -0
  25. package/src/channels/schema.ts +5 -0
  26. package/src/channels/types.ts +46 -0
  27. package/src/cli/channel.ts +76 -1
  28. package/src/cli/init.ts +1 -0
  29. package/src/cli/status.ts +37 -14
  30. package/src/config/channels-mutation.ts +2 -1
  31. package/src/doctor/channel-checks.ts +28 -0
  32. package/src/hostd/daemon.ts +11 -7
  33. package/src/hostd/protocol.ts +2 -0
  34. package/src/init/index.ts +50 -1
  35. package/src/init/instagram-auth.ts +134 -0
  36. package/src/init/run-owner-claim.ts +1 -0
  37. package/src/permissions/match-rule.ts +1 -1
  38. package/src/permissions/resolve.ts +1 -0
  39. package/src/role-claim/match-rule.ts +2 -1
  40. package/src/secrets/instagram-store.ts +112 -0
  41. package/src/secrets/schema.ts +18 -0
  42. package/src/skills/typeclaw-channel-instagram/SKILL.md +30 -0
  43. package/typeclaw.schema.json +161 -1
@@ -19,11 +19,27 @@ import type { Passage } from './passages'
19
19
  import { clearsBaseline, gateRelevance, MARGIN, streamAdmissionBaseline } from './relevance-gate'
20
20
  import { crossScriptMarginScale, dominantScript, type ScriptClass } from './script'
21
21
  import { VectorStore, type ScoredVectorRow, type VectorRow } from './store'
22
+ import { chunkEmbeddableText } from './truncation'
22
23
 
23
24
  export { collectPassages, findMissingPassages, type Passage } from './passages'
24
25
 
25
26
  const RRF_K = 60
26
27
 
28
+ // A long prompt is embedded as multiple ≤512-token chunks (not truncated to one
29
+ // vector), so a memory relevant to ANY part of the prompt — including its tail —
30
+ // can still be retrieved. The cap bounds the per-turn cosine scans: each chunk is
31
+ // a full O(rows) brute-force pass over the store, so an unbounded chunk count
32
+ // would scale per-turn retrieval cost with prompt length. At the cap, the LAST
33
+ // chunks are kept rather than the first: TypeClaw cron/agent prompts front-load
34
+ // fixed framing prose and place the actual payload last, so dropping the head is
35
+ // the lesser loss than re-introducing the tail-truncation this fix removes.
36
+ const MAX_QUERY_CHUNKS = 10
37
+
38
+ function queryEmbeddingChunks(query: string): string[] {
39
+ const chunks = chunkEmbeddableText(query)
40
+ return chunks.length <= MAX_QUERY_CHUNKS ? chunks : chunks.slice(chunks.length - MAX_QUERY_CHUNKS)
41
+ }
42
+
27
43
  export type HybridSearchResult = {
28
44
  source: 'topic' | 'stream' | 'reference'
29
45
  key: string
@@ -46,17 +62,18 @@ export async function hybridSearch(
46
62
  ): Promise<HybridSearchResult[]> {
47
63
  if (topK <= 0) return []
48
64
 
65
+ const queryChunks = queryEmbeddingChunks(query)
49
66
  const [shards, streamDays, references, queryEmbeddings] = await Promise.all([
50
67
  loadAllShards(agentDir),
51
68
  readAllUndreamedStreamDays(agentDir),
52
69
  loadAllReferences(agentDir),
53
- embedFn([query], 'query'),
70
+ embedFn(queryChunks, 'query'),
54
71
  ])
55
72
 
56
73
  const { parentSlugsByFragmentId, supersededFragmentIds } = buildParentLinks(shards)
57
74
  const index = buildContentIndex(shards, streamDays, references, supersededFragmentIds)
58
75
  const vectorRows =
59
- queryEmbeddings[0] === undefined ? [] : gatedVectorLane(queryEmbeddings[0], store, topK, query, index)
76
+ queryEmbeddings.length === 0 ? [] : gatedVectorLane(queryEmbeddings, queryChunks, store, topK, index)
60
77
  const keywordMatches = keywordLane(query, shards, streamDays, references, topK * 2)
61
78
 
62
79
  return fuseLanes(vectorRows, keywordMatches, index, parentSlugsByFragmentId).slice(0, topK)
@@ -85,13 +102,13 @@ export async function hybridSearch(
85
102
  // separate keyword lane. An empty merged lane composes with RRF exactly like a
86
103
  // lane that found nothing, so a genuine keyword hit survives a full no-match.
87
104
  function gatedVectorLane(
88
- queryEmbedding: Float32Array,
105
+ queryEmbeddings: Float32Array[],
106
+ queryChunks: string[],
89
107
  store: VectorStore,
90
108
  topK: number,
91
- query: string,
92
109
  index: Map<string, Omit<HybridSearchResult, 'rrfScore'>>,
93
110
  ): VectorRow[] {
94
- const scored = store.queryScored(queryEmbedding, EMBEDDING_MODEL_ID)
111
+ const { scored, winnerChunkByRowId } = maxScoreAcrossChunks(queryEmbeddings, store)
95
112
  const bandDefiningRows = scored.filter(({ row }) => row.source === 'topic' || row.source === 'reference')
96
113
  const streamRows = scored.filter(({ row }) => row.source === 'stream')
97
114
 
@@ -102,7 +119,14 @@ function gatedVectorLane(
102
119
  // script winner whose contrast sits between the loosened and strict margins
103
120
  // would still be suppressed. Headings (via `index`) carry the language; slugs
104
121
  // are ASCII-kebab even for non-Latin topics.
105
- const topicMargin = MARGIN * crossScriptMarginScale(dominantScript(query), headBandScripts(bandDefiningRows, index))
122
+ //
123
+ // The query-side script comes from the CHUNK that won each head row, not the
124
+ // full prompt: a boilerplate-front prompt (most TypeClaw cron prompts) has a
125
+ // dominant script set by framing prose, not by the payload that actually
126
+ // matched. Using the winning chunk's script keeps the loosening aligned with
127
+ // the text that produced the contrast.
128
+ const queryScript = dominantQueryScript(bandDefiningRows, winnerChunkByRowId, queryChunks)
129
+ const topicMargin = MARGIN * crossScriptMarginScale(queryScript, headBandScripts(bandDefiningRows, index))
106
130
  const bandScores = bandDefiningRows.map(({ score }) => score)
107
131
  const keptBandDefiningRows = bandDefiningRows.slice(0, gateRelevance(bandScores, topK * 2, topicMargin))
108
132
 
@@ -137,6 +161,49 @@ function headBandScripts(
137
161
  return [...scripts]
138
162
  }
139
163
 
164
+ // Scores every store row against ALL query-chunk embeddings and keeps each row's
165
+ // MAX similarity (a row relevant to ANY chunk should rank high; mean would dilute
166
+ // it against unrelated chunks, sum would reward prompt length). Returns the merged
167
+ // `{ row, score }[]` in the same shape `store.queryScored` produced for a single
168
+ // query, plus the chunk index that produced each row's winning score — so the
169
+ // cross-script margin can be judged against the chunk that actually matched.
170
+ function maxScoreAcrossChunks(
171
+ queryEmbeddings: Float32Array[],
172
+ store: VectorStore,
173
+ ): { scored: ScoredVectorRow[]; winnerChunkByRowId: Map<string, number> } {
174
+ const best = new Map<string, { scored: ScoredVectorRow; chunkIndex: number }>()
175
+ queryEmbeddings.forEach((embedding, chunkIndex) => {
176
+ for (const scoredRow of store.queryScored(embedding, EMBEDDING_MODEL_ID)) {
177
+ const existing = best.get(scoredRow.row.id)
178
+ if (existing === undefined || scoredRow.score > existing.scored.score) {
179
+ best.set(scoredRow.row.id, { scored: scoredRow, chunkIndex })
180
+ }
181
+ }
182
+ })
183
+ const scored = [...best.values()].map(({ scored: s }) => s).sort((a, b) => b.score - a.score)
184
+ const winnerChunkByRowId = new Map([...best].map(([id, { chunkIndex }]) => [id, chunkIndex]))
185
+ return { scored, winnerChunkByRowId }
186
+ }
187
+
188
+ // The single query script the cross-script margin is judged with, taken from the
189
+ // chunk that won the TOP-scoring band row. The gate's contrast is top1 minus the
190
+ // non-head median (`gateRelevance`), so the top row alone defines whether the
191
+ // margin loosens — a majority vote across the head would let a crowd of ambient
192
+ // same-script noise rows (each won by a framing chunk) override the cross-script
193
+ // payload chunk that actually won the real top match, keeping the margin strict
194
+ // and suppressing a genuine cross-script hit sitting in the compressed band.
195
+ function dominantQueryScript(
196
+ bandDefiningRows: ScoredVectorRow[],
197
+ winnerChunkByRowId: Map<string, number>,
198
+ queryChunks: string[],
199
+ ): ScriptClass {
200
+ const topRow = bandDefiningRows[0]
201
+ if (topRow === undefined) return 'other'
202
+ const chunkIndex = winnerChunkByRowId.get(topRow.row.id)
203
+ const chunk = chunkIndex === undefined ? undefined : queryChunks[chunkIndex]
204
+ return chunk === undefined ? 'other' : dominantScript(chunk)
205
+ }
206
+
140
207
  // Phrase-first, then token-OR fallback (mirrors `memory_search`). `hybridSearch`'s
141
208
  // query is always the whole user prompt, which never appears verbatim in a shard,
142
209
  // so a phrase-only lane returns nothing every real turn and RRF degenerates to the
@@ -8,7 +8,7 @@ import { loadAllReferences } from '../references/load-references'
8
8
  import { readAllUndreamedStreamDays, type UndreamedStreamDay } from '../stream-io'
9
9
  import { EMBEDDING_MODEL_ID } from './embedder'
10
10
  import type { VectorStore } from './store'
11
- import { boundEmbeddableText, fragmentEmbeddableText } from './truncation'
11
+ import { chunkEmbeddableText, fragmentEmbeddableText } from './truncation'
12
12
 
13
13
  export type Passage = {
14
14
  id: string
@@ -52,7 +52,7 @@ export async function referencePassages(agentDir: string): Promise<Passage[]> {
52
52
  // applies at startup.
53
53
  export function referencePassagesForOne(slug: string, body: string, demoted = false): Passage[] {
54
54
  if (demoted) return []
55
- return chunkReferenceBody(body).map((chunk, chunkIdx) => ({
55
+ return chunkEmbeddableText(body).map((chunk, chunkIdx) => ({
56
56
  id: `reference:${slug}#${chunkIdx}`,
57
57
  source: 'reference',
58
58
  key: slug,
@@ -98,28 +98,6 @@ function buildPassages(shards: TopicShard[], streamDays: UndreamedStreamDay[]):
98
98
  ]
99
99
  }
100
100
 
101
- function chunkReferenceBody(body: string): string[] {
102
- if (body.length === 0) return ['']
103
-
104
- const chunks: string[] = []
105
- let remaining = body
106
- while (remaining.length > 0) {
107
- const bounded = boundEmbeddableText(remaining)
108
- if (!bounded.bounded) {
109
- chunks.push(bounded.text)
110
- break
111
- }
112
- if (bounded.text.length === 0) {
113
- chunks.push(remaining[0]!)
114
- remaining = remaining.slice(1)
115
- continue
116
- }
117
- chunks.push(bounded.text)
118
- remaining = remaining.slice(bounded.text.length)
119
- }
120
- return chunks
121
- }
122
-
123
101
  function hashContent(content: string): string {
124
102
  return createHash('sha256').update(content).digest('hex')
125
103
  }
@@ -92,6 +92,34 @@ export function boundEmbeddableText(text: string): BoundedText {
92
92
  return { text: text.slice(0, charBudget), bounded: true, estimatedTokens }
93
93
  }
94
94
 
95
+ // Splits text into ordered ≤budget chunks so NOTHING is dropped — the
96
+ // no-silent-loss alternative to `boundEmbeddableText` for callers that can embed
97
+ // every part (stored references, retrieval queries). An in-budget input yields a
98
+ // single unchanged chunk, so the common short case is `[text]`. Each chunk is the
99
+ // longest budgeted prefix of the remaining text (same forward walk as the bound),
100
+ // guaranteeing forward progress; a degenerate input whose first char alone
101
+ // over-estimates still advances one char at a time rather than looping.
102
+ export function chunkEmbeddableText(text: string): string[] {
103
+ if (text.length === 0) return ['']
104
+ const chunks: string[] = []
105
+ let remaining = text
106
+ while (remaining.length > 0) {
107
+ const bounded = boundEmbeddableText(remaining)
108
+ if (!bounded.bounded) {
109
+ chunks.push(bounded.text)
110
+ break
111
+ }
112
+ if (bounded.text.length === 0) {
113
+ chunks.push(remaining[0]!)
114
+ remaining = remaining.slice(1)
115
+ continue
116
+ }
117
+ chunks.push(bounded.text)
118
+ remaining = remaining.slice(bounded.text.length)
119
+ }
120
+ return chunks
121
+ }
122
+
95
123
  // Returns the longest prefix length (in chars) whose estimateTokens is still
96
124
  // within budget. Recomputes the EXACT same estimate incrementally — CJK chars
97
125
  // at 1 token, plus max(non-CJK char-ratio, word count) — so a bounded prefix can
@@ -9,7 +9,7 @@ This plugin is **auto-loaded** by every TypeClaw agent. There is no `plugins[]`
9
9
  `pi-coding-agent`'s built-in tools occasionally return very large payloads that the model only needed once. Two empirically observed cases:
10
10
 
11
11
  1. **`read` on an image file** returns the base64-encoded image inline (e.g. `{type:"image", data:"<3.2MB of base64>"}`). The model uses it on the turn it was asked for, then sees the same 3.2MB of base64 as conversation context on every subsequent prompt — until compaction fires (which is token-driven, not byte-driven, so a single fat blob may sit in context for many turns before compaction is triggered).
12
- 2. **`web_fetch` on a binary URL** (PNG, ZIP, etc.) receives the raw response body, treats it as text, and stores raw binary as a JSON-encoded string. Same effect: 100KB+ of mojibake sits in the transcript permanently.
12
+ 2. **`web_fetch` on a binary URL** (PNG, ZIP, etc.) receives the raw response body, treats it as text, and stores raw binary as a JSON-encoded string. Same effect: 100KB+ of mojibake sits in the transcript permanently. (Historical: this predates `web_fetch`'s own per-strategy `OUTPUT_CAPS`, which now bound its text output to ≤200KB regardless — see the `web_fetch` text exemption below.)
13
13
 
14
14
  The result is a session JSONL file that's tens of megabytes on disk but mostly one or two giant tool results, plus 3-minute first-prompt latencies after container restart because the full transcript gets re-shipped to the LLM as context.
15
15
 
@@ -47,6 +47,15 @@ The cap is per-part, not per-result, so a result with one small text part and on
47
47
 
48
48
  Placeholders carry the literal substring `tool-result-cap:` so future agents (or human operators inspecting a session) can grep for them and recognize that the original payload was intentionally elided rather than truncated by some other layer.
49
49
 
50
+ ## The `web_fetch` text exemption
51
+
52
+ `web_fetch` is exempt from the **text** cap (but not the image cap), hardcoded in `cap-result.ts` via `TEXT_CAP_EXEMPT_TOOLS`. This is not user-configurable because it resolves a collision between two first-party caps:
53
+
54
+ - `web_fetch` has its own per-strategy `OUTPUT_CAPS` in `src/agent/tools/webfetch/types.ts` — `readability` is capped at 200KB, `raw` at 100KB, others between 50KB and 100KB — bounded above by a 5MB transport limit. These are deliberately tuned: `readability` gets a generous budget so a full article reaches the model.
55
+ - This plugin's flat `textMaxBytes` default (32KB) is smaller than every one of those, so without the exemption it would silently clip every `web_fetch` result to ~8K tokens, making the strategy caps meaningless. A `readability` fetch designed for 200KB would never deliver more than 32KB.
56
+
57
+ The exemption is **text-only**: `web_fetch` image parts still go through `imageMaxBytes`, so the binary/base64 transcript-bloat protection (case 2 above) is preserved. The tradeoff is that this plugin no longer provides a 32KB backstop for `web_fetch` text — that responsibility now belongs entirely to `web_fetch`'s own `capOutput()`. User-configured `exemptTools` is a separate, broader knob (skips _all_ capping, image included); the `web_fetch` text exemption is narrower and always on.
58
+
50
59
  ## What's not capped
51
60
 
52
61
  - `details` on tool results (an opaque structured payload provider-specific to each tool — generally small, and mutating it risks breaking tool-specific telemetry).
@@ -14,6 +14,13 @@ export type CapStats = {
14
14
 
15
15
  const ELIDED_MARKER = '[tool-result-cap: '
16
16
 
17
+ // `web_fetch` already bounds its own text via per-strategy OUTPUT_CAPS
18
+ // (src/agent/tools/webfetch/types.ts: 50KB–200KB; readability gets 200KB on
19
+ // purpose), so the flat 32KB textMaxBytes here only collides with it and clips
20
+ // every readability fetch to ~8K tokens. Skip TEXT capping for it; image parts
21
+ // still hit the image cap below, preserving the binary/base64 bloat protection.
22
+ const TEXT_CAP_EXEMPT_TOOLS = new Set(['web_fetch'])
23
+
17
24
  // A capped text part is exactly the placeholder we generated: starts with
18
25
  // `[tool-result-cap: `, ends with `]`, and contains no inner `]`. The shape
19
26
  // check exists for idempotency so a previously-capped entry survives a second
@@ -46,6 +53,7 @@ export function capContentParts(tool: string, content: ContentPart[], options: C
46
53
  continue
47
54
  }
48
55
  if (part.type === 'text') {
56
+ if (TEXT_CAP_EXEMPT_TOOLS.has(tool)) continue
49
57
  const size = part.text.length
50
58
  if (size <= options.textMaxBytes) continue
51
59
  if (isElidedPlaceholderText(part.text)) continue
@@ -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
+ }