@powerhousedao/reactor-browser 6.2.2-dev.76 → 6.2.2-dev.77
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/{attachment-service-DTFJRf5j.d.ts → attachment-service-LwpgZ358.d.ts} +4 -4
- package/dist/{attachment-service-DTFJRf5j.d.ts.map → attachment-service-LwpgZ358.d.ts.map} +1 -1
- package/dist/{client-Zz_l9QzI.js → client-B8ezRmBB.js} +1 -1
- package/dist/{client-Zz_l9QzI.js.map → client-B8ezRmBB.js.map} +1 -1
- package/dist/{client-DjkEpwu_.d.ts → client-BIHN_UyR.d.ts} +2 -2
- package/dist/{client-DjkEpwu_.d.ts.map → client-BIHN_UyR.d.ts.map} +1 -1
- package/dist/{client-DB8gP4hz.js → client-D66jVnot.js} +1 -1
- package/dist/{client-DB8gP4hz.js.map → client-D66jVnot.js.map} +1 -1
- package/dist/document-model-modules-BB9s6a3m.js +377 -0
- package/dist/document-model-modules-BB9s6a3m.js.map +1 -0
- package/dist/{document-operations-DZ-oUHRy.js → document-operations-I1cGIcPg.js} +7 -377
- package/dist/document-operations-I1cGIcPg.js.map +1 -0
- package/dist/{global-pg5gy2eZ.d.ts → global-1rvI8VdA.d.ts} +4 -4
- package/dist/{global-pg5gy2eZ.d.ts.map → global-1rvI8VdA.d.ts.map} +1 -1
- package/dist/{index-BV00np9e.d.ts → index-BE3wBHLP.d.ts} +3 -3
- package/dist/index-BE3wBHLP.d.ts.map +1 -0
- package/dist/{index-CxxxP14A.d.ts → index-BIVDXw3K.d.ts} +2 -2
- package/dist/{index-CxxxP14A.d.ts.map → index-BIVDXw3K.d.ts.map} +1 -1
- package/dist/index.d.ts +8 -8
- package/dist/index.js +11 -44
- package/dist/index.js.map +1 -1
- package/dist/{inspector-proxy-CaCFdEG4.d.ts → inspector-proxy-6h5VKAwt.d.ts} +1 -1
- package/dist/{inspector-proxy-CaCFdEG4.d.ts.map → inspector-proxy-6h5VKAwt.d.ts.map} +1 -1
- package/dist/{pglite-CntadC_p-BtEalg1H.d.ts → pglite-CntadC_p-9NDG14dS.d.ts} +1 -1
- package/dist/{pglite-CntadC_p-BtEalg1H.d.ts.map → pglite-CntadC_p-9NDG14dS.d.ts.map} +1 -1
- package/dist/{relational-C_0GdGVN.js → relational-D4sxGPz7.js} +1 -1
- package/dist/{relational-C_0GdGVN.js.map → relational-D4sxGPz7.js.map} +1 -1
- package/dist/{renown-6w_ImTvm.js → renown-BHxwP7xU.js} +1 -1
- package/dist/{renown-6w_ImTvm.js.map → renown-BHxwP7xU.js.map} +1 -1
- package/dist/{renown-DRnlawbP.js → renown-BIEv6bSI.js} +3 -3
- package/dist/renown-BIEv6bSI.js.map +1 -0
- package/dist/selected-document-CtRlEZyi.js +42 -0
- package/dist/selected-document-CtRlEZyi.js.map +1 -0
- package/dist/src/ai/index.d.ts +267 -0
- package/dist/src/ai/index.d.ts.map +1 -0
- package/dist/src/ai/index.js +951 -0
- package/dist/src/ai/index.js.map +1 -0
- package/dist/src/analytics/index.d.ts +1 -1
- package/dist/src/analytics/index.js +1 -1
- package/dist/src/graphql/client.d.ts +2 -2
- package/dist/src/graphql/client.js +1 -1
- package/dist/src/graphql-client/entry.d.ts +3 -3
- package/dist/src/graphql-client/entry.js +2 -1
- package/dist/src/relational/index.d.ts +1 -1
- package/dist/src/relational/index.js +1 -1
- package/dist/src/renown/index.d.ts +1 -1
- package/dist/src/renown/index.js +2 -2
- package/dist/src/rpc/index.d.ts +2 -2
- package/dist/src/rpc/index.js +1 -1
- package/dist/{store-DAJq6vSs.js → store-BJYcr_FL.js} +1 -1
- package/dist/{store-DAJq6vSs.js.map → store-BJYcr_FL.js.map} +1 -1
- package/dist/{types-wGaiXwjh.d.ts → types-6vDzbRRS.d.ts} +1 -1
- package/dist/{types-wGaiXwjh.d.ts.map → types-6vDzbRRS.d.ts.map} +1 -1
- package/dist/{types-4rfAFZQd.d.ts → types-Dcv1ZLoW.d.ts} +1 -1
- package/dist/{types-4rfAFZQd.d.ts.map → types-Dcv1ZLoW.d.ts.map} +1 -1
- package/package.json +19 -9
- package/dist/document-operations-DZ-oUHRy.js.map +0 -1
- package/dist/index-BV00np9e.d.ts.map +0 -1
- package/dist/renown-DRnlawbP.js.map +0 -1
|
@@ -0,0 +1,951 @@
|
|
|
1
|
+
import { S as useSelectedDriveSafe, s as useSelectedNode } from "../../document-model-modules-BB9s6a3m.js";
|
|
2
|
+
import { n as useSelectedDocumentId } from "../../selected-document-CtRlEZyi.js";
|
|
3
|
+
import { isFileNode, isFolderNode } from "@powerhousedao/shared/document-drive";
|
|
4
|
+
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
|
|
5
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { isStepCount, streamText, tool } from "ai";
|
|
8
|
+
import { toResponseMessages } from "ai/internal";
|
|
9
|
+
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
10
|
+
import { ArrowUp, Check, Maximize2, MessageCircle, Minimize2, Square, Trash2, X } from "lucide-react";
|
|
11
|
+
import ReactMarkdown from "react-markdown";
|
|
12
|
+
import remarkGfm from "remark-gfm";
|
|
13
|
+
//#region src/ai/types.ts
|
|
14
|
+
/** Tool names whose execution mutates the reactor and requires approval. */
|
|
15
|
+
const WRITE_TOOLS = new Set([
|
|
16
|
+
"createDocument",
|
|
17
|
+
"addActions",
|
|
18
|
+
"deleteDocument",
|
|
19
|
+
"addDrive",
|
|
20
|
+
"deleteDrive",
|
|
21
|
+
"addRemoteDrive"
|
|
22
|
+
]);
|
|
23
|
+
function isWriteTool(name) {
|
|
24
|
+
return WRITE_TOOLS.has(name);
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/ai/agent.ts
|
|
28
|
+
/** Hard cap on model round-trips per user message (each tool step counts). */
|
|
29
|
+
const MAX_AGENT_STEPS = 10;
|
|
30
|
+
/**
|
|
31
|
+
* Creates the chat language model for a user-supplied OpenAI-compatible
|
|
32
|
+
* endpoint. Requests go directly from the browser to the endpoint; the API
|
|
33
|
+
* key is never sent to any Powerhouse server.
|
|
34
|
+
*/
|
|
35
|
+
/**
|
|
36
|
+
* Resolves the configured base URL. Relative paths (e.g. `/v1`) resolve
|
|
37
|
+
* against the page origin, so single-origin deployments can serve the
|
|
38
|
+
* endpoint behind the same reverse proxy without CORS.
|
|
39
|
+
*/
|
|
40
|
+
function resolveBaseUrl(raw) {
|
|
41
|
+
const base = raw.trim().replace(/\/+$/, "");
|
|
42
|
+
if (/^https?:\/\//i.test(base)) return base;
|
|
43
|
+
if (typeof window === "undefined") return base;
|
|
44
|
+
return `${window.location.origin}${base.startsWith("/") ? "" : "/"}${base}`;
|
|
45
|
+
}
|
|
46
|
+
function createReactorChatModel(settings) {
|
|
47
|
+
return createOpenAICompatible({
|
|
48
|
+
name: "reactor-chat",
|
|
49
|
+
baseURL: resolveBaseUrl(settings.baseUrl),
|
|
50
|
+
apiKey: settings.apiKey
|
|
51
|
+
}).chatModel(settings.model.trim());
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Unwraps the MCP `CallToolResult` envelope produced by the reactor tool
|
|
55
|
+
* core into a plain value for the AI SDK. Throws for error results so the
|
|
56
|
+
* SDK surfaces them as tool errors in the next model step.
|
|
57
|
+
*/
|
|
58
|
+
function unwrapToolResult(raw) {
|
|
59
|
+
if (raw && typeof raw === "object") {
|
|
60
|
+
const envelope = raw;
|
|
61
|
+
if (typeof envelope.isError === "boolean" || Array.isArray(envelope.content)) {
|
|
62
|
+
if (envelope.isError) {
|
|
63
|
+
const text = envelope.content?.find((c) => c.type === "text")?.text ?? "Unknown tool error";
|
|
64
|
+
throw new Error(text.replace(/^Error:\s*/, ""));
|
|
65
|
+
}
|
|
66
|
+
if (envelope.structuredContent !== void 0) return envelope.structuredContent;
|
|
67
|
+
const textPart = envelope.content?.find((c) => c.type === "text");
|
|
68
|
+
if (textPart?.text !== void 0) try {
|
|
69
|
+
return JSON.parse(textPart.text);
|
|
70
|
+
} catch {
|
|
71
|
+
return textPart.text;
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return raw;
|
|
77
|
+
}
|
|
78
|
+
/** Builds the system prompt, grounding the agent in the current selection. */
|
|
79
|
+
function buildSystemPrompt(context) {
|
|
80
|
+
const lines = [
|
|
81
|
+
"You are an assistant embedded in the Powerhouse Connect drive explorer.",
|
|
82
|
+
"You operate on a local-first document store (the reactor) exclusively through the provided tools.",
|
|
83
|
+
"Documents are instances of typed document models; drives are collections that group documents and folders.",
|
|
84
|
+
"Prefer read-only tools to discover state (document models, drives, documents, relationships) before making changes.",
|
|
85
|
+
"Never invent document ids, drive ids, folder ids or document model types — discover them with the read tools first.",
|
|
86
|
+
"When the user refers to 'this', 'here' or 'it' without naming a target, they mean the current selection below; prefer it for create/modify targets."
|
|
87
|
+
];
|
|
88
|
+
const selection = [];
|
|
89
|
+
if (context.driveName) selection.push(`The current drive is "${context.driveName}"` + (context.driveId ? ` (id: ${context.driveId})` : "") + ".");
|
|
90
|
+
if (context.nodeKind === "folder" && context.nodeName) selection.push(`The current folder is "${context.nodeName}".`);
|
|
91
|
+
if (context.documentType) selection.push(`The current document is "${context.documentName ?? "unnamed"}" of type "${context.documentType}".`);
|
|
92
|
+
if (selection.length > 0) lines.push("Current selection:", ...selection.map((s) => `- ${s}`));
|
|
93
|
+
else lines.push("Nothing is currently selected. When the target of an action is ambiguous, ask the user which drive, folder or document it should apply to.");
|
|
94
|
+
return lines.join("\n");
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Runs one tool-loop conversation turn against an OpenAI-compatible model.
|
|
98
|
+
*
|
|
99
|
+
* The agent keeps the model message history across turns. Write tools are
|
|
100
|
+
* gated by the AI SDK's tool approval: when auto-approval is off, the
|
|
101
|
+
* pending user decision is bridged through {@link approve}/{@link reject}.
|
|
102
|
+
*/
|
|
103
|
+
var ReactorChatAgent = class {
|
|
104
|
+
history;
|
|
105
|
+
approvals = /* @__PURE__ */ new Map();
|
|
106
|
+
constructor(options) {
|
|
107
|
+
this.options = options;
|
|
108
|
+
this.history = options.history ?? [];
|
|
109
|
+
}
|
|
110
|
+
/** The model history after the last completed turn, for the next agent. */
|
|
111
|
+
getHistory() {
|
|
112
|
+
return this.history;
|
|
113
|
+
}
|
|
114
|
+
/** Clears the conversation history (a fresh chat). */
|
|
115
|
+
reset() {
|
|
116
|
+
this.history = [];
|
|
117
|
+
this.cancelPendingApprovals();
|
|
118
|
+
}
|
|
119
|
+
/** Approves a pending write tool call, resuming the agent loop. */
|
|
120
|
+
approve(toolCallId) {
|
|
121
|
+
this.resolveApproval(toolCallId, true);
|
|
122
|
+
}
|
|
123
|
+
/** Rejects a pending write tool call; the rejection is fed to the model. */
|
|
124
|
+
reject(toolCallId) {
|
|
125
|
+
this.resolveApproval(toolCallId, false);
|
|
126
|
+
}
|
|
127
|
+
resolveApproval(toolCallId, approved) {
|
|
128
|
+
const resolve = this.approvals.get(toolCallId);
|
|
129
|
+
if (resolve) {
|
|
130
|
+
this.approvals.delete(toolCallId);
|
|
131
|
+
resolve(approved);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
cancelPendingApprovals() {
|
|
135
|
+
for (const resolve of this.approvals.values()) resolve(false);
|
|
136
|
+
this.approvals.clear();
|
|
137
|
+
}
|
|
138
|
+
/** Runs one user turn: appends the message, streams the model, commits history. */
|
|
139
|
+
async send(text) {
|
|
140
|
+
const { onEvent, signal, settings } = this.options;
|
|
141
|
+
const userMessage = {
|
|
142
|
+
role: "user",
|
|
143
|
+
content: text
|
|
144
|
+
};
|
|
145
|
+
const messages = [...this.history, userMessage];
|
|
146
|
+
const tools = {};
|
|
147
|
+
for (const descriptor of this.options.tools) tools[descriptor.name] = tool({
|
|
148
|
+
description: descriptor.description,
|
|
149
|
+
inputSchema: z.object(descriptor.inputSchema),
|
|
150
|
+
execute: async (args) => unwrapToolResult(await descriptor.callback(args))
|
|
151
|
+
});
|
|
152
|
+
const model = this.options.model ?? createReactorChatModel(settings);
|
|
153
|
+
const turnMessages = [];
|
|
154
|
+
const result = streamText({
|
|
155
|
+
model,
|
|
156
|
+
system: buildSystemPrompt(this.options.context),
|
|
157
|
+
messages,
|
|
158
|
+
tools,
|
|
159
|
+
stopWhen: isStepCount(10),
|
|
160
|
+
abortSignal: signal,
|
|
161
|
+
onStepEnd: async (step) => {
|
|
162
|
+
turnMessages.push(...await toResponseMessages({
|
|
163
|
+
content: step.content,
|
|
164
|
+
tools
|
|
165
|
+
}));
|
|
166
|
+
},
|
|
167
|
+
toolApproval: async ({ toolCall }) => {
|
|
168
|
+
if (settings.autoApproveWrites || !isWriteTool(toolCall.toolName)) return "not-applicable";
|
|
169
|
+
const toolCallId = toolCall.toolCallId;
|
|
170
|
+
onEvent({
|
|
171
|
+
type: "approval-request",
|
|
172
|
+
toolCallId,
|
|
173
|
+
name: toolCall.toolName,
|
|
174
|
+
args: toolCall.input
|
|
175
|
+
});
|
|
176
|
+
const approved = await new Promise((resolve) => {
|
|
177
|
+
this.approvals.set(toolCallId, resolve);
|
|
178
|
+
});
|
|
179
|
+
onEvent({
|
|
180
|
+
type: "approval-resolved",
|
|
181
|
+
toolCallId,
|
|
182
|
+
approved
|
|
183
|
+
});
|
|
184
|
+
return approved ? "approved" : {
|
|
185
|
+
type: "denied",
|
|
186
|
+
reason: "The user denied this action. Do not retry it; acknowledge the denial and ask how to proceed."
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
for await (const part of result.fullStream) this.handleStreamPart(part, onEvent);
|
|
191
|
+
this.history = [
|
|
192
|
+
...this.history,
|
|
193
|
+
userMessage,
|
|
194
|
+
...this.dropUnresolvedToolCalls(turnMessages)
|
|
195
|
+
];
|
|
196
|
+
onEvent({ type: "finish" });
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Removes tool calls that were never executed (step cap or abort):
|
|
200
|
+
* OpenAI-compatible APIs reject a tool call without its tool result.
|
|
201
|
+
*/
|
|
202
|
+
dropUnresolvedToolCalls(messages) {
|
|
203
|
+
const resolved = /* @__PURE__ */ new Set();
|
|
204
|
+
for (const m of messages) if (m.role === "tool") {
|
|
205
|
+
for (const part of m.content) if (part.type === "tool-result") resolved.add(part.toolCallId);
|
|
206
|
+
}
|
|
207
|
+
const out = [...messages];
|
|
208
|
+
if (out.length === 0) return out;
|
|
209
|
+
const last = out[out.length - 1];
|
|
210
|
+
if (last.role !== "assistant" || typeof last.content === "string") return out;
|
|
211
|
+
const content = last.content.filter((part) => part.type !== "tool-call" || resolved.has(part.toolCallId));
|
|
212
|
+
if (content.length === 0) out.pop();
|
|
213
|
+
else out[out.length - 1] = {
|
|
214
|
+
...last,
|
|
215
|
+
content
|
|
216
|
+
};
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
handleStreamPart(part, onEvent) {
|
|
220
|
+
const p = part;
|
|
221
|
+
switch (p.type) {
|
|
222
|
+
case "text-delta": {
|
|
223
|
+
const { text } = p;
|
|
224
|
+
onEvent({
|
|
225
|
+
type: "text-delta",
|
|
226
|
+
delta: text
|
|
227
|
+
});
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
case "tool-call": {
|
|
231
|
+
const { toolCallId, toolName, input } = p;
|
|
232
|
+
onEvent({
|
|
233
|
+
type: "tool-start",
|
|
234
|
+
toolCallId,
|
|
235
|
+
name: toolName,
|
|
236
|
+
args: input
|
|
237
|
+
});
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
case "tool-result": {
|
|
241
|
+
const { toolCallId, toolName, output } = p;
|
|
242
|
+
onEvent({
|
|
243
|
+
type: "tool-result",
|
|
244
|
+
toolCallId,
|
|
245
|
+
name: toolName,
|
|
246
|
+
state: "done",
|
|
247
|
+
result: output
|
|
248
|
+
});
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
case "tool-error": {
|
|
252
|
+
const { toolCallId, toolName, error } = p;
|
|
253
|
+
onEvent({
|
|
254
|
+
type: "tool-result",
|
|
255
|
+
toolCallId,
|
|
256
|
+
name: toolName,
|
|
257
|
+
state: "error",
|
|
258
|
+
error: error instanceof Error ? error.message : String(error)
|
|
259
|
+
});
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
case "tool-approval-response": {
|
|
263
|
+
const { approved, toolCall } = p;
|
|
264
|
+
if (!approved) onEvent({
|
|
265
|
+
type: "tool-result",
|
|
266
|
+
toolCallId: toolCall.toolCallId,
|
|
267
|
+
name: toolCall.toolName,
|
|
268
|
+
state: "rejected"
|
|
269
|
+
});
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
case "tool-output-denied": {
|
|
273
|
+
const { toolCallId, toolName } = p;
|
|
274
|
+
onEvent({
|
|
275
|
+
type: "tool-result",
|
|
276
|
+
toolCallId,
|
|
277
|
+
name: toolName,
|
|
278
|
+
state: "rejected"
|
|
279
|
+
});
|
|
280
|
+
break;
|
|
281
|
+
}
|
|
282
|
+
case "abort": break;
|
|
283
|
+
case "error": {
|
|
284
|
+
const { error } = p;
|
|
285
|
+
onEvent({
|
|
286
|
+
type: "error",
|
|
287
|
+
error: error instanceof Error ? error.message : String(error)
|
|
288
|
+
});
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
default: break;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
//#endregion
|
|
296
|
+
//#region src/ai/components/approval-card.tsx
|
|
297
|
+
function formatArgs$1(args) {
|
|
298
|
+
let json;
|
|
299
|
+
try {
|
|
300
|
+
json = JSON.stringify(args, null, 2);
|
|
301
|
+
} catch {
|
|
302
|
+
return String(args);
|
|
303
|
+
}
|
|
304
|
+
return json.length > 400 ? `${json.slice(0, 400)}\n…` : json;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* In-chat approval card for a write tool call. Approving or rejecting
|
|
308
|
+
* resolves the pending approval inside the agent loop.
|
|
309
|
+
*/
|
|
310
|
+
function ApprovalCard({ approval, onApprove, onReject }) {
|
|
311
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
312
|
+
className: "rounded-lg border border-border bg-muted/40 p-3",
|
|
313
|
+
children: [
|
|
314
|
+
/* @__PURE__ */ jsxs("p", {
|
|
315
|
+
className: "mb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground",
|
|
316
|
+
children: ["Approval required — ", approval.name]
|
|
317
|
+
}),
|
|
318
|
+
/* @__PURE__ */ jsx("pre", {
|
|
319
|
+
className: "mb-3 max-h-40 overflow-auto rounded bg-background p-2 text-xs text-foreground",
|
|
320
|
+
children: formatArgs$1(approval.args)
|
|
321
|
+
}),
|
|
322
|
+
/* @__PURE__ */ jsxs("div", {
|
|
323
|
+
className: "flex gap-2",
|
|
324
|
+
children: [/* @__PURE__ */ jsxs("button", {
|
|
325
|
+
type: "button",
|
|
326
|
+
onClick: () => onApprove(approval.toolCallId),
|
|
327
|
+
className: "flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground hover:bg-primary/90",
|
|
328
|
+
children: [/* @__PURE__ */ jsx(Check, { size: 14 }), "Approve"]
|
|
329
|
+
}), /* @__PURE__ */ jsxs("button", {
|
|
330
|
+
type: "button",
|
|
331
|
+
onClick: () => onReject(approval.toolCallId),
|
|
332
|
+
className: "flex items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-sm font-medium text-foreground hover:bg-muted",
|
|
333
|
+
children: [/* @__PURE__ */ jsx(X, { size: 14 }), "Reject"]
|
|
334
|
+
})]
|
|
335
|
+
})
|
|
336
|
+
]
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
//#endregion
|
|
340
|
+
//#region src/ai/components/markdown.tsx
|
|
341
|
+
/**
|
|
342
|
+
* Markdown renderer for assistant messages.
|
|
343
|
+
*
|
|
344
|
+
* Uses react-markdown, which builds React elements from the markdown AST and
|
|
345
|
+
* does not execute raw HTML — safe for model-generated content. remark-gfm
|
|
346
|
+
* adds the table/strikethrough/task-list syntax the agent emits. Element
|
|
347
|
+
* styling is scoped to the chat window's text-sm scale via Tailwind
|
|
348
|
+
* utilities, so no extra CSS is needed.
|
|
349
|
+
*/
|
|
350
|
+
function Markdown({ text }) {
|
|
351
|
+
return /* @__PURE__ */ jsx(ReactMarkdown, {
|
|
352
|
+
remarkPlugins: [remarkGfm],
|
|
353
|
+
components: {
|
|
354
|
+
p: ({ children }) => /* @__PURE__ */ jsx("p", {
|
|
355
|
+
className: "my-1.5 leading-relaxed first:mt-0 last:mb-0",
|
|
356
|
+
children
|
|
357
|
+
}),
|
|
358
|
+
h1: ({ children }) => /* @__PURE__ */ jsx("h1", {
|
|
359
|
+
className: "mb-1 mt-3 font-semibold first:mt-0",
|
|
360
|
+
children
|
|
361
|
+
}),
|
|
362
|
+
h2: ({ children }) => /* @__PURE__ */ jsx("h2", {
|
|
363
|
+
className: "mb-1 mt-3 font-semibold first:mt-0",
|
|
364
|
+
children
|
|
365
|
+
}),
|
|
366
|
+
h3: ({ children }) => /* @__PURE__ */ jsx("h3", {
|
|
367
|
+
className: "mb-1 mt-2.5 font-semibold first:mt-0",
|
|
368
|
+
children
|
|
369
|
+
}),
|
|
370
|
+
ul: ({ children }) => /* @__PURE__ */ jsx("ul", {
|
|
371
|
+
className: "my-1.5 list-disc space-y-0.5 pl-5",
|
|
372
|
+
children
|
|
373
|
+
}),
|
|
374
|
+
ol: ({ children }) => /* @__PURE__ */ jsx("ol", {
|
|
375
|
+
className: "my-1.5 list-decimal space-y-0.5 pl-5",
|
|
376
|
+
children
|
|
377
|
+
}),
|
|
378
|
+
li: ({ children }) => /* @__PURE__ */ jsx("li", {
|
|
379
|
+
className: "leading-relaxed",
|
|
380
|
+
children
|
|
381
|
+
}),
|
|
382
|
+
blockquote: ({ children }) => /* @__PURE__ */ jsx("blockquote", {
|
|
383
|
+
className: "my-1.5 border-l-2 border-border pl-2.5 text-muted-foreground",
|
|
384
|
+
children
|
|
385
|
+
}),
|
|
386
|
+
hr: () => /* @__PURE__ */ jsx("hr", { className: "my-2 border-border" }),
|
|
387
|
+
a: ({ children, href }) => /* @__PURE__ */ jsx("a", {
|
|
388
|
+
href,
|
|
389
|
+
target: "_blank",
|
|
390
|
+
rel: "noreferrer noopener",
|
|
391
|
+
className: "text-primary underline",
|
|
392
|
+
children
|
|
393
|
+
}),
|
|
394
|
+
table: ({ children }) => /* @__PURE__ */ jsx("div", {
|
|
395
|
+
className: "my-1.5 overflow-x-auto",
|
|
396
|
+
children: /* @__PURE__ */ jsx("table", {
|
|
397
|
+
className: "w-full border-collapse text-xs",
|
|
398
|
+
children
|
|
399
|
+
})
|
|
400
|
+
}),
|
|
401
|
+
thead: ({ children }) => /* @__PURE__ */ jsx("thead", { children }),
|
|
402
|
+
th: ({ children }) => /* @__PURE__ */ jsx("th", {
|
|
403
|
+
className: "border border-border bg-muted px-2 py-1 text-left font-semibold",
|
|
404
|
+
children
|
|
405
|
+
}),
|
|
406
|
+
td: ({ children }) => /* @__PURE__ */ jsx("td", {
|
|
407
|
+
className: "border border-border px-2 py-1 align-top",
|
|
408
|
+
children
|
|
409
|
+
}),
|
|
410
|
+
pre: ({ children }) => /* @__PURE__ */ jsx("pre", {
|
|
411
|
+
className: "my-1.5 overflow-x-auto rounded-md bg-muted p-2.5 text-xs leading-relaxed",
|
|
412
|
+
children
|
|
413
|
+
}),
|
|
414
|
+
code: ({ children, className }) => {
|
|
415
|
+
if ((className ?? "").startsWith("language-")) return /* @__PURE__ */ jsx("code", {
|
|
416
|
+
className,
|
|
417
|
+
children
|
|
418
|
+
});
|
|
419
|
+
return /* @__PURE__ */ jsx("code", {
|
|
420
|
+
className: "rounded bg-muted px-1 py-0.5 text-[0.8125rem]",
|
|
421
|
+
children
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
},
|
|
425
|
+
children: text
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
//#endregion
|
|
429
|
+
//#region src/ai/components/chat-window.tsx
|
|
430
|
+
function formatArgs(args) {
|
|
431
|
+
let json;
|
|
432
|
+
try {
|
|
433
|
+
json = JSON.stringify(args);
|
|
434
|
+
} catch {
|
|
435
|
+
return String(args);
|
|
436
|
+
}
|
|
437
|
+
return json.length > 200 ? `${json.slice(0, 200)}…` : json;
|
|
438
|
+
}
|
|
439
|
+
function ToolCard({ part }) {
|
|
440
|
+
const [expanded, setExpanded] = useState(false);
|
|
441
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
442
|
+
className: "rounded-lg border border-border bg-background p-2",
|
|
443
|
+
children: [/* @__PURE__ */ jsxs("button", {
|
|
444
|
+
type: "button",
|
|
445
|
+
onClick: () => setExpanded((e) => !e),
|
|
446
|
+
className: "flex w-full items-center gap-2 text-left text-xs text-foreground",
|
|
447
|
+
children: [
|
|
448
|
+
part.state === "done" && /* @__PURE__ */ jsx(Check, {
|
|
449
|
+
size: 13,
|
|
450
|
+
className: "shrink-0 text-info"
|
|
451
|
+
}),
|
|
452
|
+
part.state === "error" && /* @__PURE__ */ jsx(X, {
|
|
453
|
+
size: 13,
|
|
454
|
+
className: "shrink-0 text-destructive"
|
|
455
|
+
}),
|
|
456
|
+
part.state === "rejected" && /* @__PURE__ */ jsx(X, {
|
|
457
|
+
size: 13,
|
|
458
|
+
className: "shrink-0 text-muted-foreground"
|
|
459
|
+
}),
|
|
460
|
+
part.state === "executing" && /* @__PURE__ */ jsx("span", {
|
|
461
|
+
className: "shrink-0 text-muted-foreground",
|
|
462
|
+
children: "⋯"
|
|
463
|
+
}),
|
|
464
|
+
/* @__PURE__ */ jsxs("span", {
|
|
465
|
+
className: "font-mono text-muted-foreground",
|
|
466
|
+
children: [
|
|
467
|
+
part.name,
|
|
468
|
+
"(",
|
|
469
|
+
formatArgs(part.args),
|
|
470
|
+
")"
|
|
471
|
+
]
|
|
472
|
+
})
|
|
473
|
+
]
|
|
474
|
+
}), expanded && /* @__PURE__ */ jsx("pre", {
|
|
475
|
+
className: "mt-2 max-h-40 overflow-auto rounded bg-muted p-2 text-xs text-foreground",
|
|
476
|
+
children: JSON.stringify({
|
|
477
|
+
args: part.args,
|
|
478
|
+
result: part.result,
|
|
479
|
+
error: part.error
|
|
480
|
+
}, null, 2)
|
|
481
|
+
})]
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
function MessageView({ message, onApprove, onReject }) {
|
|
485
|
+
if (message.role === "user") return /* @__PURE__ */ jsx("div", {
|
|
486
|
+
className: "flex justify-end",
|
|
487
|
+
children: /* @__PURE__ */ jsx("div", {
|
|
488
|
+
className: "max-w-[85%] whitespace-pre-wrap rounded-lg bg-muted px-3 py-2 text-sm text-foreground",
|
|
489
|
+
children: message.parts.filter((p) => p.type === "text").map((p) => p.text).join("")
|
|
490
|
+
})
|
|
491
|
+
});
|
|
492
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
493
|
+
className: "space-y-2",
|
|
494
|
+
children: [message.parts.map((part, index) => part.type === "text" ? /* @__PURE__ */ jsx("div", {
|
|
495
|
+
className: "text-sm text-foreground",
|
|
496
|
+
children: /* @__PURE__ */ jsx(Markdown, { text: part.text })
|
|
497
|
+
}, index) : /* @__PURE__ */ jsxs("div", {
|
|
498
|
+
className: "space-y-2",
|
|
499
|
+
children: [/* @__PURE__ */ jsx(ToolCard, { part }), part.state === "awaiting-approval" && /* @__PURE__ */ jsx(ApprovalCard, {
|
|
500
|
+
approval: {
|
|
501
|
+
toolCallId: part.toolCallId,
|
|
502
|
+
name: part.name,
|
|
503
|
+
args: part.args
|
|
504
|
+
},
|
|
505
|
+
onApprove,
|
|
506
|
+
onReject
|
|
507
|
+
})]
|
|
508
|
+
}, part.toolCallId)), message.parts.length === 0 && /* @__PURE__ */ jsx("div", {
|
|
509
|
+
className: "text-sm text-muted-foreground",
|
|
510
|
+
children: "Thinking…"
|
|
511
|
+
})]
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
/** The chat window panel, anchored above the FAB in the bottom-right. */
|
|
515
|
+
function ChatWindow({ chat, onClose }) {
|
|
516
|
+
const [fullscreen, setFullscreen] = useState(false);
|
|
517
|
+
const [draft, setDraft] = useState("");
|
|
518
|
+
const listRef = useRef(null);
|
|
519
|
+
useEffect(() => {
|
|
520
|
+
const el = listRef.current;
|
|
521
|
+
if (el) el.scrollTo({ top: el.scrollHeight });
|
|
522
|
+
}, [chat.messages]);
|
|
523
|
+
useEffect(() => {
|
|
524
|
+
if (!fullscreen) return;
|
|
525
|
+
const onKey = (event) => {
|
|
526
|
+
if (event.key === "Escape") setFullscreen(false);
|
|
527
|
+
};
|
|
528
|
+
window.addEventListener("keydown", onKey);
|
|
529
|
+
return () => window.removeEventListener("keydown", onKey);
|
|
530
|
+
}, [fullscreen]);
|
|
531
|
+
const submit = () => {
|
|
532
|
+
const text = draft;
|
|
533
|
+
setDraft("");
|
|
534
|
+
chat.send(text);
|
|
535
|
+
};
|
|
536
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
537
|
+
className: fullscreen ? "fixed inset-0 z-50 flex flex-col overflow-hidden bg-background" : "fixed bottom-24 right-6 z-40 flex max-h-[min(28rem,calc(100vh-8rem))] w-[min(24rem,calc(100vw-3rem))] flex-col overflow-hidden rounded-xl border border-border bg-background shadow-2xl",
|
|
538
|
+
children: [
|
|
539
|
+
/* @__PURE__ */ jsxs("div", {
|
|
540
|
+
className: "flex items-center justify-between border-b border-border px-4 py-2.5",
|
|
541
|
+
children: [/* @__PURE__ */ jsx("span", {
|
|
542
|
+
className: "text-sm font-semibold text-foreground",
|
|
543
|
+
children: "AI Assistant"
|
|
544
|
+
}), /* @__PURE__ */ jsxs("div", {
|
|
545
|
+
className: "flex items-center gap-1 text-muted-foreground",
|
|
546
|
+
children: [
|
|
547
|
+
/* @__PURE__ */ jsx("button", {
|
|
548
|
+
type: "button",
|
|
549
|
+
"aria-label": fullscreen ? "Exit fullscreen" : "Fullscreen",
|
|
550
|
+
title: fullscreen ? "Exit fullscreen (Esc)" : "Fullscreen",
|
|
551
|
+
onClick: () => setFullscreen((f) => !f),
|
|
552
|
+
className: "rounded p-1 hover:bg-muted hover:text-foreground",
|
|
553
|
+
children: fullscreen ? /* @__PURE__ */ jsx(Minimize2, { size: 15 }) : /* @__PURE__ */ jsx(Maximize2, { size: 15 })
|
|
554
|
+
}),
|
|
555
|
+
/* @__PURE__ */ jsx("button", {
|
|
556
|
+
type: "button",
|
|
557
|
+
"aria-label": "Clear conversation",
|
|
558
|
+
title: "New chat",
|
|
559
|
+
onClick: chat.clear,
|
|
560
|
+
className: "rounded p-1 hover:bg-muted hover:text-foreground",
|
|
561
|
+
children: /* @__PURE__ */ jsx(Trash2, { size: 15 })
|
|
562
|
+
}),
|
|
563
|
+
/* @__PURE__ */ jsx("button", {
|
|
564
|
+
type: "button",
|
|
565
|
+
"aria-label": "Close AI chat",
|
|
566
|
+
title: "Close",
|
|
567
|
+
onClick: onClose,
|
|
568
|
+
className: "rounded p-1 hover:bg-muted hover:text-foreground",
|
|
569
|
+
children: /* @__PURE__ */ jsx(X, { size: 15 })
|
|
570
|
+
})
|
|
571
|
+
]
|
|
572
|
+
})]
|
|
573
|
+
}),
|
|
574
|
+
/* @__PURE__ */ jsxs("div", {
|
|
575
|
+
ref: listRef,
|
|
576
|
+
className: "flex-1 space-y-3 overflow-y-auto px-4 py-3",
|
|
577
|
+
children: [
|
|
578
|
+
chat.messages.length === 0 && /* @__PURE__ */ jsx("div", {
|
|
579
|
+
className: "pt-8 text-center text-sm text-muted-foreground",
|
|
580
|
+
children: chat.configured ? /* @__PURE__ */ jsx("p", { children: "Ask the assistant to create or change documents, manage drives, or inspect read models." }) : /* @__PURE__ */ jsx("p", { children: "Add your OpenAI-compatible endpoint under Settings → AI Assistant, then start a conversation." })
|
|
581
|
+
}),
|
|
582
|
+
chat.messages.map((message) => /* @__PURE__ */ jsx(MessageView, {
|
|
583
|
+
message,
|
|
584
|
+
onApprove: chat.approve,
|
|
585
|
+
onReject: chat.reject
|
|
586
|
+
}, message.id)),
|
|
587
|
+
chat.error && /* @__PURE__ */ jsx("div", {
|
|
588
|
+
className: "rounded-lg border border-destructive/40 bg-destructive/10 p-2 text-xs text-destructive",
|
|
589
|
+
children: chat.error
|
|
590
|
+
})
|
|
591
|
+
]
|
|
592
|
+
}),
|
|
593
|
+
/* @__PURE__ */ jsx("div", {
|
|
594
|
+
className: "border-t border-border p-3",
|
|
595
|
+
children: /* @__PURE__ */ jsxs("div", {
|
|
596
|
+
className: "flex items-end gap-2",
|
|
597
|
+
children: [/* @__PURE__ */ jsx("textarea", {
|
|
598
|
+
rows: 2,
|
|
599
|
+
value: draft,
|
|
600
|
+
onChange: (e) => setDraft(e.target.value),
|
|
601
|
+
onKeyDown: (e) => {
|
|
602
|
+
if (e.key === "Enter" && !e.shiftKey) {
|
|
603
|
+
e.preventDefault();
|
|
604
|
+
submit();
|
|
605
|
+
}
|
|
606
|
+
},
|
|
607
|
+
placeholder: chat.configured ? "Ask the assistant… (Enter to send)" : "Configure the endpoint in settings first",
|
|
608
|
+
className: "max-h-32 min-h-[2.5rem] flex-1 resize-none rounded-md border border-border bg-background p-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none",
|
|
609
|
+
disabled: chat.isStreaming
|
|
610
|
+
}), chat.isStreaming ? /* @__PURE__ */ jsx("button", {
|
|
611
|
+
type: "button",
|
|
612
|
+
"aria-label": "Stop generating",
|
|
613
|
+
title: "Stop",
|
|
614
|
+
onClick: chat.stop,
|
|
615
|
+
className: "flex size-9 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground hover:bg-primary/90",
|
|
616
|
+
children: /* @__PURE__ */ jsx(Square, { size: 15 })
|
|
617
|
+
}) : /* @__PURE__ */ jsx("button", {
|
|
618
|
+
type: "button",
|
|
619
|
+
"aria-label": "Send message",
|
|
620
|
+
title: "Send",
|
|
621
|
+
onClick: submit,
|
|
622
|
+
disabled: !draft.trim() || !chat.configured,
|
|
623
|
+
className: "flex size-9 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:disabled-effect",
|
|
624
|
+
children: /* @__PURE__ */ jsx(ArrowUp, { size: 15 })
|
|
625
|
+
})]
|
|
626
|
+
})
|
|
627
|
+
})
|
|
628
|
+
]
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
//#endregion
|
|
632
|
+
//#region src/ai/settings-store.ts
|
|
633
|
+
const STORAGE_KEY = "ph-ai-chat-settings";
|
|
634
|
+
const DEFAULT_AI_SETTINGS = {
|
|
635
|
+
enabled: false,
|
|
636
|
+
baseUrl: "",
|
|
637
|
+
apiKey: "",
|
|
638
|
+
model: "",
|
|
639
|
+
autoApproveWrites: false
|
|
640
|
+
};
|
|
641
|
+
let snapshot = load();
|
|
642
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
643
|
+
function load() {
|
|
644
|
+
if (typeof localStorage === "undefined") return { ...DEFAULT_AI_SETTINGS };
|
|
645
|
+
try {
|
|
646
|
+
const raw = localStorage.getItem(STORAGE_KEY);
|
|
647
|
+
if (!raw) return { ...DEFAULT_AI_SETTINGS };
|
|
648
|
+
const parsed = JSON.parse(raw);
|
|
649
|
+
return {
|
|
650
|
+
enabled: typeof parsed.enabled === "boolean" ? parsed.enabled : false,
|
|
651
|
+
baseUrl: typeof parsed.baseUrl === "string" ? parsed.baseUrl : "",
|
|
652
|
+
apiKey: typeof parsed.apiKey === "string" ? parsed.apiKey : "",
|
|
653
|
+
model: typeof parsed.model === "string" ? parsed.model : "",
|
|
654
|
+
autoApproveWrites: typeof parsed.autoApproveWrites === "boolean" ? parsed.autoApproveWrites : false
|
|
655
|
+
};
|
|
656
|
+
} catch {
|
|
657
|
+
return { ...DEFAULT_AI_SETTINGS };
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
function persist(settings) {
|
|
661
|
+
try {
|
|
662
|
+
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
|
|
663
|
+
} catch {}
|
|
664
|
+
}
|
|
665
|
+
function emit() {
|
|
666
|
+
for (const listener of listeners) listener();
|
|
667
|
+
}
|
|
668
|
+
/** Returns the current settings (stable snapshot for useSyncExternalStore). */
|
|
669
|
+
function getAiSettings() {
|
|
670
|
+
return snapshot;
|
|
671
|
+
}
|
|
672
|
+
/** Merges a partial update, persists, and notifies subscribers. */
|
|
673
|
+
function updateAiSettings(patch) {
|
|
674
|
+
snapshot = {
|
|
675
|
+
...snapshot,
|
|
676
|
+
...patch
|
|
677
|
+
};
|
|
678
|
+
persist(snapshot);
|
|
679
|
+
emit();
|
|
680
|
+
return snapshot;
|
|
681
|
+
}
|
|
682
|
+
/** Clears all stored settings. */
|
|
683
|
+
function clearAiSettings() {
|
|
684
|
+
snapshot = { ...DEFAULT_AI_SETTINGS };
|
|
685
|
+
try {
|
|
686
|
+
localStorage.removeItem(STORAGE_KEY);
|
|
687
|
+
} catch {}
|
|
688
|
+
emit();
|
|
689
|
+
}
|
|
690
|
+
/** Subscribes to settings changes. Returns the unsubscribe function. */
|
|
691
|
+
function subscribeAiSettings(listener) {
|
|
692
|
+
listeners.add(listener);
|
|
693
|
+
return () => {
|
|
694
|
+
listeners.delete(listener);
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
/** True when the endpoint, key and model are all configured. */
|
|
698
|
+
function isAiConfigured(settings) {
|
|
699
|
+
return settings.baseUrl.trim().length > 0 && settings.apiKey.trim().length > 0 && settings.model.trim().length > 0;
|
|
700
|
+
}
|
|
701
|
+
//#endregion
|
|
702
|
+
//#region src/ai/context.ts
|
|
703
|
+
/**
|
|
704
|
+
* Snapshot of the current selection in the drive explorer, used to make the
|
|
705
|
+
* chat context-aware: "create a budget here" targets the selected drive,
|
|
706
|
+
* "summarize this document" targets the selected document.
|
|
707
|
+
*/
|
|
708
|
+
function useChatContext() {
|
|
709
|
+
const [drive] = useSelectedDriveSafe();
|
|
710
|
+
const node = useSelectedNode();
|
|
711
|
+
const documentId = useSelectedDocumentId();
|
|
712
|
+
const context = {
|
|
713
|
+
driveId: drive?.header.id,
|
|
714
|
+
driveName: drive?.header.name
|
|
715
|
+
};
|
|
716
|
+
if (node) {
|
|
717
|
+
context.nodeId = node.id;
|
|
718
|
+
context.nodeName = node.name;
|
|
719
|
+
if (isFolderNode(node)) context.nodeKind = "folder";
|
|
720
|
+
else if (isFileNode(node)) context.nodeKind = "file";
|
|
721
|
+
}
|
|
722
|
+
if (documentId && node && isFileNode(node)) {
|
|
723
|
+
context.documentName = node.name;
|
|
724
|
+
context.documentType = node.documentType;
|
|
725
|
+
}
|
|
726
|
+
return context;
|
|
727
|
+
}
|
|
728
|
+
//#endregion
|
|
729
|
+
//#region src/ai/use-reactor-chat.ts
|
|
730
|
+
function updateAssistantPart(messages, assistantId, update) {
|
|
731
|
+
if (!assistantId) return messages;
|
|
732
|
+
return messages.map((message) => message.id === assistantId ? {
|
|
733
|
+
...message,
|
|
734
|
+
parts: update(message.parts)
|
|
735
|
+
} : message);
|
|
736
|
+
}
|
|
737
|
+
function toErrorMessage(error) {
|
|
738
|
+
return error instanceof Error ? error.message : String(error);
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Drives one in-browser chat conversation against the reactor tools.
|
|
742
|
+
*
|
|
743
|
+
* `toolsProvider` lazily resolves the tool descriptors (e.g. from
|
|
744
|
+
* `createReactorMcpProvider` bound to `window.ph.reactorClient`) when the
|
|
745
|
+
* user sends a message, so the reactor does not need to be ready at render
|
|
746
|
+
* time.
|
|
747
|
+
*/
|
|
748
|
+
function useReactorChat(toolsProvider) {
|
|
749
|
+
const [messages, setMessages] = useState([]);
|
|
750
|
+
const [isStreaming, setIsStreaming] = useState(false);
|
|
751
|
+
const [pendingApprovals, setPendingApprovals] = useState([]);
|
|
752
|
+
const [error, setError] = useState(null);
|
|
753
|
+
const agentRef = useRef(null);
|
|
754
|
+
const abortRef = useRef(null);
|
|
755
|
+
const streamingRef = useRef(false);
|
|
756
|
+
const pendingRef = useRef(/* @__PURE__ */ new Set());
|
|
757
|
+
const assistantIdRef = useRef(null);
|
|
758
|
+
const historyRef = useRef([]);
|
|
759
|
+
const settings = useSyncExternalStore(subscribeAiSettings, getAiSettings);
|
|
760
|
+
const context = useChatContext();
|
|
761
|
+
const handleEvent = useCallback((event) => {
|
|
762
|
+
const assistantId = assistantIdRef.current;
|
|
763
|
+
switch (event.type) {
|
|
764
|
+
case "text-delta":
|
|
765
|
+
setMessages((prev) => updateAssistantPart(prev, assistantId, (parts) => {
|
|
766
|
+
const last = parts[parts.length - 1];
|
|
767
|
+
if (last?.type === "text") return [...parts.slice(0, -1), {
|
|
768
|
+
...last,
|
|
769
|
+
text: last.text + event.delta
|
|
770
|
+
}];
|
|
771
|
+
return [...parts, {
|
|
772
|
+
type: "text",
|
|
773
|
+
text: event.delta
|
|
774
|
+
}];
|
|
775
|
+
}));
|
|
776
|
+
break;
|
|
777
|
+
case "tool-start":
|
|
778
|
+
setMessages((prev) => updateAssistantPart(prev, assistantId, (parts) => [...parts, {
|
|
779
|
+
type: "tool",
|
|
780
|
+
toolCallId: event.toolCallId,
|
|
781
|
+
name: event.name,
|
|
782
|
+
args: event.args,
|
|
783
|
+
state: pendingRef.current.has(event.toolCallId) ? "awaiting-approval" : "executing"
|
|
784
|
+
}]));
|
|
785
|
+
break;
|
|
786
|
+
case "approval-request":
|
|
787
|
+
pendingRef.current.add(event.toolCallId);
|
|
788
|
+
setMessages((prev) => updateAssistantPart(prev, assistantId, (parts) => parts.map((part) => part.type === "tool" && part.toolCallId === event.toolCallId ? {
|
|
789
|
+
...part,
|
|
790
|
+
state: "awaiting-approval"
|
|
791
|
+
} : part)));
|
|
792
|
+
setPendingApprovals((prev) => [...prev, {
|
|
793
|
+
toolCallId: event.toolCallId,
|
|
794
|
+
name: event.name,
|
|
795
|
+
args: event.args
|
|
796
|
+
}]);
|
|
797
|
+
break;
|
|
798
|
+
case "approval-resolved":
|
|
799
|
+
pendingRef.current.delete(event.toolCallId);
|
|
800
|
+
setPendingApprovals((prev) => prev.filter((a) => a.toolCallId !== event.toolCallId));
|
|
801
|
+
if (!event.approved) setMessages((prev) => updateAssistantPart(prev, assistantId, (parts) => parts.map((part) => part.type === "tool" && part.toolCallId === event.toolCallId ? {
|
|
802
|
+
...part,
|
|
803
|
+
state: "rejected"
|
|
804
|
+
} : part)));
|
|
805
|
+
break;
|
|
806
|
+
case "tool-result":
|
|
807
|
+
setMessages((prev) => updateAssistantPart(prev, assistantId, (parts) => parts.map((part) => part.type === "tool" && part.toolCallId === event.toolCallId ? {
|
|
808
|
+
...part,
|
|
809
|
+
state: event.state,
|
|
810
|
+
result: event.result,
|
|
811
|
+
error: event.error
|
|
812
|
+
} : part)));
|
|
813
|
+
break;
|
|
814
|
+
case "error":
|
|
815
|
+
setError(event.error);
|
|
816
|
+
break;
|
|
817
|
+
case "finish": break;
|
|
818
|
+
}
|
|
819
|
+
}, []);
|
|
820
|
+
const send = useCallback((text) => {
|
|
821
|
+
const trimmed = text.trim();
|
|
822
|
+
if (!trimmed || streamingRef.current) return;
|
|
823
|
+
setError(null);
|
|
824
|
+
const currentSettings = getAiSettings();
|
|
825
|
+
if (!isAiConfigured(currentSettings)) {
|
|
826
|
+
setError("Configure the AI endpoint, API key and model in settings first.");
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
(async () => {
|
|
830
|
+
let tools;
|
|
831
|
+
try {
|
|
832
|
+
if (!toolsProvider) throw new Error("No tool provider configured");
|
|
833
|
+
tools = await toolsProvider();
|
|
834
|
+
} catch (toolError) {
|
|
835
|
+
setError(`Could not initialise the reactor tools: ${toErrorMessage(toolError)}`);
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
if (tools.length === 0) {
|
|
839
|
+
setError("The reactor exposed no tools.");
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
const controller = new AbortController();
|
|
843
|
+
abortRef.current = controller;
|
|
844
|
+
const agent = new ReactorChatAgent({
|
|
845
|
+
settings: currentSettings,
|
|
846
|
+
tools,
|
|
847
|
+
context,
|
|
848
|
+
onEvent: handleEvent,
|
|
849
|
+
signal: controller.signal,
|
|
850
|
+
history: historyRef.current
|
|
851
|
+
});
|
|
852
|
+
agentRef.current = agent;
|
|
853
|
+
const assistantId = crypto.randomUUID();
|
|
854
|
+
assistantIdRef.current = assistantId;
|
|
855
|
+
setMessages((prev) => [
|
|
856
|
+
...prev,
|
|
857
|
+
{
|
|
858
|
+
id: crypto.randomUUID(),
|
|
859
|
+
role: "user",
|
|
860
|
+
parts: [{
|
|
861
|
+
type: "text",
|
|
862
|
+
text: trimmed
|
|
863
|
+
}]
|
|
864
|
+
},
|
|
865
|
+
{
|
|
866
|
+
id: assistantId,
|
|
867
|
+
role: "assistant",
|
|
868
|
+
parts: []
|
|
869
|
+
}
|
|
870
|
+
]);
|
|
871
|
+
streamingRef.current = true;
|
|
872
|
+
setIsStreaming(true);
|
|
873
|
+
try {
|
|
874
|
+
await agent.send(trimmed);
|
|
875
|
+
} catch (sendError) {
|
|
876
|
+
setError(toErrorMessage(sendError));
|
|
877
|
+
} finally {
|
|
878
|
+
streamingRef.current = false;
|
|
879
|
+
setIsStreaming(false);
|
|
880
|
+
abortRef.current = null;
|
|
881
|
+
historyRef.current = agent.getHistory();
|
|
882
|
+
}
|
|
883
|
+
})();
|
|
884
|
+
}, [
|
|
885
|
+
toolsProvider,
|
|
886
|
+
context,
|
|
887
|
+
handleEvent
|
|
888
|
+
]);
|
|
889
|
+
const stop = useCallback(() => {
|
|
890
|
+
abortRef.current?.abort();
|
|
891
|
+
}, []);
|
|
892
|
+
const approve = useCallback((toolCallId) => {
|
|
893
|
+
agentRef.current?.approve(toolCallId);
|
|
894
|
+
}, []);
|
|
895
|
+
const reject = useCallback((toolCallId) => {
|
|
896
|
+
agentRef.current?.reject(toolCallId);
|
|
897
|
+
}, []);
|
|
898
|
+
const clear = useCallback(() => {
|
|
899
|
+
abortRef.current?.abort();
|
|
900
|
+
agentRef.current?.reset();
|
|
901
|
+
agentRef.current = null;
|
|
902
|
+
historyRef.current = [];
|
|
903
|
+
pendingRef.current.clear();
|
|
904
|
+
setPendingApprovals([]);
|
|
905
|
+
setError(null);
|
|
906
|
+
assistantIdRef.current = null;
|
|
907
|
+
}, []);
|
|
908
|
+
return {
|
|
909
|
+
messages,
|
|
910
|
+
isStreaming,
|
|
911
|
+
pendingApprovals,
|
|
912
|
+
error,
|
|
913
|
+
settings,
|
|
914
|
+
configured: isAiConfigured(settings),
|
|
915
|
+
send,
|
|
916
|
+
stop,
|
|
917
|
+
approve,
|
|
918
|
+
reject,
|
|
919
|
+
clear
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
//#endregion
|
|
923
|
+
//#region src/ai/components/reactor-chat-fab.tsx
|
|
924
|
+
/**
|
|
925
|
+
* Bottom-right floating action button that opens the reactor AI chat window.
|
|
926
|
+
*
|
|
927
|
+
* `getTools` lazily resolves the reactor tool descriptors (from
|
|
928
|
+
* `createReactorMcpProvider` bound to the browser reactor client) when the
|
|
929
|
+
* user sends a message.
|
|
930
|
+
*/
|
|
931
|
+
function ReactorChatFab({ getTools }) {
|
|
932
|
+
const settings = useSyncExternalStore(subscribeAiSettings, getAiSettings);
|
|
933
|
+
const [open, setOpen] = useState(false);
|
|
934
|
+
const chat = useReactorChat(getTools);
|
|
935
|
+
if (!settings.enabled) return null;
|
|
936
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("button", {
|
|
937
|
+
type: "button",
|
|
938
|
+
"aria-label": open ? "Close AI chat" : "Open AI chat",
|
|
939
|
+
title: open ? "Close AI chat" : "AI chat",
|
|
940
|
+
onClick: () => setOpen((o) => !o),
|
|
941
|
+
className: "fixed bottom-6 right-6 z-40 flex size-12 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-transform hover:scale-105 disabled:disabled-effect",
|
|
942
|
+
children: open ? /* @__PURE__ */ jsx(X, { size: 20 }) : /* @__PURE__ */ jsx(MessageCircle, { size: 20 })
|
|
943
|
+
}), open && /* @__PURE__ */ jsx(ChatWindow, {
|
|
944
|
+
chat,
|
|
945
|
+
onClose: () => setOpen(false)
|
|
946
|
+
})] });
|
|
947
|
+
}
|
|
948
|
+
//#endregion
|
|
949
|
+
export { ApprovalCard, ChatWindow, DEFAULT_AI_SETTINGS, MAX_AGENT_STEPS, ReactorChatAgent, ReactorChatFab, WRITE_TOOLS, buildSystemPrompt, clearAiSettings, createReactorChatModel, getAiSettings, isAiConfigured, isWriteTool, subscribeAiSettings, unwrapToolResult, updateAiSettings, useChatContext, useReactorChat };
|
|
950
|
+
|
|
951
|
+
//# sourceMappingURL=index.js.map
|