typeclaw 0.39.3 → 0.39.5

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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/agent/attention-escalation.ts +11 -1
  3. package/src/agent/index.ts +10 -14
  4. package/src/agent/model-fallback.ts +13 -4
  5. package/src/agent/provider-error.ts +36 -1
  6. package/src/agent/subagents.ts +34 -3
  7. package/src/agent/throttle-circuit.ts +50 -0
  8. package/src/agent/tools/channel-reply.ts +48 -3
  9. package/src/agent/tools/ddg.ts +40 -5
  10. package/src/agent/tools/keyed-semaphore.ts +114 -0
  11. package/src/agent/tools/search-retry.ts +82 -0
  12. package/src/agent/turn-runner.ts +162 -0
  13. package/src/bundled-plugins/explorer/explorer.ts +5 -0
  14. package/src/bundled-plugins/memory/README.md +14 -14
  15. package/src/bundled-plugins/memory/append-tool.ts +98 -8
  16. package/src/bundled-plugins/memory/dreaming.ts +1 -1
  17. package/src/bundled-plugins/memory/fragment-parser.ts +10 -3
  18. package/src/bundled-plugins/memory/load-memory.ts +28 -2
  19. package/src/bundled-plugins/memory/memory-logger.ts +21 -5
  20. package/src/bundled-plugins/memory/search-tool.ts +50 -7
  21. package/src/bundled-plugins/memory/stream-events.ts +23 -0
  22. package/src/bundled-plugins/memory/vector/hybrid.ts +9 -2
  23. package/src/bundled-plugins/reviewer/reviewer.ts +3 -1
  24. package/src/bundled-plugins/scout/scout.ts +5 -0
  25. package/src/bundled-plugins/security/index.ts +24 -1
  26. package/src/bundled-plugins/security/policies/cron-promotion.ts +94 -62
  27. package/src/bundled-plugins/security/policies/plugin-addition.ts +2 -4
  28. package/src/bundled-plugins/security/policies/role-promotion.ts +2 -4
  29. package/src/channels/adapters/github/permission-guidance.ts +18 -0
  30. package/src/channels/adapters/webex-bot.ts +26 -25
  31. package/src/channels/adapters/webex-prefetch-limiter.ts +120 -0
  32. package/src/channels/adapters/webex.ts +27 -30
  33. package/src/channels/manager.ts +64 -57
  34. package/src/channels/router.ts +134 -4
  35. package/src/channels/types.ts +8 -1
  36. package/src/cli/builtins.ts +6 -32
  37. package/src/cli/channel.ts +7 -11
  38. package/src/cli/command-meta.ts +93 -0
  39. package/src/cli/help.ts +24 -0
  40. package/src/cli/index.ts +34 -10
  41. package/src/cli/init.ts +2 -2
  42. package/src/cli/plugin-commands-dispatch.ts +7 -1
  43. package/src/config/config.ts +27 -1
  44. package/src/container/start.ts +22 -2
  45. package/src/hostd/daemon.ts +55 -26
  46. package/src/hostd/spawn.ts +53 -19
  47. package/src/permissions/permissions.ts +12 -0
  48. package/src/run/codex-fetch-observer.ts +11 -6
  49. package/src/secrets/oauth-xai.ts +2 -2
  50. package/src/server/index.ts +27 -2
  51. package/src/skills/typeclaw-channel-github/SKILL.md +59 -13
  52. package/src/skills/typeclaw-channels/SKILL.md +1 -1
  53. package/src/skills/typeclaw-config/SKILL.md +1 -0
  54. package/src/skills/typeclaw-cron/SKILL.md +9 -4
  55. package/src/skills/typeclaw-permissions/SKILL.md +18 -6
@@ -5,7 +5,7 @@ import { parseConfigJson } from '@/config'
5
5
  import { isBuiltinRoleName, type RoleConfig, type RolesConfig } from '@/permissions'
6
6
 
7
7
  import type { SecuritySeverity } from '../permissions'
8
- import { ACKNOWLEDGE_GUARDS, type SecurityBlock, isGuardAcknowledged } from '../policy'
8
+ import type { SecurityBlock } from '../policy'
9
9
 
