typeclaw 0.39.0 → 0.39.1

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 (36) hide show
  1. package/README.md +1 -0
  2. package/package.json +2 -2
  3. package/src/agent/attention-escalation.ts +154 -4
  4. package/src/agent/git-nudge.ts +7 -7
  5. package/src/agent/session-origin.ts +21 -0
  6. package/src/bundled-plugins/backup/index.ts +5 -2
  7. package/src/bundled-plugins/backup/runner.ts +55 -23
  8. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +7 -8
  9. package/src/bundled-plugins/memory/dreaming.ts +37 -24
  10. package/src/channels/adapters/kakaotalk-membership.ts +67 -0
  11. package/src/channels/adapters/kakaotalk.ts +8 -0
  12. package/src/channels/adapters/line-token.ts +55 -0
  13. package/src/channels/adapters/line.ts +74 -0
  14. package/src/channels/adapters/webex-bot-classify.ts +14 -1
  15. package/src/channels/adapters/webex-bot.ts +24 -1
  16. package/src/channels/adapters/webex-classify.ts +16 -1
  17. package/src/channels/adapters/webex.ts +27 -1
  18. package/src/channels/router.ts +55 -2
  19. package/src/cli/hostd.ts +40 -0
  20. package/src/config/config.ts +7 -5
  21. package/src/container/shared.ts +115 -14
  22. package/src/container/shell.ts +12 -2
  23. package/src/doctor/commit.ts +10 -10
  24. package/src/dreams/git.ts +20 -7
  25. package/src/dreams/index.ts +22 -7
  26. package/src/git/reconcile-ignored.ts +56 -27
  27. package/src/git/resolve-agent-git.ts +12 -0
  28. package/src/git/system-commit.ts +16 -10
  29. package/src/hostd/daemon.ts +16 -0
  30. package/src/hostd/webex-renewal-manager.ts +216 -0
  31. package/src/init/dockerfile.ts +13 -4
  32. package/src/init/gitignore.ts +4 -2
  33. package/src/secrets/schema.ts +1 -0
  34. package/src/secrets/webex-renewal.ts +215 -0
  35. package/src/server/index.ts +25 -3
  36. package/typeclaw.schema.json +6 -1
@@ -6,6 +6,7 @@ import { basename, join } from 'node:path'
6
6
  import { z } from 'zod'
7
7
 
8
8
  import { withGitLock } from '@/git/mutex'
9
+ import { type AgentGit, resolveAgentGit } from '@/git/resolve-agent-git'
9
10
  import { defineTool, lsTool, readTool, type Subagent, writeTool } from '@/plugin'
10
11
  import { formatLocalDate, formatLocalDateTime } from '@/shared'
11
12
 
