typeclaw 0.45.1 → 0.46.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +44 -30
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/multimodal/index.ts +1 -1
  7. package/src/agent/multimodal/look-at.ts +78 -44
  8. package/src/agent/multimodal/looker.ts +161 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +207 -0
  11. package/src/agent/plugin-tools.ts +377 -157
  12. package/src/agent/provider-error.ts +52 -1
  13. package/src/agent/restart/index.ts +61 -40
  14. package/src/agent/restart-handoff/index.ts +73 -4
  15. package/src/agent/reviewer-bash-policy.ts +42 -1
  16. package/src/agent/session-origin.ts +2 -0
  17. package/src/agent/subagent-drain.ts +117 -7
  18. package/src/agent/subagents.ts +49 -16
  19. package/src/agent/throttle-circuit.ts +25 -5
  20. package/src/agent/tool-error-remediation.ts +72 -0
  21. package/src/agent/tool-file-safety.ts +1310 -0
  22. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  23. package/src/agent/tools/ddg.ts +16 -2
  24. package/src/agent/tools/post-github-review.ts +199 -0
  25. package/src/agent/tools/spawn-subagent.ts +21 -18
  26. package/src/agent/tools/webfetch/fetch.ts +163 -183
  27. package/src/agent/tools/webfetch/tool.ts +2 -3
  28. package/src/agent/tools/websearch.ts +23 -2
  29. package/src/agent/tools-without-local-file-operands.ts +30 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/README.md +23 -10
  32. package/src/bundled-plugins/backup/git-auth.ts +6 -4
  33. package/src/bundled-plugins/backup/index.ts +85 -44
  34. package/src/bundled-plugins/backup/runner.ts +85 -1
  35. package/src/bundled-plugins/doc-render/render.ts +93 -12
  36. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  37. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  38. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  39. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
  40. package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
  41. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
  42. package/src/bundled-plugins/github-cli-auth/index.ts +207 -132
  43. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  44. package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
  45. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  46. package/src/bundled-plugins/memory/README.md +32 -11
  47. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  48. package/src/bundled-plugins/memory/citations.ts +22 -9
  49. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  50. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  51. package/src/bundled-plugins/memory/index.ts +0 -4
  52. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  53. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  54. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  55. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  56. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  57. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  58. package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
  59. package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
  60. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  61. package/src/bundled-plugins/researcher/write-report.ts +8 -5
  62. package/src/bundled-plugins/reviewer/index.ts +2 -2
  63. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  64. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  65. package/src/bundled-plugins/scout/scout.ts +8 -0
  66. package/src/bundled-plugins/security/index.ts +4 -4
  67. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  68. package/src/bundled-plugins/security/policies/private-surface-read.ts +787 -36
  69. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  70. package/src/bundled-plugins/security/policies/ssrf.ts +147 -42
  71. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  72. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  73. package/src/channels/adapters/discord-bot.ts +66 -6
  74. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  75. package/src/channels/adapters/discord-id.ts +4 -0
  76. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  77. package/src/channels/adapters/discord.ts +57 -7
  78. package/src/channels/adapters/github/auth-app.ts +41 -12
  79. package/src/channels/adapters/github/inbound.ts +11 -0
  80. package/src/channels/adapters/github/index.ts +71 -65
  81. package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
  82. package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
  83. package/src/channels/adapters/github/review-submitter.ts +302 -0
  84. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  85. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  86. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  87. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  88. package/src/channels/adapters/slack-bot-edit.ts +85 -20
  89. package/src/channels/adapters/slack-bot.ts +26 -10
  90. package/src/channels/adapters/slack-classify.ts +21 -2
  91. package/src/channels/adapters/slack-format.ts +245 -0
  92. package/src/channels/adapters/slack.ts +59 -7
  93. package/src/channels/adapters/telegram-bot.ts +18 -5
  94. package/src/channels/adapters/webex-bot.ts +8 -3
  95. package/src/channels/adapters/webex.ts +8 -3
  96. package/src/channels/fetch-attachment.ts +43 -0
  97. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  98. package/src/channels/github-token-bridge.ts +12 -6
  99. package/src/channels/manager.ts +9 -0
  100. package/src/channels/router.ts +248 -6
  101. package/src/channels/types.ts +28 -1
  102. package/src/cli/channel.ts +1 -1
  103. package/src/cli/init.ts +1 -1
  104. package/src/cli/model.ts +57 -7
  105. package/src/compose/stop.ts +17 -5
  106. package/src/config/config.ts +6 -6
  107. package/src/config/models-mutation.ts +13 -1
  108. package/src/config/providers.ts +176 -0
  109. package/src/container/docker-app.ts +42 -13
  110. package/src/container/start.ts +62 -10
  111. package/src/cron/bridge.ts +9 -2
  112. package/src/doctor/checks.ts +8 -3
  113. package/src/doctor/commit.ts +2 -1
  114. package/src/doctor/file-ownership.ts +52 -0
  115. package/src/dreams/git.ts +2 -1
  116. package/src/git/bound-gc-config.ts +82 -0
  117. package/src/git/hookless.ts +5 -0
  118. package/src/git/reconcile-ignored.ts +18 -5
  119. package/src/git/system-commit.ts +12 -6
  120. package/src/hostd/spawn.ts +133 -47
  121. package/src/init/dockerfile.ts +99 -5
  122. package/src/init/index.ts +17 -5
  123. package/src/init/models-dev.ts +4 -0
  124. package/src/init/validate-api-key.ts +2 -0
  125. package/src/inspect/replay.ts +21 -9
  126. package/src/inspect/session-list.ts +71 -33
  127. package/src/mcp/tools.ts +17 -3
  128. package/src/network/internal-destinations.ts +267 -0
  129. package/src/permissions/builtins.ts +3 -1
  130. package/src/plugin/context.ts +2 -0
  131. package/src/plugin/index.ts +1 -0
  132. package/src/plugin/manager.ts +4 -0
  133. package/src/plugin/types.ts +22 -0
  134. package/src/run/index.ts +40 -0
  135. package/src/run/llm-fetch-observer.ts +41 -4
  136. package/src/sandbox/build.ts +37 -15
  137. package/src/sandbox/canonical-secrets.ts +18 -0
  138. package/src/sandbox/env-exposure.ts +83 -0
  139. package/src/sandbox/errors.ts +13 -6
  140. package/src/sandbox/hidden-paths.ts +102 -44
  141. package/src/sandbox/index.ts +22 -4
  142. package/src/sandbox/package-install.ts +3 -27
  143. package/src/sandbox/policy.ts +16 -28
  144. package/src/sandbox/privileged-runtime.ts +256 -0
  145. package/src/sandbox/session-tmp.ts +8 -2
  146. package/src/sandbox/writable-zones.ts +204 -140
  147. package/src/secrets/index.ts +8 -0
  148. package/src/secrets/refresh-provider-oauth.ts +128 -0
  149. package/src/server/command-runner.ts +48 -4
  150. package/src/server/index.ts +4 -0
  151. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  152. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  153. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  154. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  155. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  156. package/src/skills/typeclaw-config/SKILL.md +27 -11
  157. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  158. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  159. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  160. package/src/skills/typeclaw-permissions/SKILL.md +36 -19
  161. package/src/skills/typeclaw-plugins/SKILL.md +37 -0
  162. package/src/usage/scan.ts +11 -2
  163. package/typeclaw.schema.json +25 -0
