@indexnetwork/protocol 3.6.3-rc.271.1 → 3.6.3-rc.272.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.
Files changed (76) hide show
  1. package/dist/agent/tests/fakes.d.ts.map +1 -1
  2. package/dist/agent/tests/fakes.js.map +1 -1
  3. package/dist/chat/chat.agent.d.ts.map +1 -1
  4. package/dist/chat/chat.agent.js +3 -3
  5. package/dist/chat/chat.agent.js.map +1 -1
  6. package/dist/chat/chat.streamer.d.ts.map +1 -1
  7. package/dist/chat/chat.streamer.js +1 -1
  8. package/dist/chat/chat.streamer.js.map +1 -1
  9. package/dist/chat/chat.summarizer.d.ts.map +1 -1
  10. package/dist/chat/chat.summarizer.js +1 -1
  11. package/dist/chat/chat.summarizer.js.map +1 -1
  12. package/dist/chat/tests/chat.graph.mocks.d.ts.map +1 -1
  13. package/dist/chat/tests/chat.graph.mocks.js +0 -1
  14. package/dist/chat/tests/chat.graph.mocks.js.map +1 -1
  15. package/dist/index.d.ts +21 -21
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +10 -10
  18. package/dist/index.js.map +1 -1
  19. package/dist/intent/intent.graph.js +1 -1
  20. package/dist/intent/intent.graph.js.map +1 -1
  21. package/dist/maintenance/maintenance.graph.d.ts.map +1 -1
  22. package/dist/maintenance/maintenance.graph.js +1 -1
  23. package/dist/maintenance/maintenance.graph.js.map +1 -1
  24. package/dist/negotiation/negotiation.agent.d.ts.map +1 -1
  25. package/dist/negotiation/negotiation.agent.js +1 -1
  26. package/dist/negotiation/negotiation.agent.js.map +1 -1
  27. package/dist/negotiation/negotiation.summarizer.d.ts.map +1 -1
  28. package/dist/negotiation/negotiation.summarizer.js +1 -1
  29. package/dist/negotiation/negotiation.summarizer.js.map +1 -1
  30. package/dist/network/indexer/indexer.graph.d.ts.map +1 -1
  31. package/dist/network/indexer/indexer.graph.js +2 -2
  32. package/dist/network/indexer/indexer.graph.js.map +1 -1
  33. package/dist/opportunity/discovery-question.helper.d.ts.map +1 -1
  34. package/dist/opportunity/discovery-question.helper.js.map +1 -1
  35. package/dist/opportunity/feed/feed.graph.d.ts.map +1 -1
  36. package/dist/opportunity/feed/feed.graph.js +1 -1
  37. package/dist/opportunity/feed/feed.graph.js.map +1 -1
  38. package/dist/opportunity/negotiation-summary.builder.d.ts.map +1 -1
  39. package/dist/opportunity/negotiation-summary.builder.js.map +1 -1
  40. package/dist/opportunity/opportunity.discover.d.ts.map +1 -1
  41. package/dist/opportunity/opportunity.discover.js +1 -1
  42. package/dist/opportunity/opportunity.discover.js.map +1 -1
  43. package/dist/opportunity/opportunity.enricher.d.ts.map +1 -1
  44. package/dist/opportunity/opportunity.enricher.js.map +1 -1
  45. package/dist/opportunity/opportunity.graph.d.ts.map +1 -1
  46. package/dist/opportunity/opportunity.graph.js +5 -5
  47. package/dist/opportunity/opportunity.graph.js.map +1 -1
  48. package/dist/opportunity/opportunity.persist.d.ts.map +1 -1
  49. package/dist/opportunity/opportunity.persist.js.map +1 -1
  50. package/dist/opportunity/question.generator.d.ts.map +1 -1
  51. package/dist/opportunity/question.generator.js +2 -2
  52. package/dist/opportunity/question.generator.js.map +1 -1
  53. package/dist/premise/premise.graph.d.ts.map +1 -1
  54. package/dist/premise/premise.graph.js +1 -1
  55. package/dist/premise/premise.graph.js.map +1 -1
  56. package/dist/profile/profile.graph.js +1 -1
  57. package/dist/profile/profile.graph.js.map +1 -1
  58. package/dist/questioner/questioner.agent.d.ts.map +1 -1
  59. package/dist/questioner/questioner.agent.js +1 -1
  60. package/dist/questioner/questioner.agent.js.map +1 -1
  61. package/dist/questioner/questioner.presets.d.ts.map +1 -1
  62. package/dist/questioner/questioner.presets.js +1 -1
  63. package/dist/questioner/questioner.presets.js.map +1 -1
  64. package/dist/shared/agent/response.streamer.d.ts.map +1 -1
  65. package/dist/shared/agent/response.streamer.js +1 -1
  66. package/dist/shared/agent/response.streamer.js.map +1 -1
  67. package/dist/shared/agent/tool.factory.d.ts.map +1 -1
  68. package/dist/shared/agent/tool.factory.js +1 -1
  69. package/dist/shared/agent/tool.factory.js.map +1 -1
  70. package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
  71. package/dist/shared/agent/tool.helpers.js.map +1 -1
  72. package/dist/shared/assignment/network-assignment.policy.d.ts.map +1 -1
  73. package/dist/shared/assignment/network-assignment.policy.js.map +1 -1
  74. package/dist/shared/interfaces/questioner.interface.d.ts.map +1 -1
  75. package/dist/shared/interfaces/questioner.interface.js.map +1 -1
  76. package/package.json +1 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":"AAAA,iFAAiF;AAEjF,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAW9D,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAC5F,OAAO,EAAE,cAAc,EAAE,MAAM,2CAA2C,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AACzE,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EACjB,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AAmBxC,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAyBrG,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAE1E,iFAAiF;AAEjF,OAAO,EACL,uBAAuB,GAExB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,sBAAsB,EACtB,0BAA0B,EAC1B,+BAA+B,EAC/B,kBAAkB,EAClB,uBAAuB,EACvB,mBAAmB,EACnB,oBAAoB,GAWrB,MAAM,qCAAqC,CAAC;AAG7C,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,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GAClB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAEtE,OAAO,EACL,0BAA0B,EAC1B,4BAA4B,EAC5B,sBAAsB,EACtB,sBAAsB,EACtB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,yCAAyC,CAAC;AAMjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAE/E,OAAO,EAAE,UAAU,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAC;AAChG,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,GAGxB,MAAM,sCAAsC,CAAC;AAE9C,iFAAiF;AAEjF,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,oCAAoC,CAAC;AAC5E,OAAO,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AAE5E,iFAAiF;AAEjF,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAE7H,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AACrF,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAavE,iFAAiF;AAEjF,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC","sourcesContent":["// ─── Public API (recommended for external consumers) ──────────────────────────\n\nexport { createChatTools } from \"./shared/agent/tool.factory.js\";\nexport { getModelName } from \"./shared/agent/model.config.js\";\nexport type { ChatTools } from \"./shared/agent/tool.factory.js\";\nexport type { ModelConfig, ModelSettings } from \"./shared/agent/model.config.js\";\nexport type {\n ToolContext,\n ResolvedToolContext,\n ToolDeps,\n ProtocolDeps,\n RawToolDefinition,\n CompiledGraph,\n} from \"./shared/agent/tool.helpers.js\";\nexport { ChatContextAccessError, resolveChatContext } from \"./shared/agent/tool.helpers.js\";\nexport { requestContext } from \"./shared/observability/request-context.js\";\nexport { setTimingWrapper } from \"./shared/observability/performance.js\";\nexport {\n ToolRuntimeError,\n getToolTimeoutPolicy,\n invokeToolRuntime,\n toolRuntimeErrorToResult,\n} from \"./shared/agent/tool.runtime.js\";\nexport type { ToolRuntimeErrorCode, ToolTimeoutClass, ToolTimeoutPolicy } from \"./shared/agent/tool.runtime.js\";\n\n// ─── Interfaces (implement these to wire up your infrastructure) ───────────────\n\nexport type * from \"./shared/interfaces/auth.interface.js\";\nexport type * from \"./shared/interfaces/cache.interface.js\";\nexport type * from \"./shared/interfaces/chat-session.interface.js\";\nexport type { ChatSummaryReader } from \"./shared/interfaces/chat-summary.interface.js\";\nexport type { ChatMessageWriter } from \"./shared/interfaces/chat-message-writer.interface.js\";\nexport type { QuestionGeneratorReader } from \"./shared/interfaces/question-generator.interface.js\";\nexport type {\n QuestionerDatabase,\n PersistableQuestion,\n PersistedQuestion,\n QuestionFilters,\n} from \"./shared/interfaces/questioner.interface.js\";\nexport type { NegotiationSummaryReader } from \"./shared/interfaces/negotiation-summary.interface.js\";\nexport type { DiscoveryNegotiationDigest } from \"./shared/schemas/negotiation-digest.schema.js\";\nexport { NegotiationSummarizer, buildFallbackDigest } from \"./negotiation/negotiation.summarizer.js\";\nexport type * from \"./shared/interfaces/contact.interface.js\";\nexport type * from \"./shared/interfaces/database.interface.js\";\nexport type * from \"./shared/interfaces/embedder.interface.js\";\nexport type * from \"./shared/interfaces/enrichment.interface.js\";\nexport type * from \"./shared/interfaces/integration.interface.js\";\nexport type * from \"./shared/interfaces/queue.interface.js\";\nexport type * from \"./shared/interfaces/scraper.interface.js\";\nexport type * from \"./shared/interfaces/storage.interface.js\";\nexport type * from \"./shared/interfaces/delivery-ledger.interface.js\";\nexport type * from \"./shared/interfaces/connect-link.interface.js\";\nexport type * from \"./shared/interfaces/discovery-run.interface.js\";\nexport type * from \"./shared/interfaces/profile-run.interface.js\";\nexport type * from \"./shared/interfaces/negotiation-events.interface.js\";\nexport type { AgentDispatcher, AgentDispatchResult, NegotiationTurnPayload } from \"./shared/interfaces/agent-dispatcher.interface.js\";\nexport type {\n AgentRecord,\n AgentTransportRecord,\n AgentPermissionRecord,\n AgentWithRelations,\n CreateAgentInput,\n CreateTransportInput,\n GrantPermissionInput,\n AgentDatabase,\n} from './shared/interfaces/agent.interface.js';\nexport { SYSTEM_AGENT_IDS } from './shared/interfaces/agent.interface.js';\n\n// ─── Shared schemas ───────────────────────────────────────────────────────────\n\nexport {\n ChatContextDigestSchema,\n type ChatContextDigest,\n} from \"./shared/schemas/chat-context.schema.js\";\nexport {\n QuestionOptionSchema,\n QuestionSchema,\n QuestionStrategySchema,\n QuestionWithStrategySchema,\n QuestionGeneratorResponseSchema,\n QuestionModeSchema,\n QuestionDetectionSchema,\n QuestionActorSchema,\n QuestionAnswerSchema,\n type Question,\n type QuestionOption,\n type QuestionStrategy,\n type QuestionWithStrategy,\n type QuestionGeneratorResponse,\n type QuestionGenerationResult,\n type QuestionMode,\n type QuestionDetection,\n type QuestionActor,\n type QuestionAnswer,\n} from \"./shared/schemas/question.schema.js\";\nexport type { PendingQuestionSummary } from \"./shared/schemas/pending-question.schema.js\";\nexport type { McpAuthInput } from \"./shared/schemas/mcp-auth.schema.js\";\nexport {\n ProfileIdentitySchema,\n ProfileNarrativeSchema,\n ProfileAttributesSchema,\n ProfileDocumentSchema,\n type ProfileDocument,\n} from \"./shared/schemas/profile.schema.js\";\nexport type {\n DiscoverySourceProfile,\n DiscoverySummary,\n DiscoveryNegotiation,\n DiscoveryTurn,\n DiscoveryOutcome,\n DiscoveryQuestionInput,\n NegotiationRole,\n} from \"./shared/schemas/discovery-question.schema.js\";\nexport {\n NetworkAssignmentResourceTypeSchema,\n NetworkAssignmentModeSchema,\n NetworkAssignmentScopeSchema,\n NetworkAssignmentPromptPresenceSchema,\n NetworkAssignmentPolicySchema,\n NetworkAssignmentRawScoresSchema,\n NetworkAssignmentMetadataSchema,\n OpportunityEvidenceKindSchema,\n OpportunityEvidenceSchema,\n} from \"./shared/schemas/network-assignment.schema.js\";\nexport type {\n NetworkAssignmentResourceType,\n NetworkAssignmentMode,\n NetworkAssignmentScope,\n NetworkAssignmentPromptPresence,\n NetworkAssignmentPolicy,\n NetworkAssignmentRawScores,\n NetworkAssignmentMetadata,\n OpportunityEvidenceKind,\n OpportunityEvidence,\n} from \"./shared/schemas/network-assignment.schema.js\";\nexport {\n DEFAULT_NETWORK_ASSIGNMENT_THRESHOLD,\n classifyPromptPresence,\n resolveAssignmentNetworkScope,\n buildNetworkAssignmentDecision,\n combineAssignmentScores,\n} from \"./shared/assignment/network-assignment.policy.js\";\nexport type {\n PromptPresenceInput,\n ResolveAssignmentNetworkScopeArgs,\n BuildNetworkAssignmentDecisionArgs,\n NetworkAssignmentDecision,\n} from \"./shared/assignment/network-assignment.policy.js\";\nexport {\n buildCandidateEvidence,\n withCandidateEvidence,\n mergeOpportunityEvidence,\n withMatchedStrategies,\n renderOpportunityEvidenceForPrompt,\n} from \"./opportunity/opportunity.evidence.js\";\nexport type { EvidenceCandidateInput } from \"./opportunity/opportunity.evidence.js\";\n\n// ─── Graph factories ──────────────────────────────────────────────────────────\n\nexport { ChatGraphFactory } from \"./chat/chat.graph.js\";\nexport { HomeGraphFactory } from \"./opportunity/feed/feed.graph.js\";\nexport { HydeGraphFactory } from \"./shared/hyde/hyde.graph.js\";\nexport { NetworkGraphFactory } from \"./network/network.graph.js\";\nexport { NetworkMembershipGraphFactory } from \"./network/membership/membership.graph.js\";\nexport { IntentGraphFactory } from \"./intent/intent.graph.js\";\nexport { IntentNetworkGraphFactory } from \"./network/indexer/indexer.graph.js\";\nexport { MaintenanceGraphFactory } from \"./maintenance/maintenance.graph.js\";\nexport type {\n MaintenanceGraphDatabase,\n MaintenanceGraphCache,\n MaintenanceGraphQueue,\n} from \"./maintenance/maintenance.graph.js\";\nexport { NegotiationGraphFactory, createDefaultNegotiationGraph, negotiateCandidates } from \"./negotiation/negotiation.graph.js\";\nexport { OpportunityGraphFactory } from \"./opportunity/opportunity.graph.js\";\nexport { ProfileGraphFactory } from \"./profile/profile.graph.js\";\nexport { PremiseGraphFactory } from \"./premise/premise.graph.js\";\n\n// ─── Agents ───────────────────────────────────────────────────────────────────\n\nexport { UserContextGenerator } from \"./context/context.generator.js\";\nexport type { UserContextInput, IncrementalContextInput, UserContextResult } from \"./context/context.generator.js\";\nexport { ChatTitleGenerator } from \"./chat/chat.title.generator.js\";\nexport { ChatInterruptClassifier } from \"./chat/chat.interrupt.classifier.js\";\nexport type { ClassifyInterruptInput } from \"./chat/chat.interrupt.classifier.js\";\nexport { ChatSummarizer } from \"./chat/chat.summarizer.js\";\nexport type { ChatSummarizerInput, ChatSummarizerMessage } from \"./chat/chat.summarizer.js\";\nexport { HydeGenerator } from \"./shared/hyde/hyde.generator.js\";\nexport { SuggestionGenerator } from \"./chat/chat.suggester.js\";\nexport type { SuggestionGeneratorInput } from \"./chat/chat.suggester.js\";\nexport { generateInviteMessage } from \"./contact/contact.inviter.js\";\nexport type { InviteInput, InviteOutput } from \"./contact/contact.inviter.js\";\nexport { IntentIndexer } from \"./intent/intent.indexer.js\";\nexport type { IntentIndexerOutput } from \"./intent/intent.indexer.js\";\nexport { PremiseAnalyzer } from \"./premise/premise.analyzer.js\";\nexport type { PremiseAnalyzerOutput } from \"./premise/premise.analyzer.js\";\nexport { PremiseDecomposer } from \"./premise/premise.decomposer.js\";\nexport type { PremiseDecomposerOutput, DecomposedPremise } from \"./premise/premise.decomposer.js\";\nexport { PremiseIndexer } from \"./premise/premise.indexer.js\";\nexport type { PremiseIndexerOutput } from \"./premise/premise.indexer.js\";\nexport { LensInferrer } from \"./shared/hyde/lens.inferrer.js\";\nexport { NegotiationInsightsGenerator } from \"./negotiation/insight.generator.js\";\nexport type { NegotiationDigest } from \"./negotiation/insight.generator.js\";\nexport { IndexNegotiator } from \"./negotiation/negotiation.agent.js\";\nexport type { NegotiationAgentInput } from \"./negotiation/negotiation.agent.js\";\nexport { QuestionerAgent } from \"./questioner/questioner.agent.js\";\nexport type { QuestionerAgentConfig } from \"./questioner/questioner.agent.js\";\nexport type {\n QuestionerInput,\n QuestionerContext,\n QuestionerEnqueuePayload,\n QuestionerEnqueueFn,\n DiscoveryContext,\n IntentContext,\n ProfileContext,\n NegotiationContext,\n} from \"./questioner/questioner.types.js\";\nexport { getPreset } from \"./questioner/questioner.presets.js\";\nexport type { QuestionerPreset } from \"./questioner/questioner.presets.js\";\nexport { OpportunityEvaluator } from \"./opportunity/opportunity.evaluator.js\";\nexport type {\n EvaluatorInput,\n OpportunityEvaluatorOptionsConstructor,\n} from \"./opportunity/opportunity.evaluator.js\";\nexport { OpportunityPresenter, gatherPresenterContext } from \"./opportunity/opportunity.presenter.js\";\nexport { createOpportunityTools } from \"./opportunity/opportunity.tools.js\";\nexport { createProfileTools } from \"./profile/profile.tools.js\";\nexport type { PresenterDatabase } from \"./opportunity/opportunity.presenter.js\";\nexport { QuestionGenerator } from \"./opportunity/question.generator.js\";\n\n// ─── Support utilities ────────────────────────────────────────────────────────\n\nexport { renderNetworkContext } from './shared/network/metadata.renderer.js';\nexport {\n canUserSeeOpportunity,\n isActionableForViewer,\n validateOpportunityActors,\n classifyOpportunity,\n selectByComposition,\n selectDigestCandidates,\n DIGEST_REDELIVERY_COOLDOWN_DAYS,\n FEED_SOFT_TARGETS,\n} from \"./opportunity/opportunity.utils.js\";\nexport type { DigestDeliveredRow } from \"./opportunity/opportunity.utils.js\";\nexport { getPrimaryActionLabel } from \"./opportunity/opportunity.labels.js\";\nexport { computeFeedHealth } from \"./opportunity/feed/feed.health.js\";\nexport type { FeedHealthInput, FeedHealthResult } from \"./opportunity/feed/feed.health.js\";\nexport {\n selectContactsForDiscovery,\n shouldRunIntroducerDiscovery,\n runIntroducerDiscovery,\n MAX_CONTACTS_PER_CYCLE,\n MAX_CANDIDATES_PER_CONTACT,\n INTRODUCER_DISCOVERY_SOURCE,\n} from \"./opportunity/opportunity.introducer.js\";\nexport type {\n IntroducerDiscoveryDatabase,\n IntroducerDiscoveryQueue,\n ContactWithIntents,\n} from \"./opportunity/opportunity.introducer.js\";\nexport { persistOpportunities } from \"./opportunity/opportunity.persist.js\";\nexport { presentOpportunity } from \"./opportunity/opportunity.presentation.js\";\nexport type { UserInfo } from \"./opportunity/opportunity.presentation.js\";\nexport { stripUuids, stripIntroducerMentions } from \"./opportunity/opportunity.presentation.js\";\nexport {\n getOrCreateDeliveryCardBatch,\n DELIVERY_CARD_CACHE_TTL,\n type CachedDeliveryCard,\n type OpportunityWithContext,\n} from \"./opportunity/delivery-card.cache.js\";\n\n// ─── Tools ────────────────────────────────────────────────────────────────────\n\nexport { createToolRegistry } from \"./shared/agent/tool.registry.js\";\nexport { createAgentTools } from './agent/agent.tools.js';\nexport { AMBIENT_PARK_WINDOW_MS } from './negotiation/negotiation.tools.js';\nexport { normalizeTelegramHandle } from './shared/utils/telegram-handle.js';\n\n// ─── MCP ──────────────────────────────────────────────────────────────────────\n\nexport { createMcpServer, computeAgentIndexScope, buildMcpOnboardingMessage, ONBOARDING_ALLOWED } from \"./mcp/mcp.server.js\";\nexport type { ScopedDepsFactory } from \"./mcp/mcp.server.js\";\nexport { buildElicitationCreate, flattenChoice } from \"./mcp/elicitation.builder.js\";\nexport { dispatchElicitations } from \"./mcp/elicitation.dispatcher.js\";\nexport type { ElicitResultLike, ElicitInputFn, DispatchElicitationsParams } from \"./mcp/elicitation.dispatcher.js\";\n\n// ─── States (for advanced graph consumers) ────────────────────────────────────\n\nexport type {\n UserNegotiationContext,\n NegotiationTurn,\n NegotiationOutcome,\n SeedAssessment,\n} from \"./shared/schemas/negotiation-state.schema.js\";\nexport type { NegotiationGraphLike } from \"./negotiation/negotiation.state.js\";\n\n// ─── Streamers ────────────────────────────────────────────────────────────────\n\nexport { ChatStreamer } from \"./chat/chat.streamer.js\";\nexport { ResponseStreamer } from \"./shared/agent/response.streamer.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":"AAAA,iFAAiF;AAEjF,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAI9D,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAC5F,OAAO,EAAE,cAAc,EAAE,MAAM,2CAA2C,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAcrI,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAgBrG,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAE1E,iFAAiF;AAEjF,OAAO,EAAE,uBAAuB,EAA0B,MAAM,yCAAyC,CAAC;AAC1G,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,sBAAsB,EAAE,0BAA0B,EAAE,+BAA+B,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,oBAAoB,EAA2O,MAAM,qCAAqC,CAAC;AAGjf,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,qBAAqB,EAAwB,MAAM,oCAAoC,CAAC;AAEzK,OAAO,EAAE,mCAAmC,EAAE,2BAA2B,EAAE,4BAA4B,EAAE,qCAAqC,EAAE,6BAA6B,EAAE,gCAAgC,EAAE,+BAA+B,EAAE,6BAA6B,EAAE,yBAAyB,EAAE,MAAM,+CA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E,0BAA0B,EAAE,2BAA2B,EAAE,MAAM,yCAAyC,CAAC;AAE5N,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAE/E,OAAO,EAAE,UAAU,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAC;AAChG,OAAO,EAAE,4BAA4B,EAAE,uBAAuB,EAAwD,MAAM,sCAAsC,CAAC;AAEnK,iFAAiF;AAEjF,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,oCAAoC,CAAC;AAC5E,OAAO,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AAE5E,iFAAiF;AAEjF,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAE7H,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AACrF,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAQvE,iFAAiF;AAEjF,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC","sourcesContent":["// ─── Public API (recommended for external consumers) ──────────────────────────\n\nexport { createChatTools } from \"./shared/agent/tool.factory.js\";\nexport { getModelName } from \"./shared/agent/model.config.js\";\nexport type { ChatTools } from \"./shared/agent/tool.factory.js\";\nexport type { ModelConfig, ModelSettings } from \"./shared/agent/model.config.js\";\nexport type { ToolContext, ResolvedToolContext, ToolDeps, ProtocolDeps, RawToolDefinition, CompiledGraph } from \"./shared/agent/tool.helpers.js\";\nexport { ChatContextAccessError, resolveChatContext } from \"./shared/agent/tool.helpers.js\";\nexport { requestContext } from \"./shared/observability/request-context.js\";\nexport { setTimingWrapper } from \"./shared/observability/performance.js\";\nexport { ToolRuntimeError, getToolTimeoutPolicy, invokeToolRuntime, toolRuntimeErrorToResult } from \"./shared/agent/tool.runtime.js\";\nexport type { ToolRuntimeErrorCode, ToolTimeoutClass, ToolTimeoutPolicy } from \"./shared/agent/tool.runtime.js\";\n\n// ─── Interfaces (implement these to wire up your infrastructure) ───────────────\n\nexport type * from \"./shared/interfaces/auth.interface.js\";\nexport type * from \"./shared/interfaces/cache.interface.js\";\nexport type * from \"./shared/interfaces/chat-session.interface.js\";\nexport type { ChatSummaryReader } from \"./shared/interfaces/chat-summary.interface.js\";\nexport type { ChatMessageWriter } from \"./shared/interfaces/chat-message-writer.interface.js\";\nexport type { QuestionGeneratorReader } from \"./shared/interfaces/question-generator.interface.js\";\nexport type { QuestionerDatabase, PersistableQuestion, PersistedQuestion, QuestionFilters } from \"./shared/interfaces/questioner.interface.js\";\nexport type { NegotiationSummaryReader } from \"./shared/interfaces/negotiation-summary.interface.js\";\nexport type { DiscoveryNegotiationDigest } from \"./shared/schemas/negotiation-digest.schema.js\";\nexport { NegotiationSummarizer, buildFallbackDigest } from \"./negotiation/negotiation.summarizer.js\";\nexport type * from \"./shared/interfaces/contact.interface.js\";\nexport type * from \"./shared/interfaces/database.interface.js\";\nexport type * from \"./shared/interfaces/embedder.interface.js\";\nexport type * from \"./shared/interfaces/enrichment.interface.js\";\nexport type * from \"./shared/interfaces/integration.interface.js\";\nexport type * from \"./shared/interfaces/queue.interface.js\";\nexport type * from \"./shared/interfaces/scraper.interface.js\";\nexport type * from \"./shared/interfaces/storage.interface.js\";\nexport type * from \"./shared/interfaces/delivery-ledger.interface.js\";\nexport type * from \"./shared/interfaces/connect-link.interface.js\";\nexport type * from \"./shared/interfaces/discovery-run.interface.js\";\nexport type * from \"./shared/interfaces/profile-run.interface.js\";\nexport type * from \"./shared/interfaces/negotiation-events.interface.js\";\nexport type { AgentDispatcher, AgentDispatchResult, NegotiationTurnPayload } from \"./shared/interfaces/agent-dispatcher.interface.js\";\nexport type { AgentRecord, AgentTransportRecord, AgentPermissionRecord, AgentWithRelations, CreateAgentInput, CreateTransportInput, GrantPermissionInput, AgentDatabase } from './shared/interfaces/agent.interface.js';\nexport { SYSTEM_AGENT_IDS } from './shared/interfaces/agent.interface.js';\n\n// ─── Shared schemas ───────────────────────────────────────────────────────────\n\nexport { ChatContextDigestSchema, type ChatContextDigest } from \"./shared/schemas/chat-context.schema.js\";\nexport { QuestionOptionSchema, QuestionSchema, QuestionStrategySchema, QuestionWithStrategySchema, QuestionGeneratorResponseSchema, QuestionModeSchema, QuestionDetectionSchema, QuestionActorSchema, QuestionAnswerSchema, type Question, type QuestionOption, type QuestionStrategy, type QuestionWithStrategy, type QuestionGeneratorResponse, type QuestionGenerationResult, type QuestionMode, type QuestionDetection, type QuestionActor, type QuestionAnswer } from \"./shared/schemas/question.schema.js\";\nexport type { PendingQuestionSummary } from \"./shared/schemas/pending-question.schema.js\";\nexport type { McpAuthInput } from \"./shared/schemas/mcp-auth.schema.js\";\nexport { ProfileIdentitySchema, ProfileNarrativeSchema, ProfileAttributesSchema, ProfileDocumentSchema, type ProfileDocument } from \"./shared/schemas/profile.schema.js\";\nexport type { DiscoverySourceProfile, DiscoverySummary, DiscoveryNegotiation, DiscoveryTurn, DiscoveryOutcome, DiscoveryQuestionInput, NegotiationRole } from \"./shared/schemas/discovery-question.schema.js\";\nexport { NetworkAssignmentResourceTypeSchema, NetworkAssignmentModeSchema, NetworkAssignmentScopeSchema, NetworkAssignmentPromptPresenceSchema, NetworkAssignmentPolicySchema, NetworkAssignmentRawScoresSchema, NetworkAssignmentMetadataSchema, OpportunityEvidenceKindSchema, OpportunityEvidenceSchema } from \"./shared/schemas/network-assignment.schema.js\";\nexport type { NetworkAssignmentResourceType, NetworkAssignmentMode, NetworkAssignmentScope, NetworkAssignmentPromptPresence, NetworkAssignmentPolicy, NetworkAssignmentRawScores, NetworkAssignmentMetadata, OpportunityEvidenceKind, OpportunityEvidence } from \"./shared/schemas/network-assignment.schema.js\";\nexport { DEFAULT_NETWORK_ASSIGNMENT_THRESHOLD, classifyPromptPresence, resolveAssignmentNetworkScope, buildNetworkAssignmentDecision, combineAssignmentScores } from \"./shared/assignment/network-assignment.policy.js\";\nexport type { PromptPresenceInput, ResolveAssignmentNetworkScopeArgs, BuildNetworkAssignmentDecisionArgs, NetworkAssignmentDecision } from \"./shared/assignment/network-assignment.policy.js\";\nexport { buildCandidateEvidence, withCandidateEvidence, mergeOpportunityEvidence, withMatchedStrategies, renderOpportunityEvidenceForPrompt } from \"./opportunity/opportunity.evidence.js\";\nexport type { EvidenceCandidateInput } from \"./opportunity/opportunity.evidence.js\";\n\n// ─── Graph factories ──────────────────────────────────────────────────────────\n\nexport { ChatGraphFactory } from \"./chat/chat.graph.js\";\nexport { HomeGraphFactory } from \"./opportunity/feed/feed.graph.js\";\nexport { HydeGraphFactory } from \"./shared/hyde/hyde.graph.js\";\nexport { NetworkGraphFactory } from \"./network/network.graph.js\";\nexport { NetworkMembershipGraphFactory } from \"./network/membership/membership.graph.js\";\nexport { IntentGraphFactory } from \"./intent/intent.graph.js\";\nexport { IntentNetworkGraphFactory } from \"./network/indexer/indexer.graph.js\";\nexport { MaintenanceGraphFactory } from \"./maintenance/maintenance.graph.js\";\nexport type { MaintenanceGraphDatabase, MaintenanceGraphCache, MaintenanceGraphQueue } from \"./maintenance/maintenance.graph.js\";\nexport { NegotiationGraphFactory, createDefaultNegotiationGraph, negotiateCandidates } from \"./negotiation/negotiation.graph.js\";\nexport { OpportunityGraphFactory } from \"./opportunity/opportunity.graph.js\";\nexport { ProfileGraphFactory } from \"./profile/profile.graph.js\";\nexport { PremiseGraphFactory } from \"./premise/premise.graph.js\";\n\n// ─── Agents ───────────────────────────────────────────────────────────────────\n\nexport { UserContextGenerator } from \"./context/context.generator.js\";\nexport type { UserContextInput, IncrementalContextInput, UserContextResult } from \"./context/context.generator.js\";\nexport { ChatTitleGenerator } from \"./chat/chat.title.generator.js\";\nexport { ChatInterruptClassifier } from \"./chat/chat.interrupt.classifier.js\";\nexport type { ClassifyInterruptInput } from \"./chat/chat.interrupt.classifier.js\";\nexport { ChatSummarizer } from \"./chat/chat.summarizer.js\";\nexport type { ChatSummarizerInput, ChatSummarizerMessage } from \"./chat/chat.summarizer.js\";\nexport { HydeGenerator } from \"./shared/hyde/hyde.generator.js\";\nexport { SuggestionGenerator } from \"./chat/chat.suggester.js\";\nexport type { SuggestionGeneratorInput } from \"./chat/chat.suggester.js\";\nexport { generateInviteMessage } from \"./contact/contact.inviter.js\";\nexport type { InviteInput, InviteOutput } from \"./contact/contact.inviter.js\";\nexport { IntentIndexer } from \"./intent/intent.indexer.js\";\nexport type { IntentIndexerOutput } from \"./intent/intent.indexer.js\";\nexport { PremiseAnalyzer } from \"./premise/premise.analyzer.js\";\nexport type { PremiseAnalyzerOutput } from \"./premise/premise.analyzer.js\";\nexport { PremiseDecomposer } from \"./premise/premise.decomposer.js\";\nexport type { PremiseDecomposerOutput, DecomposedPremise } from \"./premise/premise.decomposer.js\";\nexport { PremiseIndexer } from \"./premise/premise.indexer.js\";\nexport type { PremiseIndexerOutput } from \"./premise/premise.indexer.js\";\nexport { LensInferrer } from \"./shared/hyde/lens.inferrer.js\";\nexport { NegotiationInsightsGenerator } from \"./negotiation/insight.generator.js\";\nexport type { NegotiationDigest } from \"./negotiation/insight.generator.js\";\nexport { IndexNegotiator } from \"./negotiation/negotiation.agent.js\";\nexport type { NegotiationAgentInput } from \"./negotiation/negotiation.agent.js\";\nexport { QuestionerAgent } from \"./questioner/questioner.agent.js\";\nexport type { QuestionerAgentConfig } from \"./questioner/questioner.agent.js\";\nexport type { QuestionerInput, QuestionerContext, QuestionerEnqueuePayload, QuestionerEnqueueFn, DiscoveryContext, IntentContext, ProfileContext, NegotiationContext } from \"./questioner/questioner.types.js\";\nexport { getPreset } from \"./questioner/questioner.presets.js\";\nexport type { QuestionerPreset } from \"./questioner/questioner.presets.js\";\nexport { OpportunityEvaluator } from \"./opportunity/opportunity.evaluator.js\";\nexport type { EvaluatorInput, OpportunityEvaluatorOptionsConstructor } from \"./opportunity/opportunity.evaluator.js\";\nexport { OpportunityPresenter, gatherPresenterContext } from \"./opportunity/opportunity.presenter.js\";\nexport { createOpportunityTools } from \"./opportunity/opportunity.tools.js\";\nexport { createProfileTools } from \"./profile/profile.tools.js\";\nexport type { PresenterDatabase } from \"./opportunity/opportunity.presenter.js\";\nexport { QuestionGenerator } from \"./opportunity/question.generator.js\";\n\n// ─── Support utilities ────────────────────────────────────────────────────────\n\nexport { renderNetworkContext } from './shared/network/metadata.renderer.js';\nexport { canUserSeeOpportunity, isActionableForViewer, validateOpportunityActors, classifyOpportunity, selectByComposition, selectDigestCandidates, DIGEST_REDELIVERY_COOLDOWN_DAYS, FEED_SOFT_TARGETS } from \"./opportunity/opportunity.utils.js\";\nexport type { DigestDeliveredRow } from \"./opportunity/opportunity.utils.js\";\nexport { getPrimaryActionLabel } from \"./opportunity/opportunity.labels.js\";\nexport { computeFeedHealth } from \"./opportunity/feed/feed.health.js\";\nexport type { FeedHealthInput, FeedHealthResult } from \"./opportunity/feed/feed.health.js\";\nexport { selectContactsForDiscovery, shouldRunIntroducerDiscovery, runIntroducerDiscovery, MAX_CONTACTS_PER_CYCLE, MAX_CANDIDATES_PER_CONTACT, INTRODUCER_DISCOVERY_SOURCE } from \"./opportunity/opportunity.introducer.js\";\nexport type { IntroducerDiscoveryDatabase, IntroducerDiscoveryQueue, ContactWithIntents } from \"./opportunity/opportunity.introducer.js\";\nexport { persistOpportunities } from \"./opportunity/opportunity.persist.js\";\nexport { presentOpportunity } from \"./opportunity/opportunity.presentation.js\";\nexport type { UserInfo } from \"./opportunity/opportunity.presentation.js\";\nexport { stripUuids, stripIntroducerMentions } from \"./opportunity/opportunity.presentation.js\";\nexport { getOrCreateDeliveryCardBatch, DELIVERY_CARD_CACHE_TTL, type CachedDeliveryCard, type OpportunityWithContext } from \"./opportunity/delivery-card.cache.js\";\n\n// ─── Tools ────────────────────────────────────────────────────────────────────\n\nexport { createToolRegistry } from \"./shared/agent/tool.registry.js\";\nexport { createAgentTools } from './agent/agent.tools.js';\nexport { AMBIENT_PARK_WINDOW_MS } from './negotiation/negotiation.tools.js';\nexport { normalizeTelegramHandle } from './shared/utils/telegram-handle.js';\n\n// ─── MCP ──────────────────────────────────────────────────────────────────────\n\nexport { createMcpServer, computeAgentIndexScope, buildMcpOnboardingMessage, ONBOARDING_ALLOWED } from \"./mcp/mcp.server.js\";\nexport type { ScopedDepsFactory } from \"./mcp/mcp.server.js\";\nexport { buildElicitationCreate, flattenChoice } from \"./mcp/elicitation.builder.js\";\nexport { dispatchElicitations } from \"./mcp/elicitation.dispatcher.js\";\nexport type { ElicitResultLike, ElicitInputFn, DispatchElicitationsParams } from \"./mcp/elicitation.dispatcher.js\";\n\n// ─── States (for advanced graph consumers) ────────────────────────────────────\n\nexport type { UserNegotiationContext, NegotiationTurn, NegotiationOutcome, SeedAssessment } from \"./shared/schemas/negotiation-state.schema.js\";\nexport type { NegotiationGraphLike } from \"./negotiation/negotiation.state.js\";\n\n// ─── Streamers ────────────────────────────────────────────────────────────────\n\nexport { ChatStreamer } from \"./chat/chat.streamer.js\";\nexport { ResponseStreamer } from \"./shared/agent/response.streamer.js\";\n"]}
