typeclaw 0.50.0 → 0.51.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 (90) hide show
  1. package/dist/types/agent/bash-sandbox-env.d.ts +15 -0
  2. package/dist/types/agent/bash-sandbox-proc.d.ts +8 -0
  3. package/dist/types/agent/bash-sandbox.d.ts +94 -0
  4. package/dist/types/agent/compaction.d.ts +4 -4
  5. package/dist/types/agent/idle-compaction.d.ts +1 -0
  6. package/dist/types/agent/index.d.ts +5 -17
  7. package/dist/types/agent/output-allowance.d.ts +4 -0
  8. package/dist/types/agent/plugin-tools.d.ts +4 -75
  9. package/dist/types/agent/system-prompt-composition.d.ts +17 -0
  10. package/dist/types/agent/tools/ddg.d.ts +9 -0
  11. package/dist/types/agent/tools/stream-snapshot.d.ts +1 -1
  12. package/dist/types/agent/tools/webfetch/tool.d.ts +1 -1
  13. package/dist/types/channels/github-review-check.d.ts +1 -1
  14. package/dist/types/channels/router.d.ts +11 -49
  15. package/dist/types/config/config.d.ts +24 -11
  16. package/dist/types/config/providers.d.ts +3 -1
  17. package/dist/types/container/start.d.ts +1 -0
  18. package/dist/types/eval/cell.d.ts +26 -0
  19. package/dist/types/eval/config.d.ts +19 -0
  20. package/dist/types/eval/dispatch.d.ts +7 -0
  21. package/dist/types/eval/kernel.d.ts +28 -0
  22. package/dist/types/eval/process.d.ts +23 -0
  23. package/dist/types/eval/protocol.d.ts +34 -0
  24. package/dist/types/eval/sandbox.d.ts +10 -0
  25. package/dist/types/eval/tool.d.ts +17 -0
  26. package/dist/types/eval/wire.d.ts +33 -0
  27. package/dist/types/sandbox/env-exposure.d.ts +2 -0
  28. package/package.json +5 -5
  29. package/src/agent/bash-sandbox-env.ts +104 -0
  30. package/src/agent/bash-sandbox-proc.ts +70 -0
  31. package/src/agent/bash-sandbox.ts +225 -0
  32. package/src/agent/compaction.ts +22 -10
  33. package/src/agent/idle-compaction.ts +7 -3
  34. package/src/agent/index.ts +66 -157
  35. package/src/agent/output-allowance.ts +7 -0
  36. package/src/agent/plugin-tools.ts +29 -379
  37. package/src/agent/session-origin.ts +2 -1
  38. package/src/agent/subagent-completion-reminder.ts +2 -2
  39. package/src/agent/system-prompt-composition.ts +141 -0
  40. package/src/agent/system-prompt.ts +4 -4
  41. package/src/agent/todo/scope.ts +1 -1
  42. package/src/agent/tools/ddg.ts +71 -11
  43. package/src/agent/tools-without-local-file-operands.ts +4 -0
  44. package/src/browser/fill-secret.ts +307 -0
  45. package/src/bundled-plugins/explorer/explorer.ts +1 -1
  46. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +40 -16
  47. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +12 -7
  48. package/src/bundled-plugins/github-cli-auth/index.ts +10 -1
  49. package/src/bundled-plugins/managed-browser/index.ts +107 -2
  50. package/src/bundled-plugins/memory/dreaming.ts +4 -1
  51. package/src/bundled-plugins/memory/load-memory.ts +2 -4
  52. package/src/bundled-plugins/memory/memory-logger.ts +74 -2
  53. package/src/bundled-plugins/memory/transcript-preload.ts +103 -0
  54. package/src/bundled-plugins/memory/vector/hybrid.ts +25 -14
  55. package/src/bundled-plugins/security/policies/private-surface-read.ts +166 -201
  56. package/src/channels/adapters/discord-bot-reference.ts +5 -4
  57. package/src/channels/adapters/discord-bot.ts +1 -0
  58. package/src/channels/adapters/discord-classify.ts +8 -3
  59. package/src/channels/adapters/discord.ts +29 -0
  60. package/src/channels/github-review-check.ts +5 -1
  61. package/src/channels/github-review-verdict-coordinator.ts +68 -2
  62. package/src/channels/router.ts +88 -107
  63. package/src/channels/subagent-completion-bridge.ts +3 -2
  64. package/src/cli/hostd.ts +3 -0
  65. package/src/config/config.ts +15 -0
  66. package/src/config/providers.ts +10 -4
  67. package/src/container/start.ts +37 -1
  68. package/src/doctor/checks.ts +25 -16
  69. package/src/doctor/index.ts +48 -12
  70. package/src/doctor/operational-incidents.ts +16 -1
  71. package/src/doctor/plugin-bridge.ts +14 -1
  72. package/src/doctor/stage.ts +14 -0
  73. package/src/doctor/types.ts +6 -0
  74. package/src/eval/cell.ts +93 -0
  75. package/src/eval/config.ts +32 -0
  76. package/src/eval/dispatch.ts +67 -0
  77. package/src/eval/entry.ts +261 -0
  78. package/src/eval/kernel.ts +154 -0
  79. package/src/eval/process.ts +113 -0
  80. package/src/eval/protocol.ts +26 -0
  81. package/src/eval/redeclare.ts +174 -0
  82. package/src/eval/sandbox.ts +114 -0
  83. package/src/eval/tool.ts +98 -0
  84. package/src/eval/wire.ts +93 -0
  85. package/src/operations/classify-tool-outcome.ts +1 -1
  86. package/src/plugin/core-tool-names.ts +6 -1
  87. package/src/sandbox/env-exposure.ts +20 -0
  88. package/src/server/index.ts +46 -11
  89. package/src/skills/typeclaw-config/SKILL.md +20 -2
  90. package/typeclaw.schema.json +52 -0
@@ -65,7 +65,7 @@ ${BUNX_PACKAGE_RUNNER_RULE}
65
65
 
66
66
  ## Doing the work
67
67
 
68
- Act on the practical task behind the wording, in any language: a status question ("is the build red?") usually wants the answer and the obvious next step, and a capability or permission phrasing ("can you add a retry?") is a request to do it. Take the safe, conventional reading, stay within the apparent request, and do not invent a larger project. Ask only when plausible readings would materially change scope, permissions, cost, or risk; when no one can answer, follow the session origin's instructions instead. When the next action is clear, start in the same turn rather than replying with a plan.
68
+ Act on the practical task behind the wording, in any language: a status question ("is the build red?") usually wants the answer and the obvious next step, and a capability or permission phrasing ("can you add a retry?") is a request to do it. Take the conventional reading, stay within the apparent request, and do not invent a larger project. Ask only when plausible readings would materially change scope, permissions, cost, or risk; when no one can answer, follow the session origin's instructions instead. When the next action is clear, start in the same turn rather than replying with a plan.
69
69
 
70
70
  The deliverable is the requested result backed by real tool output, not a description, stub, or plan of one; keep working until you have exercised it. If a tool, install, or network call blocks the real path, say so and try an alternative. Never substitute fabricated output (made-up data, file contents, or tool results) for a result you could not produce, and never suppress errors to make things "work"; report the failure so the next run or the operator can act on it.
71
71
 
@@ -95,7 +95,7 @@ Commits to your agent folder (your own state):
95
95
 
96
96
  ## Safety
97
97
 
98
- You have no independent goals. Do not pursue self-preservation, replication, resource acquisition, influence, or plans beyond the user's request. If instructions conflict or feel unsafe, pause and ask. Comply with stop, pause, and audit requests. Never modify your own system prompt, safety rules, or runtime configuration unless explicitly requested and only through runtime mechanisms.
98
+ You have no independent goals. Do not pursue self-preservation, replication, resource acquisition, influence, or plans beyond the user's request. If instructions conflict, ask which one wins. Comply with stop, pause, and audit requests. Never modify your own system prompt, safety rules, or runtime configuration unless explicitly requested and only through runtime mechanisms.
99
99
 
100
100
  ---
101
101
 
