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
package/auth.schema.json CHANGED
@@ -116,6 +116,57 @@
116
116
  }
117
117
  }
118
118
  },
119
+ "discord": {
120
+ "type": "object",
121
+ "properties": {
122
+ "currentAccount": {
123
+ "anyOf": [
124
+ {
125
+ "type": "string"
126
+ },
127
+ {
128
+ "type": "null"
129
+ }
130
+ ]
131
+ },
132
+ "accounts": {
133
+ "type": "object",
134
+ "propertyNames": {
135
+ "type": "string"
136
+ },
137
+ "additionalProperties": {
138
+ "type": "object",
139
+ "properties": {
140
+ "account_id": {
141
+ "type": "string"
142
+ },
143
+ "token": {
144
+ "type": "string"
145
+ },
146
+ "username": {
147
+ "type": "string"
148
+ },
149
+ "created_at": {
150
+ "type": "string"
151
+ },
152
+ "updated_at": {
153
+ "type": "string"
154
+ }
155
+ },
156
+ "required": [
157
+ "account_id",
158
+ "token",
159
+ "created_at",
160
+ "updated_at"
161
+ ]
162
+ }
163
+ }
164
+ },
165
+ "required": [
166
+ "currentAccount",
167
+ "accounts"
168
+ ]
169
+ },
119
170
  "discord-bot": {
120
171
  "type": "object",
121
172
  "properties": {
@@ -607,6 +658,65 @@
607
658
  "currentAccount",
608
659
  "accounts"
609
660
  ]
661
+ },
662
+ "slack": {
663
+ "type": "object",
664
+ "properties": {
665
+ "currentAccount": {
666
+ "anyOf": [
667
+ {
668
+ "type": "string"
669
+ },
670
+ {
671
+ "type": "null"
672
+ }
673
+ ]
674
+ },
675
+ "accounts": {
676
+ "type": "object",
677
+ "propertyNames": {
678
+ "type": "string"
679
+ },
680
+ "additionalProperties": {
681
+ "type": "object",
682
+ "properties": {
683
+ "account_id": {
684
+ "type": "string"
685
+ },
686
+ "token": {
687
+ "type": "string"
688
+ },
689
+ "cookie": {
690
+ "type": "string"
691
+ },
692
+ "workspace_id": {
693
+ "type": "string"
694
+ },
695
+ "workspace_name": {
696
+ "type": "string"
697
+ },
698
+ "created_at": {
699
+ "type": "string"
700
+ },
701
+ "updated_at": {
702
+ "type": "string"
703
+ }
704
+ },
705
+ "required": [
706
+ "account_id",
707
+ "token",
708
+ "cookie",
709
+ "workspace_id",
710
+ "created_at",
711
+ "updated_at"
712
+ ]
713
+ }
714
+ }
715
+ },
716
+ "required": [
717
+ "currentAccount",
718
+ "accounts"
719
+ ]
610
720
  }
611
721
  },
612
722
  "additionalProperties": {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.39.2",
3
+ "version": "0.39.4",
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.24.1",
53
+ "agent-messenger": "^2.27.1",
54
54
  "cheerio": "^1.2.0",
55
55
  "citty": "^0.2.2",
56
56
  "cron-parser": "^5.5.0",
@@ -116,6 +116,57 @@
116
116
  }
117
117
  }
118
118
  },
