typeclaw 0.47.2 → 0.48.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 (105) hide show
  1. package/package.json +1 -1
  2. package/src/agent/index.ts +1 -2
  3. package/src/agent/loop-guard.ts +71 -41
  4. package/src/agent/plugin-tools.ts +167 -50
  5. package/src/agent/system-prompt.ts +1 -1
  6. package/src/agent/turn-runner.ts +12 -2
  7. package/src/bundled-plugins/agent-browser/index.ts +0 -38
  8. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +1 -1
  9. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +16 -1
  10. package/src/bundled-plugins/memory/append-tool.ts +75 -2
  11. package/src/bundled-plugins/memory/frontmatter.ts +13 -2
  12. package/src/bundled-plugins/memory/load-memory.ts +1 -1
  13. package/src/bundled-plugins/memory/memory-logger.ts +5 -1
  14. package/src/bundled-plugins/memory/secret-detector.ts +7 -0
  15. package/src/bundled-plugins/memory/vector/hybrid.ts +3 -1
  16. package/src/bundled-plugins/memory/vector/passages.ts +5 -1
  17. package/src/bundled-plugins/security/index.ts +148 -98
  18. package/src/bundled-plugins/security/policies/private-surface-read.ts +43 -28
  19. package/src/channels/adapters/discord-bot-edit.ts +3 -5
  20. package/src/channels/adapters/discord-bot-reactions.ts +4 -6
  21. package/src/channels/adapters/discord-bot-slash-commands.ts +3 -1
  22. package/src/channels/adapters/discord-bot.ts +20 -23
  23. package/src/channels/adapters/discord-edit.ts +3 -5
  24. package/src/channels/adapters/discord-reactions.ts +4 -6
  25. package/src/channels/adapters/discord.ts +1 -1
  26. package/src/channels/adapters/github/decoy-reviewer.ts +2 -1
  27. package/src/channels/adapters/github/history.ts +2 -1
  28. package/src/channels/adapters/github/inbound.ts +4 -11
  29. package/src/channels/adapters/github/index.ts +6 -9
  30. package/src/channels/adapters/github/outbound.ts +3 -6
  31. package/src/channels/adapters/github/reactions.ts +3 -2
  32. package/src/channels/adapters/github/reconcile-cooldown-store.ts +4 -6
  33. package/src/channels/adapters/github/reconcile-open-prs.ts +5 -4
  34. package/src/channels/adapters/github/recover-failed-deliveries.ts +2 -5
  35. package/src/channels/adapters/github/review-state.ts +3 -2
  36. package/src/channels/adapters/github/review-thread-resolver.ts +3 -2
  37. package/src/channels/adapters/github/webhook-register.ts +5 -8
  38. package/src/channels/adapters/instagram-channel-resolver.ts +3 -5
  39. package/src/channels/adapters/instagram.ts +1 -1
  40. package/src/channels/adapters/kakaotalk-author-resolver.ts +2 -5
  41. package/src/channels/adapters/kakaotalk-channel-resolver.ts +3 -5
  42. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +2 -1
  43. package/src/channels/adapters/kakaotalk-membership.ts +2 -5
  44. package/src/channels/adapters/kakaotalk-typing.ts +1 -1
  45. package/src/channels/adapters/kakaotalk.ts +1 -1
  46. package/src/channels/adapters/line-channel-resolver.ts +3 -5
  47. package/src/channels/adapters/line.ts +1 -1
  48. package/src/channels/adapters/slack-bot-edit.ts +1 -1
  49. package/src/channels/adapters/slack-bot-reactions.ts +4 -6
  50. package/src/channels/adapters/slack-bot.ts +8 -8
  51. package/src/channels/adapters/slack-edit.ts +3 -5
  52. package/src/channels/adapters/slack-reactions.ts +4 -6
  53. package/src/channels/adapters/slack.ts +1 -1
  54. package/src/channels/adapters/teams-edit.ts +2 -5
  55. package/src/channels/adapters/teams.ts +1 -1
  56. package/src/channels/adapters/telegram-bot-edit.ts +4 -7
  57. package/src/channels/adapters/telegram-bot.ts +1 -1
  58. package/src/channels/adapters/webex-bot.ts +1 -1
  59. package/src/channels/adapters/webex-edit.ts +3 -5
  60. package/src/channels/adapters/webex.ts +1 -1
  61. package/src/channels/github-review-claim.ts +89 -4
  62. package/src/channels/github-token-bridge.ts +2 -1
  63. package/src/channels/manager.ts +478 -64
  64. package/src/channels/membership-cache.ts +2 -5
  65. package/src/channels/persistence.ts +3 -6
  66. package/src/channels/reloadable.ts +23 -6
  67. package/src/channels/router.ts +134 -56
  68. package/src/channels/tunnel-bridge.ts +2 -1
  69. package/src/channels/types.ts +6 -3
  70. package/src/cli/hostd.ts +56 -28
  71. package/src/config/config.ts +10 -0
  72. package/src/config/providers.ts +179 -0
  73. package/src/dependencies/bin-resolver.ts +88 -0
  74. package/src/dependencies/bins.ts +227 -0
  75. package/src/dependencies/index.ts +17 -0
  76. package/src/doctor/checks.ts +2 -0
  77. package/src/doctor/operational-incidents.ts +32 -0
  78. package/src/hostd/credential-rotation-apply.ts +94 -0
  79. package/src/init/models-dev.ts +17 -3
  80. package/src/init/validate-api-key.ts +26 -4
  81. package/src/operations/classify-tool-outcome.ts +151 -0
  82. package/src/operations/incidents.ts +274 -0
  83. package/src/operations/index.ts +3 -0
  84. package/src/operations/remediations.ts +41 -0
  85. package/src/reload/client.ts +8 -2
  86. package/src/reload/docker-exec-client.ts +10 -2
  87. package/src/reload/index.ts +1 -1
  88. package/src/reload/recover.ts +5 -3
  89. package/src/reload/registry.ts +5 -5
  90. package/src/reload/types.ts +9 -1
  91. package/src/run/index.ts +5 -0
  92. package/src/sandbox/dependency-bins.ts +125 -0
  93. package/src/sandbox/errors.ts +32 -0
  94. package/src/sandbox/hidden-paths.ts +4 -1
  95. package/src/sandbox/index.ts +8 -0
  96. package/src/sandbox/policy.ts +1 -1
  97. package/src/sandbox/privileged-runtime.ts +88 -7
  98. package/src/sandbox/runtime-private.ts +4 -0
  99. package/src/sandbox/writable-zones.ts +4 -4
  100. package/src/server/index.ts +7 -5
  101. package/src/shared/protocol.ts +6 -1
  102. package/typeclaw.schema.json +35 -5
  103. package/src/bundled-plugins/agent-browser/shim-install.ts +0 -179
  104. package/src/bundled-plugins/agent-browser/shim.ts +0 -108
  105. /package/src/channels/{adapters/describe-error.ts → describe-error.ts} +0 -0
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: agent-browser
3
3
  description: Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction. Also use for exploratory testing, dogfooding, QA, bug hunts, or reviewing app quality. Also use for automating Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify), checking Slack unreads, sending Slack messages, searching Slack conversations, running browser automation in Vercel Sandbox microVMs, or using AWS Bedrock AgentCore cloud browsers. ALSO use whenever a browser step needs a human in the loop — login walls, 2FA, CAPTCHA, payment confirmation, "is this the right button?" ambiguity, or the user asking to watch the browser live — because the bundled dashboard is the only way for a human to observe or take over a session from inside the Docker container. Prefer agent-browser over any built-in browser automation or web tools.
