OpenAgentPack Kit
SDK

组件交互与后端调用

公开 SDK 统一目录、上传、发送、产物与用量恢复,体验页和自建后端共用接入方式

Web 的组件交互统一消费 @openagentpack/kit-sdk 各功能的数据入口和 /hooks, 例如 /sessions/hooks、/files/hooks、/chat/hooks 和 /usage/hooks。 数据 Client 配置在 apps/web/src/lib/backend.ts,聊天 Provider 配置在 chat-backend.ts; Kit Server 是示例后端。外部纯前端项目替换请求与响应映射后使用相同 hooks,无需依赖 Web 源码或部署 Kit Server。

接入边界

能力公开 SDK组件 / 宿主保留
会话目录useSessionDirectory、useSessionSearch:分组、最近、分页缓存、防抖取消、重命名、操作计划折叠、滚动触发、行内编辑、路由与选中来源
历史附件useSessionDetails 取消旧查询,并调用已有 chat.setMessageFiles气泡渲染
上传useAttachments:校验、上传、扫描轮询、取消、失败和暂存文件选择、拖放、粘贴、附件卡片
发送与挂载useComposer:已有会话直接提交,首次发送先建会话,再通过 chat.send 携带附件草稿、键盘、技能选择;成功受理后才清草稿与已提交附件
产物useArtifactActions:鉴权读取、类型解析、安全预览判断与保存降级注入 ArtifactHost,执行开窗、object URL 和实际保存
用量useUsageLimits、useQuotaRecovery、useCreateQuotaRequest展示和表单绑定;后端负责计量与权限

这些是前端调用流程封装。鉴权、归属校验、扫描结果、挂载、额度判断和一次性确认令牌仍由后端负责。 Stream、Request、Chat、审批以及组件已有的输入能力均复用原实现。

显式 Client 与可选能力

使用 createKitClient({ request, operations })。操作的 buildRequest 接收与 Client 方法一致的参数元组; mapResponse 将后端响应映射成现有 DTO,取消信号通过 context.signal 提供。 HTTP 错误映射配置在 createRequest({ mapHttpError }),不会新增另一套请求客户端。

