typeclaw 0.45.1 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -1
  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 +151 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +198 -0
  11. package/src/agent/plugin-tools.ts +379 -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 +1050 -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 +143 -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 +27 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/index.ts +2 -1
  32. package/src/bundled-plugins/backup/runner.ts +2 -1
  33. package/src/bundled-plugins/doc-render/render.ts +93 -12
  34. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  35. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  36. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  37. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  38. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  39. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  40. package/src/bundled-plugins/memory/README.md +23 -11
  41. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  42. package/src/bundled-plugins/memory/citations.ts +22 -9
  43. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  44. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  45. package/src/bundled-plugins/memory/index.ts +0 -4
  46. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  47. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  48. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  49. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  50. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  51. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  52. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  53. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  54. package/src/bundled-plugins/reviewer/index.ts +2 -2
  55. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  56. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  57. package/src/bundled-plugins/scout/scout.ts +8 -0
  58. package/src/bundled-plugins/security/index.ts +4 -4
  59. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  60. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  61. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  62. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  63. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  64. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  65. package/src/channels/adapters/discord-bot.ts +66 -6
  66. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  67. package/src/channels/adapters/discord-id.ts +4 -0
  68. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  69. package/src/channels/adapters/discord.ts +57 -7
  70. package/src/channels/adapters/github/auth-app.ts +41 -12
  71. package/src/channels/adapters/github/index.ts +23 -11
  72. package/src/channels/adapters/github/review-submitter.ts +302 -0
  73. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  74. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  75. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  76. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  77. package/src/channels/adapters/slack-bot.ts +19 -8
  78. package/src/channels/adapters/slack-classify.ts +21 -2
  79. package/src/channels/adapters/slack.ts +59 -7
  80. package/src/channels/adapters/telegram-bot.ts +18 -5
  81. package/src/channels/adapters/webex-bot.ts +8 -3
  82. package/src/channels/adapters/webex.ts +8 -3
  83. package/src/channels/fetch-attachment.ts +43 -0
  84. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  85. package/src/channels/github-token-bridge.ts +10 -3
  86. package/src/channels/manager.ts +9 -0
  87. package/src/channels/router.ts +248 -6
  88. package/src/channels/types.ts +28 -1
  89. package/src/cli/channel.ts +1 -1
  90. package/src/cli/init.ts +1 -1
  91. package/src/cli/model.ts +57 -7
  92. package/src/compose/stop.ts +17 -5
  93. package/src/config/config.ts +6 -6
  94. package/src/config/models-mutation.ts +13 -1
  95. package/src/config/providers.ts +176 -0
  96. package/src/container/start.ts +49 -10
  97. package/src/doctor/checks.ts +3 -1
  98. package/src/doctor/commit.ts +2 -1
  99. package/src/doctor/file-ownership.ts +52 -0
  100. package/src/dreams/git.ts +2 -1
  101. package/src/git/hookless.ts +5 -0
  102. package/src/git/reconcile-ignored.ts +18 -5
  103. package/src/git/secret-history.ts +371 -0
  104. package/src/git/system-commit.ts +12 -6
  105. package/src/init/dockerfile.ts +86 -5
  106. package/src/init/index.ts +17 -5
  107. package/src/init/models-dev.ts +4 -0
  108. package/src/init/validate-api-key.ts +2 -0
  109. package/src/mcp/tools.ts +16 -3
  110. package/src/permissions/builtins.ts +3 -1
  111. package/src/plugin/context.ts +2 -0
  112. package/src/plugin/index.ts +1 -0
  113. package/src/plugin/manager.ts +4 -0
  114. package/src/plugin/types.ts +21 -0
  115. package/src/run/index.ts +40 -0
  116. package/src/run/llm-fetch-observer.ts +41 -4
  117. package/src/sandbox/build.ts +37 -15
  118. package/src/sandbox/canonical-secrets.ts +18 -0
  119. package/src/sandbox/env-exposure.ts +80 -0
  120. package/src/sandbox/errors.ts +13 -6
  121. package/src/sandbox/hidden-paths.ts +102 -44
  122. package/src/sandbox/index.ts +22 -4
  123. package/src/sandbox/package-install.ts +3 -27
  124. package/src/sandbox/policy.ts +11 -25
  125. package/src/sandbox/privileged-runtime.ts +255 -0
  126. package/src/sandbox/session-tmp.ts +8 -2
  127. package/src/sandbox/writable-zones.ts +204 -140
  128. package/src/secrets/index.ts +8 -0
  129. package/src/secrets/refresh-provider-oauth.ts +128 -0
  130. package/src/server/command-runner.ts +48 -4
  131. package/src/server/index.ts +4 -0
  132. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  133. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  134. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  135. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  136. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  137. package/src/skills/typeclaw-config/SKILL.md +5 -5
  138. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  139. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  140. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  141. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  142. package/typeclaw.schema.json +20 -0
@@ -2,7 +2,15 @@
2
2
  // string-matching the reason: only `missing-repo` is eligible for a trusted
3
3
  // repo-fallback (origin/cwd) that turns the block into a mint; `composition`,
