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
@@ -0,0 +1,212 @@
1
+ import { renewCurrentAccount } from '@/secrets/teams-renewal'
2
+
3
+ // Teams skype tokens live only 60-90 minutes (far shorter than Webex's ~27h),
4
+ // so the tick is minutes not hours: 5 minutes gives ~3 refresh attempts inside
5
+ // the 15-minute renewal window before a token would lapse, while a fresh token
6
+ // short-circuits to a cheap no-op skip.
7
+ const DEFAULT_TICK_INTERVAL_MS = 5 * 60 * 1000
8
+
9
+ export type TeamsRenewalCallbacks = {
10
+ start: (input: TeamsRenewalStartInput) => void
11
+ stop: (containerName: string) => Promise<void>
12
+ drain: () => Promise<void>
13
+ }
14
+
15
+ export type TeamsRenewalStartInput = {
16
+ containerName: string
17
+ cwd: string
18
+ }
19
+
20
+ export type TeamsRenewalLogEvent =
21
+ | { kind: 'teams-renewal-tick-start'; containerName: string }
22
+ | { kind: 'teams-renewal-tick-skipped'; containerName: string; reason: string; expiresInMs?: number }
23
+ | { kind: 'teams-renewal-tick-ok'; containerName: string; accountId: string; nextExpiresAt: number }
24
+ | {
25
+ kind: 'teams-renewal-tick-reauth-required'
26
+ containerName: string
27
+ accountId: string
28
+ reason: string
29
+ message: string
30
+ }
31
+ | { kind: 'teams-renewal-tick-transient-failure'; containerName: string; accountId: string; reason: string }
32
+ | { kind: 'teams-renewal-tick-error'; containerName: string; error: string }
33
+ | { kind: 'teams-renewal-restart-scheduled'; containerName: string; accountId: string }
34
+ | { kind: 'teams-renewal-restart-failed'; containerName: string; accountId: string; reason: string }
35
+
36
+ export type TeamsRenewalManagerOptions = {
37
+ onLog?: (event: TeamsRenewalLogEvent) => void
38
+ tickIntervalMs?: number
39
+ renew?: typeof renewCurrentAccount
40
+ schedule?: (fn: () => void, intervalMs: number) => { stop: () => void }
41
+ // Invoked after a successful renewal so the host can restart the container and
42
+ // the in-memory TeamsClient picks up the fresh token. Without this, the cron
43
+ // writes a new token to secrets.json but the live client keeps the old token
44
+ // in its login closure (src/channels/adapters/teams.ts) and still fails to
45
+ // obtain an id_token for the realtime listener.
46
+ onRenewalOk?: (input: { containerName: string; cwd: string; accountId: string }) => Promise<void>
47
+ // Only start the renewal cron for containers whose typeclaw.json actually has
48
+ // a channels.teams block, so non-teams agents don't emit no_account skip logs.
49
+ shouldRenew?: (input: TeamsRenewalStartInput) => boolean
50
+ }
51
+
52
+ export function createTeamsRenewalManager(opts: TeamsRenewalManagerOptions = {}): TeamsRenewalCallbacks {
53
+ const intervalMs = opts.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS
54
+ const renew = opts.renew ?? renewCurrentAccount
55
+ const log = opts.onLog ?? (() => {})
56
+ const schedule =
57
+ opts.schedule ??
58
+ ((fn: () => void, ms: number) => {
59
+ const handle = setInterval(fn, ms)
60
+ return { stop: () => clearInterval(handle) }
61
+ })
62
+
63
+ const timers = new Map<string, { stop: () => void }>()
64
+ const latestInput = new Map<string, TeamsRenewalStartInput>()
65
+ const inFlight = new Map<string, Promise<void>>()
66
+ const pendingRerun = new Set<string>()
67
+
68
+ const runTick = async (input: TeamsRenewalStartInput): Promise<void> => {
69
+ log({ kind: 'teams-renewal-tick-start', containerName: input.containerName })
70
+ try {
71
+ const result = await renew({ agentDir: input.cwd })
72
+ if (result.kind === 'skipped') {
73
+ log({
74
+ kind: 'teams-renewal-tick-skipped',
75
+ containerName: input.containerName,
76
+ reason: result.reason,
77
+ ...(result.expiresInMs !== undefined ? { expiresInMs: result.expiresInMs } : {}),
78
+ })
79
+ } else if (result.kind === 'ok') {
80
+ log({
81
+ kind: 'teams-renewal-tick-ok',
82
+ containerName: input.containerName,
83
+ accountId: result.account_id,
84
+ nextExpiresAt: result.nextExpiresAt,
85
+ })
86
+ // A tick that started before stop()/drain() or before a re-register with
87
+ // a different cwd can finish here. Restarting a container that is no
88
+ // longer the current registration would resurrect a just-deregistered
89
+ // agent or fight a shutdown, so skip onRenewalOk unless this
90
+ // container+cwd is still the live registration.
91
+ const current = latestInput.get(input.containerName)
92
+ if (opts.onRenewalOk && current?.cwd === input.cwd) {
93
+ log({
94
+ kind: 'teams-renewal-restart-scheduled',
95
+ containerName: input.containerName,
96
+ accountId: result.account_id,
97
+ })
98
+ try {
99
+ await opts.onRenewalOk({
100
+ containerName: input.containerName,
101
+ cwd: input.cwd,
102
+ accountId: result.account_id,
103
+ })
104
+ } catch (err) {
105
+ log({
106
+ kind: 'teams-renewal-restart-failed',
107
+ containerName: input.containerName,
108
+ accountId: result.account_id,
109
+ reason: err instanceof Error ? err.message : String(err),
110
+ })
111
+ }
112
+ }
113
+ } else if (result.kind === 'reauth_required') {
114
+ log({
115
+ kind: 'teams-renewal-tick-reauth-required',
116
+ containerName: input.containerName,
117
+ accountId: result.account_id,
118
+ reason: result.reason,
119
+ message: result.message,
120
+ })
121
+ } else {
122
+ log({
123
+ kind: 'teams-renewal-tick-transient-failure',
124
+ containerName: input.containerName,
125
+ accountId: result.account_id,
126
+ reason: result.reason,
127
+ })
128
+ }
129
+ } catch (err) {
130
+ log({
131
+ kind: 'teams-renewal-tick-error',
132
+ containerName: input.containerName,
133
+ error: err instanceof Error ? err.message : String(err),
134
+ })
135
+ }
136
+ }
137
+
138
+ const scheduleTick = (containerName: string): Promise<void> => {
139
+ const existing = inFlight.get(containerName)
140
+ if (existing) {
141
+ pendingRerun.add(containerName)
142
+ return existing
143
+ }
144
+ const promise = (async () => {
145
+ while (true) {
146
+ const input = latestInput.get(containerName)
147
+ if (!input) return
148
+ await runTick(input)
149
+ if (!pendingRerun.has(containerName)) return
150
+ pendingRerun.delete(containerName)
151
+ }
152
+ })().finally(() => {
153
+ inFlight.delete(containerName)
154
+ pendingRerun.delete(containerName)
155
+ })
156
+ inFlight.set(containerName, promise)
157
+ return promise
158
+ }
159
+
160
+ return {
161
+ start(input: TeamsRenewalStartInput): void {
162
+ // Tear down any prior registration BEFORE the shouldRenew gate: the daemon
163
+ // calls start() on every registration, so a container that had Teams can
164
+ // re-register to a non-Teams cwd; returning early without clearing would
165
+ // leave the old timer ticking and let a post-login restart guard match the
166
+ // stale cwd. Clearing latestInput also fails an in-flight tick's
167
+ // onRenewalOk re-check.
168
+ const existing = timers.get(input.containerName)
169
+ if (existing) {
170
+ existing.stop()
171
+ timers.delete(input.containerName)
172
+ }
173
+ latestInput.delete(input.containerName)
174
+
175
+ if (opts.shouldRenew && !opts.shouldRenew(input)) return
176
+
177
+ latestInput.set(input.containerName, input)
178
+ const handle = schedule(() => {
179
+ void scheduleTick(input.containerName)
180
+ }, intervalMs)
181
+ timers.set(input.containerName, handle)
182
+ void scheduleTick(input.containerName)
183
+ },
184
+
185
+ // Must NOT await the in-flight tick: a successful tick runs onRenewalOk →
186
+ // hostdRestart → container stop() → deregister RPC → teamsRenewal.stop(), so
187
+ // awaiting inFlight here waits on the very tick parked waiting for this
188
+ // restart — a self-deadlock. Clearing latestInput (not the await) is what
189
+ // fails the tick's onRenewalOk guard; drain() still awaits.
190
+ stop(containerName: string): Promise<void> {
191
+ const handle = timers.get(containerName)
192
+ if (handle) {
193
+ timers.delete(containerName)
194
+ handle.stop()
195
+ }
196
+ latestInput.delete(containerName)
197
+ return Promise.resolve()
198
+ },
199
+
200
+ async drain(): Promise<void> {
201
+ for (const [, handle] of timers) handle.stop()
202
+ timers.clear()
203
+ // Clear latestInput AFTER awaiting in-flight: the onRenewalOk guard reads
204
+ // latestInput, so clearing first would suppress the restart of a tick that
205
+ // is mid-refresh when drain() runs. drain() is shutdown — it waits for
206
+ // that work to finish rather than dropping it.
207
+ const promises = Array.from(inFlight.values())
208
+ await Promise.allSettled(promises)
209
+ latestInput.clear()
210
+ },
211
+ }
212
+ }
@@ -21,7 +21,7 @@ export const INIT_CHECKPOINT_PATH = join('.typeclaw', 'init-progress.json')
21
21
 
