typeclaw 0.46.1 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +2 -1
  2. package/package.json +2 -2
  3. package/src/agent/tool-file-safety.ts +18 -9
  4. package/src/agent/tools/webfetch/strategies/jq.ts +1 -2
  5. package/src/agent/tools/webfetch/strategies/readability.ts +39 -16
  6. package/src/agent/tools/webfetch/strategies/selector.ts +4 -2
  7. package/src/agent/tools/webfetch/strategies/snapshot.ts +3 -2
  8. package/src/agent/tools/webfetch/tool.ts +3 -3
  9. package/src/bundled-plugins/backup/index.ts +21 -4
  10. package/src/bundled-plugins/backup/runner.ts +19 -5
  11. package/src/bundled-plugins/memory/dreaming.ts +2 -1
  12. package/src/bundled-plugins/memory/load-shards.ts +31 -3
  13. package/src/bundled-plugins/memory/memory-logger.ts +2 -1
  14. package/src/bundled-plugins/memory/memory-snapshot.ts +8 -0
  15. package/src/bundled-plugins/memory/vector/embedder.ts +28 -9
  16. package/src/bundled-plugins/memory/vector/hybrid.ts +10 -2
  17. package/src/bundled-plugins/memory/vector/store.ts +21 -9
  18. package/src/bundled-plugins/security/policies/git-exfil.ts +45 -27
  19. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +8 -3
  20. package/src/bundled-plugins/security/policies/private-surface-read.ts +6 -0
  21. package/src/channels/adapters/telegram-bot-classify.ts +29 -0
  22. package/src/channels/router.ts +98 -0
  23. package/src/channels/types.ts +7 -0
  24. package/src/cli/command-meta.ts +2 -0
  25. package/src/cli/compose-stats.ts +103 -0
  26. package/src/cli/compose.ts +13 -0
  27. package/src/cli/index.ts +1 -0
  28. package/src/cli/inspect.ts +16 -0
  29. package/src/cli/stats.ts +134 -0
  30. package/src/compose/index.ts +1 -0
  31. package/src/compose/stats.ts +51 -0
  32. package/src/config/config.ts +14 -0
  33. package/src/config/index.ts +4 -0
  34. package/src/container/controller.ts +6 -0
  35. package/src/container/index.ts +1 -0
  36. package/src/container/log-archive.ts +448 -0
  37. package/src/container/shared.ts +49 -19
  38. package/src/container/start.ts +78 -63
  39. package/src/container/stats.ts +86 -0
  40. package/src/container/stop.ts +63 -36
  41. package/src/init/checkpoint.ts +4 -4
  42. package/src/init/dockerfile.ts +87 -88
  43. package/src/init/gitignore.ts +5 -6
  44. package/src/init/restart-deps-preflight.ts +2 -2
  45. package/src/init/run-bun-install.ts +16 -2
  46. package/src/init/validate-api-key.ts +1 -0
  47. package/src/inspect/item-list.ts +12 -6
  48. package/src/permissions/permissions.ts +93 -2
  49. package/src/role-claim/code.ts +9 -5
  50. package/src/run/index.ts +50 -36
  51. package/src/run/resource-report.ts +226 -0
  52. package/src/sandbox/canonical-secrets.ts +7 -0
  53. package/src/sandbox/index.ts +1 -0
  54. package/src/sandbox/symlinks.ts +1 -1
  55. package/src/secrets/export-claude-credentials-file.ts +13 -22
  56. package/src/secrets/export-codex-auth-file.ts +12 -28
  57. package/typeclaw.schema.json +14 -0
@@ -4,7 +4,6 @@ import type { DockerfileConfig, DockerfileFeatureToggle } from '@/config/config'
4
4
  import {
5
5
  CLAUDE_CREDENTIALS_FILE_NAME,
6
6
  CLAUDE_CREDENTIALS_RELATIVE_PATH,
7
- CLAUDE_DEFAULT_CONFIG_DIR_NAME,
8
7
  } from '@/secrets/export-claude-credentials-file'
9
8
 
10
9
  import { GHCR_BASE_IMAGE_REPO } from './cli-version'
@@ -138,6 +137,13 @@ export const TYPECLAW_ENTRYPOINT_PATH = '/usr/local/bin/typeclaw-entrypoint'
138
137
  // a path, and resolves `/agent/typeclaw.json` (`Cannot run json files`).
139
138
  export const TYPECLAW_CLI_ENTRY = '/agent/node_modules/typeclaw/src/cli/index.ts'
140
139
 
140
+ // Perf: `--smol` selects JSC's small-heap profile (grows slower, GCs more often),
141
+ // trading a little CPU for lower resident memory. The agent runtime is a
142
+ // burst-then-idle workload, so temporary allocations get reclaimed instead of
143
+ // settling into a high-water RSS. Flag goes before `run`. Used at every exec site
144
+ // below so the runtime phase inherits it on every network-policy path.
145
+ const RUNTIME_BUN = 'bun --smol run'
146
+
141
147
  // IPv4 networks the container is forbidden to egress to when
142
148
  // `network.blockInternal` is true. Loopback (127/8) is NOT here — loopback
143
149
  // traffic uses the `lo` interface, which the shim's first ACCEPT rule
@@ -354,68 +360,6 @@ set -eu
354
360
  # -nolisten tcp refuse TCP connections (Unix socket only).
355
361
  # Defense-in-depth — we are in a netns with
356
362
  # no inbound exposure anyway.
