@indexnetwork/protocol 6.4.0-rc.383.1 → 6.5.1-rc.385.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"negotiation.tools.js","sourceRoot":"/","sources":["negotiation/negotiation.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,eAAe,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACzJ,OAAO,EAAE,mBAAmB,EAAE,MAAM,+CAA+C,CAAC;AAEpF,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAEjE,MAAM,MAAM,GAAG,cAAc,CAAC,uBAAuB,CAAC,CAAC;AAEvD;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAEpD;;;;;;;GAOG;AACH,SAAS,iBAAiB,CAAC,IAGnB;IACN,IAAI,CAAC,IAAI;QAAE,OAAO,IAAI,CAAC;IACvB,IAAI,OAAO,IAAI,CAAC,SAAS,KAAK,QAAQ,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE;QAAE,OAAO,IAAI,CAAC,SAAS,CAAC;IACvF,MAAM,eAAe,GAAG,IAAI,CAAC,WAAW,EAAE,YAAY,EAAE,SAAS,CAAC;IAClE,IAAI,OAAO,eAAe,KAAK,QAAQ,IAAI,eAAe,CAAC,IAAI,EAAE;QAAE,OAAO,eAAe,CAAC;IAC1F,OAAO,IAAI,C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X,SAAS,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC,SAAS,IAAI,EAAE;QAClE,SAAS;QACT,GAAG,CAAC,KAAK,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;KACrC,CAAC;AACJ,CAAC","sourcesContent":["import { z } from 'zod';\n\nimport type { DefineTool, ToolDeps } from '../shared/agent/tool.helpers.js';\nimport { success, error } from '../shared/agent/tool.helpers.js';\nimport { IndexNegotiator } from './negotiation.agent.js';\nimport type { NegotiationTurn, UserNegotiationContext, SeedAssessment, NegotiationOutcome } from './negotiation.state.js';\nimport { allowedActionsFor, isTerminalAction, readProtocolVersion, rejectActionFor, resolveSeat, seatViolationMessage } from './negotiation.protocol.js';\nimport { NEGOTIATION_ACTIONS } from '../shared/schemas/negotiation-state.schema.js';\nimport type { NegotiationTurnPayload } from '../shared/interfaces/agent-dispatcher.interface.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\nimport { focusedNetworkId } from '../shared/agent/tool.scope.js';\n\nconst logger = protocolLogger('ChatTools:Negotiation');\n\n/**\n * Default park-window budget for ambient (background) negotiations. When a personal\n * agent is fresh, the dispatcher parks the turn and this is how long we wait before\n * the system agent takes over as a fallback.\n *\n * Short enough that ambient opportunities materialize in minutes (not hours),\n * long enough to cover two full polling cycles (30s * 2 = 60s) plus an agent\n * subagent turn. 5 minutes gives generous headroom.\n */\nexport const AMBIENT_PARK_WINDOW_MS = 5 * 60 * 1000;\n\n/**\n * Pulls the negotiation's network from task metadata. Tasks created after the\n * scope hardening carry `metadata.networkId` directly; older tasks only have\n * the network embedded in the parked `turnContext.indexContext.networkId`.\n * Returns `null` for legacy tasks where neither field is present — callers\n * scoped by the request scope envelope must reject these defensively rather than\n * fall through to a global view.\n */\nfunction readTaskNetworkId(meta: {\n networkId?: string;\n turnContext?: { indexContext?: { networkId?: string } };\n} | null): string | null {\n if (!meta) return null;\n if (typeof meta.networkId === 'string' && meta.networkId.trim()) return meta.networkId;\n const fromTurnContext = meta.turnContext?.indexContext?.networkId;\n if (typeof fromTurnContext === 'string' && fromTurnContext.trim()) return fromTurnContext;\n return null;\n}\n\nconst SCOPE_DENIAL = 'Access denied: this negotiation is not in your bound network scope.';\n\n/** Extracts the ordered NegotiationTurn list from A2A message data parts. */\nfunction turnsFromMessages(messages: Array<{ parts: unknown[] }>): NegotiationTurn[] {\n return messages\n .map((m) => {\n const dp = (m.parts as Array<{ kind?: string; data?: unknown }>)?.find((p) => p.kind === 'data');\n return dp?.data as NegotiationTurn;\n })\n .filter(Boolean);\n}\n\n/**\n * Creates negotiation MCP tools for external agent access.\n * Exposes negotiation state for listing, reading, and responding to bilateral negotiations.\n */\nexport function createNegotiationTools(defineTool: DefineTool, deps: ToolDeps) {\n const { negotiationDatabase } = deps;\n\n const list_negotiations = defineTool({\n name: 'list_negotiations',\n description:\n 'List bilateral negotiations the authenticated user is involved in, either as the source (initiator) or candidate (responder). ' +\n 'Negotiations are turn-based exchanges where two AI agents negotiate on behalf of their users to determine if there is a ' +\n 'mutual opportunity for collaboration.\\n\\n' +\n '**Statuses:**\\n' +\n '- `active` — Negotiation is in progress, agents are exchanging turns.\\n' +\n '- `waiting_for_agent` — The graph has yielded and is waiting for an agent response (e.g. from the user via respond_to_negotiation) or a timeout.\\n' +\n '- `completed` — Negotiation has concluded (accepted, rejected, or reached turn cap).\\n\\n' +\n '**When to use:** To see ongoing and past negotiations, check which negotiations need attention, ' +\n 'or find a negotiation ID for get_negotiation or respond_to_negotiation.',\n querySchema: z.object({\n status: z.enum(['active', 'waiting_for_agent', 'completed', 'all']).optional()\n .describe('Filter by negotiation status. Omit or use \"all\" to return all negotiations.'),\n since: z.string().datetime().optional()\n .describe('ISO 8601 date-time. Only return negotiations created at or after this timestamp.'),\n limit: z.number().int().min(1).max(100).optional()\n .describe('Maximum negotiations to return per page (1-100). Omit to return all.'),\n page: z.number().int().min(1).optional()\n .describe('Page number (1-based). Only used when limit is provided. Defaults to 1.'),\n detail: z.enum(['summary', 'narrative']).optional()\n .describe(\n 'Response detail level. Omit or use \"summary\" for the default fields. ' +\n 'Use \"narrative\" to receive additional context per negotiation suitable for ' +\n 'composing a digest or field report: indexContext (the community/network prompt ' +\n 'that seeded the negotiation), recentTurns (last 3 turns with action + message), ' +\n 'and outcome (for completed negotiations). These fields are populated from data ' +\n 'already loaded for the listing, so the extra cost is minimal.',\n ),\n }),\n handler: async ({ context, query }) => {\n try {\n // Map tool status filter to task state query\n const stateFilter = query.status && query.status !== 'all' ? query.status : undefined;\n // For 'active', query 'working' state tasks\n const dbState = stateFilter === 'active' ? 'working'\n : stateFilter === 'waiting_for_agent' ? 'waiting_for_agent'\n : stateFilter === 'completed' ? 'completed'\n : undefined;\n\n const tasks = await negotiationDatabase.getTasksForUser(context.userId, dbState ? { state: dbState } : undefined);\n const scopedNetworkId = focusedNetworkId(context);\n\n const negotiations = await Promise.all(tasks.map(async (task) => {\n const meta = task.metadata as {\n sourceUserId?: string;\n candidateUserId?: string;\n type?: string;\n maxTurns?: number;\n networkId?: string;\n turnContext?: { indexContext?: { networkId?: string; prompt?: string } };\n isContinuation?: boolean;\n priorTurnCount?: number;\n } | null;\n if (meta?.type !== 'negotiation') return null;\n\n // Network-scope filter: when caller's API key carries a network-bound\n // agent, drop tasks whose network differs (or whose network we cannot\n // determine — defense in depth for legacy tasks).\n if (scopedNetworkId) {\n const taskNetworkId = readTaskNetworkId(meta);\n if (taskNetworkId !== scopedNetworkId) return null;\n }\n\n const isSource = meta.sourceUserId === context.userId;\n const counterpartyId = isSource ? meta.candidateUserId : meta.sourceUserId;\n\n // Get messages for preview (and turns when narrative detail requested)\n const messages = await negotiationDatabase.getMessagesForConversation(task.conversationId);\n const lastMessage = messages[messages.length - 1];\n const lastTurnData = lastMessage\n ? ((lastMessage.parts as Array<{ kind?: string; data?: unknown }>)?.find(p => p.kind === 'data')?.data as { action?: string; assessment?: { reasoning?: string }; message?: string | null } | undefined)\n : undefined;\n\n // Determine whose turn it is from the last message's sender — not\n // parity, which misattributes across continuation sessions. Rows\n // without senderId (legacy) fall back to parity.\n const turnCount = messages.length;\n const lastSenderId = turnCount > 0 ? messages[turnCount - 1].senderId : null;\n const currentSpeaker = lastSenderId\n ? (lastSenderId === `agent:${meta.sourceUserId}` ? 'candidate' : 'source')\n : (turnCount % 2 === 0 ? 'source' : 'candidate');\n\n // Map task state to tool status\n const status = task.state === 'working' ? 'active'\n : task.state === 'waiting_for_agent' ? 'waiting_for_agent'\n : task.state === 'completed' ? 'completed'\n : task.state;\n\n const isUsersTurn = status !== 'completed' &&\n ((isSource && currentSpeaker === 'source') || (!isSource && currentSpeaker === 'candidate'));\n\n const base = {\n id: task.id,\n counterpartyId: counterpartyId ?? 'unknown',\n role: isSource ? 'source' : 'candidate',\n turnCount,\n status,\n isUsersTurn,\n isContinuation: meta.isContinuation ?? false,\n priorTurnCount: meta.priorTurnCount ?? 0,\n latestAction: lastTurnData?.action ?? null,\n latestMessagePreview: lastTurnData?.message ?? null,\n createdAt: task.createdAt,\n updatedAt: task.updatedAt,\n };\n\n if (query.detail !== 'narrative') return base;\n\n // ── Narrative extras (messages already loaded — no extra DB cost) ──\n\n const RECENT_TURNS_LIMIT = 3;\n const recentMessages = messages.slice(-RECENT_TURNS_LIMIT);\n const recentTurns = recentMessages.map((m, sliceIdx) => {\n const absoluteIdx = messages.length - recentMessages.length + sliceIdx;\n const speaker = m.senderId\n ? (m.senderId === `agent:${meta.sourceUserId}` ? 'source' : 'candidate')\n : (absoluteIdx % 2 === 0 ? 'source' : 'candidate');\n const td = ((m.parts as Array<{ kind?: string; data?: unknown }>)?.find(p => p.kind === 'data')?.data as { action?: string; message?: string | null } | undefined);\n return {\n turnNumber: absoluteIdx + 1,\n speaker,\n role: speaker === (isSource ? 'source' : 'candidate') ? 'own' : 'other',\n action: td?.action ?? 'unknown',\n message: td?.message ?? null,\n };\n });\n\n const indexContext = meta.turnContext?.indexContext ?? null;\n\n // Outcome artifact — only meaningful for completed negotiations\n let outcome: unknown = null;\n if (status === 'completed') {\n const artifacts = await negotiationDatabase.getArtifactsForTask(task.id);\n const outcomeArtifact = artifacts.find(a => a.name === 'negotiation-outcome');\n outcome = outcomeArtifact\n ? ((outcomeArtifact.parts as Array<{ kind?: string; data?: unknown }>)?.find(p => p.kind === 'data')?.data ?? null)\n : null;\n }\n\n return { ...base, indexContext, recentTurns, outcome };\n }));\n\n let filtered = negotiations.filter(Boolean);\n\n if (query.since) {\n const sinceMs = new Date(query.since).getTime();\n filtered = filtered.filter(n => new Date(n!.createdAt).getTime() >= sinceMs);\n }\n\n const shouldPaginate = query.limit !== undefined;\n if (shouldPaginate) {\n const limit = query.limit!;\n const page = query.page ?? 1;\n const offset = (page - 1) * limit;\n const paged = filtered.slice(offset, offset + limit);\n return success({\n count: paged.length,\n totalCount: filtered.length,\n limit,\n page,\n totalPages: Math.ceil(filtered.length / limit),\n negotiations: paged,\n });\n }\n\n return success({\n count: filtered.length,\n negotiations: filtered,\n });\n } catch (err) {\n logger.error('Failed to list negotiations', { err });\n return error('Failed to list negotiations. Please try again.');\n }\n },\n });\n\n const get_negotiation = defineTool({\n name: 'get_negotiation',\n description:\n 'Get the full details of a specific negotiation, including all turns, messages, counterparty info, and current state. ' +\n 'Negotiations are bilateral exchanges where two AI agents negotiate on behalf of users. Each turn contains an action ' +\n '(propose, accept, reject, counter, question), an assessment with reasoning and suggested roles, and an optional message.\\n\\n' +\n '**Access control:** You must be a party to the negotiation (source or candidate) to view it.\\n\\n' +\n '**Statuses:** `active` — in progress. `waiting_for_agent` — waiting for an agent response or timeout. `completed` — concluded.\\n\\n' +\n '**When to use:** To review the full negotiation history before responding, to understand why a negotiation was ' +\n 'accepted or rejected, or to see the current state of an active negotiation.\\n\\n' +\n '**Negotiation-turn-mode usage.** If you are running as a silent background subagent (dispatched by the ' +\n \"openclaw runtime's poller in response to a claimed negotiation turn), call this tool FIRST with the \" +\n 'negotiationId from your task prompt. This returns the current state, both parties\\' context, and the ' +\n 'history of turns so far. Ground your response in the caller\\'s profile (read_user_contexts) and intents ' +\n '(read_intents) before deciding on a turn action. Do not produce user-facing output in this mode.',\n querySchema: z.object({\n negotiationId: z.string().describe('The negotiation task ID (from list_negotiations results).'),\n }),\n handler: async ({ context, query }) => {\n try {\n const task = await negotiationDatabase.getTask(query.negotiationId);\n if (!task) {\n return error('Negotiation not found.');\n }\n\n const meta = task.metadata as {\n sourceUserId?: string;\n candidateUserId?: string;\n initiatorUserId?: string;\n protocolVersion?: string;\n type?: string;\n maxTurns?: number;\n opportunityId?: string;\n networkId?: string;\n isContinuation?: boolean;\n priorTurnCount?: number;\n turnContext?: {\n sourceUser: UserNegotiationContext;\n candidateUser: UserNegotiationContext;\n indexContext: { networkId: string; prompt?: string };\n seedAssessment: SeedAssessment;\n discoveryQuery?: string;\n };\n } | null;\n if (meta?.type !== 'negotiation') {\n return error('Negotiation not found.');\n }\n\n // Network-scope check: a network-bound agent must not read negotiations\n // outside its bound network. Run before the participant check so we\n // don't leak existence-vs-membership signal across scopes.\n const scopedNetworkId = focusedNetworkId(context);\n if (scopedNetworkId) {\n const taskNetworkId = readTaskNetworkId(meta);\n if (taskNetworkId !== scopedNetworkId) {\n return error(SCOPE_DENIAL);\n }\n }\n\n // Access control: user must be source or candidate\n const isSource = meta.sourceUserId === context.userId;\n const isCandidate = meta.candidateUserId === context.userId;\n if (!isSource && !isCandidate) {\n return error('Access denied: you are not a party to this negotiation.');\n }\n\n const counterpartyId = isSource ? meta.candidateUserId : meta.sourceUserId;\n\n // Project absolute turn context (source/candidate) into own/other\n // perspective for the caller. Mirrors what the in-process system\n // agent receives as NegotiationAgentInput — identical context means\n // identical deliberation on both paths.\n let negotiationContext: {\n ownUser: UserNegotiationContext;\n otherUser: UserNegotiationContext;\n indexContext: { networkId: string; prompt?: string };\n seedAssessment: SeedAssessment;\n isDiscoverer: boolean;\n discoveryQuery?: string;\n } | null = null;\n if (meta.turnContext) {\n const tc = meta.turnContext;\n negotiationContext = {\n ownUser: isSource ? tc.sourceUser : tc.candidateUser,\n otherUser: isSource ? tc.candidateUser : tc.sourceUser,\n indexContext: tc.indexContext,\n seedAssessment: tc.seedAssessment,\n isDiscoverer: isSource,\n ...(tc.discoveryQuery && { discoveryQuery: tc.discoveryQuery }),\n };\n }\n\n // Load messages and artifacts\n const [messages, artifacts] = await Promise.all([\n negotiationDatabase.getMessagesForConversation(task.conversationId),\n negotiationDatabase.getArtifactsForTask(task.id),\n ]);\n\n // Parse turns from messages (speaker from senderId, not parity —\n // continuations can start with either side speaking first)\n const turns = messages.map((m, idx) => {\n const dataPart = (m.parts as Array<{ kind?: string; data?: unknown }>)?.find(p => p.kind === 'data');\n const turnData = dataPart?.data as {\n action?: string;\n assessment?: { reasoning?: string; suggestedRoles?: unknown };\n message?: string;\n } | undefined;\n\n const turnNumber = idx + 1;\n const speaker = m.senderId\n ? (m.senderId === `agent:${meta.sourceUserId}` ? 'source' : 'candidate')\n : (turnNumber % 2 === 1 ? 'source' : 'candidate');\n\n return {\n turnNumber,\n speaker,\n senderId: m.senderId,\n action: turnData?.action ?? 'unknown',\n reasoning: turnData?.assessment?.reasoning ?? null,\n suggestedRoles: turnData?.assessment?.suggestedRoles ?? null,\n message: turnData?.message ?? null,\n createdAt: m.createdAt,\n };\n });\n\n // Extract outcome from artifacts if completed\n const outcomeArtifact = artifacts.find(a => a.name === 'negotiation-outcome');\n const outcome = outcomeArtifact\n ? (outcomeArtifact.parts as Array<{ kind?: string; data?: unknown }>)?.find(p => p.kind === 'data')?.data\n : null;\n\n // Determine whose turn it is (last sender's counterpart, not parity;\n // rows without senderId fall back to parity)\n const turnCount = messages.length;\n const lastSenderId = turnCount > 0 ? messages[turnCount - 1].senderId : null;\n const currentSpeaker = lastSenderId\n ? (lastSenderId === `agent:${meta.sourceUserId}` ? 'candidate' : 'source')\n : (turnCount % 2 === 0 ? 'source' : 'candidate');\n\n const status = task.state === 'working' ? 'active'\n : task.state === 'waiting_for_agent' ? 'waiting_for_agent'\n : task.state === 'completed' ? 'completed'\n : task.state;\n\n const isUsersTurn = status !== 'completed' &&\n ((isSource && currentSpeaker === 'source') || (!isSource && currentSpeaker === 'candidate'));\n\n const isContinuation = meta.isContinuation ?? false;\n const priorTurnCount = meta.priorTurnCount ?? 0;\n\n // Seat + protocol version (v2 client-advocate): announce the caller's\n // seat and the actions it may submit so agents don't guess.\n const protocolVersion = readProtocolVersion(meta) ?? 'v1';\n const seat = resolveSeat(context.userId, meta);\n\n return success({\n id: task.id,\n conversationId: task.conversationId,\n status,\n role: isSource ? 'source' : 'candidate',\n seat,\n protocolVersion,\n allowedActions: allowedActionsFor(protocolVersion, seat),\n counterpartyId: counterpartyId ?? 'unknown',\n turnCount,\n isUsersTurn,\n isContinuation,\n priorTurnCount,\n turnsAdded: turnCount - priorTurnCount,\n turns,\n outcome,\n context: negotiationContext,\n createdAt: task.createdAt,\n updatedAt: task.updatedAt,\n });\n } catch (err) {\n logger.error('Failed to get negotiation', { err });\n return error('Failed to get negotiation. Please try again.');\n }\n },\n });\n\n const respond_to_negotiation = defineTool({\n name: 'respond_to_negotiation',\n description:\n 'Respond to a negotiation that is waiting for agent input. This tool allows users to influence the negotiation ' +\n 'by accepting, rejecting, countering, or asking a clarifying question.\\n\\n' +\n '**Turn-based model:** Negotiations alternate between source and candidate agents. When the graph yields with ' +\n '`waiting_for_agent` status, the user whose turn it is can respond.\\n\\n' +\n '**Valid actions depend on the negotiation protocol version and your seat** — call get_negotiation first: ' +\n 'its `seat`, `protocolVersion`, and `allowedActions` fields tell you exactly what you may submit.\\n\\n' +\n '**v1 negotiations (legacy):** `propose | accept | reject | counter | question` — on the first turn the action MUST be `propose`.\\n\\n' +\n '**v2 negotiations (client-advocate seat rules):**\\n' +\n '- Initiator seat (`outreach | counter | question | withdraw`): you reached out — you can NEVER accept. ' +\n '`outreach` opens the negotiation; `withdraw` ends it without an opportunity.\\n' +\n '- Counterparty seat (`accept | decline | counter | question`): only your seat can `accept` (finalizes an opportunity); ' +\n '`decline` ends the negotiation without one.\\n\\n' +\n '- `counter` — Counter with a message (message is required). The negotiation continues.\\n' +\n '- `question` — Ask the other side a clarifying question (message is required). The negotiation continues.\\n\\n' +\n '**What happens after:** Terminal actions (accept/reject/withdraw/decline) finalize the negotiation immediately. ' +\n 'Counter/question continues — if the counterparty has an agent, the negotiation yields again; otherwise the AI agent responds inline.\\n\\n' +\n '**Silent-subagent response contract.** In negotiation-turn mode, submit exactly ONE call to this tool ' +\n 'per dispatch with an action from your seat\\'s allowed set and the assessment (reasoning + suggestedRoles). ' +\n 'If the decision is ambiguous, pick the most conservative action — usually `counter` with specific objections. ' +\n 'Do not ask the user clarifying questions; you are authorized to act on their behalf within the scope granted to your agent.',\n querySchema: z.object({\n negotiationId: z.string().describe('The negotiation task ID to respond to.'),\n action: z.enum(NEGOTIATION_ACTIONS).describe('The response action. Must be within your seat\\'s allowedActions (see get_negotiation). v1 first turn MUST be \"propose\"; v2 initiator first turn MUST be \"outreach\".'),\n reasoning: z.string().describe('Why you are taking this action — your assessment of the opportunity.'),\n suggestedRoles: z.object({\n ownUser: z.enum(['agent', 'patient', 'peer']).describe('Suggested role for your user in this opportunity.'),\n otherUser: z.enum(['agent', 'patient', 'peer']).describe('Suggested role for the other user in this opportunity.'),\n }).describe('Role suggestions for both parties.'),\n message: z.string().optional().describe('Required for \"counter\" and \"question\" actions. Your message explaining what you want to change or clarify.'),\n }),\n handler: async ({ context, query }) => {\n try {\n const task = await negotiationDatabase.getTask(query.negotiationId);\n if (!task) {\n return error('Negotiation not found.');\n }\n\n const meta = task.metadata as {\n sourceUserId?: string;\n candidateUserId?: string;\n initiatorUserId?: string;\n protocolVersion?: string;\n type?: string;\n maxTurns?: number;\n networkId?: string;\n turnContext?: { indexContext?: { networkId?: string } };\n } | null;\n if (meta?.type !== 'negotiation') {\n return error('Negotiation not found.');\n }\n\n // Network-scope check (mirrors get_negotiation): a network-bound agent\n // must not act on negotiations outside its bound network.\n const scopedNetworkId = focusedNetworkId(context);\n if (scopedNetworkId) {\n const taskNetworkId = readTaskNetworkId(meta);\n if (taskNetworkId !== scopedNetworkId) {\n return error(SCOPE_DENIAL);\n }\n }\n\n // Validate negotiation is waiting for agent input (or claimed via polling)\n if (task.state !== 'waiting_for_agent' && task.state !== 'claimed') {\n return error(`Negotiation is not waiting for a response. Current status: ${task.state}`);\n }\n\n // Access control: user must be a party\n const isSource = meta.sourceUserId === context.userId;\n const isCandidate = meta.candidateUserId === context.userId;\n if (!isSource && !isCandidate) {\n return error('Access denied: you are not a party to this negotiation.');\n }\n\n // Seat + version validation (v2 client-advocate): the submitted action\n // must be within the caller's seat vocabulary. v1 tasks accept the\n // legacy vocabulary unchanged (grandfathered).\n const protocolVersion = readProtocolVersion(meta) ?? 'v1';\n const seat = resolveSeat(context.userId, meta);\n if (!allowedActionsFor(protocolVersion, seat).includes(query.action)) {\n return error(seatViolationMessage(query.action, seat, protocolVersion));\n }\n\n // Determine whose turn it is from the last message's sender — not\n // parity, which misattributes across continuation sessions. Rows\n // without senderId (legacy) fall back to the parity heuristic.\n const messages = await negotiationDatabase.getMessagesForConversation(task.conversationId);\n const turnCount = messages.length;\n const lastSenderId = turnCount > 0 ? messages[turnCount - 1].senderId : null;\n const paritySpeaker = turnCount % 2 === 0 ? 'source' : 'candidate';\n const isUsersTurn = lastSenderId\n ? lastSenderId !== `agent:${context.userId}`\n : ((isSource && paritySpeaker === 'source') || (!isSource && paritySpeaker === 'candidate'));\n\n if (!isUsersTurn) {\n return error('It is not your turn to respond in this negotiation.');\n }\n\n // The caller is the current speaker (verified above).\n const currentSpeaker: 'source' | 'candidate' = isSource ? 'source' : 'candidate';\n\n // Validate counter/question has a message\n if ((query.action === 'counter' || query.action === 'question') && !query.message?.trim()) {\n return error(`A message is required when using \"${query.action}\". Explain what you want to change or clarify.`);\n }\n\n // ── Cancel pending timeout ──\n if (deps.negotiationTimeoutQueue) {\n await deps.negotiationTimeoutQueue.cancelTimeout(task.id);\n }\n\n // ── Build and persist the external agent's turn ──\n const turnData: NegotiationTurn = {\n action: query.action,\n assessment: {\n reasoning: query.reasoning,\n suggestedRoles: query.suggestedRoles,\n },\n ...(query.message ? { message: query.message } : {}),\n };\n\n const senderId = `agent:${context.userId}`;\n const turnMessage = await negotiationDatabase.createMessage({\n conversationId: task.conversationId,\n senderId,\n role: 'agent',\n parts: [{ kind: 'data' as const, data: turnData }],\n taskId: task.id,\n });\n\n const newTurnCount = turnCount + 1;\n\n // ── Handle terminal actions (accept / reject / withdraw / decline): finalize immediately ──\n if (isTerminalAction(query.action)) {\n const allMessages = [...messages, { id: turnMessage.id, senderId: turnMessage.senderId, role: turnMessage.role, parts: turnMessage.parts as unknown[], createdAt: turnMessage.createdAt }];\n const history: NegotiationTurn[] = turnsFromMessages(allMessages);\n\n const nextSpeaker = currentSpeaker === 'source' ? 'candidate' : 'source';\n const outcome = buildNegotiationOutcome(history, newTurnCount, query.action, meta.sourceUserId!, meta.candidateUserId!, nextSpeaker);\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: outcome.hasOpportunity, turnCount: newTurnCount },\n });\n\n return success({\n message: query.action === 'accept'\n ? 'Negotiation accepted. An opportunity has been created.'\n : query.action === 'withdraw'\n ? 'Negotiation withdrawn.'\n : query.action === 'decline'\n ? 'Negotiation declined.'\n : 'Negotiation rejected.',\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n outcome,\n });\n }\n\n // ── Handle counter/question: check if under max turns ──\n const maxTurns = meta.maxTurns ?? 6; // Read from task metadata; fallback to system default\n if (newTurnCount >= maxTurns) {\n // Max turns reached — finalize with turn_cap\n const allMessages = [...messages, { id: turnMessage.id, senderId: turnMessage.senderId, role: turnMessage.role, parts: turnMessage.parts as unknown[], createdAt: turnMessage.createdAt }];\n const history: NegotiationTurn[] = turnsFromMessages(allMessages);\n\n const nextSpeakerForCap = currentSpeaker === 'source' ? 'candidate' : 'source';\n const outcome = buildNegotiationOutcome(history, newTurnCount, 'counter', meta.sourceUserId!, meta.candidateUserId!, nextSpeakerForCap);\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: false, turnCount: newTurnCount },\n });\n\n return success({\n message: 'Maximum turns reached. Negotiation finalized without opportunity.',\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n outcome,\n });\n }\n\n // ── Counter/question under max turns: dispatch to counterparty's agent ──\n const counterpartyUserId = isSource ? meta.candidateUserId! : meta.sourceUserId!;\n const counterpartySpeaker = isSource ? 'candidate' : 'source';\n const counterpartySeat = resolveSeat(counterpartyUserId, meta);\n\n // Build the current turn history for dispatcher payload\n const allMessagesWithTurn = [...messages, { id: turnMessage.id, senderId: turnMessage.senderId, role: turnMessage.role, parts: turnMessage.parts as unknown[], createdAt: turnMessage.createdAt }];\n const historyForDispatch: NegotiationTurn[] = turnsFromMessages(allMessagesWithTurn);\n\n const isFinalTurn = newTurnCount + 1 >= maxTurns;\n\n const ownUserCtx: UserNegotiationContext = { id: counterpartyUserId, intents: [], profile: {} };\n const otherUserCtx: UserNegotiationContext = { id: context.userId, intents: [], profile: {} };\n const seedAssessment: SeedAssessment = { reasoning: 'Continued negotiation', valencyRole: 'peer' };\n\n const dispatchPayload: NegotiationTurnPayload = {\n negotiationId: task.id,\n ownUser: ownUserCtx,\n otherUser: otherUserCtx,\n indexContext: { networkId: '' },\n seedAssessment,\n history: historyForDispatch,\n isFinalTurn,\n isDiscoverer: false,\n seat: counterpartySeat,\n protocolVersion,\n allowedActions: [...allowedActionsFor(protocolVersion, counterpartySeat, isFinalTurn)],\n };\n\n const scope = { action: 'negotiation.respond', scopeType: 'negotiation', scopeId: task.id };\n const timeoutMs = AMBIENT_PARK_WINDOW_MS;\n\n const dispatchResult = await deps.agentDispatcher?.dispatch(counterpartyUserId, scope, dispatchPayload, { timeoutMs });\n\n if (dispatchResult?.handled === false && dispatchResult.reason === 'waiting') {\n // Counterparty's agent acknowledged — yield and wait\n await negotiationDatabase.updateTaskState(task.id, 'waiting_for_agent');\n\n if (deps.negotiationTimeoutQueue) {\n await deps.negotiationTimeoutQueue.enqueueTimeout(task.id, newTurnCount, timeoutMs);\n }\n\n return success({\n message: `${query.action === 'question' ? 'Question' : query.action === 'propose' ? 'Proposal' : query.action === 'outreach' ? 'Outreach' : 'Counter-proposal'} submitted. Waiting for counterparty response.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n waitingForAgent: true,\n });\n }\n\n let aiTurn: NegotiationTurn;\n\n if (dispatchResult?.handled === true) {\n // Dispatcher returned an agent turn directly\n aiTurn = dispatchResult.turn;\n } else {\n // No agent or timeout — run the system AI agent inline.\n // The agent honors a per-turn LLM timeout (AbortSignal), so invoke\n // can reject. Mirror the graph turnNode's reject-shaped fallback so\n // a timed-out or failed call degrades gracefully instead of leaving\n // the task pinned in `working` while the outer catch returns a bare\n // error to the user.\n await negotiationDatabase.updateTaskState(task.id, 'working');\n\n const agent = new IndexNegotiator();\n try {\n aiTurn = await agent.invoke({\n ownUser: ownUserCtx,\n otherUser: otherUserCtx,\n indexContext: { networkId: '' },\n seedAssessment,\n history: historyForDispatch,\n isFinalTurn,\n seat: counterpartySeat,\n protocolVersion,\n });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n const errName = (err as { name?: string })?.name ?? '';\n const isTimeout = errName === 'TimeoutError' || /timeout|abort/i.test(errMsg);\n // Log the raw error for ops, but keep the persisted/returned\n // reasoning generic — this string round-trips back to the caller\n // via counterpartyResponse.reasoning and ends up in the negotiation\n // history visible through get_negotiation, so we don't want raw\n // provider messages (URLs, request IDs, internal stack hints) on\n // the wire.\n logger.warn('System negotiator inline invoke failed; treating as reject', {\n taskId: task.id,\n isTimeout,\n error: errMsg,\n });\n aiTurn = {\n action: rejectActionFor(protocolVersion, counterpartySeat),\n assessment: {\n reasoning: isTimeout\n ? 'Negotiator response timed out.'\n : 'Negotiator failed to produce a response.',\n suggestedRoles: { ownUser: 'peer', otherUser: 'peer' },\n },\n };\n }\n }\n\n // Persist the counterparty's turn (from dispatcher or inline AI)\n const aiSenderId = `agent:${counterpartyUserId}`;\n await negotiationDatabase.createMessage({\n conversationId: task.conversationId,\n senderId: aiSenderId,\n role: 'agent',\n parts: [{ kind: 'data' as const, data: aiTurn }],\n taskId: task.id,\n });\n\n const finalTurnCount = newTurnCount + 1;\n\n // Evaluate response\n if (isTerminalAction(aiTurn.action)) {\n const fullHistory = [...historyForDispatch, aiTurn];\n const outcome = buildNegotiationOutcome(fullHistory, finalTurnCount, aiTurn.action, meta.sourceUserId!, meta.candidateUserId!, counterpartySpeaker === 'source' ? 'candidate' : 'source');\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: outcome.hasOpportunity, turnCount: finalTurnCount },\n });\n\n return success({\n message: `${query.action === 'question' ? 'Question' : query.action === 'propose' ? 'Proposal' : 'Counter'} submitted. Counterparty responded with ${aiTurn.action}.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n outcome,\n });\n }\n\n // Counterparty countered/questioned — check if max turns reached\n if (finalTurnCount >= maxTurns) {\n const fullHistory = [...historyForDispatch, aiTurn];\n const outcome = buildNegotiationOutcome(fullHistory, finalTurnCount, 'counter', meta.sourceUserId!, meta.candidateUserId!, counterpartySpeaker === 'source' ? 'candidate' : 'source');\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: false, turnCount: finalTurnCount },\n });\n\n return success({\n message: 'Counterparty responded but max turns reached. Negotiation finalized.',\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n outcome,\n });\n }\n\n // Counterparty countered/questioned, now user's turn again — dispatch to user's agent\n const userDispatchPayload: NegotiationTurnPayload = {\n negotiationId: task.id,\n ownUser: { id: context.userId, intents: [], profile: {} },\n otherUser: { id: counterpartyUserId, intents: [], profile: {} },\n indexContext: { networkId: '' },\n seedAssessment,\n history: [...historyForDispatch, aiTurn],\n isFinalTurn: finalTurnCount + 1 >= maxTurns,\n isDiscoverer: true,\n seat,\n protocolVersion,\n allowedActions: [...allowedActionsFor(protocolVersion, seat, finalTurnCount + 1 >= maxTurns)],\n };\n\n const userDispatchResult = await deps.agentDispatcher?.dispatch(context.userId, scope, userDispatchPayload, { timeoutMs });\n\n if (!userDispatchResult || (userDispatchResult.handled === false && userDispatchResult.reason === 'no_agent')) {\n // No agent for user — set back to waiting_for_agent so they can use respond_to_negotiation\n await negotiationDatabase.updateTaskState(task.id, 'waiting_for_agent');\n\n if (deps.negotiationTimeoutQueue) {\n await deps.negotiationTimeoutQueue.enqueueTimeout(task.id, finalTurnCount, timeoutMs);\n }\n\n return success({\n message: `${query.action === 'question' ? 'Question' : 'Counter'} submitted. Counterparty responded. Your turn to respond.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n waitingForAgent: true,\n });\n }\n\n if (userDispatchResult.handled === false && userDispatchResult.reason === 'waiting') {\n // User's agent acknowledged — yield and wait\n await negotiationDatabase.updateTaskState(task.id, 'waiting_for_agent');\n\n if (deps.negotiationTimeoutQueue) {\n await deps.negotiationTimeoutQueue.enqueueTimeout(task.id, finalTurnCount, timeoutMs);\n }\n\n return success({\n message: `${query.action === 'question' ? 'Question' : 'Counter'} submitted. Counterparty countered back. Waiting for your agent's response.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n waitingForAgent: true,\n });\n }\n\n if (userDispatchResult.handled === true) {\n // User's agent returned a turn directly — persist, evaluate, and continue\n const userAgentTurn: NegotiationTurn = userDispatchResult.turn;\n const userAgentSenderId = `agent:${context.userId}`;\n await negotiationDatabase.createMessage({\n conversationId: task.conversationId,\n senderId: userAgentSenderId,\n role: 'agent',\n parts: [{ kind: 'data' as const, data: userAgentTurn }],\n taskId: task.id,\n });\n\n const userTurnCount = finalTurnCount + 1;\n\n if (isTerminalAction(userAgentTurn.action)) {\n const fullHistory = [...historyForDispatch, aiTurn, userAgentTurn];\n const userSpeaker = isSource ? 'source' : 'candidate';\n const outcome = buildNegotiationOutcome(fullHistory, userTurnCount, userAgentTurn.action, meta.sourceUserId!, meta.candidateUserId!, userSpeaker === 'source' ? 'candidate' : 'source');\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: outcome.hasOpportunity, turnCount: userTurnCount },\n });\n\n return success({\n message: `Your agent ${userAgentTurn.action}ed the counterparty's response.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n outcome,\n });\n }\n\n if (userTurnCount >= maxTurns) {\n const fullHistory = [...historyForDispatch, aiTurn, userAgentTurn];\n const outcome = buildNegotiationOutcome(fullHistory, userTurnCount, 'counter', meta.sourceUserId!, meta.candidateUserId!, isSource ? 'candidate' : 'source');\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: false, turnCount: userTurnCount },\n });\n\n return success({\n message: 'Your agent responded but max turns reached. Negotiation finalized.',\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n outcome,\n });\n }\n\n // User's agent countered/questioned — arm timeout for counterparty's next turn\n await negotiationDatabase.updateTaskState(task.id, 'waiting_for_agent');\n\n if (deps.negotiationTimeoutQueue) {\n await deps.negotiationTimeoutQueue.enqueueTimeout(task.id, userTurnCount, timeoutMs);\n }\n\n return success({\n message: `Your agent responded with ${userAgentTurn.action}. Waiting for counterparty.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n waitingForAgent: true,\n });\n }\n\n // No agent / timeout — set back to working so graph can continue\n await negotiationDatabase.updateTaskState(task.id, 'working');\n\n return success({\n message: `${query.action === 'question' ? 'Question' : 'Counter'} submitted. Counterparty countered back. Negotiation continues.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n });\n } catch (err) {\n logger.error('Failed to respond to negotiation', { err });\n return error('Failed to respond to negotiation. Please try again.');\n }\n },\n });\n\n return [list_negotiations, get_negotiation, respond_to_negotiation] as const;\n}\n\n/**\n * Build a NegotiationOutcome from the full turn history.\n * Mirrors the logic in the graph's finalizeNode for consistency.\n *\n * @param history - All negotiation turns\n * @param turnCount - Total number of turns\n * @param lastAction - The last turn's action (accept/reject/counter)\n * @param sourceUserId - Source user ID\n * @param candidateUserId - Candidate user ID\n * @param currentSpeaker - Who would speak next (the person after the accepter/rejector)\n */\nfunction buildNegotiationOutcome(\n history: NegotiationTurn[],\n turnCount: number,\n lastAction: string,\n sourceUserId: string,\n candidateUserId: string,\n currentSpeaker: string,\n): NegotiationOutcome {\n const hasOpportunity = lastAction === 'accept';\n // Non-terminal last action at finalization means the turn cap was hit.\n const atCap = !isTerminalAction(lastAction);\n\n let agreedRoles: NegotiationOutcome['agreedRoles'] = [];\n if (hasOpportunity && history.length >= 2) {\n const acceptTurn = history[history.length - 1];\n const precedingTurn = history[history.length - 2];\n const accepterIsSource = currentSpeaker === 'candidate';\n const [sourceRole, candidateRole] = accepterIsSource\n ? [acceptTurn.assessment.suggestedRoles.ownUser, precedingTurn.assessment.suggestedRoles.ownUser]\n : [precedingTurn.assessment.suggestedRoles.ownUser, acceptTurn.assessment.suggestedRoles.ownUser];\n agreedRoles = [\n { userId: sourceUserId, role: sourceRole },\n { userId: candidateUserId, role: candidateRole },\n ];\n }\n\n return {\n hasOpportunity,\n agreedRoles,\n reasoning: history[history.length - 1]?.assessment.reasoning ?? '',\n turnCount,\n ...(atCap && { reason: 'turn_cap' }),\n };\n}\n"]}
1
+ {"version":3,"file":"negotiation.tools.js","sourceRoot":"/","sources":["negotiation/negotiation.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,eAAe,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACzJ,OAAO,EAAE,mBAAmB,EAAE,MAAM,+CAA+C,CAAC;AAEpF,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAElF,MAAM,MAAM,GAAG,cAAc,CAAC,uBAAuB,CAAC,CA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M,IAAI,CAAC,EAAE,CAAC;QAC1C,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC/C,MAAM,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAClD,MAAM,gBAAgB,GAAG,cAAc,KAAK,WAAW,CAAC;QACxD,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,gBAAgB;YAClD,CAAC,CAAC,CAAC,UAAU,CAAC,UAAU,CAAC,cAAc,CAAC,OAAO,EAAE,aAAa,CAAC,UAAU,CAAC,cAAc,CAAC,OAAO,CAAC;YACjG,CAAC,CAAC,CAAC,aAAa,CAAC,UAAU,CAAC,cAAc,CAAC,OAAO,EAAE,UAAU,CAAC,UAAU,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;QACpG,WAAW,GAAG;YACZ,EAAE,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,UAAU,EAAE;YAC1C,EAAE,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,aAAa,EAAE;SACjD,CAAC;IACJ,CAAC;IAED,OAAO;QACL,cAAc;QACd,WAAW;QACX,SAAS,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC,SAAS,IAAI,EAAE;QAClE,SAAS;QACT,GAAG,CAAC,KAAK,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;KACrC,CAAC;AACJ,CAAC","sourcesContent":["import { z } from 'zod';\n\nimport type { DefineTool, ToolDeps } from '../shared/agent/tool.helpers.js';\nimport { success, error } from '../shared/agent/tool.helpers.js';\nimport { IndexNegotiator } from './negotiation.agent.js';\nimport type { NegotiationTurn, UserNegotiationContext, SeedAssessment, NegotiationOutcome } from './negotiation.state.js';\nimport { allowedActionsFor, isTerminalAction, readProtocolVersion, rejectActionFor, resolveSeat, seatViolationMessage } from './negotiation.protocol.js';\nimport { NEGOTIATION_ACTIONS } from '../shared/schemas/negotiation-state.schema.js';\nimport type { NegotiationTurnPayload } from '../shared/interfaces/agent-dispatcher.interface.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\nimport { focusedIntentId, focusedNetworkId } from '../shared/agent/tool.scope.js';\n\nconst logger = protocolLogger('ChatTools:Negotiation');\n\n/**\n * Default park-window budget for ambient (background) negotiations. When a personal\n * agent is fresh, the dispatcher parks the turn and this is how long we wait before\n * the system agent takes over as a fallback.\n *\n * Short enough that ambient opportunities materialize in minutes (not hours),\n * long enough to cover two full polling cycles (30s * 2 = 60s) plus an agent\n * subagent turn. 5 minutes gives generous headroom.\n */\nexport const AMBIENT_PARK_WINDOW_MS = 5 * 60 * 1000;\n\n/**\n * Pulls the negotiation's network from task metadata. Tasks created after the\n * scope hardening carry `metadata.networkId` directly; older tasks only have\n * the network embedded in the parked `turnContext.indexContext.networkId`.\n * Returns `null` for legacy tasks where neither field is present — callers\n * scoped by the request scope envelope must reject these defensively rather than\n * fall through to a global view.\n */\nfunction readTaskNetworkId(meta: {\n networkId?: string;\n turnContext?: { indexContext?: { networkId?: string } };\n} | null): string | null {\n if (!meta) return null;\n if (typeof meta.networkId === 'string' && meta.networkId.trim()) return meta.networkId;\n const fromTurnContext = meta.turnContext?.indexContext?.networkId;\n if (typeof fromTurnContext === 'string' && fromTurnContext.trim()) return fromTurnContext;\n return null;\n}\n\nconst SCOPE_DENIAL = 'Access denied: this negotiation is not in your bound network scope.';\n\n/** Extracts the ordered NegotiationTurn list from A2A message data parts. */\nfunction turnsFromMessages(messages: Array<{ parts: unknown[] }>): NegotiationTurn[] {\n return messages\n .map((m) => {\n const dp = (m.parts as Array<{ kind?: string; data?: unknown }>)?.find((p) => p.kind === 'data');\n return dp?.data as NegotiationTurn;\n })\n .filter(Boolean);\n}\n\n/**\n * Creates negotiation MCP tools for external agent access.\n * Exposes negotiation state for listing, reading, and responding to bilateral negotiations.\n */\nexport function createNegotiationTools(defineTool: DefineTool, deps: ToolDeps) {\n const { negotiationDatabase } = deps;\n\n const list_negotiations = defineTool({\n name: 'list_negotiations',\n description:\n 'List bilateral negotiations the authenticated user is involved in, either as the source (initiator) or candidate (responder). ' +\n 'Negotiations are turn-based exchanges where two AI agents negotiate on behalf of their users to determine if there is a ' +\n 'mutual opportunity for collaboration.\\n\\n' +\n '**Statuses:**\\n' +\n '- `active` — Negotiation is in progress, agents are exchanging turns.\\n' +\n '- `waiting_for_agent` — The graph has yielded and is waiting for an agent response (e.g. from the user via respond_to_negotiation) or a timeout.\\n' +\n '- `completed` — Negotiation has concluded (accepted, rejected, or reached turn cap).\\n\\n' +\n '**When to use:** To see ongoing and past negotiations, check which negotiations need attention, ' +\n 'or find a negotiation ID for get_negotiation or respond_to_negotiation.',\n querySchema: z.object({\n status: z.enum(['active', 'waiting_for_agent', 'completed', 'all']).optional()\n .describe('Filter by negotiation status. Omit or use \"all\" to return all negotiations.'),\n scope: z.enum(['signal', 'all']).optional()\n .describe('Scope to the pinned signal (requires an intent-pinned session), or pass \"all\" for the full negotiation history.'),\n since: z.string().datetime().optional()\n .describe('ISO 8601 date-time. Only return negotiations created at or after this timestamp.'),\n limit: z.number().int().min(1).max(100).optional()\n .describe('Maximum negotiations to return per page (1-100). Omit to return all.'),\n page: z.number().int().min(1).optional()\n .describe('Page number (1-based). Only used when limit is provided. Defaults to 1.'),\n detail: z.enum(['summary', 'narrative']).optional()\n .describe(\n 'Response detail level. Omit or use \"summary\" for the default fields. ' +\n 'Use \"narrative\" to receive additional context per negotiation suitable for ' +\n 'composing a digest or field report: indexContext (the community/network prompt ' +\n 'that seeded the negotiation), recentTurns (last 3 turns with action + message), ' +\n 'and outcome (for completed negotiations). These fields are populated from data ' +\n 'already loaded for the listing, so the extra cost is minimal.',\n ),\n }),\n handler: async ({ context, query }) => {\n try {\n // Map tool status filter to task state query\n const stateFilter = query.status && query.status !== 'all' ? query.status : undefined;\n // For 'active', query 'working' state tasks\n const dbState = stateFilter === 'active' ? 'working'\n : stateFilter === 'waiting_for_agent' ? 'waiting_for_agent'\n : stateFilter === 'completed' ? 'completed'\n : undefined;\n\n const tasks = await negotiationDatabase.getTasksForUser(context.userId, dbState ? { state: dbState } : undefined);\n const scopedNetworkId = focusedNetworkId(context);\n const pinnedIntentId = focusedIntentId(context);\n const effectiveScope = query.scope ?? (pinnedIntentId ? 'signal' : 'all');\n if (effectiveScope === 'signal' && !pinnedIntentId) {\n return error('Signal scope requires a pinned intent.');\n }\n\n const signalIntentIdsByOpportunity = effectiveScope === 'signal'\n ? await negotiationDatabase.getIntentIdsForOpportunities(\n [...new Set(tasks\n .map((task) => (task.metadata as { opportunityId?: unknown } | null)?.opportunityId)\n .filter((opportunityId): opportunityId is string => typeof opportunityId === 'string' && opportunityId.trim().length > 0))],\n context.userId,\n )\n : null;\n const scopeMetadata = effectiveScope === 'signal'\n ? { scope: 'signal' as const, intentId: pinnedIntentId! }\n : { scope: 'all' as const };\n\n const negotiations = await Promise.all(tasks.map(async (task) => {\n const meta = task.metadata as {\n sourceUserId?: string;\n candidateUserId?: string;\n type?: string;\n maxTurns?: number;\n opportunityId?: string;\n networkId?: string;\n turnContext?: { indexContext?: { networkId?: string; prompt?: string } };\n isContinuation?: boolean;\n priorTurnCount?: number;\n } | null;\n if (meta?.type !== 'negotiation') return null;\n\n // Network-scope filter: when caller's API key carries a network-bound\n // agent, drop tasks whose network differs (or whose network we cannot\n // determine — defense in depth for legacy tasks).\n if (scopedNetworkId) {\n const taskNetworkId = readTaskNetworkId(meta);\n if (taskNetworkId !== scopedNetworkId) return null;\n }\n\n // Intent-scope filter: a pinned negotiator workspace only shows\n // opportunity-bound tasks whose actor intent belongs to this user and\n // matches the pinned signal. Tasks without resolvable provenance are\n // dropped rather than widened into the user's full history.\n const opportunityId = typeof meta.opportunityId === 'string' ? meta.opportunityId.trim() : '';\n if (effectiveScope === 'signal'\n && (!opportunityId || signalIntentIdsByOpportunity?.[opportunityId] !== pinnedIntentId)) {\n return null;\n }\n\n const isSource = meta.sourceUserId === context.userId;\n const counterpartyId = isSource ? meta.candidateUserId : meta.sourceUserId;\n\n // Get messages for preview (and turns when narrative detail requested)\n const messages = await negotiationDatabase.getMessagesForConversation(task.conversationId);\n const lastMessage = messages[messages.length - 1];\n const lastTurnData = lastMessage\n ? ((lastMessage.parts as Array<{ kind?: string; data?: unknown }>)?.find(p => p.kind === 'data')?.data as { action?: string; assessment?: { reasoning?: string }; message?: string | null } | undefined)\n : undefined;\n\n // Determine whose turn it is from the last message's sender — not\n // parity, which misattributes across continuation sessions. Rows\n // without senderId (legacy) fall back to parity.\n const turnCount = messages.length;\n const lastSenderId = turnCount > 0 ? messages[turnCount - 1].senderId : null;\n const currentSpeaker = lastSenderId\n ? (lastSenderId === `agent:${meta.sourceUserId}` ? 'candidate' : 'source')\n : (turnCount % 2 === 0 ? 'source' : 'candidate');\n\n // Map task state to tool status\n const status = task.state === 'working' ? 'active'\n : task.state === 'waiting_for_agent' ? 'waiting_for_agent'\n : task.state === 'completed' ? 'completed'\n : task.state;\n\n const isUsersTurn = status !== 'completed' &&\n ((isSource && currentSpeaker === 'source') || (!isSource && currentSpeaker === 'candidate'));\n\n const base = {\n id: task.id,\n counterpartyId: counterpartyId ?? 'unknown',\n role: isSource ? 'source' : 'candidate',\n turnCount,\n status,\n isUsersTurn,\n isContinuation: meta.isContinuation ?? false,\n priorTurnCount: meta.priorTurnCount ?? 0,\n latestAction: lastTurnData?.action ?? null,\n latestMessagePreview: lastTurnData?.message ?? null,\n createdAt: task.createdAt,\n updatedAt: task.updatedAt,\n };\n\n if (query.detail !== 'narrative') return base;\n\n // ── Narrative extras (messages already loaded — no extra DB cost) ──\n\n const RECENT_TURNS_LIMIT = 3;\n const recentMessages = messages.slice(-RECENT_TURNS_LIMIT);\n const recentTurns = recentMessages.map((m, sliceIdx) => {\n const absoluteIdx = messages.length - recentMessages.length + sliceIdx;\n const speaker = m.senderId\n ? (m.senderId === `agent:${meta.sourceUserId}` ? 'source' : 'candidate')\n : (absoluteIdx % 2 === 0 ? 'source' : 'candidate');\n const td = ((m.parts as Array<{ kind?: string; data?: unknown }>)?.find(p => p.kind === 'data')?.data as { action?: string; message?: string | null } | undefined);\n return {\n turnNumber: absoluteIdx + 1,\n speaker,\n role: speaker === (isSource ? 'source' : 'candidate') ? 'own' : 'other',\n action: td?.action ?? 'unknown',\n message: td?.message ?? null,\n };\n });\n\n const indexContext = meta.turnContext?.indexContext ?? null;\n\n // Outcome artifact — only meaningful for completed negotiations\n let outcome: unknown = null;\n if (status === 'completed') {\n const artifacts = await negotiationDatabase.getArtifactsForTask(task.id);\n const outcomeArtifact = artifacts.find(a => a.name === 'negotiation-outcome');\n outcome = outcomeArtifact\n ? ((outcomeArtifact.parts as Array<{ kind?: string; data?: unknown }>)?.find(p => p.kind === 'data')?.data ?? null)\n : null;\n }\n\n return { ...base, indexContext, recentTurns, outcome };\n }));\n\n let filtered = negotiations.filter(Boolean);\n\n if (query.since) {\n const sinceMs = new Date(query.since).getTime();\n filtered = filtered.filter(n => new Date(n!.createdAt).getTime() >= sinceMs);\n }\n\n const shouldPaginate = query.limit !== undefined;\n if (shouldPaginate) {\n const limit = query.limit!;\n const page = query.page ?? 1;\n const offset = (page - 1) * limit;\n const paged = filtered.slice(offset, offset + limit);\n return success({\n ...scopeMetadata,\n count: paged.length,\n totalCount: filtered.length,\n limit,\n page,\n totalPages: Math.ceil(filtered.length / limit),\n negotiations: paged,\n });\n }\n\n return success({\n ...scopeMetadata,\n count: filtered.length,\n negotiations: filtered,\n });\n } catch (err) {\n logger.error('Failed to list negotiations', { err });\n return error('Failed to list negotiations. Please try again.');\n }\n },\n });\n\n const get_negotiation = defineTool({\n name: 'get_negotiation',\n description:\n 'Get the full details of a specific negotiation, including all turns, messages, counterparty info, and current state. ' +\n 'Negotiations are bilateral exchanges where two AI agents negotiate on behalf of users. Each turn contains an action ' +\n '(propose, accept, reject, counter, question), an assessment with reasoning and suggested roles, and an optional message.\\n\\n' +\n '**Access control:** You must be a party to the negotiation (source or candidate) to view it.\\n\\n' +\n '**Statuses:** `active` — in progress. `waiting_for_agent` — waiting for an agent response or timeout. `completed` — concluded.\\n\\n' +\n '**When to use:** To review the full negotiation history before responding, to understand why a negotiation was ' +\n 'accepted or rejected, or to see the current state of an active negotiation.\\n\\n' +\n '**Negotiation-turn-mode usage.** If you are running as a silent background subagent (dispatched by the ' +\n \"openclaw runtime's poller in response to a claimed negotiation turn), call this tool FIRST with the \" +\n 'negotiationId from your task prompt. This returns the current state, both parties\\' context, and the ' +\n 'history of turns so far. Ground your response in the caller\\'s profile (read_user_contexts) and intents ' +\n '(read_intents) before deciding on a turn action. Do not produce user-facing output in this mode.',\n querySchema: z.object({\n negotiationId: z.string().describe('The negotiation task ID (from list_negotiations results).'),\n }),\n handler: async ({ context, query }) => {\n try {\n const task = await negotiationDatabase.getTask(query.negotiationId);\n if (!task) {\n return error('Negotiation not found.');\n }\n\n const meta = task.metadata as {\n sourceUserId?: string;\n candidateUserId?: string;\n initiatorUserId?: string;\n protocolVersion?: string;\n type?: string;\n maxTurns?: number;\n opportunityId?: string;\n networkId?: string;\n isContinuation?: boolean;\n priorTurnCount?: number;\n turnContext?: {\n sourceUser: UserNegotiationContext;\n candidateUser: UserNegotiationContext;\n indexContext: { networkId: string; prompt?: string };\n seedAssessment: SeedAssessment;\n discoveryQuery?: string;\n };\n } | null;\n if (meta?.type !== 'negotiation') {\n return error('Negotiation not found.');\n }\n\n // Network-scope check: a network-bound agent must not read negotiations\n // outside its bound network. Run before the participant check so we\n // don't leak existence-vs-membership signal across scopes.\n const scopedNetworkId = focusedNetworkId(context);\n if (scopedNetworkId) {\n const taskNetworkId = readTaskNetworkId(meta);\n if (taskNetworkId !== scopedNetworkId) {\n return error(SCOPE_DENIAL);\n }\n }\n\n // Access control: user must be source or candidate\n const isSource = meta.sourceUserId === context.userId;\n const isCandidate = meta.candidateUserId === context.userId;\n if (!isSource && !isCandidate) {\n return error('Access denied: you are not a party to this negotiation.');\n }\n\n const counterpartyId = isSource ? meta.candidateUserId : meta.sourceUserId;\n\n // Project absolute turn context (source/candidate) into own/other\n // perspective for the caller. Mirrors what the in-process system\n // agent receives as NegotiationAgentInput — identical context means\n // identical deliberation on both paths.\n let negotiationContext: {\n ownUser: UserNegotiationContext;\n otherUser: UserNegotiationContext;\n indexContext: { networkId: string; prompt?: string };\n seedAssessment: SeedAssessment;\n isDiscoverer: boolean;\n discoveryQuery?: string;\n } | null = null;\n if (meta.turnContext) {\n const tc = meta.turnContext;\n negotiationContext = {\n ownUser: isSource ? tc.sourceUser : tc.candidateUser,\n otherUser: isSource ? tc.candidateUser : tc.sourceUser,\n indexContext: tc.indexContext,\n seedAssessment: tc.seedAssessment,\n isDiscoverer: isSource,\n ...(tc.discoveryQuery && { discoveryQuery: tc.discoveryQuery }),\n };\n }\n\n // Load messages and artifacts\n const [messages, artifacts] = await Promise.all([\n negotiationDatabase.getMessagesForConversation(task.conversationId),\n negotiationDatabase.getArtifactsForTask(task.id),\n ]);\n\n // Parse turns from messages (speaker from senderId, not parity —\n // continuations can start with either side speaking first)\n const turns = messages.map((m, idx) => {\n const dataPart = (m.parts as Array<{ kind?: string; data?: unknown }>)?.find(p => p.kind === 'data');\n const turnData = dataPart?.data as {\n action?: string;\n assessment?: { reasoning?: string; suggestedRoles?: unknown };\n message?: string;\n } | undefined;\n\n const turnNumber = idx + 1;\n const speaker = m.senderId\n ? (m.senderId === `agent:${meta.sourceUserId}` ? 'source' : 'candidate')\n : (turnNumber % 2 === 1 ? 'source' : 'candidate');\n\n return {\n turnNumber,\n speaker,\n senderId: m.senderId,\n action: turnData?.action ?? 'unknown',\n reasoning: turnData?.assessment?.reasoning ?? null,\n suggestedRoles: turnData?.assessment?.suggestedRoles ?? null,\n message: turnData?.message ?? null,\n createdAt: m.createdAt,\n };\n });\n\n // Extract outcome from artifacts if completed\n const outcomeArtifact = artifacts.find(a => a.name === 'negotiation-outcome');\n const outcome = outcomeArtifact\n ? (outcomeArtifact.parts as Array<{ kind?: string; data?: unknown }>)?.find(p => p.kind === 'data')?.data\n : null;\n\n // Determine whose turn it is (last sender's counterpart, not parity;\n // rows without senderId fall back to parity)\n const turnCount = messages.length;\n const lastSenderId = turnCount > 0 ? messages[turnCount - 1].senderId : null;\n const currentSpeaker = lastSenderId\n ? (lastSenderId === `agent:${meta.sourceUserId}` ? 'candidate' : 'source')\n : (turnCount % 2 === 0 ? 'source' : 'candidate');\n\n const status = task.state === 'working' ? 'active'\n : task.state === 'waiting_for_agent' ? 'waiting_for_agent'\n : task.state === 'completed' ? 'completed'\n : task.state;\n\n const isUsersTurn = status !== 'completed' &&\n ((isSource && currentSpeaker === 'source') || (!isSource && currentSpeaker === 'candidate'));\n\n const isContinuation = meta.isContinuation ?? false;\n const priorTurnCount = meta.priorTurnCount ?? 0;\n\n // Seat + protocol version (v2 client-advocate): announce the caller's\n // seat and the actions it may submit so agents don't guess.\n const protocolVersion = readProtocolVersion(meta) ?? 'v1';\n const seat = resolveSeat(context.userId, meta);\n\n return success({\n id: task.id,\n conversationId: task.conversationId,\n status,\n role: isSource ? 'source' : 'candidate',\n seat,\n protocolVersion,\n allowedActions: allowedActionsFor(protocolVersion, seat),\n counterpartyId: counterpartyId ?? 'unknown',\n turnCount,\n isUsersTurn,\n isContinuation,\n priorTurnCount,\n turnsAdded: turnCount - priorTurnCount,\n turns,\n outcome,\n context: negotiationContext,\n createdAt: task.createdAt,\n updatedAt: task.updatedAt,\n });\n } catch (err) {\n logger.error('Failed to get negotiation', { err });\n return error('Failed to get negotiation. Please try again.');\n }\n },\n });\n\n const respond_to_negotiation = defineTool({\n name: 'respond_to_negotiation',\n description:\n 'Respond to a negotiation that is waiting for agent input. This tool allows users to influence the negotiation ' +\n 'by accepting, rejecting, countering, or asking a clarifying question.\\n\\n' +\n '**Turn-based model:** Negotiations alternate between source and candidate agents. When the graph yields with ' +\n '`waiting_for_agent` status, the user whose turn it is can respond.\\n\\n' +\n '**Valid actions depend on the negotiation protocol version and your seat** — call get_negotiation first: ' +\n 'its `seat`, `protocolVersion`, and `allowedActions` fields tell you exactly what you may submit.\\n\\n' +\n '**v1 negotiations (legacy):** `propose | accept | reject | counter | question` — on the first turn the action MUST be `propose`.\\n\\n' +\n '**v2 negotiations (client-advocate seat rules):**\\n' +\n '- Initiator seat (`outreach | counter | question | withdraw`): you reached out — you can NEVER accept. ' +\n '`outreach` opens the negotiation; `withdraw` ends it without an opportunity.\\n' +\n '- Counterparty seat (`accept | decline | counter | question`): only your seat can `accept` (finalizes an opportunity); ' +\n '`decline` ends the negotiation without one.\\n\\n' +\n '- `counter` — Counter with a message (message is required). The negotiation continues.\\n' +\n '- `question` — Ask the other side a clarifying question (message is required). The negotiation continues.\\n\\n' +\n '**What happens after:** Terminal actions (accept/reject/withdraw/decline) finalize the negotiation immediately. ' +\n 'Counter/question continues — if the counterparty has an agent, the negotiation yields again; otherwise the AI agent responds inline.\\n\\n' +\n '**Silent-subagent response contract.** In negotiation-turn mode, submit exactly ONE call to this tool ' +\n 'per dispatch with an action from your seat\\'s allowed set and the assessment (reasoning + suggestedRoles). ' +\n 'If the decision is ambiguous, pick the most conservative action — usually `counter` with specific objections. ' +\n 'Do not ask the user clarifying questions; you are authorized to act on their behalf within the scope granted to your agent.',\n querySchema: z.object({\n negotiationId: z.string().describe('The negotiation task ID to respond to.'),\n action: z.enum(NEGOTIATION_ACTIONS).describe('The response action. Must be within your seat\\'s allowedActions (see get_negotiation). v1 first turn MUST be \"propose\"; v2 initiator first turn MUST be \"outreach\".'),\n reasoning: z.string().describe('Why you are taking this action — your assessment of the opportunity.'),\n suggestedRoles: z.object({\n ownUser: z.enum(['agent', 'patient', 'peer']).describe('Suggested role for your user in this opportunity.'),\n otherUser: z.enum(['agent', 'patient', 'peer']).describe('Suggested role for the other user in this opportunity.'),\n }).describe('Role suggestions for both parties.'),\n message: z.string().optional().describe('Required for \"counter\" and \"question\" actions. Your message explaining what you want to change or clarify.'),\n }),\n handler: async ({ context, query }) => {\n try {\n const task = await negotiationDatabase.getTask(query.negotiationId);\n if (!task) {\n return error('Negotiation not found.');\n }\n\n const meta = task.metadata as {\n sourceUserId?: string;\n candidateUserId?: string;\n initiatorUserId?: string;\n protocolVersion?: string;\n type?: string;\n maxTurns?: number;\n networkId?: string;\n turnContext?: { indexContext?: { networkId?: string } };\n } | null;\n if (meta?.type !== 'negotiation') {\n return error('Negotiation not found.');\n }\n\n // Network-scope check (mirrors get_negotiation): a network-bound agent\n // must not act on negotiations outside its bound network.\n const scopedNetworkId = focusedNetworkId(context);\n if (scopedNetworkId) {\n const taskNetworkId = readTaskNetworkId(meta);\n if (taskNetworkId !== scopedNetworkId) {\n return error(SCOPE_DENIAL);\n }\n }\n\n // Validate negotiation is waiting for agent input (or claimed via polling)\n if (task.state !== 'waiting_for_agent' && task.state !== 'claimed') {\n return error(`Negotiation is not waiting for a response. Current status: ${task.state}`);\n }\n\n // Access control: user must be a party\n const isSource = meta.sourceUserId === context.userId;\n const isCandidate = meta.candidateUserId === context.userId;\n if (!isSource && !isCandidate) {\n return error('Access denied: you are not a party to this negotiation.');\n }\n\n // Seat + version validation (v2 client-advocate): the submitted action\n // must be within the caller's seat vocabulary. v1 tasks accept the\n // legacy vocabulary unchanged (grandfathered).\n const protocolVersion = readProtocolVersion(meta) ?? 'v1';\n const seat = resolveSeat(context.userId, meta);\n if (!allowedActionsFor(protocolVersion, seat).includes(query.action)) {\n return error(seatViolationMessage(query.action, seat, protocolVersion));\n }\n\n // Determine whose turn it is from the last message's sender — not\n // parity, which misattributes across continuation sessions. Rows\n // without senderId (legacy) fall back to the parity heuristic.\n const messages = await negotiationDatabase.getMessagesForConversation(task.conversationId);\n const turnCount = messages.length;\n const lastSenderId = turnCount > 0 ? messages[turnCount - 1].senderId : null;\n const paritySpeaker = turnCount % 2 === 0 ? 'source' : 'candidate';\n const isUsersTurn = lastSenderId\n ? lastSenderId !== `agent:${context.userId}`\n : ((isSource && paritySpeaker === 'source') || (!isSource && paritySpeaker === 'candidate'));\n\n if (!isUsersTurn) {\n return error('It is not your turn to respond in this negotiation.');\n }\n\n // The caller is the current speaker (verified above).\n const currentSpeaker: 'source' | 'candidate' = isSource ? 'source' : 'candidate';\n\n // Validate counter/question has a message\n if ((query.action === 'counter' || query.action === 'question') && !query.message?.trim()) {\n return error(`A message is required when using \"${query.action}\". Explain what you want to change or clarify.`);\n }\n\n // ── Cancel pending timeout ──\n if (deps.negotiationTimeoutQueue) {\n await deps.negotiationTimeoutQueue.cancelTimeout(task.id);\n }\n\n // ── Build and persist the external agent's turn ──\n const turnData: NegotiationTurn = {\n action: query.action,\n assessment: {\n reasoning: query.reasoning,\n suggestedRoles: query.suggestedRoles,\n },\n ...(query.message ? { message: query.message } : {}),\n };\n\n const senderId = `agent:${context.userId}`;\n const turnMessage = await negotiationDatabase.createMessage({\n conversationId: task.conversationId,\n senderId,\n role: 'agent',\n parts: [{ kind: 'data' as const, data: turnData }],\n taskId: task.id,\n });\n\n const newTurnCount = turnCount + 1;\n\n // ── Handle terminal actions (accept / reject / withdraw / decline): finalize immediately ──\n if (isTerminalAction(query.action)) {\n const allMessages = [...messages, { id: turnMessage.id, senderId: turnMessage.senderId, role: turnMessage.role, parts: turnMessage.parts as unknown[], createdAt: turnMessage.createdAt }];\n const history: NegotiationTurn[] = turnsFromMessages(allMessages);\n\n const nextSpeaker = currentSpeaker === 'source' ? 'candidate' : 'source';\n const outcome = buildNegotiationOutcome(history, newTurnCount, query.action, meta.sourceUserId!, meta.candidateUserId!, nextSpeaker);\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: outcome.hasOpportunity, turnCount: newTurnCount },\n });\n\n return success({\n message: query.action === 'accept'\n ? 'Negotiation accepted. An opportunity has been created.'\n : query.action === 'withdraw'\n ? 'Negotiation withdrawn.'\n : query.action === 'decline'\n ? 'Negotiation declined.'\n : 'Negotiation rejected.',\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n outcome,\n });\n }\n\n // ── Handle counter/question: check if under max turns ──\n const maxTurns = meta.maxTurns ?? 6; // Read from task metadata; fallback to system default\n if (newTurnCount >= maxTurns) {\n // Max turns reached — finalize with turn_cap\n const allMessages = [...messages, { id: turnMessage.id, senderId: turnMessage.senderId, role: turnMessage.role, parts: turnMessage.parts as unknown[], createdAt: turnMessage.createdAt }];\n const history: NegotiationTurn[] = turnsFromMessages(allMessages);\n\n const nextSpeakerForCap = currentSpeaker === 'source' ? 'candidate' : 'source';\n const outcome = buildNegotiationOutcome(history, newTurnCount, 'counter', meta.sourceUserId!, meta.candidateUserId!, nextSpeakerForCap);\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: false, turnCount: newTurnCount },\n });\n\n return success({\n message: 'Maximum turns reached. Negotiation finalized without opportunity.',\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n outcome,\n });\n }\n\n // ── Counter/question under max turns: dispatch to counterparty's agent ──\n const counterpartyUserId = isSource ? meta.candidateUserId! : meta.sourceUserId!;\n const counterpartySpeaker = isSource ? 'candidate' : 'source';\n const counterpartySeat = resolveSeat(counterpartyUserId, meta);\n\n // Build the current turn history for dispatcher payload\n const allMessagesWithTurn = [...messages, { id: turnMessage.id, senderId: turnMessage.senderId, role: turnMessage.role, parts: turnMessage.parts as unknown[], createdAt: turnMessage.createdAt }];\n const historyForDispatch: NegotiationTurn[] = turnsFromMessages(allMessagesWithTurn);\n\n const isFinalTurn = newTurnCount + 1 >= maxTurns;\n\n const ownUserCtx: UserNegotiationContext = { id: counterpartyUserId, intents: [], profile: {} };\n const otherUserCtx: UserNegotiationContext = { id: context.userId, intents: [], profile: {} };\n const seedAssessment: SeedAssessment = { reasoning: 'Continued negotiation', valencyRole: 'peer' };\n\n const dispatchPayload: NegotiationTurnPayload = {\n negotiationId: task.id,\n ownUser: ownUserCtx,\n otherUser: otherUserCtx,\n indexContext: { networkId: '' },\n seedAssessment,\n history: historyForDispatch,\n isFinalTurn,\n isDiscoverer: false,\n seat: counterpartySeat,\n protocolVersion,\n allowedActions: [...allowedActionsFor(protocolVersion, counterpartySeat, isFinalTurn)],\n };\n\n const scope = { action: 'negotiation.respond', scopeType: 'negotiation', scopeId: task.id };\n const timeoutMs = AMBIENT_PARK_WINDOW_MS;\n\n const dispatchResult = await deps.agentDispatcher?.dispatch(counterpartyUserId, scope, dispatchPayload, { timeoutMs });\n\n if (dispatchResult?.handled === false && dispatchResult.reason === 'waiting') {\n // Counterparty's agent acknowledged — yield and wait\n await negotiationDatabase.updateTaskState(task.id, 'waiting_for_agent');\n\n if (deps.negotiationTimeoutQueue) {\n await deps.negotiationTimeoutQueue.enqueueTimeout(task.id, newTurnCount, timeoutMs);\n }\n\n return success({\n message: `${query.action === 'question' ? 'Question' : query.action === 'propose' ? 'Proposal' : query.action === 'outreach' ? 'Outreach' : 'Counter-proposal'} submitted. Waiting for counterparty response.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n waitingForAgent: true,\n });\n }\n\n let aiTurn: NegotiationTurn;\n\n if (dispatchResult?.handled === true) {\n // Dispatcher returned an agent turn directly\n aiTurn = dispatchResult.turn;\n } else {\n // No agent or timeout — run the system AI agent inline.\n // The agent honors a per-turn LLM timeout (AbortSignal), so invoke\n // can reject. Mirror the graph turnNode's reject-shaped fallback so\n // a timed-out or failed call degrades gracefully instead of leaving\n // the task pinned in `working` while the outer catch returns a bare\n // error to the user.\n await negotiationDatabase.updateTaskState(task.id, 'working');\n\n const agent = new IndexNegotiator();\n try {\n aiTurn = await agent.invoke({\n ownUser: ownUserCtx,\n otherUser: otherUserCtx,\n indexContext: { networkId: '' },\n seedAssessment,\n history: historyForDispatch,\n isFinalTurn,\n seat: counterpartySeat,\n protocolVersion,\n });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n const errName = (err as { name?: string })?.name ?? '';\n const isTimeout = errName === 'TimeoutError' || /timeout|abort/i.test(errMsg);\n // Log the raw error for ops, but keep the persisted/returned\n // reasoning generic — this string round-trips back to the caller\n // via counterpartyResponse.reasoning and ends up in the negotiation\n // history visible through get_negotiation, so we don't want raw\n // provider messages (URLs, request IDs, internal stack hints) on\n // the wire.\n logger.warn('System negotiator inline invoke failed; treating as reject', {\n taskId: task.id,\n isTimeout,\n error: errMsg,\n });\n aiTurn = {\n action: rejectActionFor(protocolVersion, counterpartySeat),\n assessment: {\n reasoning: isTimeout\n ? 'Negotiator response timed out.'\n : 'Negotiator failed to produce a response.',\n suggestedRoles: { ownUser: 'peer', otherUser: 'peer' },\n },\n };\n }\n }\n\n // Persist the counterparty's turn (from dispatcher or inline AI)\n const aiSenderId = `agent:${counterpartyUserId}`;\n await negotiationDatabase.createMessage({\n conversationId: task.conversationId,\n senderId: aiSenderId,\n role: 'agent',\n parts: [{ kind: 'data' as const, data: aiTurn }],\n taskId: task.id,\n });\n\n const finalTurnCount = newTurnCount + 1;\n\n // Evaluate response\n if (isTerminalAction(aiTurn.action)) {\n const fullHistory = [...historyForDispatch, aiTurn];\n const outcome = buildNegotiationOutcome(fullHistory, finalTurnCount, aiTurn.action, meta.sourceUserId!, meta.candidateUserId!, counterpartySpeaker === 'source' ? 'candidate' : 'source');\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: outcome.hasOpportunity, turnCount: finalTurnCount },\n });\n\n return success({\n message: `${query.action === 'question' ? 'Question' : query.action === 'propose' ? 'Proposal' : 'Counter'} submitted. Counterparty responded with ${aiTurn.action}.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n outcome,\n });\n }\n\n // Counterparty countered/questioned — check if max turns reached\n if (finalTurnCount >= maxTurns) {\n const fullHistory = [...historyForDispatch, aiTurn];\n const outcome = buildNegotiationOutcome(fullHistory, finalTurnCount, 'counter', meta.sourceUserId!, meta.candidateUserId!, counterpartySpeaker === 'source' ? 'candidate' : 'source');\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: false, turnCount: finalTurnCount },\n });\n\n return success({\n message: 'Counterparty responded but max turns reached. Negotiation finalized.',\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n outcome,\n });\n }\n\n // Counterparty countered/questioned, now user's turn again — dispatch to user's agent\n const userDispatchPayload: NegotiationTurnPayload = {\n negotiationId: task.id,\n ownUser: { id: context.userId, intents: [], profile: {} },\n otherUser: { id: counterpartyUserId, intents: [], profile: {} },\n indexContext: { networkId: '' },\n seedAssessment,\n history: [...historyForDispatch, aiTurn],\n isFinalTurn: finalTurnCount + 1 >= maxTurns,\n isDiscoverer: true,\n seat,\n protocolVersion,\n allowedActions: [...allowedActionsFor(protocolVersion, seat, finalTurnCount + 1 >= maxTurns)],\n };\n\n const userDispatchResult = await deps.agentDispatcher?.dispatch(context.userId, scope, userDispatchPayload, { timeoutMs });\n\n if (!userDispatchResult || (userDispatchResult.handled === false && userDispatchResult.reason === 'no_agent')) {\n // No agent for user — set back to waiting_for_agent so they can use respond_to_negotiation\n await negotiationDatabase.updateTaskState(task.id, 'waiting_for_agent');\n\n if (deps.negotiationTimeoutQueue) {\n await deps.negotiationTimeoutQueue.enqueueTimeout(task.id, finalTurnCount, timeoutMs);\n }\n\n return success({\n message: `${query.action === 'question' ? 'Question' : 'Counter'} submitted. Counterparty responded. Your turn to respond.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n waitingForAgent: true,\n });\n }\n\n if (userDispatchResult.handled === false && userDispatchResult.reason === 'waiting') {\n // User's agent acknowledged — yield and wait\n await negotiationDatabase.updateTaskState(task.id, 'waiting_for_agent');\n\n if (deps.negotiationTimeoutQueue) {\n await deps.negotiationTimeoutQueue.enqueueTimeout(task.id, finalTurnCount, timeoutMs);\n }\n\n return success({\n message: `${query.action === 'question' ? 'Question' : 'Counter'} submitted. Counterparty countered back. Waiting for your agent's response.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n waitingForAgent: true,\n });\n }\n\n if (userDispatchResult.handled === true) {\n // User's agent returned a turn directly — persist, evaluate, and continue\n const userAgentTurn: NegotiationTurn = userDispatchResult.turn;\n const userAgentSenderId = `agent:${context.userId}`;\n await negotiationDatabase.createMessage({\n conversationId: task.conversationId,\n senderId: userAgentSenderId,\n role: 'agent',\n parts: [{ kind: 'data' as const, data: userAgentTurn }],\n taskId: task.id,\n });\n\n const userTurnCount = finalTurnCount + 1;\n\n if (isTerminalAction(userAgentTurn.action)) {\n const fullHistory = [...historyForDispatch, aiTurn, userAgentTurn];\n const userSpeaker = isSource ? 'source' : 'candidate';\n const outcome = buildNegotiationOutcome(fullHistory, userTurnCount, userAgentTurn.action, meta.sourceUserId!, meta.candidateUserId!, userSpeaker === 'source' ? 'candidate' : 'source');\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: outcome.hasOpportunity, turnCount: userTurnCount },\n });\n\n return success({\n message: `Your agent ${userAgentTurn.action}ed the counterparty's response.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n outcome,\n });\n }\n\n if (userTurnCount >= maxTurns) {\n const fullHistory = [...historyForDispatch, aiTurn, userAgentTurn];\n const outcome = buildNegotiationOutcome(fullHistory, userTurnCount, 'counter', meta.sourceUserId!, meta.candidateUserId!, isSource ? 'candidate' : 'source');\n\n await negotiationDatabase.updateTaskState(task.id, 'completed');\n await negotiationDatabase.createArtifact({\n taskId: task.id,\n name: 'negotiation-outcome',\n parts: [{ kind: 'data', data: outcome }],\n metadata: { hasOpportunity: false, turnCount: userTurnCount },\n });\n\n return success({\n message: 'Your agent responded but max turns reached. Negotiation finalized.',\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n outcome,\n });\n }\n\n // User's agent countered/questioned — arm timeout for counterparty's next turn\n await negotiationDatabase.updateTaskState(task.id, 'waiting_for_agent');\n\n if (deps.negotiationTimeoutQueue) {\n await deps.negotiationTimeoutQueue.enqueueTimeout(task.id, userTurnCount, timeoutMs);\n }\n\n return success({\n message: `Your agent responded with ${userAgentTurn.action}. Waiting for counterparty.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n waitingForAgent: true,\n });\n }\n\n // No agent / timeout — set back to working so graph can continue\n await negotiationDatabase.updateTaskState(task.id, 'working');\n\n return success({\n message: `${query.action === 'question' ? 'Question' : 'Counter'} submitted. Counterparty countered back. Negotiation continues.`,\n negotiationId: task.id,\n action: query.action,\n turnNumber: newTurnCount,\n counterpartyResponse: { action: aiTurn.action, reasoning: aiTurn.assessment.reasoning, message: aiTurn.message ?? null },\n });\n } catch (err) {\n logger.error('Failed to respond to negotiation', { err });\n return error('Failed to respond to negotiation. Please try again.');\n }\n },\n });\n\n return [list_negotiations, get_negotiation, respond_to_negotiation] as const;\n}\n\n/**\n * Build a NegotiationOutcome from the full turn history.\n * Mirrors the logic in the graph's finalizeNode for consistency.\n *\n * @param history - All negotiation turns\n * @param turnCount - Total number of turns\n * @param lastAction - The last turn's action (accept/reject/counter)\n * @param sourceUserId - Source user ID\n * @param candidateUserId - Candidate user ID\n * @param currentSpeaker - Who would speak next (the person after the accepter/rejector)\n */\nfunction buildNegotiationOutcome(\n history: NegotiationTurn[],\n turnCount: number,\n lastAction: string,\n sourceUserId: string,\n candidateUserId: string,\n currentSpeaker: string,\n): NegotiationOutcome {\n const hasOpportunity = lastAction === 'accept';\n // Non-terminal last action at finalization means the turn cap was hit.\n const atCap = !isTerminalAction(lastAction);\n\n let agreedRoles: NegotiationOutcome['agreedRoles'] = [];\n if (hasOpportunity && history.length >= 2) {\n const acceptTurn = history[history.length - 1];\n const precedingTurn = history[history.length - 2];\n const accepterIsSource = currentSpeaker === 'candidate';\n const [sourceRole, candidateRole] = accepterIsSource\n ? [acceptTurn.assessment.suggestedRoles.ownUser, precedingTurn.assessment.suggestedRoles.ownUser]\n : [precedingTurn.assessment.suggestedRoles.ownUser, acceptTurn.assessment.suggestedRoles.ownUser];\n agreedRoles = [\n { userId: sourceUserId, role: sourceRole },\n { userId: candidateUserId, role: candidateRole },\n ];\n }\n\n return {\n hasOpportunity,\n agreedRoles,\n reasoning: history[history.length - 1]?.assessment.reasoning ?? '',\n turnCount,\n ...(atCap && { reason: 'turn_cap' }),\n };\n}\n"]}
@@ -1,3 +1,3 @@
1
1
  import type { DefineTool, ToolDeps } from "./tool.helpers.js";
2
- export declare function createUtilityTools(defineTool: DefineTool, deps: ToolDeps): readonly [any, any];
2
+ export declare function createUtilityTools(defineTool: DefineTool, deps: ToolDeps): readonly [any, any, any];
3
3
  //# sourceMappingURL=utility.tools.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utility.tools.d.ts","sourceRoot":"/","sources":["shared/agent/utility.tools.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAG9D,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,uBAsSxE"}
1
+ {"version":3,"file":"utility.tools.d.ts","sourceRoot":"/","sources":["shared/agent/utility.tools.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAG9D,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,4BAsTxE"}
@@ -273,6 +273,20 @@ Discovery is the process of finding meaningful connections between users based o
273
273
  return success({ content: fullDoc });
274
274
  },
275
275
  });
