@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
|
@@ -4,7 +4,7 @@ import type { DefineTool, ToolDeps } from "../shared/agent/tool.helpers.js";
|
|
|
4
4
|
* Exposes `read_pending_questions` for retrieving the caller's pending
|
|
5
5
|
* questions generated by QuestionerAgent (enrichment, intent, negotiation, discovery modes).
|
|
6
6
|
*
|
|
7
|
-
* Network-scoped agent keys (context.
|
|
7
|
+
* Network-scoped agent keys (context.scopeType/scopeId set via applyNetworkScopeToContext)
|
|
8
8
|
* are clamped to self-owned modes; the result then carries a `scopeRestriction`
|
|
9
9
|
* block mirroring the network-tools convention.
|
|
10
10
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"questioner.tools.d.ts","sourceRoot":"/","sources":["questioner/questioner.tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"questioner.tools.d.ts","sourceRoot":"/","sources":["questioner/questioner.tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAwB5E;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,kBA6E3E"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { error, success } from "../shared/agent/tool.helpers.js";
|
|
3
|
+
import { focusedNetworkId, focusedNetworkLabel } from "../shared/agent/tool.scope.js";
|
|
3
4
|
/**
|
|
4
5
|
* Detection modes whose questions derive solely from the caller's own data
|
|
5
6
|
* (profile gaps, own intents, own discovery sessions). Negotiation-mode
|
|
@@ -20,7 +21,7 @@ function stripInternalActors(question) {
|
|
|
20
21
|
* Exposes `read_pending_questions` for retrieving the caller's pending
|
|
21
22
|
* questions generated by QuestionerAgent (enrichment, intent, negotiation, discovery modes).
|
|
22
23
|
*
|
|
23
|
-
* Network-scoped agent keys (context.
|
|
24
|
+
* Network-scoped agent keys (context.scopeType/scopeId set via applyNetworkScopeToContext)
|
|
24
25
|
* are clamped to self-owned modes; the result then carries a `scopeRestriction`
|
|
25
26
|
* block mirroring the network-tools convention.
|
|
26
27
|
*
|
|
@@ -56,9 +57,7 @@ export function createQuestionerTools(defineTool, deps) {
|
|
|
56
57
|
}
|
|
57
58
|
const limit = query.limit ?? 10;
|
|
58
59
|
// Scoped-key discriminator: scoped contexts carry a network scope envelope.
|
|
59
|
-
const scopedNetworkId = context
|
|
60
|
-
? context.scopeId
|
|
61
|
-
: context.networkId;
|
|
60
|
+
const scopedNetworkId = focusedNetworkId(context);
|
|
62
61
|
const isScoped = Boolean(scopedNetworkId);
|
|
63
62
|
try {
|
|
64
63
|
const fetched = await deps.findPendingQuestions(context.userId, {
|
|
@@ -79,7 +78,7 @@ export function createQuestionerTools(defineTool, deps) {
|
|
|
79
78
|
questions: limited,
|
|
80
79
|
scopeRestriction: {
|
|
81
80
|
isScoped: true,
|
|
82
|
-
scopedToIndex: context
|
|
81
|
+
scopedToIndex: focusedNetworkLabel(context),
|
|
83
82
|
message: `Results are restricted to "${context.indexName ?? "this index"}" and ` +
|
|
84
83
|
`exclude negotiation questions because this agent is scoped to that index.`,
|
|
85
84
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"questioner.tools.js","sourceRoot":"/","sources":["questioner/questioner.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"questioner.tools.js","sourceRoot":"/","sources":["questioner/questioner.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAItF;;;;;;GAMG;AACH,MAAM,gBAAgB,GAAmB,CAAC,YAAY,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC;AAE/E,SAAS,wBAAwB,CAAC,QAAgC,EAAE,MAAc,EAAE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AE,OAAO,CAAC,MAAM;iBACvB,CAAC,CAAC;gBACH,OAAO,KAAK,CAAC,mCAAmC,CAAC,CAAC;YACpD,CAAC;QACH,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,oBAAoB,CAAU,CAAC;AACzC,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { error, success } from \"../shared/agent/tool.helpers.js\";\nimport { focusedNetworkId, focusedNetworkLabel } from \"../shared/agent/tool.scope.js\";\nimport type { PendingQuestionSummary } from \"../shared/schemas/pending-question.schema.js\";\nimport type { QuestionMode } from \"../shared/schemas/question.schema.js\";\n\n/**\n * Detection modes whose questions derive solely from the caller's own data\n * (profile gaps, own intents, own discovery sessions). Negotiation-mode\n * questions are excluded for network-scoped agents: their prompts are seeded\n * from opportunity metadata that can reference out-of-scope networks and\n * other users' content (same leak class as the getOpportunitiesForUser fix).\n */\nconst SELF_OWNED_MODES: QuestionMode[] = [\"enrichment\", \"intent\", \"discovery\"];\n\nfunction isVisibleInScopedNetwork(question: PendingQuestionSummary, userId: string, networkId: string): boolean {\n return question.actors?.some((actor) => actor.userId === userId && actor.networkId === networkId) === true;\n}\n\nfunction stripInternalActors(question: PendingQuestionSummary): Omit<PendingQuestionSummary, \"actors\"> {\n const { actors: _actors, ...publicQuestion } = question;\n return publicQuestion;\n}\n\n/**\n * Creates MCP tool definitions for the questioner domain.\n * Exposes `read_pending_questions` for retrieving the caller's pending\n * questions generated by QuestionerAgent (enrichment, intent, negotiation, discovery modes).\n *\n * Network-scoped agent keys (context.scopeType/scopeId set via applyNetworkScopeToContext)\n * are clamped to self-owned modes; the result then carries a `scopeRestriction`\n * block mirroring the network-tools convention.\n *\n * @param defineTool - Tool factory provided by the composition root.\n * @param deps - Shared tool dependencies; `findPendingQuestions` is optional\n * and the tool fails gracefully when absent.\n */\nexport function createQuestionerTools(defineTool: DefineTool, deps: ToolDeps) {\n const readPendingQuestions = defineTool({\n name: \"read_pending_questions\",\n description:\n \"Returns pending questions generated for the authenticated user across all modes \" +\n \"(profile, intent, negotiation, discovery). These are questions generated by the \" +\n \"system to help surface missing signals, refine intents, or capture engagement context.\\n\\n\" +\n \"**Returns:** List of pending questions, each with `id`, `title`, `prompt`, `options`, \" +\n \"`multiSelect`, `mode`, `sourceType`, `sourceId`, `createdAt`, and optional `expiresAt`. \" +\n \"Network-scoped agents receive only profile/intent/discovery questions for the scoped network plus a \" +\n \"`scopeRestriction` note.\\n\\n\" +\n \"**Use:** Call with no arguments to get all pending questions, or pass `limit` to cap the \" +\n \"count. For the daily brief the script calls with a small `limit` and renders the first \" +\n \"question that has not been delivered yet.\",\n querySchema: z.object({\n limit: z\n .number()\n .int()\n .min(1)\n .max(10)\n .optional()\n .describe(\"Maximum number of questions to return (1-10, default 10).\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.findPendingQuestions) {\n return error(\"Question lookup is not available.\");\n }\n\n const limit = query.limit ?? 10;\n // Scoped-key discriminator: scoped contexts carry a network scope envelope.\n const scopedNetworkId = focusedNetworkId(context);\n const isScoped = Boolean(scopedNetworkId);\n\n try {\n const fetched = await deps.findPendingQuestions(context.userId, {\n ...(isScoped ? { modes: SELF_OWNED_MODES, networkId: scopedNetworkId } : {}),\n limit,\n });\n // Defense-in-depth: hosts apply `modes`/`networkId`/`limit` SQL-side;\n // re-apply all three here so the clamp holds even when a custom dep\n // ignores the filters. Scoped rows without actor network metadata are\n // hidden fail-closed because they cannot prove membership in this scope.\n const visible = isScoped\n ? fetched.filter(\n (q) =>\n (SELF_OWNED_MODES as string[]).includes(q.mode) &&\n isVisibleInScopedNetwork(q, context.userId, scopedNetworkId!),\n )\n : fetched;\n const limited = visible.slice(0, limit).map(stripInternalActors);\n\n if (isScoped) {\n return success({\n questions: limited,\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: focusedNetworkLabel(context),\n message:\n `Results are restricted to \"${context.indexName ?? \"this index\"}\" and ` +\n `exclude negotiation questions because this agent is scoped to that index.`,\n },\n });\n }\n\n return success({ questions: limited });\n } catch (err) {\n deps.reportToolError?.(err, {\n operation: \"read-pending-questions\",\n toolName: \"read_pending_questions\",\n userId: context.userId,\n });\n return error(\"Failed to read pending questions.\");\n }\n },\n });\n\n return [readPendingQuestions] as const;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.factory.d.ts","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAmE,MAAM,mBAAmB,CAAC;AAehJ,YAAY,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACxF,YAAY,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAQlD;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,WAAW,EACjB,kBAAkB,CAAC,EAAE,mBAAmB,
|
|
1
|
+
{"version":3,"file":"tool.factory.d.ts","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAmE,MAAM,mBAAmB,CAAC;AAehJ,YAAY,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACxF,YAAY,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAQlD;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,WAAW,EACjB,kBAAkB,CAAC,EAAE,mBAAmB,kBAkNzC;AAED;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC,CAAC"}
|
|
@@ -39,22 +39,23 @@ const logger = protocolLogger("ChatTools");
|
|
|
39
39
|
*/
|
|
40
40
|
export async function createChatTools(deps, preResolvedContext) {
|
|
41
41
|
const { database, embedder, scraper } = deps;
|
|
42
|
+
const explicitScope = deps.scopeType && deps.scopeId
|
|
43
|
+
? { scopeType: deps.scopeType, scopeId: deps.scopeId }
|
|
44
|
+
: scopeFromNetworkId(deps.networkId);
|
|
42
45
|
// ─── Resolve context from DB ───────────────────────────────────────────────
|
|
46
|
+
// resolveChatContext still accepts a networkId because it loads scoped index
|
|
47
|
+
// presentation metadata; the canonical request scope is explicitScope.
|
|
43
48
|
const resolvedContext = preResolvedContext ??
|
|
44
49
|
(await resolveChatContext({
|
|
45
50
|
database,
|
|
46
51
|
userId: deps.userId,
|
|
47
|
-
networkId: deps.networkId,
|
|
52
|
+
networkId: explicitScope.scopeType === 'network' ? explicitScope.scopeId : deps.networkId,
|
|
48
53
|
sessionId: deps.sessionId,
|
|
49
54
|
contactsEnabled: deps.contactsEnabled,
|
|
50
55
|
}));
|
|
51
|
-
const explicitScope = deps.scopeType && deps.scopeId
|
|
52
|
-
? { scopeType: deps.scopeType, scopeId: deps.scopeId }
|
|
53
|
-
: scopeFromNetworkId(deps.networkId);
|
|
54
56
|
if (!preResolvedContext && explicitScope.scopeType && explicitScope.scopeId) {
|
|
55
57
|
resolvedContext.scopeType = explicitScope.scopeType;
|
|
56
58
|
resolvedContext.scopeId = explicitScope.scopeId;
|
|
57
|
-
resolvedContext.networkId = explicitScope.scopeId;
|
|
58
59
|
}
|
|
59
60
|
const allowedNetworkIds = deriveAllowedNetworkIds({
|
|
60
61
|
memberships: resolvedContext.userNetworks,
|
|
@@ -62,8 +63,6 @@ export async function createChatTools(deps, preResolvedContext) {
|
|
|
62
63
|
? { scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId }
|
|
63
64
|
: {}),
|
|
64
65
|
});
|
|
65
|
-
// Deprecated compatibility reach until remaining tool call sites migrate.
|
|
66
|
-
resolvedContext.indexScope = allowedNetworkIds;
|
|
67
66
|
// ─── Tool wrapper ──────────────────────────────────────────────────────────
|
|
68
67
|
/**
|
|
69
68
|
* Standardized tool factory. Auto-injects resolved context and
|
|
@@ -72,7 +71,7 @@ export async function createChatTools(deps, preResolvedContext) {
|
|
|
72
71
|
function defineTool(opts) {
|
|
73
72
|
return tool(async (query) => {
|
|
74
73
|
logger.info(`Tool: ${opts.name}`, {
|
|
75
|
-
context: { userId: resolvedContext.userId,
|
|
74
|
+
context: { userId: resolvedContext.userId, scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId },
|
|
76
75
|
query: redactSensitiveFields(query),
|
|
77
76
|
});
|
|
78
77
|
try {
|
|
@@ -128,8 +127,8 @@ export async function createChatTools(deps, preResolvedContext) {
|
|
|
128
127
|
// update) use the same adapter as the rest of the tool pipeline.
|
|
129
128
|
//
|
|
130
129
|
// The systemDb's DB-level clamp derives concrete allowed network IDs from the
|
|
131
|
-
// focused scope envelope plus memberships
|
|
132
|
-
//
|
|
130
|
+
// focused scope envelope plus memberships, rather than consuming a transported
|
|
131
|
+
// legacy indexScope array.
|
|
133
132
|
const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);
|
|
134
133
|
const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, allowedNetworkIds, embedder);
|
|
135
134
|
// ─── Assemble dependencies ─────────────────────────────────────────────────
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.factory.js","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAG7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAC9E,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B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AAG,IAAI,GAAG,CAAC;QAC5C,8BAA8B;KAC/B,CAAC,CAAC;IACH,MAAM,uBAAuB,GAAG,gBAAgB,CAAC,MAAM,CACrD,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,6BAA6B,CAAC,GAAG,CAAE,CAAsB,CAAC,IAAI,CAAC,CACxE,CAAC;IAEF,OAAO;QACL,GAAG,YAAY;QACf,GAAG,WAAW;QACd,GAAG,YAAY;QACf,GAAG,uBAAuB;QAC1B,GAAG,YAAY;QACf,GAAG,gBAAgB;QACnB,GAAG,YAAY;QACf,GAAG,UAAU;QACb,GAAG,gBAAgB;QACnB,GAAG,YAAY;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport type { HydeGraphDatabase } from \"../interfaces/database.interface.js\";\nimport { IntentGraphFactory } from \"../../intent/intent.graph.js\";\nimport { EnrichmentGraphFactory } from \"../../enrichment/enrichment.graph.js\";\nimport { OpportunityGraphFactory } from \"../../opportunity/opportunity.graph.js\";\nimport { HydeGraphFactory } from \"../hyde/hyde.graph.js\";\nimport { HydeGenerator } from \"../hyde/hyde.generator.js\";\nimport { LensInferrer } from \"../hyde/lens.inferrer.js\";\nimport { NetworkGraphFactory } from \"../../network/network.graph.js\";\nimport { NetworkMembershipGraphFactory } from \"../../network/membership/membership.graph.js\";\nimport { IntentNetworkGraphFactory } from \"../../network/indexer/indexer.graph.js\";\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { NegotiationGraphFactory } from \"../../negotiation/negotiation.graph.js\";\nimport { PremiseGraphFactory } from \"../../premise/premise.graph.js\";\nimport { protocolLogger } from \"../observability/protocol.logger.js\";\n\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\n\nimport { type ToolContext, type ResolvedToolContext, type ToolDeps, resolveChatContext, error, redactSensitiveFields } from \"./tool.helpers.js\";\nimport { deriveAllowedNetworkIds, scopeFromNetworkId } from \"./tool.scope.js\";\nimport { invokeToolRuntime, toolRuntimeErrorToResult } from \"./tool.runtime.js\";\nimport { createEnrichmentTools } from \"../../enrichment/enrichment.tools.js\";\nimport { createIntentTools } from \"../../intent/intent.tools.js\";\nimport { createNetworkTools } from \"../../network/network.tools.js\";\nimport { createOpportunityTools } from \"../../opportunity/opportunity.tools.js\";\nimport { createUtilityTools } from \"./utility.tools.js\";\nimport { createIntegrationTools } from \"../../integration/integration.tools.js\";\nimport { createContactTools } from \"../../contact/contact.tools.js\";\nimport { createAgentTools } from \"../../agent/agent.tools.js\";\nimport { createNegotiationTools } from \"../../negotiation/negotiation.tools.js\";\nimport { createPremiseTools } from \"../../premise/premise.tools.js\";\n\n// Re-export types for consumers\nexport type { ToolContext, ResolvedToolContext, ProtocolDeps } from \"./tool.helpers.js\";\nexport type { ToolDeps } from \"./tool.helpers.js\";\n\nconst logger = protocolLogger(\"ChatTools\");\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates all chat tools bound to a specific user context.\n * Resolves user/index identity from DB at init time.\n * Tools are created fresh for each user session to ensure proper isolation.\n *\n * All external dependencies (cache, integration, queue, etc.) are provided\n * via the `deps` parameter — the protocol lib never imports concrete adapters.\n */\nexport async function createChatTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext\n) {\n const { database, embedder, scraper } = deps;\n\n // ─── Resolve context from DB ───────────────────────────────────────────────\n const resolvedContext =\n preResolvedContext ??\n (await resolveChatContext({\n database,\n userId: deps.userId,\n networkId: deps.networkId,\n sessionId: deps.sessionId,\n contactsEnabled: deps.contactsEnabled,\n }));\n\n const explicitScope = deps.scopeType && deps.scopeId\n ? { scopeType: deps.scopeType, scopeId: deps.scopeId }\n : scopeFromNetworkId(deps.networkId);\n\n if (!preResolvedContext && explicitScope.scopeType && explicitScope.scopeId) {\n resolvedContext.scopeType = explicitScope.scopeType;\n resolvedContext.scopeId = explicitScope.scopeId;\n resolvedContext.networkId = explicitScope.scopeId;\n }\n\n const allowedNetworkIds = deriveAllowedNetworkIds({\n memberships: resolvedContext.userNetworks,\n ...(resolvedContext.scopeType && resolvedContext.scopeId\n ? { scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId }\n : {}),\n });\n // Deprecated compatibility reach until remaining tool call sites migrate.\n resolvedContext.indexScope = allowedNetworkIds;\n\n // ─── Tool wrapper ──────────────────────────────────────────────────────────\n /**\n * Standardized tool factory. Auto-injects resolved context and\n * provides uniform logging / error handling for every tool.\n */\n function defineTool<T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n }) {\n return tool(\n async (query: z.infer<T>) => {\n logger.info(`Tool: ${opts.name}`, {\n context: { userId: resolvedContext.userId, networkId: resolvedContext.networkId },\n query: redactSensitiveFields(query),\n });\n try {\n return await invokeToolRuntime({\n toolName: opts.name,\n tool: { handler: async ({ context, query }) => opts.handler({ context, query: query as z.infer<T> }) },\n context: resolvedContext,\n query,\n });\n } catch (err) {\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n const runtimeResult = toolRuntimeErrorToResult(err);\n if (runtimeResult) return runtimeResult;\n const reason = err instanceof Error ? err.message : String(err);\n return error(`Failed to execute ${opts.name}: ${reason}`);\n }\n },\n { name: opts.name, description: opts.description, schema: opts.querySchema }\n );\n }\n\n // ─── Compile subgraphs ─────────────────────────────────────────────────────\n\n // Wrap questionerEnqueue to include scoped/session context when available.\n const sessionAwareEnqueue: QuestionerEnqueueFn | undefined = deps.questionerEnqueue\n ? (input) => deps.questionerEnqueue!({\n ...input,\n ...(resolvedContext.scopeType && resolvedContext.scopeId && !input.scopeId\n ? { scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId }\n : {}),\n ...(resolvedContext.sessionId && !input.conversationId ? { conversationId: resolvedContext.sessionId } : {}),\n })\n : undefined;\n\n const intentGraph = new IntentGraphFactory(database, embedder, deps.intentQueue, sessionAwareEnqueue).createGraph();\n const premiseGraph = new PremiseGraphFactory(database, embedder).createGraph();\n const profileGraph = new EnrichmentGraphFactory(database, scraper, deps.enricher, sessionAwareEnqueue, premiseGraph).createGraph();\n const hydeCache = deps.hydeCache;\n const lensInferrer = new LensInferrer();\n const hydeGenerator = new HydeGenerator();\n const compiledHydeGraph = new HydeGraphFactory(\n database as unknown as HydeGraphDatabase,\n embedder,\n hydeCache,\n lensInferrer,\n hydeGenerator\n ).createGraph();\n const negotiationGraph = deps.agentDispatcher\n ? new NegotiationGraphFactory(\n deps.negotiationDatabase,\n deps.agentDispatcher,\n deps.negotiationTimeoutQueue,\n sessionAwareEnqueue,\n ).createGraph()\n : undefined;\n const opportunityGraph = new OpportunityGraphFactory(\n database,\n embedder,\n compiledHydeGraph,\n undefined, // evaluator (default)\n undefined, // queueNotification\n negotiationGraph,\n deps.agentDispatcher,\n deps.queueNegotiateExisting,\n ).createGraph();\n const networkGraph = new NetworkGraphFactory(database).createGraph();\n const networkMembershipGraph = new NetworkMembershipGraphFactory(database).createGraph();\n const intentNetworkGraph = new IntentNetworkGraphFactory(database, new IntentIndexer()).createGraph();\n\n // ─── Create context-bound databases ────────────────────────────────────────\n // Use injected instances when provided (e.g. tests). Otherwise create from the same\n // database used for graphs so that scope checks (e.g. ensureScopedMembership, opportunity\n // update) use the same adapter as the rest of the tool pipeline.\n //\n // The systemDb's DB-level clamp derives concrete allowed network IDs from the\n // focused scope envelope plus memberships. The legacy indexScope field is\n // populated above only as a compatibility bridge for unmigrated tool call sites.\n const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);\n const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, allowedNetworkIds, embedder);\n\n // ─── Assemble dependencies ─────────────────────────────────────────────────\n const cache = deps.cache;\n const integration = deps.integration;\n const toolDeps: ToolDeps = {\n database,\n userDb,\n systemDb,\n scraper,\n embedder,\n cache,\n integration,\n contactService: deps.contactService,\n contactsEnabled: deps.contactsEnabled,\n integrationImporter: deps.integrationImporter,\n enricher: deps.enricher,\n negotiationDatabase: deps.negotiationDatabase,\n negotiationTimeoutQueue: deps.negotiationTimeoutQueue,\n agentDatabase: deps.agentDatabase,\n grantDefaultSystemPermissions: deps.grantDefaultSystemPermissions,\n agentDispatcher: deps.agentDispatcher,\n deliveryLedger: deps.deliveryLedger,\n discoveryRuns: deps.discoveryRuns,\n discoveryRunQueue: deps.discoveryRunQueue,\n enrichmentRuns: deps.enrichmentRuns,\n enrichmentRunQueue: deps.enrichmentRunQueue,\n mintConnectToken: deps.mintConnectToken,\n mintConnectLink: deps.mintConnectLink,\n frontendUrl: deps.frontendUrl,\n apiBaseUrl: deps.apiBaseUrl,\n ...(deps.premiseEvents && { premiseEvents: deps.premiseEvents }),\n ...(deps.chatSummary && { chatSummary: deps.chatSummary }),\n ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),\n ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),\n ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),\n graphs: {\n profile: profileGraph,\n intent: intentGraph,\n index: networkGraph,\n networkMembership: networkMembershipGraph,\n intentIndex: intentNetworkGraph,\n opportunity: opportunityGraph,\n premise: premiseGraph,\n },\n };\n\n // ─── Create domain tools ──────────────────────────────────────────────────\n const profileTools = createEnrichmentTools(defineTool, toolDeps);\n const intentTools = createIntentTools(defineTool, toolDeps);\n const networkTools = createNetworkTools(defineTool, toolDeps);\n const opportunityTools = createOpportunityTools(defineTool, toolDeps);\n const utilityTools = createUtilityTools(defineTool, toolDeps);\n const contactTools = createContactTools(defineTool, toolDeps);\n const agentTools = createAgentTools(defineTool, toolDeps);\n const integrationTools = createIntegrationTools(defineTool, toolDeps);\n const negotiationTools = deps.agentDispatcher\n ? createNegotiationTools(defineTool, toolDeps)\n : [];\n const premiseTools = createPremiseTools(defineTool, toolDeps);\n\n // confirm_opportunity_delivery is an OpenClaw-delivery ledger write and must not be\n // callable from regular chat sessions.\n const chatOpportunityToolExclusions = new Set([\n \"confirm_opportunity_delivery\",\n ]);\n const opportunityToolsForChat = opportunityTools.filter(\n (t) => !chatOpportunityToolExclusions.has((t as { name: string }).name)\n );\n\n return [\n ...profileTools,\n ...intentTools,\n ...networkTools,\n ...opportunityToolsForChat,\n ...utilityTools,\n ...integrationTools,\n ...contactTools,\n ...agentTools,\n ...negotiationTools,\n ...premiseTools,\n ];\n}\n\n/**\n * Type for the tools array returned by createChatTools.\n */\nexport type ChatTools = Awaited<ReturnType<typeof createChatTools>>;\n"]}
|
|
1
|
+
{"version":3,"file":"tool.factory.js","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAG7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAC9E,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,6BAA6B,EAAE,MAAM,8CAA8C,CAAC;AAC7F,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AACnF,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AAIrE,OAAO,EAA6D,kBAAkB,EAAE,KAAK,EAAE,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ACnB,GAAG,YAAY;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport type { HydeGraphDatabase } from \"../interfaces/database.interface.js\";\nimport { IntentGraphFactory } from \"../../intent/intent.graph.js\";\nimport { EnrichmentGraphFactory } from \"../../enrichment/enrichment.graph.js\";\nimport { OpportunityGraphFactory } from \"../../opportunity/opportunity.graph.js\";\nimport { HydeGraphFactory } from \"../hyde/hyde.graph.js\";\nimport { HydeGenerator } from \"../hyde/hyde.generator.js\";\nimport { LensInferrer } from \"../hyde/lens.inferrer.js\";\nimport { NetworkGraphFactory } from \"../../network/network.graph.js\";\nimport { NetworkMembershipGraphFactory } from \"../../network/membership/membership.graph.js\";\nimport { IntentNetworkGraphFactory } from \"../../network/indexer/indexer.graph.js\";\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { NegotiationGraphFactory } from \"../../negotiation/negotiation.graph.js\";\nimport { PremiseGraphFactory } from \"../../premise/premise.graph.js\";\nimport { protocolLogger } from \"../observability/protocol.logger.js\";\n\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\n\nimport { type ToolContext, type ResolvedToolContext, type ToolDeps, resolveChatContext, error, redactSensitiveFields } from \"./tool.helpers.js\";\nimport { deriveAllowedNetworkIds, scopeFromNetworkId } from \"./tool.scope.js\";\nimport { invokeToolRuntime, toolRuntimeErrorToResult } from \"./tool.runtime.js\";\nimport { createEnrichmentTools } from \"../../enrichment/enrichment.tools.js\";\nimport { createIntentTools } from \"../../intent/intent.tools.js\";\nimport { createNetworkTools } from \"../../network/network.tools.js\";\nimport { createOpportunityTools } from \"../../opportunity/opportunity.tools.js\";\nimport { createUtilityTools } from \"./utility.tools.js\";\nimport { createIntegrationTools } from \"../../integration/integration.tools.js\";\nimport { createContactTools } from \"../../contact/contact.tools.js\";\nimport { createAgentTools } from \"../../agent/agent.tools.js\";\nimport { createNegotiationTools } from \"../../negotiation/negotiation.tools.js\";\nimport { createPremiseTools } from \"../../premise/premise.tools.js\";\n\n// Re-export types for consumers\nexport type { ToolContext, ResolvedToolContext, ProtocolDeps } from \"./tool.helpers.js\";\nexport type { ToolDeps } from \"./tool.helpers.js\";\n\nconst logger = protocolLogger(\"ChatTools\");\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates all chat tools bound to a specific user context.\n * Resolves user/index identity from DB at init time.\n * Tools are created fresh for each user session to ensure proper isolation.\n *\n * All external dependencies (cache, integration, queue, etc.) are provided\n * via the `deps` parameter — the protocol lib never imports concrete adapters.\n */\nexport async function createChatTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext\n) {\n const { database, embedder, scraper } = deps;\n\n const explicitScope = deps.scopeType && deps.scopeId\n ? { scopeType: deps.scopeType, scopeId: deps.scopeId }\n : scopeFromNetworkId(deps.networkId);\n\n // ─── Resolve context from DB ───────────────────────────────────────────────\n // resolveChatContext still accepts a networkId because it loads scoped index\n // presentation metadata; the canonical request scope is explicitScope.\n const resolvedContext =\n preResolvedContext ??\n (await resolveChatContext({\n database,\n userId: deps.userId,\n networkId: explicitScope.scopeType === 'network' ? explicitScope.scopeId : deps.networkId,\n sessionId: deps.sessionId,\n contactsEnabled: deps.contactsEnabled,\n }));\n\n if (!preResolvedContext && explicitScope.scopeType && explicitScope.scopeId) {\n resolvedContext.scopeType = explicitScope.scopeType;\n resolvedContext.scopeId = explicitScope.scopeId;\n }\n\n const allowedNetworkIds = deriveAllowedNetworkIds({\n memberships: resolvedContext.userNetworks,\n ...(resolvedContext.scopeType && resolvedContext.scopeId\n ? { scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId }\n : {}),\n });\n\n // ─── Tool wrapper ──────────────────────────────────────────────────────────\n /**\n * Standardized tool factory. Auto-injects resolved context and\n * provides uniform logging / error handling for every tool.\n */\n function defineTool<T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n }) {\n return tool(\n async (query: z.infer<T>) => {\n logger.info(`Tool: ${opts.name}`, {\n context: { userId: resolvedContext.userId, scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId },\n query: redactSensitiveFields(query),\n });\n try {\n return await invokeToolRuntime({\n toolName: opts.name,\n tool: { handler: async ({ context, query }) => opts.handler({ context, query: query as z.infer<T> }) },\n context: resolvedContext,\n query,\n });\n } catch (err) {\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n const runtimeResult = toolRuntimeErrorToResult(err);\n if (runtimeResult) return runtimeResult;\n const reason = err instanceof Error ? err.message : String(err);\n return error(`Failed to execute ${opts.name}: ${reason}`);\n }\n },\n { name: opts.name, description: opts.description, schema: opts.querySchema }\n );\n }\n\n // ─── Compile subgraphs ─────────────────────────────────────────────────────\n\n // Wrap questionerEnqueue to include scoped/session context when available.\n const sessionAwareEnqueue: QuestionerEnqueueFn | undefined = deps.questionerEnqueue\n ? (input) => deps.questionerEnqueue!({\n ...input,\n ...(resolvedContext.scopeType && resolvedContext.scopeId && !input.scopeId\n ? { scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId }\n : {}),\n ...(resolvedContext.sessionId && !input.conversationId ? { conversationId: resolvedContext.sessionId } : {}),\n })\n : undefined;\n\n const intentGraph = new IntentGraphFactory(database, embedder, deps.intentQueue, sessionAwareEnqueue).createGraph();\n const premiseGraph = new PremiseGraphFactory(database, embedder).createGraph();\n const profileGraph = new EnrichmentGraphFactory(database, scraper, deps.enricher, sessionAwareEnqueue, premiseGraph).createGraph();\n const hydeCache = deps.hydeCache;\n const lensInferrer = new LensInferrer();\n const hydeGenerator = new HydeGenerator();\n const compiledHydeGraph = new HydeGraphFactory(\n database as unknown as HydeGraphDatabase,\n embedder,\n hydeCache,\n lensInferrer,\n hydeGenerator\n ).createGraph();\n const negotiationGraph = deps.agentDispatcher\n ? new NegotiationGraphFactory(\n deps.negotiationDatabase,\n deps.agentDispatcher,\n deps.negotiationTimeoutQueue,\n sessionAwareEnqueue,\n ).createGraph()\n : undefined;\n const opportunityGraph = new OpportunityGraphFactory(\n database,\n embedder,\n compiledHydeGraph,\n undefined, // evaluator (default)\n undefined, // queueNotification\n negotiationGraph,\n deps.agentDispatcher,\n deps.queueNegotiateExisting,\n ).createGraph();\n const networkGraph = new NetworkGraphFactory(database).createGraph();\n const networkMembershipGraph = new NetworkMembershipGraphFactory(database).createGraph();\n const intentNetworkGraph = new IntentNetworkGraphFactory(database, new IntentIndexer()).createGraph();\n\n // ─── Create context-bound databases ────────────────────────────────────────\n // Use injected instances when provided (e.g. tests). Otherwise create from the same\n // database used for graphs so that scope checks (e.g. ensureScopedMembership, opportunity\n // update) use the same adapter as the rest of the tool pipeline.\n //\n // The systemDb's DB-level clamp derives concrete allowed network IDs from the\n // focused scope envelope plus memberships, rather than consuming a transported\n // legacy indexScope array.\n const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);\n const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, allowedNetworkIds, embedder);\n\n // ─── Assemble dependencies ─────────────────────────────────────────────────\n const cache = deps.cache;\n const integration = deps.integration;\n const toolDeps: ToolDeps = {\n database,\n userDb,\n systemDb,\n scraper,\n embedder,\n cache,\n integration,\n contactService: deps.contactService,\n contactsEnabled: deps.contactsEnabled,\n integrationImporter: deps.integrationImporter,\n enricher: deps.enricher,\n negotiationDatabase: deps.negotiationDatabase,\n negotiationTimeoutQueue: deps.negotiationTimeoutQueue,\n agentDatabase: deps.agentDatabase,\n grantDefaultSystemPermissions: deps.grantDefaultSystemPermissions,\n agentDispatcher: deps.agentDispatcher,\n deliveryLedger: deps.deliveryLedger,\n discoveryRuns: deps.discoveryRuns,\n discoveryRunQueue: deps.discoveryRunQueue,\n enrichmentRuns: deps.enrichmentRuns,\n enrichmentRunQueue: deps.enrichmentRunQueue,\n mintConnectToken: deps.mintConnectToken,\n mintConnectLink: deps.mintConnectLink,\n frontendUrl: deps.frontendUrl,\n apiBaseUrl: deps.apiBaseUrl,\n ...(deps.premiseEvents && { premiseEvents: deps.premiseEvents }),\n ...(deps.chatSummary && { chatSummary: deps.chatSummary }),\n ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),\n ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),\n ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),\n graphs: {\n profile: profileGraph,\n intent: intentGraph,\n index: networkGraph,\n networkMembership: networkMembershipGraph,\n intentIndex: intentNetworkGraph,\n opportunity: opportunityGraph,\n premise: premiseGraph,\n },\n };\n\n // ─── Create domain tools ──────────────────────────────────────────────────\n const profileTools = createEnrichmentTools(defineTool, toolDeps);\n const intentTools = createIntentTools(defineTool, toolDeps);\n const networkTools = createNetworkTools(defineTool, toolDeps);\n const opportunityTools = createOpportunityTools(defineTool, toolDeps);\n const utilityTools = createUtilityTools(defineTool, toolDeps);\n const contactTools = createContactTools(defineTool, toolDeps);\n const agentTools = createAgentTools(defineTool, toolDeps);\n const integrationTools = createIntegrationTools(defineTool, toolDeps);\n const negotiationTools = deps.agentDispatcher\n ? createNegotiationTools(defineTool, toolDeps)\n : [];\n const premiseTools = createPremiseTools(defineTool, toolDeps);\n\n // confirm_opportunity_delivery is an OpenClaw-delivery ledger write and must not be\n // callable from regular chat sessions.\n const chatOpportunityToolExclusions = new Set([\n \"confirm_opportunity_delivery\",\n ]);\n const opportunityToolsForChat = opportunityTools.filter(\n (t) => !chatOpportunityToolExclusions.has((t as { name: string }).name)\n );\n\n return [\n ...profileTools,\n ...intentTools,\n ...networkTools,\n ...opportunityToolsForChat,\n ...utilityTools,\n ...integrationTools,\n ...contactTools,\n ...agentTools,\n ...negotiationTools,\n ...premiseTools,\n ];\n}\n\n/**\n * Type for the tools array returned by createChatTools.\n */\nexport type ChatTools = Awaited<ReturnType<typeof createChatTools>>;\n"]}
|
|
@@ -33,7 +33,7 @@ export function createToolRegistry(deps) {
|
|
|
33
33
|
schema: opts.querySchema,
|
|
34
34
|
handler: async (input) => {
|
|
35
35
|
logger.verbose(`Tool: ${opts.name}`, {
|
|
36
|
-
context: { userId: input.context.userId,
|
|
36
|
+
context: { userId: input.context.userId, scopeType: input.context.scopeType, scopeId: input.context.scopeId },
|
|
37
37
|
query: redactSensitiveFields(input.query),
|
|
38
38
|
});
|
|
39
39
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.registry.js","sourceRoot":"/","sources":["shared/agent/tool.registry.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AAErE,MAAM,MAAM,GAAG,cAAc,CAAC,cAAc,CAAC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AAE,CAAC;QACrB,eAAe,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;IAED,gFAAgF;IAChF,gFAAgF;IAChF,mFAAmF;IACnF,+EAA+E;IAC/E,iDAAiD;IACjD,MAAM,uBAAuB,GAAqE;QAChG,CAAC,oBAAoB,EAAE,oBAAoB,CAAC;QAC5C,CAAC,qBAAqB,EAAE,qBAAqB,CAAC;QAC9C,CAAC,qBAAqB,EAAE,qBAAqB,CAAC;QAC9C,CAAC,sBAAsB,EAAE,sBAAsB,CAAC;QAChD,CAAC,sBAAsB,EAAE,sBAAsB,CAAC;QAChD,CAAC,iBAAiB,EAAE,oBAAoB,CAAC;QACzC,CAAC,oBAAoB,EAAE,uBAAuB,CAAC;KAChD,CAAC;IACF,KAAK,MAAM,CAAC,OAAO,EAAE,aAAa,CAAC,IAAI,uBAAuB,EAAE,CAAC;QAC/D,MAAM,SAAS,GAAG,QAAQ,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAC9C,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,MAAM,CAAC,IAAI,CAAC,oCAAoC,OAAO,eAAe,aAAa,YAAY,CAAC,CAAC;YACjG,SAAS;QACX,CAAC;QACD,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE;YACpB,GAAG,SAAS;YACZ,IAAI,EAAE,OAAO;YACb,WAAW,EAAE,uBAAuB,aAAa,uFAAuF,SAAS,CAAC,WAAW,EAAE;SAChK,CAAC,CAAC;IACL,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,8BAA8B,QAAQ,CAAC,IAAI,QAAQ,CAAC,CAAC;IACpE,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import { z } from 'zod';\n\nimport type { DefineTool, ResolvedToolContext, ToolDeps, RawToolDefinition, ToolRegistry } from './tool.helpers.js';\nimport { error, redactSensitiveFields } from './tool.helpers.js';\nimport { createEnrichmentTools } from '../../enrichment/enrichment.tools.js';\nimport { createIntentTools } from '../../intent/intent.tools.js';\nimport { createNetworkTools } from '../../network/network.tools.js';\nimport { createOpportunityTools } from '../../opportunity/opportunity.tools.js';\nimport { createUtilityTools } from './utility.tools.js';\nimport { createIntegrationTools } from '../../integration/integration.tools.js';\nimport { createContactTools } from '../../contact/contact.tools.js';\nimport { createAgentTools } from '../../agent/agent.tools.js';\nimport { createNegotiationTools } from '../../negotiation/negotiation.tools.js';\nimport { createChatTools } from '../../chat/chat.tools.js';\nimport { createPremiseTools } from '../../premise/premise.tools.js';\nimport { createQuestionerTools } from '../../questioner/questioner.tools.js';\nimport { protocolLogger } from '../observability/protocol.logger.js';\nimport { requestContext } from '../observability/request-context.js';\n\nconst logger = protocolLogger('ToolRegistry');\n\n/**\n * Creates a tool registry containing all tool handlers indexed by name.\n * Handlers are raw async functions (not LangChain tool() wrappers) that\n * accept { context, query } and return a JSON string.\n *\n * @param deps - Shared tool dependencies (graphs, database, embedder, etc.)\n * @param context - Resolved user context for this request.\n * @returns Map of tool name to raw tool definition.\n */\nexport function createToolRegistry(deps: ToolDeps): ToolRegistry {\n const registry: ToolRegistry = new Map();\n\n // defineTool that captures raw handlers into the registry\n function defineTool<T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n }) {\n const entry: RawToolDefinition = {\n name: opts.name,\n description: opts.description,\n schema: opts.querySchema,\n handler: async (input: { context: ResolvedToolContext; query: unknown }) => {\n logger.verbose(`Tool: ${opts.name}`, {\n context: { userId: input.context.userId, scopeType: input.context.scopeType, scopeId: input.context.scopeId },\n query: redactSensitiveFields(input.query),\n });\n try {\n return await opts.handler({ context: input.context, query: input.query as z.infer<T> });\n } catch (err) {\n const abortSignal = requestContext.getStore()?.abortSignal;\n if (abortSignal?.aborted) {\n throw err;\n }\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n return error(`Failed to execute ${opts.name}: ${err instanceof Error ? err.message : String(err)}`);\n }\n },\n };\n\n registry.set(opts.name, entry);\n\n // Return a dummy — create*Tools functions collect return values into arrays,\n // but for the registry path we only need the side-effect on the Map.\n return null as unknown;\n }\n\n // Create all tool domains -- each one calls defineTool() which populates the registry.\n // The local defineTool is compatible with DefineTool (which returns any).\n const dt = defineTool as DefineTool;\n createEnrichmentTools(dt, deps);\n createIntentTools(dt, deps);\n createNetworkTools(dt, deps);\n createOpportunityTools(dt, deps);\n createUtilityTools(dt, deps);\n createIntegrationTools(dt, deps);\n createContactTools(dt, deps);\n createAgentTools(dt, deps);\n createNegotiationTools(dt, deps);\n createPremiseTools(dt, deps);\n createQuestionerTools(dt, deps);\n if (deps.chatSession) {\n createChatTools(dt, deps);\n }\n\n // Deprecated tool-name aliases (IND-371). The canonical implementations are now\n // registered under their *_user_context / *_enrichment_run names; we expose the\n // legacy *_user_profile / *_profile_run names as thin aliases that delegate to the\n // exact same handler + schema, so existing MCP clients keep working while they\n // migrate. The old names are removed in IND-373.\n const DEPRECATED_TOOL_ALIASES: ReadonlyArray<readonly [oldName: string, canonicalName: string]> = [\n [\"read_user_profiles\", \"read_user_contexts\"],\n [\"create_user_profile\", \"create_user_context\"],\n [\"update_user_profile\", \"update_user_context\"],\n [\"confirm_user_profile\", \"confirm_user_context\"],\n [\"preview_user_profile\", \"preview_user_context\"],\n [\"get_profile_run\", \"get_enrichment_run\"],\n [\"cancel_profile_run\", \"cancel_enrichment_run\"],\n ];\n for (const [oldName, canonicalName] of DEPRECATED_TOOL_ALIASES) {\n const canonical = registry.get(canonicalName);\n if (!canonical) {\n logger.warn(`Cannot register deprecated alias ${oldName}: canonical ${canonicalName} not found`);\n continue;\n }\n registry.set(oldName, {\n ...canonical,\n name: oldName,\n description: `[DEPRECATED — use \\`${canonicalName}\\` instead; this alias is retained for backward compatibility and will be removed.] ${canonical.description}`,\n });\n }\n\n logger.verbose(`Tool registry created with ${registry.size} tools`);\n return registry;\n}\n"]}
|
|
@@ -22,6 +22,18 @@ export declare function hasNetworkScope(scope: ToolScopeEnvelope): scope is {
|
|
|
22
22
|
scopeType: 'network';
|
|
23
23
|
scopeId: string;
|
|
24
24
|
};
|
|
25
|
+
/**
|
|
26
|
+
* Returns the focused network id from the canonical scope envelope.
|
|
27
|
+
*
|
|
28
|
+
* This intentionally does not inspect legacy `networkId` fields; callers that
|
|
29
|
+
* still need a transition fallback should pass `scopeFromNetworkId(networkId)`
|
|
30
|
+
* at the boundary so tool logic remains envelope-driven.
|
|
31
|
+
*/
|
|
32
|
+
export declare function focusedNetworkId(scope: ToolScopeEnvelope): string | undefined;
|
|
33
|
+
/** Human-readable label for a focused scope, used in scope-restriction notes. */
|
|
34
|
+
export declare function focusedNetworkLabel(scope: ToolScopeEnvelope & {
|
|
35
|
+
indexName?: string;
|
|
36
|
+
}): string;
|
|
25
37
|
export declare function deriveAllowedNetworkIds(input: DeriveNetworkScopeInput): string[];
|
|
26
38
|
export declare function deriveDiscoveryNetworkIds(input: DeriveNetworkScopeInput): string[];
|
|
27
39
|
//# sourceMappingURL=tool.scope.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.scope.d.ts","sourceRoot":"/","sources":["shared/agent/tool.scope.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,SAAS,CAAC;AAEtC,MAAM,WAAW,iBAAiB;IAChC,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,uBAAwB,SAAQ,iBAAiB;IAChE,WAAW,EAAE,eAAe,EAAE,CAAC;CAChC;AAMD,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,iBAAiB,CAG1F;AAED,wBAAgB,eAAe,CAAC,KAA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AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,uBAAuB,GAAG,MAAM,EAAE,CAQlF"}
|
|
@@ -8,6 +8,20 @@ export function scopeFromNetworkId(networkId) {
|
|
|
8
8
|
export function hasNetworkScope(scope) {
|
|
9
9
|
return scope.scopeType === 'network' && typeof scope.scopeId === 'string' && scope.scopeId.trim().length > 0;
|
|
10
10
|
}
|
|
11
|
+
/**
|
|
12
|
+
* Returns the focused network id from the canonical scope envelope.
|
|
13
|
+
*
|
|
14
|
+
* This intentionally does not inspect legacy `networkId` fields; callers that
|
|
15
|
+
* still need a transition fallback should pass `scopeFromNetworkId(networkId)`
|
|
16
|
+
* at the boundary so tool logic remains envelope-driven.
|
|
17
|
+
*/
|
|
18
|
+
export function focusedNetworkId(scope) {
|
|
19
|
+
return hasNetworkScope(scope) ? scope.scopeId.trim() : undefined;
|
|
20
|
+
}
|
|
21
|
+
/** Human-readable label for a focused scope, used in scope-restriction notes. */
|
|
22
|
+
export function focusedNetworkLabel(scope) {
|
|
23
|
+
return scope.indexName ?? focusedNetworkId(scope) ?? 'this index';
|
|
24
|
+
}
|
|
11
25
|
export function deriveAllowedNetworkIds(input) {
|
|
12
26
|
if (!hasNetworkScope(input)) {
|
|
13
27
|
return uniqueNetworkIds(input.memberships.map((membership) => membership.networkId));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.scope.js","sourceRoot":"/","sources":["shared/agent/tool.scope.ts"],"names":[],"mappings":"AAuBA,SAAS,gBAAgB,CAAC,GAAa;IACrC,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAClE,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,SAAoC;IACrE,MAAM,OAAO,GAAG,SAAS,EAAE,IAAI,EAAE,CAAC;IAClC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CAAC;QACjB,CAAC,CAAC,EAAE,CAAC;AACT,CAAC","sourcesContent":["/**\n * Request scope primitives for protocol tools.\n *\n * `scopeType`/`scopeId` describe the user's focused scope, not the full set of\n * networks a caller may read or write. Helper functions derive concrete network\n * id sets from the focused scope plus the caller's memberships.\n */\nexport type ToolScopeType = 'network';\n\nexport interface ToolScopeEnvelope {\n scopeType?: ToolScopeType;\n scopeId?: string;\n}\n\nexport interface ScopeMembership {\n networkId: string;\n isPersonal?: boolean | null;\n}\n\nexport interface DeriveNetworkScopeInput extends ToolScopeEnvelope {\n memberships: ScopeMembership[];\n}\n\nfunction uniqueNetworkIds(ids: string[]): string[] {\n return [...new Set(ids.map((id) => id.trim()).filter(Boolean))];\n}\n\nexport function scopeFromNetworkId(networkId: string | null | undefined): ToolScopeEnvelope {\n const scopeId = networkId?.trim();\n return scopeId ? { scopeType: 'network', scopeId } : {};\n}\n\nexport function hasNetworkScope(scope: ToolScopeEnvelope): scope is { scopeType: 'network'; scopeId: string } {\n return scope.scopeType === 'network' && typeof scope.scopeId === 'string' && scope.scopeId.trim().length > 0;\n}\n\nexport function deriveAllowedNetworkIds(input: DeriveNetworkScopeInput): string[] {\n if (!hasNetworkScope(input)) {\n return uniqueNetworkIds(input.memberships.map((membership) => membership.networkId));\n }\n\n return uniqueNetworkIds(\n input.memberships\n .filter((membership) => membership.networkId === input.scopeId || membership.isPersonal === true)\n .map((membership) => membership.networkId),\n );\n}\n\nexport function deriveDiscoveryNetworkIds(input: DeriveNetworkScopeInput): string[] {\n if (!hasNetworkScope(input)) {\n return uniqueNetworkIds(input.memberships.map((membership) => membership.networkId));\n }\n\n return input.memberships.some((membership) => membership.networkId === input.scopeId)\n ? [input.scopeId]\n : [];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool.scope.js","sourceRoot":"/","sources":["shared/agent/tool.scope.ts"],"names":[],"mappings":"AAuBA,SAAS,gBAAgB,CAAC,GAAa;IACrC,OAAO,CAAC,GAAG,IAAI,GAAG,CA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,CAAC,SAAS,KAAK,KAAK,CAAC,OAAO,IAAI,UAAU,CAAC,UAAU,KAAK,IAAI,CAAC;SAChG,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC,CAC7C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,yBAAyB,CAAC,KAA8B;IACtE,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,gBAAgB,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC;IACvF,CAAC;IAED,OAAO,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,SAAS,KAAK,KAAK,CAAC,OAAO,CAAC;QACnF,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC;QACjB,CAAC,CAAC,EAAE,CAAC;AACT,CAAC","sourcesContent":["/**\n * Request scope primitives for protocol tools.\n *\n * `scopeType`/`scopeId` describe the user's focused scope, not the full set of\n * networks a caller may read or write. Helper functions derive concrete network\n * id sets from the focused scope plus the caller's memberships.\n */\nexport type ToolScopeType = 'network';\n\nexport interface ToolScopeEnvelope {\n scopeType?: ToolScopeType;\n scopeId?: string;\n}\n\nexport interface ScopeMembership {\n networkId: string;\n isPersonal?: boolean | null;\n}\n\nexport interface DeriveNetworkScopeInput extends ToolScopeEnvelope {\n memberships: ScopeMembership[];\n}\n\nfunction uniqueNetworkIds(ids: string[]): string[] {\n return [...new Set(ids.map((id) => id.trim()).filter(Boolean))];\n}\n\nexport function scopeFromNetworkId(networkId: string | null | undefined): ToolScopeEnvelope {\n const scopeId = networkId?.trim();\n return scopeId ? { scopeType: 'network', scopeId } : {};\n}\n\nexport function hasNetworkScope(scope: ToolScopeEnvelope): scope is { scopeType: 'network'; scopeId: string } {\n return scope.scopeType === 'network' && typeof scope.scopeId === 'string' && scope.scopeId.trim().length > 0;\n}\n\n/**\n * Returns the focused network id from the canonical scope envelope.\n *\n * This intentionally does not inspect legacy `networkId` fields; callers that\n * still need a transition fallback should pass `scopeFromNetworkId(networkId)`\n * at the boundary so tool logic remains envelope-driven.\n */\nexport function focusedNetworkId(scope: ToolScopeEnvelope): string | undefined {\n return hasNetworkScope(scope) ? scope.scopeId.trim() : undefined;\n}\n\n/** Human-readable label for a focused scope, used in scope-restriction notes. */\nexport function focusedNetworkLabel(scope: ToolScopeEnvelope & { indexName?: string }): string {\n return scope.indexName ?? focusedNetworkId(scope) ?? 'this index';\n}\n\nexport function deriveAllowedNetworkIds(input: DeriveNetworkScopeInput): string[] {\n if (!hasNetworkScope(input)) {\n return uniqueNetworkIds(input.memberships.map((membership) => membership.networkId));\n }\n\n return uniqueNetworkIds(\n input.memberships\n .filter((membership) => membership.networkId === input.scopeId || membership.isPersonal === true)\n .map((membership) => membership.networkId),\n );\n}\n\nexport function deriveDiscoveryNetworkIds(input: DeriveNetworkScopeInput): string[] {\n if (!hasNetworkScope(input)) {\n return uniqueNetworkIds(input.memberships.map((membership) => membership.networkId));\n }\n\n return input.memberships.some((membership) => membership.networkId === input.scopeId)\n ? [input.scopeId]\n : [];\n}\n"]}
|
|
@@ -17,9 +17,9 @@ export interface McpAuthResolver {
|
|
|
17
17
|
* agent, and `clientSurface` declaring which kind of UI is rendering the
|
|
18
18
|
* MCP response (drives connect-link redirect choice at click time).
|
|
19
19
|
*
|
|
20
|
-
* When `networkScopeId` is set, the MCP server
|
|
21
|
-
*
|
|
22
|
-
*
|
|
20
|
+
* When `networkScopeId` is set, the MCP server promotes it into the
|
|
21
|
+
* canonical `{ scopeType: 'network', scopeId }` envelope. Downstream tools
|
|
22
|
+
* derive concrete allowed network IDs from that envelope plus memberships.
|
|
23
23
|
*
|
|
24
24
|
* `isSessionAuth` is true for OAuth/JWT bearer sessions — the agent-
|
|
25
25
|
* registration gate in the MCP server is skipped for these callers.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.interface.js","sourceRoot":"/","sources":["shared/interfaces/auth.interface.ts"],"names":[],"mappings":"","sourcesContent":["import type { McpAuthInput } from '../schemas/mcp-auth.schema.js';\n\n/**\n * Resolves the authenticated MCP identity from an auth input DTO.\n * The DTO is extracted from the transport at the edge (e.g. from HTTP Request\n * headers) before the protocol layer is called. New auth paths stay free of\n * platform-specific `Request` coupling; `resolveUserId` remains only as a\n * deprecated compatibility bridge while callers migrate to `resolveIdentity`.\n */\nexport interface McpAuthResolver {\n /**\n * Extracts and validates the authenticated identity from the auth input.\n *\n * @param input - Transport-neutral auth input DTO with credential fields\n * extracted at the MCP transport edge.\n * @returns The authenticated user's UUID, optional agent UUID, auth method,\n * `networkScopeId` if the caller's API key is bound to a network-scoped\n * agent, and `clientSurface` declaring which kind of UI is rendering the\n * MCP response (drives connect-link redirect choice at click time).\n *\n * When `networkScopeId` is set, the MCP server
|
|
1
|
+
{"version":3,"file":"auth.interface.js","sourceRoot":"/","sources":["shared/interfaces/auth.interface.ts"],"names":[],"mappings":"","sourcesContent":["import type { McpAuthInput } from '../schemas/mcp-auth.schema.js';\n\n/**\n * Resolves the authenticated MCP identity from an auth input DTO.\n * The DTO is extracted from the transport at the edge (e.g. from HTTP Request\n * headers) before the protocol layer is called. New auth paths stay free of\n * platform-specific `Request` coupling; `resolveUserId` remains only as a\n * deprecated compatibility bridge while callers migrate to `resolveIdentity`.\n */\nexport interface McpAuthResolver {\n /**\n * Extracts and validates the authenticated identity from the auth input.\n *\n * @param input - Transport-neutral auth input DTO with credential fields\n * extracted at the MCP transport edge.\n * @returns The authenticated user's UUID, optional agent UUID, auth method,\n * `networkScopeId` if the caller's API key is bound to a network-scoped\n * agent, and `clientSurface` declaring which kind of UI is rendering the\n * MCP response (drives connect-link redirect choice at click time).\n *\n * When `networkScopeId` is set, the MCP server promotes it into the\n * canonical `{ scopeType: 'network', scopeId }` envelope. Downstream tools\n * derive concrete allowed network IDs from that envelope plus memberships.\n *\n * `isSessionAuth` is true for OAuth/JWT bearer sessions — the agent-\n * registration gate in the MCP server is skipped for these callers.\n *\n * `clientSurface` is passed through from the DTO. Only `'telegram'`\n * activates the t.me redirect path on `/c/{code}` clicks.\n *\n * @throws Error if authentication fails (no token, invalid token, etc.)\n */\n resolveIdentity(input: McpAuthInput): Promise<{\n userId: string;\n agentId?: string;\n isSessionAuth?: boolean;\n networkScopeId?: string | null;\n clientSurface?: 'telegram' | 'web';\n }>;\n\n /**\n * Deprecated HTTP Request bridge retained for compatibility with older\n * callers. New transport code must extract `McpAuthInput` at the edge and\n * call `resolveIdentity` instead.\n *\n * @deprecated Use resolveIdentity instead.\n */\n resolveUserId(request: Request): Promise<string>;\n}\n"]}
|
|
@@ -33,7 +33,7 @@ export interface DiscoveryRunRecord {
|
|
|
33
33
|
agentId?: string | null;
|
|
34
34
|
status: DiscoveryRunStatus;
|
|
35
35
|
input: DiscoveryRunInput;
|
|
36
|
-
context: Pick<ResolvedToolContext, "userId" | "userName" | "userEmail" | "
|
|
36
|
+
context: Pick<ResolvedToolContext, "userId" | "userName" | "userEmail" | "scopeType" | "scopeId" | "indexName" | "sessionId" | "agentId" | "clientSurface">;
|
|
37
37
|
progress?: Record<string, unknown> | null;
|
|
38
38
|
result?: unknown;
|
|
39
39
|
error?: string | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discovery-run.interface.d.ts","sourceRoot":"/","sources":["shared/interfaces/discovery-run.interface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAoBpE,MAAM,MAAM,kBAAkB,GAAG,QAAQ,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AAE7F,MAAM,WAAW,iBAAiB;IAChC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,QAAQ,CAAC,EAAE,KAAK,CAAC;QACf,MAAM,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE;YACR,IAAI,CAAC,EAAE,MAAM,CAAC;YACd,GAAG,CAAC,EAAE,MAAM,CAAC;YACb,QAAQ,CAAC,EAAE,MAAM,CAAC;YAClB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;YACrB,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;YAClB,OAAO,CAAC,EAAE,MAAM,CAAC;SAClB,CAAC;QACF,OAAO,CAAC,EAAE,KAAK,CAAC;YACd,QAAQ,EAAE,MAAM,CAAC;YACjB,OAAO,EAAE,MAAM,CAAC;YAChB,OAAO,CAAC,EAAE,MAAM,CAAC;SAClB,CAAC,CAAC;QACH,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC,CAAC;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,KAAK,EAAE,iBAAiB,CAAC;IACzB,OAAO,EAAE,IAAI,CAAC,mBAAmB,EAC/B,QAAQ,GACR,UAAU,GACV,WAAW,GACX,WAAW,GACX,
|
|
1
|
+
{"version":3,"file":"discovery-run.interface.d.ts","sourceRoot":"/","sources":["shared/interfaces/discovery-run.interface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAoBpE,MAAM,MAAM,kBAAkB,GAAG,QAAQ,GAAG,SAAS,GAAG,WAAW,GAAG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AAC,CAAC;IACxD,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC;IACjF,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7D,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACnD,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAAC;CAC3E;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC,CAAC;IACpE,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACzC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discovery-run.interface.js","sourceRoot":"/","sources":["shared/interfaces/discovery-run.interface.ts"],"names":[],"mappings":"","sourcesContent":["import type { ResolvedToolContext } from \"../agent/tool.helpers.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Discovery run persistence + queue\n//\n// Models an async `discover_opportunities` job as a durable, owner-scoped record.\n//\n// Port contract (host application implements `DiscoveryRunStore` + `DiscoveryRunQueue`):\n// • Status is a one-way lifecycle: queued → running → (succeeded | failed | cancelled).\n// The `mark*` transitions must be idempotent — re-applying a terminal state is a no-op.\n// • Every read is owner-scoped: `get` and `requestCancel` take `userId` and MUST\n// return `null` when the run is missing or owned by another user (no cross-user reads).\n// • `isCancelRequested` is polled cooperatively by the running graph; the store sets\n// the flag via `requestCancel`, the worker observes it and calls `markCancelled`.\n// • `listActive` returns queued/running runs only (used to coalesce duplicate\n// discovery requests) — empty array, never null.\n// • `DiscoveryRunQueue.cancel` returns `true` if a pending job was removed, `false`\n// if nothing was queued (already running/finished).\n// ═══════════════════════════════════════════════════════════════════════════════\n\nexport type DiscoveryRunStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\";\n\nexport interface DiscoveryRunInput {\n continueFrom?: string;\n searchQuery?: string;\n networkId?: string;\n intentId?: string;\n targetUserId?: string;\n introTargetUserId?: string;\n partyUserIds?: string[];\n entities?: Array<{\n userId: string;\n profile?: {\n name?: string;\n bio?: string;\n location?: string;\n interests?: string[];\n skills?: string[];\n context?: string;\n };\n intents?: Array<{\n intentId: string;\n payload: string;\n summary?: string;\n }>;\n networkId: string;\n }>;\n hint?: string;\n}\n\nexport interface DiscoveryRunRecord {\n id: string;\n userId: string;\n agentId?: string | null;\n status: DiscoveryRunStatus;\n input: DiscoveryRunInput;\n context: Pick<ResolvedToolContext,\n \"userId\" |\n \"userName\" |\n \"userEmail\" |\n \"
|
|
1
|
+
{"version":3,"file":"discovery-run.interface.js","sourceRoot":"/","sources":["shared/interfaces/discovery-run.interface.ts"],"names":[],"mappings":"","sourcesContent":["import type { ResolvedToolContext } from \"../agent/tool.helpers.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Discovery run persistence + queue\n//\n// Models an async `discover_opportunities` job as a durable, owner-scoped record.\n//\n// Port contract (host application implements `DiscoveryRunStore` + `DiscoveryRunQueue`):\n// • Status is a one-way lifecycle: queued → running → (succeeded | failed | cancelled).\n// The `mark*` transitions must be idempotent — re-applying a terminal state is a no-op.\n// • Every read is owner-scoped: `get` and `requestCancel` take `userId` and MUST\n// return `null` when the run is missing or owned by another user (no cross-user reads).\n// • `isCancelRequested` is polled cooperatively by the running graph; the store sets\n// the flag via `requestCancel`, the worker observes it and calls `markCancelled`.\n// • `listActive` returns queued/running runs only (used to coalesce duplicate\n// discovery requests) — empty array, never null.\n// • `DiscoveryRunQueue.cancel` returns `true` if a pending job was removed, `false`\n// if nothing was queued (already running/finished).\n// ═══════════════════════════════════════════════════════════════════════════════\n\nexport type DiscoveryRunStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\";\n\nexport interface DiscoveryRunInput {\n continueFrom?: string;\n searchQuery?: string;\n networkId?: string;\n intentId?: string;\n targetUserId?: string;\n introTargetUserId?: string;\n partyUserIds?: string[];\n entities?: Array<{\n userId: string;\n profile?: {\n name?: string;\n bio?: string;\n location?: string;\n interests?: string[];\n skills?: string[];\n context?: string;\n };\n intents?: Array<{\n intentId: string;\n payload: string;\n summary?: string;\n }>;\n networkId: string;\n }>;\n hint?: string;\n}\n\nexport interface DiscoveryRunRecord {\n id: string;\n userId: string;\n agentId?: string | null;\n status: DiscoveryRunStatus;\n input: DiscoveryRunInput;\n context: Pick<ResolvedToolContext,\n \"userId\" |\n \"userName\" |\n \"userEmail\" |\n \"scopeType\" |\n \"scopeId\" |\n \"indexName\" |\n \"sessionId\" |\n \"agentId\" |\n \"clientSurface\"\n >;\n progress?: Record<string, unknown> | null;\n result?: unknown;\n error?: string | null;\n cancelRequestedAt?: Date | null;\n createdAt: Date;\n startedAt?: Date | null;\n completedAt?: Date | null;\n expiresAt?: Date | null;\n}\n\nexport interface CreateDiscoveryRunInput {\n userId: string;\n agentId?: string | null;\n input: DiscoveryRunInput;\n context: DiscoveryRunRecord[\"context\"];\n expiresAt?: Date;\n}\n\nexport interface DiscoveryRunStore {\n create(input: CreateDiscoveryRunInput): Promise<DiscoveryRunRecord>;\n get(runId: string, userId: string): Promise<DiscoveryRunRecord | null>;\n markRunning(runId: string): Promise<DiscoveryRunRecord | null>;\n updateProgress(runId: string, progress: Record<string, unknown>): Promise<void>;\n markSucceeded(runId: string, result: unknown): Promise<void>;\n markFailed(runId: string, error: string): Promise<void>;\n requestCancel(runId: string, userId: string): Promise<DiscoveryRunRecord | null>;\n markCancelled(runId: string, reason?: string): Promise<void>;\n isCancelRequested(runId: string): Promise<boolean>;\n listActive(userId: string, limit?: number): Promise<DiscoveryRunRecord[]>;\n}\n\nexport interface DiscoveryRunQueue {\n enqueue(runId: string): Promise<{ jobId?: string | number } | void>;\n cancel(runId: string): Promise<boolean>;\n}\n"]}
|
|
@@ -26,7 +26,7 @@ export interface EnrichmentRunRecord {
|
|
|
26
26
|
operation: EnrichmentRunOperation;
|
|
27
27
|
status: EnrichmentRunStatus;
|
|
28
28
|
input: EnrichmentRunInput;
|
|
29
|
-
context: Pick<ResolvedToolContext, "userId" | "userName" | "userEmail" | "
|
|
29
|
+
context: Pick<ResolvedToolContext, "userId" | "userName" | "userEmail" | "scopeType" | "scopeId" | "indexName" | "sessionId" | "agentId" | "clientSurface">;
|
|
30
30
|
progress?: Record<string, unknown> | null;
|
|
31
31
|
result?: unknown;
|
|
32
32
|
error?: string | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enrichment-run.interface.d.ts","sourceRoot":"/","sources":["shared/interfaces/enrichment-run.interface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAiBpE,MAAM,MAAM,mBAAmB,GAAG,QAAQ,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AAI9F,MAAM,MAAM,sBAAsB,GAC9B,sBAAsB,GACtB,qBAAqB,GACrB,sBAAsB,GACtB,qBAAqB,CAAC;AAE1B,MAAM,WAAW,6BAA6B;IAC5C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CAC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jC,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC,CAAC;IACpE,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACzC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enrichment-run.interface.js","sourceRoot":"/","sources":["shared/interfaces/enrichment-run.interface.ts"],"names":[],"mappings":"","sourcesContent":["import type { ResolvedToolContext } from \"../agent/tool.helpers.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Enrichment run persistence + queue\n//\n// Mirrors the discovery-run contract for the enrichment pipeline (profile/context\n// preview + update). See discovery-run.interface.ts for the shared lifecycle rules.\n//\n// Port contract (host application implements `EnrichmentRunStore` + `EnrichmentRunQueue`):\n// • Status lifecycle queued → running → (succeeded | failed | cancelled); `mark*`\n// transitions are idempotent.\n// • `get` / `requestCancel` are owner-scoped and return `null` for missing or\n// non-owned runs.\n// • `listActive` returns queued/running runs (empty array, never null).\n// • Legacy `*_user_profile` operations are read-compat only — never written by new code.\n// ═══════════════════════════════════════════════════════════════════════════════\n\nexport type EnrichmentRunStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\";\n// Canonical run operations are the *_user_context names (IND-371). The legacy\n// *_user_profile values are retained so historical run rows persisted before the\n// rename still type-check; nothing new writes them.\nexport type EnrichmentRunOperation =\n | \"preview_user_context\"\n | \"update_user_context\"\n | \"preview_user_profile\"\n | \"update_user_profile\";\n\nexport interface PreviewUserEnrichmentRunInput {\n name?: string;\n location?: string;\n bioOrDescription?: string;\n edgeosProfileText?: string;\n allowPublicLookup?: boolean;\n linkedinUrl?: string;\n githubUrl?: string;\n twitterUrl?: string;\n websites?: string[];\n}\n\nexport interface UpdateUserEnrichmentRunInput {\n profileId?: string;\n action?: string;\n details?: string;\n socials?: Record<string, string>;\n}\n\nexport type EnrichmentRunInput = PreviewUserEnrichmentRunInput | UpdateUserEnrichmentRunInput;\n\nexport interface EnrichmentRunRecord {\n id: string;\n userId: string;\n agentId?: string | null;\n operation: EnrichmentRunOperation;\n status: EnrichmentRunStatus;\n input: EnrichmentRunInput;\n context: Pick<ResolvedToolContext,\n \"userId\" |\n \"userName\" |\n \"userEmail\" |\n \"
|
|
1
|
+
{"version":3,"file":"enrichment-run.interface.js","sourceRoot":"/","sources":["shared/interfaces/enrichment-run.interface.ts"],"names":[],"mappings":"","sourcesContent":["import type { ResolvedToolContext } from \"../agent/tool.helpers.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Enrichment run persistence + queue\n//\n// Mirrors the discovery-run contract for the enrichment pipeline (profile/context\n// preview + update). See discovery-run.interface.ts for the shared lifecycle rules.\n//\n// Port contract (host application implements `EnrichmentRunStore` + `EnrichmentRunQueue`):\n// • Status lifecycle queued → running → (succeeded | failed | cancelled); `mark*`\n// transitions are idempotent.\n// • `get` / `requestCancel` are owner-scoped and return `null` for missing or\n// non-owned runs.\n// • `listActive` returns queued/running runs (empty array, never null).\n// • Legacy `*_user_profile` operations are read-compat only — never written by new code.\n// ═══════════════════════════════════════════════════════════════════════════════\n\nexport type EnrichmentRunStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\";\n// Canonical run operations are the *_user_context names (IND-371). The legacy\n// *_user_profile values are retained so historical run rows persisted before the\n// rename still type-check; nothing new writes them.\nexport type EnrichmentRunOperation =\n | \"preview_user_context\"\n | \"update_user_context\"\n | \"preview_user_profile\"\n | \"update_user_profile\";\n\nexport interface PreviewUserEnrichmentRunInput {\n name?: string;\n location?: string;\n bioOrDescription?: string;\n edgeosProfileText?: string;\n allowPublicLookup?: boolean;\n linkedinUrl?: string;\n githubUrl?: string;\n twitterUrl?: string;\n websites?: string[];\n}\n\nexport interface UpdateUserEnrichmentRunInput {\n profileId?: string;\n action?: string;\n details?: string;\n socials?: Record<string, string>;\n}\n\nexport type EnrichmentRunInput = PreviewUserEnrichmentRunInput | UpdateUserEnrichmentRunInput;\n\nexport interface EnrichmentRunRecord {\n id: string;\n userId: string;\n agentId?: string | null;\n operation: EnrichmentRunOperation;\n status: EnrichmentRunStatus;\n input: EnrichmentRunInput;\n context: Pick<ResolvedToolContext,\n \"userId\" |\n \"userName\" |\n \"userEmail\" |\n \"scopeType\" |\n \"scopeId\" |\n \"indexName\" |\n \"sessionId\" |\n \"agentId\" |\n \"clientSurface\"\n >;\n progress?: Record<string, unknown> | null;\n result?: unknown;\n error?: string | null;\n cancelRequestedAt?: Date | null;\n createdAt: Date;\n startedAt?: Date | null;\n completedAt?: Date | null;\n expiresAt?: Date | null;\n}\n\nexport interface CreateEnrichmentRunInput {\n userId: string;\n agentId?: string | null;\n operation: EnrichmentRunOperation;\n input: EnrichmentRunInput;\n context: EnrichmentRunRecord[\"context\"];\n expiresAt?: Date;\n}\n\nexport interface EnrichmentRunStore {\n create(input: CreateEnrichmentRunInput): Promise<EnrichmentRunRecord>;\n get(runId: string, userId: string): Promise<EnrichmentRunRecord | null>;\n markRunning(runId: string): Promise<EnrichmentRunRecord | null>;\n updateProgress(runId: string, progress: Record<string, unknown>): Promise<void>;\n markSucceeded(runId: string, result: unknown): Promise<void>;\n markFailed(runId: string, error: string): Promise<void>;\n requestCancel(runId: string, userId: string): Promise<EnrichmentRunRecord | null>;\n markCancelled(runId: string, reason?: string): Promise<void>;\n isCancelRequested(runId: string): Promise<boolean>;\n listActive(userId: string, limit?: number): Promise<EnrichmentRunRecord[]>;\n}\n\nexport interface EnrichmentRunQueue {\n enqueue(runId: string): Promise<{ jobId?: string | number } | void>;\n cancel(runId: string): Promise<boolean>;\n}\n"]}
|