typeclaw 0.48.1 → 0.48.3

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 (39) hide show
  1. package/package.json +1 -1
  2. package/src/agent/index.ts +35 -9
  3. package/src/agent/plugin-tools.ts +14 -0
  4. package/src/agent/system-prompt.ts +8 -0
  5. package/src/agent/todo/continuation-policy.ts +11 -1
  6. package/src/agent/todo/continuation-state.ts +3 -1
  7. package/src/agent/todo/continuation-wiring.ts +2 -0
  8. package/src/agent/tool-file-safety.ts +7 -1
  9. package/src/agent/tools/channel-reply.ts +18 -1
  10. package/src/bundled-plugins/guard/policies/managed-config.ts +7 -20
  11. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +7 -20
  12. package/src/bundled-plugins/guard/policies/skill-authoring.ts +8 -20
  13. package/src/bundled-plugins/memory/README.md +2 -0
  14. package/src/bundled-plugins/memory/dreaming.ts +2 -0
  15. package/src/bundled-plugins/security/policies/private-surface-read.ts +98 -55
  16. package/src/channels/adapters/discord-bot-reactions.ts +1 -0
  17. package/src/channels/adapters/discord-bot.ts +11 -2
  18. package/src/channels/adapters/discord-reactions.ts +1 -0
  19. package/src/channels/adapters/discord.ts +1 -0
  20. package/src/channels/adapters/slack-bot.ts +11 -2
  21. package/src/channels/adapters/slack.ts +1 -0
  22. package/src/channels/completion-claim.ts +307 -0
  23. package/src/channels/router.ts +275 -55
  24. package/src/channels/types.ts +4 -1
  25. package/src/config/providers.ts +100 -20
  26. package/src/container/start.ts +42 -0
  27. package/src/init/models-dev.ts +25 -8
  28. package/src/mcp/client.ts +65 -7
  29. package/src/mcp/tools.ts +71 -4
  30. package/src/path-safety/real-intended-path.ts +111 -0
  31. package/src/permissions/index.ts +1 -0
  32. package/src/permissions/permissions.ts +23 -0
  33. package/src/plugin/manager.ts +19 -1
  34. package/src/sandbox/canonical-secrets.ts +24 -4
  35. package/src/sandbox/hidden-paths.ts +8 -3
  36. package/src/sandbox/index.ts +2 -0
  37. package/src/skills/typeclaw-permissions/SKILL.md +13 -1
  38. package/src/skills/typeclaw-plugins/SKILL.md +91 -11
  39. package/typeclaw.schema.json +5 -0
@@ -16,13 +16,14 @@ import path from 'node:path'
16
16
  import { fileURLToPath } from 'node:url'
17
17
 
18
18
  import { TOOLS_WITHOUT_LOCAL_FILE_OPERANDS } from '@/agent/tools-without-local-file-operands'
19
+ import { RECOVER_MISSING_OR_UNSEARCHABLE, realIntendedPathSync } from '@/path-safety/real-intended-path'
19
20
  import type { ToolFileOperands } from '@/plugin'
20
21
  import {
21
- CANONICAL_AGENT_SECRET_DIRS,
22
22
  CANONICAL_AGENT_SECRET_FILES,
23
23
  CANONICAL_HOME_SECRET_DIRS,
24
24
  CANONICAL_HOME_SECRET_FILES,
25
25
  CONTAINER_RUNTIME_HOME,
26
+ RUNTIME_OWNED_SECRET_DIRS,
26
27
  type HiddenPaths,
27
28
  } from '@/sandbox'
28
29
 
