@h-ai/ui 1.0.0-beta.30 → 1.0.0-beta.32

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 (48) hide show
  1. package/README.en.md +10 -1183
  2. package/README.ja.md +9 -1182
  3. package/README.md +12 -1183
  4. package/auto-import.d.ts +4 -0
  5. package/auto-import.js +4 -0
  6. package/dist/components/compounds/Popover.svelte +1 -0
  7. package/dist/components/scenes/ai/AiDocumentEditor.svelte +73 -7
  8. package/dist/components/scenes/ai/document-download.js +49 -86
  9. package/dist/components/scenes/ai/document-parse.js +6 -28
  10. package/dist/components/scenes/ai/document-pdf-pages.d.ts +26 -0
  11. package/dist/components/scenes/ai/document-pdf-pages.js +111 -0
  12. package/dist/components/scenes/ai/document-pdf-worker.d.ts +11 -0
  13. package/dist/components/scenes/ai/document-pdf-worker.js +29 -0
  14. package/dist/components/scenes/ai/document-render-pool.d.ts +19 -0
  15. package/dist/components/scenes/ai/document-render-pool.js +20 -0
  16. package/dist/components/scenes/ai/document-render-worker.d.ts +13 -0
  17. package/dist/components/scenes/ai/document-render-worker.js +7 -0
  18. package/dist/components/scenes/ai/document-types.d.ts +2 -0
  19. package/dist/components/scenes/ai/index.d.ts +3 -0
  20. package/dist/components/scenes/ai/index.js +2 -0
  21. package/dist/components/scenes/ai/mind/AiMindMapEditor.svelte +519 -0
  22. package/dist/components/scenes/ai/mind/AiMindMapEditor.svelte.d.ts +8 -0
  23. package/dist/components/scenes/ai/mind/mind-adapter.d.ts +38 -0
  24. package/dist/components/scenes/ai/mind/mind-adapter.js +59 -0
  25. package/dist/components/scenes/ai/mind/mind-types.d.ts +116 -0
  26. package/dist/components/scenes/ai/mind/mind-types.js +1 -0
  27. package/dist/components/scenes/index.d.ts +1 -0
  28. package/dist/components/scenes/index.js +2 -0
  29. package/dist/components/scenes/tools/ArtifactWorkspace.svelte +561 -0
  30. package/dist/components/scenes/tools/ArtifactWorkspace.svelte.d.ts +17 -0
  31. package/dist/components/scenes/tools/ToolWorkspace.svelte +435 -0
  32. package/dist/components/scenes/tools/ToolWorkspace.svelte.d.ts +17 -0
  33. package/dist/components/scenes/tools/artifact-data.d.ts +35 -0
  34. package/dist/components/scenes/tools/artifact-data.js +127 -0
  35. package/dist/components/scenes/tools/artifact-markdown.d.ts +58 -0
  36. package/dist/components/scenes/tools/artifact-markdown.js +308 -0
  37. package/dist/components/scenes/tools/artifact-preview.d.ts +9 -0
  38. package/dist/components/scenes/tools/artifact-preview.js +31 -0
  39. package/dist/components/scenes/tools/index.d.ts +4 -0
  40. package/dist/components/scenes/tools/index.js +3 -0
  41. package/dist/components/scenes/tools/tool-form.d.ts +74 -0
  42. package/dist/components/scenes/tools/tool-form.js +179 -0
  43. package/dist/components/scenes/tools/workspace-types.d.ts +221 -0
  44. package/dist/components/scenes/tools/workspace-types.js +1 -0
  45. package/dist/messages/en-US.json +99 -1
  46. package/dist/messages/ja-JP.json +99 -1
  47. package/dist/messages/zh-CN.json +99 -1
  48. package/package.json +8 -2