@@ -751,26 +752,27 @@ export async function commitMemorySnapshot(cwd: string): Promise<void> {
751
752
  async function commitMemorySnapshotUnlocked(cwd: string): Promise<void> {
752
753
  const bun = (globalThis as { Bun?: { spawn: typeof Bun.spawn } }).Bun
753
754
  if (!bun) return
754
- if (!existsSync(join(cwd, '.git'))) return
755
+ const repo = resolveAgentGit(cwd)
756
+ if (!repo) return
755
757
 
756
- await clearSkipWorktree(bun, cwd)
758
+ await clearSkipWorktree(bun, cwd, repo)
757
759
 
758
760
  // `git add -- foo bar/` fails with exit 128 if any pathspec matches no
759
761
  // path on disk. Filter to existing paths before passing them in.
760
762
  const presentPaths = SNAPSHOT_PATHS.filter((p) => existsSync(join(cwd, p)))
761
763
  if (presentPaths.length === 0) {
762
- await applySkipWorktree(bun, cwd)
764
+ await applySkipWorktree(bun, cwd, repo)
763
765
  return
764
766
  }
765
767
 
766
768
  const add = bun.spawn({
767
- cmd: ['git', 'add', '-f', '--', ...presentPaths],
769
+ cmd: ['git', ...repo.gitArgs, 'add', '-f', '--', ...presentPaths],
768
770
  cwd,
769
771
  stdout: 'pipe',
770
772
  stderr: 'pipe',
771
773
  })
772
774
  if ((await add.exited) !== 0) {
773
- await applySkipWorktree(bun, cwd)
775
+ await applySkipWorktree(bun, cwd, repo)
774
776
  return
775
777
  }
776
778
 
@@ -779,33 +781,33 @@ async function commitMemorySnapshotUnlocked(cwd: string): Promise<void> {
779
781
  // fails outright when `bar/` matches no tracked file, even if `foo` is
780
782
  // staged.
781
783
  const stagedNames = bun.spawn({
782
- cmd: ['git', 'diff', '--cached', '--name-only', '-z', '--', ...SNAPSHOT_PATHS],
784
+ cmd: ['git', ...repo.gitArgs, 'diff', '--cached', '--name-only', '-z', '--', ...SNAPSHOT_PATHS],
783
785
  cwd,
784
786
  stdout: 'pipe',
785
787
  stderr: 'pipe',
786
788
  })
787
789
  const stagedRaw = await new Response(stagedNames.stdout).text()
788
790
  if ((await stagedNames.exited) !== 0) {
789
- await applySkipWorktree(bun, cwd)
791
+ await applySkipWorktree(bun, cwd, repo)
790
792
  return
791
793
  }
792
794
  const staged = stagedRaw.split('\0').filter((p) => p.length > 0)
793
795
  if (staged.length === 0) {
794
- await applySkipWorktree(bun, cwd)
796
+ await applySkipWorktree(bun, cwd, repo)
795
797
  return
796
798
  }
797
799
 
798
- const message = await buildCommitMessage(bun, cwd, staged)
800
+ const message = await buildCommitMessage(bun, cwd, staged, undefined, repo.gitArgs)
799
801
 
800
802
  const commit = bun.spawn({
801
- cmd: ['git', 'commit', '-m', message, '--only', '--', ...staged],
803
+ cmd: ['git', ...repo.gitArgs, 'commit', '-m', message, '--only', '--', ...staged],
802
804
  cwd,
803
805
  stdout: 'pipe',
804
806
  stderr: 'pipe',
805
807
  })
806
808
  await commit.exited
807
809
 
808
- await applySkipWorktree(bun, cwd)
810
+ await applySkipWorktree(bun, cwd, repo)
809
811
  }
810
812
 
811
813
  // Pool of emojis sampled into every dream commit. The pool is small and
@@ -837,19 +839,25 @@ export async function buildCommitMessage(
837
839
  cwd: string,
838
840
  staged: string[],
839
841
  emojiPicker: () => DreamEmoji = pickDreamEmoji,
842
+ gitArgs: readonly string[] = [],
840
843
  ): Promise<string> {
841
- const summary = await buildDreamSummary(bun, cwd, staged)
844
+ const summary = await buildDreamSummary(bun, cwd, staged, gitArgs)
842
845
  return `dream: ${summary} ${emojiPicker()}`
843
846
  }
844
847
 
845
848
  const STREAM_FILE_RELATIVE = /^memory\/(?:streams\/)?\d{4}-\d{2}-\d{2}\.jsonl$/
846
849
  const SKILL_FILE_RELATIVE = /^memory\/skills\/([^/]+)\/SKILL\.md$/
847
850
 
848
- async function buildDreamSummary(bun: { spawn: typeof Bun.spawn }, cwd: string, staged: string[]): Promise<string> {
851
+ async function buildDreamSummary(
852
+ bun: { spawn: typeof Bun.spawn },
853
+ cwd: string,
854
+ staged: string[],
855
+ gitArgs: readonly string[] = [],
856
+ ): Promise<string> {
849
857
  // numstat: `<added>\t<deleted>\t<path>` per line. Use NUL-terminated so paths
850
858
  // with whitespace round-trip; -z switches the record separator to NUL.
851
859
  const numstat = bun.spawn({
852
- cmd: ['git', 'diff', '--cached', '--numstat', '-z', '--', ...staged],
860
+ cmd: ['git', ...gitArgs, 'diff', '--cached', '--numstat', '-z', '--', ...staged],
853
861
  cwd,
854
862
  stdout: 'pipe',
855
863
  stderr: 'pipe',
@@ -874,7 +882,7 @@ async function buildDreamSummary(bun: { spawn: typeof Bun.spawn }, cwd: string,
874
882
 
875
883
  // Newly-added muscle-memory skills (status A). Refinements (status M) are
876
884
  // not announced — they ride under the fragment count.
877
- const newSkills = await listNewlyAddedSkills(bun, cwd, staged)
885
+ const newSkills = await listNewlyAddedSkills(bun, cwd, staged, gitArgs)
878
886
 
879
887
  const parts: string[] = []
880
888
  if (fragmentLines > 0) {
@@ -903,9 +911,10 @@ async function listNewlyAddedSkills(
903
911
  bun: { spawn: typeof Bun.spawn },
904
912
  cwd: string,
905
913
  staged: string[],
914
+ gitArgs: readonly string[] = [],
906
915
  ): Promise<string[]> {
907
916
  const proc = bun.spawn({
908
- cmd: ['git', 'diff', '--cached', '--name-status', '-z', '--', ...staged],
917
+ cmd: ['git', ...gitArgs, 'diff', '--cached', '--name-status', '-z', '--', ...staged],
909
918
  cwd,
910
919
  stdout: 'pipe',
911
920
  stderr: 'pipe',
@@ -927,9 +936,13 @@ async function listNewlyAddedSkills(
927
936
  return names.filter((n) => n.length > 0)
928
937
  }
929
938
 
930
- async function listTrackedSnapshotFiles(bun: { spawn: typeof Bun.spawn }, cwd: string): Promise<string[]> {
939
+ async function listTrackedSnapshotFiles(
940
+ bun: { spawn: typeof Bun.spawn },
941
+ cwd: string,
942
+ repo: AgentGit,
943
+ ): Promise<string[]> {
931
944
  const ls = bun.spawn({
932
- cmd: ['git', 'ls-files', '-z', '--', ...SNAPSHOT_PATHS],
945
+ cmd: ['git', ...repo.gitArgs, 'ls-files', '-z', '--', ...SNAPSHOT_PATHS],
933
946
  cwd,
934
947
  stdout: 'pipe',
935
948
  stderr: 'pipe',
@@ -939,11 +952,11 @@ async function listTrackedSnapshotFiles(bun: { spawn: typeof Bun.spawn }, cwd: s
939
952
  return raw.split('\0').filter((p) => p.length > 0)
940
953
  }
941
954
 
942
- async function clearSkipWorktree(bun: { spawn: typeof Bun.spawn }, cwd: string): Promise<void> {
943
- const files = await listTrackedSnapshotFiles(bun, cwd)
955
+ async function clearSkipWorktree(bun: { spawn: typeof Bun.spawn }, cwd: string, repo: AgentGit): Promise<void> {
956
+ const files = await listTrackedSnapshotFiles(bun, cwd, repo)
944
957
  if (files.length === 0) return
945
958
  const proc = bun.spawn({
946
- cmd: ['git', 'update-index', '--no-skip-worktree', '--', ...files],
959
+ cmd: ['git', ...repo.gitArgs, 'update-index', '--no-skip-worktree', '--', ...files],
947
960
  cwd,
948
961
  stdout: 'pipe',
949
962
  stderr: 'pipe',
@@ -951,11 +964,11 @@ async function clearSkipWorktree(bun: { spawn: typeof Bun.spawn }, cwd: string):
951
964
  await proc.exited
952
965
  }
953
966
 
954
- async function applySkipWorktree(bun: { spawn: typeof Bun.spawn }, cwd: string): Promise<void> {
955
- const files = await listTrackedSnapshotFiles(bun, cwd)
967
+ async function applySkipWorktree(bun: { spawn: typeof Bun.spawn }, cwd: string, repo: AgentGit): Promise<void> {
968
+ const files = await listTrackedSnapshotFiles(bun, cwd, repo)
956
969
  if (files.length === 0) return
957
970
  const proc = bun.spawn({
958
- cmd: ['git', 'update-index', '--skip-worktree', '--', ...files],
971
+ cmd: ['git', ...repo.gitArgs, 'update-index', '--skip-worktree', '--', ...files],
959
972
  cwd,
960
973
  stdout: 'pipe',
961
974
  stderr: 'pipe',
@@ -0,0 +1,67 @@
1
+ import type {
2
+ MembershipCount,
3
+ MembershipResolver,
4
+ MembershipResolverFailure,
5
+ MembershipResolverResult,
6
+ } from '../membership'
7
+ import type { KakaoTalkClient } from './kakaotalk'
8
+
9
+ export type KakaoMembershipResolverOptions = {
10
+ client: Pick<KakaoTalkClient, 'getMembers'>
11
+ // The logged-in agent's own KakaoTalk user_id. Returned by `getMembers`
12
+ // alongside every human in the room, so it must be excluded from the
13
+ // human count — otherwise a 1:1 chat (agent + one human) reports two
14
+ // humans and a real group is off by one. Null before login completes,
15
+ // in which case we cannot prove self-exclusion and fail closed.
16
+ selfUserIdRef: () => string | null
17
+ logger: { warn: (msg: string) => void }
18
+ now?: () => number
19
+ }
20
+
21
+ // Without a registered resolver the router's `resolveEffectiveHumans` falls
22
+ // back to `persistedHumans` — only humans who already posted in the live
23
+ // session. On a cold-started group that is just the sender, tripping the
24
+ // engagement layer's solo-human "answer everything" fallback so the agent
25
+ // replies to messages aimed at others. Every other adapter registers a
26
+ // resolver; KakaoTalk was the lone gap. `getMembers` returns the COMPLETE
27
+ // active roster (agent-messenger merges the GETMEM subset with the CHATONROOM
28
+ // full list), so unlike Telegram's opaque count we report it as non-truncated.
29
+ // Room rosters list only human accounts plus the agent's own; hence
30
+ // `humans = roster excluding self` and `bots: 1` (the agent) — `bots: 0` would
31
+ // defeat the engagement layer's peer-bot loop suppression.
32
+ export function createKakaoMembershipResolver(options: KakaoMembershipResolverOptions): MembershipResolver {
33
+ const now = options.now ?? Date.now
34
+ return async (key): Promise<MembershipResolverResult> => {
35
+ if (key.adapter !== 'kakaotalk') return { kind: 'permanent' } satisfies MembershipResolverFailure
36
+ const selfUserId = options.selfUserIdRef()
37
+ if (selfUserId === null) {
38
+ // Pre-login: we cannot exclude ourselves from the roster, so any count
39
+ // would over-report humans by one. Fail transient so the router keeps
40
+ // its `persistedHumans` fallback and retries once we have identity.
41
+ return { kind: 'transient' } satisfies MembershipResolverFailure
42
+ }
43
+ try {
44
+ const members = await options.client.getMembers(key.chat)
45
+ // Dedupe by user_id — a merged GETMEM+CHATONROOM roster can list the
46
+ // same member twice when both sources carry them.
47
+ const memberIds = new Set<string>()
48
+ for (const m of members) memberIds.add(m.user_id)
49
+ memberIds.delete(selfUserId)
50
+ const humanMemberIds = [...memberIds]
51
+ return {
52
+ humans: humanMemberIds.length,
53
+ bots: 1,
54
+ fetchedAt: now(),
55
+ truncated: false,
56
+ humanMemberIds,
57
+ } satisfies MembershipCount
58
+ } catch (err) {
59
+ options.logger.warn(`[kakaotalk] membership chat=${key.chat} failed: ${describe(err)}`)
60
+ return { kind: 'transient' } satisfies MembershipResolverFailure
61
+ }
62
+ }
63
+ }
64
+
65
+ function describe(err: unknown): string {
66
+ return err instanceof Error ? err.message : String(err)
67
+ }
@@ -43,6 +43,7 @@ import { createKakaoChannelResolver, type KakaoChannelResolver } from './kakaota
43
43
  import { classifyInbound, type InboundDropReason } from './kakaotalk-classify'
44
44
  import { createFetchAttachmentCallback } from './kakaotalk-fetch-attachment'
45
45
  import { toKakaoPlainText } from './kakaotalk-format'
46
+ import { createKakaoMembershipResolver } from './kakaotalk-membership'
46
47
 
47
48
  // Structural duck-type of the upstream KakaoTalkClient class. The upstream
48
49
  // type is a class with private fields, and TypeScript treats those
@@ -368,6 +369,11 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
368
369
 
369
370
  const channelResolver = createKakaoChannelResolver({ client, logger })
370
371
  const authorResolver = createKakaoAuthorResolver({ client, logger })
372
+ const membershipResolver = createKakaoMembershipResolver({
373
+ client,
374
+ selfUserIdRef: () => selfUserId,
375
+ logger,
376
+ })
371
377
 
372
378
  const formatChannelTag = async (workspace: string, chat: string): Promise<string> => {
373
379
  const names = await channelResolver
@@ -658,6 +664,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
658
664
  options.router.registerChannelNameResolver('kakaotalk', channelResolver.resolve)
659
665
  options.router.registerHistory('kakaotalk', historyCallback)
660
666
  options.router.registerFetchAttachment('kakaotalk', fetchAttachmentCallback)
667
+ options.router.registerMembership('kakaotalk', membershipResolver)
661
668
  },
662
669
 
663
670
  async stop(): Promise<void> {
@@ -667,6 +674,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
667
674
  options.router.unregisterChannelNameResolver('kakaotalk', channelResolver.resolve)
668
675
  options.router.unregisterHistory('kakaotalk', historyCallback)
669
676
  options.router.unregisterFetchAttachment('kakaotalk', fetchAttachmentCallback)
677
+ options.router.unregisterMembership('kakaotalk', membershipResolver)
670
678
  if (inflightInbounds > 0) {
671
679
  await new Promise<void>((resolve) => {
672
680
  stopWaiters.push(resolve)
@@ -0,0 +1,55 @@
1
+ // LINE access tokens (`auth_token`) are JWTs with a ~7-day lifetime. The adapter
2
+ // schedules a proactive refresh ahead of expiry rather than waiting for the SDK's
3
+ // reactive MUST_REFRESH_V3_TOKEN path, which only fires on a live request and
4
+ // surfaces a cryptic failure when the token is already fully expired at startup.
5
+
6
+ // Refresh once the token is within this window of its expiry. The LINE refresh
7
+ // token lives ~365 days and rotates on use, so refreshing early is cheap and
8
+ // leaves margin for missed timers (container asleep, listener reconnecting).
9
+ export const LINE_TOKEN_REFRESH_SKEW_MS = 24 * 60 * 60 * 1000
10
+
11
+ // Clamp the scheduled timer so a malformed or far-future `exp` can't push the
12
+ // next refresh check beyond a day, and a near/past expiry retries promptly
13
+ // rather than busy-looping.
14
+ const MIN_REFRESH_DELAY_MS = 60 * 1000
15
+ const MAX_REFRESH_DELAY_MS = 24 * 60 * 60 * 1000
16
+
17
+ export function decodeJwtExpMs(token: string): number | null {
18
+ const parts = token.split('.')
19
+ if (parts.length < 2) return null
20
+ const payload = parts[1]
21
+ if (payload === undefined || payload === '') return null
22
+ try {
23
+ const json = Buffer.from(base64UrlToBase64(payload), 'base64').toString('utf-8')
24
+ const parsed: unknown = JSON.parse(json)
25
+ if (typeof parsed !== 'object' || parsed === null) return null
26
+ const exp = (parsed as { exp?: unknown }).exp
27
+ if (typeof exp !== 'number' || !Number.isFinite(exp)) return null
28
+ return exp * 1000
29
+ } catch {
30
+ return null
31
+ }
32
+ }
33
+
34
+ export function isTokenNearExpiry(token: string, now: number, skewMs = LINE_TOKEN_REFRESH_SKEW_MS): boolean {
35
+ const expMs = decodeJwtExpMs(token)
36
+ // A token we can't decode is treated as needing refresh: better to attempt a
37
+ // (cheap, idempotent) refresh than to sit on an opaque, possibly-dead token.
38
+ if (expMs === null) return true
39
+ return now >= expMs - skewMs
40
+ }
41
+
42
+ export function nextRefreshDelayMs(token: string, now: number, skewMs = LINE_TOKEN_REFRESH_SKEW_MS): number {
43
+ const expMs = decodeJwtExpMs(token)
44
+ if (expMs === null) return MIN_REFRESH_DELAY_MS
45
+ const target = expMs - skewMs
46
+ const delay = target - now
47
+ if (delay <= 0) return MIN_REFRESH_DELAY_MS
48
+ return Math.min(Math.max(delay, MIN_REFRESH_DELAY_MS), MAX_REFRESH_DELAY_MS)
49
+ }
50
+
51
+ function base64UrlToBase64(input: string): string {
52
+ const replaced = input.replace(/-/g, '+').replace(/_/g, '/')
53
+ const pad = replaced.length % 4
54
+ return pad === 0 ? replaced : replaced + '='.repeat(4 - pad)
55
+ }
@@ -29,6 +29,7 @@ import { splitInboundLine } from './line-attachment'
29
29
  import { createLineChannelResolver } from './line-channel-resolver'
30
30
  import { classifyInbound } from './line-classify'
31
31
  import { toLinePlainText } from './line-format'
32
+ import { LINE_TOKEN_REFRESH_SKEW_MS, nextRefreshDelayMs } from './line-token'
32
33
 
33
34
  // Structural duck-type of the upstream LineClient class. Declaring this as an
34
35
  // interface (rather than reusing the nominal class type) lets test fakes
@@ -41,6 +42,11 @@ export interface LineClient {
41
42
  getMessages(chatId: string, options?: { count?: number }): Promise<LineMessage[]>
42
43
  sendMessage(chatId: string, text: string): Promise<LineSendResult>
43
44
  close(): void
45
+ // Optional on the structural type: older SDK builds predate the refresh
46
+ // surface, so the adapter feature-detects both before using them and a
47
+ // missing method degrades to "no proactive refresh" rather than a crash.
48
+ ensureFreshAuthToken?: (options?: { skewMs?: number }) => Promise<string | null>
49
+ onTokenUpdate?: (listener: (authToken: string) => void) => void
44
50
  }
45
51
 
46
52
  export interface LineListener {
@@ -53,6 +59,7 @@ export interface LineListener {
53
59
  export type LineCredentialStore = {
54
60
  load(): Promise<LineConfig>
55
61
  getAccount(id?: string): Promise<LineAccountCredentials | null>
62
+ setAccount?(account: LineAccountCredentials): Promise<void>
56
63
  }
57
64
 
58
65
  const LineClient = RealLineClient as unknown as new (credManager?: LineCredentialManager) => LineClient
@@ -79,6 +86,7 @@ export type LineAdapterOptions = {
79
86
  client?: LineClient
80
87
  clientFactory?: (credManager?: LineCredentialManager) => LineClient
81
88
  listenerFactory?: (client: LineClient) => LineListener
89
+ now?: () => number
82
90
  }
83
91
 
84
92
  export type LineAdapter = {
@@ -181,6 +189,14 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
181
189
  let started = false
182
190
  let inflightInbounds = 0
183
191
  let stopWaiters: Array<() => void> = []
192
+ let refreshTimer: ReturnType<typeof setTimeout> | null = null
193
+ // currentAuthToken tracks the freshest known token for refresh SCHEDULING;
194
+ // lastPersistedToken is the dedupe marker and only advances after a write to
195
+ // secrets actually succeeds, so a failed persist can be retried with the same
196
+ // token instead of being silently swallowed by the dedupe early-return.
197
+ let currentAuthToken: string | null = null
198
+ let lastPersistedToken: string | null = null
199
+ const now = options.now ?? Date.now
184
200
 
185
201
  const channelResolver = createLineChannelResolver({ client, logger })
186
202
 
@@ -199,6 +215,51 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
199
215
 
200
216
  const outboundCallback = createOutboundCallback({ client, logger, formatChannelTag })
201
217
 
218
+ // The SDK's AuthService updates the LIVE client's token in-place and emits this
219
+ // event; we mirror it into secrets.json so the next container start boots from a
220
+ // fresh token instead of a dead one. The refresh token (which rotates on use)
221
+ // stays the SDK FileStorage's responsibility and is never copied here.
222
+ const persistAuthToken = async (authToken: string): Promise<void> => {
223
+ currentAuthToken = authToken
224
+ if (authToken === lastPersistedToken) return
225
+ const store = options.credentialsStore
226
+ if (!store?.setAccount) return
227
+ try {
228
+ const account = await store.getAccount()
229
+ if (account === null) return
230
+ await store.setAccount({ ...account, auth_token: authToken, updated_at: new Date(now()).toISOString() })
231
+ lastPersistedToken = authToken
232
+ logger.info('[line] persisted refreshed auth token to secrets')
233
+ } catch (err) {
234
+ logger.warn(`[line] failed to persist refreshed auth token: ${describe(err)}`)
235
+ }
236
+ }
237
+
238
+ const refreshNow = async (): Promise<void> => {
239
+ if (!client.ensureFreshAuthToken) return
240
+ try {
241
+ const token = await client.ensureFreshAuthToken({ skewMs: LINE_TOKEN_REFRESH_SKEW_MS })
242
+ if (token) await persistAuthToken(token)
243
+ } catch (err) {
244
+ logger.warn(`[line] token refresh failed: ${describe(err)}`)
245
+ }
246
+ }
247
+
248
+ const scheduleRefresh = (): void => {
249
+ if (refreshTimer !== null) clearTimeout(refreshTimer)
250
+ if (!client.ensureFreshAuthToken) return
251
+ const token = currentAuthToken
252
+ const delay = token ? nextRefreshDelayMs(token, now()) : LINE_TOKEN_REFRESH_SKEW_MS
253
+ refreshTimer = setTimeout(() => {
254
+ void (async () => {
255
+ if (!started) return
256
+ await refreshNow()
257
+ if (started) scheduleRefresh()
258
+ })()
259
+ }, delay)
260
+ refreshTimer.unref?.()
261
+ }
262
+
202
263
  const processInbound = async (event: LinePushMessageEvent): Promise<void> => {
203
264
  inflightInbounds++
204
265
  try {
@@ -255,6 +316,10 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
255
316
  async start(): Promise<void> {
256
317
  if (started) return
257
318
  started = true
319
+ client.onTokenUpdate?.((authToken) => {
320
+ void persistAuthToken(authToken)
321
+ })
322
+
258
323
  try {
259
324
  const credentialStore = options.credentialsStore ?? null
260
325
  if (credentialStore !== null) {
@@ -262,6 +327,8 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
262
327
  if (account === null) {
263
328
  throw new Error('no LINE account in secrets.json#channels.line (run typeclaw init to authenticate)')
264
329
  }
330
+ currentAuthToken = account.auth_token
331
+ lastPersistedToken = account.auth_token
265
332
  await client.login(account)
266
333
  } else {
267
334
  await client.login()
@@ -272,6 +339,9 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
272
339
  throw err
273
340
  }
274
341
 
342
+ await refreshNow()
343
+ scheduleRefresh()
344
+
275
345
  try {
276
346
  const profile = await client.getProfile()
277
347
  selfUserId = profile.mid
@@ -329,6 +399,10 @@ export function createLineAdapter(options: LineAdapterOptions): LineAdapter {
329
399
  async stop(): Promise<void> {
330
400
  if (!started) return
331
401
  started = false
402
+ if (refreshTimer !== null) {
403
+ clearTimeout(refreshTimer)
404
+ refreshTimer = null
405
+ }
332
406
  options.router.unregisterOutbound('line', outboundCallback)
333
407
  options.router.unregisterChannelNameResolver('line', channelResolver.resolve)
334
408
  options.router.unregisterHistory('line', historyCallback)
@@ -12,13 +12,18 @@ export type InboundClassification =
12
12
  | { kind: 'drop'; reason: InboundDropReason }
13
13
  | { kind: 'route'; payload: InboundMessage }
14
14
 
15
+ // `botPersonEmail` is a second self-identity anchor alongside `botPersonRef`:
16
+ // legacy Hydra accounts can decode the bot identity to an email on one side and a
17
+ // UUID on the other, so a ref-only check leaks the agent's own reply back as a
18
+ // new inbound. Matching personEmail closes that echo loop. See webex-classify.ts.
15
19
  export function classifyInbound(
16
20
  event: WebexInboundMessage,
17
21
  _config: ChannelAdapterConfig,
18
22
  botPersonRef: string | null,
19
23
  selfAliases: readonly string[] = [],
24
+ botPersonEmail: string | null = null,
20
25
  ): InboundClassification {
21
- if (botPersonRef !== null && event.personRef === botPersonRef) {
26
+ if (isSelfAuthor(event, botPersonRef, botPersonEmail)) {
22
27
  return { kind: 'drop', reason: 'self_author' }
23
28
  }
24
29
 
@@ -66,6 +71,14 @@ export function classifyInbound(
66
71
  }
67
72
  }
68
73
 
74
+ function isSelfAuthor(event: WebexInboundMessage, botPersonRef: string | null, botPersonEmail: string | null): boolean {
75
+ if (botPersonRef !== null && event.personRef === botPersonRef) return true
76
+ if (botPersonEmail !== null && event.personEmail !== '') {
77
+ return event.personEmail.toLowerCase() === botPersonEmail.toLowerCase()
78
+ }
79
+ return false
80
+ }
81
+
69
82
  type SplitInbound = { text: string; attachments: InboundAttachment[] }
70
83
 
71
84
  function splitInbound(event: WebexInboundMessage): SplitInbound {
@@ -136,14 +136,24 @@ async function defaultReadFile(path: string): Promise<WebexOutboundFile> {
136
136
  return { content: Bun.file(path), filename: path.split('/').pop() ?? 'attachment' }
137
137
  }
138
138
 
139
+ // See webex.ts: the bot client has no AbortSignal either, so a hung listMessages
140
+ // is bounded by a tighter internal deadline than the router's 5s history ceiling.
141
+ const WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS = 2500
142
+
139
143
  export function createWebexHistoryCallback(deps: {
140
144
  client: Pick<WebexBotClient, 'listMessages'>
141
145
  logger: WebexBotAdapterLogger
142
146
  botPersonIdRef: () => string | null
147
+ timeoutMs?: number
143
148
  }): HistoryCallback {
149
+ const timeoutMs = deps.timeoutMs ?? WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS
144
150
  return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
145
151
  try {
146
- const messages = await deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) })
152
+ const messages = await raceWithTimeout(
153
+ deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) }),
154
+ timeoutMs,
155
+ '[webex-bot] history fetch',
156
+ )
147
157
  return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, deps.botPersonIdRef())).reverse() }
148
158
  } catch (err) {
149
159
  const message = describe(err)
@@ -297,6 +307,7 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
297
307
  options.configRef(),
298
308
  botSnapshot?.ref ?? null,
299
309
  options.selfAliasesRef?.() ?? [],
310
+ botSnapshot?.emails[0] ?? null,
300
311
  )
301
312
  if (verdict.kind === 'drop') {
302
313
  logger.info(`[webex-bot] dropped id=${event.ref} reason=${verdict.reason}${dropHint(verdict.reason)}`)
@@ -451,6 +462,18 @@ function describe(err: unknown): string {
451
462
  return err instanceof Error ? err.message : String(err)
452
463
  }
453
464
 
465
+ async function raceWithTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {
466
+ let timer: ReturnType<typeof setTimeout> | null = null
467
+ const timeout = new Promise<never>((_, reject) => {
468
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
469
+ })
470
+ try {
471
+ return await Promise.race([work, timeout])
472
+ } finally {
473
+ if (timer !== null) clearTimeout(timer)
474
+ }
475
+ }
476
+
454
477
  function dropHint(reason: InboundDropReason): string {
455
478
  switch (reason) {
456
479
  case 'empty_content':
@@ -16,13 +16,20 @@ export type InboundClassification =
16
16
  // `botPersonRef` is the bot's decoded UUID ref (from WebexPerson.ref), matched
17
17
  // against the event's *Ref fields so identity comparison happens entirely in
18
18
  // ref-space — the same currency typeclaw now stores as ChannelKey/authorId.
19
+ //
20
+ // `botPersonEmail` is a second self-identity anchor: legacy Hydra accounts can
21
+ // surface the bot's ref as an email on one side (`/people/me`) and a UUID on the
22
+ // other (Mercury event), so a ref-only check leaks the agent's own reply back as
23
+ // a new inbound and burns a full prompt cycle. Matching personEmail closes that
24
+ // echo loop regardless of which side decoded to which form.
19
25
  export function classifyInbound(
20
26
  event: WebexInboundMessage,
21
27
  _config: ChannelAdapterConfig,
22
28
  botPersonRef: string | null,
23
29
  selfAliases: readonly string[] = [],
30
+ botPersonEmail: string | null = null,
24
31
  ): InboundClassification {
25
- if (botPersonRef !== null && event.personRef === botPersonRef) {
32
+ if (isSelfAuthor(event, botPersonRef, botPersonEmail)) {
26
33
  return { kind: 'drop', reason: 'self_author' }
27
34
  }
28
35
 
@@ -72,6 +79,14 @@ export function classifyInbound(
72
79
  }
73
80
  }
74
81
 
82
+ function isSelfAuthor(event: WebexInboundMessage, botPersonRef: string | null, botPersonEmail: string | null): boolean {
83
+ if (botPersonRef !== null && event.personRef === botPersonRef) return true
84
+ if (botPersonEmail !== null && event.personEmail !== '') {
85
+ return event.personEmail.toLowerCase() === botPersonEmail.toLowerCase()
86
+ }
87
+ return false
88
+ }
89
+
75
90
  type SplitInbound = { text: string; attachments: InboundAttachment[] }
76
91
 
77
92
  function splitInbound(event: WebexInboundMessage): SplitInbound {
@@ -141,14 +141,27 @@ async function defaultReadFile(path: string): Promise<WebexOutboundFile> {
141
141
  return { content: Bun.file(path), filename: path.split('/').pop() ?? 'attachment' }
142
142
  }
143
143
 
144
+ // The Webex REST/internal client offers no AbortSignal, so a hung `listMessages`
145
+ // would otherwise block cold-start prefetch for the router's full 5s history
146
+ // ceiling before degrading. Racing it against a tighter internal deadline lets
147
+ // prefetch fall back to membership-derivation (or skip) seconds sooner, mirroring
148
+ // the cold-fetch fail-fast posture the membership resolver already uses.
149
+ const WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS = 2500
150
+
144
151
  export function createWebexHistoryCallback(deps: {
145
152
  client: Pick<WebexClient, 'listMessages'>
146
153
  logger: WebexAdapterLogger
147
154
  botPersonIdRef: () => string | null
155
+ timeoutMs?: number
148
156
  }): HistoryCallback {
157
+ const timeoutMs = deps.timeoutMs ?? WEBEX_HISTORY_COLD_FETCH_TIMEOUT_MS
149
158
  return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
150
159
  try {
151
- const messages = await deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) })
160
+ const messages = await raceWithTimeout(
161
+ deps.client.listMessages(args.chat, { max: clampLimit(args.limit, 100) }),
162
+ timeoutMs,
163
+ '[webex] history fetch',
164
+ )
152
165
  const authorById = new Map(messages.map((m) => [m.ref, m.personRef]))
153
166
  const botPersonId = deps.botPersonIdRef()
154
167
  return { ok: true, messages: messages.map((m) => mapWebexHistoryMessage(m, botPersonId, authorById)).reverse() }
@@ -305,6 +318,7 @@ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
305
318
  options.configRef(),
306
319
  botSnapshot?.ref ?? null,
307
320
  options.selfAliasesRef?.() ?? [],
321
+ botSnapshot?.emails[0] ?? null,
308
322
  )
309
323
  if (verdict.kind === 'drop') {
310
324
  logger.info(`[webex] dropped id=${event.ref} reason=${verdict.reason}${dropHint(verdict.reason)}`)
@@ -482,6 +496,18 @@ function describe(err: unknown): string {
482
496
  return err instanceof Error ? err.message : String(err)
483
497
  }
484
498
 
499
+ async function raceWithTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {
500
+ let timer: ReturnType<typeof setTimeout> | null = null
501
+ const timeout = new Promise<never>((_, reject) => {
502
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
503
+ })
504
+ try {
505
+ return await Promise.race([work, timeout])
506
+ } finally {
507
+ if (timer !== null) clearTimeout(timer)
508
+ }
509
+ }
510
+
485
511
  function dropHint(reason: InboundDropReason): string {
486
512
  switch (reason) {
487
513
  case 'empty_content':