typeclaw 0.48.7 → 0.48.9

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 (108) hide show
  1. package/auth.schema.json +15 -1
  2. package/package.json +1 -1
  3. package/secrets.schema.json +15 -1
  4. package/src/agent/guard-types.ts +25 -0
  5. package/src/agent/guards.ts +102 -0
  6. package/src/agent/index.ts +33 -3
  7. package/src/agent/multimodal/read-redirect.ts +8 -9
  8. package/src/agent/plugin-tools.ts +283 -148
  9. package/src/agent/provider-error.ts +6 -1
  10. package/src/agent/reload-tool.ts +12 -5
  11. package/src/agent/retry-same-ref.ts +95 -36
  12. package/src/agent/session-origin.ts +13 -1
  13. package/src/agent/system-prompt.ts +14 -3
  14. package/src/agent/todo/continuation-policy.ts +3 -4
  15. package/src/agent/tool-file-safety.ts +36 -13
  16. package/src/agent/tools/channel-reply.ts +39 -2
  17. package/src/agent/tools/channel-send.ts +45 -2
  18. package/src/agent/tools/post-github-review.ts +31 -13
  19. package/src/agent/tools/spawn-subagent.ts +15 -0
  20. package/src/agent/tools/webfetch/inline-style-visibility.ts +2 -2
  21. package/src/agent/tools/webfetch/strategies/readability.ts +109 -10
  22. package/src/agent/turn-runner.ts +23 -19
  23. package/src/bundled-plugins/backup/git-auth.ts +7 -4
  24. package/src/bundled-plugins/backup/subagents.ts +1 -1
  25. package/src/bundled-plugins/bun-hygiene/README.md +23 -20
  26. package/src/bundled-plugins/bun-hygiene/index.ts +1 -7
  27. package/src/bundled-plugins/bun-hygiene/policy.ts +111 -35
  28. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +44 -2
  29. package/src/bundled-plugins/github-cli-auth/gh-store.ts +733 -0
  30. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +25 -0
  31. package/src/bundled-plugins/github-cli-auth/git-command.ts +209 -31
  32. package/src/bundled-plugins/github-cli-auth/git-credential-env.ts +151 -0
  33. package/src/bundled-plugins/github-cli-auth/index.ts +236 -38
  34. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +5 -0
  35. package/src/bundled-plugins/guard/index.ts +2 -25
  36. package/src/bundled-plugins/guard/keys.ts +8 -0
  37. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +7 -8
  38. package/src/bundled-plugins/guard/policy.ts +1 -7
  39. package/src/bundled-plugins/security/policies/git-exfil.ts +22 -30
  40. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +2 -4
  41. package/src/bundled-plugins/security/policies/private-surface-read.ts +8 -6
  42. package/src/bundled-plugins/security/policies/secret-exfil-bash.ts +2 -5
  43. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +2 -4
  44. package/src/bundled-plugins/security/policies/session-search-secrets.ts +2 -4
  45. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -4
  46. package/src/bundled-plugins/security/policy.ts +0 -8
  47. package/src/channels/adapters/discord-bot-slash-commands.ts +22 -0
  48. package/src/channels/adapters/discord-bot.ts +2 -1
  49. package/src/channels/adapters/discord-classify.ts +16 -4
  50. package/src/channels/adapters/discord.ts +20 -8
  51. package/src/channels/adapters/github/dedup.ts +37 -8
  52. package/src/channels/adapters/github/inbound.ts +241 -46
  53. package/src/channels/adapters/github/review-state.ts +13 -9
  54. package/src/channels/adapters/github/review-thread-resolver.ts +52 -20
  55. package/src/channels/adapters/slack-bot.ts +13 -3
  56. package/src/channels/adapters/slack-classify.ts +40 -5
  57. package/src/channels/adapters/slack.ts +3 -9
  58. package/src/channels/adapters/teams.ts +8 -6
  59. package/src/channels/adapters/webex-bot-classify.ts +4 -33
  60. package/src/channels/adapters/webex-bot.ts +2 -4
  61. package/src/channels/adapters/webex-classify.ts +4 -33
  62. package/src/channels/adapters/webex-format.ts +36 -0
  63. package/src/channels/adapters/webex.ts +2 -4
  64. package/src/channels/continuation-willingness.ts +64 -39
  65. package/src/channels/github-rereview-guard.ts +20 -0
  66. package/src/channels/github-review-turn-ledger.ts +11 -1
  67. package/src/channels/github-review-verdict-coordinator.ts +475 -41
  68. package/src/channels/github-verdict-activity.ts +14 -5
  69. package/src/channels/manager.ts +17 -1
  70. package/src/channels/persistence.ts +89 -5
  71. package/src/channels/router.ts +1187 -254
  72. package/src/channels/types.ts +21 -5
  73. package/src/cli/compose-stats.ts +6 -7
  74. package/src/cli/compose-status.ts +6 -7
  75. package/src/cli/compose-usage.ts +6 -7
  76. package/src/cli/stats.ts +6 -7
  77. package/src/cli/status.ts +7 -8
  78. package/src/cli/ui.ts +4 -4
  79. package/src/container/start.ts +41 -1
  80. package/src/container/stop.ts +2 -1
  81. package/src/cron/consumer.ts +30 -9
  82. package/src/cron/scheduler.ts +24 -9
  83. package/src/doctor/channel-checks.ts +64 -0
  84. package/src/doctor/report.ts +8 -8
  85. package/src/dreams/render.ts +2 -2
  86. package/src/init/dockerfile.ts +8 -1
  87. package/src/inspect/render.ts +2 -2
  88. package/src/path-safety/real-intended-path.ts +14 -1
  89. package/src/permissions/permissions.ts +10 -2
  90. package/src/permissions/resolve.ts +8 -2
  91. package/src/plugin/core-tool-names.ts +15 -0
  92. package/src/plugin/hooks.ts +37 -3
  93. package/src/plugin/registry.ts +7 -3
  94. package/src/run/index.ts +33 -7
  95. package/src/sandbox/build.ts +39 -10
  96. package/src/sandbox/policy.ts +6 -2
  97. package/src/secrets/export-github-cli-store.ts +158 -0
  98. package/src/secrets/index.ts +19 -1
  99. package/src/secrets/provision-github-cli-store.ts +322 -0
  100. package/src/secrets/schema.ts +13 -7
  101. package/src/secrets/storage.ts +30 -0
  102. package/src/shared/index.ts +2 -0
  103. package/src/shared/style-text.ts +13 -0
  104. package/src/skills/typeclaw-channel-github/SKILL.md +24 -12
  105. package/src/skills/typeclaw-config/SKILL.md +3 -1
  106. package/src/skills/typeclaw-github-contributing/SKILL.md +6 -2
  107. package/src/skills/typeclaw-permissions/SKILL.md +11 -22
  108. package/src/usage/report.ts +3 -3
