typeclaw 0.47.1 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/package.json +1 -1
  2. package/src/agent/index.ts +1 -2
  3. package/src/agent/loop-guard.ts +71 -41
  4. package/src/agent/plugin-tools.ts +167 -50
  5. package/src/agent/retry-same-ref.ts +89 -9
  6. package/src/agent/subagents.ts +88 -15
  7. package/src/agent/system-prompt.ts +1 -1
  8. package/src/agent/turn-runner.ts +60 -5
  9. package/src/bundled-plugins/agent-browser/index.ts +0 -35
  10. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +1 -1
  11. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +16 -1
  12. package/src/bundled-plugins/memory/append-tool.ts +75 -2
  13. package/src/bundled-plugins/memory/frontmatter.ts +13 -2
  14. package/src/bundled-plugins/memory/load-memory.ts +1 -1
  15. package/src/bundled-plugins/memory/memory-logger.ts +5 -1
  16. package/src/bundled-plugins/memory/secret-detector.ts +7 -0
  17. package/src/bundled-plugins/memory/vector/hybrid.ts +3 -1
  18. package/src/bundled-plugins/memory/vector/passages.ts +5 -1
  19. package/src/bundled-plugins/operator/operator.ts +9 -2
  20. package/src/bundled-plugins/researcher/researcher.ts +4 -6
  21. package/src/bundled-plugins/security/index.ts +148 -98
  22. package/src/bundled-plugins/security/policies/private-surface-read.ts +43 -28
  23. package/src/channels/adapters/discord-bot-edit.ts +3 -5
  24. package/src/channels/adapters/discord-bot-reactions.ts +4 -6
  25. package/src/channels/adapters/discord-bot-slash-commands.ts +3 -1
  26. package/src/channels/adapters/discord-bot.ts +20 -23
  27. package/src/channels/adapters/discord-edit.ts +3 -5
  28. package/src/channels/adapters/discord-reactions.ts +4 -6
  29. package/src/channels/adapters/discord.ts +1 -1
  30. package/src/channels/adapters/github/decoy-reviewer.ts +2 -1
  31. package/src/channels/adapters/github/history.ts +2 -1
  32. package/src/channels/adapters/github/inbound.ts +4 -11
  33. package/src/channels/adapters/github/index.ts +6 -9
  34. package/src/channels/adapters/github/outbound.ts +3 -6
  35. package/src/channels/adapters/github/reactions.ts +3 -2
  36. package/src/channels/adapters/github/reconcile-cooldown-store.ts +4 -6
  37. package/src/channels/adapters/github/reconcile-open-prs.ts +5 -4
  38. package/src/channels/adapters/github/recover-failed-deliveries.ts +2 -5
  39. package/src/channels/adapters/github/review-state.ts +3 -2
  40. package/src/channels/adapters/github/review-thread-resolver.ts +3 -2
  41. package/src/channels/adapters/github/webhook-register.ts +5 -8
  42. package/src/channels/adapters/instagram-channel-resolver.ts +3 -5
  43. package/src/channels/adapters/instagram.ts +1 -1
  44. package/src/channels/adapters/kakaotalk-author-resolver.ts +2 -5
  45. package/src/channels/adapters/kakaotalk-channel-resolver.ts +3 -5
  46. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +2 -1
  47. package/src/channels/adapters/kakaotalk-membership.ts +2 -5
  48. package/src/channels/adapters/kakaotalk-typing.ts +1 -1
  49. package/src/channels/adapters/kakaotalk.ts +1 -1
  50. package/src/channels/adapters/line-channel-resolver.ts +3 -5
  51. package/src/channels/adapters/line.ts +1 -1
  52. package/src/channels/adapters/slack-bot-edit.ts +1 -1
  53. package/src/channels/adapters/slack-bot-reactions.ts +4 -6
  54. package/src/channels/adapters/slack-bot.ts +8 -8
  55. package/src/channels/adapters/slack-edit.ts +3 -5
  56. package/src/channels/adapters/slack-reactions.ts +4 -6
  57. package/src/channels/adapters/slack.ts +1 -1
  58. package/src/channels/adapters/teams-edit.ts +2 -5
  59. package/src/channels/adapters/teams.ts +1 -1
  60. package/src/channels/adapters/telegram-bot-edit.ts +4 -7
  61. package/src/channels/adapters/telegram-bot.ts +1 -1
  62. package/src/channels/adapters/webex-bot.ts +1 -1
  63. package/src/channels/adapters/webex-edit.ts +3 -5
  64. package/src/channels/adapters/webex.ts +1 -1
  65. package/src/channels/github-review-claim.ts +89 -4
  66. package/src/channels/github-token-bridge.ts +2 -1
  67. package/src/channels/manager.ts +478 -64
  68. package/src/channels/membership-cache.ts +2 -5
  69. package/src/channels/persistence.ts +3 -6
  70. package/src/channels/reloadable.ts +23 -6
  71. package/src/channels/router.ts +134 -56
  72. package/src/channels/tunnel-bridge.ts +2 -1
  73. package/src/channels/types.ts +6 -3
  74. package/src/cli/hostd.ts +56 -28
  75. package/src/config/config.ts +10 -0
  76. package/src/config/providers.ts +179 -0
  77. package/src/dependencies/bin-resolver.ts +88 -0
  78. package/src/dependencies/bins.ts +227 -0
  79. package/src/dependencies/index.ts +17 -0
  80. package/src/doctor/checks.ts +2 -0
  81. package/src/doctor/operational-incidents.ts +32 -0
  82. package/src/hostd/credential-rotation-apply.ts +94 -0
  83. package/src/init/dockerfile.ts +36 -18
  84. package/src/init/index.ts +1 -1
  85. package/src/init/models-dev.ts +17 -3
  86. package/src/init/validate-api-key.ts +26 -4
  87. package/src/operations/classify-tool-outcome.ts +151 -0
  88. package/src/operations/incidents.ts +274 -0
  89. package/src/operations/index.ts +3 -0
  90. package/src/operations/remediations.ts +41 -0
  91. package/src/reload/client.ts +8 -2
  92. package/src/reload/docker-exec-client.ts +10 -2
  93. package/src/reload/index.ts +1 -1
  94. package/src/reload/recover.ts +5 -3
  95. package/src/reload/registry.ts +5 -5
  96. package/src/reload/types.ts +9 -1
  97. package/src/run/index.ts +5 -0
  98. package/src/sandbox/dependency-bins.ts +125 -0
  99. package/src/sandbox/errors.ts +32 -0
  100. package/src/sandbox/hidden-paths.ts +4 -1
  101. package/src/sandbox/index.ts +8 -0
  102. package/src/sandbox/policy.ts +1 -1
  103. package/src/sandbox/privileged-runtime.ts +88 -7
  104. package/src/sandbox/runtime-private.ts +4 -0
  105. package/src/sandbox/writable-zones.ts +4 -4
  106. package/src/server/index.ts +7 -5
  107. package/src/shared/protocol.ts +6 -1
  108. package/src/skills/typeclaw-monorepo/SKILL.md +1 -1
  109. package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
  110. package/typeclaw.schema.json +35 -5
  111. package/src/bundled-plugins/agent-browser/shim-install.ts +0 -158
  112. package/src/bundled-plugins/agent-browser/shim.ts +0 -108
  113. /package/src/channels/{adapters/describe-error.ts → describe-error.ts} +0 -0