276
- return [scrapeUrl, readDocs];
276
+ const reportAgentActivity = defineTool({
277
+ name: "report_agent_activity",
278
+ description: "Reports grounded, aggregate-only activity for the authenticated user's agent over a recent time window. " +
279
+ "It includes live signal count, opportunities surfaced by the user's own signals, pending/answered question counts, " +
280
+ "and negotiation totals. It never returns counterpart identities, transcripts, or per-counterparty rows.",
281
+ querySchema: z.object({
282
+ sinceHours: z.number().int().optional().default(24).describe("Look back this many hours; values are clamped to 1-168 (default 24)."),
283
+ }).strict(),
284
+ handler: async ({ query }) => {
285
+ const sinceHours = Math.max(1, Math.min(168, query.sinceHours));
286
+ const summary = await deps.userDb.getAgentActivitySummary({ sinceHours });
287
+ return success(summary);
288
+ },
289
+ });
290
+ return [scrapeUrl, readDocs, reportAgentActivity];
277
291
  }
278
292
  //# sourceMappingURL=utility.tools.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utility.tools.js","sourceRoot":"/","sources":["shared/agent/utility.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AAGrE,OAAO,EAAE,OAAO,EAAE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;;;;;;;;;;;;;;4DAkBoC;gBAEpD,eAAe,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;iGAyBwE;aAC1F,CAAC;YAEF,IAAI,KAAK,EAAE,CAAC;gBACV,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;gBACrG,IAAI,OAAO,EAAE,CAAC;oBACZ,OAAO,OAAO,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;gBAC7D,CAAC;gBACD,iCAAiC;YACnC,CAAC;YAED,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACrD,OAAO,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;QACvC,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAU,CAAC;AACxC,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport { requestContext } from \"../observability/request-context.js\";\n\nimport type { DefineTool, ToolDeps } from \"./tool.helpers.js\";\nimport { success, error, normalizeUrl } from \"./tool.helpers.js\";\n\nexport function createUtilityTools(defineTool: DefineTool, deps: ToolDeps) {\n const { scraper } = deps;\n\n const scrapeUrl = defineTool({\n name: \"scrape_url\",\n description:\n \"Extracts text content from a web URL — articles, LinkedIn/GitHub profiles, documentation, project pages, etc. \" +\n \"Returns the page's text content (up to 10,000 characters) for use in subsequent tool calls.\\n\\n\" +\n \"**When to use:**\\n\" +\n \"- Before create_intent: when the user shares a URL and wants to create an intent from it. Scrape first, then synthesize into a description.\\n\" +\n \"- Before create_user_context or update_user_context: when the user shares a profile URL to update their profile from.\\n\" +\n \"- When the user asks about content at a URL.\\n\\n\" +\n \"**URL format:** Bare domains work fine (e.g. 'github.com/user/repo') — protocol (https://) is added automatically.\\n\\n\" +\n \"**Returns:** `{ url, contentLength, content }`. Content is truncated at 10,000 chars. \" +\n \"Returns an error if the URL is unreachable, requires login, or has no extractable text.\",\n querySchema: z.object({\n url: z.string().describe(\"The URL to extract content from. Protocol is optional — 'github.com/user/repo', 'linkedin.com/in/name', and 'https://example.com' all work.\"),\n objective: z.string().optional().describe(\"Why you're scraping — guides content extraction for better results. Examples: 'User wants to create an intent from this project page', 'User wants to update their profile from this LinkedIn page', 'Extract key information about this company'. Omit for generic text extraction.\"),\n }),\n handler: async ({ context: _context, query }) => {\n const normalizedUrl = normalizeUrl(query.url);\n if (!normalizedUrl) {\n return error(\"Invalid URL format. Please provide a valid URL (e.g. 'github.com/user/repo' or 'https://example.com').\");\n }\n\n const content = await scraper.extractUrlContent(normalizedUrl, {\n objective: query.objective?.trim() || undefined,\n signal: requestContext.getStore()?.abortSignal,\n });\n\n if (!content) {\n return error(\"Couldn't extract content from that URL. It may be blocked, require login, or have no extractable text.\");\n }\n\n const truncatedContent = content.length > 10000\n ? content.substring(0, 10000) + \"\\n\\n[Content truncated...]\"\n : content;\n\n return success({\n url: normalizedUrl,\n contentLength: content.length,\n content: truncatedContent,\n });\n },\n });\n\n const readDocs = defineTool({\n name: \"read_docs\",\n description:\n \"Returns comprehensive documentation about the Index Network protocol — entity model, workflows, tool usage guidance, and domain concepts. \" +\n \"This is the primary way for an external agent to bootstrap understanding of the system.\\n\\n\" +\n \"**When to use:** Call this FIRST when starting a new session. MCP agents MUST call read_docs(topic='mcp_agent_guide') at the start of every conversation to learn proper output formatting and workflow rules.\\n\" +\n \"Also call when you need to understand:\\n\" +\n \"- What entities exist and how they relate (intents, indexes, opportunities, profiles, contacts)\\n\" +\n \"- The discovery workflow (how intents become opportunities)\\n\" +\n \"- Which tools to call in what order for common tasks\\n\" +\n \"- Authentication and API patterns\\n\\n\" +\n \"**Returns:** Markdown documentation. Pass `topic` to get a specific section, or omit for the full reference.\\n\\n\" +\n \"**Available topics:** 'entities', 'intents', 'opportunities', 'indexes', 'profiles', 'contacts', 'discovery', 'workflows', 'authentication', 'mcp_agent_guide'\",\n querySchema: z.object({\n topic: z.string().optional().describe(\"Narrow to a specific topic: 'entities', 'intents', 'opportunities', 'indexes', 'profiles', 'contacts', 'discovery', 'workflows', or 'authentication'. Omit to get the full documentation.\"),\n }),\n handler: async ({ context: _context, query }) => {\n const topic = query.topic?.trim().toLowerCase();\n\n const sections: Record<string, string> = {\n entities: `## Entity Model & Relationships\n\n- **Users**: People on the platform. Authenticated via API key (X-API-Key header) for MCP/external agents, or session-based (Better Auth) for the web app.\n- **Profiles**: A user's identity — name, bio, skills, interests, location, social links. Generated from account data or social URLs via enrichment. One profile per user.\n- **Indexes** (also called \"networks\"): Communities or groups where members share intents and discover opportunities. Each has a title, optional prompt (purpose description), join policy (anyone or invite_only), and an owner. The user's **personal network** (isPersonal=true) stores their contacts.\n- **Network Members**: Junction between Users and Indexes. Tracks permissions (owner, member, contact), join date, auto-assign setting, and optional member prompt.\n- **Intents**: Signals of interest/need — what a user is looking for (e.g. \"Looking for a React developer in Berlin\"). Each has a description (payload), summary, confidence score (0-1), inferenceType (explicit/implicit), source tracking, and vector embedding.\n- **IntentNetworks**: Many-to-many junction between Intents and Indexes. An intent can be in multiple indexes. Has a relevancyScore (0-1) indicating how well the intent fits the index's purpose.\n- **Opportunities**: Discovered connections between users based on complementary intents within shared networks. Have actors with roles (introducer, party), status lifecycle, match reasoning, confidence score, and presentation data.\n- **Contacts**: People in a user's personal network, stored as network members with 'contact' permission on the personal network. Can be real users or ghost users (placeholder accounts enriched from public data).\n- **Ghost Users**: Placeholder accounts created for contacts who aren't on the platform yet. Enriched with public profile data (LinkedIn, GitHub) and participate in opportunity matching.\n\n### Key Relationships\n- Users → Profiles (1:1)\n- Users → Indexes (many:many via Network Members)\n- Users → Intents (1:many, user owns intents)\n- Intents → Indexes (many:many via IntentNetworks with relevancyScore)\n- Opportunities → Users (many:many via actors with roles)\n- Opportunities → Indexes (scoped to shared network context)\n- Contacts → Personal Network (stored as members with 'contact' permission)`,\n\n intents: `## Intent Lifecycle\n\nIntents are the core unit of discovery — they represent what users are seeking and drive semantic matching.\n\n1. **Creation** (create_intent): User describes what they're looking for. The system runs inference (extracting structured intents from free text) and verification (checking specificity, speech-act type). Returns a proposal for user approval.\n2. **Confidence & Classification**: Each intent gets a confidence score (0-1), inferenceType (explicit = user stated directly, implicit = system inferred), and speech act classification (commissive, directive, assertive).\n3. **Index Assignment**: After creation, the intent is automatically evaluated against all networks the user belongs to. The index's prompt is used as criteria. Matching indexes get linked via IntentNetworks with a relevancyScore (0-1).\n4. **Discovery Trigger**: Creating an intent triggers background opportunity detection — the system searches for other users in shared networks whose intents complement this one.\n5. **Source Tracking**: Intents track their origin via sourceType (file, integration, link, discovery_form, enrichment) and sourceId.\n6. **Update** (update_intent): Re-processes through inference/verification, recalculates embeddings and index assignments.\n7. **Archive** (delete_intent): Soft-deletes the intent. It stops participating in discovery but is not permanently removed.\n\n### Intent Best Practices\n- Be specific: \"Looking for a senior React developer for a 3-month contract in Berlin\" > \"Need a developer\"\n- One intent per need: don't combine multiple requests into one intent\n- Update rather than delete+create to preserve history`,\n\n opportunities: `## Opportunity Lifecycle\n\nOpportunities represent discovered connections between users — potential matches worth pursuing.\n\n1. **Detection** (discover_opportunities): The opportunity graph finds users whose intents semantically complement each other within shared networks. Uses HyDE embeddings for retrieval and an LLM evaluator for scoring.\n2. **Roles**: Each opportunity assigns roles to actors:\n - **introducer**: The person who triggered the introduction (may be the system or another user)\n - **party**: The people being connected (typically 2)\n3. **Status Flow**: draft → pending → accepted/rejected/expired\n - **draft**: Created but not sent. Only the creator/introducer sees it.\n - **pending**: Sent to the other party. They're notified and can respond.\n - **accepted**: Both parties agreed to connect.\n - **rejected**: One party declined.\n - **expired**: Timed out without response.\n4. **Creation Modes**:\n - **Discovery**: Automatic — system finds matches based on intent overlap (discover_opportunities with searchQuery)\n - **Introduction**: Manual — a user introduces two specific people (discover_opportunities with partyUserIds + entities)\n - **Direct**: One-to-one — connect with a specific person (discover_opportunities with targetUserId)\n5. **Presentation**: Each opportunity includes personalized match reasoning, confidence score, and suggested next action.\n\n### Opportunity Workflow\n1. discover_opportunities(searchQuery=\"AI engineers\") → returns draft opportunity cards\n2. update_opportunity(opportunityId, status=\"pending\") → sends to other party\n3. Other party sees opportunity → calls update_opportunity(status=\"accepted\" or \"rejected\")`,\n\n indexes: `## Index Mechanics\n\nIndexes (also called \"networks\") are communities where members share what they're looking for and the system discovers connections between them.\n\n- **Purpose prompt**: Each index has an optional prompt describing its purpose (e.g. \"AI/ML co-founders in Berlin\"). This prompt is used by the intent indexer to evaluate whether an intent belongs in this community. Networks without prompts accept all intents (relevancyScore defaults to 1.0).\n- **Join policy**: \"anyone\" (open — any user can self-join) or \"invite_only\" (only the owner can add members).\n- **Personal network**: Each user has exactly one personal network (isPersonal=true) created on registration. It stores their contacts. Cannot be deleted, renamed, or listed publicly.\n- **Membership**: Members can see all intents in the index. The **auto-assign** setting on a membership means new intents by that user are automatically evaluated against the index.\n- **Owner permissions**: Network owners can update settings (title, prompt, joinPolicy), add/remove members, and delete the network (if sole member).\n- **Discovery scope**: Opportunities are discovered within index boundaries — the system matches intents of members who share at least one index.\n\n### Index Workflow\n1. create_network(title, prompt) → creates new community, you become owner\n2. create_network_membership(networkId, userId) → invite members\n3. Members create intents → auto-assigned to the index based on prompt\n4. discover_opportunities(networkId) → discover matches within this community`,\n\n profiles: `## Profile System\n\nProfiles are the user's identity on the platform, used for semantic matching in opportunity discovery.\n\n- **Structure**: name, bio, location, skills[], interests[], social links (LinkedIn, GitHub, Twitter, websites)\n- **Generation**: Auto-generated from account data (name, email, social links) via web enrichment. Can also be created from explicit user input (bioOrDescription).\n- **Enrichment**: The system scrapes public profiles (LinkedIn, GitHub, Twitter) to build a rich identity with skills, interests, and narrative context.\n- **Embeddings**: HyDE (Hypothetical Document Embedding) generates synthetic documents for semantic matching:\n - Mirror: self-description of the person\n - Reciprocal: what this person would look for in others\n - Neighborhood: related community context\n- **Onboarding flow**: create_user_context() → preview → create_user_context(confirm=true) → complete_onboarding()\n- **Updates**: Use update_user_context for targeted changes, create_user_context for full regeneration.\n\n### Profile Best Practices\n- Richer profiles produce better opportunity matches\n- Social links enable enrichment — encourage users to add LinkedIn/GitHub\n- Profiles are recalculated when updated, which may surface new matches`,\n\n contacts: `## Contact Management\n\nContacts are people in a user's personal network, stored as members of their personal network with 'contact' permission.\n\n- **Adding contacts**: Via import_contacts (bulk), add_contact (single email), or import_gmail_contacts (Google integration).\n- **Ghost users**: When a contact email doesn't match an existing account, a ghost user is created. Ghost users are enriched with public profile data and participate in opportunity matching — they can be discovered even before joining the platform.\n- **Personal network scope**: Pass the personal network networkId to discover_opportunities to scope discovery to just the user's contacts.\n- **Contact data**: Each contact has userId, name, email, avatar, and isGhost flag.\n\n### Contact Workflow\n1. import_contacts or import_gmail_contacts → bulk add to network\n2. list_contacts → view all contacts with userId\n3. discover_opportunities(networkId=personalIndexId) → find matches among contacts\n4. add_contact(email) → add individual contact\n5. remove_contact(contactUserId) → remove from network`,\n\n discovery: `## Discovery Mechanics\n\nDiscovery is the process of finding meaningful connections between users based on their intents and profiles.\n\n### How Discovery Works\n1. **Trigger**: Runs automatically when an intent is created, or explicitly when discover_opportunities is called.\n2. **Pipeline**: Preparation (gather user context) → Scope (determine which indexes to search) → Candidate retrieval (semantic matching via HyDE embeddings) → Evaluation (LLM scores relevance and complementarity) → Ranking → Persist as opportunities.\n3. **Semantic matching**: Uses HyDE (Hypothetical Document Embeddings) to find candidate intents that complement the source. This goes beyond keyword matching — it understands conceptual relationships.\n4. **Evaluation**: An LLM evaluator agent scores each candidate match on relevance, complementarity, and actionability. Low-scoring matches are filtered out.\n5. **Results**: Persisted as draft opportunities with roles, reasoning, and confidence scores.\n6. **Background processing**: After intent creation, a queue job continues looking for matches asynchronously.\n7. **Pagination**: Large result sets are paginated. Use continueFrom with the discoveryId to evaluate more candidates.\n\n### Discovery Best Practices\n- More specific intents produce more relevant matches\n- Richer profiles improve matching quality\n- Scope to a specific index (networkId) for more targeted results\n- After discovery returns no results, suggest creating an intent to attract future matches`,\n\n workflows: `## Common Tool Workflows\n\n### New User Setup\n1. create_user_context(linkedinUrl/githubUrl) → generate profile from social data\n2. complete_onboarding() → unlock full access\n3. read_networks() → see available communities\n4. create_network_membership(networkId) → join a community\n5. create_intent(description) → post what you're looking for\n6. discover_opportunities(searchQuery) → find matches\n\n### Finding Connections\n1. read_networks() → list user's communities (get networkId)\n2. discover_opportunities(searchQuery, networkId) → discover matches\n3. Review opportunity cards → update_opportunity(opportunityId, status=\"pending\") to send\n\n### Making an Introduction\n1. read_network_memberships(networkId) → find members in shared community\n2. read_user_contexts(userId) → get profiles of both parties\n3. read_intents(networkId, userId) → get intents of both parties\n4. discover_opportunities(partyUserIds=[id1,id2], entities=[...], hint=\"reason\") → create introduction\n\n### Managing Contacts\n1. import_gmail_contacts() or import_contacts([...]) → add contacts\n2. list_contacts() → view network\n3. discover_opportunities(networkId=personalIndexId) → find matches among contacts\n\n### Creating a Community\n1. create_network(title, prompt) → create network\n2. create_network_membership(networkId, userId) → invite members\n3. Members create intents → auto-indexed\n4. discover_opportunities(networkId) → discover connections within community`,\n\n authentication: `## Authentication & API Access\n\n### For External AI Agents (MCP)\n- Authenticate via **X-API-Key** header with a valid API key\n- The API key is tied to a specific user account\n- All operations execute in the context of the authenticated user\n- Base URL: protocol.index.network/mcp\n\n### Key Constraints\n- Users can only read their own intents globally, or intents in indexes they belong to\n- Users can only read profiles of people in shared networks\n- Network-scoped operations are restricted to that index\n- Personal networks cannot be deleted or renamed\n- Only network owners can update settings, add/remove members (for invite_only networks)\n\n### Rate Limits & Best Practices\n- Avoid unnecessary read_intents/read_networks calls — cache results within a conversation\n- Use pagination (limit/page) for large result sets\n- Call read_docs once at the start to understand the domain`,\n\n mcp_agent_guide: `## MCP Agent Integration Guide\n\n**IMPORTANT: Read this section if you are an AI agent accessing Index Network via MCP tools.**\n\n### Output Formatting\n- Tool results often contain structured JSON data (proposals, opportunities, cards). **Do NOT dump raw JSON to the user.** Parse the JSON and present information in natural language with clear formatting.\n- Some tool results contain interactive card markup (code blocks with \\`intent_proposal\\`, \\`opportunity_card\\` language tags). These are designed for the Index Network web UI. **As an MCP agent, ignore card markup.** Instead, extract the meaningful data from the JSON and present it conversationally.\n- When presenting opportunities or intents, use bullet points or short paragraphs — not raw JSON objects.\n\n### Intent Creation Workflow\n- **Always pass \\`autoApprove: true\\` when calling \\`create_intent\\`.** This persists intents directly without returning proposal cards that require manual UI approval.\n- The tool will return a list of created intents with their descriptions and confidence scores. Present these in natural language.\n- Do not tell the user to \"click on cards\" or \"approve above\" — there is no UI. Intents are created immediately with autoApprove.\n- After creating intents, proactively suggest or run discovery to find matches.\n\n### Discovery Workflow\n- After creating intents, proactively suggest running discovery: \\`discover_opportunities(searchQuery=...)\\`\n- Present discovered opportunities in natural language with the counterpart's name, match reasoning, and suggested next steps.\n- Do not reference \"cards\", \"panels\", or any web UI elements.\n\n### General MCP Agent Rules\n- You are operating via API tools, not a web interface. Never reference clicking, scrolling, cards, panels, or any visual UI elements.\n- Be proactive: if a logical next step exists (e.g., running discovery after creating intents), suggest or execute it.\n- Use \\`list_opportunities\\` to check existing matches, \\`list_negotiations\\` for ongoing negotiations.\n- Use \\`read_networks\\` to understand which communities the user belongs to before scoping operations.\n- When errors occur, provide clear technical context rather than vague \"backend issue\" messages.`,\n };\n\n if (topic) {\n const matched = Object.entries(sections).find(([key]) => key.includes(topic) || topic.includes(key));\n if (matched) {\n return success({ topic: matched[0], content: matched[1] });\n }\n // If topic not found, return all\n }\n\n const fullDoc = Object.values(sections).join(\"\\n\\n\");\n return success({ content: fullDoc });\n },\n });\n\n return [scrapeUrl, readDocs] as const;\n}\n"]}