10
10
  export const GUARD_ROLE_PROMOTION = 'rolePromotion'
11
11
  // Classified `medium` (silent-attack axis). Originally `high`; reclassified
@@ -88,8 +88,6 @@ export async function checkRolePromotionGuard(options: {
88
88
  const isTypeclawJson = await pathIsTypeclawJson(agentDir, targetPath)
89
89
  if (!isTypeclawJson) return undefined
90
90
 
91
- if (isGuardAcknowledged(args, GUARD_ROLE_PROMOTION)) return undefined
92
-
93
91
  const editRefusal = refuseRiskyEdit(tool, args, targetPath)
94
92
  if (editRefusal) return editRefusal
95
93
 
@@ -378,7 +376,7 @@ function buildBlockReason(tool: string, targetPath: string, findings: readonly R
378
376
  return [
379
377
  `Guard \`${GUARD_ROLE_PROMOTION}\` blocked ${tool} on ${sanitizeForReason(targetPath)}: this change is a privilege escalation — ${lines.join('; ')}.`,
380
378
  'Granting `owner` / `trusted` (or widening any role) gives the matched actor security-bypass capabilities, cron scheduling, channel respond, and operator-only subagent spawn. Even an operator running from TUI must not silently rewrite the access-control table based on a channel message: the canonical attack is a member-role speaker socially-engineering the agent into adding their own author-id to `roles.owner.match[]`, which the schema check accepts as valid.',
381
- `If this is genuinely intentional and the operator explicitly asked for it (not a channel message), retry with \`${ACKNOWLEDGE_GUARDS}.${GUARD_ROLE_PROMOTION}: true\` in the tool arguments.`,
379
+ 'This cannot be acknowledged away from an under-privileged session. The operator must make the change from a session that already resolves to `owner`/`trusted` (TUI, or a role granted `security.bypass.medium`), or claim the role out-of-band via `typeclaw role claim`.',
382
380
  ].join(' ')
383
381
  }
384
382
 
@@ -13,6 +13,24 @@ export type OutboundEndpointKind =
13
13
  | 'issue-reaction'
14
14
  | 'pr-review-comment-reaction'
15
15
 
16
+ // The required-permissions checklist shown verbatim during interactive GitHub
17
+ // channel setup (both `typeclaw init` and `typeclaw channel add github`). Kept
18
+ // here — the single owner of GitHub permission copy — so the init and
19
+ // channel-add flows can't drift apart (they did once: Actions was added to one
20
+ // and not the other). The labels mirror github.com's UI strings so a user can
21
+ // grep their settings page for the exact text. `includeWebhookNote` appends the
22
+ // "TypeClaw will create and manage the repository webhooks for you" reassurance,
23
+ // shown only on the first-setup prompts (not the rotate/switch prompts).
24
+ export function githubRequiredPermissionsNote(includeWebhookNote: boolean): string {
25
+ const webhooks = includeWebhookNote
26
+ ? 'Webhooks read/write (TypeClaw will create and manage the repository webhooks for you).'
27
+ : 'Webhooks read/write.'
28
+ return [
29
+ 'Required permissions: Issues read/write, Pull requests read/write, Discussions read/write (if used),',
30
+ `Actions read/write, Metadata read, and ${webhooks}`,
31
+ ].join('\n')
32
+ }
33
+
16
34
  // Parses webhook-register errors of the shape `list hooks failed: <status> <body>`.
17
35
  // Returns the status code when it matches the two shapes GitHub emits for
18
36
  // missing access on the list-hooks endpoint:
@@ -33,6 +33,7 @@ import { createWebexChannelNameResolver } from './webex-bot-channel-resolver'
33
33
  import { classifyInbound, type InboundDropReason, type WebexInboundMessage } from './webex-bot-classify'
34
34
  import { enrichWebexMessageReference } from './webex-bot-reference'
35
35
  import { resolveWebexBodyText } from './webex-format'
36
+ import { createWebexPrefetchLimiter, isWebexRateLimitError, type WebexPrefetchLimiter } from './webex-prefetch-limiter'
36
37
 
37
38
  export type WebexBotAdapterLogger = {
38
39
  info: (msg: string) => void
@@ -139,27 +140,39 @@ async function defaultReadFile(path: string): Promise<WebexOutboundFile> {
139
140
  return { content: Bun.file(path), filename: path.split('/').pop() ?? 'attachment' }
140
141
  }
141
142
 
142
- // See webex.ts: the bot client has no AbortSignal either, so a hung listMessages
143
- // is bounded by a tighter internal deadline than the router's 5s history ceiling.
144
- const WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS = 2500
145
-
146
143
  export function createWebexHistoryCallback(deps: {
147
144
  client: Pick<WebexBotClient, 'listMessages'>
148
145
  logger: WebexBotAdapterLogger
149
146
  botPersonIdRef: () => string | null
150
- timeoutMs?: number
147
+ limiter?: WebexPrefetchLimiter
151
148
  }): HistoryCallback {
152
- const timeoutMs = deps.timeoutMs ?? WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS
149
+ const limiter = deps.limiter ?? createWebexPrefetchLimiter()
150
+ const listMessages = (args: FetchHistoryArgs) =>
151
+ deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) })
152
+ const toHistory = (messages: WebexMessage[]): FetchHistoryResult => ({
153
+ ok: true,
154
+ messages: messages.map((m) => mapWebexHistoryMessage(m, deps.botPersonIdRef())).reverse(),
155
+ })
153
156
  return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
154
157
  try {
155
- const messages = await raceWithTimeout(
156
- deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) }),
157
- timeoutMs,
158
- '[webex-bot] history fetch',
159
- )
160
- return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, deps.botPersonIdRef())).reverse() }
158
+ // Only best-effort reads (cold-start prefetch, membership fallback) submit
159
+ // to the per-room limiter. Explicit channel_history reads bypass it so a
160
+ // user-initiated look-back is never declined by prefetch backpressure.
161
+ if (args.prefetch !== true) {
162
+ return toHistory(await listMessages(args))
163
+ }
164
+ const outcome = await limiter.run(args.chat, () => listMessages(args))
165
+ if (!outcome.admitted) {
166
+ deps.logger.info('[webex-bot] history prefetch skipped: rate-limit backpressure')
167
+ return { ok: false, error: 'prefetch skipped: rate-limit backpressure', skipReason: 'rate-limited' }
168
+ }
169
+ return toHistory(outcome.value)
161
170
  } catch (err) {
162
171
  const message = describe(err)
172
+ if (args.prefetch === true && isWebexRateLimitError(err)) {
173
+ deps.logger.info(`[webex-bot] history prefetch skipped: rate limited (${message})`)
174
+ return { ok: false, error: message, skipReason: 'rate-limited' }
175
+ }
163
176
  deps.logger.warn(`[webex-bot] history fetch failed: ${message}`)
164
177
  return { ok: false, error: message }
165
178
  }
