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
package/src/run/index.ts CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  createPrVerdictActivityBridge,
35
35
  createSubagentCompletionBridge,
36
36
  setReviewObserver,
37
+ setReviewOutputObserver,
37
38
  type ChannelManager,
38
39
  type PrVerdictActivityBridge,
39
40
  type SubagentCompletionBridge,
@@ -51,6 +52,7 @@ import {
51
52
  createScheduler,
52
53
  type LoadCronResult,
53
54
  loadCron as loadCronDefault,
55
+ type ParseCronMode,
54
56
  type Scheduler,
55
57
  } from '@/cron'
56
58
  import { CLI_VERSION } from '@/init/cli-version'
@@ -90,7 +92,10 @@ type BunServer = ReturnType<Server['start']>
90
92
 
91
93
  export type TuiFactory = (options: TuiOptions) => { run: () => Promise<unknown> }
92
94
 
93
- export type LoadCronFn = (agentDir: string, options?: { subagents?: SubagentRegistry }) => Promise<LoadCronResult>
95
+ export type LoadCronFn = (
96
+ agentDir: string,
97
+ options?: { subagents?: SubagentRegistry; mode?: ParseCronMode },
98
+ ) => Promise<LoadCronResult>
94
99
  export type SchedulerFactory = (options: {
95
100
  cwd: string
96
101
  file: CronFile
@@ -783,6 +788,15 @@ async function startAgentRuntime(
783
788
  })
784
789
  registerBootCleanup(() => setReviewObserver(null))
785
790
 
791
+ // A landed review of ANY state (incl. COMMENT) marks the recording session so its
792
+ // empty-turn fallback is suppressed: the review IS the turn's output, but it goes
793
+ // through the GitHub API, not the channel send path. In-process router call — no
794
+ // stream fan-out, since this is the recording session's own bookkeeping.
795
+ setReviewOutputObserver((output) => {
796
+ channelManager.router.noteGithubReviewOutput(output)
797
+ })
798
+ registerBootCleanup(() => setReviewOutputObserver(null))
799
+
786
800
  // Registered before channels so its cache clear lands before any channel
787
801
  // session teardown observes it. secrets.json provider credentials are not
788
802
  // part of the typeclaw.json config diff, so a rotated key takes effect on
@@ -1123,7 +1137,10 @@ function reloadRolesFromDisk(cwd: string): ReturnType<typeof getConfig>['roles']
1123
1137
  return getConfig().roles
1124
1138
  }
1125
1139
 
