@apotech-os/support-kit 8.2.0 → 8.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -321,6 +321,8 @@ interface AgentProfile {
321
321
  sentTag: string;
322
322
  needsHumanTag: string;
323
323
  followupTag: string;
324
+ /** This app's ownership mark on every ticket its triage sees — empty stamps nothing. */
325
+ appScopeTag: string;
324
326
  };
325
327
  autoSend: {
326
328
  enabled: boolean;
@@ -594,6 +596,11 @@ interface AuditTags {
594
596
  sentTag: string;
595
597
  needsHumanTag: string;
596
598
  followupTag: string;
599
+ /**
600
+ * The app's ownership mark, applied to every ticket its triage sees rather
601
+ * than to an outcome — empty when unconfigured, which stamps nothing.
602
+ */
603
+ appScopeTag: string;
597
604
  }
598
605
  interface StatePort {
599
606
  /** Materialises the triage decision (ex `ClassificationSink.record`). */
@@ -1461,7 +1468,7 @@ declare function isAutoSendEligible(state: TicketRunState, deps: Pick<NodeDeps,
1461
1468
  declare function needsRevision(verdict: Verdict | null, profile: AgentProfile, reviseCount: number): boolean;
1462
1469
 
1463
1470
  /** The `generated-response` record's `status` field (§3.4). */
1464
- declare const GENERATED_RESPONSE_STATUSES: readonly ["pending", "ready", "sending", "sent", "failed", "no_reply_needed", "invalidated", "expired", "test_draft"];
1471
+ declare const GENERATED_RESPONSE_STATUSES: readonly ["pending", "ready", "sending", "sent", "failed", "no_reply_needed", "invalidated", "expired", "test_draft", "superseded"];
1465
1472
  type GeneratedResponseStatus = (typeof GENERATED_RESPONSE_STATUSES)[number];
1466
1473
  /**
1467
1474
  * `status` lives in `AppRecord` JSONB (§3.4), so it reaches this module as an
@@ -1907,6 +1914,27 @@ interface SettingsValidationIssue {
1907
1914
  */
1908
1915
  declare function validateSettings(settings: Record<string, unknown>): SettingsValidationIssue[];
1909
1916
 
1917
+ /**
1918
+ * `settingsWarnings` — the settings problems that must NOT stop the app.
1919
+ *
1920
+ * Deliberately separate from `validateSettings`: nine handlers refuse to run
1921
+ * as soon as that function reports a single issue, so routing a "this looks
1922
+ * wrong" remark through it would take a working app off the air. Everything
1923
+ * here describes a configuration that runs, and runs in a way its operator
1924
+ * probably did not intend.
1925
+ *
1926
+ * Its only consumer is the SettingsPage, which is why these messages are
1927
+ * written in French straight away — unlike `validateSettings`' own, they are
1928
+ * never logged, never returned by a handler, and so need no translation layer.
1929
+ */
1930
+ type SettingsWarningKey = 'appScopeTagVetoesFollowups' | 'appScopeTagCollision' | 'scopeTagMismatch';
1931
+ interface SettingsWarning {
1932
+ key: SettingsWarningKey;
1933
+ /** Operator-facing French, safe to show as-is. */
1934
+ message: string;
1935
+ }
1936
+ declare function settingsWarnings(settings: Record<string, unknown>): SettingsWarning[];
1937
+
1910
1938
  /**
1911
1939
  * `settings` (§3.6) → `AgentProfile` (architecture_agent_graphe.md §5.3).
1912
1940
  *
@@ -2016,6 +2044,8 @@ interface SupportKitSettings {
2016
2044
  followupTag: string;
2017
2045
  /** D2 — the tag scoping which tickets the follow-up webhook may answer. Empty = inert (see `settings/fields.ts`). */
2018
2046
  webhookScopeTag: string;
2047
+ /** The tag this app stamps on every ticket its triage sees. Empty = stamps nothing (see `settings/fields.ts`). */
2048
+ appScopeTag: string;
2019
2049
  autoSendEnabled: boolean;
2020
2050
  senderEmail: string;
2021
2051
  requireHighTriageConfidence: boolean;
@@ -2177,4 +2207,4 @@ interface SupportPipelineFragments {
2177
2207
  }
2178
2208
  declare function buildSupportPipeline(config: SupportPipelineConfig): SupportPipelineFragments;
2179
2209
 
2180
- export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, ATTACHMENT_MARKER_ONLY, type ActionDecision, type AgentProfile, type AgentStatus, type AuditTags, type AutoReplyGuardSettings, type Budget, CANDIDATE_MIN_LENGTH, type CatalogueTool, type CategoryPolicy, type CategoryReferentialEntry, type ChannelKind, type ChatMessage, type Classification, type ClockPort, type CompletionRequest, type CompletionResult, type Conversation, type ConversationPort, type ConversationRef, type CostLedger, type CustomerInfo, DECISION_ORIGINS, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, DEFAULT_DECISION_ORIGIN, DEFAULT_LLM_PROVIDER, DEFAULT_PROFILE_KEY, DEFAULT_WHATSAPP_MODE, type DecisionOrigin, type Draft, type DraftAttribution, type DraftNodeConfig, EVALUATION_VERDICTS, type EscalateNodeConfig, type EvaluateNodeConfig, type EvaluationVerdict, GENERATED_RESPONSE_STATUSES, type GeneratedResponseStatus, type GuardrailId, InvalidStatusTransitionError, type JsonSchema, type JudgedReply, type KnowledgeHit, type LlmPort, type Message, MissingPromptError, NODE_NAMES, type Node, type NodeCost, type NodeDeps, type NodeKey, type NodeName, type NodeStep, ORIGIN_DESCRIPTION, OUTCOMES, type OrderSummary, type OutboundReply, type Outcome, PROMPT_SLOTS, type PlatformPromptReader, type PortName, type PromptCacheEntry, type PromptCachePort, type PromptDegradedEvent, type PromptNameConfig, type PromptPort, type PromptRef, type PromptReference, type PromptResolverDeps, type PromptSlot, type PromptTableKey, type ProposedAction, REASONING_MAX_LEN, type RawPrompt, type RawPromptConfig, type RawTicket, type ReasoningEffort, type RecordDef, type ReplyPort, type ResolvedPrompt, type ResumeFrom, type ReviseNodeConfig, type RunGuardrailsInput, type RunStamp, type RunTicketOptions, type RunUntil, STOP_PHRASES, SUPPORT_KIT_SETTINGS_FIELDS, type SettingsIssueKey, type SettingsValidationIssue, type SimilarTicket, type SourceDescriptor, type StatePort, type SupportKitNodeSettings, type SupportKitSettings, type SupportPipelineConfig, type SupportPipelineFragments, type TicketRunState, type ToolCallRecord, type ToolCallRequest, type ToolContext, type ToolPolicy, type ToolSpec, type TrackingSummary, type TriageNodeConfig, UNCERTAINTY_MARKERS, type Usage, type Verdict, type VerifyReplyInput, type VerifyReplyResult, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, type WhatsappMode, agentRecord, assertTransition, buildCategoryRecord, buildDiffAnalysisRecord, buildEvaluationRecord, buildGeneratedResponseRecord, buildResponseComparisonRecord, buildSupportKitRecords, buildSupportPipeline, buildTriageDecisionRecord, canTransition, categoryGroupRecord, channelPreGates, createBudget, createPromptResolver, diffAnalysisUniqueKey, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, hasReferences, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isCustomerTurnWithWords, isDecisionOrigin, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isOutcome, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, parseReferences, pipelineStateRecord, promptCacheRecord, reclaimStalledSend, requiresFollowup, resolvePromptName, runGuardrails, runTicket, settingsToProfile, stopOptOut, targetRefFor, toDecisionOrigin, validateSettings, verifyReply, whatsappModeFromLegacyBoolean };
2210
+ export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, ATTACHMENT_MARKER_ONLY, type ActionDecision, type AgentProfile, type AgentStatus, type AuditTags, type AutoReplyGuardSettings, type Budget, CANDIDATE_MIN_LENGTH, type CatalogueTool, type CategoryPolicy, type CategoryReferentialEntry, type ChannelKind, type ChatMessage, type Classification, type ClockPort, type CompletionRequest, type CompletionResult, type Conversation, type ConversationPort, type ConversationRef, type CostLedger, type CustomerInfo, DECISION_ORIGINS, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, DEFAULT_DECISION_ORIGIN, DEFAULT_LLM_PROVIDER, DEFAULT_PROFILE_KEY, DEFAULT_WHATSAPP_MODE, type DecisionOrigin, type Draft, type DraftAttribution, type DraftNodeConfig, EVALUATION_VERDICTS, type EscalateNodeConfig, type EvaluateNodeConfig, type EvaluationVerdict, GENERATED_RESPONSE_STATUSES, type GeneratedResponseStatus, type GuardrailId, InvalidStatusTransitionError, type JsonSchema, type JudgedReply, type KnowledgeHit, type LlmPort, type Message, MissingPromptError, NODE_NAMES, type Node, type NodeCost, type NodeDeps, type NodeKey, type NodeName, type NodeStep, ORIGIN_DESCRIPTION, OUTCOMES, type OrderSummary, type OutboundReply, type Outcome, PROMPT_SLOTS, type PlatformPromptReader, type PortName, type PromptCacheEntry, type PromptCachePort, type PromptDegradedEvent, type PromptNameConfig, type PromptPort, type PromptRef, type PromptReference, type PromptResolverDeps, type PromptSlot, type PromptTableKey, type ProposedAction, REASONING_MAX_LEN, type RawPrompt, type RawPromptConfig, type RawTicket, type ReasoningEffort, type RecordDef, type ReplyPort, type ResolvedPrompt, type ResumeFrom, type ReviseNodeConfig, type RunGuardrailsInput, type RunStamp, type RunTicketOptions, type RunUntil, STOP_PHRASES, SUPPORT_KIT_SETTINGS_FIELDS, type SettingsIssueKey, type SettingsValidationIssue, type SettingsWarning, type SettingsWarningKey, type SimilarTicket, type SourceDescriptor, type StatePort, type SupportKitNodeSettings, type SupportKitSettings, type SupportPipelineConfig, type SupportPipelineFragments, type TicketRunState, type ToolCallRecord, type ToolCallRequest, type ToolContext, type ToolPolicy, type ToolSpec, type TrackingSummary, type TriageNodeConfig, UNCERTAINTY_MARKERS, type Usage, type Verdict, type VerifyReplyInput, type VerifyReplyResult, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, type WhatsappMode, agentRecord, assertTransition, buildCategoryRecord, buildDiffAnalysisRecord, buildEvaluationRecord, buildGeneratedResponseRecord, buildResponseComparisonRecord, buildSupportKitRecords, buildSupportPipeline, buildTriageDecisionRecord, canTransition, categoryGroupRecord, channelPreGates, createBudget, createPromptResolver, diffAnalysisUniqueKey, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, hasReferences, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isCustomerTurnWithWords, isDecisionOrigin, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isOutcome, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, parseReferences, pipelineStateRecord, promptCacheRecord, reclaimStalledSend, requiresFollowup, resolvePromptName, runGuardrails, runTicket, settingsToProfile, settingsWarnings, stopOptOut, targetRefFor, toDecisionOrigin, validateSettings, verifyReply, whatsappModeFromLegacyBoolean };
package/dist/index.d.ts CHANGED
@@ -321,6 +321,8 @@ interface AgentProfile {
321
321
  sentTag: string;
322
322
  needsHumanTag: string;
323
323
  followupTag: string;
324
+ /** This app's ownership mark on every ticket its triage sees — empty stamps nothing. */
325
+ appScopeTag: string;
324
326
  };
325
327
  autoSend: {
326
328
  enabled: boolean;
@@ -594,6 +596,11 @@ interface AuditTags {
594
596
  sentTag: string;
595
597
  needsHumanTag: string;
596
598
  followupTag: string;
599
+ /**
600
+ * The app's ownership mark, applied to every ticket its triage sees rather
601
+ * than to an outcome — empty when unconfigured, which stamps nothing.
602
+ */
603
+ appScopeTag: string;
597
604
  }
598
605
  interface StatePort {
599
606
  /** Materialises the triage decision (ex `ClassificationSink.record`). */
@@ -1461,7 +1468,7 @@ declare function isAutoSendEligible(state: TicketRunState, deps: Pick<NodeDeps,
1461
1468
  declare function needsRevision(verdict: Verdict | null, profile: AgentProfile, reviseCount: number): boolean;
1462
1469
 
1463
1470
  /** The `generated-response` record's `status` field (§3.4). */
1464
- declare const GENERATED_RESPONSE_STATUSES: readonly ["pending", "ready", "sending", "sent", "failed", "no_reply_needed", "invalidated", "expired", "test_draft"];
1471
+ declare const GENERATED_RESPONSE_STATUSES: readonly ["pending", "ready", "sending", "sent", "failed", "no_reply_needed", "invalidated", "expired", "test_draft", "superseded"];
1465
1472
  type GeneratedResponseStatus = (typeof GENERATED_RESPONSE_STATUSES)[number];
1466
1473
  /**
1467
1474
  * `status` lives in `AppRecord` JSONB (§3.4), so it reaches this module as an
@@ -1907,6 +1914,27 @@ interface SettingsValidationIssue {
1907
1914
  */
1908
1915
  declare function validateSettings(settings: Record<string, unknown>): SettingsValidationIssue[];
1909
1916
 
1917
+ /**
1918
+ * `settingsWarnings` — the settings problems that must NOT stop the app.
1919
+ *
1920
+ * Deliberately separate from `validateSettings`: nine handlers refuse to run
1921
+ * as soon as that function reports a single issue, so routing a "this looks
1922
+ * wrong" remark through it would take a working app off the air. Everything
1923
+ * here describes a configuration that runs, and runs in a way its operator
1924
+ * probably did not intend.
1925
+ *
1926
+ * Its only consumer is the SettingsPage, which is why these messages are
1927
+ * written in French straight away — unlike `validateSettings`' own, they are
1928
+ * never logged, never returned by a handler, and so need no translation layer.
1929
+ */
1930
+ type SettingsWarningKey = 'appScopeTagVetoesFollowups' | 'appScopeTagCollision' | 'scopeTagMismatch';
1931
+ interface SettingsWarning {
1932
+ key: SettingsWarningKey;
1933
+ /** Operator-facing French, safe to show as-is. */
1934
+ message: string;
1935
+ }
1936
+ declare function settingsWarnings(settings: Record<string, unknown>): SettingsWarning[];
1937
+
1910
1938
  /**
1911
1939
  * `settings` (§3.6) → `AgentProfile` (architecture_agent_graphe.md §5.3).
1912
1940
  *
@@ -2016,6 +2044,8 @@ interface SupportKitSettings {
2016
2044
  followupTag: string;
2017
2045
  /** D2 — the tag scoping which tickets the follow-up webhook may answer. Empty = inert (see `settings/fields.ts`). */
2018
2046
  webhookScopeTag: string;
2047
+ /** The tag this app stamps on every ticket its triage sees. Empty = stamps nothing (see `settings/fields.ts`). */
2048
+ appScopeTag: string;
2019
2049
  autoSendEnabled: boolean;
2020
2050
  senderEmail: string;
2021
2051
  requireHighTriageConfidence: boolean;
@@ -2177,4 +2207,4 @@ interface SupportPipelineFragments {
2177
2207
  }
2178
2208
  declare function buildSupportPipeline(config: SupportPipelineConfig): SupportPipelineFragments;
2179
2209
 
2180
- export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, ATTACHMENT_MARKER_ONLY, type ActionDecision, type AgentProfile, type AgentStatus, type AuditTags, type AutoReplyGuardSettings, type Budget, CANDIDATE_MIN_LENGTH, type CatalogueTool, type CategoryPolicy, type CategoryReferentialEntry, type ChannelKind, type ChatMessage, type Classification, type ClockPort, type CompletionRequest, type CompletionResult, type Conversation, type ConversationPort, type ConversationRef, type CostLedger, type CustomerInfo, DECISION_ORIGINS, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, DEFAULT_DECISION_ORIGIN, DEFAULT_LLM_PROVIDER, DEFAULT_PROFILE_KEY, DEFAULT_WHATSAPP_MODE, type DecisionOrigin, type Draft, type DraftAttribution, type DraftNodeConfig, EVALUATION_VERDICTS, type EscalateNodeConfig, type EvaluateNodeConfig, type EvaluationVerdict, GENERATED_RESPONSE_STATUSES, type GeneratedResponseStatus, type GuardrailId, InvalidStatusTransitionError, type JsonSchema, type JudgedReply, type KnowledgeHit, type LlmPort, type Message, MissingPromptError, NODE_NAMES, type Node, type NodeCost, type NodeDeps, type NodeKey, type NodeName, type NodeStep, ORIGIN_DESCRIPTION, OUTCOMES, type OrderSummary, type OutboundReply, type Outcome, PROMPT_SLOTS, type PlatformPromptReader, type PortName, type PromptCacheEntry, type PromptCachePort, type PromptDegradedEvent, type PromptNameConfig, type PromptPort, type PromptRef, type PromptReference, type PromptResolverDeps, type PromptSlot, type PromptTableKey, type ProposedAction, REASONING_MAX_LEN, type RawPrompt, type RawPromptConfig, type RawTicket, type ReasoningEffort, type RecordDef, type ReplyPort, type ResolvedPrompt, type ResumeFrom, type ReviseNodeConfig, type RunGuardrailsInput, type RunStamp, type RunTicketOptions, type RunUntil, STOP_PHRASES, SUPPORT_KIT_SETTINGS_FIELDS, type SettingsIssueKey, type SettingsValidationIssue, type SimilarTicket, type SourceDescriptor, type StatePort, type SupportKitNodeSettings, type SupportKitSettings, type SupportPipelineConfig, type SupportPipelineFragments, type TicketRunState, type ToolCallRecord, type ToolCallRequest, type ToolContext, type ToolPolicy, type ToolSpec, type TrackingSummary, type TriageNodeConfig, UNCERTAINTY_MARKERS, type Usage, type Verdict, type VerifyReplyInput, type VerifyReplyResult, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, type WhatsappMode, agentRecord, assertTransition, buildCategoryRecord, buildDiffAnalysisRecord, buildEvaluationRecord, buildGeneratedResponseRecord, buildResponseComparisonRecord, buildSupportKitRecords, buildSupportPipeline, buildTriageDecisionRecord, canTransition, categoryGroupRecord, channelPreGates, createBudget, createPromptResolver, diffAnalysisUniqueKey, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, hasReferences, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isCustomerTurnWithWords, isDecisionOrigin, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isOutcome, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, parseReferences, pipelineStateRecord, promptCacheRecord, reclaimStalledSend, requiresFollowup, resolvePromptName, runGuardrails, runTicket, settingsToProfile, stopOptOut, targetRefFor, toDecisionOrigin, validateSettings, verifyReply, whatsappModeFromLegacyBoolean };
2210
+ export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, ATTACHMENT_MARKER_ONLY, type ActionDecision, type AgentProfile, type AgentStatus, type AuditTags, type AutoReplyGuardSettings, type Budget, CANDIDATE_MIN_LENGTH, type CatalogueTool, type CategoryPolicy, type CategoryReferentialEntry, type ChannelKind, type ChatMessage, type Classification, type ClockPort, type CompletionRequest, type CompletionResult, type Conversation, type ConversationPort, type ConversationRef, type CostLedger, type CustomerInfo, DECISION_ORIGINS, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, DEFAULT_DECISION_ORIGIN, DEFAULT_LLM_PROVIDER, DEFAULT_PROFILE_KEY, DEFAULT_WHATSAPP_MODE, type DecisionOrigin, type Draft, type DraftAttribution, type DraftNodeConfig, EVALUATION_VERDICTS, type EscalateNodeConfig, type EvaluateNodeConfig, type EvaluationVerdict, GENERATED_RESPONSE_STATUSES, type GeneratedResponseStatus, type GuardrailId, InvalidStatusTransitionError, type JsonSchema, type JudgedReply, type KnowledgeHit, type LlmPort, type Message, MissingPromptError, NODE_NAMES, type Node, type NodeCost, type NodeDeps, type NodeKey, type NodeName, type NodeStep, ORIGIN_DESCRIPTION, OUTCOMES, type OrderSummary, type OutboundReply, type Outcome, PROMPT_SLOTS, type PlatformPromptReader, type PortName, type PromptCacheEntry, type PromptCachePort, type PromptDegradedEvent, type PromptNameConfig, type PromptPort, type PromptRef, type PromptReference, type PromptResolverDeps, type PromptSlot, type PromptTableKey, type ProposedAction, REASONING_MAX_LEN, type RawPrompt, type RawPromptConfig, type RawTicket, type ReasoningEffort, type RecordDef, type ReplyPort, type ResolvedPrompt, type ResumeFrom, type ReviseNodeConfig, type RunGuardrailsInput, type RunStamp, type RunTicketOptions, type RunUntil, STOP_PHRASES, SUPPORT_KIT_SETTINGS_FIELDS, type SettingsIssueKey, type SettingsValidationIssue, type SettingsWarning, type SettingsWarningKey, type SimilarTicket, type SourceDescriptor, type StatePort, type SupportKitNodeSettings, type SupportKitSettings, type SupportPipelineConfig, type SupportPipelineFragments, type TicketRunState, type ToolCallRecord, type ToolCallRequest, type ToolContext, type ToolPolicy, type ToolSpec, type TrackingSummary, type TriageNodeConfig, UNCERTAINTY_MARKERS, type Usage, type Verdict, type VerifyReplyInput, type VerifyReplyResult, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, type WhatsappMode, agentRecord, assertTransition, buildCategoryRecord, buildDiffAnalysisRecord, buildEvaluationRecord, buildGeneratedResponseRecord, buildResponseComparisonRecord, buildSupportKitRecords, buildSupportPipeline, buildTriageDecisionRecord, canTransition, categoryGroupRecord, channelPreGates, createBudget, createPromptResolver, diffAnalysisUniqueKey, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, hasReferences, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isCustomerTurnWithWords, isDecisionOrigin, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isOutcome, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, parseReferences, pipelineStateRecord, promptCacheRecord, reclaimStalledSend, requiresFollowup, resolvePromptName, runGuardrails, runTicket, settingsToProfile, settingsWarnings, stopOptOut, targetRefFor, toDecisionOrigin, validateSettings, verifyReply, whatsappModeFromLegacyBoolean };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { CATEGORY_GROUP_FIELD_NAME_UID, CATEGORY_GROUP_FIELD_ORDER_UID, PIPELINE_STATE_FIELD_SINGLETON_KEY_UID, PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID, PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID, PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID, PROMPT_CACHE_FIELD_PROMPT_KEY_UID, PROMPT_CACHE_FIELD_CONTENT_UID, PROMPT_CACHE_FIELD_VERSION_UID, PROMPT_CACHE_FIELD_LABEL_UID, PROMPT_CACHE_FIELD_CONFIG_UID, CATEGORY_GROUP_INDEX_NAME_UID, CATEGORY_GROUP_OBJECT_UID, PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, PIPELINE_STATE_OBJECT_UID, PROMPT_CACHE_INDEX_PROMPT_KEY_UID, PROMPT_CACHE_OBJECT_UID, CATEGORY_INDEX_TAG_NAME_UID, CATEGORY_INDEX_NAME_UID, CATEGORY_INDEX_ORDER_UID, CATEGORY_FIELD_NAME_UID, CATEGORY_FIELD_TAG_NAME_UID, CATEGORY_FIELD_ORDER_UID, CATEGORY_FIELD_GROUP_ID_UID, CATEGORY_FIELD_AGENT_ID_UID, CATEGORY_FIELD_EXTRA_TAGS_UID, CATEGORY_FIELD_DESCRIPTION_UID, CATEGORY_FIELD_EXAMPLES_UID, CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID, CATEGORY_FIELD_FOLLOWUP_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_FOLLOWUP_AUTO_REPLY_ENABLED_UID, CATEGORY_OBJECT_UID, TRIAGE_DECISION_INDEX_TICKET_ID_UID, TRIAGE_DECISION_INDEX_DECIDED_AT_UID, TRIAGE_DECISION_INDEX_ESCALATED_UID, TRIAGE_DECISION_FIELD_TICKET_ID_UID, TRIAGE_DECISION_FIELD_TICKET_URL_UID, TRIAGE_DECISION_FIELD_DECIDED_AT_UID, TRIAGE_DECISION_FIELD_CATEGORY_ID_UID, TRIAGE_DECISION_FIELD_TAG_UID, TRIAGE_DECISION_FIELD_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_REASONING_UID, TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID, TRIAGE_DECISION_FIELD_ESCALATED_UID, TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID, TRIAGE_DECISION_FIELD_STATUS_UID, TRIAGE_DECISION_FIELD_ERROR_UID, TRIAGE_DECISION_FIELD_RUN_ID_UID, TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID, DEFAULT_DECISION_ORIGIN, ORIGIN_DESCRIPTION, TRIAGE_DECISION_FIELD_ORIGIN_UID, TRIAGE_DECISION_OBJECT_UID, GENERATED_RESPONSE_INDEX_TICKET_ID_UID, GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID, GENERATED_RESPONSE_INDEX_STATUS_UID, GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID, GENERATED_RESPONSE_INDEX_GENERATED_AT_UID, GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID, GENERATED_RESPONSE_FIELD_TICKET_ID_UID, GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID, GENERATED_RESPONSE_STATUSES, GENERATED_RESPONSE_FIELD_STATUS_UID, GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID, GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID, GENERATED_RESPONSE_FIELD_AGENT_ID_UID, GENERATED_RESPONSE_FIELD_CHANNEL_UID, GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID, GENERATED_RESPONSE_FIELD_SOURCES_UID, GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID, GENERATED_RESPONSE_FIELD_VERDICT_UID, GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID, OUTCOMES, GENERATED_RESPONSE_FIELD_OUTCOME_UID, GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID, GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID, GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID, GENERATED_RESPONSE_FIELD_SERVED_TO_UID, GENERATED_RESPONSE_FIELD_GENERATED_AT_UID, GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID, GENERATED_RESPONSE_FIELD_SENT_AT_UID, GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID, GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID, GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID, GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID, GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID, GENERATED_RESPONSE_FIELD_ERROR_UID, GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID, GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID, GENERATED_RESPONSE_FIELD_SENDING_AT_UID, GENERATED_RESPONSE_FIELD_RUN_ID_UID, GENERATED_RESPONSE_FIELD_ORIGIN_UID, GENERATED_RESPONSE_OBJECT_UID, RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID, RESPONSE_COMPARISON_INDEX_TICKET_ID_UID, RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID, RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID, RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID, RESPONSE_COMPARISON_FIELD_TICKET_ID_UID, RESPONSE_COMPARISON_FIELD_TICKET_URL_UID, RESPONSE_COMPARISON_FIELD_AGENT_ID_UID, RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID, RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID, RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID, RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID, RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID, RESPONSE_COMPARISON_FIELD_DIFF_UID, RESPONSE_COMPARISON_OBJECT_UID, EVALUATION_FIELD_AGENT_ID_UID, EVALUATION_FIELD_SATISFIED_UID, EVALUATION_FIELD_MESSAGES_UID, EVALUATION_FIELD_TICKET_URL_UID, EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID, EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID, EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID, EVALUATION_OBJECT_UID, DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID, DIFF_ANALYSIS_FIELD_AGENT_ID_UID, DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID, DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID, DIFF_ANALYSIS_FIELD_POINTS_UID, DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID, DIFF_ANALYSIS_OBJECT_UID, agentRecord, SUPPORT_KIT_SETTINGS_FIELDS, MissingPromptError, validateSettings, settingsToProfile, buildPromptsTable, draftPromptRefFor, assertTransition, openTicketKeyFor, act, initialState, applyOutcomeTags, listCategories, resolveDraftAgent, runTicket, toCategoryReferential, toAgent, draftRebinder, resolvePromptName, isGeneratedResponseStatus, isInvalidatableStatus, DEFAULT_LLM_PROVIDER, toCategoryGroup, toCategory, toGeneratedResponse, NODE_NAMES, reclaimStalledSend, applySignature, isEvaluationVerdict, requiresFollowup, computeWordDiff, findCategoryByTag, isWhatsappTicket, hasCustomerAttachment, isTicketClosed, toDecisionOrigin, isConversationOver, isFallbackClassification, hasNoDraftNode, isWhatsappChevronNote, isCustomerTurnWithWords } from './chunk-LXHPPWPM.js';
2
- export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, ATTACHMENT_MARKER_ONLY, CANDIDATE_MIN_LENGTH, DECISION_ORIGINS, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, DEFAULT_DECISION_ORIGIN, DEFAULT_LLM_PROVIDER, DEFAULT_PROFILE_KEY, DEFAULT_WHATSAPP_MODE, EVALUATION_VERDICTS, GENERATED_RESPONSE_STATUSES, InvalidStatusTransitionError, MissingPromptError, NODE_NAMES, ORIGIN_DESCRIPTION, OUTCOMES, PROMPT_SLOTS, REASONING_MAX_LEN, STOP_PHRASES, SUPPORT_KIT_SETTINGS_FIELDS, UNCERTAINTY_MARKERS, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, agentRecord, assertTransition, canTransition, channelPreGates, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isCustomerTurnWithWords, isDecisionOrigin, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isOutcome, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, reclaimStalledSend, requiresFollowup, resolvePromptName, runGuardrails, runTicket, settingsToProfile, stopOptOut, toDecisionOrigin, validateSettings, verifyReply, whatsappModeFromLegacyBoolean } from './chunk-LXHPPWPM.js';
1
+ import { CATEGORY_GROUP_FIELD_NAME_UID, CATEGORY_GROUP_FIELD_ORDER_UID, PIPELINE_STATE_FIELD_SINGLETON_KEY_UID, PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID, PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID, PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID, PROMPT_CACHE_FIELD_PROMPT_KEY_UID, PROMPT_CACHE_FIELD_CONTENT_UID, PROMPT_CACHE_FIELD_VERSION_UID, PROMPT_CACHE_FIELD_LABEL_UID, PROMPT_CACHE_FIELD_CONFIG_UID, CATEGORY_GROUP_INDEX_NAME_UID, CATEGORY_GROUP_OBJECT_UID, PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, PIPELINE_STATE_OBJECT_UID, PROMPT_CACHE_INDEX_PROMPT_KEY_UID, PROMPT_CACHE_OBJECT_UID, CATEGORY_INDEX_TAG_NAME_UID, CATEGORY_INDEX_NAME_UID, CATEGORY_INDEX_ORDER_UID, CATEGORY_FIELD_NAME_UID, CATEGORY_FIELD_TAG_NAME_UID, CATEGORY_FIELD_ORDER_UID, CATEGORY_FIELD_GROUP_ID_UID, CATEGORY_FIELD_AGENT_ID_UID, CATEGORY_FIELD_EXTRA_TAGS_UID, CATEGORY_FIELD_DESCRIPTION_UID, CATEGORY_FIELD_EXAMPLES_UID, CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID, CATEGORY_FIELD_FOLLOWUP_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_FOLLOWUP_AUTO_REPLY_ENABLED_UID, CATEGORY_OBJECT_UID, TRIAGE_DECISION_INDEX_TICKET_ID_UID, TRIAGE_DECISION_INDEX_DECIDED_AT_UID, TRIAGE_DECISION_INDEX_ESCALATED_UID, TRIAGE_DECISION_FIELD_TICKET_ID_UID, TRIAGE_DECISION_FIELD_TICKET_URL_UID, TRIAGE_DECISION_FIELD_DECIDED_AT_UID, TRIAGE_DECISION_FIELD_CATEGORY_ID_UID, TRIAGE_DECISION_FIELD_TAG_UID, TRIAGE_DECISION_FIELD_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_REASONING_UID, TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID, TRIAGE_DECISION_FIELD_ESCALATED_UID, TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID, TRIAGE_DECISION_FIELD_STATUS_UID, TRIAGE_DECISION_FIELD_ERROR_UID, TRIAGE_DECISION_FIELD_RUN_ID_UID, TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID, DEFAULT_DECISION_ORIGIN, ORIGIN_DESCRIPTION, TRIAGE_DECISION_FIELD_ORIGIN_UID, TRIAGE_DECISION_OBJECT_UID, GENERATED_RESPONSE_INDEX_TICKET_ID_UID, GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID, GENERATED_RESPONSE_INDEX_STATUS_UID, GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID, GENERATED_RESPONSE_INDEX_GENERATED_AT_UID, GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID, GENERATED_RESPONSE_FIELD_TICKET_ID_UID, GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID, GENERATED_RESPONSE_STATUSES, GENERATED_RESPONSE_FIELD_STATUS_UID, GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID, GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID, GENERATED_RESPONSE_FIELD_AGENT_ID_UID, GENERATED_RESPONSE_FIELD_CHANNEL_UID, GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID, GENERATED_RESPONSE_FIELD_SOURCES_UID, GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID, GENERATED_RESPONSE_FIELD_VERDICT_UID, GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID, OUTCOMES, GENERATED_RESPONSE_FIELD_OUTCOME_UID, GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID, GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID, GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID, GENERATED_RESPONSE_FIELD_SERVED_TO_UID, GENERATED_RESPONSE_FIELD_GENERATED_AT_UID, GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID, GENERATED_RESPONSE_FIELD_SENT_AT_UID, GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID, GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID, GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID, GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID, GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID, GENERATED_RESPONSE_FIELD_ERROR_UID, GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID, GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID, GENERATED_RESPONSE_FIELD_SENDING_AT_UID, GENERATED_RESPONSE_FIELD_RUN_ID_UID, GENERATED_RESPONSE_FIELD_ORIGIN_UID, GENERATED_RESPONSE_OBJECT_UID, RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID, RESPONSE_COMPARISON_INDEX_TICKET_ID_UID, RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID, RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID, RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID, RESPONSE_COMPARISON_FIELD_TICKET_ID_UID, RESPONSE_COMPARISON_FIELD_TICKET_URL_UID, RESPONSE_COMPARISON_FIELD_AGENT_ID_UID, RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID, RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID, RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID, RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID, RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID, RESPONSE_COMPARISON_FIELD_DIFF_UID, RESPONSE_COMPARISON_OBJECT_UID, EVALUATION_FIELD_AGENT_ID_UID, EVALUATION_FIELD_SATISFIED_UID, EVALUATION_FIELD_MESSAGES_UID, EVALUATION_FIELD_TICKET_URL_UID, EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID, EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID, EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID, EVALUATION_OBJECT_UID, DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID, DIFF_ANALYSIS_FIELD_AGENT_ID_UID, DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID, DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID, DIFF_ANALYSIS_FIELD_POINTS_UID, DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID, DIFF_ANALYSIS_OBJECT_UID, agentRecord, SUPPORT_KIT_SETTINGS_FIELDS, MissingPromptError, validateSettings, settingsToProfile, buildPromptsTable, draftPromptRefFor, assertTransition, openTicketKeyFor, act, initialState, applyOutcomeTags, listCategories, resolveDraftAgent, runTicket, toCategoryReferential, toAgent, draftRebinder, resolvePromptName, isGeneratedResponseStatus, isInvalidatableStatus, DEFAULT_LLM_PROVIDER, toCategoryGroup, toCategory, toGeneratedResponse, NODE_NAMES, reclaimStalledSend, applySignature, isEvaluationVerdict, requiresFollowup, computeWordDiff, findCategoryByTag, isWhatsappTicket, hasCustomerAttachment, isTicketClosed, isTerminalStatus, canTransition, toDecisionOrigin, isConversationOver, isFallbackClassification, hasNoDraftNode, isWhatsappChevronNote, isCustomerTurnWithWords } from './chunk-D3QGGJAI.js';
2
+ export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, ATTACHMENT_MARKER_ONLY, CANDIDATE_MIN_LENGTH, DECISION_ORIGINS, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, DEFAULT_DECISION_ORIGIN, DEFAULT_LLM_PROVIDER, DEFAULT_PROFILE_KEY, DEFAULT_WHATSAPP_MODE, EVALUATION_VERDICTS, GENERATED_RESPONSE_STATUSES, InvalidStatusTransitionError, MissingPromptError, NODE_NAMES, ORIGIN_DESCRIPTION, OUTCOMES, PROMPT_SLOTS, REASONING_MAX_LEN, STOP_PHRASES, SUPPORT_KIT_SETTINGS_FIELDS, UNCERTAINTY_MARKERS, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, agentRecord, assertTransition, canTransition, channelPreGates, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isCustomerTurnWithWords, isDecisionOrigin, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isOutcome, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, reclaimStalledSend, requiresFollowup, resolvePromptName, runGuardrails, runTicket, settingsToProfile, settingsWarnings, stopOptOut, toDecisionOrigin, validateSettings, verifyReply, whatsappModeFromLegacyBoolean } from './chunk-D3QGGJAI.js';
3
3
  import { FieldType, APPROVAL_DECIDED_EVENT, AppApiError } from '@apotech-os/app-kit';