@@ -204,7 +217,7 @@ export function createWebexMembershipResolver(deps: {
204
217
  } catch (err) {
205
218
  deps.logger.warn(`[webex-bot] membership room=${key.chat} failed: ${describe(err)}; deriving from recent history`)
206
219
  return await deriveMembershipFromHistory({
207
- fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit }),
220
+ fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit, prefetch: true }),
208
221
  now,
209
222
  })
210
223
  }
@@ -465,18 +478,6 @@ function describe(err: unknown): string {
465
478
  return err instanceof Error ? err.message : String(err)
466
479
  }
467
480
 
468
- async function raceWithTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {
469
- let timer: ReturnType<typeof setTimeout> | null = null
470
- const timeout = new Promise<never>((_, reject) => {
471
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
472
- })
473
- try {
474
- return await Promise.race([work, timeout])
475
- } finally {
476
- if (timer !== null) clearTimeout(timer)
477
- }
478
- }
479
-
480
481
  function dropHint(reason: InboundDropReason): string {
481
482
  switch (reason) {
482
483
  case 'empty_content':
@@ -0,0 +1,120 @@
1
+ // Webex's internal conversation API rate-limits reads PER ROOM, not per account:
2
+ // hammering one room's history returns HTTP 429 (x-ratelimit-limit ~3, Retry-After
3
+ // up to ~25s) while a different room served by the same token stays unaffected
4
+ // (verified empirically — saturating room A produced zero 429s on room B). The
5
+ // upstream agent-messenger SDK retries 429s, but its bucket tracker is reactive
6
+ // (it learns the limit only after a 429 lands) and its 3-retry budget cannot
7
+ // outlast a 25s window, so same-room pile-up — cold-start prefetch plus the
8
+ // membership resolver's deriveMembershipFromHistory fallback, both reading the
9
+ // same room — overflows the bucket and fails the prefetch.
10
+ //
11
+ // History prefetch is a context improvement, not liveness — the router skips it
12
+ // and the agent can call channel_history on demand later. So the fix is keyed by
13
+ // room: bound concurrent reads PER ROOM (independent rooms never wait on each
14
+ // other) and keep cold-start non-blocking with bounded admission ("admit fast or
15
+ // skip"), because starting then abandoning a listMessages we cannot cancel (the
16
+ // SDK exposes no AbortSignal) would only burn more quota on an orphaned fetch.
17
+
18
+ export type WebexPrefetchLimiter = {
19
+ // Runs `work` under the permit pool for `key` (the room id). If no slot frees
20
+ // within `admitTimeoutMs`, resolves to `{ admitted: false }` WITHOUT starting
21
+ // `work` — the caller then skips the prefetch. On admission, runs `work` and
22
+ // returns its result. Distinct keys never contend.
23
+ run<T>(key: string, work: () => Promise<T>): Promise<{ admitted: true; value: T } | { admitted: false }>
24
+ }
25
+
26
+ export type WebexPrefetchLimiterOptions = {
27
+ // Max concurrent reads PER ROOM. Defaults to 2: Webex's per-room cap is ~3, so
28
+ // 2 leaves headroom for the SDK's own retry traffic while still letting a
29
+ // prefetch and a membership-fallback read of the same room overlap.
30
+ concurrency?: number
31
+ // How long a queued caller waits for a slot before giving up and skipping.
32
+ // Defaults to 2500ms, matching the prior cold-fetch fail-fast posture so a
33
+ // backlog never stalls cold-start past the router's history ceiling.
34
+ admitTimeoutMs?: number
35
+ }
36
+
37
+ const DEFAULT_CONCURRENCY = 2
38
+ const DEFAULT_ADMIT_TIMEOUT_MS = 2500
39
+
40
+ export function createWebexPrefetchLimiter(options: WebexPrefetchLimiterOptions = {}): WebexPrefetchLimiter {
41
+ const concurrency = Math.max(1, Math.floor(options.concurrency ?? DEFAULT_CONCURRENCY))
42
+ const admitTimeoutMs = options.admitTimeoutMs ?? DEFAULT_ADMIT_TIMEOUT_MS
43
+
44
+ type Pool = { active: number; waiters: Array<() => void> }
45
+ const pools = new Map<string, Pool>()
46
+
47
+ const poolFor = (key: string): Pool => {
48
+ let pool = pools.get(key)
49
+ if (pool === undefined) {
50
+ pool = { active: 0, waiters: [] }
51
+ pools.set(key, pool)
52
+ }
53
+ return pool
54
+ }
55
+
56
+ const release = (key: string): void => {
57
+ const pool = pools.get(key)
58
+ if (pool === undefined) return
59
+ pool.active--
60
+ const next = pool.waiters.shift()
61
+ if (next) next()
62
+ // Drop idle pools so a long-lived limiter does not accumulate one entry per
63
+ // room ever seen.
64
+ else if (pool.active === 0 && pool.waiters.length === 0) pools.delete(key)
65
+ }
66
+
67
+ const acquire = (key: string): Promise<boolean> => {
68
+ const pool = poolFor(key)
69
+ if (pool.active < concurrency) {
70
+ pool.active++
71
+ return Promise.resolve(true)
72
+ }
73
+ return new Promise<boolean>((resolve) => {
74
+ let settled = false
75
+ const timer = setTimeout(() => {
76
+ if (settled) return
77
+ settled = true
78
+ const idx = pool.waiters.indexOf(grant)
79
+ if (idx >= 0) pool.waiters.splice(idx, 1)
80
+ resolve(false)
81
+ }, admitTimeoutMs)
82
+ const grant = (): void => {
83
+ if (settled) {
84
+ // Admitted after we already gave up: hand the freed slot to the next
85
+ // waiter so a timed-out grant never leaks a permanently-held slot.
86
+ release(key)
87
+ return
88
+ }
89
+ settled = true
90
+ clearTimeout(timer)
91
+ pool.active++
92
+ resolve(true)
93
+ }
94
+ pool.waiters.push(grant)
95
+ })
96
+ }
97
+
98
+ return {
99
+ async run<T>(key: string, work: () => Promise<T>): Promise<{ admitted: true; value: T } | { admitted: false }> {
100
+ const admitted = await acquire(key)
101
+ if (!admitted) return { admitted: false }
102
+ try {
103
+ return { admitted: true, value: await work() }
104
+ } finally {
105
+ release(key)
106
+ }
107
+ },
108
+ }
109
+ }
110
+
111
+ // The SDK throws WebexError with code 'rate_limited' once 429 retries are
112
+ // exhausted, and 'http_429' for a raw 429 that bypassed the retry path. Both mean
113
+ // the same thing to us: an expected, transient, non-fatal rate-limit skip — not an
114
+ // auth/network failure worth a warn. Matching on the SDK's code field (rather than
115
+ // the human message) keeps this stable across SDK message-wording changes.
116
+ export function isWebexRateLimitError(err: unknown): boolean {
117
+ if (typeof err !== 'object' || err === null) return false
118
+ const code = (err as { code?: unknown }).code
119
+ return code === 'rate_limited' || code === 'http_429'
120
+ }
@@ -37,6 +37,7 @@ import type { WebexAccountRecord } from '@/secrets/schema'
37
37
  import { createWebexChannelNameResolver } from './webex-channel-resolver'
38
38
  import { classifyInbound, type InboundDropReason, type WebexInboundMessage } from './webex-classify'
39
39
  import { resolveWebexBodyText } from './webex-format'
40
+ import { createWebexPrefetchLimiter, isWebexRateLimitError, type WebexPrefetchLimiter } from './webex-prefetch-limiter'
40
41
  import { enrichWebexMessageReference } from './webex-reference'
41
42
 
42
43
  export type WebexAdapterLogger = {
@@ -187,32 +188,40 @@ export function createTypingCallback(deps: {
187
188
  }
188
189
  }
189
190
 
190
- // The Webex REST/internal client offers no AbortSignal, so a hung `listMessages`
191
- // would otherwise block cold-start prefetch for the router's full 5s history
192
- // ceiling before degrading. Racing it against a tighter internal deadline lets
193
- // prefetch fall back to membership-derivation (or skip) seconds sooner, mirroring
194
- // the cold-fetch fail-fast posture the membership resolver already uses.
195
- const WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS = 2500
196
-
197
191
  export function createWebexHistoryCallback(deps: {
198
192
  client: Pick<WebexClient, 'listMessages'>
199
193
  logger: WebexAdapterLogger
200
194
  botPersonIdRef: () => string | null
201
- timeoutMs?: number
195
+ limiter?: WebexPrefetchLimiter
202
196
  }): HistoryCallback {
203
- const timeoutMs = deps.timeoutMs ?? WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS
197
+ const limiter = deps.limiter ?? createWebexPrefetchLimiter()
198
+ const listMessages = (args: FetchHistoryArgs) =>
199
+ deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) })
200
+ const toHistory = (messages: WebexMessage[]): FetchHistoryResult => {
201
+ const authorById = new Map(messages.map((m) => [m.ref, m.personRef]))
202
+ const botPersonId = deps.botPersonIdRef()
203
+ return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, botPersonId, authorById)).reverse() }
204
+ }
204
205
  return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
