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
@@ -1,12 +1,21 @@
1
1
  import { TYPECLAW_INTERNAL_BASH_ENV } from '@/agent/plugin-tools'
2
2
  import type { SessionOrigin } from '@/agent/session-origin'
3
+ import {
4
+ configureReviewVerdictCoordinator,
5
+ createSharedReviewVerdictGuard,
6
+ } from '@/channels/github-review-verdict-coordinator'
7
+ import { hasEnvKey } from '@/init/env-file'
8
+ import { CORE_PERMISSIONS } from '@/permissions/builtins'
3
9
  import { definePlugin } from '@/plugin'
4
- import { resolveHiddenPaths } from '@/sandbox'
5
10
 
6
- import { createApproveIdempotencyGuard } from './approve-idempotency'
7
11
  import { createGithubEffectiveApprovalResolver, createGithubHeadShaResolver } from './effective-approval'
8
- import { analyzeGhCommand, effectiveGhTokensForAuthenticatedUserEndpoint } from './gh-command'
9
- import { ensureGitAskPassHelper } from './git-askpass'
12
+ import {
13
+ analyzeGhCommand,
14
+ canInjectPatIntoPassThroughGh,
15
+ effectiveGhTokensForAuthenticatedUserEndpoint,
16
+ usesGhApiGraphqlEndpoint,
17
+ } from './gh-command'
18
+ import { ensureGitAskPassHelper, resolveSandboxGitAskPassPath } from './git-askpass'
10
19
  import { analyzeGitCommand, defaultGitResolvers, resolveGhDefaultRepoFromCwd } from './git-command'
11
20
  import { checkGraphqlAuthNudge } from './graphql-auth-nudge'
12
21
  import { commitReviewIfSucceeded, noteReviewCommand } from './review-recorder'
