@standardagents/cli 0.41.21 → 0.41.26
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/chat/next/app/page.tsx +3 -4
- package/chat/package.json +9 -3
- package/chat/src/App.tsx +2 -1
- package/chat/src/components/Chat.tsx +17 -2
- package/chat/src/components/EmptyState.tsx +52 -86
- package/chat/src/components/Login.tsx +56 -3
- package/chat/src/components/Markdown.tsx +53 -26
- package/chat/src/components/MessageInput.tsx +11 -11
- package/chat/src/components/MessageList.tsx +245 -322
- package/chat/src/components/Sidebar.tsx +12 -8
- package/chat/src/hooks/useAuth.tsx +104 -54
- package/chat/src/hooks/useThreads.ts +57 -64
- package/chat/src/lib/api.ts +53 -0
- package/chat/src/lib/streamingMarkdown.test.ts +34 -0
- package/chat/src/lib/streamingMarkdown.ts +59 -0
- package/chat/vite/main.tsx +5 -6
- package/chat/vite/vite.config.ts +35 -20
- package/dist/index.js +48 -13
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/chat/src/components/AgentSelector.tsx +0 -102
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use client'
|
|
2
2
|
|
|
3
3
|
import { useState } from 'react'
|
|
4
|
-
import { type Thread,
|
|
4
|
+
import { type Thread, getThreadName } from '../hooks/useThreads'
|
|
5
5
|
import { LogoMark } from './Logo'
|
|
6
6
|
import { useTheme } from '../hooks/useTheme'
|
|
7
7
|
import { useAuth } from '../hooks/useAuth'
|
|
@@ -176,21 +176,25 @@ export function Sidebar({
|
|
|
176
176
|
<div className="flex items-center gap-3 px-3 py-2.5">
|
|
177
177
|
<div className="flex-1 min-w-0">
|
|
178
178
|
{(() => {
|
|
179
|
-
const
|
|
179
|
+
const name = getThreadName(thread)
|
|
180
180
|
const agentName = thread.agent?.title || thread.agent?.name || 'Agent'
|
|
181
|
+
const preview = name ? null : thread.last_message_preview
|
|
181
182
|
return (
|
|
182
183
|
<>
|
|
183
184
|
<p className={`text-sm truncate ${
|
|
184
185
|
thread.id === currentThreadId ? 'text-[var(--text-primary)]' : 'text-[var(--text-secondary)]'
|
|
185
186
|
}`}>
|
|
186
|
-
{
|
|
187
|
+
{name || preview || agentName}
|
|
187
188
|
</p>
|
|
188
|
-
<div className="flex items-center gap-2 mt-0.5">
|
|
189
|
-
|
|
190
|
-
|
|
189
|
+
<div className="flex items-center gap-2 mt-0.5 min-w-0">
|
|
190
|
+
{thread.executing && (
|
|
191
|
+
<span className="w-1.5 h-1.5 rounded-full bg-violet-500 animate-pulse shrink-0" title="Running" />
|
|
192
|
+
)}
|
|
193
|
+
<span className="text-xs text-[var(--text-muted)] whitespace-nowrap">
|
|
194
|
+
{formatRelativeTime(thread.last_activity_at || thread.created_at)}
|
|
191
195
|
</span>
|
|
192
|
-
{
|
|
193
|
-
<span className="text-[10px] px-1.5 py-0.5 rounded bg-[var(--bg-hover)] text-[var(--text-muted)]">
|
|
196
|
+
{(name || preview) && (
|
|
197
|
+
<span className="text-[10px] px-1.5 py-0.5 rounded bg-[var(--bg-hover)] text-[var(--text-muted)] truncate">
|
|
194
198
|
{agentName}
|
|
195
199
|
</span>
|
|
196
200
|
)}
|
|
@@ -1,108 +1,158 @@
|
|
|
1
1
|
'use client'
|
|
2
2
|
|
|
3
3
|
import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'
|
|
4
|
+
import { TOKEN_KEY, apiFetch, apiUrl } from '../lib/api'
|
|
4
5
|
|
|
5
|
-
interface User {
|
|
6
|
+
export interface User {
|
|
6
7
|
id: string
|
|
7
8
|
username: string
|
|
8
9
|
role: string
|
|
10
|
+
email?: string | null
|
|
11
|
+
display_name?: string | null
|
|
12
|
+
avatar_url?: string | null
|
|
9
13
|
}
|
|
10
14
|
|
|
15
|
+
/** Response of `GET /api/auth/config` — decides which sign-in methods to offer. */
|
|
16
|
+
export interface AuthConfig {
|
|
17
|
+
hosted: boolean
|
|
18
|
+
platformConnected: boolean
|
|
19
|
+
standardAgentsLogin: boolean
|
|
20
|
+
localPassword: boolean
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type LoginResult = { success: boolean; error?: string }
|
|
24
|
+
|
|
11
25
|
interface AuthContextValue {
|
|
12
26
|
isAuthenticated: boolean
|
|
13
27
|
isLoading: boolean
|
|
14
28
|
user: User | null
|
|
15
|
-
|
|
29
|
+
config: AuthConfig | null
|
|
30
|
+
login: (username: string, password: string) => Promise<LoginResult>
|
|
31
|
+
/** Local dev: mint a session from the project's platform key (cookie only). */
|
|
32
|
+
bootstrapStandardAgents: () => Promise<LoginResult>
|
|
33
|
+
/** Hosted: full-page redirect through Standard Agents sign-in. */
|
|
34
|
+
redirectToStandardAgents: () => void
|
|
16
35
|
logout: () => void
|
|
17
36
|
}
|
|
18
37
|
|
|
19
38
|
const AuthContext = createContext<AuthContextValue | null>(null)
|
|
20
39
|
|
|
21
|
-
const
|
|
40
|
+
const DEFAULT_CONFIG: AuthConfig = {
|
|
41
|
+
hosted: false,
|
|
42
|
+
platformConnected: false,
|
|
43
|
+
standardAgentsLogin: false,
|
|
44
|
+
localPassword: true,
|
|
45
|
+
}
|
|
22
46
|
|
|
23
|
-
function
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
47
|
+
function clearStoredToken() {
|
|
48
|
+
try {
|
|
49
|
+
localStorage.removeItem(TOKEN_KEY)
|
|
50
|
+
} catch {
|
|
51
|
+
// Storage can be unavailable (private mode); the session cookie still applies.
|
|
27
52
|
}
|
|
28
|
-
return process.env.NEXT_PUBLIC_AGENTBUILDER_URL || ''
|
|
29
53
|
}
|
|
30
54
|
|
|
31
55
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
32
56
|
const [user, setUser] = useState<User | null>(null)
|
|
57
|
+
const [config, setConfig] = useState<AuthConfig | null>(null)
|
|
33
58
|
const [isLoading, setIsLoading] = useState(true)
|
|
34
59
|
|
|
35
|
-
const
|
|
60
|
+
const loadCurrentUser = useCallback(async (): Promise<boolean> => {
|
|
61
|
+
const res = await apiFetch('/api/auth/me')
|
|
62
|
+
if (!res.ok) return false
|
|
63
|
+
const data = await res.json() as { user: User }
|
|
64
|
+
setUser(data.user)
|
|
65
|
+
return true
|
|
66
|
+
}, [])
|
|
36
67
|
|
|
37
|
-
//
|
|
68
|
+
// One read at startup: the session may live in a bearer token (password
|
|
69
|
+
// login) or in the HttpOnly cookie (Standard Agents sign-in).
|
|
38
70
|
useEffect(() => {
|
|
39
|
-
|
|
40
|
-
|
|
71
|
+
let cancelled = false
|
|
72
|
+
async function init() {
|
|
73
|
+
const [configRes, signedIn] = await Promise.all([
|
|
74
|
+
fetch(apiUrl('/api/auth/config'), { credentials: 'include' })
|
|
75
|
+
.then(res => res.ok ? res.json() as Promise<Partial<AuthConfig>> : {})
|
|
76
|
+
.catch(() => ({})),
|
|
77
|
+
loadCurrentUser().catch(() => false),
|
|
78
|
+
])
|
|
79
|
+
if (cancelled) return
|
|
80
|
+
setConfig({ ...DEFAULT_CONFIG, ...configRes })
|
|
81
|
+
if (!signedIn) clearStoredToken()
|
|
41
82
|
setIsLoading(false)
|
|
42
|
-
return
|
|
43
83
|
}
|
|
84
|
+
init()
|
|
85
|
+
return () => { cancelled = true }
|
|
86
|
+
}, [loadCurrentUser])
|
|
44
87
|
|
|
45
|
-
|
|
46
|
-
fetch(`${baseUrl}/api/auth/me`, {
|
|
47
|
-
headers: { 'Authorization': `Bearer ${token}` }
|
|
48
|
-
})
|
|
49
|
-
.then(res => {
|
|
50
|
-
if (res.ok) return res.json()
|
|
51
|
-
throw new Error('Invalid token')
|
|
52
|
-
})
|
|
53
|
-
.then(data => {
|
|
54
|
-
setUser(data.user)
|
|
55
|
-
})
|
|
56
|
-
.catch(() => {
|
|
57
|
-
localStorage.removeItem(TOKEN_KEY)
|
|
58
|
-
})
|
|
59
|
-
.finally(() => {
|
|
60
|
-
setIsLoading(false)
|
|
61
|
-
})
|
|
62
|
-
}, [baseUrl])
|
|
63
|
-
|
|
64
|
-
const login = useCallback(async (username: string, password: string) => {
|
|
88
|
+
const login = useCallback(async (username: string, password: string): Promise<LoginResult> => {
|
|
65
89
|
try {
|
|
66
|
-
const res = await
|
|
90
|
+
const res = await apiFetch('/api/auth/login', {
|
|
67
91
|
method: 'POST',
|
|
68
|
-
|
|
69
|
-
body: JSON.stringify({ username, password })
|
|
92
|
+
body: JSON.stringify({ username, password }),
|
|
70
93
|
})
|
|
71
|
-
|
|
72
|
-
if (!res.ok) {
|
|
73
|
-
const data = await res.json().catch(() => ({}))
|
|
94
|
+
const data = await res.json().catch(() => ({})) as { token?: string; user?: User; error?: string }
|
|
95
|
+
if (!res.ok || !data.user) {
|
|
74
96
|
return { success: false, error: data.error || 'Invalid credentials' }
|
|
75
97
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
localStorage.setItem(TOKEN_KEY, data.token)
|
|
98
|
+
// The runtime also sets a session cookie; the token keeps bearer auth
|
|
99
|
+
// working when the chat is served from a different origin.
|
|
100
|
+
if (data.token) localStorage.setItem(TOKEN_KEY, data.token)
|
|
79
101
|
setUser(data.user)
|
|
80
102
|
return { success: true }
|
|
81
|
-
} catch
|
|
103
|
+
} catch {
|
|
82
104
|
return { success: false, error: 'Network error' }
|
|
83
105
|
}
|
|
84
|
-
}, [
|
|
106
|
+
}, [])
|
|
85
107
|
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
// Fire and forget logout request
|
|
90
|
-
fetch(`${baseUrl}/api/auth/logout`, {
|
|
108
|
+
const bootstrapStandardAgents = useCallback(async (): Promise<LoginResult> => {
|
|
109
|
+
try {
|
|
110
|
+
const res = await apiFetch('/api/auth/bootstrap', {
|
|
91
111
|
method: 'POST',
|
|
92
|
-
headers: { '
|
|
93
|
-
})
|
|
112
|
+
headers: { Accept: 'application/json' },
|
|
113
|
+
})
|
|
114
|
+
if (res.status === 204) {
|
|
115
|
+
return { success: false, error: 'Standard Agents sign-in is not available for this instance.' }
|
|
116
|
+
}
|
|
117
|
+
if (!res.ok) {
|
|
118
|
+
const data = await res.json().catch(() => ({})) as { error?: string }
|
|
119
|
+
return { success: false, error: data.error || 'Standard Agents sign-in failed.' }
|
|
120
|
+
}
|
|
121
|
+
const signedIn = await loadCurrentUser()
|
|
122
|
+
return signedIn ? { success: true } : { success: false, error: 'Standard Agents sign-in failed.' }
|
|
123
|
+
} catch {
|
|
124
|
+
return { success: false, error: 'Network error' }
|
|
94
125
|
}
|
|
95
|
-
|
|
126
|
+
}, [loadCurrentUser])
|
|
127
|
+
|
|
128
|
+
const redirectToStandardAgents = useCallback(() => {
|
|
129
|
+
const returnTo = encodeURIComponent(window.location.href)
|
|
130
|
+
window.location.href = apiUrl(`/api/auth/sa/start?return_to=${returnTo}`)
|
|
131
|
+
}, [])
|
|
132
|
+
|
|
133
|
+
const logout = useCallback(() => {
|
|
134
|
+
apiFetch('/api/auth/logout', { method: 'POST' })
|
|
135
|
+
.then(async res => {
|
|
136
|
+
if (!res.ok) return
|
|
137
|
+
const data = await res.json() as { redirect?: string }
|
|
138
|
+
// Hosted instances also end the Standard Agents session.
|
|
139
|
+
if (data.redirect) window.location.href = data.redirect
|
|
140
|
+
})
|
|
141
|
+
.catch(() => {})
|
|
142
|
+
clearStoredToken()
|
|
96
143
|
setUser(null)
|
|
97
|
-
}, [
|
|
144
|
+
}, [])
|
|
98
145
|
|
|
99
146
|
return (
|
|
100
147
|
<AuthContext.Provider value={{
|
|
101
148
|
isAuthenticated: !!user,
|
|
102
149
|
isLoading,
|
|
103
150
|
user,
|
|
151
|
+
config,
|
|
104
152
|
login,
|
|
105
|
-
|
|
153
|
+
bootstrapStandardAgents,
|
|
154
|
+
redirectToStandardAgents,
|
|
155
|
+
logout,
|
|
106
156
|
}}>
|
|
107
157
|
{children}
|
|
108
158
|
</AuthContext.Provider>
|
|
@@ -1,66 +1,78 @@
|
|
|
1
1
|
'use client'
|
|
2
2
|
|
|
3
|
-
import { useState, useEffect, useCallback,
|
|
3
|
+
import { useState, useEffect, useCallback, useRef } from 'react'
|
|
4
|
+
import { apiFetch } from '../lib/api'
|
|
4
5
|
|
|
6
|
+
/** Agent side backing (Standard Agent Specification 0.2.0). */
|
|
7
|
+
export type SideBacking = 'human' | 'prompt' | 'handler'
|
|
8
|
+
|
|
9
|
+
/** One row of `GET /api/threads`. */
|
|
5
10
|
export interface Thread {
|
|
6
11
|
id: string
|
|
7
12
|
agent_id: string
|
|
8
13
|
user_id: string | null
|
|
9
14
|
tags: string[]
|
|
15
|
+
parent?: string | null
|
|
16
|
+
terminated?: number | null
|
|
10
17
|
created_at: number
|
|
18
|
+
last_activity_at?: number | null
|
|
19
|
+
executing?: boolean
|
|
20
|
+
last_message_preview?: string | null
|
|
21
|
+
last_message_at?: number | null
|
|
11
22
|
agent: {
|
|
12
23
|
name?: string
|
|
13
24
|
title?: string
|
|
14
|
-
|
|
25
|
+
description?: string | null
|
|
26
|
+
icon?: string | null
|
|
27
|
+
side_a_backing?: SideBacking
|
|
28
|
+
side_b_backing?: SideBacking
|
|
15
29
|
}
|
|
16
30
|
}
|
|
17
31
|
|
|
18
|
-
|
|
32
|
+
/** Shape returned by `POST /api/threads`. */
|
|
33
|
+
export interface CreatedThread {
|
|
34
|
+
threadId: string
|
|
35
|
+
agent_id: string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// The builder UI titles threads from a `name:` tag; `title:` is the tag older
|
|
39
|
+
// versions of this chat wrote, still read so existing threads keep their names.
|
|
40
|
+
const NAME_TAG = 'name'
|
|
41
|
+
const LEGACY_TITLE_TAG = 'title'
|
|
42
|
+
|
|
19
43
|
export function getTagValue(tags: string[], key: string): string | undefined {
|
|
20
44
|
const tag = tags.find(t => t.startsWith(`${key}:`))
|
|
21
45
|
return tag ? tag.slice(key.length + 1) : undefined
|
|
22
46
|
}
|
|
23
47
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
return getTagValue(thread.tags, 'title') || 'Untitled'
|
|
48
|
+
export function getThreadName(thread: Thread): string | undefined {
|
|
49
|
+
return getTagValue(thread.tags, NAME_TAG) || getTagValue(thread.tags, LEGACY_TITLE_TAG)
|
|
27
50
|
}
|
|
28
51
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const baseUrl = isVite
|
|
33
|
-
? (import.meta.env.VITE_AGENTBUILDER_URL || '')
|
|
34
|
-
: (process.env.NEXT_PUBLIC_AGENTBUILDER_URL || '')
|
|
35
|
-
|
|
36
|
-
// Token is stored in localStorage by auth flow
|
|
37
|
-
const token = typeof localStorage !== 'undefined'
|
|
38
|
-
? localStorage.getItem('agentbuilder_auth_token') || ''
|
|
39
|
-
: ''
|
|
52
|
+
export function getThreadTitle(thread: Thread): string {
|
|
53
|
+
return getThreadName(thread) || thread.agent?.title || thread.agent?.name || 'Untitled'
|
|
54
|
+
}
|
|
40
55
|
|
|
41
|
-
|
|
56
|
+
export function withThreadName(tags: string[], name: string): string[] {
|
|
57
|
+
const rest = tags.filter(tag => !tag.startsWith(`${NAME_TAG}:`) && !tag.startsWith(`${LEGACY_TITLE_TAG}:`))
|
|
58
|
+
return [...rest, `${NAME_TAG}:${name}`]
|
|
42
59
|
}
|
|
43
60
|
|
|
44
61
|
export function useThreads() {
|
|
45
62
|
const [threads, setThreads] = useState<Thread[]>([])
|
|
46
63
|
const [loading, setLoading] = useState(true)
|
|
47
64
|
const [error, setError] = useState<string | null>(null)
|
|
65
|
+
const threadsRef = useRef(threads)
|
|
66
|
+
threadsRef.current = threads
|
|
48
67
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const headers = useMemo(() => {
|
|
52
|
-
const h: Record<string, string> = { 'Content-Type': 'application/json' }
|
|
53
|
-
if (token) h['Authorization'] = `Bearer ${token}`
|
|
54
|
-
return h
|
|
55
|
-
}, [token])
|
|
56
|
-
|
|
68
|
+
// Read on mount and after local mutations or run-state changes; never polled.
|
|
57
69
|
const fetchThreads = useCallback(async () => {
|
|
58
70
|
try {
|
|
59
|
-
|
|
60
|
-
const response = await fetch(`${baseUrl}/api/threads?limit=50`, { headers })
|
|
71
|
+
const response = await apiFetch('/api/threads?limit=50&sort=activity')
|
|
61
72
|
if (!response.ok) throw new Error('Failed to fetch threads')
|
|
62
|
-
const data = await response.json()
|
|
63
|
-
|
|
73
|
+
const data = await response.json() as { threads?: Thread[] }
|
|
74
|
+
// Subagent child threads are shown inside their parent conversation.
|
|
75
|
+
setThreads((data.threads || []).filter(t => !t.parent))
|
|
64
76
|
setError(null)
|
|
65
77
|
} catch (err) {
|
|
66
78
|
console.error('Failed to load threads:', err)
|
|
@@ -68,57 +80,38 @@ export function useThreads() {
|
|
|
68
80
|
} finally {
|
|
69
81
|
setLoading(false)
|
|
70
82
|
}
|
|
71
|
-
}, [
|
|
83
|
+
}, [])
|
|
72
84
|
|
|
73
85
|
useEffect(() => {
|
|
74
86
|
fetchThreads()
|
|
75
87
|
}, [fetchThreads])
|
|
76
88
|
|
|
77
89
|
const deleteThread = useCallback(async (threadId: string) => {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
})
|
|
83
|
-
if (!response.ok) throw new Error('Failed to delete thread')
|
|
84
|
-
setThreads((prev) => prev.filter((t) => t.id !== threadId))
|
|
85
|
-
} catch (err) {
|
|
86
|
-
console.error('Failed to delete thread:', err)
|
|
87
|
-
throw err
|
|
88
|
-
}
|
|
89
|
-
}, [baseUrl, headers])
|
|
90
|
+
const response = await apiFetch(`/api/threads/${threadId}`, { method: 'DELETE' })
|
|
91
|
+
if (!response.ok) throw new Error('Failed to delete thread')
|
|
92
|
+
setThreads((prev) => prev.filter((t) => t.id !== threadId))
|
|
93
|
+
}, [])
|
|
90
94
|
|
|
91
95
|
const updateThreadTitle = useCallback(async (threadId: string, title: string) => {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const tagsWithoutTitle = t.tags.filter(tag => !tag.startsWith('title:'))
|
|
97
|
-
return { ...t, tags: [...tagsWithoutTitle, `title:${title}`] }
|
|
98
|
-
}))
|
|
96
|
+
const thread = threadsRef.current.find(t => t.id === threadId)
|
|
97
|
+
if (!thread) return
|
|
98
|
+
const tags = withThreadName(thread.tags, title)
|
|
99
|
+
setThreads((prev) => prev.map((t) => t.id === threadId ? { ...t, tags } : t))
|
|
99
100
|
|
|
100
101
|
try {
|
|
101
|
-
|
|
102
|
-
const thread = threads.find(t => t.id === threadId)
|
|
103
|
-
if (!thread) return
|
|
104
|
-
|
|
105
|
-
const tagsWithoutTitle = thread.tags.filter(tag => !tag.startsWith('title:'))
|
|
106
|
-
const newTags = [...tagsWithoutTitle, `title:${title}`]
|
|
107
|
-
|
|
108
|
-
const response = await fetch(`${baseUrl}/api/threads/${threadId}`, {
|
|
102
|
+
const response = await apiFetch(`/api/threads/${threadId}`, {
|
|
109
103
|
method: 'PATCH',
|
|
110
|
-
|
|
111
|
-
body: JSON.stringify({ tags: newTags }),
|
|
104
|
+
body: JSON.stringify({ tags }),
|
|
112
105
|
})
|
|
113
106
|
if (!response.ok) {
|
|
114
107
|
console.error('Failed to update thread title:', response.status)
|
|
115
|
-
fetchThreads()
|
|
108
|
+
fetchThreads()
|
|
116
109
|
}
|
|
117
110
|
} catch (err) {
|
|
118
111
|
console.error('Failed to update thread:', err)
|
|
119
|
-
fetchThreads()
|
|
112
|
+
fetchThreads()
|
|
120
113
|
}
|
|
121
|
-
}, [
|
|
114
|
+
}, [fetchThreads])
|
|
122
115
|
|
|
123
116
|
return {
|
|
124
117
|
threads,
|
|
@@ -126,6 +119,6 @@ export function useThreads() {
|
|
|
126
119
|
error,
|
|
127
120
|
refreshThreads: fetchThreads,
|
|
128
121
|
deleteThread,
|
|
129
|
-
updateThreadTitle
|
|
122
|
+
updateThreadTitle,
|
|
130
123
|
}
|
|
131
124
|
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared AgentBuilder API access for the chat UI.
|
|
3
|
+
*
|
|
4
|
+
* Local AgentBuilder instances refuse cross-origin requests, so the chat talks
|
|
5
|
+
* to the runtime same-origin by default: Vite proxies `/api` in development
|
|
6
|
+
* and Next.js rewrites it. A deployment served from a different origin than a
|
|
7
|
+
* remote runtime sets the base URL from its entry point via `configureApi()`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const TOKEN_KEY = 'agentbuilder_auth_token'
|
|
11
|
+
|
|
12
|
+
let baseUrl = ''
|
|
13
|
+
|
|
14
|
+
export function configureApi(options: { baseUrl?: string }) {
|
|
15
|
+
baseUrl = (options.baseUrl || '').replace(/\/$/, '')
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function getBaseUrl(): string {
|
|
19
|
+
return baseUrl
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Endpoint passed to `AgentBuilderProvider` for SDK routes. */
|
|
23
|
+
export function getSdkEndpoint(): string {
|
|
24
|
+
return `${getBaseUrl()}/api`
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function apiUrl(path: string): string {
|
|
28
|
+
return `${getBaseUrl()}${path}`
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function getToken(): string {
|
|
32
|
+
try {
|
|
33
|
+
return localStorage.getItem(TOKEN_KEY) || ''
|
|
34
|
+
} catch {
|
|
35
|
+
return ''
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Fetch an AgentBuilder route. Same-origin requests carry the HttpOnly session
|
|
41
|
+
* cookie; a stored bearer token (password login) is sent when present.
|
|
42
|
+
*/
|
|
43
|
+
export function apiFetch(path: string, init: RequestInit = {}): Promise<Response> {
|
|
44
|
+
const headers = new Headers(init.headers)
|
|
45
|
+
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) {
|
|
46
|
+
headers.set('Content-Type', 'application/json')
|
|
47
|
+
}
|
|
48
|
+
const token = getToken()
|
|
49
|
+
if (token && !headers.has('Authorization')) {
|
|
50
|
+
headers.set('Authorization', `Bearer ${token}`)
|
|
51
|
+
}
|
|
52
|
+
return fetch(apiUrl(path), { credentials: 'include', ...init, headers })
|
|
53
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { completeStreamingTable, repairStreamingMarkdown } from './streamingMarkdown'
|
|
3
|
+
|
|
4
|
+
describe('completeStreamingTable', () => {
|
|
5
|
+
it('adds a delimiter row once a table header row finishes', () => {
|
|
6
|
+
expect(completeStreamingTable('Intro\n\n| Ticker | Sentiment |'))
|
|
7
|
+
.toBe('Intro\n\n| Ticker | Sentiment |\n| --- | --- |')
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
it('completes a partially streamed delimiter row', () => {
|
|
11
|
+
expect(completeStreamingTable('| A | B | C |\n|------|---'))
|
|
12
|
+
.toBe('| A | B | C |\n| --- | --- | --- |')
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
it('leaves complete tables and streaming body rows alone', () => {
|
|
16
|
+
const table = '| A | B |\n|---|---|\n| 1 | 2'
|
|
17
|
+
expect(completeStreamingTable(table)).toBe(table)
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
it('ignores pipes inside an open code fence', () => {
|
|
21
|
+
const fenced = '```\n| A | B |'
|
|
22
|
+
expect(completeStreamingTable(fenced)).toBe(fenced)
|
|
23
|
+
})
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
describe('repairStreamingMarkdown', () => {
|
|
27
|
+
it('closes unterminated emphasis', () => {
|
|
28
|
+
expect(repairStreamingMarkdown('Some **bold')).toBe('Some **bold**')
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('shows incomplete links as text instead of a placeholder URL', () => {
|
|
32
|
+
expect(repairStreamingMarkdown('see [the docs](https://exa')).not.toContain('streamdown:')
|
|
33
|
+
})
|
|
34
|
+
})
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import remend, { type RemendHandler } from 'remend'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Streaming repair for partial Markdown, applied only while a message is
|
|
5
|
+
* still arriving. `remend` closes unterminated emphasis, code, links and
|
|
6
|
+
* fences; the table handler below makes a GFM table render as a table as soon
|
|
7
|
+
* as its header row arrives instead of flashing raw pipes until the
|
|
8
|
+
* `|---|` delimiter row is complete.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const TABLE_ROW = /^\s*\|.*\|\s*$/
|
|
12
|
+
const PARTIAL_DELIMITER = /^\s*\|?[\s:|-]*$/
|
|
13
|
+
|
|
14
|
+
function countColumns(row: string): number {
|
|
15
|
+
return row.trim().replace(/^\||\|$/g, '').split('|').length
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function delimiterRow(columns: number): string {
|
|
19
|
+
return `|${' --- |'.repeat(columns)}`
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function isInsideFence(lines: string[]): boolean {
|
|
23
|
+
return lines.filter(line => /^\s*(```|~~~)/.test(line)).length % 2 === 1
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function completeStreamingTable(text: string): string {
|
|
27
|
+
const lines = text.split('\n')
|
|
28
|
+
const last = lines[lines.length - 1]
|
|
29
|
+
const previous = lines[lines.length - 2]
|
|
30
|
+
const beforeHeader = lines[lines.length - 3]
|
|
31
|
+
if (isInsideFence(lines)) return text
|
|
32
|
+
|
|
33
|
+
// Header row just finished: `| A | B |` → add the delimiter row.
|
|
34
|
+
if (TABLE_ROW.test(last) && (previous === undefined || !TABLE_ROW.test(previous))) {
|
|
35
|
+
return `${text}\n${delimiterRow(countColumns(last))}`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Delimiter row still streaming: `| A | B |\n|--` → finish it.
|
|
39
|
+
if (
|
|
40
|
+
previous !== undefined
|
|
41
|
+
&& TABLE_ROW.test(previous)
|
|
42
|
+
&& (beforeHeader === undefined || !TABLE_ROW.test(beforeHeader))
|
|
43
|
+
&& last.trim().length > 0
|
|
44
|
+
&& PARTIAL_DELIMITER.test(last)
|
|
45
|
+
) {
|
|
46
|
+
return [...lines.slice(0, -1), delimiterRow(countColumns(previous))].join('\n')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return text
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const tableHandler: RemendHandler = {
|
|
53
|
+
name: 'gfm-table',
|
|
54
|
+
handle: completeStreamingTable,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function repairStreamingMarkdown(text: string): string {
|
|
58
|
+
return remend(text, { linkMode: 'text-only', handlers: [tableHandler] })
|
|
59
|
+
}
|
package/chat/vite/main.tsx
CHANGED
|
@@ -3,20 +3,19 @@ import ReactDOM from 'react-dom/client'
|
|
|
3
3
|
import { AgentBuilderProvider } from '@standardagents/react'
|
|
4
4
|
import { ThemeProvider } from '../src/hooks/useTheme'
|
|
5
5
|
import { AuthProvider } from '../src/hooks/useAuth'
|
|
6
|
+
import { configureApi, getSdkEndpoint } from '../src/lib/api'
|
|
6
7
|
import App from '../src/App'
|
|
7
8
|
import '../src/index.css'
|
|
8
9
|
|
|
9
|
-
//
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
// Append /api to the endpoint for SDK routes
|
|
13
|
-
const SDK_ENDPOINT = AGENTBUILDER_URL ? `${AGENTBUILDER_URL}/api` : '/api'
|
|
10
|
+
// The dev server proxies /api to VITE_AGENTBUILDER_URL (same-origin); a
|
|
11
|
+
// production build talks to the runtime directly.
|
|
12
|
+
configureApi({ baseUrl: import.meta.env.DEV ? '' : import.meta.env.VITE_AGENTBUILDER_URL })
|
|
14
13
|
|
|
15
14
|
ReactDOM.createRoot(document.getElementById('root')!).render(
|
|
16
15
|
<React.StrictMode>
|
|
17
16
|
<ThemeProvider>
|
|
18
17
|
<AuthProvider>
|
|
19
|
-
<AgentBuilderProvider config={{ endpoint:
|
|
18
|
+
<AgentBuilderProvider config={{ endpoint: getSdkEndpoint() }}>
|
|
20
19
|
<App />
|
|
21
20
|
</AgentBuilderProvider>
|
|
22
21
|
</AuthProvider>
|