typeclaw 0.43.1 → 0.45.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 (86) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +7 -6
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +25 -2
  6. package/src/agent/model-fallback.ts +59 -40
  7. package/src/agent/multimodal/look-at.ts +29 -10
  8. package/src/agent/plugin-tools.ts +9 -4
  9. package/src/agent/provider-error.ts +71 -18
  10. package/src/agent/retry-same-ref.ts +139 -0
  11. package/src/agent/session-origin.ts +1 -0
  12. package/src/agent/subagents.ts +6 -2
  13. package/src/agent/tools/channel-edit.ts +144 -0
  14. package/src/agent/tools/channel-fetch-attachment.ts +51 -8
  15. package/src/agent/tools/channel-reply.ts +41 -18
  16. package/src/agent/tools/channel-send.ts +82 -13
  17. package/src/agent/tools/curl-impersonate.ts +40 -1
  18. package/src/agent/tools/webfetch/fetch.ts +86 -3
  19. package/src/agent/tools/webfetch/tool.ts +26 -3
  20. package/src/agent/tools/webfetch/types.ts +8 -0
  21. package/src/agent/turn-runner.ts +65 -36
  22. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
  23. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  24. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  25. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  26. package/src/bundled-plugins/memory/README.md +9 -9
  27. package/src/bundled-plugins/memory/index.ts +40 -9
  28. package/src/bundled-plugins/reviewer/skills/code-review.ts +22 -2
  29. package/src/channels/adapters/discord-bot-edit.ts +49 -0
  30. package/src/channels/adapters/discord-bot.ts +5 -0
  31. package/src/channels/adapters/discord-edit.ts +51 -0
  32. package/src/channels/adapters/discord.ts +4 -0
  33. package/src/channels/adapters/github/inbound.ts +20 -14
  34. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  35. package/src/channels/adapters/slack-bot-edit.ts +58 -0
  36. package/src/channels/adapters/slack-bot.ts +18 -6
  37. package/src/channels/adapters/slack-edit.ts +47 -0
  38. package/src/channels/adapters/slack.ts +5 -0
  39. package/src/channels/adapters/teams-classify.ts +144 -0
  40. package/src/channels/adapters/teams-edit.ts +61 -0
  41. package/src/channels/adapters/teams-id-token.ts +112 -0
  42. package/src/channels/adapters/teams-key.ts +32 -0
  43. package/src/channels/adapters/teams.ts +523 -0
  44. package/src/channels/adapters/telegram-bot-edit.ts +51 -0
  45. package/src/channels/adapters/telegram-bot.ts +5 -0
  46. package/src/channels/adapters/webex-bot.ts +5 -0
  47. package/src/channels/adapters/webex-edit.ts +47 -0
  48. package/src/channels/adapters/webex.ts +5 -0
  49. package/src/channels/continuation-willingness.ts +227 -35
  50. package/src/channels/github-review-turn-ledger.ts +43 -0
  51. package/src/channels/index.ts +1 -1
  52. package/src/channels/manager.ts +54 -1
  53. package/src/channels/router.ts +482 -53
  54. package/src/channels/schema.ts +33 -0
  55. package/src/channels/types.ts +36 -0
  56. package/src/cli/channel.ts +92 -4
  57. package/src/cli/hostd.ts +41 -0
  58. package/src/cli/init.ts +58 -1
  59. package/src/config/channels-mutation.ts +9 -1
  60. package/src/cron/index.ts +16 -4
  61. package/src/cron/reloadable.ts +25 -7
  62. package/src/cron/scheduler.ts +4 -0
  63. package/src/cron/schema.ts +143 -35
  64. package/src/doctor/channel-checks.ts +27 -0
  65. package/src/hostd/daemon.ts +23 -3
  66. package/src/hostd/protocol.ts +2 -0
  67. package/src/hostd/teams-renewal-manager.ts +212 -0
  68. package/src/init/checkpoint.ts +1 -1
  69. package/src/init/index.ts +68 -1
  70. package/src/init/run-owner-claim.ts +1 -0
  71. package/src/init/teams-auth.ts +111 -0
  72. package/src/inspect/label.ts +4 -0
  73. package/src/permissions/match-rule.ts +11 -1
  74. package/src/permissions/resolve.ts +1 -0
  75. package/src/role-claim/match-rule.ts +2 -1
  76. package/src/run/index.ts +35 -8
  77. package/src/run/llm-fetch-observer.ts +27 -5
  78. package/src/sandbox/build.ts +12 -0
  79. package/src/sandbox/policy.ts +13 -0
  80. package/src/sandbox/writable-zones.ts +46 -10
  81. package/src/secrets/schema.ts +32 -0
  82. package/src/secrets/teams-renewal.ts +229 -0
  83. package/src/secrets/teams-store.ts +108 -0
  84. package/src/server/command-runner.ts +2 -1
  85. package/src/server/index.ts +2 -1
  86. package/typeclaw.schema.json +163 -3
@@ -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
+ }
@@ -8,6 +8,7 @@ import {
8
8
  type SessionOrigin,
9
9
  } from '@/agent'
10
10
  import { applyTurnThinkingLevel } from '@/agent/attention-escalation'
11
+ import { promptWithSameRefRetryOnly } from '@/agent/retry-same-ref'
11
12
  import type { ChannelRouter } from '@/channels/router'
12
13
  import type { McpManager } from '@/mcp'
13
14
  import type { PermissionService } from '@/permissions'
@@ -427,7 +428,7 @@ export async function runPromptForCommand(args: {
427
428
  : `${renderTurnTimeAnchor()}\n\n${args.text}`
428
429
  applyTurnThinkingLevel(session, args.text, session.thinkingLevel)
429
430
  try {
430
- await session.prompt(turnText)
431
+ await promptWithSameRefRetryOnly(session, turnText)
431
432
  } finally {
432
433
  await snapshot.hooks.runSessionTurnEnd(turnEvent)
433
434
  }
@@ -18,6 +18,7 @@ import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
18
18
  import { detectProviderError, isFailoverWorthy } from '@/agent/provider-error'
19
19
  import { requestContainerRestart } from '@/agent/restart'
20
20
  import { consumeRestartHandoff, type RestartHandoff } from '@/agent/restart-handoff'
21
+ import { promptWithSameRefRetryOnly } from '@/agent/retry-same-ref'
21
22
  import { sessionMetaPayload } from '@/agent/session-meta'
22
23
  import type { SessionOrigin } from '@/agent/session-origin'
23
24
  import { parseSubagentCompletedPayload, renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
@@ -816,7 +817,7 @@ export function createServer({
816
817
  ? `${renderTurnTimeAnchor()}\n\n${msg.text}\n\n${retrievalContext.results}`
817
818
  : `${renderTurnTimeAnchor()}\n\n${msg.text}`
818
819
  applyTurnThinkingLevel(state.session, msg.text, state.turnThinkingDefault, state.lastQuestionSignal)
819
- await state.session.prompt(turnText)
820
+ await promptWithSameRefRetryOnly(state.session, turnText)
820
821
  // A usable turn seeds the next turn's escalation; a failed leaf must
821
822
  // CLEAR the prior signal (not just skip), else an older question
822
823
  // leaks across the failed turn and wrongly escalates the next one.