4
4
  // `multi-owner`, `api-repo-conflict`, and `non-literal-repo` must stay blocks.
5
- export type GhBlockCode = 'missing-repo' | 'non-literal-repo' | 'composition' | 'multi-owner' | 'api-repo-conflict'
5
+ export type GhBlockCode =
6
+ | 'missing-repo'
7
+ | 'non-literal-repo'
8
+ | 'composition'
9
+ | 'multi-owner'
10
+ | 'api-repo-conflict'
11
+ | 'repo-selector-conflict'
12
+ | 'credential-display'
13
+ | 'credential-exposure'
6
14
 
7
15
  export type GhCommandDecision =
8
16
  | { kind: 'pass-through' }
@@ -37,6 +45,19 @@ const API_REPO_CONFLICT_REASON =
37
45
  'used to mint a token for one repo while hitting another. Drop the mismatched ' +
38
46
  '`-R`, or target the repo named in the path.'
39
47
 
48
+ const REPO_SELECTOR_CONFLICT_REASON =
49
+ 'This gh command names a repository in a positional selector or GitHub PR/issue URL that differs from its ' +
50
+ 'authorized `-R/--repo` or runtime repo hint. The positional selector is where gh actually sends the request, ' +
51
+ 'so TypeClaw will not mint a token for a different repository. Use matching repository selectors.'
52
+
53
+ const CREDENTIAL_DISPLAY_REASON =
54
+ 'GitHub authentication management and token-display commands are unavailable to model-driven bash. ' +
55
+ 'In particular, `gh auth token` and `gh auth status --show-token` would print the command-scoped credential. ' +
56
+ 'Use host-side authentication setup or a redacted diagnostic instead.'
57
+
58
+ const CREDENTIAL_EXPOSURE_REASON =
59
+ 'This gh command is not in TypeClaw’s credential-safe allowlist. Model-driven gh receives a command-scoped credential only for operations whose argv cannot read arbitrary files, render process environment values, upload arbitrary files, select another host, or start extensions. Use a supported direct gh operation, a first-class TypeClaw tool, or run this command host-side.'
60
+
40
61
  // A gh segment can legitimately touch more than one repo (a `gh api` compare
41
62
  // endpoint references both the base repo and a cross-fork head). The classifier
42
63
  // returns EVERY effective target so analyzeGhCommand can allowlist-check and
@@ -60,8 +81,8 @@ const COMPOSITION_REASON =
60
81
  'exfiltrate it). One exception is allowed: a trailing reader pipeline `gh … | <reader>` ' +
61
82
  'where every downstream stage is a stdin-only reader (`jq`, `cat`, `wc`, `sort`, `uniq`) ' +
62
83
  'with no file operand — e.g. `gh api repos/o/r | jq .`. jq/JSON metacharacters are also ' +
63
- "fine INSIDE single quotes, e.g. `gh api repos/o/r --jq '.[] | {id}'`. To feed JSON to " +
64
- '`gh api`, write it to a temp file and use `gh api --input <file>`.'
84
+ "fine INSIDE single quotes, e.g. `gh api repos/o/r --jq '.[] | {id}'`. File-backed " +
85
+ '`--input`, `--body-file`, templates, aliases, extensions, and auth/config commands remain unavailable.'
65
86
 
66
87
  // Shell-active metacharacters that, OUTSIDE single quotes, either spawn another
67
88
  // process sharing the shell env (where the minted GH_TOKEN lives) or expand
@@ -104,6 +125,22 @@ function isSingleBareGhCommand(command: string): boolean {
104
125
  return quote === null
105
126
  }
106
127
 
128
+ function containsUnquotedPathnameExpansion(command: string): boolean {
129
+ let quote: '"' | "'" | null = null
130
+ for (const ch of command) {
131
+ if (quote !== null) {
132
+ if (ch === quote) quote = null
133
+ continue
134
+ }
135
+ if (ch === "'" || ch === '"') {
136
+ quote = ch
137
+ continue
138
+ }
139
+ if (ch === '*' || ch === '?' || ch === '[') return true
140
+ }
141
+ return false
142
+ }
143
+
107
144
  // GENUINELY repo-less subcommands (account/global, no -R/--repo): they need no
108
145
  // token injection and pass through. The set is intentionally minimal —
109
146
  // anything not listed (label, ruleset, secret, variable, cache, run, workflow,