1
+ {"version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CAAC;SACrI,CAAC,CAAC,MAAM,EAAE;QACX,OAAO,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE;YAC3B,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;YAChE,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,uBAAuB,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC;YAC1E,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC;QAC1B,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,SAAS,EAAE,QAAQ,EAAE,mBAAmB,CAAU,CAAC;AAC7D,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport { requestContext } from \"../observability/request-context.js\";\n\nimport type { DefineTool, ToolDeps } from \"./tool.helpers.js\";\nimport { success, error, normalizeUrl } from \"./tool.helpers.js\";\n\nexport function createUtilityTools(defineTool: DefineTool, deps: ToolDeps) {\n const { scraper } = deps;\n\n const scrapeUrl = defineTool({\n name: \"scrape_url\",\n description:\n \"Extracts text content from a web URL — articles, LinkedIn/GitHub profiles, documentation, project pages, etc. \" +\n \"Returns the page's text content (up to 10,000 characters) for use in subsequent tool calls.\\n\\n\" +\n \"**When to use:**\\n\" +\n \"- Before create_intent: when the user shares a URL and wants to create an intent from it. Scrape first, then synthesize into a description.\\n\" +\n \"- Before create_user_context or update_user_context: when the user shares a profile URL to update their profile from.\\n\" +\n \"- When the user asks about content at a URL.\\n\\n\" +\n \"**URL format:** Bare domains work fine (e.g. 'github.com/user/repo') — protocol (https://) is added automatically.\\n\\n\" +\n \"**Returns:** `{ url, contentLength, content }`. Content is truncated at 10,000 chars. \" +\n \"Returns an error if the URL is unreachable, requires login, or has no extractable text.\",\n querySchema: z.object({\n url: z.string().describe(\"The URL to extract content from. Protocol is optional — 'github.com/user/repo', 'linkedin.com/in/name', and 'https://example.com' all work.\"),\n objective: z.string().optional().describe(\"Why you're scraping — guides content extraction for better results. Examples: 'User wants to create an intent from this project page', 'User wants to update their profile from this LinkedIn page', 'Extract key information about this company'. Omit for generic text extraction.\"),\n }),\n handler: async ({ context: _context, query }) => {\n const normalizedUrl = normalizeUrl(query.url);\n if (!normalizedUrl) {\n return error(\"Invalid URL format. Please provide a valid URL (e.g. 'github.com/user/repo' or 'https://example.com').\");\n }\n\n const content = await scraper.extractUrlContent(normalizedUrl, {\n objective: query.objective?.trim() || undefined,\n signal: requestContext.getStore()?.abortSignal,\n });\n\n if (!content) {\n return error(\"Couldn't extract content from that URL. It may be blocked, require login, or have no extractable text.\");\n }\n\n const truncatedContent = content.length > 10000\n ? content.substring(0, 10000) + \"\\n\\n[Content truncated...]\"\n : content;\n\n return success({\n url: normalizedUrl,\n contentLength: content.length,\n content: truncatedContent,\n });\n },\n });\n\n const readDocs = defineTool({\n name: \"read_docs\",\n description:\n \"Returns comprehensive documentation about the Index Network protocol — entity model, workflows, tool usage guidance, and domain concepts. \" +\n \"This is the primary way for an external agent to bootstrap understanding of the system.\\n\\n\" +\n \"**When to use:** Call this FIRST when starting a new session. MCP agents MUST call read_docs(topic='mcp_agent_guide') at the start of every conversation to learn proper output formatting and workflow rules.\\n\" +\n \"Also call when you need to understand:\\n\" +\n \"- What entities exist and how they relate (intents, indexes, opportunities, profiles, contacts)\\n\" +\n \"- The discovery workflow (how intents become opportunities)\\n\" +\n \"- Which tools to call in what order for common tasks\\n\" +\n \"- Authentication and API patterns\\n\\n\" +\n \"**Returns:** Markdown documentation. Pass `topic` to get a specific section, or omit for the full reference.\\n\\n\" +\n \"**Available topics:** 'entities', 'intents', 'opportunities', 'indexes', 'profiles', 'contacts', 'discovery', 'workflows', 'authentication', 'mcp_agent_guide'\",\n querySchema: z.object({\n topic: z.string().optional().describe(\"Narrow to a specific topic: 'entities', 'intents', 'opportunities', 'indexes', 'profiles', 'contacts', 'discovery', 'workflows', or 'authentication'. Omit to get the full documentation.\"),\n }),\n handler: async ({ context: _context, query }) => {\n const topic = query.topic?.trim().toLowerCase();\n\n const sections: Record<string, string> = {\n entities: `## Entity Model & Relationships\n\n- **Users**: People on the platform. Authenticated via API key (X-API-Key header) for MCP/external agents, or session-based (Better Auth) for the web app.\n- **Profiles**: A user's identity — name, bio, skills, interests, location, social links. Generated from account data or social URLs via enrichment. One profile per user.\n- **Indexes** (also called \"networks\"): Communities or groups where members share intents and discover opportunities. Each has a title, optional prompt (purpose description), join policy (anyone or invite_only), and an owner. The user's **personal network** (isPersonal=true) stores their contacts.\n- **Network Members**: Junction between Users and Indexes. Tracks permissions (owner, member, contact), join date, auto-assign setting, and optional member prompt.\n- **Intents**: Signals of interest/need — what a user is looking for (e.g. \"Looking for a React developer in Berlin\"). Each has a description (payload), summary, confidence score (0-1), inferenceType (explicit/implicit), source tracking, and vector embedding.\n- **IntentNetworks**: Many-to-many junction between Intents and Indexes. An intent can be in multiple indexes. Has a relevancyScore (0-1) indicating how well the intent fits the index's purpose.\n- **Opportunities**: Discovered connections between users based on complementary intents within shared networks. Have actors with roles (introducer, party), status lifecycle, match reasoning, confidence score, and presentation data.\n- **Contacts**: People in a user's personal network, stored as network members with 'contact' permission on the personal network. Can be real users or ghost users (placeholder accounts enriched from public data).\n- **Ghost Users**: Placeholder accounts created for contacts who aren't on the platform yet. Enriched with public profile data (LinkedIn, GitHub) and participate in opportunity matching.\n\n### Key Relationships\n- Users → Profiles (1:1)\n- Users → Indexes (many:many via Network Members)\n- Users → Intents (1:many, user owns intents)\n- Intents → Indexes (many:many via IntentNetworks with relevancyScore)\n- Opportunities → Users (many:many via actors with roles)\n- Opportunities → Indexes (scoped to shared network context)\n- Contacts → Personal Network (stored as members with 'contact' permission)`,\n\n intents: `## Intent Lifecycle\n\nIntents are the core unit of discovery — they represent what users are seeking and drive semantic matching.\n\n1. **Creation** (create_intent): User describes what they're looking for. The system runs inference (extracting structured intents from free text) and verification (checking specificity, speech-act type). Returns a proposal for user approval.\n2. **Confidence & Classification**: Each intent gets a confidence score (0-1), inferenceType (explicit = user stated directly, implicit = system inferred), and speech act classification (commissive, directive, assertive).\n3. **Index Assignment**: After creation, the intent is automatically evaluated against all networks the user belongs to. The index's prompt is used as criteria. Matching indexes get linked via IntentNetworks with a relevancyScore (0-1).\n4. **Discovery Trigger**: Creating an intent triggers background opportunity detection — the system searches for other users in shared networks whose intents complement this one.\n5. **Source Tracking**: Intents track their origin via sourceType (file, integration, link, discovery_form, enrichment) and sourceId.\n6. **Update** (update_intent): Re-processes through inference/verification, recalculates embeddings and index assignments.\n7. **Archive** (delete_intent): Soft-deletes the intent. It stops participating in discovery but is not permanently removed.\n\n### Intent Best Practices\n- Be specific: \"Looking for a senior React developer for a 3-month contract in Berlin\" > \"Need a developer\"\n- One intent per need: don't combine multiple requests into one intent\n- Update rather than delete+create to preserve history`,\n\n opportunities: `## Opportunity Lifecycle\n\nOpportunities represent discovered connections between users — potential matches worth pursuing.\n\n1. **Detection** (discover_opportunities): The opportunity graph finds users whose intents semantically complement each other within shared networks. Uses HyDE embeddings for retrieval and an LLM evaluator for scoring.\n2. **Roles**: Each opportunity assigns roles to actors:\n - **introducer**: The person who triggered the introduction (may be the system or another user)\n - **party**: The people being connected (typically 2)\n3. **Status Flow**: draft → pending → accepted/rejected/expired\n - **draft**: Created but not sent. Only the creator/introducer sees it.\n - **pending**: Sent to the other party. They're notified and can respond.\n - **accepted**: Both parties agreed to connect.\n - **rejected**: One party declined.\n - **expired**: Timed out without response.\n4. **Creation Modes**:\n - **Discovery**: Automatic — system finds matches based on intent overlap (discover_opportunities with searchQuery)\n - **Introduction**: Manual — a user introduces two specific people (discover_opportunities with partyUserIds + entities)\n - **Direct**: One-to-one — connect with a specific person (discover_opportunities with targetUserId)\n5. **Presentation**: Each opportunity includes personalized match reasoning, confidence score, and suggested next action.\n\n### Opportunity Workflow\n1. discover_opportunities(searchQuery=\"AI engineers\") → returns draft opportunity cards\n2. update_opportunity(opportunityId, status=\"pending\") → sends to other party\n3. Other party sees opportunity → calls update_opportunity(status=\"accepted\" or \"rejected\")`,\n\n indexes: `## Index Mechanics\n\nIndexes (also called \"networks\") are communities where members share what they're looking for and the system discovers connections between them.\n\n- **Purpose prompt**: Each index has an optional prompt describing its purpose (e.g. \"AI/ML co-founders in Berlin\"). This prompt is used by the intent indexer to evaluate whether an intent belongs in this community. Networks without prompts accept all intents (relevancyScore defaults to 1.0).\n- **Join policy**: \"anyone\" (open — any user can self-join) or \"invite_only\" (only the owner can add members).\n- **Personal network**: Each user has exactly one personal network (isPersonal=true) created on registration. It stores their contacts. Cannot be deleted, renamed, or listed publicly.\n- **Membership**: Members can see all intents in the index. The **auto-assign** setting on a membership means new intents by that user are automatically evaluated against the index.\n- **Owner permissions**: Network owners can update settings (title, prompt, joinPolicy), add/remove members, and delete the network (if sole member).\n- **Discovery scope**: Opportunities are discovered within index boundaries — the system matches intents of members who share at least one index.\n\n### Index Workflow\n1. create_network(title, prompt) → creates new community, you become owner\n2. create_network_membership(networkId, userId) → invite members\n3. Members create intents → auto-assigned to the index based on prompt\n4. discover_opportunities(networkId) → discover matches within this community`,\n\n profiles: `## Profile System\n\nProfiles are the user's identity on the platform, used for semantic matching in opportunity discovery.\n\n- **Structure**: name, bio, location, skills[], interests[], social links (LinkedIn, GitHub, Twitter, websites)\n- **Generation**: Auto-generated from account data (name, email, social links) via web enrichment. Can also be created from explicit user input (bioOrDescription).\n- **Enrichment**: The system scrapes public profiles (LinkedIn, GitHub, Twitter) to build a rich identity with skills, interests, and narrative context.\n- **Embeddings**: HyDE (Hypothetical Document Embedding) generates synthetic documents for semantic matching:\n - Mirror: self-description of the person\n - Reciprocal: what this person would look for in others\n - Neighborhood: related community context\n- **Onboarding flow**: create_user_context() → preview → create_user_context(confirm=true) → complete_onboarding()\n- **Updates**: Use update_user_context for targeted changes, create_user_context for full regeneration.\n\n### Profile Best Practices\n- Richer profiles produce better opportunity matches\n- Social links enable enrichment — encourage users to add LinkedIn/GitHub\n- Profiles are recalculated when updated, which may surface new matches`,\n\n contacts: `## Contact Management\n\nContacts are people in a user's personal network, stored as members of their personal network with 'contact' permission.\n\n- **Adding contacts**: Via import_contacts (bulk), add_contact (single email), or import_gmail_contacts (Google integration).\n- **Ghost users**: When a contact email doesn't match an existing account, a ghost user is created. Ghost users are enriched with public profile data and participate in opportunity matching — they can be discovered even before joining the platform.\n- **Personal network scope**: Pass the personal network networkId to discover_opportunities to scope discovery to just the user's contacts.\n- **Contact data**: Each contact has userId, name, email, avatar, and isGhost flag.\n\n### Contact Workflow\n1. import_contacts or import_gmail_contacts → bulk add to network\n2. list_contacts → view all contacts with userId\n3. discover_opportunities(networkId=personalIndexId) → find matches among contacts\n4. add_contact(email) → add individual contact\n5. remove_contact(contactUserId) → remove from network`,\n\n discovery: `## Discovery Mechanics\n\nDiscovery is the process of finding meaningful connections between users based on their intents and profiles.\n\n### How Discovery Works\n1. **Trigger**: Runs automatically when an intent is created, or explicitly when discover_opportunities is called.\n2. **Pipeline**: Preparation (gather user context) → Scope (determine which indexes to search) → Candidate retrieval (semantic matching via HyDE embeddings) → Evaluation (LLM scores relevance and complementarity) → Ranking → Persist as opportunities.\n3. **Semantic matching**: Uses HyDE (Hypothetical Document Embeddings) to find candidate intents that complement the source. This goes beyond keyword matching — it understands conceptual relationships.\n4. **Evaluation**: An LLM evaluator agent scores each candidate match on relevance, complementarity, and actionability. Low-scoring matches are filtered out.\n5. **Results**: Persisted as draft opportunities with roles, reasoning, and confidence scores.\n6. **Background processing**: After intent creation, a queue job continues looking for matches asynchronously.\n7. **Pagination**: Large result sets are paginated. Use continueFrom with the discoveryId to evaluate more candidates.\n\n### Discovery Best Practices\n- More specific intents produce more relevant matches\n- Richer profiles improve matching quality\n- Scope to a specific index (networkId) for more targeted results\n- After discovery returns no results, suggest creating an intent to attract future matches`,\n\n workflows: `## Common Tool Workflows\n\n### New User Setup\n1. create_user_context(linkedinUrl/githubUrl) → generate profile from social data\n2. complete_onboarding() → unlock full access\n3. read_networks() → see available communities\n4. create_network_membership(networkId) → join a community\n5. create_intent(description) → post what you're looking for\n6. discover_opportunities(searchQuery) → find matches\n\n### Finding Connections\n1. read_networks() → list user's communities (get networkId)\n2. discover_opportunities(searchQuery, networkId) → discover matches\n3. Review opportunity cards → update_opportunity(opportunityId, status=\"pending\") to send\n\n### Making an Introduction\n1. read_network_memberships(networkId) → find members in shared community\n2. read_user_contexts(userId) → get profiles of both parties\n3. read_intents(networkId, userId) → get intents of both parties\n4. discover_opportunities(partyUserIds=[id1,id2], entities=[...], hint=\"reason\") → create introduction\n\n### Managing Contacts\n1. import_gmail_contacts() or import_contacts([...]) → add contacts\n2. list_contacts() → view network\n3. discover_opportunities(networkId=personalIndexId) → find matches among contacts\n\n### Creating a Community\n1. create_network(title, prompt) → create network\n2. create_network_membership(networkId, userId) → invite members\n3. Members create intents → auto-indexed\n4. discover_opportunities(networkId) → discover connections within community`,\n\n authentication: `## Authentication & API Access\n\n### For External AI Agents (MCP)\n- Authenticate via **X-API-Key** header with a valid API key\n- The API key is tied to a specific user account\n- All operations execute in the context of the authenticated user\n- Base URL: protocol.index.network/mcp\n\n### Key Constraints\n- Users can only read their own intents globally, or intents in indexes they belong to\n- Users can only read profiles of people in shared networks\n- Network-scoped operations are restricted to that index\n- Personal networks cannot be deleted or renamed\n- Only network owners can update settings, add/remove members (for invite_only networks)\n\n### Rate Limits & Best Practices\n- Avoid unnecessary read_intents/read_networks calls — cache results within a conversation\n- Use pagination (limit/page) for large result sets\n- Call read_docs once at the start to understand the domain`,\n\n mcp_agent_guide: `## MCP Agent Integration Guide\n\n**IMPORTANT: Read this section if you are an AI agent accessing Index Network via MCP tools.**\n\n### Output Formatting\n- Tool results often contain structured JSON data (proposals, opportunities, cards). **Do NOT dump raw JSON to the user.** Parse the JSON and present information in natural language with clear formatting.\n- Some tool results contain interactive card markup (code blocks with \\`intent_proposal\\`, \\`opportunity_card\\` language tags). These are designed for the Index Network web UI. **As an MCP agent, ignore card markup.** Instead, extract the meaningful data from the JSON and present it conversationally.\n- When presenting opportunities or intents, use bullet points or short paragraphs — not raw JSON objects.\n\n### Intent Creation Workflow\n- **Always pass \\`autoApprove: true\\` when calling \\`create_intent\\`.** This persists intents directly without returning proposal cards that require manual UI approval.\n- The tool will return a list of created intents with their descriptions and confidence scores. Present these in natural language.\n- Do not tell the user to \"click on cards\" or \"approve above\" — there is no UI. Intents are created immediately with autoApprove.\n- After creating intents, proactively suggest or run discovery to find matches.\n\n### Discovery Workflow\n- After creating intents, proactively suggest running discovery: \\`discover_opportunities(searchQuery=...)\\`\n- Present discovered opportunities in natural language with the counterpart's name, match reasoning, and suggested next steps.\n- Do not reference \"cards\", \"panels\", or any web UI elements.\n\n### General MCP Agent Rules\n- You are operating via API tools, not a web interface. Never reference clicking, scrolling, cards, panels, or any visual UI elements.\n- Be proactive: if a logical next step exists (e.g., running discovery after creating intents), suggest or execute it.\n- Use \\`list_opportunities\\` to check existing matches, \\`list_negotiations\\` for ongoing negotiations.\n- Use \\`read_networks\\` to understand which communities the user belongs to before scoping operations.\n- When errors occur, provide clear technical context rather than vague \"backend issue\" messages.`,\n };\n\n if (topic) {\n const matched = Object.entries(sections).find(([key]) => key.includes(topic) || topic.includes(key));\n if (matched) {\n return success({ topic: matched[0], content: matched[1] });\n }\n // If topic not found, return all\n }\n\n const fullDoc = Object.values(sections).join(\"\\n\\n\");\n return success({ content: fullDoc });\n },\n });\n\n const reportAgentActivity = defineTool({\n name: \"report_agent_activity\",\n description:\n \"Reports grounded, aggregate-only activity for the authenticated user's agent over a recent time window. \" +\n \"It includes live signal count, opportunities surfaced by the user's own signals, pending/answered question counts, \" +\n \"and negotiation totals. It never returns counterpart identities, transcripts, or per-counterparty rows.\",\n querySchema: z.object({\n sinceHours: z.number().int().optional().default(24).describe(\"Look back this many hours; values are clamped to 1-168 (default 24).\"),\n }).strict(),\n handler: async ({ query }) => {\n const sinceHours = Math.max(1, Math.min(168, query.sinceHours));\n const summary = await deps.userDb.getAgentActivitySummary({ sinceHours });\n return success(summary);\n },\n });\n\n return [scrapeUrl, readDocs, reportAgentActivity] as const;\n}\n"]}