@@ -0,0 +1,435 @@
1
+ <!--
2
+ @component ToolWorkspace
3
+ 以表单、预设和执行进度呈现工具,业务执行由宿主回调提供。
4
+ @example
5
+ ```ts
6
+ import { mount } from 'svelte'
7
+ import { ToolWorkspace } from '@h-ai/ui'
8
+ const component = mount(ToolWorkspace, { target: document.body, props: {
9
+ tools: [{ name: 'echo', description: '回显文字', inputSchema: { type: 'object', properties: { text: { type: 'string' } } } }],
10
+ onrun: async request => ({ id: 'run-1', status: 'succeeded', result: request.input }),
11
+ } })
12
+ ```
13
+ -->
14
+ <script lang='ts'>
15
+ import type { ToolResource, ToolRun, ToolRunRequest, ToolWorkspaceProps } from './workspace-types.js'
16
+ import { onDestroy, onMount, untrack } from 'svelte'
17
+ import { SvelteMap } from 'svelte/reactivity'
18
+ import { uiM } from '../../../messages.js'
19
+ import { notifyError, notifyWarning } from '../../../toast.svelte.js'
20
+ import { cn, getDataAttributes } from '../../../utils.js'
21
+ import Combobox from '../../compounds/Combobox.svelte'
22
+ import Confirm from '../../compounds/Confirm.svelte'
23
+ import FormField from '../../compounds/FormField.svelte'
24
+ import FormLayout from '../../compounds/FormLayout.svelte'
25
+ import Button from '../../primitives/Button.svelte'
26
+ import { asRecord, buildToolInput, describeToolFields, toolResourceIds, toolResourceOptions } from './tool-form.js'
27
+
28
+ const { tools, resources = [], initialRun, onrunchange, onrun, onstatus, oncancel, onartifact, onerror, pollIntervalMs = 1000, class: className, ...rest }: ToolWorkspaceProps = $props()
29
+ const dataAttributes = $derived(getDataAttributes(rest))
30
+ const uid = $props.id()
31
+ let name = $state('')
32
+ let query = $state('')
33
+ let values = $state<Record<string, unknown>>({})
34
+ let rawInput = $state('{}')
35
+ let run = $state<ToolRun | undefined>(untrack(() => initialRun))
36
+ let pendingKey = $state(untrack(() => initialRun?.idempotencyKey ?? ''))
37
+ let pendingRequest = $state.raw<ToolRunRequest>()
38
+ let pendingNotFound = $state(false)
39
+ let restoring = $state(untrack(() => !!initialRun && !!onstatus))
40
+ let confirmNewOperation = $state(false)
41
+ let submitting = $state(false)
42
+ let cancelling = $state(false)
43
+ let disconnected = $state(false)
44
+ let generatedResources = $state<ToolResource[]>([])
45
+ let initialized = ''
46
+ let request: AbortController | undefined
47
+ let timer: ReturnType<typeof setTimeout> | undefined
48
+ const selected = $derived(tools.find(tool => tool.name === name))
49
+ const visible = $derived(tools.filter(tool => `${tool.title ?? tool.name} ${tool.description}`.toLowerCase().includes(query.trim().toLowerCase())))
50
+ const fields = $derived(selected
51
+ ? describeToolFields(selected.inputSchema)
52
+ : [])
53
+ const simple = $derived(fields.filter(field => field.kind !== 'json'))
54
+ const advanced = $derived(fields.filter(field => field.kind === 'json'))
55
+ const active = $derived(!!run && ['queued', 'running', 'cancelling'].includes(run.status))
56
+ const unverifiedReceipt = $derived(run?.status === 'unknown' && !run.idempotencyKey)
57
+ const inputLocked = $derived(submitting || active || restoring || !!pendingRequest || unverifiedReceipt || (!!pendingKey && !pendingNotFound))
58
+ const submitBlocked = $derived(submitting || active || restoring || unverifiedReceipt || (!!pendingKey && !pendingRequest && !pendingNotFound))
59
+ const availableResources = $derived([
60
+ ...resources,
61
+ ...generatedResources,
62
+ ])
63
+ const resultText = $derived.by(() => {
64
+ try {
65
+ return typeof run?.result === 'string'
66
+ ? run.result
67
+ : run?.result === undefined
68
+ ? ''
69
+ : JSON.stringify(run.result, null, 2)
70
+ }
71
+ catch { return uiM('tool_result_unavailable') }
72
+ })
73
+
74
+ $effect(() => {
75
+ const first = tools[0]?.name
76
+ if (!untrack(() => name) && first)
77
+ name = first
78
+ })
79
+
80
+ $effect(() => {
81
+ const tool = selected
82
+ if (tool && tool.name !== untrack(() => initialized)) {
83
+ const previous = initialized
84
+ initialized = tool.name
85
+ values = Object.fromEntries(describeToolFields(tool.inputSchema)
86
+ .filter(field => field.defaultValue !== undefined || (field.required && (field.kind === 'boolean' || field.kind === 'string')))
87
+ .map(field => [
88
+ field.name,
89
+ field.defaultValue === undefined
90
+ ? field.kind === 'boolean'
91
+ ? false
92
+ : ''
93
+ : field.defaultValue,
94
+ ]))
95
+ rawInput = '{}'
96
+ if (previous) {
97
+ // 未知提交的幂等键保留到拿回真实回执,换表单也不能产生第二次扣费。
98
+ if (!pendingKey)
99
+ run = undefined
100
+ disconnected = false
101
+ request?.abort()
102
+ clearTimeout(timer)
103
+ }
104
+ }
105
+ })
106
+
107
+ $effect(() => {
108
+ onrunchange?.(run)
109
+ })
110
+
111
+ $effect(() => {
112
+ const completed = run
113
+ if (completed?.status === 'succeeded' && completed.artifacts?.length) {
114
+ untrack(() => {
115
+ const merged = new SvelteMap(generatedResources.map(item => [item.id, item]))
116
+ for (const artifact of completed.artifacts ?? []) {
117
+ merged.delete(artifact.id)
118
+ merged.set(artifact.id, artifact)
119
+ }
120
+ generatedResources = [
121
+ ...merged.values(),
122
+ ].slice(-100)
123
+ })
124
+ }
125
+ })
126
+
127
+ onMount(() => {
128
+ if (run && onstatus)
129
+ void refresh()
130
+ })
131
+
132
+ function failed(error: unknown) {
133
+ notifyError(error, uiM('tool_failed'))
134
+ onerror?.(error)
135
+ }
136
+
137
+ function setValue(key: string, value: unknown) {
138
+ values = { ...values, [key]: value }
139
+ }
140
+
141
+ function schedule(signal: AbortSignal) {
142
+ clearTimeout(timer)
143
+ if (signal.aborted || !run || !['queued', 'running', 'cancelling'].includes(run.status) || !onstatus)
144
+ return
145
+ const interval = Number.isFinite(pollIntervalMs)
146
+ ? Math.max(250, pollIntervalMs)
147
+ : 1000
148
+ timer = setTimeout(() => {
149
+ void refresh(signal)
150
+ }, interval)
151
+ }
152
+
153
+ async function refresh(signal?: AbortSignal) {
154
+ if (!run || !onstatus)
155
+ return
156
+ if (!signal) {
157
+ request?.abort()
158
+ request = new AbortController()
159
+ signal = request.signal
160
+ }
161
+ const id = run.id
162
+ if (run.status === 'unknown')
163
+ restoring = true
164
+ try {
165
+ const result = await onstatus(id, signal)
166
+ if (signal.aborted || run?.id !== id)
167
+ return
168
+ if (result) {
169
+ run = result
170
+ pendingKey = result.idempotencyKey ?? ''
171
+ if (!pendingKey)
172
+ pendingRequest = undefined
173
+ pendingNotFound = false
174
+ }
175
+ else {
176
+ pendingNotFound = true
177
+ run = {
178
+ ...run,
179
+ status: 'unknown',
180
+ message: uiM('tool_submission_not_found'),
181
+ }
182
+ }
183
+ disconnected = false
184
+ schedule(signal)
185
+ }
186
+ catch (error) {
187
+ if (!signal.aborted) {
188
+ disconnected = true
189
+ failed(error)
190
+ }
191
+ }
192
+ finally {
193
+ if (!signal.aborted)
194
+ restoring = false
195
+ }
196
+ }
197
+
198
+ async function submit(event: SubmitEvent) {
199
+ event.preventDefault()
200
+ if (!selected || submitBlocked)
201
+ return
202
+ let invocation = pendingRequest
203
+ if (!invocation) {
204
+ let input: Record<string, unknown>
205
+ if (fields.length) {
206
+ const parsed = buildToolInput(selected.inputSchema, values)
207
+ if (!parsed.success) {
208
+ notifyWarning(uiM('tool_invalid_field', { field: parsed.field }))
209
+ return
210
+ }
211
+ input = parsed.input
212
+ }
213
+ else {
214
+ try {
215
+ const parsed = asRecord(JSON.parse(rawInput))
216
+ if (!parsed)
217
+ throw new TypeError('Tool input must be an object')
218
+ input = parsed
219
+ }
220
+ catch {
221
+ notifyWarning(uiM('tool_invalid_json'))
222
+ return
223
+ }
224
+ }
225
+ pendingKey ||= crypto.randomUUID()
226
+ invocation = { name: selected.name, input, idempotencyKey: pendingKey }
227
+ pendingRequest = invocation
228
+ }
229
+ request?.abort()
230
+ const current = new AbortController()
231
+ request = current
232
+ submitting = true
233
+ disconnected = false
234
+ pendingNotFound = false
235
+ const idempotencyKey = invocation.idempotencyKey
236
+ try {
237
+ const result = await onrun(invocation, current.signal)
238
+ if (current.signal.aborted)
239
+ return
240
+ run = result
241
+ pendingKey = result.idempotencyKey ?? ''
242
+ if (!pendingKey)
243
+ pendingRequest = undefined
244
+ schedule(current.signal)
245
+ }
246
+ catch (error) {
247
+ if (!current.signal.aborted) {
248
+ run = {
249
+ id: `pending.${idempotencyKey}`,
250
+ idempotencyKey,
251
+ status: 'unknown',
252
+ message: uiM('tool_submission_unknown'),
253
+ }
254
+ disconnected = true
255
+ failed(error)
256
+ }
257
+ }
258
+ finally {
259
+ if (!current.signal.aborted)
260
+ submitting = false
261
+ }
262
+ }
263
+
264
+ function startAnotherOperation() {
265
+ // 只结束当前界面的等待,不宣称远端已取消;新意图生成新的幂等键。
266
+ request?.abort()
267
+ clearTimeout(timer)
268
+ pendingRequest = undefined
269
+ pendingKey = ''
270
+ pendingNotFound = false
271
+ restoring = false
272
+ disconnected = false
273
+ run = undefined
274
+ }
275
+
276
+ async function cancel() {
277
+ if (!run || !oncancel || cancelling)
278
+ return
279
+ request?.abort()
280
+ clearTimeout(timer)
281
+ const current = new AbortController()
282
+ request = current
283
+ cancelling = true
284
+ try {
285
+ const result = await oncancel(run.id, current.signal)
286
+ if (!current.signal.aborted) {
287
+ run = result
288
+ schedule(current.signal)
289
+ }
290
+ }
291
+ catch (error) {
292
+ if (!current.signal.aborted) {
293
+ disconnected = true
294
+ failed(error)
295
+ }
296
+ }
297
+ finally {
298
+ if (!current.signal.aborted)
299
+ cancelling = false
300
+ }
301
+ }
302
+
303
+ onDestroy(() => {
304
+ request?.abort()
305
+ clearTimeout(timer)
306
+ })
307
+ </script>
308
+
309
+ <section {...dataAttributes} class={cn('hai-tool-workspace grid min-w-0 content-start gap-4', className)} aria-label={uiM('tool_workspace')}>
310
+ <div class='grid min-w-0 items-end gap-3 sm:grid-cols-2'>
311
+ <label class='grid min-w-0 gap-1 text-sm'>{uiM('tool_search')}<input class='input w-full' bind:value={query} disabled={inputLocked} /></label>
312
+ <label class='grid min-w-0 gap-1 text-sm'>{uiM('tool_choose')}
313
+ <select class='select w-full' bind:value={name} disabled={inputLocked}>
314
+ {#if selected && !visible.some(tool => tool.name === selected?.name)}<option value={selected.name}>{selected.title ?? selected.name}</option>{/if}
315
+ {#if !tools.length}<option value=''>{uiM('tool_empty')}</option>{/if}
316
+ {#each visible as tool (tool.name)}<option value={tool.name}>{tool.title ?? tool.name}</option>{/each}
317
+ </select>
318
+ </label>
319
+ </div>
320
+ {#if selected}
321
+ <p class='text-sm leading-relaxed text-base-content/70'>{selected.description}</p>
322
+ {#if selected.examples?.length}
323
+ <div class='flex flex-wrap items-center gap-2' aria-label={uiM('tool_examples')}>
324
+ <span class='text-xs text-base-content/60'>{uiM('tool_examples')}</span>
325
+ {#each selected.examples as example (example.label)}
326
+ <Button size='sm' variant='ghost' disabled={inputLocked} onclick={() => {
327
+ values = { ...example.input }
328
+ rawInput = JSON.stringify(example.input, null, 2)
329
+ }}>{example.label}</Button>
330
+ {/each}
331
+ </div>
332
+ {/if}
333
+ <form class='grid min-w-0 gap-4' onsubmit={submit}>
334
+ <FormLayout columns={2}>
335
+ {#each simple as field (field.name)}
336
+ <FormField label={field.title} hint={field.description} required={field.required} for={`${uid}-${field.name}`}>
337
+ {#if field.kind === 'resource' || field.kind === 'resources'}
338
+ {@const multiple = field.kind === 'resources'}
339
+ {@const chosen = toolResourceIds(values[field.name])}
340
+ <Combobox options={toolResourceOptions(availableResources, field.mediaType, chosen)} {multiple}
341
+ value={multiple
342
+ ? chosen
343
+ : String(values[field.name] ?? '')} disabled={inputLocked}
344
+ placeholder={uiM('tool_resource_choose')} onchange={value => setValue(field.name, value)} />
345
+ <details class='mt-2 text-xs text-base-content/60'>
346
+ <summary class='cursor-pointer'>{uiM('tool_resource_manual')}</summary>
347
+ <p class='mt-2'>{uiM('tool_resource_manual_hint')}</p>
348
+ <textarea class='textarea mt-2 w-full font-mono text-xs' rows={multiple ? 3 : 1}
349
+ aria-label={uiM('tool_resource_manual_field', { field: field.title })} disabled={inputLocked}
350
+ value={Array.isArray(values[field.name])
351
+ ? chosen.join('\n')
352
+ : String(values[field.name] ?? '')}
353
+ oninput={event => setValue(field.name, event.currentTarget.value)}></textarea>
354
+ </details>
355
+ {:else if field.kind === 'boolean'}
356
+ <input id={`${uid}-${field.name}`} class='checkbox' type='checkbox' checked={values[field.name] === true} disabled={inputLocked}
357
+ onchange={event => setValue(field.name, event.currentTarget.checked)} />
358
+ {:else if field.kind === 'enum'}
359
+ <select id={`${uid}-${field.name}`} class='select w-full' required={field.required} disabled={inputLocked}
360
+ value={field.values?.indexOf(values[field.name] as string | number | boolean | null) ?? -1}
361
+ onchange={event => setValue(field.name, field.values?.[Number(event.currentTarget.value)])}>
362
+ <option value={-1}>{uiM('tool_choose_value')}</option>
363
+ {#each field.values ?? [] as value, index (index)}<option value={index}>{String(value)}</option>{/each}
364
+ </select>
365
+ {:else if field.kind === 'number' || field.kind === 'integer'}
366
+ <input id={`${uid}-${field.name}`} class='input w-full' type='number' step={field.kind === 'integer'
367
+ ? 1
368
+ : 'any'}
369
+ required={field.required} min={field.minimum} max={field.maximum} value={String(values[field.name] ?? '')} disabled={inputLocked}
370
+ oninput={event => setValue(field.name, event.currentTarget.value)} />
371
+ {:else}
372
+ <textarea id={`${uid}-${field.name}`} class='textarea w-full' rows={3} required={field.required && (field.minLength ?? 0) > 0} minlength={field.minLength} maxlength={field.maxLength}
373
+ value={String(values[field.name] ?? '')} disabled={inputLocked} oninput={event => setValue(field.name, event.currentTarget.value)}></textarea>
374
+ {/if}
375
+ </FormField>
376
+ {/each}
377
+ </FormLayout>
378
+ {#if advanced.length || !fields.length}
379
+ <details class='rounded-lg border border-base-300 p-3' open={advanced.some(field => field.required)}>
380
+ <summary class='cursor-pointer text-sm font-medium'>{uiM('tool_advanced')}</summary>
381
+ <div class='mt-3'>
382
+ <FormLayout>
383
+ {#each advanced as field (field.name)}
384
+ <FormField label={field.title} hint={field.description} required={field.required} for={`${uid}-${field.name}`}>
385
+ <textarea id={`${uid}-${field.name}`} class='textarea w-full font-mono text-sm' rows={4} disabled={inputLocked}
386
+ value={typeof values[field.name] === 'string'
387
+ ? values[field.name] as string
388
+ : values[field.name] === undefined
389
+ ? ''
390
+ : JSON.stringify(values[field.name], null, 2)}
391
+ oninput={event => setValue(field.name, event.currentTarget.value)}></textarea>
392
+ </FormField>
393
+ {:else}
394
+ <FormField label={uiM('tool_parameters')} for={`${uid}-json`}>
395
+ <textarea id={`${uid}-json`} class='textarea w-full font-mono text-sm' rows={6} bind:value={rawInput} disabled={inputLocked}></textarea>
396
+ </FormField>
397
+ {/each}
398
+ </FormLayout>
399
+ </div>
400
+ </details>
401
+ {/if}
402
+ <div class='flex flex-wrap items-center gap-2'>
403
+ <Button type='submit' variant='primary' loading={submitting} disabled={submitBlocked} submitHint>{pendingKey && run?.status === 'unknown'
404
+ ? uiM('tool_retry_submission')
405
+ : uiM('tool_run')}</Button>
406
+ {#if active && oncancel}<Button disabled={cancelling || run?.status === 'cancelling'} loading={cancelling || run?.status === 'cancelling'} onclick={cancel}>{uiM('tool_cancel')}</Button>{/if}
407
+ </div>
408
+ </form>
409
+ {:else}
410
+ <div class='rounded-lg border border-dashed border-base-300 p-6 text-sm text-base-content/60'>{uiM('tool_empty')}</div>
411
+ {/if}
412
+ {#if run}
413
+ <section class='grid min-w-0 gap-3 rounded-lg border border-base-300 p-4' aria-label={uiM('tool_result')}>
414
+ <div class='flex flex-wrap items-center gap-2' role='status'><span class='text-sm font-medium'>{uiM(`tool_status_${run.status}`)}</span>
415
+ {#if run.message}<span class='min-w-0 text-sm break-words text-base-content/70'>{run.message}</span>{/if}
416
+ {#if (disconnected || run.status === 'unknown') && onstatus}<Button size='sm' disabled={restoring} loading={restoring} onclick={() => refresh()}>{uiM('tool_resume')}</Button>{/if}
417
+ {#if run.status === 'unknown' && !restoring}<Button size='sm' variant='ghost' onclick={() => { confirmNewOperation = true }}>{uiM('tool_new_operation')}</Button>{/if}
418
+ </div>
419
+ {#if active}
420
+ <progress class='progress progress-primary w-full' aria-label={uiM('tool_progress')} max={1}
421
+ value={run.progress === undefined
422
+ ? undefined
423
+ : Math.min(1, Math.max(0, run.progress))}></progress>
424
+ {/if}
425
+ {#if resultText}<pre class='max-h-96 overflow-auto whitespace-pre-wrap break-words rounded-lg bg-base-200 p-3 text-sm'>{resultText}</pre>{/if}
426
+ {#each run.artifacts ?? [] as artifact (artifact.id)}
427
+ <Button variant='ghost' onclick={() => onartifact?.(artifact)} disabled={!onartifact}>{artifact.title}</Button>
428
+ {/each}
429
+ </section>
430
+ {/if}
431
+ {#if confirmNewOperation}
432
+ <Confirm bind:open={confirmNewOperation} title={uiM('tool_new_operation')} message={uiM('tool_new_operation_confirm')}
433
+ confirmText={uiM('tool_new_operation')} onconfirm={startAnotherOperation} />
434
+ {/if}
435
+ </section>
@@ -0,0 +1,17 @@
1
+ import type { ToolWorkspaceProps } from './workspace-types.js';
2
+ /**
3
+ * ToolWorkspace
4
+ * 以表单、预设和执行进度呈现工具,业务执行由宿主回调提供。
5
+ * @example
6
+ * ```ts
7
+ * import { mount } from 'svelte'
8
+ * import { ToolWorkspace } from '@h-ai/ui'
9
+ * const component = mount(ToolWorkspace, { target: document.body, props: {
10
+ * tools: [{ name: 'echo', description: '回显文字', inputSchema: { type: 'object', properties: { text: { type: 'string' } } } }],
11
+ * onrun: async request => ({ id: 'run-1', status: 'succeeded', result: request.input }),
12
+ * } })
13
+ * ```
14
+ */
15
+ declare const ToolWorkspace: import("svelte").Component<ToolWorkspaceProps, {}, "">;
16
+ type ToolWorkspace = ReturnType<typeof ToolWorkspace>;
17
+ export default ToolWorkspace;
@@ -0,0 +1,35 @@
1
+ import type { AiTableData } from '../ai/table/table-types.js';
2
+ import type { ChartProps } from '../charts/chart-types.js';
3
+ import type { ArtifactCreateRequest } from './workspace-types.js';
4
+ /**
5
+ * 读取可展示的表格结构,不将未知 JSON 直接断言为组件参数。
6
+ * @example 模块内部上下文
7
+ * ```ts
8
+ * const data = readArtifactTable('{"table_columns":[],"table_rows":[]}')
9
+ * ```
10
+ */
11
+ export declare function readArtifactTable(content: string): AiTableData | undefined;
12
+ /**
13
+ * 图表产物只接受数据及基本映射,不能注入组件回调或任意属性。
14
+ * @example 模块内部上下文
15
+ * ```ts
16
+ * const chart = readArtifactChart('{"type":"bar","data":[{"x":"A","y":2}],"x":"x","y":"y"}')
17
+ * ```
18
+ */
19
+ export declare function readArtifactChart(content: string): ChartProps | undefined;
20
+ /**
21
+ * 媒体和下载地址拒绝可执行协议,服务端仍须核验地址与资源授权。
22
+ * @example 模块内部上下文
23
+ * ```ts
24
+ * const url = artifactMediaUrl('/api/artifact/content?id=report')
25
+ * ```
26
+ */
27
+ export declare function artifactMediaUrl(value: string | undefined): string | undefined;
28
+ /**
29
+ * 为四种可编辑产物生成最小可操作模板,业务文案由当前 UI 语言提供。
30
+ * @example 模块内部上下文
31
+ * ```ts
32
+ * const content = newArtifactContent('markdown', '报告', '开始编辑', '名称', '数值', '点击')
33
+ * ```
34
+ */
35
+ export declare function newArtifactContent(kind: ArtifactCreateRequest['kind'], title: string, body: string, label: string, value: string, button: string): string;
@@ -0,0 +1,127 @@
1
+ import { escapeHtml } from '../ai/safe-html.js';
2
+ import { asRecord } from './tool-form.js';
3
+ /**
4
+ * 读取可展示的表格结构,不将未知 JSON 直接断言为组件参数。
5
+ * @example 模块内部上下文
6
+ * ```ts
7
+ * const data = readArtifactTable('{"table_columns":[],"table_rows":[]}')
8
+ * ```
9
+ */
10
+ export function readArtifactTable(content) {
11
+ try {
12
+ const data = asRecord(JSON.parse(content));
13
+ if (!data || !Array.isArray(data.table_columns) || !Array.isArray(data.table_rows))
14
+ return undefined;
15
+ const columns = [];
16
+ const rows = [];
17
+ for (const value of data.table_columns) {
18
+ const column = asRecord(value);
19
+ if (!column || typeof column.key !== 'string' || !column.key.trim() || typeof column.label !== 'string'
20
+ || (column.type !== 'text' && column.type !== 'number' && column.type !== 'tag')) {
21
+ return undefined;
22
+ }
23
+ columns.push({ key: column.key, label: column.label, type: column.type });
24
+ }
25
+ for (const value of data.table_rows) {
26
+ const row = asRecord(value);
27
+ if (!row || typeof row.row_id !== 'string' || !row.row_id.trim())
28
+ return undefined;
29
+ rows.push({ ...row, row_id: row.row_id });
30
+ }
31
+ if (new Set(columns.map(column => column.key)).size !== columns.length || new Set(rows.map(row => row.row_id)).size !== rows.length)
32
+ return undefined;
33
+ return { table_columns: columns, table_rows: rows };
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
39
+ /**
40
+ * 图表产物只接受数据及基本映射,不能注入组件回调或任意属性。
41
+ * @example 模块内部上下文
42
+ * ```ts
43
+ * const chart = readArtifactChart('{"type":"bar","data":[{"x":"A","y":2}],"x":"x","y":"y"}')
44
+ * ```
45
+ */
46
+ export function readArtifactChart(content) {
47
+ try {
48
+ const data = asRecord(JSON.parse(content));
49
+ if (!data || !Array.isArray(data.data) || typeof data.x !== 'string'
50
+ || !(typeof data.y === 'string' || (Array.isArray(data.y) && data.y.every(item => typeof item === 'string')))
51
+ || data.data.some(row => !asRecord(row) || Object.values(row).some(value => typeof value !== 'string' && !(typeof value === 'number' && Number.isFinite(value))))
52
+ || (data.type !== undefined && ![
53
+ 'bar',
54
+ 'line',
55
+ 'area',
56
+ 'pie',
57
+ 'scatter',
58
+ ].includes(String(data.type)))) {
59
+ return undefined;
60
+ }
61
+ // 已验证数据值和有限图形枚举,不透传未验证的 JSON 属性。
62
+ return {
63
+ type: data.type,
64
+ data: data.data,
65
+ x: data.x,
66
+ y: data.y,
67
+ };
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ }
73
+ /**
74
+ * 媒体和下载地址拒绝可执行协议,服务端仍须核验地址与资源授权。
75
+ * @example 模块内部上下文
76
+ * ```ts
77
+ * const url = artifactMediaUrl('/api/artifact/content?id=report')
78
+ * ```
79
+ */
80
+ export function artifactMediaUrl(value) {
81
+ if (!value || !/^(?:https?:|blob:|\/|\.\.?\/)/i.test(value))
82
+ return undefined;
83
+ try {
84
+ const url = new URL(value, 'https://artifact.invalid');
85
+ return !url.username && !url.password
86
+ ? value
87
+ : undefined;
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ }
93
+ /**
94
+ * 为四种可编辑产物生成最小可操作模板,业务文案由当前 UI 语言提供。
95
+ * @example 模块内部上下文
96
+ * ```ts
97
+ * const content = newArtifactContent('markdown', '报告', '开始编辑', '名称', '数值', '点击')
98
+ * ```
99
+ */
100
+ export function newArtifactContent(kind, title, body, label, value, button) {
101
+ if (kind === 'html')
102
+ return `<!doctype html>\n<html><head><meta charset="utf-8"><style>body{font-family:system-ui;padding:2rem}button{padding:.6rem 1rem;margin-right:1rem}</style></head><body><h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p><button onclick="document.querySelector('output').textContent=Number(document.querySelector('output').textContent)+1">${escapeHtml(button)}</button><output>0</output></body></html>`;
103
+ if (kind === 'table') {
104
+ return JSON.stringify({
105
+ table_columns: [
106
+ { key: 'name', label, type: 'text' },
107
+ { key: 'value', label: value, type: 'number' },
108
+ ],
109
+ table_rows: [
110
+ { row_id: 'row-1', name: 'A', value: 10 },
111
+ { row_id: 'row-2', name: 'B', value: 20 },
112
+ ],
113
+ }, null, 2);
114
+ }
115
+ if (kind === 'chart') {
116
+ return JSON.stringify({
117
+ type: 'bar',
118
+ data: [
119
+ { name: 'A', value: 10 },
120
+ { name: 'B', value: 20 },
121
+ ],
122
+ x: 'name',
123
+ y: 'value',
124
+ }, null, 2);
125
+ }
126
+ return `# ${title.replace(/[\\`*_[\]<>#]/g, '\\$&')}\n\n${body}\n`;
127
+ }
@@ -0,0 +1,58 @@
1
+ import type { MarkdownSelectionSnapshot } from '../ai/document-types.js';
2
+ /**
3
+ * 保留复杂源码的可视编辑快照;结构变化失败时不能覆盖原文。
4
+ * @example 模块内部上下文
5
+ * ```ts
6
+ * const result: MarkdownEditResult = { success: true, content: '# 简介' }
7
+ * ```
8
+ */
9
+ export type MarkdownEditResult = {
10
+ success: true;
11
+ content: string;
12
+ } | {
13
+ success: false;
14
+ };
15
+ /**
16
+ * 当前编辑 DOM 与原始 Markdown 的绑定。
17
+ * @example 模块内部上下文
18
+ * ```ts
19
+ * const session: MarkdownEditSession = { enabled: false, read: () => ({ success: false }), readSelection: () => ({ success: false }) }
20
+ * ```
21
+ */
22
+ export interface MarkdownEditSession {
23
+ enabled: boolean;
24
+ read: () => MarkdownEditResult;
25
+ readSelection: (snapshot: MarkdownSelectionSnapshot) => {
26
+ success: true;
27
+ selectedText: string;
28
+ } | {
29
+ success: false;
30
+ };
31
+ }
32
+ /**
33
+ * 将普通块的可视选区投影回源码,无法可靠对齐时失败。
34
+ * @example 模块内部上下文
35
+ * ```ts
36
+ * const host = document.createElement('article')
37
+ * host.innerHTML = '<p>Hello <strong>world</strong>.</p>'
38
+ * const result = readMarkdownSelection('Hello **world**.', host, { start: 0, end: 12, text: 'Hello world.' })
39
+ * ```
40
+ */
41
+ export declare function readMarkdownSelection(content: string, host: HTMLElement, snapshot: MarkdownSelectionSnapshot): {
42
+ success: true;
43
+ selectedText: string;
44
+ } | {
45
+ success: false;
46
+ };
47
+ /**
48
+ * 将普通段落/标题绑定到源码位置,其他块锁定并逐字保留。
49
+ * 不使用 innerText 回写全文;无法可靠对齐的文档降级为源码编辑。
50
+ * @example 模块内部上下文
51
+ * ```ts
52
+ * const host = document.createElement('article')
53
+ * host.innerHTML = '<p>原文</p>'
54
+ * const session = captureMarkdownEdit('原文', host)
55
+ * const result = session.read()
56
+ * ```
57
+ */
58
+ export declare function captureMarkdownEdit(content: string, host: HTMLElement): MarkdownEditSession;