@@ -206,8 +206,8 @@ export function renderTurnTimeAnchor(now: Date = new Date()): string {
206
206
  // This anchor surfaces the per-turn resolved role in the one place that costs
207
207
  // zero cached bytes (the non-cacheable user-turn suffix).
208
208
  //
209
- // Omitted for `owner`: owner is the unconstrained default, an absent tag means
210
- // "no special handling", and emitting it on every interactive turn would be
209
+ // Omitted for `owner`: the channel role block tells the model an absent tag
210
+ // means the owner, and emitting it on every interactive turn would be
211
211
  // pure token overhead. This mirrors resolveRoleContext skipping the session
212
212
  // block for a TUI owner.
213
213
  export function renderTurnRoleAnchor(role: string): string | undefined {
@@ -3,7 +3,7 @@ import type { SessionOrigin } from '@/agent/session-origin'
3
3
  // A todo scope is the durable identity a todo list hangs off. It is
4
4
  // deliberately NOT the raw sessionId: sessionIds churn across TUI reconnects
5
5
  // and every cron fire, and a channel session can roll to a fresh sessionId on
6
- // stale-rollover (see src/channels/router.ts SESSION_FRESHNESS_TTL_MS). Keying
6
+ // stale-rollover after 60 minutes idle (router.ts SESSION_FRESHNESS_TTL_MS). Keying
7
7
  // on origin identity instead lets a todo list survive those transitions so
8
8
  // interrupted work can be resumed.
9
9
  //
@@ -40,6 +40,41 @@ const searchLimiter = createKeyedSemaphore({ concurrency: DDG_CONCURRENCY })
40
40
 
41
41
  const DDG_KEY = 'ddg'
42
42
 
43
+ // The concurrency cap bounds parallelism, not rate: a subagent fan-out of ~10
44
+ // searches inside 30s still tripped DDG's gate behind a cap of 2 (production
45
+ // incident, 2026-10-27). Spacing every outbound request by a minimum interval
46
+ // turns such a burst into a queue instead of a volley.
47
+ export const DDG_MIN_REQUEST_INTERVAL_MS = 1_500
48
+
49
+ // Once DDG serves a challenge to every profile the source IP is boxed for
50
+ // minutes, and each further request keeps the box alive. Stop sending for a
51
+ // cooldown window: calls inside it fail fast without touching the network.
52
+ export const DDG_CAPTCHA_COOLDOWN_MS = 5 * 60_000
53
+
54
+ type Pacing = {
55
+ intervalMs: number
56
+ cooldownMs: number
57
+ now: () => number
58
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>
59
+ }
60
+ const DEFAULT_PACING: Pacing = {
61
+ intervalMs: DDG_MIN_REQUEST_INTERVAL_MS,
62
+ cooldownMs: DDG_CAPTCHA_COOLDOWN_MS,
63
+ now: () => Date.now(),
64
+ sleep: abortableSleep,
65
+ }
66
+ let pacing: Pacing = DEFAULT_PACING
67
+ let nextRequestAt = 0
68
+ let cooldownUntil = 0
69
+
70
+ // Test-only seam: swaps the clock/sleep and interval/cooldown, and resets the
71
+ // process-wide pacing state so tests don't leak a cooldown into each other.
72
+ export function _setDdgPacingForTest(override: Partial<Pacing> | null): void {
73
+ pacing = { ...DEFAULT_PACING, ...override }
74
+ nextRequestAt = 0
75
+ cooldownUntil = 0
76
+ }
77
+
43
78
  export type DdgResult = {
44
79
  title: string
45
80
  url: string
@@ -63,9 +98,14 @@ export async function ddgSearch(query: string, limit: number, signal?: AbortSign
63
98
  withSearchRetry(
64
99
  async () => {
65
100
  for (const binary of DDG_PROFILES) {
101
+ if (pacing.now() < cooldownUntil) throw new DdgCaptchaError()
102
+ await waitForRequestSlot(signal)
103
+ // A concurrent search may have started the cooldown while this one waited.
104
+ if (pacing.now() < cooldownUntil) throw new DdgCaptchaError()
66
105
  const html = await fetchDdgHtml(query, signal, binary)
67
106
  if (!isCaptcha(html)) return parseDdgHtml(html).slice(0, limit)
68
107
  }
108
+ cooldownUntil = pacing.now() + pacing.cooldownMs
69
109
  throw new DdgCaptchaError()
70
110
  },
71
111
  { ...retryOverride, shouldRetry: isTransientSearchError, signal },
@@ -74,18 +114,38 @@ export async function ddgSearch(query: string, limit: number, signal?: AbortSign
74
114
  )
75
115
  }
76
116
 
77
- // Both a tripped CAPTCHA and a bare connection timeout are transient: DDG's
78
- // gate lifts after a cooldown, and an egress timeout is almost always a
79
- // momentary network blip (the incident that motivated this: an agent's egress
80
- // timed out for a few minutes, then recovered). Retrying both under the bounded
81
- // `withSearchRetry` backoff turns an otherwise-unbounded model-driven retry
82
- // loop into at most `attempts` code-level tries that then surface a single
83
- // terminal error. A hard network failure (DNS, refused, TLS) is NOT retried —
84
- // it won't fix itself on a re-run and would just burn the budget.
117
+ // Only a bare connection timeout is retried: an egress timeout is almost
118
+ // always a momentary network blip (the incident that motivated this: an agent's
119
+ // egress timed out for a few minutes, then recovered). Retrying under the
120
+ // bounded `withSearchRetry` backoff turns an otherwise-unbounded model-driven
121
+ // retry loop into at most `attempts` code-level tries. A CAPTCHA is NOT retried:
122
+ // DDG's gate lasts minutes, far beyond the retry backoff, and every retry keeps
123
+ // the box alive — the cooldown above handles it instead. A hard network failure
124
+ // (DNS, refused, TLS) is NOT retried either; it won't fix itself on a re-run.
85
125
  export function isTransientSearchError(error: unknown): boolean {
86
- if (error instanceof DdgCaptchaError) return true
87
- if (error instanceof CurlImpersonateError && isCurlExitTimeout(error)) return true
88
- return false
126
+ return error instanceof CurlImpersonateError && isCurlExitTimeout(error)
127
+ }
128
+
129
+ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
130
+ return new Promise((resolve, reject) => {
131
+ if (signal?.aborted) return reject(signal.reason)
132
+ const onAbort = (): void => {
133
+ clearTimeout(timer)
134
+ reject(signal?.reason)
135
+ }
136
+ const timer = setTimeout(() => {
137
+ signal?.removeEventListener('abort', onAbort)
138
+ resolve()
139
+ }, ms)
140
+ signal?.addEventListener('abort', onAbort, { once: true })
141
+ })
142
+ }
143
+
144
+ async function waitForRequestSlot(signal?: AbortSignal): Promise<void> {
145
+ const now = pacing.now()
146
+ const slot = Math.max(now, nextRequestAt)
147
+ nextRequestAt = slot + pacing.intervalMs
148
+ if (slot > now) await pacing.sleep(slot - now, signal)
89
149
  }
90
150
 
91
151
  export class DdgCaptchaError extends Error {
@@ -14,8 +14,12 @@
14
14
  // can both read it without a circular-init TDZ. Add a tool here ONLY after
15
15
  // confirming it dereferences no argument as a local path.
16
16
  export const TOOLS_WITHOUT_LOCAL_FILE_OPERANDS: ReadonlySet<string> = new Set([
17
+ // Source code is not a host-side path operand. Raw I/O is confined by the
18
+ // shared bash sandbox; tool.* operands enter their own wrapped definitions.
19
+ 'eval',
17
20
  'channel_read',
18
21
  'channel_history',
22
+ 'channel_handoff',
19
23
  'channel_edit',
20
24
  'channel_react',
21
25
  'channel_fetch_attachment',
@@ -0,0 +1,307 @@
1
+ // Types a runtime-held value into the focused field of a managed-browser tab
2
+ // over CDP, so the model can enter a secret it never sees. The value only ever
3
+ // travels runtime -> Chrome; every outcome reports where it went, never what.
4
+
5
+ const COMMAND_TIMEOUT_MS = 10_000
6
+ const DEFAULT_NAVIGATION_TIMEOUT_MS = 15_000
7
+
8
+ export type FillSecretOptions = {
9
+ cdpUrl: string
10
+ value: string
11
+ url?: string
12
+ submit: boolean
13
+ navigationTimeoutMs?: number
14
+ }
15
+
16
+ export type FillSecretOutcome =
17
+ | { status: 'filled'; url: string; field: string }
18
+ | { status: 'submitted'; url: string; field: string }
19
+ | { status: 'not-navigated'; url: string; field: string; cleared: boolean }
20
+ | { status: 'refused'; reason: string }
21
+
22
+ export async function fillSecretIntoFocusedField(options: FillSecretOptions): Promise<FillSecretOutcome> {
23
+ const cdp = await CdpConnection.open(options.cdpUrl)
24
+ try {
25
+ const target = await pickTarget(cdp, options.url)
26
+ if ('reason' in target) return { status: 'refused', reason: target.reason }
27
+ const { sessionId } = (await cdp.send('Target.attachToTarget', { targetId: target.targetId, flatten: true })) as {
28
+ sessionId: string
29
+ }
30
+ // Background tabs (omowright opens them) report no focus; emulate it so
31
+ // keyboard input reaches the focused element without stealing the window.
32
+ await cdp.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId)
33
+ const focused = await inspectFocus(cdp, sessionId)
34
+ if (focused.kind === 'none') {
35
+ return {
36
+ status: 'refused',
37
+ reason: `no editable field is focused on ${target.url}${focused.field === undefined ? '' : ` (focused: ${focused.field})`}; click or focus the field first`,
38
+ }
39
+ }
40
+
41
+ await pressCommand(cdp, sessionId, 'selectAll')
42
+ try {
43
+ await cdp.send('Input.insertText', { text: options.value }, sessionId)
44
+ if (!options.submit) return { status: 'filled', url: target.url, field: focused.field }
45
+
46
+ await cdp.send('Page.enable', {}, sessionId)
47
+ const navigated = cdp.waitForEvent(
48
+ 'Page.frameNavigated',
49
+ sessionId,
50
+ (params) => (params as { frame?: { parentId?: string } }).frame?.parentId === undefined,
51
+ options.navigationTimeoutMs ?? DEFAULT_NAVIGATION_TIMEOUT_MS,
52
+ )
53
+ await submitField(cdp, sessionId, focused.objectId)
54
+ if (await navigated) return { status: 'submitted', url: target.url, field: focused.field }
55
+ } catch (error) {
56
+ // The value may already be in the field; a failed step must not leave it there.
57
+ if (focused.objectId !== undefined) await clearField(cdp, sessionId, focused.objectId)
58
+ throw error
59
+ }
60
+
61
+ // The page stayed put (wrong value, inline error, SPA): don't leave the
62
+ // secret sitting in the DOM for a later snapshot or script to read back.
63
+ const cleared = focused.objectId !== undefined && (await clearField(cdp, sessionId, focused.objectId))
64
+ return { status: 'not-navigated', url: target.url, field: focused.field, cleared }
65
+ } finally {
66
+ cdp.close()
67
+ }
68
+ }
69
+
70
+ type TargetInfo = { targetId: string; type: string; url: string }
71
+
72
+ async function pickTarget(
73
+ cdp: CdpConnection,
74
+ url: string | undefined,
75
+ ): Promise<{ targetId: string; url: string } | { reason: string }> {
76
+ const { targetInfos } = (await cdp.send('Target.getTargets')) as { targetInfos: TargetInfo[] }
77
+ const pages = targetInfos.filter((t) => t.type === 'page' && !/^(devtools|chrome|chrome-extension):/.test(t.url))
78
+ const matches = url === undefined ? pages : pages.filter((t) => t.url === url || t.url.startsWith(url))
79
+ if (matches.length === 1) return matches[0]!
80
+ if (matches.length === 0) {
81
+ return { reason: url === undefined ? 'the shared browser has no open tab' : `no open tab matches ${url}` }
82
+ }
83
+ return { reason: `several tabs match; pass \`url\` to pick one of: ${matches.map((t) => t.url).join(', ')}` }
84
+ }
85
+
86
+ type FocusInfo = { kind: 'editable'; field: string; objectId?: string } | { kind: 'none'; field?: string }
87
+
88
+ // Walks shadow roots and same-origin iframes down to the real focused element.
89
+ // A cross-origin iframe (hosted card/key widgets) can't be inspected from the
90
+ // top frame, but keyboard input still lands in its focused field.
91
+ const FOCUS_EXPRESSION = `(() => {
92
+ const deepest = (el) => { while (el && el.shadowRoot && el.shadowRoot.activeElement) el = el.shadowRoot.activeElement; return el }
93
+ let el = deepest(document.activeElement)
94
+ while (el && el.tagName === 'IFRAME') {
95
+ let doc = null
96
+ try { doc = el.contentDocument } catch {}
97
+ if (!doc) return { kind: 'frame' }
98
+ el = deepest(doc.activeElement)
99
+ }
100
+ if (!el || el === el.ownerDocument.body || el === el.ownerDocument.documentElement) return { kind: 'none' }
101
+ const tag = el.tagName.toLowerCase()
102
+ if (el.isContentEditable) return { kind: 'editable', field: tag + '[contenteditable]', el }
103
+ const usable = !el.disabled && !el.readOnly
104
+ if (tag === 'textarea') return usable ? { kind: 'editable', field: 'textarea', el } : { kind: 'none', field: tag }
105
+ if (tag === 'input') {
106
+ const type = (el.getAttribute('type') || 'text').toLowerCase()
107
+ const textual = ['text', 'password', 'email', 'tel', 'url', 'search', 'number'].includes(type)
108
+ return textual && usable ? { kind: 'editable', field: 'input[type=' + type + ']', el } : { kind: 'none', field: 'input[type=' + type + ']' }
109
+ }
110
+ return { kind: 'none', field: tag }
111
+ })()`
112
+
113
+ async function inspectFocus(cdp: CdpConnection, sessionId: string): Promise<FocusInfo> {
114
+ const described = (await cdp.send(
115
+ 'Runtime.evaluate',
116
+ {
117
+ expression: `(() => { const r = ${FOCUS_EXPRESSION}; return { kind: r.kind, field: r.field } })()`,
118
+ returnByValue: true,
119
+ },
120
+ sessionId,
121
+ )) as { result: { value?: { kind: string; field?: string } } }
122
+ const info = described.result.value
123
+ if (info?.kind === 'frame') return { kind: 'editable', field: 'cross-origin iframe' }
124
+ if (info?.kind !== 'editable' || info.field === undefined)
125
+ return { kind: 'none', ...(info?.field ? { field: info.field } : {}) }
126
+ // Hold a handle to the exact element so a later clear can't hit whatever
127
+ // happens to be focused after the page changes.
128
+ const handle = (await cdp.send('Runtime.evaluate', { expression: `(${FOCUS_EXPRESSION}).el` }, sessionId)) as {
129
+ result: { objectId?: string }
130
+ }
131
+ return {
132
+ kind: 'editable',
133
+ field: info.field,
134
+ ...(handle.result.objectId ? { objectId: handle.result.objectId } : {}),
135
+ }
136
+ }
137
+
138
+ // Frameworks such as React shadow `value` on the element itself to track the
139
+ // last value they saw; assigning through that shadow updates the tracker, so the
140
+ // input event looks like no change and the app's state keeps the secret. Writing
141
+ // through the prototype's native setter leaves the tracker stale, so the app sees
142
+ // the edit and its own state is emptied too.
143
+ export const CLEAR_FIELD_FUNCTION = `function () {
144
+ if (!this.isConnected) return true
145
+ if (this.isContentEditable) {
146
+ this.textContent = ''
147
+ this.dispatchEvent(new Event('input', { bubbles: true }))
148
+ return this.textContent === ''
149
+ }
150
+ let setter
151
+ for (let proto = Object.getPrototypeOf(this); proto && !setter; proto = Object.getPrototypeOf(proto)) {
152
+ setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
153
+ }
154
+ if (!setter) return false
155
+ setter.call(this, '')
156
+ this.dispatchEvent(new Event('input', { bubbles: true }))
157
+ return this.value === ''
158
+ }`
159
+
160
+ async function clearField(cdp: CdpConnection, sessionId: string, objectId: string): Promise<boolean> {
161
+ const result = (await cdp
162
+ .send(
163
+ 'Runtime.callFunctionOn',
164
+ {
165
+ objectId,
166
+ functionDeclaration: CLEAR_FIELD_FUNCTION,
167
+ returnByValue: true,
168
+ },
169
+ sessionId,
170
+ )
171
+ .catch(() => ({ result: { value: false } }))) as { result: { value?: boolean } }
172
+ return result.result.value === true
173
+ }
174
+
175
+ async function pressCommand(cdp: CdpConnection, sessionId: string, command: string): Promise<void> {
176
+ await cdp.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', commands: [command] }, sessionId)
177
+ await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp' }, sessionId)
178
+ }
179
+
180
+ // A form without a submit button and with several fields ignores Enter (HTML
181
+ // implicit submission), so submit the owning form directly when there is one;
182
+ // script-driven logins with no form still get the Enter keystroke.
183
+ async function submitField(cdp: CdpConnection, sessionId: string, objectId: string | undefined): Promise<void> {
184
+ if (objectId !== undefined) {
185
+ const submitted = (await cdp.send(
186
+ 'Runtime.callFunctionOn',
187
+ {
188
+ objectId,
189
+ functionDeclaration: `function () {
190
+ if (!this.form) return false
191
+ this.form.requestSubmit()
192
+ return true
193
+ }`,
194
+ returnByValue: true,
195
+ },
196
+ sessionId,
197
+ )) as { result: { value?: boolean } }
198
+ if (submitted.result.value === true) return
199
+ }
200
+ await pressEnter(cdp, sessionId)
201
+ }
202
+
203
+ async function pressEnter(cdp: CdpConnection, sessionId: string): Promise<void> {
204
+ const key = { key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 }
205
+ await cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', text: '\r', ...key }, sessionId)
206
+ await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', ...key }, sessionId)
207
+ }
208
+
209
+ type Pending = {
210
+ resolve: (value: unknown) => void
211
+ reject: (error: Error) => void
212
+ timer: ReturnType<typeof setTimeout>
213
+ }
214
+ type EventListener = { method: string; sessionId: string; onEvent: (params: unknown) => void }
215
+
216
+ class CdpConnection {
217
+ private nextId = 1
218
+ private readonly pending = new Map<number, Pending>()
219
+ private readonly listeners = new Set<EventListener>()
220
+
221
+ private constructor(private readonly socket: WebSocket) {
222
+ socket.addEventListener('message', (event) => this.onMessage(String(event.data)))
223
+ socket.addEventListener('close', () => {
224
+ for (const p of this.pending.values()) {
225
+ clearTimeout(p.timer)
226
+ p.reject(new Error('browser connection closed'))
227
+ }
228
+ this.pending.clear()
229
+ })
230
+ }
231
+
232
+ static open(url: string): Promise<CdpConnection> {
233
+ return new Promise((resolve, reject) => {
234
+ const socket = new WebSocket(url)
235
+ socket.addEventListener('open', () => resolve(new CdpConnection(socket)), { once: true })
236
+ socket.addEventListener('error', () => reject(new Error('could not connect to the shared browser')), {
237
+ once: true,
238
+ })
239
+ })
240
+ }
241
+
242
+ send(method: string, params: Record<string, unknown> = {}, sessionId?: string): Promise<unknown> {
243
+ const id = this.nextId++
244
+ return new Promise((resolve, reject) => {
245
+ const timer = setTimeout(() => {
246
+ this.pending.delete(id)
247
+ reject(new Error(`${method} timed out`))
248
+ }, COMMAND_TIMEOUT_MS)
249
+ this.pending.set(id, { resolve, reject, timer })
250
+ this.socket.send(JSON.stringify({ id, method, params, ...(sessionId === undefined ? {} : { sessionId }) }))
251
+ })
252
+ }
253
+
254
+ // Registered before the triggering command so a fast event can't slip past.
255
+ waitForEvent(
256
+ method: string,
257
+ sessionId: string,
258
+ predicate: (params: unknown) => boolean,
259
+ timeoutMs: number,
260
+ ): Promise<boolean> {
261
+ return new Promise((resolve) => {
262
+ const listener: EventListener = {
263
+ method,
264
+ sessionId,
265
+ onEvent: (params) => {
266
+ if (!predicate(params)) return
267
+ finish(true)
268
+ },
269
+ }
270
+ const timer = setTimeout(() => finish(false), timeoutMs)
271
+ const finish = (value: boolean): void => {
272
+ clearTimeout(timer)
273
+ this.listeners.delete(listener)
274
+ resolve(value)
275
+ }
276
+ this.listeners.add(listener)
277
+ })
278
+ }
279
+
280
+ close(): void {
281
+ this.socket.close()
282
+ }
283
+
284
+ private onMessage(raw: string): void {
285
+ const message = JSON.parse(raw) as {
286
+ id?: number
287
+ result?: unknown
288
+ error?: { message: string }
289
+ method?: string
290
+ params?: unknown
291
+ sessionId?: string
292
+ }
293
+ if (message.id !== undefined) {
294
+ const pending = this.pending.get(message.id)
295
+ if (pending === undefined) return
296
+ this.pending.delete(message.id)
297
+ clearTimeout(pending.timer)
298
+ if (message.error !== undefined) pending.reject(new Error(message.error.message))
299
+ else pending.resolve(message.result)
300
+ return
301
+ }
302
+ for (const listener of this.listeners) {
303
+ if (listener.method === message.method && listener.sessionId === message.sessionId)
304
+ listener.onEvent(message.params)
305
+ }
306
+ }
307
+ }
@@ -100,7 +100,7 @@ export function createExplorerSubagent(): Subagent<ExplorerPayload> {
100
100
  payloadSchema: explorerPayloadSchema,
101
101
  visibility: 'public',
102
102
  rosterDescription:
103
- 'read-only local recon — code, sessions, memory, git, config; returns the paths and excerpts you need without you grepping the tree yourself; fire liberally',
103
+ 'read-only local recon — code, sessions, memory, git, config, mounted data; finds where the evidence lives and returns paths and excerpts. It locates, it does not judge: read the decisive records yourself before concluding',
104
104
  inFlightKey: (payload) => payload?.requestId ?? `anon-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
105
105
  toolResultBudget: {
106
106
  maxTotalBytes: 256_000,
@@ -24,6 +24,7 @@ export type DetectedReview = {
24
24
  prNumber: number
25
25
  verdict: ReviewVerdict
26
26
  source: 'api' | 'pr-review'
27
+ reviewedHeadSha?: string
27
28
  }
28
29
 
29
30
  export type GhReviewDetectInput = {
@@ -246,25 +247,18 @@ function detectApiReview(args: readonly string[], fileContents: string | null):
246
247
  const prNumber = Number(m[3])
247
248
  if (!Number.isSafeInteger(prNumber)) return null
248
249
 
249
- const verdict = verdictFromInlineFields(args) ?? verdictFromFile(fileContents)
250
+ const verdict = verdictFromInlineFields(args) ?? normalizeVerdict(stringFieldFromFile(fileContents, 'event') ?? '')
250
251
  if (verdict === null) return null
251
- return { workspace, prNumber, verdict, source: 'api' }
252
+ const reviewedHeadSha = commitIdFromInlineFields(args) ?? stringFieldFromFile(fileContents, 'commit_id')
253
+ return { workspace, prNumber, verdict, source: 'api', ...(reviewedHeadSha !== null ? { reviewedHeadSha } : {}) }
252
254
  }
253
255
 
254
256
  // Inline `-f event=APPROVE` / `--field event=REQUEST_CHANGES` (and `-F` raw).
255
257
  // gh accepts both `flag value` and `flag=value` shapes; cover both.
256
258
  function verdictFromInlineFields(args: readonly string[]): ReviewVerdict | null {
257
- for (let i = 0; i < args.length; i++) {
258
- const a = args[i]
259
- if (a === undefined) continue
260
- if (a === '-f' || a === '-F' || a === '--field' || a === '--raw-field') {
261
- const v = parseEventAssignment(args[i + 1])
262
- if (v !== null) return v
263
- }
264
- if (a.startsWith('-f=') || a.startsWith('-F=') || a.startsWith('--field=') || a.startsWith('--raw-field=')) {
265
- const v = parseEventAssignment(a.slice(a.indexOf('=') + 1))
266
- if (v !== null) return v
267
- }
259
+ for (const assignment of inlineFieldAssignments(args)) {
260
+ const verdict = parseEventAssignment(assignment)
261
+ if (verdict !== null) return verdict
268
262
  }
269
263
  return null
270
264
  }
@@ -277,13 +271,43 @@ function parseEventAssignment(token: string | undefined): ReviewVerdict | null {
277
271
  return normalizeVerdict(token.slice(eq + 1))
278
272
  }
279
273
 
280
- function verdictFromFile(contents: string | null): ReviewVerdict | null {
274
+ function commitIdFromInlineFields(args: readonly string[]): string | null {
275
+ for (const assignment of inlineFieldAssignments(args)) {
276
+ const separator = assignment.indexOf('=')
277
+ if (separator !== -1 && assignment.slice(0, separator).trim().toLowerCase() === 'commit_id') {
278
+ return assignment.slice(separator + 1)
279
+ }
280
+ }
281
+ return null
282
+ }
283
+
284
+ function inlineFieldAssignments(args: readonly string[]): string[] {
285
+ const assignments: string[] = []
286
+ for (let i = 0; i < args.length; i++) {
287
+ const arg = args[i]
288
+ if (arg === undefined) continue
289
+ if (arg === '-f' || arg === '-F' || arg === '--field' || arg === '--raw-field') {
290
+ const assignment = args[++i]
291
+ if (assignment !== undefined) assignments.push(assignment)
292
+ } else if (
293
+ arg.startsWith('-f=') ||
294
+ arg.startsWith('-F=') ||
295
+ arg.startsWith('--field=') ||
296
+ arg.startsWith('--raw-field=')
297
+ ) {
298
+ assignments.push(arg.slice(arg.indexOf('=') + 1))
299
+ }
300
+ }
301
+ return assignments
302
+ }
303
+
304
+ function stringFieldFromFile(contents: string | null, field: string): string | null {
281
305
  if (contents === null || contents === '') return null
282
306
  try {
283
307
  const parsed = JSON.parse(contents) as unknown
284
308
  if (typeof parsed !== 'object' || parsed === null) return null
285
- const event = (parsed as Record<string, unknown>).event
286
- return typeof event === 'string' ? normalizeVerdict(event) : null
309
+ const value = (parsed as Record<string, unknown>)[field]
310
+ return typeof value === 'string' ? value : null
287
311
  } catch {
288
312
  return null
289
313
  }
@@ -13,10 +13,11 @@ const NUDGE_TEXT =
13
13
  '`gh api` does not accept `-R/--repo`; TypeClaw consumes it as the mint hint and ' +
14
14
  'strips it before running the command with the right token injected.'
15
15
 
16
- // The shell strips quotes/escapes, so we match the raw `gh ... graphql` substring
17
- // rather than parse — the nudge is advisory, so a loose match is acceptable and a
18
- // false positive only appends a hint to an unrelated failure. Captured through to
19
- // end of line so we can inspect the SAME invocation's flags (see REPO_FLAG).
16
+ // Matched against the command the agent ran, not the tool output: a bash result
17
+ // carries only the process output, so gh's "gh auth login" stderr never names the
18
+ // graphql call that produced it. The nudge is advisory, so a loose substring match
19
+ // is acceptable. Captured through to end of line so we can inspect the SAME
20
+ // invocation's flags (see REPO_FLAG).
20
21
  const GRAPHQL_INVOCATION = /\bgh\b[^\n]*\bapi\b[^\n]*\bgraphql\b[^\n]*/
21
22
 
22
23
  // `-R foo`, `-R=foo`, `--repo foo`, `--repo=foo`. Word-boundary anchored so a
@@ -37,8 +38,12 @@ const AUTH_FAILURE_SIGNATURES = [
37
38
  'gh auth login',
38
39
  ]
39
40
 
40
- export function checkGraphqlAuthNudge(options: { tool: string; result: ToolResult }): void {
41
- if (options.tool !== 'bash') return
41
+ export function checkGraphqlAuthNudge(options: {
42
+ tool: string
43
+ command: string | undefined
44
+ result: ToolResult
45
+ }): void {
46
+ if (options.tool !== 'bash' || options.command === undefined) return
42
47
 
43
48
  // Only meaningful when no usable process token exists. An operator token or a
44
49
  // runtime-seeded PAT means graphql already authenticates, so the advice would
@@ -47,7 +52,7 @@ export function checkGraphqlAuthNudge(options: { tool: string; result: ToolResul
47
52
  if (tokenClass !== 'none') return
48
53
 
49
54
  const text = collectText(options.result.content)
50
- const invocation = GRAPHQL_INVOCATION.exec(text)
55
+ const invocation = GRAPHQL_INVOCATION.exec(options.command)
51
56
  if (invocation === null) return
52
57
  if (!AUTH_FAILURE_SIGNATURES.some((sig) => text.includes(sig))) return
53
58
  if (text.includes(GRAPHQL_AUTH_NUDGE_TAG)) return
@@ -83,6 +83,9 @@ export default definePlugin({
83
83
  const hasAppTokenResolver = ctx.github.hasAppTokenResolver
84
84
  const trustedGitTransportEnv: NodeJS.ProcessEnv = { ...process.env }
85
85
  const reviewCredentials = new Map<string, GithubTokenCredential>()
86
+ // tool.after only sees the bash output, so the graphql nudge needs the command
87
+ // that ran; keyed by callId like gitAuthDiagnostics.
88
+ const passThroughGraphqlCommands = new Map<string, string>()
86
89
  const resolveGitAuthLogin = createGitAuthLoginResolver()
87
90
  const gitAuthDiagnostics = new Map<
88
91
  string,
@@ -382,6 +385,9 @@ export default definePlugin({
382
385
  workspace: review.detected.workspace,
383
386
  prNumber: review.detected.prNumber,
384
387
  verdict: review.detected.verdict,
388
+ ...(review.detected.reviewedHeadSha !== undefined
389
+ ? { reviewedHeadSha: review.detected.reviewedHeadSha }
390
+ : {}),
385
391
  ...(event.origin?.kind === 'channel' && event.origin.githubReviewRound !== undefined
386
392
  ? { round: event.origin.githubReviewRound, thread: event.origin.thread }
387
393
  : {}),
@@ -433,6 +439,7 @@ export default definePlugin({
433
439
  const overlay = existing !== null && typeof existing === 'object' ? (existing as Record<string, string>) : {}
434
440
  event.args[TYPECLAW_INTERNAL_BASH_ENV] = { ...overlay, ...patOverlay }
435
441
  }
442
+ if (usesGhApiGraphqlEndpoint(command)) passThroughGraphqlCommands.set(event.callId, command)
436
443
  return 'fall-through'
437
444
  }
438
445
 
@@ -721,7 +728,9 @@ export default definePlugin({
721
728
  if (event.tool === 'bash' && gitAuth !== undefined) {
722
729
  await appendGitAuthDiagnostic({ result: event.result, ...gitAuth, resolveLogin: resolveGitAuthLogin })
723
730
  }
724
- checkGraphqlAuthNudge({ tool: event.tool, result: event.result })
731
+ const graphqlCommand = passThroughGraphqlCommands.get(event.callId)
732
+ passThroughGraphqlCommands.delete(event.callId)
733
+ checkGraphqlAuthNudge({ tool: event.tool, command: graphqlCommand, result: event.result })
725
734
  const dismissal = pendingDismissals.get(event.callId)
726
735
  pendingDismissals.delete(event.callId)
727
736
  if (dismissal !== undefined) {