typeclaw 0.43.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +23 -4
  6. package/src/agent/multimodal/look-at.ts +27 -9
  7. package/src/agent/plugin-tools.ts +9 -4
  8. package/src/agent/session-origin.ts +1 -0
  9. package/src/agent/system-prompt.ts +36 -0
  10. package/src/agent/tools/channel-fetch-attachment.ts +45 -3
  11. package/src/agent/tools/channel-reply.ts +41 -18
  12. package/src/agent/tools/channel-send.ts +82 -13
  13. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  14. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  15. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  16. package/src/bundled-plugins/memory/README.md +9 -9
  17. package/src/bundled-plugins/memory/index.ts +40 -9
  18. package/src/channels/adapters/discord-bot.ts +76 -3
  19. package/src/channels/adapters/discord.ts +15 -2
  20. package/src/channels/adapters/github/inbound.ts +20 -14
  21. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  22. package/src/channels/adapters/teams-classify.ts +144 -0
  23. package/src/channels/adapters/teams-id-token.ts +112 -0
  24. package/src/channels/adapters/teams-key.ts +32 -0
  25. package/src/channels/adapters/teams.ts +519 -0
  26. package/src/channels/github-review-turn-ledger.ts +43 -0
  27. package/src/channels/index.ts +1 -1
  28. package/src/channels/manager.ts +63 -2
  29. package/src/channels/router.ts +664 -112
  30. package/src/channels/schema.ts +33 -0
  31. package/src/channels/types.ts +8 -5
  32. package/src/cli/channel.ts +131 -16
  33. package/src/cli/hostd.ts +41 -0
  34. package/src/cli/init.ts +58 -1
  35. package/src/config/channels-mutation.ts +9 -1
  36. package/src/cron/index.ts +16 -4
  37. package/src/cron/reloadable.ts +25 -7
  38. package/src/cron/scheduler.ts +4 -0
  39. package/src/cron/schema.ts +143 -35
  40. package/src/doctor/channel-checks.ts +27 -0
  41. package/src/hostd/daemon.ts +23 -3
  42. package/src/hostd/protocol.ts +2 -0
  43. package/src/hostd/teams-renewal-manager.ts +212 -0
  44. package/src/init/checkpoint.ts +1 -1
  45. package/src/init/index.ts +68 -1
  46. package/src/init/run-owner-claim.ts +1 -0
  47. package/src/init/teams-auth.ts +111 -0
  48. package/src/inspect/label.ts +4 -0
  49. package/src/permissions/match-rule.ts +11 -1
  50. package/src/permissions/resolve.ts +1 -0
  51. package/src/role-claim/match-rule.ts +2 -1
  52. package/src/run/index.ts +35 -8
  53. package/src/run/llm-fetch-observer.ts +27 -5
  54. package/src/sandbox/build.ts +12 -0
  55. package/src/sandbox/policy.ts +13 -0
  56. package/src/sandbox/writable-zones.ts +46 -10
  57. package/src/secrets/schema.ts +32 -0
  58. package/src/secrets/teams-renewal.ts +229 -0
  59. package/src/secrets/teams-store.ts +108 -0
  60. package/typeclaw.schema.json +163 -3