package/src/cli/hostd.ts CHANGED
@@ -1,7 +1,19 @@
1
1
  import { defineCommand } from 'citty'
2
2
 
3
3
  import { loadConfigSync, validateConfig, type Config, type ValidateConfigResult } from '@/config'
4
- import { resolveController, type StartOptions, type StartResult, type StopResult } from '@/container'
4
+ import {
5
+ resolveController,
6
+ resolveHostPort,
7
+ resolveTuiToken,
8
+ type StartOptions,
9
+ type StartResult,
10
+ type StopResult,
11
+ } from '@/container'
12
+ import {
13
+ applyCredentialRotation,
14
+ type CredentialRotationApplyResult,
15
+ type RenewableAdapter,
16
+ } from '@/hostd/credential-rotation-apply'
5
17
  import { createCurrentHostDaemonHolder } from '@/hostd/current-host-daemon'
6
18
  import { startDaemon, type DaemonLogEvent, type RestartPreflight } from '@/hostd/daemon'
7
19
  import { createKakaoRenewalManager } from '@/hostd/kakao-renewal-manager'
@@ -11,6 +23,7 @@ import { createTeamsRenewalManager } from '@/hostd/teams-renewal-manager'
11
23
  import { computeSourceVersion, resolveSrcRoot, UNVERSIONED_SENTINEL } from '@/hostd/version'
12
24
  import { createWebexRenewalManager } from '@/hostd/webex-renewal-manager'
13
25
  import { validateRestartDeps, type RestartDepsPreflightResult } from '@/init/restart-deps-preflight'
26
+ import { requestReloadWithFallback } from '@/reload'
14
27
 