205
206
  try {
206
- const messages = await raceWithTimeout(
207
- deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) }),
208
- timeoutMs,
209
- '[webex] history fetch',
210
- )
211
- const authorById = new Map(messages.map((m) => [m.ref, m.personRef]))
212
- const botPersonId = deps.botPersonIdRef()
213
- return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, botPersonId, authorById)).reverse() }
207
+ // Only best-effort reads (cold-start prefetch, membership fallback) submit
208
+ // to the per-room limiter. Explicit channel_history reads bypass it so a
209
+ // user-initiated look-back is never declined by prefetch backpressure.
210
+ if (args.prefetch !== true) {
211
+ return toHistory(await listMessages(args))
212
+ }
213
+ const outcome = await limiter.run(args.chat, () => listMessages(args))
214
+ if (!outcome.admitted) {
215
+ deps.logger.info('[webex] history prefetch skipped: rate-limit backpressure')
216
+ return { ok: false, error: 'prefetch skipped: rate-limit backpressure', skipReason: 'rate-limited' }
217
+ }
218
+ return toHistory(outcome.value)
214
219
  } catch (err) {
215
220
  const message = describe(err)
221
+ if (args.prefetch === true && isWebexRateLimitError(err)) {
222
+ deps.logger.info(`[webex] history prefetch skipped: rate limited (${message})`)
223
+ return { ok: false, error: message, skipReason: 'rate-limited' }
224
+ }
216
225
  deps.logger.warn(`[webex] history fetch failed: ${message}`)
217
226
  return { ok: false, error: message }
218
227
  }