@@ -9,7 +9,7 @@ export type SandboxNetwork = 'none' | 'inherit'
9
9
  // 'proc-bind' (the runtime default): --ro-bind /proc /proc binds the container's
10
10
  // ALREADY-REAL procfs straight into the sandbox — no `unshare --mount-proc`, no
11
11
  // CAP_SYS_ADMIN. A JS package runner's child gets a real /proc/self/{fd,maps,exe}
12
- // so `bunx`/`bun add`/`bun run <pkg-bin>` stop aborting with Bun's ENOTDIR. The
12
+ // so allowed `bunx`/`bun run <pkg-bin>` calls stop aborting with Bun's ENOTDIR. The
13
13
  // agent runtime's /proc/<agent>/environ (OPENAI_API_KEY, GH_TOKEN) is NOT
14
14
  // leaked: build.ts always emits --unshare-user, so the sandboxed bash runs as
15
15
  // mapped-root in a CHILD user namespace that is not an ancestor of the agent
@@ -37,6 +37,11 @@ export type SandboxProcStrategy = 'tmpfs' | 'none' | 'real-proc' | 'proc-bind'
37
37
  export type SandboxEnvPolicy = {
38
38
  set?: Record<string, string>
39
39
  passthrough?: string[]
40
+ // Preserve these names from bwrap's parent environment without rendering
41
+ // their values in argv. The builder switches from --clearenv to explicit
42
+ // --unsetenv for every other inherited name. Reserved for command-scoped
43
+ // secrets whose parent process is protected by the child-userns boundary.
44
+ inherit?: string[]
40
45
  }