4
- allowed-tools: Bash(agent-browser:*), Bash(npx agent-browser:*)
4
+ allowed-tools: Bash(agent-browser:*)
5
5
  hidden: true
6
6
  ---
7
7
 
@@ -15,7 +15,6 @@ const AGENT_ROOT_WRITE_ALLOWLIST = new Set([
15
15
  'SOUL.md',
16
16
  'USER.md',
17
17
  'cron.json',
18
- 'package.json',
19
18
  'typeclaw.json',
20
19
  ])
21
20
 
@@ -48,6 +47,12 @@ export async function checkNonWorkspaceWriteGuard(options: {
48
47
  resolveRealIntendedPath(path.resolve(agentDir)),
49
48
  resolveRealIntendedPath('/tmp'),
50
49
  ])
50
+ if (await isOperatorOwnedPackageManifest(agentDir, targetPath, realTargetPath)) {
51
+ return {
52
+ block: true,
53
+ reason: `Guard \`${GUARD_NON_WORKSPACE_WRITE}\` blocked a model write to operator-owned package manifest ${targetPath}.`,
54
+ }
55
+ }
51
56
  if (await isSkillAuthoringAllowed({ tool, args, agentDir })) return undefined
52
57
  if (await isMemoryTopicsWriteAllowed({ tool, args, agentDir, origin })) return undefined
53
58
  if (await isAllowedAgentRootWrite(agentDir, targetPath, realTargetPath)) return undefined
@@ -74,6 +79,16 @@ export async function checkNonWorkspaceWriteGuard(options: {
74
79
  }
75
80
  }
76
81
 