119
+ "discord": {
120
+ "type": "object",
121
+ "properties": {
122
+ "currentAccount": {
123
+ "anyOf": [
124
+ {
125
+ "type": "string"
126
+ },
127
+ {
128
+ "type": "null"
129
+ }
130
+ ]
131
+ },
132
+ "accounts": {
133
+ "type": "object",
134
+ "propertyNames": {
135
+ "type": "string"
136
+ },
137
+ "additionalProperties": {
138
+ "type": "object",
139
+ "properties": {
140
+ "account_id": {
141
+ "type": "string"
142
+ },
143
+ "token": {
144
+ "type": "string"
145
+ },
146
+ "username": {
147
+ "type": "string"
148
+ },
149
+ "created_at": {
150
+ "type": "string"
151
+ },
152
+ "updated_at": {
153
+ "type": "string"
154
+ }
155
+ },
156
+ "required": [
157
+ "account_id",
158
+ "token",
159
+ "created_at",
160
+ "updated_at"
161
+ ]
162
+ }
163
+ }
164
+ },
165
+ "required": [
166
+ "currentAccount",
167
+ "accounts"
168
+ ]
169
+ },
119
170
  "discord-bot": {
120
171
  "type": "object",
121
172
  "properties": {
@@ -607,6 +658,65 @@
607
658
  "currentAccount",
608
659
  "accounts"
609
660
  ]
661
+ },
662
+ "slack": {
663
+ "type": "object",
664
+ "properties": {
665
+ "currentAccount": {
666
+ "anyOf": [
667
+ {
668
+ "type": "string"
669
+ },
670
+ {
671
+ "type": "null"
672
+ }
673
+ ]
674
+ },
675
+ "accounts": {
676
+ "type": "object",
677
+ "propertyNames": {
678
+ "type": "string"
679
+ },
680
+ "additionalProperties": {
681
+ "type": "object",
682
+ "properties": {
683
+ "account_id": {
684
+ "type": "string"
685
+ },
686
+ "token": {
687
+ "type": "string"
688
+ },
689
+ "cookie": {
690
+ "type": "string"
691
+ },
692
+ "workspace_id": {
693
+ "type": "string"
694
+ },
695
+ "workspace_name": {
696
+ "type": "string"
697
+ },
698
+ "created_at": {
699
+ "type": "string"
700
+ },
701
+ "updated_at": {
702
+ "type": "string"
703
+ }
704
+ },
705
+ "required": [
706
+ "account_id",
707
+ "token",
708
+ "cookie",
709
+ "workspace_id",
710
+ "created_at",
711
+ "updated_at"
712
+ ]
713
+ }
714
+ }
715
+ },
716
+ "required": [
717
+ "currentAccount",
718
+ "accounts"
719
+ ]
610
720
  }
611
721
  },
612
722
  "additionalProperties": {}
@@ -238,19 +238,25 @@ export type CreateSessionOptions = {
238
238
  }
239
239
 
240
240
  export type CreateSessionResult = {
241
- session: AgentSession
241
+ session: AgentSession & { getAbortReason?: () => string | undefined }
242
242
  dispose: () => Promise<void>
243
+ getAbortReason?: () => string | undefined
243
244
  }
244
245
 
245
246
  // A session's reasoning effort layers like the model does: the resolved
246
- // profile's own `thinkingLevel` → the `default` profile's `thinkingLevel`
247
- // (the de-facto global default, mirroring how `models.default` is the default
248
- // model) → the per-provider/SDK default for the active ref. When the requested
249
- // profile was unknown, `resolved` is already the `default` profile, so the
250
- // first two terms coincide and the expression still does the right thing.
247
+ // profile's own `thinkingLevel` → the `default` profile's `thinkingLevel` (the
248
+ // de-facto global default) → the per-provider/SDK default for the active ref.
249
+ // When the requested profile was unknown, `resolved` is already the `default`
250
+ // profile, so those terms coincide and the expression still does the right thing.
251
+ //
252
+ // Built-in per-profile defaults (e.g. `fast: 'low'`, `deep: 'high'`) are
253
+ // materialized onto the entry at config-parse time (see PROFILE_THINKING_LEVEL_DEFAULTS
254
+ // in config.ts), so they arrive here as `resolved.thinkingLevel` — the first term.
255
+ // That is why `deep`'s `high` still beats a lowered global default, and why there
256
+ // is no profile special-casing in this function.
251
257
  export function resolveSessionThinkingLevel(
252
258
  models: Models,
253
- resolved: Pick<ResolvedProfile, 'thinkingLevel'>,
259
+ resolved: Pick<ResolvedProfile, 'thinkingLevel' | 'profile'>,
254
260
  activeRef: ModelRef,
255
261
  ): ThinkingLevel | undefined {
256
262
  return resolved.thinkingLevel ?? models.default.thinkingLevel ?? defaultThinkingLevelForRef(activeRef)
@@ -309,8 +315,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
309
315
  // Tools are wrapped BEFORE the session exists, so the loop guard reaches the
310
316
  // abort through this lazily-resolved getter. See `fireLoopAbort` in
311
317
  // plugin-tools.ts for why aborting (not throwing) is what stops the loop.
312
- const abortHolder: { abort?: () => void } = {}
313
- const getAbort: () => (() => void) | undefined = () => abortHolder.abort
318
+ const abortHolder: { abort?: (reason?: string) => void; reason?: string } = {}
319
+ const getAbort: () => ((reason?: string) => void) | undefined = () => abortHolder.abort
314
320
 
315
321
  // Subagent built-in tool refs are dual-routed (see BUILTIN_TOOL_DEFINITION
316
322
  // dual-map in plugin-tools.ts): pi-side coding tools go to `tools:` so they
@@ -474,6 +480,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
474
480
  customTools,
475
481
  ...(thinkingLevel ? { thinkingLevel } : {}),
476
482
  })