357
- # link_persistent_home_files symlinks credential files that tools write
358
- # to $HOME into a bind-mounted location so they survive container
359
- # restarts. The container's $HOME (/root by default) lives on Docker's
360
- # writable overlay and is wiped on every \`stop\`+\`start\` cycle, so
361
- # without this symlink the operator would have to re-paste credentials
362
- # after every restart.
363
- #
364
- # Two files are linked today, both following the same contract:
365
- # - ~/.codex/auth.json — Codex CLI rotates OAuth tokens in place by
366
- # rewriting auth.json with refreshed credentials.
367
- # - $CLAUDE_CONFIG_DIR/.credentials.json, or ~/.claude/.credentials.json
368
- # by default — Claude Code rotates OAuth tokens in place by rewriting
369
- # .credentials.json on every successful refresh (anthropics/claude-code
370
- # #53063). Linux/Windows path; macOS uses the Keychain entry "Claude
371
- # Code-credentials" with the same JSON shape.
372
- #
373
- # The persist root lives under /agent/.typeclaw/home/ (bind-mounted
374
- # from the agent folder via the -v <cwd>:/agent flag in start.ts).
375
- # Namespacing under .typeclaw/ keeps the agent's top-level layout clean and reserves
376
- # a system-owned subtree we can extend later (e.g. ~/.gemini/) without
377
- # colliding with user files. The directory is gitignored by buildGitignore()
378
- # so credentials never enter history.
379
- #
380
- # Three invariants this function enforces:
381
- #
382
- # 1. Symlink is unconditional and idempotent. We never check whether
383
- # auth.json exists before linking — \`ln -sfn\` creates a dangling
384
- # symlink on first boot, and the first \`codex login\` write goes
385
- # through it to land at the persistent location. -f replaces an
386
- # existing symlink; -n stops ln from dereferencing into a directory
387
- # if a previous container life happened to write a real ~/.codex/
388
- # dir before this code shipped.
389
- #
390
- # 2. We symlink credential FILES for tools whose config dirs are mostly
391
- # scratch/history (Codex, Claude). We do not redirect global config
392
- # locations such as XDG_CONFIG_HOME or ~/.config here because tools like
393
- # git also read config from those paths; first-party bundles that need
394
- # persistence should set their own app-specific env vars instead.
395
- #
396
- # 3. We mkdir -p the target's parent on every boot. /agent is bind-
397
- # mounted, so the host-side path may exist or not depending on
398
- # whether the operator ever started the container before this code
399
- # shipped. mkdir -p is idempotent and cheap.
400
- #
401
- # 4. The root is overridable via TYPECLAW_PERSIST_HOME_ROOT, which only
402
- # the shim's executable tests set. Production never sets it, so the
403
- # in-container path is always /agent/.typeclaw/home/. The override
404
- # lets the shim's behavioral tests verify symlink semantics against
405
- # a real tmpdir on the host without touching /agent (which doesn't
406
- # exist on developer machines and CI runners).
407
- link_persistent_home_files() {
408
- persist_root="\${TYPECLAW_PERSIST_HOME_ROOT:-/agent/.typeclaw/home}"
409
- mkdir -p "$persist_root/.codex" "$HOME/.codex"
410
- ln -sfn "$persist_root/.codex/auth.json" "$HOME/.codex/auth.json"
411
- claude_config_dir="\${CLAUDE_CONFIG_DIR:-}"
412
- if [ -z "$claude_config_dir" ]; then
413
- claude_config_dir="$HOME/${CLAUDE_DEFAULT_CONFIG_DIR_NAME}"
414
- fi
415
- mkdir -p "$persist_root/${CLAUDE_DEFAULT_CONFIG_DIR_NAME}" "$claude_config_dir"
416
- ln -sfn "$persist_root/${CLAUDE_CREDENTIALS_RELATIVE_PATH}" "$claude_config_dir/${CLAUDE_CREDENTIALS_FILE_NAME}"
417
- }
418
-
419
363
  # link_configured_symlinks creates the operator's \`sandbox.symlinks\` at the real
420
364
  # container $HOME for runtime-owned processes. Model-driven bash runs in bwrap
421
365
  # for every role and gets an equivalent in-jail symlink from the per-tool builder