@@ -257,7 +266,7 @@ export function createWebexMembershipResolver(deps: {
257
266
  } catch (err) {
258
267
  deps.logger.warn(`[webex] membership room=${key.chat} failed: ${describe(err)}; deriving from recent history`)
259
268
  return await deriveMembershipFromHistory({
260
- fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit }),
269
+ fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit, prefetch: true }),
261
270
  now,
262
271
  })
263
272
  }
@@ -549,18 +558,6 @@ function describe(err: unknown): string {
549
558
  return err instanceof Error ? err.message : String(err)
550
559
  }
551
560
 
552
- async function raceWithTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {
553
- let timer: ReturnType<typeof setTimeout> | null = null
554
- const timeout = new Promise<never>((_, reject) => {
555
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
556
- })
557
- try {
558
- return await Promise.race([work, timeout])
559
- } finally {
560
- if (timer !== null) clearTimeout(timer)
561
- }
562
- }
563
-
564
561
  function dropHint(reason: InboundDropReason): string {
565
562
  switch (reason) {
566
563
  case 'empty_content':
@@ -261,48 +261,58 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
261
261
  })
262
262
  }
263
263
  if (name === 'line') {
264
+ const credentialsStore = createContainerLineCredentialStore(options.agentDir, env)
265
+ if (credentialsStore === null) return null
264
266
  return createLine({
265
267
  router,
266
268
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
267
269
  logger,
268
270
  selfAliasesRef: () => router.getSelfAliases(),
269
- credentialsStore: createContainerLineCredentialStore(options.agentDir, env),
271
+ credentialsStore,
270
272
  })
271
273
  }
