typeclaw 0.39.2 → 0.39.4

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 (102) hide show
  1. package/auth.schema.json +110 -0
  2. package/package.json +2 -2
  3. package/secrets.schema.json +110 -0
  4. package/src/agent/index.ts +39 -18
  5. package/src/agent/model-fallback.ts +13 -4
  6. package/src/agent/plugin-tools.ts +12 -12
  7. package/src/agent/provider-error.ts +36 -1
  8. package/src/agent/session-origin.ts +2 -0
  9. package/src/agent/subagents.ts +29 -2
  10. package/src/agent/throttle-circuit.ts +50 -0
  11. package/src/agent/todo/store.ts +21 -1
  12. package/src/agent/tools/channel-reply.ts +18 -5
  13. package/src/agent/tools/channel-send.ts +13 -2
  14. package/src/agent/turn-runner.ts +162 -0
  15. package/src/bundled-plugins/doc-render/render.ts +2 -2
  16. package/src/bundled-plugins/github-cli-auth/approve-idempotency.ts +40 -18
  17. package/src/bundled-plugins/memory/README.md +12 -12
  18. package/src/bundled-plugins/memory/append-tool.ts +58 -6
  19. package/src/bundled-plugins/memory/dreaming.ts +1 -1
  20. package/src/bundled-plugins/memory/fragment-parser.ts +10 -3
  21. package/src/bundled-plugins/memory/load-memory.ts +28 -2
  22. package/src/bundled-plugins/memory/memory-logger.ts +14 -2
  23. package/src/bundled-plugins/memory/search-tool.ts +50 -7
  24. package/src/bundled-plugins/memory/stream-events.ts +23 -0
  25. package/src/bundled-plugins/memory/vector/hybrid.ts +9 -2
  26. package/src/bundled-plugins/security/index.ts +24 -1
  27. package/src/bundled-plugins/security/policies/cron-promotion.ts +94 -62
  28. package/src/bundled-plugins/security/policies/plugin-addition.ts +2 -4
  29. package/src/bundled-plugins/security/policies/role-promotion.ts +2 -4
  30. package/src/channels/adapters/discord-author-resolver.ts +52 -0
  31. package/src/channels/adapters/discord-bot.ts +1 -1
  32. package/src/channels/adapters/discord-channel-resolver.ts +44 -0
  33. package/src/channels/adapters/discord-classify.ts +121 -0
  34. package/src/channels/adapters/discord-reactions.ts +138 -0
  35. package/src/channels/adapters/discord.ts +416 -0
  36. package/src/channels/adapters/github/outbound.ts +23 -4
  37. package/src/channels/adapters/kakaotalk.ts +8 -1
  38. package/src/channels/adapters/line.ts +1 -1
  39. package/src/channels/adapters/slack-author-resolver.ts +54 -0
  40. package/src/channels/adapters/slack-bot.ts +3 -1
  41. package/src/channels/adapters/slack-channel-resolver.ts +49 -0
  42. package/src/channels/adapters/slack-classify.ts +83 -0
  43. package/src/channels/adapters/slack-reactions.ts +126 -0
  44. package/src/channels/adapters/slack.ts +416 -0
  45. package/src/channels/adapters/telegram-bot.ts +2 -1
  46. package/src/channels/adapters/webex-bot.ts +31 -27
  47. package/src/channels/adapters/webex-prefetch-limiter.ts +120 -0
  48. package/src/channels/adapters/webex.ts +81 -31
  49. package/src/channels/github-review-turn-ledger.ts +32 -0
  50. package/src/channels/github-verdict-activity.ts +60 -0
  51. package/src/channels/index.ts +6 -0
  52. package/src/channels/manager.ts +168 -37
  53. package/src/channels/pr-verdict-activity-bridge.ts +43 -0
  54. package/src/channels/router.ts +295 -13
  55. package/src/channels/schema.ts +4 -0
  56. package/src/channels/types.ts +25 -2
  57. package/src/cli/builtins.ts +6 -31
  58. package/src/cli/channel.ts +170 -18
  59. package/src/cli/command-meta.ts +93 -0
  60. package/src/cli/help.ts +24 -0
  61. package/src/cli/index.ts +45 -10
  62. package/src/cli/init.ts +2 -0
  63. package/src/cli/update-check.ts +14 -0
  64. package/src/cli/update-notify.ts +91 -0
  65. package/src/cli/update-suppression.ts +19 -0
  66. package/src/config/channels-mutation.ts +3 -1
  67. package/src/config/config.ts +78 -1
  68. package/src/config/index.ts +1 -0
  69. package/src/container/start.ts +52 -8
  70. package/src/doctor/channel-checks.ts +57 -3
  71. package/src/hostd/daemon.ts +77 -31
  72. package/src/hostd/index.ts +11 -1
  73. package/src/hostd/paths.ts +4 -0
  74. package/src/hostd/protocol.ts +15 -2
  75. package/src/hostd/spawn.ts +53 -19
  76. package/src/init/cli-version.ts +1 -1
  77. package/src/init/discord-auth.ts +50 -0
  78. package/src/init/index.ts +94 -4
  79. package/src/init/reconcile-plugin-deps.ts +30 -5
  80. package/src/init/run-owner-claim.ts +2 -0
  81. package/src/init/slack-auth.ts +51 -0
  82. package/src/mcp/manager.ts +94 -7
  83. package/src/mcp/tools.ts +7 -4
  84. package/src/permissions/permissions.ts +12 -0
  85. package/src/permissions/resolve.ts +2 -0
  86. package/src/role-claim/match-rule.ts +2 -0
  87. package/src/run/codex-fetch-observer.ts +11 -6
  88. package/src/run/index.ts +74 -29
  89. package/src/secrets/discord-store.ts +96 -0
  90. package/src/secrets/oauth-xai.ts +2 -2
  91. package/src/secrets/schema.ts +34 -0
  92. package/src/secrets/slack-store.ts +96 -0
  93. package/src/server/command-runner.ts +21 -0
  94. package/src/server/index.ts +27 -2
  95. package/src/skills/typeclaw-channels/SKILL.md +1 -1
  96. package/src/skills/typeclaw-config/SKILL.md +1 -0
  97. package/src/skills/typeclaw-cron/SKILL.md +20 -4
  98. package/src/skills/typeclaw-permissions/SKILL.md +18 -6
  99. package/src/tui/format.ts +0 -19
  100. package/src/tui/index.ts +2 -8
  101. package/src/update/check.ts +192 -0
  102. package/typeclaw.schema.json +332 -0