41
46
 
42
47
  export type SandboxCommandFilter = {
@@ -94,36 +99,18 @@ export type SandboxSymlinkOp = {
94
99
  dest: string
95
100
  }
96
101
 
97
- // A single RW bind of the project root, used ONLY by the package-install path
98
- // (recognized standalone `bun add`/`bun install` commands). `bun add` writes
99
- // node_modules/ AND a temp lockfile (`bun.lock.NNN.tmp`, atomically renamed)
100
- // directly under the root, so a file-level RW bind of `bun.lock` alone is
101
- // insufficient — Bun needs DIRECTORY write to create its temp file. The default
102
- // ro-root + narrow carve-out model can't express that, so this widens the root
103
- // to RW for that command class only.
102
+ // A single RW bind that preserves ordinary agent-root writes for trusted/owner
103
+ // callers. Masks and protected zones overlay it; writableRoot provides no
104
+ // package-install isolation.
104
105
  //
105
106
  // CRITICAL ordering: unlike `writable` (rendered AFTER masks), `writableRoot`
106
107
  // renders BEFORE masks so the broad RW root does not re-expose secrets. With
107
108
  // last-op-wins the chain is: ro-bind root → writableRoot (RW root) → masks
108
- // (re-hide .env/secrets.json/private dirs) → protected (re-RO node_modules/typeclaw,
109
- // packages, .agents/skills, .git/hooks, .git/config). Everything stays hidden or
110
- // EROFS except the dirs a dependency install legitimately needs to write.
109
+ // (re-hide .env/secrets.json/private dirs) → protected (.git/hooks/.git/config).
111
110
  export type SandboxWritableRootPolicy = {
112
111
  dir: string
113
112
  }
114
113
 
115
- // Paths whose CREATION must be blocked under a writable root, rendered as
116
- // `--ro-bind /dev/null <path>`. Used by the package-install path for the
117
- // semantically-guarded managed files (cron.json / typeclaw.json) when they are
118
- // ABSENT: the RW root would otherwise let a postinstall lifecycle script create
119
- // them, bypassing the write/edit-tool guards. Binding /dev/null occupies the
120
- // path with an empty read-only object (blocking creation) WITHOUT manufacturing
121
- // a real invalid file on the host FS. Renders after writableRoot, with the
122
- // protected binds, so last-op-wins keeps the path occupied.
123
- export type SandboxBlockedCreationPolicy = {
124
- files?: string[]
125
- }
126
-
127
114
  export type SandboxPolicy = {
128
115
  bwrapPath?: string
129
116
  cwd?: string
@@ -140,7 +127,6 @@ export type SandboxPolicy = {
140
127
  masks?: SandboxMaskPolicy
141
128
  writable?: SandboxWritablePolicy
142
129
  protected?: SandboxProtectedPolicy
143
- blockedCreation?: SandboxBlockedCreationPolicy
144
130
  symlinks?: SandboxSymlinkOp[]
145
131
  network?: SandboxNetwork
146
132
  env?: SandboxEnvPolicy
@@ -151,14 +137,16 @@ export type SandboxPolicy = {
151
137
 
152
138
  // The env the sandbox always re-introduces after `--clearenv`. Anything not
153
139
  // listed here (or explicitly named in `env.set` / `env.passthrough` by the
154
- // consumer) is invisible inside the sandbox. This is the load-bearing leak
155
- // guard: the container env holds OPENAI_API_KEY and GH_TOKEN, and env
156
- // inheritance is the single highest-risk exfil path for prompt-injected bash.
140
+ // consumer — including operator `.env` vars re-introduced via inherit) is
141
+ // invisible inside the sandbox. This is the load-bearing leak guard: the
142
+ // container env holds credentials the operator never declared in `.env` (e.g.
143
+ // OPENAI_API_KEY, host-injected TYPECLAW_* tokens), and env inheritance is the
144
+ // single highest-risk exfil path for prompt-injected bash.
157
145
  // HOME points at /tmp because the sandbox mounts /tmp as a fresh tmpfs.
158
146
  //
159
147
  // BUN_TMPDIR / BUN_INSTALL both point under /tmp because `--clearenv` strips
160
148
  // the host's TMPDIR, and bun refuses to run without a writable scratch dir it
161
- // can discover: `bunx`, `bun add`, and `bun run <pkg-bin>` abort with
149
+ // can discover: `bunx` and `bun run <pkg-bin>` abort with
162
150
  // "Unexpected accessing temporary directory. Please set $BUN_TMPDIR or
163
151
  // $BUN_INSTALL". /tmp is always writable inside the sandbox (fresh tmpfs, or
164
152
  // the per-session bind that overrides it), so both are safe targets. Without
@@ -0,0 +1,256 @@
1
+ import { chmod, lstat, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2
+ import { homedir, tmpdir } from 'node:os'
3
+ import path from 'node:path'
4
+
5
+ import { SandboxPolicyError } from './errors'
6
+ import type { SandboxMount } from './policy'
7
+
8
+ const SAFE_GIT_SUBCOMMANDS = new Set([
9
+ 'add',
10
+ 'branch',
11
+ 'checkout',
12
+ 'cherry-pick',
13
+ 'commit',
14
+ 'diff',
15
+ 'log',
16
+ 'merge',
17
+ 'rebase',
18
+ 'remote',
19
+ 'reset',
20
+ 'restore',
21
+ 'rev-parse',
22
+ 'show',
23
+ 'stash',
24
+ 'status',
25
+ 'switch',
26
+ 'symbolic-ref',
27
+ 'tag',
28
+ 'worktree',
29
+ ])
30
+
31
+ const SHELL_ACTIVE = new Set(['|', ';', '&', '\n', '\r', '(', ')', '{', '}', '<', '>', '`', '$', '\\'])
32
+
33
+ export type PrivilegedSandboxRuntime = {
34
+ env: Record<string, string>
35
+ mounts: SandboxMount[]
36
+ }
37
+
38
+ type StandaloneCommand = { executable: string; args: string[] }
39
+ type MountedIdentity = { birthtimeNs: bigint; ctimeNs: bigint; dev: bigint; ino: bigint }
40
+ const mountedIdentities = new WeakMap<PrivilegedSandboxRuntime, Map<string, MountedIdentity>>()
41
+ const cleanupDirs = new WeakMap<PrivilegedSandboxRuntime, Set<string>>()
42
+
43
+ export async function resolvePrivilegedSandboxRuntime(options: {
44
+ agentDir: string
45
+ command: string
46
+ env?: NodeJS.ProcessEnv
47
+ homeDir?: string
48
+ }): Promise<PrivilegedSandboxRuntime> {
49
+ const runtime = emptyRuntime()
50
+ // TYPECLAW_GIT_TOKEN is set only after the auth analyzer accepts a Git command.
51
+ // Trust that decision rather than reparsing its command with a less capable
52
+ // detector (notably, the analyzer accepts quoted `git` executables).
53
+ if (options.env?.TYPECLAW_GIT_TOKEN !== undefined || containsGitInvocation(options.command)) {
54
+ runtime.env.HOME = options.agentDir
55
+ runtime.env.GIT_CONFIG_GLOBAL = '/dev/null'
56
+ runtime.env.GIT_CONFIG_NOSYSTEM = '1'
57
+ }
58
+ const parsed = parseStandaloneCommand(options.command)
59
+ if (parsed === null) return runtime
60
+
61
+ const homeDir = options.homeDir ?? homedir()
62
+ const executable = unwrapBunx(parsed)
63
+ if (executable === null) return runtime
64
+
65
+ // These CLIs can print or upload arbitrary files. Supplying their reusable
66
+ // auth profile to a model-controlled child would therefore make the CLI a
67
+ // confused deputy even when the outer shell is syntactically standalone.
68
+ if (
69
+ executable.executable === 'gws' ||
70
+ executable.executable === 'codex' ||
71
+ executable.executable === 'claude' ||
72
+ executable.executable.startsWith('agent-')
73
+ ) {
74
+ return runtime
75
+ }
76
+
77
+ if (executable.executable === 'git') {
78
+ runtime.env.GIT_CONFIG_GLOBAL = '/dev/null'
79
+ runtime.env.GIT_CONFIG_NOSYSTEM = '1'
80
+ const subcommand = gitSubcommand(executable.args)
81
+ if (subcommand === null) return runtime
82
+ rejectNamedSubcommand(subcommand, new Set(['config', 'credential', 'credential-cache', 'credential-store']))
83
+ if (!SAFE_GIT_SUBCOMMANDS.has(subcommand)) return runtime
84
+ try {
85
+ await addSanitizedGitIdentity(runtime, path.join(homeDir, '.gitconfig'))
86
+ } catch (error) {
87
+ await cleanupPrivilegedSandboxRuntime(runtime)
88
+ throw error
89
+ }
90
+ }
91
+
92
+ return runtime
93
+ }
94
+
95
+ function containsGitInvocation(command: string): boolean {
96
+ return /(^|[;&|]\s*)git(?:\s|$)/.test(command.trim())
97
+ }
98
+
99
+ export async function verifyPrivilegedSandboxRuntime(runtime: PrivilegedSandboxRuntime): Promise<void> {
100
+ const identities = mountedIdentities.get(runtime) ?? new Map()
101
+ for (const mount of runtime.mounts) {
102
+ if (mount.type !== 'ro-bind') continue
103
+ const safe = await lstat(mount.source, { bigint: true })
104
+ .then(async (stats) => {
105
+ if (stats.isSymbolicLink()) return false
106
+ const expected = identities.get(mount.source)
107
+ return (
108
+ stats.isFile() &&
109
+ stats.nlink === 1n &&
110
+ expected !== undefined &&
111
+ stats.dev === expected.dev &&
112
+ stats.ino === expected.ino &&
113
+ stats.ctimeNs === expected.ctimeNs &&
114
+ stats.birthtimeNs === expected.birthtimeNs
115
+ )
116
+ })
117
+ .catch(() => false)
118
+ if (!safe) {
119
+ throw new SandboxPolicyError(`credential profile changed after validation: ${mount.source}. Refusing to run.`)
120
+ }
121
+ }
122
+ }
123
+
124
+ export async function cleanupPrivilegedSandboxRuntime(runtime: PrivilegedSandboxRuntime): Promise<void> {
125
+ const dirs = cleanupDirs.get(runtime) ?? new Set()
126
+ const outcomes = await Promise.allSettled([...dirs].map((dir) => rm(dir, { recursive: true, force: true })))
127
+ dirs.clear()
128
+ const failed = outcomes.find((outcome) => outcome.status === 'rejected')
129
+ if (failed?.status === 'rejected') throw failed.reason
130
+ }
131
+
132
+ function emptyRuntime(): PrivilegedSandboxRuntime {
133
+ const runtime = { env: {}, mounts: [] }
134
+ mountedIdentities.set(runtime, new Map())
135
+ cleanupDirs.set(runtime, new Set())
136
+ return runtime
137
+ }
138
+
139
+ function unwrapBunx(command: StandaloneCommand): StandaloneCommand | null {
140
+ if (command.executable !== 'bunx') return command
141
+ const args = [...command.args]
142
+ if (args[0] === '--bun') args.shift()
143
+ const executable = args.shift()
144
+ return executable === undefined ? null : { executable, args }
145
+ }
146
+
147
+ function rejectNamedSubcommand(subcommand: string, denied: ReadonlySet<string>): void {
148
+ if (denied.has(subcommand)) {
149
+ throw new SandboxPolicyError(
150
+ `credential or token management command \`${subcommand}\` is unavailable to model-driven bash; use a host-side login or redacted status command instead.`,
151
+ )
152
+ }
153
+ }
154
+
155
+ function gitSubcommand(args: readonly string[]): string | null {
156
+ for (let i = 0; i < args.length; i++) {
157
+ const arg = args[i] as string
158
+ if (arg === '-C') {
159
+ i += 1
160
+ continue
161
+ }
162
+ if (arg === '-c' || arg === '--config-env' || arg.startsWith('--config-env=')) return null
163
+ if (arg.startsWith('-')) continue
164
+ return arg
165
+ }
166
+ return null
167
+ }
168
+
169
+ async function addSanitizedGitIdentity(runtime: PrivilegedSandboxRuntime, source: string): Promise<void> {
170
+ const raw = await readFile(source, 'utf8').catch((error) => {
171
+ if (isNotFoundError(error)) return ''
172
+ throw error
173
+ })
174
+ if (raw === '') return
175
+ const values = parseGitUserIdentity(raw)
176
+ if (values.length === 0) return
177
+ const dir = await mkdtemp(path.join(tmpdir(), 'typeclaw-git-identity-'))
178
+ cleanupDirs.get(runtime)?.add(dir)
179
+ const generated = path.join(dir, 'config')
180
+ await writeFile(generated, `[user]\n${values.map(([key, value]) => `\t${key} = ${value}`).join('\n')}\n`, {
181
+ flag: 'wx',
182
+ })
183
+ await chmod(generated, 0o600)
184
+ const stats = await lstat(generated, { bigint: true })
185
+ mountedIdentities.get(runtime)?.set(generated, {
186
+ birthtimeNs: stats.birthtimeNs,
187
+ ctimeNs: stats.ctimeNs,
188
+ dev: stats.dev,
189
+ ino: stats.ino,
190
+ })
191
+ runtime.mounts.push({ type: 'ro-bind', source: generated, dest: '/tmp/.gitconfig' })
192
+ runtime.env.GIT_CONFIG_GLOBAL = '/tmp/.gitconfig'
193
+ }
194
+
195
+ function parseGitUserIdentity(raw: string): Array<['name' | 'email', string]> {
196
+ const values = new Map<'name' | 'email', string>()
197
+ let inUser = false
198
+ for (const line of raw.split(/\r?\n/)) {
199
+ const section = line.match(/^\s*\[([^\]]+)]\s*$/)
200
+ if (section !== null) {
201
+ inUser = section[1]?.trim().toLocaleLowerCase() === 'user'
202
+ continue
203
+ }
204
+ if (!inUser) continue
205
+ const entry = line.match(/^\s*(name|email)\s*=\s*(.*?)\s*$/i)
206
+ if (entry === null || entry[2] === undefined) continue
207
+ const key = entry[1]?.toLocaleLowerCase() as 'name' | 'email'
208
+ const value = entry[2].replaceAll('\r', '').replaceAll('\n', '').replaceAll('\0', '')
209
+ if (value !== '') values.set(key, value)
210
+ }
211
+ return [...values.entries()]
212
+ }
213
+
214
+ function parseStandaloneCommand(command: string): StandaloneCommand | null {
215
+ const words: string[] = []
216
+ let word = ''
217
+ let quote: "'" | '"' | null = null
218
+ let active = false
219
+ for (const ch of command.trim()) {
220
+ if (quote === "'") {
221
+ if (ch === "'") quote = null
222
+ else word += ch
223
+ continue
224
+ }
225
+ if (quote === '"') {
226
+ if (ch === '"') quote = null
227
+ else if (ch === '$' || ch === '`' || ch === '\\') return null
228
+ else word += ch
229
+ continue
230
+ }
231
+ if (ch === "'" || ch === '"') {
232
+ quote = ch
233
+ active = true
234
+ continue
235
+ }
236
+ if (SHELL_ACTIVE.has(ch)) return null
237
+ if (/\s/.test(ch)) {
238
+ if (active) {
239
+ words.push(word)
240
+ word = ''
241
+ active = false
242
+ }
243
+ continue
244
+ }
245
+ word += ch
246
+ active = true
247
+ }
248
+ if (quote !== null) return null
249
+ if (active) words.push(word)
250
+ const executable = words.shift()
251
+ return executable === undefined ? null : { executable, args: words }
252
+ }
253
+
254
+ function isNotFoundError(error: unknown): boolean {
255
+ return error instanceof Error && 'code' in error && error.code === 'ENOENT'
256
+ }
@@ -27,7 +27,7 @@ export async function ensureSessionTmpDir(sessionId: string): Promise<string> {
27
27
 
28
28
  export function isUnderTmp(agentDir: string, rawPath: string): boolean {
29
29
  const resolved = resolve(agentDir, rawPath)
30
- return resolved === '/tmp' || isInside('/tmp', resolved)
30
+ return isVirtualTmpPath(agentDir, resolved)
31
31
  }
32
32
 
33
33
  // Maps a model-facing /tmp path to its per-session backing path. Returns
@@ -37,11 +37,17 @@ export function isUnderTmp(agentDir: string, rawPath: string): boolean {
37
37
  // for the sandboxed bash that reads it back.
38
38
  export function mapVirtualTmpPath(agentDir: string, sessionId: string, rawPath: string): string | undefined {
39
39
  const resolved = resolve(agentDir, rawPath)
40
- if (resolved !== '/tmp' && !isInside('/tmp', resolved)) return undefined
40
+ if (!isVirtualTmpPath(agentDir, resolved)) return undefined
41
41
  const rel = relative('/tmp', resolved)
42
42
  return rel === '' ? sessionTmpDir(sessionId) : join(sessionTmpDir(sessionId), rel)
43
43
  }
44
44
 
45
+ function isVirtualTmpPath(agentDir: string, resolved: string): boolean {
46
+ const resolvedAgentDir = resolve(agentDir)
47
+ if (resolved === resolvedAgentDir || isInside(resolvedAgentDir, resolved)) return false
48
+ return resolved === '/tmp' || isInside('/tmp', resolved)
49
+ }
50
+
45
51
  function isInside(parent: string, child: string): boolean {
46
52
  const rel = relative(parent, child)
47
53
  return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)