typeclaw 0.48.2 → 0.48.4

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 (40) hide show
  1. package/package.json +2 -2
  2. package/scripts/dump-system-prompt.ts +146 -11
  3. package/src/agent/index.ts +35 -9
  4. package/src/agent/plugin-tools.ts +21 -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 +19 -3
  9. package/src/agent/tools/channel-reply.ts +18 -1
  10. package/src/agent/tools/runtime-notice.ts +29 -0
  11. package/src/bundled-plugins/github-cli-auth/git-command.ts +497 -652
  12. package/src/bundled-plugins/memory/load-memory.ts +23 -27
  13. package/src/bundled-plugins/security/index.ts +1 -0
  14. package/src/bundled-plugins/security/policies/private-surface-read.ts +152 -40
  15. package/src/channels/adapters/discord-bot-reactions.ts +1 -0
  16. package/src/channels/adapters/discord-bot.ts +11 -2
  17. package/src/channels/adapters/discord-reactions.ts +1 -0
  18. package/src/channels/adapters/discord.ts +1 -0
  19. package/src/channels/adapters/slack-bot.ts +11 -2
  20. package/src/channels/adapters/slack.ts +1 -0
  21. package/src/channels/completion-claim.ts +307 -0
  22. package/src/channels/router.ts +307 -102
  23. package/src/channels/types.ts +4 -1
  24. package/src/cli/hostd.ts +1 -1
  25. package/src/config/providers.ts +16 -10
  26. package/src/hostd/kakao-renewal-manager.ts +23 -11
  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/permissions/index.ts +1 -0
  31. package/src/permissions/permissions.ts +23 -0
  32. package/src/plugin/index.ts +1 -0
  33. package/src/plugin/manager.ts +19 -1
  34. package/src/plugin/types.ts +9 -0
  35. package/src/sandbox/canonical-secrets.ts +24 -4
  36. package/src/sandbox/hidden-paths.ts +8 -3
  37. package/src/sandbox/index.ts +2 -0
  38. package/src/secrets/kakao-renewal.ts +123 -20
  39. package/src/skills/typeclaw-permissions/SKILL.md +13 -1
  40. package/src/skills/typeclaw-plugins/SKILL.md +91 -11
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.2",
3
+ "version": "0.48.4",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -50,7 +50,7 @@
50
50
  "@mariozechner/pi-tui": "^0.73.1",
51
51
  "@modelcontextprotocol/sdk": "^1.29.0",
52
52
  "@mozilla/readability": "^0.6.0",
53
- "agent-messenger": "^2.32.3",
53
+ "agent-messenger": "^2.35.0",
54
54
  "cheerio": "^1.2.0",
55
55
  "citty": "^0.2.2",
56
56
  "cron-parser": "^5.5.0",
@@ -4,6 +4,8 @@ import { parseArgs } from 'node:util'
4
4
 
5
5
  import { composeSystemPrompt, deriveSystemPromptMode, renderTurnTimeAnchor, type SystemPromptMode } from '@/agent'
6
6
  import type { SessionOrigin, SessionRoleContext } from '@/agent/session-origin'
7
+ import { renderRetrievedMemorySection, type RetrievedMemoryItem } from '@/bundled-plugins/memory/load-memory'
8
+ import { composeTurnPrompt } from '@/channels/router'
7
9
 
8
10
  type OriginKind = 'tui' | 'cron' | 'channel' | 'subagent'
9
11
  const ALL_KINDS: readonly OriginKind[] = ['tui', 'cron', 'channel', 'subagent'] as const
@@ -42,6 +44,39 @@ const PLACEHOLDER_GIT_NUDGE = [
42
44
  "These are real, current modifications — not advice. Before declaring this session's task done, commit any of these you're responsible for, with `git add <paths>` and `git commit -m \"…\"` per the version-control rules above. If a listed path is from earlier work you didn't touch, leave it alone.",
43
45
  ].join('\n')
44
46
 