@@ -146,9 +183,23 @@ const REPO_LESS_SUBCOMMANDS = new Set([
146
183
  // `-R`/path repo, and is NOT applied to `non-literal-repo` (a `$var` the user
147
184
  // wrote) or `gh api` (path is authoritative).
148
185
  export function analyzeGhCommand(command: string, fallbackRepo?: string): GhCommandDecision {
186
+ if (containsReviewGraphqlMutation(command)) {
187
+ return { kind: 'block', code: 'credential-exposure', reason: CREDENTIAL_EXPOSURE_REASON }
188
+ }
149
189
  const tokens = tokenize(command)
150
190
  const ghStarts = findGhInvocations(tokens)
151
191
  if (ghStarts.length === 0) return { kind: 'pass-through' }
192
+ if (containsUnquotedPathnameExpansion(command)) {
193
+ return { kind: 'block', code: 'credential-exposure', reason: CREDENTIAL_EXPOSURE_REASON }
194
+ }
195
+
196
+ for (let i = 0; i < ghStarts.length; i++) {
197
+ const start = ghStarts[i] as number
198
+ const end = ghStarts[i + 1] ?? tokens.length
199
+ if (isCredentialDisplayOrManagement(tokens.slice(start + 1, end))) {
200
+ return { kind: 'block', code: 'credential-display', reason: CREDENTIAL_DISPLAY_REASON }
201
+ }
202
+ }
152
203
 
153
204
  const repoSlugs: string[] = []
154
205
  let stripRepoFlag = false
@@ -175,16 +226,276 @@ export function analyzeGhCommand(command: string, fallbackRepo?: string): GhComm
175
226
  // bare-`gh` shape is the safe baseline; a trailing reader pipeline (`gh | jq`)
176
227
  // is the one exception we allow, under strict conditions (see analyzeReaderPipeline).
177
228
  if (isSingleBareGhCommand(command)) {
229
+ if (!isCredentialSafeGhCommand(command)) {
230
+ return { kind: 'block', code: 'credential-exposure', reason: CREDENTIAL_EXPOSURE_REASON }
231
+ }
178
232
  if (stripRepoFlag) return { kind: 'inject', repoSlug, rewrittenCommand: stripRepoFlagFromCommand(command) }
179
233
  return { kind: 'inject', repoSlug }
180
234
  }
181
235
 
182
236
  const piped = analyzeReaderPipeline(command, stripRepoFlag)
183
- if (piped !== null) return { kind: 'inject', repoSlug, rewrittenCommand: piped }
237
+ if (piped !== null) {
238
+ if (!isCredentialSafeGhCommand(command)) {
239
+ return { kind: 'block', code: 'credential-exposure', reason: CREDENTIAL_EXPOSURE_REASON }
240
+ }
241
+ return { kind: 'inject', repoSlug, rewrittenCommand: piped }
242
+ }
184
243
 
185
244
  return { kind: 'block', code: 'composition', reason: COMPOSITION_REASON }
186
245
  }
187
246
 
247
+ function isCredentialDisplayOrManagement(args: readonly string[]): boolean {
248
+ if (args[0] !== 'auth') return false
249
+ const subcommand = args[1]
250
+ if (subcommand === 'token') return true
251
+ if (subcommand === 'status') {
252
+ return args.some(isAuthStatusTokenDisplayFlag)
253
+ }
254
+ return subcommand !== undefined && new Set(['login', 'logout', 'refresh', 'switch', 'setup-git']).has(subcommand)
255
+ }
256
+
257
+ function isAuthStatusTokenDisplayFlag(arg: string): boolean {
258
+ if (arg === '--show-token' || arg.startsWith('--show-token=')) return true
259
+ if (!arg.startsWith('-') || arg.startsWith('--')) return false
260
+ return arg.slice(1).split('=', 1)[0]?.includes('t') === true
261
+ }
262
+
263
+ export function canInjectPatIntoPassThroughGh(command: string): boolean {
264
+ if (containsReviewGraphqlMutation(command)) return false
265
+ if (command.includes('\\')) return false
266
+ if (!isSingleBareGhCommand(command)) return false
267
+ const tokens = tokenize(command)
268
+ const starts = findGhInvocations(tokens)
269
+ if (starts.length !== 1 || starts[0] !== 0) return false
270
+ const args = tokens.slice(1)
271
+ if (isCredentialDisplayOrManagement(args)) return false
272
+ const subcommand = args[0]
273
+ if (subcommand === 'alias' || subcommand === 'extension' || subcommand === 'config') return false
274
+ if (subcommand === 'auth') return args[1] === 'status'
275
+ return isCredentialSafeGhArgs(args)
276
+ }
277
+
278
+ function containsReviewGraphqlMutation(command: string): boolean {
279
+ const tokens = tokenize(command)
280
+ const ghStarts = findGhInvocations(tokens)
281
+ for (let i = 0; i < ghStarts.length; i++) {
282
+ const start = ghStarts[i] as number
283
+ const end = ghStarts[i + 1] ?? tokens.length
284
+ const args = tokens.slice(start + 1, end)
285
+ if (!isGraphqlEndpoint(args)) continue
286
+ if (extractGraphqlQueries(args).some((query) => REVIEW_GRAPHQL_MUTATION.test(query))) return true
287
+ }
288
+ return false
289
+ }
290
+
291
+ const REVIEW_GRAPHQL_MUTATION =
292
+ /\b(?:addPullRequestReview|submitPullRequestReview|addPullRequestReviewComment|addPullRequestReviewThread|addPullRequestReviewThreadReply)\b/
293
+
294
+ const GRAPHQL_FIELD_FLAGS = new Set(['-f', '--raw-field', '-F', '--field'])
295
+
296
+ function extractGraphqlQueries(args: readonly string[]): string[] {
297
+ const queries: string[] = []
298
+ for (let i = 0; i < args.length; i++) {
299
+ const arg = args[i] as string
300
+ if (GRAPHQL_FIELD_FLAGS.has(arg)) {
301
+ const field = args[i + 1]
302
+ if (field !== undefined) {
303
+ addGraphqlQuery(queries, field)
304
+ i += 1
305
+ }
306
+ continue
307
+ }
308
+ for (const prefix of ['--raw-field=', '--field=', '-f', '-F']) {
309
+ if (arg.startsWith(prefix)) {
310
+ const field = arg.slice(prefix.length)
311
+ addGraphqlQuery(queries, field.startsWith('=') ? field.slice(1) : field)
312
+ break
313
+ }
314
+ }
315
+ }
316
+ return queries
317
+ }
318
+
319
+ function addGraphqlQuery(queries: string[], field: string): void {
320
+ if (field.startsWith('query=')) queries.push(field.slice('query='.length))
321
+ }
322
+
323
+ const SAFE_GH_OPERATIONS: Readonly<Record<string, ReadonlySet<string>>> = {
324
+ api: new Set(['']),
325
+ pr: new Set(['view', 'list', 'status', 'checks', 'diff', 'review', 'comment', 'close', 'reopen', 'ready', 'merge']),
326
+ issue: new Set(['view', 'list', 'status', 'comment', 'close', 'reopen', 'create']),
327
+ label: new Set(['list', 'create', 'edit', 'delete', 'clone']),
328
+ release: new Set(['view', 'list']),
329
+ gist: new Set(['list']),
330
+ repo: new Set(['view', 'list']),
331
+ run: new Set(['view', 'list', 'watch', 'cancel', 'rerun', 'delete']),
332
+ workflow: new Set(['view', 'list', 'run', 'enable', 'disable']),
333
+ ruleset: new Set(['view', 'list', 'check']),
334
+ cache: new Set(['list', 'delete']),
335
+ variable: new Set(['list', 'get', 'set', 'delete']),
336
+ secret: new Set(['list', 'delete']),
337
+ }
338
+
339
+ const CREDENTIAL_UNSAFE_FLAGS = new Set([
340
+ '--input',
341
+ '--template',
342
+ '-t',
343
+ '--hostname',
344
+ '--body-file',
345
+ '--web',
346
+ '--delete-branch',
347
+ ])
348
+
349
+ const CREDENTIAL_SAFE_FLAGS = new Set([
350
+ '-R',
351
+ '--repo',
352
+ '-X',
353
+ '--method',
354
+ '-f',
355
+ '--raw-field',
356
+ '-F',
357
+ '--field',
358
+ '-H',
359
+ '--header',
360
+ '-i',
361
+ '--include',
362
+ '--paginate',
363
+ '--slurp',
364
+ '--cache',
365
+ '--silent',
366
+ '--verbose',
367
+ '--version',
368
+ '--help',
369
+ '--json',
370
+ '--jq',
371
+ '-q',
372
+ '--comments',
373
+ '--checks',
374
+ '--files',
375
+ '--commits',
376
+ '--body',
377
+ '-b',
378
+ '--title',
379
+ '--approve',
380
+ '--request-changes',
381
+ '--comment',
382
+ '--merge',
383
+ '--squash',
384
+ '--rebase',
385
+ '--admin',
386
+ '--auto',
387
+ '--match-head-commit',
388
+ '--subject',
389
+ '--limit',
390
+ '-L',
391
+ '--state',
392
+ '--author',
393
+ '--assignee',
394
+ '--label',
395
+ '--milestone',
396
+ '--search',
397
+ '--base',
398
+ '--head',
399
+ '--draft',
400
+ '--name',
401
+ '--color',
402
+ '--description',
403
+ '--force',
404
+ '--confirm',
405
+ '--branch',
406
+ '--event',
407
+ ])
408
+
409
+ function isCredentialSafeGhCommand(command: string): boolean {
410
+ const stages = splitTopLevelPipeStages(command)
411
+ if (stages === null || stages.length === 0) return false
412
+ const ghStage = (stages[0] as string).trim()
413
+ if (!isSingleBareGhCommand(ghStage) || ghStage.includes('\\')) return false
414
+ const tokens = tokenize(ghStage)
415
+ return tokens[0] === 'gh' && isCredentialSafeGhArgs(tokens.slice(1))
416
+ }
417
+
418
+ function isCredentialSafeGhArgs(args: readonly string[]): boolean {
419
+ const parsed = parseGhArgs(args)
420
+ if (parsed === null) return false
421
+ const { command, operation } = parsed
422
+ if (command === 'api') {
423
+ const endpoint = findApiEndpoint(args)
424
+ if (endpoint === null || endpoint.includes('://')) return false
425
+ }
426
+ if (!SAFE_GH_OPERATIONS[command]?.has(operation)) return false
427
+ if (command === 'issue' && operation === 'create' && !isSafeCreateArgs(args)) {
428
+ return false
429
+ }
430
+
431
+ for (let i = 0; i < args.length; i++) {
432
+ const arg = args[i] as string
433
+ const flag = arg.includes('=') ? arg.slice(0, arg.indexOf('=')) : arg
434
+ if (CREDENTIAL_UNSAFE_FLAGS.has(flag)) return false
435
+ if (flag.endsWith('-file') || flag.endsWith('-file-name')) return false
436
+ if (arg.startsWith('-') && !CREDENTIAL_SAFE_FLAGS.has(flag)) return false
437
+ if (
438
+ (command === 'api' || command === 'workflow') &&
439
+ (flag === '--raw-field' || flag === '-f' || flag === '--field' || flag === '-F')
440
+ ) {
441
+ const value = flagValue(args, i)
442
+ if (value === null || fieldDereferencesFile(value)) return false
443
+ }
444
+ if (flag === '--jq' || flag === '-q') {
445
+ const filter = flagValue(args, i)
446
+ if (filter === null || !isSafeGhJqFilter(filter)) return false
447
+ }
448
+ }
449
+ return true
450
+ }
451
+
452
+ function isSafeCreateArgs(args: readonly string[]): boolean {
453
+ if (extractRepoFlag(args) === null) return false
454
+ const title = findFlagValue(args, ['--title'])
455
+ const body = findFlagValue(args, ['--body', '-b'])
456
+ if (title === null || title.trim() === '' || body === null || body.trim() === '') return false
457
+ if (title.startsWith('@') || body.startsWith('@')) return false
458
+
459
+ const forbidden = new Set([
460
+ '--body-file',
461
+ '--template',
462
+ '--editor',
463
+ '--web',
464
+ '--recover',
465
+ '--fill',
466
+ '--fill-first',
467
+ '--fill-verbose',
468
+ ])
469
+ if (args.some((arg) => forbidden.has(arg.includes('=') ? arg.slice(0, arg.indexOf('=')) : arg))) return false
470
+ return true
471
+ }
472
+
473
+ function findFlagValue(args: readonly string[], names: readonly string[]): string | null {
474
+ for (let i = 0; i < args.length; i++) {
475
+ const arg = args[i] as string
476
+ for (const name of names) {
477
+ if (arg === name) return args[i + 1] ?? null
478
+ if (arg.startsWith(`${name}=`)) return arg.slice(name.length + 1)
479
+ }
480
+ }
481
+ return null
482
+ }
483
+
484
+ function flagValue(args: readonly string[], index: number): string | null {
485
+ const arg = args[index] as string
486
+ const separator = arg.indexOf('=')
487
+ return separator >= 0 ? arg.slice(separator + 1) : (args[index + 1] ?? null)
488
+ }
489
+
490
+ function fieldDereferencesFile(value: string): boolean {
491
+ const separator = value.indexOf('=')
492
+ return separator < 1 || value.slice(separator + 1).startsWith('@')
493
+ }
494
+
495
+ function isSafeGhJqFilter(filter: string): boolean {
496
+ return !/(^|[^A-Za-z0-9_])env([^A-Za-z0-9_]|$)|\$ENV\b|input_filename|modulemeta/.test(filter)
497
+ }
498
+
188
499
  // stdin-only readers whose only sink is stdout (back to the agent, who already
189
500
  // has gh's output) — they cannot open their own network/file/process sink, so a
190
501
  // `gh <repo> | <reader>` pipeline cannot exfiltrate the minted token to a third
@@ -330,7 +641,7 @@ function analyzeReaderPipeline(command: string, stripRepoFlag: boolean): string
330
641
  }
331
642
 
332
643
  const rewrittenGh = stripRepoFlag ? stripRepoFlagFromCommand(ghStage) : ghStage
333
- const rewrittenReaders = stages.slice(1).map((s) => `/usr/bin/env -u GH_TOKEN ${s.trim()}`)
644
+ const rewrittenReaders = stages.slice(1).map((s) => `/usr/bin/env -u GH_TOKEN -u GITHUB_TOKEN ${s.trim()}`)
334
645
  return [rewrittenGh, ...rewrittenReaders].join(' | ')
335
646
  }