@@ -17,28 +26,66 @@ export default definePlugin({
17
26
  const resolveTokenForRepo = ctx.github.resolveTokenForRepo
18
27
  const hasAppTokenResolver = ctx.github.hasAppTokenResolver
19
28
 
20
- // A .env PAT is broad and long-lived, so it may only reach bash that runs
21
- // WITHOUT bwrap's --clearenv — otherwise a low-trust, stranger-drivable
22
- // sandbox could exfiltrate it. We gate on the SAME signal applyBashSandbox
23
- // uses (resolveHiddenPaths empty => unsandboxed) rather than a role name, so
24
- // the credential policy can never diverge from the actual sandbox decision
25
- // and custom roles follow their real fs.see.secrets / security.bypass grant.
26
- const runsUnsandboxed = (origin: SessionOrigin | undefined): boolean => {
27
- const { dirs, files } = resolveHiddenPaths(ctx.permissions, origin, ctx.agentDir)
28
- return dirs.length === 0 && files.length === 0
29
+ // Every model-driven bash masks the canonical credential files. A role may
30
+ // still USE a PAT through this runtime-owned overlay, which injects one
31
+ // value without exposing .env/secrets.json to the model. Gate that on the
32
+ // existing credential capability rather than sandbox presence: privileged
33
+ // roles are sandboxed for file masking too.
34
+ const canUsePat = (origin: SessionOrigin | undefined): boolean =>
35
+ ctx.permissions.has(origin, CORE_PERMISSIONS.fsSeeSecrets) ||
36
+ ctx.permissions.has(origin, 'security.bypass.medium')
37
+
38
+ const effectiveProcessToken = (): { envName: 'GH_TOKEN' | 'GITHUB_TOKEN'; value: string } | undefined => {
39
+ if (process.env.GH_TOKEN !== undefined && process.env.GH_TOKEN !== '') {
40
+ return { envName: 'GH_TOKEN', value: process.env.GH_TOKEN }
41
+ }
42
+ if (process.env.GITHUB_TOKEN !== undefined && process.env.GITHUB_TOKEN !== '') {
43
+ return { envName: 'GITHUB_TOKEN', value: process.env.GITHUB_TOKEN }
44
+ }
45
+ return undefined
46
+ }
47
+
48
+ const processPatOverlay = (): Record<string, string> | undefined => {
49
+ const token = effectiveProcessToken()
50
+ if (token === undefined) return undefined
51
+ const tokenClass = classifyGhToken(token.value)
52
+ return tokenClass === 'cross-owner' || tokenClass === 'fine-grained-pat'
53
+ ? { [token.envName]: token.value }
54
+ : undefined
29
55
  }
30
56
 
31
- // The PAT is in the container env but stripped by --clearenv for this role,
32
- // and a PAT is not re-mintable per repo, so there is no token to inject. Tell
33
- // the AGENT (model-visible block) instead of letting git/gh fail ambiguously
34
- // — the silent variant of this is exactly what caused a multi-day debugging
35
- // hunt. App auth is the supported path for low-trust roles.
57
+ // The token `gh` will actually resolve INSIDE the low-trust sandbox. Only
58
+ // `.env`-declared names survive `--clearenv` (`hasEnvKey` reads the same
59
+ // `readEnvFile(agentDir)` parse the sandbox's `resolveExposableEnvNames` uses,
60
+ // so this is congruent with what the sandbox inherits), and gh's precedence is
61
+ // GH_TOKEN > GITHUB_TOKEN. So a process-only GH_TOKEN does NOT mask an
62
+ // inheritable, operator-declared GITHUB_TOKEN: the process-only name is cleared,
63
+ // leaving the declared alias as the one gh sees. Returns the surviving PAT/App
64
+ // token (value snapshotted from process.env, which holds the declared value),
65
+ // or undefined when the operator declared no usable GitHub token in `.env`.
66
+ const sandboxInheritedGhToken = (): { envName: 'GH_TOKEN' | 'GITHUB_TOKEN'; value: string } | undefined => {
67
+ for (const envName of ['GH_TOKEN', 'GITHUB_TOKEN'] as const) {
68
+ if (!hasEnvKey(ctx.agentDir, envName)) continue
69
+ const value = process.env[envName]
70
+ if (value !== undefined && value !== '') return { envName, value }
71
+ }
72
+ return undefined
73
+ }
74
+
75
+ // A process-only PAT (runtime/App-seeded process.env, NOT declared in `.env`)
76
+ // is stripped by --clearenv for this role, and a PAT is not re-mintable per
77
+ // repo, so there is no token to inject. Tell the AGENT (model-visible block)
78
+ // instead of letting git/gh fail ambiguously — the silent variant of this is
79
+ // exactly what caused a multi-day debugging hunt. This does NOT fire for a PAT
80
+ // the operator declared in `.env`: that one is inherited into the sandbox and
81
+ // handled by the allow-path above.
36
82
  const sandboxedPatWithheldReason =
37
- 'A classic/fine-grained GitHub PAT is configured (via .env GH_TOKEN), but this command runs ' +
38
- 'in a sandboxed (low-trust) role whose environment is cleared before bash — so the PAT is ' +
39
- 'withheld here and is NOT available to git/gh. This is a deliberate guard, not missing auth: a ' +
40
- 'broad, long-lived PAT must not be reachable from a low-trust sandbox. Configure GitHub App auth ' +
41
- '(channels.github) to grant per-repo, short-lived tokens that DO work for sandboxed roles.'
83
+ 'A classic/fine-grained GitHub PAT is present in the runtime environment but was NOT declared ' +
84
+ 'in `.env`, and this command runs in a sandboxed (low-trust) role whose environment is cleared ' +
85
+ 'before bash — so the PAT is withheld here and is NOT available to git/gh. This is a deliberate ' +
86
+ 'guard, not missing auth: a broad, long-lived runtime PAT must not be reachable from a low-trust ' +
87
+ 'sandbox. Configure GitHub App auth (channels.github) for per-repo, short-lived tokens that work ' +
88
+ 'for sandboxed roles, or declare the PAT in `.env` to deliberately expose it to model bash.'
42
89
 
43
90
  let warnedSandboxedPatWithheld = false
44
91
  const warnSandboxedPatWithheldOnce = (): void => {
@@ -61,14 +108,24 @@ export default definePlugin({
61
108
  'scoped calls still work). It is not a valid auth/login check. For repo data use ' +
62
109
  '`gh <cmd> -R owner/repo` or `gh api /repos/owner/repo/...`; for the actor, read the ' +
63
110
  'PR/issue/comment context you were given instead of `gh api /user`.'
111
+ const patGraphqlReason =
112
+ 'Model-driven `gh api graphql` cannot receive a classic or fine-grained GitHub PAT because the query can ' +
113
+ 'target repositories that are not visible in argv; `-R owner/repo` is only a CLI hint, not an authorization ' +
114
+ 'boundary. Configure GitHub App auth so TypeClaw can mint a server-enforced single-repository installation ' +
115
+ 'token, use a statically repo-confined REST endpoint, or run the PAT-backed GraphQL command host-side.'
64
116
  const resolveToken = async (workspace: string) => {
65
117
  const result = await resolveTokenForRepo(workspace)
66
118
  return result.kind === 'token' ? result.token : null
67
119
  }
68
- const verdictGuard = createApproveIdempotencyGuard({
69
- resolveEffectiveApproval: createGithubEffectiveApprovalResolver({ resolveToken }),
120
+ configureReviewVerdictCoordinator({
121
+ resolveEffectiveApproval: createGithubEffectiveApprovalResolver({
122
+ resolveToken,
123
+ selfLogin: ctx.github.getAppSelfLogin ?? (() => null),
124
+ isAppAuth: hasAppTokenResolver,
125
+ }),
70
126
  resolveHeadSha: createGithubHeadShaResolver({ resolveToken }),
71
127
  })
128
+ const verdictGuard = createSharedReviewVerdictGuard()
72
129
 
73
130
  type HookResult = void | { block: true; reason: string }
74
131
 
@@ -108,31 +165,6 @@ export default definePlugin({
108
165
  command: string
109
166
  }): Promise<HookResult | 'fall-through'> => {
110
167
  const { event, command } = params
111
- const review = await noteReviewCommand({ callId: event.callId, command })
112
- // guard() holds the lease expecting tool.after to release it, but a
113
- // tool.before block (from ANY guard below) means the command never runs, so
114
- // tool.after never fires and the lease strands for its full TTL — telling
115
- // every other session "the in-flight one will post" when it never will (the
116
- // lost-verdict strand: a review trips the shape guard, the lease strands, the
117
- // PR ends unreviewed). blockAfterLease() releases on such a block. guard()'s
118
- // OWN terminal block self-releases and returns directly, bypassing this path.
119
- let leaseClaimed = false
120
- const blockAfterLease = async (block: HookResult & { block: true }): Promise<HookResult> => {
121
- if (leaseClaimed) await verdictGuard.release({ callId: event.callId, succeeded: false })
122
- return block
123
- }
124
- if (review.detected !== null) {
125
- const block = await verdictGuard.guard({
126
- callId: event.callId,
127
- workspace: review.detected.workspace,
128
- prNumber: review.detected.prNumber,
129
- verdict: review.detected.verdict,
130
- })
131
- if (block !== null) return block
132
- leaseClaimed = true
133
- }
134
- if (review.dump !== null) return blockAfterLease(review.dump)
135
-
136
168
  // Analyze first WITHOUT the fallback: an explicit `-R`/path repo must win,
137
169
  // and we only pay for fallback resolution (a git subprocess) when the
138
170
  // command is otherwise repo-less. A trusted fallback is then applied ONLY to
@@ -154,6 +186,42 @@ export default definePlugin({
154
186
  }
155
187
  }
156
188
 
189
+ // Reject every statically unsafe/conflicting shape before review detection.
190
+ // noteReviewCommand may open an --input file, and verdictGuard.guard performs
191
+ // authenticated GitHub reads through the token resolver; neither may run for
192
+ // a command the argv/repository authorization layer already rejects.
193
+ if (decision.kind === 'block') {
194
+ return {
195
+ block: true,
196
+ reason:
197
+ decision.code === 'credential-display'
198
+ ? decision.reason
199
+ : decision.reason + buildGhBlockGuidance(decision.code, fallbackRepo),
200
+ }
201
+ }
202
+
203
+ const review = await noteReviewCommand({ callId: event.callId, command })
204
+ // guard() holds the lease expecting tool.after to release it. A later
205
+ // tool.before block means tool.after never fires, so blockAfterLease()
206
+ // releases the lease with succeeded:false. The static command analyzer runs
207
+ // above and never claims a lease for a command it will reject.
208
+ let leaseClaimed = false
209
+ const blockAfterLease = async (block: HookResult & { block: true }): Promise<HookResult> => {
210
+ if (leaseClaimed) await verdictGuard.release({ callId: event.callId, succeeded: false })
211
+ return block
212
+ }
213
+ if (review.detected !== null) {
214
+ const block = await verdictGuard.guard({
215
+ callId: event.callId,
216
+ workspace: review.detected.workspace,
217
+ prNumber: review.detected.prNumber,
218
+ verdict: review.detected.verdict,
219
+ })
220
+ if (block !== null) return block
221
+ leaseClaimed = true
222
+ }
223
+ if (review.dump !== null) return blockAfterLease(review.dump)
224
+
157
225
  // `/user` classifies as pass-through (no repo to mint for), so this block
158
226
  // must run BEFORE the pass-through return. Resolve the EFFECTIVE token per
159
227
  // `/user` invocation (a command-local `GH_TOKEN=…`/`GITHUB_TOKEN=…` overrides
@@ -168,7 +236,33 @@ export default definePlugin({
168
236
  return blockAfterLease({ block: true, reason: appUserEndpointReason })
169
237
  }
170
238
 
171
- if (decision.kind === 'pass-through') return 'fall-through'
239
+ const processToken = effectiveProcessToken()
240
+ const tokenClass = classifyGhToken(processToken?.value)
241
+ if (
242
+ (tokenClass === 'cross-owner' || tokenClass === 'fine-grained-pat') &&
243
+ canUsePat(event.origin) &&
244
+ usesGhApiGraphqlEndpoint(command)
245
+ ) {
246
+ return blockAfterLease({ block: true, reason: patGraphqlReason })
247
+ }
248
+
249
+ if (decision.kind === 'pass-through') {
250
+ const patOverlay = canUsePat(event.origin) ? processPatOverlay() : undefined
251
+ if (patOverlay !== undefined) {
252
+ if (!canInjectPatIntoPassThroughGh(command)) {
253
+ return blockAfterLease({
254
+ block: true,
255
+ reason:
256
+ 'A GitHub PAT can only be brokered to a single standalone known-safe `gh` command. ' +
257
+ 'Chaining, substitution, aliases, extensions, and config/auth management are blocked because a sibling or plugin could read the command-scoped token.',
258
+ })
259
+ }
260
+ const existing = event.args[TYPECLAW_INTERNAL_BASH_ENV]
261
+ const overlay = existing !== null && typeof existing === 'object' ? (existing as Record<string, string>) : {}
262
+ event.args[TYPECLAW_INTERNAL_BASH_ENV] = { ...overlay, ...patOverlay }
263
+ }
264
+ return 'fall-through'
265
+ }
172
266
 
173
267
  // The `-R` strip is a pure syntax fix (`gh api` rejects `-R`), independent
174
268
  // of token minting, so apply it for EVERY token class — including the PAT
@@ -179,62 +273,64 @@ export default definePlugin({
179
273
  event.args.command = decision.rewrittenCommand
180
274
  }
181
275
 
182
- const tokenClass = classifyGhToken(process.env.GH_TOKEN)
276
+ // When NO per-repo App minter is available, prefer the token the operator
277
+ // deliberately exposed via `.env`: the sandbox inherits it into bash for
278
+ // EVERY role, so the validated command just runs on it — no block, no
279
+ // overlay except GH_REPO (non-secret) for a trusted-fallback repo. This runs
280
+ // BEFORE the process-token-class branches so it is independent of gh's
281
+ // GH_TOKEN>GITHUB_TOKEN process preference: an undeclared (process-only)
282
+ // GH_TOKEN — even App-class `ghs_` — never masks a declared, inheritable
283
+ // GITHUB_TOKEN, because sandboxInheritedGhToken() only considers names that
284
+ // survive --clearenv. When a minter IS available it wins (least-privilege
285
+ // short-lived per-repo token over a broad declared PAT) via the paths below.
286
+ if (!hasAppTokenResolver() && sandboxInheritedGhToken() !== undefined) {
287
+ if (decision.kind === 'inject' && fallbackRepoUsed && fallbackRepo !== undefined) {
288
+ event.args[TYPECLAW_INTERNAL_BASH_ENV] = { GH_REPO: fallbackRepo }
289
+ }
290
+ return
291
+ }
183
292
 
184
293
  // PAT classes (classic = cross-owner, fine-grained) are not re-minted per
185
294
  // repo; the seeded GH_TOKEN is the only token we have. App minting, when
186
- // available, is still preferred for SANDBOXED roles (the PAT can't reach
187
- // them), so a PAT must NOT suppress minting there — only for unsandboxed
188
- // execution does the PAT win. Unsandboxed: the PAT already rides inherited
189
- // process.env, but re-asserting it in the overlay keeps the command-local
190
- // GH_TOKEN explicit and consistent with the git path. Sandboxed PAT-only:
191
- // block with guidance instead of failing silently.
295
+ // available, is preferred for ALL roles (least-privilege per-repo token over
296
+ // a broad PAT), so a PAT must not suppress minting. An entitled role with NO
297
+ // minter receives the PAT through the narrow overlay; raw process.env and
298
+ // credential files remain unavailable inside bash. Sandboxed PAT-only with no
299
+ // minter and no `.env` declaration: block with guidance instead of failing
300
+ // silently.
192
301
  // Set when a sandboxed PAT falls through to App minting: the tail's
193
302
  // shouldMintAppToken(process.env.GH_TOKEN) re-check would see the PAT and
194
303
  // bail, so this flag forces the mint that the PAT must not suppress.
195
304
  let mintForSandboxedPat = false
196
305
  if (tokenClass === 'cross-owner' || tokenClass === 'fine-grained-pat') {
197
- // Unsandboxed: the PAT authenticates directly (it already rides inherited
198
- // process.env). For a repo-targeting command we re-assert it in the
199
- // overlay so behavior is explicit and matches the git path; otherwise we
200
- // pass through. The App-oriented missing-repo / multi-owner BLOCK does
201
- // NOT apply — a PAT needs no per-repo mint — so we never surface it here.
202
- if (runsUnsandboxed(event.origin)) {
306
+ // Credential-entitled role, NO App minter: inject the PAT through the
307
+ // runtime-owned overlay. Gated on `!hasAppTokenResolver()` — when a minter
308
+ // is available it wins, so a declared/entitled PAT does not beat the
309
+ // least-privilege per-repo App token; execution falls through to minting.
310
+ if (canUsePat(event.origin) && !hasAppTokenResolver()) {
203
311
  if (decision.kind === 'inject') {
204
312
  event.args[TYPECLAW_INTERNAL_BASH_ENV] = {
205
- GH_TOKEN: process.env.GH_TOKEN as string,
313
+ [processToken?.envName ?? 'GH_TOKEN']: processToken?.value ?? '',
206
314
  ...(fallbackRepoUsed && fallbackRepo !== undefined ? { GH_REPO: fallbackRepo } : {}),
207
315
  }
208
316
  }
209
317
  return
210
318
  }
211
- // Sandboxed: the PAT is stripped by --clearenv. Prefer App minting when
212
- // available (a PAT must NOT suppress it, or the original silent-failure
213
- // bug returns); otherwise block with guidance rather than failing mute.
319
+ // Sandboxed PAT, no minter, not declared in `.env`: the sandbox clears it
320
+ // for this role, so there is no inheritable token. Block with guidance
321
+ // rather than failing mute. (A declared `.env` PAT already returned via the
322
+ // sandbox-inherited allow-path above; an available minter falls through.)
214
323
  if (!shouldMintAppToken(undefined, hasAppTokenResolver())) {
215
- if (decision.kind === 'block') {
216
- return blockAfterLease({
217
- block: true,
218
- reason: decision.reason + buildGhBlockGuidance(decision.code, fallbackRepo),
219
- })
220
- }
221
324
  warnSandboxedPatWithheldOnce()
222
325
  return blockAfterLease({ block: true, reason: sandboxedPatWithheldReason })
223
326
  }
224
327
  mintForSandboxedPat = true
225
328
  }
226
329
 
227
- if (decision.kind === 'block') {
228
- return blockAfterLease({
229
- block: true,
230
- reason: decision.reason + buildGhBlockGuidance(decision.code, fallbackRepo),
231
- })
232
- }
233
-
234
330
  // No App auth (no App-class GH_TOKEN and no live minter): leave whatever
235
331
  // is seeded so `gh` fails honestly rather than us guessing a token. The
236
332
  // sandboxed-PAT mint path bypasses this PAT-class re-check via the flag.
237
- if (!mintForSandboxedPat && !shouldMintAppToken(process.env.GH_TOKEN, hasAppTokenResolver())) return
333
+ if (!mintForSandboxedPat && !shouldMintAppToken(processToken?.value, hasAppTokenResolver())) return
238
334
 
239
335
  const result = await resolveTokenForRepo(decision.repoSlug)
240
336
  if (result.kind === 'unavailable') return blockAfterLease({ block: true, reason: result.reason })
@@ -252,71 +348,50 @@ export default definePlugin({
252
348
  }
253
349
 
254
350
  const handleGitCommand = async (params: {
255
- event: { args: Record<string, unknown>; origin?: SessionOrigin }
351
+ event: { args: Record<string, unknown> }
256
352
  command: string
257
353
  agentDir: string
258
354
  }): Promise<HookResult> => {
259
355
  const { event, command, agentDir } = params
260
- const tokenClass = classifyGhToken(process.env.GH_TOKEN)
261
- const isPat = tokenClass === 'cross-owner' || tokenClass === 'fine-grained-pat'
262
-
263
- // A PAT is not re-mintable per repo. For unsandboxed roles it rides the
264
- // git-askpass path so SSH/scp remotes get rewritten to https and clone
265
- // works uniformly (matching the gh path). For sandboxed roles the PAT is
266
- // withheld (env cleared): mint an App token instead if available, else
267
- // block with guidance rather than letting git fail silently. App auth must
268
- // still mint for sandboxed roles even when a PAT is present.
269
- const useEnvPat = isPat && runsUnsandboxed(event.origin)
270
- // Sandboxed PAT: the env is cleared, so the PAT can't reach git. Mint an
271
- // App token instead when a minter is live (a PAT must NOT suppress it);
272
- // otherwise block with guidance below rather than fail silently.
273
- const mintForSandboxedPat = isPat && !useEnvPat && shouldMintAppToken(undefined, hasAppTokenResolver())
274
- if (isPat && !useEnvPat && !mintForSandboxedPat) {
275
- const decision = await analyzeGitCommand(command, { cwd: agentDir, resolvers: defaultGitResolvers })
276
- if (decision.kind === 'pass-through') return
277
- if (decision.kind === 'block') return { block: true, reason: decision.reason }
278
- warnSandboxedPatWithheldOnce()
279
- return { block: true, reason: sandboxedPatWithheldReason }
280
- }
281
-
282
- // Neither a usable PAT nor App auth: leave the command untouched so git
283
- // fails honestly rather than us guessing a token. App auth is detected by
284
- // the live minter too, not just an App-class GH_TOKEN: multi-owner /
285
- // no-repos App configs never seed GH_TOKEN yet can mint. The mintForSandboxedPat
286
- // flag forces minting past this PAT-class re-check.
287
- if (!useEnvPat && !mintForSandboxedPat && !shouldMintAppToken(process.env.GH_TOKEN, hasAppTokenResolver())) return
288
-
289
356
  const decision = await analyzeGitCommand(command, { cwd: agentDir, resolvers: defaultGitResolvers })
290
357
  if (decision.kind === 'pass-through') return
291
358
  if (decision.kind === 'block') return { block: true, reason: decision.reason }
292
359
 
293
- // The unsandboxed-PAT path uses the PAT directly; otherwise mint a per-repo
294
- // App token. Both ride TYPECLAW_GIT_TOKEN (read by the askpass helper),
295
- // never argv/config.
296
- let gitToken: string
297
- if (useEnvPat) {
298
- gitToken = process.env.GH_TOKEN as string
299
- } else {
300
- const result = await resolveTokenForRepo(decision.repoSlug)
301
- if (result.kind === 'unavailable') return { block: true, reason: result.reason }
302
- gitToken = result.token
303
- }
360
+ // Only a per-repo GitHub App token is brokered to git — never a PAT (git,
361
+ // unlike gh, runs repo-local hooks/helpers, and a PAT is not repo-confined).
362
+ // With no App minter, pass through so git fails honestly.
363
+ if (!hasAppTokenResolver()) return
364
+ const result = await resolveTokenForRepo(decision.repoSlug)
365
+ if (result.kind === 'unavailable') return { block: true, reason: result.reason }
304
366
 
305
- const askpass = await ensureGitAskPassHelper()
367
+ // Deliver the token via GIT_ASKPASS (env, never argv/config). The analyzer
368
+ // already constrained this to a single bare github git command, so the token
369
+ // env reaches only this git. hooksPath=/dev/null + credential.helper= stop the
370
+ // two highest-value ways a repo could capture the token; insteadOf folds
371
+ // ssh/scp remotes to https so the credential applies. This is defense-in-depth
372
+ // WITHIN one trust domain, not a wall against a hostile repo — untrusted repos
373
+ // belong in a separate agent (see docs/internals/sandbox.mdx).
374
+ // Sandboxed bash: the helper must be on a sandbox-visible path (baked /usr),
375
+ // not the unsandboxed /tmp default the tmpfs would hide.
376
+ const askpass = await ensureGitAskPassHelper(resolveSandboxGitAskPassPath())
306
377
  const existing = event.args[TYPECLAW_INTERNAL_BASH_ENV]
307
378
  const overlay = existing !== null && typeof existing === 'object' ? (existing as Record<string, string>) : {}
308
- // insteadOf rewrites SSH/scp remotes to https so the helper's credential
309
- // applies; GIT_TERMINAL_PROMPT=0 fails fast instead of hanging.
310
379
  event.args[TYPECLAW_INTERNAL_BASH_ENV] = {
311
380
  ...overlay,
312
381
  GIT_ASKPASS: askpass,
313
- TYPECLAW_GIT_TOKEN: gitToken,
382
+ TYPECLAW_GIT_TOKEN: result.token,
314
383
  GIT_TERMINAL_PROMPT: '0',
315
- GIT_CONFIG_COUNT: '2',
316
- GIT_CONFIG_KEY_0: 'url.https://github.com/.insteadOf',
317
- GIT_CONFIG_VALUE_0: 'git@github.com:',
318
- GIT_CONFIG_KEY_1: 'url.https://github.com/.insteadOf',
319
- GIT_CONFIG_VALUE_1: 'ssh://git@github.com/',
384
+ GIT_CONFIG_COUNT: '4',
385
+ GIT_CONFIG_KEY_0: 'core.hooksPath',
386
+ GIT_CONFIG_VALUE_0: '/dev/null',
387
+ GIT_CONFIG_KEY_1: 'credential.helper',
388
+ GIT_CONFIG_VALUE_1: '',
389
+ // Both ssh remote spellings fold to https so the askpass credential applies:
390
+ // the scp short form (git@github.com:owner/repo) and the ssh:// URL form.
391
+ GIT_CONFIG_KEY_2: 'url.https://github.com/.insteadOf',
392
+ GIT_CONFIG_VALUE_2: 'git@github.com:',
393
+ GIT_CONFIG_KEY_3: 'url.https://github.com/.insteadOf',
394
+ GIT_CONFIG_VALUE_3: 'ssh://git@github.com/',
320
395
  }
321
396
  if (decision.rewrittenCommand !== undefined) event.args.command = decision.rewrittenCommand
322
397
  return
@@ -0,0 +1,138 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { mkdtemp, rm } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { promisify } from 'node:util'
5
+
6
+ import { z } from 'zod'
7
+
8
+ import { GITHUB_API_BASE, githubJsonHeaders } from '@/channels/adapters/github/auth-pat'
9
+ import type { ResolveGithubTokenForRepo } from '@/channels/github-token-bridge'
10
+ import { defineTool } from '@/plugin'
11
+ import { ensureSessionTmpDir } from '@/sandbox'
12
+
13
+ import { ensureGitAskPassHelper } from './git-askpass'
14
+
15
+ const execFileAsync = promisify(execFile)
16
+ const FULL_SHA = /^[0-9a-f]{40}$/i
17
+ const REPO_SLUG = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/
18
+
19
+ type RunProcess = (file: string, args: string[], options: { env: NodeJS.ProcessEnv }) => Promise<void>
20
+ type GithubFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
21
+
22
+ export async function prepareReviewerCheckout(options: {
23
+ repoSlug: string
24
+ headSha: string
25
+ sessionId: string
26
+ resolveTokenForRepo: ResolveGithubTokenForRepo
27
+ fetchImpl?: GithubFetch
28
+ runProcess?: RunProcess
29
+ ensureAskPass?: () => Promise<string>
30
+ }): Promise<{ path: string; repoSlug: string; headSha: string }> {
31
+ if (!REPO_SLUG.test(options.repoSlug)) throw new Error('repository must be one owner/repo slug')
32
+ if (!FULL_SHA.test(options.headSha)) throw new Error('headSha must be a full 40-character commit SHA')
33
+ const tokenResult = await options.resolveTokenForRepo(options.repoSlug)
34
+ if (tokenResult.kind !== 'token') throw new Error(tokenResult.reason)
35
+ const token = tokenResult.token
36
+ await verifyCommit(options.fetchImpl ?? fetch, options.repoSlug, options.headSha, token)
37
+
38
+ const sessionRoot = await ensureSessionTmpDir(options.sessionId)
39
+ const checkout = await mkdtemp(path.join(sessionRoot, 'review-checkout-'))
40
+ const run = options.runProcess ?? defaultRunProcess
41
+ try {
42
+ const baseEnv: NodeJS.ProcessEnv = {
43
+ PATH: process.env.PATH ?? '/usr/bin:/bin',
44
+ HOME: sessionRoot,
45
+ GIT_CONFIG_GLOBAL: '/dev/null',
46
+ GIT_CONFIG_NOSYSTEM: '1',
47
+ GIT_TERMINAL_PROMPT: '0',
48
+ }
49
+ await run('git', ['init', '--quiet', checkout], { env: baseEnv })
50
+ const askPass = await (options.ensureAskPass ?? ensureGitAskPassHelper)()
51
+ await run(
52
+ 'git',
53
+ [
54
+ '-C',
55
+ checkout,
56
+ '-c',
57
+ 'credential.helper=',
58
+ '-c',
59
+ 'core.hooksPath=/dev/null',
60
+ 'fetch',
61
+ '--depth=1',
62
+ `https://github.com/${options.repoSlug}.git`,
63
+ options.headSha,
64
+ ],
65
+ { env: { ...baseEnv, GIT_ASKPASS: askPass, TYPECLAW_GIT_TOKEN: token } },
66
+ )
67
+ await run(
68
+ 'git',
69
+ [
70
+ '-C',
71
+ checkout,
72
+ '-c',
73
+ 'credential.helper=',
74
+ '-c',
75
+ 'core.hooksPath=/dev/null',
76
+ 'checkout',
77
+ '--quiet',
78
+ '--detach',
79
+ options.headSha,
80
+ ],
81
+ { env: baseEnv },
82
+ )
83
+ return { path: checkout, repoSlug: options.repoSlug, headSha: options.headSha.toLocaleLowerCase() }
84
+ } catch (error) {
85
+ await rm(checkout, { recursive: true, force: true }).catch(() => {})
86
+ throw error
87
+ }
88
+ }
89
+
90
+ export function createReviewerCheckoutTool(resolveTokenForRepo: ResolveGithubTokenForRepo) {
91
+ return defineTool({
92
+ description:
93
+ 'Prepare a runtime-owned token-safe scratch checkout of one allowlisted GitHub repository at an exact full commit SHA.',
94
+ parameters: z.object({ repoSlug: z.string(), headSha: z.string() }),
95
+ // `repoSlug` ("owner/repo") and `headSha` (40-hex) are remote GitHub
96
+ // coordinates, never local paths — repoSlug is only ever interpolated into
97
+ // `https://github.com/<slug>.git` and prepareReviewerCheckout rejects
98
+ // anything not matching /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/. Declared so the
99
+ // required "/" in a slug isn't misread as a path separator. Scoped to THIS
100
+ // tool: an undeclared reader passing a slug-shaped value still fails closed.
101
+ fileOperands: { nonFile: ['repoSlug', 'headSha'] },
102
+ async execute(args, ctx) {
103
+ try {
104
+ const receipt = await prepareReviewerCheckout({
105
+ repoSlug: args.repoSlug,
106
+ headSha: args.headSha,
107
+ sessionId: ctx.sessionId,
108
+ resolveTokenForRepo,
109
+ })
110
+ return {
111
+ content: [{ type: 'text' as const, text: `Reviewer checkout ready: ${receipt.path} @ ${receipt.headSha}` }],
112
+ details: { ok: true, ...receipt },
113
+ }
114
+ } catch (error) {
115
+ const message = error instanceof Error ? error.message : String(error)
116
+ return {
117
+ content: [{ type: 'text' as const, text: `Reviewer checkout failed: ${message}` }],
118
+ details: { ok: false, error: message },
119
+ }
120
+ }
121
+ },
122
+ })
123
+ }
124
+
125
+ async function verifyCommit(fetchImpl: GithubFetch, repoSlug: string, sha: string, token: string): Promise<void> {
126
+ const response = await fetchImpl(`${GITHUB_API_BASE}/repos/${repoSlug}/commits/${sha}`, {
127
+ headers: githubJsonHeaders(token),
128
+ redirect: 'error',
129
+ })
130
+ if (!response.ok) throw new Error(`GitHub could not verify ${repoSlug}@${sha} (${response.status})`)
131
+ const body = (await response.json().catch(() => null)) as { sha?: unknown } | null
132
+ if (typeof body?.sha !== 'string' || body.sha.toLocaleLowerCase() !== sha.toLocaleLowerCase())
133
+ throw new Error('GitHub commit verification returned a different SHA')
134
+ }
135
+
136
+ async function defaultRunProcess(file: string, args: string[], options: { env: NodeJS.ProcessEnv }): Promise<void> {
137
+ await execFileAsync(file, args, { ...options, maxBuffer: 1024 * 1024 })
138
+ }
@@ -11,12 +11,10 @@ export function classifyGhToken(token: string | undefined): GhTokenClass {
11
11
  }
12
12
 
13
13
  // Whether the per-repo App minter should fire for a repo-targeting command.
14
- // App auth is detected via EITHER a seeded App-class GH_TOKEN OR a live App
15
- // token resolver — the latter is the authority because multi-owner / no-repos
16
- // App configs intentionally leave GH_TOKEN unseeded (the prefix would read
17
- // 'none'), yet the per-repo minter is still registered and able to mint. Classic
18
- // and fine-grained PATs are never re-minted: they pass through with whatever
19
- // GH_TOKEN is seeded, exactly as before.
14
+ // App auth is detected via EITHER an operator-supplied App-class GH_TOKEN OR a
15
+ // live App token resolver. The resolver is authoritative for channel App auth,
16
+ // whose credentials are never seeded into process.env. Classic and fine-grained
17
+ // PATs are never re-minted: they pass through with the effective process token.
20
18
  export function shouldMintAppToken(token: string | undefined, hasAppTokenResolver: boolean): boolean {
21
19
  const tokenClass = classifyGhToken(token)
22
20
  if (tokenClass === 'cross-owner' || tokenClass === 'fine-grained-pat') return false
@@ -1,3 +1,4 @@
1
+ import { hooklessGitArgs } from '@/git/hookless'
1
2
  import { resolveAgentGit } from '@/git/resolve-agent-git'
2
3
  import type { ContentPart, ToolResult } from '@/plugin'
3
4
 
@@ -63,7 +64,7 @@ const defaultDeps: UncommittedChangesDeps = {
63
64
  if (!bun) return null
64
65
  try {
65
66
  const proc = bun.spawn({
66
- cmd: ['git', ...gitArgs, 'status', '--porcelain=v1'],
67
+ cmd: ['git', ...hooklessGitArgs([...gitArgs, 'status', '--porcelain=v1'])],
67
68
  cwd: agentDir,
68
69
  stdout: 'pipe',
69
70
  stderr: 'pipe',