diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index 560e630..eaa1521 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -198,7 +198,6 @@ export { type MessagesCompressionEvent, type CompressMessagesResult, } from './long-task/messages-compressor.js'; -export { createTeamTools, type TeamToolDeps } from './team-tools.js'; export { ensureIdentity, type IdentityConfig } from './auto-identity.js'; export { buildSelfAwareness, type AgentCapabilities } from './self-awareness.js'; export { diff --git a/packages/agent/src/team-tools.ts b/packages/agent/src/team-tools.ts deleted file mode 100644 index 541bf6e..0000000 --- a/packages/agent/src/team-tools.ts +++ /dev/null @@ -1,334 +0,0 @@ -import type { ToolDefinition } from './tools.js'; - -export interface TeamToolDeps { - serverUrl: string; - authToken: string; - teamSlug: string; - fetch?: typeof globalThis.fetch; -} - -export interface LocalTeamToolDeps { - localServerUrl: string; - workspaceId: string; - teamId: string; - fetch?: typeof globalThis.fetch; -} - -async function apiCall( - deps: TeamToolDeps, - method: string, - path: string, - body?: unknown -): Promise { - const fetchFn = deps.fetch ?? globalThis.fetch; - const url = `${deps.serverUrl}${path}`; - const opts: RequestInit = { - method, - headers: { - 'Authorization': `Bearer ${deps.authToken}`, - 'Content-Type': 'application/json', - }, - }; - if (body !== undefined) { - opts.body = JSON.stringify(body); - } - const res = await fetchFn(url, opts); - if (!res.ok) { - const text = await res.text(); - throw new Error(`API error ${res.status}: ${text}`); - } - return res.json(); -} - -export function createTeamTools(deps: TeamToolDeps): ToolDefinition[] { - const base = `/api/teams/${deps.teamSlug}`; - - return [ - { - name: 'check_hive', - description: 'Search team knowledge graph for existing knowledge on a topic before starting work', - parameters: { - type: 'object', - properties: { - topic: { type: 'string', description: 'Topic to search for in team knowledge' }, - }, - required: ['topic'], - }, - execute: async (args) => { - const topic = args.topic as string; - const results = await apiCall(deps, 'GET', `${base}/knowledge?search=${encodeURIComponent(topic)}`) as unknown[]; - if (!results || results.length === 0) { - return 'No existing team knowledge found.'; - } - return JSON.stringify(results, null, 2); - }, - }, - - { - name: 'share_to_team', - description: 'Share a discovery or insight to the team knowledge graph', - parameters: { - type: 'object', - properties: { - content: { type: 'string', description: 'Content to share with the team' }, - type: { type: 'string', description: 'Type of knowledge (e.g., discovery, insight, pattern)' }, - }, - required: ['content', 'type'], - }, - execute: async (args) => { - const content = args.content as string; - const type = args.type as string; - const name = content.slice(0, 100); - await apiCall(deps, 'POST', `${base}/knowledge/entities`, { - name, - type, - properties: { content }, - }); - return `Shared to team: "${name}"`; - }, - }, - - { - name: 'create_team_task', - description: 'Create a new task on the team task board', - parameters: { - type: 'object', - properties: { - title: { type: 'string', description: 'Task title' }, - description: { type: 'string', description: 'Task description' }, - priority: { - type: 'string', - enum: ['low', 'medium', 'high', 'urgent'], - description: 'Task priority', - }, - }, - required: ['title'], - }, - execute: async (args) => { - const body: Record = { title: args.title }; - if (args.description) body.description = args.description; - if (args.priority) body.priority = args.priority; - const result = await apiCall(deps, 'POST', `${base}/tasks`, body) as Record; - return `Created team task: "${args.title}" (id: ${result.id})`; - }, - }, - - { - name: 'claim_team_task', - description: 'Pick up an existing task from the team board and mark it as in progress', - parameters: { - type: 'object', - properties: { - task_id: { type: 'string', description: 'ID of the task to claim' }, - }, - required: ['task_id'], - }, - execute: async (args) => { - const taskId = args.task_id as string; - await apiCall(deps, 'PATCH', `${base}/tasks/${taskId}`, { status: 'in_progress' }); - return `Claimed task ${taskId} — now in progress.`; - }, - }, - - { - name: 'send_waggle_message', - description: 'Send a Waggle Dance protocol message to the team channel', - parameters: { - type: 'object', - properties: { - message: { type: 'string', description: 'Message content' }, - type: { - type: 'string', - enum: ['broadcast', 'request', 'response'], - description: 'Message type (default: broadcast)', - }, - subtype: { - type: 'string', - enum: ['discovery', 'routed_share', 'skill_share', 'task_delegation', 'knowledge_check', 'skill_request'], - description: 'Message subtype (default: discovery)', - }, - }, - required: ['message'], - }, - execute: async (args) => { - const message = args.message as string; - const type = (args.type as string) ?? 'broadcast'; - const subtype = (args.subtype as string) ?? 'discovery'; - await apiCall(deps, 'POST', `${base}/messages`, { - type, - subtype, - content: { text: message }, - }); - return `Message sent to team (${type}/${subtype}).`; - }, - }, - - { - name: 'request_team_capability', - description: 'Request team admin approval for a restricted capability. Use when a capability is blocked by team policy and the user wants to request access.', - parameters: { - type: 'object', - properties: { - capability_name: { type: 'string', description: 'Name of the blocked capability (e.g., "bash", "custom-plugin")' }, - capability_type: { type: 'string', enum: ['native', 'skill', 'plugin', 'mcp'], description: 'Type of capability' }, - justification: { type: 'string', description: 'Why the user needs this capability — use their own words' }, - }, - required: ['capability_name', 'capability_type', 'justification'], - }, - execute: async (args) => { - const name = args.capability_name as string; - const type = args.capability_type as string; - const justification = args.justification as string; - - try { - const result = await apiCall(deps, 'POST', `${base}/capability-requests`, { - capabilityName: name, - capabilityType: type, - justification, - }); - const res = result as { error?: string }; - if (res.error?.includes('pending')) { - return `A request for "${name}" is already pending. Your team admin will review it.`; - } - return `Request submitted for "${name}" (${type}). Your team admin will be notified and can approve or reject this request. You'll receive a notification when they decide.`; - } catch (err: unknown) { - const message = err instanceof Error ? err.message : String(err); - if (message.includes('409')) { - return `A request for "${name}" is already pending. Your team admin will review it.`; - } - return `Could not submit request: ${message}`; - } - }, - }, - ]; -} - -/** - * Create read-only tools that query the local server's team endpoints. - * These tools let the agent be "team-aware" in team workspaces. - */ -export function createLocalTeamTools(deps: LocalTeamToolDeps): ToolDefinition[] { - const fetchFn = deps.fetch ?? globalThis.fetch; - const base = deps.localServerUrl; - - async function localGet(path: string): Promise { - const res = await fetchFn(`${base}${path}`, { method: 'GET' }); - if (!res.ok) throw new Error(`Local API error ${res.status}`); - return res.json() as Promise; - } - - return [ - { - name: 'team_activity', - description: 'Get recent team activity — what has the team been working on?', - parameters: { - type: 'object', - properties: { - limit: { type: 'number', description: 'Max items to return (default 10)' }, - }, - }, - execute: async (args) => { - const limit = (args.limit as number) ?? 10; - const data = await localGet<{ items: Array<{ authorName: string; summary: string; timestamp: string; type: string }> }>( - `/api/team/activity?workspaceId=${deps.teamId}&limit=${limit}`, - ); - if (!data.items || data.items.length === 0) { - return 'No recent team activity found.'; - } - return data.items.map(i => `[${i.type}] ${i.authorName}: ${i.summary}`).join('\n'); - }, - }, - - { - name: 'team_tasks', - description: 'List current tasks on the workspace task board — see what needs doing.', - parameters: { - type: 'object', - properties: { - status: { type: 'string', enum: ['open', 'in_progress', 'done'], description: 'Filter by status' }, - }, - }, - execute: async (args) => { - const statusFilter = args.status ? `?status=${args.status}` : ''; - const data = await localGet<{ tasks: Array<{ id: string; title: string; status: string; assigneeName?: string }> }>( - `/api/workspaces/${deps.workspaceId}/tasks${statusFilter}`, - ); - if (!data.tasks || data.tasks.length === 0) { - return args.status ? `No ${args.status} tasks found.` : 'No tasks on the board.'; - } - return data.tasks.map(t => { - const assignee = t.assigneeName ? ` (${t.assigneeName})` : ''; - return `[${t.status}] ${t.title}${assignee} — id: ${t.id}`; - }).join('\n'); - }, - }, - - { - name: 'team_members', - description: 'See who is on the team and their current status (online/away/offline).', - parameters: { type: 'object', properties: {} }, - execute: async () => { - const data = await localGet<{ members: Array<{ displayName: string; status: string; activitySummary?: string }> }>( - `/api/team/presence?workspaceId=${deps.teamId}`, - ); - if (!data.members || data.members.length === 0) { - return 'No team members found (team server may be unavailable).'; - } - return data.members.map(m => { - const activity = m.activitySummary ? ` — ${m.activitySummary}` : ''; - return `${m.displayName} (${m.status})${activity}`; - }).join('\n'); - }, - }, - - { - name: 'assign_task', - description: 'Create a task and assign it to a team member. The assigned member will see it on their next catch-up.', - parameters: { - type: 'object', - properties: { - title: { type: 'string', description: 'Task title' }, - assigneeName: { type: 'string', description: 'Name of the team member to assign this to' }, - assigneeId: { type: 'string', description: 'User ID of the assignee (from team_members)' }, - }, - required: ['title', 'assigneeName'], - }, - execute: async (args) => { - const res = await fetchFn(`${base}/api/workspaces/${deps.workspaceId}/tasks`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - title: args.title, - assigneeName: args.assigneeName, - assigneeId: args.assigneeId, - creatorName: 'Agent', - }), - }); - if (!res.ok) throw new Error(`Failed to create task: ${res.status}`); - const task = await res.json() as { id: string }; - return `Task assigned to ${args.assigneeName}: "${args.title}" (id: ${task.id})`; - }, - }, - - { - name: 'complete_task', - description: 'Mark a task as done on the workspace task board.', - parameters: { - type: 'object', - properties: { - task_id: { type: 'string', description: 'ID of the task to complete' }, - }, - required: ['task_id'], - }, - execute: async (args) => { - const res = await fetchFn(`${base}/api/workspaces/${deps.workspaceId}/tasks/${args.task_id}`, { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ status: 'done' }), - }); - if (!res.ok) throw new Error(`Failed to complete task: ${res.status}`); - return `Task ${args.task_id} marked as done.`; - }, - }, - ]; -} diff --git a/packages/agent/tests/team-tools.test.ts b/packages/agent/tests/team-tools.test.ts deleted file mode 100644 index 73501a5..0000000 --- a/packages/agent/tests/team-tools.test.ts +++ /dev/null @@ -1,349 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { createTeamTools, createLocalTeamTools, type TeamToolDeps, type LocalTeamToolDeps } from '../src/team-tools.js'; -import type { ToolDefinition } from '../src/tools.js'; - -function makeDeps(fetchMock: ReturnType): TeamToolDeps { - return { - serverUrl: 'http://localhost:3000', - authToken: 'test-token-123', - teamSlug: 'alpha-team', - fetch: fetchMock as unknown as typeof globalThis.fetch, - }; -} - -function okResponse(data: unknown): Response { - return { - ok: true, - status: 200, - json: async () => data, - text: async () => JSON.stringify(data), - } as unknown as Response; -} - -function errorResponse(status: number, message: string): Response { - return { - ok: false, - status, - statusText: message, - text: async () => message, - } as unknown as Response; -} - -describe('createTeamTools', () => { - let fetchMock: ReturnType; - let deps: TeamToolDeps; - let tools: ToolDefinition[]; - - beforeEach(() => { - fetchMock = vi.fn(); - deps = makeDeps(fetchMock); - tools = createTeamTools(deps); - }); - - function getTool(name: string): ToolDefinition { - const tool = tools.find((t) => t.name === name); - if (!tool) throw new Error(`Tool "${name}" not found`); - return tool; - } - - it('creates all 5 team tools', () => { - const names = tools.map((t) => t.name); - expect(names).toContain('check_hive'); - expect(names).toContain('share_to_team'); - expect(names).toContain('create_team_task'); - expect(names).toContain('claim_team_task'); - expect(names).toContain('send_waggle_message'); - expect(names).toContain('request_team_capability'); - expect(tools).toHaveLength(6); - }); - - describe('check_hive', () => { - it('calls knowledge search API with topic', async () => { - fetchMock.mockResolvedValueOnce(okResponse([ - { id: '1', name: 'React patterns', type: 'concept' }, - { id: '2', name: 'React hooks', type: 'concept' }, - ])); - - const tool = getTool('check_hive'); - const result = await tool.execute({ topic: 'React' }); - - expect(fetchMock).toHaveBeenCalledOnce(); - const [url, opts] = fetchMock.mock.calls[0]; - expect(url).toBe('http://localhost:3000/api/teams/alpha-team/knowledge?search=React'); - expect(opts.method).toBe('GET'); - expect(opts.headers['Authorization']).toBe('Bearer test-token-123'); - expect(result).toContain('React patterns'); - }); - - it('returns message when no knowledge found', async () => { - fetchMock.mockResolvedValueOnce(okResponse([])); - - const tool = getTool('check_hive'); - const result = await tool.execute({ topic: 'quantum computing' }); - expect(result).toContain('No existing team knowledge found'); - }); - }); - - describe('share_to_team', () => { - it('posts to knowledge API', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ id: 'entity-1' })); - - const tool = getTool('share_to_team'); - const result = await tool.execute({ content: 'Found a great pattern for error handling', type: 'discovery' }); - - expect(fetchMock).toHaveBeenCalledOnce(); - const [url, opts] = fetchMock.mock.calls[0]; - expect(url).toBe('http://localhost:3000/api/teams/alpha-team/knowledge/entities'); - expect(opts.method).toBe('POST'); - const body = JSON.parse(opts.body); - expect(body.name).toBe('Found a great pattern for error handling'); - expect(body.type).toBe('discovery'); - expect(result).toContain('Shared'); - }); - - it('truncates name to 100 chars', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ id: 'entity-2' })); - - const longContent = 'A'.repeat(200); - const tool = getTool('share_to_team'); - await tool.execute({ content: longContent, type: 'insight' }); - - const body = JSON.parse(fetchMock.mock.calls[0][1].body); - expect(body.name.length).toBe(100); - }); - }); - - describe('create_team_task', () => { - it('posts to tasks API', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ id: 'task-1', title: 'Fix bug' })); - - const tool = getTool('create_team_task'); - const result = await tool.execute({ title: 'Fix bug', description: 'There is a bug', priority: 'high' }); - - expect(fetchMock).toHaveBeenCalledOnce(); - const [url, opts] = fetchMock.mock.calls[0]; - expect(url).toBe('http://localhost:3000/api/teams/alpha-team/tasks'); - expect(opts.method).toBe('POST'); - const body = JSON.parse(opts.body); - expect(body.title).toBe('Fix bug'); - expect(body.description).toBe('There is a bug'); - expect(body.priority).toBe('high'); - expect(result).toContain('task'); - }); - }); - - describe('claim_team_task', () => { - it('patches task status to in_progress', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ id: 'task-1', status: 'in_progress' })); - - const tool = getTool('claim_team_task'); - const result = await tool.execute({ task_id: 'task-42' }); - - expect(fetchMock).toHaveBeenCalledOnce(); - const [url, opts] = fetchMock.mock.calls[0]; - expect(url).toBe('http://localhost:3000/api/teams/alpha-team/tasks/task-42'); - expect(opts.method).toBe('PATCH'); - const body = JSON.parse(opts.body); - expect(body.status).toBe('in_progress'); - expect(result).toContain('Claimed'); - }); - }); - - describe('send_waggle_message', () => { - it('sends valid Waggle Dance protocol message', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ id: 'msg-1' })); - - const tool = getTool('send_waggle_message'); - const result = await tool.execute({ message: 'Found relevant docs', type: 'broadcast', subtype: 'routed_share' }); - - expect(fetchMock).toHaveBeenCalledOnce(); - const [url, opts] = fetchMock.mock.calls[0]; - expect(url).toBe('http://localhost:3000/api/teams/alpha-team/messages'); - expect(opts.method).toBe('POST'); - const body = JSON.parse(opts.body); - expect(body.type).toBe('broadcast'); - expect(body.subtype).toBe('routed_share'); - expect(body.content).toEqual({ text: 'Found relevant docs' }); - expect(result).toContain('broadcast/routed_share'); - }); - - it('defaults to broadcast/discovery when type/subtype omitted', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ id: 'msg-2' })); - - const tool = getTool('send_waggle_message'); - await tool.execute({ message: 'Hello team' }); - - const body = JSON.parse(fetchMock.mock.calls[0][1].body); - expect(body.type).toBe('broadcast'); - expect(body.subtype).toBe('discovery'); - }); - }); - - describe('error handling', () => { - it('throws on API error', async () => { - fetchMock.mockResolvedValueOnce(errorResponse(403, 'Forbidden')); - - const tool = getTool('check_hive'); - await expect(tool.execute({ topic: 'test' })).rejects.toThrow('403'); - }); - - it('throws on network failure', async () => { - fetchMock.mockRejectedValueOnce(new Error('ECONNREFUSED')); - - const tool = getTool('share_to_team'); - await expect(tool.execute({ content: 'test', type: 'note' })).rejects.toThrow('ECONNREFUSED'); - }); - }); -}); - -// ── Local Team Tools ────────────────────────────────────────────── - -describe('createLocalTeamTools', () => { - let fetchMock: ReturnType; - let localDeps: LocalTeamToolDeps; - let tools: ToolDefinition[]; - - beforeEach(() => { - fetchMock = vi.fn(); - localDeps = { - localServerUrl: 'http://127.0.0.1:3333', - workspaceId: 'ws-123', - teamId: 'team-abc', - fetch: fetchMock as unknown as typeof globalThis.fetch, - }; - tools = createLocalTeamTools(localDeps); - }); - - function getTool(name: string): ToolDefinition { - const tool = tools.find((t) => t.name === name); - if (!tool) throw new Error(`Tool "${name}" not found`); - return tool; - } - - it('creates 5 local team tools', () => { - const names = tools.map((t) => t.name); - expect(names).toContain('team_activity'); - expect(names).toContain('team_tasks'); - expect(names).toContain('team_members'); - expect(names).toContain('assign_task'); - expect(names).toContain('complete_task'); - expect(tools).toHaveLength(5); - }); - - describe('team_activity', () => { - it('returns formatted activity items', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ - items: [ - { authorName: 'Alice', summary: 'Added design docs', timestamp: '2026-01-01T00:00:00Z', type: 'memory' }, - { authorName: 'Bob', summary: 'Fixed auth bug', timestamp: '2026-01-01T01:00:00Z', type: 'session' }, - ], - })); - - const tool = getTool('team_activity'); - const result = await tool.execute({}); - expect(result).toContain('Alice'); - expect(result).toContain('design docs'); - expect(result).toContain('Bob'); - }); - - it('returns message when no activity', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ items: [] })); - const tool = getTool('team_activity'); - const result = await tool.execute({}); - expect(result).toContain('No recent team activity'); - }); - }); - - describe('team_tasks', () => { - it('returns formatted task list', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ - tasks: [ - { id: 't1', title: 'Fix bug', status: 'open', assigneeName: 'Alice' }, - { id: 't2', title: 'Add tests', status: 'in_progress' }, - ], - })); - - const tool = getTool('team_tasks'); - const result = await tool.execute({}); - expect(result).toContain('Fix bug'); - expect(result).toContain('Alice'); - expect(result).toContain('Add tests'); - }); - - it('filters by status', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ tasks: [] })); - const tool = getTool('team_tasks'); - const result = await tool.execute({ status: 'done' }); - - const [url] = fetchMock.mock.calls[0]; - expect(url).toContain('?status=done'); - expect(result).toContain('No done tasks'); - }); - }); - - describe('team_members', () => { - it('returns formatted member list', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ - members: [ - { displayName: 'Alice', status: 'online', activitySummary: 'Editing docs' }, - { displayName: 'Bob', status: 'away' }, - ], - })); - - const tool = getTool('team_members'); - const result = await tool.execute({}); - expect(result).toContain('Alice (online)'); - expect(result).toContain('Editing docs'); - expect(result).toContain('Bob (away)'); - }); - - it('returns message when no members', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ members: [] })); - const tool = getTool('team_members'); - const result = await tool.execute({}); - expect(result).toContain('No team members found'); - }); - }); - - describe('assign_task', () => { - it('creates a task with assignee and returns confirmation', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ id: 'task-new-1' })); - - const tool = getTool('assign_task'); - const result = await tool.execute({ - title: 'Review the PR', - assigneeName: 'Alice', - assigneeId: 'user-alice', - }); - - expect(fetchMock).toHaveBeenCalledOnce(); - const [url, opts] = fetchMock.mock.calls[0]; - expect(url).toBe('http://127.0.0.1:3333/api/workspaces/ws-123/tasks'); - expect(opts.method).toBe('POST'); - const body = JSON.parse(opts.body); - expect(body.title).toBe('Review the PR'); - expect(body.assigneeName).toBe('Alice'); - expect(body.assigneeId).toBe('user-alice'); - expect(body.creatorName).toBe('Agent'); - expect(result).toContain('Alice'); - expect(result).toContain('Review the PR'); - }); - }); - - describe('complete_task', () => { - it('marks task as done', async () => { - fetchMock.mockResolvedValueOnce(okResponse({ id: 'task-42', status: 'done' })); - - const tool = getTool('complete_task'); - const result = await tool.execute({ task_id: 'task-42' }); - - expect(fetchMock).toHaveBeenCalledOnce(); - const [url, opts] = fetchMock.mock.calls[0]; - expect(url).toBe('http://127.0.0.1:3333/api/workspaces/ws-123/tasks/task-42'); - expect(opts.method).toBe('PATCH'); - const body = JSON.parse(opts.body); - expect(body.status).toBe('done'); - expect(result).toContain('done'); - }); - }); -});