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
@@ -9,7 +9,7 @@ import path from 'node:path'
9
9
  // not exist.
10
10
  //
11
11
  // Which errnos may be walked past is the security-sensitive part, so it is the
12
- // CALLER's decision, not a default. See the two exported sets below.
12
+ // CALLER's decision, not a default. See the three exported sets below.
13
13
 
14
14
  // The historical, strictest set: only a missing component is walked past.
15
15
  // Correct for allowlist/authorization policies, where an unresolvable component must
@@ -25,6 +25,19 @@ export const RECOVER_MISSING: ReadonlySet<string> = new Set(['ENOENT'])
25
25
  // still blocks. It is NOT sound for an allowlist — see RECOVER_MISSING.
26
26
  export const RECOVER_MISSING_OR_UNSEARCHABLE: ReadonlySet<string> = new Set(['ENOENT', 'EACCES'])
27
27
 
28
+ // Adds ENAMETOOLONG for denylist matching of values that may be prose rather
29
+ // than filesystem paths. Walking past an oversized component is sound for a
30
+ // DENYLIST because lexical matching has already caught direct and
31
+ // traversal-normalized denied paths, while the ancestor walk still resolves a
32
+ // symlinked prefix before rejoining and matching the oversized tail. The
33
+ // oversized component cannot itself name a real file on the affected
34
+ // filesystem. It is NOT sound for an allowlist — see RECOVER_MISSING.
35
+ export const RECOVER_MISSING_OR_UNSEARCHABLE_OR_NAME_TOO_LONG: ReadonlySet<string> = new Set([
36
+ 'ENOENT',
37
+ 'EACCES',
38
+ 'ENAMETOOLONG',
39
+ ])
40
+
28
41
  export type RealIntendedPathOptions = {
29
42
  // Defaults to RECOVER_MISSING: callers must opt in to the broader set.
30
43
  readonly recoverable?: ReadonlySet<string>
@@ -393,7 +393,7 @@ function resolveOne(
393
393
  // kinds worth caching:
394
394
  // - tui: verdict depends only on kind (matchesOrigin's tui rule ignores
395
395
  // sessionId), so every tui origin shares one entry.
396
- // - channel: verdict depends on adapter + workspace + chat + lastInboundAuthorId
396
+ // - channel: verdict depends on adapter + workspace + chat + parentChat + lastInboundAuthorId
397
397
  // (the exact inputs matchesChannel/matchesBucket/matchesAuthor read).
398
398
  // The `c` prefix + NUL separators keep channel keys unambiguous even if a field
399
399
  // contained the delimiter of another.
@@ -402,7 +402,14 @@ function roleCacheKey(origin: SessionOrigin): string | null {
402
402
  case 'tui':
403
403
  return 'tui'
404
404
  case 'channel':
405
- return ['c', origin.adapter, origin.workspace, origin.chat, origin.lastInboundAuthorId ?? ''].join('\u0000')
405
+ return [
406
+ 'c',
407
+ origin.adapter,
408
+ origin.workspace,
409
+ origin.chat,
410
+ origin.parentChat ?? '',
411
+ origin.lastInboundAuthorId ?? '',
412
+ ].join('\u0000')
406
413
  default:
407
414
  return null
408
415
  }
@@ -418,6 +425,7 @@ function toMatchable(origin: SessionOrigin): Parameters<typeof matchesOrigin>[1]
418
425
  adapter: origin.adapter,
419
426
  workspace: origin.workspace,
420
427
  chat: origin.chat,
428
+ ...(origin.parentChat !== undefined ? { parentChat: origin.parentChat } : {}),
421
429
  ...(origin.lastInboundAuthorId !== undefined ? { lastInboundAuthorId: origin.lastInboundAuthorId } : {}),
422
430
  }
423
431
  default:
@@ -27,6 +27,7 @@ export type MatchableOrigin =
27
27
  adapter: AdapterId
28
28
  workspace: string
29
29
  chat: string
30
+ parentChat?: string
30
31
  lastInboundAuthorId?: string
31
32
  }
32
33
 
