typeclaw 0.46.1 → 0.46.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.
- package/package.json +2 -2
- package/src/agent/tool-file-safety.ts +18 -9
- package/src/agent/tools/webfetch/strategies/jq.ts +1 -2
- package/src/agent/tools/webfetch/strategies/readability.ts +39 -16
- package/src/agent/tools/webfetch/strategies/selector.ts +4 -2
- package/src/agent/tools/webfetch/strategies/snapshot.ts +3 -2
- package/src/agent/tools/webfetch/tool.ts +3 -3
- package/src/bundled-plugins/backup/index.ts +21 -4
- package/src/bundled-plugins/backup/runner.ts +19 -5
- package/src/bundled-plugins/memory/vector/hybrid.ts +10 -2
- package/src/bundled-plugins/memory/vector/store.ts +21 -9
- package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +8 -3
- package/src/bundled-plugins/security/policies/private-surface-read.ts +6 -0
- package/src/cli/inspect.ts +16 -0
- package/src/container/shared.ts +19 -6
- package/src/init/checkpoint.ts +4 -4
- package/src/init/dockerfile.ts +87 -88
- package/src/init/gitignore.ts +5 -6
- package/src/init/run-bun-install.ts +16 -2
- package/src/init/validate-api-key.ts +1 -0
- package/src/inspect/item-list.ts +12 -6
- package/src/permissions/permissions.ts +93 -2
- package/src/role-claim/code.ts +9 -5
- package/src/run/index.ts +45 -36
- package/src/sandbox/canonical-secrets.ts +6 -0
- package/src/sandbox/index.ts +1 -0
- package/src/sandbox/symlinks.ts +1 -1
- package/src/secrets/export-claude-credentials-file.ts +13 -22
- package/src/secrets/export-codex-auth-file.ts +12 -28
package/src/init/dockerfile.ts
CHANGED
|
@@ -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
|
|
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
|
|
483
|
-
#
|
|
484
|
-
#
|
|
485
|
-
#
|
|
486
|
-
#
|
|
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
|
|
491
|
-
#
|
|
492
|
-
#
|
|
493
|
-
#
|
|
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
|
|
571
|
+
exec ${RUNTIME_BUN} ${TYPECLAW_CLI_ENTRY} "$@"
|
|
578
572
|
fi
|
|
579
573
|
|
|
580
|
-
|
|
581
|
-
|
|
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
|
-
|
|
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
|
|
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 --
|
|
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
|
|
package/src/init/gitignore.ts
CHANGED
|
@@ -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
|
|
46
|
-
#
|
|
47
|
-
#
|
|
48
|
-
#
|
|
49
|
-
#
|
|
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,
|
|
@@ -107,10 +107,24 @@ async function runTimedBunProcess({
|
|
|
107
107
|
proc.kill('SIGKILL')
|
|
108
108
|
}, timeoutMs)
|
|
109
109
|
try {
|
|
110
|
-
|
|
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)
|
package/src/inspect/item-list.ts
CHANGED
|
@@ -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
|
|
26
|
-
// tui-origin session becomes the read+write `tui` item; every other
|
|
27
|
-
// read-only. With the container down
|
|
28
|
-
// sessions are read-only. The
|
|
29
|
-
// available offline) so it sits
|
|
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
|
-
|
|
140
|
-
|
|
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':
|
package/src/role-claim/code.ts
CHANGED
|
@@ -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
|
|
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
|
@@ -122,6 +122,10 @@ export type StartAgentOptions = {
|
|
|
122
122
|
// over the real env + <cwd>/secrets.json. Injectable so tests can supply a
|
|
123
123
|
// fake secrets provider without touching process.env.
|
|
124
124
|
caps?: RuntimeCapabilities
|
|
125
|
+
// Boot credential exporters are injectable so ordering tests can prove they
|
|
126
|
+
// observe secrets only after the awaited provider-OAuth refresh settles.
|
|
127
|
+
exportCodexAuthFile?: typeof exportCodexAuthFileForAgent
|
|
128
|
+
exportClaudeCredentialsFile?: typeof exportClaudeCredentialsFileForAgent
|
|
125
129
|
// Boot-time proactive provider-OAuth refresh. Injectable so a test can supply
|
|
126
130
|
// a refresh that holds the real secrets lock on a gate, proving the boot
|
|
127
131
|
// barrier settles this before any session-producing consumer starts.
|
|
@@ -186,6 +190,8 @@ async function startAgentRuntime(
|
|
|
186
190
|
createChannelManager: createChannelManagerFor = createChannelManager,
|
|
187
191
|
createTunnelManager: createTunnelManagerFor = createTunnelManager,
|
|
188
192
|
caps = createRuntimeCapabilities(process.env, join(cwd, 'secrets.json')),
|
|
193
|
+
exportCodexAuthFile = exportCodexAuthFileForAgent,
|
|
194
|
+
exportClaudeCredentialsFile = exportClaudeCredentialsFileForAgent,
|
|
189
195
|
refreshProviderOAuth = refreshProviderOAuthForAgent,
|
|
190
196
|
}: StartAgentOptions,
|
|
191
197
|
registerBootCleanup: (cleanup: () => void | Promise<void>) => void,
|
|
@@ -355,32 +361,6 @@ async function startAgentRuntime(
|
|
|
355
361
|
// stay in env, the file stays user-owned. See src/secrets/hydrate.ts.
|
|
356
362
|
hydrateChannelEnvFromSecrets({ agentDir: cwd })
|
|
357
363
|
|
|
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
364
|
// Proactively refresh any stored provider-OAuth token now. The SDK's own
|
|
385
365
|
// refresh is lazy (fires on the first LLM call), so a container that restarts
|
|
386
366
|
// with an already-expired access token otherwise discovers the staleness —
|
|
@@ -389,21 +369,50 @@ async function startAgentRuntime(
|
|
|
389
369
|
// log. Channel-adapter OAuth already has host-side renewal crons; this is the
|
|
390
370
|
// provider-OAuth equivalent.
|
|
391
371
|
//
|
|
392
|
-
// MUST be awaited, and MUST run before the
|
|
393
|
-
//
|
|
394
|
-
// websocket server). The SDK
|
|
395
|
-
//
|
|
396
|
-
//
|
|
397
|
-
//
|
|
398
|
-
//
|
|
399
|
-
//
|
|
400
|
-
//
|
|
401
|
-
//
|
|
372
|
+
// MUST be awaited, and MUST run before the credential-file exporters below
|
|
373
|
+
// and the first session-producing consumer (subagentConsumer.start /
|
|
374
|
+
// cronConsumer.start / channelManager.start / the websocket server). The SDK
|
|
375
|
+
// refresh holds SecretsBackend's async file lock across its network request;
|
|
376
|
+
// getAuthFor()'s synchronous lock read gives up after ~200ms and
|
|
377
|
+
// process.exit(1)s on ELOCKED. Fire-and-forget here would let a slow refresh
|
|
378
|
+
// still own the lock when an exporter or consumer reads secrets — worse than
|
|
379
|
+
// the lazy path. Awaiting behind this barrier guarantees no synchronous auth
|
|
380
|
+
// reader exists while the refresh owns the lock. Never throws (the wrapper
|
|
381
|
+
// swallows and logs), so a probe failure can't block boot; a refresh that
|
|
382
|
+
// hangs on a wedged network hangs the first turn today anyway.
|
|
402
383
|
await refreshProviderOAuth({
|
|
403
384
|
agentDir: cwd,
|
|
404
385
|
log: (message) => console.warn(message),
|
|
405
386
|
})
|
|
406
387
|
|
|
388
|
+
// When the user has `docker.file.codexCli: true` AND a typeclaw-managed
|
|
389
|
+
// openai-codex OAuth credential in secrets.json, write ~/.codex/auth.json
|
|
390
|
+
// so the Codex CLI in the container can run without a second login. This runs
|
|
391
|
+
// after the awaited boot refresh so the fresh ephemeral HOME receives the
|
|
392
|
+
// refreshed token, never the stale pre-refresh value. The exporter is
|
|
393
|
+
// failure-tolerant by design: any error (gate miss, fs error, corrupt file)
|
|
394
|
+
// returns a non-fatal result and the agent boot continues. See
|
|
395
|
+
// src/secrets/export-codex-auth-file.ts for the newer-wins compare that
|
|
396
|
+
// prevents clobbering Codex CLI's in-place token refreshes.
|
|
397
|
+
exportCodexAuthFile({
|
|
398
|
+
agentDir: cwd,
|
|
399
|
+
codexCliEnabled: cwdConfig.docker.file.codexCli,
|
|
400
|
+
log: (message) => console.warn(message),
|
|
401
|
+
})
|
|
402
|
+
|
|
403
|
+
// Same shape as the codex exporter above, gated on `docker.file.claudeCode`
|
|
404
|
+
// and `secrets.json#providers.anthropic`. It likewise runs after the boot
|
|
405
|
+
// refresh, then writes ~/.claude/.credentials.json so the Claude Code CLI in
|
|
406
|
+
// the container can run without the user pasting a CLAUDE_CODE_OAUTH_TOKEN.
|
|
407
|
+
// See src/secrets/export-claude-credentials-file.ts for the newer-wins compare
|
|
408
|
+
// that prevents clobbering Claude Code's in-place token refreshes, and the
|
|
409
|
+
// read-merge-write that preserves any mcpOAuth state in the file.
|
|
410
|
+
exportClaudeCredentialsFile({
|
|
411
|
+
agentDir: cwd,
|
|
412
|
+
claudeCodeEnabled: cwdConfig.docker.file.claudeCode,
|
|
413
|
+
log: (message) => console.warn(message),
|
|
414
|
+
})
|
|
415
|
+
|
|
407
416
|
const claimController = createClaimController({
|
|
408
417
|
cwd,
|
|
409
418
|
permissions: pluginsLoaded.permissions,
|
|
@@ -6,6 +6,12 @@ export const CANONICAL_AGENT_SECRET_DIRS = [
|
|
|
6
6
|
|
|
7
7
|
export const CANONICAL_AGENT_SECRET_FILES = ['.env', 'secrets.json', 'auth.json'] as const
|
|
8
8
|
|
|
9
|
+
// Trusted runtime processes use this ephemeral container HOME. bwrap builds an
|
|
10
|
+
// empty root and never binds /home, so model bash cannot see it; non-bash tools
|
|
11
|
+
// run in-process and use this fixed path as an unconditional denial root in
|
|
12
|
+
// addition to os.homedir() (which resolves here in the container).
|
|
13
|
+
export const CONTAINER_RUNTIME_HOME = '/home/agent'
|
|
14
|
+
|
|
9
15
|
export const CANONICAL_HOME_SECRET_DIRS = [
|
|
10
16
|
'.ssh',
|
|
11
17
|
'.config/gh',
|
package/src/sandbox/index.ts
CHANGED
package/src/sandbox/symlinks.ts
CHANGED
|
@@ -12,7 +12,7 @@ export type SandboxSymlinkSpec = {
|
|
|
12
12
|
// Resolves config `sandbox.symlinks` into the in-jail `--symlink` ops the bwrap
|
|
13
13
|
// builder consumes. `from` is the symlink LOCATION: a `~/`-prefixed `from` is
|
|
14
14
|
// expanded against the SANDBOX HOME (`/tmp`, where the per-session tmp dir is
|
|
15
|
-
// bound), NOT the
|
|
15
|
+
// bound), NOT the trusted runtime's `/home/agent` — inside the jail a CLI reading
|
|
16
16
|
// `$HOME/.foo` looks under `/tmp`, so the symlink must live there. An absolute
|
|
17
17
|
// `from` is used verbatim. `to` is resolved to the absolute /agent path the
|
|
18
18
|
// symlink points at. Container paths are always POSIX, so this uses posix path
|