@@ -0,0 +1,322 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import {
3
+ accessSync,
4
+ chmodSync,
5
+ closeSync,
6
+ constants as fsConstants,
7
+ fstatSync,
8
+ lstatSync,
9
+ mkdtempSync,
10
+ openSync,
11
+ readFileSync,
12
+ realpathSync,
13
+ rmSync,
14
+ type BigIntStats,
15
+ } from 'node:fs'
16
+ import { tmpdir } from 'node:os'
17
+ import { join, posix, win32 } from 'node:path'
18
+
19
+ import { SecretsBackend } from './storage'
20
+
21
+ const COMMAND_TIMEOUT_MS = 15_000
22
+ const TOKEN_OUTPUT_LIMIT = 16 * 1024
23
+ const HOSTS_FILE_LIMIT = 256 * 1024
24
+ const PRIVATE_DIR_MODE = 0o700
25
+ const AUTH_ENV_NAMES = new Set([
26
+ 'gh_token',
27
+ 'github_token',
28
+ 'gh_enterprise_token',
29
+ 'github_enterprise_token',
30
+ 'gh_host',
31
+ ])
32
+
33
+ export type GithubCliProvisionRequest = {
34
+ command: string
35
+ args: string[]
36
+ env: NodeJS.ProcessEnv
37
+ stdin?: string
38
+ timeoutMs: number
39
+ maxOutputBytes: number
40
+ }
41
+
42
+ export type GithubCliProvisionRunner = (request: GithubCliProvisionRequest) => {
43
+ status: number | null
44
+ stdout: string
45
+ stderr: string
46
+ }
47
+
48
+ export type GithubCliProvisionResult = { ok: true } | { ok: false; reason: string }
49
+
50
+ export type ProvisionGithubCliStoreOptions = {
51
+ agentDir: string
52
+ deniedRoots?: readonly string[]
53
+ env?: NodeJS.ProcessEnv
54
+ runner?: GithubCliProvisionRunner
55
+ resolveExecutable?: GithubCliExecutableResolver
56
+ revalidateExecutable?: (identity: GithubCliExecutableIdentity) => boolean
57
+ }
58
+
59
+ export type GithubCliExecutableIdentity = {
60
+ canonicalPath: string
61
+ dev: bigint
62
+ ino: bigint
63
+ mode: bigint
64
+ size: bigint
65
+ ctimeNs: bigint
66
+ mtimeNs: bigint
67
+ }
68
+
69
+ export type GithubCliExecutableResolver = (
70
+ options: ResolveGithubCliExecutableOptions,
71
+ ) => GithubCliExecutableIdentity | null
72
+
73
+ export type ResolveGithubCliExecutableOptions = {
74
+ platform?: NodeJS.Platform
75
+ env?: NodeJS.ProcessEnv
76
+ deniedRoots?: readonly string[]
77
+ isRegularExecutable?: (path: string) => boolean
78
+ }
79
+
80
+ export function provisionGithubCliStore(options: ProvisionGithubCliStoreOptions): GithubCliProvisionResult {
81
+ const runner = options.runner ?? runGithubCli
82
+ const hostEnv = scrubGithubAuthEnv(options.env ?? process.env)
83
+ const resolveOptions = { env: hostEnv, deniedRoots: options.deniedRoots ?? [] }
84
+ const executable =
85
+ options.resolveExecutable !== undefined
86
+ ? options.resolveExecutable(resolveOptions)
87
+ : resolveGithubCliExecutable(resolveOptions)
88
+ if (executable === null) return failed('Could not find a trusted GitHub CLI executable on the host PATH.')
89
+ const revalidate = options.revalidateExecutable ?? revalidateGithubCliExecutable
90
+ const tokenResult = runPinnedGithubCli(runner, executable, revalidate, {
91
+ command: executable.canonicalPath,
92
+ args: ['auth', 'token', '--hostname', 'github.com'],
93
+ env: hostEnv,
94
+ timeoutMs: COMMAND_TIMEOUT_MS,
95
+ maxOutputBytes: TOKEN_OUTPUT_LIMIT,
96
+ })
97
+ if (tokenResult === null) return failed('The trusted GitHub CLI executable changed before invocation.')
98
+ if (tokenResult.status !== 0) return failed('Could not read the active host github.com GitHub CLI credential.')
99
+
100
+ const token = validateTokenOutput(tokenResult.stdout)
101
+ if (token === null) return failed('The active host github.com GitHub CLI credential was invalid.')
102
+
103
+ let configDir: string | undefined
104
+ try {
105
+ configDir = mkdtempSync(join(tmpdir(), 'typeclaw-gh-provision-'))
106
+ chmodSync(configDir, PRIVATE_DIR_MODE)
107
+ const loginResult = runPinnedGithubCli(runner, executable, revalidate, {
108
+ command: executable.canonicalPath,
109
+ args: [
110
+ 'auth',
111
+ 'login',
112
+ '--hostname',
113
+ 'github.com',
114
+ '--git-protocol',
115
+ 'https',
116
+ '--with-token',
117
+ '--insecure-storage',
118
+ ],
119
+ env: { ...hostEnv, GH_CONFIG_DIR: configDir },
120
+ stdin: `${token}\n`,
121
+ timeoutMs: COMMAND_TIMEOUT_MS,
122
+ maxOutputBytes: TOKEN_OUTPUT_LIMIT,
123
+ })
124
+ if (loginResult === null) return failed('The trusted GitHub CLI executable changed before invocation.')
125
+ if (loginResult.status !== 0) return failed('GitHub CLI could not generate the isolated credential store.')
126
+
127
+ const hosts = readGeneratedHosts(join(configDir, 'hosts.yml'))
128
+ if (hosts === null) return failed('GitHub CLI generated an invalid isolated credential store.')
129
+ new SecretsBackend(join(options.agentDir, 'secrets.json')).writeGithubCliSync({ hosts })
130
+ return { ok: true }
131
+ } catch {
132
+ return failed('GitHub CLI credential provisioning failed.')
133
+ } finally {
134
+ if (configDir !== undefined) rmSync(configDir, { recursive: true, force: true })
135
+ }
136
+ }
137
+
138
+ function runGithubCli(request: GithubCliProvisionRequest): ReturnType<GithubCliProvisionRunner> {
139
+ const result = spawnSync(request.command, request.args, {
140
+ encoding: 'utf8',
141
+ env: request.env,
142
+ input: request.stdin,
143
+ timeout: request.timeoutMs,
144
+ maxBuffer: request.maxOutputBytes,
145
+ stdio: ['pipe', 'pipe', 'pipe'],
146
+ })
147
+ return {
148
+ status: result.status,
149
+ stdout: typeof result.stdout === 'string' ? result.stdout : '',
150
+ stderr: typeof result.stderr === 'string' ? result.stderr : '',
151
+ }
152
+ }
153
+
154
+ export function resolveGithubCliExecutable(
155
+ options: ResolveGithubCliExecutableOptions = {},
156
+ ): GithubCliExecutableIdentity | null {
157
+ const platform = options.platform ?? process.platform
158
+ const env = options.env ?? process.env
159
+ const pathApi = platform === 'win32' ? win32 : posix
160
+ const pathValue = env.PATH ?? Object.entries(env).find(([key]) => key.toLocaleLowerCase() === 'path')?.[1]
161
+ if (pathValue === undefined) return null
162
+ const executableName = platform === 'win32' ? 'gh.exe' : 'gh'
163
+ const deniedRoots = canonicalizeDeniedRoots(options.deniedRoots ?? [], pathApi)
164
+ if (deniedRoots === null) return null
165
+
166
+ for (const rawEntry of pathValue.split(pathApi.delimiter)) {
167
+ const entry = unquotePathEntry(rawEntry)
168
+ if (entry === '' || !pathApi.isAbsolute(entry)) continue
169
+ const candidate = pathApi.join(entry, executableName)
170
+ const basename = pathApi.basename(candidate)
171
+ const nameMatches = platform === 'win32' ? basename.toLocaleLowerCase() === 'gh.exe' : basename === executableName
172
+ if (!pathApi.isAbsolute(candidate) || !nameMatches) continue
173
+ if (options.isRegularExecutable !== undefined) {
174
+ if (!options.isRegularExecutable(candidate) || isInsideAnyRoot(candidate, deniedRoots, pathApi)) continue
175
+ return syntheticExecutableIdentity(candidate)
176
+ }
177
+ const identity = inspectGithubCliExecutable(candidate, platform)
178
+ if (identity === null || isInsideAnyRoot(identity.canonicalPath, deniedRoots, pathApi)) continue
179
+ return identity
180
+ }
181
+ return null
182
+ }
183
+
184
+ function unquotePathEntry(entry: string): string {
185
+ return entry.length >= 2 && entry.startsWith('"') && entry.endsWith('"') ? entry.slice(1, -1) : entry
186
+ }
187
+
188
+ function inspectGithubCliExecutable(path: string, platform: NodeJS.Platform): GithubCliExecutableIdentity | null {
189
+ try {
190
+ const canonicalPath = realpathSync(path)
191
+ const pathApi = platform === 'win32' ? win32 : posix
192
+ const expectedName = platform === 'win32' ? 'gh.exe' : 'gh'
193
+ const actualName = pathApi.basename(canonicalPath)
194
+ if (!pathApi.isAbsolute(canonicalPath)) return null
195
+ if (platform === 'win32' ? actualName.toLocaleLowerCase() !== expectedName : actualName !== expectedName)
196
+ return null
197
+ const canonical = lstatSync(canonicalPath, { bigint: true })
198
+ if (canonical.isSymbolicLink() || !canonical.isFile()) return null
199
+ if (platform !== 'win32') accessSync(canonicalPath, fsConstants.X_OK)
200
+ return identityFromStats(canonicalPath, canonical)
201
+ } catch {
202
+ return null
203
+ }
204
+ }
205
+
206
+ function revalidateGithubCliExecutable(identity: GithubCliExecutableIdentity): boolean {
207
+ const current = inspectGithubCliExecutable(identity.canonicalPath, process.platform)
208
+ return current !== null && executableIdentitiesEqual(identity, current)
209
+ }
210
+
211
+ function runPinnedGithubCli(
212
+ runner: GithubCliProvisionRunner,
213
+ identity: GithubCliExecutableIdentity,
214
+ revalidate: (identity: GithubCliExecutableIdentity) => boolean,
215
+ request: GithubCliProvisionRequest,
216
+ ): ReturnType<GithubCliProvisionRunner> | null {
217
+ if (!revalidate(identity)) return null
218
+ return runner(request)
219
+ }
220
+
221
+ function canonicalizeDeniedRoots(roots: readonly string[], pathApi: typeof posix | typeof win32): string[] | null {
222
+ const canonical: string[] = []
223
+ try {
224
+ for (const root of roots) {
225
+ if (!pathApi.isAbsolute(root)) return null
226
+ canonical.push(realpathSync(root))
227
+ }
228
+ return canonical
229
+ } catch {
230
+ return null
231
+ }
232
+ }
233
+
234
+ function isInsideAnyRoot(candidate: string, roots: readonly string[], pathApi: typeof posix | typeof win32): boolean {
235
+ const normalizedCandidate = platformComparablePath(candidate, pathApi)
236
+ return roots.some((root) => {
237
+ const normalizedRoot = platformComparablePath(root, pathApi)
238
+ const rel = pathApi.relative(normalizedRoot, normalizedCandidate)
239
+ return rel === '' || (!rel.startsWith(`..${pathApi.sep}`) && rel !== '..' && !pathApi.isAbsolute(rel))
240
+ })
241
+ }
242
+
243
+ function platformComparablePath(path: string, pathApi: typeof posix | typeof win32): string {
244
+ return pathApi === win32 ? path.toLocaleLowerCase() : path
245
+ }
246
+
247
+ function identityFromStats(canonicalPath: string, stats: BigIntStats): GithubCliExecutableIdentity {
248
+ return {
249
+ canonicalPath,
250
+ dev: stats.dev,
251
+ ino: stats.ino,
252
+ mode: stats.mode,
253
+ size: stats.size,
254
+ ctimeNs: stats.ctimeNs,
255
+ mtimeNs: stats.mtimeNs,
256
+ }
257
+ }
258
+
259
+ function executableIdentitiesEqual(a: GithubCliExecutableIdentity, b: GithubCliExecutableIdentity): boolean {
260
+ return (
261
+ a.canonicalPath === b.canonicalPath &&
262
+ a.dev === b.dev &&
263
+ a.ino === b.ino &&
264
+ a.mode === b.mode &&
265
+ a.size === b.size &&
266
+ a.ctimeNs === b.ctimeNs &&
267
+ a.mtimeNs === b.mtimeNs
268
+ )
269
+ }
270
+
271
+ function syntheticExecutableIdentity(canonicalPath: string): GithubCliExecutableIdentity {
272
+ return { canonicalPath, dev: 0n, ino: 0n, mode: 0n, size: 0n, ctimeNs: 0n, mtimeNs: 0n }
273
+ }
274
+
275
+ function scrubGithubAuthEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
276
+ const clean = { ...env }
277
+ for (const name of Object.keys(clean)) {
278
+ if (AUTH_ENV_NAMES.has(name.toLocaleLowerCase())) delete clean[name]
279
+ }
280
+ return clean
281
+ }
282
+
283
+ function validateTokenOutput(stdout: string): string | null {
284
+ if (Buffer.byteLength(stdout) > TOKEN_OUTPUT_LIMIT || stdout.includes('\0')) return null
285
+ const normalized = stdout.endsWith('\r\n')
286
+ ? stdout.slice(0, -2)
287
+ : stdout.endsWith('\n')
288
+ ? stdout.slice(0, -1)
289
+ : stdout
290
+ if (normalized.length === 0 || normalized.includes('\r') || normalized.includes('\n')) return null
291
+ return normalized
292
+ }
293
+
294
+ function readGeneratedHosts(path: string): string | null {
295
+ let fd: number | undefined
296
+ try {
297
+ const before = lstatSync(path)
298
+ if (before.isSymbolicLink() || !before.isFile()) return null
299
+ fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)
300
+ const opened = fstatSync(fd)
301
+ if (
302
+ !opened.isFile() ||
303
+ opened.dev !== before.dev ||
304
+ opened.ino !== before.ino ||
305
+ opened.size === 0 ||
306
+ opened.size > HOSTS_FILE_LIMIT
307
+ ) {
308
+ return null
309
+ }
310
+ const hosts = readFileSync(fd, 'utf8')
311
+ if (hosts.length === 0 || hosts.includes('\0') || Buffer.byteLength(hosts) > HOSTS_FILE_LIMIT) return null
312
+ return hosts
313
+ } catch {
314
+ return null
315
+ } finally {
316
+ if (fd !== undefined) closeSync(fd)
317
+ }
318
+ }
319
+
320
+ function failed(reason: string): GithubCliProvisionResult {
321
+ return { ok: false, reason }
322
+ }
@@ -32,6 +32,8 @@ export const mcpCredentialSchema = z
32
32
 