@@ -432,8 +376,7 @@ link_persistent_home_files() {
432
376
  # per-entry so one bad symlink never blocks container boot.
433
377
  #
434
378
  # TYPECLAW_AGENT_DIR defaults to /agent (the bind-mount path) and is overridable
435
- # only by the shim's behavioral tests, which point it at a tmpdir — same escape
436
- # hatch as TYPECLAW_PERSIST_HOME_ROOT in link_persistent_home_files. Production
379
+ # only by the shim's behavioral tests, which point it at a tmpdir. Production
437
380
  # never sets it.
438
381
  link_configured_symlinks() {
439
382
  [ -n "\${TYPECLAW_SANDBOX_SYMLINKS:-}" ] || return 0
@@ -478,20 +421,72 @@ link_configured_symlinks() {
478
421
  ' || true
479
422
  }
480
423
 
424
+ # link_custom_claude_credentials keeps a custom CLAUDE_CONFIG_DIR credential file
425
+ # out of model-visible reach. The Claude Code exporter writes the OAuth refresh
426
+ # token to \$CLAUDE_CONFIG_DIR/.credentials.json when that env var is set. Under
427
+ # the default (unset) it lands in the runtime HOME's .claude, which bwrap never
428
+ # binds — invisible to sandboxed bash. But a custom dir under /agent (or any
429
+ # jail-visible root) would put the real token where model bash can read it.
430
+ #
431
+ # Instead of masking every possible custom location, plant a symlink from the
432
+ # custom path INTO the runtime HOME's .claude and let the exporter's
433
+ # symlink-aware writeAtomic() follow it — so the real bytes always live in the
434
+ # unbound, already-denied runtime HOME regardless of where CLAUDE_CONFIG_DIR
435
+ # points. This restores the invariant the old persistence helper used to provide
436
+ # (it linked into the masked persist root); the target moved to the ephemeral
437
+ # HOME, but the "credential is only an alias in the custom dir" property is
438
+ # preserved. Runs in the root phase before privilege drop so custom dirs under
439
+ # root-owned roots (e.g. /etc) can still be created. No-op when the value is
440
+ # unset/blank or already resolves to the runtime HOME's .claude (avoids a
441
+ # self-referential link). Re-linking is idempotent (an existing symlink is
442
+ # replaced); failures are non-fatal so a bad custom path never blocks boot.
443
+ #
444
+ # The from-path MUST match where the exporter actually writes. The exporter
445
+ # (src/secrets/export-claude-credentials-file.ts resolveClaudeConfigDir) applies
446
+ # JS String.trim() and treats an all-whitespace value as unset. Replicating that
447
+ # in POSIX sed would diverge on Unicode whitespace (\u00A0, \u2003, …) that
448
+ # .trim() strips but a byte-oriented sed class does not — a divergence is a
449
+ # credential-isolation bypass (exporter writes the trimmed path, alias sits at
450
+ # the padded path, token stays model-readable). So do the normalization in the
451
+ # same \`bun -e\` runtime the exporter uses, guaranteeing byte-for-byte identical
452
+ # trimming, and create the symlink there too.
453
+ link_custom_claude_credentials() {
454
+ CLAUDE_CONFIG_DIR="\${CLAUDE_CONFIG_DIR:-}" _CLAUDE_RUNTIME_HOME="$runtime_home" \\
455
+ _CLAUDE_CRED_FILE="${CLAUDE_CREDENTIALS_FILE_NAME}" _CLAUDE_CRED_REL="${CLAUDE_CREDENTIALS_RELATIVE_PATH}" bun -e '
456
+ import { mkdirSync, rmSync, symlinkSync } from "node:fs";
457
+ import { dirname, join } from "node:path";
458
+ const raw = process.env.CLAUDE_CONFIG_DIR;
459
+ const trimmed = raw?.trim();
460
+ if (trimmed === undefined || trimmed.length === 0) process.exit(0);
461
+ const runtimeHome = process.env._CLAUDE_RUNTIME_HOME || "/home/agent";
462
+ const from = join(trimmed, process.env._CLAUDE_CRED_FILE);
463
+ const to = join(runtimeHome, process.env._CLAUDE_CRED_REL);
464
+ if (from === to) process.exit(0);
465
+ try {
466
+ mkdirSync(trimmed, { recursive: true });
467
+ mkdirSync(dirname(to), { recursive: true });
468
+ // Unconditionally (re)point the alias, matching the old ln -sfn: a
469
+ // pre-existing real file at the custom path would otherwise keep the token
470
+ // model-readable, which is exactly the exposure this aliasing closes.
471
+ try { rmSync(from); } catch { /* nothing to remove */ }
472
+ symlinkSync(to, from);
473
+ } catch (e) {
474
+ console.error("typeclaw-entrypoint: failed to alias custom Claude credentials:", String(e));
475
+ }
476
+ ' || true
477
+ }
478
+
481
479
  # seed_runtime_home copies the image-baked Claude Code / Codex CLI settings from
482
- # the build-time HOME (/root) into the managed runtime HOME the non-root re-exec
483
- # switches to. The Dockerfile writes ~/.claude.json, ~/.claude/settings.json,
484
- # and ~/.codex/hooks.json against /root during \`docker build\`; once the runtime
485
- # runs under HOME=$runtime_home those files would be invisible, silently
486
- # disabling Claude onboarding state and both CLIs' completion hooks for
487
- # claudeCode/codexCli users. link_persistent_home_files only links CREDENTIALS,
488
- # not this config, so we seed it here.
480
+ # the build-time HOME (/root) into the ephemeral runtime HOME. The Dockerfile
481
+ # writes ~/.claude.json, ~/.claude/settings.json, and ~/.codex/hooks.json against
482
+ # /root during \`docker build\`; once the runtime runs under HOME=$runtime_home
483
+ # those files would otherwise be invisible, silently disabling Claude onboarding
484
+ # state and both CLIs' completion hooks for claudeCode/codexCli users.
489
485
  #
490
- # Runs in the root setup phase (HOME is still /root), BEFORE the chown so the
491
- # copies inherit the host ownership. \`cp -n\` never clobbers a file the operator
492
- # already persisted into the runtime home (the bind-mounted persist root survives
493
- # restarts), so seeding is idempotent and one-way: image defaults fill only what
494
- # is missing.
486
+ # Runs in the root setup phase (HOME is still /root), BEFORE the optional chown
487
+ # so copied files have the dynamic host ownership when the runtime drops
488
+ # privileges. \`cp -n\` keeps repeated shim execution idempotent within one
489
+ # container life; Docker removes this HOME with the container.
495
490
  seed_runtime_home() {
496
491
  _src="\${1:-/root}"
497
492
  _dst="$2"
@@ -571,19 +566,25 @@ start_xvfb() {
571
566
  }
572
567
 
573
568
  if [ "\${TYPECLAW_ENTRYPOINT_RUNTIME:-0}" = "1" ]; then
574
- link_persistent_home_files
575
569
  link_configured_symlinks
576
570
  start_xvfb
577
- exec bun run ${TYPECLAW_CLI_ENTRY} "$@"
571
+ exec ${RUNTIME_BUN} ${TYPECLAW_CLI_ENTRY} "$@"
578
572
  fi
579
573
 
580
- persist_root="\${TYPECLAW_PERSIST_HOME_ROOT:-/agent/.typeclaw/home}"
581
- runtime_home="$persist_root/runtime"
574
+ runtime_home="\${TYPECLAW_RUNTIME_HOME:-/home/agent}"
575
+ mkdir -p "$runtime_home"
576
+ seed_runtime_home "$HOME" "$runtime_home"
577
+ link_custom_claude_credentials
582
578
  if [ -n "\${TYPECLAW_HOST_UID:-}" ] && [ -n "\${TYPECLAW_HOST_GID:-}" ]; then
583
- mkdir -p "$runtime_home"
584
- seed_runtime_home "$HOME" "$runtime_home"
585
- chown -R "$TYPECLAW_HOST_UID:$TYPECLAW_HOST_GID" "$persist_root"
579
+ chown -R "$TYPECLAW_HOST_UID:$TYPECLAW_HOST_GID" "$runtime_home"
586
580
  fi
581
+ # Adopt the runtime HOME for the rest of this root phase, BEFORE any
582
+ # link_configured_symlinks call. The re-exec paths below override HOME again for
583
+ # the fresh runtime process, but the no-host-identity/root fallbacks run
584
+ # link_configured_symlinks in THIS process — without this they would create the
585
+ # operator's \`~/\` symlinks under the inherited build HOME (/root) instead of
586
+ # \$runtime_home.
587
+ export HOME="$runtime_home"
587
588
 
588
589
  if [ "\${TYPECLAW_NETWORK_BLOCK_INTERNAL:-0}" != "1" ]; then
589
590
  if [ -n "\${TYPECLAW_HOST_UID:-}" ] && [ -n "\${TYPECLAW_HOST_GID:-}" ]; then
@@ -599,10 +600,9 @@ if [ "\${TYPECLAW_NETWORK_BLOCK_INTERNAL:-0}" != "1" ]; then
599
600
  --bounding-set=-all --inh-caps=-all --ambient-caps=-all \\
600
601
  -- env HOME="$runtime_home" TYPECLAW_ENTRYPOINT_RUNTIME=1 "$0" "$@"
601
602
  fi
602
- link_persistent_home_files
603
603
  link_configured_symlinks
604
604
  start_xvfb
605
- exec bun run ${TYPECLAW_CLI_ENTRY} "$@"
605
+ exec env HOME="$runtime_home" ${RUNTIME_BUN} ${TYPECLAW_CLI_ENTRY} "$@"
606
606
  fi
607
607
 
608
608
  iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
@@ -654,10 +654,9 @@ if [ -n "\${TYPECLAW_HOST_UID:-}" ] && [ -n "\${TYPECLAW_HOST_GID:-}" ]; then
654
654
  --bounding-set=-all --inh-caps=-all --ambient-caps=-all \\
655
655
  -- env HOME="$runtime_home" TYPECLAW_ENTRYPOINT_RUNTIME=1 "$0" "$@"
656
656
  fi
657
- link_persistent_home_files
658
657
  link_configured_symlinks
659
658
  start_xvfb
660
- exec setpriv --bounding-set -net_admin --inh-caps -net_admin --ambient-caps -net_admin -- bun run ${TYPECLAW_CLI_ENTRY} "$@"
659
+ exec env HOME="$runtime_home" setpriv --bounding-set -net_admin --inh-caps -net_admin --ambient-caps -net_admin -- ${RUNTIME_BUN} ${TYPECLAW_CLI_ENTRY} "$@"
661
660
  `
662
661
  }
663
662
 
@@ -42,12 +42,11 @@ export function buildGitignore(config: GitignoreConfig = { append: [] }): string
42
42
  # as a safety net so an agent folder cloned from a pre-rename machine never
43
43
  # stages credentials by accident.
44
44
  #
45
- # .typeclaw/ is the agent's local-scratch dir. It holds the persistent-$HOME
46
- # overlay (.typeclaw/home/, populated by the entrypoint shim's
47
- # \`link_persistent_home_files\` — see src/init/dockerfile.ts, mirrors container
48
- # $HOME files like ~/.codex/auth.json so tool credentials survive restarts) and
49
- # the in-progress init checkpoint (.typeclaw/init-progress.json, non-secret
50
- # wizard selections for resume). Local-only; never commit.
45
+ # .typeclaw/ is the agent's local-scratch dir. It holds the in-progress init
46
+ # checkpoint (.typeclaw/init-progress.json, non-secret wizard selections for
47
+ # resume). Upgraded agents may also retain legacy .typeclaw/home/ credentials;
48
+ # the runtime no longer uses or migrates them, but they must remain ignored.
49
+ # Local-only; never commit.
51
50
  ${TRULY_IGNORED_PATTERNS.join('\n')}
52
51
 
53
52
  # System-managed: gitignored by default so the agent never stages them by hand,
@@ -5,8 +5,8 @@ import { isAbsolute, join, relative, resolve } from 'node:path'
5
5
  import { PACKAGE_FILE } from './packagejson'
6
6
  import { PACKAGES_DIR } from './paths'
7
7
 
8
- // The hostd restart path is destroy-then-recreate: it `docker rm -f`s the live
9
- // container BEFORE `start()` runs `bun install`. A bad agent edit to
8
+ // The hostd restart path is destroy-then-recreate: stop() archives logs, then
9
+ // non-force-removes the inspected container ID BEFORE `start()` runs `bun install`. A bad agent edit to
10
10
  // typeclaw.json#plugins or a packages/* manifest aborts that install AFTER the
11
11
  // old container is gone, with no rollback and no client to report to — the agent
12
12
  // self-locks out. This runs BEFORE stop() (via RestartPreflight) so a bad edit
@@ -107,10 +107,24 @@ async function runTimedBunProcess({
107
107
  proc.kill('SIGKILL')
108
108
  }, timeoutMs)
109
109
  try {
110
- const code = await proc.exited
110
+ // Drain both pipes alongside exit: an undrained 'pipe' stdout/stderr holds
111
+ // its fd (and can deadlock a child that fills the buffer) until GC. A drain
112
+ // that rejects must not escape before the child is reaped — otherwise the
113
+ // `finally` clears the timeout while the process is still alive. Kill and
114
+ // await exit on any drain failure so the timer never disarms a live child.
115
+ const stdoutDrain = new Response(proc.stdout).text()
116
+ const stderrDrain = new Response(proc.stderr).text()
117
+ let code: number
118
+ let stderr: string
119
+ try {
120
+ ;[code, , stderr] = await Promise.all([proc.exited, stdoutDrain, stderrDrain])
121
+ } catch (err) {
122
+ proc.kill('SIGKILL')
123
+ await Promise.allSettled([proc.exited, stdoutDrain, stderrDrain])
124
+ throw err
125
+ }
111
126
  if (timedOut) return { ok: false, reason: timeoutReason(timeoutMs / 1000) }
112
127
  if (code === 0) return { ok: true }
113
- const stderr = await new Response(proc.stderr).text()
114
128
  return { ok: false, reason: failureReason(code, stderr) }
115
129
  } finally {
116
130
  clearTimeout(timeout)
@@ -156,6 +156,7 @@ async function readCapped(res: Response, maxBytes: number): Promise<string | nul
156
156
  return null
157
157
  } finally {
158
158
  await reader.cancel().catch(() => undefined)
159
+ reader.releaseLock()
159
160
  }
160
161
  }
161
162
 
@@ -5,6 +5,11 @@ import { listSessions, type ListSessionsOptions, mergeLiveSessions, type Session
5
5
 
6
6
  export type ListViewerItemsOptions = ListSessionsOptions & {
7
7
  containerRunning: boolean
8
+ // A writable row dispatches to runTuiViewer, which drives a raw-mode pi-tui
9
+ // terminal — unusable without a TTY. Required (not defaulted) so a non-TTY
10
+ // caller can't silently promote a writable row it then can't drive, which
11
+ // would auto-open a TUI on an explicit id past the picker guard.
12
+ interactive: boolean
8
13
  includeLogs?: boolean
9
14
  // Defaults to true. The detach-to-list path (after `typeclaw tui` esc) sets
10
15
  // this false: detaching ENDS the server-side session, so the just-killed
@@ -22,18 +27,19 @@ export type ViewerList = {
22
27
  }
23
28
 
24
29
  // Builds the session-viewer list. The writable TUI row is a heuristic, not an
25
- // authoritative query: when the container is up, the single most-recent
26
- // tui-origin session becomes the read+write `tui` item; every other session is
27
- // read-only. With the container down there is no live session to drive, so all
28
- // sessions are read-only. The `logs` row is appended last (container stdout,
29
- // available offline) so it sits below the divider in the picker.
30
+ // authoritative query: when the container is up AND stdin is a TTY, the single
31
+ // most-recent tui-origin session becomes the read+write `tui` item; every other
32
+ // session is read-only. With the container down (no live session to drive) or a
33
+ // non-TTY stdin (no terminal to drive it), all sessions are read-only. The
34
+ // `logs` row is appended last (container stdout, available offline) so it sits
35
+ // below the divider in the picker.
30
36
  export async function listViewerItems(opts: ListViewerItemsOptions): Promise<ViewerList> {
31
37
  const diskSessions = await listSessions(opts)
32
38
  const sessions =
33
39
  opts.liveSessions !== undefined && opts.liveSessions.length > 0
34
40
  ? mergeLiveSessions(diskSessions, opts.liveSessions)
35
41
  : diskSessions
36
- const allowWritable = opts.allowWritable !== false
42
+ const allowWritable = opts.interactive && opts.allowWritable !== false
37
43
  const writableSessionId = opts.containerRunning && allowWritable ? pickWritableSession(sessions) : null
38
44
 
39
45
  const items: ViewerItem[] = sessions.map((summary) =>
@@ -129,6 +129,40 @@ function levenshtein(a: string, b: string): number {
129
129
  return prev[lb]!
130
130
  }
131
131
 
132
+ // Cap on the memoized role-resolution cache. Channel keys derive from
133
+ // externally-controlled coordinates, so the cache must be bounded — see the
134
+ // roleCache comment in createPermissionService.
135
+ export const ROLE_CACHE_MAX = 4096
136
+
137
+ export type BoundedCache<V> = {
138
+ get(key: string): V | undefined
139
+ set(key: string, value: V): void
140
+ clear(): void
141
+ readonly size: number
142
+ }
143
+
144
+ // Insertion-ordered cache with a hard capacity. On overflow it evicts the
145
+ // oldest inserted entry (JS Map preserves insertion order), so size never
146
+ // exceeds `max`. Extracted as a standalone factory so the bound is unit-testable
147
+ // in isolation — the in-service cache is otherwise unobservable.
148
+ export function createBoundedCache<V>(max: number): BoundedCache<V> {
149
+ const store = new Map<string, V>()
150
+ return {
151
+ get: (key) => store.get(key),
152
+ set(key, value) {
153
+ if (!store.has(key) && store.size >= max) {
154
+ const oldest = store.keys().next().value
155
+ if (oldest !== undefined) store.delete(oldest)
156
+ }
157
+ store.set(key, value)
158
+ },
159
+ clear: () => store.clear(),
160
+ get size() {
161
+ return store.size
162
+ },
163
+ }
164
+ }
165
+
132
166
  export function createPermissionService(opts: CreatePermissionServiceOptions = {}): PermissionService {
133
167
  let pluginPermissions = opts.pluginPermissions ?? []
134
168
  let ownerWildcardExclusions = opts.ownerWildcardExclusions ?? []
@@ -136,9 +170,24 @@ export function createPermissionService(opts: CreatePermissionServiceOptions = {
136
170
  let resolved = buildRoleTable(lastRoles, pluginPermissions, ownerWildcardExclusions)
137
171
  let byName = new Map(resolved.map((r) => [r.name, r]))
138
172
 
139
- function resolveRole(origin: SessionOrigin | undefined): string {
140
- if (origin === undefined) return 'guest'
173
+ // resolveRole is called several times per tool invocation (the bash sandbox
174
+ // alone resolves it up to 6x through resolveHiddenPaths) and once per channel
175
+ // admission, and each call re-scans the whole role table via matchesOrigin.
176
+ // The result is a pure function of (role table, resolved origin fields), so
177
+ // memoize it. The cache holds only the CURRENT role table's verdicts; both
178
+ // role-table rebuilds (replaceRoles / replacePluginPermissions) drop it, so a
179
+ // stale entry can never survive a config change and hand back a now-wrong
180
+ // (e.g. over-privileged) role. See roleCacheKey for exactly which fields the
181
+ // key covers — it must stay a superset of what computeRole reads.
182
+ //
183
+ // Bounded because channel cache keys derive from externally-controlled
184
+ // coordinates (workspace/chat/author): a stream of distinct GitHub issue or
185
+ // chat ids — even denied traffic that resolves to guest — would otherwise
186
+ // grow the map without limit until the next role-table rebuild. See
187
+ // createBoundedCache for the eviction policy.
188
+ const roleCache = createBoundedCache<string>(ROLE_CACHE_MAX)
141
189
 
190
+ function computeRole(origin: SessionOrigin): string {
142
191
  // Runtime-owned infrastructure (memory, backup) acts on the operator's
143
192
  // behalf over operator-owned state. It is constructed only by runtime/
144
193
  // bundled code — inbound channel/cron content cannot produce this kind —
@@ -168,6 +217,21 @@ export function createPermissionService(opts: CreatePermissionServiceOptions = {
168
217
  return 'guest'
169
218
  }
170
219
 
220
+ function resolveRole(origin: SessionOrigin | undefined): string {
221
+ if (origin === undefined) return 'guest'
222
+ const key = roleCacheKey(origin)
223
+ if (key === null) return computeRole(origin)
224
+ const cached = roleCache.get(key)
225
+ if (cached !== undefined) return cached
226
+ const role = computeRole(origin)
227
+ roleCache.set(key, role)
228
+ return role
229
+ }
230
+
231
+ function invalidateRoleCache(): void {
232
+ roleCache.clear()
233
+ }
234
+
171
235
  function roleSeverity(name: string): number | undefined {
172
236
  if (name === 'owner') return 4
173
237
  if (name === 'trusted') return 3
@@ -214,12 +278,14 @@ export function createPermissionService(opts: CreatePermissionServiceOptions = {
214
278
  lastRoles = roles ?? {}
215
279
  resolved = buildRoleTable(lastRoles, pluginPermissions, ownerWildcardExclusions)
216
280
  byName = new Map(resolved.map((r) => [r.name, r]))
281
+ invalidateRoleCache()
217
282
  },
218
283
  replacePluginPermissions(next) {
219
284
  pluginPermissions = next.pluginPermissions
220
285
  ownerWildcardExclusions = next.ownerWildcardExclusions
221
286
  resolved = buildRoleTable(lastRoles, pluginPermissions, ownerWildcardExclusions)
222
287
  byName = new Map(resolved.map((r) => [r.name, r]))
288
+ invalidateRoleCache()
223
289
  },
224
290
  }
225
291
  }
@@ -294,6 +360,31 @@ function resolveOne(
294
360
  }
295
361
  }
296
362
 
363
+ // Cache key for the memoized role resolution. It MUST enumerate exactly the
364
+ // origin fields that computeRole/matchesOrigin consult, and NOTHING that varies
365
+ // turn-to-turn without changing the verdict (participants, membership, thread,
366
+ // reactionRef, *Name display fields). Returning null opts an origin OUT of the
367
+ // cache — used for kinds where the answer is already O(1) (system/cron/subagent,
368
+ // which read only a role string off the origin) so there is no scan to save and
369
+ // no reason to risk an under-specified key. tui and channel are the scan-heavy
370
+ // kinds worth caching:
371
+ // - tui: verdict depends only on kind (matchesOrigin's tui rule ignores
372
+ // sessionId), so every tui origin shares one entry.
373
+ // - channel: verdict depends on adapter + workspace + chat + lastInboundAuthorId
374
+ // (the exact inputs matchesChannel/matchesBucket/matchesAuthor read).
375
+ // The `c` prefix + NUL separators keep channel keys unambiguous even if a field
376
+ // contained the delimiter of another.
377
+ function roleCacheKey(origin: SessionOrigin): string | null {
378
+ switch (origin.kind) {
379
+ case 'tui':
380
+ return 'tui'
381
+ case 'channel':
382
+ return ['c', origin.adapter, origin.workspace, origin.chat, origin.lastInboundAuthorId ?? ''].join('\u0000')
383
+ default:
384
+ return null
385
+ }
386
+ }
387
+
297
388
  function toMatchable(origin: SessionOrigin): Parameters<typeof matchesOrigin>[1] | null {
298
389
  switch (origin.kind) {
299
390
  case 'tui':
@@ -19,6 +19,14 @@ const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
19
19
  const BLOCK_SIZE = 4
20
20
  const BLOCK_COUNT = 2
21
21
 
22
+ // Shape is fixed by the block constants, so compile once at module load rather
23
+ // than per inbound message — extractClaimCode runs on every channel message
24
+ // carrying a potential claim.
25
+ const CLAIM_CODE_RE = new RegExp(
26
+ `${CLAIM_CODE_PREFIX}([0-9a-zA-Z]{${BLOCK_SIZE}}(?:-[0-9a-zA-Z]{${BLOCK_SIZE}}){${BLOCK_COUNT - 1}})`,
27
+ 'i',
28
+ )
29
+
22
30
  export function generateClaimCode(): string {
23
31
  const bytes = randomBytes(BLOCK_SIZE * BLOCK_COUNT)
24
32
  const chars: string[] = []
@@ -37,11 +45,7 @@ export function generateClaimCode(): string {
37
45
  // whitespace, punctuation, and case — chat clients may auto-correct case
38
46
  // or surround pastes with quotes/backticks.
39
47
  export function extractClaimCode(text: string): string | null {
40
- const pattern = new RegExp(
41
- `${CLAIM_CODE_PREFIX}([0-9a-zA-Z]{${BLOCK_SIZE}}(?:-[0-9a-zA-Z]{${BLOCK_SIZE}}){${BLOCK_COUNT - 1}})`,
42
- 'i',
43
- )
44
- const match = pattern.exec(text)
48
+ const match = CLAIM_CODE_RE.exec(text)
45
49
  if (!match) return null
46
50
  return `${CLAIM_CODE_PREFIX}${match[1]!.toUpperCase()}`
47
51
  }
package/src/run/index.ts CHANGED
@@ -88,6 +88,7 @@ import { buildChannelSessionFactory } from './channel-session-factory'
88
88
  import { installFatalGuard } from './fatal-guard'
89
89
  import { installLlmFetchObserver } from './llm-fetch-observer'
90
90
  import { createPluginRuntime, type PluginRuntime, type PluginSubagentEntry } from './plugin-runtime'
91
+ import { logResourceReport } from './resource-report'
91
92
 
92
93
  type BunServer = ReturnType<Server['start']>
93
94
 
@@ -122,6 +123,10 @@ export type StartAgentOptions = {
122
123
  // over the real env + <cwd>/secrets.json. Injectable so tests can supply a
123
124
  // fake secrets provider without touching process.env.
124
125
  caps?: RuntimeCapabilities
126
+ // Boot credential exporters are injectable so ordering tests can prove they
127
+ // observe secrets only after the awaited provider-OAuth refresh settles.
128
+ exportCodexAuthFile?: typeof exportCodexAuthFileForAgent
129
+ exportClaudeCredentialsFile?: typeof exportClaudeCredentialsFileForAgent
125
130
  // Boot-time proactive provider-OAuth refresh. Injectable so a test can supply
126
131
  // a refresh that holds the real secrets lock on a gate, proving the boot
127
132
  // barrier settles this before any session-producing consumer starts.
@@ -186,6 +191,8 @@ async function startAgentRuntime(
186
191
  createChannelManager: createChannelManagerFor = createChannelManager,
187
192
  createTunnelManager: createTunnelManagerFor = createTunnelManager,
188
193
  caps = createRuntimeCapabilities(process.env, join(cwd, 'secrets.json')),
194
+ exportCodexAuthFile = exportCodexAuthFileForAgent,
195
+ exportClaudeCredentialsFile = exportClaudeCredentialsFileForAgent,
189
196
  refreshProviderOAuth = refreshProviderOAuthForAgent,
190
197
  }: StartAgentOptions,
191
198
  registerBootCleanup: (cleanup: () => void | Promise<void>) => void,
@@ -296,6 +303,10 @@ async function startAgentRuntime(
296
303
  getGithubAppSelfLogin: githubTokenBridge.getAppSelfLogin,
297
304
  ...(cwdConfig.roles !== undefined ? { roles: cwdConfig.roles } : {}),
298
305
  })
306
+ // Emit the container's fixed resource limits BEFORE vector startup. The
307
+ // startup index build is itself an OOM path; if it kills the process, this
308
+ // line must already be in the log so the ceiling is still recorded.
309
+ logResourceReport(cwd)
299
310
  const vectorStartupPromise = runVectorStartup(cwd)
300
311
  let pluginsLoaded: LoadPluginsResult
301
312
  try {
@@ -355,32 +366,6 @@ async function startAgentRuntime(
355
366
  // stay in env, the file stays user-owned. See src/secrets/hydrate.ts.
356
367
  hydrateChannelEnvFromSecrets({ agentDir: cwd })
357
368
 
358
- // When the user has `docker.file.codexCli: true` AND a typeclaw-managed
359
- // openai-codex OAuth credential in secrets.json, write ~/.codex/auth.json
360
- // so the Codex CLI in the container can run without a second login. The
361
- // exporter is failure-tolerant by design: any error (gate miss, fs error,
362
- // corrupt file) returns a non-fatal result and the agent boot continues.
363
- // See src/secrets/export-codex-auth-file.ts for the newer-wins compare
364
- // that prevents clobbering Codex CLI's in-place token refreshes.
365
- exportCodexAuthFileForAgent({
366
- agentDir: cwd,
367
- codexCliEnabled: cwdConfig.docker.file.codexCli,
368
- log: (message) => console.warn(message),
369
- })
370
-
371
- // Same shape as the codex exporter above, gated on `docker.file.claudeCode`
372
- // and `secrets.json#providers.anthropic`. Writes ~/.claude/.credentials.json
373
- // so the Claude Code CLI in the container can run without the user pasting
374
- // a CLAUDE_CODE_OAUTH_TOKEN. See src/secrets/export-claude-credentials-
375
- // file.ts for the newer-wins compare that prevents clobbering Claude
376
- // Code's in-place token refreshes, and the read-merge-write that preserves
377
- // any mcpOAuth state in the file.
378
- exportClaudeCredentialsFileForAgent({
379
- agentDir: cwd,
380
- claudeCodeEnabled: cwdConfig.docker.file.claudeCode,
381
- log: (message) => console.warn(message),
382
- })
383
-
384
369
  // Proactively refresh any stored provider-OAuth token now. The SDK's own
385
370
  // refresh is lazy (fires on the first LLM call), so a container that restarts
386
371
  // with an already-expired access token otherwise discovers the staleness —
@@ -389,21 +374,50 @@ async function startAgentRuntime(
389
374
  // log. Channel-adapter OAuth already has host-side renewal crons; this is the
390
375
  // provider-OAuth equivalent.
391
376
  //
392
- // MUST be awaited, and MUST run before the first session-producing consumer
393
- // (subagentConsumer.start / cronConsumer.start / channelManager.start / the
394
- // websocket server). The SDK refresh holds SecretsBackend's async file lock
395
- // across its network request; getAuthFor()'s synchronous lock read gives up
396
- // after ~200ms and process.exit(1)s on ELOCKED. Fire-and-forget here would let
397
- // a slow refresh still own the lock when a consumer creates a session — worse
398
- // than the lazy path. Awaiting behind this barrier guarantees no synchronous
399
- // auth reader exists while the refresh owns the lock. Never throws (the
400
- // wrapper swallows and logs), so a probe failure can't block boot; a refresh
401
- // that hangs on a wedged network hangs the first turn today anyway.
377
+ // MUST be awaited, and MUST run before the credential-file exporters below
378
+ // and the first session-producing consumer (subagentConsumer.start /
379
+ // cronConsumer.start / channelManager.start / the websocket server). The SDK
380
+ // refresh holds SecretsBackend's async file lock across its network request;
381
+ // getAuthFor()'s synchronous lock read gives up after ~200ms and
382
+ // process.exit(1)s on ELOCKED. Fire-and-forget here would let a slow refresh
383
+ // still own the lock when an exporter or consumer reads secrets — worse than
384
+ // the lazy path. Awaiting behind this barrier guarantees no synchronous auth
385
+ // reader exists while the refresh owns the lock. Never throws (the wrapper
386
+ // swallows and logs), so a probe failure can't block boot; a refresh that
387
+ // hangs on a wedged network hangs the first turn today anyway.
402
388
  await refreshProviderOAuth({
403
389
  agentDir: cwd,
404
390
  log: (message) => console.warn(message),
405
391
  })
406
392
 
393
+ // When the user has `docker.file.codexCli: true` AND a typeclaw-managed
394
+ // openai-codex OAuth credential in secrets.json, write ~/.codex/auth.json
395
+ // so the Codex CLI in the container can run without a second login. This runs
396
+ // after the awaited boot refresh so the fresh ephemeral HOME receives the
397
+ // refreshed token, never the stale pre-refresh value. The exporter is
398
+ // failure-tolerant by design: any error (gate miss, fs error, corrupt file)
399
+ // returns a non-fatal result and the agent boot continues. See
400
+ // src/secrets/export-codex-auth-file.ts for the newer-wins compare that
401
+ // prevents clobbering Codex CLI's in-place token refreshes.
402
+ exportCodexAuthFile({
403
+ agentDir: cwd,
404
+ codexCliEnabled: cwdConfig.docker.file.codexCli,
405
+ log: (message) => console.warn(message),
406
+ })
407
+
408
+ // Same shape as the codex exporter above, gated on `docker.file.claudeCode`
409
+ // and `secrets.json#providers.anthropic`. It likewise runs after the boot
410
+ // refresh, then writes ~/.claude/.credentials.json so the Claude Code CLI in
411
+ // the container can run without the user pasting a CLAUDE_CODE_OAUTH_TOKEN.
412
+ // See src/secrets/export-claude-credentials-file.ts for the newer-wins compare
413
+ // that prevents clobbering Claude Code's in-place token refreshes, and the
414
+ // read-merge-write that preserves any mcpOAuth state in the file.
415
+ exportClaudeCredentialsFile({
416
+ agentDir: cwd,
417
+ claudeCodeEnabled: cwdConfig.docker.file.claudeCode,
418
+ log: (message) => console.warn(message),
419
+ })
420
+
407
421
  const claimController = createClaimController({
408
422
  cwd,
409
423
  permissions: pluginsLoaded.permissions,