82
+ async function isOperatorOwnedPackageManifest(
83
+ agentDir: string,
84
+ targetPath: string,
85
+ realTargetPath: string,
86
+ ): Promise<boolean> {
87
+ const rootManifest = path.join(path.resolve(agentDir), 'package.json')
88
+ const realRootManifest = await resolveRealIntendedPath(rootManifest)
89
+ return targetPath === rootManifest || realTargetPath === realRootManifest
90
+ }
91
+
77
92
  async function isAllowedAgentRootWrite(agentDir: string, targetPath: string, realTargetPath: string): Promise<boolean> {
78
93
  const resolvedAgentDir = path.resolve(agentDir)
79
94
  if (path.dirname(targetPath) === resolvedAgentDir && AGENT_ROOT_WRITE_ALLOWLIST.has(path.basename(targetPath))) {
@@ -1,4 +1,4 @@
1
- import { mkdir } from 'node:fs/promises'
1
+ import { mkdir, readFile } from 'node:fs/promises'
2
2
  import { dirname } from 'node:path'
3
3
 
4
4
  import { z } from 'zod'
@@ -28,11 +28,13 @@ export type OriginProvider = () => SessionOrigin | undefined
28
28
  // is already on disk by append time). Lets the append tool strip hallucinated
29
29
  // slugs the model invents without ever calling `store_reference`.
30
30
  export type ReferenceSlugResolver = (agentDir: string) => Promise<Iterable<string>>
31
+ export type TranscriptPathProvider = () => string | undefined
31
32
 
32
33
  export type CreateAppendToolOptions = {
33
34
  onFragmentsAppended?: FragmentsAppendedHook
34
35
  originProvider?: OriginProvider
35
36
  referenceSlugResolver?: ReferenceSlugResolver
37
+ transcriptPathProvider?: TranscriptPathProvider
36
38
  }
37
39
 
38
40
  // Stamped fields are the stable channel coordinates only. Author identity is
@@ -64,7 +66,7 @@ export function provenanceFromOrigin(origin: SessionOrigin | undefined): Fragmen
64
66
  }
65
67
 
66
68
  export function createAppendTool(options: CreateAppendToolOptions = {}) {
67
- const { onFragmentsAppended, originProvider, referenceSlugResolver } = options
69
+ const { onFragmentsAppended, originProvider, referenceSlugResolver, transcriptPathProvider } = options
68
70
  return defineTool({
69
71
  description:
70
72
  "Append a memory fragment to today's JSONL daily stream and advance the watermark. The runtime serializes your call into a JSON line and chooses the filename — do not emit raw JSON and do not pass a path. `topic`/`body` are the fragment's substance; `source` is the parent session id; `entry` is the transcript-entry-id this fragment anchors to; `latestEntryId` is the latest transcript-entry-id you evaluated in this run (advances the watermark, may equal `entry` or be later). `references` may ONLY contain slugs returned by `store_reference` (it returns the slug it wrote) — never topic ids, PR names, stream paths, or invented labels; unknown slugs are dropped. `who` is the display name/handle of the person the fragment's evidence is attributable to — set it ONLY when one transcript speaker clearly owns the evidence; omit it when the fact is the user's own, spans multiple speakers, or is not attributable. The channel/room/platform (`where`) is stamped automatically from the session origin — do not pass it and do not restate it in the body. Refuses content with recognized credential patterns and refuses byte-equivalent topic+body within the same daily stream.",
@@ -87,6 +89,16 @@ export function createAppendTool(options: CreateAppendToolOptions = {}) {
87
89
  async execute({ topic, body, source, entry, latestEntryId, references, who }, ctx) {
88
90
  const streamPath = dailyStreamPath(ctx.agentDir)
89
91
  const where = provenanceFromOrigin(originProvider?.())
92
+ const transcriptPath = transcriptPathProvider?.()
93
+ if (
94
+ transcriptPath !== undefined &&
95
+ (await anchorBelongsToOperationalIncident(transcriptPath, entry, latestEntryId))
96
+ ) {
97
+ throw new Error(
98
+ 'Refusing to append: the transcript anchor belongs to a deterministic operational incident sequence. ' +
99
+ 'Operational defects are owned by the incident ledger, not semantic memory.',
100
+ )
101
+ }
90
102
  // `who` is LLM-supplied and force-committed to memory, so it clears the
91
103
  // same secret guard as topic/body — a token-shaped display name is refused
92
104
  // with the same retryable error. (`where` names are origin-derived and the
@@ -155,6 +167,67 @@ export function createAppendTool(options: CreateAppendToolOptions = {}) {
155
167
  })
156
168
  }
157
169
 
170
+ const OPERATIONAL_INCIDENT_MARKER = 'TYPECLAW_OPERATIONAL_INCIDENT '
171
+
172
+ export async function anchorBelongsToOperationalIncident(
173
+ transcriptPath: string,
174
+ entryId: string,
175
+ latestEntryId = entryId,
176
+ ): Promise<boolean> {
177
+ let raw: string
178
+ try {
179
+ raw = await readFile(transcriptPath, 'utf8')
180
+ } catch {
181
+ return false
182
+ }
183
+ const entries = raw
184
+ .split('\n')
185
+ .filter((line) => line.length > 0)
186
+ .flatMap((line): unknown[] => {
187
+ try {
188
+ return [JSON.parse(line) as unknown]
189
+ } catch {
190
+ return []
191
+ }
192
+ })
193
+ const anchorIndex = entries.findIndex((entry) => entryIdOf(entry) === entryId)
194
+ const latestIndex = entries.findIndex((entry) => entryIdOf(entry) === latestEntryId)
195
+ if (anchorIndex < 0 || latestIndex < anchorIndex) return false
196
+
197
+ for (let i = anchorIndex; i <= latestIndex; i++) {
198
+ if (entryBelongsToOperationalIncident(entries, i)) return true
199
+ }
200
+ return false
201
+ }
202
+
203
+ function entryBelongsToOperationalIncident(entries: unknown[], entryIndex: number): boolean {
204
+ if (containsIncidentMarker(entries[entryIndex])) return true
205
+ for (let i = entryIndex - 1; i >= 0; i--) {
206
+ const entry = entries[i]
207
+ if (containsIncidentMarker(entry)) return true
208
+ if (messageRole(entry) === 'user') return false
209
+ }
210
+ return false
211
+ }
212
+
213
+ function entryIdOf(entry: unknown): string | undefined {
214
+ if (typeof entry !== 'object' || entry === null) return undefined
215
+ const id = (entry as { id?: unknown }).id
216
+ return typeof id === 'string' ? id : undefined
217
+ }
218
+
219
+ function messageRole(entry: unknown): string | undefined {
220
+ if (typeof entry !== 'object' || entry === null) return undefined
221
+ const message = (entry as { message?: unknown }).message
222
+ if (typeof message !== 'object' || message === null) return undefined
223
+ const role = (message as { role?: unknown }).role
224
+ return typeof role === 'string' ? role : undefined
225
+ }
226
+
227
+ function containsIncidentMarker(entry: unknown): boolean {
228
+ return JSON.stringify(entry).includes(OPERATIONAL_INCIDENT_MARKER)
229
+ }
230
+
158
231
  export const appendTool = createAppendTool()
159
232
 
160
233
  export const advanceWatermarkTool = defineTool({
@@ -1,11 +1,14 @@
1
1
  export type ShardFrontmatter = {
2
2
  heading: string
3
+ kind?: ShardKind
3
4
  cites: number
4
5
  days: number
5
6
  lastReinforced: string
6
7
  tags?: string[]
7
8
  }
8
9
 
10
+ export type ShardKind = 'belief' | 'procedure' | 'environmental-incident'
11
+
9
12
  const DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/
10
13
 
11
14
  export function parseShard(text: string): { frontmatter: ShardFrontmatter; body: string } {
@@ -111,7 +114,8 @@ function parseFrontmatterBlock(text: string): ShardFrontmatter {
111
114
  throw new Error(`frontmatter field 'lastReinforced': expected YYYY-MM-DD, got '${values.lastReinforced}'`)
112
115
  }
113
116
 
114
- const result: ShardFrontmatter = { heading, cites, days, lastReinforced }
117
+ const kind = values.kind ?? 'belief'
118
+ const result: ShardFrontmatter = { heading, kind: kind as ShardKind, cites, days, lastReinforced }
115
119
  if ('tags' in values) {
116
120
  result.tags = values.tags as string[]
117
121
  }
@@ -120,9 +124,15 @@ function parseFrontmatterBlock(text: string): ShardFrontmatter {
120
124
  }
121
125
 
122
126
  const FRONTMATTER_PARSERS: {
123
- [K in keyof Omit<ShardFrontmatter, 'tags'>]: (value: string) => unknown
127
+ [K in keyof Required<Omit<ShardFrontmatter, 'tags'>>]: (value: string) => unknown
124
128
  } = {
125
129
  heading: (v) => v,
130
+ kind: (v) => {
131
+ if (v !== 'belief' && v !== 'procedure' && v !== 'environmental-incident') {
132
+ throw new Error(`expected belief, procedure, or environmental-incident, got '${v}'`)
133
+ }
134
+ return v
135
+ },
126
136
  cites: parseNonNegativeInt,
127
137
  days: parseNonNegativeInt,
128
138
  lastReinforced: (v) => v,
@@ -140,6 +150,7 @@ function parseNonNegativeInt(value: string): number {
140
150
  export function renderShard(frontmatter: ShardFrontmatter, body: string): string {
141
151
  const lines = ['---']
142
152
  lines.push(`heading: ${frontmatter.heading}`)
153
+ if (frontmatter.kind !== undefined && frontmatter.kind !== 'belief') lines.push(`kind: ${frontmatter.kind}`)
143
154
  lines.push(`cites: ${frontmatter.cites}`)
144
155
  lines.push(`days: ${frontmatter.days}`)
145
156
  lines.push(`lastReinforced: ${frontmatter.lastReinforced}`)
@@ -50,7 +50,7 @@ export async function loadMemoryInjectionPlan(
50
50
  if (rootMemory.content !== null && !hasTopicsDir) {
51
51
  return buildInjectionPlan([rootFallbackEntry(rootMemory)], { budgetBytes: options.injectionBudgetBytes })
52
52
  }
53
- const shards = await loadAllShards(agentDir)
53
+ const shards = (await loadAllShards(agentDir)).filter((shard) => shard.frontmatter.kind !== 'environmental-incident')
54
54
  return buildInjectionPlan(shards, { budgetBytes: options.injectionBudgetBytes })
55
55
  }
56
56
 
@@ -68,7 +68,7 @@ export function isMemoryLoggerPayload(value: unknown): value is MemoryLoggerPayl
68
68
 
69
69
  export const MEMORY_LOGGER_SYSTEM_PROMPT = `You are typeclaw's memory-extraction subagent.
70
70
 
71
- Read the parent session transcript past the watermark and write zero or more durable memory fragments to today's stream, then exit. Capture only operational facts a future agent would concretely need: explicit user instructions, stable identity/role/tool facts, decisions with reasoning, reproducible workarounds, corrections, changed minds, and content the user explicitly taught the agent or asked it to remember. Most runs produce zero or one fragment; that is expected.
71
+ Read the parent session transcript past the watermark and write zero or more durable memory fragments to today's stream, then exit. Capture only facts a future agent would concretely need: explicit user instructions, stable identity/role/tool facts, decisions with reasoning, reproducible user-domain procedures, corrections, changed minds, and content the user explicitly taught the agent or asked it to remember. Most runs produce zero or one fragment; that is expected.
72
72
 
73
73
  A separate \`dreaming\` subagent later consolidates fragments into \`memory/topics/\`, dedupes across days, resolves contradictions, and decides what generalizes. **Dreaming is downstream consolidation, not permission to over-capture upstream.** You do not read \`memory/topics/\`; cross-shard reasoning is dreaming's job. Your inputs are the transcript past the watermark and, optionally, today's daily stream for local dedup. Recurrence across days is useful evidence for dreaming, so a repeated durable fact anchored to new evidence is not a duplicate.
74
74
 
@@ -118,6 +118,7 @@ Capture-worthy categories:
118
118
  - **Stable collaborator/contact facts.** Durable facts about non-user people the agent is likely to encounter again: name/handle, active-participant status in this context, role, responsibility, project relationship, durable working preference, or coordination/contact context. When a person actively participates in the conversation — recurring presence, multiple messages, or a back-and-forth exchange, not a single drive-by line — capture one compact identity fragment recording who they are (name/handle) and that they are an active participant here, even if they did not state a durable role or preference. A stated role/preference strengthens the fragment but is no longer required. A name appearing inside active back-and-forth can be a capture signal; a name merely mentioned in passing by someone else, especially an absent third party, is not. Keep one introduction to one compact fragment that bundles the person's core durable context (e.g. "Alex is an active participant in this project chat" or "Alex is the frontend lead for Project X and prefers GitHub issues over Slack for bug triage"), never a separate fragment per attribute. True single drive-by participants still do not earn memory. Third-party facts must come from the user/owner, or from that person describing their own role/preference in normal collaboration; do not persist one participant's reputational claims about another unless the user confirms or operationally relies on them.
119
119
  - **Decisions with reasoning.** "We chose X over Y because Z" when future sessions must honor X.
120
120
  - **Reproducible workarounds and debugging insights.** A config that worked, flag combination, procedure, root cause, or non-obvious fix.
121
+ - **Deterministic operational incidents are excluded.** A transcript tool result containing \`TYPECLAW_OPERATIONAL_INCIDENT\` and the immediately following user correction/workaround belong to TypeClaw's incident ledger. Skip the whole failure → response → correction sequence. Do not turn an environment repair into a belief or procedure, even when it recurs; the append tool mechanically rejects incident-owned anchors.
121
122
  - **In-transcript changed minds.** Capture "actually, scratch that" only when the prior position is explicit. Do not compare against \`memory/topics/\`.
122
123
  - **Corrections the user made to the agent.** Especially when the agent confidently asserted something false that future sessions may repeat. When the agent stated a factual claim and the user corrected it, capture the corrected fact as a distinct, evidence-anchored fragment EVEN IF it sounds like something memory may already know — you cannot inspect \`memory/topics/\`, so your job is to preserve this later correction occurrence so dreaming can reinforce and sharpen the stored belief (repeated corrections are how a contested fact gets stronger, not noise to skip). Anchor the body to the correction: what the agent said, what the user corrected it to. This is semantic and **language-independent** — recognize corrections in any language (Korean, Japanese, Chinese, Arabic, and every Latin-script language), not from English cue phrases.
123
124
  - **Content the user explicitly taught, trained on, or asked the agent to remember.** Capture the substance taught, not merely that teaching happened. Treat these six intent families as representative, not exhaustive:
@@ -304,10 +305,12 @@ export function createMemoryLoggerSubagent(
304
305
  // The handler runs one logger spawn at a time per agentDir (inFlightKey), so a
305
306
  // single mutable cell safely carries this spawn's origin to the append tool.
306
307
  let currentOrigin: SessionOrigin | undefined
308
+ let currentTranscriptPath: string | undefined
307
309
  const appendTool = createAppendTool({
308
310
  onFragmentsAppended: options.onFragmentsAppended,
309
311
  originProvider: () => currentOrigin,
310
312
  referenceSlugResolver: (agentDir) => listReferenceSlugs(agentDir),
313
+ transcriptPathProvider: () => currentTranscriptPath,
311
314
  })
312
315
  const storeReferenceTool = createStoreReferenceTool(options.onReferenceStored)
313
316
  const customTools = [findEntryTool, appendTool, storeReferenceTool, advanceWatermarkTool]
@@ -340,6 +343,7 @@ export function createMemoryLoggerSubagent(
340
343
  },
341
344
  handler: async (ctx, runSession) => {
342
345
  currentOrigin = ctx.payload.origin
346
+ currentTranscriptPath = ctx.payload.parentTranscriptPath
343
347
  const today = formatLocalDate()
344
348
  const memoryDir = streamsDir(ctx.payload.agentDir)
345
349
  const streamFile = streamFilePath(ctx.payload.agentDir, today)
@@ -29,6 +29,7 @@ export const SECRET_RULES: readonly SecretRule[] = [
29
29
  { name: 'google-api-key', pattern: /\bAIza[0-9A-Za-z_-]{35}\b/ },
30
30
  { name: 'stripe-secret', pattern: /\bsk_live_[0-9A-Za-z]{24,}\b/ },
31
31
  { name: 'stripe-restricted', pattern: /\brk_live_[0-9A-Za-z]{24,}\b/ },
32
+ { name: 'jwt', pattern: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/ },
32
33
  { name: 'rsa-private-key', pattern: /-----BEGIN (?:RSA |OPENSSH |EC |DSA |PGP )?PRIVATE KEY-----/ },
33
34
  ]
34
35
 
@@ -47,3 +48,9 @@ export function detectSecrets(content: string): SecretMatch[] {
47
48
  }
48
49
  return matches
49
50
  }
51
+
52
+ export function isSecretShapedToken(token: string): boolean {
53
+ if (detectSecrets(token).length > 0) return true
54
+ if (/^[A-Fa-f0-9]{48,}$/.test(token)) return true
55
+ return /^[A-Za-z0-9_+-]{48,}$/.test(token)
56
+ }
@@ -94,7 +94,9 @@ export async function hybridSearch(
94
94
  })
95
95
  return events.length === 0 ? [] : [{ ...day, events }]
96
96
  })
97
- const eligibleShards = shards.filter((shard) => provenanceIndex.topicEligible(shard.slug, scope))
97
+ const eligibleShards = shards.filter(
98
+ (shard) => shard.frontmatter.kind !== 'environmental-incident' && provenanceIndex.topicEligible(shard.slug, scope),
99
+ )
98
100
  const eligibleReferences = scoped ? [] : references
99
101
 
100
102
  const { supersededFragmentIds } = buildParentLinks(shards)
@@ -72,7 +72,11 @@ export function findMissingPassages(store: VectorStore, passages: Passage[]): Pa
72
72
  function buildPassages(shards: TopicShard[], streamDays: UndreamedStreamDay[]): Passage[] {
73
73
  const { supersededFragmentIds } = buildParentLinks(shards)
74
74
  return [
75
- ...shards.map((shard): Passage => topicPassage(shard.slug, shard.frontmatter.heading, shard.body)),
75
+ ...shards.flatMap((shard): Passage[] =>
76
+ shard.frontmatter.kind === 'environmental-incident'
77
+ ? []
78
+ : [topicPassage(shard.slug, shard.frontmatter.heading, shard.body)],
79
+ ),
76
80
  ...streamDays.flatMap((day) =>
77
81
  day.events.flatMap((event): Passage[] => {
78
82
  if (event.type === 'watermark') return []
@@ -1,4 +1,4 @@
1
- import { definePlugin } from '@/plugin'
1
+ import { definePlugin, type PluginLogger } from '@/plugin'
2
2
  import { resolveHiddenPaths } from '@/sandbox'
3
3
 
4
4
  import { HIGH_TIER_PER_GUARD_PERMISSIONS, SECURITY_PERMISSIONS, SEVERITY_PERMISSION } from './permissions'
@@ -87,6 +87,15 @@ function withPermissionHint(
87
87
  }
88
88
  }
89
89
 
90
+ const INTERNAL_SECURITY_GUARD_REASON =
91
+ 'The tool call was blocked because an internal security guard error prevented safe evaluation.'
92
+
93
+ function reportInternalGuardError(logger: PluginLogger, guard: string, error: unknown): void {
94
+ const detail = error instanceof Error ? (error.stack ?? error.message) : String(error)
95
+ const code = error instanceof Error && 'code' in error && typeof error.code === 'string' ? ` code=${error.code}` : ''
96
+ logger.error(`internal security guard error guard=${guard}${code}: ${detail}`)
97
+ }
98
+
90
99
  export default definePlugin({
91
100
  permissions: Object.values(SECURITY_PERMISSIONS),
92
101
  // No wildcard exclusions: owner bypasses every security tier by default
@@ -102,148 +111,189 @@ export default definePlugin({
102
111
  applyPromptInjectionDefense(event)
103
112
  },
104
113
  'tool.before': async (event) => {
105
- const can = (perm: string) => ctx.permissions.has(event.origin, perm)
106
- const canBypass = (severity: SecuritySeverity, perGuardPerm: string): boolean =>
107
- can(SEVERITY_PERMISSION[severity]) || can(perGuardPerm)
108
-
109
- // The cron guard blocks deferred work that fires as a role granting
110
- // permissions the caller lacks. Capability dominance — target's
111
- // permission set must be a SUBSET of the caller's — not the coarse
112
- // `compareRoleSeverity` tower: every configured custom role ranks
113
- // equal there, so rank `>= 0` would let one custom role schedule as a
114
- // different custom role (or `trusted` schedule as a custom role with
115
- // an extra grant), laundering permissions the caller never had. Unknown
116
- // caller/target role => undefined permissions => fail closed.
117
- const callerRole = ctx.permissions.resolveRole(event.origin)
118
- const canScheduleAs = (targetRole: string | undefined): boolean => {
119
- if (targetRole === undefined) return false
120
- const callerPermissions = ctx.permissions.permissionsForRole(callerRole)
121
- const targetPermissions = ctx.permissions.permissionsForRole(targetRole)
122
- if (callerPermissions === undefined || targetPermissions === undefined) return false
123
- const callerSet = new Set(callerPermissions)
124
- return targetPermissions.every((permission) => callerSet.has(permission))
125
- }
114
+ try {
115
+ const can = (perm: string) => ctx.permissions.has(event.origin, perm)
116
+ const canBypass = (severity: SecuritySeverity, perGuardPerm: string): boolean =>
117
+ can(SEVERITY_PERMISSION[severity]) || can(perGuardPerm)
118
+
119
+ // The cron guard blocks deferred work that fires as a role granting
120
+ // permissions the caller lacks. Capability dominance — target's
121
+ // permission set must be a SUBSET of the caller's — not the coarse
122
+ // `compareRoleSeverity` tower: every configured custom role ranks
123
+ // equal there, so rank `>= 0` would let one custom role schedule as a
124
+ // different custom role (or `trusted` schedule as a custom role with
125
+ // an extra grant), laundering permissions the caller never had. Unknown
126
+ // caller/target role => undefined permissions => fail closed.
127
+ const callerRole = ctx.permissions.resolveRole(event.origin)
128
+ const canScheduleAs = (targetRole: string | undefined): boolean => {
129
+ if (targetRole === undefined) return false
130
+ const callerPermissions = ctx.permissions.permissionsForRole(callerRole)
131
+ const targetPermissions = ctx.permissions.permissionsForRole(targetRole)
132
+ if (callerPermissions === undefined || targetPermissions === undefined) return false
133
+ const callerSet = new Set(callerPermissions)
134
+ return targetPermissions.every((permission) => callerSet.has(permission))
135
+ }
136
+
137
+ const rolePromotionResult = canBypass(GUARD_ROLE_PROMOTION_SEVERITY, SECURITY_PERMISSIONS.bypassRolePromotion)
138
+ ? undefined
139
+ : withPermissionHint(
140
+ await checkRolePromotionGuard({ tool: event.tool, args: event.args, agentDir: ctx.agentDir }),
141
+ SECURITY_PERMISSIONS.bypassRolePromotion,
142
+ GUARD_ROLE_PROMOTION_SEVERITY,
143
+ )
144
+ if (rolePromotionResult) return rolePromotionResult
145
+
146
+ const cronPromotionResult = canBypass(GUARD_CRON_PROMOTION_SEVERITY, SECURITY_PERMISSIONS.bypassCronPromotion)
147
+ ? undefined
148
+ : withPermissionHint(
149
+ await checkCronPromotionGuard({
150
+ tool: event.tool,
151
+ args: event.args,
152
+ agentDir: ctx.agentDir,
153
+ canScheduleAs,
154
+ }),
155
+ SECURITY_PERMISSIONS.bypassCronPromotion,
156
+ GUARD_CRON_PROMOTION_SEVERITY,
157
+ )
158
+ if (cronPromotionResult) return cronPromotionResult
159
+
160
+ const pluginAdditionResult = canBypass(
161
+ GUARD_PLUGIN_ADDITION_SEVERITY,
162
+ SECURITY_PERMISSIONS.bypassPluginAddition,
163
+ )
164
+ ? undefined
165
+ : withPermissionHint(
166
+ await checkPluginAdditionGuard({ tool: event.tool, args: event.args, agentDir: ctx.agentDir }),
167
+ SECURITY_PERMISSIONS.bypassPluginAddition,
168
+ GUARD_PLUGIN_ADDITION_SEVERITY,
169
+ )
170
+ if (pluginAdditionResult) return pluginAdditionResult
126
171
 
127
- const rolePromotionResult = canBypass(GUARD_ROLE_PROMOTION_SEVERITY, SECURITY_PERMISSIONS.bypassRolePromotion)
128
- ? undefined
129
- : withPermissionHint(
130
- await checkRolePromotionGuard({ tool: event.tool, args: event.args, agentDir: ctx.agentDir }),
131
- SECURITY_PERMISSIONS.bypassRolePromotion,
132
- GUARD_ROLE_PROMOTION_SEVERITY,
133
- )
134
- if (rolePromotionResult) return rolePromotionResult
135
-
136
- const cronPromotionResult = canBypass(GUARD_CRON_PROMOTION_SEVERITY, SECURITY_PERMISSIONS.bypassCronPromotion)
137
- ? undefined
138
- : withPermissionHint(
139
- await checkCronPromotionGuard({
140
- tool: event.tool,
141
- args: event.args,
142
- agentDir: ctx.agentDir,
143
- canScheduleAs,
144
- }),
145
- SECURITY_PERMISSIONS.bypassCronPromotion,
146
- GUARD_CRON_PROMOTION_SEVERITY,
147
- )
148
- if (cronPromotionResult) return cronPromotionResult
149
-
150
- const pluginAdditionResult = canBypass(
151
- GUARD_PLUGIN_ADDITION_SEVERITY,
152
- SECURITY_PERMISSIONS.bypassPluginAddition,
153
- )
154
- ? undefined
155
- : withPermissionHint(
156
- await checkPluginAdditionGuard({ tool: event.tool, args: event.args, agentDir: ctx.agentDir }),
157
- SECURITY_PERMISSIONS.bypassPluginAddition,
158
- GUARD_PLUGIN_ADDITION_SEVERITY,
159
- )
160
- if (pluginAdditionResult) return pluginAdditionResult
161
-
162
- // Taint-recording runs FIRST, independently of the gitExfil guard.
163
- // The gitRemoteTainted defense depends on it. We pass through
164
- // `permittedBypass` for actors who can skip gitExfil (via either the
165
- // per-guard permission or the medium-tier permission) so the
166
- // recorder still fires for them — an acked or permission-bypassed
167
- // command will actually run, so its remote change must be remembered.
168
- recordGitRemoteTaintIfAny({
169
- tool: event.tool,
170
- args: event.args,
171
- sessionId: event.sessionId,
172
- permittedBypass: canBypass(GUARD_GIT_EXFIL_SEVERITY, SECURITY_PERMISSIONS.bypassGitExfil),
173
- })
174
-
175
- const checks: (SecurityBlock | undefined)[] = [
176
- canBypass(GUARD_GIT_REMOTE_TAINTED_SEVERITY, SECURITY_PERMISSIONS.bypassGitRemoteTainted)
172
+ // Taint-recording runs FIRST, independently of the gitExfil guard.
173
+ // The gitRemoteTainted defense depends on it. We pass through
174
+ // `permittedBypass` for actors who can skip gitExfil (via either the
175
+ // per-guard permission or the medium-tier permission) so the
176
+ // recorder still fires for them — an acked or permission-bypassed
177
+ // command will actually run, so its remote change must be remembered.
178
+ recordGitRemoteTaintIfAny({
179
+ tool: event.tool,
180
+ args: event.args,
181
+ sessionId: event.sessionId,
182
+ permittedBypass: canBypass(GUARD_GIT_EXFIL_SEVERITY, SECURITY_PERMISSIONS.bypassGitExfil),
183
+ })
184
+
185
+ const gitRemoteTaintedResult = canBypass(
186
+ GUARD_GIT_REMOTE_TAINTED_SEVERITY,
187
+ SECURITY_PERMISSIONS.bypassGitRemoteTainted,
188
+ )
177
189
  ? undefined
178
190
  : withPermissionHint(
179
191
  checkGitRemoteTaintedGuard({ tool: event.tool, args: event.args, sessionId: event.sessionId }),
180
192
  SECURITY_PERMISSIONS.bypassGitRemoteTainted,
181
193
  GUARD_GIT_REMOTE_TAINTED_SEVERITY,
182
- ),
183
- canBypass(GUARD_SECRET_EXFIL_BASH_SEVERITY, SECURITY_PERMISSIONS.bypassSecretExfilBash)
194
+ )
195
+ if (gitRemoteTaintedResult) return gitRemoteTaintedResult
196
+
197
+ const secretExfilBashResult = canBypass(
198
+ GUARD_SECRET_EXFIL_BASH_SEVERITY,
199
+ SECURITY_PERMISSIONS.bypassSecretExfilBash,
200
+ )
184
201
  ? undefined
185
202
  : withPermissionHint(
186
203
  checkSecretExfilBashGuard({ tool: event.tool, args: event.args }),
187
204
  SECURITY_PERMISSIONS.bypassSecretExfilBash,
188
205
  GUARD_SECRET_EXFIL_BASH_SEVERITY,
189
- ),
190
- canBypass(GUARD_GIT_EXFIL_SEVERITY, SECURITY_PERMISSIONS.bypassGitExfil)
206
+ )
207
+ if (secretExfilBashResult) return secretExfilBashResult
208
+
209
+ const gitExfilResult = canBypass(GUARD_GIT_EXFIL_SEVERITY, SECURITY_PERMISSIONS.bypassGitExfil)
191
210
  ? undefined
192
211
  : withPermissionHint(
193
212
  checkGitExfilGuard({ tool: event.tool, args: event.args, sessionId: event.sessionId }),
194
213
  SECURITY_PERMISSIONS.bypassGitExfil,
195
214
  GUARD_GIT_EXFIL_SEVERITY,
196
- ),
197
- canBypass(GUARD_SECRET_EXFIL_READ_SEVERITY, SECURITY_PERMISSIONS.bypassSecretExfilRead)
215
+ )
216
+ if (gitExfilResult) return gitExfilResult
217
+
218
+ const secretExfilReadResult = canBypass(
219
+ GUARD_SECRET_EXFIL_READ_SEVERITY,
220
+ SECURITY_PERMISSIONS.bypassSecretExfilRead,
221
+ )
198
222
  ? undefined
199
223
  : withPermissionHint(
200
224
  checkSecretExfilReadGuard({ tool: event.tool, args: event.args }),
201
225
  SECURITY_PERMISSIONS.bypassSecretExfilRead,
202
226
  GUARD_SECRET_EXFIL_READ_SEVERITY,
203
- ),
227
+ )
228
+ if (secretExfilReadResult) return secretExfilReadResult
229
+
204
230
  // Not severity-bypassed: private directories remain role-derived,
205
231
  // while canonical credential-store denial is unconditional. Mirrors
206
232
  // the bash masks onto every non-bash path-bearing tool.
207
- checkPrivateSurfaceReadGuard({
208
- tool: event.tool,
209
- args: event.args,
210
- agentDir: ctx.agentDir,
211
- hidden: resolveHiddenPaths(ctx.permissions, event.origin, ctx.agentDir),
212
- ...(event.fileOperands !== undefined ? { fileOperands: event.fileOperands } : {}),
213
- }),
214
- canBypass(GUARD_SSRF_SEVERITY, SECURITY_PERMISSIONS.bypassSsrf)
233
+ const privateSurfaceReadResult = checkPrivateSurfaceReadGuard(
234
+ {
235
+ tool: event.tool,
236
+ args: event.args,
237
+ agentDir: ctx.agentDir,
238
+ hidden: resolveHiddenPaths(ctx.permissions, event.origin, ctx.agentDir),
239
+ ...(event.fileOperands !== undefined ? { fileOperands: event.fileOperands } : {}),
240
+ },
241
+ {
242
+ onInternalError: (error) => reportInternalGuardError(ctx.logger, 'privateSurfaceRead', error),
243
+ },
244
+ )
245
+ if (privateSurfaceReadResult) return privateSurfaceReadResult
246
+
247
+ const ssrfResult = canBypass(GUARD_SSRF_SEVERITY, SECURITY_PERMISSIONS.bypassSsrf)
215
248
  ? undefined
216
249
  : withPermissionHint(
217
250
  checkSsrfGuard({ tool: event.tool, args: event.args }),
218
251
  SECURITY_PERMISSIONS.bypassSsrf,
219
252
  GUARD_SSRF_SEVERITY,
220
- ),
221
- canBypass(GUARD_SESSION_SEARCH_SECRETS_SEVERITY, SECURITY_PERMISSIONS.bypassSessionSearchSecrets)
253
+ )
254
+ if (ssrfResult) return ssrfResult
255
+
256
+ const sessionSearchSecretsResult = canBypass(
257
+ GUARD_SESSION_SEARCH_SECRETS_SEVERITY,
258
+ SECURITY_PERMISSIONS.bypassSessionSearchSecrets,
259
+ )
222
260
  ? undefined
223
261
  : withPermissionHint(
224
262
  checkSessionSearchSecretsGuard({ tool: event.tool, args: event.args }),
225
263
  SECURITY_PERMISSIONS.bypassSessionSearchSecrets,
226
264
  GUARD_SESSION_SEARCH_SECRETS_SEVERITY,
227
- ),
228
- canBypass(GUARD_SYSTEM_PROMPT_LEAK_SEVERITY, SECURITY_PERMISSIONS.bypassSystemPromptLeak)
265
+ )
266
+ if (sessionSearchSecretsResult) return sessionSearchSecretsResult
267
+
268
+ const systemPromptLeakResult = canBypass(
269
+ GUARD_SYSTEM_PROMPT_LEAK_SEVERITY,
270
+ SECURITY_PERMISSIONS.bypassSystemPromptLeak,
271
+ )
229
272
  ? undefined
230
273
  : withPermissionHint(
231
274
  checkSystemPromptLeakGuard({ tool: event.tool, args: event.args }),
232
275
  SECURITY_PERMISSIONS.bypassSystemPromptLeak,
233
276
  GUARD_SYSTEM_PROMPT_LEAK_SEVERITY,
234
- ),
235
- canBypass(GUARD_OUTBOUND_SECRET_SEVERITY, SECURITY_PERMISSIONS.bypassOutboundSecret)
277
+ )
278
+ if (systemPromptLeakResult) return systemPromptLeakResult
279
+
280
+ const outboundSecretResult = canBypass(
281
+ GUARD_OUTBOUND_SECRET_SEVERITY,
282
+ SECURITY_PERMISSIONS.bypassOutboundSecret,
283
+ )
236
284
  ? undefined
237
285
  : withPermissionHint(
238
286
  checkOutboundSecretGuard({ tool: event.tool, args: event.args }),
239
287
  SECURITY_PERMISSIONS.bypassOutboundSecret,
240
288
  GUARD_OUTBOUND_SECRET_SEVERITY,
241
- ),
242
- ]
243
- for (const result of checks) {
244
- if (result) return result
289
+ )
290
+ if (outboundSecretResult) return outboundSecretResult
291
+
292
+ return undefined
293
+ } catch (error) {
294
+ reportInternalGuardError(ctx.logger, 'tool.before', error)
295
+ return { block: true, reason: INTERNAL_SECURITY_GUARD_REASON }
245
296
  }
246
- return undefined
247
297
  },
248
298
  'session.end': async (event) => {
249
299
  clearSessionTaints(event.sessionId)