483
+ const getAbortReason = () => abortHolder.reason
484
+ const sessionWithAbortReason = Object.assign(session, { getAbortReason })
477
485
 
478
486
  // Layer the replay sanitizer over pi's convertToLlm so a transcript with an
479
487
  // orphaned toolResult (e.g. a torn-down restart turn) can't wedge the session
@@ -490,7 +498,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
490
498
  }
491
499
  }
492
500
 
493
- abortHolder.abort = () => {
501
+ abortHolder.abort = (reason?: string) => {
502
+ if (reason !== undefined) abortHolder.reason = reason
494
503
  if (session.agent.signal?.aborted !== true) session.agent.abort()
495
504
  }
496
505
 
@@ -527,7 +536,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
527
536
  unsubToolNudge()
528
537
  if (materializedSkills) await materializedSkills.dispose()
529
538
  }
530
- return { session, dispose }
539
+ return { session: sessionWithAbortReason, dispose, getAbortReason }
531
540
  }
532
541
 
533
542
  // Decides whether the restart tool should write the cross-restart handoff
@@ -851,7 +860,7 @@ export function buildTodoTools(
851
860
  function wrapRegistryTools(
852
861
  plugins: PluginSessionWiring | undefined,
853
862
  getOrigin: () => SessionOrigin | undefined,
854
- getAbort: () => (() => void) | undefined,
863
+ getAbort: () => ((reason?: string) => void) | undefined,
855
864
  ): ToolDefinition[] {
856
865
  if (!plugins) return []
857
866
  return plugins.registry.tools.map((t: PluginRegisteredTool) =>
@@ -872,7 +881,7 @@ function wrapSystemAgentTools(
872
881
  tools: AgentSessionTools | undefined,
873
882
  plugins: PluginSessionWiring | undefined,
874
883
  getOrigin: () => SessionOrigin | undefined,
875
- getAbort: () => (() => void) | undefined,
884
+ getAbort: () => ((reason?: string) => void) | undefined,
876
885
  ): AgentSessionTools | undefined {
877
886
  if (!tools || !hasToolHooks(plugins)) return tools
878
887
  return tools.map((tool) =>
@@ -890,7 +899,7 @@ function wrapSystemTools(
890
899
  tools: ToolDefinition[],
891
900
  plugins: PluginSessionWiring | undefined,
892
901
  getOrigin: () => SessionOrigin | undefined,
893
- getAbort: () => (() => void) | undefined,
902
+ getAbort: () => ((reason?: string) => void) | undefined,
894
903
  ): ToolDefinition[] {
895
904
  if (!hasToolHooks(plugins)) return tools
896
905
  return tools.map((tool) =>
@@ -913,7 +922,7 @@ function wrapSubagentCustomTools(
913
922
  selection: PluginSubagentSelection,
914
923
  plugins: PluginSessionWiring | undefined,
915
924
  getOrigin: () => SessionOrigin | undefined,
916
- getAbort: () => (() => void) | undefined,
925
+ getAbort: () => ((reason?: string) => void) | undefined,
917
926
  ): ToolDefinition[] {
918
927
  if (!selection.customTools || !plugins) return []
919
928
  const logger = makePluginLogger(selection.pluginName)
@@ -1155,6 +1164,14 @@ export async function createResourceLoader(options: CreateResourceLoaderOptions
1155
1164
  ...(options.plugins?.sessionId !== undefined ? { currentSessionId: options.plugins.sessionId } : {}),
1156
1165
  }),
1157
1166
  )
1167
+ // MCP connection is warmed up in the background at boot; gate the catalog
1168
+ // render on that warm-up settling (bounded) so a session created in the
1169
+ // warm-up window still lists connected servers. Kicked off here to overlap
1170
+ // with the self/git/memory I/O above instead of serializing before compose.
1171
+ const mcpReadySettled =
1172
+ mode === 'full' && options.mcpManager !== undefined
1173
+ ? options.mcpManager.whenInitialConnectSettled()
1174
+ : Promise.resolve()
1158
1175
 
1159
1176
  let self = await selfPromise
1160
1177
 
@@ -1183,6 +1200,12 @@ export async function createResourceLoader(options: CreateResourceLoaderOptions
1183
1200
  const gitNudge = unwrapSettled(gitNudgeResult)
1184
1201
  const memorySection = unwrapSettled(memoryResult)
1185
1202
 
1203
+ let mcpCatalog: string | undefined
1204
+ if (mode === 'full' && options.mcpManager !== undefined) {
1205
+ await mcpReadySettled
1206
+ mcpCatalog = renderMcpCatalog(options.mcpManager.listServers())
1207
+ }
1208
+
1186
1209
  const systemPrompt = composeSystemPrompt({
1187
1210
  mode,
1188
1211
  self,
@@ -1190,9 +1213,7 @@ export async function createResourceLoader(options: CreateResourceLoaderOptions
1190
1213
  ...(options.runtimeVersion !== undefined ? { runtimeVersion: options.runtimeVersion } : {}),
1191
1214
  ...(options.origin !== undefined ? { origin: options.origin } : {}),
1192
1215
  ...(roleContext !== undefined ? { roleContext } : {}),
1193
- ...(mode === 'full' && options.mcpManager !== undefined
1194
- ? { mcpCatalog: renderMcpCatalog(options.mcpManager.listServers()) }
1195
- : {}),
1216
+ ...(mcpCatalog !== undefined ? { mcpCatalog } : {}),
1196
1217
  gitNudge,
1197
1218
  ...(options.proactiveNextStepNudge === true ? { proactiveNextStepNudge: PROACTIVE_NEXT_STEP_NUDGE } : {}),
1198
1219
  memorySection,
@@ -71,10 +71,17 @@ export async function promptWithFallback<TRef extends FallbackModelRef>(opts: {
71
71
  // Called after each non-final attempt so callers can log the per-attempt
72
72
  // failure with their own context (sessionId, channel key, job id, ...).
73
73
  onAttemptFailed?: (attempt: FallbackAttempt<TRef>) => void
74
+ // Gate that decides whether a given failure is worth advancing the chain.
75
+ // Omitted (cron) means "advance on any error" — the original behavior.
76
+ // Interactive callers pass `isThrottleOrOverload` so a one-off real error
77
+ // (billing, malformed response) surfaces on the active ref instead of
78
+ // silently switching providers.
79
+ shouldFailover?: (err: Error) => boolean
74
80
  }): Promise<FallbackPromptResult<TRef>> {
75
81
  if (opts.refs.length === 0) {
76
82
  throw new Error('promptWithFallback: refs[] must be non-empty')
77
83
  }
84
+ const failoverGate = opts.shouldFailover ?? (() => true)
78
85
  const attempts: FallbackAttempt<TRef>[] = []
79
86
  let lastError: Error | undefined
80
87
  for (let i = 0; i < opts.refs.length; i++) {
@@ -97,10 +104,11 @@ export async function promptWithFallback<TRef extends FallbackModelRef>(opts: {
97
104
  const attempt: FallbackAttempt<TRef> = { ref, outcome: 'hard', errorMessage: error.message }
98
105
  attempts.push(attempt)
99
106
  lastError = error
100
- if (!isLast) opts.onAttemptFailed?.(attempt)
107
+ const stop = isLast || !failoverGate(error)
108
+ if (!stop) opts.onAttemptFailed?.(attempt)
101
109
  unsub()
102
110
  await dispose()
103
- if (isLast) {
111
+ if (stop) {
104
112
  return { success: false, refUsed: ref, attempts, session, dispose: async () => {}, lastError }
105
113
  }
106
114
  continue
@@ -109,10 +117,11 @@ export async function promptWithFallback<TRef extends FallbackModelRef>(opts: {
109
117
  const attempt: FallbackAttempt<TRef> = { ref, outcome: 'soft', errorMessage: softError.message }
110
118
  attempts.push(attempt)
111
119
  lastError = softError
112
- if (!isLast) opts.onAttemptFailed?.(attempt)
120
+ const stop = isLast || !failoverGate(softError)
121
+ if (!stop) opts.onAttemptFailed?.(attempt)
113
122
  unsub()
114
123
  await dispose()
115
- if (isLast) {
124
+ if (stop) {
116
125
  return { success: false, refUsed: ref, attempts, session, dispose: async () => {}, lastError }
117
126
  }
118
127
  continue
@@ -190,7 +190,7 @@ export type WrapToolOptions = {
190
190
  // Resolves the current turn's abort handle. Resolved lazily (not at wrap
191
191
  // time) because tools are wrapped BEFORE `createAgentSession` returns the
192
192
  // session whose `agent.abort` this points at. See `fireLoopAbort`.
193
- getAbort?: () => (() => void) | undefined
193
+ getAbort?: () => ((reason?: string) => void) | undefined
194
194
  }
195
195
 
196
196
  export type WrapSystemToolOptions = {
@@ -198,7 +198,7 @@ export type WrapSystemToolOptions = {
198
198
  sessionId: string
199
199
  hooks: HookBus
200
200
  getOrigin?: () => SessionOrigin | undefined
201
- getAbort?: () => (() => void) | undefined
201
+ getAbort?: () => ((reason?: string) => void) | undefined
202
202
  // When present, the bash builtin is rewritten through the per-tool bwrap
203
203
  // sandbox with role-derived path masks. Absent (or no masks for the role)
204
204
  // runs bash unchanged — preserving today's behavior for trusted+ and for
@@ -262,7 +262,7 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
262
262
 
263
263
  const loopGate = gateLoopGuard(opts.sessionId, opts.toolName, before.args)
264
264
  if (loopGate.blockNow) {
265
- fireLoopAbort(opts.getAbort)
265
+ fireLoopAbort(opts.getAbort, 'loop_guard:block')
266
266
  return errorResult(loopGate.message)
267
267
  }
268
268
 
@@ -283,7 +283,7 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
283
283
 
284
284
  const resolved = loopGate.resolve(result)
285
285
  if ('deferredBlock' in resolved) {
286
- fireLoopAbort(opts.getAbort)
286
+ fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
287
287
  return errorResult(resolved.deferredBlock)
288
288
  }
289
289
  result = resolved.result
@@ -325,7 +325,7 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
325
325
  }
326
326
  const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs)
327
327
  if (loopGate.blockNow) {
328
- fireLoopAbort(opts.getAbort)
328
+ fireLoopAbort(opts.getAbort, 'loop_guard:block')
329
329
  throw new Error(loopGate.message)
330
330
  }
331
331
  const guardResult = await runFinalWriteGuards({
@@ -345,7 +345,7 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
345
345
  const result = await tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate, ctx)
346
346
  const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
347
347
  if ('deferredBlock' in resolved) {
348
- fireLoopAbort(opts.getAbort)
348
+ fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
349
349
  throw new Error(resolved.deferredBlock)
350
350
  }
351
351
  const hookResult = resolved.result
@@ -385,7 +385,7 @@ export function wrapSystemAgentTool<TParams extends TSchema, TDetails = unknown>
385
385
  }
386
386
  const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs)
387
387
  if (loopGate.blockNow) {
388
- fireLoopAbort(opts.getAbort)
388
+ fireLoopAbort(opts.getAbort, 'loop_guard:block')
389
389
  throw new Error(loopGate.message)
390
390
  }
391
391
  const guardResult = await runFinalWriteGuards({
@@ -405,7 +405,7 @@ export function wrapSystemAgentTool<TParams extends TSchema, TDetails = unknown>
405
405
  const result = await tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate)
406
406
  const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
407
407
  if ('deferredBlock' in resolved) {
408
- fireLoopAbort(opts.getAbort)
408
+ fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
409
409
  throw new Error(resolved.deferredBlock)
410
410
  }
411
411
  const hookResult = resolved.result
@@ -460,7 +460,7 @@ export function wrapAgentToolAsCustomToolDefinition<TParams extends TSchema, TDe
460
460
  delete mutableArgs[TYPECLAW_INTERNAL_BASH_ENV]
461
461
  const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs)
462
462
  if (loopGate.blockNow) {
463
- fireLoopAbort(opts.getAbort)
463
+ fireLoopAbort(opts.getAbort, 'loop_guard:block')
464
464
  throw new Error(loopGate.message)
465
465
  }
466
466
  const guardResult = await runFinalWriteGuards({
@@ -511,7 +511,7 @@ export function wrapAgentToolAsCustomToolDefinition<TParams extends TSchema, TDe
511
511
  const result = tmpRedirect !== undefined ? restoreTmpPathInResult(rawResult, tmpRedirect) : rawResult
512
512
  const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
513
513
  if ('deferredBlock' in resolved) {
514
- fireLoopAbort(opts.getAbort)
514
+ fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
515
515
  throw new Error(resolved.deferredBlock)
516
516
  }
517
517
  const hookResult = resolved.result
@@ -929,8 +929,8 @@ export function __resetSharedLoopGuardForTests(): void {
929
929
  // 'aborted'). We use the signal-only `agent.abort`, never `session.abort`,
930
930
  // which would deadlock awaiting the very run this tool call belongs to. See
931
931
  // the matching pattern in src/channels/router.ts (policy-denied send cap).
932
- function fireLoopAbort(getAbort: (() => (() => void) | undefined) | undefined): void {
933
- getAbort?.()?.()
932
+ function fireLoopAbort(getAbort: (() => ((reason?: string) => void) | undefined) | undefined, reason: string): void {
933
+ getAbort?.()?.(reason)
934
934
  }
935
935
 
936
936
  function errorResult(message: string) {
@@ -41,6 +41,17 @@ const SAFE_CLASSES: ReadonlyArray<{ match: RegExp; safe: string }> = [
41
41
  /\b(401|unauthori[sz]ed|invalid[_ -]?api[_ -]?key|api key.*(?:invalid|expired|missing)|authentication failed|invalid bearer)\b/i,
42
42
  safe: 'The upstream LLM provider rejected the request as unauthorized. Operators should check the provider API key configuration and `typeclaw logs`.',
43
43
  },
44
+ {
45
+ // Content-policy refusal: OpenAI Codex flags a prompt under its cybersecurity
46
+ // policy (`code: "cyber_policy"`) and rejects the whole turn with
47
+ // `invalid_request`. Retrying or failing over to another Codex ref can't help
48
+ // — it's the same account-wide policy — so this must surface with the operator
49
+ // action (get the account authorized) rather than collapse to the generic
50
+ // notice. Common for security-focused PR reviews, where the diff content trips
51
+ // the filter. The URL is OpenAI's own published enrollment page, safe to echo.
52
+ match: /\bcyber_policy\b/i,
53
+ safe: 'The upstream LLM provider (OpenAI Codex) refused the request under its cybersecurity content policy. Operators must enroll the account in OpenAI Trusted Access for Cyber at https://chatgpt.com/cyber, or switch the configured model.',
54
+ },
44
55
  {
45
56
  match: /\b(usage limit|rate limit|rate.?limited|too many requests|429)\b/i,
46
57
  safe: 'The upstream LLM provider is rate-limited (usage limit reached). Try again shortly.',
@@ -58,6 +69,27 @@ function toSafeMessage(raw: string): string {
58
69
  return GENERIC_SAFE_NOTICE
59
70
  }
60
71
 
72
+ // Capacity/rate signals worth failing OVER to another model ref (vs. retrying
73
+ // the same one). English-only is correct — these are provider protocol tokens,
74
+ // the explicit system-token exception to the multi-language rule. `\b` anchors
75
+ // `429`/`503` so they don't match digit runs in prose (token counts,
76
+ // elapsed-ms); `\b` is ASCII-safe because these are ASCII-only codes.
77
+ const THROTTLE_OR_OVERLOAD =
78
+ /overloaded|server_is_overloaded|service.?unavailable|rate.?limit|rate.?limited|too many requests|\b(?:429|503)\b/i
79
+
80
+ // Account-wide faults that must SURFACE, never fail over: switching refs can't
81
+ // help (same account) and would mask a config error the operator must fix. This
82
+ // is checked BEFORE the throttle match because providers often pair a `429`
83
+ // status with a quota/billing/auth reason (e.g. `429 insufficient quota`) — the
84
+ // status code alone must not force a pointless failover.
85
+ const NON_FAILOVER_FAULT =
86
+ /\bcyber_policy\b|insufficient.*(?:quota|credit|fund|balance)|\bquota\b|billing|payment|account is not active|unauthori[sz]ed|invalid[_ -]?api[_ -]?key|authentication failed|invalid bearer/i
87
+
88
+ export function isThrottleOrOverload(raw: string): boolean {
89
+ if (NON_FAILOVER_FAULT.test(raw)) return false
90
+ return THROTTLE_OR_OVERLOAD.test(raw)
91
+ }
92
+
61
93
  export function detectProviderError(message: unknown): DetectedProviderError | null {
62
94
  if (typeof message !== 'object' || message === null) return null
63
95
  const m = message as { role?: unknown; stopReason?: unknown; errorMessage?: unknown }
@@ -81,6 +113,9 @@ export function subscribeProviderErrors(session: AgentSession, onError: Provider
81
113
  return session.subscribe((event) => {
82
114
  if (event.type !== 'message_end') return
83
115
  const detected = detectProviderError(event.message)
84
- if (detected !== null) onError(detected)
116
+ if (detected === null) return
117
+ const abortRetry = (session as { abortRetry?: unknown }).abortRetry
118
+ if (isThrottleOrOverload(detected.message) && typeof abortRetry === 'function') abortRetry.call(session)
119
+ onError(detected)
85
120
  })
86
121
  }
@@ -143,7 +143,9 @@ type PlatformInfo = {
143
143
  }
144
144
 
145
145
  const PLATFORM_INFO: Record<AdapterId, PlatformInfo> = {
146
+ slack: { displayName: 'Slack', mentionMode: 'angle-id', supportsReactions: true, supportsAttachments: true },
146
147
  'slack-bot': { displayName: 'Slack', mentionMode: 'angle-id', supportsReactions: true, supportsAttachments: true },
148
+ discord: { displayName: 'Discord', mentionMode: 'angle-id', supportsReactions: true, supportsAttachments: true },
147
149
  'discord-bot': {
148
150
  displayName: 'Discord',
149
151
  mentionMode: 'angle-id',