@bikdotai/bik-component-library 0.0.849-beta.1 → 0.0.849-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/components/agent-builder/components/MentionEditor.js.map +1 -1
- package/dist/cjs/components/agent-builder/utils/mentionSerialization.js +4 -4
- package/dist/cjs/components/agent-builder/utils/mentionSerialization.js.map +1 -1
- package/dist/esm/components/agent-builder/components/MentionEditor.d.ts +2 -2
- package/dist/esm/components/agent-builder/components/MentionEditor.js.map +1 -1
- package/dist/esm/components/agent-builder/utils/mentionSerialization.d.ts +1 -1
- package/dist/esm/components/agent-builder/utils/mentionSerialization.js +10 -10
- package/dist/esm/components/agent-builder/utils/mentionSerialization.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MentionEditor.js","sources":["../../../../../src/components/agent-builder/components/MentionEditor.tsx"],"sourcesContent":["import { BikEditor, BikEditorRef, MentionItem } from '@src/editor';\nimport React, {\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState,\n} from 'react';\nimport { BodyCaption, TitleSmall } from '@src/components/TypographyStyle';\nimport { COLORS } from '@src/constants/Theme';\nimport type {\n\tVariableListInterfaceV3,\n\tVariableV3,\n} from '../../variable-picker-v3/model';\nimport { AgentTool } from '../AgentBuilder.model';\nimport {\n\tAiTextAreaShell,\n\tFieldBlock,\n\tFieldLabelRow,\n} from '../AgentBuilder.styled';\nimport { AGENT_EDITOR_STYLE } from '../constants/editorStyle';\nimport type { ToolAction, ToolSource } from '../constants/tools';\nimport {\n\tbuildMentionHtml,\n\tbuildVariableMentionItems,\n\teditorDocToInstructions,\n\tinstructionsToEditorHtml,\n\tMentionKindMeta,\n\tvariableTokenName,\n} from '../utils/mentionSerialization';\nimport { MentionPicker } from './MentionPicker';\n\ntype InsertFn = (kind: 'tool' | 'subagent', id: string, label?: string) => void;\n\ninterface MentionEditorProps {\n\tlabel: string;\n\tvalue: string;\n\tonChange: (text: string) => void;\n\tmaxLength: number;\n\tplaceholder?: string;\n\tminHeight?: string;\n\t/** Changing this remounts the editor with fresh content. */\n\tresetKey?: string | number;\n\t/** Items shown in the `@` picker (tools, and sub-agents where allowed). */\n\tmentionItems: MentionItem[];\n\t/** Tools used to serialise mention nodes back to `{{tool:KEY}}`. */\n\ttools: AgentTool[];\n\t/** Called when an item is picked from the `@` menu (to attach it upstream). */\n\tonMentionSelect?: (kind: 'tool' | 'subagent', id: string) => void;\n\tonFocus?: () => void;\n\t/** Receives an insert-at-cursor fn (and null on unmount) for side-panel adds. */\n\tregisterInsert?: (fn: InsertFn | null) => void;\n\t/**\n\t * When set, the `@` picker's Sub-agent view shows a \"Create new\" row that calls\n\t * this (opens the create-sub-agent drawer). Omit to hide it (e.g. the drawer's\n\t * own editors, which can't nest sub-agents).\n\t */\n\tonCreateSubAgent?: () => void;\n\t/**\n\t * Built-in tool actions (Rest API / Handover to email) shown in the `@` picker's\n\t * Tools view. Picking one opens its drawer instead of inserting a mention.\n\t */\n\ttoolActions?: ToolAction[];\n\tintegrationStatus?: Partial<Record<ToolSource, boolean>>;\n\tonConnectIntegration?: (source: ToolSource) => void;\n\t/**\n\t * Variable catalog for the `@` picker's \"Variables\" view. Picking one inserts\n\t * a `Variable: <name>` mention chip at the cursor, persisted as the bare\n\t * `{{actualValue}}` token. Omit to hide the category.\n\t */\n\tvariablesData?: VariableListInterfaceV3[];\n\t/** Optional action(s) rendered inside the shell, below the editor. */\n\taction?: React.ReactNode;\n\t'data-test'?: string;\n}\n\n/**\n * Presentational BikEditor field with `@` mentions. Stores firebase token text\n * (`{{tool:KEY}}` / `{{subagent:ID}}`). Context-free — both the builder's\n * Step-3 fields and the create-sub-agent drawer compose it.\n */\nexport const MentionEditor: React.FC<MentionEditorProps> = ({\n\tlabel,\n\tvalue,\n\tonChange,\n\tmaxLength,\n\tplaceholder,\n\tminHeight = '200px',\n\tresetKey,\n\tmentionItems,\n\ttools,\n\tonMentionSelect,\n\tonFocus,\n\tregisterInsert,\n\tonCreateSubAgent,\n\ttoolActions,\n\tintegrationStatus,\n\tonConnectIntegration,\n\tvariablesData,\n\taction,\n\t...rest\n}) => {\n\tconst editorRef = useRef<BikEditorRef>(null);\n\tconst [count, setCount] = useState(value.length);\n\n\t// The picker dismissed itself already (stripping the \"@\" + query) — drop a\n\t// `Variable: <name>` mention chip at the cursor, same shape as tool /\n\t// sub-agent chips. `editorDocToInstructions` serializes it back to the bare\n\t// `{{name}}` token (no kind prefix).\n\tconst onSelectVariable = useCallback((variable: VariableV3) => {\n\t\tconst name = variableTokenName(variable.actualValue);\n\t\teditorRef.current?.insertInlineContent(\n\t\t\t`${buildMentionHtml(\n\t\t\t\tname,\n\t\t\t\t`Variable: ${variable.displayName}`,\n\t\t\t\t'variable',\n\t\t\t)} `,\n\t\t);\n\t}, []);\n\n\tconst insert = useCallback<InsertFn>(\n\t\t(kind, id, overrideLabel) => {\n\t\t\tconst editor = editorRef.current;\n\t\t\tif (!editor) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst item = mentionItems.find(\n\t\t\t\t(m) =>\n\t\t\t\t\tString(m.id) === String(id) &&\n\t\t\t\t\t(m.meta as unknown as MentionKindMeta | undefined)?.kind === kind,\n\t\t\t);\n\t\t\tconst finalLabel = overrideLabel ?? item?.label ?? id;\n\t\t\teditor.insertInlineContent(\n\t\t\t\t`${buildMentionHtml(String(id), finalLabel, kind)} `,\n\t\t\t);\n\t\t},\n\t\t[mentionItems],\n\t);\n\n\tuseEffect(() => {\n\t\tif (!registerInsert) {\n\t\t\treturn;\n\t\t}\n\t\tregisterInsert(insert);\n\t\treturn () => registerInsert(null);\n\t}, [registerInsert, insert]);\n\n\t// Mount-only initial HTML; recomputed (editor remounted via key) on resetKey.\n\t// Variable items are merged in so stored `{{name}}` tokens rehydrate as chips.\n\tconst initialHtml = useMemo(\n\t\t() =>\n\t\t\tinstructionsToEditorHtml(value, [\n\t\t\t\t...mentionItems,\n\t\t\t\t...buildVariableMentionItems(variablesData),\n\t\t\t]),\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[resetKey],\n\t);\n\n\tuseEffect(\n\t\t() => setCount(value.length),\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[resetKey],\n\t);\n\n\treturn (\n\t\t<FieldBlock>\n\t\t\t<FieldLabelRow>\n\t\t\t\t<TitleSmall color={COLORS.content.primary}>{label}</TitleSmall>\n\t\t\t\t<BodyCaption color={COLORS.content.secondary}>\n\t\t\t\t\t{count}/{maxLength}\n\t\t\t\t</BodyCaption>\n\t\t\t</FieldLabelRow>\n\n\t\t\t<AiTextAreaShell minHeight={minHeight} data-test={rest['data-test']}>\n\t\t\t\t<BikEditor\n\t\t\t\t\tkey={resetKey}\n\t\t\t\t\tref={editorRef}\n\t\t\t\t\tinitialContent={initialHtml}\n\t\t\t\t\tplaceholder={placeholder}\n\t\t\t\t\t// Soft limit: blocks typing past the cap but lets a paste through\n\t\t\t\t\t// (overflow rendered grey) instead of rejecting the whole paste.\n\t\t\t\t\tcharacterLimit={maxLength}\n\t\t\t\t\tminHeight=\"120px\"\n\t\t\t\t\tmaxHeight=\"320px\"\n\t\t\t\t\tstyle={{ border: 'none' }}\n\t\t\t\t\teditorStyle={AGENT_EDITOR_STYLE}\n\t\t\t\t\tonFocus={onFocus}\n\t\t\t\t\tmentions={{\n\t\t\t\t\t\tagents: mentionItems,\n\t\t\t\t\t\tremoveTriggerOnDismiss: true,\n\t\t\t\t\t\trenderDropdown: (props) => (\n\t\t\t\t\t\t\t<MentionPicker\n\t\t\t\t\t\t\t\t{...props}\n\t\t\t\t\t\t\t\tonCreateSubAgent={onCreateSubAgent}\n\t\t\t\t\t\t\t\ttoolActions={toolActions}\n\t\t\t\t\t\t\t\tintegrationStatus={integrationStatus}\n\t\t\t\t\t\t\t\tonConnectIntegration={onConnectIntegration}\n\t\t\t\t\t\t\t\tvariablesData={variablesData}\n\t\t\t\t\t\t\t\tonSelectVariable={onSelectVariable}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t),\n\t\t\t\t\t\tonSelect: (item) => {\n\t\t\t\t\t\t\tconst kind = (item.meta as unknown as MentionKindMeta | undefined)\n\t\t\t\t\t\t\t\t?.kind;\n\t\t\t\t\t\t\t// Variables never come through this path (they use the embedded\n\t\t\t\t\t\t\t// picker's onSelectVariable) and have nothing to attach upstream.\n\t\t\t\t\t\t\tif (kind === 'tool' || kind === 'subagent') {\n\t\t\t\t\t\t\t\tonMentionSelect?.(kind, String(item.id));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t}}\n\t\t\t\t\tonChange={(snapshot) => {\n\t\t\t\t\t\tsetCount(snapshot.characterCount);\n\t\t\t\t\t\tconst doc = editorRef.current?.getJSON() ?? null;\n\t\t\t\t\t\tonChange(editorDocToInstructions(doc, tools));\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t\t{action}\n\t\t\t</AiTextAreaShell>\n\t\t</FieldBlock>\n\t);\n};\n"],"names":["MentionEditor","label","value","onChange","maxLength","placeholder","minHeight","resetKey","mentionItems","tools","onMentionSelect","onFocus","registerInsert","onCreateSubAgent","toolActions","integrationStatus","onConnectIntegration","variablesData","action","rest","editorRef","useRef","count","setCount","useState","onSelectVariable","useCallback","variable","name","variableTokenName","buildMentionHtml","insert","kind","id","overrideLabel","editor","item","m","finalLabel","useEffect","initialHtml","useMemo","instructionsToEditorHtml","buildVariableMentionItems","FieldBlock","jsxs","FieldLabelRow","jsx","TitleSmall","COLORS","BodyCaption","AiTextAreaShell","BikEditor","AGENT_EDITOR_STYLE","props","MentionPicker","snapshot","doc","editorDocToInstructions"],"mappings":"+ZAiFaA,EAA8C,CAAC,CAC3D,MAAAC,EACA,MAAAC,EACA,SAAAC,EACA,UAAAC,EACA,YAAAC,EACA,UAAAC,EAAY,QACZ,SAAAC,EACA,aAAAC,EACA,MAAAC,EACA,gBAAAC,EACA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MAACC,EAAAA,WAAA,CAAW,MAAOC,EAAAA,OAAO,QAAQ,QAAU,SAAAhD,EAAM,EAClD4C,EAAAA,KAACK,EAAAA,YAAA,CAAY,MAAOD,EAAAA,OAAO,QAAQ,UACjC,SAAA,CAAA3B,EAAM,IAAElB,CAAA,CAAA,CACV,CAAA,EACD,SAEC+C,EAAAA,gBAAA,CAAgB,UAAA7C,EAAsB,YAAWa,EAAK,WAAW,EACjE,SAAA,CAAA4B,EAAAA,IAACK,EAAAA,UAAA,CAEA,IAAKhC,EACL,eAAgBoB,EAChB,YAAAnC,EAGA,eAAgBD,EAChB,UAAU,QACV,UAAU,QACV,MAAO,CAAE,OAAQ,MAAA,EACjB,YAAaiD,EAAAA,mBACb,QAAA1C,EACA,SAAU,CACT,OAAQH,EACR,uBAAwB,GACxB,eAAiB8C,GAChBP,EAAAA,IAACQ,EAAAA,cAAA,CACC,GAAGD,EACJ,iBAAAzC,EACA,YAAAC,EACA,kBAAAC,EACA,qBAAAC,EACA,cAAAC,EACA,iBAAAQ,CAAA,CAAA,EAGF,SAAWW,GAAS,CACnB,MAAMJ,EAAQI,EAAK,MAChB,MAGCJ,IAAS,QAAUA,IAAS,aAC/BtB,IAAkBsB,EAAM,OAAOI,EAAK,EAAE,CAAC,CAEzC,CAAA,EAED,SAAWoB,GAAa,CACvBjC,EAASiC,EAAS,cAAc,EAChC,MAAMC,EAAMrC,EAAU,SAAS,QAAA,GAAa,KAC5CjB,EAASuD,EAAAA,wBAAwBD,EAAKhD,CAAK,CAAC,CAC7C,CAAA,EAxCKF,CAAA,EA0CLW,CAAA,CAAA,CACF,CAAA,EACD,CAEF"}
|
|
1
|
+
{"version":3,"file":"MentionEditor.js","sources":["../../../../../src/components/agent-builder/components/MentionEditor.tsx"],"sourcesContent":["import { BikEditor, BikEditorRef, MentionItem } from '@src/editor';\nimport React, {\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState,\n} from 'react';\nimport { BodyCaption, TitleSmall } from '@src/components/TypographyStyle';\nimport { COLORS } from '@src/constants/Theme';\nimport type {\n\tVariableListInterfaceV3,\n\tVariableV3,\n} from '../../variable-picker-v3/model';\nimport { AgentTool } from '../AgentBuilder.model';\nimport {\n\tAiTextAreaShell,\n\tFieldBlock,\n\tFieldLabelRow,\n} from '../AgentBuilder.styled';\nimport { AGENT_EDITOR_STYLE } from '../constants/editorStyle';\nimport type { ToolAction, ToolSource } from '../constants/tools';\nimport {\n\tbuildMentionHtml,\n\tbuildVariableMentionItems,\n\teditorDocToInstructions,\n\tinstructionsToEditorHtml,\n\tMentionKindMeta,\n\tvariableTokenName,\n} from '../utils/mentionSerialization';\nimport { MentionPicker } from './MentionPicker';\n\ntype InsertFn = (kind: 'tool' | 'subagent', id: string, label?: string) => void;\n\ninterface MentionEditorProps {\n\tlabel: string;\n\tvalue: string;\n\tonChange: (text: string) => void;\n\tmaxLength: number;\n\tplaceholder?: string;\n\tminHeight?: string;\n\t/** Changing this remounts the editor with fresh content. */\n\tresetKey?: string | number;\n\t/** Items shown in the `@` picker (tools, and sub-agents where allowed). */\n\tmentionItems: MentionItem[];\n\t/** Tools used to serialise mention nodes back to `{{tool:KEY}}`. */\n\ttools: AgentTool[];\n\t/** Called when an item is picked from the `@` menu (to attach it upstream). */\n\tonMentionSelect?: (kind: 'tool' | 'subagent', id: string) => void;\n\tonFocus?: () => void;\n\t/** Receives an insert-at-cursor fn (and null on unmount) for side-panel adds. */\n\tregisterInsert?: (fn: InsertFn | null) => void;\n\t/**\n\t * When set, the `@` picker's Sub-agent view shows a \"Create new\" row that calls\n\t * this (opens the create-sub-agent drawer). Omit to hide it (e.g. the drawer's\n\t * own editors, which can't nest sub-agents).\n\t */\n\tonCreateSubAgent?: () => void;\n\t/**\n\t * Built-in tool actions (Rest API / Handover to email) shown in the `@` picker's\n\t * Tools view. Picking one opens its drawer instead of inserting a mention.\n\t */\n\ttoolActions?: ToolAction[];\n\tintegrationStatus?: Partial<Record<ToolSource, boolean>>;\n\tonConnectIntegration?: (source: ToolSource) => void;\n\t/**\n\t * Variable catalog for the `@` picker's \"Variables\" view. Picking one inserts\n\t * a `Variable: <name>` mention chip at the cursor, persisted as a\n\t * `{{variable:<name>}}` token. Omit to hide the category.\n\t */\n\tvariablesData?: VariableListInterfaceV3[];\n\t/** Optional action(s) rendered inside the shell, below the editor. */\n\taction?: React.ReactNode;\n\t'data-test'?: string;\n}\n\n/**\n * Presentational BikEditor field with `@` mentions. Stores firebase token text\n * (`{{tool:KEY}}` / `{{subagent:ID}}`). Context-free — both the builder's\n * Step-3 fields and the create-sub-agent drawer compose it.\n */\nexport const MentionEditor: React.FC<MentionEditorProps> = ({\n\tlabel,\n\tvalue,\n\tonChange,\n\tmaxLength,\n\tplaceholder,\n\tminHeight = '200px',\n\tresetKey,\n\tmentionItems,\n\ttools,\n\tonMentionSelect,\n\tonFocus,\n\tregisterInsert,\n\tonCreateSubAgent,\n\ttoolActions,\n\tintegrationStatus,\n\tonConnectIntegration,\n\tvariablesData,\n\taction,\n\t...rest\n}) => {\n\tconst editorRef = useRef<BikEditorRef>(null);\n\tconst [count, setCount] = useState(value.length);\n\n\t// The picker dismissed itself already (stripping the \"@\" + query) — drop a\n\t// `Variable: <name>` mention chip at the cursor, same shape as tool /\n\t// sub-agent chips. `editorDocToInstructions` serializes it back to a\n\t// `{{variable:<name>}}` token.\n\tconst onSelectVariable = useCallback((variable: VariableV3) => {\n\t\tconst name = variableTokenName(variable.actualValue);\n\t\teditorRef.current?.insertInlineContent(\n\t\t\t`${buildMentionHtml(\n\t\t\t\tname,\n\t\t\t\t`Variable: ${variable.displayName}`,\n\t\t\t\t'variable',\n\t\t\t)} `,\n\t\t);\n\t}, []);\n\n\tconst insert = useCallback<InsertFn>(\n\t\t(kind, id, overrideLabel) => {\n\t\t\tconst editor = editorRef.current;\n\t\t\tif (!editor) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst item = mentionItems.find(\n\t\t\t\t(m) =>\n\t\t\t\t\tString(m.id) === String(id) &&\n\t\t\t\t\t(m.meta as unknown as MentionKindMeta | undefined)?.kind === kind,\n\t\t\t);\n\t\t\tconst finalLabel = overrideLabel ?? item?.label ?? id;\n\t\t\teditor.insertInlineContent(\n\t\t\t\t`${buildMentionHtml(String(id), finalLabel, kind)} `,\n\t\t\t);\n\t\t},\n\t\t[mentionItems],\n\t);\n\n\tuseEffect(() => {\n\t\tif (!registerInsert) {\n\t\t\treturn;\n\t\t}\n\t\tregisterInsert(insert);\n\t\treturn () => registerInsert(null);\n\t}, [registerInsert, insert]);\n\n\t// Mount-only initial HTML; recomputed (editor remounted via key) on resetKey.\n\t// Variable items are merged in so stored `{{name}}` tokens rehydrate as chips.\n\tconst initialHtml = useMemo(\n\t\t() =>\n\t\t\tinstructionsToEditorHtml(value, [\n\t\t\t\t...mentionItems,\n\t\t\t\t...buildVariableMentionItems(variablesData),\n\t\t\t]),\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[resetKey],\n\t);\n\n\tuseEffect(\n\t\t() => setCount(value.length),\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[resetKey],\n\t);\n\n\treturn (\n\t\t<FieldBlock>\n\t\t\t<FieldLabelRow>\n\t\t\t\t<TitleSmall color={COLORS.content.primary}>{label}</TitleSmall>\n\t\t\t\t<BodyCaption color={COLORS.content.secondary}>\n\t\t\t\t\t{count}/{maxLength}\n\t\t\t\t</BodyCaption>\n\t\t\t</FieldLabelRow>\n\n\t\t\t<AiTextAreaShell minHeight={minHeight} data-test={rest['data-test']}>\n\t\t\t\t<BikEditor\n\t\t\t\t\tkey={resetKey}\n\t\t\t\t\tref={editorRef}\n\t\t\t\t\tinitialContent={initialHtml}\n\t\t\t\t\tplaceholder={placeholder}\n\t\t\t\t\t// Soft limit: blocks typing past the cap but lets a paste through\n\t\t\t\t\t// (overflow rendered grey) instead of rejecting the whole paste.\n\t\t\t\t\tcharacterLimit={maxLength}\n\t\t\t\t\tminHeight=\"120px\"\n\t\t\t\t\tmaxHeight=\"320px\"\n\t\t\t\t\tstyle={{ border: 'none' }}\n\t\t\t\t\teditorStyle={AGENT_EDITOR_STYLE}\n\t\t\t\t\tonFocus={onFocus}\n\t\t\t\t\tmentions={{\n\t\t\t\t\t\tagents: mentionItems,\n\t\t\t\t\t\tremoveTriggerOnDismiss: true,\n\t\t\t\t\t\trenderDropdown: (props) => (\n\t\t\t\t\t\t\t<MentionPicker\n\t\t\t\t\t\t\t\t{...props}\n\t\t\t\t\t\t\t\tonCreateSubAgent={onCreateSubAgent}\n\t\t\t\t\t\t\t\ttoolActions={toolActions}\n\t\t\t\t\t\t\t\tintegrationStatus={integrationStatus}\n\t\t\t\t\t\t\t\tonConnectIntegration={onConnectIntegration}\n\t\t\t\t\t\t\t\tvariablesData={variablesData}\n\t\t\t\t\t\t\t\tonSelectVariable={onSelectVariable}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t),\n\t\t\t\t\t\tonSelect: (item) => {\n\t\t\t\t\t\t\tconst kind = (item.meta as unknown as MentionKindMeta | undefined)\n\t\t\t\t\t\t\t\t?.kind;\n\t\t\t\t\t\t\t// Variables never come through this path (they use the embedded\n\t\t\t\t\t\t\t// picker's onSelectVariable) and have nothing to attach upstream.\n\t\t\t\t\t\t\tif (kind === 'tool' || kind === 'subagent') {\n\t\t\t\t\t\t\t\tonMentionSelect?.(kind, String(item.id));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t}}\n\t\t\t\t\tonChange={(snapshot) => {\n\t\t\t\t\t\tsetCount(snapshot.characterCount);\n\t\t\t\t\t\tconst doc = editorRef.current?.getJSON() ?? null;\n\t\t\t\t\t\tonChange(editorDocToInstructions(doc, tools));\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t\t{action}\n\t\t\t</AiTextAreaShell>\n\t\t</FieldBlock>\n\t);\n};\n"],"names":["MentionEditor","label","value","onChange","maxLength","placeholder","minHeight","resetKey","mentionItems","tools","onMentionSelect","onFocus","registerInsert","onCreateSubAgent","toolActions","integrationStatus","onConnectIntegration","variablesData","action","rest","editorRef","useRef","count","setCount","useState","onSelectVariable","useCallback","variable","name","variableTokenName","buildMentionHtml","insert","kind","id","overrideLabel","editor","item","m","finalLabel","useEffect","initialHtml","useMemo","instructionsToEditorHtml","buildVariableMentionItems","FieldBlock","jsxs","FieldLabelRow","jsx","TitleSmall","COLORS","BodyCaption","AiTextAreaShell","BikEditor","AGENT_EDITOR_STYLE","props","MentionPicker","snapshot","doc","editorDocToInstructions"],"mappings":"+ZAiFaA,EAA8C,CAAC,CAC3D,MAAAC,EACA,MAAAC,EACA,SAAAC,EACA,UAAAC,EACA,YAAAC,EACA,UAAAC,EAAY,QACZ,SAAAC,EACA,aAAAC,EACA,MAAAC,EACA,gBAAAC,EACA,QAAAC,EACA,eAAAC,EACA,iBAAAC,EACA,YAAAC,EACA,kBAAAC,EACA,qBAAAC,EACA,cAAAC,EACA,OAAAC,EACA,GAAGC,CACJ,IAAM,CACL,MAAMC,EAAYC,EAAAA,OAAqB,IAAI,EACrC,CAACC,EAAOC,CAAQ,EAAIC,EAAAA,SAAStB,EAAM,MAAM,EAMzCuB,EAAmBC,cAAaC,GAAyB,CAC9D,MAAMC,EAAOC,EAAAA,kBAAkBF,EAAS,WAAW,EACnDP,EAAU,SAAS,oBAClB,GAAGU,EAAAA,iBACFF,EACA,aAAaD,EAAS,WAAW,GACjC,UAAA,CACA,QAAA,CAEH,EAAG,CAAA,CAAE,EAECI,EAASL,EAAAA,YACd,CAACM,EAAMC,EAAIC,IAAkB,CAC5B,MAAMC,EAASf,EAAU,QACzB,GAAI,CAACe,EACJ,OAED,MAAMC,EAAO5B,EAAa,KACxB6B,GACA,OAAOA,EAAE,EAAE,IAAM,OAAOJ,CAAE,GACzBI,EAAE,MAAiD,OAASL,CAAA,EAEzDM,EAAaJ,GAAiBE,GAAM,OAASH,EACnDE,EAAO,oBACN,GAAGL,EAAAA,iBAAiB,OAAOG,CAAE,EAA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,aAC/BtB,IAAkBsB,EAAM,OAAOI,EAAK,EAAE,CAAC,CAEzC,CAAA,EAED,SAAWoB,GAAa,CACvBjC,EAASiC,EAAS,cAAc,EAChC,MAAMC,EAAMrC,EAAU,SAAS,QAAA,GAAa,KAC5CjB,EAASuD,EAAAA,wBAAwBD,EAAKhD,CAAK,CAAC,CAC7C,CAAA,EAxCKF,CAAA,EA0CLW,CAAA,CAAA,CACF,CAAA,EACD,CAEF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("../constants/tools.js"),m=(e,t="Manifest")=>e?i.TOOL_SOURCE_LABELS[e]??e:t,L=e=>{const t=e?String(e):"";return t==="BIK"?"BIK":t==="BSP"?"BSP":"Manifest"},f=(e,t,n="Manifest")=>[...e.map(
|
|
2
|
-
`;case"orderedList":case"bulletList":{const n=e.type==="orderedList";return(e.content??[]).map((o
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("../constants/tools.js"),m=(e,t="Manifest")=>e?i.TOOL_SOURCE_LABELS[e]??e:t,L=e=>{const t=e?String(e):"";return t==="BIK"?"BIK":t==="BSP"?"BSP":"Manifest"},f=(e,t,n="Manifest")=>[...e.map(a=>({id:a.tool_id,label:`${m(a.source,n)} : ${a.display_name}`,meta:{kind:"tool",plainLabel:a.display_name,source:a.source,authRequired:a.auth_required}})),...t.map(a=>({id:a.id,label:`sub-agent: ${a.name}`,meta:{kind:"subagent",plainLabel:a.name}}))],d=e=>e.replace(/^\{\{|\}\}$/g,""),$=(e=[])=>{const t=[],n=a=>{const o=a.actualValue;o&&t.push({id:d(o),label:`Variable: ${a.displayName}`,meta:{kind:"variable",plainLabel:a.displayName}}),Object.values(a.variables??{}).forEach(n)};return e.forEach(n),t},p=e=>e.tool_key==="send_slack_message"?String(e.params.channelId?.value??"").trim()||"Send Slack message":String(e.params.sendTo?.value??"").split(",").map(t=>t.trim()).filter(Boolean)[0]||"Send Email",b=e=>e.name||"Rest API",g=e=>{const t=b(e);return{id:e.id,label:`${i.TOOL_SOURCE_LABELS[i.ToolSource.RestApi]} : ${t}`,meta:{kind:"tool",plainLabel:t,source:i.ToolSource.RestApi}}},S=e=>{const t=e.tool_key==="send_slack_message"?i.ToolSource.Slack:i.ToolSource.EmailHandover,n=p(e);return{id:e.id,label:`${i.TOOL_SOURCE_LABELS[t]} : ${n}`,meta:{kind:"tool",plainLabel:n,source:t}}},_=(e=[],t=[])=>[...t.map(g),...e.map(S)],l=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),s=e=>l(e).replace(/"/g,"""),T=(e,t,n)=>`<span data-type="mentionAgent" class="bik-mention bik-mention--agent" data-id="${s(e)}" data-label="${s(t)}" data-kind="${s(n)}">${l(t)}</span>`,E=(e,t,n)=>T(e,t,n),O=e=>{const t=new Map;for(const n of e){const a=n.meta;a?.kind==="tool"?t.set(`tool:${String(n.id)}`,n):a?.kind==="subagent"?t.set(`subagent:${String(n.id)}`,n):a?.kind==="variable"&&t.set(`variable:${String(n.id)}`,n)}return t},c=/\{\{((?:tool|subagent|variable):[^{}]+)\}\}/g,v=(e,t)=>{let n="",a=0;c.lastIndex=0;let o;for(;(o=c.exec(e))!==null;){n+=l(e.slice(a,o.index));const r=t.get(o[1]);if(r){const k=r.meta.kind;n+=T(String(r.id),r.label,k)}else n+=l(o[0]);a=c.lastIndex}return n+=l(e.slice(a)),n.replace(/\n/g,"<br>")},I=(e,t=[])=>{if(!e)return"";const n=O(t);return e.split(/\n{2,}/).map(a=>`<p>${v(a,n)}</p>`).join("")},M=(e,t,n)=>t==="variable"?`{{variable:${e}}}`:(t??(n.has(e)?"tool":"subagent"))==="tool"?`{{tool:${e}}}`:`{{subagent:${e}}}`,u=(e,t)=>{switch(e.type){case"text":return e.text??"";case"mentionAgent":case"mentionTeam":{const n=e.attrs?.id;if(n==null)return"";const a=e.attrs?.kind;return M(String(n),a==null?null:String(a),t)}case"variable":return`{{${String(e.attrs?.variableName??"")}}}`;case"hardBreak":return`
|
|
2
|
+
`;case"orderedList":case"bulletList":{const n=e.type==="orderedList";return(e.content??[]).map((a,o)=>`${n?`${o+1}.`:"-"} ${u(a,t).replace(/\n+$/,"")}`).join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`}default:{const n=(e.content??[]).map(
|
|
5
|
-
`:n}}},
|
|
4
|
+
`}default:{const n=(e.content??[]).map(o=>u(o,t)).join("");return["paragraph","heading","listItem","blockquote"].includes(e.type)?`${n}
|
|
5
|
+
`:n}}},A=(e,t)=>{if(!e)return"";const n=new Set(t.map(a=>a.tool_id));return u(e,n).replace(/\n+$/,"")};exports.TOOL_SOURCE_LABELS=i.TOOL_SOURCE_LABELS;exports.appTypeLabel=L;exports.buildAgentMentionItems=f;exports.buildCustomToolMentionItems=_;exports.buildMentionHtml=E;exports.buildVariableMentionItems=$;exports.configToolMentionItem=S;exports.configToolName=p;exports.editorDocToInstructions=A;exports.instructionsToEditorHtml=I;exports.restApiMentionItem=g;exports.restApiToolName=b;exports.toolSourceLabel=m;exports.variableTokenName=d;
|
|
6
6
|
//# sourceMappingURL=mentionSerialization.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mentionSerialization.js","sources":["../../../../../src/components/agent-builder/utils/mentionSerialization.ts"],"sourcesContent":["import type { ApplicationType } from '@bikdotai/bik-models/growth';\nimport { MentionItem } from '@src/editor';\nimport type {\n\tSubHeader,\n\tVariableListInterfaceV3,\n\tVariableV3,\n} from '../../variable-picker-v3/model';\nimport {\n\tAgentTool,\n\tConfigToolConfig,\n\tRestApiToolConfig,\n\tSubAgentRef,\n} from '../AgentBuilder.model';\nimport { TOOL_SOURCE_LABELS, ToolSource } from '../constants/tools';\n\n/**\n * Serialization helpers between the BikEditor document and the firebase\n * `instructions` string.\n *\n * Firebase stores `instructions` as PLAIN TEXT with inline reference tokens:\n * - `{{subagent:<agentId>}}` — hand-off to another agent\n * - `{{tool:<tool_id>}}` — an action the agent can call\n * - `{{<variableName>}}` — a template variable\n *\n * In the editor those references are inserted via the `@` mention menu (which we\n * populate with BOTH tools and sub-agents). Mention nodes keep their `id` in the\n * ProseMirror doc JSON (the rendered HTML drops it), so we serialize from the doc\n * JSON — not from HTML.\n */\n\nexport interface MentionKindMeta {\n\t/** Distinguishes a tool / sub-agent / variable reference. */\n\tkind: 'tool' | 'subagent' | 'variable';\n\t/** Plain item name (no prefix) shown in the picker dropdown rows. */\n\tplainLabel?: string;\n\t/** For tools: the source bucket (manifest / shopify / …) the picker groups by. */\n\tsource?: string;\n\t/** For tools: touches customer-private data → shows a shield in the picker. */\n\tauthRequired?: boolean;\n}\n\n// Source labels moved to constants/tools.ts; re-exported for existing importers.\nexport { TOOL_SOURCE_LABELS };\n\n/** Human label for a tool source; falls back to the host-app label, then the raw key. */\nexport const toolSourceLabel = (\n\tsource: string | undefined,\n\tfallback = 'Manifest',\n): string => {\n\tif (!source) {\n\t\treturn fallback;\n\t}\n\treturn TOOL_SOURCE_LABELS[source as ToolSource] ?? source;\n};\n\n/** Human label for the host application, used as the tool-chip prefix. */\nexport const appTypeLabel = (applicationType?: ApplicationType): string => {\n\tconst key = applicationType ? String(applicationType) : '';\n\tif (key === 'BIK') {\n\t\treturn 'BIK';\n\t}\n\tif (key === 'BSP') {\n\t\treturn 'BSP';\n\t}\n\treturn 'Manifest';\n};\n\n/**\n * Build the combined `@` mention list from the available tools + sub-agents.\n *\n * The `label` is the CHIP text shown once inserted — tools read\n * `\"<App> : <tool name>\"` (e.g. \"Manifest : Look up order\"), sub-agents read\n * `\"sub-agent: <name>\"`. `meta.plainLabel` is the un-prefixed name for the\n * picker rows, and `meta.kind` drives the `{{tool}}` / `{{subagent}}` colour.\n */\nexport const buildAgentMentionItems = (\n\ttools: AgentTool[],\n\tsubAgents: SubAgentRef[],\n\tappLabel = 'Manifest',\n): MentionItem[] => [\n\t...tools.map(\n\t\t(t): MentionItem => ({\n\t\t\tid: t.tool_id,\n\t\t\tlabel: `${toolSourceLabel(t.source, appLabel)} : ${t.display_name}`,\n\t\t\tmeta: {\n\t\t\t\tkind: 'tool',\n\t\t\t\tplainLabel: t.display_name,\n\t\t\t\tsource: t.source,\n\t\t\t\tauthRequired: t.auth_required,\n\t\t\t},\n\t\t}),\n\t),\n\t...subAgents.map(\n\t\t(s): MentionItem => ({\n\t\t\tid: s.id,\n\t\t\tlabel: `sub-agent: ${s.name}`,\n\t\t\tmeta: { kind: 'subagent', plainLabel: s.name },\n\t\t}),\n\t),\n];\n\n/** Strip the `{{ }}` wrapper from a variable token (`{{a.b}}` → `a.b`). */\nexport const variableTokenName = (actualValue: string): string =>\n\tactualValue.replace(/^\\{\\{|\\}\\}$/g, '');\n\n/**\n * Flatten the (nested) variable catalog into mention items, so stored\n * `{{<name>}}` tokens rehydrate as `Variable: <display name>` chips. The item\n * id is the BARE token name (no braces) — `resolveMentionToken` re-wraps it on\n * save. Merge alongside {@link buildAgentMentionItems} for serialization.\n */\nexport const buildVariableMentionItems = (\n\tvariablesData: VariableListInterfaceV3[] = [],\n): MentionItem[] => {\n\tconst items: MentionItem[] = [];\n\tconst walk = (entry: VariableListInterfaceV3 | SubHeader | VariableV3) => {\n\t\tconst actual = (entry as VariableV3).actualValue;\n\t\tif (actual) {\n\t\t\titems.push({\n\t\t\t\tid: variableTokenName(actual),\n\t\t\t\tlabel: `Variable: ${entry.displayName}`,\n\t\t\t\tmeta: { kind: 'variable', plainLabel: entry.displayName },\n\t\t\t});\n\t\t}\n\t\tObject.values(entry.variables ?? {}).forEach(walk);\n\t};\n\tvariablesData.forEach(walk);\n\treturn items;\n};\n\n/** Display name for a shared config tool: first recipient / channel, else generic. */\nexport const configToolName = (t: ConfigToolConfig): string => {\n\tif (t.tool_key === 'send_slack_message') {\n\t\treturn (\n\t\t\tString(t.params['channelId']?.value ?? '').trim() || 'Send Slack message'\n\t\t);\n\t}\n\treturn (\n\t\tString(t.params['sendTo']?.value ?? '')\n\t\t\t.split(',')\n\t\t\t.map((s) => s.trim())\n\t\t\t.filter(Boolean)[0] || 'Send Email'\n\t);\n};\n\n/** Display name for a Rest API tool row / chip. */\nexport const restApiToolName = (t: RestApiToolConfig): string =>\n\tt.name || 'Rest API';\n\n/** The `@`-mention chip item for a Rest API tool (kind 'tool', restapi source). */\nexport const restApiMentionItem = (t: RestApiToolConfig): MentionItem => {\n\tconst name = restApiToolName(t);\n\treturn {\n\t\tid: t.id,\n\t\tlabel: `${TOOL_SOURCE_LABELS[ToolSource.RestApi]} : ${name}`,\n\t\tmeta: { kind: 'tool', plainLabel: name, source: ToolSource.RestApi },\n\t};\n};\n\n/** The `@`-mention chip item for a shared config tool (email / Slack). */\nexport const configToolMentionItem = (t: ConfigToolConfig): MentionItem => {\n\tconst source =\n\t\tt.tool_key === 'send_slack_message'\n\t\t\t? ToolSource.Slack\n\t\t\t: ToolSource.EmailHandover;\n\tconst name = configToolName(t);\n\treturn {\n\t\tid: t.id,\n\t\tlabel: `${TOOL_SOURCE_LABELS[source]} : ${name}`,\n\t\tmeta: { kind: 'tool', plainLabel: name, source },\n\t};\n};\n\n/**\n * Mention items for the inline-configured custom tools (Rest API + email / Slack)\n * so their `{{tool:<id>}}` tokens rehydrate as chips — they live on the agent\n * value, not in the catalog `availableTools`. Merge alongside\n * {@link buildAgentMentionItems} in the editor's mention list.\n */\nexport const buildCustomToolMentionItems = (\n\tconfigTools: ConfigToolConfig[] = [],\n\trestApiTools: RestApiToolConfig[] = [],\n): MentionItem[] => [\n\t...restApiTools.map(restApiMentionItem),\n\t...configTools.map(configToolMentionItem),\n];\n\nconst escapeHtml = (raw: string): string =>\n\traw.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\nconst escapeAttr = (raw: string): string =>\n\tescapeHtml(raw).replace(/\"/g, '"');\n\n/**\n * The HTML for a single mention chip. Must round-trip through the TipTap mention\n * extension's `parseHTML` (`span[data-type=\"mentionAgent\"]`, reading\n * `data-id`/`data-label`/`data-kind`) — see MentionExtension.ts. `normalizeHtml`\n * is taught to keep `data-type=\"mention…\"` spans so this survives to the parser.\n */\nconst mentionSpanHtml = (id: string, label: string, kind: string): string =>\n\t`<span data-type=\"mentionAgent\" class=\"bik-mention bik-mention--agent\"` +\n\t` data-id=\"${escapeAttr(id)}\" data-label=\"${escapeAttr(label)}\"` +\n\t` data-kind=\"${escapeAttr(kind)}\">${escapeHtml(label)}</span>`;\n\n/**\n * Public: HTML for one mention chip, for inserting at the cursor (e.g. when a\n * tool / sub-agent is added from the Step-3 side panel). Round-trips through the\n * same parser path as the rehydrated chips.\n */\nexport const buildMentionHtml = (\n\tid: string,\n\tlabel: string,\n\tkind: 'tool' | 'subagent' | 'variable',\n): string => mentionSpanHtml(id, label, kind);\n\n/**\n * `{{tool:<id>}}` / `{{subagent:<id>}}` / `{{<variableName>}}` → the mention\n * item that produced them. The map key is the token's INNER text.\n */\nconst buildTokenLookup = (\n\tmentionItems: MentionItem[],\n): Map<string, MentionItem> => {\n\tconst byToken = new Map<string, MentionItem>();\n\tfor (const item of mentionItems) {\n\t\tconst meta = item.meta as unknown as MentionKindMeta | undefined;\n\t\t// Tools and sub-agents are keyed by their prefixed id (a tool's id is its\n\t\t// tool_id); variables by their bare token name.\n\t\tif (meta?.kind === 'tool') {\n\t\t\tbyToken.set(`tool:${String(item.id)}`, item);\n\t\t} else if (meta?.kind === 'subagent') {\n\t\t\tbyToken.set(`subagent:${String(item.id)}`, item);\n\t\t} else if (meta?.kind === 'variable') {\n\t\t\tbyToken.set(String(item.id), item);\n\t\t}\n\t}\n\treturn byToken;\n};\n\n// Matches any `{{…}}` token. Ones resolved via the lookup render as chips;\n// the rest fall through untouched (literal text for the variable decoration).\nconst REFERENCE_TOKEN = /\\{\\{([^{}]+)\\}\\}/g;\n\n/** Escape plain text, swapping recognised reference tokens for mention spans. */\nconst inlineToHtml = (\n\tsegment: string,\n\tbyToken: Map<string, MentionItem>,\n): string => {\n\tlet out = '';\n\tlet lastIndex = 0;\n\tREFERENCE_TOKEN.lastIndex = 0;\n\tlet match: RegExpExecArray | null;\n\twhile ((match = REFERENCE_TOKEN.exec(segment)) !== null) {\n\t\tout += escapeHtml(segment.slice(lastIndex, match.index));\n\t\tconst item = byToken.get(match[1]);\n\t\tif (item) {\n\t\t\tconst kind = (item.meta as unknown as MentionKindMeta).kind;\n\t\t\tout += mentionSpanHtml(String(item.id), item.label, kind);\n\t\t} else {\n\t\t\t// Not in any available list (removed tool / unknown variable) → keep the\n\t\t\t// raw token as literal text.\n\t\t\tout += escapeHtml(match[0]);\n\t\t}\n\t\tlastIndex = REFERENCE_TOKEN.lastIndex;\n\t}\n\tout += escapeHtml(segment.slice(lastIndex));\n\treturn out.replace(/\\n/g, '<br>');\n};\n\n/**\n * Convert the stored instructions string into HTML for `BikEditor.initialContent`.\n * `{{tool:KEY}}` / `{{subagent:ID}}` tokens are rehydrated into mention chips\n * (resolved via `mentionItems`); any other `{{…}}` token is left as literal text\n * for the editor's variable decoration. Newlines become paragraph / line breaks.\n */\nexport const instructionsToEditorHtml = (\n\ttext: string,\n\tmentionItems: MentionItem[] = [],\n): string => {\n\tif (!text) {\n\t\treturn '';\n\t}\n\tconst byToken = buildTokenLookup(mentionItems);\n\treturn text\n\t\t.split(/\\n{2,}/)\n\t\t.map((para) => `<p>${inlineToHtml(para, byToken)}</p>`)\n\t\t.join('');\n};\n\ninterface ProseMirrorNode {\n\ttype: string;\n\ttext?: string;\n\tattrs?: Record<string, unknown>;\n\tcontent?: ProseMirrorNode[];\n}\n\n/**\n * The token for a mention node. All kinds store their id in the node, so the\n * token value is just that id — the kind only picks the prefix (variables have\n * none: `{{<id>}}`). The node's `kind` attr is authoritative; `toolIds` is a\n * fallback for older content saved before the kind attr existed.\n */\nconst resolveMentionToken = (\n\tid: string,\n\tkind: string | null,\n\ttoolIds: Set<string>,\n): string => {\n\tif (kind === 'variable') {\n\t\treturn `{{${id}}}`;\n\t}\n\tconst resolved = kind ?? (toolIds.has(id) ? 'tool' : 'subagent');\n\treturn resolved === 'tool' ? `{{tool:${id}}}` : `{{subagent:${id}}}`;\n};\n\nconst nodeToText = (node: ProseMirrorNode, toolIds: Set<string>): string => {\n\tswitch (node.type) {\n\t\tcase 'text':\n\t\t\treturn node.text ?? '';\n\t\tcase 'mentionAgent':\n\t\tcase 'mentionTeam': {\n\t\t\tconst id = node.attrs?.['id'];\n\t\t\tif (id == null) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tconst kind = node.attrs?.['kind'];\n\t\t\treturn resolveMentionToken(\n\t\t\t\tString(id),\n\t\t\t\tkind == null ? null : String(kind),\n\t\t\t\ttoolIds,\n\t\t\t);\n\t\t}\n\t\tcase 'variable':\n\t\t\treturn `{{${String(node.attrs?.['variableName'] ?? '')}}}`;\n\t\tcase 'hardBreak':\n\t\t\treturn '\\n';\n\t\tcase 'orderedList':\n\t\tcase 'bulletList': {\n\t\t\t// Flattening to plain text otherwise drops the list markers, so a\n\t\t\t// numbered / bulleted list looks \"removed\" after publish. Emit an\n\t\t\t// ordinal (\"1. \") / bullet (\"- \") prefix per item to preserve it.\n\t\t\tconst ordered = node.type === 'orderedList';\n\t\t\treturn (\n\t\t\t\t(node.content ?? [])\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(item, i) =>\n\t\t\t\t\t\t\t`${ordered ? `${i + 1}.` : '-'} ${nodeToText(\n\t\t\t\t\t\t\t\titem,\n\t\t\t\t\t\t\t\ttoolIds,\n\t\t\t\t\t\t\t).replace(/\\n+$/, '')}`,\n\t\t\t\t\t)\n\t\t\t\t\t.join('\\n') + '\\n'\n\t\t\t);\n\t\t}\n\t\tdefault: {\n\t\t\tconst inner = (node.content ?? [])\n\t\t\t\t.map((child) => nodeToText(child, toolIds))\n\t\t\t\t.join('');\n\t\t\t// Block nodes terminate with a newline so paragraphs stay separated.\n\t\t\tconst BLOCK_NODES = ['paragraph', 'heading', 'listItem', 'blockquote'];\n\t\t\treturn BLOCK_NODES.includes(node.type) ? `${inner}\\n` : inner;\n\t\t}\n\t}\n};\n\n/**\n * Convert a BikEditor document (from `ref.getJSON()`) into the firebase\n * instructions string, replacing mention nodes with `{{subagent:<id>}}` /\n * `{{tool:<tool_id>}}` tokens.\n */\nexport const editorDocToInstructions = (\n\tdoc: Record<string, unknown> | null,\n\ttools: AgentTool[],\n): string => {\n\tif (!doc) {\n\t\treturn '';\n\t}\n\tconst toolIds = new Set(tools.map((t) => t.tool_id));\n\treturn nodeToText(doc as unknown as ProseMirrorNode, toolIds).replace(\n\t\t/\\n+$/,\n\t\t'',\n\t);\n};\n"],"names":["toolSourceLabel","source","fallback","TOOL_SOURCE_LABELS","appTypeLabel","applicationType","key","buildAgentMentionItems","tools","subAgents","appLabel","t","s","variableTokenName","actualValue","buildVariableMentionItems","variablesData","items","walk","entry","actual","configToolName","restApiToolName","restApiMentionItem","name","ToolSource","configToolMentionItem","buildCustomToolMentionItems","configTools","restApiTools","escapeHtml","raw","escapeAttr","mentionSpanHtml","id","label","kind","buildMentionHtml","buildTokenLookup","mentionItems","byToken","item","meta","REFERENCE_TOKEN","inlineToHtml","segment","out","lastIndex","match","instructionsToEditorHtml","text","para","resolveMentionToken","toolIds","nodeToText","node","ordered","i","inner","child","editorDocToInstructions","doc"],"mappings":"yHA6CaA,EAAkB,CAC9BC,EACAC,EAAW,aAEND,EAGEE,EAAAA,mBAAmBF,CAAoB,GAAKA,EAF3CC,EAMIE,EAAgBC,GAA8C,CAC1E,MAAMC,EAAMD,EAAkB,OAAOA,CAAe,EAAI,GACxD,OAAIC,IAAQ,MACJ,MAEJA,IAAQ,MACJ,MAED,UACR,EAUaC,EAAyB,CACrCC,EACAC,EACAC,EAAW,aACQ,CACnB,GAAGF,EAAM,IACPG,IAAoB,CACpB,GAAIA,EAAE,QACN,MAAO,GAAGX,EAAgBW,EAAE,OAAQD,CAAQ,CAAC,MAAMC,EAAE,YAAY,GACjE,KAAM,CACL,KAAM,OACN,WAAYA,EAAE,aACd,OAAQA,EAAE,OACV,aAAcA,EAAE,aAAA,CAC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,OACEA,EAAK,SAAW,CAAA,GACf,IACA,CAACd,EAAMgB,IACN,GAAGD,EAAU,GAAGC,EAAI,CAAC,IAAM,GAAG,IAAIH,EACjCb,EACAY,CAAA,EACC,QAAQ,OAAQ,EAAE,CAAC,EAAA,EAEtB,KAAK;AAAA,CAAI,EAAI;AAAA,CAEjB,CACA,QAAS,CACR,MAAMK,GAASH,EAAK,SAAW,CAAA,GAC7B,IAAKI,GAAUL,EAAWK,EAAON,CAAO,CAAC,EACzC,KAAK,EAAE,EAGT,MADoB,CAAC,YAAa,UAAW,WAAY,YAAY,EAClD,SAASE,EAAK,IAAI,EAAI,GAAGG,CAAK;AAAA,EAAOA,CACzD,CAAA,CAEF,EAOaE,EAA0B,CACtCC,EACArD,IACY,CACZ,GAAI,CAACqD,EACJ,MAAO,GAER,MAAMR,EAAU,IAAI,IAAI7C,EAAM,IAAKG,GAAMA,EAAE,OAAO,CAAC,EACnD,OAAO2C,EAAWO,EAAmCR,CAAO,EAAE,QAC7D,OACA,EAAA,CAEF"}
|
|
1
|
+
{"version":3,"file":"mentionSerialization.js","sources":["../../../../../src/components/agent-builder/utils/mentionSerialization.ts"],"sourcesContent":["import type { ApplicationType } from '@bikdotai/bik-models/growth';\nimport { MentionItem } from '@src/editor';\nimport type {\n\tSubHeader,\n\tVariableListInterfaceV3,\n\tVariableV3,\n} from '../../variable-picker-v3/model';\nimport {\n\tAgentTool,\n\tConfigToolConfig,\n\tRestApiToolConfig,\n\tSubAgentRef,\n} from '../AgentBuilder.model';\nimport { TOOL_SOURCE_LABELS, ToolSource } from '../constants/tools';\n\n/**\n * Serialization helpers between the BikEditor document and the firebase\n * `instructions` string.\n *\n * Firebase stores `instructions` as PLAIN TEXT with inline reference tokens:\n * - `{{subagent:<agentId>}}` — hand-off to another agent\n * - `{{tool:<tool_id>}}` — an action the agent can call\n * - `{{variable:<name>}}` — a template variable picked from the catalog\n *\n * In the editor those references are inserted via the `@` mention menu (which we\n * populate with BOTH tools and sub-agents). Mention nodes keep their `id` in the\n * ProseMirror doc JSON (the rendered HTML drops it), so we serialize from the doc\n * JSON — not from HTML.\n */\n\nexport interface MentionKindMeta {\n\t/** Distinguishes a tool / sub-agent / variable reference. */\n\tkind: 'tool' | 'subagent' | 'variable';\n\t/** Plain item name (no prefix) shown in the picker dropdown rows. */\n\tplainLabel?: string;\n\t/** For tools: the source bucket (manifest / shopify / …) the picker groups by. */\n\tsource?: string;\n\t/** For tools: touches customer-private data → shows a shield in the picker. */\n\tauthRequired?: boolean;\n}\n\n// Source labels moved to constants/tools.ts; re-exported for existing importers.\nexport { TOOL_SOURCE_LABELS };\n\n/** Human label for a tool source; falls back to the host-app label, then the raw key. */\nexport const toolSourceLabel = (\n\tsource: string | undefined,\n\tfallback = 'Manifest',\n): string => {\n\tif (!source) {\n\t\treturn fallback;\n\t}\n\treturn TOOL_SOURCE_LABELS[source as ToolSource] ?? source;\n};\n\n/** Human label for the host application, used as the tool-chip prefix. */\nexport const appTypeLabel = (applicationType?: ApplicationType): string => {\n\tconst key = applicationType ? String(applicationType) : '';\n\tif (key === 'BIK') {\n\t\treturn 'BIK';\n\t}\n\tif (key === 'BSP') {\n\t\treturn 'BSP';\n\t}\n\treturn 'Manifest';\n};\n\n/**\n * Build the combined `@` mention list from the available tools + sub-agents.\n *\n * The `label` is the CHIP text shown once inserted — tools read\n * `\"<App> : <tool name>\"` (e.g. \"Manifest : Look up order\"), sub-agents read\n * `\"sub-agent: <name>\"`. `meta.plainLabel` is the un-prefixed name for the\n * picker rows, and `meta.kind` drives the `{{tool}}` / `{{subagent}}` colour.\n */\nexport const buildAgentMentionItems = (\n\ttools: AgentTool[],\n\tsubAgents: SubAgentRef[],\n\tappLabel = 'Manifest',\n): MentionItem[] => [\n\t...tools.map(\n\t\t(t): MentionItem => ({\n\t\t\tid: t.tool_id,\n\t\t\tlabel: `${toolSourceLabel(t.source, appLabel)} : ${t.display_name}`,\n\t\t\tmeta: {\n\t\t\t\tkind: 'tool',\n\t\t\t\tplainLabel: t.display_name,\n\t\t\t\tsource: t.source,\n\t\t\t\tauthRequired: t.auth_required,\n\t\t\t},\n\t\t}),\n\t),\n\t...subAgents.map(\n\t\t(s): MentionItem => ({\n\t\t\tid: s.id,\n\t\t\tlabel: `sub-agent: ${s.name}`,\n\t\t\tmeta: { kind: 'subagent', plainLabel: s.name },\n\t\t}),\n\t),\n];\n\n/** Strip the `{{ }}` wrapper from a variable token (`{{a.b}}` → `a.b`). */\nexport const variableTokenName = (actualValue: string): string =>\n\tactualValue.replace(/^\\{\\{|\\}\\}$/g, '');\n\n/**\n * Flatten the (nested) variable catalog into mention items, so stored\n * `{{<name>}}` tokens rehydrate as `Variable: <display name>` chips. The item\n * id is the BARE token name (no braces) — `resolveMentionToken` re-wraps it on\n * save. Merge alongside {@link buildAgentMentionItems} for serialization.\n */\nexport const buildVariableMentionItems = (\n\tvariablesData: VariableListInterfaceV3[] = [],\n): MentionItem[] => {\n\tconst items: MentionItem[] = [];\n\tconst walk = (entry: VariableListInterfaceV3 | SubHeader | VariableV3) => {\n\t\tconst actual = (entry as VariableV3).actualValue;\n\t\tif (actual) {\n\t\t\titems.push({\n\t\t\t\tid: variableTokenName(actual),\n\t\t\t\tlabel: `Variable: ${entry.displayName}`,\n\t\t\t\tmeta: { kind: 'variable', plainLabel: entry.displayName },\n\t\t\t});\n\t\t}\n\t\tObject.values(entry.variables ?? {}).forEach(walk);\n\t};\n\tvariablesData.forEach(walk);\n\treturn items;\n};\n\n/** Display name for a shared config tool: first recipient / channel, else generic. */\nexport const configToolName = (t: ConfigToolConfig): string => {\n\tif (t.tool_key === 'send_slack_message') {\n\t\treturn (\n\t\t\tString(t.params['channelId']?.value ?? '').trim() || 'Send Slack message'\n\t\t);\n\t}\n\treturn (\n\t\tString(t.params['sendTo']?.value ?? '')\n\t\t\t.split(',')\n\t\t\t.map((s) => s.trim())\n\t\t\t.filter(Boolean)[0] || 'Send Email'\n\t);\n};\n\n/** Display name for a Rest API tool row / chip. */\nexport const restApiToolName = (t: RestApiToolConfig): string =>\n\tt.name || 'Rest API';\n\n/** The `@`-mention chip item for a Rest API tool (kind 'tool', restapi source). */\nexport const restApiMentionItem = (t: RestApiToolConfig): MentionItem => {\n\tconst name = restApiToolName(t);\n\treturn {\n\t\tid: t.id,\n\t\tlabel: `${TOOL_SOURCE_LABELS[ToolSource.RestApi]} : ${name}`,\n\t\tmeta: { kind: 'tool', plainLabel: name, source: ToolSource.RestApi },\n\t};\n};\n\n/** The `@`-mention chip item for a shared config tool (email / Slack). */\nexport const configToolMentionItem = (t: ConfigToolConfig): MentionItem => {\n\tconst source =\n\t\tt.tool_key === 'send_slack_message'\n\t\t\t? ToolSource.Slack\n\t\t\t: ToolSource.EmailHandover;\n\tconst name = configToolName(t);\n\treturn {\n\t\tid: t.id,\n\t\tlabel: `${TOOL_SOURCE_LABELS[source]} : ${name}`,\n\t\tmeta: { kind: 'tool', plainLabel: name, source },\n\t};\n};\n\n/**\n * Mention items for the inline-configured custom tools (Rest API + email / Slack)\n * so their `{{tool:<id>}}` tokens rehydrate as chips — they live on the agent\n * value, not in the catalog `availableTools`. Merge alongside\n * {@link buildAgentMentionItems} in the editor's mention list.\n */\nexport const buildCustomToolMentionItems = (\n\tconfigTools: ConfigToolConfig[] = [],\n\trestApiTools: RestApiToolConfig[] = [],\n): MentionItem[] => [\n\t...restApiTools.map(restApiMentionItem),\n\t...configTools.map(configToolMentionItem),\n];\n\nconst escapeHtml = (raw: string): string =>\n\traw.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\nconst escapeAttr = (raw: string): string =>\n\tescapeHtml(raw).replace(/\"/g, '"');\n\n/**\n * The HTML for a single mention chip. Must round-trip through the TipTap mention\n * extension's `parseHTML` (`span[data-type=\"mentionAgent\"]`, reading\n * `data-id`/`data-label`/`data-kind`) — see MentionExtension.ts. `normalizeHtml`\n * is taught to keep `data-type=\"mention…\"` spans so this survives to the parser.\n */\nconst mentionSpanHtml = (id: string, label: string, kind: string): string =>\n\t`<span data-type=\"mentionAgent\" class=\"bik-mention bik-mention--agent\"` +\n\t` data-id=\"${escapeAttr(id)}\" data-label=\"${escapeAttr(label)}\"` +\n\t` data-kind=\"${escapeAttr(kind)}\">${escapeHtml(label)}</span>`;\n\n/**\n * Public: HTML for one mention chip, for inserting at the cursor (e.g. when a\n * tool / sub-agent is added from the Step-3 side panel). Round-trips through the\n * same parser path as the rehydrated chips.\n */\nexport const buildMentionHtml = (\n\tid: string,\n\tlabel: string,\n\tkind: 'tool' | 'subagent' | 'variable',\n): string => mentionSpanHtml(id, label, kind);\n\n/**\n * `{{tool:<id>}}` / `{{subagent:<id>}}` / `{{<variableName>}}` → the mention\n * item that produced them. The map key is the token's INNER text.\n */\nconst buildTokenLookup = (\n\tmentionItems: MentionItem[],\n): Map<string, MentionItem> => {\n\tconst byToken = new Map<string, MentionItem>();\n\tfor (const item of mentionItems) {\n\t\tconst meta = item.meta as unknown as MentionKindMeta | undefined;\n\t\t// Everything is keyed by its kind-prefixed id (a tool's id is its tool_id).\n\t\tif (meta?.kind === 'tool') {\n\t\t\tbyToken.set(`tool:${String(item.id)}`, item);\n\t\t} else if (meta?.kind === 'subagent') {\n\t\t\tbyToken.set(`subagent:${String(item.id)}`, item);\n\t\t} else if (meta?.kind === 'variable') {\n\t\t\tbyToken.set(`variable:${String(item.id)}`, item);\n\t\t}\n\t}\n\treturn byToken;\n};\n\n// Matches the kind-prefixed reference tokens we render as chips. Other\n// `{{var}}` tokens fall through untouched (left as literal text for the\n// variable decoration).\nconst REFERENCE_TOKEN = /\\{\\{((?:tool|subagent|variable):[^{}]+)\\}\\}/g;\n\n/** Escape plain text, swapping recognised reference tokens for mention spans. */\nconst inlineToHtml = (\n\tsegment: string,\n\tbyToken: Map<string, MentionItem>,\n): string => {\n\tlet out = '';\n\tlet lastIndex = 0;\n\tREFERENCE_TOKEN.lastIndex = 0;\n\tlet match: RegExpExecArray | null;\n\twhile ((match = REFERENCE_TOKEN.exec(segment)) !== null) {\n\t\tout += escapeHtml(segment.slice(lastIndex, match.index));\n\t\tconst item = byToken.get(match[1]);\n\t\tif (item) {\n\t\t\tconst kind = (item.meta as unknown as MentionKindMeta).kind;\n\t\t\tout += mentionSpanHtml(String(item.id), item.label, kind);\n\t\t} else {\n\t\t\t// Not in any available list (removed tool / unknown variable) → keep the\n\t\t\t// raw token as literal text.\n\t\t\tout += escapeHtml(match[0]);\n\t\t}\n\t\tlastIndex = REFERENCE_TOKEN.lastIndex;\n\t}\n\tout += escapeHtml(segment.slice(lastIndex));\n\treturn out.replace(/\\n/g, '<br>');\n};\n\n/**\n * Convert the stored instructions string into HTML for `BikEditor.initialContent`.\n * `{{tool:KEY}}` / `{{subagent:ID}}` tokens are rehydrated into mention chips\n * (resolved via `mentionItems`); any other `{{…}}` token is left as literal text\n * for the editor's variable decoration. Newlines become paragraph / line breaks.\n */\nexport const instructionsToEditorHtml = (\n\ttext: string,\n\tmentionItems: MentionItem[] = [],\n): string => {\n\tif (!text) {\n\t\treturn '';\n\t}\n\tconst byToken = buildTokenLookup(mentionItems);\n\treturn text\n\t\t.split(/\\n{2,}/)\n\t\t.map((para) => `<p>${inlineToHtml(para, byToken)}</p>`)\n\t\t.join('');\n};\n\ninterface ProseMirrorNode {\n\ttype: string;\n\ttext?: string;\n\tattrs?: Record<string, unknown>;\n\tcontent?: ProseMirrorNode[];\n}\n\n/**\n * The token for a mention node. All kinds store their id in the node, so the\n * token value is just that id — the kind only picks the prefix. The node's\n * `kind` attr is authoritative; `toolIds` is a fallback for older content\n * saved before the kind attr existed.\n */\nconst resolveMentionToken = (\n\tid: string,\n\tkind: string | null,\n\ttoolIds: Set<string>,\n): string => {\n\tif (kind === 'variable') {\n\t\treturn `{{variable:${id}}}`;\n\t}\n\tconst resolved = kind ?? (toolIds.has(id) ? 'tool' : 'subagent');\n\treturn resolved === 'tool' ? `{{tool:${id}}}` : `{{subagent:${id}}}`;\n};\n\nconst nodeToText = (node: ProseMirrorNode, toolIds: Set<string>): string => {\n\tswitch (node.type) {\n\t\tcase 'text':\n\t\t\treturn node.text ?? '';\n\t\tcase 'mentionAgent':\n\t\tcase 'mentionTeam': {\n\t\t\tconst id = node.attrs?.['id'];\n\t\t\tif (id == null) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tconst kind = node.attrs?.['kind'];\n\t\t\treturn resolveMentionToken(\n\t\t\t\tString(id),\n\t\t\t\tkind == null ? null : String(kind),\n\t\t\t\ttoolIds,\n\t\t\t);\n\t\t}\n\t\tcase 'variable':\n\t\t\treturn `{{${String(node.attrs?.['variableName'] ?? '')}}}`;\n\t\tcase 'hardBreak':\n\t\t\treturn '\\n';\n\t\tcase 'orderedList':\n\t\tcase 'bulletList': {\n\t\t\t// Flattening to plain text otherwise drops the list markers, so a\n\t\t\t// numbered / bulleted list looks \"removed\" after publish. Emit an\n\t\t\t// ordinal (\"1. \") / bullet (\"- \") prefix per item to preserve it.\n\t\t\tconst ordered = node.type === 'orderedList';\n\t\t\treturn (\n\t\t\t\t(node.content ?? [])\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(item, i) =>\n\t\t\t\t\t\t\t`${ordered ? `${i + 1}.` : '-'} ${nodeToText(\n\t\t\t\t\t\t\t\titem,\n\t\t\t\t\t\t\t\ttoolIds,\n\t\t\t\t\t\t\t).replace(/\\n+$/, '')}`,\n\t\t\t\t\t)\n\t\t\t\t\t.join('\\n') + '\\n'\n\t\t\t);\n\t\t}\n\t\tdefault: {\n\t\t\tconst inner = (node.content ?? [])\n\t\t\t\t.map((child) => nodeToText(child, toolIds))\n\t\t\t\t.join('');\n\t\t\t// Block nodes terminate with a newline so paragraphs stay separated.\n\t\t\tconst BLOCK_NODES = ['paragraph', 'heading', 'listItem', 'blockquote'];\n\t\t\treturn BLOCK_NODES.includes(node.type) ? `${inner}\\n` : inner;\n\t\t}\n\t}\n};\n\n/**\n * Convert a BikEditor document (from `ref.getJSON()`) into the firebase\n * instructions string, replacing mention nodes with `{{subagent:<id>}}` /\n * `{{tool:<tool_id>}}` tokens.\n */\nexport const editorDocToInstructions = (\n\tdoc: Record<string, unknown> | null,\n\ttools: AgentTool[],\n): string => {\n\tif (!doc) {\n\t\treturn '';\n\t}\n\tconst toolIds = new Set(tools.map((t) => t.tool_id));\n\treturn nodeToText(doc as unknown as ProseMirrorNode, toolIds).replace(\n\t\t/\\n+$/,\n\t\t'',\n\t);\n};\n"],"names":["toolSourceLabel","source","fallback","TOOL_SOURCE_LABELS","appTypeLabel","applicationType","key","buildAgentMentionItems","tools","subAgents","appLabel","t","s","variableTokenName","actualValue","buildVariableMentionItems","variablesData","items","walk","entry","actual","configToolName","restApiToolName","restApiMentionItem","name","ToolSource","configToolMentionItem","buildCustomToolMentionItems","configTools","restApiTools","escapeHtml","raw","escapeAttr","mentionSpanHtml","id","label","kind","buildMentionHtml","buildTokenLookup","mentionItems","byToken","item","meta","REFERENCE_TOKEN","inlineToHtml","segment","out","lastIndex","match","instructionsToEditorHtml","text","para","resolveMentionToken","toolIds","nodeToText","node","ordered","i","inner","child","editorDocToInstructions","doc"],"mappings":"yHA6CaA,EAAkB,CAC9BC,EACAC,EAAW,aAEND,EAGEE,EAAAA,mBAAmBF,CAAoB,GAAKA,EAF3CC,EAMIE,EAAgBC,GAA8C,CAC1E,MAAMC,EAAMD,EAAkB,OAAOA,CAAe,EAAI,GACxD,OAAIC,IAAQ,MACJ,MAEJA,IAAQ,MACJ,MAED,UACR,EAUaC,EAAyB,CACrCC,EACAC,EACAC,EAAW,aACQ,CACnB,GAAGF,EAAM,IACPG,IAAoB,CACpB,GAAIA,EAAE,QACN,MAAO,GAAGX,EAAgBW,EAAE,OAAQD,CAAQ,CAAC,MAAMC,EAAE,YAAY,GACjE,KAAM,CACL,KAAM,OACN,WAAYA,EAAE,aACd,OAAQA,EAAE,OACV,aAAcA,EAAE,aAAA,CACjB,EACD,EAED,GAAGF,EAAU,IACXG,IAAoB,CACpB,GAAIA,EAAE,GACN,MAAO,cAAcA,EAAE,IAAI,GAC3B,KAAM,CAAE,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G,IAAIH,EACjCb,EACAY,CAAA,EACC,QAAQ,OAAQ,EAAE,CAAC,EAAA,EAEtB,KAAK;AAAA,CAAI,EAAI;AAAA,CAEjB,CACA,QAAS,CACR,MAAMK,GAASH,EAAK,SAAW,CAAA,GAC7B,IAAKI,GAAUL,EAAWK,EAAON,CAAO,CAAC,EACzC,KAAK,EAAE,EAGT,MADoB,CAAC,YAAa,UAAW,WAAY,YAAY,EAClD,SAASE,EAAK,IAAI,EAAI,GAAGG,CAAK;AAAA,EAAOA,CACzD,CAAA,CAEF,EAOaE,EAA0B,CACtCC,EACArD,IACY,CACZ,GAAI,CAACqD,EACJ,MAAO,GAER,MAAMR,EAAU,IAAI,IAAI7C,EAAM,IAAKG,GAAMA,EAAE,OAAO,CAAC,EACnD,OAAO2C,EAAWO,EAAmCR,CAAO,EAAE,QAC7D,OACA,EAAA,CAEF"}
|
|
@@ -37,8 +37,8 @@ interface MentionEditorProps {
|
|
|
37
37
|
onConnectIntegration?: (source: ToolSource) => void;
|
|
38
38
|
/**
|
|
39
39
|
* Variable catalog for the `@` picker's "Variables" view. Picking one inserts
|
|
40
|
-
* a `Variable: <name>` mention chip at the cursor, persisted as
|
|
41
|
-
* `{{
|
|
40
|
+
* a `Variable: <name>` mention chip at the cursor, persisted as a
|
|
41
|
+
* `{{variable:<name>}}` token. Omit to hide the category.
|
|
42
42
|
*/
|
|
43
43
|
variablesData?: VariableListInterfaceV3[];
|
|
44
44
|
/** Optional action(s) rendered inside the shell, below the editor. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MentionEditor.js","sources":["../../../../../src/components/agent-builder/components/MentionEditor.tsx"],"sourcesContent":["import { BikEditor, BikEditorRef, MentionItem } from '@src/editor';\nimport React, {\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState,\n} from 'react';\nimport { BodyCaption, TitleSmall } from '@src/components/TypographyStyle';\nimport { COLORS } from '@src/constants/Theme';\nimport type {\n\tVariableListInterfaceV3,\n\tVariableV3,\n} from '../../variable-picker-v3/model';\nimport { AgentTool } from '../AgentBuilder.model';\nimport {\n\tAiTextAreaShell,\n\tFieldBlock,\n\tFieldLabelRow,\n} from '../AgentBuilder.styled';\nimport { AGENT_EDITOR_STYLE } from '../constants/editorStyle';\nimport type { ToolAction, ToolSource } from '../constants/tools';\nimport {\n\tbuildMentionHtml,\n\tbuildVariableMentionItems,\n\teditorDocToInstructions,\n\tinstructionsToEditorHtml,\n\tMentionKindMeta,\n\tvariableTokenName,\n} from '../utils/mentionSerialization';\nimport { MentionPicker } from './MentionPicker';\n\ntype InsertFn = (kind: 'tool' | 'subagent', id: string, label?: string) => void;\n\ninterface MentionEditorProps {\n\tlabel: string;\n\tvalue: string;\n\tonChange: (text: string) => void;\n\tmaxLength: number;\n\tplaceholder?: string;\n\tminHeight?: string;\n\t/** Changing this remounts the editor with fresh content. */\n\tresetKey?: string | number;\n\t/** Items shown in the `@` picker (tools, and sub-agents where allowed). */\n\tmentionItems: MentionItem[];\n\t/** Tools used to serialise mention nodes back to `{{tool:KEY}}`. */\n\ttools: AgentTool[];\n\t/** Called when an item is picked from the `@` menu (to attach it upstream). */\n\tonMentionSelect?: (kind: 'tool' | 'subagent', id: string) => void;\n\tonFocus?: () => void;\n\t/** Receives an insert-at-cursor fn (and null on unmount) for side-panel adds. */\n\tregisterInsert?: (fn: InsertFn | null) => void;\n\t/**\n\t * When set, the `@` picker's Sub-agent view shows a \"Create new\" row that calls\n\t * this (opens the create-sub-agent drawer). Omit to hide it (e.g. the drawer's\n\t * own editors, which can't nest sub-agents).\n\t */\n\tonCreateSubAgent?: () => void;\n\t/**\n\t * Built-in tool actions (Rest API / Handover to email) shown in the `@` picker's\n\t * Tools view. Picking one opens its drawer instead of inserting a mention.\n\t */\n\ttoolActions?: ToolAction[];\n\tintegrationStatus?: Partial<Record<ToolSource, boolean>>;\n\tonConnectIntegration?: (source: ToolSource) => void;\n\t/**\n\t * Variable catalog for the `@` picker's \"Variables\" view. Picking one inserts\n\t * a `Variable: <name>` mention chip at the cursor, persisted as the bare\n\t * `{{actualValue}}` token. Omit to hide the category.\n\t */\n\tvariablesData?: VariableListInterfaceV3[];\n\t/** Optional action(s) rendered inside the shell, below the editor. */\n\taction?: React.ReactNode;\n\t'data-test'?: string;\n}\n\n/**\n * Presentational BikEditor field with `@` mentions. Stores firebase token text\n * (`{{tool:KEY}}` / `{{subagent:ID}}`). Context-free — both the builder's\n * Step-3 fields and the create-sub-agent drawer compose it.\n */\nexport const MentionEditor: React.FC<MentionEditorProps> = ({\n\tlabel,\n\tvalue,\n\tonChange,\n\tmaxLength,\n\tplaceholder,\n\tminHeight = '200px',\n\tresetKey,\n\tmentionItems,\n\ttools,\n\tonMentionSelect,\n\tonFocus,\n\tregisterInsert,\n\tonCreateSubAgent,\n\ttoolActions,\n\tintegrationStatus,\n\tonConnectIntegration,\n\tvariablesData,\n\taction,\n\t...rest\n}) => {\n\tconst editorRef = useRef<BikEditorRef>(null);\n\tconst [count, setCount] = useState(value.length);\n\n\t// The picker dismissed itself already (stripping the \"@\" + query) — drop a\n\t// `Variable: <name>` mention chip at the cursor, same shape as tool /\n\t// sub-agent chips. `editorDocToInstructions` serializes it back to the bare\n\t// `{{name}}` token (no kind prefix).\n\tconst onSelectVariable = useCallback((variable: VariableV3) => {\n\t\tconst name = variableTokenName(variable.actualValue);\n\t\teditorRef.current?.insertInlineContent(\n\t\t\t`${buildMentionHtml(\n\t\t\t\tname,\n\t\t\t\t`Variable: ${variable.displayName}`,\n\t\t\t\t'variable',\n\t\t\t)} `,\n\t\t);\n\t}, []);\n\n\tconst insert = useCallback<InsertFn>(\n\t\t(kind, id, overrideLabel) => {\n\t\t\tconst editor = editorRef.current;\n\t\t\tif (!editor) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst item = mentionItems.find(\n\t\t\t\t(m) =>\n\t\t\t\t\tString(m.id) === String(id) &&\n\t\t\t\t\t(m.meta as unknown as MentionKindMeta | undefined)?.kind === kind,\n\t\t\t);\n\t\t\tconst finalLabel = overrideLabel ?? item?.label ?? id;\n\t\t\teditor.insertInlineContent(\n\t\t\t\t`${buildMentionHtml(String(id), finalLabel, kind)} `,\n\t\t\t);\n\t\t},\n\t\t[mentionItems],\n\t);\n\n\tuseEffect(() => {\n\t\tif (!registerInsert) {\n\t\t\treturn;\n\t\t}\n\t\tregisterInsert(insert);\n\t\treturn () => registerInsert(null);\n\t}, [registerInsert, insert]);\n\n\t// Mount-only initial HTML; recomputed (editor remounted via key) on resetKey.\n\t// Variable items are merged in so stored `{{name}}` tokens rehydrate as chips.\n\tconst initialHtml = useMemo(\n\t\t() =>\n\t\t\tinstructionsToEditorHtml(value, [\n\t\t\t\t...mentionItems,\n\t\t\t\t...buildVariableMentionItems(variablesData),\n\t\t\t]),\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[resetKey],\n\t);\n\n\tuseEffect(\n\t\t() => setCount(value.length),\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[resetKey],\n\t);\n\n\treturn (\n\t\t<FieldBlock>\n\t\t\t<FieldLabelRow>\n\t\t\t\t<TitleSmall color={COLORS.content.primary}>{label}</TitleSmall>\n\t\t\t\t<BodyCaption color={COLORS.content.secondary}>\n\t\t\t\t\t{count}/{maxLength}\n\t\t\t\t</BodyCaption>\n\t\t\t</FieldLabelRow>\n\n\t\t\t<AiTextAreaShell minHeight={minHeight} data-test={rest['data-test']}>\n\t\t\t\t<BikEditor\n\t\t\t\t\tkey={resetKey}\n\t\t\t\t\tref={editorRef}\n\t\t\t\t\tinitialContent={initialHtml}\n\t\t\t\t\tplaceholder={placeholder}\n\t\t\t\t\t// Soft limit: blocks typing past the cap but lets a paste through\n\t\t\t\t\t// (overflow rendered grey) instead of rejecting the whole paste.\n\t\t\t\t\tcharacterLimit={maxLength}\n\t\t\t\t\tminHeight=\"120px\"\n\t\t\t\t\tmaxHeight=\"320px\"\n\t\t\t\t\tstyle={{ border: 'none' }}\n\t\t\t\t\teditorStyle={AGENT_EDITOR_STYLE}\n\t\t\t\t\tonFocus={onFocus}\n\t\t\t\t\tmentions={{\n\t\t\t\t\t\tagents: mentionItems,\n\t\t\t\t\t\tremoveTriggerOnDismiss: true,\n\t\t\t\t\t\trenderDropdown: (props) => (\n\t\t\t\t\t\t\t<MentionPicker\n\t\t\t\t\t\t\t\t{...props}\n\t\t\t\t\t\t\t\tonCreateSubAgent={onCreateSubAgent}\n\t\t\t\t\t\t\t\ttoolActions={toolActions}\n\t\t\t\t\t\t\t\tintegrationStatus={integrationStatus}\n\t\t\t\t\t\t\t\tonConnectIntegration={onConnectIntegration}\n\t\t\t\t\t\t\t\tvariablesData={variablesData}\n\t\t\t\t\t\t\t\tonSelectVariable={onSelectVariable}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t),\n\t\t\t\t\t\tonSelect: (item) => {\n\t\t\t\t\t\t\tconst kind = (item.meta as unknown as MentionKindMeta | undefined)\n\t\t\t\t\t\t\t\t?.kind;\n\t\t\t\t\t\t\t// Variables never come through this path (they use the embedded\n\t\t\t\t\t\t\t// picker's onSelectVariable) and have nothing to attach upstream.\n\t\t\t\t\t\t\tif (kind === 'tool' || kind === 'subagent') {\n\t\t\t\t\t\t\t\tonMentionSelect?.(kind, String(item.id));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t}}\n\t\t\t\t\tonChange={(snapshot) => {\n\t\t\t\t\t\tsetCount(snapshot.characterCount);\n\t\t\t\t\t\tconst doc = editorRef.current?.getJSON() ?? null;\n\t\t\t\t\t\tonChange(editorDocToInstructions(doc, tools));\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t\t{action}\n\t\t\t</AiTextAreaShell>\n\t\t</FieldBlock>\n\t);\n};\n"],"names":["MentionEditor","label","value","onChange","maxLength","placeholder","minHeight","resetKey","mentionItems","tools","onMentionSelect","onFocus","registerInsert","onCreateSubAgent","toolActions","integrationStatus","onConnectIntegration","variablesData","action","rest","editorRef","useRef","count","setCount","useState","onSelectVariable","useCallback","variable","name","variableTokenName","buildMentionHtml","insert","kind","id","overrideLabel","editor","item","m","finalLabel","useEffect","initialHtml","useMemo","instructionsToEditorHtml","buildVariableMentionItems","FieldBlock","jsxs","FieldLabelRow","jsx","TitleSmall","COLORS","BodyCaption","AiTextAreaShell","BikEditor","AGENT_EDITOR_STYLE","props","MentionPicker","snapshot","doc","editorDocToInstructions"],"mappings":";;;;;;;;;AAiFO,MAAMA,KAA8C,CAAC;AAAA,EAC3D,OAAAC;AAAA,EACA,OAAAC;AAAA,EACA,UAAAC;AAAA,EACA,WAAAC;AAAA,EACA,aAAAC;AAAA,EACA,WAAAC,IAAY;AAAA,EACZ,UAAAC;AAAA,EACA,cAAAC;AAAA,EACA,OAAAC;AAAA,EACA,iBAAAC;AAAA,EACA,SAAAC;AAAA,EACA,gBAAAC;AAAA,EACA,kBAAAC;AAAA,EACA,aAAAC;AAAA,EACA,mBAAAC;AAAA,EACA,sBAAAC;AAAA,EACA,eAAAC;AAAA,EACA,QAAAC;AAAA,EACA,GAAGC;AACJ,MAAM;AACL,QAAMC,IAAYC,EAAqB,IAAI,GACrC,CAACC,GAAOC,CAAQ,IAAIC,EAAStB,EAAM,MAAM,GAMzCuB,IAAmBC,EAAY,CAACC,MAAyB;AAC9D,UAAMC,IAAOC,EAAkBF,EAAS,WAAW;AACnD,IAAAP,EAAU,SAAS;AAAA,MAClB,GAAGU;AAAA,QACFF;AAAA,QACA,aAAaD,EAAS,WAAW;AAAA,QACjC;AAAA,MAAA,CACA;AAAA,IAAA;AAAA,EAEH,GAAG,CAAA,CAAE,GAECI,IAASL;AAAA,IACd,CAACM,GAAMC,GAAIC,MAAkB;AAC5B,YAAMC,IAASf,EAAU;AACzB,UAAI,CAACe;AACJ;AAED,YAAMC,IAAO5B,EAAa;AAAA,QACzB,CAAC6B,MACA,OAAOA,EAAE,EAAE,MAAM,OAAOJ,CAAE,KACzBI,EAAE,MAAiD,SAASL;AAA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;AAAA,YACT,QAAQH;AAAA,YACR,wBAAwB;AAAA,YACxB,gBAAgB,CAAC8C,MAChB,gBAAAP;AAAA,cAACQ;AAAA,cAAA;AAAA,gBACC,GAAGD;AAAA,gBACJ,kBAAAzC;AAAA,gBACA,aAAAC;AAAA,gBACA,mBAAAC;AAAA,gBACA,sBAAAC;AAAA,gBACA,eAAAC;AAAA,gBACA,kBAAAQ;AAAA,cAAA;AAAA,YAAA;AAAA,YAGF,UAAU,CAACW,MAAS;AACnB,oBAAMJ,IAAQI,EAAK,MAChB;AAGH,eAAIJ,MAAS,UAAUA,MAAS,eAC/BtB,IAAkBsB,GAAM,OAAOI,EAAK,EAAE,CAAC;AAAA,YAEzC;AAAA,UAAA;AAAA,UAED,UAAU,CAACoB,MAAa;AACvB,YAAAjC,EAASiC,EAAS,cAAc;AAChC,kBAAMC,IAAMrC,EAAU,SAAS,QAAA,KAAa;AAC5C,YAAAjB,EAASuD,EAAwBD,GAAKhD,CAAK,CAAC;AAAA,UAC7C;AAAA,QAAA;AAAA,QAxCKF;AAAA,MAAA;AAAA,MA0CLW;AAAA,IAAA,EAAA,CACF;AAAA,EAAA,GACD;AAEF;"}
|
|
1
|
+
{"version":3,"file":"MentionEditor.js","sources":["../../../../../src/components/agent-builder/components/MentionEditor.tsx"],"sourcesContent":["import { BikEditor, BikEditorRef, MentionItem } from '@src/editor';\nimport React, {\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState,\n} from 'react';\nimport { BodyCaption, TitleSmall } from '@src/components/TypographyStyle';\nimport { COLORS } from '@src/constants/Theme';\nimport type {\n\tVariableListInterfaceV3,\n\tVariableV3,\n} from '../../variable-picker-v3/model';\nimport { AgentTool } from '../AgentBuilder.model';\nimport {\n\tAiTextAreaShell,\n\tFieldBlock,\n\tFieldLabelRow,\n} from '../AgentBuilder.styled';\nimport { AGENT_EDITOR_STYLE } from '../constants/editorStyle';\nimport type { ToolAction, ToolSource } from '../constants/tools';\nimport {\n\tbuildMentionHtml,\n\tbuildVariableMentionItems,\n\teditorDocToInstructions,\n\tinstructionsToEditorHtml,\n\tMentionKindMeta,\n\tvariableTokenName,\n} from '../utils/mentionSerialization';\nimport { MentionPicker } from './MentionPicker';\n\ntype InsertFn = (kind: 'tool' | 'subagent', id: string, label?: string) => void;\n\ninterface MentionEditorProps {\n\tlabel: string;\n\tvalue: string;\n\tonChange: (text: string) => void;\n\tmaxLength: number;\n\tplaceholder?: string;\n\tminHeight?: string;\n\t/** Changing this remounts the editor with fresh content. */\n\tresetKey?: string | number;\n\t/** Items shown in the `@` picker (tools, and sub-agents where allowed). */\n\tmentionItems: MentionItem[];\n\t/** Tools used to serialise mention nodes back to `{{tool:KEY}}`. */\n\ttools: AgentTool[];\n\t/** Called when an item is picked from the `@` menu (to attach it upstream). */\n\tonMentionSelect?: (kind: 'tool' | 'subagent', id: string) => void;\n\tonFocus?: () => void;\n\t/** Receives an insert-at-cursor fn (and null on unmount) for side-panel adds. */\n\tregisterInsert?: (fn: InsertFn | null) => void;\n\t/**\n\t * When set, the `@` picker's Sub-agent view shows a \"Create new\" row that calls\n\t * this (opens the create-sub-agent drawer). Omit to hide it (e.g. the drawer's\n\t * own editors, which can't nest sub-agents).\n\t */\n\tonCreateSubAgent?: () => void;\n\t/**\n\t * Built-in tool actions (Rest API / Handover to email) shown in the `@` picker's\n\t * Tools view. Picking one opens its drawer instead of inserting a mention.\n\t */\n\ttoolActions?: ToolAction[];\n\tintegrationStatus?: Partial<Record<ToolSource, boolean>>;\n\tonConnectIntegration?: (source: ToolSource) => void;\n\t/**\n\t * Variable catalog for the `@` picker's \"Variables\" view. Picking one inserts\n\t * a `Variable: <name>` mention chip at the cursor, persisted as a\n\t * `{{variable:<name>}}` token. Omit to hide the category.\n\t */\n\tvariablesData?: VariableListInterfaceV3[];\n\t/** Optional action(s) rendered inside the shell, below the editor. */\n\taction?: React.ReactNode;\n\t'data-test'?: string;\n}\n\n/**\n * Presentational BikEditor field with `@` mentions. Stores firebase token text\n * (`{{tool:KEY}}` / `{{subagent:ID}}`). Context-free — both the builder's\n * Step-3 fields and the create-sub-agent drawer compose it.\n */\nexport const MentionEditor: React.FC<MentionEditorProps> = ({\n\tlabel,\n\tvalue,\n\tonChange,\n\tmaxLength,\n\tplaceholder,\n\tminHeight = '200px',\n\tresetKey,\n\tmentionItems,\n\ttools,\n\tonMentionSelect,\n\tonFocus,\n\tregisterInsert,\n\tonCreateSubAgent,\n\ttoolActions,\n\tintegrationStatus,\n\tonConnectIntegration,\n\tvariablesData,\n\taction,\n\t...rest\n}) => {\n\tconst editorRef = useRef<BikEditorRef>(null);\n\tconst [count, setCount] = useState(value.length);\n\n\t// The picker dismissed itself already (stripping the \"@\" + query) — drop a\n\t// `Variable: <name>` mention chip at the cursor, same shape as tool /\n\t// sub-agent chips. `editorDocToInstructions` serializes it back to a\n\t// `{{variable:<name>}}` token.\n\tconst onSelectVariable = useCallback((variable: VariableV3) => {\n\t\tconst name = variableTokenName(variable.actualValue);\n\t\teditorRef.current?.insertInlineContent(\n\t\t\t`${buildMentionHtml(\n\t\t\t\tname,\n\t\t\t\t`Variable: ${variable.displayName}`,\n\t\t\t\t'variable',\n\t\t\t)} `,\n\t\t);\n\t}, []);\n\n\tconst insert = useCallback<InsertFn>(\n\t\t(kind, id, overrideLabel) => {\n\t\t\tconst editor = editorRef.current;\n\t\t\tif (!editor) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst item = mentionItems.find(\n\t\t\t\t(m) =>\n\t\t\t\t\tString(m.id) === String(id) &&\n\t\t\t\t\t(m.meta as unknown as MentionKindMeta | undefined)?.kind === kind,\n\t\t\t);\n\t\t\tconst finalLabel = overrideLabel ?? item?.label ?? id;\n\t\t\teditor.insertInlineContent(\n\t\t\t\t`${buildMentionHtml(String(id), finalLabel, kind)} `,\n\t\t\t);\n\t\t},\n\t\t[mentionItems],\n\t);\n\n\tuseEffect(() => {\n\t\tif (!registerInsert) {\n\t\t\treturn;\n\t\t}\n\t\tregisterInsert(insert);\n\t\treturn () => registerInsert(null);\n\t}, [registerInsert, insert]);\n\n\t// Mount-only initial HTML; recomputed (editor remounted via key) on resetKey.\n\t// Variable items are merged in so stored `{{name}}` tokens rehydrate as chips.\n\tconst initialHtml = useMemo(\n\t\t() =>\n\t\t\tinstructionsToEditorHtml(value, [\n\t\t\t\t...mentionItems,\n\t\t\t\t...buildVariableMentionItems(variablesData),\n\t\t\t]),\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[resetKey],\n\t);\n\n\tuseEffect(\n\t\t() => setCount(value.length),\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[resetKey],\n\t);\n\n\treturn (\n\t\t<FieldBlock>\n\t\t\t<FieldLabelRow>\n\t\t\t\t<TitleSmall color={COLORS.content.primary}>{label}</TitleSmall>\n\t\t\t\t<BodyCaption color={COLORS.content.secondary}>\n\t\t\t\t\t{count}/{maxLength}\n\t\t\t\t</BodyCaption>\n\t\t\t</FieldLabelRow>\n\n\t\t\t<AiTextAreaShell minHeight={minHeight} data-test={rest['data-test']}>\n\t\t\t\t<BikEditor\n\t\t\t\t\tkey={resetKey}\n\t\t\t\t\tref={editorRef}\n\t\t\t\t\tinitialContent={initialHtml}\n\t\t\t\t\tplaceholder={placeholder}\n\t\t\t\t\t// Soft limit: blocks typing past the cap but lets a paste through\n\t\t\t\t\t// (overflow rendered grey) instead of rejecting the whole paste.\n\t\t\t\t\tcharacterLimit={maxLength}\n\t\t\t\t\tminHeight=\"120px\"\n\t\t\t\t\tmaxHeight=\"320px\"\n\t\t\t\t\tstyle={{ border: 'none' }}\n\t\t\t\t\teditorStyle={AGENT_EDITOR_STYLE}\n\t\t\t\t\tonFocus={onFocus}\n\t\t\t\t\tmentions={{\n\t\t\t\t\t\tagents: mentionItems,\n\t\t\t\t\t\tremoveTriggerOnDismiss: true,\n\t\t\t\t\t\trenderDropdown: (props) => (\n\t\t\t\t\t\t\t<MentionPicker\n\t\t\t\t\t\t\t\t{...props}\n\t\t\t\t\t\t\t\tonCreateSubAgent={onCreateSubAgent}\n\t\t\t\t\t\t\t\ttoolActions={toolActions}\n\t\t\t\t\t\t\t\tintegrationStatus={integrationStatus}\n\t\t\t\t\t\t\t\tonConnectIntegration={onConnectIntegration}\n\t\t\t\t\t\t\t\tvariablesData={variablesData}\n\t\t\t\t\t\t\t\tonSelectVariable={onSelectVariable}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t),\n\t\t\t\t\t\tonSelect: (item) => {\n\t\t\t\t\t\t\tconst kind = (item.meta as unknown as MentionKindMeta | undefined)\n\t\t\t\t\t\t\t\t?.kind;\n\t\t\t\t\t\t\t// Variables never come through this path (they use the embedded\n\t\t\t\t\t\t\t// picker's onSelectVariable) and have nothing to attach upstream.\n\t\t\t\t\t\t\tif (kind === 'tool' || kind === 'subagent') {\n\t\t\t\t\t\t\t\tonMentionSelect?.(kind, String(item.id));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t}}\n\t\t\t\t\tonChange={(snapshot) => {\n\t\t\t\t\t\tsetCount(snapshot.characterCount);\n\t\t\t\t\t\tconst doc = editorRef.current?.getJSON() ?? null;\n\t\t\t\t\t\tonChange(editorDocToInstructions(doc, tools));\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t\t{action}\n\t\t\t</AiTextAreaShell>\n\t\t</FieldBlock>\n\t);\n};\n"],"names":["MentionEditor","label","value","onChange","maxLength","placeholder","minHeight","resetKey","mentionItems","tools","onMentionSelect","onFocus","registerInsert","onCreateSubAgent","toolActions","integrationStatus","onConnectIntegration","variablesData","action","rest","editorRef","useRef","count","setCount","useState","onSelectVariable","useCallback","variable","name","variableTokenName","buildMentionHtml","insert","kind","id","overrideLabel","editor","item","m","finalLabel","useEffect","initialHtml","useMemo","instructionsToEditorHtml","buildVariableMentionItems","FieldBlock","jsxs","FieldLabelRow","jsx","TitleSmall","COLORS","BodyCaption","AiTextAreaShell","BikEditor","AGENT_EDIT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AAAA,gBACA,kBAAAQ;AAAA,cAAA;AAAA,YAAA;AAAA,YAGF,UAAU,CAACW,MAAS;AACnB,oBAAMJ,IAAQI,EAAK,MAChB;AAGH,eAAIJ,MAAS,UAAUA,MAAS,eAC/BtB,IAAkBsB,GAAM,OAAOI,EAAK,EAAE,CAAC;AAAA,YAEzC;AAAA,UAAA;AAAA,UAED,UAAU,CAACoB,MAAa;AACvB,YAAAjC,EAASiC,EAAS,cAAc;AAChC,kBAAMC,IAAMrC,EAAU,SAAS,QAAA,KAAa;AAC5C,YAAAjB,EAASuD,EAAwBD,GAAKhD,CAAK,CAAC;AAAA,UAC7C;AAAA,QAAA;AAAA,QAxCKF;AAAA,MAAA;AAAA,MA0CLW;AAAA,IAAA,EAAA,CACF;AAAA,EAAA,GACD;AAEF;"}
|
|
@@ -10,7 +10,7 @@ import { TOOL_SOURCE_LABELS } from '../constants/tools';
|
|
|
10
10
|
* Firebase stores `instructions` as PLAIN TEXT with inline reference tokens:
|
|
11
11
|
* - `{{subagent:<agentId>}}` — hand-off to another agent
|
|
12
12
|
* - `{{tool:<tool_id>}}` — an action the agent can call
|
|
13
|
-
* - `{{
|
|
13
|
+
* - `{{variable:<name>}}` — a template variable picked from the catalog
|
|
14
14
|
*
|
|
15
15
|
* In the editor those references are inserted via the `@` mention menu (which we
|
|
16
16
|
* populate with BOTH tools and sub-agents). Mention nodes keep their `id` in the
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TOOL_SOURCE_LABELS as m, ToolSource as
|
|
1
|
+
import { TOOL_SOURCE_LABELS as m, ToolSource as r } from "../constants/tools.js";
|
|
2
2
|
const b = (e, t = "Manifest") => e ? m[e] ?? e : t, E = (e) => {
|
|
3
3
|
const t = e ? String(e) : "";
|
|
4
4
|
return t === "BIK" ? "BIK" : t === "BSP" ? "BSP" : "Manifest";
|
|
@@ -36,11 +36,11 @@ const b = (e, t = "Manifest") => e ? m[e] ?? e : t, E = (e) => {
|
|
|
36
36
|
const t = $(e);
|
|
37
37
|
return {
|
|
38
38
|
id: e.id,
|
|
39
|
-
label: `${m[
|
|
40
|
-
meta: { kind: "tool", plainLabel: t, source:
|
|
39
|
+
label: `${m[r.RestApi]} : ${t}`,
|
|
40
|
+
meta: { kind: "tool", plainLabel: t, source: r.RestApi }
|
|
41
41
|
};
|
|
42
42
|
}, S = (e) => {
|
|
43
|
-
const t = e.tool_key === "send_slack_message" ?
|
|
43
|
+
const t = e.tool_key === "send_slack_message" ? r.Slack : r.EmailHandover, n = k(e);
|
|
44
44
|
return {
|
|
45
45
|
id: e.id,
|
|
46
46
|
label: `${m[t]} : ${n}`,
|
|
@@ -49,14 +49,14 @@ const b = (e, t = "Manifest") => e ? m[e] ?? e : t, E = (e) => {
|
|
|
49
49
|
}, M = (e = [], t = []) => [
|
|
50
50
|
...t.map(f),
|
|
51
51
|
...e.map(S)
|
|
52
|
-
], o = (e) => e.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"),
|
|
52
|
+
], o = (e) => e.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"), s = (e) => o(e).replace(/"/g, """), d = (e, t, n) => `<span data-type="mentionAgent" class="bik-mention bik-mention--agent" data-id="${s(e)}" data-label="${s(t)}" data-kind="${s(n)}">${o(t)}</span>`, y = (e, t, n) => d(e, t, n), T = (e) => {
|
|
53
53
|
const t = /* @__PURE__ */ new Map();
|
|
54
54
|
for (const n of e) {
|
|
55
55
|
const a = n.meta;
|
|
56
|
-
a?.kind === "tool" ? t.set(`tool:${String(n.id)}`, n) : a?.kind === "subagent" ? t.set(`subagent:${String(n.id)}`, n) : a?.kind === "variable" && t.set(String(n.id)
|
|
56
|
+
a?.kind === "tool" ? t.set(`tool:${String(n.id)}`, n) : a?.kind === "subagent" ? t.set(`subagent:${String(n.id)}`, n) : a?.kind === "variable" && t.set(`variable:${String(n.id)}`, n);
|
|
57
57
|
}
|
|
58
58
|
return t;
|
|
59
|
-
}, c = /\{\{([^{}]+)\}\}/g,
|
|
59
|
+
}, c = /\{\{((?:tool|subagent|variable):[^{}]+)\}\}/g, v = (e, t) => {
|
|
60
60
|
let n = "", a = 0;
|
|
61
61
|
c.lastIndex = 0;
|
|
62
62
|
let i;
|
|
@@ -75,8 +75,8 @@ const b = (e, t = "Manifest") => e ? m[e] ?? e : t, E = (e) => {
|
|
|
75
75
|
if (!e)
|
|
76
76
|
return "";
|
|
77
77
|
const n = T(t);
|
|
78
|
-
return e.split(/\n{2,}/).map((a) => `<p>${
|
|
79
|
-
},
|
|
78
|
+
return e.split(/\n{2,}/).map((a) => `<p>${v(a, n)}</p>`).join("");
|
|
79
|
+
}, L = (e, t, n) => t === "variable" ? `{{variable:${e}}}` : (t ?? (n.has(e) ? "tool" : "subagent")) === "tool" ? `{{tool:${e}}}` : `{{subagent:${e}}}`, u = (e, t) => {
|
|
80
80
|
switch (e.type) {
|
|
81
81
|
case "text":
|
|
82
82
|
return e.text ?? "";
|
|
@@ -86,7 +86,7 @@ const b = (e, t = "Manifest") => e ? m[e] ?? e : t, E = (e) => {
|
|
|
86
86
|
if (n == null)
|
|
87
87
|
return "";
|
|
88
88
|
const a = e.attrs?.kind;
|
|
89
|
-
return
|
|
89
|
+
return L(
|
|
90
90
|
String(n),
|
|
91
91
|
a == null ? null : String(a),
|
|
92
92
|
t
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mentionSerialization.js","sources":["../../../../../src/components/agent-builder/utils/mentionSerialization.ts"],"sourcesContent":["import type { ApplicationType } from '@bikdotai/bik-models/growth';\nimport { MentionItem } from '@src/editor';\nimport type {\n\tSubHeader,\n\tVariableListInterfaceV3,\n\tVariableV3,\n} from '../../variable-picker-v3/model';\nimport {\n\tAgentTool,\n\tConfigToolConfig,\n\tRestApiToolConfig,\n\tSubAgentRef,\n} from '../AgentBuilder.model';\nimport { TOOL_SOURCE_LABELS, ToolSource } from '../constants/tools';\n\n/**\n * Serialization helpers between the BikEditor document and the firebase\n * `instructions` string.\n *\n * Firebase stores `instructions` as PLAIN TEXT with inline reference tokens:\n * - `{{subagent:<agentId>}}` — hand-off to another agent\n * - `{{tool:<tool_id>}}` — an action the agent can call\n * - `{{<variableName>}}` — a template variable\n *\n * In the editor those references are inserted via the `@` mention menu (which we\n * populate with BOTH tools and sub-agents). Mention nodes keep their `id` in the\n * ProseMirror doc JSON (the rendered HTML drops it), so we serialize from the doc\n * JSON — not from HTML.\n */\n\nexport interface MentionKindMeta {\n\t/** Distinguishes a tool / sub-agent / variable reference. */\n\tkind: 'tool' | 'subagent' | 'variable';\n\t/** Plain item name (no prefix) shown in the picker dropdown rows. */\n\tplainLabel?: string;\n\t/** For tools: the source bucket (manifest / shopify / …) the picker groups by. */\n\tsource?: string;\n\t/** For tools: touches customer-private data → shows a shield in the picker. */\n\tauthRequired?: boolean;\n}\n\n// Source labels moved to constants/tools.ts; re-exported for existing importers.\nexport { TOOL_SOURCE_LABELS };\n\n/** Human label for a tool source; falls back to the host-app label, then the raw key. */\nexport const toolSourceLabel = (\n\tsource: string | undefined,\n\tfallback = 'Manifest',\n): string => {\n\tif (!source) {\n\t\treturn fallback;\n\t}\n\treturn TOOL_SOURCE_LABELS[source as ToolSource] ?? source;\n};\n\n/** Human label for the host application, used as the tool-chip prefix. */\nexport const appTypeLabel = (applicationType?: ApplicationType): string => {\n\tconst key = applicationType ? String(applicationType) : '';\n\tif (key === 'BIK') {\n\t\treturn 'BIK';\n\t}\n\tif (key === 'BSP') {\n\t\treturn 'BSP';\n\t}\n\treturn 'Manifest';\n};\n\n/**\n * Build the combined `@` mention list from the available tools + sub-agents.\n *\n * The `label` is the CHIP text shown once inserted — tools read\n * `\"<App> : <tool name>\"` (e.g. \"Manifest : Look up order\"), sub-agents read\n * `\"sub-agent: <name>\"`. `meta.plainLabel` is the un-prefixed name for the\n * picker rows, and `meta.kind` drives the `{{tool}}` / `{{subagent}}` colour.\n */\nexport const buildAgentMentionItems = (\n\ttools: AgentTool[],\n\tsubAgents: SubAgentRef[],\n\tappLabel = 'Manifest',\n): MentionItem[] => [\n\t...tools.map(\n\t\t(t): MentionItem => ({\n\t\t\tid: t.tool_id,\n\t\t\tlabel: `${toolSourceLabel(t.source, appLabel)} : ${t.display_name}`,\n\t\t\tmeta: {\n\t\t\t\tkind: 'tool',\n\t\t\t\tplainLabel: t.display_name,\n\t\t\t\tsource: t.source,\n\t\t\t\tauthRequired: t.auth_required,\n\t\t\t},\n\t\t}),\n\t),\n\t...subAgents.map(\n\t\t(s): MentionItem => ({\n\t\t\tid: s.id,\n\t\t\tlabel: `sub-agent: ${s.name}`,\n\t\t\tmeta: { kind: 'subagent', plainLabel: s.name },\n\t\t}),\n\t),\n];\n\n/** Strip the `{{ }}` wrapper from a variable token (`{{a.b}}` → `a.b`). */\nexport const variableTokenName = (actualValue: string): string =>\n\tactualValue.replace(/^\\{\\{|\\}\\}$/g, '');\n\n/**\n * Flatten the (nested) variable catalog into mention items, so stored\n * `{{<name>}}` tokens rehydrate as `Variable: <display name>` chips. The item\n * id is the BARE token name (no braces) — `resolveMentionToken` re-wraps it on\n * save. Merge alongside {@link buildAgentMentionItems} for serialization.\n */\nexport const buildVariableMentionItems = (\n\tvariablesData: VariableListInterfaceV3[] = [],\n): MentionItem[] => {\n\tconst items: MentionItem[] = [];\n\tconst walk = (entry: VariableListInterfaceV3 | SubHeader | VariableV3) => {\n\t\tconst actual = (entry as VariableV3).actualValue;\n\t\tif (actual) {\n\t\t\titems.push({\n\t\t\t\tid: variableTokenName(actual),\n\t\t\t\tlabel: `Variable: ${entry.displayName}`,\n\t\t\t\tmeta: { kind: 'variable', plainLabel: entry.displayName },\n\t\t\t});\n\t\t}\n\t\tObject.values(entry.variables ?? {}).forEach(walk);\n\t};\n\tvariablesData.forEach(walk);\n\treturn items;\n};\n\n/** Display name for a shared config tool: first recipient / channel, else generic. */\nexport const configToolName = (t: ConfigToolConfig): string => {\n\tif (t.tool_key === 'send_slack_message') {\n\t\treturn (\n\t\t\tString(t.params['channelId']?.value ?? '').trim() || 'Send Slack message'\n\t\t);\n\t}\n\treturn (\n\t\tString(t.params['sendTo']?.value ?? '')\n\t\t\t.split(',')\n\t\t\t.map((s) => s.trim())\n\t\t\t.filter(Boolean)[0] || 'Send Email'\n\t);\n};\n\n/** Display name for a Rest API tool row / chip. */\nexport const restApiToolName = (t: RestApiToolConfig): string =>\n\tt.name || 'Rest API';\n\n/** The `@`-mention chip item for a Rest API tool (kind 'tool', restapi source). */\nexport const restApiMentionItem = (t: RestApiToolConfig): MentionItem => {\n\tconst name = restApiToolName(t);\n\treturn {\n\t\tid: t.id,\n\t\tlabel: `${TOOL_SOURCE_LABELS[ToolSource.RestApi]} : ${name}`,\n\t\tmeta: { kind: 'tool', plainLabel: name, source: ToolSource.RestApi },\n\t};\n};\n\n/** The `@`-mention chip item for a shared config tool (email / Slack). */\nexport const configToolMentionItem = (t: ConfigToolConfig): MentionItem => {\n\tconst source =\n\t\tt.tool_key === 'send_slack_message'\n\t\t\t? ToolSource.Slack\n\t\t\t: ToolSource.EmailHandover;\n\tconst name = configToolName(t);\n\treturn {\n\t\tid: t.id,\n\t\tlabel: `${TOOL_SOURCE_LABELS[source]} : ${name}`,\n\t\tmeta: { kind: 'tool', plainLabel: name, source },\n\t};\n};\n\n/**\n * Mention items for the inline-configured custom tools (Rest API + email / Slack)\n * so their `{{tool:<id>}}` tokens rehydrate as chips — they live on the agent\n * value, not in the catalog `availableTools`. Merge alongside\n * {@link buildAgentMentionItems} in the editor's mention list.\n */\nexport const buildCustomToolMentionItems = (\n\tconfigTools: ConfigToolConfig[] = [],\n\trestApiTools: RestApiToolConfig[] = [],\n): MentionItem[] => [\n\t...restApiTools.map(restApiMentionItem),\n\t...configTools.map(configToolMentionItem),\n];\n\nconst escapeHtml = (raw: string): string =>\n\traw.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\nconst escapeAttr = (raw: string): string =>\n\tescapeHtml(raw).replace(/\"/g, '"');\n\n/**\n * The HTML for a single mention chip. Must round-trip through the TipTap mention\n * extension's `parseHTML` (`span[data-type=\"mentionAgent\"]`, reading\n * `data-id`/`data-label`/`data-kind`) — see MentionExtension.ts. `normalizeHtml`\n * is taught to keep `data-type=\"mention…\"` spans so this survives to the parser.\n */\nconst mentionSpanHtml = (id: string, label: string, kind: string): string =>\n\t`<span data-type=\"mentionAgent\" class=\"bik-mention bik-mention--agent\"` +\n\t` data-id=\"${escapeAttr(id)}\" data-label=\"${escapeAttr(label)}\"` +\n\t` data-kind=\"${escapeAttr(kind)}\">${escapeHtml(label)}</span>`;\n\n/**\n * Public: HTML for one mention chip, for inserting at the cursor (e.g. when a\n * tool / sub-agent is added from the Step-3 side panel). Round-trips through the\n * same parser path as the rehydrated chips.\n */\nexport const buildMentionHtml = (\n\tid: string,\n\tlabel: string,\n\tkind: 'tool' | 'subagent' | 'variable',\n): string => mentionSpanHtml(id, label, kind);\n\n/**\n * `{{tool:<id>}}` / `{{subagent:<id>}}` / `{{<variableName>}}` → the mention\n * item that produced them. The map key is the token's INNER text.\n */\nconst buildTokenLookup = (\n\tmentionItems: MentionItem[],\n): Map<string, MentionItem> => {\n\tconst byToken = new Map<string, MentionItem>();\n\tfor (const item of mentionItems) {\n\t\tconst meta = item.meta as unknown as MentionKindMeta | undefined;\n\t\t// Tools and sub-agents are keyed by their prefixed id (a tool's id is its\n\t\t// tool_id); variables by their bare token name.\n\t\tif (meta?.kind === 'tool') {\n\t\t\tbyToken.set(`tool:${String(item.id)}`, item);\n\t\t} else if (meta?.kind === 'subagent') {\n\t\t\tbyToken.set(`subagent:${String(item.id)}`, item);\n\t\t} else if (meta?.kind === 'variable') {\n\t\t\tbyToken.set(String(item.id), item);\n\t\t}\n\t}\n\treturn byToken;\n};\n\n// Matches any `{{…}}` token. Ones resolved via the lookup render as chips;\n// the rest fall through untouched (literal text for the variable decoration).\nconst REFERENCE_TOKEN = /\\{\\{([^{}]+)\\}\\}/g;\n\n/** Escape plain text, swapping recognised reference tokens for mention spans. */\nconst inlineToHtml = (\n\tsegment: string,\n\tbyToken: Map<string, MentionItem>,\n): string => {\n\tlet out = '';\n\tlet lastIndex = 0;\n\tREFERENCE_TOKEN.lastIndex = 0;\n\tlet match: RegExpExecArray | null;\n\twhile ((match = REFERENCE_TOKEN.exec(segment)) !== null) {\n\t\tout += escapeHtml(segment.slice(lastIndex, match.index));\n\t\tconst item = byToken.get(match[1]);\n\t\tif (item) {\n\t\t\tconst kind = (item.meta as unknown as MentionKindMeta).kind;\n\t\t\tout += mentionSpanHtml(String(item.id), item.label, kind);\n\t\t} else {\n\t\t\t// Not in any available list (removed tool / unknown variable) → keep the\n\t\t\t// raw token as literal text.\n\t\t\tout += escapeHtml(match[0]);\n\t\t}\n\t\tlastIndex = REFERENCE_TOKEN.lastIndex;\n\t}\n\tout += escapeHtml(segment.slice(lastIndex));\n\treturn out.replace(/\\n/g, '<br>');\n};\n\n/**\n * Convert the stored instructions string into HTML for `BikEditor.initialContent`.\n * `{{tool:KEY}}` / `{{subagent:ID}}` tokens are rehydrated into mention chips\n * (resolved via `mentionItems`); any other `{{…}}` token is left as literal text\n * for the editor's variable decoration. Newlines become paragraph / line breaks.\n */\nexport const instructionsToEditorHtml = (\n\ttext: string,\n\tmentionItems: MentionItem[] = [],\n): string => {\n\tif (!text) {\n\t\treturn '';\n\t}\n\tconst byToken = buildTokenLookup(mentionItems);\n\treturn text\n\t\t.split(/\\n{2,}/)\n\t\t.map((para) => `<p>${inlineToHtml(para, byToken)}</p>`)\n\t\t.join('');\n};\n\ninterface ProseMirrorNode {\n\ttype: string;\n\ttext?: string;\n\tattrs?: Record<string, unknown>;\n\tcontent?: ProseMirrorNode[];\n}\n\n/**\n * The token for a mention node. All kinds store their id in the node, so the\n * token value is just that id — the kind only picks the prefix (variables have\n * none: `{{<id>}}`). The node's `kind` attr is authoritative; `toolIds` is a\n * fallback for older content saved before the kind attr existed.\n */\nconst resolveMentionToken = (\n\tid: string,\n\tkind: string | null,\n\ttoolIds: Set<string>,\n): string => {\n\tif (kind === 'variable') {\n\t\treturn `{{${id}}}`;\n\t}\n\tconst resolved = kind ?? (toolIds.has(id) ? 'tool' : 'subagent');\n\treturn resolved === 'tool' ? `{{tool:${id}}}` : `{{subagent:${id}}}`;\n};\n\nconst nodeToText = (node: ProseMirrorNode, toolIds: Set<string>): string => {\n\tswitch (node.type) {\n\t\tcase 'text':\n\t\t\treturn node.text ?? '';\n\t\tcase 'mentionAgent':\n\t\tcase 'mentionTeam': {\n\t\t\tconst id = node.attrs?.['id'];\n\t\t\tif (id == null) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tconst kind = node.attrs?.['kind'];\n\t\t\treturn resolveMentionToken(\n\t\t\t\tString(id),\n\t\t\t\tkind == null ? null : String(kind),\n\t\t\t\ttoolIds,\n\t\t\t);\n\t\t}\n\t\tcase 'variable':\n\t\t\treturn `{{${String(node.attrs?.['variableName'] ?? '')}}}`;\n\t\tcase 'hardBreak':\n\t\t\treturn '\\n';\n\t\tcase 'orderedList':\n\t\tcase 'bulletList': {\n\t\t\t// Flattening to plain text otherwise drops the list markers, so a\n\t\t\t// numbered / bulleted list looks \"removed\" after publish. Emit an\n\t\t\t// ordinal (\"1. \") / bullet (\"- \") prefix per item to preserve it.\n\t\t\tconst ordered = node.type === 'orderedList';\n\t\t\treturn (\n\t\t\t\t(node.content ?? [])\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(item, i) =>\n\t\t\t\t\t\t\t`${ordered ? `${i + 1}.` : '-'} ${nodeToText(\n\t\t\t\t\t\t\t\titem,\n\t\t\t\t\t\t\t\ttoolIds,\n\t\t\t\t\t\t\t).replace(/\\n+$/, '')}`,\n\t\t\t\t\t)\n\t\t\t\t\t.join('\\n') + '\\n'\n\t\t\t);\n\t\t}\n\t\tdefault: {\n\t\t\tconst inner = (node.content ?? [])\n\t\t\t\t.map((child) => nodeToText(child, toolIds))\n\t\t\t\t.join('');\n\t\t\t// Block nodes terminate with a newline so paragraphs stay separated.\n\t\t\tconst BLOCK_NODES = ['paragraph', 'heading', 'listItem', 'blockquote'];\n\t\t\treturn BLOCK_NODES.includes(node.type) ? `${inner}\\n` : inner;\n\t\t}\n\t}\n};\n\n/**\n * Convert a BikEditor document (from `ref.getJSON()`) into the firebase\n * instructions string, replacing mention nodes with `{{subagent:<id>}}` /\n * `{{tool:<tool_id>}}` tokens.\n */\nexport const editorDocToInstructions = (\n\tdoc: Record<string, unknown> | null,\n\ttools: AgentTool[],\n): string => {\n\tif (!doc) {\n\t\treturn '';\n\t}\n\tconst toolIds = new Set(tools.map((t) => t.tool_id));\n\treturn nodeToText(doc as unknown as ProseMirrorNode, toolIds).replace(\n\t\t/\\n+$/,\n\t\t'',\n\t);\n};\n"],"names":["toolSourceLabel","source","fallback","TOOL_SOURCE_LABELS","appTypeLabel","applicationType","key","buildAgentMentionItems","tools","subAgents","appLabel","t","s","variableTokenName","actualValue","buildVariableMentionItems","variablesData","items","walk","entry","actual","configToolName","restApiToolName","restApiMentionItem","name","ToolSource","configToolMentionItem","buildCustomToolMentionItems","configTools","restApiTools","escapeHtml","raw","escapeAttr","mentionSpanHtml","id","label","kind","buildMentionHtml","buildTokenLookup","mentionItems","byToken","item","meta","REFERENCE_TOKEN","inlineToHtml","segment","out","lastIndex","match","instructionsToEditorHtml","text","para","resolveMentionToken","toolIds","nodeToText","node","ordered","inner","child","editorDocToInstructions","doc"],"mappings":";AA6CO,MAAMA,IAAkB,CAC9BC,GACAC,IAAW,eAEND,IAGEE,EAAmBF,CAAoB,KAAKA,IAF3CC,GAMIE,IAAe,CAACC,MAA8C;AAC1E,QAAMC,IAAMD,IAAkB,OAAOA,CAAe,IAAI;AACxD,SAAIC,MAAQ,QACJ,QAEJA,MAAQ,QACJ,QAED;AACR,GAUaC,IAAyB,CACrCC,GACAC,GACAC,IAAW,eACQ;AAAA,EACnB,GAAGF,EAAM;AAAA,IACR,CAACG,OAAoB;AAAA,MACpB,IAAIA,EAAE;AAAA,MACN,OAAO,GAAGX,EAAgBW,EAAE,QAAQD,CAAQ,CAAC,MAAMC,EA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ils/mentionSerialization.ts"],"sourcesContent":["import type { ApplicationType } from '@bikdotai/bik-models/growth';\nimport { MentionItem } from '@src/editor';\nimport type {\n\tSubHeader,\n\tVariableListInterfaceV3,\n\tVariableV3,\n} from '../../variable-picker-v3/model';\nimport {\n\tAgentTool,\n\tConfigToolConfig,\n\tRestApiToolConfig,\n\tSubAgentRef,\n} from '../AgentBuilder.model';\nimport { TOOL_SOURCE_LABELS, ToolSource } from '../constants/tools';\n\n/**\n * Serialization helpers between the BikEditor document and the firebase\n * `instructions` string.\n *\n * Firebase stores `instructions` as PLAIN TEXT with inline reference tokens:\n * - `{{subagent:<agentId>}}` — hand-off to another agent\n * - `{{tool:<tool_id>}}` — an action the agent can call\n * - `{{variable:<name>}}` — a template variable picked from the catalog\n *\n * In the editor those references are inserted via the `@` mention menu (which we\n * populate with BOTH tools and sub-agents). Mention nodes keep their `id` in the\n * ProseMirror doc JSON (the rendered HTML drops it), so we serialize from the doc\n * JSON — not from HTML.\n */\n\nexport interface MentionKindMeta {\n\t/** Distinguishes a tool / sub-agent / variable reference. */\n\tkind: 'tool' | 'subagent' | 'variable';\n\t/** Plain item name (no prefix) shown in the picker dropdown rows. */\n\tplainLabel?: string;\n\t/** For tools: the source bucket (manifest / shopify / …) the picker groups by. */\n\tsource?: string;\n\t/** For tools: touches customer-private data → shows a shield in the picker. */\n\tauthRequired?: boolean;\n}\n\n// Source labels moved to constants/tools.ts; re-exported for existing importers.\nexport { TOOL_SOURCE_LABELS };\n\n/** Human label for a tool source; falls back to the host-app label, then the raw key. */\nexport const toolSourceLabel = (\n\tsource: string | undefined,\n\tfallback = 'Manifest',\n): string => {\n\tif (!source) {\n\t\treturn fallback;\n\t}\n\treturn TOOL_SOURCE_LABELS[source as ToolSource] ?? source;\n};\n\n/** Human label for the host application, used as the tool-chip prefix. */\nexport const appTypeLabel = (applicationType?: ApplicationType): string => {\n\tconst key = applicationType ? String(applicationType) : '';\n\tif (key === 'BIK') {\n\t\treturn 'BIK';\n\t}\n\tif (key === 'BSP') {\n\t\treturn 'BSP';\n\t}\n\treturn 'Manifest';\n};\n\n/**\n * Build the combined `@` mention list from the available tools + sub-agents.\n *\n * The `label` is the CHIP text shown once inserted — tools read\n * `\"<App> : <tool name>\"` (e.g. \"Manifest : Look up order\"), sub-agents read\n * `\"sub-agent: <name>\"`. `meta.plainLabel` is the un-prefixed name for the\n * picker rows, and `meta.kind` drives the `{{tool}}` / `{{subagent}}` colour.\n */\nexport const buildAgentMentionItems = (\n\ttools: AgentTool[],\n\tsubAgents: SubAgentRef[],\n\tappLabel = 'Manifest',\n): MentionItem[] => [\n\t...tools.map(\n\t\t(t): MentionItem => ({\n\t\t\tid: t.tool_id,\n\t\t\tlabel: `${toolSourceLabel(t.source, appLabel)} : ${t.display_name}`,\n\t\t\tmeta: {\n\t\t\t\tkind: 'tool',\n\t\t\t\tplainLabel: t.display_name,\n\t\t\t\tsource: t.source,\n\t\t\t\tauthRequired: t.auth_required,\n\t\t\t},\n\t\t}),\n\t),\n\t...subAgents.map(\n\t\t(s): MentionItem => ({\n\t\t\tid: s.id,\n\t\t\tlabel: `sub-agent: ${s.name}`,\n\t\t\tmeta: { kind: 'subagent', plainLabel: s.name },\n\t\t}),\n\t),\n];\n\n/** Strip the `{{ }}` wrapper from a variable token (`{{a.b}}` → `a.b`). */\nexport const variableTokenName = (actualValue: string): string =>\n\tactualValue.replace(/^\\{\\{|\\}\\}$/g, '');\n\n/**\n * Flatten the (nested) variable catalog into mention items, so stored\n * `{{<name>}}` tokens rehydrate as `Variable: <display name>` chips. The item\n * id is the BARE token name (no braces) — `resolveMentionToken` re-wraps it on\n * save. Merge alongside {@link buildAgentMentionItems} for serialization.\n */\nexport const buildVariableMentionItems = (\n\tvariablesData: VariableListInterfaceV3[] = [],\n): MentionItem[] => {\n\tconst items: MentionItem[] = [];\n\tconst walk = (entry: VariableListInterfaceV3 | SubHeader | VariableV3) => {\n\t\tconst actual = (entry as VariableV3).actualValue;\n\t\tif (actual) {\n\t\t\titems.push({\n\t\t\t\tid: variableTokenName(actual),\n\t\t\t\tlabel: `Variable: ${entry.displayName}`,\n\t\t\t\tmeta: { kind: 'variable', plainLabel: entry.displayName },\n\t\t\t});\n\t\t}\n\t\tObject.values(entry.variables ?? {}).forEach(walk);\n\t};\n\tvariablesData.forEach(walk);\n\treturn items;\n};\n\n/** Display name for a shared config tool: first recipient / channel, else generic. */\nexport const configToolName = (t: ConfigToolConfig): string => {\n\tif (t.tool_key === 'send_slack_message') {\n\t\treturn (\n\t\t\tString(t.params['channelId']?.value ?? '').trim() || 'Send Slack message'\n\t\t);\n\t}\n\treturn (\n\t\tString(t.params['sendTo']?.value ?? '')\n\t\t\t.split(',')\n\t\t\t.map((s) => s.trim())\n\t\t\t.filter(Boolean)[0] || 'Send Email'\n\t);\n};\n\n/** Display name for a Rest API tool row / chip. */\nexport const restApiToolName = (t: RestApiToolConfig): string =>\n\tt.name || 'Rest API';\n\n/** The `@`-mention chip item for a Rest API tool (kind 'tool', restapi source). */\nexport const restApiMentionItem = (t: RestApiToolConfig): MentionItem => {\n\tconst name = restApiToolName(t);\n\treturn {\n\t\tid: t.id,\n\t\tlabel: `${TOOL_SOURCE_LABELS[ToolSource.RestApi]} : ${name}`,\n\t\tmeta: { kind: 'tool', plainLabel: name, source: ToolSource.RestApi },\n\t};\n};\n\n/** The `@`-mention chip item for a shared config tool (email / Slack). */\nexport const configToolMentionItem = (t: ConfigToolConfig): MentionItem => {\n\tconst source =\n\t\tt.tool_key === 'send_slack_message'\n\t\t\t? ToolSource.Slack\n\t\t\t: ToolSource.EmailHandover;\n\tconst name = configToolName(t);\n\treturn {\n\t\tid: t.id,\n\t\tlabel: `${TOOL_SOURCE_LABELS[source]} : ${name}`,\n\t\tmeta: { kind: 'tool', plainLabel: name, source },\n\t};\n};\n\n/**\n * Mention items for the inline-configured custom tools (Rest API + email / Slack)\n * so their `{{tool:<id>}}` tokens rehydrate as chips — they live on the agent\n * value, not in the catalog `availableTools`. Merge alongside\n * {@link buildAgentMentionItems} in the editor's mention list.\n */\nexport const buildCustomToolMentionItems = (\n\tconfigTools: ConfigToolConfig[] = [],\n\trestApiTools: RestApiToolConfig[] = [],\n): MentionItem[] => [\n\t...restApiTools.map(restApiMentionItem),\n\t...configTools.map(configToolMentionItem),\n];\n\nconst escapeHtml = (raw: string): string =>\n\traw.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\nconst escapeAttr = (raw: string): string =>\n\tescapeHtml(raw).replace(/\"/g, '"');\n\n/**\n * The HTML for a single mention chip. Must round-trip through the TipTap mention\n * extension's `parseHTML` (`span[data-type=\"mentionAgent\"]`, reading\n * `data-id`/`data-label`/`data-kind`) — see MentionExtension.ts. `normalizeHtml`\n * is taught to keep `data-type=\"mention…\"` spans so this survives to the parser.\n */\nconst mentionSpanHtml = (id: string, label: string, kind: string): string =>\n\t`<span data-type=\"mentionAgent\" class=\"bik-mention bik-mention--agent\"` +\n\t` data-id=\"${escapeAttr(id)}\" data-label=\"${escapeAttr(label)}\"` +\n\t` data-kind=\"${escapeAttr(kind)}\">${escapeHtml(label)}</span>`;\n\n/**\n * Public: HTML for one mention chip, for inserting at the cursor (e.g. when a\n * tool / sub-agent is added from the Step-3 side panel). Round-trips through the\n * same parser path as the rehydrated chips.\n */\nexport const buildMentionHtml = (\n\tid: string,\n\tlabel: string,\n\tkind: 'tool' | 'subagent' | 'variable',\n): string => mentionSpanHtml(id, label, kind);\n\n/**\n * `{{tool:<id>}}` / `{{subagent:<id>}}` / `{{<variableName>}}` → the mention\n * item that produced them. The map key is the token's INNER text.\n */\nconst buildTokenLookup = (\n\tmentionItems: MentionItem[],\n): Map<string, MentionItem> => {\n\tconst byToken = new Map<string, MentionItem>();\n\tfor (const item of mentionItems) {\n\t\tconst meta = item.meta as unknown as MentionKindMeta | undefined;\n\t\t// Everything is keyed by its kind-prefixed id (a tool's id is its tool_id).\n\t\tif (meta?.kind === 'tool') {\n\t\t\tbyToken.set(`tool:${String(item.id)}`, item);\n\t\t} else if (meta?.kind === 'subagent') {\n\t\t\tbyToken.set(`subagent:${String(item.id)}`, item);\n\t\t} else if (meta?.kind === 'variable') {\n\t\t\tbyToken.set(`variable:${String(item.id)}`, item);\n\t\t}\n\t}\n\treturn byToken;\n};\n\n// Matches the kind-prefixed reference tokens we render as chips. Other\n// `{{var}}` tokens fall through untouched (left as literal text for the\n// variable decoration).\nconst REFERENCE_TOKEN = /\\{\\{((?:tool|subagent|variable):[^{}]+)\\}\\}/g;\n\n/** Escape plain text, swapping recognised reference tokens for mention spans. */\nconst inlineToHtml = (\n\tsegment: string,\n\tbyToken: Map<string, MentionItem>,\n): string => {\n\tlet out = '';\n\tlet lastIndex = 0;\n\tREFERENCE_TOKEN.lastIndex = 0;\n\tlet match: RegExpExecArray | null;\n\twhile ((match = REFERENCE_TOKEN.exec(segment)) !== null) {\n\t\tout += escapeHtml(segment.slice(lastIndex, match.index));\n\t\tconst item = byToken.get(match[1]);\n\t\tif (item) {\n\t\t\tconst kind = (item.meta as unknown as MentionKindMeta).kind;\n\t\t\tout += mentionSpanHtml(String(item.id), item.label, kind);\n\t\t} else {\n\t\t\t// Not in any available list (removed tool / unknown variable) → keep the\n\t\t\t// raw token as literal text.\n\t\t\tout += escapeHtml(match[0]);\n\t\t}\n\t\tlastIndex = REFERENCE_TOKEN.lastIndex;\n\t}\n\tout += escapeHtml(segment.slice(lastIndex));\n\treturn out.replace(/\\n/g, '<br>');\n};\n\n/**\n * Convert the stored instructions string into HTML for `BikEditor.initialContent`.\n * `{{tool:KEY}}` / `{{subagent:ID}}` tokens are rehydrated into mention chips\n * (resolved via `mentionItems`); any other `{{…}}` token is left as literal text\n * for the editor's variable decoration. Newlines become paragraph / line breaks.\n */\nexport const instructionsToEditorHtml = (\n\ttext: string,\n\tmentionItems: MentionItem[] = [],\n): string => {\n\tif (!text) {\n\t\treturn '';\n\t}\n\tconst byToken = buildTokenLookup(mentionItems);\n\treturn text\n\t\t.split(/\\n{2,}/)\n\t\t.map((para) => `<p>${inlineToHtml(para, byToken)}</p>`)\n\t\t.join('');\n};\n\ninterface ProseMirrorNode {\n\ttype: string;\n\ttext?: string;\n\tattrs?: Record<string, unknown>;\n\tcontent?: ProseMirrorNode[];\n}\n\n/**\n * The token for a mention node. All kinds store their id in the node, so the\n * token value is just that id — the kind only picks the prefix. The node's\n * `kind` attr is authoritative; `toolIds` is a fallback for older content\n * saved before the kind attr existed.\n */\nconst resolveMentionToken = (\n\tid: string,\n\tkind: string | null,\n\ttoolIds: Set<string>,\n): string => {\n\tif (kind === 'variable') {\n\t\treturn `{{variable:${id}}}`;\n\t}\n\tconst resolved = kind ?? (toolIds.has(id) ? 'tool' : 'subagent');\n\treturn resolved === 'tool' ? `{{tool:${id}}}` : `{{subagent:${id}}}`;\n};\n\nconst nodeToText = (node: ProseMirrorNode, toolIds: Set<string>): string => {\n\tswitch (node.type) {\n\t\tcase 'text':\n\t\t\treturn node.text ?? '';\n\t\tcase 'mentionAgent':\n\t\tcase 'mentionTeam': {\n\t\t\tconst id = node.attrs?.['id'];\n\t\t\tif (id == null) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tconst kind = node.attrs?.['kind'];\n\t\t\treturn resolveMentionToken(\n\t\t\t\tString(id),\n\t\t\t\tkind == null ? null : String(kind),\n\t\t\t\ttoolIds,\n\t\t\t);\n\t\t}\n\t\tcase 'variable':\n\t\t\treturn `{{${String(node.attrs?.['variableName'] ?? '')}}}`;\n\t\tcase 'hardBreak':\n\t\t\treturn '\\n';\n\t\tcase 'orderedList':\n\t\tcase 'bulletList': {\n\t\t\t// Flattening to plain text otherwise drops the list markers, so a\n\t\t\t// numbered / bulleted list looks \"removed\" after publish. Emit an\n\t\t\t// ordinal (\"1. \") / bullet (\"- \") prefix per item to preserve it.\n\t\t\tconst ordered = node.type === 'orderedList';\n\t\t\treturn (\n\t\t\t\t(node.content ?? [])\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(item, i) =>\n\t\t\t\t\t\t\t`${ordered ? `${i + 1}.` : '-'} ${nodeToText(\n\t\t\t\t\t\t\t\titem,\n\t\t\t\t\t\t\t\ttoolIds,\n\t\t\t\t\t\t\t).replace(/\\n+$/, '')}`,\n\t\t\t\t\t)\n\t\t\t\t\t.join('\\n') + '\\n'\n\t\t\t);\n\t\t}\n\t\tdefault: {\n\t\t\tconst inner = (node.content ?? [])\n\t\t\t\t.map((child) => nodeToText(child, toolIds))\n\t\t\t\t.join('');\n\t\t\t// Block nodes terminate with a newline so paragraphs stay separated.\n\t\t\tconst BLOCK_NODES = ['paragraph', 'heading', 'listItem', 'blockquote'];\n\t\t\treturn BLOCK_NODES.includes(node.type) ? `${inner}\\n` : inner;\n\t\t}\n\t}\n};\n\n/**\n * Convert a BikEditor document (from `ref.getJSON()`) into the firebase\n * instructions string, replacing mention nodes with `{{subagent:<id>}}` /\n * `{{tool:<tool_id>}}` tokens.\n */\nexport const editorDocToInstructions = (\n\tdoc: Record<string, unknown> | null,\n\ttools: AgentTool[],\n): string => {\n\tif (!doc) {\n\t\treturn '';\n\t}\n\tconst toolIds = new Set(tools.map((t) => t.tool_id));\n\treturn nodeToText(doc as unknown as ProseMirrorNode, toolIds).replace(\n\t\t/\\n+$/,\n\t\t'',\n\t);\n};\n"],"names":["toolSourceLabel","source","fallback","TOOL_SOURCE_LABELS","appTypeLabel","applicationType","key","buildAgentMentionItems","tools","subAgents","appLabel","t","s","variableTokenName","actualValue","buildVariableMentionItems","variablesData","items","walk","entry","actual","configToolName","restApiToolName","restApiMentionItem","name","ToolSource","configToolMentionItem","buildCustomToolMentionItems","configTools","restApiTools","escapeHtml","raw","escapeAttr","mentionSpanHtml","id","label","kind","buildMentionHtml","buildTokenLookup","mentionItems","byToken","item","meta","REFERENCE_TOKEN","inlineToHtml","segment","out","lastIndex","match","instructionsToEditorHtml","text","para","resolveMentionToken","toolIds","nodeToText","node","ordered","inner","child","editorDocToInstructions","doc"],"mappings":";AA6CO,MAAMA,IAAkB,CAC9BC,GACAC,IAAW,eAEND,IA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