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,5 +1,7 @@
1
1
  import { readFileSync } from 'node:fs'
2
- import { join } from 'node:path'
2
+ import { dirname, join, relative } from 'node:path'
3
+
4
+ import { isWindows } from '@/shared/platform'
3
5
 
4
6
  // Single source of truth for "what version of typeclaw is this agent on,
5
7
  // and where does that mean we should pin the base image / write the dep
@@ -34,6 +36,33 @@ export function resolveScaffoldVersion(): string | null {
34
36
  return `^${CLI_VERSION}`
35
37
  }
36
38
 
39
+ const TYPECLAW_PACKAGE = 'typeclaw'
40
+
41
+ // The local typeclaw source checkout this CLI runs from (the dir holding the
42
+ // CLI's own package.json), or null when the CLI is an installed package.
43
+ export function typeclawCheckoutRoot(): string | null {
44
+ return isInstalledCli() ? null : dirname(CLI_PACKAGE_JSON_PATH)
45
+ }
46
+
47
+ // The `dependencies.typeclaw` spec a fresh/reconciled agent should declare to
48
+ // track the running CLI: `^X.Y.Z` when the CLI is an installed package, else the
49
+ // local checkout — `link:typeclaw` on native Windows (a `bun link` registration
50
+ // bun symlinks instead of copying; `file:` would copy the whole checkout incl
51
+ // `.git/` and EPERM, the #899 path) and `file:<rel>` on POSIX.
52
+ export function resolveTypeclawSpec(agentRoot: string, platform: NodeJS.Platform = process.platform): string {
53
+ const scaffoldVersion = resolveScaffoldVersion()
54
+ if (scaffoldVersion !== null) return scaffoldVersion
55
+ if (isWindows(platform)) return `link:${TYPECLAW_PACKAGE}`
56
+ const checkout = typeclawCheckoutRoot()
57
+ return checkout ? `file:${toFileSpec(relative(agentRoot, checkout))}` : 'file:../typeclaw'
58
+ }
59
+
60
+ function toFileSpec(rel: string): string {
61
+ if (rel === '') return '.'
62
+ // bun/npm accept POSIX-style paths in file: specifiers; normalize separators.
63
+ return rel.split(/[\\/]/).join('/')
64
+ }
65
+
37
66
  // The version of typeclaw the AGENT will actually run inside the container.
38
67
  // Prefers `<agent>/node_modules/typeclaw/package.json#version` because that
39
68
  // is what the bind-mount exposes to the container at /agent/node_modules,
@@ -125,6 +125,18 @@ export const CLOUDFLARED_RELEASE_URL_BASE = 'https://github.com/cloudflare/cloud
125
125
 
126
126
  export const TYPECLAW_ENTRYPOINT_PATH = '/usr/local/bin/typeclaw-entrypoint'
127
127
 
128
+ // The installed TypeClaw CLI entry, executed directly by the container
129
+ // entrypoint. `package.json#bin.typeclaw` points at `src/cli/index.ts` and the
130
+ // package ships `src`, so this path exists for both the registry install and a
131
+ // `file:`/linked dev install (where node_modules/typeclaw is the repo). Running
132
+ // it directly bypasses `bun run typeclaw`'s script/`.bin` resolution — which
133
+ // breaks when the agent folder was installed on a Windows host: the hoisted
134
+ // linker writes Windows-native `.bin/typeclaw` shims that aren't valid Linux
135
+ // executables once the folder is bind-mounted into the container, so
136
+ // `bun run typeclaw` finds no usable bin, falls back to treating `typeclaw` as
137
+ // a path, and resolves `/agent/typeclaw.json` (`Cannot run json files`).
138
+ export const TYPECLAW_CLI_ENTRY = '/agent/node_modules/typeclaw/src/cli/index.ts'
139
+
128
140
  // IPv4 networks the container is forbidden to egress to when
129
141
  // `network.blockInternal` is true. Loopback (127/8) is NOT here — loopback
130
142
  // traffic uses the `lo` interface, which the shim's first ACCEPT rule
