typeclaw 0.39.0 → 0.39.2

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 (43) 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 +112 -13
  19. package/src/cli/hostd.ts +40 -0
  20. package/src/compose/logs.ts +20 -6
  21. package/src/config/config.ts +7 -5
  22. package/src/container/logs.ts +19 -4
  23. package/src/container/shared.ts +222 -18
  24. package/src/container/shell.ts +12 -2
  25. package/src/container/start.ts +191 -30
  26. package/src/doctor/commit.ts +10 -10
  27. package/src/dreams/git.ts +20 -7
  28. package/src/dreams/index.ts +22 -7
  29. package/src/git/reconcile-ignored.ts +56 -27
  30. package/src/git/resolve-agent-git.ts +12 -0
  31. package/src/git/system-commit.ts +16 -10
  32. package/src/hostd/daemon.ts +16 -0
  33. package/src/hostd/webex-renewal-manager.ts +216 -0
  34. package/src/init/auto-upgrade.ts +38 -4
  35. package/src/init/cli-version.ts +30 -1
  36. package/src/init/dockerfile.ts +31 -9
  37. package/src/init/gitignore.ts +4 -2
  38. package/src/init/index.ts +47 -39
  39. package/src/init/windows-dev-link.ts +64 -0
  40. package/src/secrets/schema.ts +1 -0
  41. package/src/secrets/webex-renewal.ts +215 -0
  42. package/src/server/index.ts +25 -3
  43. package/typeclaw.schema.json +6 -1
@@ -1,10 +1,11 @@
1
- import { existsSync } from 'node:fs'
2
1
  import { mkdtemp, rm, writeFile } from 'node:fs/promises'
3
2
  import { tmpdir } from 'node:os'
4
3
  import { join } from 'node:path'
5
4
 
6
5
  import { SYSTEM_MANAGED_ROOTS, TRULY_IGNORED_PATTERNS } from '@/init/gitignore'
7
6
 
7
+ import { type AgentGit, resolveAgentGit } from './resolve-agent-git'
8
+
8
9
  export type UntrackResult = { untracked: string[] }
9
10
 
10
11
  // Removes from the index any tracked file that now matches a truly-ignored
