typeclaw 0.48.7 → 0.48.8

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 (104) 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-classify.ts +40 -5
  56. package/src/channels/adapters/slack.ts +3 -9
  57. package/src/channels/adapters/webex-bot-classify.ts +4 -33
  58. package/src/channels/adapters/webex-bot.ts +2 -4
  59. package/src/channels/adapters/webex-classify.ts +4 -33
  60. package/src/channels/adapters/webex-format.ts +36 -0
  61. package/src/channels/adapters/webex.ts +2 -4
  62. package/src/channels/continuation-willingness.ts +64 -39
  63. package/src/channels/github-rereview-guard.ts +20 -0
  64. package/src/channels/github-review-turn-ledger.ts +11 -1
  65. package/src/channels/github-review-verdict-coordinator.ts +475 -41
  66. package/src/channels/github-verdict-activity.ts +14 -5
  67. package/src/channels/persistence.ts +89 -5
  68. package/src/channels/router.ts +1187 -254
  69. package/src/channels/types.ts +21 -5
  70. package/src/cli/compose-stats.ts +6 -7
  71. package/src/cli/compose-status.ts +6 -7
  72. package/src/cli/compose-usage.ts +6 -7
  73. package/src/cli/stats.ts +6 -7
  74. package/src/cli/status.ts +7 -8
  75. package/src/cli/ui.ts +4 -4
  76. package/src/container/start.ts +41 -1
  77. package/src/cron/consumer.ts +30 -9
  78. package/src/cron/scheduler.ts +24 -9
  79. package/src/doctor/channel-checks.ts +64 -0
  80. package/src/doctor/report.ts +8 -8
  81. package/src/dreams/render.ts +2 -2
  82. package/src/init/dockerfile.ts +8 -1
  83. package/src/inspect/render.ts +2 -2
  84. package/src/path-safety/real-intended-path.ts +14 -1
  85. package/src/permissions/permissions.ts +10 -2
  86. package/src/permissions/resolve.ts +8 -2
  87. package/src/plugin/core-tool-names.ts +15 -0
  88. package/src/plugin/hooks.ts +37 -3
  89. package/src/plugin/registry.ts +7 -3
  90. package/src/run/index.ts +33 -7
  91. package/src/sandbox/build.ts +19 -3
  92. package/src/sandbox/policy.ts +1 -0
  93. package/src/secrets/export-github-cli-store.ts +158 -0
  94. package/src/secrets/index.ts +19 -1
  95. package/src/secrets/provision-github-cli-store.ts +322 -0
  96. package/src/secrets/schema.ts +13 -7
  97. package/src/secrets/storage.ts +30 -0
  98. package/src/shared/index.ts +2 -0
  99. package/src/shared/style-text.ts +13 -0
  100. package/src/skills/typeclaw-channel-github/SKILL.md +24 -12
  101. package/src/skills/typeclaw-config/SKILL.md +3 -1
  102. package/src/skills/typeclaw-github-contributing/SKILL.md +6 -2
  103. package/src/skills/typeclaw-permissions/SKILL.md +11 -22
  104. package/src/usage/report.ts +3 -3
@@ -12,6 +12,7 @@ import {
12
12
  type ChannelRouter,
13
13
  } from '@/channels/router'
14
14
  import { ADAPTER_IDS, type AdapterId } from '@/channels/schema'
15
+ import type { GithubReviewFollowupRound } from '@/channels/types'
15
16
 
16
17
  import { type ChannelToolLogger, consoleChannelLogger, formatChannelToolFailure } from './channel-log'
17
18
  import { renderOutboundEcho, TOOL_RESULT_PREFIX } from './channel-reply'
@@ -22,6 +23,7 @@ export type ChannelSendOrigin = {
22
23
  workspace: string
23
24
  chat: string
24
25
  thread: string | null
26
+ githubReviewRound?: GithubReviewFollowupRound
25
27
  }
26
28
 
