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
@@ -1,13 +1,16 @@
1
1
  import type { ToolDefinition } from '@mariozechner/pi-coding-agent'
2
2
  import type { z } from 'zod'
3
3
 
4
+ import { getConfig, resolveModel } from '@/config'
4
5
  import type { PermissionService } from '@/permissions'
5
6
  import type { HookBus } from '@/plugin'
6
7
  import type { Stream, Unsubscribe } from '@/stream'
7
8
 
8
9
  import { applyTurnThinkingLevel } from './attention-escalation'
9
10
  import { type AgentSession, createSession, type PluginSessionWiring } from './index'
10
- import { subscribeProviderErrors } from './provider-error'
11
+ import { resolveFallbackChain } from './model-fallback'
12
+ import { applyModelRuntimeOverrides } from './model-overrides'
13
+ import { isThrottleOrOverload, subscribeProviderErrors } from './provider-error'
11
14
  import type { SubagentBashPolicy } from './reviewer-bash-policy'
12
15
  import type { SessionOrigin } from './session-origin'
13
16
  import {
@@ -18,6 +21,7 @@ import {
18
21
  } from './subagent-drain'
19
22
  import { renderTurnTimeAnchor } from './system-prompt'
20
23
  import type { ToolResultBudget } from './tool-result-budget'
24
+ import { promptPersistentTurnWithFallback } from './turn-runner'
21
25
 
22
26
  type AgentSessionTools = NonNullable<Parameters<typeof createSession>[0]>['tools']
23
27
 
@@ -294,6 +298,7 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
294
298
  const { session, dispose, hooks, sessionId, agentDir, origin, getTranscriptPath, backgroundDrain } =
295
299
  normalizeSubagentSession(await createSessionForSubagent(subagent, sessionOptions))
296
300
  let aborted = false
301
+ let activeModelRef = resolveFallbackChain(getConfig().models, resolveSubagentProfile(subagent, sessionOptions))[0]!
297
302
  let drainWatch: SubagentDrainWatch | undefined
298
303
  const requiredBlockTag = REQUIRED_FINAL_BLOCK[name]
299
304
  const capture = attachFinalMessageCapture(session, requiredBlockTag, options.onFinalMessageCaptured ?? (() => {}))
@@ -334,7 +339,29 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
334
339
  ? `${renderTurnTimeAnchor()}\n\n${userPromptForTurn}\n\n${retrievalContext.results}`
335
340
  : `${renderTurnTimeAnchor()}\n\n${userPromptForTurn}`
336
341
  applyTurnThinkingLevel(session, userPromptForTurn, session.thinkingLevel)
337
- await session.prompt(turnText)
342
+ const result = await promptPersistentTurnWithFallback({
343
+ refs: resolveFallbackChain(getConfig().models, resolveSubagentProfile(subagent, sessionOptions)),
344
+ currentModelRef: activeModelRef,
345
+ profile: resolveSubagentProfile(subagent, sessionOptions),
346
+ session,
347
+ text: turnText,
348
+ skipProviderErrorSubscription: true,
349
+ detectSoftErrorFromLeaf: true,
350
+ shouldFailover: (err) => isThrottleOrOverload(err.message),
351
+ setModelForRef: async (ref) => {
352
+ await session.setModel(applyModelRuntimeOverrides(resolveModel(ref), ref))
353
+ activeModelRef = ref
354
+ },
355
+ beforeAttempt: () => {
356
+ applyTurnThinkingLevel(session, userPromptForTurn, session.thinkingLevel)
357
+ },
358
+ onAttemptFailed: (attempt) => {
359
+ console.warn(
360
+ `[subagent] ${name} ${attempt.outcome} failure on ${attempt.ref}: ${attempt.errorMessage ?? 'unknown'}; falling back`,
361
+ )
362
+ },
363
+ })
364
+ if (result.success) activeModelRef = result.refUsed
338
365
  } finally {
339
366
  if (hooks && turnEvent !== undefined) {
340
367
  await hooks.runSessionTurnEnd(turnEvent)
@@ -0,0 +1,50 @@
1
+ import { providerForModelRef, type ModelRef } from '@/config/providers'
2
+
3
+ export const THROTTLE_THRESHOLD = 2
4
+ export const THROTTLE_WINDOW_MS = 60_000
5
+ export const COOLDOWN_MS = 180_000
6
+
7
+ export type ThrottleCircuitKey = {
8
+ profile?: string
9
+ ref: ModelRef
10
+ }
11
+
12
+ type CircuitEntry = {
13
+ failures: number[]
14
+ openUntil: number
15
+ }
16
+
17
+ export class ThrottleCircuit {
18
+ private readonly entries = new Map<string, CircuitEntry>()
19
+ private readonly now: () => number
20
+
21
+ constructor(opts: { now?: () => number } = {}) {
22
+ this.now = opts.now ?? Date.now
23
+ }
24
+
25
+ isOpen(key: ThrottleCircuitKey): boolean {
26
+ const entry = this.entries.get(this.keyId(key))
27
+ if (entry === undefined) return false
28
+ return this.now() < entry.openUntil
29
+ }
30
+
31
+ recordThrottle(key: ThrottleCircuitKey): void {
32
+ const id = this.keyId(key)
33
+ const now = this.now()
34
+ const entry = this.entries.get(id) ?? { failures: [], openUntil: 0 }
35
+ entry.failures = entry.failures.filter((ts) => now - ts <= THROTTLE_WINDOW_MS)
36
+ entry.failures.push(now)
37
+ if (entry.failures.length >= THROTTLE_THRESHOLD) entry.openUntil = now + COOLDOWN_MS
38
+ this.entries.set(id, entry)
39
+ }
40
+
41
+ recordSuccess(key: ThrottleCircuitKey): void {
42
+ this.entries.delete(this.keyId(key))
43
+ }
44
+
45
+ private keyId(key: ThrottleCircuitKey): string {
46
+ return `${key.profile ?? 'default'}:${providerForModelRef(key.ref)}:${key.ref}`
47
+ }
48
+ }
49
+
50
+ export const modelThrottleCircuit = new ThrottleCircuit()
@@ -86,7 +86,27 @@ export async function writeTodos(agentDir: string, scope: TodoScope, todos: Todo
86
86
  await mkdir(dirname(path), { recursive: true })
87
87
  const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`
88
88
  await writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
89
- await rename(tmp, path)
89
+ await renameWithRetry(tmp, path)
90
+ }
91
+
92
+ // Windows workaround: rename() onto an existing destination is not atomic and
93
+ // fails transiently (EPERM/EACCES/EBUSY/EEXIST) when another writer or a virus
94
+ // scanner / file indexer momentarily holds the target open — concurrent
95
+ // writeTodos calls onto the same scope file reliably trip this. The retry keeps
96
+ // last-writer-wins instead of rejecting a writer. POSIX rename never hits this.
97
+ const RENAME_RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'EEXIST'])
98
+
99
+ async function renameWithRetry(from: string, to: string, attempts = 10): Promise<void> {
100
+ for (let attempt = 1; ; attempt++) {
101
+ try {
102
+ await rename(from, to)
103
+ return
104
+ } catch (err) {
105
+ const code = typeof err === 'object' && err !== null ? (err as { code?: unknown }).code : undefined
106
+ if (attempt >= attempts || typeof code !== 'string' || !RENAME_RETRY_CODES.has(code)) throw err
107
+ await new Promise((resolve) => setTimeout(resolve, attempt * 10))
108
+ }
109
+ }
90
110
  }
91
111
 
92
112
  export function incompleteTodos(todos: readonly Todo[]): Todo[] {
@@ -53,7 +53,11 @@ export function createChannelReplyTool({
53
53
  'Reply in the current conversation. This is your default way to respond to a channel session — ' +
54
54
  'addressing fields (adapter, workspace, chat, thread) are filled in from the session origin, so ' +
55
55
  'you only supply the text. To post somewhere else (different chat, break out of the current ' +
56
- 'thread, etc.), use `channel_send` instead.',
56
+ 'thread, etc.), use `channel_send` instead. ' +
57
+ 'On success the result carries `messageId` (the posted message id) and `messageIds` (every id when ' +
58
+ 'the text was split into multiple posts) when the platform reports them; pass `messageId` as a ' +
59
+ '`channel_send` `thread` to post follow-ups into the same thread. Some adapters do not report an id, ' +
60
+ 'in which case both are absent.',
57
61
  parameters: Type.Object({
58
62
  text: Type.Optional(
59
63
  Type.String({
@@ -216,10 +220,19 @@ export function createChannelReplyTool({
216
220
  // `continue` is read by the router's terminal hook (installChannelReplyTerminalHook),
217
221
  // not by this tool — it suppresses the post-reply abort so a multi-step turn
218
222
  // keeps going. Success-only: a denied reply never ran, so there is no turn to keep.
219
- const details: { ok: boolean; error?: string; continue?: boolean } = result.ok
220
- ? keepTurnAlive
221
- ? { ok: true, continue: true }
222
- : { ok: true }
223
+ const details: {
224
+ ok: boolean
225
+ error?: string
226
+ continue?: boolean
227
+ messageId?: string
228
+ messageIds?: readonly string[]
229
+ } = result.ok
230
+ ? {
231
+ ok: true,
232
+ ...(keepTurnAlive ? { continue: true } : {}),
233
+ ...(result.messageId !== undefined ? { messageId: result.messageId } : {}),
234
+ ...(result.messageIds !== undefined ? { messageIds: result.messageIds } : {}),
235
+ }
223
236
  : { ok: false, error: result.error }
224
237
  // Echo the delivered text back to the model. The adapter classifier
225
238
  // drops self-authored messages on the inbound path (`self_author`),
@@ -52,7 +52,12 @@ export function createChannelSendTool({
52
52
  'For Discord guild channels, workspace is the guild id; for Slack team channels, workspace is ' +
53
53
  'the team id (e.g. "T0ACME"). For DMs on either platform, workspace is the literal "@dm". ' +
54
54
  'On failure (no adapter registered, or the adapter-level send failed), the call returns ' +
55
- '{ ok: false, error }. There is no auto-reply: the only way for an agent to post is via this tool.',
55
+ '{ ok: false, error }. On success it returns { ok: true } and, when the platform reports it, ' +
56
+ '`messageId` (the posted message id, e.g. a Slack thread ts or Discord/Telegram message id) plus ' +
57
+ '`messageIds` (every id in send order when the post was split into multiple messages; `messageId` is ' +
58
+ 'the reply anchor — usually the first message). Pass `messageId` back as `thread` on a later send to ' +
59
+ 'post follow-ups into the same thread. Some adapters do not report an id, in which case both are absent. ' +
60
+ 'There is no auto-reply: the only way for an agent to post is via this tool.',
56
61
  parameters: Type.Object({
57
62
  adapter: Type.Union(
58
63
  ADAPTER_IDS.map((a) => Type.Literal(a)),
@@ -236,7 +241,13 @@ export function createChannelSendTool({
236
241
  ),
237
242
  )
238
243
  }
239
- const details: { ok: boolean; error?: string } = result.ok ? { ok: true } : { ok: false, error: result.error }
244
+ const details: { ok: boolean; error?: string; messageId?: string; messageIds?: readonly string[] } = result.ok
245
+ ? {
246
+ ok: true,
247
+ ...(result.messageId !== undefined ? { messageId: result.messageId } : {}),
248
+ ...(result.messageIds !== undefined ? { messageIds: result.messageIds } : {}),
249
+ }
250
+ : { ok: false, error: result.error }
240
251
  // Success wraps the echoed sent text in the strong SYSTEM MESSAGE fence;
241
252
  // denials keep the lighter prefix. See channel-reply.ts for the full
242
253
  // rationale (PR #481 self-reply loop).
@@ -0,0 +1,162 @@
1
+ import type { ModelRef } from '@/config/providers'
2
+
3
+ import type { AgentSession } from './index'
4
+ import { detectProviderError, subscribeProviderErrors } from './provider-error'
5
+ import { modelThrottleCircuit, type ThrottleCircuit } from './throttle-circuit'
6
+
7
+ export type PersistentTurnAttempt = {
8
+ ref: ModelRef
9
+ outcome: 'hard' | 'soft' | 'success'
10
+ errorMessage?: string
11
+ }
12
+
13
+ export type PersistentTurnResult = {
14
+ success: boolean
15
+ refUsed: ModelRef
16
+ attempts: PersistentTurnAttempt[]
17
+ lastError?: Error
18
+ }
19
+
20
+ type AttemptActivity = {
21
+ producedAssistantOutput: boolean
22
+ startedToolExecution: boolean
23
+ }
24
+
25
+ export async function promptPersistentTurnWithFallback(opts: {
26
+ refs: ModelRef[]
27
+ currentModelRef: ModelRef
28
+ session: AgentSession
29
+ text: string
30
+ shouldFailover: (err: Error) => boolean
31
+ setModelForRef: (ref: ModelRef) => Promise<void>
32
+ profile?: string
33
+ circuit?: ThrottleCircuit
34
+ skipProviderErrorSubscription?: boolean
35
+ detectSoftErrorFromLeaf?: boolean
36
+ beforeAttempt?: (ref: ModelRef) => void
37
+ onAttemptFailed?: (attempt: PersistentTurnAttempt) => void
38
+ }): Promise<PersistentTurnResult> {
39
+ if (opts.refs.length === 0) throw new Error('promptPersistentTurnWithFallback: refs[] must be non-empty')
40
+ const attempts: PersistentTurnAttempt[] = []
41
+ let lastError: Error | undefined
42
+ const circuit = opts.circuit ?? modelThrottleCircuit
43
+ // The model the session currently has loaded; only call setModel when the
44
+ // chosen ref differs from it. Tracked locally so successive setModel calls
45
+ // within a single turn stay coherent.
46
+ let loadedRef = opts.currentModelRef
47
+ // Always start from the head of the chain so a recovered primary is probed
48
+ // again (the circuit breaker, not a sticky start index, decides when to skip
49
+ // a still-throttled ref). Starting at the previous turn's fallback would make
50
+ // a one-time failover permanent and never let the cooldown/half-open path
51
+ // re-test the primary.
52
+ for (let i = 0; i < opts.refs.length; i++) {
53
+ const ref = opts.refs[i]!
54
+ const isLast = i === opts.refs.length - 1
55
+ // Skip a ref whose circuit is open, but never skip the last one — there is
56
+ // nowhere left to fall, so we try it regardless and let the result speak.
57
+ if (!isLast && circuit.isOpen({ profile: opts.profile, ref })) continue
58
+ if (ref !== loadedRef) {
59
+ await opts.setModelForRef(ref)
60
+ loadedRef = ref
61
+ }
62
+ opts.beforeAttempt?.(ref)
63
+ const activity: AttemptActivity = { producedAssistantOutput: false, startedToolExecution: false }
64
+ let softError: Error | undefined
65
+ // Activity tracking ALWAYS runs — the idempotency guard must hold even for
66
+ // subagents. `skipProviderErrorSubscription` only suppresses the soft-error
67
+ // listener (subagents capture their final message off the leaf instead, via
68
+ // detectSoftErrorFromLeaf, so a second listener would race that capture).
69
+ const unsubActivity = subscribeAttemptActivity(opts.session, activity)
70
+ const unsubProvider = opts.skipProviderErrorSubscription
71
+ ? () => {}
72
+ : subscribeProviderErrorsIfAvailable(opts.session, (err) => {
73
+ if (softError === undefined) softError = new Error(err.message)
74
+ })
75
+ try {
76
+ try {
77
+ await opts.session.prompt(opts.text)
78
+ } catch (err) {
79
+ const error = err instanceof Error ? err : new Error(String(err))
80
+ const attempt: PersistentTurnAttempt = { ref, outcome: 'hard', errorMessage: error.message }
81
+ attempts.push(attempt)
82
+ lastError = error
83
+ if (opts.shouldFailover(error)) circuit.recordThrottle({ profile: opts.profile, ref })
84
+ if (isLast || !canAdvance(error, activity, opts.shouldFailover)) throw error
85
+ opts.onAttemptFailed?.(attempt)
86
+ continue
87
+ }
88
+ if (softError !== undefined) {
89
+ const attempt: PersistentTurnAttempt = { ref, outcome: 'soft', errorMessage: softError.message }
90
+ attempts.push(attempt)
91
+ lastError = softError
92
+ if (opts.shouldFailover(softError)) circuit.recordThrottle({ profile: opts.profile, ref })
93
+ if (isLast || !canAdvance(softError, activity, opts.shouldFailover)) {
94
+ return { success: false, refUsed: ref, attempts, lastError }
95
+ }
96
+ opts.onAttemptFailed?.(attempt)
97
+ continue
98
+ }
99
+ const leafSoftError = opts.detectSoftErrorFromLeaf ? detectLeafSoftError(opts.session) : undefined
100
+ if (leafSoftError !== undefined) {
101
+ const attempt: PersistentTurnAttempt = { ref, outcome: 'soft', errorMessage: leafSoftError.message }
102
+ attempts.push(attempt)
103
+ lastError = leafSoftError
104
+ if (opts.shouldFailover(leafSoftError)) circuit.recordThrottle({ profile: opts.profile, ref })
105
+ if (isLast || !canAdvance(leafSoftError, activity, opts.shouldFailover)) {
106
+ return { success: false, refUsed: ref, attempts, lastError }
107
+ }
108
+ opts.onAttemptFailed?.(attempt)
109
+ continue
110
+ }
111
+ attempts.push({ ref, outcome: 'success' })
112
+ circuit.recordSuccess({ profile: opts.profile, ref })
113
+ return { success: true, refUsed: ref, attempts }
114
+ } finally {
115
+ unsubProvider()
116
+ unsubActivity()
117
+ }
118
+ }
119
+ return { success: false, refUsed: opts.refs[opts.refs.length - 1]!, attempts, lastError }
120
+ }
121
+
122
+ function canAdvance(error: Error, activity: AttemptActivity, shouldFailover: (err: Error) => boolean): boolean {
123
+ return shouldFailover(error) && !activity.producedAssistantOutput && !activity.startedToolExecution
124
+ }
125
+
126
+ function subscribeAttemptActivity(session: AgentSession, activity: AttemptActivity): () => void {
127
+ const subscribe = (session as { subscribe?: unknown }).subscribe
128
+ if (typeof subscribe !== 'function') return () => {}
129
+ return session.subscribe((event: unknown) => {
130
+ if (!isRecord(event)) return
131
+ if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
132
+ activity.startedToolExecution = true
133
+ return
134
+ }
135
+ if (event.type !== 'message_update') return
136
+ const assistantMessageEvent = event.assistantMessageEvent
137
+ if (!isRecord(assistantMessageEvent)) return
138
+ if (assistantMessageEvent.type === 'text_delta' && typeof assistantMessageEvent.delta === 'string') {
139
+ if (assistantMessageEvent.delta.length > 0) activity.producedAssistantOutput = true
140
+ }
141
+ })
142
+ }
143
+
144
+ function subscribeProviderErrorsIfAvailable(
145
+ session: AgentSession,
146
+ onError: Parameters<typeof subscribeProviderErrors>[1],
147
+ ): () => void {
148
+ const subscribe = (session as { subscribe?: unknown }).subscribe
149
+ if (typeof subscribe !== 'function') return () => {}
150
+ return subscribeProviderErrors(session, onError)
151
+ }
152
+
153
+ function detectLeafSoftError(session: AgentSession): Error | undefined {
154
+ const leaf = session.sessionManager?.getLeafEntry()
155
+ if (!leaf || leaf.type !== 'message') return undefined
156
+ const detected = detectProviderError(leaf.message)
157
+ return detected === null ? undefined : new Error(detected.message)
158
+ }
159
+
160
+ function isRecord(value: unknown): value is Record<string, unknown> {
161
+ return typeof value === 'object' && value !== null
162
+ }
@@ -79,7 +79,7 @@ export async function loadCompilerModule(cwd: string = process.cwd()): Promise<N
79
79
  }
80
80
 
81
81
  export async function renderPdf(mainFile: string, outFile: string): Promise<number> {
82
- const { existsSync, writeFileSync } = await import('node:fs')
82
+ const { existsSync } = await import('node:fs')
83
83
 
84
84
  const fontPaths = FONT_PATHS.filter((p) => existsSync(p))
85
85
  const mod = await loadCompilerModule()
@@ -88,7 +88,7 @@ export async function renderPdf(mainFile: string, outFile: string): Promise<numb
88
88
  ...(fontPaths.length > 0 ? { fontArgs: [{ fontPaths }] } : {}),
89
89
  })
90
90
  const pdf = compiler.pdf({ mainFilePath: mainFile })
91
- writeFileSync(outFile, Buffer.from(pdf))
91
+ await Bun.write(outFile, pdf)
92
92
  return pdf.length
93
93
  }
94
94
 
@@ -70,25 +70,35 @@ function duplicatesStanding(verdict: ReviewVerdict, effective: EffectiveVerdict)
70
70
  return verdict === 'APPROVE' ? effective === 'APPROVED' : effective === 'CHANGES_REQUESTED'
71
71
  }
72
72
 
73
+ // Whether the duplicate-review cooldown may fire for this GitHub state. Only the
74
+ // AMBIGUOUS states qualify: a bare NONE (read lag) or the SAME standing verdict
75
+ // (post-indexing fan-out). A DISMISSED or the opposite decisive verdict is a real
76
+ // supersession that legitimizes a fresh same-verdict review, so the cooldown is
77
+ // skipped — preserving the 35287f99 invariant against stranding a re-verdict.
78
+ function cooldownApplies(verdict: ReviewVerdict, effective: EffectiveVerdict): boolean {
79
+ return effective === 'NONE' || duplicatesStanding(verdict, effective)
80
+ }
81
+
73
82
  // How long a reservation may sit before it is treated as abandoned. A normal
74
83
  // `gh` review submit completes in seconds; this only guards against a tool.after
75
84
  // that never fires (crash mid-command), so it must outlast a slow command yet
76
85
  // never strand a PR for long.
77
86
  const LEASE_TTL_MS = 5 * 60_000
78
87
 
79
- // How long a just-landed verdict is trusted to explain a GitHub `NONE` as
80
- // read-after-write lag rather than a genuine absence. GitHub's `/pulls/<n>/reviews`
81
- // list lags a write by up to ~10s, so a second engagement turn firing in that
82
- // window reads NONE and would land a duplicate. Observed duplicates were ~10-18s
83
- // apart originally; a later fan-out incident spread FOUR sequential APPROVEs over
84
- // ~15s (one channel session per inline review thread), each ~3-7s after the last —
85
- // well inside the read lag yet beyond a single turn. 120s gives margin for that
86
- // thread fan-out plus slow API indexing without turning the shield into a human-
87
- // facing rate limit (a legitimate re-verdict after a new push carries a new head
88
- // SHA and bypasses this entirely; staying under ~5min avoids blocking genuine
89
- // re-reviews). This window only shadows a raw NONE on the SAME verdict (+ same or
90
- // uncertain head) — a DISMISSED/CHANGES_REQUESTED/flipped-verdict all bypass it.
91
- const RECENT_LANDED_TTL_MS = 120_000
88
+ // How long a just-landed verdict suppresses a redundant same-verdict re-submit on
89
+ // the same head — a duplicate-review cooldown. It started as a narrow lag shield
90
+ // for GitHub's ~10-18s read-after-write lag (the original ~10-18s-apart duplicates
91
+ // on PR #691), but the PR #1042 thread fan-out spread same-commit APPROVEs over ~2
92
+ // minutes — each one AFTER GitHub had already indexed the prior, so the
93
+ // standing-verdict read no longer returned a bare NONE for a lag-only shield to
94
+ // catch, yet the redundant verdict still landed. So the window now also fires when
95
+ // GitHub reports the standing verdict, and is widened to 5 minutes to cover slow
96
+ // sequential fan-out. It only ever shadows the SAME verdict on the SAME (or
97
+ // uncertain) head: a DISMISSED, the opposite decisive verdict, a flipped verdict,
98
+ // and a new-push head all bypass it, so a genuine re-review is never stranded. 5min
99
+ // stays well under the lease TTL and short enough that a deliberate human-driven
100
+ // re-approval of the identical commit is the only thing it can delay.
101
+ const RECENT_LANDED_TTL_MS = 5 * 60_000
92
102
 
93
103
  type Reservation = {
94
104
  key: string
@@ -204,11 +214,23 @@ export function createApproveIdempotencyGuard(deps: {
204
214
  return { block: true, reason: duplicateReason(args.verdict) }
205
215
  }
206
216
 
207
- // Layer 3: only a raw NONE from a successful read is ambiguous — it can mean
208
- // "no review" or "our just-landed review not yet indexed". A recent same
209
- // verdict on the same head resolves it to lag and blocks the duplicate. Any
210
- // non-NONE state already decided above, so this never overrides a supersession.
211
- if (remote.ok && remote.effective === 'NONE' && recentlyLandedSame(key, args.verdict, headSha, now)) {
217
+ // Layer 3 — duplicate-review cooldown. A recently-landed SAME verdict on the
218
+ // SAME (or uncertain) head blocks a redundant re-submit for the window. It
219
+ // fires on a bare NONE (read-after-write lag, the original shield) AND on the
220
+ // now-indexed SAME standing verdict (the PR #1042 fan-out, where siblings fired
221
+ // minutes apart after indexing) — `duplicatesStanding` above already returned
222
+ // here for that case, so reaching this line on a same-standing-verdict means
223
+ // only that the lease-released duplicate is being re-tried; either way the
224
+ // cooldown holds. It must NOT fire on a DISMISSED or the opposite decisive
225
+ // verdict: those are genuine supersessions, so the cooldown is gated to the
226
+ // ambiguous states (NONE, or the same standing verdict) and skipped for any
227
+ // decisive state that contradicts a redundant re-submit. A read error skips it
228
+ // (fails open) so a transient failure cannot strand a re-verdict.
229
+ if (
230
+ remote.ok &&
231
+ cooldownApplies(args.verdict, remote.effective) &&
232
+ recentlyLandedSame(key, args.verdict, headSha, now)
233
+ ) {
212
234
  releaseReservation(args.callId, reservation)
213
235
  return { block: true, reason: duplicateReason(args.verdict) }
214
236
  }
@@ -32,17 +32,17 @@ All fields are **restart-required** — the plugin reads them once at boot. The
32
32
 
33
33
  ## What it contributes
34
34
 
35
- | Kind | Name | Notes |
36
- | -------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
37
- | Subagent | `memory-logger` | Reads a parent transcript past a watermark and appends fragments to `memory/streams/<today>.jsonl`. Coalesced per `agentDir`. |
38
- | Subagent | `dreaming` | Reads shards under `memory/topics/` plus undreamed daily-stream events and rebalances the topic shards. Coalesced per `agentDir`. Citation-superset invariant enforced on every run. |
39
- | Subagent | `memory-retrieval` | On `session.turn.start` when injection plan is `index` mode, reads the user's actual prompt for this turn + shard listing, writes a focused summary to `memory/.retrieval-cache/<sessionId>.md`. Coalesced per `parentSessionId`. Declares `profile: 'fast'` (retrieval is "≤3 keyword searches + 1 write", no reasoning required) and `timeoutMs: 30_000` so a wedged provider call releases the coalescing key instead of poisoning the cache for every subsequent turn. |
40
- | Tool | `memory_search` | Main-agent tool. Pass `query` to search, or `topic` to look up one shard by exact slug (not both). Search is substring/regex across BOTH topic shards (slugs, frontmatter, bodies) and undreamed daily-stream events (fragment topic/body, legacy prose). Plain queries are phrase-first: the whole query is tried as one substring, and if that finds nothing the query is split on whitespace and the distinct words are OR-matched, ranked by how many words each hit contains (regex queries never fall back). Results are discriminated by `source: "topic" \| "stream"`; exact-phrase (and regex) results list topics first, then streams newest-first, while word-fallback results are ranked by matched-word count with that order as the tiebreak (so a higher-scoring stream can precede a lower-scoring topic). The `topic` mode reads `memory/topics/<slug>.md` directly via `loadShard` and returns that one shard with its full body — no fuzzy search — so a channel agent can open a topic whose slug the per-turn injection already showed it, instead of re-searching for a body the retrieval layer already located. When no topic shard matches the slug it falls back to a reference of the same slug (`memory/references/<slug>.md`), because the per-turn injection renders topic and reference entries with the same `slug:` line and the same `memory_search({ topic: "<slug>" })` recovery hint — so a reference slug surfaced in channel memory must resolve here, not dead-end. Bad slugs (path traversal) come back as a structured error; a slug matching neither a topic nor a reference is an empty match set. |
41
- | Tool | `delete_topic_shard` | Subagent-only (dreaming). Deletes a topic shard at `memory/topics/<slug>.md`. Path-guarded. |
42
- | Cron | `__plugin_memory_dreaming` | `kind: 'prompt'`, `subagent: 'dreaming'`, scheduled per `memory.dreaming.schedule`. |
43
- | Hook | `session.idle` | Per-session debouncer with size-based ceiling. Spawns `memory-logger` on idle or buffer-trip. |
44
- | Hook | `session.end` | Spawns `memory-logger` immediately; also unlinks the retrieval-cache file for this session. |
45
- | Hook | `session.turn.start` | **Vector on:** renders the per-turn user-prompt memory block into `event.retrievalContext.results` (direct-mode shards under budget, de-duplicated across turns per session; top-K `hybridSearch` over budget; channel origins always index/headings-only); runs for every origin that supplies a `retrievalContext`, including user-delegated subagents (researcher, reviewer) — but NOT TypeClaw-owned infrastructure turns (`system` origins and `system`-spawned subagents memory-logger/backup, plus the dreaming cron job matched by its `__plugin_memory_dreaming` job id), whose `userPrompt` is a fixed instruction block, not a user message (see [Internal-infrastructure turns skip retrieval](#internal-infrastructure-turns-skip-retrieval)). **Vector off:** when `buildInjectionPlan` returns `mode: 'index'` and origin is not a subagent, spawns `memory-retrieval` (detached) with the turn's `userPrompt` so the cache reflects the user's current question. Fire-and-forget; failures route through the plugin logger. |
35
+ | Kind | Name | Notes |
36
+ | -------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
37
+ | Subagent | `memory-logger` | Reads a parent transcript past a watermark and appends fragments to `memory/streams/<today>.jsonl`. Coalesced per `agentDir`. |
38
+ | Subagent | `dreaming` | Reads shards under `memory/topics/` plus undreamed daily-stream events and rebalances the topic shards. Coalesced per `agentDir`. Citation-superset invariant enforced on every run. |
39
+ | Subagent | `memory-retrieval` | On `session.turn.start` when injection plan is `index` mode, reads the user's actual prompt for this turn + shard listing, writes a focused summary to `memory/.retrieval-cache/<sessionId>.md`. Coalesced per `parentSessionId`. Declares `profile: 'fast'` (retrieval is "≤3 keyword searches + 1 write", no reasoning required) and `timeoutMs: 30_000` so a wedged provider call releases the coalescing key instead of poisoning the cache for every subsequent turn. |
40
+ | Tool | `memory_search` | Main-agent tool. Pass `query` to search, or `topic` to look up one shard by exact slug (not both). Search is substring/regex across BOTH topic shards (slugs, frontmatter, bodies) and undreamed daily-stream events (fragment topic/body, legacy prose). Plain queries are phrase-first: the whole query is tried as one substring, and if that finds nothing the query is split on whitespace and the distinct words are OR-matched, ranked by how many words each hit contains (regex queries never fall back). Results are discriminated by `source: "topic" \| "stream"`; exact-phrase (and regex) results list topics first, then streams newest-first, while word-fallback results are ranked by matched-word count with that order as the tiebreak (so a higher-scoring stream can precede a lower-scoring topic). The `topic` mode reads `memory/topics/<slug>.md` directly via `loadShard` and returns that one shard with its full body — no fuzzy search — so a channel agent can open a topic whose slug the per-turn injection already showed it, instead of re-searching for a body the retrieval layer already located. When no topic shard matches the slug it falls back to a reference of the same slug (`memory/references/<slug>.md`), because the per-turn injection renders topic and reference entries with the same `slug:` line and the same `memory_search({ topic: "<slug>" })` recovery hint — so a reference slug surfaced in channel memory must resolve here, not dead-end. Bad slugs (path traversal) come back as a structured error; a slug matching neither a topic nor a reference is an empty match set. The optional `where` param scopes a query to one room (`"#incidents"` or its raw chat id): it keeps only stream fragments whose captured `where` matches the room by raw `chat` id or `chatName` (case-insensitive, leading `#` optional) and — because room is fragment-only provenance — returns ONLY stream matches, excluding topic shards and references. |
41
+ | Tool | `delete_topic_shard` | Subagent-only (dreaming). Deletes a topic shard at `memory/topics/<slug>.md`. Path-guarded. |
42
+ | Cron | `__plugin_memory_dreaming` | `kind: 'prompt'`, `subagent: 'dreaming'`, scheduled per `memory.dreaming.schedule`. |
43
+ | Hook | `session.idle` | Per-session debouncer with size-based ceiling. Spawns `memory-logger` on idle or buffer-trip. |
44
+ | Hook | `session.end` | Spawns `memory-logger` immediately; also unlinks the retrieval-cache file for this session. |
45
+ | Hook | `session.turn.start` | **Vector on:** renders the per-turn user-prompt memory block into `event.retrievalContext.results` (direct-mode shards under budget, de-duplicated across turns per session; top-K `hybridSearch` over budget; channel origins always index/headings-only); runs for every origin that supplies a `retrievalContext`, including user-delegated subagents (researcher, reviewer) — but NOT TypeClaw-owned infrastructure turns (`system` origins and `system`-spawned subagents memory-logger/backup, plus the dreaming cron job matched by its `__plugin_memory_dreaming` job id), whose `userPrompt` is a fixed instruction block, not a user message (see [Internal-infrastructure turns skip retrieval](#internal-infrastructure-turns-skip-retrieval)). **Vector off:** when `buildInjectionPlan` returns `mode: 'index'` and origin is not a subagent, spawns `memory-retrieval` (detached) with the turn's `userPrompt` so the cache reflects the user's current question. Fire-and-forget; failures route through the plugin logger. |
46
46
 
47
47
  ## Memory injection (two-tier, topic shards only)
48
48
 
@@ -132,7 +132,7 @@ A `[dreaming] citation-superset violation: …` warning logs the dropped ids and
132
132
  ## Files on disk
133
133
 
134
134
  - **`memory/topics/<slug>.md`** — per-topic shards with YAML frontmatter (`heading`, `cites`, `days`, `lastReinforced`, `tags?`) + body markdown. Runtime owns the frontmatter (recomputed after every dreaming run from the body's citations); dreaming subagent writes body only. The body is a **compact belief record**: one belief sentence stating the current truth (subject + predicate + essential scope qualifier; the strength wording — "mentioned" / "consistently" / "always" — is calibrated from `days`), followed by the `fragments:` list (active evidence behind the belief) and an optional `superseded:` list (evidence overturned by a later contradiction — kept cited for GC/history but excluded from vector retrieval). One sentence (not a paragraph) keeps bodies small so more topics stay under the direct-injection budget; the citation lists are the only load-bearing part of the body, so the prose shape is free to be terse. Existing verbose shards are rewritten into this form by the next dreaming run (no migration).
135
- - **`memory/streams/yyyy-MM-dd.jsonl`** — daily fragment streams. One event per line, discriminated union of `fragment | watermark | legacy_prose`. Force-committed alongside the shards.
135
+ - **`memory/streams/yyyy-MM-dd.jsonl`** — daily fragment streams. One event per line, discriminated union of `fragment | watermark | legacy_prose`. Force-committed alongside the shards. A `fragment` event carries optional **situational provenance** for "who said what, where, and when": `who` (display name/handle of the attributed speaker, LLM-supplied per-fragment by `memory-logger` only when one transcript speaker clearly owns the evidence), `where` (`{ adapter, workspace, workspaceName?, chat, chatName?, thread }` — runtime-stamped from the session origin in the append tool, channel origins only), and `when` (reuses the existing `ts`). Both are optional, so legacy fragments and non-channel (TUI) origins parse with them absent. `who`/`where` are deliberately NOT in `fragmentContentHash` (dedup stays content-identity) and NOT in `fragmentEmbeddableText` (provenance is retrieval metadata, not embedded — it must not burn the 512-token budget or let same-room/same-person dominate recall). **Secret-scanning covers provenance too**: `who` (LLM-supplied) clears the same `detectSecrets` guard as `topic`/`body` and a credential-shaped value is refused with the retryable error; the origin-derived `where` names (`workspaceName`/`chatName`) are external channel data the agent can't rewrite, so a credential-shaped name is silently dropped (raw id kept) rather than wedging the logger. Raw ids are platform-issued identifiers, not free text, so they are not scanned. `where` is runtime-stamped rather than LLM-supplied because the channel is stable for a whole logger run; `who` is per-fragment because a single run spans many speakers and `origin.lastInboundAuthorId` is only the spawn-time one — auto-stamping it would misattribute fragments about earlier speakers. Surfaced to the agent (not embedded) via `memory_search` (`StreamMatch.who/when/where`), `hybridSearch` (`HybridSearchResult.who/when/where` on self-resolved undreamed fragments), and the per-turn retrieval render (`renderProvenanceLine` → `_Jisoo in #incidents on 2026-06-24_`).
136
136
  - **`memory/MEMORY.md.pre-shard.bak`** — legacy pre-shard backup left by older TypeClaw versions. Safe to delete after verifying.
137
137
  - **`memory/skills/<name>/SKILL.md`** — muscle memory (Form A). Skills the dreaming subagent distills from repeated procedures. Auto-loaded as first-class skills. CLI/plugin suggestions (Forms B and C) are recorded as topic shards instead — see [Muscle memory](#muscle-memory-three-forms).
138
138
  - **`memory/references/<slug>.md`** — verbatim reference artifacts (gated behind `memory.references.enabled`). Written by `store_reference`. When vector is enabled, a freshly stored reference is embedded into the vector index immediately via the `store_reference` on-write hook (`vector/reference-index-on-write.ts`), mirroring the stream-fragment on-write hook — so it is vector-retrievable within the same container uptime instead of only after the next startup index build. Chunks are derived by the same `referencePassagesForOne` the startup build uses, and re-storing a shorter body prunes the stale higher-index chunk rows.