@@ -82,22 +83,27 @@ export function checkPrivateSurfaceReadGuard(
82
83
  const { tool, args, agentDir, hidden, fileOperands } = options
83
84
  if (UNSCANNED_TOOLS.has(tool)) return undefined
84
85
  try {
85
- const { deniedDirs, deniedFiles } = deniedSurface(agentDir, hidden)
86
- if (deniedDirs.length === 0 && deniedFiles.length === 0) return undefined
87
- const identityScanner = createHardlinkIdentityScanner(agentDir, deniedDirs, deniedFiles, hooks)
86
+ const { canonicalDirs, canonicalFiles, roleDirs, roleFiles } = deniedSurface(agentDir, hidden)
87
+ const canonicalEmpty = canonicalDirs.length === 0 && canonicalFiles.length === 0
88
+ const roleEmpty = roleDirs.length === 0 && roleFiles.length === 0
89
+ if (canonicalEmpty && roleEmpty) return undefined
88
90
  const realpath = hooks.realpathNative ?? realpathSync.native
89
91
 
90
- const nonFile = fileOperands?.nonFile === undefined ? undefined : new Set(fileOperands.nonFile)
91
- for (const candidate of collectPathCandidates(args, tool, nonFile)) {
92
- const hit = matchHidden(candidate, agentDir, deniedDirs, deniedFiles, identityScanner, realpath)
93
- if (hit !== undefined) {
94
- return {
95
- block: true,
96
- reason: [
97
- `Guard \`${GUARD_PRIVATE_SURFACE_READ}\` blocked ${tool}: argument \`${candidate}\` resolves to ${hit}, which is not available to LLM tools.`,
98
- 'The bash sandbox masks the same path. Privileged roles cannot bypass canonical agent credential files; use host-side redacted diagnostics such as `typeclaw doctor`, `typeclaw provider list`, or `typeclaw channel list` instead.',
99
- ].join(' '),
100
- }
92
+ if (!canonicalEmpty) {
93
+ const identityScanner = createHardlinkIdentityScanner(agentDir, canonicalDirs, canonicalFiles, hooks)
94
+ for (const candidate of collectPathCandidates(args, tool, undefined, undefined, true)) {
95
+ const hit = matchHidden(candidate, agentDir, canonicalDirs, canonicalFiles, identityScanner, realpath)
96
+ if (hit !== undefined) return privateSurfacePathBlock(tool, candidate, hit)
97
+ }
98
+ }
99
+
100
+ if (!roleEmpty) {
101
+ const identityScanner = createHardlinkIdentityScanner(agentDir, roleDirs, roleFiles, hooks)
102
+ const nonFile = fileOperands?.nonFile === undefined ? undefined : new Set(fileOperands.nonFile)
103
+ const localOperands = collectLocalOperandPaths(fileOperands)
104
+ for (const candidate of collectPathCandidates(args, tool, nonFile, localOperands, false)) {
105
+ const hit = matchHidden(candidate, agentDir, roleDirs, roleFiles, identityScanner, realpath)
106
+ if (hit !== undefined) return privateSurfacePathBlock(tool, candidate, hit)
101
107
  }
102
108
  }
103
109
  return undefined
@@ -133,7 +139,9 @@ export function createPrivateSurfaceReadIdentityVerifier(
133
139
  options: PrivateSurfaceIdentityOptions,
134
140
  hooks: PrivateSurfaceIdentityScanHooks = {},
135
141
  ): PrivateSurfaceIdentityVerifier {
136
- const { deniedDirs, deniedFiles } = deniedSurface(options.agentDir, options.hidden)
142
+ const { canonicalDirs, canonicalFiles, roleDirs, roleFiles } = deniedSurface(options.agentDir, options.hidden)
143
+ const deniedDirs = [...new Set([...canonicalDirs, ...roleDirs])]
144
+ const deniedFiles = [...new Set([...canonicalFiles, ...roleFiles])]
137
145
  const scanner = createHardlinkIdentityScanner(options.agentDir, deniedDirs, deniedFiles, hooks)
138
146
  return {
139
147
  check(identity) {
@@ -173,12 +181,14 @@ function createHardlinkIdentityScanner(
173
181
  })
174
182
  }
175
183
 
176
- function deniedSurface(agentDir: string, hidden: HiddenPaths): { deniedDirs: string[]; deniedFiles: string[] } {
184
+ function deniedSurface(
185
+ agentDir: string,
186
+ hidden: HiddenPaths,
187
+ ): { canonicalDirs: string[]; canonicalFiles: string[]; roleDirs: string[]; roleFiles: string[] } {
177
188
  return {
178
- deniedDirs: [
189
+ canonicalDirs: [
179
190
  ...new Set([
180
- ...hidden.dirs,
181
- ...CANONICAL_AGENT_SECRET_DIRS.map((dir) => path.join(agentDir, dir)),
191
+ ...RUNTIME_OWNED_SECRET_DIRS.map((dir) => path.join(agentDir, dir)),
182
192
  // homedir() follows the live container HOME; the fixed runtime path
183
193
  // keeps the same denial deterministic in host-stage tests and any
184
194
  // partially-initialized caller whose environment has not switched yet.
@@ -188,14 +198,25 @@ function deniedSurface(agentDir: string, hidden: HiddenPaths): { deniedDirs: str
188
198
  ],
189
199
  // Keep runtime-owned credential stores independent of role-derived
190
200
  // visibility so a partially-wired caller cannot expose raw credentials.
191
- deniedFiles: [
201
+ canonicalFiles: [
192
202
  ...new Set([
193
- ...hidden.files,
194
203
  ...CANONICAL_AGENT_SECRET_FILES.map((file) => path.join(agentDir, file)),
195
204
  ...CANONICAL_HOME_SECRET_FILES.map((file) => path.join(homedir(), file)),
196
205
  ...CANONICAL_HOME_SECRET_FILES.map((file) => path.join(CONTAINER_RUNTIME_HOME, file)),
197
206
  ]),
198
207
  ],
208
+ roleDirs: [...new Set(hidden.dirs)],
209
+ roleFiles: [...new Set(hidden.files)],
210
+ }
211
+ }
212
+
213
+ function privateSurfacePathBlock(tool: string, candidate: string, hit: string): SecurityBlock {
214
+ return {
215
+ block: true,
216
+ reason: [
217
+ `Guard \`${GUARD_PRIVATE_SURFACE_READ}\` blocked ${tool}: argument \`${candidate}\` resolves to ${hit}, which is not available to LLM tools.`,
218
+ 'The bash sandbox masks the same path. Privileged roles cannot bypass canonical agent credential files; use host-side redacted diagnostics such as `typeclaw doctor`, `typeclaw provider list`, or `typeclaw channel list` instead.',
219
+ ].join(' '),
199
220
  }
200
221
  }
201
222
 
@@ -294,11 +315,37 @@ function trimmedFileUri(value: string): string | undefined {
294
315
  // enforcement points agree — an id like `{ tenant: "memory" }` on a tool that
295
316
  // declared `nonFile: ['tenant']` is not blocked here. Scoped by EXACT operand
296
317
  // path (not key name), so an undeclared key still fails closed; `input`/
297
- // `output`/`destructive` are deliberately NOT honored (a declared real-file path
298
- // that resolves under a hidden dir must still block).
299
- function collectPathCandidates(value: unknown, tool: string, nonFile?: ReadonlySet<string>): string[] {
318
+ // `output`/`create`/`destructive` are never exemptions — they FORCE a scan (a
319
+ // declared real-file path that resolves under a hidden dir must still block).
320
+ // `localOperands` holds the declared `input`/`output`/`create`/`destructive`
321
+ // operand PATHS. A string at one of those paths is ALWAYS scanned, overriding
322
+ // both the prose-key exemptions above and any `nonFile` claim on the same path.
323
+ // Without that override the two exemption layers compose into a bypass: a tool
324
+ // declaring a real local operand under a universally-free-text key (`query`,
325
+ // `content`, `text`, `name`, ...) would have its value skipped here as prose,
326
+ // then dereferenced downstream — so `{ input: ['query'], query: 'memory/x' }`
327
+ // would reach a hidden directory the role cannot see. Declaring a path as a
328
+ // local file is exactly the claim that it is NOT prose.
329
+ function collectLocalOperandPaths(operands: ToolFileOperands | undefined): ReadonlySet<string> | undefined {
330
+ if (operands === undefined) return undefined
331
+ const paths = new Set([
332
+ ...(operands.input ?? []),
333
+ ...(operands.output ?? []),
334
+ ...(operands.create ?? []),
335
+ ...(operands.destructive ?? []),
336
+ ])
337
+ return paths.size === 0 ? undefined : paths
338
+ }
339
+
340
+ function collectPathCandidates(
341
+ value: unknown,
342
+ tool: string,
343
+ nonFile?: ReadonlySet<string>,
344
+ localOperands?: ReadonlySet<string>,
345
+ disableExemptions = false,
346
+ ): string[] {
300
347
  const out: string[] = []
301
- walk(value, out, tool, false, nonFile, '')
348
+ walk(value, out, tool, false, nonFile, localOperands, '', disableExemptions)
302
349
  return out
303
350
  }
304
351
 
@@ -308,27 +355,37 @@ function walk(
308
355
  tool: string,
309
356
  underExempt: boolean,
310
357
  nonFile: ReadonlySet<string> | undefined,
358
+ localOperands: ReadonlySet<string> | undefined,
311
359
  operandPath: string,
360
+ disableExemptions: boolean,
312
361
  key?: string,
313
362
  ): void {
314
363
  if (typeof value === 'string') {
315
- if (nonFile?.has(operandPath) === true) return
316
- const isFileUrl = trimmedFileUri(value) !== undefined
317
- if (underExempt && !isPathKey(key) && !isFileUrl) return
364
+ if (!disableExemptions) {
365
+ const declaredLocal = localOperands?.has(operandPath) === true
366
+ if (!declaredLocal) {
367
+ if (nonFile?.has(operandPath) === true) return
368
+ const isFileUrl = trimmedFileUri(value) !== undefined
369
+ if (underExempt && !isPathKey(key) && !isFileUrl) return
370
+ }
371
+ }
318
372
  const normalized = normalizeCandidate(value)
319
373
  if (normalized !== undefined) out.push(normalized)
320
374
  return
321
375
  }
322
376
  if (Array.isArray(value)) {
323
- for (const item of value) walk(item, out, tool, underExempt, nonFile, operandPath, key)
377
+ for (const item of value) {
378
+ walk(item, out, tool, underExempt, nonFile, localOperands, operandPath, disableExemptions, key)
379
+ }
324
380
  return
325
381
  }
326
382
  if (value !== null && typeof value === 'object') {
327
383
  const toolFreeText = FREE_TEXT_KEYS_BY_TOOL[tool]
328
384
  for (const [childKey, item] of Object.entries(value)) {
329
- const keyIsExempt = NON_PATH_KEYS.has(childKey) || (toolFreeText?.has(childKey) ?? false)
385
+ if (disableExemptions && childKey === 'filename' && toolFreeText?.has(childKey) === true) continue
386
+ const keyIsExempt = !disableExemptions && (NON_PATH_KEYS.has(childKey) || (toolFreeText?.has(childKey) ?? false))
330
387
  const childPath = operandPath === '' ? childKey : `${operandPath}.${childKey}`
331
- walk(item, out, tool, underExempt || keyIsExempt, nonFile, childPath, childKey)
388
+ walk(item, out, tool, underExempt || keyIsExempt, nonFile, localOperands, childPath, disableExemptions, childKey)
332
389
  }
333
390
  }
334
391
  }
@@ -959,30 +1016,16 @@ function hasSameFileIdentity(candidate: string, deniedFile: string): boolean {
959
1016
  }
960
1017
  }
961
1018
 
962
- // Resolves symlinks on the longest existing prefix of an absolute path, then
963
- // re-appends the non-existent tail. A bare realpathSync throws on a path that
964
- // does not exist yet (a write target, or a read of a not-yet-created file), so
965
- // we walk up to the nearest existing ancestor, realpath THAT (collapsing any
966
- // symlinked component including a planted symlink), and rejoin the remainder.
967
- // This catches `public/leak/x` where `public/leak` is a symlink into a hidden
968
- // dir even though `public/leak/x` itself does not exist. Sync (realpathSync)
969
- // keeps the guard synchronous; the cost is one syscall per existing component,
970
- // negligible at the tool-call boundary. Sync mirror of resolveRealIntendedPath
971
- // in the guard plugin's non-workspace-write policy.
1019
+ // Sync keeps the guard synchronous; the cost is one syscall per existing
1020
+ // component, negligible at the tool-call boundary. EACCES is recoverable here
1021
+ // (but NOT in the guard plugin's write policies): this is denylist matching, so
1022
+ // a path under an unsearchable ancestor must still be matched rather than
1023
+ // aborting the whole guard. See @/path-safety/real-intended-path.
972
1024
  function realpathRealIntendedPath(absolutePath: string, realpath: (candidate: string) => string): string {
973
- const pending: string[] = []
974
- let current = absolutePath
975
- while (true) {
976
- try {
977
- return path.join(realpath(current), ...pending.reverse())
978
- } catch (err) {
979
- if (!isNotFoundError(err)) throw err
980
- }
981
- const parent = path.dirname(current)
982
- if (parent === current) return absolutePath
983
- pending.push(path.basename(current))
984
- current = parent
985
- }
1025
+ return realIntendedPathSync(absolutePath, realpath, {
1026
+ recoverable: RECOVER_MISSING_OR_UNSEARCHABLE,
1027
+ onExhausted: 'return-input',
1028
+ })
986
1029
  }
987
1030
 
988
1031
  function isNotFoundError(err: unknown): boolean {
@@ -78,6 +78,7 @@ const EMOJI_UNICODE: Record<string, string> = {
78
78
  eye: '👁️',
79
79
  raised_hands: '🙌',
80
80
  zipper_mouth_face: '🤐',
81
+ hourglass_flowing_sand: '⏳',
81
82
  }
82
83
 
83
84
  function resolveEmoji(emoji: string): string | null {
@@ -60,7 +60,11 @@ import {
60
60
  } from './discord-bot-classify'
61
61
  import { createDiscordEditMessageCallback } from './discord-bot-edit'
62
62
  import { convertDiscordTables } from './discord-bot-format'
63
- import { createDiscordReactionCallback, createDiscordRemoveReactionCallback } from './discord-bot-reactions'
63
+ import {
64
+ createDiscordReactionCallback,
65
+ createDiscordRemoveReactionCallback,
66
+ encodeDiscordReactionRef,
67
+ } from './discord-bot-reactions'
64
68
  import { enrichDiscordMessageReferences } from './discord-bot-reference'
65
69
  import {
66
70
  ackInteraction,
@@ -840,7 +844,12 @@ export function createOutboundCallback(deps: {
840
844
  Object.keys(sendOptions).length > 0 ? sendOptions : undefined,
841
845
  )
842
846
  logger.info(`[discord-bot] sent id=${sent.id} ${tag}`)
843
- return { ok: true, messageId: sent.id, messageIds: [sent.id] }
847
+ return {
848
+ ok: true,
849
+ messageId: sent.id,
850
+ messageIds: [sent.id],
851
+ reactionRef: encodeDiscordReactionRef({ channel: msg.chat, message: sent.id }),
852
+ }
844
853
  } catch (err) {
845
854
  const message = describeError(err)
846
855
  logger.error(`[discord-bot] sendMessage failed: ${message}`)
@@ -61,6 +61,7 @@ const EMOJI_UNICODE: Record<string, string> = {
61
61
  eye: '👁️',
62
62
  raised_hands: '🙌',
63
63
  zipper_mouth_face: '🤐',
64
+ hourglass_flowing_sand: '⏳',
64
65
  }
65
66
 
66
67
  function resolveEmoji(emoji: string): string | null {
@@ -108,6 +108,7 @@ export function createDiscordOutboundCallback(deps: {
108
108
  await deps.client.sendMessage(msg.chat, chunk, replyOption(index === 0 ? replyTo : undefined))
109
109
  }
110
110
  }
111
+ // The user-account SDK send APIs return no posted-message id, so no reaction target ref is available.
111
112
  return { ok: true }
112
113
  } catch (err) {
113
114
  const message = describeError(err)
@@ -56,7 +56,11 @@ import {
56
56
  } from './slack-bot-classify'
57
57
  import { createSlackDedupe } from './slack-bot-dedupe'
58
58
  import { createSlackEditMessageCallback } from './slack-bot-edit'
59
- import { createSlackReactionCallback, createSlackRemoveReactionCallback } from './slack-bot-reactions'
59
+ import {
60
+ createSlackReactionCallback,
61
+ createSlackRemoveReactionCallback,
62
+ encodeSlackReactionRef,
63
+ } from './slack-bot-reactions'
60
64
  import { enrichSlackReferenceContext } from './slack-bot-reference'
61
65
  import {
62
66
  buildSlashAckPayload,
@@ -1006,7 +1010,12 @@ export function createOutboundCallback(deps: {
1006
1010
  if (threadTs === null && chunks.length > 1) threadTs = sent.ts
1007
1011
  }
1008
1012
  if (typingTracker) await typingTracker.clearAfterSend(msg.chat, msg.typingThread ?? msg.thread)
1009
- return { ok: true, messageId: sentTs[0], messageIds: sentTs }
1013
+ return {
1014
+ ok: true,
1015
+ messageId: sentTs[0],
1016
+ messageIds: sentTs,
1017
+ reactionRef: encodeSlackReactionRef({ channel: msg.chat, ts: sentTs[0]! }),
1018
+ }
1010
1019
  } catch (err) {
1011
1020
  const message = describeError(err)
1012
1021
  logger.error(`[slack-bot] postMessage failed: ${message}`)
@@ -106,6 +106,7 @@ export function createSlackOutboundCallback(deps: {
106
106
  const filename = attachment.filename ?? basename(path)
107
107
  await deps.client.uploadFile([msg.chat], buffer, filename)
108
108
  }
109
+ // The user-account SDK send APIs return no posted-message id, so no reaction target ref is available.
109
110
  return { ok: true }
110
111
  } catch (err) {
111
112
  const message = describeError(err)
@@ -0,0 +1,307 @@
1
+ export type CompletionClaimDecision =
2
+ | { kind: 'allow' }
3
+ | { kind: 'block'; reason: string }
4
+ | { kind: 'warn'; notice: string }
5
+
6
+ export type CompletionClaimInput = {
7
+ text: string | undefined
8
+ qualifyingWorkObserved: boolean
9
+ }
10
+
11
+ export type ToolResultEvidenceInput = {
12
+ toolName: string
13
+ isError: boolean
14
+ details: unknown
15
+ }
16
+
17
+ export function checkCompletionClaim(input: CompletionClaimInput): CompletionClaimDecision {
18
+ if (input.qualifyingWorkObserved) return { kind: 'allow' }
19
+ const text = normalize(input.text ?? '')
20
+ if (text === '') return { kind: 'allow' }
21
+
22
+ if (matchesKoreanClaim(text) || hasAssertivePhrase(text, ALL_FIRST_PERSON_PHRASES)) {
23
+ return { kind: 'block', reason: UNSUPPORTED_COMPLETION_REASON }
24
+ }
25
+ if (SOFT_PHRASES.some((phrase) => text.includes(phrase))) {
26
+ return { kind: 'warn', notice: SOFT_NOTICE }
27
+ }
28
+ return { kind: 'allow' }
29
+ }
30
+
31
+ export function isQualifyingWorkResult(input: ToolResultEvidenceInput): boolean {
32
+ if (input.isError) return false
33
+ const details = isRecord(input.details) ? input.details : undefined
34
+ if (details?.ok === false || details?.error === true) return false
35
+ if (
36
+ NON_WORK_TOOLS.has(input.toolName) ||
37
+ input.toolName.startsWith('channel_') ||
38
+ input.toolName.startsWith('todo_')
39
+ ) {
40
+ return false
41
+ }
42
+ if (input.toolName === 'spawn_subagent') return details?.mode === 'sync'
43
+ if (input.toolName === 'subagent_output') return details?.status === 'completed'
44
+ return true
45
+ }
46
+
47
+ function normalize(text: string): string {
48
+ return maskQuotedAndCodeSpans(text)
49
+ .toLocaleLowerCase()
50
+ .replace(/[*_~]/gu, ' ')
51
+ .replace(/\r\n?/gu, '\n')
52
+ .replace(/[^\S\n]+/gu, ' ')
53
+ .replace(/ *\n */gu, '\n')
54
+ .replace(/\n+/gu, '\n')
55
+ .trim()
56
+ }
57
+
58
+ function maskQuotedAndCodeSpans(text: string): string {
59
+ return NON_ASSERTED_SPAN_PATTERNS.reduce(
60
+ (masked, pattern) => masked.replace(pattern, (span) => span.replace(/[^\r\n]/gu, ' ')),
61
+ text,
62
+ )
63
+ }
64
+
65
+ function matchesKoreanClaim(text: string): boolean {
66
+ for (const phrase of KO_PHRASES) {
67
+ for (const index of phraseIndexes(text, phrase)) {
68
+ if (claimIsQuestion(text, index) || claimHasPastOrAttributedContext(text, index)) continue
69
+ const prefix = text.slice(Math.max(latestSentenceBoundary(text, index) + 1, index - 24), index)
70
+ if (KOREAN_OTHER_SUBJECT.test(prefix) && !KOREAN_FIRST_PERSON_SUBJECT.test(prefix)) continue
71
+ return true
72
+ }
73
+ }
74
+ return false
75
+ }
76
+
77
+ function hasAssertivePhrase(text: string, phrases: readonly string[]): boolean {
78
+ return phrases.some((phrase) => {
79
+ return phraseIndexes(text, phrase).some(
80
+ (index) => !claimIsQuestion(text, index) && !claimHasPastOrAttributedContext(text, index),
81
+ )
82
+ })
83
+ }
84
+
85
+ function phraseIndexes(text: string, phrase: string): number[] {
86
+ const indexes: number[] = []
87
+ let offset = 0
88
+ while (offset < text.length) {
89
+ const index = text.indexOf(phrase, offset)
90
+ if (index < 0) break
91
+ indexes.push(index)
92
+ offset = index + phrase.length
93
+ }
94
+ return indexes
95
+ }
96
+
97
+ function claimIsQuestion(text: string, claimIndex: number): boolean {
98
+ const nextQuestion = earliestIndex(text, QUESTION_TERMINATORS, claimIndex)
99
+ if (nextQuestion < 0) return false
100
+ const nextStatementEnd = earliestIndex(text, DECLARATIVE_TERMINATORS, claimIndex)
101
+ if (nextStatementEnd < 0) return true
102
+ return nextQuestion < nextStatementEnd
103
+ }
104
+
105
+ function earliestIndex(text: string, needles: readonly string[], offset: number): number {
106
+ const indexes = needles.map((needle) => text.indexOf(needle, offset)).filter((index) => index >= 0)
107
+ return indexes.length === 0 ? -1 : Math.min(...indexes)
108
+ }
109
+
110
+ function claimHasPastOrAttributedContext(text: string, claimIndex: number): boolean {
111
+ const sentenceStart = latestSentenceBoundary(text, claimIndex)
112
+ const prefix = text.slice(sentenceStart + 1, claimIndex)
113
+ return HISTORICAL_MARKERS.some((marker) => prefix.includes(marker)) || ATTRIBUTION_END.test(prefix)
114
+ }
115
+
116
+ function latestSentenceBoundary(text: string, offset: number): number {
117
+ return Math.max(...SENTENCE_TERMINATORS.map((terminator) => text.lastIndexOf(terminator, offset)))
118
+ }
119
+
120
+ function isRecord(value: unknown): value is Record<string, unknown> {
121
+ return typeof value === 'object' && value !== null
122
+ }
123
+
124
+ // Every block phrase is first-person and perfective. Bare verbs stay in the
125
+ // warning tier so descriptions of another actor are never hard-denied.
126
+ const EN_PHRASES: readonly string[] = [
127
+ 'i saved it',
128
+ "i've saved it",
129
+ 'i have saved it',
130
+ 'i wrote it',
131
+ "i've written it",
132
+ 'i recorded it',
133
+ 'i applied it',
134
+ 'i updated it',
135
+ "i've updated it",
136
+ 'i fixed it',
137
+ "i've fixed it",
138
+ 'i deployed it',
139
+ 'i committed it',
140
+ 'i removed it',
141
+ 'i deleted it',
142
+ 'i saved the ',
143
+ "i've saved the ",
144
+ 'i wrote the ',
145
+ "i've written the ",
146
+ 'i recorded the ',
147
+ 'i applied the ',
148
+ 'i updated the ',
149
+ "i've updated the ",
150
+ 'i fixed the ',
151
+ "i've fixed the ",
152
+ 'i deployed the ',
153
+ 'i committed the ',
154
+ 'i removed the ',
155
+ 'i deleted the ',
156
+ 'i saved your ',
157
+ 'i updated your ',
158
+ 'i fixed your ',
159
+ ]
160
+
161
+ // Korean commonly drops the subject. The perfective endings below are safe for
162
+ // a bare assistant ack; an explicit nearby third-person 은/는/이/가 subject
163
+ // demotes the match, while 내가/제가 keeps the first-person reading.
164
+ const KO_PHRASES: readonly string[] = [
165
+ '저장했어',
166
+ '저장했습니다',
167
+ '기록했어',
168
+ '기록했습니다',
169
+ '반영했어',
170
+ '반영했습니다',
171
+ '고쳤어',
172
+ '고쳤습니다',
173
+ '수정했어',
174
+ '수정했습니다',
175
+ '커밋했어',
176
+ '커밋했습니다',
177
+ '삭제했어',
178
+ '삭제했습니다',
179
+ ]
180
+
181
+ const ES_PHRASES: readonly string[] = ['lo guardé', 'lo escribí', 'lo actualicé', 'lo corregí', 'lo eliminé']
182
+ const FR_PHRASES: readonly string[] = [
183
+ "je l'ai enregistré",
184
+ "je l'ai écrit",
185
+ "je l'ai mis à jour",
186
+ "je l'ai corrigé",
187
+ "je l'ai supprimé",
188
+ ]
189
+ const IT_PHRASES: readonly string[] = [
190
+ "l'ho salvato",
191
+ "l'ho scritto",
192
+ "l'ho aggiornato",
193
+ "l'ho corretto",
194
+ "l'ho eliminato",
195
+ ]
196
+ const PT_PHRASES: readonly string[] = ['eu salvei', 'eu escrevi', 'eu atualizei', 'eu corrigi', 'eu removi']
197
+ const DE_PHRASES: readonly string[] = [
198
+ 'ich habe es gespeichert',
199
+ 'ich habe es geschrieben',
200
+ 'ich habe es aktualisiert',
201
+ 'ich habe es korrigiert',
202
+ 'ich habe es gelöscht',
203
+ ]
204
+ const RU_PHRASES: readonly string[] = ['я сохранил', 'я записал', 'я обновил', 'я исправил', 'я удалил']
205
+ const ZH_PHRASES: readonly string[] = ['我已经保存了', '我已经写好了', '我已经更新了', '我已经修好了', '我已经删除了']
206
+ const JA_PHRASES: readonly string[] = [
207
+ '私は保存しておきました',
208
+ '私は書いておきました',
209
+ '私は更新しておきました',
210
+ '私は修正しておきました',
211
+ '私は削除しておきました',
212
+ ]
213
+ const AR_PHRASES: readonly string[] = ['أنا حفظته', 'أنا كتبته', 'أنا حدّثته', 'أنا أصلحته', 'أنا حذفته']
214
+ const HI_PHRASES: readonly string[] = [
215
+ 'मैंने इसे सहेज दिया',
216
+ 'मैंने इसे लिख दिया',
217
+ 'मैंने इसे अपडेट कर दिया',
218
+ 'मैंने इसे ठीक कर दिया',
219
+ 'मैंने इसे हटा दिया',
220
+ ]
221
+ const TR_PHRASES: readonly string[] = ['kaydettim', 'yazdım', 'güncelledim', 'düzelttim', 'sildim']
222
+ const VI_PHRASES: readonly string[] = ['tôi đã lưu', 'tôi đã viết', 'tôi đã cập nhật', 'tôi đã sửa', 'tôi đã xóa']
223
+ const ID_PHRASES: readonly string[] = [
224
+ 'saya sudah menyimpan',
225
+ 'saya sudah menulis',
226
+ 'saya sudah memperbarui',
227
+ 'saya sudah memperbaiki',
228
+ 'saya sudah menghapus',
229
+ ]
230
+
231
+ const ALL_FIRST_PERSON_PHRASES: readonly string[] = [
232
+ ...EN_PHRASES,
233
+ ...ES_PHRASES,
234
+ ...FR_PHRASES,
235
+ ...IT_PHRASES,
236
+ ...PT_PHRASES,
237
+ ...DE_PHRASES,
238
+ ...RU_PHRASES,
239
+ ...ZH_PHRASES,
240
+ ...JA_PHRASES,
241
+ ...AR_PHRASES,
242
+ ...HI_PHRASES,
243
+ ...TR_PHRASES,
244
+ ...VI_PHRASES,
245
+ ...ID_PHRASES,
246
+ ]
247
+
248
+ const KOREAN_OTHER_SUBJECT = /(?:^|[\s,])[^\s,]{1,16}(?:은|는|이|가)(?:\s+\S+){0,3}\s*$/u
249
+ const KOREAN_FIRST_PERSON_SUBJECT = /(?:내가|제가|나는|저는)(?:\s+\S+){0,3}\s*$/u
250
+ const ATTRIBUTION_END =
251
+ /(?:said|wrote|reported|dijo|a dit|ha detto|disse|sagte|сказал[аи]?|说|言いました|قال|कहा|dedi|nói|berkata|말했어|말했습니다|썼어|썼습니다)\s*[:"“']?\s*$/u
252
+ const QUESTION_TERMINATORS: readonly string[] = ['?', '?', '﹖']
253
+ const DECLARATIVE_TERMINATORS: readonly string[] = ['.', '!', '。', '!', '。', '.', '﹒', '﹗', '\n']
254
+ const SENTENCE_TERMINATORS: readonly string[] = [...QUESTION_TERMINATORS, ...DECLARATIVE_TERMINATORS]
255
+ const NON_ASSERTED_SPAN_PATTERNS: readonly RegExp[] = [
256
+ /```[\s\S]*?```/gu,
257
+ /`[^`\r\n]*`/gu,
258
+ /"[^"\r\n]*"/gu,
259
+ /(?<![\p{L}\p{N}])'[^'\r\n]+'(?![\p{L}\p{N}])/gu,
260
+ /“[^”\r\n]*”/gu,
261
+ /‘[^’\r\n]*’/gu,
262
+ /「[^」\r\n]*」/gu,
263
+ /『[^』\r\n]*』/gu,
264
+ ]
265
+ const HISTORICAL_MARKERS: readonly string[] = [
266
+ 'yesterday',
267
+ 'earlier',
268
+ 'previously',
269
+ 'i thought',
270
+ 'i think',
271
+ 'last week',
272
+ 'last month',
273
+ 'for another project',
274
+ 'ayer',
275
+ 'hier',
276
+ 'ieri',
277
+ 'ontem',
278
+ 'gestern',
279
+ 'вчера',
280
+ '昨天',
281
+ '昨日',
282
+ 'أمس',
283
+ 'कल',
284
+ 'dün',
285
+ 'hôm qua',
286
+ 'kemarin',
287
+ '어제',
288
+ '라고',
289
+ '줄 알았',
290
+ '전에',
291
+ '이전에',
292
+ '지난주',
293
+ '지난달',
294
+ ]
295
+
296
+ const SOFT_PHRASES: readonly string[] = ['saved and ready', 'updated and ready', '반영 완료', '수정 완료']
297
+
298
+ const NON_WORK_TOOLS = new Set(['skip_response', 'restart', 'grant_role', 'subagent_cancel'])
299
+
300
+ const UNSUPPORTED_COMPLETION_REASON =
301
+ 'This reply claims you already completed durable work, but this logical turn has no successful non-communication work result to support it. ' +
302
+ 'Actually perform the work with the appropriate tool, confirm that it succeeds, and then reply with the completion claim. ' +
303
+ 'If no durable change was intended, reword the reply without claiming it was saved, applied, updated, fixed, or otherwise completed.'
304
+
305
+ const SOFT_NOTICE =
306
+ 'This reply sounds completion-shaped, but no successful non-communication work was observed this turn. ' +
307
+ 'Only claim a durable result after the relevant tool succeeds; otherwise describe what remains to be done.'