272
274
  if (name === 'kakaotalk') {
275
+ const credentialsStore = createContainerKakaoCredentialStore(options.agentDir, env)
276
+ if (credentialsStore === null) return null
273
277
  return createKakaotalk({
274
278
  router,
275
279
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
276
280
  logger,
277
281
  selfAliasesRef: () => router.getSelfAliases(),
278
- credentialsStore: createContainerKakaoCredentialStore(options.agentDir, env),
282
+ credentialsStore,
279
283
  })
280
284
  }
281
285
  if (name === 'slack') {
286
+ const credentialsStore = createContainerSlackCredentialStore(options.agentDir, env)
287
+ if (credentialsStore === null) return null
282
288
  return createSlackUser({
283
289
  router,
284
290
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
285
291
  logger,
286
292
  selfAliasesRef: () => router.getSelfAliases(),
287
- credentialsStore: createContainerSlackCredentialStore(options.agentDir, env),
293
+ credentialsStore,
288
294
  })
289
295
  }
290
296
  if (name === 'discord') {
297
+ const credentialsStore = createContainerDiscordCredentialStore(options.agentDir, env)
298
+ if (credentialsStore === null) return null
291
299
  return createDiscordUser({
292
300
  router,
293
301
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
294
302
  logger,
295
303
  selfAliasesRef: () => router.getSelfAliases(),
296
- credentialsStore: createContainerDiscordCredentialStore(options.agentDir, env),
304
+ credentialsStore,
297
305
  })
298
306
  }