47
+ const PLACEHOLDER_TURN_TEXT: Record<OriginKind, string> = {
48
+ tui: '<PLACEHOLDER: interactive user request from the TUI>',
49
+ cron: '<PLACEHOLDER: scheduled cron job prompt>',
50
+ channel: '<PLACEHOLDER: current channel message addressed to the agent>',
51
+ subagent: '<PLACEHOLDER: delegated subagent task>',
52
+ }
53
+
54
+ const PLACEHOLDER_MEMORY_ITEMS: RetrievedMemoryItem[] = [
55
+ {
56
+ source: 'topic',
57
+ key: 'placeholder-working-preference',
58
+ heading: '<PLACEHOLDER: durable user preference relevant to the current request>',
59
+ excerpt:
60
+ '<PLACEHOLDER: full memory excerpt with the durable preference, supporting context, and fragment citations>',
61
+ },
62
+ {
63
+ source: 'stream',
64
+ key: 'stream:<PLACEHOLDER-fragment-id>',
65
+ heading: '<PLACEHOLDER: recent undreamed observation relevant to this turn>',
66
+ excerpt: '<PLACEHOLDER: recent observation body awaiting dreaming consolidation>',
67
+ who: '<PLACEHOLDER: speaker name>',
68
+ when: '2026-05-21T08:30:00.000Z',
69
+ where: {
70
+ adapter: 'slack-bot',
71
+ workspace: 'T<PLACEHOLDER-WS>',
72
+ workspaceName: '<PLACEHOLDER: workspace display name>',
73
+ chat: 'C<PLACEHOLDER-CH>',
74
+ chatName: '<PLACEHOLDER: channel display name>',
75
+ thread: null,
76
+ },
77
+ },
78
+ ]
79
+
45
80
  type Fixture = {
46
81
  origin: SessionOrigin
47
82
  roleContext: SessionRoleContext
@@ -263,6 +298,106 @@ export function dumpSystemPrompt(kind: OriginKind, options: { gitNudge: boolean
263
298
  return dumpSystemPromptWithBreakdown(kind, options).prompt
264
299
  }
265
300
 
301
+ export function dumpTurnPromptWithBreakdown(kind: OriginKind): DumpResult {
302
+ const fixture = buildFixture(kind)
303
+ const memory = renderRetrievedMemorySection(PLACEHOLDER_MEMORY_ITEMS, { origin: fixture.origin })
304
+ if (kind !== 'channel') {
305
+ const timeAnchor = `${renderTurnTimeAnchor(PLACEHOLDER_NOW)}\n\n`
306
+ const userText = `${PLACEHOLDER_TURN_TEXT[kind]}\n\n`
307
+ const prompt = `${timeAnchor}${userText}${memory}`
308
+ return buildDumpResult(prompt, [
309
+ ['Time anchor', timeAnchor],
310
+ ['User text', userText],
311
+ ['Memory block', memory],
312
+ ])
313
+ }
314
+
315
+ const observed = [
316
+ {
317
+ text: '<PLACEHOLDER: earlier human message observed while the agent was not engaged>',
318
+ authorId: 'U<PLACEHOLDER-OBSERVER-1>',
319
+ authorName: '<PLACEHOLDER: first participant name>',
320
+ authorIsBot: false,
321
+ receivedAt: PLACEHOLDER_NOW.getTime() - 90_000,
322
+ ts: PLACEHOLDER_NOW.getTime() - 90_000,
323
+ source: 'observed' as const,
324
+ },
325
+ {
326
+ text: '<PLACEHOLDER: peer-bot follow-up retained as recent channel context>',
327
+ authorId: 'U<PLACEHOLDER-PEER-BOT>',
328
+ authorName: '<PLACEHOLDER: peer bot name>',
329
+ authorIsBot: true,
330
+ receivedAt: PLACEHOLDER_NOW.getTime() - 45_000,
331
+ ts: PLACEHOLDER_NOW.getTime() - 45_000,
332
+ source: 'observed' as const,
333
+ },
334
+ ]
335
+ const batch = [
336
+ {
337
+ text: PLACEHOLDER_TURN_TEXT.channel,
338
+ authorId: 'U<PLACEHOLDER-AUTHOR>',
339
+ authorName: '<PLACEHOLDER: current speaker name>',
340
+ authorIsBot: false,
341
+ externalMessageId: '<PLACEHOLDER-message-id>',
342
+ isBotMention: true,
343
+ replyToBotMessageId: '<PLACEHOLDER-prior-bot-message-id>',
344
+ isDm: false,
345
+ receivedAt: PLACEHOLDER_NOW.getTime(),
346
+ ts: PLACEHOLDER_NOW.getTime(),
347
+ },
348
+ ]
349
+ const channelTurn = composeTurnPrompt(observed, batch, {
350
+ adapter: 'slack-bot',
351
+ loopGuardActive: false,
352
+ groupChatNudge: true,
353
+ now: PLACEHOLDER_NOW,
354
+ role: fixture.roleContext.role,
355
+ })
356
+ const prompt = `${channelTurn}\n\n${memory}`
357
+ return buildDumpResultFromMarkers(prompt, [
358
+ ['Time anchor', '<current-time>'],
359
+ ['Role anchor', '<your-role authority="current-speaker">'],
360
+ // Anchored on the fence, not the notice's prose: the fence is the invariant
361
+ // every runtime notice carries, so rewording a notice can't break the dump.
362
+ ['Group-chat nudge', '---\n**[SYSTEM MESSAGE — not from a human]**'],
363
+ ['Recent context', '## Recent context (not addressed to you, for awareness only)'],
364
+ ['Current message', 'Note: if earlier turns appear above, they are real conversation history you can use.'],
365
+ ['Memory block (channel headings only)', '# Memory'],
366
+ ])
367
+ }
368
+
369
+ export function dumpTurnPrompt(kind: OriginKind): string {
370
+ return dumpTurnPromptWithBreakdown(kind).prompt
371
+ }
372
+
373
+ function buildDumpResult(prompt: string, parts: ReadonlyArray<readonly [string, string]>): DumpResult {
374
+ if (parts.map(([, body]) => body).join('') !== prompt) {
375
+ throw new Error('turn-prompt breakdown does not cover the rendered prompt exactly')
376
+ }
377
+ return {
378
+ prompt,
379
+ sections: parts.map(([name, body]) => mkSection(name, body)),
380
+ totalBytes: byteLength(prompt),
381
+ totalChars: prompt.length,
382
+ totalTokens: estimateTokens(prompt),
383
+ }
384
+ }
385
+
386
+ function buildDumpResultFromMarkers(prompt: string, markers: ReadonlyArray<readonly [string, string]>): DumpResult {
387
+ const starts = markers.map(([name, marker], index) => {
388
+ const start = prompt.indexOf(marker, index === 0 ? 0 : 1)
389
+ if (start < 0) throw new Error(`turn-prompt section marker not found: ${name}`)
390
+ return { name, start }
391
+ })
392
+ if (starts[0]?.start !== 0 || starts.some((part, index) => index > 0 && part.start <= starts[index - 1]!.start)) {
393
+ throw new Error('turn-prompt section markers are not in rendered order')
394
+ }
395
+ return buildDumpResult(
396
+ prompt,
397
+ starts.map((part, index) => [part.name, prompt.slice(part.start, starts[index + 1]?.start)] as const),
398
+ )
399
+ }
400
+
266
401
  // Slice between two unique headers in the rendered prompt. Both anchors are
267
402
  // guaranteed unique by `composeSystemPrompt`'s contract (each section's
268
403
  // header appears exactly once). Used by the breakdown so we attribute each
@@ -276,10 +411,10 @@ function extractSection(prompt: string, startHeader: string, endHeader: string |
276
411
  return end < 0 ? prompt.slice(afterStart) : prompt.slice(afterStart, end)
277
412
  }
278
413
 
279
- function header(kind: OriginKind, result: DumpResult): string {
414
+ function header(kind: OriginKind, result: DumpResult, label: 'SYSTEM PROMPT' | 'USER TURN'): string {
280
415
  const bar = '═'.repeat(78)
281
416
  const summary = `~${result.totalTokens} tok / ${result.totalChars} chars / ${result.totalBytes} bytes (tok est. chars/4)`
282
- return `\n${bar}\n SYSTEM PROMPT — origin: ${kind} — ${summary}\n${bar}\n`
417
+ return `\n${bar}\n ${label} — origin: ${kind} — ${summary}\n${bar}\n`
283
418
  }
284
419
 
285
420
  function renderBreakdownTable(result: DumpResult): string {
@@ -309,6 +444,7 @@ function main(): void {
309
444
  options: {
310
445
  origin: { type: 'string', short: 'o', default: 'all' },
311
446
  'no-git-nudge': { type: 'boolean', default: false },
447
+ turn: { type: 'boolean', default: false },
312
448
  help: { type: 'boolean', short: 'h', default: false },
313
449
  },
314
450
  allowPositionals: false,
@@ -317,15 +453,17 @@ function main(): void {
317
453
  if (values.help) {
318
454
  process.stdout.write(
319
455
  [
320
- 'Usage: bun run debug:prompt [--origin <kind>] [--no-git-nudge]',
456
+ 'Usage: bun run debug:prompt [--turn] [--origin <kind>] [--no-git-nudge]',
321
457
  '',
322
- 'Dump the rendered system prompt for one or all session-origin kinds,',
458
+ 'Dump the rendered system prompt, or the per-turn user message with --turn,',
459
+ 'for one or all session-origin kinds,',
323
460
  'using placeholder values for every dynamic field. Each dump is prefixed',
324
461
  'with a per-section breakdown showing approximate tokens (chars/4),',
325
462
  'character count, and UTF-8 byte length.',
326
463
  '',
327
464
  'Options:',
328
465
  ' -o, --origin <kind> tui | cron | channel | subagent | all (default: all)',
466
+ ' --turn dump the non-cacheable user-turn message instead',
329
467
  ' --no-git-nudge omit the "Uncommitted changes at session start" block',
330
468
  ' -h, --help show this help',
331
469
  '',
@@ -348,18 +486,15 @@ function main(): void {
348
486
  })()
349
487
 
350
488
  for (const kind of kinds) {
351
- const result = dumpSystemPromptWithBreakdown(kind, { gitNudge: !values['no-git-nudge'] })
352
- process.stdout.write(header(kind, result))
489
+ const result = values.turn
490
+ ? dumpTurnPromptWithBreakdown(kind)
491
+ : dumpSystemPromptWithBreakdown(kind, { gitNudge: !values['no-git-nudge'] })
492
+ process.stdout.write(header(kind, result, values.turn ? 'USER TURN' : 'SYSTEM PROMPT'))
353
493
  process.stdout.write(renderBreakdownTable(result))
354
494
  process.stdout.write('\n\n')
355
495
  process.stdout.write(result.prompt)
356
496
  process.stdout.write('\n')
357
497
  }
358
-
359
- const anchor = renderTurnTimeAnchor(PLACEHOLDER_NOW)
360
- const bar = '═'.repeat(78)
361
- process.stdout.write(`\n${bar}\n PER-TURN INJECTION (prepended to every user message)\n${bar}\n\n`)
362
- process.stdout.write(`${anchor}\n`)
363
498
  }
364
499
 
365
500
  if (import.meta.main) {
@@ -23,7 +23,7 @@ import {
23
23
  import { defaultThinkingLevelForRef, isOpenAiFamilyRef, providerForModelRef, type ModelRef } from '@/config/providers'
24
24
  import { renderMcpCatalog } from '@/mcp/catalog'
25
25
  import type { McpManager } from '@/mcp/manager'
26
- import { createMcpDispatcherTools, MCP_DISPATCHER_TOOL_NAMES } from '@/mcp/tools'
26
+ import { createMcpDispatcherTools, MCP_DISPATCHER_TOOL_NAMES, resolveMcpCallPreflightFileOperands } from '@/mcp/tools'
27
27
  import { noopPermissionService, type PermissionService, type RolesConfig } from '@/permissions'
28
28
  import type {
29
29
  BuiltinToolRef,
@@ -35,6 +35,7 @@ import type {
35
35
  } from '@/plugin'
36
36
  import { createHookBus, materializeSkills } from '@/plugin'
37
37
  import type { ReloadRegistry } from '@/reload'
38
+ import { resolveHiddenPaths } from '@/sandbox'
38
39
  import type { Stream } from '@/stream'
39
40
 
40
41
  import { applyAdaptiveThinkingCompat } from './adaptive-thinking-compat'
@@ -406,7 +407,13 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
406
407
  webSearchTool,
407
408
  webFetchTool,
408
409
  createLookAtTool(options.permissions),
409
- ...(options.mcpManager ? buildMcpDispatcherToolDefinitions(options.mcpManager) : []),
410
+ ...(options.mcpManager
411
+ ? buildMcpDispatcherToolDefinitions(options.mcpManager, {
412
+ permissions: options.permissions,
413
+ getOrigin,
414
+ agentDir: options.plugins?.agentDir ?? process.cwd(),
415
+ })
416
+ : []),
410
417
  ...(options.reloadRegistry ? [createReloadTool({ registry: options.reloadRegistry })] : []),
411
418
  ...(options.stream ? [createStreamSnapshotTool({ stream: options.stream })] : []),
412
419
  ...buildChannelTools(
@@ -471,6 +478,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
471
478
  getOrigin,
472
479
  getAbort,
473
480
  getLoopGuardTurn,
481
+ ...(options.mcpManager === undefined ? {} : { mcpManager: options.mcpManager }),
474
482
  })
475
483
  const customToolsPreBudget = [...wrappedCustomSystemTools, ...pluginCustomTools, ...builtinPiToolOverrides]
476
484
  const customTools =
@@ -783,16 +791,26 @@ export function buildChannelTools(
783
791
  return tools
784
792
  }
785
793
 
786
- export function buildMcpDispatcherToolDefinitions(manager: McpManager): ToolDefinition[] {
787
- const tools = createMcpDispatcherTools(manager)
794
+ export function buildMcpDispatcherToolDefinitions(
795
+ manager: McpManager,
796
+ opts: {
797
+ permissions: PermissionService | undefined
798
+ getOrigin: () => SessionOrigin | undefined
799
+ agentDir: string
800
+ },
801
+ ): ToolDefinition[] {
802
+ const permissions = opts.permissions ?? noopPermissionService
803
+ const tools = createMcpDispatcherTools(manager, {
804
+ resolveHidden: () => resolveHiddenPaths(permissions, opts.getOrigin(), opts.agentDir),
805
+ })
788
806
  return [
789
- defineMcpDispatcherTool(MCP_DISPATCHER_TOOL_NAMES[0], tools[0]),
790
- defineMcpDispatcherTool(MCP_DISPATCHER_TOOL_NAMES[1], tools[1]),
791
- defineMcpDispatcherTool(MCP_DISPATCHER_TOOL_NAMES[2], tools[2]),
807
+ defineMcpDispatcherTool(MCP_DISPATCHER_TOOL_NAMES[0], tools[0], opts.agentDir),
808
+ defineMcpDispatcherTool(MCP_DISPATCHER_TOOL_NAMES[1], tools[1], opts.agentDir),
809
+ defineMcpDispatcherTool(MCP_DISPATCHER_TOOL_NAMES[2], tools[2], opts.agentDir),
792
810
  ]
793
811
  }
794
812
 
795
- function defineMcpDispatcherTool<P>(name: string, tool: PluginTool<P>): ToolDefinition {
813
+ function defineMcpDispatcherTool<P>(name: string, tool: PluginTool<P>, agentDir: string): ToolDefinition {
796
814
  return definePiTool({
797
815
  name,
798
816
  label: name,
@@ -809,7 +827,7 @@ function defineMcpDispatcherTool<P>(name: string, tool: PluginTool<P>): ToolDefi
809
827
  const result = await tool.execute(validated.data, {
810
828
  signal,
811
829
  sessionId: 'mcp-dispatcher',
812
- agentDir: process.cwd(),
830
+ agentDir,
813
831
  logger: { info() {}, warn() {}, error() {} },
814
832
  })
815
833
  return { content: result.content, details: result.details ?? null }
@@ -925,8 +943,15 @@ export function wrapSystemTools(
925
943
  getOrigin: () => SessionOrigin | undefined
926
944
  getAbort: () => ((reason?: string) => void) | undefined
927
945
  getLoopGuardTurn?: () => number | undefined
946
+ mcpManager?: McpManager
928
947
  },
929
948
  ): ToolDefinition[] {
949
+ const mcpManager = options.mcpManager
950
+ const resolvePreflightFileOperands =
951
+ mcpManager === undefined
952
+ ? undefined
953
+ : (tool: string, args: Record<string, unknown>) =>
954
+ tool === MCP_DISPATCHER_TOOL_NAMES[2] ? resolveMcpCallPreflightFileOperands(mcpManager, args) : undefined
930
955
  return tools.map((tool) =>
931
956
  wrapSystemTool(tool, {
932
957
  agentDir: options.agentDir,
@@ -935,6 +960,7 @@ export function wrapSystemTools(
935
960
  getOrigin: options.getOrigin,
936
961
  getAbort: options.getAbort,
937
962
  getLoopGuardTurn: options.getLoopGuardTurn,
963
+ ...(resolvePreflightFileOperands === undefined ? {} : { resolvePreflightFileOperands }),
938
964
  }),
939
965
  )
940
966
  }
@@ -44,6 +44,7 @@ import type {
44
44
  Tool,
45
45
  ToolBeforeEvent,
46
46
  ToolContext,
47
+ ToolFileOperands,
47
48
  ToolResult,
48
49
  } from '@/plugin'
49
50
  import {
@@ -300,6 +301,14 @@ export type WrapSystemToolOptions = {
300
301
  bashSandboxBoundary?: BashSandboxBoundary
301
302
  realProcDependencyCheck?: typeof commandNeedsRealProc
302
303
  remediations?: RemediationRegistry
304
+ // A dispatcher system tool (mcp_call) forwards a nested payload to a target
305
+ // chosen at call time, so its operand declarations are not knowable from the
306
+ // static tool definition the way a plugin tool's are. This seam resolves them
307
+ // per call, BEFORE the hooks run. The result feeds the security hooks ONLY —
308
+ // it is never handed to `enforceAndPinToolFiles`, so it can never make this
309
+ // boundary pin a file. It must not perform I/O against an unconnected target;
310
+ // returning undefined keeps the existing fail-closed scan.
311
+ resolvePreflightFileOperands?: (tool: string, args: Record<string, unknown>) => ToolFileOperands | undefined
303
312
  incidentLedger?: IncidentLedger
304
313
  }
305
314
 
@@ -345,6 +354,8 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
345
354
  sessionId: opts.sessionId,
346
355
  callId: toolCallId,
347
356
  args: mutableArgs,
357
+ toolProvenance: 'plugin',
358
+
348
359
  ...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
349
360
  ...(tool.fileOperands !== undefined ? { fileOperands: tool.fileOperands } : {}),
350
361
  }
@@ -379,6 +390,7 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
379
390
  tool: opts.toolName,
380
391
  args: before.args,
381
392
  agentDir: opts.agentDir,
393
+ toolProvenance: 'plugin',
382
394
  genericInputs: true,
383
395
  fileOperands: tool.fileOperands,
384
396
  logger: opts.logger,
@@ -438,12 +450,15 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
438
450
  const mutableArgs = params as Record<string, unknown>
439
451
  normalizeDefaultTreeRoot(tool.name, mutableArgs)
440
452
  const liveOrigin = opts.getOrigin?.()
453
+ const preflightFileOperands = opts.resolvePreflightFileOperands?.(tool.name, mutableArgs)
441
454
  const blockResult = await opts.hooks.runToolBefore({
442
455
  tool: tool.name,
443
456
  sessionId: opts.sessionId,
444
457
  callId: toolCallId,
445
458
  args: mutableArgs,
459
+ toolProvenance: 'first-party',
446
460
  ...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
461
+ ...(preflightFileOperands !== undefined ? { fileOperands: preflightFileOperands } : {}),
447
462
  })
448
463
  if (blockResult !== undefined) {
449
464
  throw new Error(`blocked: ${blockResult.reason}`)
@@ -467,10 +482,14 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
467
482
  }
468
483
  stripGuardAcknowledgements(mutableArgs)
469
484
 
485
+ // `preflightFileOperands` is deliberately NOT forwarded: this boundary's
486
+ // canonical credential denial must stay unconditional, so a target-declared
487
+ // nonFile operand can never exempt `secrets.json`/`.env`/`~/.ssh` from it.
470
488
  const pinnedFiles = await enforceAndPinToolFiles({
471
489
  tool: tool.name,
472
490
  args: mutableArgs,
473
491
  agentDir: opts.agentDir,
492
+ toolProvenance: 'first-party',
474
493
  genericInputs: tool.name !== 'mcp_call',
475
494
  ...(opts.permissions !== undefined
476
495
  ? { hidden: resolveHiddenPaths(opts.permissions, liveOrigin, opts.agentDir) }
@@ -548,6 +567,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
548
567
  sessionId: opts.sessionId,
549
568
  callId: toolCallId,
550
569
  args: mutableArgs,
570
+ toolProvenance: 'first-party',
551
571
  ...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
552
572
  })
553
573
  if (blockResult !== undefined) {
@@ -632,6 +652,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
632
652
  tool: tool.name,
633
653
  args: attemptArgs,
634
654
  agentDir: opts.agentDir,
655
+ toolProvenance: 'first-party',
635
656
  ...(opts.permissions !== undefined
636
657
  ? {
637
658
  hidden:
@@ -46,6 +46,9 @@ export type ContinuationEpisode = {
46
46
  export type TurnOutcome = {
47
47
  turnId: string
48
48
  stopReason: 'stop' | 'length' | 'aborted' | 'error' | 'unknown'
49
+ // Trusted runtime provenance for the one intentional abort that is safe to
50
+ // continue. Optional so older state files remain valid.
51
+ termination?: 'terminal-after-channel-reply'
49
52
  endedAt: number
50
53
  // Total tokens the just-completed turn consumed (from the assistant
51
54
  // message's usage). Accumulated into the episode's cumulativeTokens so the
@@ -136,6 +139,7 @@ function parseOutcome(value: unknown): TurnOutcome | null {
136
139
  turnId: o.turnId,
137
140
  stopReason: o.stopReason as TurnOutcome['stopReason'],
138
141
  endedAt: o.endedAt,
142
+ ...(o.termination === 'terminal-after-channel-reply' ? { termination: o.termination } : {}),
139
143
  ...(isFiniteNumber(o.tokens) ? { tokens: o.tokens } : {}),
140
144
  }
141
145
  }
@@ -209,7 +213,13 @@ export function decideContinuation(args: {
209
213
  if (state.autoResumeBlockedUntilRealUserTurn) return { kind: 'skip', reason: 'user-abort-blocked' }
210
214
 
211
215
  const outcome = state.lastTurnOutcome
212
- if (outcome === null || outcome.stopReason === 'unknown' || outcome.stopReason === 'aborted') {
216
+ const isSafeTerminalReplyAbort =
217
+ outcome?.stopReason === 'aborted' && outcome.termination === 'terminal-after-channel-reply'
218
+ if (
219
+ outcome === null ||
220
+ outcome.stopReason === 'unknown' ||
221
+ (outcome.stopReason === 'aborted' && !isSafeTerminalReplyAbort)
222
+ ) {
213
223
  return { kind: 'skip', reason: 'turn-not-safe' }
214
224
  }
215
225
 
@@ -81,7 +81,9 @@ export function onTurnStart(state: ContinuationState, isRealUserTurn: boolean):
81
81
  // consumed here regardless — so a later genuine user abort still arms D1.
82
82
  export function onTurnOutcome(state: ContinuationState, outcome: TurnOutcome): ContinuationState {
83
83
  const next: ContinuationState = { ...state, lastTurnOutcome: outcome, restartAbortPending: false }
84
- if (outcome.stopReason === 'aborted' && !state.restartAbortPending) {
84
+ const isSafeTerminalReplyAbort =
85
+ outcome.stopReason === 'aborted' && outcome.termination === 'terminal-after-channel-reply'
86
+ if (outcome.stopReason === 'aborted' && !state.restartAbortPending && !isSafeTerminalReplyAbort) {
85
87
  next.autoResumeBlockedUntilRealUserTurn = true
86
88
  }
87
89
  return next
@@ -52,6 +52,7 @@ export async function recordTurnOutcome(args: {
52
52
  origin: SessionOrigin
53
53
  turnId: string
54
54
  stopReason: TurnOutcome['stopReason']
55
+ termination?: TurnOutcome['termination']
55
56
  tokens?: number
56
57
  now?: number
57
58
  }): Promise<void> {
@@ -62,6 +63,7 @@ export async function recordTurnOutcome(args: {
62
63
  turnId: args.turnId,
63
64
  stopReason: args.stopReason,
64
65
  endedAt: args.now ?? Date.now(),
66
+ ...(args.termination !== undefined ? { termination: args.termination } : {}),
65
67
  ...(args.tokens !== undefined ? { tokens: args.tokens } : {}),
66
68
  }
67
69
  await writeContinuationState(args.agentDir, scope, onTurnOutcome(state, outcome))
@@ -11,7 +11,7 @@ import {
11
11
  createPrivateSurfaceReadIdentityVerifier,
12
12
  type PrivateSurfaceIdentityVerifier,
13
13
  } from '@/bundled-plugins/security/policies/private-surface-read'
14
- import type { ToolFileOperands, ToolLogger, ToolResult } from '@/plugin'
14
+ import type { ToolFileOperands, ToolLogger, ToolProvenance, ToolResult } from '@/plugin'
15
15
  import { CANONICAL_AGENT_SECRET_FILES } from '@/sandbox/canonical-secrets'
16
16
  import type { HiddenPaths } from '@/sandbox/hidden-paths'
17
17
 
@@ -84,6 +84,7 @@ export async function enforceAndPinToolFiles(
84
84
  hidden?: HiddenPaths
85
85
  logger?: Pick<ToolLogger, 'warn'>
86
86
  signal?: AbortSignal
87
+ toolProvenance?: ToolProvenance
87
88
  },
88
89
  hooks: EnforceAndPinToolFilesHooks = {},
89
90
  ): Promise<PinnedToolFiles> {
@@ -97,6 +98,7 @@ export async function enforceAndPinToolFiles(
97
98
  options.fileOperands,
98
99
  options.agentDir,
99
100
  options.logger,
101
+ options.toolProvenance,
100
102
  )
101
103
  enforceCanonicalSecretDenial(options)
102
104
  const outputs = outputTargets(options.tool, options.args, TOOL_OUTPUT_MAX_COUNT, options.fileOperands)
@@ -245,12 +247,25 @@ async function removePinnedSnapshot(root: string): Promise<void> {
245
247
  await rm(root, { recursive: true, force: true })
246
248
  }
247
249
 
250
+ // Canonical credential denial is the one check no operand declaration can waive:
251
+ // `fileOperands` is destructured away rather than spread through, so a tool (or a
252
+ // remote MCP server) declaring `nonFile` on an operand cannot make `secrets.json`,
253
+ // `.env`, or `~/.ssh` pass here. Role-derived private directories stay declarable
254
+ // and are enforced separately by the private-surface-read guard.
248
255
  export function enforceCanonicalSecretDenial(options: {
249
256
  tool: string
250
257
  args: Record<string, unknown>
251
258
  agentDir: string
259
+ toolProvenance?: ToolProvenance
252
260
  }): void {
253
- const blocked = checkPrivateSurfaceReadGuard({ ...options, hidden: { dirs: [], files: [] } })
261
+ const { tool, args, agentDir, toolProvenance } = options
262
+ const blocked = checkPrivateSurfaceReadGuard({
263
+ tool,
264
+ args,
265
+ agentDir,
266
+ hidden: { dirs: [], files: [] },
267
+ ...(toolProvenance !== undefined ? { toolProvenance } : {}),
268
+ })
254
269
  if (blocked !== undefined) throw new Error(`blocked: ${blocked.reason}`)
255
270
  }
256
271
 
@@ -262,9 +277,10 @@ function fileTargets(
262
277
  fileOperands: ToolFileOperands | undefined,
263
278
  agentDir: string,
264
279
  logger: Pick<ToolLogger, 'warn'> | undefined,
280
+ toolProvenance: ToolProvenance | undefined,
265
281
  ): FileTarget[] {
266
282
  if (isOutputTool(tool)) return []
267
- if (TOOLS_WITHOUT_LOCAL_FILE_OPERANDS.has(tool)) return []
283
+ if (toolProvenance === 'first-party' && TOOLS_WITHOUT_LOCAL_FILE_OPERANDS.has(tool)) return []
268
284
  if (tool === 'read' && typeof args.path === 'string') return [propertyTarget(args, 'path')]
269
285
  if (isTreeInputTool(tool)) {
270
286
  if (typeof args.path !== 'string') args.path = '.'
@@ -1,6 +1,7 @@
1
1
  import { Type } from '@mariozechner/pi-ai'
2
2
  import { defineTool } from '@mariozechner/pi-coding-agent'
3
3
 
4
+ import { checkCompletionClaim } from '@/channels/completion-claim'
4
5
  import { checkFalseReceipt } from '@/channels/github-false-receipt'
5
6
  import { evaluateRereviewGuard } from '@/channels/github-rereview-guard'
6
7
  import {
@@ -197,6 +198,19 @@ export function createChannelReplyTool({
197
198
  }
198
199
  const falseReceiptNotice = falseReceipt.kind === 'warn' ? falseReceipt.notice : null
199
200
 
201
+ const completionClaim = checkCompletionClaim({
202
+ text,
203
+ qualifyingWorkObserved: router.hasQualifyingWorkThisLogicalTurn?.(origin) === true,
204
+ })
205
+ if (completionClaim.kind === 'block') {
206
+ logger.warn(formatChannelToolFailure('channel_reply', completionClaim.reason))
207
+ return {
208
+ content: [{ type: 'text' as const, text: `channel_reply denied: ${completionClaim.reason}` }],
209
+ details: { ok: false, error: completionClaim.reason },
210
+ }
211
+ }
212
+ const completionClaimNotice = completionClaim.kind === 'warn' ? completionClaim.notice : null
213
+
200
214
  // Re-review stranding guard: block a thread close-out / verdict ack while
201
215
  // the bot still holds its own CHANGES_REQUESTED on this PR, so it can't
202
216
  // silently leave the PR blocked (PR #644). Runs before the resolve so a
@@ -307,7 +321,10 @@ export function createChannelReplyTool({
307
321
  // TOOL_RESULT_PREFIX to match the denial branch below. The prefix is
308
322
  // intentionally weaker and is safe ONLY because denials carry no echoed
309
323
  // prose; the success result does, and the weak prefix let Kimi loop.
310
- const warnNote = falseReceiptNotice !== null ? fenceRuntimeNotice(falseReceiptNotice) : ''
324
+ const warnings = [falseReceiptNotice, completionClaimNotice].filter(
325
+ (notice): notice is string => notice !== null,
326
+ )
327
+ const warnNote = warnings.length > 0 ? fenceRuntimeNotice(warnings.join('\n\n')) : ''
311
328
  const missNote = resolveMissNotice ?? ''
312
329
  return {
313
330
  content: [{ type: 'text' as const, text: `${fenceToolResult(receipt)}${hint}${warnNote}${missNote}` }],
@@ -29,6 +29,35 @@
29
29
  // a second model family exhibited the same misread, so we accept the
30
30
  // universal cost in exchange for never having to remember to add a new
31
31
  // family to a list.
32
+ // The bracketed marker is what tells the model a block is runtime-emitted, so
33
+ // any untrusted string rendered into a turn must not be able to carry one.
34
+ // Inbound channel text and memory headings/excerpts are both reproduced
35
+ // verbatim, so without this a participant (or a poisoned shard) could forge a
36
+ // fence and inherit whatever standing the real one has.
37
+ //
38
+ // Only the marker is defused, not the `---` rules around it: a horizontal rule
39
+ // is ordinary markdown that appears in pasted diffs, YAML, and tables all the
40
+ // time, and mangling those would corrupt real messages for no gain. The marker
41
+ // is the rare, load-bearing token — neutralize that and the fence cannot form.
42
+ //
43
+ // Matching is deliberately loose (case-insensitive, any wording after the
44
+ // keyword) because an attacker chooses both; the real emitters always produce
45
+ // the canonical form, so a false positive can only ever hit text that was
46
+ // already imitating a runtime marker.
47
+ //
48
+ // Only the OPENER is matched, via a lookahead that consumes nothing past `**[`.
49
+ // Matching the whole `**[...]**` span instead would be exploitable: the span
50
+ // ends at the first `]**`, so a nested opener (`**[SYSTEM MESSAGE a **[SYSTEM
51
+ // MESSAGE b]** c]**`) lands inside the replacement, and `String.replace` never
52
+ // rescans what it just emitted — leaving a live marker behind. Neutralizing
53
+ // openers independently is single-pass safe and idempotent, because the
54
+ // replacement text contains no `**[` for a later pass to find.
55
+ const RUNTIME_MARKER_OPENER = /\*\*\s*\[(?=\s*(?:SYSTEM MESSAGE|MEMORY CONTEXT)\b)/gi
56
+
57
+ export function defuseRuntimeMarkers(text: string): string {
58
+ return text.replace(RUNTIME_MARKER_OPENER, '(quoted from untrusted text) [')
59
+ }
60
+
32
61
  export function fenceRuntimeNotice(body: string): string {
33
62
  return (
34
63
  '\n\n---\n' +