@@ -53,16 +54,21 @@ function matchesChannel(rule: Extract<MatchRule, { kind: 'channel' }>, origin: M
53
54
 
54
55
  if (rule.bucket !== undefined) {
55
56
  if (!matchesBucket(rule.bucket, origin)) return false
56
- if (rule.chat !== undefined && rule.chat !== origin.chat) return false
57
+ if (rule.chat !== undefined && !matchesChat(rule.chat, origin)) return false
57
58
  } else {
58
59
  if (rule.workspace !== undefined && rule.workspace !== origin.workspace) return false
59
- if (rule.chat !== undefined && rule.chat !== origin.chat) return false
60
+ if (rule.chat !== undefined && !matchesChat(rule.chat, origin)) return false
60
61
  }
61
62
 
62
63
  if (rule.author !== undefined && !matchesAuthor(rule.platform, rule.author, origin.lastInboundAuthorId)) return false
63
64
  return true
64
65
  }
65
66
 
67
+ function matchesChat(ruleChat: string, origin: Extract<MatchableOrigin, { kind: 'channel' }>): boolean {
68
+ if (ruleChat === origin.chat) return true
69
+ return ADAPTER_TO_PLATFORM[origin.adapter] === 'discord' && ruleChat === origin.parentChat
70
+ }
71
+
66
72
  // Webex person ids are base64(`ciscospark://<cluster>/PEOPLE/<uuid-or-email>`),
67
73
  // so a hand-authored or claim-generated rule may carry the raw base64 id, its
68
74
  // decoded ref (UUID for modern accounts, email for legacy Hydra accounts), and
@@ -0,0 +1,15 @@
1
+ export type PiBuiltinToolName = 'read' | 'bash' | 'edit' | 'write' | 'grep' | 'find' | 'ls'
2
+
3
+ export const PI_BUILTIN_TOOL_NAMES: readonly PiBuiltinToolName[] = [
4
+ 'read',
5
+ 'bash',
6
+ 'edit',
7
+ 'write',
8
+ 'grep',
9
+ 'find',
10
+ 'ls',
11
+ ]
12
+
13
+ export const CORE_SYSTEM_TOOL_NAMES = ['web_search', 'web_fetch', 'look_at'] as const
14
+
15
+ export const CORE_TOOL_NAMES: ReadonlySet<string> = new Set([...PI_BUILTIN_TOOL_NAMES, ...CORE_SYSTEM_TOOL_NAMES])
@@ -61,7 +61,21 @@ export type HookBus = {
61
61
  runSessionPrompt: (event: SessionPromptEvent) => Promise<void>
62
62
  runSessionTurnStart: (event: SessionTurnStartEvent) => Promise<void>
63
63
  runSessionTurnEnd: (event: SessionTurnEndEvent) => Promise<void>
64
- runToolBefore: (event: ToolBeforeEvent) => Promise<{ block: true; reason: string } | undefined>
64
+ runToolBefore: (
65
+ event: ToolBeforeEvent,
66
+ guards?: readonly {
67
+ owner: string
68
+ key: string
69
+ tools: ReadonlySet<string>
70
+ check: (
71
+ event: Readonly<ToolBeforeEvent>,
72
+ ) =>
73
+ | undefined
74
+ | { readonly kind: 'block' | 'acknowledgement-required'; readonly reason: string }
75
+ | Promise<undefined | { readonly kind: 'block' | 'acknowledgement-required'; readonly reason: string }>
76
+ }[],
77
+ acknowledgements?: Readonly<Record<string, Readonly<Record<string, boolean>>>>,
78
+ ) => Promise<{ block: true; reason: string } | undefined>
65
79
  runToolAfter: (event: ToolAfterEvent) => Promise<void>
66
80
  count: (name: keyof Hooks) => number
67
81
  }
@@ -84,7 +98,7 @@ type Registries = {
84
98
  'session.prompt': RegisteredHook<'session.prompt'>[]
85
99
  'session.turn.start': RegisteredHook<'session.turn.start'>[]
86
100
  'session.turn.end': RegisteredHook<'session.turn.end'>[]
87
- 'tool.before': RegisteredHook<'tool.before'>[]
101
+ 'tool.before': Array<RegisteredHook<'tool.before'> | { pluginName: string; guardOwner: true; logger: PluginLogger }>
88
102
  'tool.after': RegisteredHook<'tool.after'>[]
89
103
  }
90
104
 
