typeclaw 0.43.1 → 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 (56) 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 +14 -2
  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/tools/channel-fetch-attachment.ts +45 -3
  10. package/src/agent/tools/channel-reply.ts +41 -18
  11. package/src/agent/tools/channel-send.ts +82 -13
  12. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  13. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  14. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  15. package/src/bundled-plugins/memory/README.md +9 -9
  16. package/src/bundled-plugins/memory/index.ts +40 -9
  17. package/src/channels/adapters/github/inbound.ts +20 -14
  18. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  19. package/src/channels/adapters/teams-classify.ts +144 -0
  20. package/src/channels/adapters/teams-id-token.ts +112 -0
  21. package/src/channels/adapters/teams-key.ts +32 -0
  22. package/src/channels/adapters/teams.ts +519 -0
  23. package/src/channels/github-review-turn-ledger.ts +43 -0
  24. package/src/channels/index.ts +1 -1
  25. package/src/channels/manager.ts +54 -1
  26. package/src/channels/router.ts +302 -39
  27. package/src/channels/schema.ts +9 -0
  28. package/src/cli/channel.ts +92 -4
  29. package/src/cli/hostd.ts +41 -0
  30. package/src/cli/init.ts +58 -1
  31. package/src/config/channels-mutation.ts +9 -1
  32. package/src/cron/index.ts +16 -4
  33. package/src/cron/reloadable.ts +25 -7
  34. package/src/cron/scheduler.ts +4 -0
  35. package/src/cron/schema.ts +143 -35
  36. package/src/doctor/channel-checks.ts +27 -0
  37. package/src/hostd/daemon.ts +23 -3
  38. package/src/hostd/protocol.ts +2 -0
  39. package/src/hostd/teams-renewal-manager.ts +212 -0
  40. package/src/init/checkpoint.ts +1 -1
  41. package/src/init/index.ts +68 -1
  42. package/src/init/run-owner-claim.ts +1 -0
  43. package/src/init/teams-auth.ts +111 -0
  44. package/src/inspect/label.ts +4 -0
  45. package/src/permissions/match-rule.ts +11 -1
  46. package/src/permissions/resolve.ts +1 -0
  47. package/src/role-claim/match-rule.ts +2 -1
  48. package/src/run/index.ts +35 -8
  49. package/src/run/llm-fetch-observer.ts +27 -5
  50. package/src/sandbox/build.ts +12 -0
  51. package/src/sandbox/policy.ts +13 -0
  52. package/src/sandbox/writable-zones.ts +46 -10
  53. package/src/secrets/schema.ts +32 -0
  54. package/src/secrets/teams-renewal.ts +229 -0
  55. package/src/secrets/teams-store.ts +108 -0
  56. package/typeclaw.schema.json +163 -3
@@ -66,15 +66,28 @@ export type HandlerJob = z.infer<typeof baseJob> & {
66
66
  export type CronJob = ParsedCronJob | HandlerJob
67
67
  export type CronFile = z.infer<typeof cronFileSchema>
68
68
 
69
- export type ParseCronResult = { ok: true; file: CronFile } | { ok: false; reason: string }
69
+ export type CronParseWarning = { jobId?: string; index: number; reason: string }
70
70
 
71
- // `edit` is the strict path for an agent writing/editing cron.json: a past
72
- // enabled `at` is rejected so a reminder scheduled in the past surfaces as an
73
- // error instead of silently becoming a never-firing no-op. `load` is the
74
- // tolerant path the scheduler uses on boot/reload: a fired or missed one-shot
75
- // lingers on disk with a now-past `at`, and rejecting it would brick the whole
76
- // file — so `load` accepts it and lets the scheduler retire it passively.
77
- export type ParseCronMode = 'edit' | 'load'
71
+ export type ParseCronResult =
72
+ | { ok: true; file: CronFile; warnings?: CronParseWarning[] }
73
+ | { ok: false; reason: string }
74
+
75
+ // `edit` is the strict authoring path for an agent writing/editing cron.json: a
76
+ // past enabled `at`/`until` is rejected so a job scheduled in the past surfaces
77
+ // as an error instead of silently becoming a never-firing no-op, and any single
78
+ // bad job fails the whole file so the author sees it.
79
+ //
80
+ // `load` is the strict programmatic/security path (cron-promotion inspection,
81
+ // reload validation): it tolerates fired past `at`/`until` tombstones but still
82
+ // fails the whole file on any structurally bad job, so a security policy never
83
+ // reasons over a silently-filtered subset.
84
+ //
85
+ // `boot` is the runtime-survivability path used only by the scheduler on
86
+ // container boot/reload: it isolates bad individual jobs (skips them, emits a
87
+ // warning) and keeps the valid ones, so one malformed job can never brick every
88
+ // cron — including the plugin-registered dreaming job that isn't even in the
89
+ // file. It shares `load`'s tolerance for expired `at`/`until`.
90
+ export type ParseCronMode = 'edit' | 'load' | 'boot'
78
91
 
79
92
  export type ParseCronOptions = {
80
93
  // When provided, prompt jobs with a `subagent` field are validated against
@@ -106,6 +119,81 @@ export function parseCronJson(raw: string, options: ParseCronJsonOptions = {}):
106
119
  })
