Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions packages/builtin-tools/src/tools/ListPeersTool/ListPeersTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,21 +85,35 @@ Use this tool to discover messaging targets before sending cross-session message
// and optionally includes Remote Control bridge peers.
const peers: PeerInfo[] = []

// Discovery is handled by the UDS messaging subsystem initialized in setup.ts.
// Return discovered peers from the app state.
const appState = context.getAppState()
const messagingSocketPath = (appState as Record<string, unknown>).messagingSocketPath as string | undefined
/* eslint-disable @typescript-eslint/no-require-imports */
const udsMessaging =
require('src/utils/udsMessaging.js') as typeof import('src/utils/udsMessaging.js')
const udsClient =
require('src/utils/udsClient.js') as typeof import('src/utils/udsClient.js')
/* eslint-enable @typescript-eslint/no-require-imports */

const messagingSocketPath = udsMessaging.getUdsMessagingSocketPath()
if (messagingSocketPath) {
// Self entry for reference
if (_input.include_self) {
peers.push({
address: `uds:${messagingSocketPath}`,
address: udsMessaging.formatUdsAddress(messagingSocketPath),
name: 'self',
pid: process.pid,
})
}
}

for (const peer of await udsClient.listPeers()) {
if (!peer.messagingSocketPath) continue
peers.push({
address: udsMessaging.formatUdsAddress(peer.messagingSocketPath),
name: peer.name ?? peer.kind,
cwd: peer.cwd,
pid: peer.pid,
})
}

