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
@@ -29,12 +29,15 @@ import type {
29
29
  OutboundMessage,
30
30
  ResolvedChannelNames,
31
31
  SendResult,
32
+ TypingCallback,
33
+ TypingTarget,
32
34
  } from '@/channels/types'
33
35
  import type { WebexAccountRecord } from '@/secrets/schema'
34
36
 
35
37
  import { createWebexChannelNameResolver } from './webex-channel-resolver'
36
38
  import { classifyInbound, type InboundDropReason, type WebexInboundMessage } from './webex-classify'
37
39
  import { resolveWebexBodyText } from './webex-format'
40
+ import { createWebexPrefetchLimiter, isWebexRateLimitError, type WebexPrefetchLimiter } from './webex-prefetch-limiter'
38
41
  import { enrichWebexMessageReference } from './webex-reference'
39
42
 
40
43
  export type WebexAdapterLogger = {
@@ -112,6 +115,7 @@ export function createOutboundCallback(deps: {
112
115
 
113
116
  try {
114
117
  if (attachments.length > 0) {
118
+ const uploadedRefs: string[] = []
115
119
  for (const [index, attachment] of attachments.entries()) {
116
120
  const path = resolvePath ? resolvePath(attachment.path) : attachment.path
117
121
  const file = await readFile(path)
@@ -121,14 +125,16 @@ export function createOutboundCallback(deps: {
121
125
  ...(carriesText ? { text } : {}),
122
126
  ...(parentId !== undefined ? { parentId } : {}),
123
127
  })
128
+ uploadedRefs.push(sent.ref)
124
129
  logger.info(`[webex] uploaded id=${sent.ref} filename=${file.filename} ${tag}`)
125
130
  }
126
- return { ok: true }
131
+ // First upload carries the text and is the thread parent, so it is the reply anchor.
132
+ return { ok: true, messageId: uploadedRefs[0], messageIds: uploadedRefs }
127
133
  }
128
134
 
129
135
  const sent = await client.sendMessage(msg.chat, text, parentId !== undefined ? { parentId } : undefined)
130
136
  logger.info(`[webex] sent id=${sent.ref} ${tag}`)
131
- return { ok: true }
137
+ return { ok: true, messageId: sent.ref, messageIds: [sent.ref] }
132
138
  } catch (err) {
133
139
  const message = describe(err)
134
140
  logger.error(`[webex] outbound failed: ${message}`)
@@ -141,32 +147,81 @@ async function defaultReadFile(path: string): Promise<WebexOutboundFile> {
141
147
  return { content: Bun.file(path), filename: path.split('/').pop() ?? 'attachment' }
142
148
  }
143
149
 
144
- // The Webex REST/internal client offers no AbortSignal, so a hung `listMessages`
145
- // would otherwise block cold-start prefetch for the router's full 5s history
146
- // ceiling before degrading. Racing it against a tighter internal deadline lets
147
- // prefetch fall back to membership-derivation (or skip) seconds sooner, mirroring
148
- // the cold-fetch fail-fast posture the membership resolver already uses.
149
- const WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS = 2500
150
+ // Webex's typing indicator does not auto-expire, so unlike Telegram both phases
151
+ // are load-bearing: 'tick' raises it (re-fired on each router heartbeat) and
152
+ // 'stop' explicitly clears it once the turn ends.
153
+ //
154
+ // The router fires ticks fire-and-forget (`void fireTyping(live, 'tick')`) and
155
+ // relies on adapters with explicit clears to order 'stop' after any in-flight
156
+ // 'tick' — see router.ts stopTypingHeartbeat ("The FIFO inside the slack adapter
157
+ // ensures this clear lands AFTER any in-flight 'tick'"). Without serialization a
158
+ // slow `setTyping(room, true)` could resolve AFTER the `setTyping(room, false)`
159
+ // clear and strand the persistent indicator on. So calls are chained through a
160
+ // per-room FIFO (mirroring createSlackTypingTracker) BEFORE awaiting any slow
161
+ // work, guaranteeing on-the-wire order matches enqueue order.
162
+ //
163
+ // A swallowed error never surfaces to the router — a dropped indicator is
164
+ // cosmetic and must not abort a send or teardown.
165
+ export function createTypingCallback(deps: {
166
+ client: Pick<WebexClient, 'setTyping'>
167
+ logger: WebexAdapterLogger
168
+ formatChannelTag?: (chat: string) => Promise<string>
169
+ }): TypingCallback {
170
+ const { client, logger, formatChannelTag } = deps
171
+ const queues = new Map<string, Promise<void>>()
172
+ return async (target: TypingTarget): Promise<void> => {
173
+ if (target.adapter !== 'webex') return
174
+ const typing = target.phase === 'tick'
175
+ const prev = queues.get(target.chat) ?? Promise.resolve()
176
+ const next = prev
177
+ .catch(() => {})
178
+ .then(() => client.setTyping(target.chat, typing))
179
+ .catch(async (err: unknown) => {
180
+ const tag = formatChannelTag ? await formatChannelTag(target.chat) : `room=${target.chat}`
181
+ logger.warn(`[webex] typing ${tag} phase=${target.phase} failed: ${describe(err)}`)
182
+ })
183
+ queues.set(target.chat, next)
184
+ void next.finally(() => {
185
+ if (queues.get(target.chat) === next) queues.delete(target.chat)
186
+ })
187
+ await next
188
+ }
189
+ }
150
190
 
151
191
  export function createWebexHistoryCallback(deps: {
152
192
  client: Pick<WebexClient, 'listMessages'>
153
193
  logger: WebexAdapterLogger
154
194
  botPersonIdRef: () => string | null
155
- timeoutMs?: number
195
+ limiter?: WebexPrefetchLimiter
156
196
  }): HistoryCallback {
157
- const timeoutMs = deps.timeoutMs ?? WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS
197
+ const limiter = deps.limiter ?? createWebexPrefetchLimiter()
198
+ const listMessages = (args: FetchHistoryArgs) =>
199
+ deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) })
200
+ const toHistory = (messages: WebexMessage[]): FetchHistoryResult => {
201
+ const authorById = new Map(messages.map((m) => [m.ref, m.personRef]))
202
+ const botPersonId = deps.botPersonIdRef()
203
+ return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, botPersonId, authorById)).reverse() }
204
+ }
158
205
  return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
