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
@@ -9,6 +9,8 @@ const SECRETS_FILE = 'secrets.json'
9
9
 
10
10
  export const CHANNEL_KINDS = [
11
11
  'slack-bot',
12
+ 'slack',
13
+ 'discord',
12
14
  'discord-bot',
13
15
  'telegram-bot',
14
16
  'webex',
@@ -187,7 +189,7 @@ function buildDetail(kind: ChannelKind, channelConfig: unknown, secretsBlock: un
187
189
  const repos = isObjectRecord(channelConfig) && Array.isArray(channelConfig.repos) ? channelConfig.repos.length : 0
188
190
  return { detail: `${repos} repo${repos === 1 ? '' : 's'}` }
189
191
  }
190
- if (kind === 'line' || kind === 'kakaotalk' || kind === 'webex') {
192
+ if (kind === 'line' || kind === 'kakaotalk' || kind === 'webex' || kind === 'discord') {
191
193
  if (!isObjectRecord(secretsBlock)) return {}
192
194
  const accounts = isObjectRecord(secretsBlock.accounts) ? Object.keys(secretsBlock.accounts).length : 0
193
195
  const current = typeof secretsBlock.currentAccount === 'string' ? secretsBlock.currentAccount : undefined
@@ -495,6 +495,22 @@ export const composeSchema = z
495
495
 
496
496
  export type ComposeConfig = z.infer<typeof composeSchema>
497
497
 
498
+ // Host-stage update-checker knob. `enabled: false` turns off the once-a-day
499
+ // "a newer typeclaw is on npm" notice the host CLI prints before a command
500
+ // runs. The container never reads this — the check is a pure host-stage
501
+ // affordance that compares the installed CLI version against the npm registry
502
+ // off the hot path (a detached, throttled background refresh writes a cache
503
+ // under ~/.typeclaw/; every CLI invocation only does a disk read). Env
504
+ // overrides (TYPECLAW_NO_UPDATE_CHECK, NO_UPDATE_NOTIFIER, CI) also disable it
505
+ // without touching config, so this field is the persistent opt-out.
506
+ export const updateCheckSchema = z
507
+ .object({
508
+ enabled: z.boolean().default(true),
509
+ })
510
+ .default({ enabled: true })
511
+
512
+ export type UpdateCheckConfig = z.infer<typeof updateCheckSchema>
513
+
498
514
  // Reverse-proxy tunnels expose a container-private port to the public internet
499
515
  // via a managed subprocess (cloudflared) or a user-supplied external URL.
500
516
  // See AGENTS.md `## Tunnels`. Keeping the enum scoped to what's implemented
@@ -691,13 +707,39 @@ const profileEntrySchema = z
691
707
  return value.thinkingLevel === undefined ? { refs } : { refs, thinkingLevel: value.thinkingLevel }
692
708
  })
693
709
 
710
+ // Built-in per-profile `thinkingLevel` defaults, materialized at parse time so
711
+ // resolved config / `typeclaw model list` / prompt dumps show the effective level
712
+ // and users can override per profile. Materialized here (not as a runtime
713
+ // constant) the `deep: 'high'` default rides on the `deep` entry itself, so it
714
+ // still beats a lowered `models.default.thinkingLevel` (resolution reads the
715
+ // profile's own level first). `default` and `vision` carry none — they fall
716
+ // through to the model/SDK default. `high` over `xhigh`: `xhigh` ~doubles latency
717
+ // and spend for no agentic-quality gain.
718
+ const PROFILE_THINKING_LEVEL_DEFAULTS = {
719
+ fast: 'low',
720
+ deep: 'high',
721
+ } satisfies Partial<Record<string, ThinkingLevel>>
722
+
694
723
  export const modelsSchema = z
695
724
  .record(z.string().min(1), profileEntrySchema)
696
725
  .refine((m) => 'default' in m, { message: 'models.default is required' })
726
+ // Fill only when unset, so an explicit level (including `off`) always wins.
727
+ .transform((models): Models => {
728
+ let next: Record<string, ProfileEntry> | undefined
729
+ for (const [profile, thinkingLevel] of Object.entries(PROFILE_THINKING_LEVEL_DEFAULTS)) {
730
+ const entry = models[profile]
731
+ if (entry !== undefined && entry.thinkingLevel === undefined) {
732
+ next ??= { ...models }
733
+ next[profile] = { ...entry, thinkingLevel }
734
+ }
735
+ }
736
+ return (next ?? models) as Models
737
+ })
697
738
 
698
739
  // A model profile after normalisation: its fallback chain (always non-empty)
699
740
  // plus an optional reasoning effort. `thinkingLevel` resolution is layered at
700
- // session creation: profile's own → `default` profile's → SDK default.
741
+ // session creation: profile's own (incl. built-in per-profile defaults
742
+ // materialized above) → `default` profile's → SDK default.
701
743
  export type ProfileEntry = {
702
744
  refs: ModelRef[]
703
745
  thinkingLevel?: ThinkingLevel
@@ -735,6 +777,7 @@ export const configSchema = z
735
777
  // here, so a freshly-hatched bot already has its identity wired up.
736
778
  alias: z.array(z.string().trim().min(1)).default([]),
737
779
  compose: composeSchema,
780
+ updateCheck: updateCheckSchema,
738
781
  channels: channelsSchema,
739
782
  portForward: portForwardSchema,
740
783
  network: networkSchema,
@@ -951,6 +994,7 @@ export const FIELD_EFFECTS: Record<string, FieldEffect> = {
951
994
  plugins: 'restart-required',
952
995
  alias: 'applied',
953
996
  compose: 'ignored',
997
+ updateCheck: 'ignored',
954
998
  channels: 'applied',
955
999
  portForward: 'restart-required',
956
1000
  network: 'restart-required',
@@ -1045,6 +1089,7 @@ export function extractPluginConfigs(raw: unknown): Record<string, unknown> {
1045
1089
  'plugins',
1046
1090
  'alias',
1047
1091
  'compose',
1092
+ 'updateCheck',
1048
1093
  'channels',
1049
1094
  'portForward',
1050
1095
  'network',
@@ -1110,6 +1155,38 @@ export function loadConfigSync(cwd: string): Config {
1110
1155
  return result.data
1111
1156
  }
1112
1157
 
1158
+ // Single-read variant of loadConfigSync + loadPluginConfigsSync for the boot
1159
+ // path, which otherwise reads + parses + migrates typeclaw.json twice. Throws on
1160
+ // invalid JSON / failed schema parse and returns defaults + `{}` on a missing
1161
+ // file, matching loadConfigSync.
1162
+ export function loadConfigBundleSync(cwd: string): { config: Config; pluginConfigs: Record<string, unknown> } {
1163
+ let raw: string
1164
+ try {
1165
+ raw = readFileSync(join(cwd, CONFIG_FILE), 'utf8')
1166
+ } catch {
1167
+ return { config: configSchema.parse({}), pluginConfigs: {} }
1168
+ }
1169
+
1170
+ let json: unknown
1171
+ try {
1172
+ json = JSON.parse(raw)
1173
+ } catch (error) {
1174
+ const detail = error instanceof Error ? error.message : String(error)
1175
+ throw new Error(`${CONFIG_FILE} is not valid JSON: ${detail}`)
1176
+ }
1177
+
1178
+ const migrated = migrateLegacyConfigShape(json)
1179
+ if (migrated.changed) {
1180
+ persistMigratedConfig(cwd, migrated.json, migrated.applied)
1181
+ }
1182
+
1183
+ const result = configSchema.safeParse(migrated.json)
1184
+ if (!result.success) {
1185
+ throw new Error(`${CONFIG_FILE} is invalid: ${formatZodError(result.error)}`)
1186
+ }
1187
+ return { config: result.data, pluginConfigs: extractPluginConfigs(migrated.json) }
1188
+ }
1189
+
1113
1190
  // Strips a `channels.github.eventAllowlist` that deep-equals a value `channel
1114
1191
  // add` / `init` previously seeded verbatim, so the config re-tracks the shipped
1115
1192
  // default. Called from every entry point that reads `typeclaw.json` so the rest
@@ -15,6 +15,7 @@ export {
15
15
  GWS_MULTI_ACCOUNT_PLUGIN_PACKAGE,
16
16
  GWS_MULTI_ACCOUNT_PLUGIN_VERSION,
17
17
  thinkingLevelSchema,
18
+ loadConfigBundleSync,
18
19
  loadConfigSync,
19
20
  loadConfigSyncOrDefaults,
20
21
  loadPluginConfigsSync,
@@ -2,7 +2,7 @@ import { randomBytes } from 'node:crypto'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
4
4
  import { tmpdir } from 'node:os'
5
- import { isAbsolute, join, resolve } from 'node:path'
5
+ import { isAbsolute, join, relative, resolve } from 'node:path'
6
6
 
7
7
  import { agentUsesVector } from '@/bundled-plugins/memory/vector/config'
8
8
  import { expandMountPath, loadConfigSync, withDefaultPlugins, type Config } from '@/config'
@@ -12,7 +12,7 @@ import { send as sendToDaemon } from '@/hostd/client'
12
12
  import { ensureModels } from '@/hostd/models'
13
13
  import { homeRoot } from '@/hostd/paths'
14
14
  import type { HttpInfoResult } from '@/hostd/protocol'
15
- import { ensureDaemon } from '@/hostd/spawn'
15
+ import { ensureDaemon, type EnsureDaemonResult } from '@/hostd/spawn'
16
16
  import {
17
17
  autoUpgradeTypeclawDep,
18
18
  type AutoUpgradeOutcome,
@@ -716,7 +716,7 @@ export async function planStart({
716
716
 
717
717
  if (shouldMirrorDevSource(devSourcePath, cwd, platform)) {
718
718
  runArgs.push(...dockerBindMount({ src: devSourcePath, dst: devSourcePath, readonly: true }))
719
- } else if (shouldMountWindowsDevSource(devSourcePath, platform)) {
719
+ } else if (shouldMountWindowsDevSource(devSourcePath, cwd, platform)) {
720
720
  runArgs.push(...dockerBindMount({ src: devSourcePath, dst: DEV_SOURCE_CONTAINER_PATH, readonly: true }))
721
721
  }
722
722
 
@@ -767,8 +767,16 @@ export async function refreshDockerfile(
767
767
  opts: { buildKit?: boolean } = {},
768
768
  ): Promise<{ changed: boolean; warnings: string[] }> {
769
769
  const cfg = await loadTypeclawConfig(cwd)
770
+ // A local-spec (`file:`/`link:`) dev install must inline the heavy stack: its
771
+ // unreleased version has no published `typeclaw-base` tag, and
772
+ // resolveBaseImageVersion prefers node_modules/typeclaw/package.json#version —
773
+ // which `ensureDeps` has already materialized by the time start() calls this —
774
+ // so without the gate a release-shaped dev version pins a nonexistent
775
+ // `FROM ghcr.io/...:<version>`. `null` selects the inline `oven/bun:1-slim`
776
+ // path. Mirrors the same gate in writeDockerAssets (src/init/index.ts).
777
+ const devMode = await hasLocallyLinkedTypeclawDep(cwd)
770
778
  const next = buildDockerfile(cfg.docker.file, {
771
- baseImageVersion: resolveBaseImageVersion(cwd),
779
+ baseImageVersion: devMode ? null : resolveBaseImageVersion(cwd),
772
780
  cjkFontsAuto: hostLocaleIsCjk(),
773
781
  buildKit: opts.buildKit,
774
782
  })
@@ -1060,6 +1068,18 @@ async function detectDevSource(cwd: string): Promise<string | null> {
1060
1068
  }
1061
1069
  }
1062
1070
 
1071
+ // True when `child` is `parent` itself or nested beneath it. Lexical, not
1072
+ // realpath-aware — callers pass already-resolved absolute paths. Preferred over
1073
+ // `child.startsWith(parent)`, which mis-fires on sibling-prefix collisions
1074
+ // (`C:\foo` vs `C:\foobar`), trailing-separator skew, and would treat
1075
+ // `/srv/agentX` as inside `/srv/agent`. A dev source already inside the agent
1076
+ // folder is reachable through the `/agent` bind mount, so neither dev-source
1077
+ // branch should add a second mount for it.
1078
+ export function isPathInsideOrEqual(child: string, parent: string): boolean {
1079
+ const rel = relative(parent, child)
1080
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
1081
+ }
1082
+
1063
1083
  // POSIX dev mode: node_modules/typeclaw is a symlink to an absolute host path
1064
1084
  // outside /agent. The mirror mount bind-mounts that path at the SAME path inside
1065
1085
  // the (Linux) container so the symlink resolves. That only works when the host
@@ -1074,7 +1094,7 @@ export function shouldMirrorDevSource(
1074
1094
  cwd: string,
1075
1095
  platform: NodeJS.Platform = process.platform,
1076
1096
  ): devSourcePath is string {
1077
- return devSourcePath !== null && !devSourcePath.startsWith(cwd) && !isWindows(platform)
1097
+ return devSourcePath !== null && !isPathInsideOrEqual(devSourcePath, cwd) && !isWindows(platform)
1078
1098
  }
1079
1099
 
1080
1100
  // Native-Windows dev mode (#899): the host's `C:\...` checkout cannot be
@@ -1082,12 +1102,16 @@ export function shouldMirrorDevSource(
1082
1102
  // checkout directly over the standard resolution path `/agent/node_modules/
1083
1103
  // typeclaw` inside the container, so Node/Bun resolve typeclaw from source
1084
1104
  // regardless of how the host materialized node_modules/typeclaw (a junction,
1085
- // per prepareWindowsDevJunction).
1105
+ // per prepareWindowsDevJunction). Like the POSIX branch, skip when the dev
1106
+ // source lives inside the agent folder: a `file:./vendor/typeclaw` checkout is
1107
+ // already exposed via the `/agent` mount, so a second mount is wrong. A
1108
+ // bun-linked (`link:`) checkout legitimately lives outside cwd and still mounts.
1086
1109
  export function shouldMountWindowsDevSource(
1087
1110
  devSourcePath: string | null,
1111
+ cwd: string,
1088
1112
  platform: NodeJS.Platform = process.platform,
1089
1113
  ): devSourcePath is string {
1090
- return devSourcePath !== null && isWindows(platform)
1114
+ return devSourcePath !== null && !isPathInsideOrEqual(devSourcePath, cwd) && isWindows(platform)
1091
1115
  }
1092
1116
 
1093
1117
  // True when the agent's package.json declares typeclaw via `file:` or
@@ -1141,7 +1165,7 @@ async function registerWithDaemon({
1141
1165
  hostPort: number
1142
1166
  reuseCurrentHostDaemon: boolean
1143
1167
  }): Promise<PreparedHostDaemonStatus> {
1144
- const prepared = reuseCurrentHostDaemon ? await useCurrentHostDaemon() : await ensureDaemon({ cliEntry })
1168
+ const prepared = reuseCurrentHostDaemon ? await useCurrentHostDaemon() : await ensureDaemonWithBridgeRetry(cliEntry)
1145
1169
  if (!prepared.ok) return { state: 'unavailable', reason: prepared.reason }
1146
1170
  const token = randomBytes(32).toString('base64url')
1147
1171
  const brokerToken = randomBytes(32).toString('base64url')
@@ -1162,6 +1186,26 @@ async function registerWithDaemon({
1162
1186
  }
1163
1187
  }
1164
1188
 
1189
+ // ensureDaemon spawns the daemon detached and polls for readiness, but a cold
1190
+ // daemon can take longer than that internal window to bind its socket. Rather
1191
+ // than treat the first not-ready-yet as a hard failure (which would drop the
1192
+ // hostd env vars and crash hostd-backed channel adapters on boot), re-probe a
1193
+ // few times: the still-booting daemon becomes reachable and ensureDaemon
1194
+ // fast-paths through its top-of-function isDaemonReachable() check WITHOUT
1195
+ // re-spawning. Bridges the first-boot spawn race; a genuinely dead daemon still
1196
+ // surfaces as unavailable after the budget.
1197
+ const HOSTD_BRIDGE_RETRIES = 3
1198
+ const HOSTD_BRIDGE_RETRY_DELAY_MS = 2_000
1199
+
1200
+ async function ensureDaemonWithBridgeRetry(cliEntry: string): Promise<EnsureDaemonResult> {
1201
+ let last = await ensureDaemon({ cliEntry })
1202
+ for (let attempt = 0; !last.ok && attempt < HOSTD_BRIDGE_RETRIES; attempt++) {
1203
+ await new Promise((resolve) => setTimeout(resolve, HOSTD_BRIDGE_RETRY_DELAY_MS))
1204
+ last = await ensureDaemon({ cliEntry })
1205
+ }
1206
+ return last
1207
+ }
1208
+
1165
1209
  async function useCurrentHostDaemon(): Promise<{ ok: true; httpPort: number } | { ok: false; reason: string }> {
1166
1210
  const reply = await sendToDaemon({ kind: 'http-info' })
1167
1211
  if (!reply.ok) return { ok: false, reason: reply.reason }
@@ -29,6 +29,8 @@ export function buildChannelChecks(): DoctorCheck[] {
29
29
  discordBotCredentials(),
30
30
  telegramBotCredentials(),
31
31
  webexBotCredentials(),
32
+ discordUserCredentials(),
33
+ slackUserCredentials(),
32
34
  webexUserCredentials(),
33
35
  lineCredentials(),
34
36
  kakaotalkCredentials(),
@@ -47,6 +49,32 @@ function slackBotCredentials(): DoctorCheck {
47
49
  }
48
50
  }
49
51
 
52
+ function slackUserCredentials(): DoctorCheck {
53
+ return {
54
+ name: 'channel.slack.credentials',
55
+ category: 'channels',
56
+ description: 'slack adapter has a current account with a token in secrets.json',
57
+ applies: (ctx) => ctx.hasAgentFolder,
58
+ async run(ctx) {
59
+ const channels = readDeclaredChannels(ctx)
60
+ if (channels === null) return configInvalidResult()
61
+ if (!isAdapterActive(channels, 'slack')) {
62
+ return { status: 'skipped', message: 'slack not configured' }
63
+ }
64
+ const block = readChannelsSecrets(ctx)?.slack
65
+ if (!hasCurrentAccountTokenField(block, 'token')) {
66
+ return {
67
+ status: 'warning',
68
+ message: 'slack has no current account token in secrets.json',
69
+ details: ['Adapter will start but fail authentication and stay disconnected.'],
70
+ fix: { description: 'Run `typeclaw channel add slack` to log in an account.' },
71
+ }
72
+ }
73
+ return { status: 'ok', message: 'slack has a current account token' }
74
+ },
75
+ }
76
+ }
77
+
50
78
  function discordBotCredentials(): DoctorCheck {
51
79
  return {
52
80
  name: 'channel.discord-bot.credentials',
@@ -57,6 +85,32 @@ function discordBotCredentials(): DoctorCheck {
57
85
  }
58
86
  }
59
87
 
88
+ function discordUserCredentials(): DoctorCheck {
89
+ return {
90
+ name: 'channel.discord.credentials',
91
+ category: 'channels',
92
+ description: 'discord adapter has a current account with a token in secrets.json',
93
+ applies: (ctx) => ctx.hasAgentFolder,
94
+ async run(ctx) {
95
+ const channels = readDeclaredChannels(ctx)
96
+ if (channels === null) return configInvalidResult()
97
+ if (!isAdapterActive(channels, 'discord')) {
98
+ return { status: 'skipped', message: 'discord not configured' }
99
+ }
100
+ const block = readChannelsSecrets(ctx)?.discord
101
+ if (!hasCurrentAccountTokenField(block, 'token')) {
102
+ return {
103
+ status: 'warning',
104
+ message: 'discord has no current account token in secrets.json',
105
+ details: ['Adapter will start but fail authentication and stay disconnected.'],
106
+ fix: { description: 'Run `typeclaw channel add discord` to log in an account.' },
107
+ }
108
+ }
109
+ return { status: 'ok', message: 'discord has a current account token' }
110
+ },
111
+ }
112
+ }
113
+
60
114
  function telegramBotCredentials(): DoctorCheck {
61
115
  return {
62
116
  name: 'channel.telegram-bot.credentials',
@@ -90,7 +144,7 @@ function webexUserCredentials(): DoctorCheck {
90
144
  return { status: 'skipped', message: 'webex not configured' }
91
145
  }
92
146
  const block = readChannelsSecrets(ctx)?.webex
93
- if (!hasCurrentAccountToken(block)) {
147
+ if (!hasCurrentAccountTokenField(block, 'access_token')) {
94
148
  return {
95
149
  status: 'warning',
96
150
  message: 'webex has no current account access_token in secrets.json',
@@ -353,7 +407,7 @@ function isSecretShape(value: unknown): value is { value?: string; env?: string
353
407
  return hasValue || hasEnv
354
408
  }
355
409
 
356
- function hasCurrentAccountToken(block: unknown): boolean {
410
+ function hasCurrentAccountTokenField(block: unknown, field: string): boolean {
357
411
  if (!isObjectRecord(block)) return false
358
412
  const current = (block as { currentAccount?: unknown }).currentAccount
359
413
  if (typeof current !== 'string' || current.length === 0) return false
@@ -361,7 +415,7 @@ function hasCurrentAccountToken(block: unknown): boolean {
361
415
  if (!isObjectRecord(accounts)) return false
362
416
  const account = accounts[current]
363
417
  if (!isObjectRecord(account)) return false
364
- const token = (account as { access_token?: unknown }).access_token
418
+ const token = account[field]
365
419
  return typeof token === 'string' && token.length > 0
366
420
  }
367
421
 
@@ -6,7 +6,13 @@ import { join } from 'node:path'
6
6
  import type { PortForward } from '@/config'
7
7
  import { defaultDockerExec, type DockerExec } from '@/container'
8
8
  import type { PortForwardEvent } from '@/portbroker'
9
- import { kakaoChannelBlockSchema, lineChannelBlockSchema, webexChannelBlockSchema } from '@/secrets/schema'
9
+ import {
10
+ discordChannelBlockSchema,
11
+ kakaoChannelBlockSchema,
12
+ lineChannelBlockSchema,
13
+ slackChannelBlockSchema,
14
+ webexChannelBlockSchema,
15
+ } from '@/secrets/schema'
10
16
  import { SecretsBackend } from '@/secrets/storage'
11
17
  import { isWindows } from '@/shared'
12
18
 
@@ -279,6 +285,12 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
279
285
  const gcMisses = new Map<string, number>()
280
286
  let stopped = false
281
287
  let httpPort = 0
288
+ // Boot-time restore runs concurrently with the listeners (see the kickoff
289
+ // below). Declared here so the IPC dispatcher and HTTP handler — both defined
290
+ // before restore starts — can gate on it; until it's assigned, no registry
291
+ // RPC has been accepted yet, so resolving immediately is safe.
292
+ let restoreComplete: Promise<void> | null = null
293
+ const awaitRestored = (): Promise<void> => restoreComplete ?? Promise.resolve()
282
294
 
283
295
  const supervisor = opts.restart
284
296
  ? buildSupervisor({
@@ -461,7 +473,14 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
461
473
 
462
474
  const handleSecretsPatch = async (req: {
463
475
  containerName: string
464
- patch: { channels: { kakaotalk: unknown } | { line: unknown } | { webex: unknown } }
476
+ patch: {
477
+ channels:
478
+ | { kakaotalk: unknown }
479
+ | { discord: unknown }
480
+ | { line: unknown }
481
+ | { webex: unknown }
482
+ | { slack: unknown }
483
+ }
465
484
  }): Promise<RpcResponse> =>
466
485
  runSerially(req.containerName, async () => {
467
486
  const cwd = cwds.get(req.containerName)
@@ -473,9 +492,13 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
473
492
  const patch =
474
493
  'line' in channelsPatch
475
494
  ? { key: 'line' as const, parsed: lineChannelBlockSchema.safeParse(channelsPatch.line) }
476
- : 'webex' in channelsPatch
477
- ? { key: 'webex' as const, parsed: webexChannelBlockSchema.safeParse(channelsPatch.webex) }
478
- : { key: 'kakaotalk' as const, parsed: kakaoChannelBlockSchema.safeParse(channelsPatch.kakaotalk) }
495
+ : 'discord' in channelsPatch
496
+ ? { key: 'discord' as const, parsed: discordChannelBlockSchema.safeParse(channelsPatch.discord) }
497
+ : 'webex' in channelsPatch
498
+ ? { key: 'webex' as const, parsed: webexChannelBlockSchema.safeParse(channelsPatch.webex) }
499
+ : 'slack' in channelsPatch
500
+ ? { key: 'slack' as const, parsed: slackChannelBlockSchema.safeParse(channelsPatch.slack) }
501
+ : { key: 'kakaotalk' as const, parsed: kakaoChannelBlockSchema.safeParse(channelsPatch.kakaotalk) }
479
502
  if (!patch.parsed.success) {
480
503
  return { ok: false, reason: patch.parsed.error.issues.map((issue) => issue.message).join('; ') }
481
504
  }
@@ -521,16 +544,21 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
521
544
  const dispatch = async (req: Request): Promise<RpcResponse> => {
522
545
  switch (req.kind) {
523
546
  case 'register':
547
+ await awaitRestored()
524
548
  return handleRegister(req)
525
549
  case 'deregister':
550
+ await awaitRestored()
526
551
  return handleDeregister(req)
527
552
  case 'list':
528
553
  return handleList()
529
554
  case 'status':
555
+ await awaitRestored()
530
556
  return handleStatus(req)
531
557
  case 'restart':
558
+ await awaitRestored()
532
559
  return handleRestart(req)
533
560
  case 'secrets-patch':
561
+ await awaitRestored()
534
562
  return handleSecretsPatch(req)
535
563
  case 'http-info':
536
564
  return handleHttpInfo()
@@ -597,12 +625,52 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
597
625
  if (rpc.kind !== 'restart' && rpc.kind !== 'secrets-patch') {
598
626
  return json({ ok: false, reason: 'http transport only supports restart and secrets-patch' }, 403)
599
627
  }
628
+ // restartTokens is populated by boot-time restore; authorizing before it
629
+ // completes would reject a valid token as "invalid restart token".
630
+ await awaitRestored()
600
631
  if (restartTokens.get(rpc.containerName) !== token) {
601
632
  return json({ ok: false, reason: 'invalid restart token' }, 403)
602
633
  }
603
634
  return json(rpc.kind === 'restart' ? await handleRestart(rpc) : await handleSecretsPatch(rpc))
604
635
  }
605
636
 
637
+ // GC tick distinguishes "container confirmed gone" from "docker call failed":
638
+ // a `docker ps` blip should not deregister a live container registration, so
639
+ // we require gcMissesToDeregister consecutive confirmed absences. Boot-time
640
+ // restore reuses the same probe but with a stricter policy — see
641
+ // restorePersistedRegistrations.
642
+ const probeContainerAlive = async (name: string): Promise<'alive' | 'gone' | 'unknown'> => {
643
+ try {
644
+ const result = await exec(['ps', '-a', '--filter', `name=^${name}$`, '--format', '{{.Names}}'])
645
+ if (result.exitCode !== 0) return 'unknown'
646
+ const names = result.stdout
647
+ .trim()
648
+ .split('\n')
649
+ .filter((s) => s.length > 0)
650
+ return names.includes(name) ? 'alive' : 'gone'
651
+ } catch {
652
+ return 'unknown'
653
+ }
654
+ }
655
+
656
+ // Boot-time restore replays every persisted registration into the in-memory
657
+ // maps and revives portbroker. It runs N docker-ps probes, so on a cold
658
+ // daemon it can take seconds — longer than the CLI's spawn-readiness window.
659
+ // We therefore start it WITHOUT blocking the listeners: the sockets accept
660
+ // connections immediately (so `isDaemonReachable` succeeds fast and the CLI
661
+ // injects the hostd env vars), but every handler that reads or mutates the
662
+ // restored registry awaits `awaitRestored` first. That preserves the original
663
+ // invariant — no RPC observes a half-restored registry — without coupling
664
+ // readiness to docker latency. Kicked off BEFORE the HTTP/IPC listeners so no
665
+ // request can slip past the gate in an unrestored window. A bad file (parse
666
+ // error, schema mismatch) is logged-and-skipped; one corrupt registration
667
+ // must not gate recovery.
668
+ restoreComplete = restorePersistedRegistrations(applyRegistration, log, probeContainerAlive, removeRegistrationFile)
669
+ // Swallow the rejection on a detached handle so a restore failure never
670
+ // becomes an unhandledRejection before the first gated handler awaits it.
671
+ // Handlers await `restoreComplete` directly so they still fail closed.
672
+ restoreComplete.catch(() => {})
673
+
606
674
  const httpHostname = opts.httpHost ?? '0.0.0.0'
607
675
  // Try the stable port first so containers' cached TYPECLAW_HOSTD_URL stays
608
676
  // valid across hostd respawns. EADDRINUSE means another local service holds
@@ -632,32 +700,6 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
632
700
  httpPort = httpServer.port ?? 0
633
701
  log({ kind: 'daemon-http-listening', host: httpHostname, port: httpPort })
634
702
 
635
- // GC tick distinguishes "container confirmed gone" from "docker call failed":
636
- // a `docker ps` blip should not deregister a live container registration, so
637
- // we require gcMissesToDeregister consecutive confirmed absences. Boot-time
638
- // restore reuses the same probe but with a stricter policy — see
639
- // restorePersistedRegistrations.
640
- const probeContainerAlive = async (name: string): Promise<'alive' | 'gone' | 'unknown'> => {
641
- try {
642
- const result = await exec(['ps', '-a', '--filter', `name=^${name}$`, '--format', '{{.Names}}'])
643
- if (result.exitCode !== 0) return 'unknown'
644
- const names = result.stdout
645
- .trim()
646
- .split('\n')
647
- .filter((s) => s.length > 0)
648
- return names.includes(name) ? 'alive' : 'gone'
649
- } catch {
650
- return 'unknown'
651
- }
652
- }
653
-
654
- // Boot-time restore: replay every persisted registration into the in-memory
655
- // maps and revive portbroker for it. Runs before the IPC listener so the socket
656
- // is never accepting RPCs against a half-restored registry. A bad file
657
- // (parse error, schema mismatch) is logged-and-skipped — one corrupt
658
- // registration must not gate every other container's recovery.
659
- await restorePersistedRegistrations(applyRegistration, log, probeContainerAlive, removeRegistrationFile)
660
-
661
703
  const sockets = new Set<NetSocket>()
662
704
  const listener = createServer((socket) => {
663
705
  const state = { buf: '' }
@@ -717,6 +759,10 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
717
759
  clearInterval(gcTimer)
718
760
  await closeSocketServer(listener, sockets)
719
761
  httpServer.stop(true)
762
+ // A stop racing an in-flight boot restore could let a portbroker start
763
+ // after the teardown loop below already ran, leaking it. Let restore
764
+ // settle (it never rejects past the detached catch) before tearing down.
765
+ await (restoreComplete ?? Promise.resolve()).catch(() => {})
720
766
  if (opts.portbroker) {
721
767
  const names = Array.from(cwds.keys())
722
768
  await Promise.allSettled(names.map((n) => opts.portbroker!.stop(n, 'broker-stopped')))
@@ -1,6 +1,16 @@
1
1
  export { isDaemonReachable, send } from './client'
2
2
  export { startDaemon, type Daemon, type DaemonLogEvent, type DaemonOptions } from './daemon'
3
- export { ensureDirs, homeRoot, lockfilePath, logDir, logfilePath, pidfilePath, runDir, socketPath } from './paths'
3
+ export {
4
+ ensureDirs,
5
+ homeRoot,
6
+ lockfilePath,
7
+ logDir,
8
+ logfilePath,
9
+ pidfilePath,
10
+ runDir,
11
+ socketPath,
12
+ versionCachePath,
13
+ } from './paths'
4
14
  export type {
5
15
  ListResult,
6
16
  Request,
@@ -75,6 +75,10 @@ export function modelsDir(): string {
75
75
  return join(homeRoot(), 'models')
76
76
  }
77
77
 
78
+ export function versionCachePath(): string {
79
+ return join(homeRoot(), 'version-cache.json')
80
+ }
81
+
78
82
  // Throws on any name that could traverse out of registrationsDir() or
79
83
  // confuse the filesystem. Caller's responsibility to handle the error;
80
84
  // don't catch-and-ignore — an invalid name is a protocol violation.
@@ -1,5 +1,11 @@
1
1
  import type { PortForward } from '@/config'
2
- import type { KakaoChannelBlock, LineChannelBlock, WebexChannelBlock } from '@/secrets/schema'
2
+ import type {
3
+ DiscordChannelBlock,
4
+ KakaoChannelBlock,
5
+ LineChannelBlock,
6
+ SlackChannelBlock,
7
+ WebexChannelBlock,
8
+ } from '@/secrets/schema'
3
9
 
4
10
  export type Request =
5
11
  | {
@@ -18,7 +24,14 @@ export type Request =
18
24
  | {
19
25
  kind: 'secrets-patch'
20
26
  containerName: string
21
- patch: { channels: { kakaotalk: KakaoChannelBlock } | { line: LineChannelBlock } | { webex: WebexChannelBlock } }
27
+ patch: {
28
+ channels:
29
+ | { kakaotalk: KakaoChannelBlock }
30
+ | { discord: DiscordChannelBlock }
31
+ | { line: LineChannelBlock }
32
+ | { webex: WebexChannelBlock }
33
+ | { slack: SlackChannelBlock }
34
+ }
22
35
  }
23
36
  | { kind: 'http-info' }
24
37
  | { kind: 'version' }