27
29
  export type CreateChannelSendToolOptions = {
@@ -233,6 +235,14 @@ export function createChannelSendTool({
233
235
  wantsResolve,
234
236
  moreWorkThisTurn: false,
235
237
  getReviewState: (req) => router.getReviewState(req),
238
+ ...(origin !== undefined &&
239
+ origin.adapter === adapter &&
240
+ origin.workspace === params.workspace &&
241
+ origin.chat === params.chat &&
242
+ origin.thread === (params.thread ?? null) &&
243
+ origin.githubReviewRound !== undefined
244
+ ? { round: origin.githubReviewRound }
245
+ : {}),
236
246
  })
237
247
  if (rereview.block) {
238
248
  logger.warn(formatChannelToolFailure('channel_send', rereview.reason))
@@ -261,6 +271,18 @@ export function createChannelSendTool({
261
271
  details: { ok: false, error: resolve.error },
262
272
  }
263
273
  }
274
+ if (resolve.kind === 'already-resolved') {
275
+ router.finishGithubReviewRoundCloseout?.({
276
+ sessionId,
277
+ workspace: params.workspace,
278
+ prNumber: parseGithubPrNumber(params.chat),
279
+ thread: params.thread ?? null,
280
+ })
281
+ return {
282
+ content: [{ type: 'text' as const, text: alreadyResolvedHint(params.thread ?? null) }],
283
+ details: { ok: true },
284
+ }
285
+ }
264
286
  // `no-match`: the thread listed cleanly but nothing is rooted at this
265
287
  // comment (gone, or a mispaired id from the bare-id follow-up list). It
266
288
  // stays non-blocking so a genuinely-deleted thread's ack still posts,
@@ -271,6 +293,12 @@ export function createChannelSendTool({
271
293
  resolveMissNotice = resolveMissHint(params.thread ?? null)
272
294
  } else {
273
295
  recordResolvedThreadFromSend(sessionId, params.workspace, params.chat, params.thread ?? null)
296
+ router.finishGithubReviewRoundCloseout?.({
297
+ sessionId,
298
+ workspace: params.workspace,
299
+ prNumber: parseGithubPrNumber(params.chat),
300
+ thread: params.thread ?? null,
301
+ })
274
302
  }
275
303
  }
276
304
 
@@ -340,6 +368,11 @@ export function createChannelSendTool({
340
368
  })
341
369
  }
342
370
 
371
+ function parseGithubPrNumber(chat: string): number {
372
+ const match = /^pr:(\d+)$/.exec(chat)
373
+ return match === null ? 0 : Number(match[1])
374
+ }
375
+
343
376
  function missingReviewThreadResolveChoiceError(input: {
344
377
  adapter: AdapterId
345
378
  chat: string
@@ -360,7 +393,11 @@ function missingReviewThreadResolveChoiceError(input: {
360
393
  )
361
394
  }
362
395
 
363
- type ResolveOutcome = { kind: 'resolved' } | { kind: 'no-match' } | { kind: 'block'; error: string }
396
+ type ResolveOutcome =
397
+ | { kind: 'resolved' }
398
+ | { kind: 'already-resolved' }
399
+ | { kind: 'no-match' }
400
+ | { kind: 'block'; error: string }
364
401
 
365
402
  async function resolveReviewThreadBeforeSend(
366
403
  router: ChannelRouter,
@@ -378,11 +415,17 @@ async function resolveReviewThreadBeforeSend(
378
415
  chat: target.chat,
379
416
  rootCommentId: target.thread,
380
417
  })
381
- if (result.ok) return { kind: 'resolved' }
418
+ if (result.ok) return { kind: result.alreadyResolved === true ? 'already-resolved' : 'resolved' }
382
419
  if (result.code === 'no-match') return { kind: 'no-match' }
383
420
  return { kind: 'block', error: `could not resolve review thread: ${result.error}` }
384
421
  }
385
422
 
423
+ function alreadyResolvedHint(thread: string | null): string {
424
+ return fenceRuntimeNotice(
425
+ `review thread ${JSON.stringify(thread)} was already resolved; no acknowledgement comment was posted.`,
426
+ )
427
+ }
428
+
386
429
  // The model asked to resolve but no thread was rooted at this comment. Fenced
387
430
  // as a runtime notice (not chat prose) so a persona-rich model reads it as
388
431
  // tool feedback and re-targets, rather than replying to it in-character.
@@ -66,6 +66,8 @@ export function createPostGithubReviewTool(options: {
66
66
  workspace: origin.workspace,
67
67
  prNumber,
68
68
  verdict,
69
+ ...(origin.githubReviewRound !== undefined ? { round: origin.githubReviewRound } : {}),
70
+ thread: origin.thread,
69
71
  retainDuplicateLease: params.event === 'REQUEST_CHANGES',
70
72
  })
71
73
  if (blocked !== null) {
@@ -74,8 +76,9 @@ export function createPostGithubReviewTool(options: {
74
76
  blocked.kind === 'duplicate' &&
75
77
  blocked.duplicateSource === 'standing'
76
78
  ) {
79
+ let fallbackLanded = false
77
80
  try {
78
- return await postDuplicateRequestChangesComment({
81
+ const fallback = await postDuplicateRequestChangesComment({
79
82
  router,
80
83
  origin,
81
84
  sessionId,
@@ -84,9 +87,18 @@ export function createPostGithubReviewTool(options: {
84
87
  comments: (params.comments ?? []).map(toReviewFinding),
85
88
  logger,
86
89
  })
90
+ fallbackLanded = fallback.landed
91
+ return fallback.result
87
92
  } finally {
93
+ // The retained lease only serializes OVERLAPPING siblings. Recording the
94
+ // landing is what stops the sequential ones: sibling thread sessions of
95
+ // the same PR finish minutes apart, and without this each would see the
96
+ // same `standing` block and publish its own copy of the review.
88
97
  if (blocked.leaseRetained === true) {
89
- await verdictGuard.release({ callId: coordinationCallId, succeeded: false })
98
+ await verdictGuard.release({
99
+ callId: coordinationCallId,
100
+ outcome: fallbackLanded ? 'fallback-landed' : 'failed',
101
+ })
90
102
  }
91
103
  }
92
104
  }
@@ -133,7 +145,10 @@ export function createPostGithubReviewTool(options: {
133
145
  return { content: [{ type: 'text' as const, text: fenceToolResult(receipt) }], details }
134
146
  } finally {
135
147
  if (verdict !== null) {
136
- await verdictGuard.release({ callId: coordinationCallId, succeeded: releaseAsLanded })
148
+ await verdictGuard.release({
149
+ callId: coordinationCallId,
150
+ outcome: releaseAsLanded ? 'formal-landed' : 'failed',
151
+ })
137
152
  }
138
153
  }
139
154
  },
@@ -159,7 +174,7 @@ async function postDuplicateRequestChangesComment(args: {
159
174
  },
160
175
  { accountingTarget: args.origin },
161
176
  )
162
- if (!result.ok) return denied(args.logger, result.error, result.code)
177
+ if (!result.ok) return { landed: false, result: denied(args.logger, result.error, result.code) }
163
178
 
164
179
  recordReviewOutput({
165
180
  sessionId: args.sessionId,
@@ -175,15 +190,18 @@ async function postDuplicateRequestChangesComment(args: {
175
190
  ...(result.messageIds !== undefined ? { messageIds: result.messageIds } : {}),
176
191
  }
177
192
  return {
178
- content: [
179
- {
180
- type: 'text' as const,
181
- text: fenceToolResult(
182
- 'GitHub PR comment posted because the existing CHANGES_REQUESTED review is still active.',
183
- ),
184
- },
185
- ],
186
- details,
193
+ landed: true,
194
+ result: {
195
+ content: [
196
+ {
197
+ type: 'text' as const,
198
+ text: fenceToolResult(
199
+ 'GitHub PR comment posted because the existing CHANGES_REQUESTED review is still active.',
200
+ ),
201
+ },
202
+ ],
203
+ details,
204
+ },
187
205
  }
188
206
  }
189
207
 
@@ -146,6 +146,21 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
146
146
  if (!hasPermissionForSubagent(permissions, origin, params.subagent_type, subagent)) {
147
147
  return errorResult('subagent.spawn denied: insufficient permissions')
148
148
  }
149
+ // Ordered AFTER the permission check on purpose: this message reports which
150
+ // sibling session holds the round, so an unauthorized caller must be turned
151
+ // away as unauthorized rather than told anything about the PR's round state.
152
+ if (
153
+ params.subagent_type === 'reviewer' &&
154
+ origin?.kind === 'channel' &&
155
+ origin.adapter === 'github' &&
156
+ /^pr:\d+$/.test(origin.chat) &&
157
+ origin.githubReviewRound !== undefined &&
158
+ origin.thread !== origin.githubReviewRound.carrierThread
159
+ ) {
160
+ return errorResult(
161
+ "reviewer spawn denied: another session of this PR is the designated carrier for this review round and will post the review; close out only this session's thread.",
162
+ )
163
+ }
149
164
  // Fail closed past the chain-length ceiling. The tool is present on
150
165
  // subagent sessions (operator/reviewer can delegate), but a session
151
166
  // already at MAX_SUBAGENT_DEPTH cannot spawn a deeper one — this is the
@@ -2,7 +2,7 @@ export type InlineStyleVisibility = 'hidden' | 'visible' | 'uncertain'
2
2
 
3
3
  const MAX_RAW_INLINE_STYLE_CHARS = 64 * 1024
4
4
  const MAX_CSS_NESTING_DEPTH = 32
5
- const RELEVANT_PROPERTIES = new Set(['content-visibility', 'display', 'visibility', 'opacity'])
5
+ export const VISIBILITY_PROPERTIES = new Set(['content-visibility', 'display', 'visibility', 'opacity'])
6
6
  const CSS_NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/iu
7
7
  const CSS_PERCENTAGE = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?%$/iu
8
8
  const VISIBLE_DISPLAY_VALUES = new Set([
@@ -54,7 +54,7 @@ export function classifyRawInlineStyleVisibility(style: string): InlineStyleVisi
54
54
  continue
55
55
  }
56
56
  const property = asciiFold(decodedProperty.value.trim())
57
- if (!RELEVANT_PROPERTIES.has(property)) continue
57
+ if (!VISIBILITY_PROPERTIES.has(property)) continue
58
58
 
59
59
  const declaration = classifyDeclaration(property, rawValue)
60
60
  const prior = declarations.get(property)
@@ -2,7 +2,7 @@ import type { Readability as ReadabilityClass } from '@mozilla/readability'
2
2
  import type TurndownService from 'turndown'
3
3
 
4
4
  import { walkHtmlLexically } from '../html-lexical'
5
- import { classifyRawInlineStyleVisibility } from '../inline-style-visibility'
5
+ import { classifyRawInlineStyleVisibility, VISIBILITY_PROPERTIES } from '../inline-style-visibility'
6
6
 
7
7
  // Perf: jsdom (+readability+turndown) costs ~40-60MB RSS at import time. Keep it
8
8
  // lazy so idle agents that never call web_fetch don't pay for it. Do NOT hoist to
@@ -180,7 +180,7 @@ function countRawCssRules(source: string): { rules: number; selectorComponents:
180
180
  return { rules, selectorComponents }
181
181
  }
182
182
 
183
- function buildComputedStyleResolver(
183
+ export function buildComputedStyleResolver(
184
184
  document: Document,
185
185
  resolve: (element: Element) => CSSStyleDeclaration,
186
186
  ): ((element: Element) => CSSStyleDeclaration) | undefined {
@@ -206,7 +206,52 @@ function buildComputedStyleResolver(
206
206
  if (selectorComponentCount * elementCount > MAX_COMPUTED_STYLE_WORK) {
207
207
  throw new Error('Embedded stylesheet complexity limit exceeded')
208
208
  }
209
- return resolve
209
+ reduceToVisibilityDeclarations(styles)
210
+ return (element) => {
211
+ reduceInlineStyleToVisibilityDeclarations(element)
212
+ return resolve(element)
213
+ }
214
+ }
215
+
216
+ // getComputedStyle resolves the WHOLE declaration, but pruneHiddenContent reads
217
+ // only VISIBILITY_PROPERTIES. Everything else is computed at our expense and at
218
+ // our risk, so it is deleted from the CSSOM before the first resolve.
219
+ //
220
+ // Load-bearing, not a micro-optimization: this is the fix for an OOM that killed
221
+ // a live agent. jsdom 29.0.2 allocates ~27GB and burns ~11s inside a SINGLE
222
+ // getComputedStyle() call while reconciling a `border` shorthand against a
223
+ // `border-bottom` longhand (living/css/helpers/shorthand-properties.js), then
224
+ // throws a TypeError. The triggering CSS is ubiquitous rather than hostile: a
225
+ // reset (`span { border: 0 }`) plus a component rule that omits the border
226
+ // colour (`.x { border-bottom: 1px solid }`), as every Emotion/MUI page emits.
227
+ // A 236KB page with 545 elements was enough to exhaust a 16GB host.
228
+ //
229
+ // Nothing upstream can catch it. The allocation is SYNCHRONOUS, so the request
230
+ // AbortSignal and the 30s timeout never get a turn, and the try/catch in
231
+ // isHiddenElement catches the TypeError only after the memory is committed. The
232
+ // complexity budgets above bound the QUANTITY of CSS work, so a single
233
+ // pathological declaration on a small page passes all of them.
234
+ //
235
+ // Deleting declarations rather than hand-rolling a cascade keeps jsdom
236
+ // authoritative for specificity, inheritance, and !important on the properties
237
+ // actually read, so pruning behaviour is unchanged. It also generalises: a
238
+ // future jsdom blowup in any property never read here is now unreachable.
239
+ // Only the CSSOM is edited — <style> textContent is untouched, so the budgets
240
+ // above still measure the original stylesheet.
241
+ export function reduceToVisibilityDeclarations(styles: HTMLStyleElement[]): void {
242
+ let budget = MAX_EMBEDDED_STYLE_RULES
243
+ const visit = (rules: CSSRuleList): void => {
244
+ for (const rule of Array.from(rules)) {
245
+ if (budget-- <= 0) return
246
+ if ('cssRules' in rule) visit((rule as CSSGroupingRule).cssRules)
247
+ const { style } = rule as CSSStyleRule
248
+ if (!style) continue
249
+ removeUnreadDeclarations(style)
250
+ }
251
+ }
252
+ for (const style of styles) {
253
+ if (style.sheet !== null) visit(style.sheet.cssRules)
254
+ }
210
255
  }
211
256
 
212
257
  function countCssRules(rules: CSSRuleList): { rules: number; selectorComponents: number } {
@@ -273,14 +318,61 @@ function countVisibleTextCharacters(body: HTMLElement | null): number {
273
318
  return Array.from(normalizeVisibleText(body.textContent ?? '')).length
274
319
  }
275
320
 
276
- function pruneHiddenContent(
321
+ export function pruneHiddenContent(
277
322
  document: Document,
278
323
  computedStyle: ((element: Element) => CSSStyleDeclaration) | undefined,
279
324
  ): void {
280
325
  for (const details of document.querySelectorAll('details:not([open])')) pruneClosedDetails(details)
281
326
 
282
- for (const element of document.querySelectorAll('*')) {
283
- if (isHiddenElement(element, computedStyle)) element.remove()
327
+ const elements = Array.from(document.querySelectorAll('*'))
328
+ // Three passes, because reducing an element's inline style has to happen
329
+ // after the checks that read the declarations it removes, but before ANY
330
+ // element resolves a computed style.
331
+ //
332
+ // A single interleaved pass cannot satisfy both. querySelectorAll returns a
333
+ // STATIC list, so a descendant is still visited after its ancestor is
334
+ // removed, and jsdom resolves inherited properties by walking parentElement
335
+ // into that removed ancestor. An ancestor pruned by `hidden`, aria-hidden or
336
+ // the offscreen test returns before the resolver ever touches it, so it would
337
+ // still be carrying its full inline declaration when the descendant reaches
338
+ // it — the OOM route again, one level up.
339
+ const staticallyHidden = new Set<Element>()
340
+ for (const element of elements) {
341
+ if (isStaticallyHiddenElement(element)) staticallyHidden.add(element)
342
+ }
343
+ for (const element of elements) reduceInlineStyleToVisibilityDeclarations(element)
344
+ for (const element of elements) {
345
+ if (staticallyHidden.has(element) || isComputedHiddenElement(element, computedStyle)) element.remove()
346
+ }
347
+ }
348
+
349
+ // The inline style attribute is the second way a declaration reaches the
350
+ // cascade, so reducing stylesheets alone leaves the same OOM reachable via
351
+ // style="border:0;border-bottom:1px solid". See reduceToVisibilityDeclarations
352
+ // for the mechanism.
353
+ //
354
+ // This runs inside the resolver rather than at a call site so the invariant
355
+ // holds for every caller: an element cannot reach getComputedStyle carrying a
356
+ // declaration outside VISIBILITY_PROPERTIES. It is safe to reduce this late
357
+ // because the callers that need the removed declarations read them WITHOUT the
358
+ // resolver — classifyRawInlineStyleVisibility parses the raw attribute text and
359
+ // the offscreen test reads position/left/top off element.style, both before
360
+ // isHiddenElement resolves anything.
361
+ function reduceInlineStyleToVisibilityDeclarations(element: Element): void {
362
+ if (!('style' in element)) return
363
+ removeUnreadDeclarations((element as HTMLElement).style)
364
+ }
365
+
366
+ // Custom properties are retained even though they are not read directly: a
367
+ // retained declaration can be written `opacity: var(--hidden)`, and dropping
368
+ // the `--hidden` definition would silently un-hide content this guard exists to
369
+ // prune. They are safe to keep because a custom property is stored as an
370
+ // unparsed token sequence — it never enters the shorthand expansion that makes
371
+ // ordinary properties dangerous.
372
+ function removeUnreadDeclarations(style: CSSStyleDeclaration): void {
373
+ for (const property of Array.from(style)) {
374
+ if (property.startsWith('--')) continue
375
+ if (!VISIBILITY_PROPERTIES.has(property.toLocaleLowerCase())) style.removeProperty(property)
284
376
  }
285
377
  }
286
378
 
@@ -291,10 +383,10 @@ function pruneClosedDetails(details: Element): void {
291
383
  }
292
384
  }
293
385
 
294
- function isHiddenElement(
295
- element: Element,
296
- computedStyle: ((element: Element) => CSSStyleDeclaration) | undefined,
297
- ): boolean {
386
+ // Everything decidable from attributes and the element's own inline style, so
387
+ // it stays readable before reduceInlineStyleToVisibilityDeclarations strips the
388
+ // declarations these checks consume.
389
+ function isStaticallyHiddenElement(element: Element): boolean {
298
390
  if (element.hasAttribute('hidden')) return true
299
391
  if (element.getAttribute('aria-hidden')?.toLocaleLowerCase() === 'true') return true
300
392
  if (element.tagName === 'INPUT' && element.getAttribute('type')?.toLocaleLowerCase() === 'hidden') return true
@@ -308,6 +400,13 @@ function isHiddenElement(
308
400
  if ((position === 'absolute' || position === 'fixed') && (isFarOffscreen(left) || isFarOffscreen(top))) return true
309
401
  }
310
402
 
403
+ return false
404
+ }
405
+
406
+ function isComputedHiddenElement(
407
+ element: Element,
408
+ computedStyle: ((element: Element) => CSSStyleDeclaration) | undefined,
409
+ ): boolean {
311
410
  if (computedStyle === undefined || NON_CONTENT_ELEMENTS.has(element.tagName)) return false
312
411
  let resolved: CSSStyleDeclaration
313
412
  try {
@@ -9,9 +9,7 @@ import {
9
9
  subscribeProviderErrors,
10
10
  } from './provider-error'
11
11
  import {
12
- PATIENT_OVERLOAD_RETRIES,
13
- PATIENT_OVERLOAD_WINDOW_MS,
14
- patientOverloadBackoffMs,
12
+ overloadRetryBudget,
15
13
  RETRIES_PER_REF,
16
14
  retryTurnAfterCompletedToolResult,
17
15
  retryTurnOnPersistentSession,
@@ -61,7 +59,7 @@ export async function promptPersistentTurnWithFallback(opts: {
61
59
  detectSoftErrorFromLeaf?: boolean
62
60
  authorizeRetryAfterCompletedToolResult?: () => boolean
63
61
  retryRandom?: () => number
64
- patientBackoffMs?: (attempt: number) => number
62
+ overloadBackoffMs?: (attempt: number) => number
65
63
  onRetryBackoffStart?: () => void
66
64
  beforeAttempt?: (ref: ModelRef) => void
67
65
  onAttemptFailed?: (attempt: PersistentTurnAttempt) => void
@@ -80,6 +78,7 @@ export async function promptPersistentTurnWithFallback(opts: {
80
78
  // NTP/system-clock correction the way Date.now() can, which would otherwise
81
79
  // prematurely trip or stall the 60s cap.
82
80
  const now = opts.now ?? (() => performance.now())
81
+ const overloadBudget = overloadRetryBudget(opts.retryPolicy)
83
82
  const hasNonCodexFallback = opts.refs.some((ref) => !isCodexRef(ref))
84
83
  let noHeaderAttempts = 0
85
84
  let cumulativeNoProgressMs = 0
@@ -127,7 +126,7 @@ export async function promptPersistentTurnWithFallback(opts: {
127
126
  let outcome: AttemptOutcome | undefined
128
127
  let retryAfterCompletedToolResult = false
129
128
  let overloadRetries = 0
130
- let patientWindowStartedAt: number | undefined
129
+ let overloadWindowStartedAt: number | undefined
131
130
  let nextDelayMs: number | undefined
132
131
  for (let retry = 0; ; retry++) {
133
132
  softError = undefined
@@ -175,23 +174,28 @@ export async function promptPersistentTurnWithFallback(opts: {
175
174
  // is to fail OVER rather than burn same-ref retries — which is why
176
175
  // isRetryableSameRef excludes it. But on the LAST usable ref there is
177
176
  // nothing to fail over to, and a single-ref chain is all last, so that
178
- // policy leaves a capacity outage with no recovery whatsoever. A patient
179
- // call site rides it out here instead; a responsive one still fails fast.
177
+ // policy would leave a capacity outage with no recovery whatsoever: the
178
+ // turn dies on its first attempt in seconds and the caller drops the
179
+ // user's message. Both policies therefore ride it out here, differing
180
+ // only in how long (see overloadRetryBudget) — patient for minutes,
181
+ // responsive for a live-chat-sized handful of seconds.
180
182
  // Budget the delay BEFORE accepting the retry. Testing only the elapsed
181
183
  // window lets a retry accepted just under the deadline sleep past it, so
182
184
  // the next provider attempt would START after the window we advertise.
183
185
  const nowMs = now()
184
- const patientDelayMs =
185
- opts.retryPolicy === 'patient' && isLast && isThrottleOrOverload(outcome.error.message)
186
- ? (opts.patientBackoffMs ?? ((n: number) => patientOverloadBackoffMs(n, opts.retryRandom)))(overloadRetries)
186
+ const overloadDelayMs =
187
+ isLast && isThrottleOrOverload(outcome.error.message)
188
+ ? (opts.overloadBackoffMs ?? ((n: number) => overloadBudget.backoffMs(n, opts.retryRandom)))(
189
+ overloadRetries,
190
+ )
187
191
  : undefined
188
- const patientElapsedMs = patientWindowStartedAt === undefined ? 0 : nowMs - patientWindowStartedAt
189
- const patientOverload =
190
- patientDelayMs !== undefined &&
191
- overloadRetries < PATIENT_OVERLOAD_RETRIES &&
192
- patientElapsedMs + patientDelayMs <= PATIENT_OVERLOAD_WINDOW_MS
192
+ const overloadElapsedMs = overloadWindowStartedAt === undefined ? 0 : nowMs - overloadWindowStartedAt
193
+ const overloadRetry =
194
+ overloadDelayMs !== undefined &&
195
+ overloadRetries < overloadBudget.retries &&
196
+ overloadElapsedMs + overloadDelayMs <= overloadBudget.windowMs
193
197
  const retryableWithinBudget =
194
- patientOverload || (retry < RETRIES_PER_REF && isRetryableSameRef(outcome.error.message))
198
+ overloadRetry || (retry < RETRIES_PER_REF && isRetryableSameRef(outcome.error.message))
195
199
  const mayRetryWithoutActivity = !activity.producedAssistantOutput && !activity.startedToolExecution
196
200
  retryAfterCompletedToolResult =
197
201
  retryableWithinBudget &&
@@ -199,9 +203,9 @@ export async function promptPersistentTurnWithFallback(opts: {
199
203
  opts.authorizeRetryAfterCompletedToolResult?.() === true
200
204
  const mayRetry = retryableWithinBudget && (mayRetryWithoutActivity || retryAfterCompletedToolResult)
201
205
  if (!mayRetry) break
202
- if (patientOverload) {
203
- patientWindowStartedAt ??= nowMs
204
- nextDelayMs = patientDelayMs
206
+ if (overloadRetry) {
207
+ overloadWindowStartedAt ??= nowMs
208
+ nextDelayMs = overloadDelayMs
205
209
  overloadRetries++
206
210
  } else {
207
211
  nextDelayMs = undefined
@@ -47,11 +47,14 @@ export async function resolveBackupPushAuthEnv(
47
47
  GIT_ASKPASS: askpass,
48
48
  TYPECLAW_GIT_TOKEN: token.token,
49
49
  GIT_TERMINAL_PROMPT: '0',
50
- GIT_CONFIG_COUNT: '2',
51
- GIT_CONFIG_KEY_0: 'url.https://github.com/.insteadOf',
52
- GIT_CONFIG_VALUE_0: 'git@github.com:',
50
+ GIT_ALLOW_PROTOCOL: 'https',
51
+ GIT_CONFIG_COUNT: '3',
52
+ GIT_CONFIG_KEY_0: 'credential.helper',
53
+ GIT_CONFIG_VALUE_0: '',
53
54
  GIT_CONFIG_KEY_1: 'url.https://github.com/.insteadOf',
54
- GIT_CONFIG_VALUE_1: 'ssh://git@github.com/',
55
+ GIT_CONFIG_VALUE_1: 'git@github.com:',
56
+ GIT_CONFIG_KEY_2: 'url.https://github.com/.insteadOf',
57
+ GIT_CONFIG_VALUE_2: 'ssh://git@github.com/',
55
58
  }
56
59
  }
57
60
 
@@ -77,7 +77,7 @@ You MAY:
77
77
  - Set up a missing upstream branch via \`git push -u origin <branch>\` if it's clear that's the only issue.
78
78
  - Retry \`git push\` once after fixing a clear, narrow issue.
79
79
 
80
- **When you run \`git push\` (either to set upstream or to retry), the security plugin's \`gitExfil\` guard will block unless you pass \`acknowledgeGuards: { gitExfil: true }\` on the bash tool call.** You are running on the operator's behalf as the recovery step of a deterministic backup the operator already approved by enabling \`backup.pushToOrigin\`; the ack is justified for this specific retry path. Do NOT use this ack for any other reason — only the one push retry the rules above allow. If your push retry fails again, write the diagnosis and stop; do not ack a second push.
80
+ **When you run \`git push\` (either to set upstream or to retry), do not add an acknowledgement argument.** Security guards are permission-only; this recovery subagent inherits the operator role that launched the approved backup workflow. If your push retry fails again, write the diagnosis and stop.
81
81
 
82
82
  You MUST NOT:
83
83
  - Force-push (\`--force\`, \`--force-with-lease\`).
@@ -1,37 +1,40 @@
1
1
  # typeclaw-plugin-bun-hygiene
2
2
 
3
- The bundled bun-hygiene plugin. Registers a `tool.before` hook that blocks two classes of `bash` command:
3
+ The bundled bun-hygiene policy contributes three runtime-internal guards for `bash` commands:
4
4
 
5
5
  1. **Global package installs** — `npm install -g`, `pnpm add -g`, `yarn global add`, `bun add -g`, and their `--global` / bundled-flag variants.
6
- 2. **Non-bun install managers** — any `npm`, `pnpm`, or `yarn` invocation. The ephemeral runners `npx` and `pnpx` are **allowed** (alongside `bunx`): they execute a tool once without touching the dependency tree or writing a competing lockfile, so they don't undermine the bun-standardization this guard protects.
6
+ 2. **Non-bun install managers** — any `npm`, `pnpm`, or `yarn` invocation.
7
+ 3. **Non-bun package runners** — `npx` or `pnpx` at a command boundary. Use `bunx` for one-off package binaries; the runner guard remains separately bypassable for genuine exceptions.
7
8
 
8
- This plugin is **auto-loaded** by every TypeClaw agent. There is no `plugins[]` entry to add. Both guards carry an `acknowledgeGuards` escape hatch (below) for the cases where the agent genuinely needs the blocked command.
9
+ This plugin is **auto-loaded** by every TypeClaw agent. There is no `plugins[]` entry to add. All three guards carry an `acknowledgeGuards` escape hatch (below) for the cases where the agent genuinely needs the blocked command.
9
10
 
10
11
  ## Why it exists
11
12
 
12
13
  **Global installs don't persist.** The agent folder is bind-mounted at `/agent`; everything else in the container — including `~/.bun`, `~/.npm`, and the global `node_modules` a global install writes to — is ephemeral and wiped on every `typeclaw restart`. An agent that runs `npm install -g some-cli` gets a tool that works for the rest of the session and silently vanishes on the next boot, leading to confusing "command not found" failures that look like regressions. The fix is to either add the dependency to `package.json` (`bun add <pkg>`, which lives in the bind-mounted folder and survives) or run it once without installing (`bunx <pkg>`).
13
14
 
14
- **The container standardizes on bun for dependency management.** TypeClaw is Bun-native end to end (see the root README). Mixing in `npm`/`pnpm`/`yarn` installs produces competing lockfiles and install trees, so those are steered to bun. Ephemeral runners (`npx`/`pnpx`/`bunx`) are not install managers — they run a tool once and leave no lockfile or `node_modules` behind — so they're allowed for one-off execution.
15
+ **The container standardizes on bun for package execution.** TypeClaw is Bun-native end to end (see the root README). Mixing in `npm`/`pnpm`/`yarn` installs produces competing lockfiles and install trees, so those are steered to bun. For one-off package binaries, `bunx` is the Bun-native equivalent and the only package runner the default image ships: the `oven/bun` slim base provides `bun`, the `bunx` symlink, and a `node` fallback shim, but no `npm`, `npx`, `pnpm`, or `pnpx`. Reaching for one of those either fails outright or, in a custom image that supplies them, runs with npm/pnpm semantics rather than bun's — so the guard steers them to `bunx` instead of treating them as equivalent spellings.
15
16
 
16
- Both guards **block with guidance** rather than silently rewriting the command — the agent sees exactly why the command was rejected and what to run instead, the same UX as the bundled `security` and `guard` policies.
17
+ All three guards **block with guidance** rather than silently rewriting the command — the agent sees exactly why the command was rejected and what to run instead, the same UX as the bundled `security` and `guard` policies.
17
18
 
18
19
  ## Guards
19
20
 
20
- | Guard | Triggers on | Guidance in the block reason |
21
- | ---------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
22
- | `globalInstall` | `npm`/`pnpm` install/add with `-g`/`--global`, `yarn global add`, `bun add -g` / `bun install -g` | Use `bun add <pkg>` (persists) or `bunx <pkg>` (ephemeral run). |
23
- | `nonBunPackageManager` | `npm`, `pnpm`, `yarn` at a command boundary (`npx`/`pnpx`/`bunx` are allowed) | Use `bun install` / `bun add <pkg>`. Ephemeral runners are fine as-is. |
21
+ | Guard | Triggers on | Guidance in the block reason |
22
+ | ---------------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
23
+ | `globalInstall` | `npm`/`pnpm` install/add with `-g`/`--global`, `yarn global add`, `bun add -g` / `bun install -g` | Use `bun add <pkg>` (persists) or `bunx <pkg>` (ephemeral run). |
24
+ | `nonBunPackageManager` | `npm`, `pnpm`, `yarn` at a command boundary | Use `bun install` / `bun add <pkg>`; use `bunx` for one-offs. |
25
+ | `nonBunPackageRunner` | `npx`, `pnpx` at a command boundary | Use `bunx <pkg>` for one-off package binaries. |
24
26
 
25
- A global install (e.g. `npm install -g x`) trips **only** `globalInstall`, not both — the global install is the more specific violation, so acknowledging `globalInstall` lets the command through without a second acknowledgement for `nonBunPackageManager`.
27
+ A global install (e.g. `npm install -g x`) trips **only** `globalInstall`, not both — the global install is the more specific violation, so acknowledging `globalInstall` lets that install through without a second acknowledgement for `nonBunPackageManager`. That subsumption is scoped to the segment the global install appears in: in `bun add -g foo && npx tsc`, acknowledging `globalInstall` still leaves the `npx` segment blocked on `nonBunPackageRunner`.
26
28
 
27
29
  ## Bypass
28
30
 
29
- Both guards follow the repo-wide `acknowledgeGuards` convention (shared with the `security` and `guard` plugins). To run a blocked command intentionally, pass the matching flag in the `bash` tool arguments:
31
+ All three guards follow the plugin-nested `acknowledgeGuards` convention. To run a blocked command intentionally, pass the matching flag in the `bash` tool arguments:
30
32
 
31
33
  ```jsonc
32
34
  // bash tool args
33
- { "command": "npm install", "acknowledgeGuards": { "nonBunPackageManager": true } }
34
- { "command": "npm install -g some-cli", "acknowledgeGuards": { "globalInstall": true } }
35
+ { "command": "npm install", "acknowledgeGuards": { "bun-hygiene": { "nonBunPackageManager": true } } }
36
+ { "command": "npm install -g some-cli", "acknowledgeGuards": { "bun-hygiene": { "globalInstall": true } } }
37
+ { "command": "npx tsc", "acknowledgeGuards": { "bun-hygiene": { "nonBunPackageRunner": true } } }
35
38
  ```
36
39
 
37
40
  ## How it works
@@ -45,13 +48,14 @@ For each segment, the guard strips leading **preamble wrappers** (`sudo`, `env`,
45
48
 
46
49
  1. command word is `npm`/`pnpm`/`yarn` (or `bun`) **and** the segment has an install subcommand **and** a global flag → `globalInstall` (for `yarn`, the `global add` sequence must appear adjacent and in command position, so `yarn add global foo` — a local install of a package named `global` — is not misflagged);
47
50
  2. command word is a non-bun install manager `npm`/`pnpm`/`yarn` (not via global) → `nonBunPackageManager`;
48
- 3. otherwise (including the ephemeral runners `npx`/`pnpx`/`bunx`) → allowed.
51
+ 3. command word is a non-bun package runner `npx`/`pnpx` → `nonBunPackageRunner`;
52
+ 4. otherwise (including `bunx` and `bun x`) → allowed.
49
53
 
50
- A `globalInstall` verdict on any segment wins over a plain non-bun verdict. This is a command-position detector, not a full shell parser — it doesn't interpret redirections or expansions beyond boundary marking — but it is linear-time and closes the structural gaps a single regex left open.
54
+ Every segment is classified and the verdicts are returned in precedence order — `globalInstall`, then `nonBunPackageManager`, then `nonBunPackageRunner` — with the guard blocking on the first one that is not acknowledged. A global install suppresses the manager verdict for **its own segment only**, so acknowledging one verdict surfaces the next rather than clearing violations elsewhere in the command. This is a command-position detector, not a full shell parser — it doesn't interpret redirections or expansions beyond boundary marking — but it is linear-time and closes the structural gaps a single regex left open.
51
55
 
52
56
  ## Scope: not a security boundary
53
57
 
54
- This guard is a **hygiene nudge**, not an isolation mechanism. It deliberately does not chase manager invocations hidden inside a wrapper's code payload — `sh -c 'npm install'`, `bash -lc "pnpm add foo"`, `python -c '...os.system("npx tsc")'`, `node -e`, `eval`, `base64 | sh`, etc. That set is unbounded (any interpreter can reach any binary), and inspecting arbitrary `-c`/`-e` payloads is an arms race with diminishing returns and rising false-positive risk. An agent that genuinely wants a package manager can always reach one; the guard's job is to steer the common, direct invocations toward bun and to stop accidental global installs. The real isolation boundary is the per-tool **bwrap sandbox** (see `/docs/internals/sandbox`), not this policy. Optioned preamble _wrappers_ (`env -i`, `sudo -u`, `nice -n`) are handled because they prefix a real command word that the tokenizer can still see; code-payload wrappers are not, by design.
58
+ This guard is a **hygiene nudge**, not an isolation mechanism. It deliberately does not chase manager or runner invocations hidden inside a wrapper's code payload — `sh -c 'npm install'`, `bash -lc "pnpm add foo"`, `python -c '...os.system("npx tsc")'`, `node -e`, `eval`, `base64 | sh`, etc. That set is unbounded (any interpreter can reach any binary), and inspecting arbitrary `-c`/`-e` payloads is an arms race with diminishing returns and rising false-positive risk. An agent that genuinely needs another package command can still reach one through the acknowledgement escape hatch; the guard's job is to steer common, direct invocations toward bun and to stop accidental global installs. The real isolation boundary is the per-tool **bwrap sandbox** (see `/docs/internals/sandbox`), not this policy. Optioned preamble _wrappers_ (`env -i`, `sudo -u`, `nice -n`) are handled because they prefix a real command word that the tokenizer can still see; code-payload wrappers are not, by design.
55
59
 
56
60
  ## Why a tokenizer, not a regex
57
61
 
@@ -70,8 +74,7 @@ Because classification scans a segment's words as a set (after preamble strippin
70
74
  ## What is NOT blocked
71
75
 
72
76
  - `bun`, `bunx`, `bun run`, `bun add`, `bun install` (local) — the intended package commands. (`bun add -g` / `bun install -g` are still blocked as global installs: bun globals live in `~/.bun`, outside `/agent`, and are wiped on restart.)
73
- - `npx`, `pnpx` — ephemeral runners, allowed for one-off tool execution (they leave no lockfile or install tree). A global install through them is still nothing to block since they don't install into the dependency tree at all.
74
- - A non-bun manager name appearing as a substring or argument: `my-npm-wrapper`, `./npm`, `cat npm-debug.log`, `git commit -m "drop npm"`, `grep -rn npx src/`, `echo "npm install -g foo"`. Only the **command word** of a segment is classified, so a manager name inside an argument, path, quoted string, or longer token never trips the guard.
77
+ - A non-bun manager or runner name appearing as a substring or argument: `my-npm-wrapper`, `./npm`, `cat npm-debug.log`, `git commit -m "drop npm"`, `grep -rn npx src/`, `echo "npm install -g foo"`. Only the **command word** of a segment is classified, so a package command name inside an argument, path, quoted string, or longer token never trips the guard.
75
78
 
76
79
  ## Ordering against other bundled plugins
77
80
 
@@ -79,5 +82,5 @@ Registered after `guard` in `src/run/bundled-plugins.ts`. It guards a disjoint s
79
82
 
80
83
  ## Tests
81
84
 
82
- - `policy.test.ts` — pure-function unit tests for the detection logic: every global-install form, every non-bun install manager, the ephemeral-runner allowance (`npx`/`pnpx`/`bunx`, including behind preamble wrappers), the allowed-command set (bun/bunx, substrings, paths, quoted text), both bypasses, the global-install-takes-precedence rule, escaped/quoted evasions, leading-assignment preambles, newline-as-separator scoping, falsy `--global=`, option placement, and subshell/substitution detection.
83
- - `index.test.ts` — composition tests: the plugin registers the `tool.before` hook and wires it to the policy (block on global install, block on `npm install`, allow `bunx`/`npx`, honor the bypass).
85
+ - `policy.test.ts` — pure-function unit tests for the detection logic: every global-install form, every non-bun install manager, `npx`/`pnpx` runner blocking (including behind preamble wrappers), the allowed-command set (`bunx`, `bun x`, substrings, paths, quoted text), all bypasses, guard precedence, escaped/quoted evasions, leading-assignment preambles, newline-as-separator scoping, falsy `--global=`, option placement, and subshell/substitution detection.
86
+ - `index.test.ts` — composition tests: the plugin registers guards and wires them to the policy (block on global install, `npm install`, and `npx`; allow `bunx`; honor the bypass).
@@ -1,11 +1,5 @@
1
1
  import { definePlugin } from '@/plugin'
2
2
 
3
- import { checkBunHygieneGuard } from './policy'
4
-
5
3
  export default definePlugin({
6
- plugin: async () => ({
7
- hooks: {
8
- 'tool.before': (event) => checkBunHygieneGuard({ tool: event.tool, args: event.args }),
9
- },
10
- }),
4
+ plugin: async () => ({}),
11
5
  })