typeclaw 0.38.1 → 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 (56) hide show
  1. package/README.md +5 -0
  2. package/package.json +2 -2
  3. package/src/agent/attention-escalation.ts +158 -7
  4. package/src/agent/auth.ts +2 -2
  5. package/src/agent/git-nudge.ts +7 -7
  6. package/src/agent/index.ts +25 -2
  7. package/src/agent/restart/index.ts +17 -8
  8. package/src/agent/session-origin.ts +21 -0
  9. package/src/agent/subagents.ts +29 -1
  10. package/src/agent/system-prompt.ts +18 -5
  11. package/src/agent/tools/restart.ts +0 -3
  12. package/src/agent/tools/spawn-subagent.ts +7 -0
  13. package/src/bundled-plugins/backup/index.ts +5 -2
  14. package/src/bundled-plugins/backup/runner.ts +55 -23
  15. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +7 -8
  16. package/src/bundled-plugins/memory/dreaming.ts +37 -24
  17. package/src/bundled-plugins/memory/index.ts +24 -6
  18. package/src/bundled-plugins/memory/memory-logger.ts +14 -10
  19. package/src/bundled-plugins/operator/operator.ts +1 -0
  20. package/src/channels/adapters/kakaotalk-membership.ts +67 -0
  21. package/src/channels/adapters/kakaotalk.ts +8 -0
  22. package/src/channels/adapters/line-token.ts +55 -0
  23. package/src/channels/adapters/line.ts +74 -0
  24. package/src/channels/adapters/webex-bot-classify.ts +14 -1
  25. package/src/channels/adapters/webex-bot.ts +24 -1
  26. package/src/channels/adapters/webex-classify.ts +16 -1
  27. package/src/channels/adapters/webex.ts +27 -1
  28. package/src/channels/router.ts +55 -2
  29. package/src/cli/hostd.ts +40 -0
  30. package/src/cli/model.ts +143 -3
  31. package/src/config/config.ts +101 -36
  32. package/src/config/index.ts +3 -0
  33. package/src/config/models-mutation.ts +105 -15
  34. package/src/config/providers-mutation.ts +4 -4
  35. package/src/config/providers.ts +6 -14
  36. package/src/container/shared.ts +136 -14
  37. package/src/container/shell.ts +12 -2
  38. package/src/container/start.ts +25 -7
  39. package/src/doctor/commit.ts +10 -10
  40. package/src/dreams/git.ts +20 -7
  41. package/src/dreams/index.ts +22 -7
  42. package/src/git/reconcile-ignored.ts +56 -27
  43. package/src/git/resolve-agent-git.ts +12 -0
  44. package/src/git/system-commit.ts +16 -10
  45. package/src/hostd/daemon.ts +16 -0
  46. package/src/hostd/index.ts +1 -11
  47. package/src/hostd/paths.ts +0 -16
  48. package/src/hostd/webex-renewal-manager.ts +216 -0
  49. package/src/init/dockerfile.ts +13 -4
  50. package/src/init/gitignore.ts +4 -2
  51. package/src/run/index.ts +4 -1
  52. package/src/secrets/schema.ts +1 -0
  53. package/src/secrets/webex-renewal.ts +215 -0
  54. package/src/server/index.ts +25 -3
  55. package/src/skills/typeclaw-config/SKILL.md +18 -16
  56. package/typeclaw.schema.json +172 -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) {
@@ -1,16 +1,6 @@
1
1
  export { isDaemonReachable, send } from './client'
2
2
  export { startDaemon, type Daemon, type DaemonLogEvent, type DaemonOptions } from './daemon'
3
- export {
4
- containerSocketPath,
5
- ensureDirs,
6
- homeRoot,
7
- lockfilePath,
8
- logDir,
9
- logfilePath,
10
- pidfilePath,
11
- runDir,
12
- socketPath,
13
- } from './paths'
3
+ export { ensureDirs, homeRoot, lockfilePath, logDir, logfilePath, pidfilePath, runDir, socketPath } from './paths'
14
4
  export type {
15
5
  ListResult,
16
6
  Request,
@@ -5,11 +5,6 @@ import { join, resolve } from 'node:path'
5
5
 
6
6
  import { isWindows } from '@/shared'
7
7
 
8
- // Fixed in-container path where the host daemon's run dir is bind-mounted.
9
- // The agent uses this to reach the host daemon (e.g. for the `restart` tool).
10
- // Kept stable so the agent never has to discover the host's `~/.typeclaw`
11
- // location at runtime.
12
- const CONTAINER_HOST_RUN_DIR = '/run/typeclaw-host'
13
8
  const SOCKET_FILE = 'hostd.sock'
14
9
  const REGISTRATIONS_DIR = 'registrations'
15
10
  const KEYS_DIR = 'keys'
@@ -90,17 +85,6 @@ export function registrationFilePath(containerName: string): string {
90
85
  return join(registrationsDir(), `${containerName}.json`)
91
86
  }
92
87
 
93
- // In-container path to the same socket the host daemon listens on. The
94
- // container-stage agent tool dials this path; the host bind-mounts the host
95
- // run dir at CONTAINER_HOST_RUN_DIR so the socket is reachable.
96
- export function containerSocketPath(): string {
97
- return join(CONTAINER_HOST_RUN_DIR, SOCKET_FILE)
98
- }
99
-
100
- export function containerHostRunDir(): string {
101
- return CONTAINER_HOST_RUN_DIR
102
- }
103
-
104
88
  export async function ensureDirs(): Promise<void> {
105
89
  await mkdir(runDir(), { recursive: true })
106
90
  await mkdir(logDir(), { recursive: true })
@@ -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
+ }
@@ -627,9 +627,18 @@ export const TRANSFORMERS_VERSION = '4.2.0'
627
627
  // resolves. A future transformers bump that moves sharp must bump
628
628
  // TRANSFORMERS_VERSION, `sharp@`, `@img/sharp-linux-*`, and
629
629
  // `@img/sharp-libvips-linux-*` together — mismatched sharp/libvips platform
630
- // packages are a known failure mode. `$TARGETARCH` is `arm64` or `amd64`; an
631
- // empty value (bare `docker build` without buildx) falls back to x64 for
632
- // determinism.
630
+ // packages are a known failure mode.
631
+ //
632
+ // ARCH DETECTION — uname -m, not $TARGETARCH. Deriving the arch from the build
633
+ // arg as `${TARGETARCH:-amd64}` was a footgun: a bare `docker build` without
634
+ // BuildKit/buildx leaves TARGETARCH unset, so the default installed x64 packages
635
+ // even on arm64 hosts. The arm64 platform packages then exist in NEITHER
636
+ // /agent/node_modules/@img NOR /node_modules/@img, so sharp exhausts every
637
+ // candidate and aborts with a clean MODULE_NOT_FOUND ("Could not load the sharp
638
+ // module using the linux-arm64 runtime") the moment any code touches it (e.g.
639
+ // `typeclaw --help`). `uname -m` is the arch that actually runs this `bun add`
640
+ // (and the arch the native code must later load on), correct in every build path
641
+ // including emulated cross-builds. Unknown machines fail the build loudly.
633
642
  const LAYER_TRANSFORMERS_INSTALL = `# Layer 7: install @huggingface/transformers with its linux-native binaries.
634
643
  # Installs the linux onnxruntime-node addon AND sharp's linux platform packages
635
644
  # (@img/sharp-linux-*) into the image's /node_modules so they survive the
@@ -637,7 +646,7 @@ const LAYER_TRANSFORMERS_INSTALL = `# Layer 7: install @huggingface/transformers
637
646
  # /agent/node_modules/sharp. The transformers version is pinned EXACT (this
638
647
  # bun add has no lockfile) — see src/init/dockerfile.ts for the rationale.
639
648
  WORKDIR /
640
- RUN SHARP_ARCH="$(if [ "\${TARGETARCH:-amd64}" = "arm64" ]; then echo arm64; else echo x64; fi)" \\
649
+ RUN SHARP_ARCH="$(case "$(uname -m)" in aarch64|arm64) echo arm64 ;; x86_64|amd64) echo x64 ;; *) echo "unsupported arch: $(uname -m)" >&2; exit 1 ;; esac)" \\
641
650
  && bun add \\
642
651
  @huggingface/transformers@${TRANSFORMERS_VERSION} \\
643
652
  sharp@0.34.5 \\
@@ -5,6 +5,7 @@ export const GITIGNORE_FILE = '.gitignore'
5
5
  // Match scope for the untrack reconciler (src/git/reconcile-ignored.ts): when a
6
6
  // tracked file later matches one of these, start() removes it from the index.
7
7
  export const TRULY_IGNORED_PATTERNS = [
8
+ '.gitstore/',
8
9
  '.env',
9
10
  '.env.local',
10
11
  'secrets.json',
@@ -28,8 +29,9 @@ export const SYSTEM_MANAGED_ROOTS = ['sessions/', 'memory/', 'channels/', 'todo/
28
29
  export function buildGitignore(config: GitignoreConfig = { append: [] }): string {
29
30
  const customEntries = renderCustomGitignoreEntries(config.append)
30
31
 
31
- return `${customEntries}# Truly ignored: secrets, runtime junk, the agent's free-write zone, and
32
- # regenerated-on-every-start system files. Never enter git history.
32
+ return `${customEntries}# Truly ignored: secrets, runtime junk, the agent's free-write zone, the
33
+ # relocated monorepo-member git DB, and regenerated-on-every-start system files.
34
+ # Never enter git history.
33
35
  #
34
36
  # Dockerfile is rewritten from the typeclaw CLI template on every \`typeclaw
35
37
  # start\` (see src/init/dockerfile.ts), so tracking it would only produce