typeclaw 0.39.1 → 0.39.3

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 (79) 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 +44 -19
  5. package/src/agent/plugin-tools.ts +12 -12
  6. package/src/agent/session-origin.ts +2 -0
  7. package/src/agent/todo/store.ts +21 -1
  8. package/src/agent/tools/channel-reply.ts +18 -5
  9. package/src/agent/tools/channel-send.ts +13 -2
  10. package/src/bundled-plugins/doc-render/render.ts +2 -2
  11. package/src/bundled-plugins/github-cli-auth/approve-idempotency.ts +40 -18
  12. package/src/channels/adapters/discord-author-resolver.ts +52 -0
  13. package/src/channels/adapters/discord-bot.ts +1 -1
  14. package/src/channels/adapters/discord-channel-resolver.ts +44 -0
  15. package/src/channels/adapters/discord-classify.ts +121 -0
  16. package/src/channels/adapters/discord-reactions.ts +138 -0
  17. package/src/channels/adapters/discord.ts +416 -0
  18. package/src/channels/adapters/github/outbound.ts +23 -4
  19. package/src/channels/adapters/kakaotalk.ts +8 -1
  20. package/src/channels/adapters/line.ts +1 -1
  21. package/src/channels/adapters/slack-author-resolver.ts +54 -0
  22. package/src/channels/adapters/slack-bot.ts +3 -1
  23. package/src/channels/adapters/slack-channel-resolver.ts +49 -0
  24. package/src/channels/adapters/slack-classify.ts +83 -0
  25. package/src/channels/adapters/slack-reactions.ts +126 -0
  26. package/src/channels/adapters/slack.ts +416 -0
  27. package/src/channels/adapters/telegram-bot.ts +2 -1
  28. package/src/channels/adapters/webex-bot.ts +5 -2
  29. package/src/channels/adapters/webex.ts +55 -2
  30. package/src/channels/github-review-turn-ledger.ts +32 -0
  31. package/src/channels/github-verdict-activity.ts +60 -0
  32. package/src/channels/index.ts +6 -0
  33. package/src/channels/manager.ts +130 -6
  34. package/src/channels/pr-verdict-activity-bridge.ts +43 -0
  35. package/src/channels/router.ts +218 -20
  36. package/src/channels/schema.ts +4 -0
  37. package/src/channels/types.ts +17 -1
  38. package/src/cli/builtins.ts +1 -0
  39. package/src/cli/channel.ts +170 -18
  40. package/src/cli/index.ts +11 -0
  41. package/src/cli/init.ts +2 -0
  42. package/src/cli/update-check.ts +14 -0
  43. package/src/cli/update-notify.ts +91 -0
  44. package/src/cli/update-suppression.ts +19 -0
  45. package/src/compose/logs.ts +20 -6
  46. package/src/config/channels-mutation.ts +3 -1
  47. package/src/config/config.ts +51 -0
  48. package/src/config/index.ts +1 -0
  49. package/src/container/logs.ts +19 -4
  50. package/src/container/shared.ts +108 -5
  51. package/src/container/start.ts +218 -33
  52. package/src/doctor/channel-checks.ts +57 -3
  53. package/src/hostd/daemon.ts +22 -5
  54. package/src/hostd/index.ts +11 -1
  55. package/src/hostd/paths.ts +4 -0
  56. package/src/hostd/protocol.ts +15 -2
  57. package/src/init/auto-upgrade.ts +38 -4
  58. package/src/init/cli-version.ts +31 -2
  59. package/src/init/discord-auth.ts +50 -0
  60. package/src/init/dockerfile.ts +18 -5
  61. package/src/init/index.ts +140 -42
  62. package/src/init/reconcile-plugin-deps.ts +30 -5
  63. package/src/init/run-owner-claim.ts +2 -0
  64. package/src/init/slack-auth.ts +51 -0
  65. package/src/init/windows-dev-link.ts +64 -0
  66. package/src/mcp/manager.ts +94 -7
  67. package/src/mcp/tools.ts +7 -4
  68. package/src/permissions/resolve.ts +2 -0
  69. package/src/role-claim/match-rule.ts +2 -0
  70. package/src/run/index.ts +74 -29
  71. package/src/secrets/discord-store.ts +96 -0
  72. package/src/secrets/schema.ts +34 -0
  73. package/src/secrets/slack-store.ts +96 -0
  74. package/src/server/command-runner.ts +21 -0
  75. package/src/skills/typeclaw-cron/SKILL.md +13 -2
  76. package/src/tui/format.ts +0 -19
  77. package/src/tui/index.ts +2 -8
  78. package/src/update/check.ts +192 -0
  79. package/typeclaw.schema.json +332 -0
@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto'
2
2
 
3
3
  import { cancel, confirm, intro, isCancel, log, note, password, select, spinner, text } from '@clack/prompts'
4
4
  import { defineCommand } from 'citty'
5
+ import QRCode from 'qrcode'
5
6
 
6
7
  import { config } from '@/config'
7
8
  import {
@@ -25,14 +26,18 @@ import {
25
26
  setGithubSecrets,
26
27
  type AddChannelStepEvent,
27
28
  type ChannelKind,
29
+ type DiscordAuthResult,
28
30
  type GithubCredentialPatch,
29
31
  type GithubTunnelProvider,
30
32
  type KakaotalkAuthResult,
31
33
  type LineAuthResult,
34
+ type SlackAuthResult,
32
35
  type WebexAuthResult,
33
36
  } from '@/init'
37
+ import { runDiscordBootstrap } from '@/init/discord-auth'
34
38
  import { runKakaotalkBootstrap } from '@/init/kakaotalk-auth'
35
39
  import { runLineBootstrap } from '@/init/line-auth'
40
+ import { runSlackBootstrap } from '@/init/slack-auth'
36
41
  import { runWebexBootstrap } from '@/init/webex-auth'
37
42
  import { SecretsKakaoCredentialStore } from '@/secrets/kakao-store'
38
43
  import { SecretsWebexCredentialStore } from '@/secrets/webex-store'
@@ -43,6 +48,8 @@ import { c, done, errorLine, printDiscordInviteHint, printSlackAppManifestSetup,
43
48
 
44
49
  const CHANNEL_LABELS: Record<ChannelKind, string> = {
45
50
  'slack-bot': 'Slack',
51
+ slack: 'Slack (User)',
52
+ discord: 'Discord (User)',
46
53
  'discord-bot': 'Discord',
47
54
  'telegram-bot': 'Telegram',
48
55
  webex: 'Webex (User)',
@@ -612,16 +619,18 @@ async function pickChannel(configured: Set<ChannelKind>): Promise<ChannelKind> {
612
619
  process.exit(0)
613
620
  }
614
621
 
615
- type PickerValue = Exclude<ChannelKind, 'webex' | 'webex-bot'> | 'webex-family'
616
- const webexModes = available.filter((kind): kind is 'webex' | 'webex-bot' => kind === 'webex' || kind === 'webex-bot')
622
+ type FamilyValue = 'webex-family' | 'slack-family' | 'discord-family'
623
+ type FlatKind = Exclude<ChannelKind, 'webex' | 'webex-bot' | 'slack' | 'slack-bot' | 'discord' | 'discord-bot'>
624
+ type PickerValue = FlatKind | FamilyValue
617
625
  const options: Array<{ value: PickerValue; label: string }> = []
618
626
  for (const kind of available) {
619
- if (kind === 'webex' || kind === 'webex-bot') {
620
- if (!options.some((option) => option.value === 'webex-family'))
621
- options.push({ value: 'webex-family', label: 'Webex' })
627
+ const family = FAMILY_OF[kind]
628
+ if (family !== undefined) {
629
+ if (!options.some((option) => option.value === family.value))
630
+ options.push({ value: family.value, label: family.label })
622
631
  continue
623
632
  }
624
- options.push({ value: kind, label: CHANNEL_LABELS[kind] })
633
+ options.push({ value: kind as FlatKind, label: CHANNEL_LABELS[kind] })
625
634
  }
626
635
 
627
636
  const selected = await select<PickerValue>({
@@ -633,20 +642,87 @@ async function pickChannel(configured: Set<ChannelKind>): Promise<ChannelKind> {
633
642
  cancel('Aborted.')
634
643
  process.exit(0)
635
644
  }
636
- if (selected !== 'webex-family') return selected
637
- if (webexModes.length === 1) return webexModes[0]!
638
- const allWebexOptions: Array<{ value: 'webex' | 'webex-bot'; label: string }> = [
639
- {
640
- value: 'webex',
641
- label: 'User (ID/PW) — receives all messages, no @mention needed (recommended)',
642
- },
643
- { value: 'webex-bot', label: 'Bot (Token) — only sees @mentions in group spaces' },
644
- ]
645
- const webexOptions = allWebexOptions.filter((option) => webexModes.includes(option.value))
645
+ if (selected === 'webex-family') return pickWebexMode(available)
646
+ if (selected === 'slack-family') return pickSlackMode(available)
647
+ if (selected === 'discord-family') return pickDiscordMode(available)
648
+ return selected
649
+ }
650
+
651
+ const FAMILY_OF: Partial<Record<ChannelKind, { value: FamilyValue; label: string }>> = {
652
+ webex: { value: 'webex-family', label: 'Webex' },
653
+ 'webex-bot': { value: 'webex-family', label: 'Webex' },
654
+ slack: { value: 'slack-family', label: 'Slack' },
655
+ 'slack-bot': { value: 'slack-family', label: 'Slack' },
656
+ discord: { value: 'discord-family', label: 'Discord' },
657
+ 'discord-bot': { value: 'discord-family', label: 'Discord' },
658
+ }
659
+
660
+ type FamilyValue = 'webex-family' | 'slack-family' | 'discord-family'
661
+
662
+ type FamilyMode<K extends ChannelKind> = { value: K; label: string }
663
+
664
+ export const WEBEX_MODES: ReadonlyArray<FamilyMode<'webex' | 'webex-bot'>> = [
665
+ { value: 'webex', label: 'User (ID/PW) — receives all messages, no @mention needed (recommended)' },
666
+ { value: 'webex-bot', label: 'Bot (Token) — only sees @mentions in group spaces' },
667
+ ]
668
+
669
+ export const SLACK_MODES: ReadonlyArray<FamilyMode<'slack' | 'slack-bot'>> = [
670
+ { value: 'slack-bot', label: 'Bot (Token) — posts as a Slack app/bot user (recommended)' },
671
+ { value: 'slack', label: 'User (QR) — posts as your own Slack account; unofficial session, may need re-auth' },
672
+ ]
673
+
674
+ export const DISCORD_MODES: ReadonlyArray<FamilyMode<'discord' | 'discord-bot'>> = [
675
+ { value: 'discord-bot', label: 'Bot (Token) — posts as a Discord app/bot user (recommended)' },
676
+ { value: 'discord', label: 'User (QR) — posts as your own Discord account; unofficial session, may need re-auth' },
677
+ ]
678
+
679
+ // Keep the displayed order (recommended/User first), dropping already-configured
680
+ // modes. The caller defaults the selection to options[0], so this order — NOT
681
+ // CHANNEL_KINDS order — decides which mode is preselected.
682
+ export function familyModeOptions<K extends ChannelKind>(
683
+ modes: ReadonlyArray<FamilyMode<K>>,
684
+ available: ReadonlyArray<ChannelKind>,
685
+ ): Array<FamilyMode<K>> {
686
+ return modes.filter((mode) => available.includes(mode.value))
687
+ }
688
+
689
+ async function pickWebexMode(available: ReadonlyArray<ChannelKind>): Promise<'webex' | 'webex-bot'> {
690
+ const options = familyModeOptions(WEBEX_MODES, available)
691
+ if (options.length === 1) return options[0]!.value
646
692
  const mode = await select<'webex' | 'webex-bot'>({
647
693
  message: 'Which Webex mode?',
648
- options: webexOptions,
649
- initialValue: webexModes[0],
694
+ options: options.map((o) => ({ value: o.value, label: o.label })),
695
+ initialValue: options[0]?.value,
696
+ })
697
+ if (isCancel(mode)) {
698
+ cancel('Aborted.')
699
+ process.exit(0)
700
+ }
701
+ return mode
702
+ }
703
+
704
+ async function pickSlackMode(available: ReadonlyArray<ChannelKind>): Promise<'slack' | 'slack-bot'> {
705
+ const options = familyModeOptions(SLACK_MODES, available)
706
+ if (options.length === 1) return options[0]!.value
707
+ const mode = await select<'slack' | 'slack-bot'>({
708
+ message: 'Which Slack mode?',
709
+ options: options.map((o) => ({ value: o.value, label: o.label })),
710
+ initialValue: options[0]?.value,
711
+ })
712
+ if (isCancel(mode)) {
713
+ cancel('Aborted.')
714
+ process.exit(0)
715
+ }
716
+ return mode
717
+ }
718
+
719
+ async function pickDiscordMode(available: ReadonlyArray<ChannelKind>): Promise<'discord' | 'discord-bot'> {
720
+ const options = familyModeOptions(DISCORD_MODES, available)
721
+ if (options.length === 1) return options[0]!.value
722
+ const mode = await select<'discord' | 'discord-bot'>({
723
+ message: 'Which Discord mode?',
724
+ options: options.map((o) => ({ value: o.value, label: o.label })),
725
+ initialValue: options[0]?.value,
650
726
  })
651
727
  if (isCancel(mode)) {
652
728
  cancel('Aborted.')
@@ -852,7 +928,13 @@ async function runSetGithub(cwd: string): Promise<void> {
852
928
  }
853
929
 
854
930
  type CollectedCredentials =
931
+ | { channel: 'discord'; runDiscordAuth: (options: { cwd: string }) => Promise<DiscordAuthResult> }
855
932
  | { channel: 'discord-bot'; discordBotToken: string }
933
+ | {
934
+ channel: 'slack'
935
+ slackQrDataUrl: string
936
+ runSlackAuth: (options: { cwd: string; qrDataUrl: string }) => Promise<SlackAuthResult>
937
+ }
856
938
  | { channel: 'slack-bot'; slackBotToken: string; slackAppToken: string }
857
939
  | { channel: 'telegram-bot'; telegramBotToken: string }
858
940
  | { channel: 'webex'; runWebexAuth: (options: { cwd: string }) => Promise<WebexAuthResult> }
@@ -875,12 +957,22 @@ async function collectCredentials(
875
957
  lineSpinnerHolder?: LineAuthSpinnerHolder,
876
958
  ): Promise<CollectedCredentials> {
877
959
  switch (channel) {
960
+ case 'discord':
961
+ return { channel, runDiscordAuth: ({ cwd: agentDir }) => runDiscordQrAuth(agentDir) }
878
962
  case 'discord-bot':
879
963
  return { channel, discordBotToken: await promptDiscordToken() }
880
964
  case 'slack-bot': {
881
965
  const slack = await promptSlackTokens()
882
966
  return { channel, slackBotToken: slack.bot, slackAppToken: slack.app }
883
967
  }
968
+ case 'slack': {
969
+ const qrDataUrl = await promptSlackQrDataUrl()
970
+ return {
971
+ channel,
972
+ slackQrDataUrl: qrDataUrl,
973
+ runSlackAuth: ({ cwd: agentDir, qrDataUrl }) => runSlackBootstrap({ qrDataUrl, agentDir }),
974
+ }
975
+ }
884
976
  case 'telegram-bot':
885
977
  return { channel, telegramBotToken: await promptTelegramToken() }
886
978
  case 'webex': {
@@ -920,6 +1012,20 @@ async function collectCredentials(
920
1012
  }
921
1013
  }
922
1014
 
1015
+ async function runDiscordQrAuth(agentDir: string): Promise<DiscordAuthResult> {
1016
+ return await runDiscordBootstrap({ agentDir, onQrUrl: renderDiscordQrToTerminal })
1017
+ }
1018
+
1019
+ async function renderDiscordQrToTerminal(url: string): Promise<void> {
1020
+ const qr = await QRCode.toString(url, { type: 'terminal', small: true })
1021
+ note(
1022
+ [`Open Discord mobile app → Settings → scan QR.`, '', qr, '', 'Approve the login on your phone to continue.'].join(
1023
+ '\n',
1024
+ ),
1025
+ 'Discord QR login',
1026
+ )
1027
+ }
1028
+
923
1029
  async function promptGithubCredentials(cwd: string): Promise<{
924
1030
  webhookSecret: string
925
1031
  tunnelProvider: GithubTunnelProvider
@@ -1241,6 +1347,34 @@ async function promptSlackTokens(): Promise<{ bot: string; app: string }> {
1241
1347
  return { bot, app }
1242
1348
  }
1243
1349
 
1350
+ async function promptSlackQrDataUrl(): Promise<string> {
1351
+ note(
1352
+ [
1353
+ 'Slack user mode signs in as your own account — messages are sent and',
1354
+ 'received as this Slack user, not a bot.',
1355
+ '',
1356
+ 'Copy the QR image data URL from the Slack desktop app:',
1357
+ '',
1358
+ '1. Click your name (top-left) → "Sign in on mobile".',
1359
+ '2. Right-click the QR code → "Copy Image Address".',
1360
+ '3. Paste it below (a long data:image/png;base64,... string).',
1361
+ '',
1362
+ 'Generate a fresh QR each time — the sign-in link expires quickly.',
1363
+ ].join('\n'),
1364
+ 'Sign in to Slack (user account)',
1365
+ )
1366
+ const qrDataUrl = await text({
1367
+ message: 'Slack QR data URL (data:image/png;base64,...)',
1368
+ validate: (value) =>
1369
+ value && value.startsWith('data:image/') ? undefined : 'QR data URL must start with "data:image/"',
1370
+ })
1371
+ if (isCancel(qrDataUrl)) {
1372
+ cancel('Aborted.')
1373
+ process.exit(0)
1374
+ }
1375
+ return qrDataUrl
1376
+ }
1377
+
1244
1378
  async function promptSlackBotToken(): Promise<string> {
1245
1379
  const botToken = await password({
1246
1380
  message: 'Slack bot token (xoxb-...)',
@@ -1557,6 +1691,12 @@ function reportProgress(
1557
1691
  case 'webex-auth':
1558
1692
  s.stop(reportWebexAuth(event.result))
1559
1693
  break
1694
+ case 'discord-auth':
1695
+ s.stop(reportDiscordAuth(event.result))
1696
+ break
1697
+ case 'slack-auth':
1698
+ s.stop(reportSlackAuth(event.result))
1699
+ break
1560
1700
  case 'config':
1561
1701
  s.stop('Updated typeclaw.json.')
1562
1702
  break
@@ -1574,6 +1714,8 @@ const START_MESSAGES: Record<AddChannelStepEvent['step'], string> = {
1574
1714
  'line-auth': 'Logging in to LINE...',
1575
1715
  'kakaotalk-auth': 'Logging in to KakaoTalk...',
1576
1716
  'webex-auth': 'Logging in to Webex...',
1717
+ 'discord-auth': 'Logging in to Discord...',
1718
+ 'slack-auth': 'Logging in to Slack...',
1577
1719
  config: 'Updating typeclaw.json...',
1578
1720
  secrets: 'Saving credentials to secrets.json...',
1579
1721
  'github-webhooks': 'Installing GitHub repository webhooks...',
@@ -1584,6 +1726,16 @@ function reportKakaotalkAuth(result: KakaotalkAuthResult): string {
1584
1726
  return `KakaoTalk login failed: ${result.reason}`
1585
1727
  }
1586
1728
 
1729
+ function reportSlackAuth(result: SlackAuthResult): string {
1730
+ if (result.ok) return 'Slack credentials saved to secrets.json.'
1731
+ return `Slack login failed: ${result.reason}`
1732
+ }
1733
+
1734
+ function reportDiscordAuth(result: DiscordAuthResult): string {
1735
+ if (result.ok) return 'Discord credentials saved to secrets.json.'
1736
+ return `Discord login failed: ${result.reason}`
1737
+ }
1738
+
1587
1739
  function reportWebexAuth(result: WebexAuthResult): string {
1588
1740
  if (result.ok) return 'Webex credentials saved to secrets.json.'
1589
1741
  return `Webex login failed: ${result.reason}`
package/src/cli/index.ts CHANGED
@@ -39,6 +39,7 @@ const main = defineCommand({
39
39
  usage: () => import('./usage').then((m) => m.usageCommand),
40
40
  update: () => import('./update').then((m) => m.updateCommand),
41
41
  _hostd: () => import('./hostd').then((m) => m.hostdCommand),
42
+ '_update-check': () => import('./update-check').then((m) => m.updateCheckCommand),
42
43
  },
43
44
  })
44
45
 
@@ -80,6 +81,16 @@ async function runWithPluginDispatch(): Promise<void> {
80
81
 
81
82
  runHostStartupMigrationsOnce(first)
82
83
 
84
+ // Disk-only read + detached background refresh; fail-open and never blocks the
85
+ // command. The suppression check is dependency-free and runs FIRST so a bare
86
+ // flag or plugin command never imports update-notify (which eagerly loads
87
+ // @/config). See src/cli/update-suppression.ts and src/cli/update-notify.ts.
88
+ const { shouldConsiderUpdateNotice } = await import('./update-suppression')
89
+ if (shouldConsiderUpdateNotice(first)) {
90
+ const { maybeNotifyUpdate } = await import('./update-notify')
91
+ await maybeNotifyUpdate(first)
92
+ }
93
+
83
94
  if (first === '--help' || first === '-h') {
84
95
  // citty calls process.exit() after rendering help, so anything we print
85
96
  // AFTER `runMain(main)` is never reached. Print the plugin commands
package/src/cli/init.ts CHANGED
@@ -2043,6 +2043,8 @@ const START_MESSAGES: Record<Exclude<InitStep, 'hatching'>, string> = {
2043
2043
  preflight: 'Checking Docker...',
2044
2044
  'oauth-login': 'Waiting for browser login...',
2045
2045
  scaffold: 'Laying the egg...',
2046
+ 'slack-auth': 'Logging in to Slack...',
2047
+ 'discord-auth': 'Logging in to Discord...',
2046
2048
  'kakaotalk-auth': 'Logging in to KakaoTalk...',
2047
2049
  'webex-auth': 'Logging in to Webex...',
2048
2050
  'github-webhooks': 'Installing GitHub repository webhooks...',
@@ -0,0 +1,14 @@
1
+ import { defineCommand } from 'citty'
2
+
3
+ import { runBackgroundCheck } from '@/update/check'
4
+
5
+ export const updateCheckCommand = defineCommand({
6
+ meta: {
7
+ name: '_update-check',
8
+ description: 'internal: refresh the typeclaw version cache (do not invoke directly)',
9
+ hidden: true,
10
+ },
11
+ async run() {
12
+ await runBackgroundCheck()
13
+ },
14
+ })
@@ -0,0 +1,91 @@
1
+ import { CLI_VERSION, isInstalledCli } from '@/init/cli-version'
2
+ import {
3
+ isCacheFresh,
4
+ readVersionCache,
5
+ renderUpdateNotice,
6
+ resolveSkipReason,
7
+ type VersionCache,
8
+ } from '@/update/check'
9
+
10
+ import { shouldConsiderUpdateNotice, UPDATE_CHECK_COMMAND } from './update-suppression'
11
+
12
+ export { shouldConsiderUpdateNotice }
13
+
14
+ export type UpdateAction = { notice: string | null; refresh: boolean }
15
+
16
+ // Pure decision, kept config-free (takes `configEnabled` as a param) so it is
17
+ // unit-testable without spawning or loading config. Two invariants the reviews
18
+ // pinned: a skipped check suppresses BOTH the notice and the refresh; and a
19
+ // FRESH cache (success or failure-only) suppresses the refresh so the parent
20
+ // stops forking a check child on every invocation while the throttle holds.
21
+ export function decideUpdateAction(opts: {
22
+ current: string
23
+ isInstalled: boolean
24
+ configEnabled: boolean
25
+ env: Record<string, string | undefined>
26
+ cache: VersionCache | null
27
+ now: number
28
+ }): UpdateAction {
29
+ const skip = resolveSkipReason({
30
+ current: opts.current,
31
+ isInstalled: opts.isInstalled,
32
+ configEnabled: opts.configEnabled,
33
+ env: opts.env,
34
+ })
35
+ if (skip !== null) return { notice: null, refresh: false }
36
+ return {
37
+ notice: renderUpdateNotice({ current: opts.current, cache: opts.cache }),
38
+ refresh: !isCacheFresh(opts.cache, opts.now),
39
+ }
40
+ }
41
+
42
+ // The host-stage entry hook. Fail-open: a thrown error here must never disrupt
43
+ // the command the user actually ran, so the whole body is best-effort. Order is
44
+ // load-bearing: the dependency-free skip (env / dev / non-release) runs BEFORE
45
+ // @/config is ever imported, so a suppressed command (CI / opt-out) never pays
46
+ // the eager config load that would emit malformed-typeclaw.json warnings.
47
+ export async function maybeNotifyUpdate(commandName: string | undefined): Promise<void> {
48
+ try {
49
+ if (!shouldConsiderUpdateNotice(commandName)) return
50
+
51
+ const { resolveDependencyFreeSkip } = await import('@/update/check')
52
+ if (resolveDependencyFreeSkip({ current: CLI_VERSION, isInstalled: isInstalledCli(), env: process.env }) !== null) {
53
+ return
54
+ }
55
+
56
+ const { config } = await import('@/config')
57
+ const cache = await readVersionCache()
58
+ const action = decideUpdateAction({
59
+ current: CLI_VERSION,
60
+ isInstalled: isInstalledCli(),
61
+ configEnabled: config.updateCheck.enabled,
62
+ env: process.env,
63
+ cache,
64
+ now: Date.now(),
65
+ })
66
+
67
+ if (action.notice !== null) process.stderr.write(`${action.notice}\n`)
68
+ if (action.refresh) spawnBackgroundRefresh()
69
+ } catch {}
70
+ }
71
+
72
+ // Detached `typeclaw _update-check` child: fully unref'd so the parent process
73
+ // exits immediately regardless of the network call's fate (the user's hard rule
74
+ // — the command is 10000x more important than the check). stdio is ignored so
75
+ // the child can't write into the parent's terminal.
76
+ function spawnBackgroundRefresh(): void {
77
+ const bun = (globalThis as { Bun?: { spawn: typeof Bun.spawn } }).Bun
78
+ if (!bun) return
79
+ const cliEntry = process.argv[1]
80
+ if (cliEntry === undefined) return
81
+ try {
82
+ const proc = bun.spawn({
83
+ cmd: [process.execPath, cliEntry, UPDATE_CHECK_COMMAND],
84
+ stdin: 'ignore',
85
+ stdout: 'ignore',
86
+ stderr: 'ignore',
87
+ env: { ...process.env },
88
+ })
89
+ proc.unref()
90
+ } catch {}
91
+ }
@@ -0,0 +1,19 @@
1
+ import { BUILTIN_COMMAND_NAMES } from './builtins'
2
+
3
+ export const UPDATE_CHECK_COMMAND = '_update-check'
4
+
5
+ // Commands for which an update nudge would be noise or out of place: the
6
+ // container stage (`run`), the hidden internals, and `update` itself (the user
7
+ // is already updating). Bare flags are filtered separately by the `-` prefix.
8
+ const SUPPRESSED_COMMANDS = new Set(['run', 'update', '_hostd', UPDATE_CHECK_COMMAND])
9
+
10
+ // Dependency-free on purpose: index.ts calls this BEFORE importing the rest of
11
+ // the update-notify path so a suppressed command (bare flag, plugin command,
12
+ // `run`) never pays the eager `@/config` load that module triggers. Keep this
13
+ // file's imports limited to the builtin-name list.
14
+ export function shouldConsiderUpdateNotice(commandName: string | undefined): boolean {
15
+ if (commandName === undefined) return false
16
+ if (commandName.startsWith('-')) return false
17
+ if (SUPPRESSED_COMMANDS.has(commandName)) return false
18
+ return BUILTIN_COMMAND_NAMES.includes(commandName as (typeof BUILTIN_COMMAND_NAMES)[number])
19
+ }
@@ -1,7 +1,7 @@
1
1
  import { buildDockerLogsCmd, containerExists } from '@/container'
2
2
  import { supportsColor } from '@/container/log-colors'
3
3
  import { makeLogTimestampReformatter, type TimestampReformatter } from '@/container/log-timestamps'
4
- import { getBun } from '@/container/shared'
4
+ import { getBun, resolveDockerBinary } from '@/container/shared'
5
5
 
6
6
  import { discoverAgents, type AgentEntry } from './discover'
7
7
 
@@ -74,6 +74,17 @@ export async function composeLogs({
74
74
  }: ComposeLogsOptions): Promise<ComposeLogsResult> {
75
75
  const agents = discoverAgents(rootCwd)
76
76
 
77
+ // Resolve docker BEFORE probing containers: containerExists collapses a
78
+ // missing docker binary into `false`, so every agent would be classified
79
+ // "container not running" and the empty-attached early return would exit 0 —
80
+ // masking the real "docker not on PATH" cause (the stale-Windows-PATH case
81
+ // #1007 covers for start/init). Resolving first surfaces it correctly.
82
+ const dockerBinary = resolveDockerBinary()
83
+ if (dockerBinary === null) {
84
+ err.write('compose: docker not found on PATH\n')
85
+ return { agents, attached: [], missing: agents, exitCode: 1 }
86
+ }
87
+
77
88
  const liveness = await Promise.all(
78
89
  agents.map(async (a) => ({ agent: a, exists: await containerExists(a.containerName) })),
79
90
  )
@@ -95,11 +106,14 @@ export async function composeLogs({
95
106
  const useColor = supportsColor(out)
96
107
 
97
108
  const procs = attached.map((agent) => {
98
- const cmd = buildDockerLogsCmd({
99
- containerName: agent.containerName,
100
- follow,
101
- ...(tail !== undefined ? { tail } : {}),
102
- })
109
+ const cmd = buildDockerLogsCmd(
110
+ {
111
+ containerName: agent.containerName,
112
+ follow,
113
+ ...(tail !== undefined ? { tail } : {}),
114
+ },
115
+ dockerBinary,
116
+ )
103
117
  const proc = bun.spawn({ cmd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
104
118
  return { agent, proc }
105
119
  })
@@ -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
@@ -735,6 +751,7 @@ export const configSchema = z
735
751
  // here, so a freshly-hatched bot already has its identity wired up.
736
752
  alias: z.array(z.string().trim().min(1)).default([]),
737
753
  compose: composeSchema,
754
+ updateCheck: updateCheckSchema,
738
755
  channels: channelsSchema,
739
756
  portForward: portForwardSchema,
740
757
  network: networkSchema,
@@ -951,6 +968,7 @@ export const FIELD_EFFECTS: Record<string, FieldEffect> = {
951
968
  plugins: 'restart-required',
952
969
  alias: 'applied',
953
970
  compose: 'ignored',
971
+ updateCheck: 'ignored',
954
972
  channels: 'applied',
955
973
  portForward: 'restart-required',
956
974
  network: 'restart-required',
@@ -1045,6 +1063,7 @@ export function extractPluginConfigs(raw: unknown): Record<string, unknown> {
1045
1063
  'plugins',
1046
1064
  'alias',
1047
1065
  'compose',
1066
+ 'updateCheck',
1048
1067
  'channels',
1049
1068
  'portForward',
1050
1069
  'network',
@@ -1110,6 +1129,38 @@ export function loadConfigSync(cwd: string): Config {
1110
1129
  return result.data
1111
1130
  }
1112
1131
 
1132
+ // Single-read variant of loadConfigSync + loadPluginConfigsSync for the boot
1133
+ // path, which otherwise reads + parses + migrates typeclaw.json twice. Throws on
1134
+ // invalid JSON / failed schema parse and returns defaults + `{}` on a missing
1135
+ // file, matching loadConfigSync.
1136
+ export function loadConfigBundleSync(cwd: string): { config: Config; pluginConfigs: Record<string, unknown> } {
1137
+ let raw: string
1138
+ try {
1139
+ raw = readFileSync(join(cwd, CONFIG_FILE), 'utf8')
1140
+ } catch {
1141
+ return { config: configSchema.parse({}), pluginConfigs: {} }
1142
+ }
1143
+
1144
+ let json: unknown
1145
+ try {
1146
+ json = JSON.parse(raw)
1147
+ } catch (error) {
1148
+ const detail = error instanceof Error ? error.message : String(error)
1149
+ throw new Error(`${CONFIG_FILE} is not valid JSON: ${detail}`)
1150
+ }
1151
+
1152
+ const migrated = migrateLegacyConfigShape(json)
1153
+ if (migrated.changed) {
1154
+ persistMigratedConfig(cwd, migrated.json, migrated.applied)
1155
+ }
1156
+
1157
+ const result = configSchema.safeParse(migrated.json)
1158
+ if (!result.success) {
1159
+ throw new Error(`${CONFIG_FILE} is invalid: ${formatZodError(result.error)}`)
1160
+ }
1161
+ return { config: result.data, pluginConfigs: extractPluginConfigs(migrated.json) }
1162
+ }
1163
+
1113
1164
  // Strips a `channels.github.eventAllowlist` that deep-equals a value `channel
1114
1165
  // add` / `init` previously seeded verbatim, so the config re-tracks the shipped
1115
1166
  // 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,
@@ -1,6 +1,6 @@
1
1
  import { supportsColor } from './log-colors'
2
2
  import { makeLogTimestampReformatter, type TimestampReformatter } from './log-timestamps'
3
- import { containerExists, containerNameFromCwd, getBun } from './shared'
3
+ import { containerExists, containerNameFromCwd, getBun, resolveDockerBinary } from './shared'
4
4
 
5
5
  export type LogsPlan = {
6
6
  containerName: string
@@ -39,6 +39,17 @@ export async function logs({
39
39
 
40
40
  const plan = planLogs(cwd, { follow, tail })
41
41
 
42
+ // Resolve docker before inspecting: containerExists collapses a missing
43
+ // docker binary into `false`, so deferring this would surface the misleading
44
+ // "Container … not found" instead of the real "Docker is not installed" on a
45
+ // host where docker isn't on PATH (cf. shell.ts). resolveDockerBinary also
46
+ // recovers the stale-Windows-PATH case where Bun.which misses (#1007).
47
+ const dockerBinary = resolveDockerBinary()
48
+ if (dockerBinary === null) {
49
+ return { ok: false, reason: 'Docker is not installed (docker not found on PATH).' }
50
+ }
51
+ const cmd = buildDockerLogsCmd(plan, dockerBinary)
52
+
42
53
  try {
43
54
  if (!(await containerExists(plan.containerName))) {
44
55
  return { ok: false, reason: `Container ${plan.containerName} not found. Run \`typeclaw start\` first.` }
@@ -47,7 +58,7 @@ export async function logs({
47
58
  // stdin:'ignore' — `docker logs` never reads stdin, and letting the child
48
59
  // hold the TTY breaks the viewer's raw-mode keypress listener (esc/q/ctrl-c
49
60
  // stop reaching it, freezing the logs view with no way out).
50
- const proc = bun.spawn({ cmd: buildDockerLogsCmd(plan), cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
61
+ const proc = bun.spawn({ cmd, cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
51
62
 
52
63
  // `docker logs -f` never exits on its own; aborting the signal must kill it
53
64
  // so the pumps' stream readers end. Escalate to SIGKILL if SIGTERM is
@@ -112,8 +123,12 @@ export function parseTailValue(raw: string): { ok: true; value: string } | { ok:
112
123
  }
113
124
 
114
125
  // Exported so `compose/logs.ts` builds the exact same `docker logs` argv shape.
115
- export function buildDockerLogsCmd(plan: LogsPlan): string[] {
116
- const cmd = ['docker', 'logs', '--timestamps']
126
+ // Takes the already-resolved docker binary path (from resolveDockerBinary) as
127
+ // the argv head so a stale Windows PATH still spawns — passing a bare 'docker'
128
+ // throws ENOENT on the #1007 case. Callers resolve the binary and handle the
129
+ // missing-docker error before getting here.
130
+ export function buildDockerLogsCmd(plan: LogsPlan, dockerBinary: string): string[] {
131
+ const cmd = [dockerBinary, 'logs', '--timestamps']
117
132
  if (plan.tail !== undefined) cmd.push('--tail', plan.tail)
118
133
  if (plan.follow) cmd.push('-f')
119
134
  cmd.push(plan.containerName)