159
206
  try {
160
- const messages = await raceWithTimeout(
161
- deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) }),
162
- timeoutMs,
163
- '[webex] history fetch',
164
- )
165
- const authorById = new Map(messages.map((m) => [m.ref, m.personRef]))
166
- const botPersonId = deps.botPersonIdRef()
167
- return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, botPersonId, authorById)).reverse() }
207
+ // Only best-effort reads (cold-start prefetch, membership fallback) submit
208
+ // to the per-room limiter. Explicit channel_history reads bypass it so a
209
+ // user-initiated look-back is never declined by prefetch backpressure.
210
+ if (args.prefetch !== true) {
211
+ return toHistory(await listMessages(args))
212
+ }
213
+ const outcome = await limiter.run(args.chat, () => listMessages(args))
214
+ if (!outcome.admitted) {
215
+ deps.logger.info('[webex] history prefetch skipped: rate-limit backpressure')
216
+ return { ok: false, error: 'prefetch skipped: rate-limit backpressure', skipReason: 'rate-limited' }
217
+ }
218
+ return toHistory(outcome.value)
168
219
  } catch (err) {
169
220
  const message = describe(err)
221
+ if (args.prefetch === true && isWebexRateLimitError(err)) {
222
+ deps.logger.info(`[webex] history prefetch skipped: rate limited (${message})`)
223
+ return { ok: false, error: message, skipReason: 'rate-limited' }
224
+ }
170
225
  deps.logger.warn(`[webex] history fetch failed: ${message}`)
171
226
  return { ok: false, error: message }
172
227
  }
@@ -211,7 +266,7 @@ export function createWebexMembershipResolver(deps: {
211
266
  } catch (err) {
212
267
  deps.logger.warn(`[webex] membership room=${key.chat} failed: ${describe(err)}; deriving from recent history`)
213
268
  return await deriveMembershipFromHistory({
214
- fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit }),
269
+ fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit, prefetch: true }),
215
270
  now,
216
271
  })
217
272
  }
@@ -305,6 +360,7 @@ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
305
360
  botPersonIdRef: () => botPerson?.ref ?? null,
306
361
  })
307
362
  const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
363
+ const typingCallback = createTypingCallback({ client, logger, formatChannelTag })
308
364
  const fetchAttachmentCallback = createFetchAttachmentCallback({ tokenRef: () => currentToken, logger, fetchImpl })
309
365
 