336
647
 
@@ -514,8 +825,9 @@ function matchRepoFlagAt(command: string, start: number): number | null {
514
825
  }
515
826
 
516
827
  function classifyGhSegment(args: readonly string[], fallbackRepo?: string): GhSegmentDecision {
517
- const subcommand = args.find((t) => !t.startsWith('-'))
518
- if (subcommand === undefined) return { kind: 'pass-through' }
828
+ const parsed = parseGhArgs(args)
829
+ if (parsed === null) return { kind: 'pass-through' }
830
+ const { command: subcommand } = parsed
519
831
 
520
832
  // `gh api` is resolved BEFORE the generic -R extraction: for a literal
521
833
  // `/repos/{owner}/{repo}` endpoint the request goes to the PATH repo and `gh`
@@ -523,26 +835,234 @@ function classifyGhSegment(args: readonly string[], fallbackRepo?: string): GhSe
523
835
  // call hits another (the allowlist-bypass this guards against).
524
836
  if (subcommand === 'api') return classifyGhApiSegment(args)
525
837
 
526
- const explicit = extractRepoFlag(args)
527
- if (explicit !== null) return { kind: 'inject', repoSlugs: [explicit] }
838
+ if (repoFlagHasNonLiteralValue(args))
839
+ return { kind: 'block', code: 'non-literal-repo', reason: NON_LITERAL_REPO_REASON }
840
+
841
+ const explicitRepos = extractAllRepoFlags(args)
842
+ const explicit = explicitRepos[0] ?? null
843
+ if (explicit !== null && explicitRepos.some((repo) => !sameRepo(repo, explicit))) {
844
+ return { kind: 'block', code: 'repo-selector-conflict', reason: REPO_SELECTOR_CONFLICT_REASON }
845
+ }
846
+ const positionalTargets = extractReposFromPositionalSelectors(parsed)
847
+ if (positionalTargets.invalid) {
848
+ return { kind: 'block', code: 'repo-selector-conflict', reason: REPO_SELECTOR_CONFLICT_REASON }
849
+ }
850
+ const positionalRepos = positionalTargets.repos
851
+ if (explicit !== null) {
852
+ if (positionalRepos.some((repo) => !sameRepo(repo, explicit))) {
853
+ return { kind: 'block', code: 'repo-selector-conflict', reason: REPO_SELECTOR_CONFLICT_REASON }
854
+ }
855
+ return { kind: 'inject', repoSlugs: [explicit] }
856
+ }
528
857
 
529
858
  // A `-R`/`--repo` IS present but its value isn't a literal slug (e.g. `-R "$repo"`):
530
859
  // tell the user that, not the misleading "add -R" message — they already did.
531
860
  // A trusted fallback never papers over a value the user explicitly mistyped.
532
- if (repoFlagHasNonLiteralValue(args))
533
- return { kind: 'block', code: 'non-literal-repo', reason: NON_LITERAL_REPO_REASON }
534
-
535
861
  if (REPO_LESS_SUBCOMMANDS.has(subcommand)) return { kind: 'pass-through' }
536
862
 
537
863
  // Repo-less repo-scoped subcommand. A caller-supplied trusted fallback repo
538
864
  // (origin/cwd, already allowlisted) fills it so the command can mint; absent
539
865
  // one, block missing-repo. The fallback still passes through the composition
540
866
  // gate in analyzeGhCommand, so a compound command blocks regardless.
867
+ const isLabelClone = subcommand === 'label' && parsed.operation === 'clone'
868
+ if (positionalRepos.length > 0) {
869
+ if (fallbackRepo !== undefined && isRepoSlug(fallbackRepo)) {
870
+ if (positionalRepos.some((repo) => !sameRepo(repo, fallbackRepo))) {
871
+ return { kind: 'block', code: 'repo-selector-conflict', reason: REPO_SELECTOR_CONFLICT_REASON }
872
+ }
873
+ return { kind: 'inject', repoSlugs: [fallbackRepo] }
874
+ }
875
+ if (isLabelClone) return { kind: 'block', code: 'missing-repo', reason: MISSING_REPO_REASON }
876
+ return { kind: 'inject', repoSlugs: positionalRepos }
877
+ }
878
+
541
879
  if (fallbackRepo !== undefined && isRepoSlug(fallbackRepo)) return { kind: 'inject', repoSlugs: [fallbackRepo] }
542
880
 
543
881
  return { kind: 'block', code: 'missing-repo', reason: MISSING_REPO_REASON }
544
882
  }