@@ -9,6 +9,7 @@ export const ADAPTER_IDS = [
9
9
  'kakaotalk',
10
10
  'slack',
11
11
  'slack-bot',
12
+ 'teams',
12
13
  'telegram-bot',
13
14
  'webex',
14
15
  'webex-bot',
@@ -16,6 +17,31 @@ export const ADAPTER_IDS = [
16
17
 
17
18
  export type AdapterId = (typeof ADAPTER_IDS)[number]
18
19
 
20
+ export type ReadCapability = 'history' | 'message-get' | 'list'
21
+
22
+ // Which arbitrary-read callbacks each adapter registers when it starts healthy.
23
+ // A missing callback means "adapter-unavailable" (failed to start) ONLY for a
24
+ // capability listed here; capabilities an adapter never implements stay
25
+ // "not-supported" even when the adapter is configured and running. Kept as a
26
+ // static table because the distinction must survive a failed start() (which
27
+ // registers nothing), so it can't be derived from the live callback registry.
28
+ // The guard test in schema.test.ts asserts this matches what each adapter's
29
+ // start() actually registers — update both together or CI fails.
30
+ export const ADAPTER_READ_CAPABILITIES: Record<AdapterId, readonly ReadCapability[]> = {
31
+ discord: ['history'],
32
+ 'discord-bot': ['history', 'message-get', 'list'],
33
+ github: ['history'],
34
+ instagram: ['history'],
35
+ line: ['history'],
36
+ kakaotalk: ['history'],
37
+ slack: ['history'],
38
+ 'slack-bot': ['history', 'message-get', 'list'],
39
+ teams: ['history'],
40
+ 'telegram-bot': [],
41
+ webex: ['history'],
42
+ 'webex-bot': ['history'],
43
+ }
44
+
19
45
  const engagementTriggerSchema = z.enum(['mention', 'reply', 'dm'])
20
46
 
21
47
  const stickinessSchema = z.union([
@@ -279,6 +305,13 @@ export const channelsSchema = z
279
305
  kakaotalk: adapterSchema.optional(),
280
306
  slack: adapterSchema.optional(),
281
307
  'slack-bot': adapterSchema.optional(),
308
+ // Teams is a personal-account channel: user-account auth (no bot token),
309
+ // credentials in secrets.json#channels.teams. v1 is chat-only (1:1/group/
310
+ // self chats) driven by agent-messenger's TeamsListener (trouter
311
+ // WebSocket); Teams team/channel messaging is out of scope because the
312
+ // realtime event carries only a chatId, no team/channel id. Plain-text
313
+ // sends only; standard adapterSchema (engagement + history + enabled).
314
+ teams: adapterSchema.optional(),
282
315
  'telegram-bot': adapterSchema.optional(),
283
316
  webex: adapterSchema.optional(),
284
317
  // Webex bots receive messages in real time over a Mercury WebSocket
@@ -365,7 +365,8 @@ export type FetchHistoryResult =
365
365
  // Registered per-adapter on the ChannelRouter alongside outbound/typing
366
366
  // callbacks. Adapters that cannot fetch history (e.g. webhook-only future
367
367
  // adapters) simply do not register one; the router answers
368
- // 'history-not-supported' for those.
368
+ // 'history-not-supported' for those, or 'history-adapter-unavailable' when the
369
+ // adapter is configured but failed to start (see setAdapterConfigured).
369
370
  export type HistoryCallback = (args: FetchHistoryArgs) => Promise<FetchHistoryResult>
370
371
 
371
372
  // Fetch a single message by its platform id from an arbitrary chat. Backs the
@@ -383,9 +384,11 @@ export type GetMessageArgs = {
383
384
  export type GetMessageResult =
384
385
  | { ok: true; message: ChannelHistoryMessage }
385
386
  // `code: 'not-found'` is an expected miss (deleted/wrong id) the tool surfaces
386
- // as a soft error; `code: 'not-supported'` means no adapter callback is
387
- // registered, mirroring `fetchHistory`'s 'history-not-supported' contract.
388
- | { ok: false; error: string; code?: 'not-found' | 'not-supported' }
387
+ // as a soft error; `code: 'not-supported'` means the adapter is not configured
388
+ // at all; `code: 'adapter-unavailable'` means it IS configured but currently
389
+ // has no live callback (e.g. failed to start), mirroring `fetchHistory`'s
390
+ // 'message-get-adapter-unavailable' string contract.
391
+ | { ok: false; error: string; code?: 'not-found' | 'not-supported' | 'adapter-unavailable' }
389
392
 
390
393
  export type MessageGetCallback = (args: GetMessageArgs) => Promise<GetMessageResult>
391
394
 
@@ -408,7 +411,7 @@ export type ListChannelsArgs = {
408
411
 
409
412
  export type ListChannelsResult =
410
413
  | { ok: true; entries: ChannelListEntry[]; nextCursor?: string }
411
- | { ok: false; error: string; code?: 'not-supported' }
414
+ | { ok: false; error: string; code?: 'not-supported' | 'adapter-unavailable' }
412
415
 
413
416
  // Backs the `channel_read` tool's `mode: "list"`. Opt-in per adapter like
414
417
  // history; the router answers 'list-not-supported' when none is registered.
@@ -34,6 +34,7 @@ import {
34
34
  type KakaotalkAuthResult,
35
35
  type LineAuthResult,
36
36
  type SlackAuthResult,
37
+ type TeamsAuthResult,
37
38
  type WebexAuthResult,
38
39
  } from '@/init'
39
40
  import { runDiscordBootstrap } from '@/init/discord-auth'
@@ -41,8 +42,10 @@ import { runInstagramBootstrap, type InstagramLoginCallbacks } from '@/init/inst
41
42
  import { runKakaotalkBootstrap } from '@/init/kakaotalk-auth'
42
43
  import { runLineBootstrap } from '@/init/line-auth'
43
44
  import { runSlackBootstrap } from '@/init/slack-auth'
45
+ import { runTeamsBootstrap, type TeamsDeviceCodeCallbacks } from '@/init/teams-auth'
44
46
  import { runWebexBootstrap } from '@/init/webex-auth'
45
47
  import { SecretsKakaoCredentialStore } from '@/secrets/kakao-store'
48
+ import type { TeamsAccountType } from '@/secrets/schema'
46
49
  import { SecretsWebexCredentialStore } from '@/secrets/webex-store'
47
50
 
48
51
  import { CANCEL_SYMBOL, promptPrivateKeyPem } from './prompt-pem'
@@ -57,12 +60,15 @@ const CHANNEL_LABELS: Record<ChannelKind, string> = {
57
60
  'telegram-bot': 'Telegram',
58
61
  webex: 'Webex (User)',
59
62
  'webex-bot': 'Webex',
63
+ teams: 'Teams',
60
64
  instagram: 'Instagram',
61
65
  line: 'LINE',
62
66
  kakaotalk: 'KakaoTalk',
63
67
  github: 'GitHub',
64
68
  }
65
69
 
70
+ const ADDABLE_CHANNEL_KINDS = CHANNEL_KINDS
71
+
66
72
  const addSub = defineCommand({
67
73
  meta: {
68
74
  name: 'add',
@@ -71,7 +77,7 @@ const addSub = defineCommand({
71
77
  args: {
72
78
  adapter: {
73
79
  type: 'positional',
74
- description: `which adapter to add (${CHANNEL_KINDS.join(' | ')}); omit to pick interactively`,
80
+ description: `which adapter to add (${ADDABLE_CHANNEL_KINDS.join(' | ')}); omit to pick interactively`,
75
81
  required: false,
76
82
  },
77
83
  },
@@ -183,7 +189,11 @@ const setSub = defineCommand({
183
189
  },
184
190
  })
185
191
 
186
- const REAUTHABLE_ADAPTERS = ['line', 'instagram', 'kakaotalk', 'webex'] as const
192
+ // Adapters that re-authenticate through a full interactive login replay rather
193
+ // than a token-field rotation (`channel set`). Discord (User) belongs here — its
194
+ // unofficial QR session expires and is refreshed by replaying the QR login, the
195
+ // same shape as LINE's QR flow. `discord-bot` stays in SETTABLE_ADAPTERS.
196
+ const REAUTHABLE_ADAPTERS = ['line', 'instagram', 'kakaotalk', 'webex', 'discord', 'teams'] as const
187
197
  type ReauthableAdapter = (typeof REAUTHABLE_ADAPTERS)[number]
188
198
 
189
199
  const reauthSub = defineCommand({
@@ -405,9 +415,7 @@ async function resolveReauthableAdapter(
405
415
  ): Promise<ReauthableAdapter> {
406
416
  if (requested !== undefined) {
407
417
  if (!isReauthableAdapter(requested)) {
408
- console.error(
409
- errorLine(`Adapter "${requested}" does not support reauth. Supported: ${REAUTHABLE_ADAPTERS.join(', ')}.`),
410
- )
418
+ console.error(errorLine(reauthAdapterRejectionMessage(requested)))
411
419
  process.exit(1)
412
420
  }
413
421
  if (!configured.has(requested)) {
@@ -448,6 +456,14 @@ function isReauthableAdapter(value: string): value is ReauthableAdapter {
448
456
  return (REAUTHABLE_ADAPTERS as ReadonlyArray<string>).includes(value)
449
457
  }
450
458
 
459
+ // Returns the string (rather than exiting inline) so the routing stays testable.
460
+ export function reauthAdapterRejectionMessage(adapter: string): string {
461
+ if (isSettableAdapter(adapter)) {
462
+ return `Adapter "${adapter}" does not support reauth. Use \`typeclaw channel set ${adapter}\` to rotate its credentials.`
463
+ }
464
+ return `Adapter "${adapter}" does not support reauth. Supported: ${REAUTHABLE_ADAPTERS.join(', ')}.`
465
+ }
466
+
451
467
  async function runReauth(cwd: string, adapter: ReauthableAdapter): Promise<void> {
452
468
  switch (adapter) {
453
469
  case 'line':
@@ -462,9 +478,27 @@ async function runReauth(cwd: string, adapter: ReauthableAdapter): Promise<void>
462
478
  case 'webex':
463
479
  await runWebexReauth(cwd)
464
480
  return
481
+ case 'discord':
482
+ await runDiscordReauth(cwd)
483
+ return
484
+ case 'teams':
485
+ await runTeamsReauth(cwd)
486
+ return
465
487
  }
466
488
  }
467
489
 
490
+ async function runTeamsReauth(cwd: string): Promise<void> {
491
+ const accountType = await promptTeamsAccountType()
492
+ const result = await runTeamsBootstrap({ agentDir: cwd, accountType, callbacks: teamsDeviceCodeCallbacks() })
493
+ if (!result.ok) {
494
+ console.error(errorLine(`Teams login failed: ${result.reason}`))
495
+ process.exit(1)
496
+ }
497
+ process.stdout.write(`${successLine('Teams credentials refreshed in secrets.json.')}\n`)
498
+
499
+ await maybePromptReauthRefresh(cwd, 'teams')
500
+ }
501
+
468
502
  async function runInstagramReauth(cwd: string): Promise<void> {
469
503
  const creds = await promptInstagramCredentials()
470
504
  const s = spinner()
@@ -540,6 +574,17 @@ async function runWebexReauth(cwd: string): Promise<void> {
540
574
  await maybePromptReauthRefresh(cwd, 'webex')
541
575
  }
542
576
 
577
+ async function runDiscordReauth(cwd: string): Promise<void> {
578
+ const result = await runDiscordBootstrap({ agentDir: cwd, onQrUrl: renderDiscordQrToTerminal })
579
+ if (!result.ok) {
580
+ console.error(errorLine(`Discord login failed: ${result.reason}`))
581
+ process.exit(1)
582
+ }
583
+ process.stdout.write(`${successLine('Discord credentials refreshed in secrets.json.')}\n`)
584
+
585
+ await maybePromptReauthRefresh(cwd, 'discord')
586
+ }
587
+
543
588
  async function readExistingKakaotalkEmail(cwd: string): Promise<string | undefined> {
544
589
  try {
545
590
  const store = new SecretsKakaoCredentialStore({ mode: 'host', secretsPath: `${cwd}/secrets.json` })
@@ -630,7 +675,15 @@ async function maybePromptCredentialRefresh(
630
675
 
631
676
  function validateAdapterArg(adapter: string, configured: Set<ChannelKind>): ChannelKind {
632
677
  if (!isChannelKind(adapter)) {
633
- console.error(errorLine(`Unknown adapter "${adapter}". Expected one of: ${CHANNEL_KINDS.join(', ')}.`))
678
+ console.error(errorLine(`Unknown adapter "${adapter}". Expected one of: ${ADDABLE_CHANNEL_KINDS.join(', ')}.`))
679
+ process.exit(1)
680
+ }
681
+ if (!(ADDABLE_CHANNEL_KINDS as ReadonlyArray<string>).includes(adapter)) {
682
+ console.error(
683
+ errorLine(
684
+ `${CHANNEL_LABELS[adapter]} ("${adapter}") has no interactive auth yet. Populate secrets.json#channels.${adapter} manually.`,
685
+ ),
686
+ )
634
687
  process.exit(1)
635
688
  }
636
689
  if (configured.has(adapter)) {
@@ -649,7 +702,7 @@ function isChannelKind(value: string): value is ChannelKind {
649
702
  }
650
703
 
651
704
  async function pickChannel(configured: Set<ChannelKind>): Promise<ChannelKind> {
652
- const available = CHANNEL_KINDS.filter((kind) => !configured.has(kind))
705
+ const available = ADDABLE_CHANNEL_KINDS.filter((kind) => !configured.has(kind))
653
706
  if (available.length === 0) {
654
707
  console.error(errorLine('All supported channel adapters are already configured in typeclaw.json. Nothing to add.'))
655
708
  process.exit(0)
@@ -771,17 +824,20 @@ function isSettableAdapter(value: string): value is SettableAdapter {
771
824
  return (SETTABLE_ADAPTERS as ReadonlyArray<string>).includes(value)
772
825
  }
773
826
 
827
+ // Returns the string (rather than exiting inline) so the routing stays testable.
828
+ export function setAdapterRejectionMessage(adapter: string): string {
829
+ if (isReauthableAdapter(adapter)) {
830
+ return `Adapter "${adapter}" does not support \`channel set\`. Use \`typeclaw channel reauth ${adapter}\` instead.`
831
+ }
832
+ if (isChannelKind(adapter)) {
833
+ return `Adapter "${adapter}" does not support \`channel set\`. Rotate its credentials by removing and re-adding it: \`typeclaw channel remove ${adapter} && typeclaw channel add ${adapter}\`.`
834
+ }
835
+ return `Unknown adapter "${adapter}". Expected one of: ${SETTABLE_ADAPTERS.join(', ')}.`
836
+ }
837
+
774
838
  function validateSetAdapterArg(adapter: string, configured: Set<ChannelKind>): SettableAdapter {
775
839
  if (!isSettableAdapter(adapter)) {
776
- if (isChannelKind(adapter)) {
777
- console.error(
778
- errorLine(
779
- `Adapter "${adapter}" does not support \`channel set\`. Use \`typeclaw channel reauth ${adapter}\` instead.`,
780
- ),
781
- )
782
- } else {
783
- console.error(errorLine(`Unknown adapter "${adapter}". Expected one of: ${SETTABLE_ADAPTERS.join(', ')}.`))
784
- }
840
+ console.error(errorLine(setAdapterRejectionMessage(adapter)))
785
841
  process.exit(1)
786
842
  }
787
843
  if (!configured.has(adapter)) {
@@ -975,6 +1031,7 @@ type CollectedCredentials =
975
1031
  | { channel: 'telegram-bot'; telegramBotToken: string }
976
1032
  | { channel: 'webex'; runWebexAuth: (options: { cwd: string }) => Promise<WebexAuthResult> }
977
1033
  | { channel: 'webex-bot'; webexBotToken: string }
1034
+ | { channel: 'teams'; runTeamsAuth: (options: { cwd: string }) => Promise<TeamsAuthResult> }
978
1035
  | { channel: 'instagram'; runInstagramAuth: (options: { cwd: string }) => Promise<InstagramAuthResult> }
979
1036
  | { channel: 'line'; runLineAuth: (options: { cwd: string }) => Promise<LineAuthResult> }
980
1037
  | { channel: 'kakaotalk'; runKakaotalkAuth: (options: { cwd: string }) => Promise<KakaotalkAuthResult> }
@@ -1022,6 +1079,14 @@ async function collectCredentials(
1022
1079
  }
1023
1080
  case 'webex-bot':
1024
1081
  return { channel, webexBotToken: await promptWebexToken() }
1082
+ case 'teams': {
1083
+ const accountType = await promptTeamsAccountType()
1084
+ return {
1085
+ channel,
1086
+ runTeamsAuth: ({ cwd: agentDir }) =>
1087
+ runTeamsBootstrap({ agentDir, accountType, callbacks: teamsDeviceCodeCallbacks() }),
1088
+ }
1089
+ }
1025
1090
  case 'instagram': {
1026
1091
  const creds = await promptInstagramCredentials()
1027
1092
  const callbacks = instagramLoginCallbacks(lineSpinnerHolder ? holderSpinnerControl(lineSpinnerHolder) : undefined)
@@ -1495,6 +1560,47 @@ async function promptWebexToken(): Promise<string> {
1495
1560
  return token
1496
1561
  }
1497
1562
 
1563
+ async function promptTeamsAccountType(): Promise<TeamsAccountType> {
1564
+ note(
1565
+ [
1566
+ 'Teams signs in as your own Microsoft account via device-code login —',
1567
+ 'no bot registration. You get a short code to enter at',
1568
+ 'microsoft.com/devicelogin, then approve the sign-in.',
1569
+ ].join('\n'),
1570
+ 'About to log in to Teams',
1571
+ )
1572
+ const accountType = await select<TeamsAccountType>({
1573
+ message: 'Which kind of Microsoft account?',
1574
+ options: [
1575
+ { value: 'work', label: 'Work or school (Microsoft 365 / Azure AD)' },
1576
+ { value: 'personal', label: 'Personal Microsoft account (outlook.com, live.com, …)' },
1577
+ ],
1578
+ initialValue: 'work',
1579
+ })
1580
+ if (isCancel(accountType)) {
1581
+ cancel('Aborted.')
1582
+ process.exit(0)
1583
+ }
1584
+ return accountType
1585
+ }
1586
+
1587
+ export function teamsDeviceCodeCallbacks(): TeamsDeviceCodeCallbacks {
1588
+ return {
1589
+ onCode: (prompt) => {
1590
+ note(
1591
+ [
1592
+ `Open ${prompt.verificationUri}`,
1593
+ `Enter code: ${prompt.userCode}`,
1594
+ '',
1595
+ 'Then approve the sign-in in your browser. Waiting for approval…',
1596
+ ].join('\n'),
1597
+ 'Teams device-code login',
1598
+ )
1599
+ },
1600
+ onPending: () => log.info('Approved — minting the Teams token…'),
1601
+ }
1602
+ }
1603
+
1498
1604
  async function promptKakaotalkCredentials(
1499
1605
  opts: { defaultEmail?: string } = {},
1500
1606
  ): Promise<{ email: string; password: string }> {
@@ -1792,6 +1898,9 @@ function reportProgress(
1792
1898
  case 'webex-auth':
1793
1899
  s.stop(reportWebexAuth(event.result))
1794
1900
  break
1901
+ case 'teams-auth':
1902
+ s.stop(reportTeamsAuth(event.result))
1903
+ break
1795
1904
  case 'discord-auth':
1796
1905
  s.stop(reportDiscordAuth(event.result))
1797
1906
  break
@@ -1816,6 +1925,7 @@ const START_MESSAGES: Record<AddChannelStepEvent['step'], string> = {
1816
1925
  'instagram-auth': 'Logging in to Instagram...',
1817
1926
  'kakaotalk-auth': 'Logging in to KakaoTalk...',
1818
1927
  'webex-auth': 'Logging in to Webex...',
1928
+ 'teams-auth': 'Logging in to Teams...',
1819
1929
  'discord-auth': 'Logging in to Discord...',
1820
1930
  'slack-auth': 'Logging in to Slack...',
1821
1931
  config: 'Updating typeclaw.json...',
@@ -1843,6 +1953,11 @@ function reportWebexAuth(result: WebexAuthResult): string {
1843
1953
  return `Webex login failed: ${result.reason}`
1844
1954
  }
1845
1955
 
1956
+ function reportTeamsAuth(result: TeamsAuthResult): string {
1957
+ if (result.ok) return 'Teams credentials saved to secrets.json.'
1958
+ return `Teams login failed: ${result.reason}`
1959
+ }
1960
+
1846
1961
  function reportLineAuth(result: LineAuthResult): string {
1847
1962
  if (result.ok) return 'LINE credentials saved to secrets.json.'
1848
1963
  return `LINE login failed: ${result.reason}`
package/src/cli/hostd.ts CHANGED
@@ -7,6 +7,7 @@ import { startDaemon, type DaemonLogEvent, type RestartPreflight } from '@/hostd
7
7
  import { createKakaoRenewalManager } from '@/hostd/kakao-renewal-manager'
8
8
  import { createPortbrokerManager } from '@/hostd/portbroker-manager'
9
9
  import type { SupervisorLogEvent, SupervisorRestart } from '@/hostd/supervisor'
10
+ import { createTeamsRenewalManager } from '@/hostd/teams-renewal-manager'
10
11
  import { computeSourceVersion, resolveSrcRoot, UNVERSIONED_SENTINEL } from '@/hostd/version'
11
12
  import { createWebexRenewalManager } from '@/hostd/webex-renewal-manager'
12
13
  import { validateRestartDeps, type RestartDepsPreflightResult } from '@/init/restart-deps-preflight'
@@ -57,6 +58,19 @@ export const hostdCommand = defineCommand({
57
58
  },
58
59
  shouldRenew: ({ cwd }) => webexChannelConfigured(cwd),
59
60
  })
61
+ const teamsRenewal = createTeamsRenewalManager({
62
+ onLog: (event) => writeLogLine(formatLog(event)),
63
+ onRenewalOk: async ({ containerName, cwd }) => {
64
+ // Restart so the in-memory TeamsClient picks up the renewed token from
65
+ // secrets.json. Without this, the cron writes a fresh token but the
66
+ // running adapter keeps the old token in its login closure and still
67
+ // cannot obtain an id_token for the realtime listener.
68
+ const currentHostDaemon = await currentHostDaemonHolder.ready()
69
+ const result = await hostdRestart({ containerName, cwd, currentHostDaemon })
70
+ if (!result.ok) throw new Error(result.reason)
71
+ },
72
+ shouldRenew: ({ cwd }) => teamsChannelConfigured(cwd),
73
+ })
60
74
 
61
75
  const daemon = await startDaemon({
62
76
  onLog: (e) => writeLogLine(formatLog(e)),
@@ -65,6 +79,7 @@ export const hostdCommand = defineCommand({
65
79
  portbroker,
66
80
  kakaoRenewal,
67
81
  webexRenewal,
82
+ teamsRenewal,
68
83
  currentHostDaemonHolder,
69
84
  restartPreflight: buildHostdRestartPreflight(cliEntry, version, defaultPreflightDeps),
70
85
  restart: hostdRestart,
@@ -76,6 +91,7 @@ export const hostdCommand = defineCommand({
76
91
  .then(() => portbroker.drain())
77
92
  .then(() => kakaoRenewal.drain())
78
93
  .then(() => webexRenewal.drain())
94
+ .then(() => teamsRenewal.drain())
79
95
  .then(() => process.exit(0))
80
96
  }
81
97
  process.on('SIGTERM', shutdown)
@@ -242,6 +258,22 @@ function formatLog(event: DaemonLogEvent | SupervisorLogEvent): string {
242
258
  return `[hostd] webex renewal scheduled container restart for ${event.containerName} account=${event.accountId}`
243
259
  case 'webex-renewal-restart-failed':
244
260
  return `[hostd] webex renewal container restart FAILED for ${event.containerName} account=${event.accountId}: ${event.reason}`
261
+ case 'teams-renewal-tick-start':
262
+ return `[hostd] teams renewal tick started for ${event.containerName}`
263
+ case 'teams-renewal-tick-skipped':
264
+ return `[hostd] teams renewal skipped for ${event.containerName}: ${event.reason}${event.expiresInMs !== undefined ? ` (expires in ${Math.round(event.expiresInMs / 1000 / 60)}m)` : ''}`
265
+ case 'teams-renewal-tick-ok':
266
+ return `[hostd] teams renewal OK for ${event.containerName} account=${event.accountId} (new token expires ${new Date(event.nextExpiresAt).toISOString()})`
267
+ case 'teams-renewal-tick-reauth-required':
268
+ return `[hostd] teams renewal REAUTH REQUIRED for ${event.containerName} account=${event.accountId} reason=${event.reason} — ${event.message}`
269
+ case 'teams-renewal-tick-transient-failure':
270
+ return `[hostd] teams renewal transient failure for ${event.containerName} account=${event.accountId}: ${event.reason}`
271
+ case 'teams-renewal-tick-error':
272
+ return `[hostd] teams renewal ERROR for ${event.containerName}: ${event.error}`
273
+ case 'teams-renewal-restart-scheduled':
274
+ return `[hostd] teams renewal scheduled container restart for ${event.containerName} account=${event.accountId}`
275
+ case 'teams-renewal-restart-failed':
276
+ return `[hostd] teams renewal container restart FAILED for ${event.containerName} account=${event.accountId}: ${event.reason}`
245
277
  }
246
278
  }
247
279
 
@@ -269,6 +301,15 @@ function webexChannelConfigured(cwd: string): boolean {
269
301
  }
270
302
  }
271
303
 
304
+ function teamsChannelConfigured(cwd: string): boolean {
305
+ try {
306
+ const cfg = loadConfigSync(cwd)
307
+ return cfg.channels?.teams !== undefined
308
+ } catch {
309
+ return false
310
+ }
311
+ }
312
+
272
313
  function formatPortForwardEvent(event: import('@/portbroker').PortForwardEvent): string {
273
314
  switch (event.kind) {
274
315
  case 'port-forward-opened':
package/src/cli/init.ts CHANGED
@@ -67,6 +67,7 @@ import { runKakaotalkBootstrap } from '@/init/kakaotalk-auth'
67
67
  import { customModelMetaFromOption, fetchModelOptions, type ModelOption } from '@/init/models-dev'
68
68
  import { makeOAuthLoginRunner, type OAuthLoginResult } from '@/init/oauth-login'
69
69
  import { detectInitProgress } from '@/init/progress'
70
+ import { runTeamsBootstrap } from '@/init/teams-auth'
70
71
  import {
71
72
  API_KEY_DASHBOARD_URL,
72
73
  MINIMAX_TOKEN_PLAN_DASHBOARD_URL,
@@ -74,7 +75,9 @@ import {
74
75
  type KeyValidationResult,
75
76
  } from '@/init/validate-api-key'
76
77
  import { runWebexBootstrap } from '@/init/webex-auth'
78
+ import type { TeamsAccountType } from '@/secrets/schema'
77
79
 
80
+ import { teamsDeviceCodeCallbacks } from './channel'
78
81
  import { fuzzyMatch } from './fuzzy-filter'
79
82
  import { buildOAuthCallbacks } from './oauth-callbacks'
80
83
  import { CANCEL_SYMBOL, promptPrivateKeyPem } from './prompt-pem'
@@ -225,6 +228,7 @@ export const init = defineCommand({
225
228
  kakaotalkPassword,
226
229
  webexEmail,
227
230
  webexPassword,
231
+ teamsAccountType,
228
232
  github: githubCredentials,
229
233
  } = channelSecrets
230
234
  const modelMeta = customModelMetaFromOption(model)
@@ -244,9 +248,11 @@ export const init = defineCommand({
244
248
  const reuseTelegram = reuseExistingChannel && channelChoice === 'telegram'
245
249
  const reuseKakaotalk = reuseExistingChannel && channelChoice === 'kakaotalk'
246
250
  const reuseWebex = reuseExistingChannel && channelChoice === 'webex'
251
+ const reuseTeams = reuseExistingChannel && channelChoice === 'teams'
247
252
  const reuseGithub = reuseExistingChannel && channelChoice === 'github'
248
253
  const wantsKakaotalk = (kakaotalkEmail !== undefined && kakaotalkPassword !== undefined) || reuseKakaotalk
249
254
  const wantsWebex = (webexEmail !== undefined && webexPassword !== undefined) || reuseWebex
255
+ const wantsTeams = teamsAccountType !== undefined || reuseTeams
250
256
  const wantsGithub = githubCredentials !== undefined || reuseGithub
251
257
  let hatchingOk = false
252
258
  let preflightFailure: Extract<DockerAvailability, { ok: false }> | null = null
@@ -299,6 +305,21 @@ export const init = defineCommand({
299
305
  }),
300
306
  }
301
307
  : {}),
308
+ ...(wantsTeams
309
+ ? {
310
+ withTeams: true,
311
+ ...(reuseTeams
312
+ ? {}
313
+ : {
314
+ runTeamsAuth: ({ cwd: agentDir }) =>
315
+ runTeamsBootstrap({
316
+ agentDir,
317
+ accountType: teamsAccountType!,
318
+ callbacks: teamsDeviceCodeCallbacks(),
319
+ }),
320
+ }),
321
+ }
322
+ : {}),
302
323
  ...(wantsGithub
303
324
  ? {
304
325
  withGithub: true,
@@ -407,7 +428,7 @@ interface WizardState {
407
428
  channelReuseExisting?: boolean
408
429
  }
409
430
 
410
- type ChannelChoice = 'slack' | 'discord' | 'telegram' | 'webex' | 'kakaotalk' | 'github' | 'none'
431
+ type ChannelChoice = 'slack' | 'discord' | 'telegram' | 'webex' | 'teams' | 'kakaotalk' | 'github' | 'none'
411
432
 
412
433
  interface CollectedInputs {
413
434
  model: ModelOption
@@ -429,6 +450,7 @@ interface CollectedInputs {
429
450
  telegramBotToken?: string
430
451
  webexEmail?: string
431
452
  webexPassword?: string
453
+ teamsAccountType?: TeamsAccountType
432
454
  kakaotalkEmail?: string
433
455
  kakaotalkPassword?: string
434
456
  // Structured (auth union + webhook + repo allowlist) rather than flat
@@ -1141,6 +1163,8 @@ function channelDisplayName(choice: Exclude<ChannelChoice, 'none'>): string {
1141
1163
  return 'Telegram'
1142
1164
  case 'webex':
1143
1165
  return 'Webex (User)'
1166
+ case 'teams':
1167
+ return 'Teams (User)'
1144
1168
  case 'kakaotalk':
1145
1169
  return 'KakaoTalk'
1146
1170
  case 'github':
@@ -1483,6 +1507,7 @@ async function pickChannel(initial: ChannelChoice | undefined): Promise<StepResu
1483
1507
  { value: 'discord', label: 'Discord' },
1484
1508
  { value: 'telegram', label: 'Telegram' },
1485
1509
  { value: 'webex', label: 'Webex (User)' },
1510
+ { value: 'teams', label: 'Teams (User)' },
1486
1511
  { value: 'kakaotalk', label: 'KakaoTalk' },
1487
1512
  { value: 'github', label: 'GitHub' },
1488
1513
  { value: 'none', label: 'Skip — no channel right now' },
@@ -1510,11 +1535,34 @@ async function runChannelFlow(
1510
1535
  return runTelegramFlow()
1511
1536
  case 'webex':
1512
1537
  return runWebexUserFlow()
1538
+ case 'teams':
1539
+ return runTeamsFlow()
1513
1540
  case 'github':
1514
1541
  return runGithubFlow(cwd)
1515
1542
  }
1516
1543
  }
1517
1544
 
1545
+ async function runTeamsFlow(): Promise<StepResult<CollectedInputs['channelSecrets']>> {
1546
+ note(
1547
+ [
1548
+ 'Teams signs in as your own Microsoft account via device-code login —',
1549
+ 'you get a short code to enter at microsoft.com/devicelogin, then approve.',
1550
+ 'The sign-in itself runs after scaffolding, not now.',
1551
+ ].join('\n'),
1552
+ 'About to log in to Teams',
1553
+ )
1554
+ const accountType = await select<TeamsAccountType>({
1555
+ message: 'Which kind of Microsoft account?',
1556
+ options: [
1557
+ { value: 'work', label: 'Work or school (Microsoft 365 / Azure AD)' },
1558
+ { value: 'personal', label: 'Personal Microsoft account (outlook.com, live.com, …)' },
1559
+ ],
1560
+ initialValue: 'work',
1561
+ })
1562
+ if (isCancel(accountType)) return back()
1563
+ return value({ teamsAccountType: accountType })
1564
+ }
1565
+
1518
1566
  async function runDiscordFlow(): Promise<StepResult<CollectedInputs['channelSecrets']>> {
1519
1567
  note(
1520
1568
  [
@@ -1903,6 +1951,9 @@ function reportProgress(
1903
1951
  case 'webex-auth':
1904
1952
  s.stop(reportWebexAuth(event.result))
1905
1953
  break
1954
+ case 'teams-auth':
1955
+ s.stop(reportTeamsAuth(event.result))
1956
+ break
1906
1957
  case 'github-webhooks':
1907
1958
  s.stop(formatEagerGithubWebhookInstallResult(event.result))
1908
1959
  break
@@ -1967,6 +2018,11 @@ function reportWebexAuth(result: { ok: true } | { ok: false; reason: string }):
1967
2018
  return `Webex login failed: ${result.reason}`
1968
2019
  }
1969
2020
 
2021
+ function reportTeamsAuth(result: { ok: true } | { ok: false; reason: string }): string {
2022
+ if (result.ok) return 'Teams credentials saved to secrets.json.'
2023
+ return `Teams login failed: ${result.reason}`
2024
+ }
2025
+
1970
2026
  // Hatching launches the container and foregrounds the TUI, so it steals stdin
1971
2027
  // and cannot share the spinner lifecycle with the other steps. Print plain
1972
2028
  // lines instead.
@@ -2050,6 +2106,7 @@ const START_MESSAGES: Record<Exclude<InitStep, 'hatching'>, string> = {
2050
2106
  'instagram-auth': 'Logging in to Instagram...',
2051
2107
  'kakaotalk-auth': 'Logging in to KakaoTalk...',
2052
2108
  'webex-auth': 'Logging in to Webex...',
2109
+ 'teams-auth': 'Logging in to Teams...',
2053
2110
  'github-webhooks': 'Installing GitHub repository webhooks...',
2054
2111
  install: 'Installing dependencies with bun...',
2055
2112
  dockerfile: 'Writing Dockerfile...',
@@ -15,6 +15,7 @@ export const CHANNEL_KINDS = [
15
15
  'telegram-bot',
16
16
  'webex',
17
17
  'webex-bot',
18
+ 'teams',
18
19
  'instagram',
19
20
  'line',
20
21
  'kakaotalk',
@@ -190,7 +191,14 @@ function buildDetail(kind: ChannelKind, channelConfig: unknown, secretsBlock: un
190
191
  const repos = isObjectRecord(channelConfig) && Array.isArray(channelConfig.repos) ? channelConfig.repos.length : 0
191
192
  return { detail: `${repos} repo${repos === 1 ? '' : 's'}` }
192
193
  }
193
- if (kind === 'line' || kind === 'instagram' || kind === 'kakaotalk' || kind === 'webex' || kind === 'discord') {
194
+ if (
195
+ kind === 'line' ||
196
+ kind === 'instagram' ||
197
+ kind === 'kakaotalk' ||
198
+ kind === 'webex' ||
199
+ kind === 'discord' ||
200
+ kind === 'teams'
201
+ ) {
194
202
  if (!isObjectRecord(secretsBlock)) return {}
195
203
  const accounts = isObjectRecord(secretsBlock.accounts) ? Object.keys(secretsBlock.accounts).length : 0
196
204
  const current = typeof secretsBlock.currentAccount === 'string' ? secretsBlock.currentAccount : undefined