4
4
  import { createHash } from 'node:crypto';
5
5
 
@@ -1234,7 +1234,7 @@ async function extraTagsFor(api, tagName) {
1234
1234
  }
1235
1235
  async function resolveHandledTags(api, classification, audit) {
1236
1236
  const extraTags = await extraTagsFor(api, classification.category);
1237
- return dedupeTagNames([classification.category, ...extraTags, audit.handledTag]);
1237
+ return dedupeTagNames([classification.category, ...extraTags, audit.handledTag, audit.appScopeTag]);
1238
1238
  }
1239
1239
 
1240
1240
  // src/adapters/ctx-ports.ts
@@ -1958,6 +1958,7 @@ async function handleTicketFailure(ctx, ref, err, deps) {
1958
1958
  await finalizeFailedResponse(ctx, ref, err.generatedResponseId, message);
1959
1959
  } else {
1960
1960
  await writeErrorDecision(ctx, ref, message, deps);
1961
+ await stampAppScope(ctx, ref, deps.profile.audit.appScopeTag, deps.ports);
1961
1962
  }
1962
1963
  await escalateTicket(ctx, ref, deps);
1963
1964
  }
@@ -1997,6 +1998,16 @@ async function writeErrorDecision(ctx, ref, message, deps) {
1997
1998
  async function escalateTicket(ctx, ref, deps) {
1998
1999
  await flagEscalation(ctx, ref, deps.profile.audit.escalationTag, deps.ports);
1999
2000
  }
2001
+ async function stampAppScope(ctx, ref, tag, ports) {
2002
+ if (!tag) return;
2003
+ try {
2004
+ await ports.state.flag(ref, tag);
2005
+ } catch (err) {
2006
+ ctx.logger.error(`triage-tick: failed to stamp the app scope tag on ticket ${ref.id}`, {
2007
+ error: err instanceof Error ? err.message : String(err)
2008
+ });
2009
+ }
2010
+ }
2000
2011
  async function flagEscalation(ctx, ref, tag, ports) {
2001
2012
  if (!tag) {
2002
2013
  ctx.logger.warn(`triage-tick: ticket ${ref.id} is escalated but escalationTag is not configured \u2014 no tag applied`);
@@ -2120,11 +2131,11 @@ async function sweepHandler(ctx) {
2120
2131
  const statePort = createGorgiasStatePort(ctx.api);
2121
2132
  const escalationTag = typeof settings?.escalationTag === "string" ? settings.escalationTag : "";
2122
2133
  if (!escalationTag) {
2123
- ctx.logger.warn("sweep: escalationTag is not configured \u2014 a stalled-send reclaim will proceed without an escalation tag");
2134
+ ctx.logger.warn("sweep: escalationTag is not configured \u2014 a stalled-send reclaim or an orphaned-pending hand-off will proceed without an escalation tag");
2124
2135
  }
2125
2136
  await sweepExpiredReady(ctx, now);
2126
2137
  await sweepStalledSending(ctx, now, escalationTag, statePort);
2127
- await sweepStalledPending(ctx, now);
2138
+ await sweepStalledPending(ctx, now, escalationTag, statePort);
2128
2139
  await upsertPipelineState(ctx.api, { lastSweepAt: now });
2129
2140
  }
2130
2141
  async function sweepExpiredReady(ctx, now) {
@@ -2170,23 +2181,26 @@ async function sweepStalledSending(ctx, now, escalationTag, statePort) {
2170
2181
  await statePort.flag(ref, escalationTag);
2171
2182
  }
2172
2183
  }
2173
- async function sweepStalledPending(ctx, now) {
2184
+ async function sweepStalledPending(ctx, now, escalationTag, statePort) {
2174
2185
  const page = await ctx.api.list("generated-response", { filter: { status: "pending" }, limit: SWEEP_PAGE_SIZE });
2175
2186
  for (const row of page.items) {
2176
2187
  const expiresAt = toDate(row.data.expiresAt);
2177
2188
  if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;
2189
+ const ticketId = row.data.ticketId;
2178
2190
  assertTransition("pending", "failed");
2179
2191
  try {
2180
2192
  await ctx.api.update(
2181
2193
  "generated-response",
2182
2194
  row.id,
2183
- { status: "failed", openTicketKey: openTicketKeyFor("failed", row.data.ticketId), error: "orphaned pending row past its TTL (sweep)" },
2195
+ { status: "failed", openTicketKey: openTicketKeyFor("failed", ticketId), error: "orphaned pending row past its TTL (sweep)" },
2184
2196
  { ifMatch: { status: "pending" } }
2185
2197
  );
2186
2198
  } catch (err) {
2187
2199
  if (err instanceof AppApiError && err.status === 409) continue;
2188
2200
  throw err;
2189
2201
  }
2202
+ const ref = { id: ticketId, channel: "gorgias" };
2203
+ await statePort.flag(ref, escalationTag);
2190
2204
  }
2191
2205
  }
2192
2206
  function buildHandleApprovalFunctionDef(config) {
@@ -4064,7 +4078,8 @@ var LABELS = {
4064
4078
  G5: "Tag de p\xE9rim\xE8tre pr\xE9sent sur le ticket",
4065
4079
  G6: "Aucune reprise humaine",
4066
4080
  G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
4067
- G8: "Nouveau message client"
4081
+ G8: "Nouveau message client",
4082
+ G9: "R\xE9ponse ouverte pr\xE9empt\xE9e"
4068
4083
  };
4069
4084
  function humanTakeoverTags(settings) {
4070
4085
  const configured = [settings.escalationTag, settings.needsReviewTag, settings.followupTag].map((tag) => tag.trim()).filter((tag) => tag !== "");
@@ -4090,15 +4105,23 @@ function completeFollowupLadder(results) {
4090
4105
  return missing.length === 0 ? results : [...results, ...skippedFollowupGates(missing)];
4091
4106
  }
4092
4107
  var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
4093
- var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES];
4108
+ var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES, "G9"];
4094
4109
  function evaluateTicketGates(input) {
4095
- const { settings, tags, categories, conversation, anchor, ignoreCategoryOptIn = false } = input;
4110
+ const {
4111
+ settings,
4112
+ tags,
4113
+ categories,
4114
+ conversation,
4115
+ anchor,
4116
+ openResponse = null,
4117
+ ignoreCategoryOptIn = false
4118
+ } = input;
4096
4119
  const trace = newTrace(FRESH_READ_GATES);
4097
4120
  trace.record(scopeTagOnTicket(settings, tags));
4098
4121
  trace.record(noHumanTakeover(settings, tags));
4099
4122
  const match = trace.record(categoryGate(categories, tags, ignoreCategoryOptIn));
4100
4123
  if (match) trace.category = match;
4101
- trace.record(newCustomerMessage(conversation, anchor));
4124
+ trace.record(newCustomerMessage(conversation, anchor, openResponse));
4102
4125
  return trace.done();
4103
4126
  }
4104
4127
  function evaluatePayloadGates(input) {
@@ -4161,15 +4184,20 @@ function noMatchingCategory() {
4161
4184
  function matchingCategories(categories, tags) {
4162
4185
  return categories.filter((category) => tags.includes(category.tagName));
4163
4186
  }
4164
- function newCustomerMessage(conversation, anchor) {
4187
+ function newCustomerMessage(conversation, anchor, openResponse) {
4165
4188
  if (conversation.isClosed) return stopped("G8", "Le ticket est ferm\xE9.");
4166
4189
  const last = conversation.messages[conversation.messages.length - 1];
4167
4190
  if (!last) return stopped("G8", "La conversation extraite est vide.");
4168
4191
  if (!isCustomerTurnWithWords(last)) {
4169
4192
  return stopped("G8", "Le dernier message du fil n\u2019est pas un message client porteur de mots (agent, note interne, ou pi\xE8ce jointe seule).");
4170
4193
  }
4171
- if (anchor === null) return passed("G8", "Le dernier message est du client ; aucune r\xE9ponse ant\xE9rieure, donc aucune ancre \xE0 battre.");
4172
4194
  const lastAt = conversation.lastMessageAt;
4195
+ if (openResponse?.status === "pending" && lastAt && openResponse.ownAnchor?.getTime() === lastAt.getTime()) {
4196
+ return passed("G8", "Une tentative pr\xE9c\xE9dente de ce passage a laiss\xE9 une r\xE9ponse en attente sur ce m\xEAme message : reprise.");
4197
+ }
4198
+ if (anchor === null) {
4199
+ return openResponse === null ? passed("G8", "Le dernier message est du client ; aucune r\xE9ponse ant\xE9rieure, donc aucune ancre \xE0 battre.") : stopped("G8", "Une r\xE9ponse est d\xE9j\xE0 en cours de r\xE9daction sur ce ticket et ne porte aucune ancre : impossible de prouver que ce message est nouveau.");
4200
+ }
4173
4201
  if (!lastAt) return stopped("G8", "Le dernier message ne porte aucun horodatage : impossible de prouver qu\u2019il est post\xE9rieur \xE0 la derni\xE8re r\xE9ponse.");
4174
4202
  return lastAt.getTime() > anchor.getTime() ? passed("G8", `Message client du ${lastAt.toISOString()}, post\xE9rieur \xE0 la derni\xE8re r\xE9ponse.`) : stopped("G8", `Le dernier message (${lastAt.toISOString()}) n\u2019est pas post\xE9rieur \xE0 la derni\xE8re r\xE9ponse (${anchor.toISOString()}) : relivraison ou \xE9v\xE9nement en retard.`);
4175
4203
  }
@@ -4380,7 +4408,7 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
4380
4408
  const scope = evaluateScopeGate(settings);
4381
4409
  ladder.push(scope);
4382
4410
  if (scope.status === "stopped") return stopAt(ctx, ticketId, scope, ladder);
4383
- const { anchor, hasOpenResponse } = await readFollowupAnchor(ctx, ticketId);
4411
+ const { anchor, openResponse } = await readFollowupAnchor(ctx, ticketId);
4384
4412
  const categories = await listCategories(ctx.api);
4385
4413
  const preGates = evaluatePayloadGates({ settings, body, categories, anchor });
4386
4414
  if (preGates.stop) {
@@ -4397,6 +4425,7 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
4397
4425
  categories,
4398
4426
  conversation,
4399
4427
  anchor,
4428
+ openResponse,
4400
4429
  ignoreCategoryOptIn: generateOnly
4401
4430
  });
4402
4431
  ladder.push(...gates.results);
@@ -4404,15 +4433,27 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
4404
4433
  return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory(), ladder);
4405
4434
  }
4406
4435
  const category = gates.category;
4407
- if (hasOpenResponse) return stop(ctx, ticketId, "G9", "une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket", ladder);
4436
+ const preemption = openResponse ? generateOnly ? stopped("G9", "Une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket : l'essai ne la remplace pas, contrairement \xE0 un passage r\xE9el.") : await preemptOpenResponse(ctx, ticketId, openResponse) : passed("G9", "Aucune r\xE9ponse ouverte sur ce ticket.");
4437
+ if (preemption.status === "stopped") {
4438
+ ladder.push(preemption);
4439
+ return stopAt(ctx, ticketId, preemption, ladder);
4440
+ }
4408
4441
  run.id ??= (await ctx.api.runs.start({
4409
4442
  kind: FOLLOWUP_RUN_KIND,
4410
4443
  message: `Message suivant \u2014 ticket ${ticketId}`,
4411
4444
  metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
4412
4445
  })).id;
4413
4446
  const ticketUrl = ticketUrlFor(await resolveTicketUrlBase(ctx), ticketId);
4414
- const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id, ticketUrl });
4415
- if (!created) return stop(ctx, ticketId, "G9", "une autre ex\xE9cution a ouvert la r\xE9ponse en premier", ladder);
4447
+ const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id, ticketUrl, generateOnly });
4448
+ if (!created) {
4449
+ const lost = stopped(
4450
+ "G9",
4451
+ `Une autre ex\xE9cution a ouvert la r\xE9ponse en premier. ${preemption.detail}`.trim()
4452
+ );
4453
+ ladder.push(lost);
4454
+ return stopAt(ctx, ticketId, lost, ladder);
4455
+ }
4456
+ ladder.push(preemption);
4416
4457
  const outcome = await respondToPendingResponse(ctx, config, created.id, { testRun: generateOnly });