545
883
 
884
+ const GH_FLAGS_WITH_VALUES = new Set([
885
+ '-R',
886
+ '--repo',
887
+ '-X',
888
+ '--method',
889
+ '-f',
890
+ '--raw-field',
891
+ '-F',
892
+ '--field',
893
+ '-H',
894
+ '--header',
895
+ '-q',
896
+ '--jq',
897
+ '-t',
898
+ '--template',
899
+ '--input',
900
+ '--hostname',
901
+ '--body-file',
902
+ '--cache',
903
+ '--json',
904
+ '--body',
905
+ '-b',
906
+ '--title',
907
+ '--match-head-commit',
908
+ '--subject',
909
+ '--limit',
910
+ '-L',
911
+ '--state',
912
+ '--author',
913
+ '--assignee',
914
+ '--label',
915
+ '--milestone',
916
+ '--search',
917
+ '--base',
918
+ '--head',
919
+ '--name',
920
+ '--color',
921
+ '--description',
922
+ '--branch',
923
+ '--event',
924
+ ])
925
+
926
+ const PR_REPO_SELECTOR_OPERATIONS = new Set([
927
+ 'view',
928
+ 'list',
929
+ 'status',
930
+ 'checks',
931
+ 'diff',
932
+ 'review',
933
+ 'comment',
934
+ 'close',
935
+ 'reopen',
936
+ 'ready',
937
+ 'merge',
938
+ 'checkout',
939
+ ])
940
+ const ISSUE_REPO_SELECTOR_OPERATIONS = new Set(['view', 'list', 'status', 'comment', 'close', 'reopen'])
941
+
942
+ type ParsedGhArgs = {
943
+ command: string
944
+ operation: string
945
+ operands: string[]
946
+ }
947
+
948
+ function parseGhArgs(args: readonly string[]): ParsedGhArgs | null {
949
+ const positionals = positionalArgs(args)
950
+ const command = positionals[0]
951
+ if (command === undefined) return null
952
+ if (command === 'api') return { command, operation: '', operands: positionals.slice(1) }
953
+ const operation = positionals[1]
954
+ if (operation === undefined) return { command, operation: '', operands: [] }
955
+ return { command, operation, operands: positionals.slice(2) }
956
+ }
957
+
958
+ // Audit of SAFE_GH_OPERATIONS positional repository authority:
959
+ // - repo view: first operand is a repository slug/URL.
960
+ // - the PR/issue sets below: a URL operand overrides -R's effective repo.
961
+ // - label clone: first operand is a second (source) repository and must agree
962
+ // with the authorized destination repo; cross-repo clone is intentionally
963
+ // unavailable under a command-scoped credential.
964
+ // Every other allowlisted operation accepts only repo-local names/IDs/refs or
965
+ // no positional operand; none names a secondary repository.
966
+ function extractReposFromPositionalSelectors(parsed: ParsedGhArgs): { repos: string[]; invalid: boolean } {
967
+ const { command, operation, operands } = parsed
968
+ if (command === 'repo' && operation === 'view') {
969
+ const selector = operands[0]
970
+ if (selector === undefined) return { repos: [], invalid: false }
971
+ const repo = repoFromSelector(selector)
972
+ return repo === null ? { repos: [], invalid: true } : { repos: [repo], invalid: false }
973
+ }
974
+
975
+ if (command === 'pr' && PR_REPO_SELECTOR_OPERATIONS.has(operation)) {
976
+ return reposFromIssueLikeSelectors(operands, 'pr')
977
+ }
978
+ if (command === 'issue' && ISSUE_REPO_SELECTOR_OPERATIONS.has(operation)) {
979
+ return reposFromIssueLikeSelectors(operands, 'issue')
980
+ }
981
+ if (command === 'label' && operation === 'clone') {
982
+ const source = operands[0]
983
+ if (source === undefined) return { repos: [], invalid: false }
984
+ const repo = repoFromSelector(source)
985
+ return repo === null ? { repos: [], invalid: true } : { repos: [repo], invalid: false }
986
+ }
987
+ return { repos: [], invalid: false }
988
+ }
989
+
990
+ function reposFromIssueLikeSelectors(
991
+ selectors: readonly string[],
992
+ kind: 'pr' | 'issue',
993
+ ): { repos: string[]; invalid: boolean } {
994
+ const repos: string[] = []
995
+ for (const selector of selectors) {
996
+ const repo = repoFromGithubUrl(selector, kind)
997
+ if (repo !== null) repos.push(repo)
998
+ else if (looksLikeUrl(selector)) return { repos: [], invalid: true }
999
+ }
1000
+ return { repos, invalid: false }
1001
+ }
1002
+
1003
+ function repoFromSelector(value: string): string | null {
1004
+ if (isRepoSlug(value)) return value
1005
+ const hostQualified = value.split('/')
1006
+ if (hostQualified.length === 3 && hostQualified[0]?.toLocaleLowerCase() === 'github.com') {
1007
+ const slug = `${hostQualified[1]}/${hostQualified[2]}`
1008
+ return isRepoSlug(slug) ? slug : null
1009
+ }
1010
+ return repoFromGithubUrl(value)
1011
+ }
1012
+
1013
+ function looksLikeUrl(value: string): boolean {
1014
+ return /^[a-z][a-z\d+.-]*:\/\//i.test(value)
1015
+ }
1016
+
1017
+ function positionalArgs(args: readonly string[]): string[] {
1018
+ const result: string[] = []
1019
+ let command: string | undefined
1020
+ for (let i = 0; i < args.length; i++) {
1021
+ const arg = args[i] as string
1022
+ if (!arg.startsWith('-')) {
1023
+ result.push(arg)
1024
+ if (command === undefined) command = arg
1025
+ continue
1026
+ }
1027
+ const equals = arg.indexOf('=')
1028
+ const flag = equals === -1 ? arg : arg.slice(0, equals)
1029
+ if (equals === -1 && ghFlagTakesValue(flag, command)) i += 1
1030
+ }
1031
+ return result
1032
+ }
1033
+
1034
+ // Short flags are scoped by Cobra command, not globally. In the credential-safe
1035
+ // surface, `-f` is value-taking for `gh api` and `gh workflow run`, but boolean
1036
+ // `--force` for `gh label create/clone`. Treating it globally as value-taking
1037
+ // hides label clone's following source repository from authorization. The other
1038
+ // short value flags in GH_FLAGS_WITH_VALUES have no boolean overload in the
1039
+ // allowlisted operations audited above.
1040
+ function ghFlagTakesValue(flag: string, command: string | undefined): boolean {
1041
+ if (flag === '-f' && command === 'label') return false
1042
+ return GH_FLAGS_WITH_VALUES.has(flag)
1043
+ }
1044
+
1045
+ function repoFromGithubUrl(value: string, kind?: 'pr' | 'issue'): string | null {
1046
+ let url: URL
1047
+ try {
1048
+ url = new URL(value)
1049
+ } catch {
1050
+ return null
1051
+ }
1052
+ if (url.protocol !== 'https:' || url.hostname.toLocaleLowerCase() !== 'github.com') return null
1053
+ const segments = url.pathname.split('/').filter(Boolean)
1054
+ const owner = segments[0]
1055
+ const repo = segments[1]?.replace(/\.git$/i, '')
1056
+ if (owner === undefined || repo === undefined || !isRepoSlug(`${owner}/${repo}`)) return null
1057
+ if (kind === 'pr' && (segments[2] !== 'pull' || !/^\d+$/.test(segments[3] ?? ''))) return null
1058
+ if (kind === 'issue' && (segments[2] !== 'issues' || !/^\d+$/.test(segments[3] ?? ''))) return null
1059
+ return `${owner}/${repo}`
1060
+ }
1061
+
1062
+ function sameRepo(left: string, right: string): boolean {
1063
+ return left.toLocaleLowerCase() === right.toLocaleLowerCase()
1064
+ }
1065
+
546
1066
  // Repo authority for `gh api`: the literal endpoint path wins. A `-R/--repo`