33
33
  export const mcpSliceSchema = z.record(z.string(), mcpCredentialSchema)
34
34
 
35
+ export const githubCliSecretsSchema = z.object({ hosts: z.string().min(1) }).strict()
36
+
35
37
  // Per-adapter channel slots use named fields (`botToken`, `appToken`, `token`)
36
38
  // instead of env-var-name keys. The Secret union per field carries the env-var
37
39
  // override. Unknown adapter ids pass through via catchall so a future
@@ -259,18 +261,22 @@ export const channelsSchema = z
259
261
  // channel field shapes.
260
262
  export const SECRETS_FILE_VERSION = 2
261
263
 
262
- export const secretsFileSchema = z.object({
263
- $schema: z.string().optional(),
264
- version: z.literal(SECRETS_FILE_VERSION),
265
- providers: providersSchema.default({}),
266
- channels: channelsSchema.default({}),
267
- mcp: mcpSliceSchema.default({}),
268
- })
264
+ export const secretsFileSchema = z
265
+ .object({
266
+ $schema: z.string().optional(),
267
+ version: z.literal(SECRETS_FILE_VERSION),
268
+ providers: providersSchema.default({}),
269
+ channels: channelsSchema.default({}),
270
+ mcp: mcpSliceSchema.default({}),
271
+ githubCli: githubCliSecretsSchema.optional(),
272
+ })
273
+ .catchall(z.unknown())
269
274
 