22
22
  export const WIZARD_CHECKPOINT_VERSION = 1
23
23
 
24
- export type WizardChannelChoice = 'slack' | 'discord' | 'telegram' | 'webex' | 'kakaotalk' | 'github' | 'none'
24
+ export type WizardChannelChoice = 'slack' | 'discord' | 'telegram' | 'webex' | 'teams' | 'kakaotalk' | 'github' | 'none'
25
25
 
26
26
  export type AuthMethod = 'api-key' | 'oauth'
27
27
 
package/src/init/index.ts CHANGED
@@ -89,6 +89,7 @@ export type InitStep =
89
89
  | 'instagram-auth'
90
90
  | 'kakaotalk-auth'
91
91
  | 'webex-auth'
92
+ | 'teams-auth'
92
93
  | 'github-webhooks'
93
94
  | 'install'
94
95
  | 'dockerfile'
@@ -97,6 +98,7 @@ export type InitStep =
97
98
 
98
99
  export type KakaotalkAuthResult = { ok: true } | { ok: false; reason: string }
99
100
  export type WebexAuthResult = { ok: true } | { ok: false; reason: string }
101
+ export type TeamsAuthResult = { ok: true } | { ok: false; reason: string }
100
102
  export type SlackAuthResult = { ok: true } | { ok: false; reason: string }