@@ -26,7 +27,8 @@ export async function untrackTrulyIgnoredFiles(
26
27
 
27
28
  const bun = getBun()
28
29
  if (!bun) return empty
29
- if (!existsSync(join(cwd, '.git'))) return empty
30
+ const repo = resolveAgentGit(cwd)
31
+ if (!repo) return empty
30
32
 
31
33
  const patterns = [...TRULY_IGNORED_PATTERNS, ...customAppend]
32
34
  let excludeDir: string | null = null
@@ -35,11 +37,11 @@ export async function untrackTrulyIgnoredFiles(
35
37
  const excludeFile = join(excludeDir, 'exclude')
36
38
  await writeFile(excludeFile, `${patterns.join('\n')}\n`)
37
39
 
38
- const candidates = await listTrackedIgnored(bun, cwd, excludeFile)
40
+ const candidates = await listTrackedIgnored(bun, cwd, repo.gitArgs, excludeFile)
39
41
  const removable = candidates.filter((path) => !isSystemManaged(path))
40
42
  if (removable.length === 0) return empty
41
43
 
42
- const removed = await gitRmCached(bun, cwd, removable)
44
+ const removed = await gitRmCached(bun, cwd, repo.gitArgs, removable)
43
45
  return { untracked: removed }
44
46
  } catch {
45
47
  return empty
@@ -76,6 +78,7 @@ export type CommitGitignoreDeps = {
76
78
  commitAtomic?: (
77
79
  bun: BunLike,
78
80
  cwd: string,
81
+ repo: AgentGit,
79
82
  gitignoreFile: string,
80
83
  untracked: readonly string[],
81
84
  message: string,
@@ -91,39 +94,41 @@ export async function commitGitignoreWithUntracks(
91
94
  ): Promise<boolean> {
92
95
  const bun = getBun()
93
96
  if (!bun) return false
94
- if (!existsSync(join(cwd, '.git'))) return false
97
+ const repo = resolveAgentGit(cwd)
98
+ if (!repo) return false
95
99
  if (untracked.length === 0) return false
96
100
 
97
101
  const commitAtomic = deps.commitAtomic ?? commitViaTempIndex
98
- if (!(await run(bun, cwd, ['add', '--', gitignoreFile]))) return false
99
- if (await commitAtomic(bun, cwd, gitignoreFile, untracked, message)) return true
100
- return await commitRealIndexIfExactlyOurs(bun, cwd, gitignoreFile, untracked, message)
102
+ if (!(await run(bun, cwd, repo.gitArgs, ['add', '--', gitignoreFile]))) return false
103
+ if (await commitAtomic(bun, cwd, repo, gitignoreFile, untracked, message)) return true
104
+ return await commitRealIndexIfExactlyOurs(bun, cwd, repo.gitArgs, gitignoreFile, untracked, message)
101
105
  }
102
106
 
103
107
  async function commitViaTempIndex(
104
108
  bun: BunLike,
105
109
  cwd: string,
110
+ repo: AgentGit,
106
111
  gitignoreFile: string,
107
112
  untracked: readonly string[],
108
113
  message: string,
109
114
  ): Promise<boolean> {
110
115
  let indexDir: string | null = null
111
116
  try {
112
- const parent = (await capture(bun, cwd, ['rev-parse', '--verify', 'HEAD'])).trim()
117
+ const parent = (await capture(bun, cwd, repo.gitArgs, ['rev-parse', '--verify', 'HEAD'])).trim()
113
118
  if (parent.length === 0) return false
114
119
 
115
120
  indexDir = await mkdtemp(join(tmpdir(), 'typeclaw-untrack-idx-'))
116
121
  const env = { ...process.env, GIT_INDEX_FILE: join(indexDir, 'index') }
117
- if (!(await run(bun, cwd, ['read-tree', parent], env))) return false
118
- if (!(await run(bun, cwd, ['add', '--', gitignoreFile], env))) return false
119
- if (!(await forceRemove(bun, cwd, untracked, env))) return false
122
+ if (!(await run(bun, cwd, repo.gitArgs, ['read-tree', parent], env))) return false
123
+ if (!(await run(bun, cwd, repo.gitArgs, ['add', '--', gitignoreFile], env))) return false
124
+ if (!(await forceRemove(bun, cwd, repo.gitArgs, untracked, env))) return false
120
125
 
121
- const tree = (await capture(bun, cwd, ['write-tree'], env)).trim()
126
+ const tree = (await capture(bun, cwd, repo.gitArgs, ['write-tree'], env)).trim()
122
127
  if (tree.length === 0) return false
123
- const commit = (await capture(bun, cwd, ['commit-tree', tree, '-p', parent, '-m', message])).trim()
128
+ const commit = (await capture(bun, cwd, repo.gitArgs, ['commit-tree', tree, '-p', parent, '-m', message])).trim()
124
129
  if (commit.length === 0) return false
125
130
 
126
- return await run(bun, cwd, ['update-ref', '-m', message, 'HEAD', commit, parent])
131
+ return await run(bun, cwd, repo.gitArgs, ['update-ref', '-m', message, 'HEAD', commit, parent])
127
132
  } catch {
128
133
  return false
129
134
  } finally {
@@ -134,11 +139,12 @@ async function commitViaTempIndex(
134
139
  async function commitRealIndexIfExactlyOurs(
135
140
  bun: BunLike,
136
141
  cwd: string,
142
+ gitArgs: readonly string[],
137
143
  gitignoreFile: string,
138
144
  untracked: readonly string[],
139
145
  message: string,
140
146
  ): Promise<boolean> {
141
- const staged = (await capture(bun, cwd, ['diff', '--cached', '--name-only', '-z']))
147
+ const staged = (await capture(bun, cwd, gitArgs, ['diff', '--cached', '--name-only', '-z']))
142
148
  .split('\0')
143
149
  .filter((entry) => entry.length > 0)
144
150
  if (staged.length === 0) return false
@@ -146,7 +152,7 @@ async function commitRealIndexIfExactlyOurs(
146
152
  const expected = new Set([gitignoreFile, ...untracked])
147
153
  if (staged.length !== expected.size || !staged.every((path) => expected.has(path))) return false
148
154
 
149
- return await run(bun, cwd, ['commit', '-m', message])
155
+ return await run(bun, cwd, gitArgs, ['commit', '-m', message])
150
156
  }
151
157
 
152
158
  // Hardcoded fail-closed guard: even if a custom git.ignore.append pattern
@@ -157,9 +163,14 @@ function isSystemManaged(path: string): boolean {
157
163
  return SYSTEM_MANAGED_ROOTS.some((root) => path === root.replace(/\/$/, '') || path.startsWith(root))
158
164
  }
159
165
 
160
- async function listTrackedIgnored(bun: BunLike, cwd: string, excludeFile: string): Promise<string[]> {
166
+ async function listTrackedIgnored(
167
+ bun: BunLike,
168
+ cwd: string,
169
+ gitArgs: readonly string[],
170
+ excludeFile: string,
171
+ ): Promise<string[]> {
161
172
  const proc = bun.spawn({
162
- cmd: ['git', 'ls-files', '-z', '-c', '-i', '--exclude-from', excludeFile],
173
+ cmd: ['git', ...gitArgs, 'ls-files', '-z', '-c', '-i', '--exclude-from', excludeFile],
163
174
  cwd,
164
175
  stdout: 'pipe',
165
176
  stderr: 'pipe',
@@ -169,9 +180,9 @@ async function listTrackedIgnored(bun: BunLike, cwd: string, excludeFile: string
169
180
  return raw.split('\0').filter((entry) => entry.length > 0)
170
181
  }
171
182
 
172
- async function gitRmCached(bun: BunLike, cwd: string, files: string[]): Promise<string[]> {
183
+ async function gitRmCached(bun: BunLike, cwd: string, gitArgs: readonly string[], files: string[]): Promise<string[]> {
173
184
  const proc = bun.spawn({
174
- cmd: ['git', 'rm', '--cached', '-q', '--', ...files],
185
+ cmd: ['git', ...gitArgs, 'rm', '--cached', '-q', '--', ...files],
175
186
  cwd,
176
187
  stdout: 'pipe',
177
188
  stderr: 'pipe',
@@ -182,22 +193,40 @@ async function gitRmCached(bun: BunLike, cwd: string, files: string[]): Promise<
182
193
 
183
194
  type GitEnv = Record<string, string | undefined>
184
195
 
185
- async function run(bun: BunLike, cwd: string, args: string[], env?: GitEnv): Promise<boolean> {
186
- const proc = bun.spawn({ cmd: ['git', ...args], cwd, env, stdout: 'pipe', stderr: 'pipe' })
196
+ async function run(
197
+ bun: BunLike,
198
+ cwd: string,
199
+ gitArgs: readonly string[],
200
+ args: readonly string[],
201
+ env?: GitEnv,
202
+ ): Promise<boolean> {
203
+ const proc = bun.spawn({ cmd: ['git', ...gitArgs, ...args], cwd, env, stdout: 'pipe', stderr: 'pipe' })
187
204
  return (await proc.exited) === 0
188
205
  }
189
206
 
190
- async function capture(bun: BunLike, cwd: string, args: string[], env?: GitEnv): Promise<string> {
191
- const proc = bun.spawn({ cmd: ['git', ...args], cwd, env, stdout: 'pipe', stderr: 'pipe' })
207
+ async function capture(
208
+ bun: BunLike,
209
+ cwd: string,
210
+ gitArgs: readonly string[],
211
+ args: readonly string[],
212
+ env?: GitEnv,
213
+ ): Promise<string> {
214
+ const proc = bun.spawn({ cmd: ['git', ...gitArgs, ...args], cwd, env, stdout: 'pipe', stderr: 'pipe' })
192
215
  if ((await proc.exited) !== 0) return ''
193
216
  return await new Response(proc.stdout).text()
194
217
  }
195
218
 
196
219
  // --force-remove drops the index entry regardless of the file existing on disk;
197
220
  // the NUL-delimited stdin form is safe for paths with spaces/newlines.
198
- async function forceRemove(bun: BunLike, cwd: string, files: readonly string[], env: GitEnv): Promise<boolean> {
221
+ async function forceRemove(
222
+ bun: BunLike,
223
+ cwd: string,
224
+ gitArgs: readonly string[],
225
+ files: readonly string[],
226
+ env: GitEnv,
227
+ ): Promise<boolean> {
199
228
  const proc = bun.spawn({
200
- cmd: ['git', 'update-index', '-z', '--force-remove', '--stdin'],
229
+ cmd: ['git', ...gitArgs, 'update-index', '-z', '--force-remove', '--stdin'],
201
230
  cwd,
202
231
  env,
203
232
  stdin: new TextEncoder().encode(files.join('\0')),
@@ -0,0 +1,12 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ export type AgentGit = { kind: 'dotgit'; gitArgs: readonly [] } | { kind: 'gitstore'; gitArgs: readonly string[] }
5
+
6
+ export function resolveAgentGit(cwd: string): AgentGit | null {
7
+ if (existsSync(join(cwd, '.git'))) return { kind: 'dotgit', gitArgs: [] }
8
+ if (existsSync(join(cwd, '.gitstore'))) {
9
+ return { kind: 'gitstore', gitArgs: ['--git-dir', join(cwd, '.gitstore'), '--work-tree', cwd] }
10
+ }
11
+ return null
12
+ }
@@ -1,5 +1,4 @@
1
- import { existsSync } from 'node:fs'
2
- import { join } from 'node:path'
1
+ import { resolveAgentGit } from './resolve-agent-git'
3
2
 
4
3
  // Commits TypeClaw-owned tracked files (.gitignore, package.json,
5
4
  // typeclaw.json) if any are dirty in git. Skips silently when the agent
@@ -24,10 +23,11 @@ export async function commitSystemFile(cwd: string, file: string | readonly stri
24
23
 
25
24
  const bun = getBunAsync()
26
25
  if (!bun) return
27
- if (!existsSync(join(cwd, '.git'))) return
26
+ const repo = resolveAgentGit(cwd)
27
+ if (!repo) return
28
28
 
29
29
  const status = bun.spawn({
30
- cmd: ['git', 'status', '--porcelain', '--', ...files],
30
+ cmd: ['git', ...repo.gitArgs, 'status', '--porcelain', '--', ...files],
31
31
  cwd,
32
32
  stdout: 'pipe',
33
33
  stderr: 'pipe',
@@ -36,11 +36,11 @@ export async function commitSystemFile(cwd: string, file: string | readonly stri
36
36
  const dirty = (await new Response(status.stdout).text()).trim().length > 0
37
37
  if (!dirty) return
38
38
 
39
- const add = bun.spawn({ cmd: ['git', 'add', '--', ...files], cwd, stdout: 'pipe', stderr: 'pipe' })
39
+ const add = bun.spawn({ cmd: ['git', ...repo.gitArgs, 'add', '--', ...files], cwd, stdout: 'pipe', stderr: 'pipe' })
40
40
  if ((await add.exited) !== 0) return
41
41
 
42
42
  const commit = bun.spawn({
43
- cmd: ['git', 'commit', '-m', message, '--only', '--', ...files],
43
+ cmd: ['git', ...repo.gitArgs, 'commit', '-m', message, '--only', '--', ...files],
44
44
  cwd,
45
45
  stdout: 'pipe',
46
46
  stderr: 'pipe',
@@ -69,10 +69,11 @@ export function commitSystemFileSync(cwd: string, file: string | readonly string
69
69
 
70
70
  const bun = getBunSync()
71
71
  if (!bun) return
72
- if (!existsSync(join(cwd, '.git'))) return
72
+ const repo = resolveAgentGit(cwd)
73
+ if (!repo) return
73
74
 
74
75
  const status = bun.spawnSync({
75
- cmd: ['git', 'status', '--porcelain', '--', ...files],
76
+ cmd: ['git', ...repo.gitArgs, 'status', '--porcelain', '--', ...files],
76
77
  cwd,
77
78
  stdout: 'pipe',
78
79
  stderr: 'pipe',
@@ -80,11 +81,16 @@ export function commitSystemFileSync(cwd: string, file: string | readonly string
80
81
  if (status.exitCode !== 0) return
81
82
  if (new TextDecoder().decode(status.stdout).trim().length === 0) return
82
83
 
83
- const add = bun.spawnSync({ cmd: ['git', 'add', '--', ...files], cwd, stdout: 'pipe', stderr: 'pipe' })
84
+ const add = bun.spawnSync({
85
+ cmd: ['git', ...repo.gitArgs, 'add', '--', ...files],
86
+ cwd,
87
+ stdout: 'pipe',
88
+ stderr: 'pipe',
89
+ })
84
90
  if (add.exitCode !== 0) return
85
91
 
86
92
  bun.spawnSync({
87
- cmd: ['git', 'commit', '-m', message, '--only', '--', ...files],
93
+ cmd: ['git', ...repo.gitArgs, 'commit', '-m', message, '--only', '--', ...files],
88
94
  cwd,
89
95
  stdout: 'pipe',
90
96
  stderr: 'pipe',
@@ -27,6 +27,7 @@ import type {
27
27
  import { buildSupervisor, type SupervisorLogEvent, type SupervisorRestart } from './supervisor'
28
28
  import type { TailscaleServeEvent } from './tailscale'
29
29
  import { UNVERSIONED_SENTINEL } from './version'
30
+ import type { WebexRenewalCallbacks, WebexRenewalLogEvent } from './webex-renewal-manager'
30
31
 
31
32
  export type DaemonOptions = {
32
33
  exec?: DockerExec
@@ -60,6 +61,10 @@ export type DaemonOptions = {
60
61
  // deregister. Omit to disable in tests / when the agent has no kakaotalk
61
62
  // channel configured.
62
63
  kakaoRenewal?: KakaoRenewalCallbacks
64
+ // Webex credential renewal capability. Same lifecycle as kakaoRenewal but
65
+ // ticks hourly because Webex password tokens live ~27h (see
66
+ // webex-renewal-manager.ts). Omit when the agent has no webex channel.
67
+ webexRenewal?: WebexRenewalCallbacks
63
68
  }
64
69
 
65
70
  export type RestartPreflight = (input: {
@@ -102,6 +107,7 @@ export type DaemonLogEvent =
102
107
  | { kind: 'port-forward-event'; event: PortForwardEvent }
103
108
  | { kind: 'tailscale-serve-event'; event: TailscaleServeEvent }
104
109
  | KakaoRenewalLogEvent
110
+ | WebexRenewalLogEvent
105
111
 
106
112
  export type Daemon = {
107
113
  registered: () => string[]
@@ -341,6 +347,7 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
341
347
  gcMisses.delete(containerName)
342
348
  if (opts.portbroker) await opts.portbroker.stop(containerName, 'fatal-auth').catch(() => {})
343
349
  if (opts.kakaoRenewal) await opts.kakaoRenewal.stop(containerName).catch(() => {})
350
+ if (opts.webexRenewal) await opts.webexRenewal.stop(containerName).catch(() => {})
344
351
  await removeRegistrationFile(containerName)
345
352
  log({ kind: 'registration-skipped', containerName, reason: `fatal broker auth: ${reason}` })
346
353
  })
@@ -376,6 +383,9 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
376
383
  if (opts.kakaoRenewal) {
377
384
  opts.kakaoRenewal.start({ containerName: payload.containerName, cwd: payload.cwd })
378
385
  }
386
+ if (opts.webexRenewal) {
387
+ opts.webexRenewal.start({ containerName: payload.containerName, cwd: payload.cwd })
388
+ }
379
389
  }
380
390
 
381
391
  const handleRegister = async (req: RegisterPayload): Promise<RpcResponse> => {
@@ -403,6 +413,7 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
403
413
  gcMisses.delete(req.containerName)
404
414
  if (opts.portbroker) await opts.portbroker.stop(req.containerName, 'deregistered').catch(() => {})
405
415
  if (opts.kakaoRenewal) await opts.kakaoRenewal.stop(req.containerName).catch(() => {})
416
+ if (opts.webexRenewal) await opts.webexRenewal.stop(req.containerName).catch(() => {})
406
417
  await removeRegistrationFile(req.containerName)
407
418
  if (hadCwd) log({ kind: 'deregister', containerName: req.containerName, reason: 'requested' })
408
419
  return { ok: true }
@@ -684,6 +695,7 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
684
695
  restartTokens.delete(name)
685
696
  if (opts.portbroker) await opts.portbroker.stop(name, 'deregistered').catch(() => {})
686
697
  if (opts.kakaoRenewal) await opts.kakaoRenewal.stop(name).catch(() => {})
698
+ if (opts.webexRenewal) await opts.webexRenewal.stop(name).catch(() => {})
687
699
  await removeRegistrationFile(name)
688
700
  if (hadCwd) log({ kind: 'deregister', containerName: name, reason: 'gone' })
689
701
  return { ok: true }
@@ -713,6 +725,10 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
713
725
  const names = Array.from(cwds.keys())
714
726
  await Promise.allSettled(names.map((n) => opts.kakaoRenewal!.stop(n)))
715
727
  }
728
+ if (opts.webexRenewal) {
729
+ const names = Array.from(cwds.keys())
730
+ await Promise.allSettled(names.map((n) => opts.webexRenewal!.stop(n)))
731
+ }
716
732
  cwds.clear()
717
733
  restartTokens.clear()
718
734
  if (!onWindows) {
@@ -0,0 +1,216 @@
1
+ import { createKeyStore, type KeyStore } from '@/secrets/keys'
2
+ import { renewCurrentAccount, type LoginWithPasswordFn } from '@/secrets/webex-renewal'
3
+
4
+ import { keysDir } from './paths'
5
+
6
+ // Webex password-login tokens live ~27h and renewal triggers within 8h of
7
+ // expiry (see RENEWAL_WINDOW_MS). A 24h tick like KakaoTalk's would let a token
8
+ // cross into the 8h window and expire before the next tick, so Webex ticks
9
+ // hourly: short enough to always catch the window, cheap because a fresh token
10
+ // short-circuits to a no-op skip.
11
+ const DEFAULT_TICK_INTERVAL_MS = 60 * 60 * 1000
12
+
13
+ export type WebexRenewalCallbacks = {
14
+ start: (input: WebexRenewalStartInput) => void
15
+ stop: (containerName: string) => Promise<void>
16
+ drain: () => Promise<void>
17
+ }
18
+
19
+ export type WebexRenewalStartInput = {
20
+ containerName: string
21
+ cwd: string
22
+ }
23
+
24
+ export type WebexRenewalLogEvent =
25
+ | { kind: 'webex-renewal-tick-start'; containerName: string }
26
+ | { kind: 'webex-renewal-tick-skipped'; containerName: string; reason: string; expiresInMs?: number }
27
+ | { kind: 'webex-renewal-tick-ok'; containerName: string; accountId: string; nextExpiresAt: number }
28
+ | {
29
+ kind: 'webex-renewal-tick-reauth-required'
30
+ containerName: string
31
+ accountId: string
32
+ reason: string
33
+ message: string
34
+ }
35
+ | { kind: 'webex-renewal-tick-transient-failure'; containerName: string; accountId: string; reason: string }
36
+ | { kind: 'webex-renewal-tick-error'; containerName: string; error: string }
37
+ | { kind: 'webex-renewal-restart-scheduled'; containerName: string; accountId: string }
38
+ | { kind: 'webex-renewal-restart-failed'; containerName: string; accountId: string; reason: string }
39
+
40
+ export type WebexRenewalManagerOptions = {
41
+ onLog?: (event: WebexRenewalLogEvent) => void
42
+ tickIntervalMs?: number
43
+ keyStoreFactory?: () => KeyStore
44
+ loginWithPassword?: LoginWithPasswordFn
45
+ schedule?: (fn: () => void, intervalMs: number) => { stop: () => void }
46
+ // Invoked after a successful renewal so the host can restart the container
47
+ // and the in-memory adapter picks up the fresh token. Without this, the cron
48
+ // writes a new token to secrets.json but the live WebexClient keeps the old
49
+ // token in its `getToken` closure (src/channels/adapters/webex.ts) and still
50
+ // hits 401 on every outbound REST call and KMS key fetch.
51
+ onRenewalOk?: (input: { containerName: string; cwd: string; accountId: string }) => Promise<void>
52
+ // Only start the renewal cron for containers whose typeclaw.json actually has
53
+ // a channels.webex block, so non-webex agents don't emit hourly no_account
54
+ // skip logs.
55
+ shouldRenew?: (input: WebexRenewalStartInput) => boolean
56
+ }
57
+
58
+ export function createWebexRenewalManager(opts: WebexRenewalManagerOptions = {}): WebexRenewalCallbacks {
59
+ const intervalMs = opts.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS
60
+ const keyStore = (opts.keyStoreFactory ?? (() => createKeyStore({ keysDir: keysDir() })))()
61
+ const log = opts.onLog ?? (() => {})
62
+ const schedule =
63
+ opts.schedule ??
64
+ ((fn: () => void, ms: number) => {
65
+ const handle = setInterval(fn, ms)
66
+ return { stop: () => clearInterval(handle) }
67
+ })
68
+
69
+ const timers = new Map<string, { stop: () => void }>()
70
+ const latestInput = new Map<string, WebexRenewalStartInput>()
71
+ const inFlight = new Map<string, Promise<void>>()
72
+ const pendingRerun = new Set<string>()
73
+
74
+ const runTick = async (input: WebexRenewalStartInput): Promise<void> => {
75
+ log({ kind: 'webex-renewal-tick-start', containerName: input.containerName })
76
+ try {
77
+ const result = await renewCurrentAccount({
78
+ containerName: input.containerName,
79
+ agentDir: input.cwd,
80
+ keyStore,
81
+ ...(opts.loginWithPassword ? { loginWithPassword: opts.loginWithPassword } : {}),
82
+ })
83
+ if (result.kind === 'skipped') {
84
+ log({
85
+ kind: 'webex-renewal-tick-skipped',
86
+ containerName: input.containerName,
87
+ reason: result.reason,
88
+ ...(result.expiresInMs !== undefined ? { expiresInMs: result.expiresInMs } : {}),
89
+ })
90
+ } else if (result.kind === 'ok') {
91
+ log({
92
+ kind: 'webex-renewal-tick-ok',
93
+ containerName: input.containerName,
94
+ accountId: result.account_id,
95
+ nextExpiresAt: result.nextExpiresAt,
96
+ })
97
+ // A tick that started before stop()/drain() (deregister, shutdown) or
98
+ // before a re-register with a different cwd can finish the slow login
99
+ // here. Restarting a container that is no longer the current
100
+ // registration would resurrect a just-deregistered agent or fight a
101
+ // shutdown, so skip onRenewalOk unless this container+cwd is still the
102
+ // live registration.
103
+ const current = latestInput.get(input.containerName)
104
+ if (opts.onRenewalOk && current?.cwd === input.cwd) {
105
+ log({
106
+ kind: 'webex-renewal-restart-scheduled',
107
+ containerName: input.containerName,
108
+ accountId: result.account_id,
109
+ })
110
+ try {
111
+ await opts.onRenewalOk({
112
+ containerName: input.containerName,
113
+ cwd: input.cwd,
114
+ accountId: result.account_id,
115
+ })
116
+ } catch (err) {
117
+ log({
118
+ kind: 'webex-renewal-restart-failed',
119
+ containerName: input.containerName,
120
+ accountId: result.account_id,
121
+ reason: err instanceof Error ? err.message : String(err),
122
+ })
123
+ }
124
+ }
125
+ } else if (result.kind === 'reauth_required') {
126
+ log({
127
+ kind: 'webex-renewal-tick-reauth-required',
128
+ containerName: input.containerName,
129
+ accountId: result.account_id,
130
+ reason: result.reason,
131
+ message: result.message,
132
+ })
133
+ } else {
134
+ log({
135
+ kind: 'webex-renewal-tick-transient-failure',
136
+ containerName: input.containerName,
137
+ accountId: result.account_id,
138
+ reason: result.reason,
139
+ })
140
+ }
141
+ } catch (err) {
142
+ log({
143
+ kind: 'webex-renewal-tick-error',
144
+ containerName: input.containerName,
145
+ error: err instanceof Error ? err.message : String(err),
146
+ })
147
+ }
148
+ }
149
+
150
+ const scheduleTick = (containerName: string): Promise<void> => {
151
+ const existing = inFlight.get(containerName)
152
+ if (existing) {
153
+ pendingRerun.add(containerName)
154
+ return existing
155
+ }
156
+ const promise = (async () => {
157
+ while (true) {
158
+ const input = latestInput.get(containerName)
159
+ if (!input) return
160
+ await runTick(input)
161
+ if (!pendingRerun.has(containerName)) return
162
+ pendingRerun.delete(containerName)
163
+ }
164
+ })().finally(() => {
165
+ inFlight.delete(containerName)
166
+ pendingRerun.delete(containerName)
167
+ })
168
+ inFlight.set(containerName, promise)
169
+ return promise
170
+ }
171
+
172
+ return {
173
+ start(input: WebexRenewalStartInput): void {
174
+ // Tear down any prior registration for this container BEFORE the
175
+ // shouldRenew gate. The daemon calls start() on every registration, so a
176
+ // container that had Webex can re-register to a non-Webex cwd; if we
177
+ // returned early without clearing, the old timer would keep ticking and a
178
+ // post-login restart guard would still match the stale cwd. Clearing
179
+ // latestInput also makes an in-flight tick's onRenewalOk re-check fail.
180
+ const existing = timers.get(input.containerName)
181
+ if (existing) {
182
+ existing.stop()
183
+ timers.delete(input.containerName)
184
+ }
185
+ latestInput.delete(input.containerName)
186
+
187
+ if (opts.shouldRenew && !opts.shouldRenew(input)) return
188
+
189
+ latestInput.set(input.containerName, input)
190
+ const handle = schedule(() => {
191
+ void scheduleTick(input.containerName)
192
+ }, intervalMs)
193
+ timers.set(input.containerName, handle)
194
+ void scheduleTick(input.containerName)
195
+ },
196
+
197
+ async stop(containerName: string): Promise<void> {
198
+ const handle = timers.get(containerName)
199
+ if (handle) {
200
+ timers.delete(containerName)
201
+ handle.stop()
202
+ }
203
+ latestInput.delete(containerName)
204
+ const promise = inFlight.get(containerName)
205
+ if (promise) await promise.catch(() => {})
206
+ },
207
+
208
+ async drain(): Promise<void> {
209
+ for (const [, handle] of timers) handle.stop()
210
+ timers.clear()
211
+ latestInput.clear()
212
+ const promises = Array.from(inFlight.values())
213
+ await Promise.allSettled(promises)
214
+ },
215
+ }
216
+ }
@@ -30,21 +30,21 @@ export type AutoUpgradeOutcome =
30
30
  | { kind: 'exact-pin-respected'; declared: string; cliVersion: string }
31
31
  | { kind: 'spec-rewritten'; from: string; to: string; cliVersion: string }
32
32
  | { kind: 'reinstall-needed'; from: string; to: string }
33
+ | { kind: 'relinked-to-local'; from: string; to: string }
33
34
 
34
35
  export type AutoUpgradeOptions = {
35
36
  cwd: string
36
37
  // Test seam: lets tests simulate dev-mode (null) and arbitrary release
37
38
  // versions without depending on the test runner's actual CLI version.
38
39
  scaffoldVersion?: string | null
40
+ // Test seam: the local spec to relink to in dev-mode, so tests don't depend
41
+ // on the test runner's actual checkout path.
42
+ localSpec?: string
39
43
  }
40
44
 
41
45
  export async function autoUpgradeTypeclawDep(options: AutoUpgradeOptions): Promise<AutoUpgradeOutcome> {
42
46
  const { cwd } = options
43
47
  const scaffold = options.scaffoldVersion !== undefined ? options.scaffoldVersion : resolveScaffoldVersion()
44
- if (scaffold === null) return { kind: 'skipped-dev-mode' }
45
-
46
- const cliVersion = stripCaret(scaffold)
47
- if (cliVersion === null) return { kind: 'skipped-dev-mode' }
48
48
 
49
49
  const pkg = await readAgentPackageJson(cwd)
50
50
  if (pkg === null) return { kind: 'skipped-no-dep' }
@@ -52,8 +52,32 @@ export async function autoUpgradeTypeclawDep(options: AutoUpgradeOptions): Promi
52
52
  const declared = pkg.parsed.dependencies?.[TYPECLAW]
53
53
  if (typeof declared !== 'string') return { kind: 'skipped-no-dep' }
54
54
 
55
+ // The CLI runs from a source checkout (scaffold === null): the agent should
56
+ // track that checkout, not a published version. Relink any registry-range
57
+ // spec to the local spec (`file:`/`link:`); leave an exact pin (explicit user
58
+ // override) and an already-local spec alone.
59
+ if (scaffold === null) {
60
+ const localSpec = options.localSpec ?? null
61
+ if (localSpec === null || declared.startsWith('file:') || declared.startsWith('link:')) {
62
+ return { kind: 'skipped-dev-mode' }
63
+ }
64
+ if (classifyDepSpec(declared).kind === 'exact') return { kind: 'skipped-dev-mode' }
65
+ await writeDepSpec(cwd, pkg.raw, pkg.parsed, localSpec)
66
+ return { kind: 'relinked-to-local', from: declared, to: localSpec }
67
+ }
68
+
69
+ const cliVersion = stripCaret(scaffold)
70
+ if (cliVersion === null) return { kind: 'skipped-dev-mode' }
71
+
55
72
  const declaredKind = classifyDepSpec(declared)
56
73
  if (declaredKind.kind === 'non-release') {
74
+ // An installed CLI against a local (`file:`/`link:`) spec: the agent was on
75
+ // a dev checkout but is now run by an npm CLI — restore the registry range.
76
+ if (declared.startsWith('file:') || declared.startsWith('link:')) {
77
+ const newSpec = `^${cliVersion}`
78
+ await writeDepSpec(cwd, pkg.raw, pkg.parsed, newSpec)
79
+ return { kind: 'spec-rewritten', from: declared, to: newSpec, cliVersion }
80
+ }
57
81
  return { kind: 'skipped-non-release-spec', declared }
58
82
  }
59
83
 
@@ -113,6 +137,14 @@ export function outcomeForcesInstall(outcome: AutoUpgradeOutcome): boolean {
113
137
  return outcome.kind === 'spec-rewritten' || outcome.kind === 'reinstall-needed'
114
138
  }
115
139
 
140
+ // A relink to a local `file:`/`link:` spec installs via a forced `bun install`
141
+ // (file deps don't "update"), NOT the `bun update --latest` path above — and it
142
+ // skips version verification, since a local install's version is whatever the
143
+ // checkout declares. start.ts ORs this into its ensureDeps force flag.
144
+ export function outcomeRequiresForceInstall(outcome: AutoUpgradeOutcome): boolean {
145
+ return outcome.kind === 'relinked-to-local'
146
+ }
147
+
116
148
  // The version we expect to find in node_modules/typeclaw after the
117
149
  // auto-upgrade-triggered install completes. Callers use this to verify
118
150
  // the install actually moved the on-disk version (not just resolved the
@@ -130,6 +162,8 @@ export function describeAutoUpgrade(outcome: AutoUpgradeOutcome): string {
130
162
  return `Upgrading agent typeclaw ${outcome.from} → ${outcome.to} to match CLI`
131
163
  case 'reinstall-needed':
132
164
  return `Upgrading agent typeclaw ${outcome.from} → ${outcome.to} to match CLI`
165
+ case 'relinked-to-local':
166
+ return `Linking agent typeclaw to local checkout (${outcome.to})`
133
167
  case 'exact-pin-respected':
134
168
  return `Agent typeclaw is exact-pinned to ${outcome.declared}; CLI is ${outcome.cliVersion}. Not upgrading (remove the exact pin to allow auto-upgrade).`
135
169
  default: