@field-studio/sdk 0.0.0-stage → 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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +131 -2
  3. package/dist/index.d.ts +97 -0
  4. package/dist/index.js +129 -0
  5. package/dist/node/identity.d.ts +89 -0
  6. package/dist/node/identity.js +1 -0
  7. package/dist/node/index.d.ts +41 -0
  8. package/dist/node/index.js +165 -0
  9. package/dist/react/agent/AgentEditor.d.ts +16 -0
  10. package/dist/react/agent/AgentEditor.js +51 -0
  11. package/dist/react/agent/MCPManager.d.ts +12 -0
  12. package/dist/react/agent/MCPManager.js +72 -0
  13. package/dist/react/agent/SkillImport.d.ts +8 -0
  14. package/dist/react/agent/SkillImport.js +31 -0
  15. package/dist/react/agent/SkillViewer.d.ts +7 -0
  16. package/dist/react/agent/SkillViewer.js +61 -0
  17. package/dist/react/agent/catalog.css +205 -0
  18. package/dist/react/agent/index.d.ts +7 -0
  19. package/dist/react/agent/index.js +5 -0
  20. package/dist/react/agent/skillTitle.d.ts +3 -0
  21. package/dist/react/agent/skillTitle.js +4 -0
  22. package/dist/react/agent/types.d.ts +46 -0
  23. package/dist/react/agent/types.js +1 -0
  24. package/dist/react/assistant/AssistantPanel.d.ts +15 -0
  25. package/dist/react/assistant/AssistantPanel.js +144 -0
  26. package/dist/react/assistant/AssistantProvider.d.ts +119 -0
  27. package/dist/react/assistant/AssistantProvider.js +427 -0
  28. package/dist/react/assistant/QuestionPanel.d.ts +8 -0
  29. package/dist/react/assistant/QuestionPanel.js +32 -0
  30. package/dist/react/assistant/TaskComposer.d.ts +25 -0
  31. package/dist/react/assistant/TaskComposer.js +354 -0
  32. package/dist/react/assistant/TaskFiles.d.ts +24 -0
  33. package/dist/react/assistant/TaskFiles.js +107 -0
  34. package/dist/react/assistant/assistant.css +428 -0
  35. package/dist/react/assistant/composer.css +116 -0
  36. package/dist/react/assistant/files.css +19 -0
  37. package/dist/react/assistant/index.d.ts +10 -0
  38. package/dist/react/assistant/index.js +6 -0
  39. package/dist/react/assistant/layout.d.ts +7 -0
  40. package/dist/react/assistant/layout.js +19 -0
  41. package/dist/react/assistant/messages.d.ts +355 -0
  42. package/dist/react/assistant/messages.js +239 -0
  43. package/dist/react/assistant/questions.css +6 -0
  44. package/dist/react/assistant/types.d.ts +85 -0
  45. package/dist/react/assistant/types.js +1 -0
  46. package/dist/react/auth/AuthShell.d.ts +37 -0
  47. package/dist/react/auth/AuthShell.js +287 -0
  48. package/dist/react/auth/RoleManager.d.ts +23 -0
  49. package/dist/react/auth/RoleManager.js +95 -0
  50. package/dist/react/auth/auth.css +76 -0
  51. package/dist/react/auth/index.d.ts +2 -0
  52. package/dist/react/auth/index.js +1 -0
  53. package/dist/react/index.d.ts +57 -0
  54. package/dist/react/index.js +177 -0
  55. package/dist/react/ui/Controls.d.ts +78 -0
  56. package/dist/react/ui/Controls.js +234 -0
  57. package/dist/react/ui/base.css +261 -0
  58. package/dist/react/ui/controls.css +35 -0
  59. package/dist/react/ui/index.d.ts +2 -0
  60. package/dist/react/ui/index.js +2 -0
  61. package/dist/workspace.d.ts +107 -0
  62. package/dist/workspace.js +139 -0
  63. package/package.json +86 -3
@@ -0,0 +1,354 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { usePlatform } from '../index.js';
3
+ import { Fragment, useEffect, useLayoutEffect, useRef, useState } from 'react';
4
+ import { ArrowUp, Download, FileText, FolderOpen, Loader2, Plus, RefreshCw, Square, Trash2, Upload, X, } from 'lucide-react';
5
+ import { Dialog } from '../ui/index.js';
6
+ import { useAssistantDisplay } from './messages.js';
7
+ import { FilePreview, previewKind, validateAttachments } from './TaskFiles.js';
8
+ import './composer.css';
9
+ const promptLimit = 6000;
10
+ const fileLabel = (file) => file.relative_path ?? file.name;
11
+ function editMentions(mentions, start, end, length) {
12
+ const offset = start + length - end;
13
+ return mentions.flatMap((mention) => {
14
+ if (mention.end <= start)
15
+ return [mention];
16
+ if (mention.start >= end)
17
+ return [{ ...mention, start: mention.start + offset, end: mention.end + offset }];
18
+ return [];
19
+ });
20
+ }
21
+ function mentionsAfterInput(mentions, prompt, next, caret) {
22
+ if (!mentions.length)
23
+ return mentions;
24
+ let end = prompt.length;
25
+ let nextEnd = next.length;
26
+ // Anchor the unchanged suffix to the caret so identical text inserted before
27
+ // a mention does not inherit its target.
28
+ const suffix = next.slice(caret);
29
+ const anchored = prompt.endsWith(suffix);
30
+ if (anchored) {
31
+ end -= suffix.length;
32
+ nextEnd = caret;
33
+ }
34
+ let start = 0;
35
+ while (start < end && start < nextEnd && prompt[start] === next[start])
36
+ start++;
37
+ if (!anchored) {
38
+ while (start < end && start < nextEnd && prompt[end - 1] === next[nextEnd - 1]) {
39
+ end--;
40
+ nextEnd--;
41
+ }
42
+ }
43
+ return editMentions(mentions, start, end, nextEnd - start);
44
+ }
45
+ /** Compose a task with explicit skills and immutable references to persistent workspace files. */
46
+ export default function TaskComposer({ prompt, onPrompt, attachments, onAttachments, skills, agents = [], busy, available, sandbox, uploadStatus, running = false, onStop, onSubmit, }) {
47
+ const { name, locale, messages } = useAssistantDisplay();
48
+ const platform = usePlatform();
49
+ const workspaceRequest = (url, init) => platform.request(url, init);
50
+ const [selectedSkills, setSelectedSkills] = useState([]);
51
+ const [draft, setDraft] = useState({
52
+ prompt,
53
+ mentions: [],
54
+ });
55
+ if (draft.prompt !== prompt)
56
+ setDraft({ prompt, mentions: [] });
57
+ const mentions = draft.prompt === prompt ? draft.mentions : [];
58
+ const selectedAgents = mentions.flatMap((mention) => mention.kind === 'agent' ? [mention.id] : []);
59
+ const selectedFiles = [
60
+ ...new Map(mentions.flatMap((mention) => mention.kind === 'files'
61
+ ? mention.files.map((file) => [file.id, file])
62
+ : [])).values(),
63
+ ];
64
+ const [files, setFiles] = useState([]);
65
+ const [panel, setPanel] = useState(false);
66
+ const [loading, setLoading] = useState(false);
67
+ const [working, setWorking] = useState(false);
68
+ const [error, setError] = useState('');
69
+ const [dragging, setDragging] = useState(false);
70
+ const [caret, setCaret] = useState(0);
71
+ const [dismissed, setDismissed] = useState(false);
72
+ const [active, setActive] = useState(0);
73
+ const [preview, setPreview] = useState(null);
74
+ const input = useRef(null);
75
+ const highlights = useRef(null);
76
+ const pendingCaret = useRef(null);
77
+ const picker = useRef(null);
78
+ const workspacePicker = useRef(null);
79
+ const folderPicker = useRef(null);
80
+ const [workspaceStatus, setWorkspaceStatus] = useState('');
81
+ const disabled = busy || !available || working;
82
+ const match = prompt.slice(0, caret).match(/(?:^|\s)([/@])([^\s@]*)$/);
83
+ const queryStart = match ? caret - match[2].length - 1 : caret;
84
+ const mode = !disabled &&
85
+ !panel &&
86
+ !dismissed &&
87
+ match &&
88
+ !mentions.some(({ start, end }) => queryStart < end && caret > start)
89
+ ? match[1]
90
+ : null;
91
+ const query = (match?.[2] ?? '').toLowerCase();
92
+ const folderMap = new Map();
93
+ for (const file of files) {
94
+ const parts = fileLabel(file).split('/');
95
+ for (let i = 1; i < parts.length; i++) {
96
+ const name = parts.slice(0, i).join('/') + '/';
97
+ if (!folderMap.has(name))
98
+ folderMap.set(name, { id: `folder:${name}`, name, files: [] });
99
+ folderMap.get(name).files.push(file);
100
+ }
101
+ }
102
+ const folders = [...folderMap.values()].sort((a, b) => a.name.localeCompare(b.name));
103
+ const mentionAgents = agents.map((e) => ({
104
+ ...e,
105
+ kind: 'agent',
106
+ }));
107
+ const options = mode === '/'
108
+ ? skills.filter((s) => `${s.name} ${s.id}`.toLowerCase().includes(query) &&
109
+ !selectedSkills.some((v) => v.id === s.id))
110
+ : mode === '@'
111
+ ? [
112
+ ...mentionAgents.filter((e) => `${e.name} ${e.id}`.toLowerCase().includes(query) &&
113
+ !selectedAgents.includes(e.id)),
114
+ ...(sandbox
115
+ ? [
116
+ ...folders.filter((f) => f.name.toLowerCase().includes(query) &&
117
+ f.files.some((item) => !selectedFiles.some((v) => v.id === item.id))),
118
+ ...files.filter((f) => fileLabel(f).toLowerCase().includes(query) &&
119
+ !selectedFiles.some((v) => v.id === f.id)),
120
+ ]
121
+ : []),
122
+ ]
123
+ : [];
124
+ const listOpen = Boolean(mode && (mode !== '@' || agents.length > 0 || sandbox));
125
+ async function refreshFiles() {
126
+ setLoading(true);
127
+ setError('');
128
+ try {
129
+ setFiles(await workspaceRequest('/workspace/files'));
130
+ }
131
+ catch (e) {
132
+ setError(e instanceof Error ? e.message : messages.workspaceLoadError);
133
+ }
134
+ finally {
135
+ setLoading(false);
136
+ }
137
+ }
138
+ useEffect(() => {
139
+ if (sandbox && (panel || mode === '@'))
140
+ void refreshFiles();
141
+ }, [panel, mode === '@', sandbox]);
142
+ function syncHighlightScroll() {
143
+ if (highlights.current && input.current) {
144
+ highlights.current.scrollTop = input.current.scrollTop;
145
+ highlights.current.scrollLeft = input.current.scrollLeft;
146
+ }
147
+ }
148
+ useLayoutEffect(() => {
149
+ if (pendingCaret.current !== null && input.current) {
150
+ input.current.focus();
151
+ input.current.setSelectionRange(pendingCaret.current, pendingCaret.current);
152
+ pendingCaret.current = null;
153
+ }
154
+ syncHighlightScroll();
155
+ });
156
+ function updateDraft(next, nextMentions) {
157
+ setDraft({ prompt: next, mentions: nextMentions });
158
+ onPrompt(next);
159
+ }
160
+ function checkBudget(local, remote) {
161
+ const issue = validateAttachments([...local, ...remote], messages);
162
+ setError(issue);
163
+ return !issue;
164
+ }
165
+ function addFiles(incoming) {
166
+ if (disabled || !sandbox)
167
+ return;
168
+ const next = [...attachments, ...incoming];
169
+ if (checkBudget(next, selectedFiles))
170
+ onAttachments(next);
171
+ }
172
+ function choose(item, fromSuggestions = false) {
173
+ if (disabled)
174
+ return;
175
+ const start = fromSuggestions ? queryStart : prompt.length;
176
+ const end = fromSuggestions ? caret : prompt.length;
177
+ const skill = 'instructions' in item;
178
+ const label = skill ? '' : `@${'size' in item ? fileLabel(item) : item.name}`;
179
+ const leadingSpace = !fromSuggestions && start > 0 && !/\s$/.test(prompt) ? ' ' : '';
180
+ const reuseSpace = !skill && prompt[end] === ' ';
181
+ const trailingSpace = skill || reuseSpace ? '' : ' ';
182
+ const replacement = leadingSpace + label + trailingSpace;
183
+ const next = prompt.slice(0, start) + replacement + prompt.slice(end);
184
+ if (next.length > promptLimit) {
185
+ setError(messages.promptLimit(promptLimit));
186
+ return;
187
+ }
188
+ const nextMentions = editMentions(mentions, start, end, replacement.length);
189
+ if (skill) {
190
+ setSelectedSkills((previous) => [...previous, item]);
191
+ }
192
+ else {
193
+ const labelStart = start + leadingSpace.length;
194
+ const range = { start: labelStart, end: labelStart + label.length };
195
+ if ('files' in item || 'size' in item) {
196
+ const additions = 'files' in item ? item.files : [item];
197
+ const newFiles = additions.filter((file) => !selectedFiles.some((f) => f.id === file.id));
198
+ if (!newFiles.length || !checkBudget(attachments, [...selectedFiles, ...newFiles]))
199
+ return;
200
+ nextMentions.push({ ...range, kind: 'files', files: additions });
201
+ }
202
+ else {
203
+ nextMentions.push({ ...range, kind: 'agent', id: item.id });
204
+ }
205
+ nextMentions.sort((a, b) => a.start - b.start);
206
+ }
207
+ const position = start + replacement.length + Number(reuseSpace);
208
+ if (fromSuggestions)
209
+ pendingCaret.current = position;
210
+ setCaret(position);
211
+ updateDraft(next, nextMentions);
212
+ setError('');
213
+ setDismissed(true);
214
+ setActive(0);
215
+ }
216
+ async function uploadWorkspace(incoming) {
217
+ if (!incoming.length || disabled)
218
+ return;
219
+ if (incoming.some((file) => file.size > 10 * 1024 * 1024)) {
220
+ setError(messages.fileLimit);
221
+ return;
222
+ }
223
+ if (files.length + incoming.length > 50 ||
224
+ [...files, ...incoming].reduce((sum, file) => sum + file.size, 0) >
225
+ 100 * 1024 * 1024) {
226
+ setError(messages.workspaceLimit);
227
+ return;
228
+ }
229
+ setWorking(true);
230
+ setError('');
231
+ setWorkspaceStatus('');
232
+ let uploaded = 0;
233
+ let failure = '';
234
+ try {
235
+ for (const file of incoming) {
236
+ setWorkspaceStatus(messages.uploadProgress(uploaded + 1, incoming.length, file.webkitRelativePath || file.name));
237
+ const path = file.webkitRelativePath
238
+ ? `&relative_path=${encodeURIComponent(file.webkitRelativePath)}`
239
+ : '';
240
+ await workspaceRequest(`/workspace/files?filename=${encodeURIComponent(file.name)}${path}`, {
241
+ method: 'POST',
242
+ headers: { 'Content-Type': 'application/octet-stream' },
243
+ body: file,
244
+ });
245
+ uploaded++;
246
+ }
247
+ }
248
+ catch (e) {
249
+ failure = e instanceof Error ? e.message : messages.uploadFailed;
250
+ }
251
+ await refreshFiles();
252
+ if (failure)
253
+ setError(messages.uploadPartial(uploaded, incoming.length, failure));
254
+ setWorkspaceStatus(failure ? '' : messages.uploaded(uploaded));
255
+ setWorking(false);
256
+ }
257
+ async function deleteFile(file) {
258
+ setWorking(true);
259
+ setError('');
260
+ try {
261
+ await workspaceRequest(`/workspace/files/${encodeURIComponent(file.id)}`, {
262
+ method: 'DELETE',
263
+ });
264
+ setDraft((previous) => ({
265
+ ...previous,
266
+ mentions: previous.mentions.flatMap((mention) => {
267
+ if (mention.kind === 'agent')
268
+ return [mention];
269
+ const files = mention.files.filter((f) => f.id !== file.id);
270
+ return files.length ? [{ ...mention, files }] : [];
271
+ }),
272
+ }));
273
+ await refreshFiles();
274
+ }
275
+ catch (e) {
276
+ setError(e instanceof Error ? e.message : messages.deleteFailed);
277
+ }
278
+ finally {
279
+ setWorking(false);
280
+ }
281
+ }
282
+ function send() {
283
+ if (!disabled && prompt.trim() && checkBudget(attachments, selectedFiles))
284
+ onSubmit(selectedSkills.map((s) => s.id), selectedFiles.map((f) => f.id), selectedAgents);
285
+ }
286
+ return (_jsxs("form", { "aria-label": messages.taskInput, className: `composer task-composer ${dragging ? 'is-dragging' : ''}`, onSubmit: (e) => {
287
+ e.preventDefault();
288
+ send();
289
+ }, onDragOver: (e) => {
290
+ e.preventDefault();
291
+ if (sandbox && !disabled && Array.from(e.dataTransfer.types).includes('Files'))
292
+ setDragging(true);
293
+ }, onDragLeave: (e) => {
294
+ if (!e.currentTarget.contains(e.relatedTarget))
295
+ setDragging(false);
296
+ }, onDrop: (e) => {
297
+ e.preventDefault();
298
+ setDragging(false);
299
+ addFiles(Array.from(e.dataTransfer.files));
300
+ }, children: [sandbox && (_jsx("input", { hidden: true, ref: picker, type: "file", multiple: true, "aria-label": messages.addTaskAttachments, disabled: disabled, onChange: (e) => {
301
+ addFiles(Array.from(e.target.files ?? []));
302
+ e.target.value = '';
303
+ } })), (selectedSkills.length > 0 || attachments.length > 0) && (_jsxs("div", { className: "composer-chips", children: [selectedSkills.map((s) => (_jsxs("span", { className: "composer-chip", children: ["/", s.name, _jsx("button", { type: "button", disabled: disabled, "aria-label": messages.removeSkill(s.name), onClick: () => setSelectedSkills((previous) => previous.filter((v) => v.id !== s.id)), children: _jsx(X, { size: 12 }) })] }, s.id))), attachments.map((file, i) => (_jsxs("span", { className: "composer-chip", title: file.name, children: [file.name, _jsx("button", { type: "button", disabled: disabled, "aria-label": messages.removeAttachment(file.name, i + 1), onClick: () => onAttachments(attachments.filter((_, n) => n !== i)), children: _jsx(X, { size: 12 }) })] }, `${file.name}-${i}`)))] })), _jsxs("div", { className: "composer-input", children: [mentions.length > 0 && (_jsxs("div", { ref: highlights, className: "composer-highlights", "aria-hidden": "true", children: [prompt.slice(0, mentions[0].start), mentions.map(({ start, end }, index) => (_jsxs(Fragment, { children: [_jsx("mark", { children: prompt.slice(start, end) }), prompt.slice(end, mentions[index + 1]?.start)] }, start))), prompt.endsWith('\n') ? '\u200b' : null] })), _jsx("textarea", { ref: input, "aria-label": messages.ask(name), placeholder: available ? messages.promptHint : messages.unavailable, "aria-controls": listOpen ? 'composer-options' : undefined, "aria-autocomplete": "list", "aria-activedescendant": listOpen && options[active] ? `composer-option-${active}` : undefined, value: prompt, maxLength: promptLimit, disabled: disabled, onChange: (e) => {
304
+ const { value, selectionStart } = e.currentTarget;
305
+ updateDraft(value, mentionsAfterInput(mentions, prompt, value, selectionStart));
306
+ setCaret(selectionStart);
307
+ setDismissed(false);
308
+ setActive(0);
309
+ }, onScroll: syncHighlightScroll, onSelect: (e) => setCaret(e.currentTarget.selectionStart), onKeyDown: (e) => {
310
+ if (e.nativeEvent.isComposing)
311
+ return;
312
+ if (listOpen && e.key === 'Escape') {
313
+ e.preventDefault();
314
+ setDismissed(true);
315
+ return;
316
+ }
317
+ if (listOpen && options.length && ['ArrowDown', 'ArrowUp'].includes(e.key)) {
318
+ e.preventDefault();
319
+ setActive((active + (e.key === 'ArrowDown' ? 1 : -1) + options.length) %
320
+ options.length);
321
+ return;
322
+ }
323
+ if (e.key === 'Enter' && !e.shiftKey) {
324
+ e.preventDefault();
325
+ if (listOpen) {
326
+ if (options[active])
327
+ choose(options[active], true);
328
+ }
329
+ else
330
+ send();
331
+ }
332
+ } })] }), listOpen && (_jsxs("div", { className: "composer-suggestions", children: [_jsxs("div", { className: "composer-list-title", children: [mode === '/' ? messages.selectSkill : messages.mention, _jsx("button", { type: "button", "aria-label": messages.dismissSuggestion, onClick: () => setDismissed(true), children: _jsx(X, { size: 13 }) })] }), _jsx("div", { id: "composer-options", role: "listbox", "aria-label": mode === '/' ? messages.suggestedSkills : messages.suggestedMentions, children: options.map((item, i) => (_jsxs("button", { type: "button", role: "option", id: `composer-option-${i}`, "aria-selected": active === i, "aria-label": 'files' in item
333
+ ? `@${item.name} ${messages.fileCount(item.files.length)}`
334
+ : undefined, onMouseDown: (e) => e.preventDefault(), onClick: () => choose(item, true), children: [_jsxs("span", { children: [mode, 'size' in item ? fileLabel(item) : item.name] }), 'kind' in item && item.kind === 'agent' && _jsx("small", { children: messages.agent }), 'files' in item && _jsx("small", { children: messages.fileCount(item.files.length) }), 'description' in item && _jsx("small", { children: item.description })] }, item.id))) }), !options.length && (_jsx("p", { children: loading
335
+ ? messages.loading
336
+ : mode === '/'
337
+ ? messages.noSkills
338
+ : messages.noMentions }))] })), dragging && _jsx("div", { className: "composer-drop-hint", children: messages.dropFiles }), _jsxs("div", { className: "composer-footer", children: [_jsxs("div", { className: "composer-tools", children: [_jsx("button", { type: "button", className: "composer-icon", "aria-label": messages.addAttachments, title: messages.attachHint, disabled: disabled || !sandbox, onClick: () => picker.current?.click(), children: _jsx(Plus, { size: 19 }) }), _jsx("button", { type: "button", className: "composer-icon", "aria-label": messages.workspaceFiles, title: messages.workspace, "aria-expanded": panel, disabled: !sandbox || busy, onClick: () => setPanel(!panel), children: _jsx(FolderOpen, { size: 15 }) })] }), running && onStop ? (_jsx("button", { type: "button", className: "send", "aria-label": messages.stop, title: messages.stopHint, disabled: busy, onClick: onStop, children: busy ? (_jsx(Loader2, { size: 17, className: "spin" })) : (_jsx(Square, { size: 12, fill: "currentColor" })) })) : (_jsx("button", { className: "send", "aria-label": messages.send, title: messages.sendHint, disabled: disabled || !prompt.trim(), children: busy ? _jsx(Loader2, { size: 17, className: "spin" }) : _jsx(ArrowUp, { size: 18 }) }))] }), panel && (_jsxs(Dialog, { title: messages.workspace, lang: locale, className: "workspace-dialog", closeLabel: messages.closeWorkspace, onClose: () => setPanel(false), children: [_jsxs("div", { className: "dialog-body", children: [_jsx("p", { className: "muted", children: messages.workspaceHint }), _jsxs("div", { className: "workspace-file-actions", children: [_jsxs("button", { type: "button", disabled: disabled || loading, onClick: () => workspacePicker.current?.click(), children: [_jsx(Upload, { size: 14 }), messages.uploadFiles] }), _jsxs("button", { type: "button", disabled: disabled || loading, onClick: () => folderPicker.current?.click(), children: [_jsx(FolderOpen, { size: 14 }), messages.uploadFolder] }), _jsx("button", { type: "button", "aria-label": messages.refreshFiles, disabled: loading || working, onClick: () => void refreshFiles(), children: _jsx(RefreshCw, { size: 14 }) })] }), _jsx("input", { hidden: true, ref: workspacePicker, type: "file", multiple: true, "aria-label": messages.uploadToWorkspace, disabled: disabled, onChange: (e) => {
339
+ void uploadWorkspace(Array.from(e.target.files ?? []));
340
+ e.target.value = '';
341
+ } }), _jsx("input", { hidden: true, ref: (element) => {
342
+ folderPicker.current = element;
343
+ if (element)
344
+ element.setAttribute('webkitdirectory', '');
345
+ }, type: "file", multiple: true, "aria-label": messages.uploadFolderToWorkspace, disabled: disabled, onChange: (e) => {
346
+ void uploadWorkspace(Array.from(e.target.files ?? []));
347
+ e.target.value = '';
348
+ } }), workspaceStatus && _jsx("p", { role: "status", children: workspaceStatus }), error && (_jsx("p", { role: "alert", className: "composer-error", children: error })), folders.length > 0 && (_jsx("div", { className: "workspace-folders", children: folders.map((folder) => (_jsxs("button", { type: "button", disabled: disabled, onClick: () => choose(folder), title: messages.referenceFolder, children: [_jsx(FolderOpen, { size: 15 }), folder.name, _jsx("small", { children: messages.fileCount(folder.files.length) })] }, folder.id))) })), loading ? (_jsx("p", { role: "status", children: messages.loadingFiles })) : files.length === 0 ? (_jsx("p", { className: "muted", children: messages.emptyWorkspace })) : (_jsx("ul", { className: "workspace-file-list", children: files.map((file) => (_jsxs("li", { children: [_jsxs("button", { className: "workspace-reference", type: "button", disabled: disabled || selectedFiles.some((f) => f.id === file.id), onClick: () => choose(file), title: fileLabel(file), children: [_jsx("span", { children: fileLabel(file) }), _jsx("small", { children: file.size < 1024
349
+ ? `${file.size} B`
350
+ : `${(file.size / 1024).toFixed(1)} KiB` })] }), previewKind(file.name) && (_jsx("button", { type: "button", "aria-label": messages.preview(fileLabel(file)), onClick: () => setPreview({
351
+ name: fileLabel(file),
352
+ url: platform.contentUrl(`/workspace/files/${encodeURIComponent(file.id)}`),
353
+ }), children: _jsx(FileText, { size: 14 }) })), _jsx("a", { "aria-label": messages.download(fileLabel(file)), href: platform.contentUrl(`/workspace/files/${encodeURIComponent(file.id)}`), download: true, children: _jsx(Download, { size: 14 }) }), _jsx("button", { type: "button", disabled: working || busy, "aria-label": messages.deleteFile(fileLabel(file)), onClick: () => void deleteFile(file), children: _jsx(Trash2, { size: 14 }) })] }, file.id))) })), _jsx("small", { className: "muted", children: messages.workspaceLimitsHint })] }), preview && (_jsx(FilePreview, { name: preview.name, url: preview.url, onClose: () => setPreview(null) }))] })), (attachments.length > 0 || selectedFiles.length > 0) && (_jsx("p", { className: "composer-note", children: messages.selectedFileCount(attachments.length + selectedFiles.length) })), !sandbox && _jsx("p", { className: "composer-note", children: messages.attachmentsUnavailable }), (uploadStatus || working) && (_jsx("p", { role: "status", className: "composer-note", children: uploadStatus || messages.updatingWorkspace })), error && !panel && (_jsx("p", { role: "alert", className: "composer-error", children: error }))] }));
354
+ }
@@ -0,0 +1,24 @@
1
+ import type { WorkspaceClient } from '../../index.js';
2
+ import './files.css';
3
+ import { type AssistantMessages } from './messages.js';
4
+ import type { TaskFile } from './types.js';
5
+ /** Validate the same per-task upload budget enforced by the backend. */
6
+ export declare function validateAttachments(files: ReadonlyArray<{
7
+ size: number;
8
+ }>, messages?: AssistantMessages): string;
9
+ /** Classify a file name as in-page previewable text or PDF, else null (download only). */
10
+ export declare function previewKind(name: string): 'text' | 'pdf' | null;
11
+ /** Fetch previewable bytes once and render text or the browser PDF viewer in a dialog. */
12
+ export declare function FilePreview({ name, url, onClose, }: {
13
+ name: string;
14
+ url: string;
15
+ onClose: () => void;
16
+ }): import("react").JSX.Element;
17
+ /** Upload bytes, then create the task; discard unclaimed uploads on failure. */
18
+ export declare function submitWithAttachments<T>(files: File[], create: (ids: string[]) => Promise<T>, progress: (text: string) => void, platform: WorkspaceClient, messages?: AssistantMessages): Promise<T>;
19
+ /** Show persistent files; previewable names open in-page, others stay download links. */
20
+ export declare function TaskFileLinks({ taskId, files, title, }: {
21
+ taskId: string;
22
+ files: TaskFile[];
23
+ title: string;
24
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,107 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { usePlatform } from '../index.js';
3
+ import { useEffect, useState } from 'react';
4
+ import './files.css';
5
+ import { Dialog } from '../ui/index.js';
6
+ import { english, useAssistantDisplay } from './messages.js';
7
+ const FILE_LIMIT = 10 * 1024 * 1024;
8
+ /** Validate the same per-task upload budget enforced by the backend. */
9
+ export function validateAttachments(files, messages = english) {
10
+ if (files.length > 5)
11
+ return messages.attachmentCountLimit;
12
+ if (files.some((file) => file.size > FILE_LIMIT))
13
+ return messages.attachmentSizeLimit;
14
+ if (files.reduce((size, file) => size + file.size, 0) > 25 * 1024 * 1024)
15
+ return messages.attachmentTotalLimit;
16
+ return '';
17
+ }
18
+ /** Classify a file name as in-page previewable text or PDF, else null (download only). */
19
+ export function previewKind(name) {
20
+ const lower = name.toLowerCase();
21
+ if (lower.endsWith('.pdf'))
22
+ return 'pdf';
23
+ if (lower.endsWith('.txt') || lower.endsWith('.md') || lower.endsWith('.markdown'))
24
+ return 'text';
25
+ return null;
26
+ }
27
+ /** Fetch previewable bytes once and render text or the browser PDF viewer in a dialog. */
28
+ export function FilePreview({ name, url, onClose, }) {
29
+ const { locale, messages } = useAssistantDisplay();
30
+ const platform = usePlatform();
31
+ const kind = previewKind(name);
32
+ const [text, setText] = useState('');
33
+ const [objectUrl, setObjectUrl] = useState('');
34
+ const [error, setError] = useState('');
35
+ const [loading, setLoading] = useState(true);
36
+ useEffect(() => {
37
+ let active = true;
38
+ let created = '';
39
+ setLoading(true);
40
+ setError('');
41
+ void (async () => {
42
+ try {
43
+ const response = await platform.raw(url);
44
+ if (!response.ok)
45
+ throw new Error(`${messages.fileLoadError} (${response.status})`);
46
+ if (kind === 'pdf') {
47
+ created = URL.createObjectURL(new Blob([await response.blob()], { type: 'application/pdf' }));
48
+ if (active)
49
+ setObjectUrl(created);
50
+ }
51
+ else {
52
+ const body = await response.text();
53
+ if (active)
54
+ setText(body);
55
+ }
56
+ }
57
+ catch (e) {
58
+ if (active)
59
+ setError(e instanceof Error ? e.message : messages.fileLoadError);
60
+ }
61
+ finally {
62
+ if (active)
63
+ setLoading(false);
64
+ }
65
+ })();
66
+ return () => {
67
+ active = false;
68
+ if (created)
69
+ URL.revokeObjectURL(created);
70
+ };
71
+ }, [url, kind, platform, messages]);
72
+ return (_jsx(Dialog, { title: name, lang: locale, closeLabel: messages.closeDialog(name), className: "file-preview-dialog", onClose: onClose, children: _jsxs("div", { className: "dialog-body file-preview-body", children: [loading ? (_jsx("p", { role: "status", children: messages.loadingFiles })) : error ? (_jsx("p", { role: "alert", className: "definition-error", children: error })) : kind === 'pdf' ? (_jsx("iframe", { title: messages.previewTitle(name), src: objectUrl })) : (_jsx("pre", { children: text })), _jsx("a", { className: "button", href: url, download: true, children: messages.downloadFile })] }) }));
73
+ }
74
+ /** Upload bytes, then create the task; discard unclaimed uploads on failure. */
75
+ export async function submitWithAttachments(files, create, progress, platform, messages = english) {
76
+ const error = validateAttachments(files, messages);
77
+ if (error)
78
+ throw new Error(error);
79
+ const ids = [];
80
+ try {
81
+ for (const file of files) {
82
+ progress(messages.uploadProgress(ids.length + 1, files.length, file.name));
83
+ ids.push((await platform.files.upload(file, file.name)).id);
84
+ }
85
+ progress(files.length ? messages.attachmentsUploaded : '');
86
+ return await create(ids);
87
+ }
88
+ catch (error) {
89
+ await Promise.allSettled(ids.map((id) => platform.files.delete(id)));
90
+ throw error;
91
+ }
92
+ finally {
93
+ progress('');
94
+ }
95
+ }
96
+ /** Show persistent files; previewable names open in-page, others stay download links. */
97
+ export function TaskFileLinks({ taskId, files, title, }) {
98
+ const { messages } = useAssistantDisplay();
99
+ const platform = usePlatform();
100
+ const [preview, setPreview] = useState(null);
101
+ if (!files.length)
102
+ return null;
103
+ return (_jsxs("section", { className: "task-files", "aria-label": title, children: [_jsx("strong", { children: title }), _jsx("ul", { children: files.map((file) => {
104
+ const url = platform.contentUrl(`/tasks/${encodeURIComponent(taskId)}/files/${encodeURIComponent(file.id)}`);
105
+ return (_jsxs("li", { children: [previewKind(file.name) ? (_jsx("button", { type: "button", className: "file-preview-link", onClick: () => setPreview({ name: file.name, url }), children: file.name })) : (_jsx("a", { href: url, download: true, children: file.name })), _jsxs("small", { children: [(file.size / 1024).toFixed(1), " KiB", file.attempt ? ` · ${messages.attempt(file.attempt)}` : ''] })] }, file.id));
106
+ }) }), preview && (_jsx(FilePreview, { name: preview.name, url: preview.url, onClose: () => setPreview(null) }))] }));
107
+ }