aifirst: lift context/agents/tools runtime to lib-aifirst-ui

The mechanism (context surface registry, persona storage + hooks, tool
parser/dispatcher) is now generic and lives in @crema/aifirst-ui/{context,
agents,tools}. This template keeps only the arcadia-shaped configuration:

- agents.ts — owns DEFAULT_AGENTS + legacy/retired migration sets, calls
  configureAgents() at module load, re-exports the runtime
- admin-tools.ts — keeps the 19 arcadia tool definitions, binds the
  runtime via createToolRuntime(TOOLS), re-exports the bound functions
- admin-context.ts — deleted; 18 routes now import directly from
  @crema/aifirst-ui/context

Routes that import from ~/lib/agents and ~/lib/admin-tools are unchanged
(wrapper modules preserve the existing import surface).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
jules
2026-05-05 15:18:48 +10:00
parent c968ac0735
commit a286b9cdce
21 changed files with 73 additions and 370 deletions

View File

@@ -6,7 +6,10 @@
// raw HTTP — only the menu below.
import type { ArcadiaClient } from "@crema/arcadia-client"
import type { Tool, ToolCall as LLMToolCall } from "@crema/llm-ui"
import {
createToolRuntime,
type ToolDef,
} from "@crema/aifirst-ui/tools"
import {
activateTenant,
@@ -163,30 +166,9 @@ async function kbRead(chunkId: string, corpus: string): Promise<unknown> {
return await res.json()
}
export type ToolCall = {
name: string
args: Record<string, unknown>
}
export type ToolResult = {
name: string
args: Record<string, unknown>
ok: boolean
data?: unknown
error?: string
}
type ToolDef = {
name: string
description: string
parameters: Record<string, unknown> // JSON Schema for OpenAI tool calling
isWrite: boolean
run: (args: Record<string, unknown>, ctx: ToolCtx) => Promise<unknown>
}
type ToolCtx = { arcadia: ArcadiaClient }
const TOOLS: ToolDef[] = [
const TOOLS: ToolDef<ToolCtx>[] = [
{
name: "list_tenants",
description:
@@ -927,58 +909,6 @@ interface UserEntry {
roles?: { slug?: string; name?: string }[]
}
/** OpenAI-format tool list to pass into ChatRequest.tools. */
export function getOpenAITools(): Tool[] {
return TOOLS.map((t) => ({
name: t.name,
description: t.description,
parameters: t.parameters,
}))
}
/** Split an LLM tool-call list into reads (run automatically) and writes
* (held for user confirmation). Unknown tools fall into reads so the runner
* can surface a structured "unknown tool" error to the model. */
export function classifyCalls(calls: LLMToolCall[]): {
reads: LLMToolCall[]
writes: LLMToolCall[]
} {
const reads: LLMToolCall[] = []
const writes: LLMToolCall[] = []
for (const c of calls) {
const def = TOOL_BY_NAME.get(c.name)
if (def?.isWrite) writes.push(c)
else reads.push(c)
}
return { reads, writes }
}
/** Synthesise tool-result messages saying the user denied a write call. */
export function buildDenialMessages(
calls: LLMToolCall[],
): { role: "tool"; content: string; toolCallId: string; name: string }[] {
return calls.map((c) => ({
role: "tool",
content: JSON.stringify({
error: "User denied this write. Do not retry without re-asking the user.",
}),
toolCallId: c.id,
name: c.name,
}))
}
/** Pretty-print args for the confirm UI. */
export function formatToolCallArgs(c: LLMToolCall): string {
try {
const parsed = c.arguments ? JSON.parse(c.arguments) : {}
const keys = Object.keys(parsed)
if (keys.length === 0) return ""
return keys.map((k) => `${k}=${JSON.stringify(parsed[k])}`).join(", ")
} catch {
return c.arguments
}
}
function summarize(t: Tenant) {
return {
id: t.id,
@@ -990,62 +920,15 @@ function summarize(t: Tenant) {
}
}
const TOOL_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]))
const runtime = createToolRuntime(TOOLS)
function safeJson(value: unknown): string {
try {
const text = JSON.stringify(value, null, 2)
if (text.length > 6000) return text.slice(0, 6000) + "\n…(truncated)"
return text
} catch {
return "(unserializable)"
}
}
export const getOpenAITools = runtime.getOpenAITools
export const classifyCalls = runtime.classifyCalls
export const runLLMToolCalls = runtime.runLLMToolCalls
/** Run a list of provider-native tool calls and return `tool` role messages
* ready to push back into useChat history. */
export async function runLLMToolCalls(
calls: LLMToolCall[],
ctx: ToolCtx,
opts: { allowWrites?: boolean } = {},
): Promise<{
results: ToolResult[]
toolMessages: { role: "tool"; content: string; toolCallId: string; name: string }[]
}> {
const results: ToolResult[] = []
const toolMessages: { role: "tool"; content: string; toolCallId: string; name: string }[] = []
for (const call of calls) {
const def = TOOL_BY_NAME.get(call.name)
let parsed: Record<string, unknown> = {}
try {
parsed = call.arguments ? (JSON.parse(call.arguments) as Record<string, unknown>) : {}
} catch {
const err = `Could not parse arguments JSON: ${call.arguments}`
results.push({ name: call.name, args: {}, ok: false, error: err })
toolMessages.push({ role: "tool", content: JSON.stringify({ error: err }), toolCallId: call.id, name: call.name })
continue
}
if (!def) {
const err = `Unknown tool: ${call.name}`
results.push({ name: call.name, args: parsed, ok: false, error: err })
toolMessages.push({ role: "tool", content: JSON.stringify({ error: err }), toolCallId: call.id, name: call.name })
continue
}
if (def.isWrite && !opts.allowWrites) {
const err = "Write tools require user confirmation."
results.push({ name: call.name, args: parsed, ok: false, error: err })
toolMessages.push({ role: "tool", content: JSON.stringify({ error: err }), toolCallId: call.id, name: call.name })
continue
}
try {
const data = await def.run(parsed, ctx)
results.push({ name: call.name, args: parsed, ok: true, data })
toolMessages.push({ role: "tool", content: safeJson(data), toolCallId: call.id, name: call.name })
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
results.push({ name: call.name, args: parsed, ok: false, error: msg })
toolMessages.push({ role: "tool", content: JSON.stringify({ error: msg }), toolCallId: call.id, name: call.name })
}
}
return { results, toolMessages }
}
export {
buildDenialMessages,
formatToolCallArgs,
type ToolCall,
type ToolResult,
} from "@crema/aifirst-ui/tools"