@skaile/forge-layer-chat 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +170 -1
- package/app/app.config.ts +8 -0
- package/app/components/AssistantToggle.vue +35 -0
- package/app/components/ChatAssistantPanel.vue +203 -0
- package/app/components/ChatDrawer.vue +262 -0
- package/app/components/ChatThreadRenameModal.vue +83 -0
- package/app/composables/useAssistant.ts +32 -0
- package/app/composables/useAssistantBackends.ts +35 -0
- package/app/middleware/chat-links.global.ts +12 -0
- package/app/plugins/chat.ts +73 -0
- package/app/utils/chatMarkdown.ts +49 -0
- package/nuxt.config.ts +14 -0
- package/package.json +48 -5
- package/server/api/chat.post.ts +8 -0
- package/server/plugins/chat.ts +11 -0
- package/server/utils/assistant-settings.ts +27 -0
- package/server/utils/chat-actions.ts +147 -0
- package/server/utils/chat-assistant.ts +189 -0
- package/server/utils/chat-threads.ts +149 -0
- package/server/utils/tool-schema.ts +56 -0
- package/shared/chat-context.ts +40 -0
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import type { DropdownMenuItem } from '@nuxt/ui'
|
|
3
|
+
import { provideDashboardContext, useDashboard } from '@nuxt/ui/utils/dashboard'
|
|
4
|
+
import { createReusableTemplate, useStorage } from '@vueuse/core'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The assistant on every page: a resizable right-hand `UDashboardSidebar`
|
|
8
|
+
* (mounted once by the layout from `shell.drawers`), a slideover below `lg`.
|
|
9
|
+
* Header: thread picker (switch, rename, delete), New conversation, and
|
|
10
|
+
* `AssistantToggle` as the close button in the top-right corner, where the
|
|
11
|
+
* header's toggle sat before the drawer opened. Body: `ChatAssistantPanel`.
|
|
12
|
+
* ⌘J, the palette and `AssistantToggle` open and close it through
|
|
13
|
+
* `useAssistant().open`.
|
|
14
|
+
*
|
|
15
|
+
* Width and open state live in localStorage under
|
|
16
|
+
* `<group storage key>-sidebar-assistant` (`{ size, collapsed }`, the format
|
|
17
|
+
* `UDashboardSidebar` uses): the sidebar stores `size`, this component stores
|
|
18
|
+
* `collapsed` (= closed) and applies it after mount, so the server's markup
|
|
19
|
+
* (drawer closed) always hydrates. The open state is desktop-only: on phones
|
|
20
|
+
* the drawer starts closed and opening or closing the slideover leaves the
|
|
21
|
+
* stored desktop state alone.
|
|
22
|
+
*/
|
|
23
|
+
const DEFAULT_SIZE = 28
|
|
24
|
+
|
|
25
|
+
const { open, thread, toggle } = useAssistant()
|
|
26
|
+
const client = useChatClient()
|
|
27
|
+
const toast = useToast()
|
|
28
|
+
const route = useRoute()
|
|
29
|
+
const router = useRouter()
|
|
30
|
+
const { confirm } = useConfirm()
|
|
31
|
+
const { formatDateTime } = useDates()
|
|
32
|
+
|
|
33
|
+
defineShortcuts({ meta_j: toggle })
|
|
34
|
+
|
|
35
|
+
// Nuxt UI wires every `UDashboardSidebar` of a group to the group's collapse and
|
|
36
|
+
// mobile-toggle state, so the header's sidebar buttons would also flip this drawer
|
|
37
|
+
// and it would overwrite their state. The drawer gets a context of its own; it is
|
|
38
|
+
// not `collapsible`, so the group-wide collapse hook leaves it alone.
|
|
39
|
+
// The context shape is Nuxt UI internal, pinned at @nuxt/ui 4.12.0: recheck this
|
|
40
|
+
// override on every @nuxt/ui upgrade.
|
|
41
|
+
const group = useDashboard()
|
|
42
|
+
provideDashboardContext({
|
|
43
|
+
...group,
|
|
44
|
+
sidebarOpen: ref(false),
|
|
45
|
+
sidebarCollapsed: ref(false),
|
|
46
|
+
toggleSidebar: toggle,
|
|
47
|
+
collapseSidebar: (collapsed: boolean) => {
|
|
48
|
+
open.value = !collapsed
|
|
49
|
+
},
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
// VueUse's storage ref, as `UDashboardSidebar` uses for the size: storage events keep both copies in sync.
|
|
53
|
+
const stored = useStorage(
|
|
54
|
+
`${group.storageKey ?? 'dashboard'}-sidebar-assistant`,
|
|
55
|
+
{ size: DEFAULT_SIZE, collapsed: true },
|
|
56
|
+
undefined,
|
|
57
|
+
{ initOnMounted: true, mergeDefaults: true },
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
/** At `lg` the drawer sits beside the page; below it opens as a slideover. */
|
|
61
|
+
const desktop = useMediaQuery('(min-width: 1024px)')
|
|
62
|
+
|
|
63
|
+
/** The slideover only closes itself (overlay, Escape, navigation); opening is `open`'s job. */
|
|
64
|
+
function onMenuOpen(value: boolean) {
|
|
65
|
+
if (!value) open.value = false
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const loadThreadList = () => client.call('chat.threads.list', {})
|
|
69
|
+
type ThreadRow = Awaited<ReturnType<typeof loadThreadList>>['items'][number]
|
|
70
|
+
const threads = ref<ThreadRow[]>([])
|
|
71
|
+
|
|
72
|
+
async function loadThreads() {
|
|
73
|
+
try {
|
|
74
|
+
threads.value = (await loadThreadList()).items
|
|
75
|
+
} catch (error) {
|
|
76
|
+
toast.add({ title: 'Could not load your conversations', description: actionErrorMessage(error), color: 'error' })
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const current = computed(() => threads.value.find(row => row.id === thread.value?.id) ?? null)
|
|
81
|
+
|
|
82
|
+
function select(row: ThreadRow) {
|
|
83
|
+
thread.value = { id: row.id, transport: row.transport }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function startOver() {
|
|
87
|
+
thread.value = null
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const renameOpen = ref(false)
|
|
91
|
+
|
|
92
|
+
async function remove() {
|
|
93
|
+
const row = current.value
|
|
94
|
+
if (!row) return
|
|
95
|
+
const accepted = await confirm({
|
|
96
|
+
title: 'Delete this conversation?',
|
|
97
|
+
description: `“${row.title}” and its messages are removed for good.`,
|
|
98
|
+
confirmLabel: 'Delete conversation',
|
|
99
|
+
})
|
|
100
|
+
if (!accepted) return
|
|
101
|
+
try {
|
|
102
|
+
await client.call('chat.threads.delete', { id: row.id })
|
|
103
|
+
await loadThreads()
|
|
104
|
+
if (thread.value?.id === row.id) {
|
|
105
|
+
const newest = threads.value[0]
|
|
106
|
+
thread.value = newest ? { id: newest.id, transport: newest.transport } : null
|
|
107
|
+
}
|
|
108
|
+
toast.add({ title: 'Conversation deleted', description: row.title, color: 'success' })
|
|
109
|
+
} catch (error) {
|
|
110
|
+
toast.add({ title: 'Could not delete the conversation', description: actionErrorMessage(error), color: 'error' })
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const threadMenu = computed<DropdownMenuItem[][]>(() => {
|
|
115
|
+
const rows: DropdownMenuItem[] = threads.value.map(row => ({
|
|
116
|
+
label: row.title,
|
|
117
|
+
description:
|
|
118
|
+
row.transport === 'model'
|
|
119
|
+
? formatDateTime(String(row.updatedAt))
|
|
120
|
+
: `${formatDateTime(String(row.updatedAt))} · ${row.transport}`,
|
|
121
|
+
icon: row.id === thread.value?.id ? 'i-lucide-check' : 'i-lucide-message-square',
|
|
122
|
+
onSelect: () => select(row),
|
|
123
|
+
}))
|
|
124
|
+
const menu: DropdownMenuItem[][] = [rows.length ? rows : [{ label: 'No conversations yet', disabled: true }]]
|
|
125
|
+
if (current.value) {
|
|
126
|
+
menu.push([
|
|
127
|
+
{
|
|
128
|
+
label: 'Rename conversation',
|
|
129
|
+
icon: 'i-lucide-pencil',
|
|
130
|
+
onSelect: () => {
|
|
131
|
+
renameOpen.value = true
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
{ label: 'Delete conversation', icon: 'i-lucide-trash-2', color: 'error', onSelect: () => void remove() },
|
|
135
|
+
])
|
|
136
|
+
}
|
|
137
|
+
return menu
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Old `/chat` links arrive as `?assistant=<thread id>` (`middleware/chat-links.global.ts`):
|
|
142
|
+
* open the drawer on that thread (or as it was, for a bare `/chat`) and drop the query.
|
|
143
|
+
*/
|
|
144
|
+
async function openFromLink() {
|
|
145
|
+
if (!('assistant' in route.query)) return
|
|
146
|
+
const id = typeof route.query.assistant === 'string' ? route.query.assistant : ''
|
|
147
|
+
const query = { ...route.query }
|
|
148
|
+
delete query.assistant
|
|
149
|
+
await router.replace({ query })
|
|
150
|
+
open.value = true
|
|
151
|
+
if (!id) return
|
|
152
|
+
await loadThreads()
|
|
153
|
+
const row = threads.value.find(t => t.id === id)
|
|
154
|
+
if (row) select(row)
|
|
155
|
+
else
|
|
156
|
+
toast.add({
|
|
157
|
+
title: 'Conversation not found',
|
|
158
|
+
description: 'It was deleted or belongs to someone else.',
|
|
159
|
+
color: 'warning',
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Runs after `useStorage` read the stored state (its own mounted hook comes first).
|
|
164
|
+
onMounted(() => {
|
|
165
|
+
open.value = desktop.value && !stored.value.collapsed
|
|
166
|
+
void openFromLink()
|
|
167
|
+
})
|
|
168
|
+
watch(open, value => {
|
|
169
|
+
if (desktop.value) stored.value.collapsed = !value
|
|
170
|
+
if (value) void loadThreads()
|
|
171
|
+
})
|
|
172
|
+
watch(
|
|
173
|
+
() => route.query.assistant,
|
|
174
|
+
() => void openFromLink(),
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
const [DefineHeader, ReuseHeader] = createReusableTemplate()
|
|
178
|
+
const [DefineBody, ReuseBody] = createReusableTemplate()
|
|
179
|
+
</script>
|
|
180
|
+
|
|
181
|
+
<template>
|
|
182
|
+
<DefineHeader>
|
|
183
|
+
<UDropdownMenu
|
|
184
|
+
:items="threadMenu"
|
|
185
|
+
:content="{ align: 'start' }"
|
|
186
|
+
:ui="{ content: 'w-72' }"
|
|
187
|
+
>
|
|
188
|
+
<UButton
|
|
189
|
+
:label="current?.title ?? 'New conversation'"
|
|
190
|
+
trailing-icon="i-lucide-chevron-down"
|
|
191
|
+
color="neutral"
|
|
192
|
+
variant="ghost"
|
|
193
|
+
class="min-w-0"
|
|
194
|
+
:ui="{ label: 'truncate' }"
|
|
195
|
+
data-testid="chat-thread-picker"
|
|
196
|
+
/>
|
|
197
|
+
</UDropdownMenu>
|
|
198
|
+
<div class="ms-auto flex shrink-0 items-center gap-1">
|
|
199
|
+
<UTooltip text="New conversation">
|
|
200
|
+
<UButton
|
|
201
|
+
icon="i-lucide-square-pen"
|
|
202
|
+
color="neutral"
|
|
203
|
+
variant="ghost"
|
|
204
|
+
aria-label="New conversation"
|
|
205
|
+
data-testid="chat-new-conversation"
|
|
206
|
+
@click="startOver"
|
|
207
|
+
/>
|
|
208
|
+
</UTooltip>
|
|
209
|
+
<AssistantToggle in-drawer />
|
|
210
|
+
</div>
|
|
211
|
+
</DefineHeader>
|
|
212
|
+
|
|
213
|
+
<DefineBody>
|
|
214
|
+
<ClientOnly>
|
|
215
|
+
<ChatAssistantPanel
|
|
216
|
+
v-model:thread="thread"
|
|
217
|
+
@update:thread="loadThreads"
|
|
218
|
+
@turn-end="loadThreads"
|
|
219
|
+
/>
|
|
220
|
+
</ClientOnly>
|
|
221
|
+
</DefineBody>
|
|
222
|
+
|
|
223
|
+
<UDashboardSidebar
|
|
224
|
+
v-if="open"
|
|
225
|
+
id="assistant"
|
|
226
|
+
side="right"
|
|
227
|
+
resizable
|
|
228
|
+
:default-size="DEFAULT_SIZE"
|
|
229
|
+
:min-size="20"
|
|
230
|
+
:max-size="48"
|
|
231
|
+
:open="open && !desktop"
|
|
232
|
+
:auto-close="false"
|
|
233
|
+
:menu="{ side: 'right', title: 'Assistant', description: 'Acts in this app with your rights' }"
|
|
234
|
+
:ui="{ header: 'border-b border-default lg:pe-6', body: 'min-h-0 gap-0 overflow-hidden p-0' }"
|
|
235
|
+
class="border-s border-default"
|
|
236
|
+
data-testid="chat-drawer"
|
|
237
|
+
@update:open="onMenuOpen"
|
|
238
|
+
>
|
|
239
|
+
<template #header>
|
|
240
|
+
<ReuseHeader v-if="desktop" />
|
|
241
|
+
</template>
|
|
242
|
+
|
|
243
|
+
<ReuseBody v-if="desktop" />
|
|
244
|
+
|
|
245
|
+
<template #content>
|
|
246
|
+
<div class="flex min-h-0 flex-1 flex-col">
|
|
247
|
+
<div class="flex h-(--ui-header-height) shrink-0 items-center gap-1.5 border-b border-default px-4 sm:pe-6">
|
|
248
|
+
<ReuseHeader />
|
|
249
|
+
</div>
|
|
250
|
+
<div class="flex min-h-0 flex-1 flex-col">
|
|
251
|
+
<ReuseBody />
|
|
252
|
+
</div>
|
|
253
|
+
</div>
|
|
254
|
+
</template>
|
|
255
|
+
</UDashboardSidebar>
|
|
256
|
+
|
|
257
|
+
<ChatThreadRenameModal
|
|
258
|
+
v-model:open="renameOpen"
|
|
259
|
+
:thread="current"
|
|
260
|
+
@renamed="loadThreads"
|
|
261
|
+
/>
|
|
262
|
+
</template>
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import type { FormSubmitEvent } from '@nuxt/ui'
|
|
3
|
+
import * as z from 'zod'
|
|
4
|
+
|
|
5
|
+
/** Renames one of the person's conversations (the assistant drawer's thread picker). */
|
|
6
|
+
const props = defineProps<{ thread: { id: string; title: string } | null }>()
|
|
7
|
+
const open = defineModel<boolean>('open', { default: false })
|
|
8
|
+
const emit = defineEmits<{ renamed: [] }>()
|
|
9
|
+
|
|
10
|
+
const client = useChatClient()
|
|
11
|
+
const toast = useToast()
|
|
12
|
+
const form = useTemplateRef('form')
|
|
13
|
+
|
|
14
|
+
// The server's limits (`chat.threads.rename` validates again).
|
|
15
|
+
const schema = z.object({ title: z.string().trim().min(1).max(200) })
|
|
16
|
+
type State = z.input<typeof schema>
|
|
17
|
+
|
|
18
|
+
const LABELS = { title: 'Title' } satisfies Record<keyof State, string>
|
|
19
|
+
|
|
20
|
+
const state = reactive<State>({ title: '' })
|
|
21
|
+
const saving = ref(false)
|
|
22
|
+
const { dirty, markClean } = useFormDirty(state)
|
|
23
|
+
const missing = computed(() => missingFields(schema, state, LABELS))
|
|
24
|
+
|
|
25
|
+
watch(open, isOpen => {
|
|
26
|
+
if (!isOpen) return
|
|
27
|
+
state.title = props.thread?.title ?? ''
|
|
28
|
+
markClean()
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
async function onSubmit(event: FormSubmitEvent<z.output<typeof schema>>) {
|
|
32
|
+
const thread = props.thread
|
|
33
|
+
if (!thread) return
|
|
34
|
+
saving.value = true
|
|
35
|
+
try {
|
|
36
|
+
await client.call('chat.threads.rename', { id: thread.id, title: event.data.title })
|
|
37
|
+
emit('renamed')
|
|
38
|
+
open.value = false
|
|
39
|
+
} catch (error) {
|
|
40
|
+
applyServerError(error, {
|
|
41
|
+
form: form.value,
|
|
42
|
+
fields: Object.keys(LABELS),
|
|
43
|
+
toast,
|
|
44
|
+
title: 'Could not rename the conversation',
|
|
45
|
+
})
|
|
46
|
+
} finally {
|
|
47
|
+
saving.value = false
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
</script>
|
|
51
|
+
|
|
52
|
+
<template>
|
|
53
|
+
<FormModal
|
|
54
|
+
v-model:open="open"
|
|
55
|
+
title="Rename conversation"
|
|
56
|
+
form-id="chat-rename-form"
|
|
57
|
+
:saving="saving"
|
|
58
|
+
:dirty="dirty"
|
|
59
|
+
:missing="missing"
|
|
60
|
+
submit-testid="chat-rename-submit"
|
|
61
|
+
>
|
|
62
|
+
<UForm
|
|
63
|
+
id="chat-rename-form"
|
|
64
|
+
ref="form"
|
|
65
|
+
:schema="schema"
|
|
66
|
+
:state="state"
|
|
67
|
+
@submit="onSubmit"
|
|
68
|
+
>
|
|
69
|
+
<UFormField
|
|
70
|
+
name="title"
|
|
71
|
+
:label="LABELS.title"
|
|
72
|
+
required
|
|
73
|
+
>
|
|
74
|
+
<UInput
|
|
75
|
+
v-model="state.title"
|
|
76
|
+
class="w-full"
|
|
77
|
+
autofocus
|
|
78
|
+
:maxlength="200"
|
|
79
|
+
/>
|
|
80
|
+
</UFormField>
|
|
81
|
+
</UForm>
|
|
82
|
+
</FormModal>
|
|
83
|
+
</template>
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ChatActions } from '../../server/utils/chat-actions'
|
|
2
|
+
|
|
3
|
+
/** The typed actions client for the chat catalogue (`chat.threads.*`). */
|
|
4
|
+
export function useChatClient() {
|
|
5
|
+
return useActions<ChatActions>()
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** A thread as the chat panel needs it: which backend (`transport`) answers in it. */
|
|
9
|
+
export interface PanelThread {
|
|
10
|
+
id: string
|
|
11
|
+
transport: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Shell-wide assistant state: whether the right-hand drawer (`ChatDrawer`) is
|
|
16
|
+
* open and which thread it shows. ⌘J, the palette entry "Ask the assistant"
|
|
17
|
+
* and the header toggle (`AssistantToggle`) all flip `open`. `ChatDrawer`
|
|
18
|
+
* persists `open` with the drawer's width in localStorage
|
|
19
|
+
* (`skaile-app-sidebar-assistant`) and restores it after mount, so the server
|
|
20
|
+
* always renders the drawer closed. The thread lasts for the browser session.
|
|
21
|
+
*/
|
|
22
|
+
export function useAssistant() {
|
|
23
|
+
const open = useState('chat:assistant-open', () => false)
|
|
24
|
+
const thread = useState<PanelThread | null>('chat:assistant-thread', () => null)
|
|
25
|
+
return {
|
|
26
|
+
open,
|
|
27
|
+
thread,
|
|
28
|
+
toggle: () => {
|
|
29
|
+
open.value = !open.value
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ChatTransport } from '@skaile/forge-chat'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* One way the chat panel can answer: the in-app model (`model`, this layer) or
|
|
5
|
+
* another layer's assistant (e.g. `workspace`, the workspace-agent layer). The
|
|
6
|
+
* panel shows a switcher only when more than one backend is registered and
|
|
7
|
+
* available. The backend id is stored as the thread's `transport`.
|
|
8
|
+
*/
|
|
9
|
+
export type AssistantBackend = {
|
|
10
|
+
id: string
|
|
11
|
+
label: string
|
|
12
|
+
icon?: string
|
|
13
|
+
/** Whether this backend can answer right now; `reason` is shown when it cannot. */
|
|
14
|
+
status: () => Promise<{ available: boolean; reason?: string }>
|
|
15
|
+
/** A transport bound to one persisted thread; `history()` restores it. */
|
|
16
|
+
createTransport: (ctx: { threadId: string }) => ChatTransport
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Module scope on purpose: backends are registered by client plugins (the same
|
|
20
|
+
// set on every page load) and hold functions, which `useState` cannot carry.
|
|
21
|
+
const registry = shallowReactive(new Map<string, AssistantBackend>())
|
|
22
|
+
|
|
23
|
+
/** Adds or replaces the backend with `backend.id`. Call from a layer's `app/plugins/*.ts`. */
|
|
24
|
+
export function registerAssistantBackend(backend: AssistantBackend): void {
|
|
25
|
+
registry.set(backend.id, backend)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function useAssistantBackends() {
|
|
29
|
+
const backends = computed(() => [...registry.values()])
|
|
30
|
+
return {
|
|
31
|
+
/** Every registered backend, in registration order. */
|
|
32
|
+
backends,
|
|
33
|
+
find: (id: string): AssistantBackend | undefined => registry.get(id),
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/chat` and `/chat/<id>` were the assistant's full page; the assistant now
|
|
3
|
+
* lives in the right-hand drawer. Old links land on `/` with the drawer open
|
|
4
|
+
* on that thread: `?assistant=<id>` (empty for a bare `/chat`), applied and
|
|
5
|
+
* removed by `ChatDrawer`. A query rather than state, because on a first page
|
|
6
|
+
* load this redirect is an HTTP 302 and state set here would not survive it.
|
|
7
|
+
*/
|
|
8
|
+
export default defineNuxtRouteMiddleware(to => {
|
|
9
|
+
const match = /^\/chat(?:\/([^/]+))?\/?$/.exec(to.path)
|
|
10
|
+
if (!match) return
|
|
11
|
+
return navigateTo({ path: '/', query: { assistant: match[1] ?? '' } }, { replace: true })
|
|
12
|
+
})
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { ChatStreamEvent, ChatTransport } from '@skaile/forge-chat'
|
|
2
|
+
import { createAiSdkTransport } from '@skaile/forge-chat/transports/ai-sdk'
|
|
3
|
+
// From `#components`, not by path, so an app's own `AssistantToggle` or `ChatDrawer` (same name) replaces the layer's.
|
|
4
|
+
import { AssistantToggle, ChatDrawer } from '#components'
|
|
5
|
+
import { chatContextFor } from '../../shared/chat-context'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Wires the chat layer into the shell: the built-in `model` backend (AI SDK
|
|
9
|
+
* transport to `/api/chat`, history from the stored thread), the ⌘K entry,
|
|
10
|
+
* the header toggle and the right-hand drawer (`app-shell:extend`). ⌘J lives
|
|
11
|
+
* in `ChatDrawer`.
|
|
12
|
+
*/
|
|
13
|
+
export default defineNuxtPlugin(nuxtApp => {
|
|
14
|
+
const router = useRouter()
|
|
15
|
+
const client = useChatClient()
|
|
16
|
+
const core = useActions()
|
|
17
|
+
const assistant = useAssistant()
|
|
18
|
+
const endpoint = `${useRuntimeConfig().app.baseURL.replace(/\/$/, '')}/api/chat`
|
|
19
|
+
|
|
20
|
+
registerAssistantBackend({
|
|
21
|
+
id: 'model',
|
|
22
|
+
label: 'In-app assistant',
|
|
23
|
+
icon: 'i-lucide-sparkles',
|
|
24
|
+
status: async () => {
|
|
25
|
+
const { roles } = await core.call('ai.status', {})
|
|
26
|
+
const assistantRole = roles.find(role => role.id === 'assistant')
|
|
27
|
+
return assistantRole?.available
|
|
28
|
+
? { available: true }
|
|
29
|
+
: { available: false, reason: assistantRole?.reason ?? undefined }
|
|
30
|
+
},
|
|
31
|
+
createTransport: ({ threadId }): ChatTransport => {
|
|
32
|
+
const live = createAiSdkTransport({
|
|
33
|
+
endpoint,
|
|
34
|
+
// Sent with every turn: the thread to store it in and where the person is right now.
|
|
35
|
+
body: () => ({ threadId, context: chatContextFor(router.currentRoute.value.path) }),
|
|
36
|
+
})
|
|
37
|
+
return {
|
|
38
|
+
send: (input, snapshot, signal) => live.send(input, snapshot, signal),
|
|
39
|
+
subscribe: listener => live.subscribe(listener),
|
|
40
|
+
abort: live.abort && (() => live.abort!()),
|
|
41
|
+
dispose: live.dispose && (() => live.dispose!()),
|
|
42
|
+
history: async () => (await client.call('chat.threads.get', { id: threadId })).events as ChatStreamEvent[],
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
nuxtApp.hook('app-shell:extend', shell => {
|
|
48
|
+
shell.commands.push({
|
|
49
|
+
id: 'assistant',
|
|
50
|
+
label: 'Assistant',
|
|
51
|
+
items: [
|
|
52
|
+
{
|
|
53
|
+
id: 'ask-assistant',
|
|
54
|
+
label: 'Ask the assistant',
|
|
55
|
+
icon: 'i-lucide-sparkles',
|
|
56
|
+
kbds: ['meta', 'J'],
|
|
57
|
+
onSelect: () => {
|
|
58
|
+
assistant.open.value = true
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
],
|
|
62
|
+
})
|
|
63
|
+
shell.header.push(AssistantToggle)
|
|
64
|
+
shell.drawers.push(ChatDrawer)
|
|
65
|
+
shell.settingsSections.push({
|
|
66
|
+
route: '/settings/agents',
|
|
67
|
+
title: 'In-app assistant',
|
|
68
|
+
order: 10,
|
|
69
|
+
role: 'assistant',
|
|
70
|
+
scope: 'assistant',
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
})
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Marked, Tokenizer } from 'marked'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Markdown of an assistant answer as HTML for the chat panel (forge-chat sets
|
|
5
|
+
* it with `innerHTML`).
|
|
6
|
+
*
|
|
7
|
+
* The model reads data other people wrote (task descriptions, notes), so its
|
|
8
|
+
* text is untrusted. `marked` filters nothing by itself, hence: raw HTML is
|
|
9
|
+
* shown as text, images appear only as their alt text (no request to foreign
|
|
10
|
+
* hosts), and links keep only `http(s):`, `mailto:`, in-app paths and anchors.
|
|
11
|
+
*
|
|
12
|
+
* `marked`'s lexer switches into a "raw block" after an inline tag such as
|
|
13
|
+
* `<pre>`, `<code>` or `<script>`; text after it would stay unescaped
|
|
14
|
+
* (`x <pre> <img src=x onerror=…>`). The raw-block state is reset after every
|
|
15
|
+
* tag, so all text goes through the escaping renderer.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
function escapeHtml(text: string): string {
|
|
19
|
+
return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const ALLOWED_HREF = /^(https?:|mailto:|\/(?!\/)|#)/i
|
|
23
|
+
/** Targets outside the app open next to it; paths and anchors stay in the window. */
|
|
24
|
+
const EXTERNAL_HREF = /^(https?:|mailto:)/i
|
|
25
|
+
|
|
26
|
+
const markdown = new Marked({
|
|
27
|
+
tokenizer: {
|
|
28
|
+
tag(src) {
|
|
29
|
+
const token = Tokenizer.prototype.tag.call(this, src)
|
|
30
|
+
this.lexer.state.inRawBlock = false
|
|
31
|
+
return token
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
renderer: {
|
|
35
|
+
html: ({ text }) => escapeHtml(text),
|
|
36
|
+
image: ({ text }) => escapeHtml(text),
|
|
37
|
+
link(token) {
|
|
38
|
+
const href = token.href.trim()
|
|
39
|
+
if (!ALLOWED_HREF.test(href)) return this.parser.parseInline(token.tokens)
|
|
40
|
+
const title = token.title ? ` title="${escapeHtml(token.title)}"` : ''
|
|
41
|
+
const target = EXTERNAL_HREF.test(href) ? ' target="_blank" rel="noopener noreferrer"' : ''
|
|
42
|
+
return `<a href="${escapeHtml(href)}"${title}${target}>${this.parser.parseInline(token.tokens)}</a>`
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
export function chatMarkdown(text: string): string {
|
|
48
|
+
return markdown.parse(text, { async: false })
|
|
49
|
+
}
|
package/nuxt.config.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { defineNuxtConfig } from 'nuxt/config'
|
|
2
|
+
|
|
3
|
+
// Layer: `extends: ['@skaile/forge-layer-chat']` in an app built on forge-template-app.
|
|
4
|
+
//
|
|
5
|
+
// The forge-chat assistant (right-hand drawer on every page) answering with the
|
|
6
|
+
// app's `llm` actions as tools, persisted threads, the `assistant` settings
|
|
7
|
+
// scope and model role. It uses the host's core (host contract in README.md).
|
|
8
|
+
// Remove the `extends` entry to drop it.
|
|
9
|
+
export default defineNuxtConfig({
|
|
10
|
+
// After @nuxt/ui (root modules come first): it renders Nuxt UI primitives from `dist`.
|
|
11
|
+
modules: ['@skaile/forge-chat/nuxt'],
|
|
12
|
+
// Pre-bundled up front: otherwise Vite discovers it on the first chat render and reloads the page.
|
|
13
|
+
vite: { optimizeDeps: { include: ['marked'] } },
|
|
14
|
+
})
|
package/package.json
CHANGED
|
@@ -1,9 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skaile/forge-layer-chat",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Nuxt layer for apps built on forge-template-app: the in-app assistant, a forge-chat drawer that answers with the app's own llm actions as tools, persisted threads, the assistant model role and settings.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./nuxt.config.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"nuxt.config.ts",
|
|
9
|
+
"app",
|
|
10
|
+
"server",
|
|
11
|
+
"shared",
|
|
12
|
+
"README.md",
|
|
13
|
+
"CHANGELOG.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/skaile-ai/forge.git",
|
|
19
|
+
"directory": "packages/layer-chat"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"nuxt",
|
|
23
|
+
"nuxt-layer",
|
|
24
|
+
"forge-chat",
|
|
25
|
+
"ai-sdk",
|
|
26
|
+
"skaile"
|
|
27
|
+
],
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
5
31
|
"license": "MIT",
|
|
6
|
-
"
|
|
7
|
-
|
|
8
|
-
|
|
32
|
+
"scripts": {
|
|
33
|
+
"check": "bun ../../scripts/check-package.ts"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@nuxt/ui": "^4.11.1",
|
|
37
|
+
"@skaile/forge-app-actions": "^0.6.0",
|
|
38
|
+
"@skaile/forge-chat": "^0.6.0",
|
|
39
|
+
"@skaile/forge-settings": "^2.0.1",
|
|
40
|
+
"@vueuse/core": "^15.0.0",
|
|
41
|
+
"ai": "^7.0.0",
|
|
42
|
+
"drizzle-orm": "^0.45.0",
|
|
43
|
+
"h3": "^1.15.0",
|
|
44
|
+
"marked": "^15.0.0",
|
|
45
|
+
"nuxt": "^4.0.0",
|
|
46
|
+
"vue": "^3.5.0",
|
|
47
|
+
"zod": "^4.0.0"
|
|
48
|
+
},
|
|
49
|
+
"engines": {
|
|
50
|
+
"node": ">=20"
|
|
51
|
+
}
|
|
9
52
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { handleChatRequest } from '../utils/chat-assistant'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The in-app assistant (forge-chat AI SDK transport): `{ threadId, context, messages, input }`
|
|
5
|
+
* → SSE. Tools are the catalogue's `llm` actions with the signed-in person's rights;
|
|
6
|
+
* 503 `{ error: 'assistant_not_configured' }` without a model. See `handleChatRequest`.
|
|
7
|
+
*/
|
|
8
|
+
export default defineEventHandler(event => handleChatRequest(event))
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { registerActions } from '~~/server/utils/actions/registry'
|
|
2
|
+
import { registerModelRole } from '~~/server/utils/ai/roles'
|
|
3
|
+
import { chatActions } from '../utils/chat-actions'
|
|
4
|
+
import { ASSISTANT_ROLE } from '../utils/chat-assistant'
|
|
5
|
+
// Importing the scope declares it, so `settings.get`/`settings.update` know "assistant".
|
|
6
|
+
import '../utils/assistant-settings'
|
|
7
|
+
|
|
8
|
+
export default defineNitroPlugin(() => {
|
|
9
|
+
registerActions(chatActions)
|
|
10
|
+
registerModelRole(ASSISTANT_ROLE)
|
|
11
|
+
})
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import * as z from 'zod'
|
|
2
|
+
import { defineSettingsScope } from '~~/server/utils/settings'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The `assistant` settings scope (`settings.get`/`settings.update` with
|
|
6
|
+
* `scope: "assistant"`): how the in-app assistant behaves. Which model answers
|
|
7
|
+
* is the `assistant` model role (Settings › Harness, `ai` scope), not a field here.
|
|
8
|
+
*/
|
|
9
|
+
export const assistantSettings = defineSettingsScope(
|
|
10
|
+
'assistant',
|
|
11
|
+
z
|
|
12
|
+
.object({
|
|
13
|
+
systemPromptAddendum: z
|
|
14
|
+
.string()
|
|
15
|
+
.max(4000)
|
|
16
|
+
.describe(
|
|
17
|
+
"Extra instructions appended to the assistant's system prompt, e.g. house style or domain vocabulary",
|
|
18
|
+
),
|
|
19
|
+
maxSteps: z.number().int().min(1).max(20).describe('How many model steps (tool call rounds) one answer may take'),
|
|
20
|
+
})
|
|
21
|
+
.strict(),
|
|
22
|
+
{
|
|
23
|
+
systemPromptAddendum: '',
|
|
24
|
+
maxSteps: 6,
|
|
25
|
+
},
|
|
26
|
+
{ label: 'AI assistant', description: 'Extra instructions and tool-loop limit of the in-app assistant' },
|
|
27
|
+
)
|