4417
4458
  return {
4418
4459
  ticketId,
@@ -4433,16 +4474,66 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
4433
4474
  async function readFollowupAnchor(ctx, ticketId) {
4434
4475
  const page = await ctx.api.list("generated-response", { filter: { ticketId }, limit: ANCHOR_LOOKUP_LIMIT });
4435
4476
  let anchor = null;
4436
- let hasOpenResponse = false;
4477
+ let openResponse = null;
4437
4478
  for (const item of page.items) {
4438
4479
  const data = item.data;
4439
- if (data.openTicketKey === ticketId) hasOpenResponse = true;
4480
+ let ownAnchor = null;
4440
4481
  for (const raw of [data.generatedLastMessageAt, data.sentAt]) {
4441
4482
  const at = toDate2(raw);
4483
+ if (at && (!ownAnchor || at > ownAnchor)) ownAnchor = at;
4442
4484
  if (at && (!anchor || at > anchor)) anchor = at;
4443
4485
  }
4486
+ if (data.openTicketKey === ticketId) {
4487
+ openResponse = { id: item.id, status: isGeneratedResponseStatus(data.status) ? data.status : null, ownAnchor };
4488
+ }
4444
4489
  }
4445
- return { anchor, hasOpenResponse };
4490
+ return { anchor, openResponse };
4491
+ }
4492
+ var SEND_SETTLE_POLL_MS = 2e3;
4493
+ var SEND_SETTLE_ATTEMPTS = 4;
4494
+ var PREEMPT_ATTEMPTS = 3;
4495
+ async function preemptOpenResponse(ctx, ticketId, open) {
4496
+ let status = open.status;
4497
+ for (let attempt = 1; attempt <= PREEMPT_ATTEMPTS; attempt += 1) {
4498
+ if (status === null) {
4499
+ return stopped("G9", "Une r\xE9ponse ouverte porte un statut illisible : elle doit \xEAtre d\xE9bloqu\xE9e \xE0 la main.");
4500
+ }
4501
+ if (isTerminalStatus(status)) {
4502
+ return passed("G9", "La r\xE9ponse ouverte s'est termin\xE9e d'elle-m\xEAme : le ticket est libre.");
4503
+ }
4504
+ if (status === "sending") {
4505
+ status = await awaitSettledSend(ctx, open.id);
4506
+ if (status === "sending") {
4507
+ ctx.logger.warn(
4508
+ `gorgias-webhook: stop at G9 for ticket ${ticketId} \u2014 envoi bloqu\xE9 depuis plus de ${SEND_SETTLE_POLL_MS * SEND_SETTLE_ATTEMPTS / 1e3} s, message suivant non trait\xE9`
4509
+ );
4510
+ return stopped("G9", "Une r\xE9ponse est en cours d'envoi et ne se termine pas : au sweep de la r\xE9clamer.");
4511
+ }
4512
+ continue;
4513
+ }
4514
+ if (!canTransition(status, "superseded")) {
4515
+ return stopped("G9", `Une r\xE9ponse au statut \xAB ${status} \xBB tient le ticket et ne peut pas \xEAtre remplac\xE9e.`);
4516
+ }
4517
+ if (await transitionGeneratedResponse(ctx.api, { id: open.id, ticketId, from: status, to: "superseded" })) {
4518
+ return passed("G9", `La r\xE9ponse ouverte (${status}) r\xE9pondait \xE0 un message ant\xE9rieur : remplac\xE9e.`);
4519
+ }
4520
+ status = await readResponseStatus(ctx, open.id);
4521
+ }
4522
+ return stopped("G9", "La r\xE9ponse ouverte change de statut plus vite que ce passage ne peut la remplacer.");
4523
+ }
4524
+ async function awaitSettledSend(ctx, id) {
4525
+ let status = "sending";
4526
+ for (let attempt = 1; attempt <= SEND_SETTLE_ATTEMPTS && status === "sending"; attempt += 1) {
4527
+ await new Promise((resolve) => setTimeout(resolve, SEND_SETTLE_POLL_MS));
4528
+ status = await readResponseStatus(ctx, id);
4529
+ }
4530
+ return status;
4531
+ }
4532
+ async function readResponseStatus(ctx, id) {
4533
+ const row = await getOptional(ctx, "generated-response", id);
4534
+ if (!row) return "sent";
4535
+ const raw = row.data.status;
4536
+ return isGeneratedResponseStatus(raw) ? raw : null;
4446
4537
  }
4447
4538
  var ANCHOR_LOOKUP_LIMIT = 100;
4448
4539
  function toDate2(raw) {
@@ -4514,6 +4605,15 @@ async function openFollowupResponse(ctx, input) {
4514
4605
  channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
4515
4606
  generatedAt,
4516
4607
  expiresAt: new Date(generatedAt.getTime() + settings.responseTtlMinutes * 6e4),
4608
+ // Stamped HERE, not only when `process-response` finishes with the row:
4609
+ // until it exists the draft contributes nothing to §6's anchor, so a
4610
+ // webhook redelivered while it is still `pending` would read "no anchor
4611
+ // to beat" at G8 and draft the very same message all over again.
4612
+ //
4613
+ // Withheld from the operator's essay for the reason §8 keeps it out of
4614
+ // the lifecycle entirely: raising the anchor there would make the REAL
4615
+ // reply to that same message impossible ever after.
4616
+ ...input.generateOnly ? {} : { generatedMessageCount: conversation.messageCount, generatedLastMessageAt: conversation.lastMessageAt },
4517
4617
  sources: [],
4518
4618
  tracedInput: [],
4519
4619
  guardrailHits: [],
@@ -4529,12 +4629,7 @@ async function openFollowupResponse(ctx, input) {
4529
4629
  }
4530
4630
  }
4531
4631
  function unresolvedCategory() {
4532
- return {
4533
- gate: "G7",
4534
- label: "Cat\xE9gorie r\xE9solue et opt\xE9e",
4535
- status: "stopped",
4536
- detail: "Aucune cat\xE9gorie r\xE9solue."
4537
- };
4632
+ return stopped("G7", "Aucune cat\xE9gorie r\xE9solue.");
4538
4633
  }
4539
4634
  function stopAt(ctx, ticketId, result, ladder, kind = "gate") {
4540
4635
  return stop(ctx, ticketId, `${result.gate}${kind === "gate" ? "" : ` (${kind})`}`, result.detail, ladder);
@@ -4603,7 +4698,7 @@ async function diagnose(ctx, ticketId) {
4603
4698
  const scope = evaluateScopeGate(settings);
4604
4699
  gates.push(scope);
4605
4700
  if (scope.status === "stopped") return finish(gates, ticketId);
4606
- const { anchor } = await readFollowupAnchor(ctx, ticketId);
4701
+ const { anchor, openResponse } = await readFollowupAnchor(ctx, ticketId);
4607
4702
  const categories = await listCategories(ctx.api);
4608
4703
  const ref = { id: ticketId, channel: "gorgias" };
4609
4704
  const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
@@ -4611,8 +4706,26 @@ async function diagnose(ctx, ticketId) {
4611
4706
  const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
4612
4707
  const trace = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
4613
4708
  gates.push(...trace.results);
4709
+ if (!trace.stop) gates.push(predictPreemption(openResponse));
4614
4710
  return finish(gates, ticketId);
4615
4711
  }
4712
+ function predictPreemption(openResponse) {
4713
+ if (!openResponse) return passed("G9", "Aucune r\xE9ponse ouverte sur ce ticket.");
4714
+ const { status } = openResponse;
4715
+ if (status === null) {
4716
+ return stopped("G9", "Une r\xE9ponse ouverte porte un statut illisible : elle doit \xEAtre d\xE9bloqu\xE9e \xE0 la main.");
4717
+ }
4718
+ if (status === "sending") {
4719
+ return passed("G9", "Une r\xE9ponse est en cours d'envoi : le passage attendrait qu'elle se termine.");
4720
+ }
4721
+ if (isTerminalStatus(status)) {
4722
+ return passed("G9", "La r\xE9ponse ouverte est d\xE9j\xE0 termin\xE9e : le ticket est libre.");
4723
+ }
4724
+ if (!canTransition(status, "superseded")) {
4725
+ return stopped("G9", `Une r\xE9ponse au statut \xAB ${status} \xBB tient le ticket et ne peut pas \xEAtre remplac\xE9e.`);
4726
+ }
4727
+ return passed("G9", `Une r\xE9ponse ouverte (${status}) serait remplac\xE9e.`);
4728
+ }
4616
4729
  function finish(gates, ticketId) {
4617
4730
  const full = completeFollowupLadder(gates);
4618
4731
  return {