1126
- async function startScheduler({
1140
+ // Exported for the resilience regression test in `index.test.ts` (survives a
1141
+ // file-level cron.json failure by still scheduling plugin jobs). Not re-exported
1142
+ // from the package entry point, so this stays module-internal in practice.
1143
+ export async function startScheduler({
1127
1144
  cwd,
1128
1145
  loadCron,
1129
1146
  createSchedulerFor,
@@ -1145,17 +1162,27 @@ async function startScheduler({
1145
1162
  let result: LoadCronResult
1146
1163
  const subagents = getSubagents?.()
1147
1164
  try {
1148
- result = await loadCron(cwd, subagents !== undefined ? { subagents } : {})
1165
+ result = await loadCron(cwd, { mode: 'boot', ...(subagents !== undefined ? { subagents } : {}) })
1149
1166
  } catch (err) {
1150
- console.error(`[cron] load failed: ${err instanceof Error ? err.message : err}`)
1151
- return null
1167
+ result = { ok: false, reason: err instanceof Error ? err.message : String(err) }
1152
1168
  }
1169
+
1170
+ // A file-level cron.json failure (malformed JSON or top-level schema
1171
+ // violation) must not take the whole scheduler down: plugin-registered jobs
1172
+ // (e.g. memory dreaming) live outside cron.json and have to keep running.
1173
+ // Boot with an empty user file so the factory still merges internal jobs;
1174
+ // give up only when there is nothing to schedule at all.
1153
1175
  if (!result.ok) {
1154
1176
  console.error(`[cron] failed to load cron.json: ${result.reason}`)
1155
- return null
1177
+ if (!hasInternalJobs) return null
1178
+ } else {
1179
+ for (const warning of result.warnings ?? []) {
1180
+ console.error(`[cron] skipped invalid job at boot: ${warning.reason}`)
1181
+ }
1156
1182
  }
1157
- const file: CronFile = result.file ?? { jobs: [] }
1158
- if (!result.file && !hasInternalJobs) return null
1183
+
1184
+ const file: CronFile = result.ok ? (result.file ?? { jobs: [] }) : { jobs: [] }
1185
+ if (result.ok && !result.file && !hasInternalJobs) return null
1159
1186
 
1160
1187
  const onFire = (job: CronJob) => {
1161
1188
  stream.publish({ target: { kind: 'cron', jobId: job.id }, payload: job })
@@ -3,6 +3,24 @@ export type LlmFetchObserverLogger = {
3
3
  warn: (msg: string) => void
4
4
  }
5
5
 
6
+ // Per-request timeout override, attached to a RequestInit under a Symbol key so
7
+ // it travels with a single fetch() without leaking a wire header to the provider
8
+ // and without widening the endpoint matcher. Used where one call on a SHARED
9
+ // endpoint URL needs a different deadline than its siblings — e.g. GLM vision and
10
+ // GLM text hit the identical /chat/completions URL, so a URL/header match cannot
11
+ // tell them apart, but the vision caller owns its fetch and can tag it directly.
12
+ export const LLM_FETCH_OBSERVER_TIMEOUTS = Symbol.for('typeclaw.llmFetchObserverTimeouts')
13
+
14
+ export type LlmFetchObserverTimeoutOverrides = {
15
+ ttfbMs?: number
16
+ idleMs?: number
17
+ overallMs?: number
18
+ }
19
+
20
+ export type LlmFetchObservedRequestInit = RequestInit & {
21
+ [LLM_FETCH_OBSERVER_TIMEOUTS]?: LlmFetchObserverTimeoutOverrides
22
+ }
23
+
6
24
  // A provider endpoint the observer should instrument. `match` is host-agnostic
7
25
  // on purpose: base URLs are user-configured (ANTHROPIC_BASE_URL, OPENAI_BASE_URL,
8
26
  // OpenRouter/LiteLLM/Fireworks/arbitrary proxies), so a host allowlist would be
@@ -442,12 +460,15 @@ export function installLlmFetchObserver(opts: LlmFetchObserverOptions = {}): ()
442
460
  // "force this across all endpoints" (the test seam and any global override),
443
461
  // so it must beat a per-endpoint tuned value. The master `timeoutsEnabled=off`
444
462
  // switch forces every timer to 0 regardless.
445
- const resolveTimeouts = (endpoint: LlmFetchEndpoint): ResolvedTimeouts => {
463
+ const resolveTimeouts = (
464
+ endpoint: LlmFetchEndpoint,
465
+ perRequest: LlmFetchObserverTimeoutOverrides | undefined,
466
+ ): ResolvedTimeouts => {
446
467
  if (!timeoutsEnabled) return { ttfbMs: 0, idleMs: 0, overallMs: 0 }
447
468
  return {
448
- ttfbMs: opts.ttfbMs ?? endpoint.ttfbMs ?? envDefaults.ttfbMs,
449
- idleMs: opts.idleMs ?? endpoint.idleMs ?? envDefaults.idleMs,
450
- overallMs: opts.overallMs ?? endpoint.overallMs ?? envDefaults.overallMs,
469
+ ttfbMs: opts.ttfbMs ?? perRequest?.ttfbMs ?? endpoint.ttfbMs ?? envDefaults.ttfbMs,
470
+ idleMs: opts.idleMs ?? perRequest?.idleMs ?? endpoint.idleMs ?? envDefaults.idleMs,
471
+ overallMs: opts.overallMs ?? perRequest?.overallMs ?? endpoint.overallMs ?? envDefaults.overallMs,
451
472
  }
452
473
  }
453
474
 
@@ -459,7 +480,8 @@ export function installLlmFetchObserver(opts: LlmFetchObserverOptions = {}): ()
459
480
  if (endpoint === null) {
460
481
  return originalFetch(input, init)
461
482
  }
462
- const timeouts = resolveTimeouts(endpoint)
483
+ const perRequest = (init as LlmFetchObservedRequestInit | undefined)?.[LLM_FETCH_OBSERVER_TIMEOUTS]
484
+ const timeouts = resolveTimeouts(endpoint, perRequest)
463
485
  const provider = endpoint.label
464
486
  const start = now()
465
487
 
@@ -171,6 +171,7 @@ function buildArgv(command: string, policy: SandboxPolicy): string[] {
171
171
  appendMasks(argv, policy)
172
172
  appendWritable(argv, policy)
173
173
  appendProtected(argv, policy)
174
+ appendBlockedCreation(argv, policy)
174
175
  appendSymlinks(argv, policy)
175
176
 
176
177
  if (policy.cwd !== undefined) {
@@ -217,6 +218,17 @@ function appendProtected(argv: string[], policy: SandboxPolicy): void {
217
218
  }
218
219
  }
219
220
 
221
+ // Occupies each path with an empty read-only object so a writable-root install
222
+ // script cannot CREATE a real file there. /dev/null always exists (bwrap mounts
223
+ // --dev), so unlike --ro-bind-data this needs no manufactured placeholder on the
224
+ // host FS. Renders after appendProtected: both are RO carve-outs of the RW root,
225
+ // last-op-wins.
226
+ function appendBlockedCreation(argv: string[], policy: SandboxPolicy): void {
227
+ for (const file of policy.blockedCreation?.files ?? []) {
228
+ argv.push('--ro-bind', '/dev/null', file)
229
+ }
230
+ }
231
+
220
232
  // Rendered after every bind (incl. the /tmp session bind in policy.mounts) so
221
233
  // last-op-wins keeps the symlink: a `/tmp/.foo` dest emitted before the /tmp
222
234
  // bind would be erased by it. `--dir` ensures the symlink's parent exists inside
@@ -112,6 +112,18 @@ export type SandboxWritableRootPolicy = {
112
112
  dir: string
113
113
  }
114
114
 
115
+ // Paths whose CREATION must be blocked under a writable root, rendered as
116
+ // `--ro-bind /dev/null <path>`. Used by the package-install path for the
117
+ // semantically-guarded managed files (cron.json / typeclaw.json) when they are
118
+ // ABSENT: the RW root would otherwise let a postinstall lifecycle script create
119
+ // them, bypassing the write/edit-tool guards. Binding /dev/null occupies the
120
+ // path with an empty read-only object (blocking creation) WITHOUT manufacturing
121
+ // a real invalid file on the host FS. Renders after writableRoot, with the
122
+ // protected binds, so last-op-wins keeps the path occupied.
123
+ export type SandboxBlockedCreationPolicy = {
124
+ files?: string[]
125
+ }
126
+
115
127
  export type SandboxPolicy = {
116
128
  bwrapPath?: string
117
129
  cwd?: string
@@ -128,6 +140,7 @@ export type SandboxPolicy = {
128
140
  masks?: SandboxMaskPolicy
129
141
  writable?: SandboxWritablePolicy
130
142
  protected?: SandboxProtectedPolicy
143
+ blockedCreation?: SandboxBlockedCreationPolicy
131
144
  symlinks?: SandboxSymlinkOp[]
132
145
  network?: SandboxNetwork
133
146
  env?: SandboxEnvPolicy
@@ -59,15 +59,19 @@ const PROTECTED_GIT_FILES = ['.git/config'] as const
59
59
 
60
60
  // Bash may EDIT these when present; creating a MISSING root file goes through
61
61
  // write/edit (bwrap cannot RW-bind a non-existent source without pre-creating it).
62
- const WRITABLE_ROOT_FILES = [
63
- 'AGENTS.md',
64
- 'IDENTITY.md',
65
- 'SOUL.md',
66
- 'USER.md',
67
- 'cron.json',
68
- 'package.json',
69
- 'typeclaw.json',
70
- ] as const
62
+ //
63
+ // SECURITY: the semantically-guarded managed files (`cron.json`, `typeclaw.json`)
64
+ // are deliberately EXCLUDED. Those two are the only files gated by the
65
+ // managedConfig / cronPromotion guards, which fire on the `write`/`edit` tools
66
+ // only. Granting bash a blanket RW bind to them opened a bypass: an agent
67
+ // blocked from writing cron.json through the guarded tools could just
68
+ // `echo … > cron.json` from bash and defeat the guard entirely. Keeping them off
69
+ // this list forces every mutation of a guarded file through the one guarded path
70
+ // (the write/edit tool), so a managed file has exactly one mutation boundary.
71
+ // `package.json` stays writable: it is NOT a semantically-guarded managed file
72
+ // (only cron.json/typeclaw.json are), and `bun add`/manual dep edits legitimately
73
+ // touch it from bash.
74
+ const WRITABLE_ROOT_FILES = ['AGENTS.md', 'IDENTITY.md', 'SOUL.md', 'USER.md', 'package.json'] as const
71
75
 
72
76
  // SECURITY: the symlink rejection is load-bearing. An RW bind follows symlinks,
73
77
  // so a `workspace -> /etc` symlink at a zone root would grant write access to an
@@ -152,8 +156,23 @@ function dedupe(values: string[]): string[] {
152
156
  export type PackageInstallZones = {
153
157
  root: string
154
158
  protected: ProtectedZones
159
+ // Guarded managed files that are ABSENT at jail-build time. The RW package-
160
+ // install root would otherwise let a `bun install` postinstall lifecycle
161
+ // script CREATE them (a guard bypass — see the SECURITY note on
162
+ // MANAGED_ROOT_FILES). Rendered as `--ro-bind /dev/null <path>` so the path is
163
+ // occupied by an empty read-only object that blocks creation, without
164
+ // manufacturing a real (invalid) file on the host FS the way the secret-mask
165
+ // placeholder pattern would. Present managed files go in `protected.files`.
166
+ blockedCreation: string[]
155
167
  }
156
168
 
169
+ // SECURITY: the semantically-guarded managed files. They are gated by the
170
+ // managedConfig / cronPromotion guards (write/edit tools only), so bash must
171
+ // never be able to write OR create them. The normal jail already excludes them
172
+ // from WRITABLE_ROOT_FILES; the package-install RW root needs the extra step of
173
+ // blocking their CREATION when absent (see PackageInstallZones.blockedCreation).
174
+ const MANAGED_ROOT_FILES = ['cron.json', 'typeclaw.json'] as const
175
+
157
176
  // SECURITY: the package-install RW root is governed by an ALLOWLIST, not a
158
177
  // denylist. `bun add` writes exactly these and nothing else: `node_modules/`
159
178
  // (deps), `package.json` + `bun.lock` (manifest + lockfile, plus the temp
@@ -214,7 +233,24 @@ export async function resolvePackageInstallZones(agentDir: string): Promise<Pack
214
233
  const runtime = join(agentDir, 'node_modules', 'typeclaw')
215
234
  if (await isRealEntry(runtime, 'dir')) dirs.push(runtime)
216
235
 
217
- return { root: agentDir, protected: { dirs: dedupe(dirs), files: dedupe(files) } }
236
+ // Guarded managed files: a PRESENT real one is already RO-bound by the readdir
237
+ // loop above (it is not in the writable set). The gap is a managed file ABSENT
238
+ // at jail-build time — readdir never sees it, so nothing occupies its path and
239
+ // a postinstall script could CREATE it under the RW root. Block that path with
240
+ // `--ro-bind /dev/null`. A managed file that exists as a SYMLINK is also blocked
241
+ // here rather than RO-bound (the readdir loop skipped it, and an RO bind would
242
+ // follow it out of the jail) — occupying the path with /dev/null is safe.
243
+ const blockedCreation: string[] = []
244
+ for (const name of MANAGED_ROOT_FILES) {
245
+ const target = join(agentDir, name)
246
+ if (!(await isRealEntry(target, 'file'))) blockedCreation.push(target)
247
+ }
248
+
249
+ return {
250
+ root: agentDir,
251
+ protected: { dirs: dedupe(dirs), files: dedupe(files) },
252
+ blockedCreation: dedupe(blockedCreation),
253
+ }
218
254
  }
219
255
 
220
256
  async function exists(target: string): Promise<boolean> {
@@ -182,6 +182,35 @@ export const webexChannelBlockSchema = z.object({
182
182
  accounts: z.record(z.string(), webexAccountRecordSchema),
183
183
  })
184
184
 
185
+ const teamsAccountTypeSchema = z.union([z.literal('work'), z.literal('personal')])
186
+ export type TeamsAccountType = z.infer<typeof teamsAccountTypeSchema>
187
+ const teamsRegionSchema = z.union([z.literal('amer'), z.literal('emea'), z.literal('apac')])
188
+
189
+ // Teams user-account credentials. The short-lived `access_token` expires in
190
+ // 60-90 minutes, so a long-running adapter relies on `aad_refresh_token` (+
191
+ // client/tenant ids from the device-code login) to silently re-mint it through
192
+ // the agent-messenger SDK. The refresh trio is optional so an extracted-token
193
+ // account still parses, but such an account degrades to "reauth required" once
194
+ // the access token lapses.
195
+ export const teamsAccountRecordSchema = z.object({
196
+ account_id: z.string(),
197
+ access_token: z.string(),
198
+ token_expires_at: z.string().optional(),
199
+ account_type: teamsAccountTypeSchema,
200
+ region: teamsRegionSchema.optional(),
201
+ user_name: z.string().optional(),
202
+ aad_refresh_token: z.string().optional(),
203
+ aad_client_id: z.string().optional(),
204
+ aad_tenant_id: z.string().optional(),
205
+ created_at: z.string(),
206
+ updated_at: z.string(),
207
+ })
208
+
209
+ export const teamsChannelBlockSchema = z.object({
210
+ currentAccount: z.string().nullable(),
211
+ accounts: z.record(z.string(), teamsAccountRecordSchema),
212
+ })
213
+
185
214
  export const slackAccountRecordSchema = z.object({
186
215
  account_id: z.string(),
187
216
  token: z.string(),
@@ -221,6 +250,7 @@ export const channelsSchema = z
221
250
  instagram: instagramChannelBlockSchema.optional(),
222
251
  kakaotalk: kakaoChannelBlockSchema.optional(),
223
252
  webex: webexChannelBlockSchema.optional(),
253
+ teams: teamsChannelBlockSchema.optional(),
224
254
  slack: slackChannelBlockSchema.optional(),
225
255
  })
226
256
  .catchall(z.unknown())
@@ -257,6 +287,8 @@ export type KakaoChannelBlock = z.infer<typeof kakaoChannelBlockSchema>
257
287
  export type WebexAccountRecord = z.infer<typeof webexAccountRecordSchema>
258
288
  export type WebexChannelBlock = z.infer<typeof webexChannelBlockSchema>
259
289
  export type WebexEncryptedPassword = z.infer<typeof webexEncryptedPasswordSchema>
290
+ export type TeamsAccountRecord = z.infer<typeof teamsAccountRecordSchema>
291
+ export type TeamsChannelBlock = z.infer<typeof teamsChannelBlockSchema>
260
292
  export type SlackAccountRecord = z.infer<typeof slackAccountRecordSchema>
261
293
  export type SlackChannelBlock = z.infer<typeof slackChannelBlockSchema>
262
294
  export type SecretsFile = z.infer<typeof secretsFileSchema>
@@ -0,0 +1,229 @@
1
+ import { mkdtemp, rm } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+
5
+ import { refreshDeviceCodeAccount, TeamsCredentialManager } from 'agent-messenger/teams'
6
+
7
+ import { type TeamsAccountRecord, type TeamsChannelBlock, teamsChannelBlockSchema } from './schema'
8
+ import { SecretsBackend } from './storage'
9
+ import { SecretsTeamsCredentialStore } from './teams-store'
10
+
11
+ // Teams user-account skype tokens live only 60-90 minutes, so a long-running
12
+ // adapter must silently re-mint them from the stored AAD refresh trio. The
13
+ // host tick fires every 5 minutes and renews once the token is within 15
14
+ // minutes of `token_expires_at`: that clears a full tick-interval with headroom
15
+ // for host sleep / daemon respawn, and gives ~3 attempts before a token would
16
+ // otherwise lapse mid-session.
17
+ export const RENEWAL_WINDOW_MS = 15 * 60 * 1000
18
+
19
+ // `TeamsCredentialManager.accountOverride` is static process state and the SDK
20
+ // refresh reads/writes a file store, so only one Teams refresh may run in a
21
+ // hostd process at a time. Serialize every SDK call through this chain.
22
+ let refreshChain: Promise<unknown> = Promise.resolve()
23
+
24
+ export type TeamsRenewalDecision =
25
+ | { kind: 'skip'; reason: 'no_account' | 'fresh_enough'; expiresInMs?: number }
26
+ | { kind: 'reauth_required'; reason: 'no_refresh_token'; message: string }
27
+ | { kind: 'should_renew'; account: TeamsAccountRecord }
28
+
29
+ export type TeamsRenewalAttempt =
30
+ | { kind: 'ok'; account_id: string; previousExpiresAt: number; nextExpiresAt: number }
31
+ | { kind: 'reauth_required'; account_id: string; reason: string; message: string }
32
+ | { kind: 'transient_failure'; account_id: string; reason: string }
33
+
34
+ export type RefreshDeviceCodeAccountFn = typeof refreshDeviceCodeAccount
35
+
36
+ export type TeamsRenewalContext = {
37
+ agentDir: string
38
+ now?: () => number
39
+ refreshDeviceCodeAccount?: RefreshDeviceCodeAccountFn
40
+ }
41
+
42
+ export function decideRenewal(block: TeamsChannelBlock, now: number): TeamsRenewalDecision {
43
+ const accountId = block.currentAccount
44
+ if (!accountId) return { kind: 'skip', reason: 'no_account' }
45
+ const account = block.accounts[accountId]
46
+ if (!account) return { kind: 'skip', reason: 'no_account' }
47
+
48
+ // A present-and-parseable expiry more than a window away is the only reason
49
+ // to skip. A missing or unparseable expiry falls through to renew (better to
50
+ // spend a refresh than leave an extracted/legacy record stuck until manual
51
+ // reauth) — but only if there's refresh material to spend.
52
+ const expiresAt = account.token_expires_at !== undefined ? Date.parse(account.token_expires_at) : Number.NaN
53
+ if (Number.isFinite(expiresAt)) {
54
+ const expiresInMs = expiresAt - now
55
+ if (expiresInMs > RENEWAL_WINDOW_MS) return { kind: 'skip', reason: 'fresh_enough', expiresInMs }
56
+ }
57
+
58
+ if (!account.aad_refresh_token) {
59
+ return {
60
+ kind: 'reauth_required',
61
+ reason: 'no_refresh_token',
62
+ message: `Teams account ${accountId} has no AAD refresh token — run \`typeclaw channel reauth teams\`.`,
63
+ }
64
+ }
65
+
66
+ return { kind: 'should_renew', account }
67
+ }
68
+
69
+ export async function renewCurrentAccount(
70
+ ctx: TeamsRenewalContext,
71
+ ): Promise<TeamsRenewalAttempt | { kind: 'skipped'; reason: string; expiresInMs?: number }> {
72
+ const secretsPath = join(ctx.agentDir, 'secrets.json')
73
+ const backend = new SecretsBackend(secretsPath)
74
+ const block = parseBlockOrEmpty(backend.readChannelsSync()?.teams)
75
+ const decision = decideRenewal(block, (ctx.now ?? Date.now)())
76
+
77
+ if (decision.kind === 'skip') {
78
+ return {
79
+ kind: 'skipped',
80
+ reason: decision.reason,
81
+ ...(decision.expiresInMs !== undefined ? { expiresInMs: decision.expiresInMs } : {}),
82
+ }
83
+ }
84
+ if (decision.kind === 'reauth_required') {
85
+ return {
86
+ kind: 'reauth_required',
87
+ account_id: block.currentAccount ?? '',
88
+ reason: decision.reason,
89
+ message: decision.message,
90
+ }
91
+ }
92
+
93
+ const refreshFn = ctx.refreshDeviceCodeAccount ?? refreshDeviceCodeAccount
94
+ const outcome = await enqueueRefresh(() => runBridgedRefresh(decision.account, refreshFn))
95
+ if (outcome.kind === 'failed') {
96
+ // The SDK only returns a boolean, but its debug callback first reports the
97
+ // underlying AAD error. A revoked/expired refresh token (invalid_grant,
98
+ // interaction_required, the AADSTS7xxxx expiry/revocation family) can never
99
+ // recover without a human, so surface it as reauth_required rather than
100
+ // retrying it forever; a network/5xx blip stays transient and retries next
101
+ // tick.
102
+ if (isPermanentAadFailure(outcome.detail)) {
103
+ return {
104
+ kind: 'reauth_required',
105
+ account_id: decision.account.account_id,
106
+ reason: 'refresh_token_rejected',
107
+ message: `Teams silent refresh was rejected (${outcome.detail ?? 'invalid_grant'}) — run \`typeclaw channel reauth teams\`.`,
108
+ }
109
+ }
110
+ return {
111
+ kind: 'transient_failure',
112
+ account_id: decision.account.account_id,
113
+ reason: outcome.detail ?? 'silent_refresh_failed',
114
+ }
115
+ }
116
+ const refreshed = outcome.fields
117
+
118
+ const store = new SecretsTeamsCredentialStore({ mode: 'host', secretsPath })
119
+ const previousExpiresAt = Date.parse(decision.account.token_expires_at ?? '')
120
+ const nextExpiresAt = Date.parse(refreshed.token_expires_at ?? '')
121
+ // setAccount's mergeAccountPreservingRefreshFields backfills any AAD field the
122
+ // readback omitted, so we always keep a spendable refresh trio.
123
+ await store.setAccount({
124
+ ...decision.account,
125
+ access_token: refreshed.access_token,
126
+ ...(refreshed.token_expires_at !== undefined ? { token_expires_at: refreshed.token_expires_at } : {}),
127
+ ...(refreshed.aad_refresh_token !== undefined ? { aad_refresh_token: refreshed.aad_refresh_token } : {}),
128
+ ...(refreshed.region !== undefined ? { region: refreshed.region } : {}),
129
+ updated_at: new Date().toISOString(),
130
+ })
131
+
132
+ return {
133
+ kind: 'ok',
134
+ account_id: decision.account.account_id,
135
+ previousExpiresAt: Number.isFinite(previousExpiresAt) ? previousExpiresAt : 0,
136
+ nextExpiresAt: Number.isFinite(nextExpiresAt) ? nextExpiresAt : 0,
137
+ }
138
+ }
139
+
140
+ type RefreshedFields = Pick<TeamsAccountRecord, 'access_token' | 'token_expires_at' | 'aad_refresh_token' | 'region'>
141
+
142
+ type BridgedRefreshResult = { kind: 'ok'; fields: RefreshedFields } | { kind: 'failed'; detail?: string }
143
+
144
+ // The only public Teams refresh entry point writes through the SDK's own
145
+ // file-backed TeamsCredentialManager, so bridge it: seed a throwaway manager in
146
+ // a temp dir from our stored record, let the SDK exchange the AAD refresh token
147
+ // for a fresh skype token, then read the refreshed account back out and hand
148
+ // only the TypeClaw-owned fields to the caller. On failure the SDK just returns
149
+ // false, but its debug callback reports the underlying AAD error first, so
150
+ // capture that into `detail` for the caller's permanent-vs-transient split.
151
+ async function runBridgedRefresh(
152
+ account: TeamsAccountRecord,
153
+ refreshFn: RefreshDeviceCodeAccountFn,
154
+ ): Promise<BridgedRefreshResult> {
155
+ const dir = await mkdtemp(join(tmpdir(), 'typeclaw-teams-refresh-'))
156
+ let lastDebug: string | undefined
157
+ try {
158
+ const manager = new TeamsCredentialManager(dir)
159
+ await manager.setDeviceCodeAccount({
160
+ accountType: account.account_type,
161
+ token: account.access_token,
162
+ tokenExpiresAt: account.token_expires_at ?? '',
163
+ ...(account.aad_refresh_token !== undefined ? { aadRefreshToken: account.aad_refresh_token } : {}),
164
+ ...(account.aad_client_id !== undefined ? { aadClientId: account.aad_client_id } : {}),
165
+ ...(account.aad_tenant_id !== undefined ? { aadTenantId: account.aad_tenant_id } : {}),
166
+ ...(account.region !== undefined ? { region: account.region } : {}),
167
+ ...(account.user_name !== undefined ? { userName: account.user_name } : {}),
168
+ teams: {},
169
+ currentTeam: null,
170
+ authMethod: 'device-code',
171
+ makeCurrent: true,
172
+ })
173
+
174
+ const ok = await refreshFn(account.account_type, manager, (message) => {
175
+ lastDebug = message
176
+ })
177
+ if (!ok) return { kind: 'failed', ...(lastDebug !== undefined ? { detail: lastDebug } : {}) }
178
+
179
+ const refreshed = await manager.getCurrentAccount()
180
+ // A true return with a null/tokenless readback is a malformed success — the
181
+ // caller treats a failure as transient rather than persisting garbage.
182
+ if (!refreshed || !refreshed.token) return { kind: 'failed' }
183
+
184
+ return {
185
+ kind: 'ok',
186
+ fields: {
187
+ access_token: refreshed.token,
188
+ ...(refreshed.token_expires_at !== undefined ? { token_expires_at: refreshed.token_expires_at } : {}),
189
+ ...(refreshed.aad_refresh_token !== undefined ? { aad_refresh_token: refreshed.aad_refresh_token } : {}),
190
+ ...(refreshed.region !== undefined ? { region: refreshed.region } : {}),
191
+ },
192
+ }
193
+ } catch (err) {
194
+ return { kind: 'failed', detail: err instanceof Error ? err.message : lastDebug }
195
+ } finally {
196
+ await rm(dir, { recursive: true, force: true })
197
+ }
198
+ }
199
+
200
+ // AAD returns these for a refresh token that a human must re-mint: an explicit
201
+ // invalid_grant / interaction_required, or the AADSTS token expiry/revocation
202
+ // family (700082 expired, 70008 expired, 50173 changed-password, 700084/50076
203
+ // re-auth). Anything else (network, 5xx, throttling) is transient. Matched
204
+ // case-insensitively as a substring because the detail is a free-form
205
+ // error_description line, not a stable code field.
206
+ function isPermanentAadFailure(detail: string | undefined): boolean {
207
+ if (detail === undefined) return false
208
+ const haystack = detail.toLowerCase()
209
+ return [
210
+ 'invalid_grant',
211
+ 'interaction_required',
212
+ 'aadsts700082',
213
+ 'aadsts70008',
214
+ 'aadsts50173',
215
+ 'aadsts700084',
216
+ 'aadsts50076',
217
+ ].some((needle) => haystack.includes(needle))
218
+ }
219
+
220
+ function enqueueRefresh<T>(op: () => Promise<T>): Promise<T> {
221
+ const next = refreshChain.then(op, op)
222
+ refreshChain = next.catch(() => {})
223
+ return next
224
+ }
225
+
226
+ function parseBlockOrEmpty(value: unknown): TeamsChannelBlock {
227
+ if (value === undefined) return { currentAccount: null, accounts: {} }
228
+ return teamsChannelBlockSchema.parse(value)
229
+ }
@@ -0,0 +1,108 @@
1
+ import { type TeamsAccountRecord, type TeamsChannelBlock, teamsChannelBlockSchema } from './schema'
2
+ import type { RuntimeSecretsProvider } from './secrets-provider'
3
+ import { SecretsBackend } from './storage'
4
+
5
+ export type SetTeamsAccountInput = TeamsAccountRecord
6
+
7
+ export type SecretsTeamsCredentialStoreOptions =
8
+ | { mode: 'host'; secretsPath: string }
9
+ | { mode: 'container'; secretsPath: string; hostProvider: RuntimeSecretsProvider }
10
+
11
+ const EMPTY_BLOCK: TeamsChannelBlock = { currentAccount: null, accounts: {} }
12
+
13
+ export class SecretsTeamsCredentialStore {
14
+ private readonly backend: SecretsBackend
15
+ private writeChain: Promise<void> = Promise.resolve()
16
+
17
+ constructor(private readonly options: SecretsTeamsCredentialStoreOptions) {
18
+ this.backend = new SecretsBackend(options.secretsPath)
19
+ }
20
+
21
+ async getAccount(id?: string): Promise<TeamsAccountRecord | null> {
22
+ const block = this.readBlock()
23
+ const accountId = id ?? block.currentAccount
24
+ if (!accountId) return null
25
+ return block.accounts[accountId] ?? null
26
+ }
27
+
28
+ async setAccount(account: SetTeamsAccountInput): Promise<void> {
29
+ await this.writeBlock((block) => {
30
+ const merged = mergeAccountPreservingRefreshFields(account, block.accounts[account.account_id])
31
+ const accounts = { ...block.accounts, [account.account_id]: merged }
32
+ return { ...block, currentAccount: block.currentAccount ?? account.account_id, accounts }
33
+ })
34
+ }
35
+
36
+ async removeAccount(id: string): Promise<void> {
37
+ await this.writeBlock((block) => {
38
+ const accounts = { ...block.accounts }
39
+ delete accounts[id]
40
+ const currentAccount = block.currentAccount === id ? (Object.keys(accounts)[0] ?? null) : block.currentAccount
41
+ return { ...block, currentAccount, accounts }
42
+ })
43
+ }
44
+
45
+ async listAccounts(): Promise<Array<TeamsAccountRecord & { is_current: boolean }>> {
46
+ const block = this.readBlock()
47
+ return Object.values(block.accounts).map((account) => ({
48
+ ...account,
49
+ is_current: account.account_id === block.currentAccount,
50
+ }))
51
+ }
52
+
53
+ async setCurrentAccount(id: string): Promise<void> {
54
+ await this.writeBlock((block) => ({ ...block, currentAccount: id }))
55
+ }
56
+
57
+ private readBlock(): TeamsChannelBlock {
58
+ const channels =
59
+ this.options.mode === 'container' ? this.options.hostProvider.readChannels() : this.backend.readChannelsSync()
60
+ return parseBlock(channels?.teams)
61
+ }
62
+
63
+ private async writeBlock(update: (current: TeamsChannelBlock) => TeamsChannelBlock): Promise<void> {
64
+ return this.enqueueWrite(async () => {
65
+ if (this.options.mode === 'container') {
66
+ const next = update(this.readBlock())
67
+ await this.options.hostProvider.writeBackChannelBlock({ teams: next })
68
+ return
69
+ }
70
+
71
+ await this.backend.updateChannelsAsync(async (channels) => {
72
+ const next = { ...channels, teams: update(parseBlock(channels.teams)) }
73
+ return { result: undefined, next }
74
+ })
75
+ })
76
+ }
77
+
78
+ private enqueueWrite(op: () => Promise<void>): Promise<void> {
79
+ const next = this.writeChain.then(op, op)
80
+ this.writeChain = next.catch(() => {})
81
+ return next
82
+ }
83
+ }
84
+
85
+ function parseBlock(value: unknown): TeamsChannelBlock {
86
+ if (value === undefined) return EMPTY_BLOCK
87
+ return teamsChannelBlockSchema.parse(value)
88
+ }
89
+
90
+ // A silent-refresh write (new access token from the stored refresh token)
91
+ // carries only the freshly minted access fields; the AAD refresh trio it was
92
+ // minted from must survive so the NEXT refresh still has something to spend.
93
+ function mergeAccountPreservingRefreshFields(
94
+ incoming: SetTeamsAccountInput,
95
+ priorOnDisk: TeamsChannelBlock['accounts'][string] | undefined,
96
+ ): TeamsAccountRecord {
97
+ const merged: TeamsAccountRecord = { ...incoming }
98
+ if (incoming.aad_refresh_token === undefined && priorOnDisk?.aad_refresh_token !== undefined) {
99
+ merged.aad_refresh_token = priorOnDisk.aad_refresh_token
100
+ }
101
+ if (incoming.aad_client_id === undefined && priorOnDisk?.aad_client_id !== undefined) {
102
+ merged.aad_client_id = priorOnDisk.aad_client_id
103
+ }
104
+ if (incoming.aad_tenant_id === undefined && priorOnDisk?.aad_tenant_id !== undefined) {
105
+ merged.aad_tenant_id = priorOnDisk.aad_tenant_id
106
+ }
107
+ return merged
108
+ }