@indexnetwork/protocol 4.3.4-rc.309.1 → 4.3.4-rc.310.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/IMPLEMENTATION.md +2 -2
- package/dist/chat/chat.agent.d.ts +1 -1
- package/dist/chat/chat.agent.js +1 -1
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/chat/chat.prompt.js +30 -30
- package/dist/chat/chat.prompt.js.map +1 -1
- package/dist/chat/chat.prompt.modules.js +8 -8
- package/dist/chat/chat.prompt.modules.js.map +1 -1
- package/dist/chat/chat.state.d.ts +1 -1
- package/dist/chat/chat.state.d.ts.map +1 -1
- package/dist/chat/chat.state.js.map +1 -1
- package/dist/chat/tests/chat.graph.mocks.d.ts +1 -1
- package/dist/chat/tests/chat.graph.mocks.js +1 -1
- package/dist/chat/tests/chat.graph.mocks.js.map +1 -1
- package/dist/contact/contact.tools.js +6 -6
- package/dist/contact/contact.tools.js.map +1 -1
- package/dist/enrichment/enrichment.tools.js +7 -7
- package/dist/enrichment/enrichment.tools.js.map +1 -1
- package/dist/integration/integration.tools.js +1 -1
- package/dist/integration/integration.tools.js.map +1 -1
- package/dist/intent/intent.graph.d.ts.map +1 -1
- package/dist/intent/intent.graph.js +9 -9
- package/dist/intent/intent.graph.js.map +1 -1
- package/dist/intent/intent.indexer.d.ts +1 -1
- package/dist/intent/intent.indexer.js +4 -4
- package/dist/intent/intent.indexer.js.map +1 -1
- package/dist/intent/intent.state.d.ts +7 -7
- package/dist/intent/intent.state.js +7 -7
- package/dist/intent/intent.state.js.map +1 -1
- package/dist/intent/intent.tools.js +26 -26
- package/dist/intent/intent.tools.js.map +1 -1
- package/dist/maintenance/maintenance.graph.d.ts +2 -2
- package/dist/maintenance/maintenance.graph.d.ts.map +1 -1
- package/dist/maintenance/maintenance.graph.js.map +1 -1
- package/dist/mcp/mcp.server.d.ts +2 -2
- package/dist/mcp/mcp.server.js +4 -4
- package/dist/mcp/mcp.server.js.map +1 -1
- package/dist/network/indexer/indexer.graph.d.ts +2 -2
- package/dist/network/indexer/indexer.graph.d.ts.map +1 -1
- package/dist/network/indexer/indexer.graph.js +13 -13
- package/dist/network/indexer/indexer.graph.js.map +1 -1
- package/dist/network/indexer/indexer.state.d.ts +3 -3
- package/dist/network/indexer/indexer.state.d.ts.map +1 -1
- package/dist/network/indexer/indexer.state.js +4 -4
- package/dist/network/indexer/indexer.state.js.map +1 -1
- package/dist/network/membership/membership.graph.d.ts +1 -1
- package/dist/network/membership/membership.graph.js +21 -21
- package/dist/network/membership/membership.graph.js.map +1 -1
- package/dist/network/membership/membership.state.d.ts +2 -2
- package/dist/network/membership/membership.state.js +2 -2
- package/dist/network/membership/membership.state.js.map +1 -1
- package/dist/network/network.graph.d.ts +1 -1
- package/dist/network/network.graph.d.ts.map +1 -1
- package/dist/network/network.graph.js +13 -13
- package/dist/network/network.graph.js.map +1 -1
- package/dist/network/network.state.d.ts +3 -3
- package/dist/network/network.state.d.ts.map +1 -1
- package/dist/network/network.state.js +3 -3
- package/dist/network/network.state.js.map +1 -1
- package/dist/network/network.tools.d.ts.map +1 -1
- package/dist/network/network.tools.js +95 -107
- package/dist/network/network.tools.js.map +1 -1
- package/dist/opportunity/opportunity.discover.d.ts +1 -1
- package/dist/opportunity/opportunity.discover.d.ts.map +1 -1
- package/dist/opportunity/opportunity.discover.js +1 -1
- package/dist/opportunity/opportunity.discover.js.map +1 -1
- package/dist/opportunity/opportunity.graph.js +10 -10
- package/dist/opportunity/opportunity.graph.js.map +1 -1
- package/dist/opportunity/opportunity.introducer.d.ts +3 -3
- package/dist/opportunity/opportunity.introducer.d.ts.map +1 -1
- package/dist/opportunity/opportunity.introducer.js +2 -2
- package/dist/opportunity/opportunity.introducer.js.map +1 -1
- package/dist/opportunity/opportunity.state.d.ts +1 -1
- package/dist/opportunity/opportunity.state.js +1 -1
- package/dist/opportunity/opportunity.state.js.map +1 -1
- package/dist/opportunity/opportunity.tools.js +18 -18
- package/dist/opportunity/opportunity.tools.js.map +1 -1
- package/dist/premise/premise.indexer.d.ts +1 -1
- package/dist/premise/premise.indexer.js +5 -5
- package/dist/premise/premise.indexer.js.map +1 -1
- package/dist/questioner/questioner.tools.js +1 -1
- package/dist/questioner/questioner.tools.js.map +1 -1
- package/dist/shared/agent/tool.factory.d.ts +1 -1
- package/dist/shared/agent/tool.factory.js +1 -1
- package/dist/shared/agent/tool.factory.js.map +1 -1
- package/dist/shared/agent/tool.helpers.d.ts +6 -6
- package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
- package/dist/shared/agent/tool.helpers.js +2 -2
- package/dist/shared/agent/tool.helpers.js.map +1 -1
- package/dist/shared/agent/tool.scope.js +1 -1
- package/dist/shared/agent/tool.scope.js.map +1 -1
- package/dist/shared/agent/utility.tools.js +20 -20
- package/dist/shared/agent/utility.tools.js.map +1 -1
- package/dist/shared/interfaces/database.interface.d.ts +59 -59
- package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/database.interface.js.map +1 -1
- package/dist/shared/interfaces/embedder.interface.d.ts +2 -2
- package/dist/shared/interfaces/embedder.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/embedder.interface.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.tools.js","sourceRoot":"/","sources":["integration/integration.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CAAC,UAAsB,EAAE,IAAc;IAC3E,MAAM,EAAE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AAO,CAAC,MAAM;oBACtB,QAAQ,EAAE,YAAY,CAAC,QAAQ;oBAC/B,OAAO,EAAE,YAAY,CAAC,OAAO;oBAC7B,WAAW,EAAE,YAAY,CAAC,WAAW;oBACrC,gBAAgB,EAAE,YAAY,CAAC,gBAAgB;iBAChD,CAAC,CAAC;gBAEH,OAAO,OAAO,CAAC;oBACb,OAAO,EAAE,YAAY,CAAC,WAAW,GAAG,CAAC;wBACnC,CAAC,CAAC,YAAY,YAAY,CAAC,QAAQ,yBAAyB,YAAY,CAAC,WAAW,SAAS,YAAY,CAAC,gBAAgB,2BAA2B;wBACrJ,CAAC,CAAC,YAAY,CAAC,QAAQ,GAAG,CAAC;4BACzB,CAAC,CAAC,OAAO,YAAY,CAAC,QAAQ,2EAA2E;4BACzG,CAAC,CAAC,oEAAoE;oBAC1E,QAAQ,EAAE,YAAY,CAAC,QAAQ;oBAC/B,WAAW,EAAE,YAAY,CAAC,WAAW;oBACrC,gBAAgB,EAAE,YAAY,CAAC,gBAAgB;oBAC/C,OAAO,EAAE,YAAY,CAAC,OAAO;iBAC9B,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,CAAC,KAAK,CAAC,8BAA8B,EAAE;oBAC3C,MAAM,EAAE,OAAO,CAAC,MAAM;oBACtB,GAAG;iBACJ,CAAC,CAAC;gBACH,OAAO,KAAK,CAAC,oDAAoD,CAAC,CAAC;YACrE,CAAC;QACH,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,qBAAqB,CAAC,CAAC;AACjC,CAAC","sourcesContent":["import { z } from 'zod';\nimport type { DefineTool, ToolDeps } from '../shared/agent/tool.helpers.js';\nimport { success, error } from '../shared/agent/tool.helpers.js';\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('IntegrationTools');\n\n/**\n * Creates integration tools for the chat agent.\n *\n * Exposes `import_gmail_contacts` which authenticates via the integration adapter,\n * fetches all Gmail contacts (paginated), and imports them as ghost users into the network.\n *\n * @param defineTool - Tool definition helper injected by the tool registry.\n * @param deps - Shared tool dependencies including the integration adapter.\n * @returns An array of tool definitions to register with the chat agent.\n */\nexport function createIntegrationTools(defineTool: DefineTool, deps: ToolDeps) {\n const { integration, integrationImporter } = deps;\n\n // import_gmail_contacts creates ghost users, so it is gated behind the\n // CONTACTS_ENABLED flag (injected as deps.contactsEnabled). When disabled the\n // tool is not registered at all (defineTool registers as a side effect).\n if (deps.contactsEnabled !== true) {\n return [];\n }\n\n const import_gmail_contacts = defineTool({\n name: 'import_gmail_contacts',\n description:\n \"Imports contacts from the user's connected Gmail/Google account into their personal network. \" +\n \"This is the preferred method for importing Google Contacts — handles OAuth authentication, pagination, and deduplication automatically.\\n\\n\" +\n \"**Authentication flow:** If Gmail is not yet connected, returns an `authUrl` the user must visit to grant access. \" +\n \"After they complete OAuth, call this tool again to perform the actual import.\\n\\n\" +\n \"**What happens on import:** All Gmail contacts with valid name+email are imported. \" +\n \"Contacts without existing platform accounts become ghost users (enriched with public profile data from LinkedIn, GitHub, etc.). \" +\n \"All imported contacts are added to the user's personal network for opportunity discovery.\\n\\n\" +\n \"**When to use:** When the user asks to import or sync their Gmail/Google contacts. No parameters needed.\\n\\n\" +\n \"**Returns:** Either `{ requiresAuth: true, authUrl }` (user needs to authenticate) or import statistics: \" +\n \"imported (total), newContacts (ghost users created), existingContacts (already in network), skipped (invalid entries).\",\n querySchema: z.object({}),\n handler: async ({ context }) => {\n try {\n const session = await integration.createSession(context.userId);\n const toolkits = await session.toolkits();\n\n const gmailToolkit = toolkits.items.find(t => t.slug === 'gmail');\n const isConnected = !!gmailToolkit?.connection?.connectedAccount?.id;\n\n if (!isConnected) {\n logger.info('Gmail not connected, returning auth URL', { userId: context.userId });\n const originUrl = requestContext.getStore()?.originUrl;\n const callbackUrl = originUrl ? `${originUrl}/oauth/callback` : undefined;\n type AuthorizeFn = (toolkit: string, options?: { callbackUrl?: string }) => Promise<{ redirectUrl: string }>;\n const authRequest = await (session.authorize as unknown as AuthorizeFn)('gmail', callbackUrl ? { callbackUrl } : undefined);\n return success({\n requiresAuth: true,\n message: 'Please connect your Gmail account to import contacts.',\n authUrl: authRequest.redirectUrl,\n });\n }\n\n const importResult = await integrationImporter.importContacts(context.userId, 'gmail');\n\n logger.info('Gmail contacts imported', {\n userId: context.userId,\n imported: importResult.imported,\n skipped: importResult.skipped,\n newContacts: importResult.newContacts,\n existingContacts: importResult.existingContacts,\n });\n\n return success({\n message: importResult.newContacts > 0\n ? `Imported ${importResult.imported} contacts from Gmail. ${importResult.newContacts} new, ${importResult.existingContacts} already in your network.`\n : importResult.imported > 0\n ? `All ${importResult.imported} contacts from Gmail were already in your network. No new contacts added.`\n : 'No contacts with valid name and email found in your Gmail account.',\n imported: importResult.imported,\n newContacts: importResult.newContacts,\n existingContacts: importResult.existingContacts,\n skipped: importResult.skipped,\n });\n } catch (err) {\n logger.error('import_gmail_contacts failed', {\n userId: context.userId,\n err,\n });\n return error('Failed to import Gmail contacts. Please try again.');\n }\n },\n });\n\n return [import_gmail_contacts];\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intent.graph.d.ts","sourceRoot":"/","sources":["intent/intent.graph.ts"],"names":[],"mappings":"AACA,OAAO,EAAoB,cAAc,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAKtF,OAAO,EAAE,mBAAmB,EAAE,MAAM,4CAA4C,CAAC;AAEjF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,4CAA4C,CAAC;AACrF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAIhF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAmE7E;;GAEG;AACH,qBAAa,kBAAkB;IAE3B,OAAO,CAAC,QAAQ;IA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;sBAAlB,CAAP;wBAAwB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBAAlB,CAAP;wBAAwB,CAAC;;;;;;;;;;;sBAAlB,CAAP;wBAAwB,CAAC;;;;;;;;;;;sBAAlB,CAAP;wBAAwB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBAAlB,CAAP;wBAAwB,CAAC;;;;;;;;;;;sBAAlB,CAAP;wBAAwB,CAAC;;;;;;;;;;;sBAAlB,CAAP;wBAAwB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0BAAlB,CAAP;4BAAwB,CAAC;;;;;;;;;;;0BAAlB,CAAP;4BAAwB,CAAC;;;;;;;;;;;0BAAlB,CAAP;4BAAwB,CAAC;;;;;;;;;;CA2xB3B"}
|
|
@@ -94,7 +94,7 @@ export class IntentGraphFactory {
|
|
|
94
94
|
* Node 0: Prep
|
|
95
95
|
* Always fetches ALL of the user's active intents from the DB via getActiveIntents(userId).
|
|
96
96
|
* This ensures reconciliation can detect duplicates and modifications globally,
|
|
97
|
-
* regardless of
|
|
97
|
+
* regardless of network scope.
|
|
98
98
|
*/
|
|
99
99
|
const prepNode = async (state) => {
|
|
100
100
|
return timed("IntentGraph.prep", async () => {
|
|
@@ -579,7 +579,7 @@ export class IntentGraphFactory {
|
|
|
579
579
|
/**
|
|
580
580
|
* Node: Query
|
|
581
581
|
* Fast-path read node — fetches intents from DB based on scope.
|
|
582
|
-
* Handles: global user intents,
|
|
582
|
+
* Handles: global user intents, network-scoped (all or filtered by user).
|
|
583
583
|
* No LLM calls; no inference/verification/reconciliation.
|
|
584
584
|
*/
|
|
585
585
|
const queryNode = async (state) => {
|
|
@@ -591,7 +591,7 @@ export class IntentGraphFactory {
|
|
|
591
591
|
allUserIntents: state.allUserIntents,
|
|
592
592
|
});
|
|
593
593
|
try {
|
|
594
|
-
// Scope-aware default: caller's intents across all reachable
|
|
594
|
+
// Scope-aware default: caller's intents across all reachable networks.
|
|
595
595
|
// Triggered when the tool layer passed indexScope and did not pick a
|
|
596
596
|
// specific networkId or queryUserId — i.e. "my intents" in a chat
|
|
597
597
|
// where the agent's reach is more than one index.
|
|
@@ -621,7 +621,7 @@ export class IntentGraphFactory {
|
|
|
621
621
|
},
|
|
622
622
|
};
|
|
623
623
|
}
|
|
624
|
-
// When allUserIntents is true, ignore
|
|
624
|
+
// When allUserIntents is true, ignore network scope and return all
|
|
625
625
|
const effectiveIndexId = state.allUserIntents ? undefined : state.networkId;
|
|
626
626
|
if (effectiveIndexId) {
|
|
627
627
|
// Verify membership
|
|
@@ -635,7 +635,7 @@ export class IntentGraphFactory {
|
|
|
635
635
|
},
|
|
636
636
|
};
|
|
637
637
|
}
|
|
638
|
-
//
|
|
638
|
+
// Network-scoped read
|
|
639
639
|
if (!state.queryUserId) {
|
|
640
640
|
// All intents in the index (any member can see)
|
|
641
641
|
const intents = await this.database.getNetworkIntentsForMember(effectiveIndexId, state.userId, { limit: 50, offset: 0 });
|
|
@@ -644,7 +644,7 @@ export class IntentGraphFactory {
|
|
|
644
644
|
readResult: {
|
|
645
645
|
count: 0,
|
|
646
646
|
intents: [],
|
|
647
|
-
message: "No intents in this
|
|
647
|
+
message: "No intents in this network yet.",
|
|
648
648
|
networkId: effectiveIndexId,
|
|
649
649
|
},
|
|
650
650
|
};
|
|
@@ -673,8 +673,8 @@ export class IntentGraphFactory {
|
|
|
673
673
|
count: 0,
|
|
674
674
|
intents: [],
|
|
675
675
|
message: effectiveUserId === state.userId
|
|
676
|
-
? "You don't have any intents in this
|
|
677
|
-
: "No intents for that user in this
|
|
676
|
+
? "You don't have any intents in this network yet."
|
|
677
|
+
: "No intents for that user in this network.",
|
|
678
678
|
networkId: effectiveIndexId,
|
|
679
679
|
},
|
|
680
680
|
};
|
|
@@ -696,7 +696,7 @@ export class IntentGraphFactory {
|
|
|
696
696
|
},
|
|
697
697
|
};
|
|
698
698
|
}
|
|
699
|
-
// Global (no
|
|
699
|
+
// Global (no network scope): return user's own active intents
|
|
700
700
|
const intents = await this.database.getActiveIntents(state.userId);
|
|
701
701
|
if (intents.length === 0) {
|
|
702
702
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intent.graph.js","sourceRoot":"/","sources":["intent/intent.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAmC,MAAM,mBAAmB,CAAC;AACtF,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAGvE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAI5E,MAAM,MAAM,GAAG,cAAc,CAAC,oBAAoB,CAAC,CAAC;AACpD,MAAM,uBAAuB,GAAG,IAAI,CAAC;AACrC,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAClC,MAAM,kBAAkB,GAAG,2BAA2B,CAAC;AAEvD,MAAM,wBAAwB,GAAG,CAAC,IAAY,EAAiB,EAAE;IAC/D,M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,MAAM,EAAE,cAAc,EAAE;YAC3C,KAAK,EAAE,OAAO;YACd,SAAS,EAAE,WAAW;YACtB,UAAU,EAAE,YAAY;YACxB,OAAO,EAAE,GAAG;SACb,CAAC;YAEF,gCAAgC;aAC/B,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;YAEtB,uEAAuE;aACtE,mBAAmB,CAAC,WAAW,EAAE,qBAAqB,EAAE;YACvD,YAAY,EAAE,cAAc;YAC5B,UAAU,EAAE,YAAY;YACxB,OAAO,EAAE,GAAG;SACb,CAAC;YAEF,kFAAkF;aACjF,mBAAmB,CAAC,cAAc,EAAE,CAAC,KAAoC,EAAE,EAAE;YAC5E,IAAI,KAAK,CAAC,aAAa,KAAK,SAAS,EAAE,CAAC;gBACtC,MAAM,CAAC,OAAO,CAAC,qEAAqE,CAAC,CAAC;gBACtF,OAAO,SAAS,CAAC;YACnB,CAAC;YACD,OAAO,YAAY,CAAC;QACtB,CAAC,EAAE;YACD,UAAU,EAAE,YAAY;YACxB,OAAO,EAAE,GAAG;SACb,CAAC;YAEF,yCAAyC;aACxC,OAAO,CAAC,YAAY,EAAE,UAAU,CAAC;YAElC,6BAA6B;aAC5B,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;QAE5B,OAAO,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC5B,CAAC;CACF","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\nimport { IntentGraphState, VerifiedIntent, ExecutionResult } from \"./intent.state.js\";\nimport { ExplicitIntentInferrer } from \"./intent.inferrer.js\";\nimport { SemanticVerifier } from \"./intent.verifier.js\";\nimport { DEFAULT_SPECIFICITY_WARNING } from \"./intent.specificity.js\";\nimport { IntentReconciler } from \"./intent.reconciler.js\";\nimport { IntentGraphDatabase } from \"../shared/interfaces/database.interface.js\";\nimport { getAbortSignalConfig } from \"../shared/agent/model-signal.js\";\nimport type { EmbeddingGenerator } from \"../shared/interfaces/embedder.interface.js\";\nimport type { IntentGraphQueue } from \"../shared/interfaces/queue.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { timed } from \"../shared/observability/performance.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport type { DebugMetaAgent } from \"../chat/chat-streaming.types.js\";\nimport type { QuestionerEnqueueFn } from \"../questioner/questioner.types.js\";\n\nconst logger = protocolLogger(\"IntentGraphFactory\");\nconst MAX_PERMISSIBLE_ENTROPY = 0.75;\nconst MIN_CLEAR_INTENT_SCORE = 40;\nconst GENERIC_JOB_PHRASE = /\\b(?:a|any|some)\\s+job\\b/i;\n\nconst inferRoleFromContextText = (text: string): string | null => {\n const normalized = text.toLowerCase();\n if (/\\b(engineer|developer)\\b/.test(normalized)) return \"software engineering\";\n if (/\\b(designer|ux|ui)\\b/.test(normalized)) return \"product design\";\n if (/\\b(marketing|marketer|growth)\\b/.test(normalized)) return \"marketing\";\n if (/\\b(product manager|product)\\b/.test(normalized)) return \"product management\";\n if (/\\b(data scientist|machine learning|ml|ai)\\b/.test(normalized)) return \"AI/ML\";\n if (/\\b(sales|account executive|business development)\\b/.test(normalized)) return \"sales\";\n return null;\n};\n\n/**\n * Derive a job-role qualifier from the user's global user_context paragraph\n * (the identity text that replaced the legacy profile projection). Role is\n * inferred from the free text; the old structured skills/interests extraction\n * is gone with the removed profile fields.\n */\nconst buildJobQualifierFromContext = (contextText: string): string | null => {\n const roleHint = inferRoleFromContextText(contextText ?? \"\");\n return roleHint ? `${roleHint} role` : null;\n};\n\nconst enrichVagueIntentWithContext = (description: string, userContext: string): string => {\n const trimmed = description?.trim();\n if (!trimmed) return description;\n\n const isGenericJobRequest =\n GENERIC_JOB_PHRASE.test(trimmed) ||\n /\\b(?:find|get|look(?:ing)?\\s+for|want)\\s+(?:to\\s+)?(?:find\\s+)?job\\b/i.test(trimmed);\n if (!isGenericJobRequest) return description;\n\n const qualifier = buildJobQualifierFromContext(userContext);\n if (!qualifier) return description;\n\n const enriched = trimmed\n .replace(/\\ba job\\b/i, `a ${qualifier}`)\n .replace(/\\bjob\\b/i, `${qualifier}`)\n .replace(/\\s{2,}/g, \" \")\n .trim();\n\n return enriched.length > 0 ? enriched : description;\n};\n\nconst isVague = (description: string, entropy: number, clarity: number): boolean => {\n if (GENERIC_JOB_PHRASE.test(description)) return true;\n if (entropy > MAX_PERMISSIBLE_ENTROPY) return true;\n if (clarity < MIN_CLEAR_INTENT_SCORE) return true;\n return false;\n};\n\nconst getSpecificityWarning = (verdict: { specificity_warning?: string | null }): string => {\n const warning = verdict.specificity_warning?.trim();\n return warning && warning.length > 0 ? warning : DEFAULT_SPECIFICITY_WARNING;\n};\n\nconst toSpeechActType = (classification?: string): \"COMMISSIVE\" | \"DIRECTIVE\" | null => {\n if (classification === \"COMMISSIVE\" || classification === \"DIRECTIVE\") return classification;\n return null;\n};\n\n/**\n * Factory class to build and compile the Intent Processing Graph.\n */\nexport class IntentGraphFactory {\n constructor(\n private database: IntentGraphDatabase,\n private embedder?: EmbeddingGenerator,\n private intentQueue?: IntentGraphQueue,\n private questionerEnqueue?: QuestionerEnqueueFn,\n ) { }\n\n public createGraph() {\n // Instantiate Agents (Nodes)\n const inferrer = new ExplicitIntentInferrer();\n const verifier = new SemanticVerifier();\n const reconciler = new IntentReconciler();\n\n // --- NODE DEFINITIONS ---\n\n /**\n * Node 0: Prep\n * Always fetches ALL of the user's active intents from the DB via getActiveIntents(userId).\n * This ensures reconciliation can detect duplicates and modifications globally,\n * regardless of index scope.\n */\n const prepNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.prep\", async () => {\n logger.verbose(\"Starting preparation phase\", {\n operationMode: state.operationMode,\n hasContent: !!state.inputContent,\n targetIntentIds: state.targetIntentIds,\n networkId: state.networkId,\n });\n\n // Gate: write operations require an existing profile\n if (state.operationMode !== 'read') {\n const profile = await this.database.getProfile(state.userId);\n if (!profile) {\n const msg = \"You need to create a profile before creating intents. Please set up your profile first.\";\n logger.error(\"Prep failed: no profile for user\", { userId: state.userId });\n return { error: msg };\n }\n }\n\n const activeIntents = await this.database.getActiveIntents(state.userId);\n const formattedActiveIntents = activeIntents\n .map(i => `ID: ${i.id}, Description: ${i.payload}, Summary: ${i.summary || 'N/A'}`)\n .join('\\n') || \"No active intents.\";\n\n logger.verbose(\"Fetched active intents\", {\n count: activeIntents.length,\n operationMode: state.operationMode\n });\n\n return {\n activeIntents: formattedActiveIntents,\n trace: [{\n node: \"prep\",\n detail: `Fetched ${activeIntents.length} active intent(s)`,\n }],\n };\n });\n };\n\n /**\n * Node 1: Inference\n * Extracts intents from raw content.\n * Phase 4: Uses operation mode to control behavior and determine if node should execute.\n * Phase 5: Passes conversation context for anaphoric resolution.\n */\n const inferenceNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.inference\", async () => {\n logger.verbose(\"Starting inference\", {\n operationMode: state.operationMode,\n hasContent: !!state.inputContent,\n contentPreview: state.inputContent?.substring(0, 50),\n hasConversationContext: !!state.conversationContext,\n conversationMessagesCount: state.conversationContext?.length || 0\n });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Phase 4: Control profile fallback based on operation mode\n // Only allow for create operations without explicit content\n const allowProfileFallback = state.operationMode === 'create' && !state.inputContent;\n\n // Cast operationMode: 'read' and 'propose' map to 'create' for the inferrer\n // (inference node is never called in read mode; propose behaves like create for inference)\n const inferrerMode = (state.operationMode === 'read' || state.operationMode === 'propose') ? 'create' : state.operationMode;\n const _traceEmitterInferrer = requestContext.getStore()?.traceEmitter;\n const inferrerStart = Date.now();\n _traceEmitterInferrer?.({ type: \"agent_start\", name: \"intent-inferrer\" });\n const result = await inferrer.invoke(\n state.inputContent || null,\n state.userProfile,\n {\n allowProfileFallback,\n operationMode: inferrerMode,\n conversationContext: state.conversationContext // Phase 5: Pass conversation history\n }\n );\n agentTimingsAccum.push({ name: 'intent.inferrer', durationMs: Date.now() - inferrerStart });\n _traceEmitterInferrer?.({ type: \"agent_end\", name: \"intent-inferrer\", durationMs: Date.now() - inferrerStart, summary: result.intents.length > 0 ? `Extracted ${result.intents.length} intent(s)` : \"intent-inferrer completed\" });\n\n logger.verbose(\"Inference complete\", {\n inferredCount: result.intents.length,\n operationMode: state.operationMode\n });\n\n const descriptions = result.intents.map(i => i.description).slice(0, 3);\n const truncated = result.intents.length > 3 ? `... +${result.intents.length - 3} more` : \"\";\n\n return {\n inferredIntents: result.intents,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"inference\",\n detail: result.intents.length === 0\n ? \"No intents extracted\"\n : `Extracted ${result.intents.length}: ${descriptions.map(d => `\"${d.slice(0, 50)}${d.length > 50 ? '...' : ''}\"`).join(\", \")}${truncated}`,\n }],\n };\n });\n };\n\n /**\n * Node 2: Verification (Map-Reduce / Parallel)\n * Verifies each inferred intent in parallel.\n * Phase 4: Can be skipped for delete operations and updates with no new intents.\n */\n const verificationNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.verification\", async () => {\n const intents = state.inferredIntents;\n\n logger.verbose(\"Starting verification\", {\n operationMode: state.operationMode,\n intentCount: intents.length\n });\n\n if (intents.length === 0) {\n logger.verbose(\"No intents to verify\");\n return { verifiedIntents: [], agentTimings: [] };\n }\n\n logger.verbose(`Verifying ${intents.length} intents in parallel...`);\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Parallel Execution\n const verificationResults = await Promise.all(\n intents.map(async (intent): Promise<VerifiedIntent | null> => {\n try {\n let description = intent.description;\n const _traceEmitterVerifier = requestContext.getStore()?.traceEmitter;\n const verifierStart1 = Date.now();\n _traceEmitterVerifier?.({ type: \"agent_start\", name: \"intent-verifier\" });\n let verdict = await verifier.invoke(description, state.userProfile);\n agentTimingsAccum.push({ name: 'intent.verifier', durationMs: Date.now() - verifierStart1 });\n _traceEmitterVerifier?.({ type: \"agent_end\", name: \"intent-verifier\", durationMs: Date.now() - verifierStart1, summary: `Verified: ${verdict.classification}` });\n\n if (isVague(description, verdict.semantic_entropy, verdict.felicity_scores.clarity)) {\n // Role-hint enrichment for vague job intents reads the global\n // user_context paragraph instead of the structured profile fields.\n const roleHintContext = (await this.database.getUserContext(state.userId, null))?.text ?? '';\n const enrichedDescription = enrichVagueIntentWithContext(description, roleHintContext);\n if (enrichedDescription !== description) {\n logger.verbose(\"Enriched vague intent using profile context\", {\n before: description,\n after: enrichedDescription,\n });\n const _traceEmitterVerifier2 = requestContext.getStore()?.traceEmitter;\n const verifierStart2 = Date.now();\n _traceEmitterVerifier2?.({ type: \"agent_start\", name: \"intent-verifier\" });\n const enrichedVerdict = await verifier.invoke(enrichedDescription, state.userProfile);\n agentTimingsAccum.push({ name: 'intent.verifier', durationMs: Date.now() - verifierStart2 });\n _traceEmitterVerifier2?.({ type: \"agent_end\", name: \"intent-verifier\", durationMs: Date.now() - verifierStart2, summary: `Verified (enriched): ${enrichedVerdict.classification}` });\n const becameClear =\n enrichedVerdict.semantic_entropy < verdict.semantic_entropy ||\n enrichedVerdict.felicity_scores.clarity > verdict.felicity_scores.clarity;\n if (becameClear) {\n description = enrichedDescription;\n verdict = enrichedVerdict;\n }\n }\n }\n\n // Filter Logic: Must be a Commissive, Directive, or Declaration\n const VALID_TYPES = ['COMMISSIVE', 'DIRECTIVE', 'DECLARATION'];\n if (!VALID_TYPES.includes(verdict.classification)) {\n logger.warn(`Dropping intent: \"${description}\" (Type: ${verdict.classification})`);\n return null;\n }\n\n if (isVague(description, verdict.semantic_entropy, verdict.felicity_scores.clarity)) {\n logger.warn(`Dropping vague intent after verification: \"${description}\"`, {\n entropy: verdict.semantic_entropy,\n clarity: verdict.felicity_scores.clarity,\n });\n return null;\n }\n\n if (state.operationMode !== 'propose' && verdict.referential_breadth === 'broad') {\n logger.warn(`Dropping broad attributive intent before persistence: \"${description}\"`, {\n referentialBreadth: verdict.referential_breadth,\n missingSelectionalConstraints: verdict.missing_selectional_constraints,\n warning: getSpecificityWarning(verdict),\n });\n return null;\n }\n\n // Calculate Score\n const score = Math.min(\n verdict.felicity_scores.authority,\n verdict.felicity_scores.sincerity,\n verdict.felicity_scores.clarity\n );\n\n // Return enriched intent\n return {\n ...intent,\n description,\n verification: verdict,\n score\n };\n } catch (e) {\n logger.error(`Error verifying intent: ${intent.description}`, { error: e });\n return null;\n }\n })\n );\n\n // Filter out nulls\n const verified = verificationResults.filter((i): i is VerifiedIntent => i !== null);\n logger.verbose(`Verification complete`, {\n passed: verified.length,\n total: intents.length,\n operationMode: state.operationMode\n });\n\n // Build trace entries with Felicity scores for each verified intent\n const traceEntries = verified.map(v => {\n const fs = v.verification?.felicity_scores;\n const entropy = v.verification?.semantic_entropy;\n const classification = v.verification?.classification;\n const referentialBreadth = v.verification?.referential_breadth;\n return {\n node: \"verification\",\n detail: `\"${v.description.slice(0, 40)}${v.description.length > 40 ? '...' : ''}\" → ${classification}${referentialBreadth ? ` (${referentialBreadth} referential breadth)` : ''}`,\n data: fs ? {\n clarity: fs.clarity,\n authority: fs.authority,\n sincerity: fs.sincerity,\n entropy: entropy != null ? Math.round(entropy * 100) / 100 : undefined,\n referentialBreadth,\n missingSelectionalConstraints: v.verification?.missing_selectional_constraints,\n specificityWarning: v.verification?.specificity_warning ?? undefined,\n classification,\n score: v.score,\n } : undefined,\n };\n });\n\n // Add summary trace if some intents were filtered out\n const dropped = intents.length - verified.length;\n if (dropped > 0) {\n traceEntries.unshift({\n node: \"verification\",\n detail: `Verified ${verified.length}/${intents.length} (${dropped} filtered as invalid)`,\n data: undefined,\n });\n } else if (verified.length > 0) {\n traceEntries.unshift({\n node: \"verification\",\n detail: `Verified ${verified.length} intent(s)`,\n data: undefined,\n });\n }\n\n return { verifiedIntents: verified, agentTimings: agentTimingsAccum, trace: traceEntries };\n });\n };\n\n /**\n * Node 3: Reconciliation\n * Decides on final actions (Create, Update, Expire).\n * Phase 4: Handles delete operations directly without LLM reconciliation.\n */\n const reconciliationNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.reconciliation\", async () => {\n logger.verbose(\"Starting reconciliation\", {\n operationMode: state.operationMode,\n verifiedIntentCount: state.verifiedIntents.length,\n targetIntentIds: state.targetIntentIds\n });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Phase 4: Handle delete operations directly\n if (state.operationMode === 'delete') {\n if (!state.targetIntentIds || state.targetIntentIds.length === 0) {\n logger.warn(\"Delete mode with no target IDs\");\n return {\n actions: [],\n agentTimings: agentTimingsAccum,\n trace: [{ node: \"reconciler\", detail: \"Delete mode with no target IDs\" }],\n };\n }\n\n logger.verbose(\"Delete mode - generating expire actions\", {\n targetIds: state.targetIntentIds\n });\n\n const actions = state.targetIntentIds.map(id => ({\n type: 'expire' as const,\n id,\n reasoning: 'User requested deletion'\n }));\n\n return {\n actions,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"reconciler\",\n detail: `Actions: expire=${actions.length}`,\n }],\n };\n }\n\n // Standard reconciliation for create/update operations\n const candidates = state.verifiedIntents;\n if (candidates.length === 0) {\n logger.verbose(\"No verified intents to reconcile\");\n return {\n actions: [],\n agentTimings: agentTimingsAccum,\n trace: [{ node: \"reconciler\", detail: \"No intents to reconcile\" }],\n };\n }\n\n // Format candidates for the Reconciler Prompt\n const formattedCandidates = candidates.map(c =>\n `- [${c.type.toUpperCase()}] \"${c.description}\" (Confidence: ${c.confidence}, Score: ${c.score})\\n` +\n ` Reasoning: ${c.reasoning}\\n` +\n ` Verification: ${c.verification?.classification} (Flags: ${c.verification?.flags.join(', ') || 'None'})`\n ).join('\\n');\n\n logger.verbose(\"Invoking reconciler agent\", {\n candidateCount: candidates.length,\n operationMode: state.operationMode\n });\n\n const _traceEmitterReconciler = requestContext.getStore()?.traceEmitter;\n const reconcilerStart = Date.now();\n _traceEmitterReconciler?.({ type: \"agent_start\", name: \"intent-reconciler\" });\n const result = await reconciler.invoke(formattedCandidates, state.activeIntents);\n agentTimingsAccum.push({ name: 'intent.reconciler', durationMs: Date.now() - reconcilerStart });\n _traceEmitterReconciler?.({ type: \"agent_end\", name: \"intent-reconciler\", durationMs: Date.now() - reconcilerStart, summary: `Reconciled ${result.actions.length} action(s)` });\n\n logger.verbose(\"Reconciliation complete\", {\n actionCount: result.actions.length,\n operationMode: state.operationMode\n });\n\n // Count actions by type\n const counts = { create: 0, update: 0, expire: 0 };\n for (const a of result.actions) {\n if (a.type in counts) counts[a.type as keyof typeof counts]++;\n }\n\n return {\n actions: result.actions,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"reconciler\",\n detail: `Actions: create=${counts.create}, update=${counts.update}, expire=${counts.expire}`,\n }],\n };\n });\n };\n\n /** Strip URLs and \"More details at [url]\" from intent payloads before persisting. */\n const sanitizePayload = (payload: string): string => {\n if (!payload || typeof payload !== \"string\") return payload;\n const out = payload\n .replace(/\\s*More details at\\s*:?\\s*https?:\\/\\/[^\\s\"'<>)\\]]+/gi, \"\")\n .replace(/\\s*See\\s+https?:\\/\\/[^\\s\"'<>)\\]]+\\s+for\\s+more[^.]*\\.?/gi, \"\")\n .replace(/https?:\\/\\/[^\\s\"'<>)\\]]+/g, \"\")\n .replace(/\\s{2,}/g, \" \")\n .trim();\n return out.replace(/[.,;]\\s*$/, \"\").trim() || payload;\n };\n\n /**\n * Generate a flat embedding for an intent payload, swallowing failures so\n * persistence can continue without an embedding. `intentId` is logging-only\n * (present for updates, absent for creates).\n */\n const generateIntentEmbedding = async (\n sanitizedPayload: string,\n intentId?: string,\n ): Promise<number[] | undefined> => {\n if (!this.embedder) return undefined;\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n const flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for intent\", {\n ...(intentId ? { intentId } : {}),\n dimensions: flatEmbedding?.length,\n });\n return flatEmbedding;\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent (continuing without)\", {\n ...(intentId ? { intentId } : {}),\n error: embErr,\n });\n return undefined;\n }\n };\n\n /**\n * Node 4: Executor\n * Executes reconciler actions against the database.\n */\n const executorNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.executor\", async () => {\n const actions = state.actions;\n if (!actions || actions.length === 0) {\n return { executionResults: [] };\n }\n\n logger.verbose(`Executing ${actions.length} actions...`);\n const results: ExecutionResult[] = [];\n const scopeEnvelope = state.scopeType && state.scopeId\n ? { scopeType: state.scopeType, scopeId: state.scopeId }\n : {};\n const verifiedIntentByPayload = new Map<string, VerifiedIntent>();\n for (const verifiedIntent of state.verifiedIntents) {\n verifiedIntentByPayload.set(verifiedIntent.description, verifiedIntent);\n verifiedIntentByPayload.set(sanitizePayload(verifiedIntent.description), verifiedIntent);\n }\n\n for (const action of actions) {\n const actionType = action.type.toLowerCase() as 'create' | 'update' | 'expire';\n try {\n if (actionType === 'create') {\n const createAction = action as {\n payload: string;\n score: number | null;\n semanticEntropy?: number | null;\n referentialAnchor?: string | null;\n intentMode?: 'REFERENTIAL' | 'ATTRIBUTIVE' | null;\n };\n const sanitizedPayload = sanitizePayload(createAction.payload);\n const matchedVerifiedIntent =\n verifiedIntentByPayload.get(createAction.payload) ||\n verifiedIntentByPayload.get(sanitizedPayload);\n\n // Generate embedding for the intent payload\n const flatEmbedding = await generateIntentEmbedding(sanitizedPayload);\n\n const created = await this.database.createIntent({\n userId: state.userId,\n payload: sanitizedPayload,\n confidence: createAction.score ? createAction.score / 100 : 1.0,\n inferenceType: 'explicit',\n sourceType: 'discovery_form',\n embedding: flatEmbedding,\n semanticEntropy:\n createAction.semanticEntropy ??\n matchedVerifiedIntent?.verification?.semantic_entropy ??\n null,\n referentialAnchor:\n createAction.referentialAnchor ??\n matchedVerifiedIntent?.verification?.referential_anchor ??\n null,\n felicityAuthority: matchedVerifiedIntent?.verification?.felicity_scores.authority ?? null,\n felicitySincerity: matchedVerifiedIntent?.verification?.felicity_scores.sincerity ?? null,\n felicityClarity: matchedVerifiedIntent?.verification?.felicity_scores.clarity ?? null,\n intentMode: createAction.intentMode ?? null,\n speechActType: toSpeechActType(matchedVerifiedIntent?.verification?.classification),\n });\n\n results.push({ actionType: 'create', success: true, intentId: created.id, payload: sanitizedPayload });\n logger.verbose(`Created intent: ${created.id}`);\n\n this.intentQueue?.addGenerateHydeJob({\n intentId: created.id,\n userId: state.userId,\n ...scopeEnvelope,\n }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE job', { intentId: created.id, error: err })\n );\n\n if (this.questionerEnqueue) {\n const userContext = (await this.database.getUserContext(state.userId, null))?.text ?? '';\n this.questionerEnqueue({\n mode: 'intent',\n userId: state.userId,\n sourceType: 'intent',\n sourceId: created.id,\n ...scopeEnvelope,\n context: {\n intentId: created.id,\n payload: sanitizedPayload,\n userContext,\n },\n }).catch((err) =>\n logger.error('Failed to enqueue intent question generation', { intentId: created.id, error: err })\n );\n }\n\n } else if (actionType === 'update') {\n const updateAction = action as {\n id: string;\n payload: string;\n intentMode?: 'REFERENTIAL' | 'ATTRIBUTIVE' | null;\n };\n const sanitizedPayload = sanitizePayload(updateAction.payload);\n const matchedVerifiedIntent =\n verifiedIntentByPayload.get(updateAction.payload) ||\n verifiedIntentByPayload.get(sanitizedPayload);\n\n // Regenerate embedding for the updated payload\n const flatEmbedding = await generateIntentEmbedding(sanitizedPayload, updateAction.id);\n\n const updated = await this.database.updateIntent(updateAction.id, {\n payload: sanitizedPayload,\n embedding: flatEmbedding,\n semanticEntropy:\n matchedVerifiedIntent?.verification?.semantic_entropy ??\n null,\n referentialAnchor:\n matchedVerifiedIntent?.verification?.referential_anchor ??\n null,\n felicityAuthority: matchedVerifiedIntent?.verification?.felicity_scores.authority ?? null,\n felicitySincerity: matchedVerifiedIntent?.verification?.felicity_scores.sincerity ?? null,\n felicityClarity: matchedVerifiedIntent?.verification?.felicity_scores.clarity ?? null,\n intentMode: updateAction.intentMode ?? null,\n speechActType: toSpeechActType(matchedVerifiedIntent?.verification?.classification),\n });\n results.push({\n actionType: 'update',\n success: !!updated,\n intentId: updateAction.id,\n payload: sanitizedPayload,\n error: updated ? undefined : 'Intent not found'\n });\n logger.verbose(`Updated intent: ${updateAction.id}`);\n if (updated) {\n this.intentQueue?.addGenerateHydeJob({\n intentId: updateAction.id,\n userId: state.userId,\n ...scopeEnvelope,\n }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE job', { intentId: updateAction.id, error: err })\n );\n }\n\n } else if (actionType === 'expire') {\n const expireAction = action as { id: string };\n const result = await this.database.archiveIntent(expireAction.id);\n results.push({\n actionType: 'expire',\n success: result.success,\n intentId: expireAction.id,\n error: result.error\n });\n logger.verbose(`Archived intent: ${expireAction.id}`);\n if (result.success) {\n this.intentQueue?.addDeleteHydeJob({ intentId: expireAction.id }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE delete job', { intentId: expireAction.id, error: err })\n );\n }\n }\n } catch (error) {\n logger.error(`Failed to execute ${action.type}:`, { error });\n results.push({\n actionType,\n success: false,\n intentId: 'id' in action ? action.id : undefined,\n error: error instanceof Error ? error.message : 'Unknown error'\n });\n }\n }\n\n return { executionResults: results };\n });\n };\n\n // --- QUERY NODE (Read Mode) ---\n\n /**\n * Node: Query\n * Fast-path read node — fetches intents from DB based on scope.\n * Handles: global user intents, index-scoped (all or filtered by user).\n * No LLM calls; no inference/verification/reconciliation.\n */\n const queryNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.query\", async () => {\n logger.verbose(\"Starting query (read mode)\", {\n userId: state.userId,\n networkId: state.networkId,\n queryUserId: state.queryUserId,\n allUserIntents: state.allUserIntents,\n });\n\n try {\n // Scope-aware default: caller's intents across all reachable indexes.\n // Triggered when the tool layer passed indexScope and did not pick a\n // specific networkId or queryUserId — i.e. \"my intents\" in a chat\n // where the agent's reach is more than one index.\n if (\n !state.queryUserId &&\n !state.networkId &&\n state.indexScope &&\n state.indexScope.length > 0\n ) {\n const intents = await this.database.getActiveIntentsAcrossIndexes(\n state.userId,\n state.indexScope,\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"You don't have any active intents yet. Share what you're looking for.\",\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n })),\n },\n };\n }\n\n // When allUserIntents is true, ignore index scope and return all\n const effectiveIndexId = state.allUserIntents ? undefined : state.networkId;\n\n if (effectiveIndexId) {\n // Verify membership\n const isMember = await this.database.isNetworkMember(effectiveIndexId, state.userId);\n if (!isMember) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"Index not found or you are not a member.\",\n },\n };\n }\n\n // Index-scoped read\n if (!state.queryUserId) {\n // All intents in the index (any member can see)\n const intents = await this.database.getNetworkIntentsForMember(\n effectiveIndexId,\n state.userId,\n { limit: 50, offset: 0 }\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"No intents in this index yet.\",\n networkId: effectiveIndexId,\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n networkId: effectiveIndexId,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n userId: i.userId,\n userName: i.userName,\n })),\n },\n };\n }\n\n // Specific user's intents in the index\n const effectiveUserId = state.queryUserId;\n const intents = await this.database.getIntentsInIndexForMember(\n effectiveUserId,\n effectiveIndexId\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message:\n effectiveUserId === state.userId\n ? \"You don't have any intents in this index yet.\"\n : \"No intents for that user in this index.\",\n networkId: effectiveIndexId,\n },\n };\n }\n const user = await this.database.getUser(effectiveUserId);\n const userName = user?.name ?? null;\n return {\n readResult: {\n count: intents.length,\n networkId: effectiveIndexId,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n userId: effectiveUserId,\n userName,\n })),\n },\n };\n }\n\n // Global (no index scope): return user's own active intents\n const intents = await this.database.getActiveIntents(state.userId);\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message:\n \"You don't have any active intents yet. Share what you're looking for.\",\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n })),\n },\n };\n } catch (err) {\n logger.error(\"Query node failed\", { error: err });\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"Failed to fetch intents. Please try again.\",\n },\n };\n }\n });\n };\n\n // --- CONDITIONAL ROUTING FUNCTIONS ---\n\n /**\n * After prep: read mode → query; otherwise decide inference vs reconciler by operation mode.\n */\n const afterPrepRoute = (state: typeof IntentGraphState.State): string => {\n if (state.error) {\n logger.warn('Prep failed with error, short-circuiting to END', { error: state.error });\n return '__end__';\n }\n if (state.operationMode === 'read') {\n logger.verbose('Read mode - routing to query (fast path)');\n return 'query';\n }\n return shouldRunInference(state);\n };\n \n /**\n * Determines if inference should run based on operation mode.\n * Delete operations skip inference entirely and go straight to reconciliation.\n */\n const shouldRunInference = (state: typeof IntentGraphState.State): string => {\n if (state.operationMode === 'delete') {\n logger.verbose('Delete mode - skipping inference, routing to reconciliation');\n return 'reconciler';\n }\n \n logger.verbose('Running inference', {\n operationMode: state.operationMode\n });\n return 'inference';\n };\n \n /**\n * Determines if verification should run based on operation mode and inferred intents.\n * Skips verification for:\n * - Operations with no inferred intents\n * - Can be extended to skip for update operations with no new intents\n */\n const shouldRunVerification = (state: typeof IntentGraphState.State): string => {\n if (state.inferredIntents.length === 0) {\n if (state.operationMode === 'propose') {\n logger.verbose('Propose mode with no inferred intents - exiting early');\n return '__end__';\n }\n logger.verbose('No intents to verify - skipping verification, routing to reconciliation');\n return 'reconciler';\n }\n \n if (state.operationMode === 'update') {\n logger.verbose('Update mode with new intents - running verification');\n return 'verification';\n }\n \n if (state.operationMode === 'create') {\n logger.verbose('Create mode - running verification');\n return 'verification';\n }\n \n // Default to verification for safety\n logger.verbose('Default routing to verification');\n return 'verification';\n };\n\n // --- GRAPH ASSEMBLY WITH CONDITIONAL EDGES (PHASE 4) ---\n\n const workflow = new StateGraph(IntentGraphState)\n .addNode(\"prep\", prepNode)\n .addNode(\"query\", queryNode)\n .addNode(\"inference\", inferenceNode)\n .addNode(\"verification\", verificationNode)\n .addNode(\"reconciler\", reconciliationNode)\n .addNode(\"executor\", executorNode)\n\n // Flow paths:\n // - READ: prep → query → END (fast path, no LLM calls)\n // - CREATE: prep → inference → verification → reconciler → executor → END\n // - UPDATE: prep → inference → reconciliation → executor → END (skips verification if no new intents)\n // - DELETE: prep → reconciliation → executor → END (skips inference and verification)\n // - PROPOSE: prep → inference → verification → END (no reconciliation/execution, no DB writes)\n .addEdge(START, \"prep\")\n \n // After prep: read mode → query; else inference or reconciler\n .addConditionalEdges(\"prep\", afterPrepRoute, {\n query: \"query\",\n inference: \"inference\",\n reconciler: \"reconciler\",\n __end__: END,\n })\n\n // Query (read mode) always ends\n .addEdge(\"query\", END)\n \n // After inference: decide if we need verification (skip if no intents)\n .addConditionalEdges(\"inference\", shouldRunVerification, {\n verification: \"verification\",\n reconciler: \"reconciler\",\n __end__: END,\n })\n \n // After verification: propose mode exits early; others continue to reconciliation\n .addConditionalEdges(\"verification\", (state: typeof IntentGraphState.State) => {\n if (state.operationMode === 'propose') {\n logger.verbose('Propose mode - stopping after verification, skipping reconciliation');\n return '__end__';\n }\n return 'reconciler';\n }, {\n reconciler: \"reconciler\",\n __end__: END,\n })\n \n // Reconciliation always goes to executor\n .addEdge(\"reconciler\", \"executor\")\n \n // Executor is always the end\n .addEdge(\"executor\", END);\n\n return workflow.compile();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"intent.graph.js","sourceRoot":"/","sources":["intent/intent.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAmC,MAAM,mBAAmB,CAAC;AACtF,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAA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ACb,CAAC;YAEF,yCAAyC;aACxC,OAAO,CAAC,YAAY,EAAE,UAAU,CAAC;YAElC,6BAA6B;aAC5B,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;QAE5B,OAAO,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC5B,CAAC;CACF","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\nimport { IntentGraphState, VerifiedIntent, ExecutionResult } from \"./intent.state.js\";\nimport { ExplicitIntentInferrer } from \"./intent.inferrer.js\";\nimport { SemanticVerifier } from \"./intent.verifier.js\";\nimport { DEFAULT_SPECIFICITY_WARNING } from \"./intent.specificity.js\";\nimport { IntentReconciler } from \"./intent.reconciler.js\";\nimport { IntentGraphDatabase } from \"../shared/interfaces/database.interface.js\";\nimport { getAbortSignalConfig } from \"../shared/agent/model-signal.js\";\nimport type { EmbeddingGenerator } from \"../shared/interfaces/embedder.interface.js\";\nimport type { IntentGraphQueue } from \"../shared/interfaces/queue.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { timed } from \"../shared/observability/performance.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport type { DebugMetaAgent } from \"../chat/chat-streaming.types.js\";\nimport type { QuestionerEnqueueFn } from \"../questioner/questioner.types.js\";\n\nconst logger = protocolLogger(\"IntentGraphFactory\");\nconst MAX_PERMISSIBLE_ENTROPY = 0.75;\nconst MIN_CLEAR_INTENT_SCORE = 40;\nconst GENERIC_JOB_PHRASE = /\\b(?:a|any|some)\\s+job\\b/i;\n\nconst inferRoleFromContextText = (text: string): string | null => {\n const normalized = text.toLowerCase();\n if (/\\b(engineer|developer)\\b/.test(normalized)) return \"software engineering\";\n if (/\\b(designer|ux|ui)\\b/.test(normalized)) return \"product design\";\n if (/\\b(marketing|marketer|growth)\\b/.test(normalized)) return \"marketing\";\n if (/\\b(product manager|product)\\b/.test(normalized)) return \"product management\";\n if (/\\b(data scientist|machine learning|ml|ai)\\b/.test(normalized)) return \"AI/ML\";\n if (/\\b(sales|account executive|business development)\\b/.test(normalized)) return \"sales\";\n return null;\n};\n\n/**\n * Derive a job-role qualifier from the user's global user_context paragraph\n * (the identity text that replaced the legacy profile projection). Role is\n * inferred from the free text; the old structured skills/interests extraction\n * is gone with the removed profile fields.\n */\nconst buildJobQualifierFromContext = (contextText: string): string | null => {\n const roleHint = inferRoleFromContextText(contextText ?? \"\");\n return roleHint ? `${roleHint} role` : null;\n};\n\nconst enrichVagueIntentWithContext = (description: string, userContext: string): string => {\n const trimmed = description?.trim();\n if (!trimmed) return description;\n\n const isGenericJobRequest =\n GENERIC_JOB_PHRASE.test(trimmed) ||\n /\\b(?:find|get|look(?:ing)?\\s+for|want)\\s+(?:to\\s+)?(?:find\\s+)?job\\b/i.test(trimmed);\n if (!isGenericJobRequest) return description;\n\n const qualifier = buildJobQualifierFromContext(userContext);\n if (!qualifier) return description;\n\n const enriched = trimmed\n .replace(/\\ba job\\b/i, `a ${qualifier}`)\n .replace(/\\bjob\\b/i, `${qualifier}`)\n .replace(/\\s{2,}/g, \" \")\n .trim();\n\n return enriched.length > 0 ? enriched : description;\n};\n\nconst isVague = (description: string, entropy: number, clarity: number): boolean => {\n if (GENERIC_JOB_PHRASE.test(description)) return true;\n if (entropy > MAX_PERMISSIBLE_ENTROPY) return true;\n if (clarity < MIN_CLEAR_INTENT_SCORE) return true;\n return false;\n};\n\nconst getSpecificityWarning = (verdict: { specificity_warning?: string | null }): string => {\n const warning = verdict.specificity_warning?.trim();\n return warning && warning.length > 0 ? warning : DEFAULT_SPECIFICITY_WARNING;\n};\n\nconst toSpeechActType = (classification?: string): \"COMMISSIVE\" | \"DIRECTIVE\" | null => {\n if (classification === \"COMMISSIVE\" || classification === \"DIRECTIVE\") return classification;\n return null;\n};\n\n/**\n * Factory class to build and compile the Intent Processing Graph.\n */\nexport class IntentGraphFactory {\n constructor(\n private database: IntentGraphDatabase,\n private embedder?: EmbeddingGenerator,\n private intentQueue?: IntentGraphQueue,\n private questionerEnqueue?: QuestionerEnqueueFn,\n ) { }\n\n public createGraph() {\n // Instantiate Agents (Nodes)\n const inferrer = new ExplicitIntentInferrer();\n const verifier = new SemanticVerifier();\n const reconciler = new IntentReconciler();\n\n // --- NODE DEFINITIONS ---\n\n /**\n * Node 0: Prep\n * Always fetches ALL of the user's active intents from the DB via getActiveIntents(userId).\n * This ensures reconciliation can detect duplicates and modifications globally,\n * regardless of network scope.\n */\n const prepNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.prep\", async () => {\n logger.verbose(\"Starting preparation phase\", {\n operationMode: state.operationMode,\n hasContent: !!state.inputContent,\n targetIntentIds: state.targetIntentIds,\n networkId: state.networkId,\n });\n\n // Gate: write operations require an existing profile\n if (state.operationMode !== 'read') {\n const profile = await this.database.getProfile(state.userId);\n if (!profile) {\n const msg = \"You need to create a profile before creating intents. Please set up your profile first.\";\n logger.error(\"Prep failed: no profile for user\", { userId: state.userId });\n return { error: msg };\n }\n }\n\n const activeIntents = await this.database.getActiveIntents(state.userId);\n const formattedActiveIntents = activeIntents\n .map(i => `ID: ${i.id}, Description: ${i.payload}, Summary: ${i.summary || 'N/A'}`)\n .join('\\n') || \"No active intents.\";\n\n logger.verbose(\"Fetched active intents\", {\n count: activeIntents.length,\n operationMode: state.operationMode\n });\n\n return {\n activeIntents: formattedActiveIntents,\n trace: [{\n node: \"prep\",\n detail: `Fetched ${activeIntents.length} active intent(s)`,\n }],\n };\n });\n };\n\n /**\n * Node 1: Inference\n * Extracts intents from raw content.\n * Phase 4: Uses operation mode to control behavior and determine if node should execute.\n * Phase 5: Passes conversation context for anaphoric resolution.\n */\n const inferenceNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.inference\", async () => {\n logger.verbose(\"Starting inference\", {\n operationMode: state.operationMode,\n hasContent: !!state.inputContent,\n contentPreview: state.inputContent?.substring(0, 50),\n hasConversationContext: !!state.conversationContext,\n conversationMessagesCount: state.conversationContext?.length || 0\n });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Phase 4: Control profile fallback based on operation mode\n // Only allow for create operations without explicit content\n const allowProfileFallback = state.operationMode === 'create' && !state.inputContent;\n\n // Cast operationMode: 'read' and 'propose' map to 'create' for the inferrer\n // (inference node is never called in read mode; propose behaves like create for inference)\n const inferrerMode = (state.operationMode === 'read' || state.operationMode === 'propose') ? 'create' : state.operationMode;\n const _traceEmitterInferrer = requestContext.getStore()?.traceEmitter;\n const inferrerStart = Date.now();\n _traceEmitterInferrer?.({ type: \"agent_start\", name: \"intent-inferrer\" });\n const result = await inferrer.invoke(\n state.inputContent || null,\n state.userProfile,\n {\n allowProfileFallback,\n operationMode: inferrerMode,\n conversationContext: state.conversationContext // Phase 5: Pass conversation history\n }\n );\n agentTimingsAccum.push({ name: 'intent.inferrer', durationMs: Date.now() - inferrerStart });\n _traceEmitterInferrer?.({ type: \"agent_end\", name: \"intent-inferrer\", durationMs: Date.now() - inferrerStart, summary: result.intents.length > 0 ? `Extracted ${result.intents.length} intent(s)` : \"intent-inferrer completed\" });\n\n logger.verbose(\"Inference complete\", {\n inferredCount: result.intents.length,\n operationMode: state.operationMode\n });\n\n const descriptions = result.intents.map(i => i.description).slice(0, 3);\n const truncated = result.intents.length > 3 ? `... +${result.intents.length - 3} more` : \"\";\n\n return {\n inferredIntents: result.intents,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"inference\",\n detail: result.intents.length === 0\n ? \"No intents extracted\"\n : `Extracted ${result.intents.length}: ${descriptions.map(d => `\"${d.slice(0, 50)}${d.length > 50 ? '...' : ''}\"`).join(\", \")}${truncated}`,\n }],\n };\n });\n };\n\n /**\n * Node 2: Verification (Map-Reduce / Parallel)\n * Verifies each inferred intent in parallel.\n * Phase 4: Can be skipped for delete operations and updates with no new intents.\n */\n const verificationNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.verification\", async () => {\n const intents = state.inferredIntents;\n\n logger.verbose(\"Starting verification\", {\n operationMode: state.operationMode,\n intentCount: intents.length\n });\n\n if (intents.length === 0) {\n logger.verbose(\"No intents to verify\");\n return { verifiedIntents: [], agentTimings: [] };\n }\n\n logger.verbose(`Verifying ${intents.length} intents in parallel...`);\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Parallel Execution\n const verificationResults = await Promise.all(\n intents.map(async (intent): Promise<VerifiedIntent | null> => {\n try {\n let description = intent.description;\n const _traceEmitterVerifier = requestContext.getStore()?.traceEmitter;\n const verifierStart1 = Date.now();\n _traceEmitterVerifier?.({ type: \"agent_start\", name: \"intent-verifier\" });\n let verdict = await verifier.invoke(description, state.userProfile);\n agentTimingsAccum.push({ name: 'intent.verifier', durationMs: Date.now() - verifierStart1 });\n _traceEmitterVerifier?.({ type: \"agent_end\", name: \"intent-verifier\", durationMs: Date.now() - verifierStart1, summary: `Verified: ${verdict.classification}` });\n\n if (isVague(description, verdict.semantic_entropy, verdict.felicity_scores.clarity)) {\n // Role-hint enrichment for vague job intents reads the global\n // user_context paragraph instead of the structured profile fields.\n const roleHintContext = (await this.database.getUserContext(state.userId, null))?.text ?? '';\n const enrichedDescription = enrichVagueIntentWithContext(description, roleHintContext);\n if (enrichedDescription !== description) {\n logger.verbose(\"Enriched vague intent using profile context\", {\n before: description,\n after: enrichedDescription,\n });\n const _traceEmitterVerifier2 = requestContext.getStore()?.traceEmitter;\n const verifierStart2 = Date.now();\n _traceEmitterVerifier2?.({ type: \"agent_start\", name: \"intent-verifier\" });\n const enrichedVerdict = await verifier.invoke(enrichedDescription, state.userProfile);\n agentTimingsAccum.push({ name: 'intent.verifier', durationMs: Date.now() - verifierStart2 });\n _traceEmitterVerifier2?.({ type: \"agent_end\", name: \"intent-verifier\", durationMs: Date.now() - verifierStart2, summary: `Verified (enriched): ${enrichedVerdict.classification}` });\n const becameClear =\n enrichedVerdict.semantic_entropy < verdict.semantic_entropy ||\n enrichedVerdict.felicity_scores.clarity > verdict.felicity_scores.clarity;\n if (becameClear) {\n description = enrichedDescription;\n verdict = enrichedVerdict;\n }\n }\n }\n\n // Filter Logic: Must be a Commissive, Directive, or Declaration\n const VALID_TYPES = ['COMMISSIVE', 'DIRECTIVE', 'DECLARATION'];\n if (!VALID_TYPES.includes(verdict.classification)) {\n logger.warn(`Dropping intent: \"${description}\" (Type: ${verdict.classification})`);\n return null;\n }\n\n if (isVague(description, verdict.semantic_entropy, verdict.felicity_scores.clarity)) {\n logger.warn(`Dropping vague intent after verification: \"${description}\"`, {\n entropy: verdict.semantic_entropy,\n clarity: verdict.felicity_scores.clarity,\n });\n return null;\n }\n\n if (state.operationMode !== 'propose' && verdict.referential_breadth === 'broad') {\n logger.warn(`Dropping broad attributive intent before persistence: \"${description}\"`, {\n referentialBreadth: verdict.referential_breadth,\n missingSelectionalConstraints: verdict.missing_selectional_constraints,\n warning: getSpecificityWarning(verdict),\n });\n return null;\n }\n\n // Calculate Score\n const score = Math.min(\n verdict.felicity_scores.authority,\n verdict.felicity_scores.sincerity,\n verdict.felicity_scores.clarity\n );\n\n // Return enriched intent\n return {\n ...intent,\n description,\n verification: verdict,\n score\n };\n } catch (e) {\n logger.error(`Error verifying intent: ${intent.description}`, { error: e });\n return null;\n }\n })\n );\n\n // Filter out nulls\n const verified = verificationResults.filter((i): i is VerifiedIntent => i !== null);\n logger.verbose(`Verification complete`, {\n passed: verified.length,\n total: intents.length,\n operationMode: state.operationMode\n });\n\n // Build trace entries with Felicity scores for each verified intent\n const traceEntries = verified.map(v => {\n const fs = v.verification?.felicity_scores;\n const entropy = v.verification?.semantic_entropy;\n const classification = v.verification?.classification;\n const referentialBreadth = v.verification?.referential_breadth;\n return {\n node: \"verification\",\n detail: `\"${v.description.slice(0, 40)}${v.description.length > 40 ? '...' : ''}\" → ${classification}${referentialBreadth ? ` (${referentialBreadth} referential breadth)` : ''}`,\n data: fs ? {\n clarity: fs.clarity,\n authority: fs.authority,\n sincerity: fs.sincerity,\n entropy: entropy != null ? Math.round(entropy * 100) / 100 : undefined,\n referentialBreadth,\n missingSelectionalConstraints: v.verification?.missing_selectional_constraints,\n specificityWarning: v.verification?.specificity_warning ?? undefined,\n classification,\n score: v.score,\n } : undefined,\n };\n });\n\n // Add summary trace if some intents were filtered out\n const dropped = intents.length - verified.length;\n if (dropped > 0) {\n traceEntries.unshift({\n node: \"verification\",\n detail: `Verified ${verified.length}/${intents.length} (${dropped} filtered as invalid)`,\n data: undefined,\n });\n } else if (verified.length > 0) {\n traceEntries.unshift({\n node: \"verification\",\n detail: `Verified ${verified.length} intent(s)`,\n data: undefined,\n });\n }\n\n return { verifiedIntents: verified, agentTimings: agentTimingsAccum, trace: traceEntries };\n });\n };\n\n /**\n * Node 3: Reconciliation\n * Decides on final actions (Create, Update, Expire).\n * Phase 4: Handles delete operations directly without LLM reconciliation.\n */\n const reconciliationNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.reconciliation\", async () => {\n logger.verbose(\"Starting reconciliation\", {\n operationMode: state.operationMode,\n verifiedIntentCount: state.verifiedIntents.length,\n targetIntentIds: state.targetIntentIds\n });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n // Phase 4: Handle delete operations directly\n if (state.operationMode === 'delete') {\n if (!state.targetIntentIds || state.targetIntentIds.length === 0) {\n logger.warn(\"Delete mode with no target IDs\");\n return {\n actions: [],\n agentTimings: agentTimingsAccum,\n trace: [{ node: \"reconciler\", detail: \"Delete mode with no target IDs\" }],\n };\n }\n\n logger.verbose(\"Delete mode - generating expire actions\", {\n targetIds: state.targetIntentIds\n });\n\n const actions = state.targetIntentIds.map(id => ({\n type: 'expire' as const,\n id,\n reasoning: 'User requested deletion'\n }));\n\n return {\n actions,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"reconciler\",\n detail: `Actions: expire=${actions.length}`,\n }],\n };\n }\n\n // Standard reconciliation for create/update operations\n const candidates = state.verifiedIntents;\n if (candidates.length === 0) {\n logger.verbose(\"No verified intents to reconcile\");\n return {\n actions: [],\n agentTimings: agentTimingsAccum,\n trace: [{ node: \"reconciler\", detail: \"No intents to reconcile\" }],\n };\n }\n\n // Format candidates for the Reconciler Prompt\n const formattedCandidates = candidates.map(c =>\n `- [${c.type.toUpperCase()}] \"${c.description}\" (Confidence: ${c.confidence}, Score: ${c.score})\\n` +\n ` Reasoning: ${c.reasoning}\\n` +\n ` Verification: ${c.verification?.classification} (Flags: ${c.verification?.flags.join(', ') || 'None'})`\n ).join('\\n');\n\n logger.verbose(\"Invoking reconciler agent\", {\n candidateCount: candidates.length,\n operationMode: state.operationMode\n });\n\n const _traceEmitterReconciler = requestContext.getStore()?.traceEmitter;\n const reconcilerStart = Date.now();\n _traceEmitterReconciler?.({ type: \"agent_start\", name: \"intent-reconciler\" });\n const result = await reconciler.invoke(formattedCandidates, state.activeIntents);\n agentTimingsAccum.push({ name: 'intent.reconciler', durationMs: Date.now() - reconcilerStart });\n _traceEmitterReconciler?.({ type: \"agent_end\", name: \"intent-reconciler\", durationMs: Date.now() - reconcilerStart, summary: `Reconciled ${result.actions.length} action(s)` });\n\n logger.verbose(\"Reconciliation complete\", {\n actionCount: result.actions.length,\n operationMode: state.operationMode\n });\n\n // Count actions by type\n const counts = { create: 0, update: 0, expire: 0 };\n for (const a of result.actions) {\n if (a.type in counts) counts[a.type as keyof typeof counts]++;\n }\n\n return {\n actions: result.actions,\n agentTimings: agentTimingsAccum,\n trace: [{\n node: \"reconciler\",\n detail: `Actions: create=${counts.create}, update=${counts.update}, expire=${counts.expire}`,\n }],\n };\n });\n };\n\n /** Strip URLs and \"More details at [url]\" from intent payloads before persisting. */\n const sanitizePayload = (payload: string): string => {\n if (!payload || typeof payload !== \"string\") return payload;\n const out = payload\n .replace(/\\s*More details at\\s*:?\\s*https?:\\/\\/[^\\s\"'<>)\\]]+/gi, \"\")\n .replace(/\\s*See\\s+https?:\\/\\/[^\\s\"'<>)\\]]+\\s+for\\s+more[^.]*\\.?/gi, \"\")\n .replace(/https?:\\/\\/[^\\s\"'<>)\\]]+/g, \"\")\n .replace(/\\s{2,}/g, \" \")\n .trim();\n return out.replace(/[.,;]\\s*$/, \"\").trim() || payload;\n };\n\n /**\n * Generate a flat embedding for an intent payload, swallowing failures so\n * persistence can continue without an embedding. `intentId` is logging-only\n * (present for updates, absent for creates).\n */\n const generateIntentEmbedding = async (\n sanitizedPayload: string,\n intentId?: string,\n ): Promise<number[] | undefined> => {\n if (!this.embedder) return undefined;\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n const flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for intent\", {\n ...(intentId ? { intentId } : {}),\n dimensions: flatEmbedding?.length,\n });\n return flatEmbedding;\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent (continuing without)\", {\n ...(intentId ? { intentId } : {}),\n error: embErr,\n });\n return undefined;\n }\n };\n\n /**\n * Node 4: Executor\n * Executes reconciler actions against the database.\n */\n const executorNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.executor\", async () => {\n const actions = state.actions;\n if (!actions || actions.length === 0) {\n return { executionResults: [] };\n }\n\n logger.verbose(`Executing ${actions.length} actions...`);\n const results: ExecutionResult[] = [];\n const scopeEnvelope = state.scopeType && state.scopeId\n ? { scopeType: state.scopeType, scopeId: state.scopeId }\n : {};\n const verifiedIntentByPayload = new Map<string, VerifiedIntent>();\n for (const verifiedIntent of state.verifiedIntents) {\n verifiedIntentByPayload.set(verifiedIntent.description, verifiedIntent);\n verifiedIntentByPayload.set(sanitizePayload(verifiedIntent.description), verifiedIntent);\n }\n\n for (const action of actions) {\n const actionType = action.type.toLowerCase() as 'create' | 'update' | 'expire';\n try {\n if (actionType === 'create') {\n const createAction = action as {\n payload: string;\n score: number | null;\n semanticEntropy?: number | null;\n referentialAnchor?: string | null;\n intentMode?: 'REFERENTIAL' | 'ATTRIBUTIVE' | null;\n };\n const sanitizedPayload = sanitizePayload(createAction.payload);\n const matchedVerifiedIntent =\n verifiedIntentByPayload.get(createAction.payload) ||\n verifiedIntentByPayload.get(sanitizedPayload);\n\n // Generate embedding for the intent payload\n const flatEmbedding = await generateIntentEmbedding(sanitizedPayload);\n\n const created = await this.database.createIntent({\n userId: state.userId,\n payload: sanitizedPayload,\n confidence: createAction.score ? createAction.score / 100 : 1.0,\n inferenceType: 'explicit',\n sourceType: 'discovery_form',\n embedding: flatEmbedding,\n semanticEntropy:\n createAction.semanticEntropy ??\n matchedVerifiedIntent?.verification?.semantic_entropy ??\n null,\n referentialAnchor:\n createAction.referentialAnchor ??\n matchedVerifiedIntent?.verification?.referential_anchor ??\n null,\n felicityAuthority: matchedVerifiedIntent?.verification?.felicity_scores.authority ?? null,\n felicitySincerity: matchedVerifiedIntent?.verification?.felicity_scores.sincerity ?? null,\n felicityClarity: matchedVerifiedIntent?.verification?.felicity_scores.clarity ?? null,\n intentMode: createAction.intentMode ?? null,\n speechActType: toSpeechActType(matchedVerifiedIntent?.verification?.classification),\n });\n\n results.push({ actionType: 'create', success: true, intentId: created.id, payload: sanitizedPayload });\n logger.verbose(`Created intent: ${created.id}`);\n\n this.intentQueue?.addGenerateHydeJob({\n intentId: created.id,\n userId: state.userId,\n ...scopeEnvelope,\n }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE job', { intentId: created.id, error: err })\n );\n\n if (this.questionerEnqueue) {\n const userContext = (await this.database.getUserContext(state.userId, null))?.text ?? '';\n this.questionerEnqueue({\n mode: 'intent',\n userId: state.userId,\n sourceType: 'intent',\n sourceId: created.id,\n ...scopeEnvelope,\n context: {\n intentId: created.id,\n payload: sanitizedPayload,\n userContext,\n },\n }).catch((err) =>\n logger.error('Failed to enqueue intent question generation', { intentId: created.id, error: err })\n );\n }\n\n } else if (actionType === 'update') {\n const updateAction = action as {\n id: string;\n payload: string;\n intentMode?: 'REFERENTIAL' | 'ATTRIBUTIVE' | null;\n };\n const sanitizedPayload = sanitizePayload(updateAction.payload);\n const matchedVerifiedIntent =\n verifiedIntentByPayload.get(updateAction.payload) ||\n verifiedIntentByPayload.get(sanitizedPayload);\n\n // Regenerate embedding for the updated payload\n const flatEmbedding = await generateIntentEmbedding(sanitizedPayload, updateAction.id);\n\n const updated = await this.database.updateIntent(updateAction.id, {\n payload: sanitizedPayload,\n embedding: flatEmbedding,\n semanticEntropy:\n matchedVerifiedIntent?.verification?.semantic_entropy ??\n null,\n referentialAnchor:\n matchedVerifiedIntent?.verification?.referential_anchor ??\n null,\n felicityAuthority: matchedVerifiedIntent?.verification?.felicity_scores.authority ?? null,\n felicitySincerity: matchedVerifiedIntent?.verification?.felicity_scores.sincerity ?? null,\n felicityClarity: matchedVerifiedIntent?.verification?.felicity_scores.clarity ?? null,\n intentMode: updateAction.intentMode ?? null,\n speechActType: toSpeechActType(matchedVerifiedIntent?.verification?.classification),\n });\n results.push({\n actionType: 'update',\n success: !!updated,\n intentId: updateAction.id,\n payload: sanitizedPayload,\n error: updated ? undefined : 'Intent not found'\n });\n logger.verbose(`Updated intent: ${updateAction.id}`);\n if (updated) {\n this.intentQueue?.addGenerateHydeJob({\n intentId: updateAction.id,\n userId: state.userId,\n ...scopeEnvelope,\n }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE job', { intentId: updateAction.id, error: err })\n );\n }\n\n } else if (actionType === 'expire') {\n const expireAction = action as { id: string };\n const result = await this.database.archiveIntent(expireAction.id);\n results.push({\n actionType: 'expire',\n success: result.success,\n intentId: expireAction.id,\n error: result.error\n });\n logger.verbose(`Archived intent: ${expireAction.id}`);\n if (result.success) {\n this.intentQueue?.addDeleteHydeJob({ intentId: expireAction.id }).catch((err) =>\n logger.error('Failed to enqueue intent HyDE delete job', { intentId: expireAction.id, error: err })\n );\n }\n }\n } catch (error) {\n logger.error(`Failed to execute ${action.type}:`, { error });\n results.push({\n actionType,\n success: false,\n intentId: 'id' in action ? action.id : undefined,\n error: error instanceof Error ? error.message : 'Unknown error'\n });\n }\n }\n\n return { executionResults: results };\n });\n };\n\n // --- QUERY NODE (Read Mode) ---\n\n /**\n * Node: Query\n * Fast-path read node — fetches intents from DB based on scope.\n * Handles: global user intents, network-scoped (all or filtered by user).\n * No LLM calls; no inference/verification/reconciliation.\n */\n const queryNode = async (state: typeof IntentGraphState.State) => {\n return timed(\"IntentGraph.query\", async () => {\n logger.verbose(\"Starting query (read mode)\", {\n userId: state.userId,\n networkId: state.networkId,\n queryUserId: state.queryUserId,\n allUserIntents: state.allUserIntents,\n });\n\n try {\n // Scope-aware default: caller's intents across all reachable networks.\n // Triggered when the tool layer passed indexScope and did not pick a\n // specific networkId or queryUserId — i.e. \"my intents\" in a chat\n // where the agent's reach is more than one index.\n if (\n !state.queryUserId &&\n !state.networkId &&\n state.indexScope &&\n state.indexScope.length > 0\n ) {\n const intents = await this.database.getActiveIntentsAcrossIndexes(\n state.userId,\n state.indexScope,\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"You don't have any active intents yet. Share what you're looking for.\",\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n })),\n },\n };\n }\n\n // When allUserIntents is true, ignore network scope and return all\n const effectiveIndexId = state.allUserIntents ? undefined : state.networkId;\n\n if (effectiveIndexId) {\n // Verify membership\n const isMember = await this.database.isNetworkMember(effectiveIndexId, state.userId);\n if (!isMember) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"Index not found or you are not a member.\",\n },\n };\n }\n\n // Network-scoped read\n if (!state.queryUserId) {\n // All intents in the index (any member can see)\n const intents = await this.database.getNetworkIntentsForMember(\n effectiveIndexId,\n state.userId,\n { limit: 50, offset: 0 }\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"No intents in this network yet.\",\n networkId: effectiveIndexId,\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n networkId: effectiveIndexId,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n userId: i.userId,\n userName: i.userName,\n })),\n },\n };\n }\n\n // Specific user's intents in the index\n const effectiveUserId = state.queryUserId;\n const intents = await this.database.getIntentsInIndexForMember(\n effectiveUserId,\n effectiveIndexId\n );\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message:\n effectiveUserId === state.userId\n ? \"You don't have any intents in this network yet.\"\n : \"No intents for that user in this network.\",\n networkId: effectiveIndexId,\n },\n };\n }\n const user = await this.database.getUser(effectiveUserId);\n const userName = user?.name ?? null;\n return {\n readResult: {\n count: intents.length,\n networkId: effectiveIndexId,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n userId: effectiveUserId,\n userName,\n })),\n },\n };\n }\n\n // Global (no network scope): return user's own active intents\n const intents = await this.database.getActiveIntents(state.userId);\n if (intents.length === 0) {\n return {\n readResult: {\n count: 0,\n intents: [],\n message:\n \"You don't have any active intents yet. Share what you're looking for.\",\n },\n };\n }\n return {\n readResult: {\n count: intents.length,\n intents: intents.map((i) => ({\n id: i.id,\n description: i.payload,\n summary: i.summary,\n createdAt: i.createdAt,\n })),\n },\n };\n } catch (err) {\n logger.error(\"Query node failed\", { error: err });\n return {\n readResult: {\n count: 0,\n intents: [],\n message: \"Failed to fetch intents. Please try again.\",\n },\n };\n }\n });\n };\n\n // --- CONDITIONAL ROUTING FUNCTIONS ---\n\n /**\n * After prep: read mode → query; otherwise decide inference vs reconciler by operation mode.\n */\n const afterPrepRoute = (state: typeof IntentGraphState.State): string => {\n if (state.error) {\n logger.warn('Prep failed with error, short-circuiting to END', { error: state.error });\n return '__end__';\n }\n if (state.operationMode === 'read') {\n logger.verbose('Read mode - routing to query (fast path)');\n return 'query';\n }\n return shouldRunInference(state);\n };\n\n /**\n * Determines if inference should run based on operation mode.\n * Delete operations skip inference entirely and go straight to reconciliation.\n */\n const shouldRunInference = (state: typeof IntentGraphState.State): string => {\n if (state.operationMode === 'delete') {\n logger.verbose('Delete mode - skipping inference, routing to reconciliation');\n return 'reconciler';\n }\n\n logger.verbose('Running inference', {\n operationMode: state.operationMode\n });\n return 'inference';\n };\n\n /**\n * Determines if verification should run based on operation mode and inferred intents.\n * Skips verification for:\n * - Operations with no inferred intents\n * - Can be extended to skip for update operations with no new intents\n */\n const shouldRunVerification = (state: typeof IntentGraphState.State): string => {\n if (state.inferredIntents.length === 0) {\n if (state.operationMode === 'propose') {\n logger.verbose('Propose mode with no inferred intents - exiting early');\n return '__end__';\n }\n logger.verbose('No intents to verify - skipping verification, routing to reconciliation');\n return 'reconciler';\n }\n\n if (state.operationMode === 'update') {\n logger.verbose('Update mode with new intents - running verification');\n return 'verification';\n }\n\n if (state.operationMode === 'create') {\n logger.verbose('Create mode - running verification');\n return 'verification';\n }\n\n // Default to verification for safety\n logger.verbose('Default routing to verification');\n return 'verification';\n };\n\n // --- GRAPH ASSEMBLY WITH CONDITIONAL EDGES (PHASE 4) ---\n\n const workflow = new StateGraph(IntentGraphState)\n .addNode(\"prep\", prepNode)\n .addNode(\"query\", queryNode)\n .addNode(\"inference\", inferenceNode)\n .addNode(\"verification\", verificationNode)\n .addNode(\"reconciler\", reconciliationNode)\n .addNode(\"executor\", executorNode)\n\n // Flow paths:\n // - READ: prep → query → END (fast path, no LLM calls)\n // - CREATE: prep → inference → verification → reconciler → executor → END\n // - UPDATE: prep → inference → reconciliation → executor → END (skips verification if no new intents)\n // - DELETE: prep → reconciliation → executor → END (skips inference and verification)\n // - PROPOSE: prep → inference → verification → END (no reconciliation/execution, no DB writes)\n .addEdge(START, \"prep\")\n\n // After prep: read mode → query; else inference or reconciler\n .addConditionalEdges(\"prep\", afterPrepRoute, {\n query: \"query\",\n inference: \"inference\",\n reconciler: \"reconciler\",\n __end__: END,\n })\n\n // Query (read mode) always ends\n .addEdge(\"query\", END)\n\n // After inference: decide if we need verification (skip if no intents)\n .addConditionalEdges(\"inference\", shouldRunVerification, {\n verification: \"verification\",\n reconciler: \"reconciler\",\n __end__: END,\n })\n\n // After verification: propose mode exits early; others continue to reconciliation\n .addConditionalEdges(\"verification\", (state: typeof IntentGraphState.State) => {\n if (state.operationMode === 'propose') {\n logger.verbose('Propose mode - stopping after verification, skipping reconciliation');\n return '__end__';\n }\n return 'reconciler';\n }, {\n reconciler: \"reconciler\",\n __end__: END,\n })\n\n // Reconciliation always goes to executor\n .addEdge(\"reconciler\", \"executor\")\n\n // Executor is always the end\n .addEdge(\"executor\", END);\n\n return workflow.compile();\n }\n}\n"]}
|
|
@@ -37,7 +37,7 @@ export declare class IntentIndexer {
|
|
|
37
37
|
invoke(intent: string, indexPrompt: string | null, memberPrompt: string | null, sourceName?: string | null, networkContext?: string | null): Promise<IntentIndexerOutput | null>;
|
|
38
38
|
/**
|
|
39
39
|
* Alias for invoke. Evaluates the appropriateness of an intent for a given index and member context.
|
|
40
|
-
* Kept for compatibility with callers (e.g.
|
|
40
|
+
* Kept for compatibility with callers (e.g. Network Graph) that use evaluate().
|
|
41
41
|
*/
|
|
42
42
|
evaluate(intent: string, indexPrompt: string | null, memberPrompt: string | null, sourceName?: string | null, networkContext?: string | null): Promise<IntentIndexerOutput | null>;
|
|
43
43
|
/**
|
|
@@ -35,7 +35,7 @@ Determine if a User Intent is appropriate for a specific Index (community) and m
|
|
|
35
35
|
|
|
36
36
|
INPUTS:
|
|
37
37
|
1. Intent: The content/action the user wants to perform.
|
|
38
|
-
2.
|
|
38
|
+
2. Network Prompt: The purpose/scope of the target community (Index).
|
|
39
39
|
3. Member Prompt: The specific sharing preferences of the user in that community (optional).
|
|
40
40
|
4. Source: Origin of the intent (file, link, etc.) (optional).
|
|
41
41
|
5. Network Context: Rendered context about the network including type, dates, location, and events (optional).
|
|
@@ -43,7 +43,7 @@ INPUTS:
|
|
|
43
43
|
NETWORK TYPE AWARENESS:
|
|
44
44
|
- When Network Context is provided, use it to inform your scoring.
|
|
45
45
|
- For EVENT networks: consider temporal relevance. An intent about "meeting at the venue" is highly relevant to an upcoming event but irrelevant after it ends. Intents about topics aligned with the event's themes should score higher.
|
|
46
|
-
- For COMMUNITY networks: score based on the
|
|
46
|
+
- For COMMUNITY networks: score based on the network prompt and member preferences as usual.
|
|
47
47
|
- If the network context includes dates and the intent is time-sensitive, factor temporal proximity into the score.
|
|
48
48
|
|
|
49
49
|
SCORING RUBRIC:
|
|
@@ -54,7 +54,7 @@ SCORING RUBRIC:
|
|
|
54
54
|
- 0.0-0.2: Not appropriate.
|
|
55
55
|
|
|
56
56
|
OUTPUT RULES:
|
|
57
|
-
- Provide \`indexScore\` based on how well the Intent fits the
|
|
57
|
+
- Provide \`indexScore\` based on how well the Intent fits the Network Prompt.
|
|
58
58
|
- Provide \`memberScore\` based on how well the Intent fits the Member Prompt (if provided). If Member Prompt is missing/empty, return 0.0 for memberScore.
|
|
59
59
|
- Provide concise \`reasoning\`.
|
|
60
60
|
`;
|
|
@@ -130,7 +130,7 @@ export class IntentIndexer {
|
|
|
130
130
|
}
|
|
131
131
|
/**
|
|
132
132
|
* Alias for invoke. Evaluates the appropriateness of an intent for a given index and member context.
|
|
133
|
-
* Kept for compatibility with callers (e.g.
|
|
133
|
+
* Kept for compatibility with callers (e.g. Network Graph) that use evaluate().
|
|
134
134
|
*/
|
|
135
135
|
async evaluate(intent, indexPrompt, memberPrompt, sourceName, networkContext) {
|
|
136
136
|
return this.invoke(intent, indexPrompt, memberPrompt, sourceName, networkContext);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intent.indexer.js","sourceRoot":"/","sources":["intent/intent.indexer.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAA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E,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,2DAA2D,CAAC;aACvH,CAAC;SACH,CACF,CAAC;IACJ,CAAC;CACF;AAhGc;IADZ,KAAK,EAAE;;;;2CA4CP;AAOY;IADZ,KAAK,EAAE;;;;6CASP","sourcesContent":["import type { ChatOpenAI } from \"@langchain/openai\";\nimport { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { log } from \"../shared/observability/log.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport { createModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\n// ──────────────────────────────────────────────────────────────\n// Response schema\n// ──────────────────────────────────────────────────────────────\n\nexport const IntentIndexerOutputSchema = z.object({\n indexScore: z.number().min(0).max(1).describe(\"Score for index appropriateness (0.0-1.0)\"),\n memberScore: z.number().min(0).max(1).describe(\"Score for member preference match (0.0-1.0)\"),\n reasoning: z.string().describe(\"Brief reasoning for the scores\"),\n});\n\n/**\n * Output structure for the Intent Indexer agent.\n */\nexport type IntentIndexerOutput = z.infer<typeof IntentIndexerOutputSchema>;\n\nconst logger = log.lib.from(\"IntentIndexer\");\n\nconst model = createModel(\"intentIndexer\");\n\n// ──────────────────────────────────────────────────────────────\n// 1. SYSTEM PROMPT\n// ──────────────────────────────────────────────────────────────\n\nconst systemPrompt = `\nYou are an expert Intent Evaluator for a social networking protocol.\n\nTASK:\nDetermine if a User Intent is appropriate for a specific Index (community) and matches a Member's sharing preferences.\n\nINPUTS:\n1. Intent: The content/action the user wants to perform.\n2. Index Prompt: The purpose/scope of the target community (Index).\n3. Member Prompt: The specific sharing preferences of the user in that community (optional).\n4. Source: Origin of the intent (file, link, etc.) (optional).\n5. Network Context: Rendered context about the network including type, dates, location, and events (optional).\n\nNETWORK TYPE AWARENESS:\n- When Network Context is provided, use it to inform your scoring.\n- For EVENT networks: consider temporal relevance. An intent about \"meeting at the venue\" is highly relevant to an upcoming event but irrelevant after it ends. Intents about topics aligned with the event's themes should score higher.\n- For COMMUNITY networks: score based on the index prompt and member preferences as usual.\n- If the network context includes dates and the intent is time-sensitive, factor temporal proximity into the score.\n\nSCORING RUBRIC:\n- 0.9-1.0: Highly appropriate, perfect match.\n- 0.7-0.8: Good match, relevant.\n- 0.5-0.6: Moderate, borderline.\n- 0.3-0.4: Low appropriateness, poor fit.\n- 0.0-0.2: Not appropriate.\n\nOUTPUT RULES:\n- Provide \\`indexScore\\` based on how well the Intent fits the Index Prompt.\n- Provide \\`memberScore\\` based on how well the Intent fits the Member Prompt (if provided). If Member Prompt is missing/empty, return 0.0 for memberScore.\n- Provide concise \\`reasoning\\`.\n`;\n\n// ──────────────────────────────────────────────────────────────\n// 2. RESPONSE SCHEMA (Zod)\n// ──────────────────────────────────────────────────────────────\n\nconst responseFormat = IntentIndexerOutputSchema;\n\n// ──────────────────────────────────────────────────────────────\n// 3. TYPE DEFINITIONS\n// ──────────────────────────────────────────────────────────────\n\ntype ResponseType = z.infer<typeof responseFormat>;\n\n// ──────────────────────────────────────────────────────────────\n// 4. CLASS DEFINITION\n// ──────────────────────────────────────────────────────────────\n\nexport class IntentIndexer {\n private model: ReturnType<ChatOpenAI[\"withStructuredOutput\"]>;\n\n constructor() {\n this.model = model.withStructuredOutput(responseFormat, {\n name: \"intent_indexer\",\n });\n }\n\n /**\n * Converts the structured response into a string for logging or embedding.\n * Used when the output needs to be serialized (e.g. for traces).\n */\n private toString(output: ResponseType): string {\n return [\n `indexScore: ${output.indexScore}`,\n `memberScore: ${output.memberScore}`,\n `reasoning: ${output.reasoning}`,\n ].join(\"\\n\");\n }\n\n /**\n * Main entry point. Evaluates the appropriateness of an intent for a given index and member context.\n *\n * @param intent - The intent payload.\n * @param indexPrompt - The purpose of the index (community).\n * @param memberPrompt - The member's sharing preferences (optional).\n * @param sourceName - Optional source name for context (e.g. file, link).\n * @param networkContext - Optional rendered network context (type, dates, metadata).\n * @returns Structured output with indexScore, memberScore, and reasoning, or null on error.\n */\n @Timed()\n public async invoke(\n intent: string,\n indexPrompt: string | null,\n memberPrompt: string | null,\n sourceName?: string | null,\n networkContext?: string | null\n ): Promise<IntentIndexerOutput | null> {\n logger.verbose(\"[IntentIndexer.invoke] Evaluating intent\");\n\n const contextParts: string[] = [];\n if (sourceName) contextParts.push(`Source: ${sourceName}`);\n contextParts.push(indexPrompt ? `Index Purpose: ${indexPrompt}` : \"Index Purpose: (Not provided)\");\n contextParts.push(memberPrompt ? `Member Preferences: ${memberPrompt}` : \"Member Preferences: (Not provided)\");\n if (networkContext) contextParts.push(`Network Context:\\n${networkContext}`);\n\n const prompt = `\n # Context\n ${contextParts.join(\"\\n\")}\n\n # Intent\n ${intent}\n\n Evaluate the appropriateness of this intent.\n `;\n\n const messages = [\n new SystemMessage(systemPrompt),\n new HumanMessage(prompt),\n ];\n\n try {\n const result = await invokeWithAbortSignal(this.model, messages);\n const output = responseFormat.parse(result) as IntentIndexerOutput;\n\n logger.verbose(\"[IntentIndexer.invoke] Evaluation complete\", {\n indexScore: output.indexScore,\n memberScore: output.memberScore,\n });\n return output;\n } catch (error) {\n logger.error(\"[IntentIndexer] Error during execution\", { error });\n return null;\n }\n }\n\n /**\n * Alias for invoke. Evaluates the appropriateness of an intent for a given index and member context.\n * Kept for compatibility with callers (e.g. Index Graph) that use evaluate().\n */\n @Timed()\n public async evaluate(\n intent: string,\n indexPrompt: string | null,\n memberPrompt: string | null,\n sourceName?: string | null,\n networkContext?: string | null\n ): Promise<IntentIndexerOutput | null> {\n return this.invoke(intent, indexPrompt, memberPrompt, sourceName, networkContext);\n }\n\n /**\n * Factory method to expose the agent as a LangChain tool.\n * Useful for composing agents into larger graphs.\n */\n public static asTool() {\n return tool(\n async (args: {\n intent: string;\n indexPrompt: string | null;\n memberPrompt: string | null;\n sourceName?: string | null;\n networkContext?: string | null;\n }) => {\n const agent = new IntentIndexer();\n return await agent.invoke(\n args.intent,\n args.indexPrompt,\n args.memberPrompt,\n args.sourceName,\n args.networkContext\n );\n },\n {\n name: \"intent_indexer\",\n description:\n \"Evaluates whether an intent is appropriate for a specific index (community or event) and matches member sharing preferences.\",\n schema: z.object({\n intent: z.string().describe(\"The intent payload to evaluate\"),\n indexPrompt: z.string().nullable().describe(\"The purpose of the index (community)\"),\n memberPrompt: z.string().nullable().describe(\"The member's sharing preferences\"),\n sourceName: z.string().nullable().optional().describe(\"Optional source name for context\"),\n networkContext: z.string().nullable().optional().describe(\"Optional rendered network context (type, dates, metadata)\"),\n }),\n }\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"intent.indexer.js","sourceRoot":"/","sources":["intent/intent.indexer.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,iEAAiE;AACjE,kBAAkB;AAClB,iEAAiE;AAEjE,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC,MAAM,CAAC;IAChD,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,2CAA2C,CAAC;IAC1F,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,6CAA6C,CAAC;IAC7F,SAAS,EA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G,IAAI,aAAa,EAAE,CAAC;YAClC,OAAO,MAAM,KAAK,CAAC,MAAM,CACvB,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,WAAW,EAChB,IAAI,CAAC,YAAY,EACjB,IAAI,CAAC,UAAU,EACf,IAAI,CAAC,cAAc,CACpB,CAAC;QACJ,CAAC,EACD;YACE,IAAI,EAAE,gBAAgB;YACtB,WAAW,EACT,8HAA8H;YAChI,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC;gBACf,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,gCAAgC,CAAC;gBAC7D,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,sCAAsC,CAAC;gBACnF,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,kCAAkC,CAAC;gBAChF,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,kCAAkC,CAAC;gBACzF,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,2DAA2D,CAAC;aACvH,CAAC;SACH,CACF,CAAC;IACJ,CAAC;CACF;AAhGc;IADZ,KAAK,EAAE;;;;2CA4CP;AAOY;IADZ,KAAK,EAAE;;;;6CASP","sourcesContent":["import type { ChatOpenAI } from \"@langchain/openai\";\nimport { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\nimport { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { log } from \"../shared/observability/log.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport { createModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\n// ──────────────────────────────────────────────────────────────\n// Response schema\n// ──────────────────────────────────────────────────────────────\n\nexport const IntentIndexerOutputSchema = z.object({\n indexScore: z.number().min(0).max(1).describe(\"Score for index appropriateness (0.0-1.0)\"),\n memberScore: z.number().min(0).max(1).describe(\"Score for member preference match (0.0-1.0)\"),\n reasoning: z.string().describe(\"Brief reasoning for the scores\"),\n});\n\n/**\n * Output structure for the Intent Indexer agent.\n */\nexport type IntentIndexerOutput = z.infer<typeof IntentIndexerOutputSchema>;\n\nconst logger = log.lib.from(\"IntentIndexer\");\n\nconst model = createModel(\"intentIndexer\");\n\n// ──────────────────────────────────────────────────────────────\n// 1. SYSTEM PROMPT\n// ──────────────────────────────────────────────────────────────\n\nconst systemPrompt = `\nYou are an expert Intent Evaluator for a social networking protocol.\n\nTASK:\nDetermine if a User Intent is appropriate for a specific Index (community) and matches a Member's sharing preferences.\n\nINPUTS:\n1. Intent: The content/action the user wants to perform.\n2. Network Prompt: The purpose/scope of the target community (Index).\n3. Member Prompt: The specific sharing preferences of the user in that community (optional).\n4. Source: Origin of the intent (file, link, etc.) (optional).\n5. Network Context: Rendered context about the network including type, dates, location, and events (optional).\n\nNETWORK TYPE AWARENESS:\n- When Network Context is provided, use it to inform your scoring.\n- For EVENT networks: consider temporal relevance. An intent about \"meeting at the venue\" is highly relevant to an upcoming event but irrelevant after it ends. Intents about topics aligned with the event's themes should score higher.\n- For COMMUNITY networks: score based on the network prompt and member preferences as usual.\n- If the network context includes dates and the intent is time-sensitive, factor temporal proximity into the score.\n\nSCORING RUBRIC:\n- 0.9-1.0: Highly appropriate, perfect match.\n- 0.7-0.8: Good match, relevant.\n- 0.5-0.6: Moderate, borderline.\n- 0.3-0.4: Low appropriateness, poor fit.\n- 0.0-0.2: Not appropriate.\n\nOUTPUT RULES:\n- Provide \\`indexScore\\` based on how well the Intent fits the Network Prompt.\n- Provide \\`memberScore\\` based on how well the Intent fits the Member Prompt (if provided). If Member Prompt is missing/empty, return 0.0 for memberScore.\n- Provide concise \\`reasoning\\`.\n`;\n\n// ──────────────────────────────────────────────────────────────\n// 2. RESPONSE SCHEMA (Zod)\n// ──────────────────────────────────────────────────────────────\n\nconst responseFormat = IntentIndexerOutputSchema;\n\n// ──────────────────────────────────────────────────────────────\n// 3. TYPE DEFINITIONS\n// ──────────────────────────────────────────────────────────────\n\ntype ResponseType = z.infer<typeof responseFormat>;\n\n// ──────────────────────────────────────────────────────────────\n// 4. CLASS DEFINITION\n// ──────────────────────────────────────────────────────────────\n\nexport class IntentIndexer {\n private model: ReturnType<ChatOpenAI[\"withStructuredOutput\"]>;\n\n constructor() {\n this.model = model.withStructuredOutput(responseFormat, {\n name: \"intent_indexer\",\n });\n }\n\n /**\n * Converts the structured response into a string for logging or embedding.\n * Used when the output needs to be serialized (e.g. for traces).\n */\n private toString(output: ResponseType): string {\n return [\n `indexScore: ${output.indexScore}`,\n `memberScore: ${output.memberScore}`,\n `reasoning: ${output.reasoning}`,\n ].join(\"\\n\");\n }\n\n /**\n * Main entry point. Evaluates the appropriateness of an intent for a given index and member context.\n *\n * @param intent - The intent payload.\n * @param indexPrompt - The purpose of the index (community).\n * @param memberPrompt - The member's sharing preferences (optional).\n * @param sourceName - Optional source name for context (e.g. file, link).\n * @param networkContext - Optional rendered network context (type, dates, metadata).\n * @returns Structured output with indexScore, memberScore, and reasoning, or null on error.\n */\n @Timed()\n public async invoke(\n intent: string,\n indexPrompt: string | null,\n memberPrompt: string | null,\n sourceName?: string | null,\n networkContext?: string | null\n ): Promise<IntentIndexerOutput | null> {\n logger.verbose(\"[IntentIndexer.invoke] Evaluating intent\");\n\n const contextParts: string[] = [];\n if (sourceName) contextParts.push(`Source: ${sourceName}`);\n contextParts.push(indexPrompt ? `Index Purpose: ${indexPrompt}` : \"Index Purpose: (Not provided)\");\n contextParts.push(memberPrompt ? `Member Preferences: ${memberPrompt}` : \"Member Preferences: (Not provided)\");\n if (networkContext) contextParts.push(`Network Context:\\n${networkContext}`);\n\n const prompt = `\n # Context\n ${contextParts.join(\"\\n\")}\n\n # Intent\n ${intent}\n\n Evaluate the appropriateness of this intent.\n `;\n\n const messages = [\n new SystemMessage(systemPrompt),\n new HumanMessage(prompt),\n ];\n\n try {\n const result = await invokeWithAbortSignal(this.model, messages);\n const output = responseFormat.parse(result) as IntentIndexerOutput;\n\n logger.verbose(\"[IntentIndexer.invoke] Evaluation complete\", {\n indexScore: output.indexScore,\n memberScore: output.memberScore,\n });\n return output;\n } catch (error) {\n logger.error(\"[IntentIndexer] Error during execution\", { error });\n return null;\n }\n }\n\n /**\n * Alias for invoke. Evaluates the appropriateness of an intent for a given index and member context.\n * Kept for compatibility with callers (e.g. Network Graph) that use evaluate().\n */\n @Timed()\n public async evaluate(\n intent: string,\n indexPrompt: string | null,\n memberPrompt: string | null,\n sourceName?: string | null,\n networkContext?: string | null\n ): Promise<IntentIndexerOutput | null> {\n return this.invoke(intent, indexPrompt, memberPrompt, sourceName, networkContext);\n }\n\n /**\n * Factory method to expose the agent as a LangChain tool.\n * Useful for composing agents into larger graphs.\n */\n public static asTool() {\n return tool(\n async (args: {\n intent: string;\n indexPrompt: string | null;\n memberPrompt: string | null;\n sourceName?: string | null;\n networkContext?: string | null;\n }) => {\n const agent = new IntentIndexer();\n return await agent.invoke(\n args.intent,\n args.indexPrompt,\n args.memberPrompt,\n args.sourceName,\n args.networkContext\n );\n },\n {\n name: \"intent_indexer\",\n description:\n \"Evaluates whether an intent is appropriate for a specific index (community or event) and matches member sharing preferences.\",\n schema: z.object({\n intent: z.string().describe(\"The intent payload to evaluate\"),\n indexPrompt: z.string().nullable().describe(\"The purpose of the index (community)\"),\n memberPrompt: z.string().nullable().describe(\"The member's sharing preferences\"),\n sourceName: z.string().nullable().optional().describe(\"Optional source name for context\"),\n networkContext: z.string().nullable().optional().describe(\"Optional rendered network context (type, dates, metadata)\"),\n }),\n }\n );\n }\n}\n"]}
|