310
366
  const handleMessage = async (event: WebexInboundMessage): Promise<void> => {
@@ -391,6 +447,8 @@ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
391
447
  })
392
448
 
393
449
  options.router.registerOutbound('webex', outboundCallback)
450
+ options.router.registerTyping('webex', typingCallback)
451
+ options.router.setTypingCapability('webex', true)
394
452
  options.router.registerChannelNameResolver('webex', channelResolver)
395
453
  options.router.registerSelfIdentity('webex', selfIdentityResolver)
396
454
  options.router.registerHistory('webex', historyCallback)
@@ -399,6 +457,8 @@ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
399
457
 
400
458
  const rollbackStart = (reason: string, cause: Error): never => {
401
459
  options.router.unregisterOutbound('webex', outboundCallback)
460
+ options.router.unregisterTyping('webex', typingCallback)
461
+ options.router.setTypingCapability('webex', false)
402
462
  options.router.unregisterChannelNameResolver('webex', channelResolver)
403
463
  options.router.unregisterSelfIdentity('webex', selfIdentityResolver)
404
464
  options.router.unregisterHistory('webex', historyCallback)
@@ -431,6 +491,8 @@ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
431
491
  if (!started) return
432
492
  started = false
433
493
  options.router.unregisterOutbound('webex', outboundCallback)
494
+ options.router.unregisterTyping('webex', typingCallback)
495
+ options.router.setTypingCapability('webex', false)
434
496
  options.router.unregisterChannelNameResolver('webex', channelResolver)
435
497
  options.router.unregisterSelfIdentity('webex', selfIdentityResolver)
436
498
  options.router.unregisterHistory('webex', historyCallback)
@@ -496,18 +558,6 @@ function describe(err: unknown): string {
496
558
  return err instanceof Error ? err.message : String(err)
497
559
  }
498
560
 
499
- async function raceWithTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {
500
- let timer: ReturnType<typeof setTimeout> | null = null
501
- const timeout = new Promise<never>((_, reject) => {
502
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
503
- })
504
- try {
505
- return await Promise.race([work, timeout])
506
- } finally {
507
- if (timer !== null) clearTimeout(timer)
508
- }
509
- }
510
-
511
561
  function dropHint(reason: InboundDropReason): string {
512
562
  switch (reason) {
513
563
  case 'empty_content':
@@ -8,12 +8,35 @@
8
8
 
9
9
  export type ReviewVerdict = 'APPROVE' | 'REQUEST_CHANGES'
10
10
 
11
+ export type ReviewObserver = (args: {
12
+ sessionId: string
13
+ workspace: string
14
+ prNumber: number
15
+ verdict: ReviewVerdict
16
+ }) => void
17
+
11
18
  type PrKey = string
12
19
  type ThreadKey = string
13
20
 
14
21
  const reviewsByPr = new Map<PrKey, Set<ReviewVerdict>>()
15
22
  const resolvedThreads = new Set<ThreadKey>()
16
23
 
24
+ // A single process-wide observer notified AFTER a verdict is recorded, so the
25
+ // run-side wiring can fan a landed verdict out over the broadcast bus to sibling
26
+ // PR sessions (see github-verdict-activity.ts) WITHOUT giving the github-cli-auth
27
+ // plugin stream access. Registered once at boot from run/index.ts. The ledger
28
+ // stays the single seam where "a formal verdict happened" is known across the
29
+ // plugin/channels boundary, which is why it owns this hook.
30
+ let reviewObserver: ReviewObserver | null = null
31
+
32
+ export function setReviewObserver(observer: ReviewObserver | null): void {
33
+ reviewObserver = observer
34
+ }
35
+
36
+ export function __resetReviewObserverForTest(): void {
37
+ reviewObserver = null
38
+ }
39
+
17
40
  function prKey(sessionId: string, workspace: string, prNumber: number): PrKey {
18
41
  return `${sessionId}::${workspace}::${prNumber}`
19
42
  }
@@ -41,6 +64,15 @@ export function recordReview(args: {
41
64
  const set = reviewsByPr.get(key) ?? new Set<ReviewVerdict>()
42
65
  set.add(args.verdict)
43
66
  reviewsByPr.set(key, set)
67
+ // Notify AFTER the record lands and never let an observer failure corrupt the
68
+ // ledger write — the false-receipt guard depends on this record being durable.
69
+ if (reviewObserver !== null) {
70
+ try {
71
+ reviewObserver(args)
72
+ } catch {
73
+ // swallow: a broken broadcast must not break verdict bookkeeping
74
+ }
75
+ }
44
76
  }
45
77
 
46
78
  export function hasReview(args: {
@@ -0,0 +1,60 @@
1
+ import type { ReviewVerdict } from './github-review-turn-ledger'
2
+
3
+ // A formal review verdict (APPROVE / REQUEST_CHANGES) that LANDED on a PR, fanned
4
+ // out over the broadcast bus so the OTHER live sessions reviewing the same PR
5
+ // stand down from posting their own redundant verdict. The duplicate-review
6
+ // incident was driven by per-thread session fan-out: N sessions for one PR each
7
+ // independently submitted a verdict, blind to the others. The hard idempotency
8
+ // lease + cooldown catch overlapping/near-simultaneous submits; this advisory
9
+ // signal covers the SEQUENTIAL case — a sibling that wakes after another already
10
+ // landed the verdict and would otherwise re-derive and re-submit it.
11
+ //
12
+ // Routing is by { workspace, prNumber } only (the PR is the unit), with sessionId
13
+ // carried so the publisher excludes itself. No channel key — the publish seam is
14
+ // the turn-ledger's recordReview(), which has no channel coordinate, and Oracle's
15
+ // review favored not expanding plugin coupling just to mirror subagent.completed.
16
+
17
+ export type PrVerdictActivityPayload = {
18
+ workspace: string
19
+ prNumber: number
20
+ verdict: ReviewVerdict
21
+ sessionId: string
22
+ }
23
+
24
+ export function parsePrVerdictActivityPayload(payload: unknown): PrVerdictActivityPayload | null {
25
+ if (payload === null || typeof payload !== 'object') return null
26
+ const p = payload as {
27
+ kind?: unknown
28
+ workspace?: unknown
29
+ prNumber?: unknown
30
+ verdict?: unknown
31
+ sessionId?: unknown
32
+ }
33
+ if (p.kind !== 'pr.verdict-activity') return null
34
+ if (typeof p.workspace !== 'string' || p.workspace === '') return null
35
+ if (typeof p.prNumber !== 'number' || !Number.isInteger(p.prNumber)) return null
36
+ if (typeof p.sessionId !== 'string' || p.sessionId === '') return null
37
+ const verdict = parseVerdict(p.verdict)
38
+ if (verdict === null) return null
39
+ return { workspace: p.workspace, prNumber: p.prNumber, verdict, sessionId: p.sessionId }
40
+ }
41
+
42
+ function parseVerdict(value: unknown): ReviewVerdict | null {
43
+ return value === 'APPROVE' || value === 'REQUEST_CHANGES' ? value : null
44
+ }
45
+
46
+ // Advisory and deliberately soft (per the design review): it must not suppress a
47
+ // genuine flipped verdict or a re-review after new commits/evidence, so it forbids
48
+ // only a REDUNDANT same-intent verdict and explicitly preserves inline-thread
49
+ // replies. The hard guards remain the correctness boundary; this only trims wasted
50
+ // sibling work before they fire.
51
+ export function renderPrVerdictStandDownReminder(args: { prNumber: number; verdict: ReviewVerdict }): string {
52
+ return (
53
+ `<system-reminder>\n` +
54
+ `Another session in this agent has already posted a formal ${args.verdict} review for PR #${args.prNumber}. ` +
55
+ `Do not submit your own ${args.verdict} (or any redundant verdict) for this PR this turn unless new ` +
56
+ `information genuinely invalidates that result (e.g. new commits, or a different verdict warranted by ` +
57
+ `fresh evidence). You may still reply to inline review comments / threads as normal.\n` +
58
+ `</system-reminder>`
59
+ )
60
+ }
@@ -15,6 +15,12 @@ export {
15
15
  type CreateSessionForChannel,
16
16
  } from './router'
17
17
  export { createChannelsReloadable } from './reloadable'
18
+ export {
19
+ createPrVerdictActivityBridge,
20
+ type PrVerdictActivityBridge,
21
+ type PrVerdictActivityBridgeOptions,
22
+ } from './pr-verdict-activity-bridge'
23
+ export { setReviewObserver } from './github-review-turn-ledger'
18
24
  export {
19
25
  createSubagentCompletionBridge,
20
26
  type SubagentCompletionBridge,