Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬

feat: verify customer email before Captain uses sensitive tools [PR-3] (#16230)

Shivam Mishra292d8756eff6
diff --git a/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CreateCustomToolDialog.vue b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CreateCustomToolDialog.vue
index 5362226dd1c..83a2b6eac82 100644
--- a/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CreateCustomToolDialog.vue
+++ b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CreateCustomToolDialog.vue
@@ -9,6 +9,7 @@ import { parseAPIErrorResponse } from 'dashboard/store/utils/api';
import SidePanel from 'dashboard/components-next/side-panel/SidePanel.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import CustomToolForm from './CustomToolForm.vue';
+import CustomToolDetails from './CustomToolDetails.vue';
const props = defineProps({
selectedTool: {
@@ -85,11 +86,19 @@ defineExpose({ dialogRef });
<SidePanel
ref="dialogRef"
width="2xl"
- :title="$t(`${i18nKey}.TITLE`)"
- :description="$t('CAPTAIN.CUSTOM_TOOLS.FORM_DESCRIPTION')"
+ :title="type === 'view' ? selectedTool.title : $t(`${i18nKey}.TITLE`)"
+ :description="
+ type === 'view' ? '' : $t('CAPTAIN.CUSTOM_TOOLS.FORM_DESCRIPTION')
+ "
@after-leave="handleClose"
>
- <CustomToolForm :mode="type" :tool="selectedTool" @submit="handleSubmit" />
+ <CustomToolDetails v-if="type === 'view'" :tool="selectedTool" />
+ <CustomToolForm
+ v-else
+ :mode="type"
+ :tool="selectedTool"
+ @submit="handleSubmit"
+ />
<template #footer>
<div class="flex gap-3 justify-end">
<Button
diff --git a/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CustomToolDetails.vue b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CustomToolDetails.vue
new file mode 100644
index 00000000000..41b843283c2
--- /dev/null
+++ b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CustomToolDetails.vue
@@ -0,0 +1,258 @@
+<script setup>
+import { computed, ref, watch } from 'vue';
+import { useRoute } from 'vue-router';
+import { useI18n } from 'vue-i18n';
+import { useStore } from 'dashboard/composables/store';
+import { useAlert } from 'dashboard/composables';
+import { useAdmin } from 'dashboard/composables/useAdmin';
+import { parseAPIErrorResponse } from 'dashboard/store/utils/api';
+
+import Switch from 'dashboard/components-next/switch/Switch.vue';
+import ToolFormSection from './ToolFormSection.vue';
+
+const props = defineProps({
+ tool: {
+ type: Object,
+ required: true,
+ },
+});
+
+const { t } = useI18n();
+const route = useRoute();
+const store = useStore();
+const { isAdmin } = useAdmin();
+
+const authTypeLabel = computed(
+ () =>
+ ({
+ bearer: t('CAPTAIN.CUSTOM_TOOLS.FORM.AUTH_TYPES.BEARER'),
+ basic: t('CAPTAIN.CUSTOM_TOOLS.FORM.AUTH_TYPES.BASIC'),
+ api_key: t('CAPTAIN.CUSTOM_TOOLS.FORM.AUTH_TYPES.API_KEY'),
+ })[props.tool.auth_type] || t('CAPTAIN.CUSTOM_TOOLS.FORM.AUTH_TYPES.NONE')
+);
+
+const paramTypeLabels = computed(() => ({
+ string: t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAM_TYPES.STRING'),
+ number: t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAM_TYPES.NUMBER'),
+ boolean: t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAM_TYPES.BOOLEAN'),
+ array: t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAM_TYPES.ARRAY'),
+ object: t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAM_TYPES.OBJECT'),
+}));
+
+const params = computed(() => props.tool.param_schema || []);
+const headers = computed(() => Object.entries(props.tool.headers || {}));
+const hasRequestBody = computed(() => props.tool.http_method !== 'GET');
+const showRequest = ref(false);
+const usesVerifiedEmail = computed(() =>
+ params.value.some(param => param.source === 'verified.email')
+);
+
+// Admins can change email verification on an installed tool. It saves as soon as it changes.
+const canChangeVerification = computed(
+ () =>
+ isAdmin.value && !!props.tool.source_metadata && !usesVerifiedEmail.value
+);
+
+const verificationSetting = ref(false);
+const isSaving = ref(false);
+watch(
+ () => props.tool.settings?.requires_email_verification,
+ value => {
+ verificationSetting.value = value === true;
+ },
+ { immediate: true }
+);
+
+const saveVerification = async value => {
+ isSaving.value = true;
+ try {
+ await store.dispatch('captainCustomTools/update', {
+ id: props.tool.id,
+ settings: { requires_email_verification: value },
+ assistantId: route.params.assistantId,
+ });
+ useAlert(t('CAPTAIN.CUSTOM_TOOLS.EDIT.SUCCESS_MESSAGE'));
+ } catch (error) {
+ verificationSetting.value = !value;
+ useAlert(
+ parseAPIErrorResponse(error) ||
+ t('CAPTAIN.CUSTOM_TOOLS.EDIT.ERROR_MESSAGE')
+ );
+ } finally {
+ isSaving.value = false;
+ }
+};
+
+const requiresEmailVerification = computed({
+ get: () => usesVerifiedEmail.value || verificationSetting.value,
+ set: value => {
+ verificationSetting.value = value;
+ saveVerification(value);
+ },
+});
+</script>
+
+<template>
+ <div class="flex flex-col gap-6">
+ <div class="flex flex-col gap-2">
+ <p v-if="tool.description" class="mb-0 text-sm text-n-slate-12">
+ {{ tool.description }}
+ </p>
+ <p
+ v-if="tool.source_metadata"
+ class="flex items-center gap-1.5 mb-0 text-xs text-n-slate-11"
+ >
+ <i class="i-lucide-lock size-3 shrink-0" />
+ {{ t('CAPTAIN.CUSTOM_TOOLS.VIEW.INSTALLED_NOTE') }}
+ </p>
+ </div>
+
+ <label
+ class="flex items-start justify-between gap-3 px-4 py-3 rounded-xl outline outline-1 outline-n-weak"
+ >
+ <span class="flex flex-col gap-0.5">
+ <span class="text-sm font-medium text-n-slate-12">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.EMAIL_VERIFICATION.LABEL') }}
+ </span>
+ <span class="text-sm text-n-slate-11">
+ {{
+ usesVerifiedEmail
+ ? t('CAPTAIN.CUSTOM_TOOLS.FORM.EMAIL_VERIFICATION.IMPLIED')
+ : t('CAPTAIN.CUSTOM_TOOLS.FORM.EMAIL_VERIFICATION.DESCRIPTION')
+ }}
+ </span>
+ </span>
+ <Switch
+ v-model="requiresEmailVerification"
+ :disabled="!canChangeVerification || isSaving"
+ class="shrink-0"
+ />
+ </label>
+
+ <section class="flex flex-col gap-2">
+ <h4 class="text-sm font-medium text-n-slate-12">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.AUTH_TYPE.LABEL') }}
+ </h4>
+ <div
+ class="flex items-center gap-2 px-4 py-3 text-sm rounded-xl outline outline-1 outline-n-weak text-n-slate-12"
+ >
+ <i class="i-lucide-key-round size-3.5 shrink-0 text-n-slate-11" />
+ {{ authTypeLabel }}
+ </div>
+ </section>
+
+ <section v-if="params.length" class="flex flex-col gap-2">
+ <h4 class="text-sm font-medium text-n-slate-12">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAMETERS.LABEL') }}
+ </h4>
+ <ul
+ class="m-0 list-none divide-y rounded-xl outline outline-1 outline-n-weak divide-n-weak"
+ >
+ <li
+ v-for="param in params"
+ :key="param.name"
+ class="flex flex-col gap-1 px-4 py-3"
+ >
+ <div class="flex flex-wrap items-center gap-2">
+ <code class="text-sm font-medium font-mono text-n-slate-12">
+ {{ param.name }}
+ </code>
+ <span v-if="param.source" class="text-xs text-n-slate-11">
+ <i class="i-lucide-lock size-3 align-[-0.125rem]" />
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.VERIFIED_VALUES.EMAIL') }}
+ </span>
+ <template v-else>
+ <span class="text-xs text-n-slate-11">
+ {{ paramTypeLabels[param.type] }}
+ </span>
+ <span v-if="param.required" class="text-xs text-n-slate-10">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAM_REQUIRED.LABEL') }}
+ </span>
+ </template>
+ </div>
+ <p
+ v-if="param.source || param.description"
+ class="mb-0 text-xs text-n-slate-11"
+ >
+ {{
+ param.source
+ ? t('CAPTAIN.CUSTOM_TOOLS.FORM.VERIFIED_VALUES.HELP')
+ : param.description
+ }}
+ </p>
+ </li>
+ </ul>
+ </section>
+
+ <ToolFormSection
+ v-model:open="showRequest"
+ :title="t('CAPTAIN.CUSTOM_TOOLS.VIEW.REQUEST')"
+ class="border-b"
+ >
+ <div class="flex flex-col gap-1.5">
+ <span class="text-xs font-medium text-n-slate-11">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.ENDPOINT_URL.LABEL') }}
+ </span>
+ <div
+ dir="ltr"
+ class="flex items-start gap-2 p-3 rounded-lg bg-n-alpha-black2"
+ >
+ <span
+ class="px-1.5 text-xs font-medium leading-5 rounded shrink-0 font-mono bg-n-alpha-2 text-n-slate-12"
+ >
+ {{ tool.http_method }}
+ </span>
+ <code
+ class="min-w-0 text-xs leading-5 break-words font-mono text-n-slate-12"
+ >
+ {{ tool.endpoint_url }}
+ </code>
+ </div>
+ </div>
+
+ <div v-if="headers.length" class="flex flex-col gap-1.5">
+ <span class="text-xs font-medium text-n-slate-11">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.HEADERS.LABEL') }}
+ </span>
+ <ul
+ dir="ltr"
+ class="m-0 list-none divide-y rounded-lg outline outline-1 outline-n-weak divide-n-weak"
+ >
+ <li
+ v-for="[name, value] in headers"
+ :key="name"
+ class="grid grid-cols-3 gap-3 px-3 py-2 text-xs font-mono"
+ >
+ <span class="break-words text-n-slate-11">{{ name }}</span>
+ <span class="col-span-2 min-w-0 break-words text-n-slate-12">
+ {{ value }}
+ </span>
+ </li>
+ </ul>
+ </div>
+
+ <div
+ v-if="hasRequestBody && tool.request_template"
+ class="flex flex-col gap-1.5"
+ >
+ <span class="text-xs font-medium text-n-slate-11">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.REQUEST_TEMPLATE.LABEL') }}
+ </span>
+ <pre
+ dir="ltr"
+ class="p-3 m-0 text-xs leading-5 whitespace-pre-wrap break-words rounded-lg font-mono bg-n-alpha-black2 text-n-slate-12"
+ ><code>{{ tool.request_template }}</code></pre>
+ </div>
+
+ <div v-if="tool.response_template" class="flex flex-col gap-1.5">
+ <span class="text-xs font-medium text-n-slate-11">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.RESPONSE_TEMPLATE.LABEL') }}
+ </span>
+ <pre
+ dir="ltr"
+ class="p-3 m-0 text-xs leading-5 whitespace-pre-wrap break-words rounded-lg font-mono bg-n-alpha-black2 text-n-slate-12"
+ ><code>{{ tool.response_template }}</code></pre>
+ </div>
+ </ToolFormSection>
+ </div>
+</template>
diff --git a/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CustomToolForm.vue b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CustomToolForm.vue
index 553715e3967..4927a53d249 100644
--- a/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CustomToolForm.vue
+++ b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/CustomToolForm.vue
@@ -10,16 +10,20 @@ import Input from 'dashboard/components-next/input/Input.vue';
import TextArea from 'dashboard/components-next/textarea/TextArea.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import ComboBox from 'dashboard/components-next/combobox/ComboBox.vue';
+import Switch from 'dashboard/components-next/switch/Switch.vue';
+import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
import ParamRow from './ParamRow.vue';
+import VerifiedParamRow from './VerifiedParamRow.vue';
import AuthConfig from './AuthConfig.vue';
import HeadersConfig from './HeadersConfig.vue';
import ToolFormSection from './ToolFormSection.vue';
+import { toolRiskLevel, isEmailLikeParam, RISK_LEVELS } from './toolRisk';
const props = defineProps({
mode: {
type: String,
default: 'create',
- validator: value => ['create', 'edit', 'view'].includes(value),
+ validator: value => ['create', 'edit'].includes(value),
},
tool: {
type: Object,
@@ -43,18 +47,19 @@ const initialState = {
auth_config: {},
headers: {},
param_schema: [],
+ settings: { requires_email_verification: false },
};
-const state = reactive({ ...initialState });
-
-// Tools installed from a manifest are shown read-only
-const isReadOnly = computed(() => props.mode === 'view');
+const state = reactive({
+ ...initialState,
+ settings: { ...initialState.settings },
+});
-// Populate form when editing or viewing an existing tool
+// Populate form when editing an existing tool
watch(
() => props.tool,
newTool => {
- if (props.mode !== 'create' && newTool && newTool.id) {
+ if (props.mode === 'edit' && newTool && newTool.id) {
state.title = newTool.title || '';
state.description = newTool.description || '';
state.endpoint_url = newTool.endpoint_url || '';
@@ -65,11 +70,25 @@ watch(
state.auth_config = newTool.auth_config || {};
state.headers = newTool.headers || {};
state.param_schema = newTool.param_schema || [];
+ state.settings = { ...initialState.settings, ...newTool.settings };
}
},
{ immediate: true }
);
+// A parameter that takes the verified email means the tool cannot run without one
+const usesVerifiedEmail = computed(() =>
+ state.param_schema.some(param => param.source === 'verified.email')
+);
+
+const requiresEmailVerification = computed({
+ get: () =>
+ usesVerifiedEmail.value || state.settings.requires_email_verification,
+ set: value => {
+ state.settings.requires_email_verification = value;
+ },
+});
+
const DEFAULT_PARAM = {
name: '',
type: 'string',
@@ -104,11 +123,10 @@ const authTypeOptions = computed(() => [
},
]);
-// Read-only section headers can't be clicked, so view mode starts with every section open
const openSections = reactive({
- headers: isReadOnly.value,
- params: isReadOnly.value,
- templates: isReadOnly.value,
+ headers: false,
+ params: false,
+ templates: false,
});
const sectionSummaries = computed(() => {
@@ -159,6 +177,42 @@ const addParam = () => {
state.param_schema.push({ ...DEFAULT_PARAM });
};
+// Chatwoot fills this from the email the customer verified. Captain sees the description only where a team member is the user.
+// Advice only. Saving a tool that looks like it handles customer data asks once whether to require verification.
+const riskDialogRef = useTemplateRef('riskDialogRef');
+const riskLevel = computed(() =>
+ requiresEmailVerification.value ? RISK_LEVELS.NONE : toolRiskLevel(state)
+);
+const riskMessage = computed(() =>
+ riskLevel.value === RISK_LEVELS.HIGH
+ ? t('CAPTAIN.CUSTOM_TOOLS.FORM.RISK.HIGH')
+ : t('CAPTAIN.CUSTOM_TOOLS.FORM.RISK.MEDIUM')
+);
+
+const suggestsVerifiedEmail = param =>
+ !usesVerifiedEmail.value && isEmailLikeParam(param);
+
+// Keeps the name and description, so templates that read the parameter keep working
+const useVerifiedEmail = param => {
+ Object.assign(param, {
+ type: 'string',
+ required: true,
+ source: 'verified.email',
+ });
+};
+
+const addVerifiedEmailParam = () => {
+ state.param_schema.push({
+ name: 'email',
+ type: 'string',
+ description: t(
+ 'CAPTAIN.CUSTOM_TOOLS.FORM.VERIFIED_VALUES.EMAIL_DESCRIPTION'
+ ),
+ required: true,
+ source: 'verified.email',
+ });
+};
+
const handleSubmit = async () => {
const isFormValid = await v$.value.$validate();
const isHeadersValid = headersRef.value.validate();
@@ -168,10 +222,19 @@ const handleSubmit = async () => {
if (!isFormValid || !areParamsValid || !isHeadersValid) {
return;
}
+ if (riskLevel.value !== RISK_LEVELS.NONE) {
+ riskDialogRef.value.open();
+ return;
+ }
emit('submit', state);
};
+const saveDespiteRisk = () => {
+ riskDialogRef.value.close();
+ emit('submit', state);
+};
+
const isTesting = ref(false);
const testResult = ref(null);
const isTestDisabled = computed(
@@ -211,90 +274,117 @@ const handleTest = async () => {
class="flex flex-col gap-4"
@submit.prevent="handleSubmit"
>
- <!-- Disables every field and button inside for read-only (view) mode; contents keeps the form's layout -->
- <fieldset :disabled="isReadOnly" class="contents">
- <Input
- v-model="state.title"
- :label="t('CAPTAIN.CUSTOM_TOOLS.FORM.TITLE.LABEL')"
- :placeholder="t('CAPTAIN.CUSTOM_TOOLS.FORM.TITLE.PLACEHOLDER')"
- :message="formErrors.title"
- :message-type="formErrors.title ? 'error' : 'info'"
- />
-
- <TextArea
- v-model="state.description"
- :label="t('CAPTAIN.CUSTOM_TOOLS.FORM.DESCRIPTION.LABEL')"
- :placeholder="t('CAPTAIN.CUSTOM_TOOLS.FORM.DESCRIPTION.PLACEHOLDER')"
- auto-height
- min-height="2.5rem"
- />
-
- <div class="flex gap-2">
- <div class="flex flex-col gap-1 w-32">
- <label class="mb-0.5 text-sm font-medium text-n-slate-12">
- {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.HTTP_METHOD.LABEL') }}
- </label>
- <ComboBox
- v-model="state.http_method"
- :options="httpMethodOptions"
- class="[&>div>button]:bg-n-alpha-black2 [&_li]:font-mono [&_button]:font-mono [&>div>button]:outline-offset-[-1px]"
- />
- </div>
- <Input
- v-model="state.endpoint_url"
- :label="t('CAPTAIN.CUSTOM_TOOLS.FORM.ENDPOINT_URL.LABEL')"
- :placeholder="t('CAPTAIN.CUSTOM_TOOLS.FORM.ENDPOINT_URL.PLACEHOLDER')"
- :message="formErrors.endpoint_url"
- :message-type="formErrors.endpoint_url ? 'error' : 'info'"
- class="flex-1"
- />
- </div>
-
- <div class="flex flex-col gap-1">
+ <Input
+ v-model="state.title"
+ :label="t('CAPTAIN.CUSTOM_TOOLS.FORM.TITLE.LABEL')"
+ :placeholder="t('CAPTAIN.CUSTOM_TOOLS.FORM.TITLE.PLACEHOLDER')"
+ :message="formErrors.title"
+ :message-type="formErrors.title ? 'error' : 'info'"
+ />
+
+ <TextArea
+ v-model="state.description"
+ :label="t('CAPTAIN.CUSTOM_TOOLS.FORM.DESCRIPTION.LABEL')"
+ :placeholder="t('CAPTAIN.CUSTOM_TOOLS.FORM.DESCRIPTION.PLACEHOLDER')"
+ auto-height
+ min-height="2.5rem"
+ />
+
+ <div class="flex gap-2">
+ <div class="flex flex-col gap-1 w-32">
<label class="mb-0.5 text-sm font-medium text-n-slate-12">
- {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.AUTH_TYPE.LABEL') }}
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.HTTP_METHOD.LABEL') }}
</label>
<ComboBox
- v-model="state.auth_type"
- :options="authTypeOptions"
- class="[&>div>button]:bg-n-alpha-black2"
+ v-model="state.http_method"
+ :options="httpMethodOptions"
+ class="[&>div>button]:bg-n-alpha-black2 [&_li]:font-mono [&_button]:font-mono [&>div>button]:outline-offset-[-1px]"
/>
</div>
-
- <AuthConfig
- v-model:auth-config="state.auth_config"
- :auth-type="state.auth_type"
+ <Input
+ v-model="state.endpoint_url"
+ :label="t('CAPTAIN.CUSTOM_TOOLS.FORM.ENDPOINT_URL.LABEL')"
+ :placeholder="t('CAPTAIN.CUSTOM_TOOLS.FORM.ENDPOINT_URL.PLACEHOLDER')"
+ :message="formErrors.endpoint_url"
+ :message-type="formErrors.endpoint_url ? 'error' : 'info'"
+ class="flex-1"
/>
-
- <div class="flex flex-col">
- <ToolFormSection
- v-model:open="openSections.headers"
- :title="t('CAPTAIN.CUSTOM_TOOLS.FORM.HEADERS.LABEL')"
- :summary="sectionSummaries.headers"
- >
- <HeadersConfig ref="headersRef" v-model:headers="state.headers" />
- </ToolFormSection>
-
- <ToolFormSection
- v-model:open="openSections.params"
- :title="t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAMETERS.LABEL')"
- :summary="sectionSummaries.params"
- >
- <p class="text-xs text-n-slate-11">
- {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAMETERS.HELP_TEXT') }}
- </p>
- <ul v-if="state.param_schema.length > 0" class="grid gap-2 list-none">
+ </div>
+
+ <div class="flex flex-col gap-1">
+ <label class="mb-0.5 text-sm font-medium text-n-slate-12">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.AUTH_TYPE.LABEL') }}
+ </label>
+ <ComboBox
+ v-model="state.auth_type"
+ :options="authTypeOptions"
+ class="[&>div>button]:bg-n-alpha-black2"
+ />
+ </div>
+
+ <AuthConfig
+ v-model:auth-config="state.auth_config"
+ :auth-type="state.auth_type"
+ />
+
+ <label class="flex items-start justify-between gap-3">
+ <span class="flex flex-col gap-0.5">
+ <span class="text-sm font-medium text-n-slate-12">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.EMAIL_VERIFICATION.LABEL') }}
+ </span>
+ <span class="text-sm text-n-slate-11">
+ {{
+ usesVerifiedEmail
+ ? t('CAPTAIN.CUSTOM_TOOLS.FORM.EMAIL_VERIFICATION.IMPLIED')
+ : t('CAPTAIN.CUSTOM_TOOLS.FORM.EMAIL_VERIFICATION.DESCRIPTION')
+ }}
+ </span>
+ </span>
+ <Switch
+ v-model="requiresEmailVerification"
+ :disabled="usesVerifiedEmail"
+ class="shrink-0"
+ />
+ </label>
+ <div class="flex flex-col">
+ <ToolFormSection
+ v-model:open="openSections.headers"
+ :title="t('CAPTAIN.CUSTOM_TOOLS.FORM.HEADERS.LABEL')"
+ :summary="sectionSummaries.headers"
+ >
+ <HeadersConfig ref="headersRef" v-model:headers="state.headers" />
+ </ToolFormSection>
+
+ <ToolFormSection
+ v-model:open="openSections.params"
+ :title="t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAMETERS.LABEL')"
+ :summary="sectionSummaries.params"
+ >
+ <p class="text-xs text-n-slate-11">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAMETERS.HELP_TEXT') }}
+ </p>
+ <ul v-if="state.param_schema.length > 0" class="grid gap-2 list-none">
+ <template v-for="(param, index) in state.param_schema" :key="index">
+ <VerifiedParamRow
+ v-if="param.source"
+ ref="paramsRef"
+ v-model:name="param.name"
+ @remove="removeParam(index)"
+ />
<ParamRow
- v-for="(param, index) in state.param_schema"
- :key="index"
+ v-else
ref="paramsRef"
v-model:name="param.name"
v-model:type="param.type"
v-model:description="param.description"
v-model:required="param.required"
+ :suggest-verified-email="suggestsVerifiedEmail(param)"
@remove="removeParam(index)"
+ @use-verified-email="useVerifiedEmail(param)"
/>
- </ul>
+ </template>
+ </ul>
+ <div class="flex items-center gap-2">
<Button
type="button"
sm
@@ -304,85 +394,105 @@ const handleTest = async () => {
:label="t('CAPTAIN.CUSTOM_TOOLS.FORM.ADD_PARAMETER')"
@click="addParam"
/>
- </ToolFormSection>
+ <Button
+ v-if="!usesVerifiedEmail"
+ type="button"
+ sm
+ ghost
+ blue
+ icon="i-lucide-mail-check"
+ :label="t('CAPTAIN.CUSTOM_TOOLS.FORM.VERIFIED_VALUES.ADD')"
+ @click="addVerifiedEmailParam"
+ />
+ </div>
+ </ToolFormSection>
+
+ <ToolFormSection
+ v-model:open="openSections.templates"
+ :title="
+ hasRequestBody
+ ? t('CAPTAIN.CUSTOM_TOOLS.FORM.SECTIONS.TEMPLATES')
+ : t('CAPTAIN.CUSTOM_TOOLS.FORM.RESPONSE_TEMPLATE.LABEL')
+ "
+ class="border-b"
+ >
+ <p class="text-xs text-n-slate-11">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.SECTIONS.TEMPLATES_HELP_TEXT') }}
+ </p>
+ <TextArea
+ v-if="hasRequestBody"
+ v-model="state.request_template"
+ :label="t('CAPTAIN.CUSTOM_TOOLS.FORM.REQUEST_TEMPLATE.LABEL')"
+ :placeholder="
+ t('CAPTAIN.CUSTOM_TOOLS.FORM.REQUEST_TEMPLATE.PLACEHOLDER')
+ "
+ :rows="4"
+ class="[&_textarea]:font-mono"
+ />
- <ToolFormSection
- v-model:open="openSections.templates"
- :title="
+ <TextArea
+ v-model="state.response_template"
+ :label="
hasRequestBody
- ? t('CAPTAIN.CUSTOM_TOOLS.FORM.SECTIONS.TEMPLATES')
- : t('CAPTAIN.CUSTOM_TOOLS.FORM.RESPONSE_TEMPLATE.LABEL')
+ ? t('CAPTAIN.CUSTOM_TOOLS.FORM.RESPONSE_TEMPLATE.LABEL')
+ : ''
"
- class="border-b"
- >
- <p class="text-xs text-n-slate-11">
- {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.SECTIONS.TEMPLATES_HELP_TEXT') }}
- </p>
- <TextArea
- v-if="hasRequestBody"
- v-model="state.request_template"
- :label="t('CAPTAIN.CUSTOM_TOOLS.FORM.REQUEST_TEMPLATE.LABEL')"
- :placeholder="
- t('CAPTAIN.CUSTOM_TOOLS.FORM.REQUEST_TEMPLATE.PLACEHOLDER')
- "
- :rows="4"
- class="[&_textarea]:font-mono"
- />
-
- <TextArea
- v-model="state.response_template"
- :label="
- hasRequestBody
- ? t('CAPTAIN.CUSTOM_TOOLS.FORM.RESPONSE_TEMPLATE.LABEL')
- : ''
- "
- :placeholder="
- t('CAPTAIN.CUSTOM_TOOLS.FORM.RESPONSE_TEMPLATE.PLACEHOLDER')
- "
- :rows="4"
- class="[&_textarea]:font-mono"
- />
- </ToolFormSection>
- </div>
-
- <div class="flex flex-col gap-2">
- <Button
- type="button"
- variant="faded"
- color="slate"
- icon="i-lucide-play"
- :label="t('CAPTAIN.CUSTOM_TOOLS.TEST.BUTTON')"
- :is-loading="isTesting"
- :disabled="isTesting || !state.endpoint_url || isTestDisabled"
- @click="handleTest"
+ :placeholder="
+ t('CAPTAIN.CUSTOM_TOOLS.FORM.RESPONSE_TEMPLATE.PLACEHOLDER')
+ "
+ :rows="4"
+ class="[&_textarea]:font-mono"
/>
- <p v-if="isTestDisabled" class="text-xs text-n-slate-11">
- {{ t('CAPTAIN.CUSTOM_TOOLS.TEST.DISABLED_HINT') }}
- </p>
- <div
- v-if="testResult"
- class="flex items-center gap-2 px-3 py-2 text-xs rounded-lg"
+ </ToolFormSection>
+ </div>
+
+ <div class="flex flex-col gap-2">
+ <Button
+ type="button"
+ variant="faded"
+ color="slate"
+ icon="i-lucide-play"
+ :label="t('CAPTAIN.CUSTOM_TOOLS.TEST.BUTTON')"
+ :is-loading="isTesting"
+ :disabled="isTesting || !state.endpoint_url || isTestDisabled"
+ @click="handleTest"
+ />
+ <p v-if="isTestDisabled" class="text-xs text-n-slate-11">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.TEST.DISABLED_HINT') }}
+ </p>
+ <div
+ v-if="testResult"
+ class="flex items-center gap-2 px-3 py-2 text-xs rounded-lg"
+ :class="
+ testResult.success
+ ? 'bg-n-teal-2 text-n-teal-11'
+ : 'bg-n-ruby-2 text-n-ruby-11'
+ "
+ >
+ <span
:class="
- testResult.success
- ? 'bg-n-teal-2 text-n-teal-11'
- : 'bg-n-ruby-2 text-n-ruby-11'
+ testResult.success ? 'i-lucide-check-circle' : 'i-lucide-x-circle'
"
- >
- <span
- :class="
- testResult.success ? 'i-lucide-check-circle' : 'i-lucide-x-circle'
- "
- class="size-3.5 shrink-0"
- />
- {{
- testResult.status
- ? t('CAPTAIN.CUSTOM_TOOLS.TEST.SUCCESS', {
- status: testResult.status,
- })
- : testResult.message
- }}
- </div>
+ class="size-3.5 shrink-0"
+ />
+ {{
+ testResult.status
+ ? t('CAPTAIN.CUSTOM_TOOLS.TEST.SUCCESS', {
+ status: testResult.status,
+ })
+ : testResult.message
+ }}
</div>
- </fieldset>
+ </div>
+ <Dialog
+ ref="riskDialogRef"
+ type="alert"
+ width="md"
+ :title="t('CAPTAIN.CUSTOM_TOOLS.FORM.RISK.TITLE')"
+ :description="riskMessage"
+ :cancel-button-label="t('CAPTAIN.CUSTOM_TOOLS.FORM.RISK.GO_BACK')"
+ :confirm-button-label="t('CAPTAIN.CUSTOM_TOOLS.FORM.RISK.SAVE_ANYWAY')"
+ @confirm="saveDespiteRisk"
+ />
</form>
</template>
diff --git a/app/javascript/dashboard/components-next/captain/pageComponents/customTool/ParamRow.vue b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/ParamRow.vue
index 469a90927f6..b7defc095ed 100644
--- a/app/javascript/dashboard/components-next/captain/pageComponents/customTool/ParamRow.vue
+++ b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/ParamRow.vue
@@ -6,7 +6,14 @@ import Input from 'dashboard/components-next/input/Input.vue';
import ComboBox from 'dashboard/components-next/combobox/ComboBox.vue';
import Checkbox from 'dashboard/components-next/checkbox/Checkbox.vue';
-const emit = defineEmits(['remove']);
+defineProps({
+ suggestVerifiedEmail: {
+ type: Boolean,
+ default: false,
+ },
+});
+
+const emit = defineEmits(['remove', 'useVerifiedEmail']);
const { t } = useI18n();
const showErrors = ref(false);
@@ -104,6 +111,19 @@ defineExpose({ validate });
/>
</div>
</div>
+ <p
+ v-if="suggestVerifiedEmail"
+ class="flex flex-wrap items-center gap-1 mt-1 mb-0 text-sm text-n-amber-11"
+ >
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.RISK.EMAIL_PARAM') }}
+ <Button
+ type="button"
+ link
+ xs
+ :label="t('CAPTAIN.CUSTOM_TOOLS.FORM.RISK.USE_VERIFIED_EMAIL')"
+ @click="emit('useVerifiedEmail')"
+ />
+ </p>
<span
v-if="showErrors && validationError"
class="block mt-1 text-sm text-n-ruby-11"
diff --git a/app/javascript/dashboard/components-next/captain/pageComponents/customTool/VerifiedParamRow.vue b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/VerifiedParamRow.vue
new file mode 100644
index 00000000000..f7f013e44e9
--- /dev/null
+++ b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/VerifiedParamRow.vue
@@ -0,0 +1,74 @@
+<script setup>
+import { computed, ref, watch } from 'vue';
+import { useI18n } from 'vue-i18n';
+import Button from 'dashboard/components-next/button/Button.vue';
+import Input from 'dashboard/components-next/input/Input.vue';
+
+const emit = defineEmits(['remove']);
+const { t } = useI18n();
+const showErrors = ref(false);
+
+const name = defineModel('name', {
+ type: String,
+ required: true,
+});
+
+const isNameMissing = computed(() => !name.value || name.value.trim() === '');
+
+watch(name, () => {
+ showErrors.value = false;
+});
+
+const validate = () => {
+ showErrors.value = true;
+ return !isNameMissing.value;
+};
+
+defineExpose({ validate });
+</script>
+
+<template>
+ <li class="list-none">
+ <div
+ class="flex flex-col gap-2 p-3 rounded-lg border border-n-weak"
+ :class="{
+ 'animate-wiggle border-n-ruby-9': showErrors && isNameMissing,
+ }"
+ >
+ <div class="grid grid-cols-3 gap-2">
+ <Input
+ v-model="name"
+ :placeholder="t('CAPTAIN.CUSTOM_TOOLS.FORM.PARAM_NAME.PLACEHOLDER')"
+ class="col-span-2 [&_input]:font-mono"
+ />
+ <span
+ class="flex items-center gap-1.5 h-10 px-3 rounded-lg outline outline-1 outline-offset-[-1px] outline-n-weak bg-n-alpha-black2 text-sm text-n-slate-12 min-w-0"
+ >
+ <span class="i-lucide-lock size-3.5 shrink-0 text-n-slate-11" />
+ <span class="truncate">{{
+ t('CAPTAIN.CUSTOM_TOOLS.FORM.VERIFIED_VALUES.EMAIL')
+ }}</span>
+ </span>
+ </div>
+ <div class="flex items-center justify-between gap-2">
+ <span class="text-sm text-n-slate-11">
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.VERIFIED_VALUES.HELP') }}
+ </span>
+ <Button
+ type="button"
+ ghost
+ slate
+ xs
+ icon="i-lucide-trash-2"
+ @click.stop="emit('remove')"
+ />
+ </div>
+ </div>
+ <span
+ v-if="showErrors && isNameMissing"
+ class="block mt-1 text-sm text-n-ruby-11"
+ >
+ {{ t('CAPTAIN.CUSTOM_TOOLS.FORM.ERRORS.PARAM_NAME_REQUIRED') }}
+ </span>
+ </li>
+</template>
diff --git a/app/javascript/dashboard/components-next/captain/pageComponents/customTool/toolRisk.js b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/toolRisk.js
new file mode 100644
index 00000000000..68bb6405b17
--- /dev/null
+++ b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/toolRisk.js
@@ -0,0 +1,125 @@
+// Hints for admins about custom tools that may need email verification. These are advice only and never block a save.
+
+export const RISK_WEIGHTS = {
+ WRITE_METHOD: 10,
+ DELETE_METHOD: 15,
+ CREDENTIALS: 5,
+ EMAIL_PARAM: 5,
+ ID_PARAM: 5,
+ MONEY_WORDS: 5,
+ PERSONAL_DATA_WORDS: 5,
+ PRIVATE_API_HOST: 5,
+};
+
+export const RISK_LEVELS = { NONE: 'none', MEDIUM: 'medium', HIGH: 'high' };
+export const MEDIUM_RISK_SCORE = 10;
+export const HIGH_RISK_SCORE = 15;
+
+const WRITE_METHODS = ['POST', 'PUT', 'PATCH'];
+const ID_WORDS = ['id', 'number', 'account', 'customer', 'order', 'invoice'];
+const MONEY_WORDS = [
+ 'payment',
+ 'payments',
+ 'billing',
+ 'invoice',
+ 'invoices',
+ 'subscription',
+ 'subscriptions',
+ 'charge',
+ 'charges',
+ 'refund',
+ 'refunds',
+ 'card',
+ 'cards',
+ 'plan',
+ 'plans',
+];
+const PERSONAL_DATA_WORDS = [
+ 'customer',
+ 'customers',
+ 'account',
+ 'accounts',
+ 'profile',
+ 'profiles',
+ 'address',
+ 'phone',
+ 'user',
+ 'users',
+ 'contact',
+ 'contacts',
+ 'person',
+ 'people',
+];
+const PRIVATE_API_HOSTS = [
+ 'api.stripe.com',
+ 'api.attio.com',
+ 'api.hubapi.com',
+ 'api.shopify.com',
+];
+
+// Splits text into lowercase words, so "customer_id", "customerId" and "Customer ID" all give "customer" and "id"
+const words = text =>
+ (text || '')
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
+ .toLowerCase()
+ .split(/[^a-z0-9]+/)
+ .filter(Boolean);
+
+const hasAnyWord = (text, list) =>
+ words(text).some(word => list.includes(word));
+
+const modelFilledParams = tool =>
+ (tool.param_schema || []).filter(param => !param.source);
+
+// "email", "customer_email", "customerEmail" and "e_mail" all count, as does a description that mentions an email
+export const isEmailLikeParam = param => {
+ const nameWords = words(param.name);
+ return (
+ nameWords.includes('email') ||
+ nameWords.join('_').includes('e_mail') ||
+ words(param.description).includes('email')
+ );
+};
+
+export const isIdLikeParam = param => hasAnyWord(param.name, ID_WORDS);
+
+const urlHost = url => {
+ try {
+ return new URL(url).host;
+ } catch {
+ return '';
+ }
+};
+
+const hasCredentials = tool =>
+ (tool.auth_type && tool.auth_type !== 'none') ||
+ Object.keys(tool.headers || {}).length > 0;
+
+export const toolRiskScore = tool => {
+ const params = modelFilledParams(tool);
+ const text = [tool.title, tool.description, tool.endpoint_url].join(' ');
+ const signals = [
+ [WRITE_METHODS.includes(tool.http_method), RISK_WEIGHTS.WRITE_METHOD],
+ [tool.http_method === 'DELETE', RISK_WEIGHTS.DELETE_METHOD],
+ [hasCredentials(tool), RISK_WEIGHTS.CREDENTIALS],
+ [params.some(isEmailLikeParam), RISK_WEIGHTS.EMAIL_PARAM],
+ [params.some(isIdLikeParam), RISK_WEIGHTS.ID_PARAM],
+ [hasAnyWord(text, MONEY_WORDS), RISK_WEIGHTS.MONEY_WORDS],
+ [hasAnyWord(text, PERSONAL_DATA_WORDS), RISK_WEIGHTS.PERSONAL_DATA_WORDS],
+ [
+ PRIVATE_API_HOSTS.includes(urlHost(tool.endpoint_url)),
+ RISK_WEIGHTS.PRIVATE_API_HOST,
+ ],
+ ];
+ return signals.reduce(
+ (score, [matches, weight]) => (matches ? score + weight : score),
+ 0
+ );
+};
+
+export const toolRiskLevel = tool => {
+ const score = toolRiskScore(tool);
+ if (score >= HIGH_RISK_SCORE) return RISK_LEVELS.HIGH;
+ if (score >= MEDIUM_RISK_SCORE) return RISK_LEVELS.MEDIUM;
+ return RISK_LEVELS.NONE;
+};
diff --git a/app/javascript/dashboard/components-next/captain/pageComponents/customTool/toolRisk.spec.js b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/toolRisk.spec.js
new file mode 100644
index 00000000000..d467ac1881f
--- /dev/null
+++ b/app/javascript/dashboard/components-next/captain/pageComponents/customTool/toolRisk.spec.js
@@ -0,0 +1,121 @@
+import {
+ toolRiskScore,
+ toolRiskLevel,
+ isEmailLikeParam,
+ isIdLikeParam,
+ RISK_LEVELS,
+} from './toolRisk';
+
+const baseTool = {
+ title: 'Weather',
+ description: 'Current weather for a city',
+ endpoint_url: 'https://weather.example.com/now?city={{ city }}',
+ http_method: 'GET',
+ auth_type: 'none',
+ headers: {},
+ param_schema: [{ name: 'city', type: 'string', description: 'City name' }],
+};
+
+describe('toolRisk', () => {
+ it('gives a public lookup no score', () => {
+ expect(toolRiskScore(baseTool)).toBe(0);
+ expect(toolRiskLevel(baseTool)).toBe(RISK_LEVELS.NONE);
+ });
+
+ it('scores a Stripe lookup by email as high', () => {
+ const tool = {
+ ...baseTool,
+ title: 'Find customer by email',
+ description: 'Looks up a Stripe customer',
+ endpoint_url:
+ 'https://api.stripe.com/v1/customers/search?query={{ email }}',
+ auth_type: 'bearer',
+ param_schema: [
+ { name: 'email', type: 'string', description: 'Customer email' },
+ ],
+ };
+
+ expect(toolRiskScore(tool)).toBe(20);
+ expect(toolRiskLevel(tool)).toBe(RISK_LEVELS.HIGH);
+ });
+
+ it('scores a write with credentials as high', () => {
+ const tool = {
+ ...baseTool,
+ title: 'Create ticket',
+ description: 'Opens a ticket',
+ http_method: 'POST',
+ auth_type: 'api_key',
+ };
+
+ expect(toolRiskScore(tool)).toBe(15);
+ });
+
+ it('scores a delete more than other writes', () => {
+ expect(toolRiskScore({ ...baseTool, http_method: 'DELETE' })).toBe(15);
+ expect(toolRiskScore({ ...baseTool, http_method: 'PATCH' })).toBe(10);
+ });
+
+ it('scores a lookup with credentials and an ID as medium', () => {
+ const tool = {
+ ...baseTool,
+ title: 'Ticket status',
+ description: 'Status of a ticket',
+ headers: { 'X-Api-Key': 'secret' },
+ param_schema: [
+ { name: 'ticket_id', type: 'string', description: 'The ticket' },
+ ],
+ };
+
+ expect(toolRiskScore(tool)).toBe(10);
+ expect(toolRiskLevel(tool)).toBe(RISK_LEVELS.MEDIUM);
+ });
+
+ it('counts each signal once', () => {
+ const tool = {
+ ...baseTool,
+ title: 'Billing invoice payment',
+ description: 'Billing and invoices',
+ };
+
+ expect(toolRiskScore(tool)).toBe(5);
+ });
+
+ it('does not count a parameter that Chatwoot fills from the verified email', () => {
+ const tool = {
+ ...baseTool,
+ param_schema: [
+ {
+ name: 'email',
+ type: 'string',
+ description: 'Email',
+ source: 'verified.email',
+ },
+ ],
+ };
+
+ expect(toolRiskScore(tool)).toBe(0);
+ });
+
+ it('recognises email parameters by name or description', () => {
+ expect(isEmailLikeParam({ name: 'customer_email' })).toBe(true);
+ expect(isEmailLikeParam({ name: 'customerEmail' })).toBe(true);
+ expect(isEmailLikeParam({ name: 'e_mail' })).toBe(true);
+ expect(
+ isEmailLikeParam({
+ name: 'address',
+ description: 'The email of the customer',
+ })
+ ).toBe(true);
+ expect(isEmailLikeParam({ name: 'city', description: 'City name' })).toBe(
+ false
+ );
+ });
+
+ it('recognises ID parameters by name', () => {
+ expect(isIdLikeParam({ name: 'customer_id' })).toBe(true);
+ expect(isIdLikeParam({ name: 'orderNumber' })).toBe(true);
+ expect(isIdLikeParam({ name: 'city' })).toBe(false);
+ expect(isIdLikeParam({ name: 'video' })).toBe(false);
+ });
+});
diff --git a/app/javascript/dashboard/i18n/locale/en/integrations.json b/app/javascript/dashboard/i18n/locale/en/integrations.json
index 45775e2ef94..185f06e8e27 100644
--- a/app/javascript/dashboard/i18n/locale/en/integrations.json
+++ b/app/javascript/dashboard/i18n/locale/en/integrations.json
@@ -1424,7 +1424,9 @@
"ERROR_MESSAGE": "Failed to create custom tool"
},
"VIEW": {
- "TITLE": "Custom Tool Details"
+ "TITLE": "Custom Tool Details",
+ "REQUEST": "Request and response",
+ "INSTALLED_NOTE": "This tool is read-only because it was installed from the Tools Catalog."
},
"EDIT": {
"TITLE": "Edit Custom Tool",
@@ -1478,6 +1480,11 @@
"AUTH_TYPE": {
"LABEL": "Authentication Type"
},
+ "EMAIL_VERIFICATION": {
+ "LABEL": "Require email verification",
+ "DESCRIPTION": "Captain can use this tool only after the customer verifies their email with a one-time code.",
+ "IMPLIED": "A parameter takes the customer's verified email, so email verification is always required."
+ },
"AUTH_TYPES": {
"NONE": "None",
"BEARER": "Bearer Token",
@@ -1533,6 +1540,21 @@
"PARAM_REQUIRED": {
"LABEL": "Required"
},
+ "RISK": {
+ "MEDIUM": "This tool may return customer data. Consider requiring email verification.",
+ "HIGH": "This tool looks like it reads or changes customer data. Require email verification so only a verified customer can use it.",
+ "TITLE": "Save without email verification?",
+ "GO_BACK": "Go back",
+ "SAVE_ANYWAY": "Save anyway",
+ "EMAIL_PARAM": "This email is not verified. A customer could type someone else's.",
+ "USE_VERIFIED_EMAIL": "Use verified email"
+ },
+ "VERIFIED_VALUES": {
+ "ADD": "Add verified email",
+ "EMAIL": "Contact email",
+ "EMAIL_DESCRIPTION": "The contact's verified email address",
+ "HELP": "Filled by Chatwoot from the email the contact confirmed with a one-time code. Captain cannot see or change it in customer conversations."
+ },
"REQUEST_TEMPLATE": {
"LABEL": "Request Body Template (Optional)",
"PLACEHOLDER": "{'{'}\n \"order_id\": \"{'{{'} order_id {'}}'}\"\n{'}'}"
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 798b7b2d0c1..0fa39e91016 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -538,7 +538,7 @@ en:
custom_tool:
slug_generation_failed: 'Unable to generate unique slug after 5 attempts'
limit_exceeded: 'You can create a maximum of %{limit} custom tools per assistant'
- installed_read_only: 'Tools installed from a manifest are read-only; you can only enable or disable them'
+ installed_read_only: 'Tools installed from a manifest are read-only. You can only enable or disable them, or change email verification.'
headers:
invalid: 'must be an object of header names and values'
too_many: 'cannot contain more than %{limit} entries'
diff --git a/enterprise/app/controllers/api/v1/accounts/captain/custom_tools_controller.rb b/enterprise/app/controllers/api/v1/accounts/captain/custom_tools_controller.rb
index 2d8bd616b6c..cb6c42af5d6 100644
--- a/enterprise/app/controllers/api/v1/accounts/captain/custom_tools_controller.rb
+++ b/enterprise/app/controllers/api/v1/accounts/captain/custom_tools_controller.rb
@@ -25,8 +25,8 @@ class Api::V1::Accounts::Captain::CustomToolsController < Api::V1::Accounts::Bas
end
def update
- # Tools installed from a manifest are managed by their manifest; only the user-owned enabled flag can change
- if @custom_tool.source_metadata.present? && (custom_tool_params.keys - ['enabled']).any?
+ # Tools installed from a manifest are managed by their manifest. Only the user-owned enabled flag and settings can change.
+ if @custom_tool.source_metadata.present? && (custom_tool_params.keys - %w[enabled settings]).any?
return render_could_not_create_error(I18n.t('captain.custom_tool.installed_read_only'))
end
diff --git a/enterprise/app/models/concerns/agentable.rb b/enterprise/app/models/concerns/agentable.rb
index b1df68960bf..69ea573c1be 100644
--- a/enterprise/app/models/concerns/agentable.rb
+++ b/enterprise/app/models/concerns/agentable.rb
@@ -25,6 +25,8 @@ module Concerns::Agentable
current_time: format_current_time(state[:timezone]),
conversation: state[:conversation] || {},
contact: config['feature_contact_attributes'].present? ? state[:contact] : nil,
+ can_verify_email: state[:can_verify_email],
+ verified_email: state[:verified_email],
campaign: state[:campaign] || {},
message_length_limit: state[:message_length_limit]
)
diff --git a/enterprise/app/models/concerns/toolable.rb b/enterprise/app/models/concerns/toolable.rb
index 034cf419c5a..eeb7cba5f1b 100644
--- a/enterprise/app/models/concerns/toolable.rb
+++ b/enterprise/app/models/concerns/toolable.rb
@@ -2,12 +2,13 @@ module Concerns::Toolable
extend ActiveSupport::Concern
# Isolated namespace for user-defined custom tool classes.
- # Keeps them separate from built-in classes in Captain::Tools (e.g., HttpTool, CustomHttpTool).
+ # Keeps them separate from built-in classes in Captain::Tools (e.g., HttpTool).
module CustomTools; end
# A parameter with a source is filled by Chatwoot from what the customer verified, so the model does not see it.
# The base class says whether the model fills it instead, for runs where an admin or an agent is the user.
- def tool(assistant, base_class: Captain::Tools::HttpTool, **) # rubocop:disable Metrics/AbcSize
+ # Builds the customer-facing tool unless told otherwise, so a caller that does not choose gets the gate
+ def tool(assistant, base_class: Captain::Tools::PublicHttpTool, **) # rubocop:disable Metrics/AbcSize
custom_tool_record = self
class_name = custom_tool_record.slug.underscore.camelize
diff --git a/enterprise/app/services/captain/assistant/agent_runner_service.rb b/enterprise/app/services/captain/assistant/agent_runner_service.rb
index 89be75c2eb4..2c190c03c14 100644
--- a/enterprise/app/services/captain/assistant/agent_runner_service.rb
+++ b/enterprise/app/services/captain/assistant/agent_runner_service.rb
@@ -13,6 +13,9 @@ class Captain::Assistant::AgentRunnerService
attr_reader :last_run_result
REPLY_SUGGESTION_SOURCE = 'copilot_reply_suggestion'.freeze
+ EMAIL_VERIFICATION_TOOLS = [Captain::Tools::SendEmailVerificationCodeTool, Captain::Tools::VerifyEmailCodeTool].freeze
+ # Runs where an admin or an agent is the user. The playground runs a tool the way Copilot would. Everywhere else a customer is.
+ COPILOT_SOURCES = %w[playground copilot_reply_suggestion].freeze
RunOptions = Data.define(:callbacks, :source, :responding_to_message_id, :runtime_configuration) do
def initialize(callbacks: {}, source: nil, responding_to_message_id: nil, runtime_configuration: nil)
super
@@ -149,17 +152,42 @@ class Captain::Assistant::AgentRunnerService
end
def wire_agents(assistant_agent, scenario_agents)
+ assistant_agent = with_tools_for_user(assistant_agent)
+ scenario_agents = scenario_agents.map { |agent| with_tools_for_user(agent) }
assistant_agent.register_handoffs(*scenario_agents) if scenario_agents.any?
scenario_agents.each { |scenario_agent| scenario_agent.register_handoffs(assistant_agent) }
[assistant_agent] + scenario_agents
end
+ def with_tools_for_user(agent)
+ return agent.clone(tools: copilot_tools(agent.tools)) if COPILOT_SOURCES.include?(@source)
+
+ with_email_verification_tools(agent)
+ end
+
+ # Custom tools are built for customers by default. Here an admin or an agent is the user, so they are rebuilt for Copilot.
+ def copilot_tools(tools)
+ tools.map { |tool| tool.is_a?(Captain::Tools::HttpTool) ? tool.custom_tool.tool(@assistant, base_class: Captain::Tools::CopilotHttpTool) : tool }
+ end
+
+ # Every agent in a customer conversation can verify the customer, so whichever one is asked for account data can do it
+ def with_email_verification_tools(agent)
+ return agent unless can_verify_email?
+
+ agent.clone(tools: agent.tools + EMAIL_VERIFICATION_TOOLS.map { |tool_class| tool_class.new(@assistant) })
+ end
+
+ # A customer is the user, and a tool needs their verified email. The prompt reads this from the state.
+ def can_verify_email?
+ @conversation.present? && COPILOT_SOURCES.exclude?(@source) && @assistant.custom_tools.enabled.any?(&:requires_email_verification?)
+ end
+
def reply_suggestion_agent
agent = @assistant.agent
agent.clone(
instructions: ->(context) { @assistant.agent_instructions(context, prompt_template: 'copilot_reply_suggestion') },
- tools: agent.tools.select { |tool| available_in_reply_suggestion?(tool) }
+ tools: copilot_tools(agent.tools.select { |tool| available_in_reply_suggestion?(tool) })
)
end
diff --git a/enterprise/app/services/captain/assistant/runner_state_helper.rb b/enterprise/app/services/captain/assistant/runner_state_helper.rb
index b6dc265b03b..f6a4ac5df18 100644
--- a/enterprise/app/services/captain/assistant/runner_state_helper.rb
+++ b/enterprise/app/services/captain/assistant/runner_state_helper.rb
@@ -34,9 +34,15 @@ module Captain::Assistant::RunnerStateHelper
state[:conversation][:label_list] = @conversation.label_list.to_a
state[:channel_type] = @conversation.inbox&.channel_type
state[:message_length_limit] = Captain::MessageLengthLimit.for(@conversation)
+ state[:can_verify_email] = can_verify_email?
state[:contact] = slice_attrs(@conversation.contact, CONTACT_STATE_ATTRIBUTES) if @conversation.contact
state[:campaign] = slice_attrs(@conversation.campaign, CAMPAIGN_STATE_ATTRIBUTES) if @conversation.campaign
- state[:contact_inbox] = slice_attrs(@conversation.contact_inbox, CONTACT_INBOX_STATE_ATTRIBUTES) if @conversation.contact_inbox
+ build_contact_inbox_state(state) if @conversation.contact_inbox
+ end
+
+ def build_contact_inbox_state(state)
+ state[:contact_inbox] = slice_attrs(@conversation.contact_inbox, CONTACT_INBOX_STATE_ATTRIBUTES)
+ state[:verified_email] = Captain::EmailVerification.new(@conversation).verified_email
end
def slice_attrs(record, keys)
diff --git a/enterprise/app/services/captain/email_verification.rb b/enterprise/app/services/captain/email_verification.rb
index a22c22320dc..29d4a41754a 100644
--- a/enterprise/app/services/captain/email_verification.rb
+++ b/enterprise/app/services/captain/email_verification.rb
@@ -1,18 +1,21 @@
# Verifies that the customer in a conversation can read an email address, by
# emailing a one-time code that they type back into the conversation.
#
-# Verification is bound to the contact inbox and to the exact address that
-# received the code. It expires on its own, so a new session or a different
-# address is never treated as verified.
+# Verification is bound to the conversation and to the exact address that
+# received the code. It expires on its own, so a new conversation or a different
+# address is never treated as verified. The send budget is per contact inbox,
+# so opening new conversations does not give more codes.
class Captain::EmailVerification
CODE_LENGTH = 6
SEND_LIMIT = 5
SEND_WINDOW = 1.hour
- VERIFIED_TTL = 24.hours
+ VERIFIED_TTL = 1.hour
+ # Email replies arrive slowly, and only people who received the thread can add messages to it
+ EMAIL_VERIFIED_TTL = 3.hours
# Tools place the verified address in URLs and JSON bodies, so it can only hold characters that cannot change the request
EMAIL_PATTERN = /\A[a-z0-9._+-]+@[a-z0-9.-]+\z/
- pattr_initialize :contact_inbox
+ pattr_initialize :conversation
# The code must never appear in serialized job arguments, since Sidekiq logs the payload when a job fails
def self.encrypt_code(code)
@@ -38,13 +41,13 @@ class Captain::EmailVerification
code = format("%0#{CODE_LENGTH}d", SecureRandom.random_number(10**CODE_LENGTH))
pending_code.store(email, code)
- inbox = contact_inbox.inbox
+ inbox = conversation.inbox
Captain::EmailVerificationMailer.with(account: inbox.account).verification_code(inbox, email, self.class.encrypt_code(code)).deliver_later
:sent
end
def verify(typed_code)
- pending_code.consume(typed_code) { |email| ::Redis::Alfred.setex(verified_key, email, VERIFIED_TTL) }
+ pending_code.consume(typed_code) { |email| ::Redis::Alfred.setex(verified_key, email, verified_ttl) }
end
def verified_email
@@ -55,10 +58,14 @@ class Captain::EmailVerification
pending_code.attempts_left
end
+ def verified_ttl
+ conversation.inbox.email? ? EMAIL_VERIFIED_TTL : VERIFIED_TTL
+ end
+
private
def pending_code
- @pending_code ||= Captain::EmailVerification::Code.new(contact_inbox)
+ @pending_code ||= Captain::EmailVerification::Code.new(conversation)
end
# The contact inbox is checked first, so a blocked contact inbox does not use up the address's budget
@@ -68,10 +75,10 @@ class Captain::EmailVerification
end
def verified_key
- format(::Redis::RedisKeys::CAPTAIN_EMAIL_VERIFICATION_VERIFIED, contact_inbox_id: contact_inbox.id)
+ format(::Redis::RedisKeys::CAPTAIN_EMAIL_VERIFICATION_VERIFIED, conversation_id: conversation.id)
end
def sends_key
- format(::Redis::RedisKeys::CAPTAIN_EMAIL_VERIFICATION_SENDS, contact_inbox_id: contact_inbox.id)
+ format(::Redis::RedisKeys::CAPTAIN_EMAIL_VERIFICATION_SENDS, contact_inbox_id: conversation.contact_inbox_id)
end
end
diff --git a/enterprise/app/services/captain/email_verification/code.rb b/enterprise/app/services/captain/email_verification/code.rb
index 4bd4f43dfc4..bfec28aac9b 100644
--- a/enterprise/app/services/captain/email_verification/code.rb
+++ b/enterprise/app/services/captain/email_verification/code.rb
@@ -1,4 +1,4 @@
-# The one-time code a contact inbox is waiting on. A contact inbox holds one code at a time.
+# The one-time code a conversation is waiting on. A conversation holds one code at a time.
#
# The code is stored as a digest, together with the address it was sent to, in one key.
# Storing a new code replaces the code and its address in one write.
@@ -7,7 +7,7 @@ class Captain::EmailVerification::Code
TTL = 30.minutes
MAX_ATTEMPTS = 5
- pattr_initialize :contact_inbox
+ pattr_initialize :conversation
# A new code starts with a full set of attempts. Both writes run together, so an overlapping store cannot clear the attempts of a newer code.
def store(email, code)
@@ -42,7 +42,7 @@ class Captain::EmailVerification::Code
private
def stored_value(email, code)
- { email: email, digest: OpenSSL::HMAC.hexdigest('SHA256', Rails.application.secret_key_base, "#{contact_inbox.id}:#{email}:#{code}") }.to_json
+ { email: email, digest: OpenSSL::HMAC.hexdigest('SHA256', Rails.application.secret_key_base, "#{conversation.id}:#{email}:#{code}") }.to_json
end
def attempts
@@ -50,10 +50,10 @@ class Captain::EmailVerification::Code
end
def code_key
- format(::Redis::RedisKeys::CAPTAIN_EMAIL_VERIFICATION_CODE, contact_inbox_id: contact_inbox.id)
+ format(::Redis::RedisKeys::CAPTAIN_EMAIL_VERIFICATION_CODE, conversation_id: conversation.id)
end
def attempts_key
- format(::Redis::RedisKeys::CAPTAIN_EMAIL_VERIFICATION_ATTEMPTS, contact_inbox_id: contact_inbox.id)
+ format(::Redis::RedisKeys::CAPTAIN_EMAIL_VERIFICATION_ATTEMPTS, conversation_id: conversation.id)
end
end
diff --git a/enterprise/app/services/captain/tools/custom_http_tool.rb b/enterprise/app/services/captain/tools/custom_http_tool.rb
deleted file mode 100644
index 45e5245bf2e..00000000000
--- a/enterprise/app/services/captain/tools/custom_http_tool.rb
+++ /dev/null
@@ -1,47 +0,0 @@
-# V1-compatible wrapper for custom HTTP tools.
-#
-# V2's HttpTool inherits from Agents::Tool which overrides execute(tool_context, **params),
-# making it incompatible with V1's RubyLLM pipeline that calls execute(**keyword_args).
-#
-# This class bridges the gap: it inherits from BaseTool (RubyLLM::Tool) for V1 compatibility
-# and delegates the actual HTTP execution to HttpTool#perform.
-class Captain::Tools::CustomHttpTool < Captain::Tools::BaseTool
- # BaseTool prepends Instrumentation, but our execute() shadows it in the MRO.
- # Re-prepend so Langfuse captures tool call input/output/timing.
- prepend Captain::Tools::Instrumentation
-
- attr_reader :custom_tool
-
- def initialize(assistant, custom_tool, conversation: nil)
- @custom_tool = custom_tool
- @conversation = conversation
- super(assistant)
- end
-
- def active?
- @custom_tool.enabled?
- end
-
- def execute(**params)
- http_tool = Captain::Tools::HttpTool.new(assistant, @custom_tool)
- http_tool.perform(build_tool_context, **params)
- end
-
- private
-
- def build_tool_context
- state = { account_id: assistant.account_id, assistant_id: assistant.id }
- add_conversation_state(state) if @conversation
- OpenStruct.new(state: state)
- end
-
- def add_conversation_state(state)
- state[:conversation] = { id: @conversation.id, display_id: @conversation.display_id }
- state[:contact] = slice_record_attrs(@conversation.contact, :id, :email, :phone_number)
- state[:contact_inbox] = slice_record_attrs(@conversation.contact_inbox, :id, :hmac_verified)
- end
-
- def slice_record_attrs(record, *keys)
- record&.attributes&.symbolize_keys&.slice(*keys)
- end
-end
diff --git a/enterprise/app/services/captain/tools_manifest/install_service.rb b/enterprise/app/services/captain/tools_manifest/install_service.rb
index ab170d83579..817deb10f90 100644
--- a/enterprise/app/services/captain/tools_manifest/install_service.rb
+++ b/enterprise/app/services/captain/tools_manifest/install_service.rb
@@ -3,7 +3,7 @@
# The toolset is pinned to a commit: the given revision, or the latest commit on the
# default branch. Installing the same commit again is a no-op once every tool is
# present. Otherwise the existing tools are updated in place, matched by manifest
-# tool id so slugs and the user-owned enabled flag stay, and missing ones are added.
+# tool id so slugs and the user-owned enabled flag and settings stay, and missing ones are added.
class Captain::ToolsManifest::InstallService
class InstallError < StandardError; end
@@ -16,18 +16,11 @@ class Captain::ToolsManifest::InstallService
# call time. Secrets are only used in auth_config, which is never rendered, so they may contain these characters.
LIQUID_DELIMITER_PATTERN = /\{\{|\{%/
- # Installed at this commit with every manifest tool present and its settings applied, so there is nothing to add or update
+ # Installed at this commit with every manifest tool present, so there is nothing to add or update
def self.complete?(tools, manifest, revision)
tools.any? &&
tools.all? { |tool| tool.source_metadata['revision'] == revision } &&
- (manifest['tools'].pluck('id') - tools.map { |tool| tool.source_metadata['tool_id'] }).empty? &&
- settings_applied?(tools, manifest)
- end
-
- # A version that did not know a setting records the commit without it, so the commit alone does not prove the install is current
- def self.settings_applied?(tools, manifest)
- verification_required = manifest['tools'].to_h { |tool| [tool['id'], tool['requires_email_verification'] == true] }
- tools.all? { |tool| (tool.settings['requires_email_verification'] == true) == verification_required[tool.source_metadata['tool_id']] }
+ (manifest['tools'].pluck('id') - tools.map { |tool| tool.source_metadata['tool_id'] }).empty?
end
# Fields filled into auth_config must have a value even when optional, or the tool would send blank credentials
@@ -142,11 +135,14 @@ class Captain::ToolsManifest::InstallService
def save_tool!(existing_tool, tool, attributes)
return existing_tool.tap { |record| record.update!(attributes) } if existing_tool
- @assistant.custom_tools.create!(attributes.merge(account: @assistant.account, enabled: tool['enabled']))
+ @assistant.custom_tools.create!(
+ attributes.merge(account: @assistant.account, enabled: tool['enabled'],
+ settings: { 'requires_email_verification' => tool['requires_email_verification'] })
+ )
end
- # Everything except enabled comes from the manifest; enabled belongs to the user once a tool exists.
- # The manifest keeps tool options flat; they are stored together in settings.
+ # Everything except enabled and settings comes from the manifest. Those belong to the user once a tool exists.
+ # The manifest keeps tool options flat. They are stored together in settings.
def tool_attributes(tool, manifest, values, metadata)
{
title: tool['title'],
@@ -159,7 +155,6 @@ class Captain::ToolsManifest::InstallService
request_template: interpolate(tool['request_template'], values),
response_template: tool['response_template'],
headers: manifest['headers'],
- settings: { 'requires_email_verification' => tool['requires_email_verification'] },
source_metadata: metadata.merge('tool_id' => tool['id'])
}
end
diff --git a/enterprise/lib/captain/prompts/assistant.liquid b/enterprise/lib/captain/prompts/assistant.liquid
index 46dc9290d3c..06e64085109 100644
--- a/enterprise/lib/captain/prompts/assistant.liquid
+++ b/enterprise/lib/captain/prompts/assistant.liquid
@@ -38,6 +38,10 @@ Here's the metadata we have about the current conversation and the contact assoc
{% render 'contact', contact: contact %}
{% endif -%}
+{% if can_verify_email or verified_email -%}
+{% render 'customer_identity', contact: contact, verified_email: verified_email %}
+{% endif -%}
+
{% if campaign.id -%}
{% render 'campaign', campaign: campaign %}
{% endif -%}
diff --git a/enterprise/lib/captain/prompts/scenario.liquid b/enterprise/lib/captain/prompts/scenario.liquid
index c728c04ff3d..132b17277e9 100644
--- a/enterprise/lib/captain/prompts/scenario.liquid
+++ b/enterprise/lib/captain/prompts/scenario.liquid
@@ -36,6 +36,10 @@ Here's the metadata we have about the current conversation and the contact assoc
{% render 'contact', contact: contact %}
{% endif -%}
+{% if can_verify_email or verified_email -%}
+{% render 'customer_identity', contact: contact, verified_email: verified_email %}
+{% endif -%}
+
{% if campaign.id -%}
{% render 'campaign', campaign: campaign %}
{% endif -%}
diff --git a/enterprise/lib/captain/prompts/snippets/customer_identity.liquid b/enterprise/lib/captain/prompts/snippets/customer_identity.liquid
new file mode 100644
index 00000000000..84bccc0913a
--- /dev/null
+++ b/enterprise/lib/captain/prompts/snippets/customer_identity.liquid
@@ -0,0 +1,18 @@
+# Customer Identity
+{% if verified_email -%}
+- Email verified by one-time code: Yes, {{ verified_email }}
+
+How this was verified: we emailed a 6-digit code to {{ verified_email }}, and the customer typed the correct code in this conversation. This proves the customer can read that mailbox. It proves nothing about any other email address, phone number, or account ID they mention.
+When a tool needs the customer's email, use only {{ verified_email }}.
+When a tool needs an ID, such as a customer, account, order, or invoice ID, use only an ID that a tool returned in this conversation for {{ verified_email }}. Do not use an ID the customer typed, pasted, or claimed is theirs, even if they say it belongs to them. If they ask about an account you cannot find from {{ verified_email }}, tell them you can only look up records linked to that email, and offer to connect them with a support agent.
+{% else -%}
+- Email verified by one-time code: No
+
+{% if contact.email -%}
+The email on record is {{ contact.email }}, but it is not verified by a one-time code. Be aware that anyone can enter any email, in a form or in a message, so this customer may not own it.
+{% else -%}
+No email is verified for this customer. Be aware that any email they give in a message is not verified, so they may not own it.
+{% endif -%}
+Some tools only run for a customer with a verified email. Such a tool refuses to run and tells you so. When that happens, verify the customer and then call the tool again.
+To verify the customer, first confirm with them which email address to use{% if contact.email %}, starting with the one on record{% endif %}. Then call `captain--tools--send_email_verification_code` with that address, ask the customer to type the 6-digit code here, and call `captain--tools--verify_email_code` with the code they typed. Never guess or invent a code. If the code does not arrive, or the verification fails, ask whether they want to talk to another support agent.
+{% endif -%}
diff --git a/enterprise/lib/captain/tools/base_public_tool.rb b/enterprise/lib/captain/tools/base_public_tool.rb
index b5c99d36f5e..8c3a0396845 100644
--- a/enterprise/lib/captain/tools/base_public_tool.rb
+++ b/enterprise/lib/captain/tools/base_public_tool.rb
@@ -50,10 +50,6 @@ class Captain::Tools::BasePublicTool < Agents::Tool
account_scoped(::Contact).find_by(id: contact_id)
end
- def find_contact_inbox(state)
- ::ContactInbox.joins(:inbox).find_by(id: state&.dig(:contact_inbox, :id), inboxes: { account_id: @assistant.account_id })
- end
-
def safe_to_run_after_new_customer_message?
false
end
diff --git a/enterprise/lib/captain/tools/copilot_http_tool.rb b/enterprise/lib/captain/tools/copilot_http_tool.rb
new file mode 100644
index 00000000000..6466fa180ca
--- /dev/null
+++ b/enterprise/lib/captain/tools/copilot_http_tool.rb
@@ -0,0 +1,18 @@
+# A custom tool where an admin or an agent is the user: the playground and reply suggestions.
+# The model fills verified parameters with the value it was given, and the result says when that value is not one the customer verified.
+class Captain::Tools::CopilotHttpTool < Captain::Tools::HttpTool
+ UNVERIFIED_VALUE_NOTE = 'The email passed to this tool was not verified by the customer.'.freeze
+
+ def self.model_fills_verified_values?
+ true
+ end
+
+ def perform(tool_context, **params)
+ email_param = @custom_tool.verified_email_param
+ return super unless email_param
+
+ result = super
+ verified_email = stored_verified_email(tool_context.state)
+ verified_email && params[email_param.to_sym].to_s.strip.casecmp?(verified_email) ? result : "#{result}\n\n#{UNVERIFIED_VALUE_NOTE}"
+ end
+end
diff --git a/enterprise/lib/captain/tools/http_tool.rb b/enterprise/lib/captain/tools/http_tool.rb
index abc91c77240..f80ff015b3d 100644
--- a/enterprise/lib/captain/tools/http_tool.rb
+++ b/enterprise/lib/captain/tools/http_tool.rb
@@ -6,7 +6,9 @@ class Captain::Tools::HttpTool < Captain::Tools::BasePublicTool
super(assistant)
end
- # A customer is the user, so Chatwoot fills a verified parameter and the model does not see it
+ attr_reader :custom_tool
+
+ # Whether the model sees and fills a verified parameter. Each subclass answers for the user it serves.
def self.model_fills_verified_values?
false
end
@@ -16,11 +18,7 @@ class Captain::Tools::HttpTool < Captain::Tools::BasePublicTool
end
def perform(tool_context, **params)
- url = @custom_tool.build_request_url(params)
- body = @custom_tool.build_request_body(params)
-
- response_body = execute_http_request(url, body, tool_context)
- @custom_tool.format_response(response_body)
+ request(tool_context, params)
rescue StandardError => e
Rails.logger.error("HttpTool execution error for #{@custom_tool.slug}: #{e.class} - #{e.message}")
failure_result('An error occurred while executing the request', tool_context.state)
@@ -32,6 +30,18 @@ class Captain::Tools::HttpTool < Captain::Tools::BasePublicTool
private
+ def request(tool_context, params)
+ url = @custom_tool.build_request_url(params)
+ body = @custom_tool.build_request_body(params)
+ @custom_tool.format_response(execute_http_request(url, body, tool_context))
+ end
+
+ # Read from stored data on every call, never from the run state the model can influence
+ def stored_verified_email(state)
+ conversation = find_conversation(state)
+ conversation && Captain::EmailVerification.new(conversation).verified_email
+ end
+
def safe_to_run_after_new_customer_message?
@custom_tool.http_method == 'GET'
end
@@ -39,6 +49,8 @@ class Captain::Tools::HttpTool < Captain::Tools::BasePublicTool
# Limit response size to prevent memory exhaustion and match LLM token limits
# 1MB of text ≈ 250K tokens, which exceeds most LLM context windows
MAX_RESPONSE_SIZE = 1.megabyte
+ # Customer details Chatwoot sends with every request. They are dropped on a redirect to another origin, like credentials.
+ PERSONAL_HEADERS = %w[X-Chatwoot-Contact-Email X-Chatwoot-Contact-Phone X-Chatwoot-Verified-Email].freeze
# Route through SafeFetch so custom tool requests share the app's centralized HTTP
# fetching (resolution, timeouts, response size limits, and redirect handling).
@@ -55,7 +67,7 @@ class Captain::Tools::HttpTool < Captain::Tools::BasePublicTool
method: @custom_tool.http_method.downcase.to_sym,
body: json_body,
headers: request_headers(tool_context, json_body, auth_headers),
- sensitive_headers: auth_headers.keys + @custom_tool.headers.keys,
+ sensitive_headers: auth_headers.keys + @custom_tool.headers.keys + PERSONAL_HEADERS,
http_basic_authentication: @custom_tool.build_basic_auth_credentials,
max_bytes: MAX_RESPONSE_SIZE,
validate_content_type: false
@@ -66,6 +78,10 @@ class Captain::Tools::HttpTool < Captain::Tools::BasePublicTool
def request_headers(tool_context, json_body, auth_headers)
headers = @custom_tool.headers.merge(auth_headers)
headers.merge!(@custom_tool.build_metadata_headers(tool_context&.state || {}))
+ # The contact email can be typed by anyone, so the email the customer verified travels in its own header.
+ # The admin test request runs without a conversation, so it has no customer to look up.
+ verified_email = stored_verified_email(tool_context.state) if tool_context
+ headers['X-Chatwoot-Verified-Email'] = verified_email if verified_email
headers['Content-Type'] = 'application/json' if json_body.present?
headers
end
diff --git a/enterprise/lib/captain/tools/public_http_tool.rb b/enterprise/lib/captain/tools/public_http_tool.rb
new file mode 100644
index 00000000000..895cea15cf3
--- /dev/null
+++ b/enterprise/lib/captain/tools/public_http_tool.rb
@@ -0,0 +1,18 @@
+# A custom tool in a conversation where a customer is the user. A tool that requires email verification runs only
+# for a customer who verified an email, and a verified email parameter always carries that email.
+class Captain::Tools::PublicHttpTool < Captain::Tools::HttpTool
+ EMAIL_REQUIRED = 'This tool needs a verified email, and this customer has not verified an email yet. ' \
+ 'Verify their email with a one-time code first, then call this tool again. ' \
+ 'If that is not possible, ask whether they want to talk to a support agent.'.freeze
+
+ def perform(tool_context, **params)
+ return super unless @custom_tool.requires_email_verification?
+
+ verified_email = stored_verified_email(tool_context.state)
+ return failure_result(EMAIL_REQUIRED, tool_context.state) unless verified_email
+
+ # Set last, so a value from the model can never replace the verified email
+ email_param = @custom_tool.verified_email_param
+ super(tool_context, **(email_param ? params.merge(email_param.to_sym => verified_email) : params))
+ end
+end
diff --git a/enterprise/lib/captain/tools/send_email_verification_code_tool.rb b/enterprise/lib/captain/tools/send_email_verification_code_tool.rb
index abd3bb52668..a9f3044592f 100644
--- a/enterprise/lib/captain/tools/send_email_verification_code_tool.rb
+++ b/enterprise/lib/captain/tools/send_email_verification_code_tool.rb
@@ -4,12 +4,12 @@ class Captain::Tools::SendEmailVerificationCodeTool < Captain::Tools::BasePublic
parameter :email, type: 'string', description: 'The email address the customer confirmed they want the code sent to'
def perform(tool_context, email:)
- contact_inbox = find_contact_inbox(tool_context.state)
- return failure_result('Email verification is not available in this conversation', tool_context.state) unless contact_inbox
+ conversation = find_conversation(tool_context.state)
+ return failure_result('Email verification is not available in this conversation', tool_context.state) unless conversation
- log_tool_usage('send_email_verification_code', { contact_inbox_id: contact_inbox.id })
+ log_tool_usage('send_email_verification_code', { conversation_id: conversation.id })
- case Captain::EmailVerification.new(contact_inbox).send_code(email)
+ case Captain::EmailVerification.new(conversation).send_code(email)
when :sent then sent_message(email)
when :already_verified then 'This email address is already verified for this customer. No code was sent. Continue with their request.'
when :unavailable then 'Email verification is not available right now. Do not try again. Ask whether the customer wants a support agent.'
diff --git a/enterprise/lib/captain/tools/verify_email_code_tool.rb b/enterprise/lib/captain/tools/verify_email_code_tool.rb
index 4a7d82281bb..691ec138bec 100644
--- a/enterprise/lib/captain/tools/verify_email_code_tool.rb
+++ b/enterprise/lib/captain/tools/verify_email_code_tool.rb
@@ -4,15 +4,15 @@ class Captain::Tools::VerifyEmailCodeTool < Captain::Tools::BasePublicTool
parameter :code, type: 'string', description: 'The 6-digit code the customer typed in the conversation'
def perform(tool_context, code:)
- contact_inbox = find_contact_inbox(tool_context.state)
- return failure_result('Email verification is not available in this conversation', tool_context.state) unless contact_inbox
+ conversation = find_conversation(tool_context.state)
+ return failure_result('Email verification is not available in this conversation', tool_context.state) unless conversation
- verification = Captain::EmailVerification.new(contact_inbox)
+ verification = Captain::EmailVerification.new(conversation)
result = verification.verify(code)
- log_tool_usage('verify_email_code', { contact_inbox_id: contact_inbox.id, result: result })
+ log_tool_usage('verify_email_code', { conversation_id: conversation.id, result: result })
case result
- when :verified then verified_message(tool_context, verification.verified_email)
+ when :verified then verified_message(tool_context, verification)
when :invalid_code then invalid_code_message(verification.attempts_left)
when :locked then 'Too many wrong codes were entered, so this code no longer works. Send a new code, or offer a support agent.'
else 'There is no active code. It may have expired. Send a new code first.'
@@ -22,10 +22,11 @@ class Captain::Tools::VerifyEmailCodeTool < Captain::Tools::BasePublicTool
private
# The rest of this run reads the state, so the prompt shows the email as verified straight away
- def verified_message(tool_context, email)
+ def verified_message(tool_context, verification)
+ email = verification.verified_email
tool_context.state[:verified_email] = email
- hours = Captain::EmailVerification::VERIFIED_TTL.in_hours.to_i
- "Verified. The customer entered the code that was emailed to #{email}, so they can read that mailbox. This stays valid for #{hours} hours."
+ "Verified. The customer entered the code that was emailed to #{email}, so they can read that mailbox. " \
+ "This stays valid for #{verification.verified_ttl.inspect}."
end
def invalid_code_message(attempts_left)
diff --git a/lib/redis/redis_keys.rb b/lib/redis/redis_keys.rb
index be2318a4c07..670f4fa94e4 100644
--- a/lib/redis/redis_keys.rb
+++ b/lib/redis/redis_keys.rb
@@ -115,13 +115,13 @@ module Redis::RedisKeys
## Captain email verification (one-time code typed by the customer in a conversation)
# Email address the active code was sent to, with the HMAC digest of the code, consumed atomically on verification
- CAPTAIN_EMAIL_VERIFICATION_CODE = 'CAPTAIN::EMAIL_VERIFICATION::CODE::%<contact_inbox_id>d'.freeze
+ CAPTAIN_EMAIL_VERIFICATION_CODE = 'CAPTAIN::EMAIL_VERIFICATION::CODE::%<conversation_id>d'.freeze
# Wrong-code counter for the active code
- CAPTAIN_EMAIL_VERIFICATION_ATTEMPTS = 'CAPTAIN::EMAIL_VERIFICATION::ATTEMPTS::%<contact_inbox_id>d'.freeze
+ CAPTAIN_EMAIL_VERIFICATION_ATTEMPTS = 'CAPTAIN::EMAIL_VERIFICATION::ATTEMPTS::%<conversation_id>d'.freeze
# Hourly budget of codes sent from one contact inbox, counted from the first send
CAPTAIN_EMAIL_VERIFICATION_SENDS = 'CAPTAIN::EMAIL_VERIFICATION::SENDS::%<contact_inbox_id>d'.freeze
# Hourly budget of codes sent to one email address across contact inboxes, counted from the first send
CAPTAIN_EMAIL_VERIFICATION_EMAIL_SENDS = 'CAPTAIN::EMAIL_VERIFICATION::EMAIL_SENDS::%<email_digest>s'.freeze
- # Email address the contact inbox has verified
- CAPTAIN_EMAIL_VERIFICATION_VERIFIED = 'CAPTAIN::EMAIL_VERIFICATION::VERIFIED::%<contact_inbox_id>d'.freeze
+ # Email address verified in the conversation
+ CAPTAIN_EMAIL_VERIFICATION_VERIFIED = 'CAPTAIN::EMAIL_VERIFICATION::VERIFIED::%<conversation_id>d'.freeze
end
diff --git a/lib/tasks/captain_chat.rake b/lib/tasks/captain_chat.rake
index 0a5348e3ab0..d197d89ec5a 100644
--- a/lib/tasks/captain_chat.rake
+++ b/lib/tasks/captain_chat.rake
@@ -141,7 +141,8 @@ class CaptainChatSession
end
def generate_assistant_response
- run_options = Captain::Assistant::AgentRunnerService::RunOptions.new(callbacks: build_callbacks)
+ # An admin runs this, so tools run the way they do in the playground
+ run_options = Captain::Assistant::AgentRunnerService::RunOptions.new(callbacks: build_callbacks, source: 'playground')
runner = Captain::Assistant::AgentRunnerService.new(assistant: @assistant, run_options: run_options)
runner.generate_response(message_history: @message_history)
end
diff --git a/spec/enterprise/controllers/api/v1/accounts/captain/custom_tools_controller_spec.rb b/spec/enterprise/controllers/api/v1/accounts/captain/custom_tools_controller_spec.rb
index 59a8bcabc40..396a17aa32a 100644
--- a/spec/enterprise/controllers/api/v1/accounts/captain/custom_tools_controller_spec.rb
+++ b/spec/enterprise/controllers/api/v1/accounts/captain/custom_tools_controller_spec.rb
@@ -523,17 +523,19 @@ RSpec.describe 'Api::V1::Accounts::Captain::CustomTools', type: :request do
patch tool_url, params: { custom_tool: { title: 'Renamed', enabled: false } }, headers: admin.create_new_auth_token, as: :json
expect(response).to have_http_status(:unprocessable_entity)
- expect(json_response[:error]).to eq('Tools installed from a manifest are read-only; you can only enable or disable them')
+ expect(json_response[:error]).to eq(I18n.t('captain.custom_tool.installed_read_only'))
expect(installed_tool.reload).to have_attributes(title: 'Get Order', enabled: true)
end
- it 'rejects turning email verification off' do
- installed_tool.update!(settings: { 'requires_email_verification' => true })
+ it 'allows turning email verification on and off' do
+ patch tool_url, params: { custom_tool: { settings: { requires_email_verification: true } } }, headers: admin.create_new_auth_token, as: :json
+
+ expect(response).to have_http_status(:success)
+ expect(installed_tool.reload.requires_email_verification?).to be(true)
patch tool_url, params: { custom_tool: { settings: { requires_email_verification: false } } }, headers: admin.create_new_auth_token, as: :json
- expect(response).to have_http_status(:unprocessable_entity)
- expect(installed_tool.reload.requires_email_verification?).to be(true)
+ expect(installed_tool.reload.requires_email_verification?).to be(false)
end
it 'allows enabling and disabling' do
diff --git a/spec/enterprise/lib/captain/tools/copilot_http_tool_spec.rb b/spec/enterprise/lib/captain/tools/copilot_http_tool_spec.rb
new file mode 100644
index 00000000000..a0f6b86fcb0
--- /dev/null
+++ b/spec/enterprise/lib/captain/tools/copilot_http_tool_spec.rb
@@ -0,0 +1,73 @@
+require 'rails_helper'
+
+RSpec.describe Captain::Tools::CopilotHttpTool, type: :model do
+ let(:account) { create(:account) }
+ let(:assistant) { create(:captain_assistant, account: account) }
+ let(:inbox) { create(:inbox, account: account) }
+ let(:contact_inbox) { create(:contact_inbox, inbox: inbox, contact: create(:contact, account: account)) }
+ let(:conversation) { create(:conversation, account: account, inbox: inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact) }
+ let(:state) { { account_id: account.id, source: 'copilot_reply_suggestion', conversation: { id: conversation.id } } }
+ let(:tool_context) { Struct.new(:state).new(state) }
+ let(:email_param) { { 'name' => 'email', 'type' => 'string', 'description' => 'Email', 'source' => 'verified.email' } }
+ let(:custom_tool) do
+ create(:captain_custom_tool, account: account, http_method: 'GET', response_template: nil,
+ endpoint_url: 'https://example.com/customers?email={{ email | url_encode }}', param_schema: [email_param])
+ end
+ let(:tool) { custom_tool.tool(assistant, base_class: described_class) }
+ let(:request_stub) { stub_request(:get, %r{\Ahttps://example.com/customers}).to_return(status: 200, body: '{"found": true}') }
+
+ before do
+ request_stub
+ allow(Captain::EmailVerification).to receive(:new).with(conversation)
+ .and_return(instance_double(Captain::EmailVerification, verified_email: '[email protected]'))
+ end
+
+ it 'shows verified parameters to the model' do
+ expect(tool.class.declared_parameters.keys).to contain_exactly(:email)
+ end
+
+ describe '#perform' do
+ it 'uses the email passed, and says when it is not what the customer verified' do
+ result = tool.perform(tool_context, email: '[email protected]')
+
+ expect(WebMock).to have_requested(:get, 'https://example.com/customers?email=typed%40example.com')
+ expect(result).to start_with('{"found": true}')
+ expect(result).to include('was not verified by the customer')
+ end
+
+ it 'adds no note when the email passed is what the customer verified' do
+ expect(tool.perform(tool_context, email: '[email protected]')).to eq('{"found": true}')
+ end
+
+ it 'says an empty email is not verified when the customer has verified none' do
+ unverified = instance_double(Captain::EmailVerification, verified_email: nil)
+ allow(Captain::EmailVerification).to receive(:new).with(conversation).and_return(unverified)
+
+ expect(tool.perform(tool_context, email: ' ')).to include('was not verified by the customer')
+ end
+
+ it 'uses the values an admin supplies in the playground' do
+ result = tool.perform(Struct.new(:state).new({ source: 'playground' }), email: '[email protected]')
+
+ expect(WebMock).to have_requested(:get, 'https://example.com/customers?email=test%40example.com')
+ expect(result).to include('was not verified by the customer')
+ end
+
+ it 'runs a tool that only has the setting turned on, for a customer who has not verified' do
+ custom_tool.update!(param_schema: [], endpoint_url: 'https://example.com/customers', settings: { 'requires_email_verification' => true })
+ allow(Captain::EmailVerification).to receive(:new).and_return(instance_double(Captain::EmailVerification, verified_email: nil))
+
+ expect(tool.perform(tool_context)).to eq('{"found": true}')
+ end
+
+ it 'runs with another email the agent passes for a reply suggestion' do
+ custom_tool.update!(param_schema: [{ 'name' => 'email', 'type' => 'string', 'description' => 'Email' }],
+ endpoint_url: 'https://example.com/customers?email={{ email | url_encode }}',
+ settings: { 'requires_email_verification' => true })
+
+ tool.perform(tool_context, email: '[email protected]')
+
+ expect(WebMock).to have_requested(:get, 'https://example.com/customers?email=typed%40example.com')
+ end
+ end
+end
diff --git a/spec/enterprise/lib/captain/tools/http_tool_spec.rb b/spec/enterprise/lib/captain/tools/http_tool_spec.rb
index 6262865d321..58b91149369 100644
--- a/spec/enterprise/lib/captain/tools/http_tool_spec.rb
+++ b/spec/enterprise/lib/captain/tools/http_tool_spec.rb
@@ -4,7 +4,7 @@ RSpec.describe Captain::Tools::HttpTool, type: :model do
let(:account) { create(:account) }
let(:assistant) { create(:captain_assistant, account: account) }
let(:custom_tool) { create(:captain_custom_tool, account: account) }
- let(:tool) { described_class.new(assistant, custom_tool) }
+ let(:tool) { Captain::Tools::PublicHttpTool.new(assistant, custom_tool) }
let(:tool_context) { Struct.new(:state).new({}) }
describe '#active?' do
@@ -455,6 +455,43 @@ RSpec.describe Captain::Tools::HttpTool, type: :model do
)
end
+ it 'sends the email the customer verified with a one-time code, next to the contact email' do
+ allow(Captain::EmailVerification).to receive(:new).with(conversation)
+ .and_return(instance_double(Captain::EmailVerification, verified_email: '[email protected]'))
+ stub_request(:get, 'https://example.com/api/data').to_return(status: 200, body: '{}')
+
+ tool.perform(tool_context_with_state)
+
+ expect(WebMock).to(have_requested(:get, 'https://example.com/api/data').with do |request|
+ request.headers['X-Chatwoot-Verified-Email'] == '[email protected]' && request.headers['X-Chatwoot-Contact-Email'] == contact.email
+ end)
+ end
+
+ it 'strips the contact and verified email headers on cross-origin redirects' do
+ contact.update!(email: '[email protected]', phone_number: '+14155550100')
+ tool_context_with_state.state[:contact].merge!(email: contact.email, phone_number: contact.phone_number)
+ allow(Captain::EmailVerification).to receive(:new).with(conversation)
+ .and_return(instance_double(Captain::EmailVerification, verified_email: '[email protected]'))
+ redirected_headers = nil
+ stub_request(:get, 'https://example.com/api/data').to_return(status: 302, headers: { 'Location' => 'http://example.com/data' })
+ stub_request(:get, 'http://example.com/data').with do |request|
+ redirected_headers = request.headers.transform_keys(&:downcase)
+ true
+ end
+
+ tool.perform(tool_context_with_state)
+
+ expect(redirected_headers.keys).not_to include('x-chatwoot-verified-email', 'x-chatwoot-contact-email', 'x-chatwoot-contact-phone')
+ end
+
+ it 'leaves out the verified email header when the customer has not verified an email' do
+ stub_request(:get, 'https://example.com/api/data').to_return(status: 200, body: '{}')
+
+ tool.perform(tool_context_with_state)
+
+ expect(WebMock).to(have_requested(:get, 'https://example.com/api/data').with { |request| !request.headers.key?('X-Chatwoot-Verified-Email') })
+ end
+
it 'includes metadata headers in GET request' do
stub_request(:get, 'https://example.com/api/data')
.with(headers: {
diff --git a/spec/enterprise/lib/captain/tools/public_http_tool_spec.rb b/spec/enterprise/lib/captain/tools/public_http_tool_spec.rb
new file mode 100644
index 00000000000..3fba4d7ba60
--- /dev/null
+++ b/spec/enterprise/lib/captain/tools/public_http_tool_spec.rb
@@ -0,0 +1,155 @@
+require 'rails_helper'
+
+RSpec.describe Captain::Tools::PublicHttpTool, type: :model do
+ let(:account) { create(:account) }
+ let(:assistant) { create(:captain_assistant, account: account) }
+ let(:custom_tool) { create(:captain_custom_tool, account: account) }
+ let(:tool) { described_class.new(assistant, custom_tool) }
+ let(:tool_context) { Struct.new(:state).new({}) }
+
+ describe '#perform' do
+ context 'when a parameter takes a verified value' do
+ let(:inbox) { create(:inbox, account: account) }
+ let(:contact_inbox) { create(:contact_inbox, inbox: inbox, contact: create(:contact, account: account)) }
+ let(:conversation) { create(:conversation, account: account, inbox: inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact) }
+ let(:state) { { account_id: account.id, conversation: { id: conversation.id }, contact_inbox: { id: contact_inbox.id, hmac_verified: false } } }
+ let(:tool_context) { Struct.new(:state).new(state) }
+ let(:verified_email) { '[email protected]' }
+ let(:request_stub) { stub_request(:get, %r{\Ahttps://example.com/customers}).to_return(status: 200, body: '{"found": true}') }
+ let(:email_param) { { 'name' => 'email', 'type' => 'string', 'description' => 'Email', 'source' => 'verified.email' } }
+
+ before do
+ custom_tool.update!(http_method: 'GET', endpoint_url: 'https://example.com/customers?email={{ email | url_encode }}',
+ param_schema: [email_param], response_template: nil)
+ request_stub
+ verification = instance_double(Captain::EmailVerification, verified_email: verified_email)
+ allow(Captain::EmailVerification).to receive(:new).with(conversation).and_return(verification)
+ end
+
+ it 'sends the verified email' do
+ expect(tool.perform(tool_context)).to eq('{"found": true}')
+ expect(WebMock).to have_requested(:get, 'https://example.com/customers?email=jane%40example.com')
+ end
+
+ it 'replaces an email the model passes with the verified one' do
+ tool.perform(tool_context, email: ' [email protected] ')
+
+ expect(WebMock).to have_requested(:get, 'https://example.com/customers?email=jane%40example.com')
+ end
+
+ it 'sends the verified email when the model passes another one' do
+ tool.perform(tool_context, email: '[email protected]')
+
+ expect(WebMock).to have_requested(:get, 'https://example.com/customers?email=jane%40example.com')
+ expect(WebMock).not_to have_requested(:get, 'https://example.com/customers?email=victim%40example.com')
+ end
+
+ it 'is blocked for a customer without a verified email, with no setting turned on' do
+ unverified = instance_double(Captain::EmailVerification, verified_email: nil)
+ allow(Captain::EmailVerification).to receive(:new).with(conversation).and_return(unverified)
+
+ expect(tool.perform(tool_context)).to include('has not verified an email')
+ expect(request_stub).not_to have_been_requested
+ end
+ end
+
+ context 'when the tool requires email verification' do
+ let(:inbox) { create(:inbox, account: account) }
+ let(:contact_inbox) { create(:contact_inbox, inbox: inbox, contact: create(:contact, account: account)) }
+ let(:conversation) { create(:conversation, account: account, inbox: inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact) }
+ let(:state) { { account_id: account.id, conversation: { id: conversation.id }, contact_inbox: { id: contact_inbox.id, hmac_verified: false } } }
+ let(:tool_context) { Struct.new(:state).new(state) }
+ let(:verified_email) { nil }
+
+ before do
+ custom_tool.update!(http_method: 'GET', endpoint_url: 'https://example.com/orders/123', response_template: nil,
+ settings: { 'requires_email_verification' => true })
+ stub_request(:get, 'https://example.com/orders/123').to_return(status: 200, body: '{"status": "success"}')
+ verification = instance_double(Captain::EmailVerification, verified_email: verified_email)
+ allow(Captain::EmailVerification).to receive(:new).with(conversation).and_return(verification)
+ end
+
+ it 'does not call the endpoint for a customer without a verified email' do
+ result = tool.perform(tool_context)
+
+ expect(result).to include('has not verified an email')
+ expect(WebMock).not_to have_requested(:get, 'https://example.com/orders/123')
+ end
+
+ it 'does not accept HMAC verification in place of a verified email' do
+ contact_inbox.update!(hmac_verified: true)
+ state[:contact_inbox][:hmac_verified] = true
+
+ tool.perform(tool_context)
+
+ expect(WebMock).not_to have_requested(:get, 'https://example.com/orders/123')
+ end
+
+ it 'does not call the endpoint when the run has no conversation' do
+ state.delete(:conversation)
+
+ result = tool.perform(tool_context)
+
+ expect(result).to include('has not verified an email')
+ expect(WebMock).not_to have_requested(:get, 'https://example.com/orders/123')
+ end
+
+ it 'does not look up a conversation from another account' do
+ other_conversation = create(:conversation)
+ allow(Captain::EmailVerification).to receive(:new).with(other_conversation)
+ .and_return(instance_double(Captain::EmailVerification, verified_email: '[email protected]'))
+ state[:conversation][:id] = other_conversation.id
+
+ tool.perform(tool_context)
+
+ expect(WebMock).not_to have_requested(:get, 'https://example.com/orders/123')
+ end
+
+ context 'when the customer has verified an email' do
+ let(:verified_email) { '[email protected]' }
+
+ it 'calls the endpoint' do
+ result = tool.perform(tool_context)
+
+ expect(result).to eq('{"status": "success"}')
+ expect(WebMock).to have_requested(:get, 'https://example.com/orders/123')
+ end
+ end
+
+ context 'when the request takes an email from the model' do
+ let(:verified_email) { '[email protected]' }
+ let(:request_stub) { stub_request(:get, %r{\Ahttps://example.com/customers}).to_return(status: 200, body: '{"found": true}') }
+
+ before do
+ custom_tool.update!(endpoint_url: 'https://example.com/customers?email={{ email | url_encode }}&note={{ note | url_encode }}',
+ param_schema: [{ 'name' => 'email', 'type' => 'string', 'description' => 'Customer email' },
+ { 'name' => 'note', 'type' => 'string', 'description' => 'Note' }])
+ request_stub
+ end
+
+ # Binding the email is what a verified email parameter is for. The setting alone only requires a verified customer.
+ it 'runs with the email the model passes once the customer has verified one' do
+ tool.perform(tool_context, email: '[email protected]')
+
+ expect(WebMock).to have_requested(:get, 'https://example.com/customers?email=someone%40example.com&note=')
+ end
+ end
+
+ it 'does not block a tool that does not require verification' do
+ custom_tool.update!(settings: {})
+
+ expect(tool.perform(tool_context)).to eq('{"status": "success"}')
+ end
+ end
+
+ it 'ignores a run state that says an admin or an agent is the user' do
+ custom_tool.update!(settings: { 'requires_email_verification' => true })
+ stub_request(:get, %r{\Ahttps://example.com}).to_return(status: 200, body: '{}')
+
+ result = tool.perform(Struct.new(:state).new({ source: 'playground' }))
+
+ expect(result).to include('has not verified an email')
+ expect(WebMock).not_to have_requested(:get, %r{\Ahttps://example.com})
+ end
+ end
+end
diff --git a/spec/enterprise/lib/captain/tools/send_email_verification_code_tool_spec.rb b/spec/enterprise/lib/captain/tools/send_email_verification_code_tool_spec.rb
index 946b948088e..ff7edffd432 100644
--- a/spec/enterprise/lib/captain/tools/send_email_verification_code_tool_spec.rb
+++ b/spec/enterprise/lib/captain/tools/send_email_verification_code_tool_spec.rb
@@ -4,12 +4,12 @@ RSpec.describe Captain::Tools::SendEmailVerificationCodeTool, type: :model do
let(:account) { create(:account) }
let(:assistant) { create(:captain_assistant, account: account) }
let(:inbox) { create(:inbox, account: account) }
- let(:contact_inbox) { create(:contact_inbox, inbox: inbox, contact: create(:contact, account: account)) }
+ let(:conversation) { create(:conversation, account: account, inbox: inbox) }
let(:tool) { described_class.new(assistant) }
- let(:tool_context) { Struct.new(:state).new({ contact_inbox: { id: contact_inbox.id } }) }
+ let(:tool_context) { Struct.new(:state).new({ conversation: { id: conversation.id } }) }
let(:verification) { instance_double(Captain::EmailVerification) }
- before { allow(Captain::EmailVerification).to receive(:new).with(contact_inbox).and_return(verification) }
+ before { allow(Captain::EmailVerification).to receive(:new).with(conversation).and_return(verification) }
it 'tells Captain the code was emailed and what to do next' do
allow(verification).to receive(:send_code).with('[email protected]').and_return(:sent)
@@ -49,9 +49,8 @@ RSpec.describe Captain::Tools::SendEmailVerificationCodeTool, type: :model do
expect(tool.perform(Struct.new(:state).new({}), email: '[email protected]')).to eq('Email verification is not available in this conversation')
end
- it 'does not use a contact inbox from another account' do
- other_contact_inbox = create(:contact_inbox)
- context = Struct.new(:state).new({ contact_inbox: { id: other_contact_inbox.id } })
+ it 'does not use a conversation from another account' do
+ context = Struct.new(:state).new({ conversation: { id: create(:conversation).id } })
expect(tool.perform(context, email: '[email protected]')).to eq('Email verification is not available in this conversation')
end
diff --git a/spec/enterprise/lib/captain/tools/verify_email_code_tool_spec.rb b/spec/enterprise/lib/captain/tools/verify_email_code_tool_spec.rb
index 1313bad1606..b817c4a8640 100644
--- a/spec/enterprise/lib/captain/tools/verify_email_code_tool_spec.rb
+++ b/spec/enterprise/lib/captain/tools/verify_email_code_tool_spec.rb
@@ -4,19 +4,19 @@ RSpec.describe Captain::Tools::VerifyEmailCodeTool, type: :model do
let(:account) { create(:account) }
let(:assistant) { create(:captain_assistant, account: account) }
let(:inbox) { create(:inbox, account: account) }
- let(:contact_inbox) { create(:contact_inbox, inbox: inbox, contact: create(:contact, account: account)) }
+ let(:conversation) { create(:conversation, account: account, inbox: inbox) }
let(:tool) { described_class.new(assistant) }
- let(:tool_context) { Struct.new(:state).new({ contact_inbox: { id: contact_inbox.id } }) }
- let(:verification) { instance_double(Captain::EmailVerification, verified_email: '[email protected]', attempts_left: 3) }
+ let(:tool_context) { Struct.new(:state).new({ conversation: { id: conversation.id } }) }
+ let(:verification) { instance_double(Captain::EmailVerification, verified_email: '[email protected]', attempts_left: 3, verified_ttl: 1.hour) }
- before { allow(Captain::EmailVerification).to receive(:new).with(contact_inbox).and_return(verification) }
+ before { allow(Captain::EmailVerification).to receive(:new).with(conversation).and_return(verification) }
it 'confirms the verified address and records it for the rest of the run' do
allow(verification).to receive(:verify).with('482913').and_return(:verified)
result = tool.perform(tool_context, code: '482913')
- expect(result).to start_with('Verified.').and include('[email protected]').and include('24 hours')
+ expect(result).to start_with('Verified.').and include('[email protected]').and include('This stays valid for 1 hour.')
expect(tool_context.state[:verified_email]).to eq('[email protected]')
end
diff --git a/spec/enterprise/models/captain/assistant_spec.rb b/spec/enterprise/models/captain/assistant_spec.rb
index b183199ba6c..0bc39d9fb88 100644
--- a/spec/enterprise/models/captain/assistant_spec.rb
+++ b/spec/enterprise/models/captain/assistant_spec.rb
@@ -369,5 +369,54 @@ RSpec.describe Captain::Assistant, type: :model do
)
expect(instructions).not_to include('# Human Handoff Protocol', scenario.title, "handoff_to_#{scenario.handoff_key}")
end
+
+ it 'names the verified address even when contact information is not allowed' do
+ state = { channel_type: 'Channel::WebWidget', contact_inbox: { id: 1, hmac_verified: false }, verified_email: '[email protected]',
+ contact: { id: 1, name: 'Jane Doe', email: '[email protected]' }, assistant_config: {} }
+
+ instructions = assistant.agent_instructions(Struct.new(:context).new({ state: state }))
+
+ expect(instructions).to include('Email verified by one-time code: Yes, [email protected]')
+ expect(instructions).not_to include('# Contact Information', 'Jane Doe')
+ end
+
+ it 'tells Captain to use only IDs found for the verified email' do
+ state = { channel_type: 'Channel::WebWidget', conversation: { id: 1 }, verified_email: '[email protected]', assistant_config: {} }
+
+ instructions = assistant.agent_instructions(Struct.new(:context).new({ state: state }))
+
+ expect(instructions).to include('use only an ID that a tool returned in this conversation for [email protected]')
+ end
+
+ it 'leaves out the ID rule before the customer verifies' do
+ state = { channel_type: 'Channel::WebWidget', conversation: { id: 1 }, can_verify_email: true, assistant_config: {} }
+
+ expect(assistant.agent_instructions(Struct.new(:context).new({ state: state }))).not_to include('use only an ID that a tool returned')
+ end
+
+ it 'gives the steps to verify on a messaging channel, without any HMAC status' do
+ state = { channel_type: 'Channel::Whatsapp', conversation: { id: 1 }, contact_inbox: { id: 1, hmac_verified: true }, can_verify_email: true,
+ assistant_config: {} }
+
+ instructions = assistant.agent_instructions(Struct.new(:context).new({ state: state }))
+
+ expect(instructions).to include('Email verified by one-time code: No', 'captain--tools--send_email_verification_code')
+ expect(instructions).not_to include('HMAC')
+ end
+
+ it 'gives the steps to verify in an email conversation too' do
+ state = { channel_type: 'Channel::Email', conversation: { id: 1 }, contact_inbox: { id: 1, hmac_verified: false }, can_verify_email: true,
+ assistant_config: {} }
+
+ instructions = assistant.agent_instructions(Struct.new(:context).new({ state: state }))
+
+ expect(instructions).to include('Email verified by one-time code: No', 'captain--tools--send_email_verification_code')
+ end
+
+ it 'leaves out the verification steps when Captain cannot verify the customer' do
+ state = { channel_type: 'Channel::WebWidget', conversation: { id: 1 }, assistant_config: {} }
+
+ expect(assistant.agent_instructions(Struct.new(:context).new({ state: state }))).not_to include('# Customer Identity')
+ end
end
end
diff --git a/spec/enterprise/services/captain/assistant/agent_runner_service_spec.rb b/spec/enterprise/services/captain/assistant/agent_runner_service_spec.rb
index f6f337c363a..d9002a9166f 100644
--- a/spec/enterprise/services/captain/assistant/agent_runner_service_spec.rb
+++ b/spec/enterprise/services/captain/assistant/agent_runner_service_spec.rb
@@ -49,6 +49,9 @@ RSpec.describe Captain::Assistant::AgentRunnerService do
allow(mock_runner).to receive(:on_run_complete).and_return(mock_runner)
allow(mock_agent).to receive(:register_handoffs)
allow(mock_scenario_agent).to receive(:register_handoffs)
+ # The runner adds the email verification tools with clone, so the doubles return themselves
+ allow(mock_agent).to receive_messages(tools: [], clone: mock_agent)
+ allow(mock_scenario_agent).to receive_messages(tools: [], clone: mock_scenario_agent)
end
describe '#initialize' do
@@ -112,11 +115,51 @@ RSpec.describe Captain::Assistant::AgentRunnerService do
expect(service.send(:build_and_wire_agents)).to eq([mock_agent, mock_scenario_agent])
end
+ context 'with a tool that has a verified parameter' do
+ before do
+ email_param = { 'name' => 'email', 'type' => 'string', 'description' => 'Email', 'source' => 'verified.email' }
+ create(:captain_custom_tool, account: account, assistant: assistant, endpoint_url: 'https://example.com/c?email={{ email }}',
+ param_schema: [email_param])
+ allow(assistant).to receive(:agent).and_call_original
+ allow(assistant).to receive(:scenarios).and_return(instance_double(Captain::Scenario, enabled: []))
+ end
+
+ def http_tool_for(source)
+ service = described_class.new(assistant: assistant, conversation: conversation, run_options: run_options(source: source))
+ service.send(:build_and_wire_agents).first.tools.find { |tool| tool.is_a?(Captain::Tools::HttpTool) }
+ end
+
+ def email_parameters(source)
+ http_tool_for(source).class.declared_parameters.keys
+ end
+
+ it 'uses the customer tool in a customer conversation' do
+ expect(http_tool_for(nil)).to be_a(Captain::Tools::PublicHttpTool)
+ end
+
+ it 'uses the Copilot tool where an admin or an agent is the user' do
+ expect(http_tool_for('playground')).to be_a(Captain::Tools::CopilotHttpTool)
+ end
+
+ it 'gives the model no email parameter in a customer conversation' do
+ expect(email_parameters(nil)).to be_empty
+ end
+
+ it 'gives the model an email parameter in the playground' do
+ expect(email_parameters('playground')).to contain_exactly(:email)
+ end
+
+ it 'gives the model an email parameter for a reply suggestion' do
+ expect(email_parameters('copilot_reply_suggestion')).to contain_exactly(:email)
+ end
+ end
+
it 'keeps only reply-safe tools and excludes scenarios in reply suggestion mode' do
faq_tool = Captain::Tools::FaqLookupTool.new(assistant)
handoff_tool = Captain::Tools::HandoffTool.new(assistant)
- get_tool = Captain::Tools::HttpTool.new(assistant, create(:captain_custom_tool, account: account, http_method: 'GET'))
- post_tool = Captain::Tools::HttpTool.new(assistant, create(:captain_custom_tool, account: account, http_method: 'POST'))
+ get_custom_tool = create(:captain_custom_tool, account: account, http_method: 'GET')
+ get_tool = get_custom_tool.tool(assistant)
+ post_tool = create(:captain_custom_tool, account: account, http_method: 'POST').tool(assistant)
private_note_tool = Captain::Tools::AddPrivateNoteTool.new(assistant)
assistant_agent = Agents::Agent.new(name: 'assistant', tools: [faq_tool, handoff_tool, get_tool, post_tool, private_note_tool])
service = described_class.new(
@@ -130,7 +173,10 @@ RSpec.describe Captain::Assistant::AgentRunnerService do
configured_assistant = service.send(:build_and_wire_agents).sole
- expect(configured_assistant.tools).to contain_exactly(faq_tool, get_tool)
+ expect(configured_assistant.tools.first).to be(faq_tool)
+ expect(configured_assistant.tools.second).to be_a(Captain::Tools::CopilotHttpTool)
+ expect(configured_assistant.tools.second.custom_tool).to eq(get_custom_tool)
+ expect(configured_assistant.tools.size).to eq(2)
expect(configured_assistant.handoff_agents).to be_empty
end
@@ -1008,6 +1054,24 @@ RSpec.describe Captain::Assistant::AgentRunnerService do
)
end
+ it 'lets Captain verify the customer when an enabled tool needs a verified email' do
+ create(:captain_custom_tool, account: account, assistant: assistant, settings: { 'requires_email_verification' => true })
+
+ expect(service.send(:build_state)[:can_verify_email]).to be(true)
+ end
+
+ it 'does not let Captain verify the customer when no tool needs a verified email' do
+ expect(service.send(:build_state)[:can_verify_email]).to be(false)
+ end
+
+ it 'does not let Captain verify anyone where an admin or an agent is the user' do
+ create(:captain_custom_tool, account: account, assistant: assistant, settings: { 'requires_email_verification' => true })
+ service = described_class.new(assistant: assistant, conversation: conversation,
+ run_options: described_class::RunOptions.new(source: 'playground'))
+
+ expect(service.send(:build_state)[:can_verify_email]).to be(false)
+ end
+
it 'does not include campaign when conversation has no campaign' do
state = service.send(:build_state)
diff --git a/spec/enterprise/services/captain/email_verification_spec.rb b/spec/enterprise/services/captain/email_verification_spec.rb
index 4bb3d3026ce..cb6e96d7ab3 100644
--- a/spec/enterprise/services/captain/email_verification_spec.rb
+++ b/spec/enterprise/services/captain/email_verification_spec.rb
@@ -4,7 +4,8 @@ RSpec.describe Captain::EmailVerification do
let(:account) { create(:account) }
let(:inbox) { create(:inbox, account: account) }
let(:contact_inbox) { create(:contact_inbox, inbox: inbox, contact: create(:contact, account: account)) }
- let(:verification) { described_class.new(contact_inbox) }
+ let(:conversation) { create(:conversation, account: account, inbox: inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact) }
+ let(:verification) { described_class.new(conversation) }
let(:email) { "customer-#{SecureRandom.hex(4)}@example.com" }
let(:emailed_codes) { [] }
let(:mailer) { class_double(Captain::EmailVerificationMailer) }
@@ -18,6 +19,10 @@ RSpec.describe Captain::EmailVerification do
end
end
+ def conversation_for(conversation_contact_inbox)
+ create(:conversation, account: account, inbox: inbox, contact_inbox: conversation_contact_inbox, contact: conversation_contact_inbox.contact)
+ end
+
def wrong_code
emailed_codes.last == '000000' ? '111111' : '000000'
end
@@ -71,7 +76,13 @@ RSpec.describe Captain::EmailVerification do
expect(verification.send_code(email)).to eq(:sent)
end
- it 'allows 5 codes per hour from one contact inbox' do
+ it 'allows 5 codes per hour from one contact inbox, across its conversations' do
+ results = Array.new(6) { described_class.new(conversation_for(contact_inbox)).send_code("customer-#{SecureRandom.hex(4)}@example.com") }
+
+ expect(results).to eq(([:sent] * 5) + [:rate_limited])
+ end
+
+ it 'allows 5 codes per hour from one conversation' do
results = Array.new(6) { verification.send_code("customer-#{SecureRandom.hex(4)}@example.com") }
expect(results).to eq(([:sent] * 5) + [:rate_limited])
@@ -82,13 +93,12 @@ RSpec.describe Captain::EmailVerification do
5.times { verification.send_code(email) }
other_contact_inbox = create(:contact_inbox, inbox: inbox, contact: create(:contact, account: account))
- expect(described_class.new(other_contact_inbox).send_code(email)).to eq(:sent)
+ expect(described_class.new(conversation_for(other_contact_inbox)).send_code(email)).to eq(:sent)
end
it 'allows 5 codes per hour to one email address across contact inboxes' do
results = Array.new(6) do
- other_contact_inbox = create(:contact_inbox, inbox: inbox, contact: create(:contact, account: account))
- described_class.new(other_contact_inbox).send_code(email)
+ described_class.new(conversation_for(create(:contact_inbox, inbox: inbox, contact: create(:contact, account: account)))).send_code(email)
end
expect(results).to eq(([:sent] * 5) + [:rate_limited])
@@ -155,8 +165,8 @@ RSpec.describe Captain::EmailVerification do
expect(verification.verify(emailed_codes.last)).to eq(:expired)
end
- it 'does not accept a code sent to another contact inbox' do
- other = described_class.new(create(:contact_inbox, inbox: inbox, contact: create(:contact, account: account)))
+ it 'does not accept a code sent in another conversation' do
+ other = described_class.new(conversation_for(contact_inbox))
other.send_code(email)
other_code = emailed_codes.last
verification.send_code(email)
@@ -165,12 +175,26 @@ RSpec.describe Captain::EmailVerification do
expect(verification.verify(other_code)).to eq(:invalid_code)
end
- it 'keeps the verification to the contact inbox that entered the code' do
+ it 'keeps the verification to the conversation that entered the code' do
verification.send_code(email)
verification.verify(emailed_codes.last)
- other_contact_inbox = create(:contact_inbox, inbox: inbox, contact: contact_inbox.contact)
- expect(described_class.new(other_contact_inbox).verified_email).to be_nil
+ expect(described_class.new(conversation_for(contact_inbox)).verified_email).to be_nil
+ end
+
+ it 'keeps the verification for 1 hour' do
+ verification.send_code(email)
+ verification.verify(emailed_codes.last)
+
+ expect(Redis::Alfred.ttl(format(Redis::RedisKeys::CAPTAIN_EMAIL_VERIFICATION_VERIFIED, conversation_id: conversation.id))).to eq(1.hour.to_i)
+ end
+ end
+
+ describe '#verified_ttl' do
+ it 'keeps an email conversation verified for 3 hours' do
+ conversation.inbox.update!(channel: create(:channel_email, account: account))
+
+ expect(verification.verified_ttl).to eq(3.hours)
end
end
end
diff --git a/spec/enterprise/services/captain/tools_manifest/install_service_spec.rb b/spec/enterprise/services/captain/tools_manifest/install_service_spec.rb
index 2a76135dd1f..23da2e4fcfd 100644
--- a/spec/enterprise/services/captain/tools_manifest/install_service_spec.rb
+++ b/spec/enterprise/services/captain/tools_manifest/install_service_spec.rb
@@ -80,15 +80,14 @@ RSpec.describe Captain::ToolsManifest::InstallService do
expect(install.map(&:requires_email_verification?)).to eq([true, false])
end
- it 'applies the setting on a reinstall when the same commit was installed without it' do
+ it 'keeps a setting the user changed when the same commit is installed again' do
tools = install
- # An older version records the commit but ignores the key
- tools.first.update_columns(settings: {}) # rubocop:disable Rails/SkipsModelValidations
+ tools.first.update!(settings: { 'requires_email_verification' => false })
parsed_manifest = Captain::ToolsManifest::Manifest.parse(manifest.to_yaml)
- expect(described_class.complete?(assistant.custom_tools.to_a, parsed_manifest, latest_revision)).to be(false)
- expect(install.map(&:requires_email_verification?)).to eq([true, false])
+ expect(described_class.complete?(assistant.custom_tools.to_a, parsed_manifest, latest_revision)).to be(true)
+ expect(install.map(&:requires_email_verification?)).to eq([false, false])
end
end
@@ -207,14 +206,14 @@ RSpec.describe Captain::ToolsManifest::InstallService do
expect(updated.source_metadata['installation_id']).to eq(installed_tools.first.source_metadata['installation_id'])
end
- it 'follows the manifest when a tool starts requiring email verification' do
+ it 'keeps the email verification setting of a tool that already exists' do
manifest['tools'].first['requires_email_verification'] = true
stub_request(:get, manifest_url).to_return(status: 200, body: manifest.to_yaml)
updated = install.find { |tool| tool.source_metadata['tool_id'] == 'get_order' }
expect(updated.id).to eq(installed_tools.first.id)
- expect(updated.requires_email_verification?).to be(true)
+ expect(updated.requires_email_verification?).to be(false)
end
it 'creates tools added to the manifest and deletes tools it dropped' do