@@ -0,0 +1,54 @@
1
+ import type { SlackClient, SlackUser } from 'agent-messenger/slack'
2
+
3
+ const DEFAULT_TTL_MS = 60 * 60 * 1000
4
+
5
+ export type SlackAuthorResolverOptions = {
6
+ client: Pick<SlackClient, 'getUser'>
7
+ now?: () => number
8
+ ttlMs?: number
9
+ }
10
+
11
+ export type SlackAuthorResolver = {
12
+ resolve: (userId: string) => Promise<string>
13
+ }
14
+
15
+ type CacheEntry = { name: string; expiresAt: number }
16
+
17
+ export function createSlackAuthorResolver(options: SlackAuthorResolverOptions): SlackAuthorResolver {
18
+ const now = options.now ?? Date.now
19
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
20
+ const cache = new Map<string, CacheEntry>()
21
+ const inflight = new Map<string, Promise<string>>()
22
+
23
+ const resolve = async (userId: string): Promise<string> => {
24
+ const cached = cache.get(userId)
25
+ if (cached && cached.expiresAt > now()) return cached.name
26
+ const existing = inflight.get(userId)
27
+ if (existing) return existing
28
+ const promise = options.client
29
+ .getUser(userId)
30
+ .then((user) => pickDisplayName(user) ?? userId)
31
+ .catch(() => userId)
32
+ .then((name) => {
33
+ if (name !== userId) cache.set(userId, { name, expiresAt: now() + ttlMs })
34
+ return name
35
+ })
36
+ .finally(() => {
37
+ inflight.delete(userId)
38
+ })
39
+ inflight.set(userId, promise)
40
+ return promise
41
+ }
42
+
43
+ return { resolve }
44
+ }
45
+
46
+ // Identity fields only. `profile.status_text` is presence text ("In a meeting"),
47
+ // not a name, so it must never stand in for the author's display name.
48
+ function pickDisplayName(user: SlackUser): string | null {
49
+ const candidates = [user.real_name, user.name]
50
+ for (const c of candidates) {
51
+ if (typeof c === 'string' && c !== '') return c
52
+ }
53
+ return null
54
+ }
@@ -845,12 +845,14 @@ export function createOutboundCallback(deps: {
845
845
  const chunks = chunkMarkdown(text, SLACK_MARKDOWN_BLOCK_LIMIT)
846
846
  const explicitThread = msg.thread !== undefined && msg.thread !== null ? msg.thread : null
847
847
  let threadTs: string | null = explicitThread
848
+ const sentTs: string[] = []
848
849
  try {
849
850
  for (let i = 0; i < chunks.length; i++) {
850
851
  const chunk = chunks[i]!
851
852
  const options: { thread_ts?: string; blocks?: unknown[] } = { blocks: [buildMarkdownBlock(chunk)] }
852
853
  if (threadTs !== null) options.thread_ts = threadTs
853
854
  const sent = await client.postMessage(msg.chat, chunk, options)
855
+ sentTs.push(sent.ts)
854
856
  logger.info(
855
857
  `[slack-bot] sent ts=${sent.ts} ${tag} chunk=${i + 1}/${chunks.length} blocks=markdown len=${chunk.length}`,
856
858
  )
@@ -860,7 +862,7 @@ export function createOutboundCallback(deps: {
860
862
  if (threadTs === null && chunks.length > 1) threadTs = sent.ts
861
863
  }
862
864
  if (typingTracker) await typingTracker.clearAfterSend(msg.chat, msg.typingThread ?? msg.thread)
863
- return { ok: true }
865
+ return { ok: true, messageId: sentTs[0], messageIds: sentTs }
864
866
  } catch (err) {
865
867
  const message = err instanceof Error ? err.message : String(err)
866
868
  logger.error(`[slack-bot] postMessage failed: ${message}`)
@@ -0,0 +1,49 @@
1
+ import type { SlackClient } from 'agent-messenger/slack'
2
+
3
+ import type { ChannelKey, ChannelNameResolver, ResolvedChannelNames } from '@/channels/types'
4
+
5
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000
6
+
7
+ export type SlackChannelResolverOptions = {
8
+ client: Pick<SlackClient, 'getChannel'>
9
+ teamNameRef?: () => string | null
10
+ now?: () => number
11
+ ttlMs?: number
12
+ }
13
+
14
+ type CacheEntry<T> = { value: T; expiresAt: number }
15
+
16
+ export function createSlackChannelResolver(options: SlackChannelResolverOptions): ChannelNameResolver {
17
+ const now = options.now ?? Date.now
18
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
19
+ const chatCache = new Map<string, CacheEntry<string>>()
20
+
21
+ const fetchCached = async <T>(
22
+ cache: Map<string, CacheEntry<T>>,
23
+ key: string,
24
+ fetcher: () => Promise<T | null>,
25
+ ): Promise<T | null> => {
26
+ const cached = cache.get(key)
27
+ if (cached && cached.expiresAt > now()) return cached.value
28
+ const value = await fetcher()
29
+ if (value !== null) cache.set(key, { value, expiresAt: now() + ttlMs })
30
+ return value
31
+ }
32
+
33
+ return async (key: ChannelKey): Promise<ResolvedChannelNames> => {
34
+ if (key.workspace === '@dm') return {}
35
+ const chatName = await fetchCached(chatCache, key.chat, async () => {
36
+ try {
37
+ const channel = await options.client.getChannel(key.chat)
38
+ return channel.name || null
39
+ } catch {
40
+ return null
41
+ }
42
+ })
43
+ const workspaceName = options.teamNameRef?.() ?? null
44
+ const result: ResolvedChannelNames = {}
45
+ if (chatName !== null) result.chatName = chatName
46
+ if (workspaceName !== null) result.workspaceName = workspaceName
47
+ return result
48
+ }
49
+ }
@@ -0,0 +1,83 @@
1
+ import type { SlackRTMMessageEvent } from 'agent-messenger/slack'
2
+
3
+ import { matchesAnyAlias } from '@/channels/engagement'
4
+ import type { ChannelAdapterConfig } from '@/channels/schema'
5
+ import type { InboundMessage } from '@/channels/types'
6
+
7
+ import { slackTsToMillis } from './slack-bot-time'
8
+ import { encodeSlackReactionRef } from './slack-reactions'
9
+
10
+ export type SlackInboundMessageEvent = SlackRTMMessageEvent
11
+
12
+ export type InboundDropReason = 'self_author' | 'no_user' | 'slack_system_message' | 'empty_text' | 'pre_connect'
13
+
14
+ export type InboundClassification =
15
+ | { kind: 'drop'; reason: InboundDropReason }
16
+ | { kind: 'route'; payload: InboundMessage }
17
+
18
+ export type SlackInboundContext = {
19
+ teamId: string
20
+ selfUserId: string | null
21
+ selfAliases?: readonly string[]
22
+ }
23
+
24
+ export function classifyInbound(
25
+ event: SlackInboundMessageEvent,
26
+ _config: ChannelAdapterConfig,
27
+ context: SlackInboundContext,
28
+ ): InboundClassification {
29
+ if (context.selfUserId !== null && event.user === context.selfUserId) return { kind: 'drop', reason: 'self_author' }
30
+ if (event.user === undefined || event.user === '') return { kind: 'drop', reason: 'no_user' }
31
+ if (!isRouteableSlackMessageSubtype(event.subtype)) return { kind: 'drop', reason: 'slack_system_message' }
32
+ if ((event.text ?? '') === '') return { kind: 'drop', reason: 'empty_text' }
33
+ if (context.selfUserId === null) return { kind: 'drop', reason: 'pre_connect' }
34
+
35
+ const rawText = event.text ?? ''
36
+ const isDm = event.channel.startsWith('D')
37
+ const workspace = isDm ? '@dm' : context.teamId
38
+ const hasGroupMention = GROUP_MENTION_PATTERN.test(rawText)
39
+ const isBotMention = hasGroupMention || rawText.includes(`<@${context.selfUserId}>`)
40
+ const aliasMatched = !isBotMention && matchesAnyAlias(rawText, context.selfAliases ?? [])
41
+ const thread = event.thread_ts ?? (!isDm && (isBotMention || aliasMatched) ? event.ts : null)
42
+ const mentionedUserIds = extractMentionedUserIds(rawText)
43
+ const mentionsOthers = mentionedUserIds.length > 0 && !mentionedUserIds.includes(context.selfUserId)
44
+
45
+ return {
46
+ kind: 'route',
47
+ payload: {
48
+ adapter: 'slack',
49
+ workspace,
50
+ chat: event.channel,
51
+ thread,
52
+ text: rawText,
53
+ externalMessageId: event.ts,
54
+ reactionRef: encodeSlackReactionRef({ channel: event.channel, ts: event.ts }),
55
+ authorId: event.user,
56
+ authorName: event.user,
57
+ authorIsBot: false,
58
+ isBotMention,
59
+ // RTM user-session replies do not include parent_user_id; a pure classifier
60
+ // cannot prove parent authorship without an async Slack lookup.
61
+ replyToBotMessageId: null,
62
+ mentionsOthers,
63
+ replyToOtherMessageId: null,
64
+ isDm,
65
+ ts: slackTsToMillis(event.ts),
66
+ },
67
+ }
68
+ }
69
+
70
+ export function isRouteableSlackMessageSubtype(subtype: string | undefined): boolean {
71
+ return subtype === undefined || subtype === 'me_message'
72
+ }
73
+
74
+ const MENTION_PATTERN = /<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g
75
+ const GROUP_MENTION_PATTERN = /<!(?:here|channel|everyone)(?:\|[^>]*)?>/
76
+
77
+ function extractMentionedUserIds(text: string): string[] {
78
+ const seen = new Set<string>()
79
+ for (const match of text.matchAll(MENTION_PATTERN)) {
80
+ seen.add(match[1]!)
81
+ }
82
+ return Array.from(seen)
83
+ }
@@ -0,0 +1,126 @@
1
+ import type { SlackClient } from 'agent-messenger/slack'
2
+
3
+ import type {
4
+ ReactionCallback,
5
+ ReactionErrorCode,
6
+ ReactionRef,
7
+ ReactionResult,
8
+ RemoveReactionCallback,
9
+ } from '@/channels/types'
10
+
11
+ export type SlackReactionTarget = { channel: string; ts: string }
12
+ export type SlackReactionRemovalTarget = { channel: string; ts: string; emoji: string }
13
+
14
+ export function encodeSlackReactionRef(target: SlackReactionTarget): ReactionRef {
15
+ return { adapter: 'slack', value: JSON.stringify(target) }
16
+ }
17
+
18
+ export function decodeSlackReactionRef(ref: ReactionRef): SlackReactionTarget | null {
19
+ if (ref.adapter !== 'slack') return null
20
+ const parsed = parseRecord(ref.value)
21
+ if (parsed === null || parsed.op !== undefined) return null
22
+ const channel = typeof parsed.channel === 'string' ? parsed.channel : null
23
+ const ts = typeof parsed.ts === 'string' ? parsed.ts : null
24
+ if (channel === null || ts === null) return null
25
+ return { channel, ts }
26
+ }
27
+
28
+ export function encodeSlackRemovalRef(target: SlackReactionRemovalTarget): ReactionRef {
29
+ return { adapter: 'slack', value: JSON.stringify({ op: 'remove', ...target }) }
30
+ }
31
+
32
+ export function decodeSlackRemovalRef(ref: ReactionRef): SlackReactionRemovalTarget | null {
33
+ if (ref.adapter !== 'slack') return null
34
+ const parsed = parseRecord(ref.value)
35
+ if (parsed === null || parsed.op !== 'remove') return null
36
+ const channel = typeof parsed.channel === 'string' ? parsed.channel : null
37
+ const ts = typeof parsed.ts === 'string' ? parsed.ts : null
38
+ const emoji = typeof parsed.emoji === 'string' ? parsed.emoji : null
39
+ if (channel === null || ts === null || emoji === null) return null
40
+ return { channel, ts, emoji }
41
+ }
42
+
43
+ export function createSlackReactionCallback(deps: { client: Pick<SlackClient, 'addReaction'> }): ReactionCallback {
44
+ return async (req): Promise<ReactionResult> => {
45
+ if (req.adapter !== 'slack') return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'unsupported' }
46
+ const target = decodeSlackReactionRef(req.reactionRef)
47
+ if (target === null) return { ok: false, error: 'unparseable slack reaction ref', code: 'unsupported' }
48
+ const emoji = normalizeEmoji(req.emoji)
49
+ try {
50
+ await deps.client.addReaction(target.channel, target.ts, emoji)
51
+ } catch (err) {
52
+ const code = slackErrorCode(err)
53
+ if (code === 'already_reacted') return { ok: true, reactionRef: encodeSlackRemovalRef({ ...target, emoji }) }
54
+ return { ok: false, error: describe(err), code: classifySlackError(code) }
55
+ }
56
+ return { ok: true, reactionRef: encodeSlackRemovalRef({ ...target, emoji }) }
57
+ }
58
+ }
59
+
60
+ export function createSlackRemoveReactionCallback(deps: {
61
+ client: Pick<SlackClient, 'removeReaction'>
62
+ }): RemoveReactionCallback {
63
+ return async (req): Promise<ReactionResult> => {
64
+ if (req.adapter !== 'slack') return { ok: false, error: `unknown adapter: ${req.adapter}`, code: 'unsupported' }
65
+ const target = decodeSlackRemovalRef(req.reactionRef)
66
+ if (target === null) return { ok: false, error: 'unparseable slack reaction removal ref', code: 'unsupported' }
67
+ try {
68
+ await deps.client.removeReaction(target.channel, target.ts, target.emoji)
69
+ } catch (err) {
70
+ const code = slackErrorCode(err)
71
+ if (code === 'no_reaction') return { ok: true }
72
+ return { ok: false, error: describe(err), code: classifySlackError(code) }
73
+ }
74
+ return { ok: true }
75
+ }
76
+ }
77
+
78
+ function normalizeEmoji(emoji: string): string {
79
+ return emoji.replace(/^:|:$/g, '')
80
+ }
81
+
82
+ function slackErrorCode(err: unknown): string | null {
83
+ if (typeof err === 'object' && err !== null && 'code' in err) {
84
+ const code = (err as { code: unknown }).code
85
+ if (typeof code === 'string') return code
86
+ }
87
+ return null
88
+ }
89
+
90
+ function classifySlackError(code: string | null): ReactionErrorCode {
91
+ switch (code) {
92
+ case 'invalid_name':
93
+ case 'no_item_specified':
94
+ return 'unsupported'
95
+ case 'missing_scope':
96
+ case 'not_in_channel':
97
+ case 'is_archived':
98
+ case 'not_authed':
99
+ case 'invalid_auth':
100
+ return 'permission-denied'
101
+ case 'message_not_found':
102
+ case 'channel_not_found':
103
+ return 'not-found'
104
+ case 'ratelimited':
105
+ case 'rate_limited':
106
+ return 'rate-limited'
107
+ default:
108
+ return 'transient'
109
+ }
110
+ }
111
+
112
+ function parseRecord(value: string): Record<string, unknown> | null {
113
+ let parsed: unknown
114
+ try {
115
+ parsed = JSON.parse(value)
116
+ } catch {
117
+ return null
118
+ }
119
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
120
+ ? (parsed as Record<string, unknown>)
121
+ : null
122
+ }
123
+
124
+ function describe(err: unknown): string {
125
+ return err instanceof Error ? err.message : String(err)
126
+ }