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.
- 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/multimodal/look-at.ts +87 -0
- 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/index.ts +10 -11
- package/src/bundled-plugins/memory/vector/hybrid.ts +73 -6
- package/src/bundled-plugins/memory/vector/index-on-write.ts +25 -20
- package/src/bundled-plugins/memory/vector/passages.ts +2 -24
- package/src/bundled-plugins/memory/vector/reference-index-on-write.ts +28 -23
- package/src/bundled-plugins/memory/vector/store.ts +2 -0
- package/src/bundled-plugins/memory/vector/truncation.ts +28 -0
- package/src/bundled-plugins/planner/planner.ts +4 -2
- package/src/bundled-plugins/reviewer/reviewer.ts +9 -1
- 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/kakaotalk-classify.ts +31 -6
- package/src/channels/adapters/kakaotalk.ts +1 -1
- 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 +59 -19
- package/src/hostd/kakao-renewal-manager.ts +35 -10
- package/src/hostd/protocol.ts +2 -0
- package/src/hostd/tailscale.ts +41 -5
- package/src/hostd/webex-renewal-manager.ts +13 -4
- 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/plugin/index.ts +1 -0
- package/src/plugin/manager.ts +14 -0
- package/src/plugin/registry.ts +12 -0
- package/src/plugin/types.ts +4 -0
- package/src/role-claim/match-rule.ts +2 -1
- package/src/run/index.ts +46 -20
- 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/src/test-helpers/rm-temp-dir.ts +24 -0
- package/typeclaw.schema.json +161 -1
package/README.md
CHANGED
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
|
|
27
27
|
## Channels — one agent, many inboxes
|
|
28
28
|
|
|
29
|
-
- 📨 **Supported channels** — Slack, Discord, Telegram, Webex, LINE, KakaoTalk, GitHub, and a websocket TUI, driven by the same agent
|
|
29
|
+
- 📨 **Supported channels** — Slack, Discord, Telegram, Webex, Instagram, LINE, KakaoTalk, GitHub, and a websocket TUI, driven by the same agent
|
|
30
|
+
- 🔎 **Cross-channel reading** — beyond the conversation it's in, it can read another channel's history, pull a single message by id, or list a workspace's channels on demand, so "check what's going on in #general" or "what do you make of this message?" just works
|
|
30
31
|
- ✅ **Pull-request review** — treats a GitHub PR as a conversation, reviewing as a participant, with guards against claiming a verdict it didn't actually post and against leaving a PR stranded
|
|
31
32
|
|
|
32
33
|
## Web & research — reads the web like a person
|
|
@@ -125,7 +126,7 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for the recommended local dev loop (`bu
|
|
|
125
126
|
|
|
126
127
|
## Acknowledgments
|
|
127
128
|
|
|
128
|
-
- **Multi-channel** is powered by [agent-messenger](https://github.com/agent-messenger/agent-messenger) — every non-GitHub adapter (`slack-bot`, `discord-bot`, `telegram-bot`, `webex-bot`, `line`, `kakaotalk`) is built on its SDK. Thanks to the maintainers for the credential extraction, listener protocols, and platform coverage that made multi-channel a feature instead of a year-long project.
|
|
129
|
+
- **Multi-channel** is powered by [agent-messenger](https://github.com/agent-messenger/agent-messenger) — every non-GitHub adapter (`slack-bot`, `discord-bot`, `telegram-bot`, `webex-bot`, `instagram`, `line`, `kakaotalk`) is built on its SDK. Thanks to the maintainers for the credential extraction, listener protocols, and platform coverage that made multi-channel a feature instead of a year-long project.
|
|
129
130
|
- **Subagent architecture** is inspired by [oh-my-openagent](https://github.com/code-yeongyu/oh-my-openagent) by [@code-yeongyu](https://github.com/code-yeongyu). Thanks for the shape that made this clean.
|
|
130
131
|
- **Question-mark attention escalation** ("Jeff Bezos detection") was suggested by [@kdhfred](https://github.com/kdhfred). Thanks for the idea that turned a wall of `?` into a real signal.
|
|
131
132
|
|
package/auth.schema.json
CHANGED
|
@@ -393,6 +393,63 @@
|
|
|
393
393
|
"accounts"
|
|
394
394
|
]
|
|
395
395
|
},
|
|
396
|
+
"instagram": {
|
|
397
|
+
"type": "object",
|
|
398
|
+
"properties": {
|
|
399
|
+
"currentAccount": {
|
|
400
|
+
"anyOf": [
|
|
401
|
+
{
|
|
402
|
+
"type": "string"
|
|
403
|
+
},
|
|
404
|
+
{
|
|
405
|
+
"type": "null"
|
|
406
|
+
}
|
|
407
|
+
]
|
|
408
|
+
},
|
|
409
|
+
"accounts": {
|
|
410
|
+
"type": "object",
|
|
411
|
+
"propertyNames": {
|
|
412
|
+
"type": "string"
|
|
413
|
+
},
|
|
414
|
+
"additionalProperties": {
|
|
415
|
+
"type": "object",
|
|
416
|
+
"properties": {
|
|
417
|
+
"account_id": {
|
|
418
|
+
"type": "string"
|
|
419
|
+
},
|
|
420
|
+
"username": {
|
|
421
|
+
"type": "string"
|
|
422
|
+
},
|
|
423
|
+
"full_name": {
|
|
424
|
+
"type": "string"
|
|
425
|
+
},
|
|
426
|
+
"profile_pic_url": {
|
|
427
|
+
"type": "string"
|
|
428
|
+
},
|
|
429
|
+
"pk": {
|
|
430
|
+
"type": "string"
|
|
431
|
+
},
|
|
432
|
+
"created_at": {
|
|
433
|
+
"type": "string"
|
|
434
|
+
},
|
|
435
|
+
"updated_at": {
|
|
436
|
+
"type": "string"
|
|
437
|
+
}
|
|
438
|
+
},
|
|
439
|
+
"required": [
|
|
440
|
+
"account_id",
|
|
441
|
+
"username",
|
|
442
|
+
"created_at",
|
|
443
|
+
"updated_at"
|
|
444
|
+
]
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
},
|
|
448
|
+
"required": [
|
|
449
|
+
"currentAccount",
|
|
450
|
+
"accounts"
|
|
451
|
+
]
|
|
452
|
+
},
|
|
396
453
|
"kakaotalk": {
|
|
397
454
|
"type": "object",
|
|
398
455
|
"properties": {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "typeclaw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.42.0",
|
|
4
4
|
"homepage": "https://github.com/typeclaw/typeclaw#readme",
|
|
5
5
|
"bugs": {
|
|
6
6
|
"url": "https://github.com/typeclaw/typeclaw/issues"
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"@mariozechner/pi-tui": "^0.67.3",
|
|
51
51
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
52
52
|
"@mozilla/readability": "^0.6.0",
|
|
53
|
-
"agent-messenger": "^2.
|
|
53
|
+
"agent-messenger": "^2.28.0",
|
|
54
54
|
"cheerio": "^1.2.0",
|
|
55
55
|
"citty": "^0.2.2",
|
|
56
56
|
"cron-parser": "^5.5.0",
|
package/secrets.schema.json
CHANGED
|
@@ -393,6 +393,63 @@
|
|
|
393
393
|
"accounts"
|
|
394
394
|
]
|
|
395
395
|
},
|
|
396
|
+
"instagram": {
|
|
397
|
+
"type": "object",
|
|
398
|
+
"properties": {
|
|
399
|
+
"currentAccount": {
|
|
400
|
+
"anyOf": [
|
|
401
|
+
{
|
|
402
|
+
"type": "string"
|
|
403
|
+
},
|
|
404
|
+
{
|
|
405
|
+
"type": "null"
|
|
406
|
+
}
|
|
407
|
+
]
|
|
408
|
+
},
|
|
409
|
+
"accounts": {
|
|
410
|
+
"type": "object",
|
|
411
|
+
"propertyNames": {
|
|
412
|
+
"type": "string"
|
|
413
|
+
},
|
|
414
|
+
"additionalProperties": {
|
|
415
|
+
"type": "object",
|
|
416
|
+
"properties": {
|
|
417
|
+
"account_id": {
|
|
418
|
+
"type": "string"
|
|
419
|
+
},
|
|
420
|
+
"username": {
|
|
421
|
+
"type": "string"
|
|
422
|
+
},
|
|
423
|
+
"full_name": {
|
|
424
|
+
"type": "string"
|
|
425
|
+
},
|
|
426
|
+
"profile_pic_url": {
|
|
427
|
+
"type": "string"
|
|
428
|
+
},
|
|
429
|
+
"pk": {
|
|
430
|
+
"type": "string"
|
|
431
|
+
},
|
|
432
|
+
"created_at": {
|
|
433
|
+
"type": "string"
|
|
434
|
+
},
|
|
435
|
+
"updated_at": {
|
|
436
|
+
"type": "string"
|
|
437
|
+
}
|
|
438
|
+
},
|
|
439
|
+
"required": [
|
|
440
|
+
"account_id",
|
|
441
|
+
"username",
|
|
442
|
+
"created_at",
|
|
443
|
+
"updated_at"
|
|
444
|
+
]
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
},
|
|
448
|
+
"required": [
|
|
449
|
+
"currentAccount",
|
|
450
|
+
"accounts"
|
|
451
|
+
]
|
|
452
|
+
},
|
|
396
453
|
"kakaotalk": {
|
|
397
454
|
"type": "object",
|
|
398
455
|
"properties": {
|
package/src/agent/index.ts
CHANGED
|
@@ -78,6 +78,7 @@ import { createChannelDisengageTool } from './tools/channel-disengage'
|
|
|
78
78
|
import { createChannelFetchAttachmentTool } from './tools/channel-fetch-attachment'
|
|
79
79
|
import { createChannelHistoryTool } from './tools/channel-history'
|
|
80
80
|
import { createChannelReactTool } from './tools/channel-react'
|
|
81
|
+
import { createChannelReadTool } from './tools/channel-read'
|
|
81
82
|
import { createChannelReplyTool } from './tools/channel-reply'
|
|
82
83
|
import { createChannelSendTool } from './tools/channel-send'
|
|
83
84
|
import { createGrantRoleTool } from './tools/grant-role'
|
|
@@ -665,12 +666,13 @@ export function formatRestartNoticeOriginating(restartedAt: string): string {
|
|
|
665
666
|
].join('\n')
|
|
666
667
|
}
|
|
667
668
|
|
|
668
|
-
// Builds the channel tool subset: channel_send
|
|
669
|
-
//
|
|
670
|
-
//
|
|
671
|
-
//
|
|
672
|
-
// (when sessionId is known)
|
|
673
|
-
// addressing or per-session turn
|
|
669
|
+
// Builds the channel tool subset: channel_send and channel_read (both always
|
|
670
|
+
// when a router is available — they take explicit addressing, not origin-bound),
|
|
671
|
+
// plus the origin-bound channel tools when the session origin is a channel —
|
|
672
|
+
// channel_reply, channel_history, channel_react, channel_fetch_attachment,
|
|
673
|
+
// look_at_channel_attachment, channel_disengage, and (when sessionId is known)
|
|
674
|
+
// skip_response. Those rely on origin-bound addressing or per-session turn
|
|
675
|
+
// state. Extracted from
|
|
674
676
|
// createSessionWithDispose so composition can be unit-tested without
|
|
675
677
|
// going through createAgentSession / auth.
|
|
676
678
|
//
|
|
@@ -702,6 +704,7 @@ export function buildChannelTools(
|
|
|
702
704
|
}),
|
|
703
705
|
)
|
|
704
706
|
tools.push(createChannelHistoryTool({ router: channelRouter, origin: channelOrigin }))
|
|
707
|
+
tools.push(createChannelReadTool({ router: channelRouter }))
|
|
705
708
|
tools.push(
|
|
706
709
|
createChannelSendTool({
|
|
707
710
|
router: channelRouter,
|
|
@@ -736,6 +739,7 @@ export function buildChannelTools(
|
|
|
736
739
|
}
|
|
737
740
|
} else {
|
|
738
741
|
tools.push(createChannelSendTool({ router: channelRouter }))
|
|
742
|
+
tools.push(createChannelReadTool({ router: channelRouter }))
|
|
739
743
|
}
|
|
740
744
|
return tools
|
|
741
745
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
|
|
1
3
|
import { Type } from '@mariozechner/pi-ai'
|
|
2
4
|
import type { ImageContent } from '@mariozechner/pi-ai'
|
|
3
5
|
import { defineTool } from '@mariozechner/pi-coding-agent'
|
|
@@ -5,6 +7,9 @@ import { defineTool } from '@mariozechner/pi-coding-agent'
|
|
|
5
7
|
import { createSessionWithDispose, type SessionOrigin } from '@/agent'
|
|
6
8
|
import type { ChannelRouter } from '@/channels/router'
|
|
7
9
|
import type { AdapterId } from '@/channels/schema'
|
|
10
|
+
import { getConfig, resolveModel, resolveProfile } from '@/config'
|
|
11
|
+
import { providerForModelRef } from '@/config/providers'
|
|
12
|
+
import { SecretsBackend } from '@/secrets'
|
|
8
13
|
|
|
9
14
|
import { buildMultimodalLookerSystemPrompt, resolveImage, type ImageInput } from './looker'
|
|
10
15
|
|
|
@@ -139,6 +144,15 @@ function toImageContent(data: string, mimeType: string): ImageContent {
|
|
|
139
144
|
}
|
|
140
145
|
|
|
141
146
|
async function runLookAtImages(imageContents: ImageContent[], prompt: string | undefined) {
|
|
147
|
+
// Exception for text-only GLM Coding Plan models: the subagent below would
|
|
148
|
+
// resolve to the same image-blind model and silently fail. GLM-4.6V vision is
|
|
149
|
+
// reachable on the coding-plan endpoint with the same key (POST
|
|
150
|
+
// /api/coding/paas/v4 → 200, drawn from the plan's vision quota). Only this
|
|
151
|
+
// setup diverts; every other one keeps the subagent path.
|
|
152
|
+
if (shouldUseGlmCodingPlanVision()) {
|
|
153
|
+
return await analyzeWithGlmCodingPlanVision(imageContents, prompt)
|
|
154
|
+
}
|
|
155
|
+
|
|
142
156
|
const systemPrompt = buildMultimodalLookerSystemPrompt(prompt)
|
|
143
157
|
const userText =
|
|
144
158
|
prompt !== undefined && prompt.trim() !== '' ? prompt.trim() : 'Please describe the attached image(s).'
|
|
@@ -188,6 +202,79 @@ async function runLookAtImages(imageContents: ImageContent[], prompt: string | u
|
|
|
188
202
|
}
|
|
189
203
|
}
|
|
190
204
|
|
|
205
|
+
const GLM_VISION_PROVIDER = 'zai-coding'
|
|
206
|
+
const GLM_VISION_MODEL = 'glm-4.6v'
|
|
207
|
+
const GLM_VISION_ENDPOINT = 'https://api.z.ai/api/coding/paas/v4/chat/completions'
|
|
208
|
+
const GLM_VISION_MAX_TOKENS = 32768
|
|
209
|
+
|
|
210
|
+
function shouldUseGlmCodingPlanVision(): boolean {
|
|
211
|
+
const ref = resolveProfile(getConfig().models, 'vision').ref
|
|
212
|
+
return providerForModelRef(ref) === GLM_VISION_PROVIDER && !resolveModel(ref).input.includes('image')
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function analyzeWithGlmCodingPlanVision(imageContents: ImageContent[], prompt: string | undefined) {
|
|
216
|
+
const details = { count: imageContents.length, prompt }
|
|
217
|
+
const apiKey = new SecretsBackend(join(process.cwd(), 'secrets.json')).tryReadProviderApiKeySync(GLM_VISION_PROVIDER)
|
|
218
|
+
if (apiKey === null) {
|
|
219
|
+
return errorResult('GLM Coding Plan vision unavailable: no zai-coding API key', details)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
let response: Response
|
|
223
|
+
try {
|
|
224
|
+
response = await fetch(GLM_VISION_ENDPOINT, {
|
|
225
|
+
method: 'POST',
|
|
226
|
+
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
|
227
|
+
body: JSON.stringify({
|
|
228
|
+
model: GLM_VISION_MODEL,
|
|
229
|
+
max_tokens: GLM_VISION_MAX_TOKENS,
|
|
230
|
+
messages: buildGlmVisionMessages(imageContents, prompt),
|
|
231
|
+
}),
|
|
232
|
+
})
|
|
233
|
+
} catch (error) {
|
|
234
|
+
return errorResult(`GLM vision request failed: ${error instanceof Error ? error.message : String(error)}`, details)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (!response.ok) {
|
|
238
|
+
return errorResult(`GLM vision request failed: HTTP ${response.status}`, details)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const text = extractGlmVisionText(await response.json().catch(() => null))
|
|
242
|
+
if (text === null) {
|
|
243
|
+
return errorResult('GLM vision returned no text response', details)
|
|
244
|
+
}
|
|
245
|
+
return successResult(text, details)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Mirror the subagent path's systemPromptOverride so the direct route keeps
|
|
249
|
+
// the same visible-only / faithful-transcription / no-preamble behavior.
|
|
250
|
+
export function buildGlmVisionMessages(imageContents: ImageContent[], prompt: string | undefined) {
|
|
251
|
+
const userText =
|
|
252
|
+
prompt !== undefined && prompt.trim() !== '' ? prompt.trim() : 'Please describe the attached image(s).'
|
|
253
|
+
return [
|
|
254
|
+
{ role: 'system' as const, content: buildMultimodalLookerSystemPrompt(prompt) },
|
|
255
|
+
{
|
|
256
|
+
role: 'user' as const,
|
|
257
|
+
content: [
|
|
258
|
+
...imageContents.map((image) => ({
|
|
259
|
+
type: 'image_url' as const,
|
|
260
|
+
image_url: { url: `data:${image.mimeType};base64,${image.data}` },
|
|
261
|
+
})),
|
|
262
|
+
{ type: 'text' as const, text: userText },
|
|
263
|
+
],
|
|
264
|
+
},
|
|
265
|
+
]
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function extractGlmVisionText(body: unknown): string | null {
|
|
269
|
+
if (typeof body !== 'object' || body === null) return null
|
|
270
|
+
const choices = (body as { choices?: unknown }).choices
|
|
271
|
+
if (!Array.isArray(choices) || choices.length === 0) return null
|
|
272
|
+
const message = (choices[0] as { message?: unknown }).message
|
|
273
|
+
const text = (message as { content?: unknown } | undefined)?.content
|
|
274
|
+
if (typeof text !== 'string' || text.trim() === '') return null
|
|
275
|
+
return text.trim()
|
|
276
|
+
}
|
|
277
|
+
|
|
191
278
|
function toImageInput(p: ImageParam): ImageInput {
|
|
192
279
|
const hasUrl = 'url' in p && p.url !== undefined && p.url !== ''
|
|
193
280
|
const hasPath = 'path' in p && p.path !== undefined && p.path !== ''
|
|
@@ -153,6 +153,7 @@ const PLATFORM_INFO: Record<AdapterId, PlatformInfo> = {
|
|
|
153
153
|
supportsAttachments: true,
|
|
154
154
|
},
|
|
155
155
|
github: { displayName: 'GitHub', mentionMode: 'at-username', supportsReactions: true, supportsAttachments: false },
|
|
156
|
+
instagram: { displayName: 'Instagram', mentionMode: 'alias', supportsReactions: false, supportsAttachments: false },
|
|
156
157
|
'telegram-bot': {
|
|
157
158
|
displayName: 'Telegram',
|
|
158
159
|
mentionMode: 'at-username',
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ChannelHistoryMessage } from '@/channels/types'
|
|
2
|
+
|
|
3
|
+
// Render history as one line per message, chronological order. `BOT` marker
|
|
4
|
+
// distinguishes the agent's own past replies from user messages so the model
|
|
5
|
+
// does not treat them as user input. Author name is shown alongside the id so
|
|
6
|
+
// the agent can refer to people by name. Shared by channel_history (origin-
|
|
7
|
+
// bound) and channel_read (arbitrary-chat) so both render identically.
|
|
8
|
+
export function renderHistoryMessages(messages: readonly ChannelHistoryMessage[]): string {
|
|
9
|
+
if (messages.length === 0) return '(no messages)'
|
|
10
|
+
const lines: string[] = []
|
|
11
|
+
for (const m of messages) {
|
|
12
|
+
lines.push(renderHistoryMessage(m))
|
|
13
|
+
}
|
|
14
|
+
return lines.join('\n')
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function renderHistoryMessage(m: ChannelHistoryMessage): string {
|
|
18
|
+
const iso = m.ts > 0 ? new Date(m.ts).toISOString() : 'unknown-time'
|
|
19
|
+
const who = m.isBot ? `BOT (${m.authorName})` : `${m.authorName} (<@${m.authorId}>)`
|
|
20
|
+
return `[${iso}] ${who}: ${m.text}`
|
|
21
|
+
}
|
|
@@ -3,8 +3,8 @@ import { defineTool } from '@mariozechner/pi-coding-agent'
|
|
|
3
3
|
|
|
4
4
|
import type { ChannelRouter } from '@/channels/router'
|
|
5
5
|
import type { AdapterId } from '@/channels/schema'
|
|
6
|
-
import type { ChannelHistoryMessage } from '@/channels/types'
|
|
7
6
|
|
|
7
|
+
import { renderHistoryMessages } from './channel-history-render'
|
|
8
8
|
import { type ChannelToolLogger, consoleChannelLogger, formatChannelToolFailure } from './channel-log'
|
|
9
9
|
|
|
10
10
|
export type ChannelHistoryOrigin = {
|
|
@@ -96,7 +96,7 @@ export function createChannelHistoryTool({
|
|
|
96
96
|
|
|
97
97
|
router.registerHistoryAttachments(origin, result.messages)
|
|
98
98
|
|
|
99
|
-
const rendered =
|
|
99
|
+
const rendered = renderHistoryMessages(result.messages)
|
|
100
100
|
const cursorLine =
|
|
101
101
|
result.nextCursor !== undefined
|
|
102
102
|
? `\n\n(more older messages available — call channel_history again with cursor: ${JSON.stringify(result.nextCursor)})`
|
|
@@ -113,18 +113,3 @@ export function createChannelHistoryTool({
|
|
|
113
113
|
},
|
|
114
114
|
})
|
|
115
115
|
}
|
|
116
|
-
|
|
117
|
-
// Render history as one line per message, chronological order. `BOT` marker
|
|
118
|
-
// distinguishes the agent's own past replies from user messages so the
|
|
119
|
-
// model doesn't treat them as user input. Author name is shown alongside
|
|
120
|
-
// the id so the agent can refer to people by name in its reply.
|
|
121
|
-
function renderMessages(messages: readonly ChannelHistoryMessage[]): string {
|
|
122
|
-
if (messages.length === 0) return '(no messages)'
|
|
123
|
-
const lines: string[] = []
|
|
124
|
-
for (const m of messages) {
|
|
125
|
-
const iso = m.ts > 0 ? new Date(m.ts).toISOString() : 'unknown-time'
|
|
126
|
-
const who = m.isBot ? `BOT (${m.authorName})` : `${m.authorName} (<@${m.authorId}>)`
|
|
127
|
-
lines.push(`[${iso}] ${who}: ${m.text}`)
|
|
128
|
-
}
|
|
129
|
-
return lines.join('\n')
|
|
130
|
-
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { Type } from '@mariozechner/pi-ai'
|
|
2
|
+
import { defineTool } from '@mariozechner/pi-coding-agent'
|
|
3
|
+
|
|
4
|
+
import type { ChannelRouter } from '@/channels/router'
|
|
5
|
+
import { ADAPTER_IDS, type AdapterId } from '@/channels/schema'
|
|
6
|
+
import type { ChannelListEntry } from '@/channels/types'
|
|
7
|
+
|
|
8
|
+
import { renderHistoryMessage, renderHistoryMessages } from './channel-history-render'
|
|
9
|
+
import { type ChannelToolLogger, consoleChannelLogger, formatChannelToolFailure } from './channel-log'
|
|
10
|
+
|
|
11
|
+
export type CreateChannelReadToolOptions = {
|
|
12
|
+
router: ChannelRouter
|
|
13
|
+
logger?: ChannelToolLogger
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const DEFAULT_LIMIT = 20
|
|
17
|
+
|
|
18
|
+
// channel_read is the arbitrary-addressing read counterpart to channel_send:
|
|
19
|
+
// where channel_history is locked to the current session's chat, channel_read
|
|
20
|
+
// takes an explicit adapter/workspace/chat so the agent can look at a DIFFERENT
|
|
21
|
+
// conversation ("check the #general messages", "what's this message id"). Three
|
|
22
|
+
// modes share one tool to keep the per-turn tool-schema budget small, mirroring
|
|
23
|
+
// web_fetch's strategy union; mode-specific required params are validated at
|
|
24
|
+
// runtime since JSON-Schema can't express "required-if".
|
|
25
|
+
export function createChannelReadTool({ router, logger = consoleChannelLogger }: CreateChannelReadToolOptions) {
|
|
26
|
+
return defineTool({
|
|
27
|
+
name: 'channel_read',
|
|
28
|
+
label: 'Channel Read',
|
|
29
|
+
description:
|
|
30
|
+
'Read from an external messenger channel you are NOT necessarily engaged in. Always specify `adapter` and `workspace`. ' +
|
|
31
|
+
'Three modes:\n' +
|
|
32
|
+
'- "history": fetch recent messages from `chat` (optionally a `thread`). Returns oldest-first; pass `cursor` to page further back. Use for "check the #general messages".\n' +
|
|
33
|
+
'- "message": fetch ONE message from `chat` by `message_id`. Use for "what do you think of <message id>".\n' +
|
|
34
|
+
'- "list": discover channels/chats in `workspace` (no `chat` needed). Use when you do not yet know a chat id.\n' +
|
|
35
|
+
'For Discord guild channels, `workspace` is the guild id; for Slack team channels, `workspace` is the team id (e.g. "T0ACME"); for DMs, "@dm". ' +
|
|
36
|
+
'On failure returns { ok: false, error }. Not every adapter supports every mode — an unsupported mode returns a not-supported error rather than throwing. ' +
|
|
37
|
+
'This is read-only; use channel_send to post.',
|
|
38
|
+
parameters: Type.Object({
|
|
39
|
+
mode: Type.Union([Type.Literal('history'), Type.Literal('message'), Type.Literal('list')], {
|
|
40
|
+
description:
|
|
41
|
+
'What to read: "history" (recent messages), "message" (one message by id), or "list" (discover chats).',
|
|
42
|
+
}),
|
|
43
|
+
adapter: Type.Union(
|
|
44
|
+
ADAPTER_IDS.map((a) => Type.Literal(a)),
|
|
45
|
+
{ description: 'Adapter id, e.g. "discord-bot", "slack-bot".' },
|
|
46
|
+
),
|
|
47
|
+
workspace: Type.String({
|
|
48
|
+
description: 'Discord guild id or Slack team id (e.g. "T0ACME"); "@dm" for direct messages.',
|
|
49
|
+
minLength: 1,
|
|
50
|
+
}),
|
|
51
|
+
chat: Type.Optional(
|
|
52
|
+
Type.String({
|
|
53
|
+
description: 'Channel/chat id. Required for mode "history" and "message"; omit for mode "list".',
|
|
54
|
+
minLength: 1,
|
|
55
|
+
}),
|
|
56
|
+
),
|
|
57
|
+
thread: Type.Optional(
|
|
58
|
+
Type.String({
|
|
59
|
+
description: 'Optional thread id/ts to narrow history or a threaded message lookup.',
|
|
60
|
+
minLength: 1,
|
|
61
|
+
}),
|
|
62
|
+
),
|
|
63
|
+
message_id: Type.Optional(
|
|
64
|
+
Type.String({ description: 'Message id to fetch. Required for mode "message".', minLength: 1 }),
|
|
65
|
+
),
|
|
66
|
+
limit: Type.Optional(
|
|
67
|
+
Type.Number({
|
|
68
|
+
description: 'history/list: number of items to fetch (default 20). Adapters cap this further.',
|
|
69
|
+
minimum: 1,
|
|
70
|
+
maximum: 200,
|
|
71
|
+
}),
|
|
72
|
+
),
|
|
73
|
+
cursor: Type.Optional(
|
|
74
|
+
Type.String({
|
|
75
|
+
description: 'history/list: opaque cursor from a previous result to page further.',
|
|
76
|
+
minLength: 1,
|
|
77
|
+
}),
|
|
78
|
+
),
|
|
79
|
+
}),
|
|
80
|
+
|
|
81
|
+
async execute(_toolCallId, params) {
|
|
82
|
+
const adapter = params.adapter as AdapterId
|
|
83
|
+
const limit = params.limit ?? DEFAULT_LIMIT
|
|
84
|
+
|
|
85
|
+
if (params.mode === 'history') {
|
|
86
|
+
return await readHistory({ router, logger, adapter, params, limit })
|
|
87
|
+
}
|
|
88
|
+
if (params.mode === 'message') {
|
|
89
|
+
return await readMessage({ router, logger, adapter, params })
|
|
90
|
+
}
|
|
91
|
+
return await readList({ router, logger, adapter, params, limit })
|
|
92
|
+
},
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
type Details = { ok: boolean; error?: string; count?: number; nextCursor?: string }
|
|
97
|
+
|
|
98
|
+
function fail(error: string): { content: [{ type: 'text'; text: string }]; details: Details } {
|
|
99
|
+
return { content: [{ type: 'text' as const, text: `channel_read error: ${error}` }], details: { ok: false, error } }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function readHistory(args: {
|
|
103
|
+
router: ChannelRouter
|
|
104
|
+
logger: ChannelToolLogger
|
|
105
|
+
adapter: AdapterId
|
|
106
|
+
params: { workspace: string; chat?: string; thread?: string; cursor?: string }
|
|
107
|
+
limit: number
|
|
108
|
+
}) {
|
|
109
|
+
const { router, logger, adapter, params, limit } = args
|
|
110
|
+
if (params.chat === undefined) {
|
|
111
|
+
logger.warn(formatChannelToolFailure('channel_read', 'history-requires-chat'))
|
|
112
|
+
return fail('mode "history" requires `chat`.')
|
|
113
|
+
}
|
|
114
|
+
const result = await router.fetchHistory(adapter, {
|
|
115
|
+
chat: params.chat,
|
|
116
|
+
thread: params.thread ?? null,
|
|
117
|
+
limit,
|
|
118
|
+
...(params.cursor !== undefined ? { cursor: params.cursor } : {}),
|
|
119
|
+
})
|
|
120
|
+
if (!result.ok) {
|
|
121
|
+
logger.warn(formatChannelToolFailure('channel_read', `${adapter}:${params.chat}: ${result.error}`))
|
|
122
|
+
return fail(result.error)
|
|
123
|
+
}
|
|
124
|
+
const rendered = renderHistoryMessages(result.messages)
|
|
125
|
+
const cursorLine =
|
|
126
|
+
result.nextCursor !== undefined
|
|
127
|
+
? `\n\n(more older messages available — call channel_read again with cursor: ${JSON.stringify(result.nextCursor)})`
|
|
128
|
+
: ''
|
|
129
|
+
const header = `## ${adapter}:${params.workspace}/${params.chat} history (${result.messages.length} message${result.messages.length === 1 ? '' : 's'}, oldest first)`
|
|
130
|
+
const details: Details =
|
|
131
|
+
result.nextCursor !== undefined
|
|
132
|
+
? { ok: true, count: result.messages.length, nextCursor: result.nextCursor }
|
|
133
|
+
: { ok: true, count: result.messages.length }
|
|
134
|
+
return { content: [{ type: 'text' as const, text: `${header}\n${rendered}${cursorLine}` }], details }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function readMessage(args: {
|
|
138
|
+
router: ChannelRouter
|
|
139
|
+
logger: ChannelToolLogger
|
|
140
|
+
adapter: AdapterId
|
|
141
|
+
params: { workspace: string; chat?: string; thread?: string; message_id?: string }
|
|
142
|
+
}) {
|
|
143
|
+
const { router, logger, adapter, params } = args
|
|
144
|
+
if (params.chat === undefined) {
|
|
145
|
+
logger.warn(formatChannelToolFailure('channel_read', 'message-requires-chat'))
|
|
146
|
+
return fail('mode "message" requires `chat`.')
|
|
147
|
+
}
|
|
148
|
+
if (params.message_id === undefined) {
|
|
149
|
+
logger.warn(formatChannelToolFailure('channel_read', 'message-requires-message_id'))
|
|
150
|
+
return fail('mode "message" requires `message_id`.')
|
|
151
|
+
}
|
|
152
|
+
const result = await router.getMessage(adapter, {
|
|
153
|
+
chat: params.chat,
|
|
154
|
+
thread: params.thread ?? null,
|
|
155
|
+
messageId: params.message_id,
|
|
156
|
+
})
|
|
157
|
+
if (!result.ok) {
|
|
158
|
+
logger.warn(formatChannelToolFailure('channel_read', `${adapter}:${params.chat}: ${result.error}`))
|
|
159
|
+
return fail(result.error)
|
|
160
|
+
}
|
|
161
|
+
const header = `## ${adapter}:${params.workspace}/${params.chat} message ${params.message_id}`
|
|
162
|
+
return {
|
|
163
|
+
content: [{ type: 'text' as const, text: `${header}\n${renderHistoryMessage(result.message)}` }],
|
|
164
|
+
details: { ok: true, count: 1 } satisfies Details,
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function readList(args: {
|
|
169
|
+
router: ChannelRouter
|
|
170
|
+
logger: ChannelToolLogger
|
|
171
|
+
adapter: AdapterId
|
|
172
|
+
params: { workspace: string; cursor?: string }
|
|
173
|
+
limit: number
|
|
174
|
+
}) {
|
|
175
|
+
const { router, logger, adapter, params, limit } = args
|
|
176
|
+
const result = await router.listChannels(adapter, {
|
|
177
|
+
workspace: params.workspace,
|
|
178
|
+
limit,
|
|
179
|
+
...(params.cursor !== undefined ? { cursor: params.cursor } : {}),
|
|
180
|
+
})
|
|
181
|
+
if (!result.ok) {
|
|
182
|
+
logger.warn(formatChannelToolFailure('channel_read', `${adapter}:${params.workspace}: ${result.error}`))
|
|
183
|
+
return fail(result.error)
|
|
184
|
+
}
|
|
185
|
+
const rendered = renderChannelList(result.entries)
|
|
186
|
+
const cursorLine =
|
|
187
|
+
result.nextCursor !== undefined
|
|
188
|
+
? `\n\n(more channels available — call channel_read again with cursor: ${JSON.stringify(result.nextCursor)})`
|
|
189
|
+
: ''
|
|
190
|
+
const header = `## ${adapter}:${params.workspace} channels (${result.entries.length})`
|
|
191
|
+
const details: Details =
|
|
192
|
+
result.nextCursor !== undefined
|
|
193
|
+
? { ok: true, count: result.entries.length, nextCursor: result.nextCursor }
|
|
194
|
+
: { ok: true, count: result.entries.length }
|
|
195
|
+
return { content: [{ type: 'text' as const, text: `${header}\n${rendered}${cursorLine}` }], details }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function renderChannelList(entries: readonly ChannelListEntry[]): string {
|
|
199
|
+
if (entries.length === 0) return '(no channels)'
|
|
200
|
+
return entries
|
|
201
|
+
.map((e) => {
|
|
202
|
+
const member = e.isMember === undefined ? '' : e.isMember ? ', member' : ', not-member'
|
|
203
|
+
return `${e.name} (chat=${e.chat}, ${e.kind}${member})`
|
|
204
|
+
})
|
|
205
|
+
.join('\n')
|
|
206
|
+
}
|
|
@@ -44,8 +44,32 @@ The dashboard takes a moment to come up and the user needs time to open the URL.
|
|
|
44
44
|
3. Tell the user: **"Open `http://localhost:<port>` in your browser."** Over
|
|
45
45
|
Tailscale or LAN, the same port works on the host's external address:
|
|
46
46
|
`http://<host>:<port>`.
|
|
47
|
-
4.
|
|
48
|
-
|
|
47
|
+
4. **Also offer a public tunnel URL — assume the user is non-technical.** Most
|
|
48
|
+
users won't know what "the dashboard" is, won't be on the host machine, and
|
|
49
|
+
won't be on the same LAN/Tailscale, so `localhost:<port>` is useless to them.
|
|
50
|
+
Whenever you hand off the dashboard, in the same message tell them you can
|
|
51
|
+
also expose it as a public link they can open from any device. In plain
|
|
52
|
+
words — never make them reason about "cloudflared" or "tunnels":
|
|
53
|
+
|
|
54
|
+
> I've started the live browser view. If `http://localhost:<port>` doesn't
|
|
55
|
+
> open on your device, I can also give you a public web link that works from
|
|
56
|
+
> anywhere — want me to set that up?
|
|
57
|
+
|
|
58
|
+
If they say yes, expose the dashboard over a Cloudflare Quick tunnel (no
|
|
59
|
+
signup, URL looks like `https://<random>.trycloudflare.com`) and hand them
|
|
60
|
+
that URL instead. Point the tunnel at the dashboard's **in-container** service
|
|
61
|
+
— not the host-forward port from `/tmp/typeclaw-agent-browser-proxy-port`.
|
|
62
|
+
That hint file is the host-visible mapping for `localhost`/Tailscale/LAN
|
|
63
|
+
handoff; it can fall back to a different host port, and a tunnel upstream must
|
|
64
|
+
be the in-container port the dashboard actually listens on. Let
|
|
65
|
+
`typeclaw-tunnels` own the upstream choice: the mechanics —
|
|
66
|
+
`docker.file.cloudflared`, `typeclaw tunnel add`, picking the right
|
|
67
|
+
`upstreamPort`, restart-required, root-cause diagnosis — live there; load it
|
|
68
|
+
before touching `typeclaw.json`. Surface the public URL to the user as a
|
|
69
|
+
normal link; never make them think about cloudflared, ports, or config.
|
|
70
|
+
|
|
71
|
+
5. Wait for the user to confirm they're ready before proceeding.
|
|
72
|
+
6. When the user is done, they hand control back implicitly — just resume your
|
|
49
73
|
normal `agent-browser` commands. Session state is shared with the dashboard.
|
|
50
74
|
|
|
51
75
|
The dashboard is served directly by `agent-browser` on one origin; TypeClaw only
|