@@ -433,7 +433,7 @@ export class IntentGraphFactory {
433
433
  const sanitizePayload = (payload) => {
434
434
  if (!payload || typeof payload !== "string")
435
435
  return payload;
436
- let out = payload
436
+ const out = payload
437
437
  .replace(/\s*More details at\s*:?\s*https?:\/\/[^\s"'<>)\]]+/gi, "")
438
438
  .replace(/\s*See\s+https?:\/\/[^\s"'<>)\]]+\s+for\s+more[^.]*\.?/gi, "")
439
439
  .replace(/https?:\/\/[^\s"'<>)\]]+/g, "")
@@ -1 +1 @@
1
- {"version":3,"file":"intent.graph.js","sourceRoot":"/","sources":["intent/intent.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAA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C;YAElC,cAAc;YACd,0DAA0D;YAC1D,2EAA2E;YAC3E,uGAAuG;YACvG,uFAAuF;YACvF,+FAA+F;aAC9F,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC;YAEvB,8DAA8D;aAC7D,mBAAmB,CAAC,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\ntype ParsedProfile = {\n identity?: { bio?: string; name?: string; location?: string };\n narrative?: { context?: string };\n attributes?: { skills?: string[]; interests?: string[] };\n};\n\nconst parseProfile = (profile: string): ParsedProfile | null => {\n if (!profile || !profile.trim()) return null;\n try {\n const parsed = JSON.parse(profile) as ParsedProfile;\n return parsed && typeof parsed === \"object\" ? parsed : null;\n } catch {\n return null;\n }\n};\n\nconst inferRoleFromProfileText = (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\nconst buildJobQualifierFromProfile = (profile: ParsedProfile | null): string | null => {\n if (!profile) return null;\n\n const skills = (profile.attributes?.skills ?? [])\n .filter((skill): skill is string => typeof skill === \"string\" && skill.trim().length > 0)\n .slice(0, 2);\n const interests = (profile.attributes?.interests ?? [])\n .filter((interest): interest is string => typeof interest === \"string\" && interest.trim().length > 0)\n .slice(0, 1);\n\n const profileText = [\n profile.identity?.bio,\n profile.narrative?.context,\n ]\n .filter((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n .join(\" \");\n const roleHint = inferRoleFromProfileText(profileText);\n\n if (skills.length > 0 && roleHint) {\n return `${skills.join(\" / \")} ${roleHint} role`;\n }\n if (skills.length > 0) {\n return `${skills.join(\" / \")} role`;\n }\n if (interests.length > 0 && roleHint) {\n return `${interests[0]} ${roleHint} role`;\n }\n if (roleHint) {\n return `${roleHint} role`;\n }\n return null;\n};\n\nconst enrichVagueIntentWithProfile = (description: string, profileContext: 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 profile = parseProfile(profileContext);\n const qualifier = buildJobQualifierFromProfile(profile);\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 const enrichedDescription = enrichVagueIntentWithProfile(description, state.userProfile);\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 let 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 * 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 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 let flatEmbedding: number[] | undefined;\n if (this.embedder) {\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for new intent\", { dimensions: flatEmbedding?.length });\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent (continuing without)\", { error: embErr });\n }\n }\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 ...(state.networkId ? { networkScopeId: state.networkId } : {}),\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 parsed = parseProfile(state.userProfile);\n this.questionerEnqueue({\n mode: 'intent',\n userId: state.userId,\n sourceType: 'intent',\n sourceId: created.id,\n context: {\n intentId: created.id,\n payload: sanitizedPayload,\n userProfile: {\n name: parsed?.identity?.name,\n bio: parsed?.identity?.bio,\n skills: parsed?.attributes?.skills,\n interests: parsed?.attributes?.interests,\n },\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 let flatEmbedding: number[] | undefined;\n if (this.embedder) {\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for updated intent\", { intentId: updateAction.id, dimensions: flatEmbedding?.length });\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent update (continuing without)\", { error: embErr });\n }\n }\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 ...(state.networkId ? { networkScopeId: state.networkId } : {}),\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,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;AAQvD,MAAM,YAAY,GAAG,CAAC,OAAe,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,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\ntype ParsedProfile = {\n identity?: { bio?: string; name?: string; location?: string };\n narrative?: { context?: string };\n attributes?: { skills?: string[]; interests?: string[] };\n};\n\nconst parseProfile = (profile: string): ParsedProfile | null => {\n if (!profile || !profile.trim()) return null;\n try {\n const parsed = JSON.parse(profile) as ParsedProfile;\n return parsed && typeof parsed === \"object\" ? parsed : null;\n } catch {\n return null;\n }\n};\n\nconst inferRoleFromProfileText = (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\nconst buildJobQualifierFromProfile = (profile: ParsedProfile | null): string | null => {\n if (!profile) return null;\n\n const skills = (profile.attributes?.skills ?? [])\n .filter((skill): skill is string => typeof skill === \"string\" && skill.trim().length > 0)\n .slice(0, 2);\n const interests = (profile.attributes?.interests ?? [])\n .filter((interest): interest is string => typeof interest === \"string\" && interest.trim().length > 0)\n .slice(0, 1);\n\n const profileText = [\n profile.identity?.bio,\n profile.narrative?.context,\n ]\n .filter((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n .join(\" \");\n const roleHint = inferRoleFromProfileText(profileText);\n\n if (skills.length > 0 && roleHint) {\n return `${skills.join(\" / \")} ${roleHint} role`;\n }\n if (skills.length > 0) {\n return `${skills.join(\" / \")} role`;\n }\n if (interests.length > 0 && roleHint) {\n return `${interests[0]} ${roleHint} role`;\n }\n if (roleHint) {\n return `${roleHint} role`;\n }\n return null;\n};\n\nconst enrichVagueIntentWithProfile = (description: string, profileContext: 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 profile = parseProfile(profileContext);\n const qualifier = buildJobQualifierFromProfile(profile);\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 const enrichedDescription = enrichVagueIntentWithProfile(description, state.userProfile);\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 * 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 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 let flatEmbedding: number[] | undefined;\n if (this.embedder) {\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for new intent\", { dimensions: flatEmbedding?.length });\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent (continuing without)\", { error: embErr });\n }\n }\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 ...(state.networkId ? { networkScopeId: state.networkId } : {}),\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 parsed = parseProfile(state.userProfile);\n this.questionerEnqueue({\n mode: 'intent',\n userId: state.userId,\n sourceType: 'intent',\n sourceId: created.id,\n context: {\n intentId: created.id,\n payload: sanitizedPayload,\n userProfile: {\n name: parsed?.identity?.name,\n bio: parsed?.identity?.bio,\n skills: parsed?.attributes?.skills,\n interests: parsed?.attributes?.interests,\n },\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 let flatEmbedding: number[] | undefined;\n if (this.embedder) {\n try {\n const embedding = await this.embedder.generate(sanitizedPayload, undefined, getAbortSignalConfig());\n flatEmbedding = Array.isArray(embedding?.[0])\n ? (embedding as number[][])[0]\n : (embedding as number[]);\n logger.verbose(\"Generated embedding for updated intent\", { intentId: updateAction.id, dimensions: flatEmbedding?.length });\n } catch (embErr) {\n logger.error(\"Failed to generate embedding for intent update (continuing without)\", { error: embErr });\n }\n }\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 ...(state.networkId ? { networkScopeId: state.networkId } : {}),\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 +1 @@
1
- {"version":3,"file":"maintenance.graph.d.ts","sourceRoot":"/","sources":["maintenance/maintenance.graph.ts"],"names":[],"mappings":"AAyBA,wFAAwF;AACxF,MAAM,WAAW,wBAAwB;IACvC,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,KAAK,CA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6KZ"}
@@ -10,7 +10,7 @@ import { StateGraph, START, END } from '@langchain/langgraph';
10
10
  import { MaintenanceGraphState } from './maintenance.state.js';
11
11
  import { computeFeedHealth } from '../opportunity/feed/feed.health.js';
12
12
  import { canUserSeeOpportunity, classifyOpportunity, isActionableForViewer, FEED_SOFT_TARGETS } from '../opportunity/opportunity.utils.js';
13
- import { shouldRunIntroducerDiscovery, runIntroducerDiscovery, } from '../opportunity/opportunity.introducer.js';
13
+ import { shouldRunIntroducerDiscovery, runIntroducerDiscovery } from '../opportunity/opportunity.introducer.js';
14
14
  import { protocolLogger } from '../shared/observability/protocol.logger.js';
15
15
  const logger = protocolLogger('MaintenanceGraph');
16
16
  const FRESHNESS_WINDOW_MS = 12 * 60 * 60 * 1000; // 12 hours
@@ -1 +1 @@
1
- {"version":3,"file":"maintenance.graph.js","sourceRoot":"/","sources":["maintenance/maintenance.graph.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAC3I,OAAO,EACL,4BAA4B,EAC5B,sBAAsB,GAGvB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD,MAAM,mBAAmB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAA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CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["/**\n * Maintenance Graph: evaluate feed health and trigger rediscovery when unhealthy.\n * Also runs introducer discovery when connector-flow slots are underfilled.\n *\n * Write path — separate from the read-only HomeGraph.\n * Flow: loadCurrentFeed → scoreFeedHealth → [shouldRediscover] → rediscover → introducerDiscovery → logMaintenance → END\n * └─ [skip rediscovery] ─────────────→ introducerDiscovery → logMaintenance → END\n */\nimport { StateGraph, START, END } from '@langchain/langgraph';\n\nimport { MaintenanceGraphState } from './maintenance.state.js';\nimport { computeFeedHealth } from '../opportunity/feed/feed.health.js';\nimport { canUserSeeOpportunity, classifyOpportunity, isActionableForViewer, FEED_SOFT_TARGETS } from '../opportunity/opportunity.utils.js';\nimport {\n shouldRunIntroducerDiscovery,\n runIntroducerDiscovery,\n type IntroducerDiscoveryDatabase,\n type IntroducerDiscoveryQueue,\n} from '../opportunity/opportunity.introducer.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('MaintenanceGraph');\n\nconst FRESHNESS_WINDOW_MS = 12 * 60 * 60 * 1000; // 12 hours\n\n/** Database methods needed by the maintenance graph (includes introducer discovery). */\nexport interface MaintenanceGraphDatabase {\n getOpportunitiesForUser(userId: string, options?: { limit?: number }): Promise<Array<{ id: string; actors: Array<{ userId: string; role: string }>; status: string; [key: string]: unknown }>>;\n getActiveIntents(userId: string): Promise<Array<{ id: string; payload: string }>>;\n /** Get the user's personal index ID (for introducer discovery). */\n getPersonalIndexId(userId: string): Promise<string | null>;\n /** Get contacts with intent freshness data from a personal index (for introducer discovery). */\n getContactsWithIntentFreshness(\n personalIndexId: string,\n ownerId: string,\n limit: number,\n ): Promise<Array<{ userId: string; latestIntentAt: string | null; intentCount: number }>>;\n}\n\n/** Cache methods needed by the maintenance graph. */\nexport interface MaintenanceGraphCache {\n get<T = unknown>(key: string): Promise<T | null>;\n set(key: string, value: unknown, options?: { ttl?: number }): Promise<void>;\n}\n\n/** Queue methods needed by the maintenance graph. */\nexport interface MaintenanceGraphQueue {\n addJob(data: { intentId: string; userId: string; indexIds?: string[]; contactUserId?: string }, options?: { priority?: number; jobId?: string }): Promise<unknown>;\n}\n\n/**\n * Factory for the Maintenance Graph.\n * Accepts database, cache, and queue dependencies via constructor injection.\n */\nexport class MaintenanceGraphFactory {\n constructor(\n private database: MaintenanceGraphDatabase,\n private cache: MaintenanceGraphCache,\n private queue: MaintenanceGraphQueue,\n ) {}\n\n /** Compile and return the maintenance graph. */\n createGraph() {\n const loadCurrentFeedNode = async (state: typeof MaintenanceGraphState.State) => {\n if (!state.userId) {\n return { error: 'userId is required' };\n }\n try {\n const raw = await this.database.getOpportunitiesForUser(state.userId, { limit: 150 });\n const actionable = raw.filter((opp) =>\n isActionableForViewer(opp.actors, opp.status, state.userId)\n );\n const expired = raw.filter((opp) =>\n opp.status === 'expired' && canUserSeeOpportunity(opp.actors, opp.status, state.userId)\n );\n const activeIntents = await this.database.getActiveIntents(state.userId);\n\n // Read last rediscovery timestamp from cache\n let lastRediscoveryAt: number | null = null;\n try {\n const cached = await this.cache.get<{ triggeredAt: string }>(`rediscovery:lastRun:${state.userId}`);\n if (typeof cached?.triggeredAt === 'string') {\n const parsed = Date.parse(cached.triggeredAt);\n if (Number.isFinite(parsed)) {\n lastRediscoveryAt = parsed;\n }\n }\n } catch {\n // Cache unavailable — treat as no data\n }\n\n return {\n currentOpportunities: actionable,\n expiredCount: expired.length,\n activeIntents: activeIntents ?? [],\n lastRediscoveryAt,\n };\n } catch (e) {\n logger.error('MaintenanceGraph loadCurrentFeed failed', { error: e });\n return { error: 'Failed to load current feed' };\n }\n };\n\n const scoreFeedHealthNode = async (state: typeof MaintenanceGraphState.State) => {\n if (state.error) return {};\n try {\n const opps = state.currentOpportunities ?? [];\n let connectionCount = 0;\n let connectorFlowCount = 0;\n\n for (const opp of opps) {\n const category = classifyOpportunity(opp, state.userId);\n if (category === 'connection') connectionCount++;\n else if (category === 'connector-flow') connectorFlowCount++;\n }\n\n const healthResult = computeFeedHealth({\n connectionCount,\n connectorFlowCount,\n expiredCount: state.expiredCount,\n totalActionable: opps.length,\n lastRediscoveryAt: state.lastRediscoveryAt,\n freshnessWindowMs: FRESHNESS_WINDOW_MS,\n });\n\n logger.verbose(`[MaintenanceGraph] Feed health scored — userId=${state.userId} score=${healthResult.score} shouldMaintain=${healthResult.shouldMaintain} connectorFlowCount=${connectorFlowCount}`);\n\n return { healthResult, connectorFlowCount };\n } catch (e) {\n logger.error('MaintenanceGraph scoreFeedHealth failed', { error: e });\n return { error: 'Failed to score feed health' };\n }\n };\n\n const shouldRediscover = (state: typeof MaintenanceGraphState.State): string => {\n if (state.error) return 'introducerDiscovery';\n if (state.healthResult?.shouldMaintain && state.activeIntents.length > 0) {\n return 'rediscover';\n }\n return 'introducerDiscovery';\n };\n\n const rediscoverNode = async (state: typeof MaintenanceGraphState.State) => {\n try {\n const bucket = Math.floor(Date.now() / (6 * 60 * 60 * 1000));\n let enqueued = 0;\n\n const results = await Promise.allSettled(\n state.activeIntents.map((intent) =>\n this.queue.addJob(\n { intentId: intent.id, userId: state.userId },\n { priority: 10, jobId: `rediscovery-${state.userId}-${intent.id}-${bucket}` },\n )\n )\n );\n\n for (const r of results) {\n if (r.status === 'rejected') {\n const errMsg = r.reason instanceof Error ? r.reason.message : String(r.reason);\n logger.error(`[MaintenanceGraph] Rediscovery job enqueue failed: ${errMsg}`);\n }\n }\n enqueued = results.filter((r) => r.status === 'fulfilled').length;\n\n // Record last run timestamp\n if (enqueued > 0) {\n try {\n await this.cache.set(\n `rediscovery:lastRun:${state.userId}`,\n { triggeredAt: new Date().toISOString() },\n { ttl: 24 * 60 * 60 },\n );\n } catch {\n // Cache write failure is non-fatal\n }\n }\n\n return { rediscoveryJobsEnqueued: enqueued };\n } catch (e) {\n logger.error('MaintenanceGraph rediscover failed', { error: e });\n return { error: 'Failed to enqueue rediscovery jobs' };\n }\n };\n\n const introducerDiscoveryNode = async (state: typeof MaintenanceGraphState.State) => {\n try {\n const connectorFlowTarget = FEED_SOFT_TARGETS.connectorFlow;\n if (!shouldRunIntroducerDiscovery(state.connectorFlowCount, connectorFlowTarget)) {\n logger.verbose(`[MaintenanceGraph] Introducer discovery skipped — connector-flow target met — userId=${state.userId} connectorFlowCount=${state.connectorFlowCount} connectorFlowTarget=${connectorFlowTarget}`);\n return {};\n }\n\n // Cast database/queue to introducer discovery interfaces (they are compatible)\n const result = await runIntroducerDiscovery(\n this.database as IntroducerDiscoveryDatabase,\n this.queue as IntroducerDiscoveryQueue,\n state.userId,\n );\n\n logger.info(`[MaintenanceGraph] Introducer discovery complete — userId=${state.userId} contactsEvaluated=${result.contactsEvaluated} jobsEnqueued=${result.jobsEnqueued}${result.skippedReason ? ` skippedReason=${result.skippedReason}` : ''}`);\n\n return { introducerDiscoveryJobsEnqueued: result.jobsEnqueued };\n } catch (e) {\n logger.error('MaintenanceGraph introducerDiscovery failed', { error: e });\n // Non-fatal: do not set error, just log and continue\n return {};\n }\n };\n\n const logMaintenanceNode = async (state: typeof MaintenanceGraphState.State) => {\n logger.info(`[MaintenanceGraph] Maintenance complete — userId=${state.userId} score=${state.healthResult?.score} shouldMaintain=${state.healthResult?.shouldMaintain} rediscoveryJobs=${state.rediscoveryJobsEnqueued} introducerDiscoveryJobs=${state.introducerDiscoveryJobsEnqueued} activeIntents=${state.activeIntents.length} connectorFlowCount=${state.connectorFlowCount}`);\n return {};\n };\n\n const graph = new StateGraph(MaintenanceGraphState)\n .addNode('loadCurrentFeed', loadCurrentFeedNode)\n .addNode('scoreFeedHealth', scoreFeedHealthNode)\n .addNode('rediscover', rediscoverNode)\n .addNode('introducerDiscovery', introducerDiscoveryNode)\n .addNode('logMaintenance', logMaintenanceNode)\n .addEdge(START, 'loadCurrentFeed')\n .addConditionalEdges('loadCurrentFeed', (state) => (state.error ? 'end' : 'scoreFeedHealth'), {\n scoreFeedHealth: 'scoreFeedHealth',\n end: END,\n })\n .addConditionalEdges('scoreFeedHealth', shouldRediscover, {\n rediscover: 'rediscover',\n introducerDiscovery: 'introducerDiscovery',\n })\n .addEdge('rediscover', 'introducerDiscovery')\n .addEdge('introducerDiscovery', 'logMaintenance')\n .addEdge('logMaintenance', END);\n\n return graph.compile();\n }\n}\n"]}
1
+ {"version":3,"file":"maintenance.graph.js","sourceRoot":"/","sources":["maintenance/maintenance.graph.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAC3I,OAAO,EAAE,4BAA4B,EAAE,sBAAsB,EAAmE,MAAM,0CAA0C,CAAC;AACjL,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD,MAAM,mBAAmB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,WAAW;AA2B5D;;;GAGG;AACH,MAAM,OAAO,uBAAuB;IAClC,YACU,QAAkC,EAClC,KAA4B,EAC5B,KAA4B;QAF5B,aAAQ,GAAR,QAAQ,CAA0B;QAClC,UAAK,GAAL,KAAK,CAAuB;QAC5B,UAAK,GAAL,KAAK,CAAuB;IACnC,CAAC;IAEJ,gDAAgD;IAChD,WAAW;QACT,MAAM,mBAAmB,GAAG,KAAK,EAAE,KAAyC,EAAE,EAAE;YAC9E,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;gBAClB,OAAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC;YACzC,CAAC;YACD,IAAI,CAAC;gBACH,MAAM,G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BAAqB,CAAC;aAChD,OAAO,CAAC,iBAAiB,EAAE,mBAAmB,CAAC;aAC/C,OAAO,CAAC,iBAAiB,EAAE,mBAAmB,CAAC;aAC/C,OAAO,CAAC,YAAY,EAAE,cAAc,CAAC;aACrC,OAAO,CAAC,qBAAqB,EAAE,uBAAuB,CAAC;aACvD,OAAO,CAAC,gBAAgB,EAAE,kBAAkB,CAAC;aAC7C,OAAO,CAAC,KAAK,EAAE,iBAAiB,CAAC;aACjC,mBAAmB,CAAC,iBAAiB,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,iBAAiB,CAAC,EAAE;YAC5F,eAAe,EAAE,iBAAiB;YAClC,GAAG,EAAE,GAAG;SACT,CAAC;aACD,mBAAmB,CAAC,iBAAiB,EAAE,gBAAgB,EAAE;YACxD,UAAU,EAAE,YAAY;YACxB,mBAAmB,EAAE,qBAAqB;SAC3C,CAAC;aACD,OAAO,CAAC,YAAY,EAAE,qBAAqB,CAAC;aAC5C,OAAO,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;aAChD,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;QAElC,OAAO,KAAK,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["/**\n * Maintenance Graph: evaluate feed health and trigger rediscovery when unhealthy.\n * Also runs introducer discovery when connector-flow slots are underfilled.\n *\n * Write path — separate from the read-only HomeGraph.\n * Flow: loadCurrentFeed → scoreFeedHealth → [shouldRediscover] → rediscover → introducerDiscovery → logMaintenance → END\n * └─ [skip rediscovery] ─────────────→ introducerDiscovery → logMaintenance → END\n */\nimport { StateGraph, START, END } from '@langchain/langgraph';\n\nimport { MaintenanceGraphState } from './maintenance.state.js';\nimport { computeFeedHealth } from '../opportunity/feed/feed.health.js';\nimport { canUserSeeOpportunity, classifyOpportunity, isActionableForViewer, FEED_SOFT_TARGETS } from '../opportunity/opportunity.utils.js';\nimport { shouldRunIntroducerDiscovery, runIntroducerDiscovery, type IntroducerDiscoveryDatabase, type IntroducerDiscoveryQueue } from '../opportunity/opportunity.introducer.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('MaintenanceGraph');\n\nconst FRESHNESS_WINDOW_MS = 12 * 60 * 60 * 1000; // 12 hours\n\n/** Database methods needed by the maintenance graph (includes introducer discovery). */\nexport interface MaintenanceGraphDatabase {\n getOpportunitiesForUser(userId: string, options?: { limit?: number }): Promise<Array<{ id: string; actors: Array<{ userId: string; role: string }>; status: string; [key: string]: unknown }>>;\n getActiveIntents(userId: string): Promise<Array<{ id: string; payload: string }>>;\n /** Get the user's personal index ID (for introducer discovery). */\n getPersonalIndexId(userId: string): Promise<string | null>;\n /** Get contacts with intent freshness data from a personal index (for introducer discovery). */\n getContactsWithIntentFreshness(\n personalIndexId: string,\n ownerId: string,\n limit: number,\n ): Promise<Array<{ userId: string; latestIntentAt: string | null; intentCount: number }>>;\n}\n\n/** Cache methods needed by the maintenance graph. */\nexport interface MaintenanceGraphCache {\n get<T = unknown>(key: string): Promise<T | null>;\n set(key: string, value: unknown, options?: { ttl?: number }): Promise<void>;\n}\n\n/** Queue methods needed by the maintenance graph. */\nexport interface MaintenanceGraphQueue {\n addJob(data: { intentId: string; userId: string; indexIds?: string[]; contactUserId?: string }, options?: { priority?: number; jobId?: string }): Promise<unknown>;\n}\n\n/**\n * Factory for the Maintenance Graph.\n * Accepts database, cache, and queue dependencies via constructor injection.\n */\nexport class MaintenanceGraphFactory {\n constructor(\n private database: MaintenanceGraphDatabase,\n private cache: MaintenanceGraphCache,\n private queue: MaintenanceGraphQueue,\n ) {}\n\n /** Compile and return the maintenance graph. */\n createGraph() {\n const loadCurrentFeedNode = async (state: typeof MaintenanceGraphState.State) => {\n if (!state.userId) {\n return { error: 'userId is required' };\n }\n try {\n const raw = await this.database.getOpportunitiesForUser(state.userId, { limit: 150 });\n const actionable = raw.filter((opp) =>\n isActionableForViewer(opp.actors, opp.status, state.userId)\n );\n const expired = raw.filter((opp) =>\n opp.status === 'expired' && canUserSeeOpportunity(opp.actors, opp.status, state.userId)\n );\n const activeIntents = await this.database.getActiveIntents(state.userId);\n\n // Read last rediscovery timestamp from cache\n let lastRediscoveryAt: number | null = null;\n try {\n const cached = await this.cache.get<{ triggeredAt: string }>(`rediscovery:lastRun:${state.userId}`);\n if (typeof cached?.triggeredAt === 'string') {\n const parsed = Date.parse(cached.triggeredAt);\n if (Number.isFinite(parsed)) {\n lastRediscoveryAt = parsed;\n }\n }\n } catch {\n // Cache unavailable — treat as no data\n }\n\n return {\n currentOpportunities: actionable,\n expiredCount: expired.length,\n activeIntents: activeIntents ?? [],\n lastRediscoveryAt,\n };\n } catch (e) {\n logger.error('MaintenanceGraph loadCurrentFeed failed', { error: e });\n return { error: 'Failed to load current feed' };\n }\n };\n\n const scoreFeedHealthNode = async (state: typeof MaintenanceGraphState.State) => {\n if (state.error) return {};\n try {\n const opps = state.currentOpportunities ?? [];\n let connectionCount = 0;\n let connectorFlowCount = 0;\n\n for (const opp of opps) {\n const category = classifyOpportunity(opp, state.userId);\n if (category === 'connection') connectionCount++;\n else if (category === 'connector-flow') connectorFlowCount++;\n }\n\n const healthResult = computeFeedHealth({\n connectionCount,\n connectorFlowCount,\n expiredCount: state.expiredCount,\n totalActionable: opps.length,\n lastRediscoveryAt: state.lastRediscoveryAt,\n freshnessWindowMs: FRESHNESS_WINDOW_MS,\n });\n\n logger.verbose(`[MaintenanceGraph] Feed health scored — userId=${state.userId} score=${healthResult.score} shouldMaintain=${healthResult.shouldMaintain} connectorFlowCount=${connectorFlowCount}`);\n\n return { healthResult, connectorFlowCount };\n } catch (e) {\n logger.error('MaintenanceGraph scoreFeedHealth failed', { error: e });\n return { error: 'Failed to score feed health' };\n }\n };\n\n const shouldRediscover = (state: typeof MaintenanceGraphState.State): string => {\n if (state.error) return 'introducerDiscovery';\n if (state.healthResult?.shouldMaintain && state.activeIntents.length > 0) {\n return 'rediscover';\n }\n return 'introducerDiscovery';\n };\n\n const rediscoverNode = async (state: typeof MaintenanceGraphState.State) => {\n try {\n const bucket = Math.floor(Date.now() / (6 * 60 * 60 * 1000));\n let enqueued = 0;\n\n const results = await Promise.allSettled(\n state.activeIntents.map((intent) =>\n this.queue.addJob(\n { intentId: intent.id, userId: state.userId },\n { priority: 10, jobId: `rediscovery-${state.userId}-${intent.id}-${bucket}` },\n )\n )\n );\n\n for (const r of results) {\n if (r.status === 'rejected') {\n const errMsg = r.reason instanceof Error ? r.reason.message : String(r.reason);\n logger.error(`[MaintenanceGraph] Rediscovery job enqueue failed: ${errMsg}`);\n }\n }\n enqueued = results.filter((r) => r.status === 'fulfilled').length;\n\n // Record last run timestamp\n if (enqueued > 0) {\n try {\n await this.cache.set(\n `rediscovery:lastRun:${state.userId}`,\n { triggeredAt: new Date().toISOString() },\n { ttl: 24 * 60 * 60 },\n );\n } catch {\n // Cache write failure is non-fatal\n }\n }\n\n return { rediscoveryJobsEnqueued: enqueued };\n } catch (e) {\n logger.error('MaintenanceGraph rediscover failed', { error: e });\n return { error: 'Failed to enqueue rediscovery jobs' };\n }\n };\n\n const introducerDiscoveryNode = async (state: typeof MaintenanceGraphState.State) => {\n try {\n const connectorFlowTarget = FEED_SOFT_TARGETS.connectorFlow;\n if (!shouldRunIntroducerDiscovery(state.connectorFlowCount, connectorFlowTarget)) {\n logger.verbose(`[MaintenanceGraph] Introducer discovery skipped — connector-flow target met — userId=${state.userId} connectorFlowCount=${state.connectorFlowCount} connectorFlowTarget=${connectorFlowTarget}`);\n return {};\n }\n\n // Cast database/queue to introducer discovery interfaces (they are compatible)\n const result = await runIntroducerDiscovery(\n this.database as IntroducerDiscoveryDatabase,\n this.queue as IntroducerDiscoveryQueue,\n state.userId,\n );\n\n logger.info(`[MaintenanceGraph] Introducer discovery complete — userId=${state.userId} contactsEvaluated=${result.contactsEvaluated} jobsEnqueued=${result.jobsEnqueued}${result.skippedReason ? ` skippedReason=${result.skippedReason}` : ''}`);\n\n return { introducerDiscoveryJobsEnqueued: result.jobsEnqueued };\n } catch (e) {\n logger.error('MaintenanceGraph introducerDiscovery failed', { error: e });\n // Non-fatal: do not set error, just log and continue\n return {};\n }\n };\n\n const logMaintenanceNode = async (state: typeof MaintenanceGraphState.State) => {\n logger.info(`[MaintenanceGraph] Maintenance complete — userId=${state.userId} score=${state.healthResult?.score} shouldMaintain=${state.healthResult?.shouldMaintain} rediscoveryJobs=${state.rediscoveryJobsEnqueued} introducerDiscoveryJobs=${state.introducerDiscoveryJobsEnqueued} activeIntents=${state.activeIntents.length} connectorFlowCount=${state.connectorFlowCount}`);\n return {};\n };\n\n const graph = new StateGraph(MaintenanceGraphState)\n .addNode('loadCurrentFeed', loadCurrentFeedNode)\n .addNode('scoreFeedHealth', scoreFeedHealthNode)\n .addNode('rediscover', rediscoverNode)\n .addNode('introducerDiscovery', introducerDiscoveryNode)\n .addNode('logMaintenance', logMaintenanceNode)\n .addEdge(START, 'loadCurrentFeed')\n .addConditionalEdges('loadCurrentFeed', (state) => (state.error ? 'end' : 'scoreFeedHealth'), {\n scoreFeedHealth: 'scoreFeedHealth',\n end: END,\n })\n .addConditionalEdges('scoreFeedHealth', shouldRediscover, {\n rediscover: 'rediscover',\n introducerDiscovery: 'introducerDiscovery',\n })\n .addEdge('rediscover', 'introducerDiscovery')\n .addEdge('introducerDiscovery', 'logMaintenance')\n .addEdge('logMaintenance', END);\n\n return graph.compile();\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"negotiation.agent.d.ts","sourceRoot":"/","sources":["negotiation/negotiation.agent.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,KAAK,cAAc,EACpB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AAsBxF,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,sB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AAO,EAAE,eAAe,EAAE,CAAC;IAC3B,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,sFAAsF;IACtF,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,2GAA2G;IAC3G,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,8FAA8F;IAC9F,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,6EAA6E;IAC7E,WAAW,CAAC,EAAE,qBAAqB,EAAE,CAAC;CACvC;AAED,MAAM,WAAW,qBAAqB;IACpC;;;;;;;;;;OAUG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AA0BD;;;;GAIG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;gBAE3B,MAAM,CAAC,EAAE,qBAAqB;IAI1C;;;;;OAKG;IACG,MAAM,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAAC,eAAe,CAAC;CA+FrE"}
@@ -1,6 +1,6 @@
1
1
  import { createModel } from "../shared/agent/model.config.js";
2
2
  import { invokeWithAbortSignal } from "../shared/agent/model-signal.js";
3
- import { SystemNegotiationTurnSchema, FinalNegotiationTurnSchema, } from "./negotiation.state.js";
3
+ import { SystemNegotiationTurnSchema, FinalNegotiationTurnSchema } from "./negotiation.state.js";
4
4
  const SYSTEM_PROMPT = `You are the Index Negotiator, an AI agent acting on behalf of {userName}. You represent their interests in a bilateral negotiation about a potential connection on a discovery network.
5
5
 
6
6
  {discoveryContext}