101
103
  export type DiscordAuthResult = { ok: true } | { ok: false; reason: string }
102
104
  export type InstagramAuthResult = { ok: true } | { ok: false; reason: string }
@@ -137,6 +139,8 @@ export type InitStepEvent =
137
139
  | { step: 'kakaotalk-auth'; phase: 'done'; result: KakaotalkAuthResult }
138
140
  | { step: 'webex-auth'; phase: 'start' }
139
141
  | { step: 'webex-auth'; phase: 'done'; result: WebexAuthResult }
142
+ | { step: 'teams-auth'; phase: 'start' }
143
+ | { step: 'teams-auth'; phase: 'done'; result: TeamsAuthResult }
140
144
  | { step: 'discord-auth'; phase: 'start' }
141
145
  | { step: 'discord-auth'; phase: 'done'; result: DiscordAuthResult }
142
146
  | { step: 'instagram-auth'; phase: 'start' }
@@ -170,6 +174,7 @@ export type HatchRunner = (options: {
170
174
 
171
175
  export type KakaotalkAuthRunner = (options: { cwd: string }) => Promise<KakaotalkAuthResult>
172
176
  export type WebexAuthRunner = (options: { cwd: string }) => Promise<WebexAuthResult>
177
+ export type TeamsAuthRunner = (options: { cwd: string }) => Promise<TeamsAuthResult>
173
178
 
174
179
  export type LineAuthResult = { ok: true } | { ok: false; reason: string }
175
180
  export type LineAuthRunner = (options: { cwd: string }) => Promise<LineAuthResult>
@@ -228,11 +233,13 @@ export type InitOptions = {
228
233
  withTelegram?: boolean
229
234
  withWebex?: boolean
230
235
  withWebexUser?: boolean
236
+ withTeams?: boolean
231
237
  withInstagram?: boolean
232
238
  withKakaotalk?: boolean
233
239
  withGithub?: boolean
234
240
  runKakaotalkAuth?: KakaotalkAuthRunner
235
241
  runWebexAuth?: WebexAuthRunner
242
+ runTeamsAuth?: TeamsAuthRunner
236
243
  runDiscordAuth?: DiscordAuthRunner
237
244
  runInstagramAuth?: InstagramAuthRunner
238
245
  // Structured GitHub credentials collected by the wizard. When omitted and
@@ -280,11 +287,13 @@ export async function runInit({
280
287
  withTelegram,
281
288
  withWebex,
282
289
  withWebexUser = false,
290
+ withTeams = false,
283
291
  withInstagram = false,
284
292
  withKakaotalk = false,
285
293
  withGithub = false,
286
294
  runKakaotalkAuth,
287
295
  runWebexAuth,
296
+ runTeamsAuth,
288
297
  runDiscordAuth,
289
298
  runInstagramAuth,
290
299
  githubCredentials,
@@ -367,6 +376,7 @@ export async function runInit({
367
376
  withTelegram: wantsTelegram,
368
377
  withWebex: wantsWebex,
369
378
  withWebexUser,
379
+ withTeams,
370
380
  withInstagram,
371
381
  withKakaotalk,
372
382
  platform,
@@ -412,6 +422,15 @@ export async function runInit({
412
422
  }
413
423
  }
414
424
 
425
+ if (withTeams && runTeamsAuth !== undefined) {
426
+ emit({ step: 'teams-auth', phase: 'start' })
427
+ const result = await runTeamsAuth({ cwd })
428
+ emit({ step: 'teams-auth', phase: 'done', result })
429
+ if (!result.ok) {
430
+ throw new Error(`Teams authentication failed: ${result.reason}`)
431
+ }
432
+ }
433
+
415
434
  if (withDiscordUser) {
416
435
  emit({ step: 'discord-auth', phase: 'start' })
417
436
  const runner = runDiscordAuth ?? defaultDiscordAuthRunner
@@ -482,6 +501,7 @@ export async function runInit({
482
501
  if (wantsTelegram) configuredChannels.push('telegram-bot')
483
502
  if (wantsWebex) configuredChannels.push('webex-bot')
484
503
  if (withWebexUser) configuredChannels.push('webex')
504
+ if (withTeams) configuredChannels.push('teams')
485
505
  if (withInstagram) configuredChannels.push('instagram')
486
506
  if (withKakaotalk) configuredChannels.push('kakaotalk')
487
507
  if (withGithub) configuredChannels.push('github')
@@ -653,6 +673,7 @@ export type ScaffoldOptions = {
653
673
  withTelegram?: boolean
654
674
  withWebex?: boolean
655
675
  withWebexUser?: boolean
676
+ withTeams?: boolean
656
677
  withInstagram?: boolean
657
678
  withKakaotalk?: boolean
658
679
  // Defaults to `process.platform`; controls the dev-mode typeclaw spec
@@ -692,6 +713,7 @@ export async function scaffold(root: string, options: ScaffoldOptions = {}): Pro
692
713
  if (options.withTelegram) channels['telegram-bot'] = {}
693
714
  if (options.withWebex) channels['webex-bot'] = {}
694
715
  if (options.withWebexUser) channels.webex = {}
716
+ if (options.withTeams) channels.teams = {}
695
717
  if (options.withInstagram) channels.instagram = {}
696
718
  if (options.withKakaotalk) channels.kakaotalk = {}
697
719
  if (Object.keys(channels).length > 0) config.channels = channels
@@ -1008,7 +1030,7 @@ export async function hasExistingOAuthCredentials(root: string, providerId: Know
1008
1030
  // kakaotalk` anyway — better to re-auth now during init.
1009
1031
  export async function hasExistingChannelSecrets(
1010
1032
  root: string,
1011
- channel: 'discord' | 'slack' | 'telegram' | 'webex' | 'instagram' | 'line' | 'kakaotalk' | 'github',
1033
+ channel: 'discord' | 'slack' | 'telegram' | 'webex' | 'teams' | 'instagram' | 'line' | 'kakaotalk' | 'github',
1012
1034
  ): Promise<boolean> {
1013
1035
  const channels = new SecretsBackend(join(root, 'secrets.json')).tryReadChannelsSync()
1014
1036
  if (channels === null) return false
@@ -1021,6 +1043,8 @@ export async function hasExistingChannelSecrets(
1021
1043
  return hasSecretField(channels['telegram-bot'], 'token')
1022
1044
  case 'webex':
1023
1045
  return hasCurrentWebexAccount(channels.webex)
1046
+ case 'teams':
1047
+ return hasCurrentTeamsAccount(channels.teams)
1024
1048
  case 'github':
1025
1049
  // GitHub credentials alone are not enough to scaffold a working
1026
1050
  // channel: typeclaw.json#channels.github also needs webhookUrl and
@@ -1105,6 +1129,33 @@ function hasCurrentWebexAccount(block: unknown): boolean {
1105
1129
  return typeof token === 'string' && token.length > 0 && typeof email === 'string' && isObjectRecord(encryptedPassword)
1106
1130
  }
1107
1131
 
1132
+ // A Teams block is only reusable when the current account can survive
1133
+ // unattended: the Skype access token lapses in ~60-90min, so silent renewal
1134
+ // needs the full AAD refresh trio (refresh token + client id + tenant id). An
1135
+ // access-token-only block (e.g. a hand-pasted token) would go stale with no way
1136
+ // to re-mint, so treat it as not-configured and let the wizard re-run the
1137
+ // device-code login rather than wiring a channel that dies within the hour.
1138
+ function hasCurrentTeamsAccount(block: unknown): boolean {
1139
+ if (!isObjectRecord(block)) return false
1140
+ const current = (block as { currentAccount?: unknown }).currentAccount
1141
+ if (typeof current !== 'string' || current.length === 0) return false
1142
+ const accounts = (block as { accounts?: unknown }).accounts
1143
+ if (!isObjectRecord(accounts)) return false
1144
+ const account = accounts[current]
1145
+ if (!isObjectRecord(account)) return false
1146
+ return (
1147
+ hasNonEmptyString(account, 'access_token') &&
1148
+ hasNonEmptyString(account, 'aad_refresh_token') &&
1149
+ hasNonEmptyString(account, 'aad_client_id') &&
1150
+ hasNonEmptyString(account, 'aad_tenant_id')
1151
+ )
1152
+ }
1153
+
1154
+ function hasNonEmptyString(record: Record<string, unknown>, key: string): boolean {
1155
+ const value = record[key]
1156
+ return typeof value === 'string' && value.length > 0
1157
+ }
1158
+
1108
1159
  function isObjectRecord(value: unknown): value is Record<string, unknown> {
1109
1160
  return typeof value === 'object' && value !== null && !Array.isArray(value)
1110
1161
  }
@@ -1149,6 +1200,7 @@ export type ChannelKind =
1149
1200
  | 'telegram-bot'
1150
1201
  | 'webex'
1151
1202
  | 'webex-bot'
1203
+ | 'teams'
1152
1204
  | 'instagram'
1153
1205
  | 'line'
1154
1206
  | 'kakaotalk'
@@ -1166,6 +1218,7 @@ export const CHANNEL_KINDS: ReadonlyArray<ChannelKind> = [
1166
1218
  'telegram-bot',
1167
1219
  'webex',
1168
1220
  'webex-bot',
1221
+ 'teams',
1169
1222
  'instagram',
1170
1223
  'line',
1171
1224
  'kakaotalk',
@@ -1194,6 +1247,8 @@ export type AddChannelStepEvent =
1194
1247
  | { step: 'kakaotalk-auth'; phase: 'done'; result: KakaotalkAuthResult }
1195
1248
  | { step: 'webex-auth'; phase: 'start' }
1196
1249
  | { step: 'webex-auth'; phase: 'done'; result: WebexAuthResult }
1250
+ | { step: 'teams-auth'; phase: 'start' }
1251
+ | { step: 'teams-auth'; phase: 'done'; result: TeamsAuthResult }
1197
1252
  | { step: 'discord-auth'; phase: 'start' }
1198
1253
  | { step: 'discord-auth'; phase: 'done'; result: DiscordAuthResult }
1199
1254
  | { step: 'slack-auth'; phase: 'start' }
@@ -1217,6 +1272,7 @@ export type AddChannelOptions = {
1217
1272
  | { channel: 'telegram-bot'; telegramBotToken: string }
1218
1273
  | { channel: 'webex-bot'; webexBotToken: string }
1219
1274
  | { channel: 'webex'; runWebexAuth: WebexAuthRunner }
1275
+ | { channel: 'teams'; runTeamsAuth: TeamsAuthRunner }
1220
1276
  | { channel: 'instagram'; runInstagramAuth: InstagramAuthRunner }
1221
1277
  | { channel: 'line'; runLineAuth: LineAuthRunner }
1222
1278
  | { channel: 'kakaotalk'; runKakaotalkAuth: KakaotalkAuthRunner }
@@ -1276,6 +1332,13 @@ export async function runAddChannel(options: AddChannelOptions): Promise<void> {
1276
1332
  if (!result.ok) throw new Error(`Webex authentication failed: ${result.reason}`)
1277
1333
  }
1278
1334
 
1335
+ if (options.channel === 'teams') {
1336
+ emit({ step: 'teams-auth', phase: 'start' })
1337
+ const result = await options.runTeamsAuth({ cwd: options.cwd })
1338
+ emit({ step: 'teams-auth', phase: 'done', result })
1339
+ if (!result.ok) throw new Error(`Teams authentication failed: ${result.reason}`)
1340
+ }
1341
+
1279
1342
  if (options.channel === 'discord') {
1280
1343
  emit({ step: 'discord-auth', phase: 'start' })
1281
1344
  const result = await options.runDiscordAuth({ cwd: options.cwd })
@@ -1371,6 +1434,10 @@ function channelSecretsFromOptions(options: AddChannelOptions): ChannelSecrets {
1371
1434
  return { token: options.webexBotToken }
1372
1435
  case 'webex':
1373
1436
  return {}
1437
+ case 'teams':
1438
+ // Teams auth writes its structured account block directly to
1439
+ // secrets.json#channels.teams before config mutation.
1440
+ return {}
1374
1441
  case 'instagram':
1375
1442
  return {}
1376
1443
  case 'line':
@@ -14,6 +14,7 @@ const CHANNEL_LABELS: Record<ChannelKind, string> = {
14
14
  'telegram-bot': 'Telegram',
15
15
  webex: 'Webex (User)',
16
16
  'webex-bot': 'Webex',
17
+ teams: 'Teams',
17
18
  instagram: 'Instagram',
18
19
  line: 'LINE',
19
20
  kakaotalk: 'KakaoTalk',
@@ -0,0 +1,111 @@
1
+ import { join } from 'node:path'
2
+
3
+ import {
4
+ loginWithDeviceCode as upstreamLoginWithDeviceCode,
5
+ TeamsCredentialManager,
6
+ type DeviceCodePrompt,
7
+ type DeviceLoginResult,
8
+ } from 'agent-messenger/teams'
9
+
10
+ import type { TeamsAccountRecord, TeamsAccountType } from '@/secrets/schema'
11
+ import { SecretsTeamsCredentialStore } from '@/secrets/teams-store'
12
+
13
+ export type TeamsBootstrapStatus = { ok: true } | { ok: false; reason: string }
14
+
15
+ export type LoginWithDeviceCodeFn = typeof upstreamLoginWithDeviceCode
16
+
17
+ export type TeamsDeviceCodeCallbacks = {
18
+ onCode: (prompt: DeviceCodePrompt) => void | Promise<void>
19
+ onPending?: () => void
20
+ }
21
+
22
+ export type TeamsLoginInput = {
23
+ agentDir: string
24
+ accountType: TeamsAccountType
25
+ callbacks: TeamsDeviceCodeCallbacks
26
+ loginWithDeviceCode?: LoginWithDeviceCodeFn
27
+ // The SDK persists the minted token in its own config dir; scope it to the
28
+ // agent folder so the login is self-contained and read-back is deterministic
29
+ // instead of leaking into the operator's global agent-messenger config.
30
+ credManager?: TeamsCredentialManager
31
+ }
32
+
33
+ export function teamsSecretsPath(agentDir: string): string {
34
+ return join(agentDir, 'secrets.json')
35
+ }
36
+
37
+ export async function runTeamsBootstrap(input: TeamsLoginInput): Promise<TeamsBootstrapStatus> {
38
+ try {
39
+ const loginWithDeviceCode = input.loginWithDeviceCode ?? upstreamLoginWithDeviceCode
40
+ const credManager = input.credManager ?? new TeamsCredentialManager(teamsConfigDir(input.agentDir))
41
+
42
+ const result = await loginWithDeviceCode(
43
+ {
44
+ accountType: input.accountType,
45
+ onCode: input.callbacks.onCode,
46
+ ...(input.callbacks.onPending !== undefined ? { onPending: input.callbacks.onPending } : {}),
47
+ },
48
+ credManager,
49
+ )
50
+
51
+ const record = await buildAccountRecord(result, credManager)
52
+ if (record === null) {
53
+ return { ok: false, reason: 'device-code login did not persist a usable Teams token' }
54
+ }
55
+
56
+ const store = new SecretsTeamsCredentialStore({ mode: 'host', secretsPath: teamsSecretsPath(input.agentDir) })
57
+ await store.setAccount(record)
58
+ await store.setCurrentAccount(record.account_id)
59
+
60
+ return { ok: true }
61
+ } catch (err) {
62
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) }
63
+ }
64
+ }
65
+
66
+ // The SDK writes the minted token into its own credential manager keyed by
67
+ // account type; read it back and translate into typeclaw's TeamsAccountRecord
68
+ // shape for secrets.json. The AAD refresh trio is what lets the runtime adapter
69
+ // silently re-mint the ~60-90min skype token, so it must survive the hop.
70
+ async function buildAccountRecord(
71
+ result: DeviceLoginResult,
72
+ credManager: TeamsCredentialManager,
73
+ ): Promise<TeamsAccountRecord | null> {
74
+ const config = await credManager.loadConfig()
75
+ const account = config?.accounts[result.accountType]
76
+ if (account === undefined || account.token === '') return null
77
+
78
+ const now = new Date().toISOString()
79
+ const accountId = accountIdFor(result)
80
+ return {
81
+ account_id: accountId,
82
+ access_token: account.token,
83
+ ...(account.token_expires_at !== undefined ? { token_expires_at: account.token_expires_at } : {}),
84
+ account_type: result.accountType,
85
+ ...(account.region !== undefined ? { region: account.region } : {}),
86
+ ...(result.userName !== undefined ? { user_name: result.userName } : {}),
87
+ ...(account.aad_refresh_token !== undefined ? { aad_refresh_token: account.aad_refresh_token } : {}),
88
+ ...(account.aad_client_id !== undefined ? { aad_client_id: account.aad_client_id } : {}),
89
+ ...(account.aad_tenant_id !== undefined ? { aad_tenant_id: account.aad_tenant_id } : {}),
90
+ created_at: now,
91
+ updated_at: now,
92
+ }
93
+ }
94
+
95
+ // A stable per-account id for secrets.json. Teams has no cheap unique user id
96
+ // surfaced by the device-code result, so key on the display name when present
97
+ // and fall back to the account type, so a re-auth of the same account replaces
98
+ // its record rather than accumulating duplicates.
99
+ function accountIdFor(result: DeviceLoginResult): string {
100
+ const name = result.userName?.trim()
101
+ return name !== undefined && name !== '' ? name : result.accountType
102
+ }
103
+
104
+ // The SDK caches the minted token in this dir; keep it under the already
105
+ // gitignored `.typeclaw/` local-scratch root so Teams tokens / AAD refresh
106
+ // tokens can never be staged into git by accident.
107
+ function teamsConfigDir(agentDir: string): string {
108
+ return join(agentDir, '.typeclaw', 'teams-auth')
109
+ }
110
+
111
+ export type { DeviceCodePrompt, DeviceLoginResult }
@@ -3,11 +3,15 @@ import { toRef } from '@/channels/adapters/webex-id-ref'
3
3
 
4
4
  const ADAPTER_DISPLAY: Record<string, string> = {
5
5
  'slack-bot': 'Slack',
6
+ slack: 'Slack',
6
7
  'discord-bot': 'Discord',
8
+ discord: 'Discord',
7
9
  github: 'GitHub',
8
10
  'telegram-bot': 'Telegram',
9
11
  webex: 'Webex',
10
12
  'webex-bot': 'Webex',
13
+ teams: 'Teams',
14
+ instagram: 'Instagram',
11
15
  line: 'LINE',
12
16
  kakaotalk: 'KakaoTalk',
13
17
  }
@@ -16,7 +16,17 @@
16
16
  // error messages with typo suggestions; a single big regex would only ever
17
17
  // say "didn't match".
18
18
 
19
- export const PLATFORMS = ['slack', 'discord', 'telegram', 'webex', 'instagram', 'line', 'kakao', 'github'] as const
19
+ export const PLATFORMS = [
20
+ 'slack',
21
+ 'discord',
22
+ 'telegram',
23
+ 'webex',
24
+ 'teams',
25
+ 'instagram',
26
+ 'line',
27
+ 'kakao',
28
+ 'github',
29
+ ] as const
20
30
  export type Platform = (typeof PLATFORMS)[number]
21
31
 
22
32
  const SUBAGENT_NAME = /^[a-z][a-z0-9-]*$/
@@ -13,6 +13,7 @@ const ADAPTER_TO_PLATFORM: Record<AdapterId, Platform> = {
13
13
  'telegram-bot': 'telegram',
14
14
  webex: 'webex',
15
15
  'webex-bot': 'webex',
16
+ teams: 'teams',
16
17
  line: 'line',
17
18
  kakaotalk: 'kakao',
18
19
  }
@@ -27,7 +27,7 @@ export type PartialChannelOrigin = {
27
27
 
28
28
  const ADAPTER_TO_PLATFORM: Record<
29
29
  ChannelKey['adapter'],
30
- 'slack' | 'discord' | 'telegram' | 'webex' | 'kakao' | 'line' | 'github' | 'instagram'
30
+ 'slack' | 'discord' | 'telegram' | 'webex' | 'teams' | 'kakao' | 'line' | 'github' | 'instagram'
31
31
  > = {
32
32
  slack: 'slack',
33
33
  'slack-bot': 'slack',
@@ -38,6 +38,7 @@ const ADAPTER_TO_PLATFORM: Record<
38
38
  'telegram-bot': 'telegram',
39
39
  webex: 'webex',
40
40
  'webex-bot': 'webex',
41
+ teams: 'teams',
41
42
  line: 'line',
42
43
  kakaotalk: 'kakao',
43
44
  }