299
307
  if (name === 'webex') {
308
+ const credentialsStore = createContainerWebexCredentialStore(options.agentDir, env)
309
+ if (credentialsStore === null) return null
300
310
  return createWebex({
301
311
  router,
302
312
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
303
313
  logger,
304
314
  selfAliasesRef: () => router.getSelfAliases(),
305
- credentialsStore: createContainerWebexCredentialStore(options.agentDir, env),
315
+ credentialsStore,
306
316
  })
307
317
  }
308
318
  if (name === 'github') {
@@ -538,22 +548,33 @@ const TOKEN_ENV: Record<
538
548
  'webex-bot': ['WEBEX_BOT_TOKEN'],
539
549
  }
540
550
 
541
- function createContainerDiscordCredentialStore(
542
- agentDir: string,
543
- env: NodeJS.ProcessEnv,
544
- ): SecretsDiscordCredentialStore {
551
+ // Personal-account adapters (line/kakaotalk/slack/discord/webex) need the hostd
552
+ // triple the host CLI injects at `docker run` time, gated on a successful daemon
553
+ // registration (src/container/start.ts). If the daemon wasn't reachable at
554
+ // launch (e.g. a lost first-boot spawn race) the triple is absent; null lets
555
+ // buildAdapter skip the adapter instead of throwing and crashing the whole
556
+ // channel manager. startAdapter's signature pre-check only reads secrets.json,
557
+ // so this is the only place the missing triple is caught.
558
+ type HostdContainerCredentials = { hostdUrl: string; restartToken: string; containerName: string }
559
+
560
+ function resolveHostdContainerCredentials(env: NodeJS.ProcessEnv): HostdContainerCredentials | null {
545
561
  const hostdUrl = env.TYPECLAW_HOSTD_URL
546
562
  const restartToken = env.TYPECLAW_HOSTD_TOKEN
547
563
  const containerName = env.TYPECLAW_CONTAINER_NAME
548
- if (!hostdUrl || !restartToken || !containerName) {
549
- throw new Error('Discord credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME')
550
- }
564
+ if (!hostdUrl || !restartToken || !containerName) return null
565
+ return { hostdUrl, restartToken, containerName }
566
+ }
567
+
568
+ function createContainerDiscordCredentialStore(
569
+ agentDir: string,
570
+ env: NodeJS.ProcessEnv,
571
+ ): SecretsDiscordCredentialStore | null {
572
+ const creds = resolveHostdContainerCredentials(env)
573
+ if (creds === null) return null
551
574
  return new SecretsDiscordCredentialStore({
552
575
  mode: 'container',
553
576
  secretsPath: join(agentDir, 'secrets.json'),
554
- hostdUrl,
555
- restartToken,
556
- containerName,
577
+ ...creds,
557
578
  })
558
579
  }
559
580
 
@@ -571,19 +592,16 @@ function buildDiscordSignature(agentDir: string): { signature: string; missing:
571
592
  }
572
593
  }
573
594
 
574
- function createContainerSlackCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsSlackCredentialStore {
575
- const hostdUrl = env.TYPECLAW_HOSTD_URL
576
- const restartToken = env.TYPECLAW_HOSTD_TOKEN
577
- const containerName = env.TYPECLAW_CONTAINER_NAME
578
- if (!hostdUrl || !restartToken || !containerName) {
579
- throw new Error('Slack credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME')
580
- }
595
+ function createContainerSlackCredentialStore(
596
+ agentDir: string,
597
+ env: NodeJS.ProcessEnv,
598
+ ): SecretsSlackCredentialStore | null {
599
+ const creds = resolveHostdContainerCredentials(env)
600
+ if (creds === null) return null
581
601
  return new SecretsSlackCredentialStore({
582
602
  mode: 'container',
583
603
  secretsPath: join(agentDir, 'secrets.json'),
584
- hostdUrl,
585
- restartToken,
586
- containerName,
604
+ ...creds,
587
605
  })
588
606
  }
589
607
 
@@ -601,19 +619,16 @@ function buildSlackSignature(agentDir: string): { signature: string; missing: st
601
619
  }
602
620
  }