@@ -110,6 +124,7 @@ export function createHookBus(options: CreateHookBusOptions = {}): HookBus {
110
124
  return {
111
125
  registerAll(pluginName, agentDir, logger, hooks) {
112
126
  const base = { pluginName, agentDir, logger }
127
+ r['tool.before'].push({ pluginName, guardOwner: true, logger })
113
128
  if (hooks['session.start']) r['session.start'].push({ ...base, handler: hooks['session.start'] })
114
129
  if (hooks['session.end']) r['session.end'].push({ ...base, handler: hooks['session.end'] })
115
130
  if (hooks['session.idle']) r['session.idle'].push({ ...base, handler: hooks['session.idle'] })
@@ -206,8 +221,26 @@ export function createHookBus(options: CreateHookBusOptions = {}): HookBus {
206
221
  // First plugin to return `{ block: true, reason }` short-circuits. Earlier
207
222
  // plugins' arg mutations remain visible to later plugins via the shared
208
223
  // event.args object.
209
- async runToolBefore(event) {
224
+ async runToolBefore(event, guards = [], acknowledgements) {
210
225
  for (const reg of r['tool.before']) {
226
+ if ('guardOwner' in reg) {
227
+ for (const guard of guards) {
228
+ if (guard.owner !== reg.pluginName || !guard.tools.has(event.tool)) continue
229
+ let result
230
+ try {
231
+ result = await guard.check(event)
232
+ } catch (err) {
233
+ reg.logger.error(`guard ${guard.key} threw: ${err instanceof Error ? err.message : String(err)}`)
234
+ return { block: true, reason: `guard ${guard.key} failed closed after its check threw` }
235
+ }
236
+ if (result === undefined) continue
237
+ if (result.kind === 'block') return { block: true, reason: result.reason }
238
+ if (acknowledgements?.[guard.owner]?.[guard.key] !== true) {
239
+ return { block: true, reason: result.reason }
240
+ }
241
+ }
242
+ continue
243
+ }
211
244
  let result: ToolBeforeResult
212
245
  try {
213
246
  result = await reg.handler(event, ctx(reg))
@@ -234,6 +267,7 @@ export function createHookBus(options: CreateHookBusOptions = {}): HookBus {
234
267
  },
235
268
 
236
269
  count(name) {
270
+ if (name === 'tool.before') return r[name].filter((entry) => !('guardOwner' in entry)).length
237
271
  return r[name].length
238
272
  },
239
273
  }
@@ -1,5 +1,7 @@
1
1
  import { existsSync } from 'node:fs'
2
2
 
3
+ import { z } from 'zod'
4
+
3
5
  import { BUILTIN_COMMAND_NAMES } from '@/cli/builtins'
4
6
  import type { CronJob, PromptJob } from '@/cron'
5
7
 
@@ -65,6 +67,7 @@ export type RegisterContributionsOptions = {
65
67
  }
66
68
 
67
69
  const COMMAND_NAME_REGEX = /^[a-z][a-z0-9-]*$/
70
+ const ACKNOWLEDGE_GUARDS = 'acknowledgeGuards'
68
71
 
69
72
  // CLI subcommands plugins MUST NOT shadow. Derived from BUILTIN_COMMAND_NAMES
70
73
  // so cli/index.ts and registry.ts cannot drift apart.
@@ -80,6 +83,9 @@ export function registerContributions(opts: RegisterContributionsOptions): void
80
83
  if (ex.tools) {
81
84
  for (const [toolName, tool] of Object.entries(ex.tools)) {
82
85
  assertNotEmpty('tool name', toolName, pluginName)
86
+ if (tool.parameters instanceof z.ZodObject && ACKNOWLEDGE_GUARDS in tool.parameters.shape) {
87
+ throw new Error(`plugin ${pluginName}: tool "${toolName}" declares reserved parameter "${ACKNOWLEDGE_GUARDS}"`)
88
+ }
83
89
  const conflict = registry.tools.find((t) => t.toolName === toolName)
84
90
  if (conflict) {
85
91
  throw new Error(`plugin ${pluginName}: tool "${toolName}" already registered by plugin ${conflict.pluginName}`)
@@ -138,9 +144,7 @@ export function registerContributions(opts: RegisterContributionsOptions): void
138
144
  }
139
145
  }
140
146
 
141
- if (ex.hooks) {
142
- hooks.registerAll(pluginName, agentDir, logger, ex.hooks)
143
- }
147
+ hooks.registerAll(pluginName, agentDir, logger, ex.hooks ?? {})
144
148
 
145
149
  if (ex.doctorChecks) {
146
150
  for (const [checkName, check] of Object.entries(ex.doctorChecks)) {
package/src/run/index.ts CHANGED
@@ -64,11 +64,12 @@ import { loadPlugins, type LoadPluginsResult, pluginCronJobs, type PluginRegistr
64
64
  import { createPluginLogger } from '@/plugin/context'
65
65
  import type { CronHandlerContext } from '@/plugin/types'
66
66
  import { createContainerBroker, publishForwardResult, subscribeForwardRequest } from '@/portbroker'
67
- import { formatChannelReloadSummary, ReloadRegistry } from '@/reload'
67
+ import { formatChannelReloadSummary, ReloadRegistry, type ReloadAllResult, type ReloadContext } from '@/reload'
68
68
  import { createClaimController } from '@/role-claim'
69
69
  import {
70
70
  exportClaudeCredentialsFileForAgent,
71
71
  exportCodexAuthFileForAgent,
72
+ exportGithubCliStoreForAgent,
72
73
  hydrateChannelEnvFromSecrets,
73
74
  refreshProviderOAuthForAgent,
74
75
  } from '@/secrets'
@@ -130,6 +131,7 @@ export type StartAgentOptions = {
130
131
  // observe secrets only after the awaited provider-OAuth refresh settles.
131
132
  exportCodexAuthFile?: typeof exportCodexAuthFileForAgent
132
133
  exportClaudeCredentialsFile?: typeof exportClaudeCredentialsFileForAgent
134
+ exportGithubCliStore?: typeof exportGithubCliStoreForAgent
133
135
  // Boot-time proactive provider-OAuth refresh. Injectable so a test can supply
134
136
  // a refresh that holds the real secrets lock on a gate, proving the boot
135
137
  // barrier settles this before any session-producing consumer starts.
@@ -196,12 +198,22 @@ async function startAgentRuntime(
196
198
  caps = createRuntimeCapabilities(process.env, join(cwd, 'secrets.json')),
197
199
  exportCodexAuthFile = exportCodexAuthFileForAgent,
198
200
  exportClaudeCredentialsFile = exportClaudeCredentialsFileForAgent,
201
+ exportGithubCliStore = exportGithubCliStoreForAgent,
199
202
  refreshProviderOAuth = refreshProviderOAuthForAgent,
200
203
  }: StartAgentOptions,
201
204
  registerBootCleanup: (cleanup: () => void | Promise<void>) => void,
202
205
  ): Promise<StartAgentResult> {
203
206
  const reloadRegistry = new ReloadRegistry()
204
207
 
208
+ const reloadAllNonDestructive = async (context?: ReloadContext): Promise<ReloadAllResult> => {
209
+ const results = []
210
+ for (const item of reloadRegistry.list()) {
211
+ if (item.scope === 'providers') continue
212
+ results.push(await reloadRegistry.reloadOne(item.scope, context))
213
+ }
214
+ return { results }
215
+ }
216
+
205
217
  // Wrap globalThis.fetch BEFORE any plugin/session/manager construction so
206
218
  // every LLM provider stream from anywhere in the container is guarded. Logs
207
219
  // one `[llm-fetch]` line per matched request with phase timings and applies
@@ -425,6 +437,17 @@ async function startAgentRuntime(
425
437
  log: (message) => console.warn(message),
426
438
  })
427
439
 
440
+ const githubCliExport = exportGithubCliStore({
441
+ agentDir: cwd,
442
+ log: (message) => console.warn(message),
443
+ })
444
+ if (githubCliExport.action === 'failed') {
445
+ console.warn(
446
+ '[run] trusted GitHub CLI store unavailable; store-backed GitHub pushes will not authenticate. ' +
447
+ 'On the host, run `gh auth login --hostname github.com`, then run a real `typeclaw restart`.',
448
+ )
449
+ }
450
+
428
451
  const claimController = createClaimController({
429
452
  cwd,
430
453
  permissions: pluginsLoaded.permissions,
@@ -482,7 +505,7 @@ async function startAgentRuntime(
482
505
  .filter((child) => child.status === 'running' && child.background === true)
483
506
  .map((child) => child.subagentName),
484
507
  onReload: async () => {
485
- const { results } = await reloadRegistry.reloadAll()
508
+ const { results } = await reloadAllNonDestructive()
486
509
  return formatChannelReloadSummary(results)
487
510
  },
488
511
  // Always registered so /restart's presence in /help, the Slack manifest,
@@ -836,10 +859,13 @@ async function startAgentRuntime(
836
859
  })
837
860
  registerBootCleanup(() => prVerdictActivityBridge.stop())
838
861
  setReviewObserver((review) => {
839
- stream.publish({
840
- target: { kind: 'broadcast' },
841
- payload: { kind: 'pr.verdict-activity', ...review },
842
- })
862
+ void (async () => {
863
+ await channelManager.router.completeGithubReviewRound?.(review)
864
+ stream.publish({
865
+ target: { kind: 'broadcast' },
866
+ payload: { kind: 'pr.verdict-activity', ...review },
867
+ })
868
+ })()
843
869
  })
844
870
  registerBootCleanup(() => setReviewObserver(null))
845
871
 
@@ -1013,7 +1039,7 @@ async function startAgentRuntime(
1013
1039
 
1014
1040
  const serverFactory = createServer({
1015
1041
  port,
1016
- reloadAll: () => reloadRegistry.reloadAll(),
1042
+ reloadAll: reloadAllNonDestructive,
1017
1043
  reloadRegistry,
1018
1044
  sessionFactory,
1019
1045
  stream,
@@ -24,10 +24,22 @@ export type SandboxedCommand = {
24
24
  spawnEnv: Record<string, string>
25
25
  }
26
26
 
27
- // Fixed fd the rendered commandString opens to /dev/null for --ro-bind-data
27
+ // First fd the rendered commandString opens to /dev/null for --ro-bind-data
28
28
  // file masks. 3 is the first fd above stdio; the bash tool's spawn does not
29
29
  // inherit it, so the redirect is part of the command string itself.
30
- const MASK_DATA_FD = 3
30
+ //
31
+ // Each masked file gets its OWN fd counting up from here. bwrap copies a
32
+ // --ro-bind-data op's content out of the fd and then close()s it, so a second
33
+ // op naming an already-consumed fd aborts the whole invocation with
34
+ // "Can't write data to file <dest>: Bad file descriptor" — taking every
35
+ // sandboxed bash call down, not just the mask. Upstream defines no reuse
36
+ // semantics for the operand fd (bwrap.xml: "Copy from the file descriptor FD"),
37
+ // and bubblewrap's own demo plus flatpak both allocate a distinct fd per op.
38
+ const FIRST_MASK_DATA_FD = 3
39
+
40
+ function maskDataFd(index: number): number {
41
+ return FIRST_MASK_DATA_FD + index
42
+ }
31
43
 
32
44
  // Pure: no I/O, no bwrap availability probe (that is `ensureBwrapAvailable`'s
33
45
  // job). Given a bash command and a policy, returns the bwrap-wrapped argv plus
@@ -40,8 +52,9 @@ export function buildSandboxedCommand(command: string, policy: SandboxPolicy = {
40
52
  applyCommandFilter(command, policy.commandFilter)
41
53
  }
42
54
  const argv = buildArgv(command, policy)
43
- const needsMaskFd = (policy.masks?.files?.length ?? 0) > 0
44
- const commandString = needsMaskFd ? `${formatCommand(argv)} ${MASK_DATA_FD}</dev/null` : formatCommand(argv)
55
+ const maskRedirects = (policy.masks?.files ?? []).map((_, i) => `${maskDataFd(i)}</dev/null`)
56
+ const commandString =
57
+ maskRedirects.length > 0 ? `${formatCommand(argv)} ${maskRedirects.join(' ')}` : formatCommand(argv)
45
58
  return { argv, commandString, spawnEnv: resolveSpawnEnv(policy.env) }
46
59
  }
47
60
 
@@ -91,7 +104,14 @@ function buildArgv(command: string, policy: SandboxPolicy): string[] {
91
104
  argv.push('--die-with-parent')
92
105
  }
93
106
 
94
- const inheritedNames = new Set(policy.env?.inherit ?? [])
107
+ const withheldNames = new Set(policy.env?.withhold ?? [])
108
+ const inheritedNames = new Set((policy.env?.inherit ?? []).filter((name) => !withheldNames.has(name)))
109
+ const unsetNames = new Set<string>()
110
+ const pushUnset = (name: string): void => {
111
+ if (unsetNames.has(name)) return
112
+ unsetNames.add(name)
113
+ argv.push('--unsetenv', name)
114
+ }
95
115
  if (inheritedNames.size === 0) {
96
116
  argv.push('--clearenv')
97
117
  } else {
@@ -101,9 +121,10 @@ function buildArgv(command: string, policy: SandboxPolicy): string[] {
101
121
  ...Object.keys(policy.env?.set ?? {}),
102
122
  ])
103
123
  for (const key of Object.keys(process.env).sort()) {
104
- if (!retained.has(key)) argv.push('--unsetenv', key)
124
+ if (!retained.has(key)) pushUnset(key)
105
125
  }
106
126
  }
127
+ for (const name of withheldNames) pushUnset(name)
107
128
  for (const [key, value] of Object.entries(resolveEnv(policy.env))) {
108
129
  if (inheritedNames.has(key)) continue
109
130
  argv.push('--setenv', key, value)
@@ -214,9 +235,9 @@ function appendMasks(argv: string[], policy: SandboxPolicy): void {
214
235
  for (const dir of policy.masks?.dirs ?? []) {
215
236
  argv.push('--tmpfs', dir)
216
237
  }
217
- for (const file of policy.masks?.files ?? []) {
218
- argv.push('--ro-bind-data', String(MASK_DATA_FD), file)
219
- }
238
+ ;(policy.masks?.files ?? []).forEach((file, i) => {
239
+ argv.push('--ro-bind-data', String(maskDataFd(i)), file)
240
+ })
220
241
  }
221
242
 
222
243
  function appendWritable(argv: string[], policy: SandboxPolicy): void {
@@ -267,8 +288,13 @@ function appendMount(argv: string[], mount: SandboxMount): void {
267
288
  }
268
289
 
269
290
  function resolveEnv(env: SandboxEnvPolicy | undefined): Record<string, string> {
270
- const resolved: Record<string, string> = { ...DEFAULT_SANDBOX_ENV, ...env?.set }
291
+ const withheldNames = new Set(env?.withhold ?? [])
292
+ const resolved: Record<string, string> = {}
293
+ for (const [key, value] of Object.entries({ ...DEFAULT_SANDBOX_ENV, ...env?.set })) {
294
+ if (!withheldNames.has(key)) resolved[key] = value
295
+ }
271
296
  for (const key of env?.passthrough ?? []) {
297
+ if (withheldNames.has(key)) continue
272
298
  const value = process.env[key]
273
299
  if (value !== undefined) resolved[key] = value
274
300
  }
@@ -282,10 +308,13 @@ function resolveEnv(env: SandboxEnvPolicy | undefined): Record<string, string> {
282
308
  // build-to-spawn TOCTOU on the --unsetenv enumeration.
283
309
  function resolveSpawnEnv(env: SandboxEnvPolicy | undefined): Record<string, string> {
284
310
  const resolved = resolveEnv(env)
311
+ const withheldNames = new Set(env?.withhold ?? [])
285
312
  for (const name of env?.inherit ?? []) {
313
+ if (withheldNames.has(name)) continue
286
314
  const value = process.env[name]
287
315
  if (value !== undefined) resolved[name] = value
288
316
  }
317
+ for (const name of withheldNames) delete resolved[name]
289
318
  return resolved
290
319
  }
291
320
 
@@ -37,6 +37,7 @@ export type SandboxProcStrategy = 'tmpfs' | 'none' | 'real-proc' | 'proc-bind'
37
37
  export type SandboxEnvPolicy = {
38
38
  set?: Record<string, string>
39
39
  passthrough?: string[]
40
+ withhold?: string[]
40
41
  // Preserve these names from bwrap's parent environment without rendering
41
42
  // their values in argv. The builder switches from --clearenv to explicit
42
43
  // --unsetenv for every other inherited name. Reserved for command-scoped
@@ -59,8 +60,11 @@ export type SandboxProcessPolicy = {
59
60
  // bwrap primitive that masks a single FILE (--tmpfs is dir-only). --ro-bind-data
60
61
  // reads its empty content from a file descriptor, and the bash tool spawns with
61
62
  // stdio ["ignore","pipe","pipe"] — no inherited extra fds — so the rendered
62
- // commandString self-opens fd MASK_DATA_FD via a `<fd>< /dev/null` redirection
63
- // appended after `bash -c <command>`. Masks MUST render after the broad parent
63
+ // commandString self-opens ONE fd PER masked file (counting up from
64
+ // FIRST_MASK_DATA_FD) via `<fd></dev/null` redirections appended after
65
+ // `bash -c <command>`. The fds cannot be shared: bwrap close()s each after
66
+ // copying it, so a reused fd aborts the entire invocation with EBADF and kills
67
+ // every sandboxed bash call. Masks MUST render after the broad parent
64
68
  // mounts: bwrap applies mount ops in command-line order and the last op on a
65
69
  // path wins, so a mask emitted before its parent bind would be re-exposed.
66
70
  export type SandboxMaskPolicy = {
@@ -0,0 +1,158 @@
1
+ import {
2
+ chmodSync,
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ openSync,
7
+ closeSync,
8
+ renameSync,
9
+ unlinkSync,
10
+ writeFileSync,
11
+ } from 'node:fs'
12
+ import { homedir } from 'node:os'
13
+ import { dirname, join } from 'node:path'
14
+
15
+ import type { GithubCliSecrets } from './schema'
16
+ import { SecretsBackend } from './storage'
17
+
18
+ const DIR_MODE = 0o700
19
+ const FILE_MODE = 0o600
20
+ const HOSTS_FILE_LIMIT = 256 * 1024
21
+
22
+ export type ExportGithubCliStoreResult =
23
+ | { action: 'skipped'; reason: 'no-github-cli-credential' }
24
+ | { action: 'wrote'; path: string }
25
+ | { action: 'failed'; reason: string }
26
+
27
+ export type ExportGithubCliStoreOptions = {
28
+ githubCli?: GithubCliSecrets
29
+ homeDir?: string
30
+ log?: (message: string) => void
31
+ }
32
+
33
+ export function exportGithubCliStoreIfApplicable(options: ExportGithubCliStoreOptions): ExportGithubCliStoreResult {
34
+ const homeDir = options.homeDir ?? homedir()
35
+ const target = join(homeDir, '.config', 'gh', 'hosts.yml')
36
+ if (options.githubCli === undefined) {
37
+ try {
38
+ removeRuntimeStore(target, homeDir)
39
+ return { action: 'skipped', reason: 'no-github-cli-credential' }
40
+ } catch {
41
+ return failedExport(options.log)
42
+ }
43
+ }
44
+ try {
45
+ validateHosts(options.githubCli.hosts)
46
+ ensurePrivateDirectoryChain(dirname(target), homeDir)
47
+ rejectUnsafeTarget(target)
48
+ writeAtomic(target, options.githubCli.hosts)
49
+ return { action: 'wrote', path: target }
50
+ } catch {
51
+ try {
52
+ removeRuntimeStore(target, homeDir)
53
+ } catch {
54
+ // The original export failure remains the operator-facing cause.
55
+ }
56
+ return failedExport(options.log)
57
+ }
58
+ }
59
+
60
+ export function exportGithubCliStoreForAgent(options: {
61
+ agentDir: string
62
+ homeDir?: string
63
+ log?: (message: string) => void
64
+ }): ExportGithubCliStoreResult {
65
+ try {
66
+ const githubCli = new SecretsBackend(join(options.agentDir, 'secrets.json')).tryReadGithubCliSync()
67
+ return exportGithubCliStoreIfApplicable({
68
+ ...(githubCli !== undefined ? { githubCli } : {}),
69
+ ...(options.homeDir !== undefined ? { homeDir: options.homeDir } : {}),
70
+ ...(options.log !== undefined ? { log: options.log } : {}),
71
+ })
72
+ } catch {
73
+ try {
74
+ removeRuntimeStore(join(options.homeDir ?? homedir(), '.config', 'gh', 'hosts.yml'), options.homeDir ?? homedir())
75
+ } catch {
76
+ // Reading failed first; cleanup is best-effort and must not mask that cause.
77
+ }
78
+ const reason = 'Could not read the stored trusted GitHub CLI credential.'
79
+ options.log?.(`exportGithubCliStore: ${reason}`)
80
+ return { action: 'failed', reason }
81
+ }
82
+ }
83
+
84
+ function failedExport(log: ((message: string) => void) | undefined): ExportGithubCliStoreResult {
85
+ const reason = 'Could not reconstruct the trusted GitHub CLI credential store.'
86
+ log?.(`exportGithubCliStore: ${reason}`)
87
+ return { action: 'failed', reason }
88
+ }
89
+
90
+ function validateHosts(hosts: string): void {
91
+ if (hosts.length === 0 || hosts.includes('\0') || Buffer.byteLength(hosts) > HOSTS_FILE_LIMIT) {
92
+ throw new Error('invalid GitHub CLI store')
93
+ }
94
+ }
95
+
96
+ function ensurePrivateDirectoryChain(targetDir: string, homeDir: string): void {
97
+ rejectNonDirectoryOrSymlink(homeDir)
98
+ const configDir = join(homeDir, '.config')
99
+ ensurePrivateDirectory(configDir)
100
+ ensurePrivateDirectory(targetDir)
101
+ }
102
+
103
+ function ensurePrivateDirectory(path: string): void {
104
+ if (existsSync(path)) rejectNonDirectoryOrSymlink(path)
105
+ else mkdirSync(path, { mode: DIR_MODE })
106
+ chmodSync(path, DIR_MODE)
107
+ }
108
+
109
+ function rejectNonDirectoryOrSymlink(path: string): void {
110
+ const stat = lstatSync(path)
111
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error('unsafe GitHub CLI store directory')
112
+ }
113
+
114
+ function rejectUnsafeTarget(path: string): void {
115
+ let stat: ReturnType<typeof lstatSync>
116
+ try {
117
+ stat = lstatSync(path)
118
+ } catch (error) {
119
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
120
+ throw error
121
+ }
122
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error('unsafe GitHub CLI store target')
123
+ }
124
+
125
+ function removeRuntimeStore(target: string, homeDir: string): void {
126
+ rejectNonDirectoryOrSymlink(homeDir)
127
+ for (const path of [join(homeDir, '.config'), dirname(target)]) {
128
+ if (!existsSync(path)) return
129
+ rejectNonDirectoryOrSymlink(path)
130
+ }
131
+ let stat: ReturnType<typeof lstatSync>
132
+ try {
133
+ stat = lstatSync(target)
134
+ } catch (error) {
135
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
136
+ throw error
137
+ }
138
+ if (!stat.isFile() && !stat.isSymbolicLink()) throw new Error('unsafe GitHub CLI store target')
139
+ unlinkSync(target)
140
+ }
141
+
142
+ function writeAtomic(target: string, hosts: string): void {
143
+ const tmp = `${target}.${process.pid}.${Date.now()}.tmp`
144
+ const fd = openSync(tmp, 'wx', FILE_MODE)
145
+ closeSync(fd)
146
+ try {
147
+ writeFileSync(tmp, hosts, { encoding: 'utf8', mode: FILE_MODE })
148
+ renameSync(tmp, target)
149
+ chmodSync(target, FILE_MODE)
150
+ } catch (error) {
151
+ try {
152
+ unlinkSync(tmp)
153
+ } catch {
154
+ // best-effort cleanup after an atomic write failure
155
+ }
156
+ throw error
157
+ }
158
+ }
@@ -1,4 +1,10 @@
1
- export { type Channels, type GithubSecretsBlock, type McpCredential, type McpSlice } from './schema'
1
+ export {
2
+ type Channels,
3
+ type GithubCliSecrets,
4
+ type GithubSecretsBlock,
5
+ type McpCredential,
6
+ type McpSlice,
7
+ } from './schema'
2
8
 
3
9
  export { createSecretsStoreForAgent, SecretsBackend } from './storage'
4
10
 
@@ -6,6 +12,18 @@ export { type Secret } from './resolve'
6
12
 
7
13
  export { hydrateChannelEnvFromSecrets } from './hydrate'
8
14
 
15
+ export {
16
+ type GithubCliProvisionResult,
17
+ type GithubCliProvisionRunner,
18
+ provisionGithubCliStore,
19
+ } from './provision-github-cli-store'
20
+
21
+ export {
22
+ type ExportGithubCliStoreResult,
23
+ exportGithubCliStoreForAgent,
24
+ exportGithubCliStoreIfApplicable,
25
+ } from './export-github-cli-store'
26
+
9
27
  export {
10
28
  type ExportCodexAuthFileResult,
11
29
  exportCodexAuthFileForAgent,