return {
data: { peers },
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,43 @@ export type SendMessageToolOutput =
| RequestOutput
| ResponseOutput

const UDS_INLINE_TOKEN_MARKER = '#token='
const UDS_INLINE_TOKEN_REJECTED_KEY = '__udsInlineTokenRejected'

function stripInlineUdsToken(target: string): string {
const markerIndex = target.lastIndexOf(UDS_INLINE_TOKEN_MARKER)
return markerIndex === -1 ? target : target.slice(0, markerIndex)
}

function hasInlineUdsToken(to: string): boolean {
const addr = parseAddress(to)
return (
addr.scheme === 'uds' && addr.target.includes(UDS_INLINE_TOKEN_MARKER)
)
}

function recipientForDisplay(to: string): string {
const addr = parseAddress(to)
if (addr.scheme !== 'uds') return to
return `uds:${stripInlineUdsToken(addr.target)}`
}

function markAndRedactInlineUdsToken(
input: { to: string } & Record<string, unknown>,
): void {
if (!hasInlineUdsToken(input.to)) return
input.to = recipientForDisplay(input.to)
input[UDS_INLINE_TOKEN_REJECTED_KEY] = true
}

function wasInlineUdsTokenRejected(input: unknown): boolean {
return (
typeof input === 'object' &&
input !== null &&
(input as Record<string, unknown>)[UDS_INLINE_TOKEN_REJECTED_KEY] === true
)
}

function findTeammateColor(
appState: {
teamContext?: { teammates: { [id: string]: { color?: string } } }
Expand Down Expand Up @@ -541,15 +578,19 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
},

backfillObservableInput(input) {
if ('type' in input) return
if (typeof input.to !== 'string') return

markAndRedactInlineUdsToken(
input as { to: string } & Record<string, unknown>,
)
if ('type' in input) return

if (input.to === '*') {
input.type = 'broadcast'
if (typeof input.message === 'string') input.content = input.message
} else if (typeof input.message === 'string') {
input.type = 'message'
input.recipient = input.to
input.recipient = recipientForDisplay(input.to)
input.content = input.message
} else if (typeof input.message === 'object' && input.message !== null) {
const msg = input.message as {
Expand All @@ -560,7 +601,7 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
feedback?: string
}
input.type = msg.type
input.recipient = input.to
input.recipient = recipientForDisplay(input.to)
if (msg.request_id !== undefined) input.request_id = msg.request_id
if (msg.approve !== undefined) input.approve = msg.approve
const content = msg.reason ?? msg.feedback
Expand All @@ -569,16 +610,17 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
},

toAutoClassifierInput(input) {
const recipient = recipientForDisplay(input.to)
if (typeof input.message === 'string') {
return `to ${input.to}: ${input.message}`
return `to ${recipient}: ${input.message}`
}
switch (input.message.type) {
case 'shutdown_request':
return `shutdown_request to ${input.to}`
return `shutdown_request to ${recipient}`
case 'shutdown_response':
return `shutdown_response ${input.message.approve ? 'approve' : 'reject'} ${input.message.request_id}`
case 'plan_approval_response':
return `plan_approval ${input.message.approve ? 'approve' : 'reject'} to ${input.to}`
return `plan_approval ${input.message.approve ? 'approve' : 'reject'} to ${recipient}`
}
},

Expand Down Expand Up @@ -630,6 +672,19 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
errorCode: 9,
}
}
if (feature('UDS_INBOX')) {
if (
addr.scheme === 'uds' &&
(hasInlineUdsToken(input.to) || wasInlineUdsTokenRejected(input))
) {
return {
result: false,
message:
'uds addresses must not include inline auth tokens; use the ListPeers address',
errorCode: 9,
}
}
}
if (input.to.includes('@')) {
return {
result: false,
Expand Down Expand Up @@ -787,6 +842,16 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
}
}
if (addr.scheme === 'uds') {
const recipient = recipientForDisplay(input.to)
if (hasInlineUdsToken(input.to) || wasInlineUdsTokenRejected(input)) {
return {
data: {
success: false,
message:
'uds addresses must not include inline auth tokens; use the ListPeers address',
},
}
}
/* eslint-disable @typescript-eslint/no-require-imports */
const { sendToUdsSocket } =
require('src/utils/udsClient.js') as typeof import('src/utils/udsClient.js')
Expand All @@ -797,14 +862,14 @@ export const SendMessageTool: Tool<InputSchema, SendMessageToolOutput> =
return {
data: {
success: true,
message: `”${preview}” → ${input.to}`,
message: `”${preview}” → ${recipient}`,
},
}
} catch (e) {
return {
data: {
success: false,
message: `Failed to send to ${input.to}: ${errorMessage(e)}`,
message: `Failed to send to ${recipient}: ${errorMessage(e)}`,
},
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { describe, expect, mock, test } from 'bun:test'

mock.module('bun:bundle', () => ({
feature: (name: string) => name === 'UDS_INBOX',
}))

describe('SendMessageTool UDS recipient handling', () => {
test('redacts inline UDS tokens before classifier and observable paths', async () => {
const { SendMessageTool } = await import('../SendMessageTool.js')
const tokenAddress = 'uds:/tmp/peer.sock#token=secret-token'

const observableInput = {
to: tokenAddress,
message: 'hello',
} as Record<string, unknown>
SendMessageTool.backfillObservableInput!(observableInput)

expect(observableInput.recipient).toBe('uds:/tmp/peer.sock')
expect(JSON.stringify(observableInput)).not.toContain('secret-token')
expect(
SendMessageTool.toAutoClassifierInput({
to: tokenAddress,
message: 'hello',
}),
).toBe('to uds:/tmp/peer.sock: hello')
})

test('rejects inline UDS tokens during validation', async () => {
const { SendMessageTool } = await import('../SendMessageTool.js')
const result = await SendMessageTool.validateInput!(
{
to: 'uds:/tmp/peer.sock#token=secret-token',
message: 'hello',
},
{} as never,
)

expect(result.result).toBe(false)
expect(JSON.stringify(result)).not.toContain('secret-token')
})
})
28 changes: 26 additions & 2 deletions src/cli/print.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2763,13 +2763,37 @@ function runHeadlessStreaming(
// when a message arrives via the UDS socket in headless mode.
if (feature('UDS_INBOX')) {
/* eslint-disable @typescript-eslint/no-require-imports */
const { setOnEnqueue } = require('../utils/udsMessaging.js')
const { drainInbox, setOnEnqueue } =
require('../utils/udsMessaging.js') as typeof import('../utils/udsMessaging.js')
/* eslint-enable @typescript-eslint/no-require-imports */

const enqueueUdsInboxMessages = (): boolean => {
const entries = drainInbox()
for (const entry of entries) {
const value =
typeof entry.message.data === 'string'
? entry.message.data
: jsonStringify(entry.message)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
enqueue({
mode: 'prompt',
value,
uuid: randomUUID(),
})
}
return entries.length > 0
}

setOnEnqueue(() => {
if (!inputClosed) {
void run()
if (enqueueUdsInboxMessages()) {
void run()
}
}
})

if (enqueueUdsInboxMessages()) {
void run()
}
}

// Cron scheduler: runs scheduled_tasks.json tasks in SDK/-p mode.
Expand Down
15 changes: 9 additions & 6 deletions src/commands/peers/peers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import type { LocalCommandCall } from '../../types/command.js'
import { listPeers, isPeerAlive } from '../../utils/udsClient.js'
import { getUdsMessagingSocketPath } from '../../utils/udsMessaging.js'
import {
formatUdsAddress,
getUdsMessagingSocketPath,
} from '../../utils/udsMessaging.js'

export const call: LocalCommandCall = async (_args, _context) => {
const mySocket = getUdsMessagingSocketPath()
Expand Down Expand Up @@ -29,11 +32,11 @@ export const call: LocalCommandCall = async (_args, _context) => {
? ` started: ${formatAge(peer.startedAt)}`
: ''

lines.push(
` [${status}] PID ${peer.pid} (${label})${cwd}${age}`,
)
lines.push(` [${status}] PID ${peer.pid} (${label})${cwd}${age}`)
if (peer.messagingSocketPath) {
lines.push(` socket: ${peer.messagingSocketPath}`)
lines.push(
` socket: ${formatUdsAddress(peer.messagingSocketPath)}`,
)
}
if (peer.sessionId) {
lines.push(` session: ${peer.sessionId}`)
Expand All @@ -43,7 +46,7 @@ export const call: LocalCommandCall = async (_args, _context) => {

lines.push('')
lines.push(
'To message a peer: use SendMessage with to="uds:<socket-path>"',
'To message a peer: use SendMessage with the shown uds:<socket-path> address',
)

return { type: 'text', value: lines.join('\n') }
Expand Down
Loading
Loading