15
28
  export const hostdCommand = defineCommand({
16
29
  meta: {
@@ -32,43 +45,43 @@ export const hostdCommand = defineCommand({
32
45
  // they must thread currentHostDaemon themselves to get the in-process
33
46
  // registration path. The daemon populates this holder once booted.
34
47
  const currentHostDaemonHolder = createCurrentHostDaemonHolder()
48
+ // The renewal cron writes a fresh credential to secrets.json, but the
49
+ // running adapter captured the old one in a client closure at start(). It
50
+ // has to be told to pick the new one up; bouncing that single adapter is
51
+ // enough, and leaves the rest of the agent's work untouched.
52
+ const applyRenewedCredential = async (
53
+ adapter: RenewableAdapter,
54
+ { containerName, cwd }: { containerName: string; cwd: string },
55
+ ): Promise<void> => {
56
+ const result = await applyCredentialRotation(
57
+ { containerName, cwd, adapter },
58
+ {
59
+ resolveHostPort,
60
+ resolveTuiToken,
61
+ requestReloadWithFallback,
62
+ restartContainer: async (input) => {
63
+ const currentHostDaemon = await currentHostDaemonHolder.ready()
64
+ return await hostdRestart({ ...input, currentHostDaemon })
65
+ },
66
+ },
67
+ )
68
+ writeLogLine(formatCredentialApply(adapter, containerName, result))
69
+ if (result.kind === 'failed') throw new Error(result.restartError)
70
+ }
71
+
35
72
  const kakaoRenewal = createKakaoRenewalManager({
36
73
  onLog: (event) => writeLogLine(formatLog(event)),
37
- onRenewalOk: async ({ containerName, cwd }) => {
38
- // Restart the container so the in-memory KakaoTalk LOCO client picks
39
- // up the renewed tokens from secrets.json. Without this, the cron
40
- // would write fresh tokens but the running adapter would keep using
41
- // the old token in its closure and still 401 at the ~7-day wall.
42
- const currentHostDaemon = await currentHostDaemonHolder.ready()
43
- const result = await hostdRestart({ containerName, cwd, currentHostDaemon })
44
- if (!result.ok) throw new Error(result.reason)
45
- },
74
+ onRenewalOk: async (input) => await applyRenewedCredential('kakaotalk', input),
46
75
  shouldRenew: ({ cwd }) => kakaoChannelConfigured(cwd),
47
76
  })
48
77
  const webexRenewal = createWebexRenewalManager({
49
78
  onLog: (event) => writeLogLine(formatLog(event)),
50
- onRenewalOk: async ({ containerName, cwd }) => {
51
- // Restart so the in-memory WebexClient picks up the renewed token from
52
- // secrets.json. Without this, the cron writes a fresh token but the
53
- // running adapter keeps the old token in its getToken closure and still
54
- // 401s on every outbound REST call + KMS key fetch.
55
- const currentHostDaemon = await currentHostDaemonHolder.ready()
56
- const result = await hostdRestart({ containerName, cwd, currentHostDaemon })
57
- if (!result.ok) throw new Error(result.reason)
58
- },
79
+ onRenewalOk: async (input) => await applyRenewedCredential('webex', input),
59
80
  shouldRenew: ({ cwd }) => webexChannelConfigured(cwd),
60
81
  })
61
82
  const teamsRenewal = createTeamsRenewalManager({
62
83
  onLog: (event) => writeLogLine(formatLog(event)),
63
- onRenewalOk: async ({ containerName, cwd }) => {
64
- // Restart so the in-memory TeamsClient picks up the renewed token from
65
- // secrets.json. Without this, the cron writes a fresh token but the
66
- // running adapter keeps the old token in its login closure and still
67
- // cannot obtain an id_token for the realtime listener.
68
- const currentHostDaemon = await currentHostDaemonHolder.ready()
69
- const result = await hostdRestart({ containerName, cwd, currentHostDaemon })
70
- if (!result.ok) throw new Error(result.reason)
71
- },
84
+ onRenewalOk: async (input) => await applyRenewedCredential('teams', input),
72
85
  shouldRenew: ({ cwd }) => teamsChannelConfigured(cwd),
73
86
  })
74
87
 
@@ -198,6 +211,21 @@ function writeLogLine(msg: string): void {
198
211
  console.log(`${new Date().toISOString()} ${msg}`)
199
212
  }
200
213
 
214
+ function formatCredentialApply(
215
+ adapter: RenewableAdapter,
216
+ containerName: string,
217
+ result: CredentialRotationApplyResult,
218
+ ): string {
219
+ const prefix = `[hostd] ${adapter} renewal`
220
+ if (result.kind === 'reloaded') {
221
+ return `${prefix} applied to ${containerName} via ${result.transport} reload (no container restart)`
222
+ }
223
+ if (result.kind === 'restarted') {
224
+ return `${prefix} fell back to a container restart for ${containerName}: ${result.reloadError}`
225
+ }
226
+ return `${prefix} could not be applied to ${containerName}: ${result.reloadError}; restart also failed: ${result.restartError}`
227
+ }
228
+
201
229
  function formatLog(event: DaemonLogEvent | SupervisorLogEvent): string {
202
230
  switch (event.kind) {
203
231
  case 'daemon-listening':
@@ -839,6 +839,16 @@ export function resolveModel(ref: KnownModelRef | ModelRef | string): Model<Know
839
839
  provider: providerId,
840
840
  baseUrl: provider.baseUrl ?? template.baseUrl,
841
841
  api: template.api,
842
+ // Carried from the template for the same reason `api` and `baseUrl` are:
843
+ // it describes the PROVIDER's wire dialect, not the model. pi-ai infers
844
+ // compat from the baseUrl and only recognises first-party hosts, so a
845
+ // custom ref on a provider that pins compat (OpenGateway, Upstage) would
846
+ // otherwise fall back to OpenAI-native defaults and send `store`, the
847
+ // `developer` role, `strict` tool schemas and `max_completion_tokens` to
848
+ // an endpoint that never accepts them. `thinkingLevelMap` is deliberately
849
+ // NOT carried: it varies per model even within one provider, so copying
850
+ // the template's would be a guess.
851
+ ...(template.compat !== undefined ? { compat: template.compat } : {}),
842
852
  name: meta?.name ?? modelId,
843
853
  reasoning: meta?.reasoning ?? false,
844
854
  input: resolveCustomModelInput(meta?.input),
@@ -1036,6 +1036,178 @@ export const KNOWN_PROVIDERS = {
1036
1036
  },
1037
1037
  },
1038
1038
  },
1039
+ // OpenGateway.ai (Sionic AI) — a multi-vendor LLM GATEWAY, not a lab. One
1040
+ // OpenAI-compatible surface (Bearer + /chat/completions) fronts OpenAI,
1041
+ // Anthropic, Google, Moonshot, MiniMax, DeepSeek, Z.AI, xAI, and Qwen, so by
1042
+ // the granularity rule above it is ONE provider id: one endpoint, one wire
1043
+ // transport, one key.
1044
+ //
1045
+ // Model ids are creator-qualified (`openai/gpt-5.5`, not `gpt-5.5`) — the
1046
+ // namespace is mandatory upstream. TypeClaw refs therefore carry two slashes:
1047
+ // `opengateway/anthropic/claude-sonnet-5`. That parses fine because
1048
+ // `providerForModelRef()` matches on the registered provider prefix, the same
1049
+ // mechanism that already handles the slash-heavy Fireworks router ids.
1050
+ //
1051
+ // Curation rule (why only six of the ~56 live chat models): every curated
1052
+ // entry mirrors a model THIS registry already prices natively, so the numbers
1053
+ // below are copied from a sibling entry rather than invented. Models with no
1054
+ // in-repo price (google/*, qwen/*) and models whose native reasoning contract
1055
+ // is NOT plain OpenAI `reasoning_effort` (deepseek's `thinking:{type}`,
1056
+ // z-ai/qwen's `enable_thinking`) are deliberately left out: pi-ai picks
1057
+ // thinkingFormat from the baseUrl, and `apis.opengateway.ai` resolves to
1058
+ // "openai", so routing those here would silently send the wrong reasoning
1059
+ // field. They all remain reachable as custom `opengateway/...` refs — curation
1060
+ // only drives the picker, JSON-schema enum, and autocomplete.
1061
+ //
1062
+ // Costs are UPSTREAM LIST PRICES in USD per 1M tokens, pinned to the sibling
1063
+ // entry by a guard test in providers.test.ts. OpenGateway bills upstream usage
1064
+ // plus a platform fee and exposes no pricing in /v1/models, so `typeclaw usage`
1065
+ // is an estimate that reads LOW against the real invoice. Do NOT "fix" these
1066
+ // to zero: zero means "no attributable per-token charge" in this registry
1067
+ // (flat-subscription products like the Fireworks Fire Pass router), and
1068
+ // OpenGateway is metered. Replace with gateway-billed rates only if
1069
+ // OpenGateway ever publishes them.
1070
+ //
1071
+ // Every model carries an explicit `compat` for the same reason Upstage does:
1072
+ // pi-ai auto-detects compatibility from the baseUrl, and `apis.opengateway.ai`
1073
+ // matches none of its known hosts, so it would otherwise assume a first-party
1074
+ // OpenAI endpoint and send `store`, the `developer` role, `strict` tool
1075
+ // schemas, and `max_completion_tokens` to a gateway fronting Anthropic and
1076
+ // Moonshot. `supportsUsageInStreaming` is deliberately left unset (pi-ai
1077
+ // defaults it true) — turning it off would break token and cost reporting.
1078
+ opengateway: {
1079
+ id: 'opengateway',
1080
+ name: 'OpenGateway.ai',
1081
+ baseUrl: 'https://apis.opengateway.ai/v1',
1082
+ auth: ['api-key'],
1083
+ apiKeyEnv: 'OPENGATEWAY_API_KEY',
1084
+ oauthProviderId: null,
1085
+ models: {
1086
+ // Mirrors openai/gpt-5.4-nano.
1087
+ 'openai/gpt-5.4-nano': {
1088
+ id: 'openai/gpt-5.4-nano',
1089
+ name: 'GPT-5.4 nano',
1090
+ api: 'openai-completions',
1091
+ provider: 'opengateway',
1092
+ baseUrl: 'https://apis.opengateway.ai/v1',
1093
+ reasoning: true,
1094
+ compat: {
1095
+ supportsStore: false,
1096
+ supportsDeveloperRole: false,
1097
+ supportsReasoningEffort: false,
1098
+ supportsStrictMode: false,
1099
+ maxTokensField: 'max_tokens',
1100
+ },
1101
+ input: ['text', 'image'],
1102
+ cost: { input: 0.2, output: 1.25, cacheRead: 0.02, cacheWrite: 0 },
1103
+ contextWindow: 400000,
1104
+ maxTokens: 128000,
1105
+ },
1106
+ // Mirrors openai/gpt-5.5.
1107
+ 'openai/gpt-5.5': {
1108
+ id: 'openai/gpt-5.5',
1109
+ name: 'GPT-5.5',
1110
+ api: 'openai-completions',
1111
+ provider: 'opengateway',
1112
+ baseUrl: 'https://apis.opengateway.ai/v1',
1113
+ reasoning: true,
1114
+ compat: {
1115
+ supportsStore: false,
1116
+ supportsDeveloperRole: false,
1117
+ supportsReasoningEffort: false,
1118
+ supportsStrictMode: false,
1119
+ maxTokensField: 'max_tokens',
1120
+ },
1121
+ input: ['text', 'image'],
1122
+ cost: { input: 5, output: 30, cacheRead: 0.5, cacheWrite: 0 },
1123
+ contextWindow: 1050000,
1124
+ maxTokens: 128000,
1125
+ },
1126
+ // Mirrors anthropic/claude-sonnet-5. Note the transport differs from the
1127
+ // native entry: Anthropic is `anthropic-messages` first-party, but the
1128
+ // gateway only speaks OpenAI chat-completions.
1129
+ 'anthropic/claude-sonnet-5': {
1130
+ id: 'anthropic/claude-sonnet-5',
1131
+ name: 'Claude Sonnet 5',
1132
+ api: 'openai-completions',
1133
+ provider: 'opengateway',
1134
+ baseUrl: 'https://apis.opengateway.ai/v1',
1135
+ reasoning: true,
1136
+ compat: {
1137
+ supportsStore: false,
1138
+ supportsDeveloperRole: false,
1139
+ supportsReasoningEffort: false,
1140
+ supportsStrictMode: false,
1141
+ maxTokensField: 'max_tokens',
1142
+ },
1143
+ input: ['text', 'image'],
1144
+ cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
1145
+ contextWindow: 1000000,
1146
+ maxTokens: 128000,
1147
+ },
1148
+ // Mirrors anthropic/claude-opus-4-8.
1149
+ 'anthropic/claude-opus-4-8': {
1150
+ id: 'anthropic/claude-opus-4-8',
1151
+ name: 'Claude Opus 4.8',
1152
+ api: 'openai-completions',
1153
+ provider: 'opengateway',
1154
+ baseUrl: 'https://apis.opengateway.ai/v1',
1155
+ reasoning: true,
1156
+ compat: {
1157
+ supportsStore: false,
1158
+ supportsDeveloperRole: false,
1159
+ supportsReasoningEffort: false,
1160
+ supportsStrictMode: false,
1161
+ maxTokensField: 'max_tokens',
1162
+ },
1163
+ input: ['text', 'image'],
1164
+ cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
1165
+ contextWindow: 1000000,
1166
+ maxTokens: 128000,
1167
+ },
1168
+ // Mirrors moonshot/kimi-k2.6. The gateway namespaces Moonshot as
1169
+ // `moonshotai`, so the id is NOT the native `kimi-k2.6`.
1170
+ 'moonshotai/kimi-k2.6': {
1171
+ id: 'moonshotai/kimi-k2.6',
1172
+ name: 'Kimi K2.6',
1173
+ api: 'openai-completions',
1174
+ provider: 'opengateway',
1175
+ baseUrl: 'https://apis.opengateway.ai/v1',
1176
+ reasoning: true,
1177
+ compat: {
1178
+ supportsStore: false,
1179
+ supportsDeveloperRole: false,
1180
+ supportsReasoningEffort: false,
1181
+ supportsStrictMode: false,
1182
+ maxTokensField: 'max_tokens',
1183
+ },
1184
+ input: ['text', 'image'],
1185
+ cost: { input: 0.6, output: 2.5, cacheRead: 0.15, cacheWrite: 0 },
1186
+ contextWindow: 256000,
1187
+ maxTokens: 64000,
1188
+ },
1189
+ // Mirrors minimax/MiniMax-M3.
1190
+ 'minimax/MiniMax-M3': {
1191
+ id: 'minimax/MiniMax-M3',
1192
+ name: 'MiniMax M3',
1193
+ api: 'openai-completions',
1194
+ provider: 'opengateway',
1195
+ baseUrl: 'https://apis.opengateway.ai/v1',
1196
+ reasoning: true,
1197
+ compat: {
1198
+ supportsStore: false,
1199
+ supportsDeveloperRole: false,
1200
+ supportsReasoningEffort: false,
1201
+ supportsStrictMode: false,
1202
+ maxTokensField: 'max_tokens',
1203
+ },
1204
+ input: ['text', 'image'],
1205
+ cost: { input: 0.3, output: 1.2, cacheRead: 0.06, cacheWrite: 0 },
1206
+ contextWindow: 1000000,
1207
+ maxTokens: 524288,
1208
+ },
1209
+ },
1210
+ },
1039
1211
  } as const satisfies Record<string, KnownProvider>
1040
1212
 
1041
1213
  export type KnownProviderId = keyof typeof KNOWN_PROVIDERS
@@ -1123,6 +1295,13 @@ export const KNOWN_PROVIDER_VENDORS = {
1123
1295
  'moonshot-coding': { label: 'Coding Plan', hint: 'Kimi Code subscription' },
1124
1296
  },
1125
1297
  },
1298
+ // Listed last because it is a reseller, not a lab: a user who knows they want
1299
+ // Anthropic should land on the Anthropic row, not the gateway that proxies it.
1300
+ opengateway: {
1301
+ id: 'opengateway',
1302
+ name: 'OpenGateway.ai (multi-vendor gateway)',
1303
+ providers: ['opengateway'],
1304
+ },
1126
1305
  } as const satisfies Record<string, KnownProviderVendor>
1127
1306
 
1128
1307
  export type KnownProviderVendorId = keyof typeof KNOWN_PROVIDER_VENDORS
@@ -0,0 +1,88 @@
1
+ import { constants } from 'node:fs'
2
+ import { access, realpath } from 'node:fs/promises'
3
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path'
4
+
5
+ export const TRUSTED_BASELINE_BIN_DIRS = ['/usr/local/bin', '/usr/bin', '/bin'] as const
6
+ export const DEPENDENCY_BIN_DENYLIST: ReadonlySet<string> = new Set(['typeclaw'])
7
+
8
+ export type DependencyBinDeclaration = {
9
+ package: string
10
+ bin: string
11
+ entry: string
12
+ workspace?: boolean
13
+ }
14
+
15
+ export type ResolvedDependencyBin =
16
+ | { kind: 'baseline'; declaration: DependencyBinDeclaration; executable: string }
17
+ | { kind: 'package'; declaration: DependencyBinDeclaration; entrypoint: string; containerEntrypoint: string }
18
+ | { kind: 'unavailable'; declaration: DependencyBinDeclaration; reason: string }
19
+ | { kind: 'denied'; declaration: DependencyBinDeclaration; reason: string }
20
+
21
+ export async function resolveDependencyBin(
22
+ agentDir: string,
23
+ declaration: DependencyBinDeclaration,
24
+ baselineDirs: readonly string[] = TRUSTED_BASELINE_BIN_DIRS,
25
+ deniedBins: ReadonlySet<string> = DEPENDENCY_BIN_DENYLIST,
26
+ ): Promise<ResolvedDependencyBin> {
27
+ if (deniedBins.has(declaration.bin)) {
28
+ return { kind: 'denied', declaration, reason: 'bin is denied by runtime policy' }
29
+ }
30
+ for (const dir of baselineDirs) {
31
+ const executable = join(dir, declaration.bin)
32
+ if (await isExecutable(executable)) return { kind: 'baseline', declaration, executable }
33
+ }
34
+
35
+ const agentRoot = await realpath(agentDir).catch(() => undefined)
36
+ const nodeModulesRoot = await realpath(join(agentDir, 'node_modules')).catch(() => undefined)
37
+ const packageRoot = join(agentDir, 'node_modules', ...declaration.package.split('/'))
38
+ const resolvedRoot = await realpath(packageRoot).catch(() => undefined)
39
+ if (agentRoot === undefined || nodeModulesRoot === undefined || resolvedRoot === undefined) {
40
+ return {
41
+ kind: 'unavailable',
42
+ declaration,
43
+ reason: `direct dependency ${declaration.package} is not installed`,
44
+ }
45
+ }
46
+ const resolvedEntry = await realpath(resolve(resolvedRoot, declaration.entry)).catch(() => undefined)
47
+ const packageRootAllowed =
48
+ isInside(nodeModulesRoot, resolvedRoot) || (declaration.workspace === true && isInside(agentRoot, resolvedRoot))
49
+ if (resolvedEntry === undefined || !packageRootAllowed || !isInside(resolvedRoot, resolvedEntry)) {
50
+ return {
51
+ kind: 'unavailable',
52
+ declaration,
53
+ reason: `direct dependency ${declaration.package} bin entry is missing or escapes its package`,
54
+ }
55
+ }
56
+ return {
57
+ kind: 'package',
58
+ declaration,
59
+ entrypoint: resolvedEntry,
60
+ // The agent directory is bound into bwrap at its original absolute path.
61
+ // /bin/sh consumes this path, so keep POSIX separators even in Windows tests;
62
+ // production sandbox execution itself is Linux-only.
63
+ containerEntrypoint: resolvedEntry.split(sep).join('/'),
64
+ }
65
+ }
66
+
67
+ export async function resolveDependencyBins(
68
+ agentDir: string,
69
+ declarations: readonly DependencyBinDeclaration[],
70
+ baselineDirs: readonly string[] = TRUSTED_BASELINE_BIN_DIRS,
71
+ deniedBins: ReadonlySet<string> = DEPENDENCY_BIN_DENYLIST,
72
+ ): Promise<ResolvedDependencyBin[]> {
73
+ return Promise.all(
74
+ declarations.map((declaration) => resolveDependencyBin(agentDir, declaration, baselineDirs, deniedBins)),
75
+ )
76
+ }
77
+
78
+ async function isExecutable(path: string): Promise<boolean> {
79
+ return access(path, constants.X_OK).then(
80
+ () => true,
81
+ () => false,
82
+ )
83
+ }
84
+
85
+ function isInside(parent: string, child: string): boolean {
86
+ const rel = relative(parent, child)
87
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
88
+ }
@@ -0,0 +1,227 @@
1
+ import { readFile, realpath } from 'node:fs/promises'
2
+ import { basename, isAbsolute, join, relative } from 'node:path'
3
+
4
+ import type { PluginLogger, PluginRegistry } from '@/plugin'
5
+
6
+ import {
7
+ DEPENDENCY_BIN_DENYLIST,
8
+ resolveDependencyBins,
9
+ type DependencyBinDeclaration,
10
+ type ResolvedDependencyBin,
11
+ } from './bin-resolver'
12
+
13
+ export { DEPENDENCY_BIN_DENYLIST } from './bin-resolver'
14
+
15
+ export type DependencyBinIssue = {
16
+ package?: string
17
+ message: string
18
+ }
19
+
20
+ export type DependencyBinDiscovery = {
21
+ declarations: DependencyBinDeclaration[]
22
+ issues: DependencyBinIssue[]
23
+ protectedFiles: string[]
24
+ }
25
+
26
+ export type DependencyBinValidation = DependencyBinDiscovery & {
27
+ resolutions: ResolvedDependencyBin[]
28
+ unavailable: Extract<ResolvedDependencyBin, { kind: 'unavailable' }>[]
29
+ }
30
+
31
+ const PACKAGE_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i
32
+ const BIN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
33
+
34
+ export async function discoverDependencyBins(agentDir: string): Promise<DependencyBinDiscovery> {
35
+ const rootManifestPath = join(agentDir, 'package.json')
36
+ const resolvedRootManifest = await realpath(rootManifestPath).catch(() => undefined)
37
+ const rootManifest = await readManifest(rootManifestPath)
38
+ if (!rootManifest.ok) {
39
+ return {
40
+ declarations: [],
41
+ issues: [{ message: rootManifest.message }],
42
+ protectedFiles: resolvedRootManifest === undefined ? [] : [resolvedRootManifest],
43
+ }
44
+ }
45
+ if (!isRecord(rootManifest.value)) {
46
+ return {
47
+ declarations: [],
48
+ issues: [{ message: 'agent package.json must contain an object' }],
49
+ protectedFiles: [resolvedRootManifest ?? rootManifestPath],
50
+ }
51
+ }
52
+ const dependencies = rootManifest.value.dependencies
53
+ if (dependencies === undefined) {
54
+ return { declarations: [], issues: [], protectedFiles: [resolvedRootManifest ?? rootManifestPath] }
55
+ }
56
+ if (!isRecord(dependencies)) {
57
+ return {
58
+ declarations: [],
59
+ issues: [{ message: 'agent package.json dependencies must be an object' }],
60
+ protectedFiles: [resolvedRootManifest ?? rootManifestPath],
61
+ }
62
+ }
63
+
64
+ const declarations: DependencyBinDeclaration[] = []
65
+ const issues: DependencyBinIssue[] = []
66
+ const protectedFiles = [resolvedRootManifest ?? rootManifestPath]
67
+ const agentRoot = await realpath(agentDir).catch(() => undefined)
68
+ const nodeModulesRoot = await realpath(join(agentDir, 'node_modules')).catch(() => undefined)
69
+ for (const packageName of Object.keys(dependencies).sort()) {
70
+ if (!PACKAGE_PATTERN.test(packageName)) {
71
+ issues.push({ package: packageName, message: 'direct dependency has an unsafe package name' })
72
+ continue
73
+ }
74
+ const workspace =
75
+ typeof dependencies[packageName] === 'string' && dependencies[packageName].startsWith('workspace:')
76
+ const packageRoot = join(agentDir, 'node_modules', ...packageName.split('/'))
77
+ const resolvedRoot = await realpath(packageRoot).catch(() => undefined)
78
+ const packageRootAllowed =
79
+ resolvedRoot !== undefined &&
80
+ ((nodeModulesRoot !== undefined && isInside(nodeModulesRoot, resolvedRoot)) ||
81
+ (workspace && agentRoot !== undefined && isInside(agentRoot, resolvedRoot)))
82
+ if (!packageRootAllowed) {
83
+ issues.push({ package: packageName, message: 'direct dependency is not installed in an allowed agent path' })
84
+ continue
85
+ }
86
+ const packageManifestPath = join(resolvedRoot, 'package.json')
87
+ const packageManifest = await readManifest(packageManifestPath)
88
+ if (!packageManifest.ok) {
89
+ issues.push({ package: packageName, message: packageManifest.message })
90
+ continue
91
+ }
92
+ if (!isRecord(packageManifest.value)) {
93
+ issues.push({ package: packageName, message: 'dependency package.json must contain an object' })
94
+ continue
95
+ }
96
+ const binEntries = packageBinEntries(packageManifest.value, packageName)
97
+ if (binEntries === undefined) continue
98
+ for (const [bin, entry] of binEntries) {
99
+ if (!BIN_PATTERN.test(bin) || typeof entry !== 'string') {
100
+ issues.push({ package: packageName, message: 'dependency package.json#bin contains an unsafe entry' })
101
+ continue
102
+ }
103
+ if (DEPENDENCY_BIN_DENYLIST.has(bin)) continue
104
+ declarations.push({ package: packageName, bin, entry, ...(workspace ? { workspace: true } : {}) })
105
+ }
106
+ }
107
+ const packagesByBin = new Map<string, string[]>()
108
+ for (const declaration of declarations) {
109
+ const packages = packagesByBin.get(declaration.bin) ?? []
110
+ packages.push(declaration.package)
111
+ packagesByBin.set(declaration.bin, packages)
112
+ }
113
+ const ambiguousBins = new Set<string>()
114
+ for (const [bin, packages] of packagesByBin) {
115
+ if (packages.length < 2) continue
116
+ ambiguousBins.add(bin)
117
+ issues.push({
118
+ message: `direct dependencies ${packages.join(', ')} expose duplicate bin ${bin}; no wrapper generated`,
119
+ })
120
+ }
121
+ return {
122
+ declarations: declarations.filter((entry) => !ambiguousBins.has(entry.bin)),
123
+ issues,
124
+ protectedFiles: [...new Set(protectedFiles)],
125
+ }
126
+ }
127
+
128
+ export async function validateDependencyBins(
129
+ agentDir: string,
130
+ baselineDirs?: readonly string[],
131
+ ): Promise<DependencyBinValidation> {
132
+ const discovery = await discoverDependencyBins(agentDir)
133
+ const resolutions = await resolveDependencyBins(
134
+ agentDir,
135
+ discovery.declarations,
136
+ baselineDirs,
137
+ DEPENDENCY_BIN_DENYLIST,
138
+ )
139
+ return {
140
+ ...discovery,
141
+ resolutions,
142
+ unavailable: resolutions.filter(
143
+ (resolution): resolution is Extract<ResolvedDependencyBin, { kind: 'unavailable' }> =>
144
+ resolution.kind === 'unavailable',
145
+ ),
146
+ }
147
+ }
148
+
149
+ export function registerDependencyBinDoctorCheck(
150
+ registry: PluginRegistry,
151
+ agentDir: string,
152
+ logger: PluginLogger,
153
+ ): void {
154
+ registry.doctorChecks.push({
155
+ pluginName: 'typeclaw',
156
+ checkName: 'dependency-bins',
157
+ pluginConfig: undefined,
158
+ logger,
159
+ check: {
160
+ description: 'direct dependency CLI binaries resolve inside the container',
161
+ category: 'runtime',
162
+ async run() {
163
+ const validation = await validateDependencyBins(agentDir)
164
+ const problems = dependencyBinProblemDetails(validation)
165
+ if (problems.length === 0) {
166
+ return { status: 'ok', message: `${validation.declarations.length} direct dependency bin(s) resolvable` }
167
+ }
168
+ return {
169
+ status: 'error',
170
+ message: `${problems.length} dependency bin problem(s)`,
171
+ details: problems,
172
+ fix: {
173
+ description:
174
+ 'On the host stage, run `bun install` in the agent folder and fix malformed dependency manifests, then restart TypeClaw.',
175
+ },
176
+ }
177
+ },
178
+ },
179
+ })
180
+ }
181
+
182
+ export function logDependencyBinProblems(validation: DependencyBinValidation, logger: PluginLogger): void {
183
+ for (const detail of dependencyBinProblemDetails(validation)) logger.warn(`[dependency-bin] ${detail}`)
184
+ }
185
+
186
+ function packageBinEntries(manifest: Record<string, unknown>, packageName: string): [string, unknown][] | undefined {
187
+ if (typeof manifest.bin === 'string') {
188
+ const manifestName = typeof manifest.name === 'string' ? manifest.name : packageName
189
+ return [[basename(manifestName), manifest.bin]]
190
+ }
191
+ return isRecord(manifest.bin) ? Object.entries(manifest.bin) : undefined
192
+ }
193
+
194
+ async function readManifest(path: string): Promise<{ ok: true; value: unknown } | { ok: false; message: string }> {
195
+ let text: string
196
+ try {
197
+ text = await readFile(path, 'utf8')
198
+ } catch {
199
+ return { ok: false, message: 'package.json is missing or unreadable' }
200
+ }
201
+ try {
202
+ return { ok: true, value: JSON.parse(text) }
203
+ } catch {
204
+ return { ok: false, message: 'package.json is malformed' }
205
+ }
206
+ }
207
+
208
+ function dependencyBinProblemDetails(validation: DependencyBinValidation): string[] {
209
+ return [
210
+ ...validation.issues.map((issue) =>
211
+ issue.package === undefined ? issue.message : `direct dependency ${issue.package}: ${issue.message}`,
212
+ ),
213
+ ...validation.unavailable.map(
214
+ (entry) =>
215
+ `direct dependency ${entry.declaration.package}: bin ${entry.declaration.bin} unavailable (${entry.reason})`,
216
+ ),
217
+ ]
218
+ }
219
+
220
+ function isInside(parent: string, child: string): boolean {
221
+ const rel = relative(parent, child)
222
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
223
+ }
224
+
225
+ function isRecord(value: unknown): value is Record<string, unknown> {
226
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
227
+ }
@@ -0,0 +1,17 @@
1
+ export {
2
+ discoverDependencyBins,
3
+ logDependencyBinProblems,
4
+ registerDependencyBinDoctorCheck,
5
+ validateDependencyBins,
6
+ type DependencyBinDiscovery,
7
+ type DependencyBinIssue,
8
+ type DependencyBinValidation,
9
+ } from './bins'
10
+ export {
11
+ DEPENDENCY_BIN_DENYLIST,
12
+ resolveDependencyBin,
13
+ resolveDependencyBins,
14
+ TRUSTED_BASELINE_BIN_DIRS,
15
+ type DependencyBinDeclaration,
16
+ type ResolvedDependencyBin,
17
+ } from './bin-resolver'
@@ -24,6 +24,7 @@ import { detectWsl, isWindows, isWindowsDriveMount, type WslInfo } from '@/share
24
24
 
25
25
  import { buildChannelChecks } from './channel-checks'
26
26
  import { agentFileOwnership, type FileOwnershipDeps } from './file-ownership'
27
+ import { buildOperationalIncidentChecks } from './operational-incidents'
27
28
  import type { DoctorCheck } from './types'
28
29
 
29
30
  export function buildStaticChecks(opts: { dockerExec?: DockerExec } & FileOwnershipDeps = {}): DoctorCheck[] {
@@ -47,6 +48,7 @@ export function buildStaticChecks(opts: { dockerExec?: DockerExec } & FileOwners
47
48
  windowsBindMount(),
48
49
  containerState(dockerExec),
49
50
  containerHostPort(),
51
+ ...buildOperationalIncidentChecks(),
50
52
  ...buildChannelChecks(),
51
53
  ]
52
54
  }