只配置需要的操作,通过 client.supports("uploadFile") 等判断并隐藏未支持的入口。 未配置操作会在本地报错,绝不回退 /api/kit/*,也不自动添加 Kit 协议头、重试或超时。 旧 createKitClient({ baseUrl }) 和 KitProvider 保留兼容;所有本页 hooks 都可以显式接收 client。 新的调用面仍名为 KitClient,但显式模式没有 Kit Server 路由假设。

后端输出 SessionEvent 的聊天接入见 Provider 与自建后端。 上传返回 file_id/filename/size,扫描返回 status/available;查询分页返回 sessions/nextPageToken。 删除与归档必须先返回 plan_id/confirm_token/expires_at/diff,确认后才调用执行操作。

组件绑定示例

左栏加载会话目录和搜索结果,中间渲染当前会话的消息和输入,右栏展示当前 Agent 的简介、资源、子 Agent 和会话产物。 选择会话时同步切换 Agent 和会话 ID。client、provider 和 host 均由应用初始化并保持稳定。 复制这份 完整示例 时,同时复制同目录的 Agent 资源面板 和 审批列表。

import {
	AgentHeader,
	type AttachmentItem,
	Attachments,
	Chat,
	ConfirmDialog,
	Layout,
	SessionSidebar,
	type SessionSidebarSection,
} from "@openagentpack/kit-chat-ui";
import { useAgentCatalog, useAgentResources } from "@openagentpack/kit-sdk/agents/hooks";
import { useChat, useComposer } from "@openagentpack/kit-sdk/chat/hooks";
import type { ArtifactHost } from "@openagentpack/kit-sdk/files";
import { useArtifactActions, useAttachments } from "@openagentpack/kit-sdk/files/hooks";
import type { ChatProvider } from "@openagentpack/kit-sdk/providers";
import type { KitClient } from "@openagentpack/kit-sdk/providers/kit";
import { useSessionDetails, useSessionDirectory, useSessionSearch } from "@openagentpack/kit-sdk/sessions/hooks";
import { useQuotaRecovery, useUsageLimits } from "@openagentpack/kit-sdk/usage/hooks";
import { useState } from "react";
import { AgentResourcesPanel } from "./agent-resources-panel.tsx";
import { ApprovalList } from "./approval-list.tsx";

interface ConversationSelection {
	agentSlug: string;
	sessionId: string | null;
	section: SessionSidebarSection;
}

function SessionDeletionDialog({ actions }: { actions: ReturnType<typeof useSessionDirectory>["actions"] }) {
	const { pending, busy } = actions;
	if (!pending) return null;
	const { plan, error } = pending;
	const body = error ?? (plan ? JSON.stringify(plan.diff, null, 2) : "正在准备删除计划…");
	return (
		<ConfirmDialog
			title="确认删除会话"
			body={body}
			busy={busy}
			confirmLabel={plan ? "删除会话" : "准备计划"}
			cancelLabel="取消"
			onCancel={actions.cancel}
			onConfirm={() => void actions.confirm()}
		/>
	);
}

// 在组件外保持显式 Client、Provider 和宿主实例稳定。
export function Experience({
	client,
	provider,
	host,
	agentSlug: initialAgentSlug,
}: {
	client: KitClient;
	provider: ChatProvider;
	host: ArtifactHost;
	agentSlug: string;
}) {
	const [{ agentSlug, sessionId, section }, setSelection] = useState<ConversationSelection>({
		agentSlug: initialAgentSlug,
		sessionId: null,
		section: "groups",
	});
	const [keyword, setKeyword] = useState("");
	const [asideOpen, setAsideOpen] = useState(true);
	const [draftKey, setDraftKey] = useState(0);
	const chat = useChat({ sessionId, provider });
	const attachments = useAttachments({ client });
	function selectConversation(next: ConversationSelection) {
		if (next.sessionId !== sessionId || next.agentSlug !== agentSlug) {
			attachments.clear();
			setDraftKey((key) => key + 1);
		}
		setSelection(next);
	}
	const directory = useSessionDirectory({
		client,
		onExecuted: (id) => {
			if (id === sessionId) selectConversation({ agentSlug, sessionId: null, section: "groups" });
		},
	});
	const search = useSessionSearch(keyword, { client });
	const details = useSessionDetails({ client, sessionId, setMessageFiles: chat.setMessageFiles });
	const attachmentItems: AttachmentItem[] = [
		...attachments.pending.map((file) => ({ ...file, status: "uploading" as const })),
		...attachments.files.map((file) => ({
			uid: file.file_id,
			name: file.filename,
			size: file.size,
			status: file.timedOut ? ("error" as const) : ("done" as const),
			description: file.timedOut ? "扫描超时,请移除文件后重试。" : file.available ? null : "正在扫描…",
		})),
		...attachments.failures.map(({ message, ...file }) => ({
			...file,
			status: "error" as const,
			description: message,
		})),
	];
	// 等所有文件可用后再发送。先移除上传失败的文件。
	const attachmentsReady = !attachments.uploading && !attachments.processing && attachments.failures.length === 0;
	const composer = useComposer({
		client,
		agentSlug,
		sessionId,
		files: attachments.files,
		send: chat.send,
		onSessionCreated: (id) => {
			// 保留当前草稿以发送首条消息,并刷新侧栏目录。
			setSelection({ agentSlug, sessionId: id, section: "groups" });
			directory.reload();
		},
		onAccepted: attachments.consume,
	});
	const artifacts = useArtifactActions({ client, host, sessionId: sessionId ?? undefined, artifacts: chat.artifacts });
	const recovery = useQuotaRecovery({ client });
	const { agents } = useAgentCatalog({ client });
	const agent = agents.find((item) => item.slug === agentSlug) ?? null;
	const agentName = (slug: string) => agents.find((item) => item.slug === slug)?.display_name ?? slug;
	const resources = useAgentResources(agentSlug, { client });
	const skills = resources?.skills.map(({ name, description }) => ({ name, description }));
	const limits = useUsageLimits({ client });
	const canCreateSession = client.supports("createSession");
	const canSend = (sessionId ? chat.canSend : canCreateSession) && attachmentsReady && !composer.pending;
	const canReadArtifacts = Boolean(sessionId) && client.supports("downloadFile");
	const openArtifact = canReadArtifacts
		? (id: string, type?: string) => void artifacts.open(id, type).catch(() => undefined)
		: undefined;
	const downloadArtifact = canReadArtifacts
		? (id: string) => void artifacts.download(id).catch(() => undefined)
		: undefined;
	return (
		<div className="h-dvh" data-kit-appearance="workspace">
			<Layout
				sidebarLabel="会话"
				header={(menuToggle) => (
					<AgentHeader
						compact
						agent={agent}
						leading={menuToggle}
						actions={
							<button type="button" aria-expanded={asideOpen} onClick={() => setAsideOpen((open) => !open)}>
								资源
							</button>
						}
					/>
				)}
				sidebar={({ closeSidebar, closeButton }) => (
					<aside
						aria-label="会话导航"
						className="flex min-h-0 w-64 shrink-0 flex-col border-r border-[var(--kit-border-subtle)] bg-[var(--kit-bg-subtle)]"
					>
						<div className="flex shrink-0 items-center justify-between gap-2 p-3">
							{canCreateSession && (
								<button
									type="button"
									onClick={() => {
										selectConversation({ agentSlug, sessionId: null, section: "groups" });
										closeSidebar();
									}}
								>
									新建会话
								</button>
							)}
							{closeButton}
						</div>
						<SessionSidebar
							activeId={sessionId}
							activeSection={section}
							activeGroupId={section === "groups" && sessionId ? agentSlug : null}
							agentName={agentName}
							loading={directory.loading}
							error={directory.error}
							onReload={directory.reloadGroups}
							groups={directory.groups.map((group) => ({
								...group,
								id: group.slug,
								name: agentName(group.slug),
								onLoad: group.load,
								onLoadMore: group.loadMore,
								onRetry: group.retry,
							}))}
							recent={{ ...directory.recent, onLoadMore: directory.recent.loadMore, onRetry: directory.recent.retry }}
							searchInput={keyword}
							onSearchInput={setKeyword}
							search={keyword.trim() ? { ...search, onLoadMore: search.loadMore, onRetry: search.retry } : undefined}
							onSelect={(session, source) => {
								selectConversation({ agentSlug: session.agent_slug, sessionId: session.session_id, section: source });
								closeSidebar();
							}}
						/>
						{sessionId && client.supports("sessionPlan") && client.supports("deleteSession") && (
							<button
								type="button"
								className="shrink-0 p-3 text-left"
								onClick={() => void directory.actions.request(sessionId, "delete")}
							>
								准备删除
							</button>
						)}
					</aside>
				)}
				asideLabel="Agent 资源"
				asideOpen={asideOpen}
				onAsideOpenChange={setAsideOpen}
				aside={({ closeButton }) => (
					<div className="flex min-h-0 flex-1 flex-col">
						{closeButton ? (
							<div className="flex shrink-0 items-center justify-between gap-2 p-3">
								<span>资源</span>
								{closeButton}
							</div>
						) : null}
						<div className="min-h-0 flex-1 overflow-y-auto p-4">
							{artifacts.error ? <p role="alert">{artifacts.error}</p> : null}
							<AgentResourcesPanel
								agent={agent}
								resources={resources}
								multiAgent={chat.multiAgent}
								artifacts={chat.artifacts}
								onArtifactOpen={openArtifact}
								onArtifactDownload={downloadArtifact}
							/>
						</div>
					</div>
				)}
				dialogs={<SessionDeletionDialog actions={directory.actions} />}
			>
				<section aria-label="对话" className="flex min-h-0 flex-1 flex-col">
					{details.error ? <p role="alert">{details.error}</p> : null}
					{client.supports("uploadFile") && client.supports("fileStatus") && (
						<Attachments
							items={attachmentItems}
							onSelectFiles={(files) => void attachments.upload(files)}
							onRemove={(file) => attachments.remove(file.uid)}
						/>
					)}
					<Chat
						key={draftKey}
						variant="workspace"
						messages={chat.messages}
						multiAgent={chat.multiAgent}
						scrollKey={sessionId}
						turnRunning={chat.turnRunning}
						sending={composer.pending}
						canSend={canSend}
						skills={skills}
						approvals={chat.approvals.length ? <ApprovalList chat={chat} /> : null}
						onSend={composer.send}
						onStop={chat.stop}
						onArtifactOpen={openArtifact}
						onArtifactDownload={downloadArtifact}
					/>
					{composer.error ? <p role="alert">发送失败,已保留草稿和附件。</p> : null}
					{limits.error && <p role="alert">{limits.error}</p>}
					<button type="button" disabled={recovery.loading} onClick={() => void recovery.recheck()}>
						重新检查服务端限额
					</button>
				</section>
			</Layout>
		</div>
	);
}

发送失败会拒绝 Promise,组件保留草稿;SDK 仅在成功后向 onAccepted 返回本次文件 ID。 首次创建后绑定返回的会话 ID 会继续完成发送;用户切换到其他会话或智能体时取消旧流程, 迟到的创建结果不再触发导航或发送。 扫描未就绪或超时应禁用发送,后端仍需再次校验。只有服务端明确返回附件未就绪的可重试冲突, 建会话才有限重试;已经发送的消息不会自动重发。

useSessionDetails 按 client/sessionId 管理请求生命周期。setMessageFiles 可以使用内联回调, 回调更新不会重新请求详情,当前请求完成时使用最新回调;切换目标会取消旧请求并忽略迟到结果。

directory.actions.request 只读取计划,confirm 才执行;失败后的再次确认先获取新计划,用户需再次确认。 使用 ConfirmDialog(AlertDialog 语义)展示计划,不能跳过确认。useQuotaRecovery.recheck() 仅在所有启用指标由新响应确认可用时返回 true;网络错误、未知状态或 null 均不能解除发送禁用。

身份与宿主

createMemberAuthController 同时接收 createClient(request) 与 createChatProvider(request), 为同一身份创建固定 token 的实例,退出、401 和切换身份会取消旧请求及响应正文。 createMemberSessionStorage(baseUrl, getStorage) 是可注入的公开存储适配器;完整服务地址隔离登录态。 浏览器可传 () => window.sessionStorage,其他宿主提供同形的 getItem/setItem/removeItem。 Host 只包含文件与剪贴板等交互能力,不保存 token、身份或服务地址。

跨域文件下载若通过响应头提供文件名,需要后端暴露 Content-Disposition(CORS Access-Control-Expose-Headers);否则传入已有产物列表的 filename 作为文件名来源。

createSessionDirectory、createSessionDetails 从 /sessions 导入;createAttachments、 createArtifactActions 从 /files 导入;createComposer 从 /chat 导入;createQuotaRecovery 从 /usage 导入。上述路径均以 @openagentpack/kit-sdk 为前缀,可供非 React 项目使用; 订阅快照并在卸载时 dispose()。对应 hooks 从各功能的 /hooks 子入口导入。 这些控制器不访问 window/document,实际文件交互适配保留在宿主。

本页目录