107
120
  }
108
121
 
122
+ // Authoring-delta validation for a cron.json edit. Strict `edit` mode fails the
123
+ // whole file on any enabled job with a past `at`/`until`, which lets a single
124
+ // stale pre-existing job (an expired `until` from weeks ago) brick EVERY edit —
125
+ // including the edit that would remove it, or an edit to a completely unrelated
126
+ // job. That is the trap: expired history holds the file hostage.
127
+ //
128
+ // This validator parses the proposed content in tolerant `load` mode (so it
129
+ // still catches structural errors and duplicate ids), then applies the strict
130
+ // `edit` timing check ONLY to jobs whose timing is newly-authored — a job that
131
+ // is new, or whose timing fields changed versus the on-disk baseline. A job
132
+ // carried over unchanged keeps its stale boundary tolerated, so removing it or
133
+ // editing a sibling is never blocked. Adding a new past job, or re-timing an
134
+ // existing one into the past, is still rejected exactly as before.
135
+ //
136
+ // `existingRaw` is the current on-disk cron.json (undefined on first-init). If
137
+ // it is missing or unparseable the baseline is empty, so every proposed job is
138
+ // treated as new and strict-checked — the safe direction (fail closed).
139
+ export function validateCronEdit(
140
+ proposedRaw: string,
141
+ existingRaw: string | undefined,
142
+ options: ParseCronOptions = {},
143
+ ): ParseCronResult {
144
+ const now = options.now ?? Date.now()
145
+ const proposed = parseCronJson(proposedRaw, { ...options, mode: 'load' })
146
+ if (!proposed.ok) return proposed
147
+
148
+ const baselineTiming = existingRaw !== undefined ? timingSignaturesByJobId(existingRaw) : new Map<string, string>()
149
+
150
+ for (const job of proposed.file.jobs) {
151
+ const prior = baselineTiming.get(job.id)
152
+ const timingUnchanged = prior !== undefined && prior === timingSignature(job)
153
+ if (timingUnchanged) continue
154
+ const timingError = validateTiming(job, now, 'edit')
155
+ if (timingError !== null) return { ok: false, reason: `job ${job.id}: ${timingError}` }
156
+ }
157
+
158
+ return proposed
159
+ }
160
+
161
+ // The timing fields whose change re-arms the strict past-boundary check. A job
162
+ // is exempt from the stale-boundary rejection only when ALL of these match the
163
+ // baseline; touching any of them (including flipping `enabled` back on) counts
164
+ // as re-authoring the schedule and is strict-checked afresh.
165
+ function timingSignature(job: {
166
+ schedule?: string | undefined
167
+ at?: string | undefined
168
+ until?: string | undefined
169
+ count?: number | undefined
170
+ timezone?: string | undefined
171
+ enabled: boolean
172
+ }): string {
173
+ return JSON.stringify([
174
+ job.schedule ?? null,
175
+ job.at ?? null,
176
+ job.until ?? null,
177
+ job.count ?? null,
178
+ job.timezone ?? null,
179
+ job.enabled,
180
+ ])
181
+ }
182
+
183
+ function timingSignaturesByJobId(raw: string): Map<string, string> {
184
+ const signatures = new Map<string, string>()
185
+ let json: unknown
186
+ try {
187
+ json = JSON.parse(raw)
188
+ } catch {
189
+ return signatures
190
+ }
191
+ const parsed = cronFileSchema.safeParse(json)
192
+ if (!parsed.success) return signatures
193
+ for (const job of parsed.data.jobs) signatures.set(job.id, timingSignature(job))
194
+ return signatures
195
+ }
196
+
109
197
  export function parseCronFile(raw: unknown, options: ParseCronOptions = {}): ParseCronResult {
110
198
  const parsed = cronFileSchema.safeParse(raw)
111
199
  if (!parsed.success) {
@@ -113,40 +201,56 @@ export function parseCronFile(raw: unknown, options: ParseCronOptions = {}): Par
113
201
  }
114
202
 
115
203
  const file = parsed.data
204
+ const mode = options.mode ?? 'load'
205
+ const now = options.now ?? Date.now()
206
+
207
+ const validJobs: ParsedCronJob[] = []
208
+ const warnings: CronParseWarning[] = []
116
209
  const seen = new Set<string>()
117
- for (const job of file.jobs) {
118
- if (seen.has(job.id)) {
119
- return { ok: false, reason: `duplicate job id: ${job.id}` }
210
+
211
+ for (const [index, job] of file.jobs.entries()) {
212
+ const duplicate = seen.has(job.id)
213
+ const reason = duplicate
214
+ ? `duplicate job id: ${job.id}`
215
+ : validateJob(job, { now, mode, subagents: options.subagents })
216
+
217
+ if (reason !== null) {
218
+ const scoped = duplicate ? reason : `job ${job.id}: ${reason}`
219
+ if (mode !== 'boot') return { ok: false, reason: scoped }
220
+ warnings.push({ jobId: job.id, index, reason: scoped })
221
+ continue
120
222
  }
223
+
121
224
  seen.add(job.id)
225
+ validJobs.push(job)
226
+ }
122
227
 
123
- const timingError = validateTiming(job, options.now ?? Date.now(), options.mode ?? 'load')
124
- if (timingError !== null) {
125
- return { ok: false, reason: `job ${job.id}: ${timingError}` }
126
- }
228
+ if (mode !== 'boot') return { ok: true, file }
229
+ return { ok: true, file: { ...file, jobs: validJobs }, ...(warnings.length > 0 ? { warnings } : {}) }
230
+ }
127
231
 
128
- if (job.scheduledByRole === undefined) {
129
- return {
130
- ok: false,
131
- reason: `job ${job.id}: missing 'scheduledByRole'. Add "scheduledByRole": "owner" if you authored this entry manually.`,
132
- }
133
- }
232
+ function validateJob(
233
+ job: ParsedCronJob,
234
+ { now, mode, subagents }: { now: number; mode: ParseCronMode; subagents?: SubagentRegistry },
235
+ ): string | null {
236
+ const timingError = validateTiming(job, now, mode)
237
+ if (timingError !== null) return timingError
134
238
 
135
- if (job.kind === 'prompt' && job.subagent !== undefined && options.subagents !== undefined) {
136
- const subagent = options.subagents[job.subagent]
137
- if (!subagent) {
138
- return { ok: false, reason: `job ${job.id}: unknown subagent "${job.subagent}"` }
139
- }
140
- try {
141
- validateSubagentPayload(job.subagent, subagent, job.payload)
142
- } catch (err) {
143
- const message = err instanceof Error ? err.message : String(err)
144
- return { ok: false, reason: `job ${job.id}: ${message}` }
145
- }
239
+ if (job.scheduledByRole === undefined) {
240
+ return `missing 'scheduledByRole'. Add "scheduledByRole": "owner" if you authored this entry manually.`
241
+ }
242
+
243
+ if (job.kind === 'prompt' && job.subagent !== undefined && subagents !== undefined) {
244
+ const subagent = subagents[job.subagent]
245
+ if (!subagent) return `unknown subagent "${job.subagent}"`
246
+ try {
247
+ validateSubagentPayload(job.subagent, subagent, job.payload)
248
+ } catch (err) {
249
+ return err instanceof Error ? err.message : String(err)
146
250
  }
147
251
  }
148
252
 
149
- return { ok: true, file }
253
+ return null
150
254
  }
151
255
 
152
256
  type TimingJob = {
@@ -181,7 +285,11 @@ function validateTiming(job: TimingJob, now: number = Date.now(), mode: ParseCro
181
285
  if (job.until !== undefined) {
182
286
  until = parseInstant(job.until)
183
287
  if (until === null) return `invalid "until": "${job.until}" is not an ISO datetime with an explicit zone/offset`
184
- if (job.enabled && until <= now) return `"until" is in the past: "${job.until}"`
288
+ // Reject an expired boundary only on `edit`; `load`/`boot` tolerate an
289
+ // already-past `until` (the recurring counterpart of a fired one-shot `at`)
290
+ // so an expired job goes inert instead of bricking the whole file on reload.
291
+ // See ParseCronMode for the full rationale.
292
+ if (mode === 'edit' && job.enabled && until <= now) return `"until" is in the past: "${job.until}"`
185
293
  }
186
294
 
187
295
  let firstFire: number
@@ -199,7 +307,7 @@ function validateTiming(job: TimingJob, now: number = Date.now(), mode: ParseCro
199
307
  return `invalid schedule "${job.schedule}": ${message}`
200
308
  }
201
309
 
202
- if (job.enabled && until !== null && firstFire > until) {
310
+ if (mode === 'edit' && job.enabled && until !== null && firstFire > until) {
203
311
  return `schedule has no occurrence at or before "until" ("${job.until}")`
204
312
  }
205
313
 
@@ -32,6 +32,7 @@ export function buildChannelChecks(): DoctorCheck[] {
32
32
  discordUserCredentials(),
33
33
  slackUserCredentials(),
34
34
  webexUserCredentials(),
35
+ teamsCredentials(),
35
36
  instagramCredentials(),
36
37
  lineCredentials(),
37
38
  kakaotalkCredentials(),
@@ -158,6 +159,32 @@ function webexUserCredentials(): DoctorCheck {
158
159
  }
159
160
  }
160
161
 
162
+ function teamsCredentials(): DoctorCheck {
163
+ return {
164
+ name: 'channel.teams.credentials',
165
+ category: 'channels',
166
+ description: 'teams adapter has a current account with an access token in secrets.json',
167
+ applies: (ctx) => ctx.hasAgentFolder,
168
+ async run(ctx) {
169
+ const channels = readDeclaredChannels(ctx)
170
+ if (channels === null) return configInvalidResult()
171
+ if (!isAdapterActive(channels, 'teams')) {
172
+ return { status: 'skipped', message: 'teams not configured' }
173
+ }
174
+ const block = readChannelsSecrets(ctx)?.teams
175
+ if (!hasCurrentAccountTokenField(block, 'access_token')) {
176
+ return {
177
+ status: 'warning',
178
+ message: 'teams has no current account access_token in secrets.json',
179
+ details: ['Adapter will start but fail authentication and stay disconnected.'],
180
+ fix: { description: 'Populate secrets.json#channels.teams manually with an access token to authenticate.' },
181
+ }
182
+ }
183
+ return { status: 'ok', message: 'teams has a current account access_token' }
184
+ },
185
+ }
186
+ }
187
+
161
188
  function instagramCredentials(): DoctorCheck {
162
189
  return {
163
190
  name: 'channel.instagram.credentials',
@@ -13,6 +13,7 @@ import {
13
13
  lineChannelBlockSchema,
14
14
  mcpCredentialSchema,
15
15
  slackChannelBlockSchema,
16
+ teamsChannelBlockSchema,
16
17
  webexChannelBlockSchema,
17
18
  } from '@/secrets/schema'
18
19
  import { SecretsBackend } from '@/secrets/storage'
@@ -35,6 +36,7 @@ import type {
35
36
  } from './protocol'
36
37
  import { buildSupervisor, type SupervisorLogEvent, type SupervisorRestart } from './supervisor'
37
38
  import type { TailscaleServeEvent } from './tailscale'
39
+ import type { TeamsRenewalCallbacks, TeamsRenewalLogEvent } from './teams-renewal-manager'
38
40
  import { UNVERSIONED_SENTINEL } from './version'
39
41
  import type { WebexRenewalCallbacks, WebexRenewalLogEvent } from './webex-renewal-manager'
40
42
 
@@ -78,6 +80,10 @@ export type DaemonOptions = {
78
80
  // ticks hourly because Webex password tokens live ~27h (see
79
81
  // webex-renewal-manager.ts). Omit when the agent has no webex channel.
80
82
  webexRenewal?: WebexRenewalCallbacks
83
+ // Teams credential renewal capability. Same lifecycle as webexRenewal but
84
+ // ticks every 5 minutes because Teams skype tokens live only 60-90 min (see
85
+ // teams-renewal-manager.ts). Omit when the agent has no teams channel.
86
+ teamsRenewal?: TeamsRenewalCallbacks
81
87
  // Populated once the daemon is booted so direct callers of the restart
82
88
  // (the renewal callbacks in cli/hostd.ts) get the in-process registration
83
89
  // path instead of the socket self-RPC. Omit in tests that don't exercise it.
@@ -125,6 +131,7 @@ export type DaemonLogEvent =
125
131
  | { kind: 'tailscale-serve-event'; event: TailscaleServeEvent }
126
132
  | KakaoRenewalLogEvent
127
133
  | WebexRenewalLogEvent
134
+ | TeamsRenewalLogEvent
128
135
 
129
136
  export type Daemon = {
130
137
  registered: () => string[]
@@ -396,6 +403,7 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
396
403
  await withCleanupTimeout(opts.portbroker.stop(containerName, 'fatal-auth'), cleanupStepTimeoutMs)
397
404
  if (opts.kakaoRenewal) await withCleanupTimeout(opts.kakaoRenewal.stop(containerName), cleanupStepTimeoutMs)
398
405
  if (opts.webexRenewal) await withCleanupTimeout(opts.webexRenewal.stop(containerName), cleanupStepTimeoutMs)
406
+ if (opts.teamsRenewal) await withCleanupTimeout(opts.teamsRenewal.stop(containerName), cleanupStepTimeoutMs)
399
407
  await removeRegistrationFile(containerName)
400
408
  log({ kind: 'registration-skipped', containerName, reason: `fatal broker auth: ${reason}` })
401
409
  })
@@ -434,6 +442,9 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
434
442
  if (opts.webexRenewal) {
435
443
  opts.webexRenewal.start({ containerName: payload.containerName, cwd: payload.cwd })
436
444
  }
445
+ if (opts.teamsRenewal) {
446
+ opts.teamsRenewal.start({ containerName: payload.containerName, cwd: payload.cwd })
447
+ }
437
448
  }
438
449
 
439
450
  const registerContainer = async (req: RegisterPayload): Promise<RpcResponse> => {
@@ -465,6 +476,7 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
465
476
  await withCleanupTimeout(opts.portbroker.stop(req.containerName, 'deregistered'), cleanupStepTimeoutMs)
466
477
  if (opts.kakaoRenewal) await withCleanupTimeout(opts.kakaoRenewal.stop(req.containerName), cleanupStepTimeoutMs)
467
478
  if (opts.webexRenewal) await withCleanupTimeout(opts.webexRenewal.stop(req.containerName), cleanupStepTimeoutMs)
479
+ if (opts.teamsRenewal) await withCleanupTimeout(opts.teamsRenewal.stop(req.containerName), cleanupStepTimeoutMs)
468
480
  await removeRegistrationFile(req.containerName)
469
481
  if (hadCwd) log({ kind: 'deregister', containerName: req.containerName, reason: 'requested' })
470
482
  return { ok: true }
@@ -536,6 +548,7 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
536
548
  | { instagram: unknown }
537
549
  | { line: unknown }
538
550
  | { webex: unknown }
551
+ | { teams: unknown }
539
552
  | { slack: unknown }
540
553
  mcp?: never
541
554
  }
@@ -572,9 +585,11 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
572
585
  ? { key: 'discord' as const, parsed: discordChannelBlockSchema.safeParse(channelsPatch.discord) }
573
586
  : 'webex' in channelsPatch
574
587
  ? { key: 'webex' as const, parsed: webexChannelBlockSchema.safeParse(channelsPatch.webex) }
575
- : 'slack' in channelsPatch
576
- ? { key: 'slack' as const, parsed: slackChannelBlockSchema.safeParse(channelsPatch.slack) }
577
- : { key: 'kakaotalk' as const, parsed: kakaoChannelBlockSchema.safeParse(channelsPatch.kakaotalk) }
588
+ : 'teams' in channelsPatch
589
+ ? { key: 'teams' as const, parsed: teamsChannelBlockSchema.safeParse(channelsPatch.teams) }
590
+ : 'slack' in channelsPatch
591
+ ? { key: 'slack' as const, parsed: slackChannelBlockSchema.safeParse(channelsPatch.slack) }
592
+ : { key: 'kakaotalk' as const, parsed: kakaoChannelBlockSchema.safeParse(channelsPatch.kakaotalk) }
578
593
  if (!patch.parsed.success) {
579
594
  return { ok: false, reason: patch.parsed.error.issues.map((issue) => issue.message).join('; ') }
580
595
  }
@@ -815,6 +830,7 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
815
830
  if (opts.portbroker) await withCleanupTimeout(opts.portbroker.stop(name, 'deregistered'), cleanupStepTimeoutMs)
816
831
  if (opts.kakaoRenewal) await withCleanupTimeout(opts.kakaoRenewal.stop(name), cleanupStepTimeoutMs)
817
832
  if (opts.webexRenewal) await withCleanupTimeout(opts.webexRenewal.stop(name), cleanupStepTimeoutMs)
833
+ if (opts.teamsRenewal) await withCleanupTimeout(opts.teamsRenewal.stop(name), cleanupStepTimeoutMs)
818
834
  await removeRegistrationFile(name)
819
835
  if (hadCwd) log({ kind: 'deregister', containerName: name, reason: 'gone' })
820
836
  return { ok: true }
@@ -858,6 +874,10 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
858
874
  const names = Array.from(cwds.keys())
859
875
  await withCleanupTimeout(Promise.allSettled(names.map((n) => opts.webexRenewal!.stop(n))), cleanupStepTimeoutMs)
860
876
  }
877
+ if (opts.teamsRenewal) {
878
+ const names = Array.from(cwds.keys())
879
+ await withCleanupTimeout(Promise.allSettled(names.map((n) => opts.teamsRenewal!.stop(n))), cleanupStepTimeoutMs)
880
+ }
861
881
  cwds.clear()
862
882
  restartTokens.clear()
863
883
  if (!onWindows) {
@@ -6,6 +6,7 @@ import type {
6
6
  LineChannelBlock,
7
7
  McpCredential,
8
8
  SlackChannelBlock,
9
+ TeamsChannelBlock,
9
10
  WebexChannelBlock,
10
11
  } from '@/secrets/schema'
11
12
 
@@ -15,6 +16,7 @@ export type SecretsPatchChannels =
15
16
  | { instagram: InstagramChannelBlock }
16
17
  | { line: LineChannelBlock }
17
18
  | { webex: WebexChannelBlock }
19
+ | { teams: TeamsChannelBlock }
18
20
  | { slack: SlackChannelBlock }
19
21
 
20
22
  export type SecretsPatchMcp = { server: string; credential: McpCredential }
@@ -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