typeclaw 0.50.0 → 0.52.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 (258) hide show
  1. package/dist/types/agent/bash-sandbox-env.d.ts +17 -0
  2. package/dist/types/agent/bash-sandbox-proc.d.ts +8 -0
  3. package/dist/types/agent/bash-sandbox.d.ts +98 -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 +10 -17
  7. package/dist/types/agent/multimodal/look-at.d.ts +1 -1
  8. package/dist/types/agent/output-allowance.d.ts +4 -0
  9. package/dist/types/agent/plugin-tools.d.ts +8 -75
  10. package/dist/types/agent/prompt-cache-key.d.ts +1 -0
  11. package/dist/types/agent/session-tail.d.ts +12 -0
  12. package/dist/types/agent/subagents.d.ts +5 -0
  13. package/dist/types/agent/system-prompt-composition.d.ts +18 -0
  14. package/dist/types/agent/system-prompt.d.ts +2 -0
  15. package/dist/types/agent/tools/channel-disengage.d.ts +1 -1
  16. package/dist/types/agent/tools/channel-edit.d.ts +1 -1
  17. package/dist/types/agent/tools/channel-fetch-attachment.d.ts +1 -1
  18. package/dist/types/agent/tools/channel-handoff.d.ts +1 -1
  19. package/dist/types/agent/tools/channel-history.d.ts +1 -1
  20. package/dist/types/agent/tools/channel-react.d.ts +1 -1
  21. package/dist/types/agent/tools/channel-read.d.ts +10 -2
  22. package/dist/types/agent/tools/channel-reply.d.ts +1 -1
  23. package/dist/types/agent/tools/channel-send.d.ts +1 -1
  24. package/dist/types/agent/tools/channel-session-search.d.ts +1 -1
  25. package/dist/types/agent/tools/ddg.d.ts +9 -0
  26. package/dist/types/agent/tools/grant-role.d.ts +1 -1
  27. package/dist/types/agent/tools/post-github-review.d.ts +1 -1
  28. package/dist/types/agent/tools/restart.d.ts +1 -1
  29. package/dist/types/agent/tools/skip-response.d.ts +1 -1
  30. package/dist/types/agent/tools/spawn-subagent.d.ts +2 -1
  31. package/dist/types/agent/tools/stream-snapshot.d.ts +2 -2
  32. package/dist/types/agent/tools/subagent-cancel.d.ts +1 -1
  33. package/dist/types/agent/tools/subagent-output.d.ts +1 -1
  34. package/dist/types/agent/tools/todo/index.d.ts +1 -1
  35. package/dist/types/agent/tools/webfetch/adaptive-html.d.ts +3 -3
  36. package/dist/types/agent/tools/webfetch/strategies/readability-process.d.ts +48 -0
  37. package/dist/types/agent/tools/webfetch/tool.d.ts +2 -2
  38. package/dist/types/agent/tools/websearch.d.ts +1 -1
  39. package/dist/types/channels/adapters/github/auth-app.d.ts +25 -0
  40. package/dist/types/channels/adapters/github/auth-pat.d.ts +17 -0
  41. package/dist/types/channels/adapters/github/auth.d.ts +24 -0
  42. package/dist/types/channels/github-review-check.d.ts +1 -1
  43. package/dist/types/channels/github-token-bridge.d.ts +4 -0
  44. package/dist/types/channels/lost-background-context.d.ts +2 -0
  45. package/dist/types/channels/persistence.d.ts +1 -0
  46. package/dist/types/channels/router.d.ts +16 -50
  47. package/dist/types/channels/types.d.ts +1 -0
  48. package/dist/types/coding-agent/tool.d.ts +1 -1
  49. package/dist/types/config/config.d.ts +22 -0
  50. package/dist/types/config/providers.d.ts +50 -1
  51. package/dist/types/container/start.d.ts +1 -0
  52. package/dist/types/eval/cell.d.ts +26 -0
  53. package/dist/types/eval/config.d.ts +19 -0
  54. package/dist/types/eval/dispatch.d.ts +7 -0
  55. package/dist/types/eval/kernel.d.ts +28 -0
  56. package/dist/types/eval/process.d.ts +23 -0
  57. package/dist/types/eval/protocol.d.ts +34 -0
  58. package/dist/types/eval/sandbox.d.ts +12 -0
  59. package/dist/types/eval/tool.d.ts +17 -0
  60. package/dist/types/eval/wire.d.ts +33 -0
  61. package/dist/types/git/resolve-identity.d.ts +2 -0
  62. package/dist/types/init/dockerfile.d.ts +1 -0
  63. package/dist/types/init/gitignore.d.ts +1 -1
  64. package/dist/types/permissions/builtins.d.ts +1 -0
  65. package/dist/types/plugin/types.d.ts +3 -0
  66. package/dist/types/sandbox/canonical-secrets.d.ts +2 -2
  67. package/dist/types/sandbox/coding-agent.d.ts +1 -1
  68. package/dist/types/sandbox/dependency-bins.d.ts +1 -0
  69. package/dist/types/sandbox/dev-source.d.ts +2 -2
  70. package/dist/types/sandbox/env-exposure.d.ts +2 -0
  71. package/dist/types/sandbox/hidden-paths.d.ts +1 -0
  72. package/dist/types/sandbox/index.d.ts +1 -1
  73. package/dist/types/sandbox/policy.d.ts +3 -0
  74. package/dist/types/typevault/cli-path.d.ts +2 -0
  75. package/dist/types/typevault/envelope-store.d.ts +11 -0
  76. package/dist/types/typevault/lifecycle.d.ts +13 -0
  77. package/dist/types/typevault/vault.d.ts +27 -0
  78. package/package.json +8 -7
  79. package/scripts/test.ts +252 -0
  80. package/src/agent/bash-sandbox-env.ts +136 -0
  81. package/src/agent/bash-sandbox-proc.ts +70 -0
  82. package/src/agent/bash-sandbox.ts +239 -0
  83. package/src/agent/compaction.ts +22 -10
  84. package/src/agent/idle-compaction.ts +7 -3
  85. package/src/agent/index.ts +185 -187
  86. package/src/agent/multimodal/look-at.ts +1 -1
  87. package/src/agent/output-allowance.ts +7 -0
  88. package/src/agent/plugin-tools.ts +64 -380
  89. package/src/agent/prompt-cache-key.ts +26 -3
  90. package/src/agent/session-origin.ts +41 -19
  91. package/src/agent/session-tail.ts +28 -0
  92. package/src/agent/subagent-completion-reminder.ts +2 -2
  93. package/src/agent/subagents.ts +21 -2
  94. package/src/agent/system-prompt-composition.ts +159 -0
  95. package/src/agent/system-prompt.ts +43 -5
  96. package/src/agent/todo/scope.ts +1 -1
  97. package/src/agent/tool-error-remediation.ts +18 -3
  98. package/src/agent/tools/channel-disengage.ts +1 -1
  99. package/src/agent/tools/channel-edit.ts +1 -1
  100. package/src/agent/tools/channel-fetch-attachment.ts +1 -1
  101. package/src/agent/tools/channel-handoff.ts +3 -2
  102. package/src/agent/tools/channel-history.ts +2 -1
  103. package/src/agent/tools/channel-react.ts +1 -1
  104. package/src/agent/tools/channel-read.ts +36 -3
  105. package/src/agent/tools/channel-reply.ts +1 -1
  106. package/src/agent/tools/channel-send.ts +4 -3
  107. package/src/agent/tools/channel-session-search.ts +13 -4
  108. package/src/agent/tools/ddg.ts +71 -11
  109. package/src/agent/tools/grant-role.ts +1 -1
  110. package/src/agent/tools/post-github-review.ts +1 -1
  111. package/src/agent/tools/restart.ts +1 -1
  112. package/src/agent/tools/skip-response.ts +1 -1
  113. package/src/agent/tools/spawn-subagent.ts +15 -1
  114. package/src/agent/tools/stream-snapshot.ts +1 -1
  115. package/src/agent/tools/subagent-cancel.ts +1 -1
  116. package/src/agent/tools/subagent-output.ts +1 -1
  117. package/src/agent/tools/todo/index.ts +1 -1
  118. package/src/agent/tools/webfetch/adaptive-html.ts +6 -4
  119. package/src/agent/tools/webfetch/strategies/readability-child.ts +25 -0
  120. package/src/agent/tools/webfetch/strategies/readability-process.ts +185 -0
  121. package/src/agent/tools/webfetch/tool.ts +6 -5
  122. package/src/agent/tools/websearch.ts +1 -1
  123. package/src/agent/tools-without-local-file-operands.ts +4 -0
  124. package/src/browser/dockerfile.ts +1 -1
  125. package/src/browser/fill-secret.ts +364 -0
  126. package/src/browser/registry.ts +6 -6
  127. package/src/bundled-plugins/agent-messenger-cli-auth/command.ts +211 -0
  128. package/src/bundled-plugins/agent-messenger-cli-auth/index.ts +186 -0
  129. package/src/bundled-plugins/backup/index.ts +17 -2
  130. package/src/bundled-plugins/backup/runner.ts +37 -2
  131. package/src/bundled-plugins/browser-agent/browser-agent.ts +51 -14
  132. package/src/bundled-plugins/browser-agent/index.ts +12 -5
  133. package/src/bundled-plugins/explorer/explorer.ts +1 -1
  134. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +40 -16
  135. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +12 -7
  136. package/src/bundled-plugins/github-cli-auth/index.ts +10 -1
  137. package/src/bundled-plugins/managed-browser/index.ts +130 -2
  138. package/src/bundled-plugins/managed-browser/skills/browserskill/browserskill/SKILL.md +13 -5
  139. package/src/bundled-plugins/managed-browser/skills/omowright/omowright/SKILL.md +56 -5
  140. package/src/bundled-plugins/memory/README.md +23 -2
  141. package/src/bundled-plugins/memory/append-fragment.ts +133 -0
  142. package/src/bundled-plugins/memory/append-tool.ts +80 -149
  143. package/src/bundled-plugins/memory/dreaming.ts +6 -1
  144. package/src/bundled-plugins/memory/index.ts +33 -6
  145. package/src/bundled-plugins/memory/load-memory.ts +2 -4
  146. package/src/bundled-plugins/memory/memory-logger.ts +200 -6
  147. package/src/bundled-plugins/memory/references/store-reference-tool.ts +56 -32
  148. package/src/bundled-plugins/memory/remember-tool.ts +81 -0
  149. package/src/bundled-plugins/memory/search-tool-hybrid.ts +91 -0
  150. package/src/bundled-plugins/memory/search-tool.ts +58 -12
  151. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  152. package/src/bundled-plugins/memory/transcript-cursor.ts +30 -0
  153. package/src/bundled-plugins/memory/transcript-preload.ts +208 -0
  154. package/src/bundled-plugins/memory/transcript-view.ts +36 -0
  155. package/src/bundled-plugins/memory/vector/hybrid.ts +25 -14
  156. package/src/bundled-plugins/memory/watermark.ts +19 -10
  157. package/src/bundled-plugins/reviewer/reviewer.ts +20 -0
  158. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +3 -6
  159. package/src/bundled-plugins/security/policies/outbound-text.ts +20 -0
  160. package/src/bundled-plugins/security/policies/private-surface-read.ts +166 -201
  161. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -7
  162. package/src/bundled-plugins/typevault/grants.ts +119 -0
  163. package/src/bundled-plugins/typevault/index.ts +152 -0
  164. package/src/bundled-plugins/typevault/request.ts +87 -0
  165. package/src/bundled-plugins/typevault/runtime.ts +45 -0
  166. package/src/bundled-plugins/typevault/skills/typevault/SKILL.md +65 -0
  167. package/src/channels/adapter-halt.ts +17 -0
  168. package/src/channels/adapters/discord-bot-reference.ts +5 -4
  169. package/src/channels/adapters/discord-bot.ts +1 -0
  170. package/src/channels/adapters/discord-classify.ts +8 -3
  171. package/src/channels/adapters/discord.ts +29 -0
  172. package/src/channels/adapters/github/history.ts +23 -2
  173. package/src/channels/adapters/github/inbound.ts +60 -1
  174. package/src/channels/adapters/github/index.ts +27 -5
  175. package/src/channels/adapters/github/reconcile-open-prs.ts +7 -1
  176. package/src/channels/adapters/kakaotalk-author-resolver.ts +7 -5
  177. package/src/channels/adapters/kakaotalk-channel-resolver.ts +45 -15
  178. package/src/channels/adapters/kakaotalk-classify.ts +7 -9
  179. package/src/channels/adapters/kakaotalk-list.ts +62 -0
  180. package/src/channels/adapters/kakaotalk-member-cache.ts +67 -0
  181. package/src/channels/adapters/kakaotalk-membership.ts +27 -10
  182. package/src/channels/adapters/kakaotalk-mention.ts +61 -0
  183. package/src/channels/adapters/kakaotalk.ts +159 -125
  184. package/src/channels/adapters/teams-classify.ts +18 -8
  185. package/src/channels/github-review-check.ts +5 -1
  186. package/src/channels/github-review-verdict-coordinator.ts +68 -2
  187. package/src/channels/github-token-bridge.ts +13 -0
  188. package/src/channels/lost-background-context.ts +46 -0
  189. package/src/channels/manager.ts +52 -3
  190. package/src/channels/persistence.ts +5 -0
  191. package/src/channels/router.ts +208 -128
  192. package/src/channels/schema.ts +1 -1
  193. package/src/channels/subagent-completion-bridge.ts +3 -2
  194. package/src/channels/types.ts +3 -0
  195. package/src/cli/hostd.ts +3 -0
  196. package/src/coding-agent/tool.ts +1 -1
  197. package/src/config/config.ts +35 -1
  198. package/src/config/providers.ts +75 -4
  199. package/src/container/start.ts +52 -3
  200. package/src/doctor/channel-checks.ts +33 -0
  201. package/src/doctor/checks.ts +37 -18
  202. package/src/doctor/index.ts +48 -12
  203. package/src/doctor/operational-incidents.ts +16 -1
  204. package/src/doctor/plugin-bridge.ts +14 -1
  205. package/src/doctor/stage.ts +14 -0
  206. package/src/doctor/types.ts +6 -0
  207. package/src/eval/cell.ts +93 -0
  208. package/src/eval/config.ts +32 -0
  209. package/src/eval/dispatch.ts +67 -0
  210. package/src/eval/entry.ts +261 -0
  211. package/src/eval/kernel.ts +154 -0
  212. package/src/eval/process.ts +113 -0
  213. package/src/eval/protocol.ts +26 -0
  214. package/src/eval/redeclare.ts +174 -0
  215. package/src/eval/sandbox.ts +117 -0
  216. package/src/eval/tool.ts +99 -0
  217. package/src/eval/wire.ts +93 -0
  218. package/src/git/resolve-identity.ts +67 -2
  219. package/src/git/system-commit.ts +7 -0
  220. package/src/init/dockerfile.ts +5 -1
  221. package/src/init/gitignore.ts +3 -3
  222. package/src/init/index.ts +1 -0
  223. package/src/init/models-dev.ts +2 -0
  224. package/src/init/validate-api-key.ts +5 -0
  225. package/src/migrations/secrets-v1-to-v2.ts +2 -0
  226. package/src/operations/classify-tool-outcome.ts +1 -1
  227. package/src/permissions/builtins.ts +8 -0
  228. package/src/plugin/core-tool-names.ts +6 -1
  229. package/src/plugin/types.ts +6 -0
  230. package/src/run/bundled-plugins.ts +12 -0
  231. package/src/run/channel-session-factory.ts +3 -0
  232. package/src/run/index.ts +13 -2
  233. package/src/sandbox/build.ts +1 -0
  234. package/src/sandbox/canonical-secrets.ts +6 -0
  235. package/src/sandbox/dependency-bins.ts +13 -1
  236. package/src/sandbox/dev-source.ts +21 -12
  237. package/src/sandbox/env-exposure.ts +20 -0
  238. package/src/sandbox/hidden-paths.ts +1 -1
  239. package/src/sandbox/index.ts +1 -0
  240. package/src/sandbox/policy.ts +5 -0
  241. package/src/secrets/hydrate.ts +4 -1
  242. package/src/secrets/storage.ts +10 -1
  243. package/src/server/command-runner.ts +4 -0
  244. package/src/server/index.ts +54 -12
  245. package/src/skills/typeclaw-config/SKILL.md +36 -2
  246. package/src/skills/typeclaw-memory/SKILL.md +3 -1
  247. package/src/skills/typeclaw-permissions/SKILL.md +8 -8
  248. package/src/skills/typeclaw-troubleshooting/SKILL.md +18 -1
  249. package/src/tunnels/active.ts +14 -0
  250. package/src/typevault/bash-cli.ts +18 -0
  251. package/src/typevault/cli-path.ts +11 -0
  252. package/src/typevault/envelope-helper.ts +17 -0
  253. package/src/typevault/envelope-store.ts +98 -0
  254. package/src/typevault/lifecycle.ts +132 -0
  255. package/src/typevault/prompt-tunnel.ts +33 -0
  256. package/src/typevault/redaction.ts +37 -0
  257. package/src/typevault/vault.ts +283 -0
  258. package/typeclaw.schema.json +92 -10
@@ -1,12 +1,19 @@
1
+ import { join } from 'node:path'
2
+
1
3
  import { getConfig } from '@/config'
2
4
  import { definePlugin } from '@/plugin'
5
+ import { isTypevaultMarkerFile } from '@/typevault/envelope-store'
3
6
 
4
7
  import { createBrowserSubagent } from './browser-agent'
5
8
 
6
9
  export default definePlugin({
7
- plugin: async () => ({
8
- subagents: {
9
- browser: createBrowserSubagent(getConfig().browser),
10
- },
11
- }),
10
+ plugin: async (ctx) => {
11
+ const config = getConfig()
12
+ const typevault = config.typevault.enabled && isTypevaultMarkerFile(join(ctx.agentDir, 'secrets.json'))
13
+ return {
14
+ subagents: {
15
+ browser: createBrowserSubagent(config.browser, { typevault }),
16
+ },
17
+ }
18
+ },
12
19
  })
@@ -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) {
@@ -1,12 +1,18 @@
1
1
  import { join } from 'node:path'
2
2
 
3
+ import { z } from 'zod'
4
+
3
5
  import { TYPECLAW_INTERNAL_BASH_ENV } from '@/agent/plugin-tools'
6
+ import { fillSecretIntoFocusedField, type FillSecretOutcome } from '@/browser/fill-secret'
4
7
  import { type ManagedBrowser, startManagedBrowser } from '@/browser/managed-browser'
5
8
  import { BROWSER_ENGINES, type BrowserConfig, needsManagedBrowser } from '@/browser/registry'
9
+ import { readVaultValue } from '@/bundled-plugins/typevault/runtime'
6
10
  import { getConfig } from '@/config'
11
+ import { readEnvFile } from '@/init/env-file'
7
12
  import type { PermissionService } from '@/permissions'
8
13
  import { CORE_PERMISSIONS } from '@/permissions/builtins'
9
- import { definePlugin, type Hooks } from '@/plugin'
14
+ import { definePlugin, defineTool, type Hooks } from '@/plugin'
15
+ import { resolveFillableEnvNames, SECRET_ENV_PREFIX } from '@/sandbox/env-exposure'
10
16
 
11
17
  const SKILLS_ROOT = join(import.meta.dir, 'skills')
12
18
 
@@ -26,10 +32,18 @@ export default definePlugin({
26
32
  return { skillsDirs }
27
33
  }
28
34
  const overlay = browserEnvOverlay(browser, managed)
35
+ const bashHook = sharedBrowserBashHook(ctx.permissions, overlay)
36
+ const fillGuard = fillSecretGuardHook(ctx.permissions)
29
37
 
30
38
  return {
31
39
  skillsDirs,
32
- hooks: { 'tool.before': sharedBrowserBashHook(ctx.permissions, overlay) },
40
+ tools: { [FILL_SECRET_TOOL]: createFillSecretTool(managed.cdpUrl) },
41
+ hooks: {
42
+ 'tool.before': async (event, hookCtx) => {
43
+ await bashHook(event, hookCtx)
44
+ return fillGuard(event, hookCtx)
45
+ },
46
+ },
33
47
  onDispose: () => managed.stop(),
34
48
  }
35
49
  },
@@ -48,6 +62,120 @@ export function sharedBrowserBashHook(
48
62
  }
49
63
  }
50
64
 
65
+ export const FILL_SECRET_TOOL = 'browser_fill_secret'
66
+ const VAULT_REF_PREFIX = 'typevault://'
67
+
68
+ // The tool drives the shared browser, so it needs `browser.shared` like bash's
69
+ // CDP URL does. Typing the withheld TYPECLAW_SECRET_* tier is runtime-owned
70
+ // credential use, which `fs.see.secrets` authorizes; ordinary .env vars are
71
+ // already in that role's bash, so typing them needs nothing more. This gates
72
+ // who may USE a secret, not who may observe it: every `browser.shared` holder
73
+ // drives the same pages over CDP and can watch what is typed there.
74
+ export function fillSecretGuardHook(permissions: PermissionService): NonNullable<Hooks['tool.before']> {
75
+ return (event) => {
76
+ if (event.tool !== FILL_SECRET_TOOL) return
77
+ if (!permissions.has(event.origin, CORE_PERMISSIONS.browserShared)) {
78
+ return { block: true, reason: `${FILL_SECRET_TOOL} needs the ${CORE_PERMISSIONS.browserShared} permission` }
79
+ }
80
+ const name = event.args['name']
81
+ if (typeof name === 'string' && name.startsWith(VAULT_REF_PREFIX)) {
82
+ return permissions.has(event.origin, CORE_PERMISSIONS.vaultUse)
83
+ ? undefined
84
+ : { block: true, reason: `${VAULT_REF_PREFIX} values need the ${CORE_PERMISSIONS.vaultUse} permission` }
85
+ }
86
+ if (
87
+ typeof name === 'string' &&
88
+ name.startsWith(SECRET_ENV_PREFIX) &&
89
+ !permissions.has(event.origin, CORE_PERMISSIONS.fsSeeSecrets)
90
+ ) {
91
+ return {
92
+ block: true,
93
+ reason: `${SECRET_ENV_PREFIX}* values need the ${CORE_PERMISSIONS.fsSeeSecrets} permission`,
94
+ }
95
+ }
96
+ }
97
+ }
98
+
99
+ export function createFillSecretTool(
100
+ cdpUrl: string,
101
+ fill: typeof fillSecretIntoFocusedField = fillSecretIntoFocusedField,
102
+ ) {
103
+ return defineTool({
104
+ description: [
105
+ 'Type the value of a .env variable into the focused field of a shared-browser tab without the value ever entering your context.',
106
+ 'Focus the field first with your browser engine (click it), then call this. Pass `url` (exact or prefix) when several tabs are open.',
107
+ `Accepts any ordinary .env variable and the ${SECRET_ENV_PREFIX}* tier, which is hidden from bash and reachable only through this tool.`,
108
+ `With TypeVault enabled, \`name\` can also be a vault reference such as ${VAULT_REF_PREFIX}github/bot#password, read through this session's grant.`,
109
+ 'With `submit: true` it presses Enter (submitting the form directly only if Enter did nothing) and waits for the page to navigate; if it does not, the field is cleared so the value is not left on the page.',
110
+ 'The result names the tab and field, never the value. Never read the field back, screenshot a non-password field after filling, or echo the variable.',
111
+ ].join(' '),
112
+ parameters: z.object({
113
+ name: z
114
+ .string()
115
+ .describe(
116
+ 'The .env variable name, e.g. TYPECLAW_SECRET_GITHUB_PASSWORD, or a vault reference like typevault://github/bot#password',
117
+ ),
118
+ url: z.string().optional().describe('Exact URL or prefix of the target tab'),
119
+ submit: z.boolean().default(false),
120
+ }),
121
+ fileOperands: { nonFile: ['name', 'url'] },
122
+ execute: async (args, ctx) => {
123
+ if (args.name.startsWith(VAULT_REF_PREFIX)) {
124
+ const read = await readVaultValue(ctx.sessionId, args.name, 'fill a browser field')
125
+ if (!read.ok) return text(`Not filled: ${read.reason}.`)
126
+ const outcome = await fill({
127
+ cdpUrl,
128
+ value: read.value,
129
+ submit: args.submit,
130
+ ...(args.url === undefined ? {} : { url: args.url }),
131
+ })
132
+ return text(describeOutcome(args.name, outcome))
133
+ }
134
+ const fillable = new Set(resolveFillableEnvNames(readEnvFile(ctx.agentDir), process.env))
135
+ if (!fillable.has(args.name)) {
136
+ return text(
137
+ `${args.name} is not a fillable variable: declare it with a non-empty value in .env (runtime controls are never fillable).`,
138
+ )
139
+ }
140
+ const value = process.env[args.name]
141
+ if (value === undefined || value.length === 0) {
142
+ return text(
143
+ `${args.name} is in .env but not loaded yet; the operator must restart the agent after editing .env.`,
144
+ )
145
+ }
146
+ const outcome = await fill({
147
+ cdpUrl,
148
+ value,
149
+ submit: args.submit,
150
+ ...(args.url === undefined ? {} : { url: args.url }),
151
+ })
152
+ return text(describeOutcome(args.name, outcome))
153
+ },
154
+ })
155
+ }
156
+
157
+ function describeOutcome(name: string, outcome: FillSecretOutcome): string {
158
+ switch (outcome.status) {
159
+ case 'refused':
160
+ return `Not filled: ${outcome.reason}.`
161
+ case 'filled':
162
+ return `Filled ${name} into ${outcome.field} on ${outcome.url}.`
163
+ case 'submitted':
164
+ return `Filled ${name} into ${outcome.field} on ${outcome.url} and submitted; the page navigated.`
165
+ case 'not-navigated':
166
+ return (
167
+ `Filled ${name} into ${outcome.field} on ${outcome.url} and submitted, but the page did not navigate. ` +
168
+ (outcome.cleared
169
+ ? 'The field was cleared; check the page for an error.'
170
+ : 'The field could not be cleared (cross-origin frame); check the page for an error.')
171
+ )
172
+ }
173
+ }
174
+
175
+ function text(value: string) {
176
+ return { content: [{ type: 'text' as const, text: value }] }
177
+ }
178
+
51
179
  export function browserSkillDirs(browser: BrowserConfig): string[] {
52
180
  const ids = [...browser.engines.filter((id) => id !== 'agent-browser'), ...browser.extensions]
53
181
  // One root per id (skills/<id>/<skill>/SKILL.md) so disabled engines stay out of the catalog.
@@ -9,13 +9,21 @@ The `bsk` CLI talks to a daemon TypeClaw runs next to the shared browser; the Br
9
9
 
10
10
  ```bash
11
11
  bsk status --json # a connected browser must be listed
12
- SID=$(bsk session start --json | jq -r .session_id)
13
- bsk navigate https://example.com --session "$SID"
14
- bsk snapshot --session "$SID" # @eN refs
15
- bsk click @e3 --session "$SID"
12
+ SID=$(bsk session start --agent-name TypeClaw --json | jq -r .session_id)
13
+ bsk navigate https://example.com/signup --session "$SID" # the first navigation of the blank tab needs no context
14
+ SYNC=$(bsk cooperate sync --session "$SID" --json)
15
+ CTX=$(jq -r .context_id <<<"$SYNC"); OBS=$(jq -r .observation_id <<<"$SYNC")
16
+ bsk snapshot --session "$SID" # @eN refs; use the ones your snapshot shows
17
+ bsk fill @e2 --value Alice --session "$SID" --context "$CTX"
18
+ bsk press Enter --ref @e2 --session "$SID" --context "$CTX"
16
19
  bsk session stop "$SID" # always stop, success or failure
17
20
  ```
18
21
 
22
+ - Targeted page actions (`click`, `fill`, `select`, `press --ref`, `hover`, `scroll-to`, ...) need `--context` from `bsk cooperate sync`. One context covers reads and completed DOM actions until the document changes (a navigation, a form submit); then sync again and take fresh refs. Reads (`snapshot`, `get-html`, `screenshot`) need none.
23
+ - `navigate` (after the first one), `evaluate`, `wheel`, a `press` without `--ref`, and screenshot-coordinate clicks also need `--observation` with the top-level `observation_id` from a sync (not the nested `observation.observation_id`). Each observation is single-use: sync again before the next such action.
24
+ - `--expect '[{"target":"@e4","field":"text","equals":"Save"}]'` makes an action fail with `precondition_failed` instead of acting when the fact you decided on changed.
25
+ - A `permission_denied` refusal names why in `data.reason`: `control_context_invalid` (missing or stale `--context`), `observation_required` (add a fresh `--observation`), `cooperation_sync_required`. Each means sync, read the page again, and decide afresh; never replay the refused action blindly. If `effect_state` is `unknown`, check the page for the result before retrying.
26
+ - Redirect large output to a file (`bsk get-html --session "$SID" --json > /tmp/page.json`); piping it straight into another command can crash `bsk` with `failed printing to stdout`.
19
27
  - Sessions open their own Agent Window. Never borrow an existing tab: borrowing asks a human to confirm, and nobody can click it here.
20
28
  - `bsk --help` and `bsk <command> --help` list everything (`extract`, `observe`, `record`, `debug`).
21
29
  - Never run `bsk update`, `bsk daemon stop`, or `bsk daemon restart`; TypeClaw owns the daemon and its version.
@@ -24,5 +32,5 @@ bsk session stop "$SID" # always stop, success or failure
24
32
 
25
33
  - One TypeClaw-managed Chrome serves every engine and every session that has `browser.shared`. Logins and tabs persist across bash calls and sessions.
26
34
  - Work only in tabs you opened. Never navigate or close a tab another engine or session is using.
27
- - Files: downloads land in `$TYPECLAW_BROWSER_FILES`; to upload a file, copy it there first and pass that path. Chrome cannot see other paths.
35
+ - Files: Chrome's own downloads land in `$TYPECLAW_BROWSER_FILES`, and Chrome cannot see other paths. `bsk upload --file <path>` and `bsk download --out <path>` move files through the CLI, so they accept any path your bash can read or write.
28
36
  - The browser runs in its own sandbox with no view of the agent folder, so `file://` URLs outside `$TYPECLAW_BROWSER_FILES` fail by design.
@@ -5,7 +5,7 @@ description: Playwright-shaped browser automation library (OmOWright) for the sh
5
5
 
6
6
  # omowright
7
7
 
8
- OmOWright is a JavaScript library with the Playwright API shape (`page.goto`, `page.locator(ref).click()`, `page.mouse.wheel`, `page.keyboard.type`, `page.screenshot`). Write a short Bun script and run it with `bun`. Each script connects to the shared browser, so state survives between scripts.
8
+ OmOWright is a JavaScript library with the Playwright API shape (`page.goto`, `page.locator(ref).click()`, `page.mouse.wheel`, `page.keyboard.type`, `page.screenshot`). Write a short Bun script and run it with `bun`. Each script connects to the shared browser, so tabs, logins, and cookies survive between scripts. Snapshot refs do not.
9
9
 
10
10
  `$OMOWRIGHT_CDP_URL` holds the connection URL. If the variable is unset, this session's role cannot use the shared browser (it needs the `browser.shared` permission) or the browser failed to start; the operator log (`typeclaw logs`) names which. Do not try to start Chrome yourself.
11
11
 
@@ -17,20 +17,71 @@ const url = process.env.OMOWRIGHT_CDP_URL
17
17
  // The relay requires the token on every request; omowright drops the URL query
18
18
  // for HTTP discovery (listTargets), so pass it as an Authorization header too.
19
19
  const token = new URL(url).searchParams.get('token')
20
- const browser = await connect(url, {
20
+ // `await using` closes this script's connection when the script ends, so the
21
+ // script exits on its own; the tab and the browser keep running.
22
+ await using browser = await connect(url, {
21
23
  client: { authorizer: { resolveAuthorization: async () => `Bearer ${token}` } },
22
24
  })
23
25
  const tabs = createAgentTabs(browser) // background tabs that never steal focus
24
- const page = await tabs.open('https://example.com')
26
+ const { targetId, page } = await tabs.create('https://example.com')
27
+ console.log(targetId) // keep it: later scripts reattach with browser.attachPage(targetId)
25
28
  console.log(compactSnapshot(await page.snapshot())) // refs like [ref=e1]
26
29
  await page.locator('e1').click()
27
- process.exit(0) // leaves the tab and browser running
28
30
  ```
29
31
 
32
+ Always connect with `await using browser = await connect(...)`, as above. With a plain `const`, the open connection keeps Bun running, so the script prints its output and then hangs until the bash timeout kills it. `await using` also closes the connection when the script throws. Tabs made with `createAgentTabs` stay open for the next script; a popup tab the script attached (from `window.open`) closes with the connection, so do work that must continue later in an agent tab.
33
+
34
+ A "Command timed out" result after the script printed output means the script did not exit, not that the browser or the site failed. Do not report a browser timeout and do not blindly rerun it: its actions (a click, a submit) may already have gone through. Reattach to the tab with `attachPage`, snapshot it, and continue from what the page shows; repeat a step only if the page shows it did not happen.
35
+
36
+ A later script continues in the same tab with `const page = await browser.attachPage(targetId)`. `browser.listTargets()` lists open tabs when the id is lost.
37
+
38
+ Refs like `e14` belong to the script that took the snapshot. A new script has none, so `page.locator('e14')` from an earlier run always throws `RefStaleError`. In every script that acts on refs, call `page.snapshot()` first and use the refs from that snapshot in the same script. A page change (a click that navigates, a modal opening) also invalidates refs: snapshot again in the same script before the next ref action. When a ref stays stale, use a semantic locator instead, such as `page.getByRole('link', { name: '로그인' })` or `page.locator('#userId')`.
39
+
40
+ Reuse your tab across retries with `attachPage` instead of opening another `tabs.create` for the same site, and close tabs you no longer need (`await page.close()`). Duplicate tabs of one site make it unclear which tab later steps (and `browser_fill_secret`) act on.
41
+
30
42
  - Prefer `compactSnapshot(await page.snapshot())` over screenshots; re-snapshots come back as a diff.
31
43
  - Long lists: `createNetworkSnoop` + `collectWhileScrolling` read the page's JSON instead of scraping rows.
32
44
  - Canvas or custom widgets: `createCua(page)` gives coordinate-level clicks and scrolls.
33
- - `connectPipe()` and `connectBrowserSkill()` launch or find other browsers; do not use them here.
45
+ - `connectBrowser()`, `connectPipe()`, and `connectBrowserSkill()` launch or find other browsers; do not use them here.
46
+
47
+ ## Sites with anti-macro checks
48
+
49
+ Some sites (ticketing and banking sites such as Korail, often behind DynaPath) score how input arrives and reject requests that look scripted. On Korail the rejection is a dialog like "매크로, 개발자도구 등 미허가 도구 사용 시 이용이 제한될 수 있습니다" or a `CODE : -8002`. That dialog is a block of the request, not a notice to click away; the login or search did not go through.
50
+
51
+ `locator(ref).click()` jumps the pointer straight to the element and `keyboard.type(text)` types with no delay between keys, which these checks reject. Both a moving pointer and a typing delay are needed; either alone is still rejected. On such sites, click and type like this instead:
52
+
53
+ ```js
54
+ const rand = (min, max) => min + Math.random() * (max - min)
55
+ const pause = (min, max) => new Promise((resolve) => setTimeout(resolve, rand(min, max)))
56
+
57
+ async function humanClick(page, ref, [fromX, toX] = [0.3, 0.7]) {
58
+ await page.locator(ref).scrollIntoViewIfNeeded()
59
+ const box = await page.locator(ref).boundingBox()
60
+ const x = box.x + box.width * rand(fromX, toX)
61
+ const y = box.y + box.height * rand(0.3, 0.7)
62
+ await page.mouse.move(x, y, { steps: Math.round(rand(12, 25)) })
63
+ await pause(80, 250)
64
+ await page.mouse.down()
65
+ await pause(40, 110)
66
+ await page.mouse.up()
67
+ }
68
+
69
+ async function humanType(page, ref, text) {
70
+ // Aim at the left of the field: the right edge often holds an overlay
71
+ // (password reveal, virtual-keypad toggle) that swallows the keystrokes.
72
+ await humanClick(page, ref, [0.1, 0.35])
73
+ await pause(300, 700)
74
+ // Clear what a previous attempt left in the field so a retry does not append.
75
+ await page.keyboard.press('Control+A')
76
+ await page.keyboard.press('Backspace')
77
+ await pause(150, 400)
78
+ await page.keyboard.type(text, { delay: 120 })
79
+ }
80
+ ```
81
+
82
+ - Before submitting, take a fresh snapshot and check every field holds what you typed; if one is empty, a click hit an overlay instead of the field.
83
+ - After a block, dismiss the dialog and redo the same step with `humanClick`/`humanType`. Do not report the site as unusable until that retry also fails.
84
+ - Do not call the site's endpoints yourself with `page.evaluate(() => fetch(...))`. The check signs the page's own requests, so a hand-made request is rejected even when the UI flow would pass. Drive the UI.
34
85
 
35
86
  ## Shared browser rules
36
87
 
@@ -4,6 +4,16 @@ The bundled memory plugin. Owns `memory/topics/` (sharded long-term memory) and
4
4
 
5
5
  Auto-loaded by every TypeClaw agent. No `plugins[]` entry to add and no opt-out. Configure via the `memory` block in `typeclaw.json`.
6
6
 
7
+ ## Extractor pages
8
+
9
+ `memory-logger` receives a projected, bounded transcript view rather than provider bookkeeping and opaque replay signatures. Message content, timestamps, attribution, source IDs, parent/tool-call links, errors, and unknown evidence fields remain available; canonical transcripts stay unchanged.
10
+
11
+ Large projected records are supplied as lossless `entry-part` segments. The runtime persists a starting checkpoint before each page, defers progress while fragments are being written, and accepts page completion only for the issued checkpoint and source. An interruption replays the unfinished page. Explicit checkpoints remain authoritative across daily streams; fragments alone cannot advance an unfinished page.
12
+
13
+ Each continuation includes bounded read-only `precedingText` from the same record, charged to the page budget, so split instructions can be interpreted with their preceding context. Only new `text` contributes to checkpoint progress. If a partial cursor cannot be preloaded because limits are unavailable or insufficient, it remains pending with an operator warning; the legacy reader never receives it.
14
+
15
+ Partial-entry checkpoints use versioned `memory-page:` cursors. Changed source records restart at their beginning, and legacy complete-entry watermarks remain supported. Drain pending pages before downgrading to a version without cursor support. No scheduling, idle-delta, or buffer-ceiling settings change.
16
+
7
17
  ## Config
8
18
 
9
19
  ```json
@@ -34,13 +44,20 @@ All fields are **restart-required** — the plugin reads them once at boot. The
34
44
  | -------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
35
45
  | Subagent | `memory-logger` | Reads a parent transcript past a watermark and appends fragments to `memory/streams/<today>.jsonl`. Coalesced per `agentDir`. |
36
46
  | Subagent | `dreaming` | Reads shards under `memory/topics/` plus undreamed daily-stream events and rebalances the topic shards. Coalesced per `agentDir`. Citation-superset invariant enforced on every run. |
37
- | Tool | `memory_search` | Main-agent tool. Pass `query` for phrase-first/token-fallback lexical search, or `topic` for exact slug lookup (not both). Searches topic shards, active cited-child provenance, undreamed streams, and references. Optional `workspace`, `chat`, and `thread` scopes apply to both query and exact-topic mode; legacy `where` aliases `chat`. Results include eligible active-child provenance. See [Provenance-aware recall](#provenance-aware-recall). |
47
+ | Tool | `memory_search` | Main-agent tool. Pass `query` for semantic+keyword hybrid search (default `mode: "hybrid"`), or `topic` for exact topic/reference slug lookup (not both). Use `mode: "lexical"` for the existing phrase-first/token-fallback behavior; `asRegex: true` and `topic` always stay lexical. Searches topics, active cited-child provenance, undreamed streams, and references. `maxResults` caps hybrid top-K; `full: true` loads complete bodies. Missing indexes or semantic errors produce a reported lexical fallback and an operator log. Optional `workspace`, `chat`, and `thread` scopes apply to both modes; legacy `where` aliases `chat`. See [Provenance-aware recall](#provenance-aware-recall). |
48
+ | Tool | `memory_remember` | Main-agent tool for immediate deliberate capture: `topic`, `body`, optional `who` and `verbatim`. Writes one explicit fragment with runtime provenance; optional exact reference; shared vector hooks; no logger progress or topic-shard writes. |
38
49
  | Tool | `delete_topic_shard` | Subagent-only (dreaming). Deletes a topic shard at `memory/topics/<slug>.md`. Path-guarded. |
39
50
  | Cron | `__plugin_memory_dreaming` | `kind: 'prompt'`, `subagent: 'dreaming'`, scheduled per `memory.dreaming.schedule`. |
40
51
  | Hook | `session.idle` | Per-session debouncer with size-based ceiling. Spawns `memory-logger` on idle or buffer-trip. |
41
52
  | Hook | `session.end` | Spawns `memory-logger` immediately and clears per-session retrieval de-dup state. |
42
53
  | Hook | `session.turn.start` | Renders the per-turn user-prompt memory block into `event.retrievalContext.results` (direct-mode shards under budget, de-duplicated across turns per session; top-K `hybridSearch` over budget; channel origins always index/headings-only); runs for every origin that supplies a `retrievalContext`, including user-delegated subagents (researcher, reviewer) — but NOT TypeClaw-owned infrastructure turns (`system` origins and `system`-spawned subagents memory-logger/backup, plus the dreaming cron job matched by its `__plugin_memory_dreaming` job id), whose `userPrompt` is a fixed instruction block, not a user message (see [Internal-infrastructure turns skip retrieval](#internal-infrastructure-turns-skip-retrieval)). |
43
54
 
55
+ ## Deliberate capture
56
+
57
+ `memory_remember({ topic, body, who?, verbatim? })` lets the agent immediately save a durable fact, decision, preference, or correction in every role and standard origin. It appends one `kind: "explicit"` fragment to today's stream. The runtime stamps the session id as `source`, the transcript leaf at invocation as `entry`, and channel coordinates from the live origin. Direct calls without a transcript use an empty `entry`. It never writes topic shards or advances the memory-logger watermark, including the legacy fragment-derived fallback.
58
+
59
+ With `verbatim: true`, the existing reference writer also stores the exact body and links its returned slug from `references`. Credential checks run before either write. Fragment and reference writes use memory-logger's vector hooks for immediate retrieval. Dreaming gives deliberate capture weight while retaining its normal consolidation, deduplication, citation-superset, and runtime-owned frontmatter rules. Memory-logger skips facts already saved by successful `memory_remember` calls in the transcript.
60
+
44
61
  ## Provenance-aware recall
45
62
 
46
63
  Fragments can carry runtime-stamped `where` coordinates (`adapter`, workspace/chat/thread IDs, captured names, and Discord parent-room metadata) plus an attributed `who`. A topic derives searchable provenance only from its **active** `fragments:` children. `superseded:` evidence is excluded, and unresolved citations remain explicit rather than receiving invented metadata. The same eligible children determine scope eligibility, lexical matching, and returned `provenance`, so a multi-workspace topic cannot return another workspace's child details through a scoped result.
@@ -67,6 +84,10 @@ Each stripped topic is injected with its `slug:` line so the agent can re-fetch
67
84
 
68
85
  The system prompt never contains long-term memory, so a session cannot double-carry memory in both the system prompt and the user turn.
69
86
 
87
+ ### Blank-prompt turns skip retrieval
88
+
89
+ A runtime wakeup (a subagent completion or review-state reminder in a channel) has no inbound text, so its `userPrompt` is blank. An empty query embeds to a vector that scores every topic alike, and the slug tie-break used to inject the same first ten headings on every such turn. A blank prompt now injects nothing; the human turn that started the work already carried its own memory, and `memory_search` stays available.
90
+
70
91
  ### Internal-infrastructure turns skip retrieval
71
92
 
72
93
  The `session.turn.start` per-turn injection runs for user-delegated subagents (researcher, reviewer) but is skipped entirely for **TypeClaw-owned infrastructure turns**. Their `userPrompt` is a fixed instruction block (`buildInitialPrompt`), not a user message — feeding it into `hybridSearch` keyword-mines the subagent's own framing prose ("Read the transcript past the watermark…"), retrieves nothing useful, and embeds a ~560-token query that trips the 512-token bound warning on every spawn. None of these subagents consume injected long-term memory the way a conversational turn does, so retrieval there is pure waste.
@@ -187,7 +208,7 @@ The `session.idle` hook fires after every prompt completion. A chatty channel se
187
208
 
188
209
  ### Byte-equality skip (session.end)
189
210
 
190
- When `session.end` arrives and an earlier idle/buffer-trip spawn already drained the transcript to its current size, the session-end spawn is skipped. The skip is logged as `memory-logger session-end skip ses_X (no new bytes since last spawn at N)`. The skip only applies when a real baseline was recorded (`bytesAtLastRun > 0`); sessions that ended before any spawn ran still fire on close.
211
+ When `session.end` arrives, the final sweep is skipped only when an earlier spawn recorded the same byte size **and** its durable watermark matches the transcript's complete final entry. Returning from a logger spawn does not itself prove the evidence was drained. Missing checkpoints, partial-entry cursors, malformed tails, and failed coverage checks retain the final sweep. The skip is logged as `memory-logger session-end skip ses_X (no new bytes since last spawn at N)`. Sessions that ended before any spawn ran still fire on close.
191
212
 
192
213
  ### Daily-stream cursor (memory-logger payload)
193
214