547
1067
  // that names a DIFFERENT repo than the path is a mint-for-X-but-hit-Y attempt
548
1068
  // and blocks. A placeholder endpoint (`repos/{owner}/{repo}`) has no literal
@@ -571,7 +1091,7 @@ function classifyGhApiSegment(args: readonly string[]): GhSegmentDecision {
571
1091
  // must block even when an earlier flag matches the path and would otherwise
572
1092
  // mask it.
573
1093
  const flagRepos = extractAllRepoFlags(args)
574
- if (flagRepos.some((slug) => !pathRepos.includes(slug))) {
1094
+ if (flagRepos.some((slug) => !pathRepos.some((pathRepo) => sameRepo(slug, pathRepo)))) {
575
1095
  return { kind: 'block', code: 'api-repo-conflict', reason: API_REPO_CONFLICT_REASON }
576
1096
  }
577
1097
  // Every `-R` here is redundant: it matches the repo already named in the
@@ -590,7 +1110,8 @@ function classifyGhApiSegment(args: readonly string[]): GhSegmentDecision {
590
1110
  // graphql encodes its repo in the query body / opaque node IDs, never an
591
1111
  // inspectable path, so `-R` is taken as the mint hint. Safe because there is
592
1112
  // no literal path to conflict with (cf. the API_REPO_CONFLICT_REASON guard
593
- // above): the minted token's installation scope, not the flag, bounds reach.
1113
+ // above): the minted token's server-side repository restriction, not the
1114
+ // flag, bounds reach.
594
1115
  // `gh api` rejects `-R`, so the flag must be stripped from the command.
595
1116
  if (flagRepo !== null && isGraphqlEndpoint(args)) {
596
1117
  return { kind: 'inject', repoSlugs: [flagRepo], stripRepoFlag: true }
@@ -607,7 +1128,15 @@ function classifyGhApiSegment(args: readonly string[]): GhSegmentDecision {
607
1128
  }
608
1129
 
609
1130
  function isGraphqlEndpoint(args: readonly string[]): boolean {
610
- return findApiEndpoint(args) === 'graphql'
1131
+ const endpoint = findApiEndpoint(args)
1132
+ if (endpoint === null) return false
1133
+ const base = new URL('https://api.github.invalid/')
1134
+ try {
1135
+ const parsed = new URL(endpoint, base)
1136
+ return parsed.origin === base.origin && parsed.pathname === '/graphql'
1137
+ } catch {
1138
+ return false
1139
+ }
611
1140
  }
612
1141
 
613
1142
  export type GhAuthEnv = {
@@ -646,6 +1175,17 @@ export function usesGhApiAuthenticatedUserEndpoint(command: string): boolean {
646
1175
  return effectiveGhTokensForAuthenticatedUserEndpoint(command, {}).length > 0
647
1176
  }
648
1177
 
1178
+ export function usesGhApiGraphqlEndpoint(command: string): boolean {
1179
+ const tokens = tokenize(command)
1180
+ const ghStarts = findGhInvocations(tokens)
1181
+ for (let i = 0; i < ghStarts.length; i++) {
1182
+ const start = ghStarts[i] as number
1183
+ const end = ghStarts[i + 1] ?? tokens.length
1184
+ if (isGraphqlEndpoint(tokens.slice(start + 1, end))) return true
1185
+ }
1186
+ return false
1187
+ }
1188
+
649
1189
  function isAuthenticatedUserEndpointArgs(args: readonly string[]): boolean {
650
1190
  if (args[0] !== 'api') return false
651
1191
  const endpoint = findApiEndpoint(args)