270
275
  export type ProviderCredential = z.infer<typeof providerCredentialSchema>
271
276
  export type Providers = z.infer<typeof providersSchema>
272
277
  export type McpCredential = z.infer<typeof mcpCredentialSchema>
273
278
  export type McpSlice = z.infer<typeof mcpSliceSchema>
279
+ export type GithubCliSecrets = z.infer<typeof githubCliSecretsSchema>
274
280
  export type Channels = z.infer<typeof channelsSchema>
275
281
  export type GithubPatAuthBlock = z.infer<typeof githubPatAuthSchema>
276
282
  export type GithubAppAuthBlock = z.infer<typeof githubAppAuthSchema>
@@ -13,6 +13,7 @@ import { registerXaiOAuthProvider } from './oauth-xai'
13
13
  import { resolveSecret, type Secret } from './resolve'
14
14
  import {
15
15
  type Channels,
16
+ type GithubCliSecrets,
16
17
  type McpCredential,
17
18
  type McpSlice,
18
19
  type ProviderCredential,
@@ -204,6 +205,35 @@ export class SecretsBackend implements AuthStorageBackend {
204
205
  }
205
206
  }
206
207
 
208
+ tryReadGithubCliSync(): GithubCliSecrets | undefined {
209
+ if (!existsSync(this.secretsPath)) return undefined
210
+ let release: (() => void) | undefined
211
+ try {
212
+ release = this.acquireSyncLockWithRetry()
213
+ return this.readEnvelope().githubCli
214
+ } finally {
215
+ release?.()
216
+ }
217
+ }
218
+
219
+ writeGithubCliSync(githubCli: GithubCliSecrets): void {
220
+ this.ensureParentDir()
221
+ this.ensureFileExists()
222
+ let release: (() => void) | undefined
223
+ try {
224
+ release = this.acquireSyncLockWithRetry()
225
+ const envelope = this.readEnvelope()
226
+ this.writeEnvelopeAtomic({
227
+ ...envelope,
228
+ $schema: envelope.$schema ?? SCHEMA_REL,
229
+ version: SECRETS_FILE_VERSION,
230
+ githubCli,
231
+ })
232
+ } finally {
233
+ release?.()
234
+ }
235
+ }
236
+
207
237
  readMcpCredentialSync(serverName: string): McpCredential | undefined {
208
238
  if (!existsSync(this.secretsPath)) return undefined
209
239
  let release: (() => void) | undefined
@@ -31,3 +31,5 @@ export { formatLocalDate, formatLocalDateTime, formatLocalWeekday, resolveLocalT
31
31
  export { detectWsl, isWindowsDriveMount, type WslInfo, type WslVersion } from './wsl'
32
32
 
33
33
  export { isMacOS, isWindows } from './platform'
34
+
35
+ export { styled, type StyleFormat } from './style-text'
@@ -0,0 +1,13 @@
1
+ import { styleText } from 'node:util'
2
+
3
+ export type StyleFormat = Parameters<typeof styleText>[0]
4
+
5
+ // Callers own the color decision (an explicit `useColor`/`opts.color` flag, or
6
+ // `colorsEnabled()` in src/cli/ui.ts, which honors FORCE_COLOR). styleText's
7
+ // default stream validation is a second authority that silently overrides the
8
+ // first, so `FORCE_COLOR=1 typeclaw status | cat` would print no color. Bun
9
+ // <=1.3.x skipped the check; Bun 1.4's node-compat rewrite applies it. Both
10
+ // accept `validateStream: false`.
11
+ export function styled(format: StyleFormat, text: string): string {
12
+ return styleText(format, text, { validateStream: false })
13
+ }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: typeclaw-channel-github
3
- description: Use this skill ALWAYS for PR review requests in any phrasing, including "requested your review on PR #N", "requested a review from team @… on PR #N", "@bot review this", "can you take a look at #123", "이 PR 리뷰해줘", and "리뷰 반영"; delegate reviews of other people's PRs to the `reviewer` subagent and post line-anchored findings with `post_github_review`. ALWAYS settle PR authorship first (triage #0): on a PR you opened, act as the CONTRIBUTOR/author, never review your own PR, and use host-stage operator checkout/push help to address feedback. Also use this skill to resolve threads you authored with `resolve_review_thread`, create issues with model-driven `gh issue create`, or prepare host-stage PR creation, checkout, and push actions.
3
+ description: Use this skill ALWAYS for PR review requests in any phrasing, including "requested your review on PR #N", "requested a review from team @… on PR #N", "@bot review this", "can you take a look at #123", "이 PR 리뷰해줘", and "리뷰 반영"; delegate reviews of other people's PRs to the `reviewer` subagent and post line-anchored findings with `post_github_review`. ALWAYS settle PR authorship first (triage #0): on a PR you opened, act as the CONTRIBUTOR/author, never review your own PR, use host-stage operator help only for checkout and PR creation, and perform eligible configured-remote pushes yourself through the broker. Also use this skill to resolve threads you authored with `resolve_review_thread`, create issues with model-driven `gh issue create`, or prepare host-stage PR creation/checkout and brokered push actions.
4
4
  ---
5
5
 
6
6
  GitHub renders normal Markdown in issues, PRs, discussions, and review comments. Use headings, lists, tables, fenced code blocks, links, and inline code when they improve clarity.
@@ -24,7 +24,7 @@ Before you pick an action, classify the inbound. Skipping this step is how a PR
24
24
  gh pr view <N> --repo owner/repo --json author --jq '.author.login'
25
25
  ```
26
26
 
27
- - **The PR author is you (`<your-login>`).** You are the **contributor/author** on this PR, not its reviewer. Feedback on it — a review, a "리뷰 반영 부탁드려요" / "address the review" / "please apply the feedback" / "fixed?" comment, a `CHANGES_REQUESTED` someone else left — is yours to **address as the author**: read it, ask the operator for the required host-stage checkout, change and commit the code, ask the operator to push, and reply. Go to the **contributor flow** ("When the PR is yours"). **You never review your own PR**, and you never spawn the `reviewer` subagent on it — GitHub does not even let an author formally review their own PR, so an attempt produces a self-addressed "review" comment, which is the exact persona-confusion bug to avoid. Gates 1–2 below (review obligations / review requests) describe the _reviewer_ persona and **do not apply when the PR is yours** — skip straight to the contributor flow.
27
+ - **The PR author is you (`<your-login>`).** You are the **contributor/author** on this PR, not its reviewer. Feedback on it — a review, a "리뷰 반영 부탁드려요" / "address the review" / "please apply the feedback" / "fixed?" comment, a `CHANGES_REQUESTED` someone else left — is yours to **address as the author**: read it, ask the operator for the required host-stage checkout, change and commit the code, push the configured remote yourself through an eligible broker credential, and reply. Go to the **contributor flow** ("When the PR is yours"). **You never review your own PR**, and you never spawn the `reviewer` subagent on it — GitHub does not even let an author formally review their own PR, so an attempt produces a self-addressed "review" comment, which is the exact persona-confusion bug to avoid. Gates 1–2 below (review obligations / review requests) describe the _reviewer_ persona and **do not apply when the PR is yours** — skip straight to the contributor flow.
28
28
  - **The PR author is someone else.** You may be its reviewer. Continue to gate 1.
29
29
 
30
30
  This gate is first because everything after it assumes the reviewer persona. "Address the review" sounds identical whether you wrote the PR or someone else did; only the author check disambiguates, and getting it wrong is what makes the agent review its own work.
@@ -74,29 +74,31 @@ The flow:
74
74
  gh api /repos/owner/repo/pulls/<N>/comments --jq '[.[] | {path, line, user: .user.login, body}]'
75
75
  ```
76
76
 
77
- 2. **Update the PR's branch with host-stage help.** Model-driven bash cannot run `gh pr checkout` or authenticated `git push`: both may execute local hooks while carrying reusable credentials. Ask the operator to run the checkout from the host-stage repository directory:
77
+ 2. **Get the branch checked out, then push it yourself.** `gh pr checkout` is host-stage only — it may execute local hooks while carrying reusable credentials — so ask the operator to run it from the host-stage repository directory:
78
78
 
79
79
  ```sh
80
80
  gh pr checkout <N> --repo owner/repo
81
81
  ```
82
82
 
83
- After the operator confirms the checkout, make the minimal fixes and commit them locally with `typeclaw-git` hygiene. Then ask the operator to push that same branch from the host stage:
83
+ After the operator confirms the checkout, make the minimal fixes and commit them locally with `typeclaw-git` hygiene. Pushing is **not** host-stage only when an eligible broker credential exists. Credential precedence is GitHub App, then an authorized PAT declared in `.env`, then the trusted GitHub CLI store. A configured GitHub remote can use the store fallback from any accessible repository path. The store accepts one configured destination and does not accept explicit-URL or `--set-upstream` pushes.
84
84
 
85
85
  ```sh
86
- git push
86
+ git -C <checkout> push origin <branch>
87
87
  ```
88
88
 
89
- Do **not** open a _new_ PR to fix your existing one; the operator pushes to the same branch so the open PR updates in place.
89
+ Fix ordinary Git errors (missing upstream, stale ref, needs a rebase) yourself and retry. If the broker or your permissions refuse it — no eligible credential for the repo, or your role lacks the `gitExfil` bypass — surface that exact denial instead of claiming every push is host-stage.
90
90
 
91
- If a point is a genuine disagreement (the reviewer is mistaken, or the behavior is intentional), don't silently change it — reply in the thread with your reasoning instead.
91
+ Do **not** open a _new_ PR to fix your existing one; the push goes to the same branch so the open PR updates in place.
92
+
93
+ If a point is a genuine disagreement (the reviewer is mistaken, or the behavior is intentional), don't silently change it — reply in the thread with your reasoning instead.
92
94
 
93
95
  3. **Reply to the feedback as the author.** After pushing, acknowledge each addressed thread with a normal `channel_reply` (keep `thread` set to stay in the inline thread; omit it for the PR conversation). Say what you changed ("Fixed — switched to the wiki-link form in `abc1234`") or why you didn't ("Left as-is — this path can't be null because …"). Keep it short.
94
96
  - **Do not resolve the threads.** On your own PR the open inline threads were authored by your **reviewer**, not by you — and the base principle is _whoever opened the thread closes it_. Resolving is the reviewer's call once they're satisfied; the runtime enforces this (it only lets you resolve threads whose root comment **you** authored). Push the fix, reply, and leave the thread for the reviewer to close.
95
97
  - **Do not post a verdict.** "LGTM", "Approved", "Request changes" are reviewer words. As the author you reply in plain prose; you never emit a review verdict on your own PR.
96
98
 
97
- 4. **If CI is failing on your PR**, that's also contributor work: read the failing check, fix the cause on the checked-out branch, commit locally, then ask the operator to run `git push` from the host stage. You can't always read another system's CI logs — if you can't, say so and ask for the error rather than guessing.
99
+ 4. **If CI is failing on your PR**, that's also contributor work: read the failing check, fix the cause on the checked-out branch, commit locally, then push it yourself the same way. You can't always read another system's CI logs — if you can't, say so and ask for the error rather than guessing.
98
100
 
99
- That's the whole contributor loop: read feedback → operator checks out at the host stage → fix and commit locally → operator pushes at the host stage → reply. No subagent, no formal review, no thread resolution.
101
+ That's the whole contributor loop: read feedback → operator checks out at the host stage → fix and commit locally → push the branch yourself → reply. No subagent, no formal review, no thread resolution.
100
102
 
101
103
  ### When you are being asked to review
102
104
 
@@ -115,7 +117,9 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
115
117
 
116
118
  **The reviewer's `<review>` block is the only source of the verdict and the findings.** You do not review the PR yourself. Between spawning the reviewer and reading its result you do **no analysis of this PR** — do not run `gh pr diff`, do not read the changed files to form an opinion, do not draft a verdict. The reviewer runs on the `deep` model precisely so this judgment is not yours to make on the parent model. If you analyze the diff and post your own assessment while the reviewer is still running, you will post one verdict now and the reviewer's (often different) verdict when it completes — **two contradictory reviews on the same PR**, the exact failure this flow exists to prevent. Wait for the reviewer; post what it returns; nothing before that.
117
119
 
118
- **HARD RULE — a review with actionable findings is a formal review, never a flat comment.** If the reviewer returns **one or more** actionable findings (`blocker`/`concern`/`nit`), the ONLY acceptable way to deliver them is a formal review via `POST /pulls/<N>/reviews` (step 4) — `REQUEST_CHANGES`, `COMMENT`, or `APPROVE` per the verdict, with the line-anchored findings in `comments[]`. You may **never** flatten those findings into a `channel_reply` or a top-level issue comment, **even when** the `gh api` call fails. A 422 means an anchor is wrong (almost always a `line` not in the diff): re-anchor it or move that one finding into the top-level review `body`, then resubmit the formal review — do **not** abandon the formal review and post prose instead. A flat "## Review … two blockers" comment is a bug, not a fallback: it strands the findings without line anchors and is the exact failure this rule exists to prevent. The flat/issue-comment path is reserved for the **zero-actionable-findings** branch only (see below). **Narrow exception:** when `post_github_review` finds that this bot's identical `CHANGES_REQUESTED` verdict is already effective, the tool itself converts the redundant submission into one substantive root PR comment while the existing formal block remains authoritative. This is a successful tool-managed fallback, not permission to replace a failed or invalid formal review manually. If you genuinely cannot land a formal review after fixing anchors, say so plainly and post nothing that claims a review happened — silence beats a false receipt.
120
+ **Reply-triggered re-review carrier rule.** Obey the session-origin carrier status before delegating. If you are not the carrier, do not spawn a reviewer or publish findings anywhere; once the carrier's verdict lands, close out only your own thread.
121
+
122
+ **HARD RULE — a review with actionable findings is a formal review, never a flat comment.** If the reviewer returns **one or more** actionable findings (`blocker`/`concern`/`nit`), the ONLY acceptable way to deliver them is a formal review via `POST /pulls/<N>/reviews` (step 4) — `REQUEST_CHANGES`, `COMMENT`, or `APPROVE` per the verdict, with the line-anchored findings in `comments[]`. You may **never** flatten those findings into a `channel_reply` or a top-level issue comment, **even when** the `gh api` call fails. A 422 means an anchor is wrong (almost always a `line` not in the diff): re-anchor it or move that one finding into the top-level review `body`, then resubmit the formal review — do **not** abandon the formal review and post prose instead. A flat "## Review … two blockers" comment is a bug, not a fallback: it strands the findings without line anchors and is the exact failure this rule exists to prevent. The flat/issue-comment path is reserved for the **zero-actionable-findings** branch only (see below). **Narrow exception:** when `post_github_review` finds that this bot's identical `CHANGES_REQUESTED` verdict is already effective, the tool itself converts the redundant submission into one substantive root PR comment while the existing formal block remains authoritative. This is a successful tool-managed fallback, not permission to replace a failed or invalid formal review manually. **That conversion fires at most once per pull request per head.** If another session already landed it — a sibling thread session of the same PR is the usual case — your call is denied outright instead, and the denial says the prior verdict is still live. That denial is final: the findings for this head have already been published by the sibling, so **stand down and close out only your own thread**. Do not re-post them as a `channel_reply`, a top-level comment, or a reply in your thread; the HARD RULE above applies with full force to this case. If you genuinely cannot land a formal review after fixing anchors, say so plainly and post nothing that claims a review happened — silence beats a false receipt.
119
123
 
120
124
  1. **Minimal intake, then delegate immediately.** Capture only the repo, PR number, current head SHA, exact base OID, authorship, and the prior blocking context needed to identify a re-review. Do not inspect the diff or changed files. Batch the independent metadata/history reads where the tool interface permits.
121
125
 
@@ -185,7 +189,7 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
185
189
 
186
190
  **Operator approval policy.** If the inbound carries a note that PR approval is disabled (`channels.github.review.approve: false` — the adapter appends "Operator policy: PR approval is disabled for this agent" to the message), you must **not** submit an `APPROVE`. Map an `approve` verdict to `COMMENT` instead: post the same `<summary>` and all inline `comments[]` as a `COMMENT` review, just without the formal approval. `request-changes` and `comment` verdicts are unaffected (they never approve). Absent that note, approval is enabled and the table above applies unchanged.
187
191
 
188
- **Re-review.** If step 1 established this is a re-review (an unresolved blocking obligation of yours — a formal `CHANGES_REQUESTED` **or** an unretracted flat-comment blocker), the result MUST clear or re-assert that block. The only top-level-comment exception is the tool-managed duplicate fallback described above: the existing identical `CHANGES_REQUESTED` already re-asserts the formal block, so the new summary/findings may be added as one root comment without posting another blocking review. The clearing mechanics depend on which form the prior block took:
192
+ **Re-review.** On a reply-triggered re-review round, obey the session-origin carrier status. If you are **not** the carrier, do not spawn a reviewer, do not publish findings anywhere, and close out only your own thread once the carrier's verdict lands. If step 1 established this is a re-review (an unresolved blocking obligation of yours — a formal `CHANGES_REQUESTED` **or** an unretracted flat-comment blocker), the result MUST clear or re-assert that block. The only top-level-comment exception is the tool-managed duplicate fallback described above: the existing identical `CHANGES_REQUESTED` already re-asserts the formal block, so the new summary/findings may be added as one root comment without posting another blocking review — once per head. If a sibling session already landed that comment, your attempt is denied and the block stands re-asserted by both the formal review and the sibling's comment; discharge your obligation by closing out your own thread, not by publishing again. The clearing mechanics depend on which form the prior block took:
189
193
  - **Prior block was a formal `CHANGES_REQUESTED`.** It is sticky: **only** a fresh `APPROVE` from you, or a dismissal of your prior review, clears it. A plain issue comment does **not** clear it, and — critically — **neither does a `COMMENT` review.**
190
194
  - **Prior block was a flat comment** (no formal `CHANGES_REQUESTED` exists). There is no sticky GitHub state to clear, but the obligation is still yours to discharge as a **formal** review so the verdict finally lands as review state: submit `APPROVE` (resolved, approval enabled) or `REQUEST_CHANGES` (not resolved). Do not discharge a flat-comment block with another flat comment — that re-strands the verdict, the original bug.
191
195
 
@@ -307,7 +311,15 @@ gh issue create --repo owner/repo --title 'Bug: ...' --body '...'
307
311
 
308
312
  ```
309
313
 
310
- For a pull request, prepare the exact title, body, pushed head branch, and base branch, then ask the operator to run `gh pr create --repo owner/repo --title 'Fix: ...' --head my-branch --base main --body '...'` at the host stage from the repository checkout. Model-driven bash cannot push or create a PR because network Git and `gh pr create` may execute local Git hooks with reusable credentials.
314
+ For a pull request from any accessible project checkout, push the head branch yourself when an eligible broker credential exists. Credential precedence is GitHub App, then an authorized PAT declared in `.env`, then the trusted GitHub CLI store. The store can fund a configured GitHub remote from `workspace`, mounts, nested repositories, or `/tmp`; it requires one configured destination and does not accept explicit-URL or `--set-upstream` pushes. Name the checkout, remote, and branch explicitly:
315
+
316
+ ```sh
317
+ git -C <checkout> push <remote> <branch>
318
+ ```
319
+
320
+ If the trusted store is unavailable, ask the operator to run `gh auth login --hostname github.com` on the host. The next real `typeclaw start` or `typeclaw restart` refreshes the stored account automatically; a start that finds the container already running does not.
321
+
322
+ Then prepare the exact title, body, head branch and base branch and ask the operator to run `gh pr create --repo owner/repo --title 'Fix: ...' --head my-branch --base main --body '...'` at the host stage from that same checkout: `gh pr create` is host-stage only because it may execute local Git hooks with reusable credentials. Fix ordinary Git push errors yourself and retry; if the broker or your permissions refuse, surface the exact denial. For the PR-creation handoff, name the host-accessible `workspace/<repo>` checkout; never direct the operator to a per-session `/tmp` path.
311
323
 
312
324
  For the supported issue form under App auth, TypeClaw mints a short-lived token for the explicit `--repo owner/repo` target and withholds it from sibling commands and shell expansions.
313
325
 
@@ -128,6 +128,8 @@ The `mounts/` directory itself is **gitignored** in your agent folder. The mount
128
128
  7. **Commit** with a message explaining which mount was added and why (`typeclaw-git` skill).
129
129
  8. **Tell the user to restart**: "Added mount `<name>` → `<path>`. Run `typeclaw restart` (host stage). The mount will appear at `mounts/<name>/` after the next start."
130
130
 
131
+ GitHub push credentials are independent of mounts. For store-backed pushes, the operator selects the host account with `gh auth login --hostname github.com`; the next real `typeclaw start` or `typeclaw restart` refreshes the masked trusted store automatically. Configured GitHub remotes can then push from any accessible repository path. Runtime credential precedence is GitHub App, then an authorized PAT declared in `.env`, then the trusted store. The store fallback supports one configured destination, not explicit-URL or `--set-upstream` pushes.
132
+
131
133
  ### When the user asks "what can you see / what's mounted"
132
134
 
133
135
  1. **Read `typeclaw.json`**, list each mount: `name`, `path`, `readOnly`, `description`.
@@ -281,7 +283,7 @@ These are two independent gates:
281
283
 
282
284
  Each variable is unset/empty or a comma-separated list of at most 64 entries; empty or malformed entries fail boot. They are parsed once at container startup, withheld from model bash, and protected by the raw live `.env` mask. A model must not read or edit them. Tell the operator to update `.env` out-of-band and run `typeclaw restart`; `reload` does not re-read them.
283
285
 
284
- The transport still performs DNS answer validation, socket pinning, mixed-answer fail-closed checks, and redirect revalidation. Neither hostname/CIDR exceptions, `acknowledgeGuards.ssrf`, nor any role—including `owner`—can permit known metadata/control-plane endpoints, their standardized compatible/mapped/translatable, well-known NAT64, and 6to4 IPv6 forms, or the ambiguous RFC 8215 `64:ff9b:1::/48` translator range. When `network.blockInternal` is on, an allowed private IPv4 HTTP target generally needs both the `.env` transport exception and a narrow `network.allow` firewall entry.
286
+ The transport still performs DNS answer validation, socket pinning, mixed-answer fail-closed checks, and redirect revalidation. Neither hostname/CIDR exceptions nor any role—including `owner`—can permit known metadata/control-plane endpoints, their standardized compatible/mapped/translatable, well-known NAT64, and 6to4 IPv6 forms, or the ambiguous RFC 8215 `64:ff9b:1::/48` translator range. When `network.blockInternal` is on, an allowed private IPv4 HTTP target generally needs both the `.env` transport exception and a narrow `network.allow` firewall entry.
285
287
 
286
288
  ## Dockerfile
287
289
 
@@ -98,11 +98,15 @@ The same applies to PRs: a quick `gh pr list --search` avoids opening a PR for s
98
98
  ```sh
99
99
  gh issue create --repo OWNER/REPO --title '<conventional title>' --body '<filled body>'
100
100
  ```
101
- For a **pull request**, prepare the exact title, body, pushed head branch, and base branch, then ask the operator to run this at the host stage from the repository checkout:
101
+ For a **pull request**, push the head branch yourself first when an eligible broker credential exists. Credential precedence is GitHub App, then an authorized PAT declared in `.env`, then the trusted GitHub CLI store. The store can fund a configured GitHub remote from any accessible repository path, including `workspace`, mounts, nested repositories, and `/tmp`. It accepts one configured destination and does not accept explicit-URL or `--set-upstream` pushes. Name the remote and branch explicitly:
102
+ ```sh
103
+ git -C <checkout> push <remote> <branch>
104
+ ```
105
+ Then prepare the exact title, body, head branch and base branch and ask the operator to run this at the host stage from that same checkout:
102
106
  ```sh
103
107
  gh pr create --repo OWNER/REPO --title '<conventional title>' --body '<filled body>' --head <branch> --base <branch>
104
108
  ```
105
- Model-driven bash cannot create or push a PR: TypeClaw deliberately withholds reusable credentials from network Git and blocks `gh pr create` because it may invoke local Git hooks.
109
+ `gh pr create` is host-stage only: TypeClaw blocks it because it may invoke local Git hooks with reusable credentials. Fix ordinary Git errors yourself and retry; only hand the operator a push command when the broker or your permissions refuse it. If the trusted store is unavailable, ask the operator to run `gh auth login --hostname github.com` on the host; the next real `typeclaw start` or `typeclaw restart` refreshes it automatically, while a start against an already-running container does not. When handing off, name a host-accessible checkout; never direct the operator to a per-session `/tmp` path.
106
110
  5. **Verify it landed** as intended (`gh issue view` / `gh pr view`) — confirm the template rendered and nothing got truncated.
107
111
 
108
112
  ## Things you must not do