@@ -157,9 +169,10 @@ export const NETWORK_BLOCK_IPV6_NETS = ['fc00::/7', 'fe80::/10', 'ff00::/8', '::
157
169
  // modes, picked at boot time from `$TYPECLAW_NETWORK_BLOCK_INTERNAL`:
158
170
  //
159
171
  // off (env unset or != "1"): no rules installed, no setpriv. Just exec
160
- // `bun run typeclaw "$@"`. Identical observable behavior to a container
161
- // without this feature. This is the opt-out path for users who set
162
- // `network.blockInternal: false` in their `typeclaw.json`.
172
+ // the TypeClaw CLI entry directly (see TYPECLAW_CLI_ENTRY). Identical
173
+ // observable behavior to a container without this feature. This is the
174
+ // opt-out path for users who set `network.blockInternal: false` in their
175
+ // `typeclaw.json`.
163
176
  //
164
177
  // on (default, env = "1" via `network.blockInternal: true`): walks IPv4 +
165
178
  // IPv6 block lists and installs
@@ -515,7 +528,7 @@ if [ "\${TYPECLAW_NETWORK_BLOCK_INTERNAL:-0}" != "1" ]; then
515
528
  link_persistent_home_files
516
529
  link_configured_symlinks
517
530
  start_xvfb
518
- exec bun run typeclaw "$@"
531
+ exec bun run ${TYPECLAW_CLI_ENTRY} "$@"
519
532
  fi
520
533
 
521
534
  iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
@@ -562,7 +575,7 @@ ${ipv6Rules.join('\n')}
562
575
  link_persistent_home_files
563
576
  link_configured_symlinks
564
577
  start_xvfb
565
- exec setpriv --bounding-set -net_admin --inh-caps -net_admin --ambient-caps -net_admin -- bun run typeclaw "$@"
578
+ exec setpriv --bounding-set -net_admin --inh-caps -net_admin --ambient-caps -net_admin -- bun run ${TYPECLAW_CLI_ENTRY} "$@"
566
579
  `
567
580
  }
568
581
 
@@ -627,9 +640,18 @@ export const TRANSFORMERS_VERSION = '4.2.0'
627
640
  // resolves. A future transformers bump that moves sharp must bump
628
641
  // TRANSFORMERS_VERSION, `sharp@`, `@img/sharp-linux-*`, and
629
642
  // `@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.
643
+ // packages are a known failure mode.
644
+ //
645
+ // ARCH DETECTION — uname -m, not $TARGETARCH. Deriving the arch from the build
646
+ // arg as `${TARGETARCH:-amd64}` was a footgun: a bare `docker build` without
647
+ // BuildKit/buildx leaves TARGETARCH unset, so the default installed x64 packages
648
+ // even on arm64 hosts. The arm64 platform packages then exist in NEITHER
649
+ // /agent/node_modules/@img NOR /node_modules/@img, so sharp exhausts every
650
+ // candidate and aborts with a clean MODULE_NOT_FOUND ("Could not load the sharp
651
+ // module using the linux-arm64 runtime") the moment any code touches it (e.g.
652
+ // `typeclaw --help`). `uname -m` is the arch that actually runs this `bun add`
653
+ // (and the arch the native code must later load on), correct in every build path
654
+ // including emulated cross-builds. Unknown machines fail the build loudly.
633
655
  const LAYER_TRANSFORMERS_INSTALL = `# Layer 7: install @huggingface/transformers with its linux-native binaries.
634
656
  # Installs the linux onnxruntime-node addon AND sharp's linux platform packages
635
657
  # (@img/sharp-linux-*) into the image's /node_modules so they survive the
@@ -637,7 +659,7 @@ const LAYER_TRANSFORMERS_INSTALL = `# Layer 7: install @huggingface/transformers
637
659
  # /agent/node_modules/sharp. The transformers version is pinned EXACT (this
638
660
  # bun add has no lockfile) — see src/init/dockerfile.ts for the rationale.
639
661
  WORKDIR /
640
- RUN SHARP_ARCH="$(if [ "\${TARGETARCH:-amd64}" = "arm64" ]; then echo arm64; else echo x64; fi)" \\
662
+ 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
663
  && bun add \\
642
664
  @huggingface/transformers@${TRANSFORMERS_VERSION} \\
643
665
  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
package/src/init/index.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { existsSync, readdirSync, readFileSync } from 'node:fs'
1
+ import { existsSync, readdirSync } from 'node:fs'
2
2
  import { mkdir, readFile, writeFile } from 'node:fs/promises'
3
- import { basename, dirname, join, relative, resolve } from 'node:path'
4
- import { fileURLToPath } from 'node:url'
3
+ import { basename, join, resolve } from 'node:path'
5
4
 
6
5
  import {
7
6
  config,
@@ -31,9 +30,10 @@ import {
31
30
  import { commitSystemFile } from '@/git/system-commit'
32
31
  import { createSecretsStoreForAgent, type Channels, type Secret, SecretsBackend } from '@/secrets'
33
32
  import { hostLocaleIsCjk } from '@/shared/host-locale'
33
+ import { isWindows } from '@/shared/platform'
34
34
  import { createTui } from '@/tui'
35
35
 
36
- import { resolveBaseImageVersion, resolveScaffoldVersion } from './cli-version'
36
+ import { resolveBaseImageVersion, resolveTypeclawSpec, typeclawCheckoutRoot } from './cli-version'
37
37
  import { buildDockerfile, DOCKERFILE } from './dockerfile'
38
38
  import { CONFIG_FILE, findAgentDir, isInitialized } from './find-agent-dir'
39
39
  import { installGithubWebhooksEagerly, type EagerGithubWebhookInstallResult } from './github-webhook-install'
@@ -42,6 +42,7 @@ import { buildHatchingPrompt } from './hatching'
42
42
  import type { OAuthLoginRunner, OAuthLoginResult } from './oauth-login'
43
43
  import { GITKEEP_FILE, PACKAGES_DIR, PUBLIC_DIR } from './paths'
44
44
  import { type InstallResult, type InstallRunner, runBunInstall } from './run-bun-install'
45
+ import { linkWindowsDevTypeclaw, type RunBunLink } from './windows-dev-link'
45
46
 
46
47
  export { type InstallResult, type InstallRunner, runBunInstall } from './run-bun-install'
47
48
 
@@ -231,6 +232,11 @@ export type InitOptions = {
231
232
  runHatching?: HatchRunner
232
233
  runBunInstall?: InstallRunner
233
234
  dockerExec?: DockerExec
235
+ // Test seams for the native-Windows dev-mode `bun link` flow. `platform`
236
+ // defaults to `process.platform`; `runBunLink` defaults to spawning
237
+ // `bun link` in the typeclaw checkout.
238
+ platform?: NodeJS.Platform
239
+ runBunLink?: RunBunLink
234
240
  // Production CLI callers (src/cli/init.ts) pass `process.argv[1]` so the
235
241
  // hatching step's `start()` call spawns the host daemon and registers the
236
242
  // freshly-hatched container — same path `typeclaw start` takes. Tests omit
@@ -269,6 +275,8 @@ export async function runInit({
269
275
  runBunInstall: installRunner = runBunInstall,
270
276
  dockerExec,
271
277
  cliEntry,
278
+ platform = process.platform,
279
+ runBunLink,
272
280
  }: InitOptions): Promise<void> {
273
281
  const emit = onProgress ?? (() => {})
274
282
 
@@ -340,6 +348,7 @@ export async function runInit({
340
348
  withWebex: wantsWebex,
341
349
  withWebexUser,
342
350
  withKakaotalk,
351
+ platform,
343
352
  })
344
353
  // Only write the LLM API key on the api-key path. OAuth providers persist
345
354
  // their credentials to secrets.json (via the OAuth login step above); writing
@@ -407,6 +416,12 @@ export async function runInit({
407
416
  }
408
417
 
409
418
  emit({ step: 'install', phase: 'start' })
419
+ // Native-Windows dev-mode emits `link:typeclaw` (see resolveTypeclawSpec);
420
+ // register the checkout with `bun link` first so the subsequent install
421
+ // resolves it to a symlink bun SKIPS copying, instead of `file:` copying the
422
+ // checkout (incl `.git/`) and EPERMing — the #899 path. Registry deps still
423
+ // install normally. No-op on POSIX / registry installs.
424
+ await maybeLinkWindowsDevTypeclaw(platform, runBunLink)
410
425
  const install = await installRunner(cwd)
411
426
  emit({ step: 'install', phase: 'done', result: install })
412
427
  if (!install.ok) throw new Error(`Dependency install failed: ${install.reason}`)
@@ -481,7 +496,7 @@ export async function defaultRunHatching({
481
496
  // the preferred port, otherwise we'd connect to the wrong service.
482
497
  const hostPort = launch.hostPort
483
498
 
484
- await waitForAgentFn(`http://127.0.0.1:${hostPort}`, { timeoutMs: 30_000 })
499
+ await waitForAgentFn(`http://127.0.0.1:${hostPort}`, { timeoutMs: hatchingReadinessTimeoutMs() })
485
500
 
486
501
  if (configuredChannels !== undefined && configuredChannels.length > 0) {
487
502
  const url = buildTuiUrl(hostPort, launch.tuiToken)
@@ -527,6 +542,20 @@ function buildTuiUrl(hostPort: number, token: string | null): string {
527
542
  return url.toString()
528
543
  }
529
544
 
545
+ // Cold-boot readiness budget for the first `typeclaw init`. The image was just
546
+ // unpacked and the agent folder (incl. a large node_modules) is bind-mounted
547
+ // into the container, so the very first server boot is markedly slower than
548
+ // subsequent `typeclaw start`s — plugin loading reads hundreds of files off a
549
+ // cold mount before Bun.serve() binds the port. On Windows Docker Desktop that
550
+ // mount crosses into the WSL2 VM and is slower still; during the warmup window
551
+ // Docker Desktop's port proxy may accept then immediately reset connections
552
+ // ("socket connection was closed unexpectedly"), which is why a too-short budget
553
+ // fails the first run even though an immediate retry (warm caches) succeeds.
554
+ // Give Windows a generous budget; keep other platforms tighter.
555
+ export function hatchingReadinessTimeoutMs(platform: NodeJS.Platform = process.platform): number {
556
+ return isWindows(platform) ? 120_000 : 60_000
557
+ }
558
+
530
559
  // Probe the server's plain HTTP fallback (non-upgrade requests get a 200 with
531
560
  // body "typeclaw agent") instead of opening a WebSocket. Opening a WS here
532
561
  // would trigger createSession on the server and burn an LLM session just to
@@ -582,6 +611,9 @@ export type ScaffoldOptions = {
582
611
  withWebex?: boolean
583
612
  withWebexUser?: boolean
584
613
  withKakaotalk?: boolean
614
+ // Defaults to `process.platform`; controls the dev-mode typeclaw spec
615
+ // (`link:` on Windows, `file:` on POSIX). Tests inject it.
616
+ platform?: NodeJS.Platform
585
617
  }
586
618
 
587
619
  export async function scaffold(root: string, options: ScaffoldOptions = {}): Promise<void> {
@@ -630,7 +662,7 @@ export async function scaffold(root: string, options: ScaffoldOptions = {}): Pro
630
662
  }
631
663
  await writeFile(join(root, CRON_FILE), `${JSON.stringify(cron, null, 2)}\n`, { flag: 'wx' }).catch(ignoreExists)
632
664
 
633
- const pkg = buildPackageJson(root, basename(root))
665
+ const pkg = buildPackageJson(root, basename(root), options.platform ?? process.platform)
634
666
  await writeFile(join(root, PACKAGE_FILE), `${JSON.stringify(pkg, null, 2)}\n`, { flag: 'wx' }).catch(ignoreExists)
635
667
 
636
668
  await Promise.all(MARKDOWN_FILES.map((file) => writeFile(join(root, file), '', { flag: 'wx' }).catch(ignoreExists)))
@@ -664,14 +696,14 @@ function addCustomModel(
664
696
  // two installs of the same CLI and a skew is silent. Enforced by a guard test
665
697
  // in packagejson.test.ts.
666
698
  export const AGENT_BROWSER_VERSION = '^0.27.0'
667
- function buildPackageJson(root: string, name: string): Record<string, unknown> {
699
+ function buildPackageJson(root: string, name: string, platform: NodeJS.Platform): Record<string, unknown> {
668
700
  return {
669
701
  name,
670
702
  private: true,
671
703
  type: 'module',
672
704
  workspaces: [`${PACKAGES_DIR}/*`],
673
705
  dependencies: {
674
- typeclaw: resolveTypeclawSpec(root),
706
+ typeclaw: resolveTypeclawSpec(root, platform),
675
707
  'agent-browser': AGENT_BROWSER_VERSION,
676
708
  [GWS_MULTI_ACCOUNT_PLUGIN_PACKAGE]: GWS_MULTI_ACCOUNT_PLUGIN_VERSION,
677
709
  },
@@ -683,37 +715,13 @@ function buildPackageJson(root: string, name: string): Record<string, unknown> {
683
715
  }
684
716
  }
685
717
 
686
- // Prefer the registry-style range (`^X.Y.Z`) when typeclaw is itself an
687
- // installed package — that's what lets `bun install` in the agent resolve
688
- // typeclaw from npm. Fall back to `file:` against the local checkout for
689
- // dev contributors running `bun run src/cli/index.ts init` from the repo.
690
- function resolveTypeclawSpec(agentRoot: string): string {
691
- const scaffoldVersion = resolveScaffoldVersion()
692
- if (scaffoldVersion !== null) return scaffoldVersion
693
- const typeclawRoot = findTypeclawRoot()
694
- return typeclawRoot ? `file:${toFileSpec(relative(agentRoot, typeclawRoot))}` : 'file:../typeclaw'
695
- }
696
-
697
- function toFileSpec(rel: string): string {
698
- if (rel === '') return '.'
699
- // bun/npm accept POSIX-style paths in file: specifiers; normalize separators.
700
- return rel.split(/[\\/]/).join('/')
701
- }
702
-
703
- function findTypeclawRoot(): string | null {
704
- try {
705
- let dir = dirname(fileURLToPath(import.meta.url))
706
- const root = resolve('/')
707
- while (dir !== root) {
708
- const pkgPath = join(dir, 'package.json')
709
- if (existsSync(pkgPath)) {
710
- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { name?: string }
711
- if (pkg.name === 'typeclaw') return dir
712
- }
713
- dir = dirname(dir)
714
- }
715
- } catch {}
716
- return null
718
+ async function maybeLinkWindowsDevTypeclaw(
719
+ platform: NodeJS.Platform,
720
+ runBunLink: RunBunLink | undefined,
721
+ ): Promise<void> {
722
+ const typeclawRoot = typeclawCheckoutRoot()
723
+ if (typeclawRoot === null) return
724
+ await linkWindowsDevTypeclaw(typeclawRoot, { platform, ...(runBunLink !== undefined ? { runBunLink } : {}) })
717
725
  }
718
726
 
719
727
  export async function writeDockerAssets(root: string): Promise<DockerAssetsResult> {
@@ -0,0 +1,64 @@
1
+ import { realpathSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { join } from 'node:path'
4
+
5
+ import { isWindows } from '@/shared/platform'
6
+
7
+ const NODE_MODULES = 'node_modules'
8
+ const TYPECLAW_DEP = 'typeclaw'
9
+
10
+ export type RunBunLink = (cwd: string) => Promise<void>
11
+
12
+ export type LinkWindowsDevTypeclawOptions = {
13
+ platform?: NodeJS.Platform
14
+ runBunLink?: RunBunLink
15
+ env?: NodeJS.ProcessEnv
16
+ }
17
+
18
+ // Mirrors Bun's `openGlobalDir` env-var precedence (BUN_INSTALL_GLOBAL_DIR >
19
+ // BUN_INSTALL/install/global > XDG_CACHE_HOME/bun/install/global >
20
+ // homedir/.bun/install/global) so we resolve the same global-link location Bun
21
+ // writes to. The node_modules/<name> entry is a junction (Windows) or symlink
22
+ // (POSIX) whose target is the checkout absolute path; realpathSync resolves both.
23
+ export function resolveBunLinkedPackage(packageName: string, env: NodeJS.ProcessEnv = process.env): string | null {
24
+ const globalDir =
25
+ env.BUN_INSTALL_GLOBAL_DIR ??
26
+ (env.BUN_INSTALL ? join(env.BUN_INSTALL, 'install', 'global') : null) ??
27
+ (env.XDG_CACHE_HOME ? join(env.XDG_CACHE_HOME, 'bun', 'install', 'global') : null) ??
28
+ join(homedir(), '.bun', 'install', 'global')
29
+ try {
30
+ return realpathSync(join(globalDir, NODE_MODULES, packageName))
31
+ } catch {
32
+ return null
33
+ }
34
+ }
35
+
36
+ // Native-Windows dev-mode only: register the typeclaw checkout via `bun link` so
37
+ // the agent can depend on it as `link:typeclaw`. `link:` resolves to a
38
+ // symlink/junction that bun's installer SKIPS entirely (no `.folder` verify,
39
+ // no uninstall-before-install, no source-tree copy) — unlike `file:`, which
40
+ // copies the whole checkout incl `.git/` and EPERMs on locked git files (the
41
+ // #899 path). Returns the linked target path (for the container bind-mount) or
42
+ // null when not Windows. POSIX keeps `file:` (registry users use a version spec
43
+ // and never reach here).
44
+ export async function linkWindowsDevTypeclaw(
45
+ typeclawRoot: string,
46
+ options: LinkWindowsDevTypeclawOptions = {},
47
+ ): Promise<string | null> {
48
+ const platform = options.platform ?? process.platform
49
+ if (!isWindows(platform)) return null
50
+ const runLink = options.runBunLink ?? defaultRunBunLink
51
+ await runLink(typeclawRoot)
52
+ return resolveBunLinkedPackage(TYPECLAW_DEP, options.env ?? process.env) ?? typeclawRoot
53
+ }
54
+
55
+ async function defaultRunBunLink(cwd: string): Promise<void> {
56
+ const bun = (globalThis as { Bun?: { spawn: typeof Bun.spawn } }).Bun
57
+ if (!bun) throw new Error('bun runtime not available to run `bun link`')
58
+ const proc = bun.spawn({ cmd: ['bun', 'link'], cwd, stdout: 'pipe', stderr: 'pipe' })
59
+ const code = await proc.exited
60
+ if (code !== 0) {
61
+ const stderr = await new Response(proc.stderr).text()
62
+ throw new Error(`bun link failed in ${cwd}: ${stderr.trim() || `exited with code ${code}`}`)
63
+ }
64
+ }
@@ -193,6 +193,7 @@ export type PendingLoginRecord = z.infer<typeof kakaoPendingLoginRecordSchema>
193
193
  export type KakaoChannelBlock = z.infer<typeof kakaoChannelBlockSchema>
194
194
  export type WebexAccountRecord = z.infer<typeof webexAccountRecordSchema>
195
195
  export type WebexChannelBlock = z.infer<typeof webexChannelBlockSchema>
196
+ export type WebexEncryptedPassword = z.infer<typeof webexEncryptedPasswordSchema>
196
197
  export type SecretsFile = z.infer<typeof secretsFileSchema>
197
198
 
198
199
  export type ParseSecretsResult = { ok: true; file: SecretsFile } | { ok: false; reason: string }
@@ -0,0 +1,215 @@
1
+ import { join } from 'node:path'
2
+
3
+ import { loginWithPassword as upstreamLoginWithPassword } from 'agent-messenger/webex'
4
+
5
+ import { decrypt, EncryptionError } from './encryption'
6
+ import { type KeyStore, KeyStoreError } from './keys'
7
+ import { type WebexChannelBlock } from './schema'
8
+ import { SecretsBackend } from './storage'
9
+ import { SecretsWebexCredentialStore } from './webex-store'
10
+
11
+ // Webex password-login access tokens live ~27h. The daily renewal tick fires
12
+ // every 24h, so a token must be refreshed while it still has more than one
13
+ // tick-interval of life left — otherwise it expires in the gap between two
14
+ // ticks and every REST call (send, history, KMS key fetch) 401s while the
15
+ // Mercury listener stays connected on its already-authenticated socket. We
16
+ // renew when the token is within 8h of `expires_at`: that clears a full 24h
17
+ // tick plus headroom for host sleep / daemon respawn, and a fresh token
18
+ // minted on each tick keeps the window comfortably ahead of expiry.
19
+ export const RENEWAL_WINDOW_MS = 8 * 60 * 60 * 1000
20
+
21
+ export type WebexRenewalDecision =
22
+ | { kind: 'skip'; reason: 'no_account' | 'fresh_enough'; expiresInMs?: number }
23
+ | {
24
+ kind: 'reauth_required'
25
+ reason: 'no_password' | 'no_email' | 'key_missing' | 'decrypt_failed'
26
+ message: string
27
+ }
28
+ | { kind: 'should_renew'; account: WebexAccountSnapshot; password: string }
29
+
30
+ export type WebexAccountSnapshot = {
31
+ account_id: string
32
+ email: string
33
+ created_at: string
34
+ updated_at: string
35
+ }
36
+
37
+ export type WebexRenewalAttempt =
38
+ | { kind: 'ok'; account_id: string; previousExpiresAt: number; nextExpiresAt: number }
39
+ | { kind: 'reauth_required'; account_id: string; reason: string; message: string }
40
+ | { kind: 'transient_failure'; account_id: string; reason: string }
41
+
42
+ export type LoginWithPasswordFn = typeof upstreamLoginWithPassword
43
+
44
+ export type WebexRenewalContext = {
45
+ containerName: string
46
+ agentDir: string
47
+ keyStore: KeyStore
48
+ now?: () => number
49
+ loginWithPassword?: LoginWithPasswordFn
50
+ idbrokerHost?: string
51
+ }
52
+
53
+ export async function decideRenewal(block: WebexChannelBlock, ctx: WebexRenewalContext): Promise<WebexRenewalDecision> {
54
+ const accountId = block.currentAccount
55
+ if (!accountId) return { kind: 'skip', reason: 'no_account' }
56
+ const account = block.accounts[accountId]
57
+ if (!account) return { kind: 'skip', reason: 'no_account' }
58
+
59
+ const now = (ctx.now ?? Date.now)()
60
+ const expiresInMs = account.expires_at - now
61
+ if (Number.isFinite(expiresInMs) && expiresInMs > RENEWAL_WINDOW_MS) {
62
+ return { kind: 'skip', reason: 'fresh_enough', expiresInMs }
63
+ }
64
+
65
+ if (!account.email) {
66
+ return {
67
+ kind: 'reauth_required',
68
+ reason: 'no_email',
69
+ message: `Webex account ${accountId} has no stored email — run \`typeclaw channel reauth webex\`.`,
70
+ }
71
+ }
72
+ if (!account.encryptedPassword) {
73
+ return {
74
+ kind: 'reauth_required',
75
+ reason: 'no_password',
76
+ message: `Webex account ${accountId} has no stored password — run \`typeclaw channel reauth webex\`.`,
77
+ }
78
+ }
79
+
80
+ let plaintextPassword: string
81
+ try {
82
+ const key = await ctx.keyStore.read(ctx.containerName)
83
+ plaintextPassword = decrypt(account.encryptedPassword, key, {
84
+ containerName: ctx.containerName,
85
+ accountId: account.account_id,
86
+ })
87
+ } catch (err) {
88
+ return classifyDecryptFailure(err, accountId)
89
+ }
90
+
91
+ return {
92
+ kind: 'should_renew',
93
+ account: {
94
+ account_id: account.account_id,
95
+ email: account.email,
96
+ created_at: account.created_at,
97
+ updated_at: account.updated_at,
98
+ },
99
+ password: plaintextPassword,
100
+ }
101
+ }
102
+
103
+ export async function renewCurrentAccount(
104
+ ctx: WebexRenewalContext,
105
+ ): Promise<WebexRenewalAttempt | { kind: 'skipped'; reason: string; expiresInMs?: number }> {
106
+ const secretsPath = join(ctx.agentDir, 'secrets.json')
107
+ const backend = new SecretsBackend(secretsPath)
108
+ const block = backend.readChannelsSync()?.webex
109
+ const parsed = parseBlockOrEmpty(block)
110
+ const decision = await decideRenewal(parsed, ctx)
111
+
112
+ if (decision.kind === 'skip') {
113
+ return {
114
+ kind: 'skipped',
115
+ reason: decision.reason,
116
+ ...(decision.expiresInMs !== undefined ? { expiresInMs: decision.expiresInMs } : {}),
117
+ }
118
+ }
119
+ if (decision.kind === 'reauth_required') {
120
+ return {
121
+ kind: 'reauth_required',
122
+ account_id: parsed.currentAccount ?? '',
123
+ reason: decision.reason,
124
+ message: decision.message,
125
+ }
126
+ }
127
+
128
+ const loginWithPassword = ctx.loginWithPassword ?? upstreamLoginWithPassword
129
+ const loginOptions = ctx.idbrokerHost !== undefined ? { idbrokerHost: ctx.idbrokerHost } : undefined
130
+
131
+ let result: Awaited<ReturnType<LoginWithPasswordFn>>
132
+ try {
133
+ result = await loginWithPassword(decision.account.email, decision.password, loginOptions)
134
+ } catch (err) {
135
+ return classifyLoginFailure(err, decision.account.account_id)
136
+ }
137
+
138
+ // The renewed login resolves to the same Webex user, so reuse the stored
139
+ // account_id rather than `result.userId`: the store keys accounts by id and a
140
+ // drifted id would orphan the record (and its encryptedPassword) instead of
141
+ // updating it. `setAccount` merges and preserves email/encryptedPassword.
142
+ const store = new SecretsWebexCredentialStore({ mode: 'host', secretsPath })
143
+ const nowIso = new Date().toISOString()
144
+ const previousExpiresAt = parsed.accounts[decision.account.account_id]?.expires_at ?? 0
145
+ await store.setAccount({
146
+ account_id: decision.account.account_id,
147
+ access_token: result.accessToken,
148
+ refresh_token: result.refreshToken,
149
+ expires_at: result.expiresAt,
150
+ device_url: result.deviceUrl,
151
+ user_id: result.userId,
152
+ created_at: decision.account.created_at,
153
+ updated_at: nowIso,
154
+ email: decision.account.email,
155
+ })
156
+
157
+ return {
158
+ kind: 'ok',
159
+ account_id: decision.account.account_id,
160
+ previousExpiresAt,
161
+ nextExpiresAt: result.expiresAt,
162
+ }
163
+ }
164
+
165
+ function parseBlockOrEmpty(value: unknown): WebexChannelBlock {
166
+ if (value === undefined) return { currentAccount: null, accounts: {} }
167
+ return value as WebexChannelBlock
168
+ }
169
+
170
+ function classifyLoginFailure(err: unknown, accountId: string): WebexRenewalAttempt {
171
+ const message = err instanceof Error ? err.message : String(err)
172
+ // agent-messenger's loginWithPassword throws WebexError with a `code` for
173
+ // unrecoverable auth states (SSO/IdP or MFA accounts that headless password
174
+ // login can't satisfy). Those need human reauth; everything else (network,
175
+ // 5xx, transient idbroker hiccup) is retried on the next tick.
176
+ const code = (err as { code?: unknown })?.code
177
+ if (code === 'sso_required' || code === 'mfa_required') {
178
+ return {
179
+ kind: 'reauth_required',
180
+ account_id: accountId,
181
+ reason: String(code),
182
+ message: `${message} — run \`typeclaw channel reauth webex\`.`,
183
+ }
184
+ }
185
+ return { kind: 'transient_failure', account_id: accountId, reason: message }
186
+ }
187
+
188
+ function classifyDecryptFailure(err: unknown, accountId: string): WebexRenewalDecision {
189
+ if (err instanceof KeyStoreError) {
190
+ if (err.code === 'missing') {
191
+ return {
192
+ kind: 'reauth_required',
193
+ reason: 'key_missing',
194
+ message: `Encryption key missing for Webex account ${accountId} — run \`typeclaw channel reauth webex\` to mint a fresh one.`,
195
+ }
196
+ }
197
+ return {
198
+ kind: 'reauth_required',
199
+ reason: 'key_missing',
200
+ message: `Encryption key for Webex account ${accountId} is unusable (${err.code}: ${err.message}). Move it aside and run \`typeclaw channel reauth webex\` to mint a fresh one.`,
201
+ }
202
+ }
203
+ if (err instanceof EncryptionError) {
204
+ return {
205
+ kind: 'reauth_required',
206
+ reason: 'decrypt_failed',
207
+ message: `Could not decrypt stored Webex password (${err.code}) — run \`typeclaw channel reauth webex\`.`,
208
+ }
209
+ }
210
+ return {
211
+ kind: 'reauth_required',
212
+ reason: 'decrypt_failed',
213
+ message: `Could not decrypt stored Webex password (${err instanceof Error ? err.message : String(err)}).`,
214
+ }
215
+ }