@indexnetwork/protocol 4.3.3-rc.308.1 → 4.3.4-rc.309.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.
- package/dist/chat/chat.agent.d.ts.map +1 -1
- package/dist/chat/chat.agent.js +11 -1
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/chat/chat.graph.d.ts +16 -0
- package/dist/chat/chat.graph.d.ts.map +1 -1
- package/dist/chat/chat.graph.js +5 -2
- package/dist/chat/chat.graph.js.map +1 -1
- package/dist/chat/chat.prompt.d.ts.map +1 -1
- package/dist/chat/chat.prompt.js +19 -12
- package/dist/chat/chat.prompt.js.map +1 -1
- package/dist/chat/chat.state.d.ts +6 -3
- package/dist/chat/chat.state.d.ts.map +1 -1
- package/dist/chat/chat.state.js +12 -3
- package/dist/chat/chat.state.js.map +1 -1
- package/dist/chat/chat.streamer.d.ts +5 -0
- package/dist/chat/chat.streamer.d.ts.map +1 -1
- package/dist/chat/chat.streamer.js +13 -4
- package/dist/chat/chat.streamer.js.map +1 -1
- package/dist/enrichment/enrichment.tools.d.ts.map +1 -1
- package/dist/enrichment/enrichment.tools.js +16 -19
- package/dist/enrichment/enrichment.tools.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/intent/intent.graph.d.ts.map +1 -1
- package/dist/intent/intent.state.d.ts +1 -1
- package/dist/intent/intent.state.js +1 -1
- package/dist/intent/intent.state.js.map +1 -1
- package/dist/intent/intent.tools.d.ts.map +1 -1
- package/dist/intent/intent.tools.js +60 -43
- package/dist/intent/intent.tools.js.map +1 -1
- package/dist/mcp/mcp.server.d.ts +3 -5
- package/dist/mcp/mcp.server.d.ts.map +1 -1
- package/dist/mcp/mcp.server.js +7 -16
- package/dist/mcp/mcp.server.js.map +1 -1
- package/dist/negotiation/negotiation.tools.d.ts.map +1 -1
- package/dist/negotiation/negotiation.tools.js +11 -7
- package/dist/negotiation/negotiation.tools.js.map +1 -1
- package/dist/network/network.tools.d.ts.map +1 -1
- package/dist/network/network.tools.js +50 -38
- package/dist/network/network.tools.js.map +1 -1
- package/dist/opportunity/opportunity.graph.js +1 -1
- package/dist/opportunity/opportunity.graph.js.map +1 -1
- package/dist/opportunity/opportunity.tools.d.ts.map +1 -1
- package/dist/opportunity/opportunity.tools.js +25 -29
- package/dist/opportunity/opportunity.tools.js.map +1 -1
- package/dist/questioner/questioner.tools.d.ts +1 -1
- package/dist/questioner/questioner.tools.d.ts.map +1 -1
- package/dist/questioner/questioner.tools.js +4 -5
- package/dist/questioner/questioner.tools.js.map +1 -1
- package/dist/shared/agent/tool.factory.d.ts.map +1 -1
- package/dist/shared/agent/tool.factory.js +9 -10
- package/dist/shared/agent/tool.factory.js.map +1 -1
- package/dist/shared/agent/tool.registry.js +1 -1
- package/dist/shared/agent/tool.registry.js.map +1 -1
- package/dist/shared/agent/tool.scope.d.ts +12 -0
- package/dist/shared/agent/tool.scope.d.ts.map +1 -1
- package/dist/shared/agent/tool.scope.js +14 -0
- package/dist/shared/agent/tool.scope.js.map +1 -1
- package/dist/shared/interfaces/auth.interface.d.ts +3 -3
- package/dist/shared/interfaces/auth.interface.js.map +1 -1
- package/dist/shared/interfaces/discovery-run.interface.d.ts +1 -1
- package/dist/shared/interfaces/discovery-run.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/discovery-run.interface.js.map +1 -1
- package/dist/shared/interfaces/enrichment-run.interface.d.ts +1 -1
- package/dist/shared/interfaces/enrichment-run.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/enrichment-run.interface.js.map +1 -1
- package/package.json +1 -1
|
@@ -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,KA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E,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 type { NegotiationTurnPayload } from '../shared/interfaces/agent-dispatcher.interface.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('NegotiationTools');\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 `context.networkId` 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\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 (context.networkId) {\n const taskNetworkId = readTaskNetworkId(meta);\n if (taskNetworkId !== context.networkId) 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 based on message count (alternating source/candidate)\n const turnCount = messages.length;\n const currentSpeaker = 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 = 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 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 if (context.networkId) {\n const taskNetworkId = readTaskNetworkId(meta);\n if (taskNetworkId !== context.networkId) {\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\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 = 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\n const turnCount = messages.length;\n const currentSpeaker = 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 return success({\n id: task.id,\n conversationId: task.conversationId,\n status,\n role: isSource ? 'source' : 'candidate',\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:**\\n' +\n '- `accept` — Accept the current proposal. The negotiation will be finalized as an opportunity.\\n' +\n '- `reject` — Reject the current proposal. The negotiation will end without creating an opportunity.\\n' +\n '- `counter` — Counter the proposal with a message (message is required). The negotiation will continue.\\n' +\n '- `question` — Ask the counterparty a clarifying question (message is required). The negotiation will continue.\\n\\n' +\n '**What happens after:** Accept/reject finalizes the negotiation immediately. Counter/question continues the negotiation — ' +\n '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 the action (propose | counter | accept | reject | question) and the assessment ' +\n '(reasoning + suggestedRoles). If the decision is ambiguous, pick the most conservative action — usually ' +\n '`counter` with specific objections, or `reject` with clear reasoning. On the first turn of a negotiation ' +\n '(turnCount === 0) the action MUST be `propose`. Do not ask the user clarifying questions; you are ' +\n '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(['propose', 'accept', 'reject', 'counter', 'question']).describe('The response action. On the first turn (turnCount === 0) this MUST be \"propose\".'),\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 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 if (context.networkId) {\n const taskNetworkId = readTaskNetworkId(meta);\n if (taskNetworkId !== context.networkId) {\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 // Determine whose turn it is\n const messages = await negotiationDatabase.getMessagesForConversation(task.conversationId);\n const turnCount = messages.length;\n const currentSpeaker = turnCount % 2 === 0 ? 'source' : 'candidate';\n const isUsersTurn = (isSource && currentSpeaker === 'source') || (!isSource && currentSpeaker === 'candidate');\n\n if (!isUsersTurn) {\n return error('It is not your turn to respond in this negotiation.');\n }\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 accept/reject: finalize immediately ──\n if (query.action === 'accept' || query.action === 'reject') {\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 : '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\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 };\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' : '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 });\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: 'reject',\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 (aiTurn.action === 'accept' || aiTurn.action === 'reject') {\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 };\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 (userAgentTurn.action === 'accept' || userAgentTurn.action === 'reject') {\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 const atCap = lastAction === 'counter';\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;AAGzD,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAEjE,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;;;;;;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,CAAC;AACd,CAAC;AAED,MAAM,YAAY,GAAG,qEAAqE,CAAC;AAE3F,6EAA6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AoB,EACpB,eAAuB,EACvB,cAAsB;IAEtB,MAAM,cAAc,GAAG,UAAU,KAAK,QAAQ,CAAC;IAC/C,MAAM,KAAK,GAAG,UAAU,KAAK,SAAS,CAAC;IAEvC,IAAI,WAAW,GAAsC,EAAE,CAAC;IACxD,IAAI,cAAc,IAAI,OAAO,CAAC,MAAM,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 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('NegotiationTools');\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 based on message count (alternating source/candidate)\n const turnCount = messages.length;\n const currentSpeaker = 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 = 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 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\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 = 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\n const turnCount = messages.length;\n const currentSpeaker = 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 return success({\n id: task.id,\n conversationId: task.conversationId,\n status,\n role: isSource ? 'source' : 'candidate',\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:**\\n' +\n '- `accept` — Accept the current proposal. The negotiation will be finalized as an opportunity.\\n' +\n '- `reject` — Reject the current proposal. The negotiation will end without creating an opportunity.\\n' +\n '- `counter` — Counter the proposal with a message (message is required). The negotiation will continue.\\n' +\n '- `question` — Ask the counterparty a clarifying question (message is required). The negotiation will continue.\\n\\n' +\n '**What happens after:** Accept/reject finalizes the negotiation immediately. Counter/question continues the negotiation — ' +\n '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 the action (propose | counter | accept | reject | question) and the assessment ' +\n '(reasoning + suggestedRoles). If the decision is ambiguous, pick the most conservative action — usually ' +\n '`counter` with specific objections, or `reject` with clear reasoning. On the first turn of a negotiation ' +\n '(turnCount === 0) the action MUST be `propose`. Do not ask the user clarifying questions; you are ' +\n '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(['propose', 'accept', 'reject', 'counter', 'question']).describe('The response action. On the first turn (turnCount === 0) this MUST be \"propose\".'),\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 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 // Determine whose turn it is\n const messages = await negotiationDatabase.getMessagesForConversation(task.conversationId);\n const turnCount = messages.length;\n const currentSpeaker = turnCount % 2 === 0 ? 'source' : 'candidate';\n const isUsersTurn = (isSource && currentSpeaker === 'source') || (!isSource && currentSpeaker === 'candidate');\n\n if (!isUsersTurn) {\n return error('It is not your turn to respond in this negotiation.');\n }\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 accept/reject: finalize immediately ──\n if (query.action === 'accept' || query.action === 'reject') {\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 : '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\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 };\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' : '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 });\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: 'reject',\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 (aiTurn.action === 'accept' || aiTurn.action === 'reject') {\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 };\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 (userAgentTurn.action === 'accept' || userAgentTurn.action === 'reject') {\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 const atCap = lastAction === 'counter';\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network.tools.d.ts","sourceRoot":"/","sources":["network/network.tools.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"network.tools.d.ts","sourceRoot":"/","sources":["network/network.tools.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAS5E,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,gDA2nBxE"}
|
|
@@ -2,6 +2,7 @@ import { z } from "zod";
|
|
|
2
2
|
import { requestContext } from "../shared/observability/request-context.js";
|
|
3
3
|
import { renderNetworkContext } from '../shared/network/metadata.renderer.js';
|
|
4
4
|
import { success, error, UUID_REGEX } from "../shared/agent/tool.helpers.js";
|
|
5
|
+
import { focusedNetworkId, focusedNetworkLabel } from "../shared/agent/tool.scope.js";
|
|
5
6
|
import { NetworkRecommender } from "./network.recommender.js";
|
|
6
7
|
// Lazy singleton — only instantiated on first onboarding ranking call so that
|
|
7
8
|
// importing this module does not require OPENROUTER_API_KEY at load time.
|
|
@@ -34,12 +35,14 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
34
35
|
if (query.userId && query.userId.trim() !== context.userId) {
|
|
35
36
|
return error("You can only list your own indexes. Omit userId to see the current user's indexes.");
|
|
36
37
|
}
|
|
38
|
+
const scopedNetworkId = focusedNetworkId(context);
|
|
39
|
+
const scopedIndexLabel = focusedNetworkLabel(context);
|
|
37
40
|
const _readIndexGraphStart = Date.now();
|
|
38
41
|
const _readIndexTraceEmitter = requestContext.getStore()?.traceEmitter;
|
|
39
42
|
_readIndexTraceEmitter?.({ type: "graph_start", name: "index" });
|
|
40
43
|
const result = await graphs.index.invoke({
|
|
41
44
|
userId: context.userId,
|
|
42
|
-
networkId:
|
|
45
|
+
networkId: scopedNetworkId,
|
|
43
46
|
operationMode: 'read',
|
|
44
47
|
showAll: false, // Never allow bypass - strict scope enforcement
|
|
45
48
|
});
|
|
@@ -57,13 +60,13 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
57
60
|
...(Array.isArray(rr.publicNetworks) ? { publicNetworks: enrichWithContext(rr.publicNetworks) } : {}),
|
|
58
61
|
};
|
|
59
62
|
// When scoped, add clear metadata so model knows results are limited
|
|
60
|
-
if (
|
|
63
|
+
if (scopedNetworkId) {
|
|
61
64
|
return success({
|
|
62
65
|
...enriched,
|
|
63
66
|
scopeRestriction: {
|
|
64
67
|
isScoped: true,
|
|
65
|
-
scopedToIndex:
|
|
66
|
-
message: `Results are limited to "${
|
|
68
|
+
scopedToIndex: scopedIndexLabel,
|
|
69
|
+
message: `Results are limited to "${scopedIndexLabel}" because this chat is scoped to that community. The user may belong to other communities not shown here.`,
|
|
67
70
|
},
|
|
68
71
|
_graphTimings: [{ name: 'index', durationMs: _readIndexGraphMs, agents: result.agentTimings ?? [] }],
|
|
69
72
|
});
|
|
@@ -163,6 +166,8 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
163
166
|
userId: z.string().optional().describe("User ID — lists that user's index memberships. Omit to get the current user's memberships. When combined with networkId, checks if this user is in that specific index."),
|
|
164
167
|
}),
|
|
165
168
|
handler: async ({ context, query }) => {
|
|
169
|
+
const scopedNetworkId = focusedNetworkId(context);
|
|
170
|
+
const scopedIndexLabel = focusedNetworkLabel(context);
|
|
166
171
|
const networkId = query.networkId?.trim() || undefined;
|
|
167
172
|
const userId = query.userId?.trim() || undefined;
|
|
168
173
|
if (networkId && !UUID_REGEX.test(networkId)) {
|
|
@@ -171,8 +176,8 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
171
176
|
// Mode 1: list members of an index
|
|
172
177
|
if (networkId && !userId) {
|
|
173
178
|
// Enforce strict scope: when chat is index-scoped, only allow querying that index
|
|
174
|
-
if (
|
|
175
|
-
return error(`This chat is scoped to ${
|
|
179
|
+
if (scopedNetworkId && networkId !== scopedNetworkId) {
|
|
180
|
+
return error(`This chat is scoped to ${scopedIndexLabel}. You can only query members of this index.`);
|
|
176
181
|
}
|
|
177
182
|
const _readMembersGraphStart = Date.now();
|
|
178
183
|
const _readMembersTraceEmitter = requestContext.getStore()?.traceEmitter;
|
|
@@ -201,8 +206,8 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
201
206
|
const callerMemberships = await userDb.getNetworkMemberships();
|
|
202
207
|
if (networkId) {
|
|
203
208
|
// Strict scope enforcement: when chat is index-scoped, only allow querying that index
|
|
204
|
-
if (
|
|
205
|
-
return error(`This chat is scoped to ${
|
|
209
|
+
if (scopedNetworkId && networkId !== scopedNetworkId) {
|
|
210
|
+
return error(`This chat is scoped to ${scopedIndexLabel}. You can only query membership in this community.`);
|
|
206
211
|
}
|
|
207
212
|
const callerInIndex = callerMemberships.some((m) => m.networkId === networkId);
|
|
208
213
|
if (!callerInIndex) {
|
|
@@ -217,29 +222,29 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
217
222
|
}
|
|
218
223
|
else {
|
|
219
224
|
// Strict scope enforcement: when chat is index-scoped, only check the scoped index
|
|
220
|
-
if (
|
|
221
|
-
const isMember = await systemDb.isNetworkMember(
|
|
225
|
+
if (scopedNetworkId) {
|
|
226
|
+
const isMember = await systemDb.isNetworkMember(scopedNetworkId, targetUserId);
|
|
222
227
|
if (isMember) {
|
|
223
228
|
return success({
|
|
224
229
|
isMember: true,
|
|
225
230
|
userId: targetUserId,
|
|
226
|
-
networkId:
|
|
231
|
+
networkId: scopedNetworkId,
|
|
227
232
|
scopeRestriction: {
|
|
228
233
|
isScoped: true,
|
|
229
|
-
scopedToIndex:
|
|
230
|
-
message: `This chat is scoped to "${
|
|
234
|
+
scopedToIndex: scopedIndexLabel,
|
|
235
|
+
message: `This chat is scoped to "${scopedIndexLabel}". Only membership in this community is shown.`,
|
|
231
236
|
},
|
|
232
237
|
});
|
|
233
238
|
}
|
|
234
239
|
return success({
|
|
235
240
|
isMember: false,
|
|
236
241
|
userId: targetUserId,
|
|
237
|
-
networkId:
|
|
242
|
+
networkId: scopedNetworkId,
|
|
238
243
|
message: "User is not a member of this community.",
|
|
239
244
|
scopeRestriction: {
|
|
240
245
|
isScoped: true,
|
|
241
|
-
scopedToIndex:
|
|
242
|
-
message: `This chat is scoped to "${
|
|
246
|
+
scopedToIndex: scopedIndexLabel,
|
|
247
|
+
message: `This chat is scoped to "${scopedIndexLabel}". Only membership in this community was checked.`,
|
|
243
248
|
},
|
|
244
249
|
});
|
|
245
250
|
}
|
|
@@ -268,19 +273,18 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
268
273
|
else {
|
|
269
274
|
// Own memberships - use userDb
|
|
270
275
|
memberships = await userDb.getNetworkMemberships();
|
|
271
|
-
//
|
|
272
|
-
// what we show, not what we can reach.
|
|
273
|
-
// network is one element of it. See IND-306 for the equivalent in read_intents.
|
|
276
|
+
// The scope envelope's network id is the focus of the scoped chat — it filters
|
|
277
|
+
// what we show, not what we can reach. Concrete reach is derived separately.
|
|
274
278
|
// Strict scope enforcement: when chat is index-scoped, only return the scoped index membership
|
|
275
|
-
if (
|
|
276
|
-
memberships = memberships.filter((m) => m.networkId ===
|
|
279
|
+
if (scopedNetworkId && !networkId) {
|
|
280
|
+
memberships = memberships.filter((m) => m.networkId === scopedNetworkId);
|
|
277
281
|
}
|
|
278
282
|
}
|
|
279
283
|
// If both networkId and userId: filter to that specific membership
|
|
280
284
|
if (networkId) {
|
|
281
285
|
// Strict scope enforcement: when chat is index-scoped, only allow querying that index
|
|
282
|
-
if (
|
|
283
|
-
return error(`This chat is scoped to ${
|
|
286
|
+
if (scopedNetworkId && networkId !== scopedNetworkId) {
|
|
287
|
+
return error(`This chat is scoped to ${scopedIndexLabel}. You can only query membership in this community.`);
|
|
284
288
|
}
|
|
285
289
|
const callerMemberships = await userDb.getNetworkMemberships();
|
|
286
290
|
const callerInIndex = targetUserId === context.userId ||
|
|
@@ -302,7 +306,7 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
302
306
|
});
|
|
303
307
|
}
|
|
304
308
|
// When scoped, add clear metadata so model knows results are limited
|
|
305
|
-
if (
|
|
309
|
+
if (scopedNetworkId && targetUserId === context.userId) {
|
|
306
310
|
return success({
|
|
307
311
|
userId: targetUserId,
|
|
308
312
|
count: memberships.length,
|
|
@@ -314,8 +318,8 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
314
318
|
})),
|
|
315
319
|
scopeRestriction: {
|
|
316
320
|
isScoped: true,
|
|
317
|
-
scopedToIndex:
|
|
318
|
-
message: `Results are limited to "${
|
|
321
|
+
scopedToIndex: scopedIndexLabel,
|
|
322
|
+
message: `Results are limited to "${scopedIndexLabel}" because this chat is scoped to that community. The user may belong to other communities not shown here.`,
|
|
319
323
|
},
|
|
320
324
|
});
|
|
321
325
|
}
|
|
@@ -353,13 +357,15 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
353
357
|
settings: updateNetworkSettingsSchema.describe("Object with fields to update. All fields are optional — only include the ones to change. title: display name. prompt: purpose description (used for intent auto-assignment). imageUrl: community image URL (null to remove). joinPolicy: 'anyone' or 'invite_only'. allowGuestVibeCheck: boolean."),
|
|
354
358
|
}),
|
|
355
359
|
handler: async ({ context, query }) => {
|
|
356
|
-
const
|
|
360
|
+
const scopedNetworkId = focusedNetworkId(context);
|
|
361
|
+
const scopedIndexLabel = focusedNetworkLabel(context);
|
|
362
|
+
const effectiveIndexId = (query.networkId?.trim() || scopedNetworkId) ?? null;
|
|
357
363
|
if (!effectiveIndexId || !UUID_REGEX.test(effectiveIndexId)) {
|
|
358
364
|
return error("Valid networkId required.");
|
|
359
365
|
}
|
|
360
366
|
// Strict scope enforcement: when chat is index-scoped, only allow updating that index
|
|
361
|
-
if (
|
|
362
|
-
return error(`This chat is scoped to ${
|
|
367
|
+
if (scopedNetworkId && effectiveIndexId !== scopedNetworkId) {
|
|
368
|
+
return error(`This chat is scoped to ${scopedIndexLabel}. You can only update this community's settings.`);
|
|
363
369
|
}
|
|
364
370
|
const _updateNetworkGraphStart = Date.now();
|
|
365
371
|
const _updateNetworkTraceEmitter = requestContext.getStore()?.traceEmitter;
|
|
@@ -437,13 +443,15 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
437
443
|
networkId: z.string().optional().describe("Index UUID to delete. Get from read_networks. Defaults to the scoped index in index-scoped chats. Cannot be a personal index."),
|
|
438
444
|
}),
|
|
439
445
|
handler: async ({ context, query }) => {
|
|
440
|
-
const
|
|
446
|
+
const scopedNetworkId = focusedNetworkId(context);
|
|
447
|
+
const scopedIndexLabel = focusedNetworkLabel(context);
|
|
448
|
+
const networkId = query.networkId?.trim() || scopedNetworkId;
|
|
441
449
|
if (!networkId || !UUID_REGEX.test(networkId)) {
|
|
442
450
|
return error("Valid networkId required.");
|
|
443
451
|
}
|
|
444
452
|
// Strict scope enforcement: when chat is index-scoped, only allow deleting that index
|
|
445
|
-
if (
|
|
446
|
-
return error(`This chat is scoped to ${
|
|
453
|
+
if (scopedNetworkId && networkId !== scopedNetworkId) {
|
|
454
|
+
return error(`This chat is scoped to ${scopedIndexLabel}. You can only delete this community.`);
|
|
447
455
|
}
|
|
448
456
|
const _deleteNetworkGraphStart = Date.now();
|
|
449
457
|
const _deleteNetworkTraceEmitter = requestContext.getStore()?.traceEmitter;
|
|
@@ -476,14 +484,16 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
476
484
|
networkId: z.string().optional().describe("Index UUID to add the member to. Get from read_networks. Defaults to the scoped index in index-scoped chats."),
|
|
477
485
|
}),
|
|
478
486
|
handler: async ({ context, query }) => {
|
|
479
|
-
const
|
|
487
|
+
const scopedNetworkId = focusedNetworkId(context);
|
|
488
|
+
const scopedIndexLabel = focusedNetworkLabel(context);
|
|
489
|
+
const networkId = query.networkId?.trim() || scopedNetworkId;
|
|
480
490
|
const targetUserId = query.userId?.trim() || context.userId;
|
|
481
491
|
if (!networkId || !UUID_REGEX.test(networkId)) {
|
|
482
492
|
return error("Invalid index ID format. Use the exact UUID from read_networks.");
|
|
483
493
|
}
|
|
484
494
|
// Strict scope enforcement: when chat is index-scoped, only allow adding to that index
|
|
485
|
-
if (
|
|
486
|
-
return error(`This chat is scoped to ${
|
|
495
|
+
if (scopedNetworkId && networkId !== scopedNetworkId) {
|
|
496
|
+
return error(`This chat is scoped to ${scopedIndexLabel}. You can only add members to this community.`);
|
|
487
497
|
}
|
|
488
498
|
const _createMembershipGraphStart = Date.now();
|
|
489
499
|
const _createMembershipTraceEmitter = requestContext.getStore()?.traceEmitter;
|
|
@@ -523,7 +533,9 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
523
533
|
networkId: z.string().optional().describe("Index UUID to remove the member from. Get from read_networks. Defaults to the scoped index in index-scoped chats."),
|
|
524
534
|
}),
|
|
525
535
|
handler: async ({ context, query }) => {
|
|
526
|
-
const
|
|
536
|
+
const scopedNetworkId = focusedNetworkId(context);
|
|
537
|
+
const scopedIndexLabel = focusedNetworkLabel(context);
|
|
538
|
+
const networkId = query.networkId?.trim() || scopedNetworkId;
|
|
527
539
|
const targetUserId = query.userId?.trim();
|
|
528
540
|
if (!networkId || !UUID_REGEX.test(networkId)) {
|
|
529
541
|
return error("Valid networkId required. Use the exact UUID from read_networks.");
|
|
@@ -532,8 +544,8 @@ export function createNetworkTools(defineTool, deps) {
|
|
|
532
544
|
return error("userId is required.");
|
|
533
545
|
}
|
|
534
546
|
// Strict scope enforcement: when chat is index-scoped, only allow that index
|
|
535
|
-
if (
|
|
536
|
-
return error(`This chat is scoped to ${
|
|
547
|
+
if (scopedNetworkId && networkId !== scopedNetworkId) {
|
|
548
|
+
return error(`This chat is scoped to ${scopedIndexLabel}. You can only manage members of this community.`);
|
|
537
549
|
}
|
|
538
550
|
const _deleteMembershipGraphStart = Date.now();
|
|
539
551
|
const _deleteMembershipTraceEmitter = requestContext.getStore()?.traceEmitter;
|