603
621
 
604
- function createContainerWebexCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsWebexCredentialStore {
605
- const hostdUrl = env.TYPECLAW_HOSTD_URL
606
- const restartToken = env.TYPECLAW_HOSTD_TOKEN
607
- const containerName = env.TYPECLAW_CONTAINER_NAME
608
- if (!hostdUrl || !restartToken || !containerName) {
609
- throw new Error('Webex credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME')
610
- }
622
+ function createContainerWebexCredentialStore(
623
+ agentDir: string,
624
+ env: NodeJS.ProcessEnv,
625
+ ): SecretsWebexCredentialStore | null {
626
+ const creds = resolveHostdContainerCredentials(env)
627
+ if (creds === null) return null
611
628
  return new SecretsWebexCredentialStore({
612
629
  mode: 'container',
613
630
  secretsPath: join(agentDir, 'secrets.json'),
614
- hostdUrl,
615
- restartToken,
616
- containerName,
631
+ ...creds,
617
632
  })
618
633
  }
619
634
 
@@ -631,21 +646,16 @@ function buildWebexSignature(agentDir: string): { signature: string; missing: st
631
646
  }
632
647
  }
633
648
 
634
- function createContainerKakaoCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsKakaoCredentialStore {
635
- const hostdUrl = env.TYPECLAW_HOSTD_URL
636
- const restartToken = env.TYPECLAW_HOSTD_TOKEN
637
- const containerName = env.TYPECLAW_CONTAINER_NAME
638
- if (!hostdUrl || !restartToken || !containerName) {
639
- throw new Error(
640
- 'KakaoTalk credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME',
641
- )
642
- }
649
+ function createContainerKakaoCredentialStore(
650
+ agentDir: string,
651
+ env: NodeJS.ProcessEnv,
652
+ ): SecretsKakaoCredentialStore | null {
653
+ const creds = resolveHostdContainerCredentials(env)
654
+ if (creds === null) return null
643
655
  return new SecretsKakaoCredentialStore({
644
656
  mode: 'container',
645
657
  secretsPath: join(agentDir, 'secrets.json'),
646
- hostdUrl,
647
- restartToken,
648
- containerName,
658
+ ...creds,
649
659
  })
650
660
  }
651
661
 
@@ -663,19 +673,16 @@ function buildKakaotalkSignature(agentDir: string): { signature: string; missing
663
673
  }
664
674
  }
665
675
 
666
- function createContainerLineCredentialStore(agentDir: string, env: NodeJS.ProcessEnv): SecretsLineCredentialStore {
667
- const hostdUrl = env.TYPECLAW_HOSTD_URL
668
- const restartToken = env.TYPECLAW_HOSTD_TOKEN
669
- const containerName = env.TYPECLAW_CONTAINER_NAME
670
- if (!hostdUrl || !restartToken || !containerName) {
671
- throw new Error('LINE credentials require TYPECLAW_HOSTD_URL, TYPECLAW_HOSTD_TOKEN, and TYPECLAW_CONTAINER_NAME')
672
- }
676
+ function createContainerLineCredentialStore(
677
+ agentDir: string,
678
+ env: NodeJS.ProcessEnv,
679
+ ): SecretsLineCredentialStore | null {
680
+ const creds = resolveHostdContainerCredentials(env)
681
+ if (creds === null) return null
673
682
  return new SecretsLineCredentialStore({
674
683
  mode: 'container',
675
684
  secretsPath: join(agentDir, 'secrets.json'),
676
- hostdUrl,
677
- restartToken,
678
- containerName,
685
+ ...creds,
679
686
  })
680
687
  }
681
688