@things-factory/ai-assistant 10.1.113 → 10.1.116

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 (76) hide show
  1. package/client/components/assistant-chat.ts +19 -0
  2. package/client/components/assistant-dock.ts +26 -3
  3. package/client/setup-assistant-dock.ts +3 -2
  4. package/client/utils/entry-proposal.ts +14 -1
  5. package/client/utils/open-page.ts +21 -0
  6. package/dist-client/components/assistant-chat.d.ts +2 -0
  7. package/dist-client/components/assistant-chat.js +19 -0
  8. package/dist-client/components/assistant-chat.js.map +1 -1
  9. package/dist-client/components/assistant-dock.d.ts +5 -0
  10. package/dist-client/components/assistant-dock.js +25 -3
  11. package/dist-client/components/assistant-dock.js.map +1 -1
  12. package/dist-client/setup-assistant-dock.d.ts +1 -0
  13. package/dist-client/setup-assistant-dock.js +1 -0
  14. package/dist-client/setup-assistant-dock.js.map +1 -1
  15. package/dist-client/tsconfig.tsbuildinfo +1 -1
  16. package/dist-client/utils/entry-proposal.d.ts +10 -1
  17. package/dist-client/utils/entry-proposal.js +13 -1
  18. package/dist-client/utils/entry-proposal.js.map +1 -1
  19. package/dist-client/utils/open-page.d.ts +5 -0
  20. package/dist-client/utils/open-page.js +19 -0
  21. package/dist-client/utils/open-page.js.map +1 -0
  22. package/dist-server/service/assistant-mode/resolve.d.ts +1 -0
  23. package/dist-server/service/assistant-mode/resolve.js +2 -1
  24. package/dist-server/service/assistant-mode/resolve.js.map +1 -1
  25. package/dist-server/service/assistant-mode/types.d.ts +2 -0
  26. package/dist-server/service/assistant-mode/types.js.map +1 -1
  27. package/dist-server/service/chat-session/attachment-tool-result.d.ts +28 -0
  28. package/dist-server/service/chat-session/attachment-tool-result.js +9 -0
  29. package/dist-server/service/chat-session/attachment-tool-result.js.map +1 -0
  30. package/dist-server/service/chat-session/attachment-tools.js +4 -5
  31. package/dist-server/service/chat-session/attachment-tools.js.map +1 -1
  32. package/dist-server/service/data-entry/entry-apply.d.ts +8 -0
  33. package/dist-server/service/data-entry/entry-apply.js +19 -2
  34. package/dist-server/service/data-entry/entry-apply.js.map +1 -1
  35. package/dist-server/service/data-entry/entry-refusal.d.ts +6 -0
  36. package/dist-server/service/data-entry/entry-refusal.js +25 -0
  37. package/dist-server/service/data-entry/entry-refusal.js.map +1 -0
  38. package/dist-server/service/data-entry/entry-resolver.js +2 -0
  39. package/dist-server/service/data-entry/entry-resolver.js.map +1 -1
  40. package/dist-server/service/data-read/list-read.d.ts +36 -0
  41. package/dist-server/service/data-read/list-read.js +64 -0
  42. package/dist-server/service/data-read/list-read.js.map +1 -0
  43. package/dist-server/service/data-read/read-target.d.ts +109 -0
  44. package/dist-server/service/data-read/read-target.js +189 -0
  45. package/dist-server/service/data-read/read-target.js.map +1 -0
  46. package/dist-server/service/data-read/read-tools.d.ts +228 -0
  47. package/dist-server/service/data-read/read-tools.js +197 -0
  48. package/dist-server/service/data-read/read-tools.js.map +1 -0
  49. package/dist-server/service/index.d.ts +3 -0
  50. package/dist-server/service/index.js +7 -1
  51. package/dist-server/service/index.js.map +1 -1
  52. package/dist-server/tsconfig.tsbuildinfo +1 -1
  53. package/package.json +5 -5
  54. package/server/service/assistant-mode/resolve.ts +3 -2
  55. package/server/service/assistant-mode/types.ts +2 -0
  56. package/server/service/chat-session/attachment-tool-result.test.ts +26 -0
  57. package/server/service/chat-session/attachment-tool-result.ts +18 -0
  58. package/server/service/chat-session/attachment-tools.ts +4 -5
  59. package/server/service/data-entry/data-entry-update.test.ts +10 -1
  60. package/server/service/data-entry/data-entry.test.ts +29 -1
  61. package/server/service/data-entry/entry-apply.ts +27 -2
  62. package/server/service/data-entry/entry-refusal.test.ts +73 -0
  63. package/server/service/data-entry/entry-refusal.ts +20 -0
  64. package/server/service/data-entry/entry-resolver.ts +2 -0
  65. package/server/service/data-read/data-read.test.ts +229 -0
  66. package/server/service/data-read/list-read.ts +98 -0
  67. package/server/service/data-read/read-target.ts +230 -0
  68. package/server/service/data-read/read-tools.ts +212 -0
  69. package/server/service/index.ts +4 -0
  70. package/test/entry-proposal.test.ts +31 -1
  71. package/test/open-page.test.ts +31 -0
  72. package/translations/en.json +14 -0
  73. package/translations/ja.json +14 -0
  74. package/translations/ko.json +14 -0
  75. package/translations/ms.json +14 -0
  76. package/translations/zh.json +14 -0
@@ -0,0 +1,98 @@
1
+ /*
2
+ * A list declared in one line (operato-application/design/ai/read-targets.md §3) - the shape most list screens share:
3
+ * a ListParam query, the fields it reads, a date to range over, a status, an amount, search words, and a screen.
4
+ * Each application writes its lists as these lines; this turns one into a read target with the conditions it takes.
5
+ */
6
+ import type { ReadColumn, ReadCriterion, ReadTarget } from './read-target.js'
7
+
8
+ export interface ListRead {
9
+ /** `<app>.<record>`. */
10
+ key: string
11
+ /** i18n key of the screen's title - the card's name. */
12
+ title: string
13
+ /** The screen's name as the person knows it - the model picks the list by it. */
14
+ name: string
15
+ /** The ListParam query (`cashTransactions`). */
16
+ listQuery: string
17
+ /** The fields of each item it reads - the screen's own selection where there is one. */
18
+ selection: string
19
+ columns: ReadColumn[]
20
+ /** A date (or date-time) field the `from` / `to` conditions range over. */
21
+ dateField?: string
22
+ /** Integer year and month fields, and an in/out field (INCOME | EXPENSE) - the `year`, `month`, `flow` conditions. */
23
+ narrowing?: { year?: string; month?: string; flow?: string }
24
+ /** A field holding the period as YYYY-MM - the `period` condition. */
25
+ monthField?: string
26
+ /** A status field and its values - the `status` condition. */
27
+ status?: { field: string; values: string[] }
28
+ /** The resolver's searchables, said for the model - the list takes ListParam search (the `text` condition). */
29
+ search?: string
30
+ /** The screen's route. Left out, the list has no screen card. */
31
+ route?: string
32
+ /** The conditions the screen reads from its address - `year`, `month`, `flow` and `text` (as `search`). Empty: it opens as it is. */
33
+ screenTakes?: ('year' | 'month' | 'flow' | 'text')[]
34
+ }
35
+
36
+ /** The money column a minimum or maximum amount means - `amount` when there is one, else the first summed column. */
37
+ const amountOf = (list: ListRead) => list.columns.find(one => one.name === 'amount' && one.type === 'number')?.name ?? list.columns.find(one => one.total)?.name
38
+
39
+ export function listReadTarget(list: ListRead): ReadTarget {
40
+ const search = !!list.search
41
+ const amount = amountOf(list)
42
+ const narrowing = list.narrowing ?? {}
43
+ const criteria: ReadCriterion[] = [
44
+ ...(list.dateField
45
+ ? [
46
+ { name: 'from', type: 'date', labelKey: 'ai-assistant.read.from', description: `the first ${list.dateField}, inclusive`, filter: (v: any) => ({ name: list.dateField!, operator: 'gte', value: v }) },
47
+ { name: 'to', type: 'date', labelKey: 'ai-assistant.read.to', description: `the last ${list.dateField}, inclusive`, filter: (v: any) => ({ name: list.dateField!, operator: 'lte', value: `${v}${/T/.test(String(v)) ? '' : 'T23:59:59.999'}` }) }
48
+ ]
49
+ : []),
50
+ ...(narrowing.year ? [{ name: 'year', type: 'integer', labelKey: 'ai-assistant.read.year', description: 'a year (2026)', filter: (v: any) => ({ name: narrowing.year!, operator: 'eq', value: v }) }] : []),
51
+ ...(narrowing.month ? [{ name: 'month', type: 'integer', labelKey: 'ai-assistant.read.month', description: '1-12, with a year', filter: (v: any) => ({ name: narrowing.month!, operator: 'eq', value: v }) }] : []),
52
+ ...(narrowing.flow
53
+ ? [{ name: 'flow', type: 'enum', values: ['INCOME', 'EXPENSE'], labelKey: 'ai-assistant.read.flow', description: 'money in or out', filter: (v: any) => ({ name: narrowing.flow!, operator: 'eq', value: v }) }]
54
+ : []),
55
+ ...(list.monthField
56
+ ? [{ name: 'period', type: 'string', labelKey: 'ai-assistant.read.period', description: 'a month as YYYY-MM', filter: (v: any) => ({ name: list.monthField!, operator: 'eq', value: v }) }]
57
+ : []),
58
+ ...(list.status
59
+ ? [{ name: 'status', type: 'enum', values: list.status.values, labelKey: 'ai-assistant.read.status', filter: (v: any) => ({ name: list.status!.field, operator: 'eq', value: v }) }]
60
+ : []),
61
+ ...(amount
62
+ ? [
63
+ { name: 'minAmount', type: 'number', labelKey: 'ai-assistant.read.min-amount', description: `at least this ${amount}`, filter: (v: any) => ({ name: amount, operator: 'gte', value: v }) },
64
+ { name: 'maxAmount', type: 'number', labelKey: 'ai-assistant.read.max-amount', description: `at most this ${amount}`, filter: (v: any) => ({ name: amount, operator: 'lte', value: v }) }
65
+ ]
66
+ : [])
67
+ ] as ReadCriterion[]
68
+
69
+ const takes = (list.screenTakes ?? []).filter(name => (name === 'text' ? search : !!narrowing[name]))
70
+ return {
71
+ key: list.key,
72
+ labelKey: list.title,
73
+ description: `the rows of the list 「${list.name}」 (${list.columns.map(one => one.name).join(', ')}).`,
74
+ query:
75
+ `query ($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]${search ? ', $search: String' : ''}) ` +
76
+ `{ ${list.listQuery}(filters: $filters, pagination: $pagination, sortings: $sortings${search ? ', search: $search' : ''}) { items { ${list.selection} } total } }`,
77
+ criteria,
78
+ columns: list.columns,
79
+ rowsOf: data => ({ rows: data?.[list.listQuery]?.items ?? [], total: data?.[list.listQuery]?.total ?? 0 }),
80
+ ...(search ? { search: { description: `the ${list.search}` } } : {}),
81
+ ...(list.dateField ? { sortings: [{ name: list.dateField, desc: true }] } : {}),
82
+ ...(list.route
83
+ ? {
84
+ screen: {
85
+ route: list.route,
86
+ labelKey: list.title,
87
+ takes,
88
+ params: (c: Record<string, any>) => ({
89
+ ...(takes.includes('year') ? { year: c.year } : {}),
90
+ ...(takes.includes('month') && c.year ? { month: c.month } : {}),
91
+ ...(takes.includes('flow') ? { flow: c.flow } : {}),
92
+ ...(takes.includes('text') ? { search: c.text } : {})
93
+ })
94
+ }
95
+ }
96
+ : {})
97
+ }
98
+ }
@@ -0,0 +1,230 @@
1
+ /*
2
+ * AI 조회 - an application's list, read through its own query as the person (operato-application/design/ai/read-targets.md).
3
+ *
4
+ * The application declares what it lets the assistant read: its list query, the conditions the model may set and
5
+ * how each becomes one of the query's filters, the columns to show, and the screen that lists the same records.
6
+ * The framework reads the rows through that query with the person's request state - the same @privilege and
7
+ * domain as the screen - counts and sums them itself, and puts a long result on the AI 작업판 as the query returned
8
+ * it. The model is told the count, the sums and a few rows; it never copies a table.
9
+ *
10
+ * Pure but for the GraphQL runner, which comes in as an argument - the rules are tested without a server.
11
+ */
12
+ import { readFieldValue, rootFieldOf, type EntryField } from '../data-entry/entry-target.js'
13
+ import type { GraphqlRunner } from '../data-entry/entry-update.js'
14
+
15
+ export interface ReadFilter {
16
+ name: string
17
+ operator: string
18
+ value: unknown
19
+ }
20
+
21
+ /** A condition the model may set - read with the entry fields' rules, turned into the query's filters by the application. */
22
+ export interface ReadCriterion extends Omit<EntryField, 'required' | 'reference' | 'total'> {
23
+ filter: (value: any) => ReadFilter | ReadFilter[]
24
+ }
25
+
26
+ export interface ReadColumn {
27
+ /** The key in the workspace table. */
28
+ name: string
29
+ /** Where the value is in a row - a dotted path into the query's item (`account.name`). Defaults to `name`. */
30
+ path?: string
31
+ type: 'string' | 'number' | 'date'
32
+ labelKey?: string
33
+ /** A number column the server sums. */
34
+ total?: boolean
35
+ }
36
+
37
+ export interface ReadScreen {
38
+ /** The application's route of the list screen (`cash-transaction-list`). */
39
+ route: string
40
+ /** The conditions the screen takes, as its address's query arguments. A condition left out is said on the card. */
41
+ params: (criteria: Record<string, any>) => Record<string, string | number | undefined>
42
+ /** The conditions `params` carries - the card names the others as not applied on the screen. */
43
+ takes: string[]
44
+ labelKey?: string
45
+ }
46
+
47
+ export interface ReadTarget {
48
+ /** `<app>.<record>` - the tools are named after it. */
49
+ key: string
50
+ /** i18n key naming the records (「은행 입출금」). */
51
+ labelKey?: string
52
+ /** What the records are, for the model. */
53
+ description: string
54
+ /**
55
+ * The list query - takes `$filters: [Filter!]`, `$pagination: Pagination` and `$sortings: [Sorting!]`, and
56
+ * `$search: String` when `search` is declared.
57
+ */
58
+ query: string
59
+ /**
60
+ * The list takes ListParam's free-text term, matched by the resolver across its own searchable fields - the
61
+ * condition `text`. Say what it finds in, for the model.
62
+ */
63
+ search?: { description: string }
64
+ criteria: ReadCriterion[]
65
+ columns: ReadColumn[]
66
+ rowsOf: (data: any) => { rows: any[]; total: number }
67
+ /** Orders the rows; the query's own order when left out. */
68
+ sortings?: { name: string; desc?: boolean }[]
69
+ screen?: ReadScreen
70
+ }
71
+
72
+ /** At most this many rows are read - the AI 작업판 table's own limit (workspace-blocks MAX_TABLE_ROWS). */
73
+ export const MAX_READ_ROWS = 1000
74
+ /** Rows the model is shown; the rest stay on the card. */
75
+ export const ROWS_FOR_MODEL = 20
76
+ /** A page of the list query. */
77
+ export const READ_PAGE = 200
78
+
79
+ const registry = new Map<string, ReadTarget>()
80
+
81
+ const pascalOf = (key: string) =>
82
+ key
83
+ .split(/[^a-zA-Z0-9]+/)
84
+ .filter(Boolean)
85
+ .map(part => part[0].toUpperCase() + part.slice(1))
86
+ .join('')
87
+
88
+ export const queryToolName = (key: string) => `query${pascalOf(key)}`
89
+ export const screenToolName = (key: string) => `open${pascalOf(key)}Screen`
90
+ export const readCategoryName = (key: string) => `data-read:${key}`
91
+
92
+ export function declareReadTarget(target: ReadTarget): void {
93
+ if (!/^[a-z0-9-]+\.[a-z0-9-]+$/.test(target.key)) throw new Error(`read target key '${target.key}' is not <app>.<record>`)
94
+ if (registry.has(target.key)) throw new Error(`read target '${target.key}' is declared twice`)
95
+ rootFieldOf(target.query, 'query')
96
+ if (!target.columns.length) throw new Error(`read target '${target.key}' shows no column`)
97
+ const names = new Set<string>()
98
+ for (const criterion of target.criteria) {
99
+ if (criterion.name === 'id') throw new Error(`read target '${target.key}' declares 'id' - every target takes it`)
100
+ if (criterion.name === 'text' && target.search) throw new Error(`read target '${target.key}' declares 'text' and search - search is the text condition`)
101
+ if (names.has(criterion.name)) throw new Error(`read target '${target.key}' names the condition '${criterion.name}' twice`)
102
+ names.add(criterion.name)
103
+ if (criterion.type === 'enum' && !criterion.values?.length) throw new Error(`condition '${criterion.name}' of '${target.key}' lists no values`)
104
+ }
105
+ if (target.search) names.add('text')
106
+ for (const taken of target.screen?.takes ?? []) if (!names.has(taken)) throw new Error(`the screen of '${target.key}' takes '${taken}', which is no condition`)
107
+ registry.set(target.key, target)
108
+ }
109
+
110
+ export function readTargetOf(key: string | undefined): ReadTarget | undefined {
111
+ return key ? registry.get(key) : undefined
112
+ }
113
+
114
+ export function clearReadTargets(): void {
115
+ registry.clear()
116
+ }
117
+
118
+ /** The conditions the model set, read by their declared types; a value that does not fit is said, never guessed at. */
119
+ export function readCriteria(target: ReadTarget, args: any): { criteria: Record<string, unknown>; refused: { name: string; code: string }[] } {
120
+ const criteria: Record<string, unknown> = {}
121
+ const refused: { name: string; code: string }[] = []
122
+ /* One record by its id - every target takes it (the id a list answer or a find tool gave). */
123
+ if (typeof args?.id === 'string' && args.id.trim()) criteria.id = args.id.trim()
124
+ if (target.search && typeof args?.text === 'string' && args.text.trim()) criteria.text = args.text.trim()
125
+ for (const criterion of target.criteria) {
126
+ const value = args?.[criterion.name]
127
+ if (value === undefined || value === null || value === '') continue
128
+ const { read, code } = readFieldValue(criterion as EntryField, value)
129
+ if (read === undefined) refused.push({ name: criterion.name, code: code ?? 'unreadable' })
130
+ else criteria[criterion.name] = read
131
+ }
132
+ return { criteria, refused }
133
+ }
134
+
135
+ export function filtersOf(target: ReadTarget, criteria: Record<string, unknown>): ReadFilter[] {
136
+ return [
137
+ ...(typeof criteria.id === 'string' ? [{ name: 'id', operator: 'eq', value: criteria.id }] : []),
138
+ ...target.criteria.flatMap(criterion => (criterion.name in criteria ? [criterion.filter(criteria[criterion.name])].flat() : []))
139
+ ]
140
+ }
141
+
142
+ const valueAt = (row: any, path: string) => path.split('.').reduce((at, part) => (at === null || at === undefined ? undefined : at[part]), row)
143
+
144
+ /** One row as the columns say - a number column as a number, a missing value as null. */
145
+ export function rowOf(target: ReadTarget, item: any): Record<string, string | number | null> {
146
+ return Object.fromEntries([
147
+ /* The id names the record to the model - for one record's detail, a change, or its screen. */
148
+ ...(item?.id ? [['id', String(item.id)] as [string, string]] : []),
149
+ ...target.columns.map(column => {
150
+ const raw = valueAt(item, column.path ?? column.name)
151
+ if (raw === undefined || raw === null || raw === '') return [column.name, null]
152
+ if (column.type === 'number') {
153
+ const number = Number(raw)
154
+ return [column.name, Number.isFinite(number) ? number : null]
155
+ }
156
+ return [column.name, String(raw)]
157
+ })
158
+ ])
159
+ }
160
+
161
+ /**
162
+ * Reads the rows through the application's query, page by page, up to MAX_READ_ROWS. `complete` is false when the
163
+ * list holds more - a sum of the rows read is then not the sum of the list, and is never said as one.
164
+ */
165
+ export async function readRows(target: ReadTarget, filters: ReadFilter[], run: GraphqlRunner, search?: string): Promise<{ rows: Record<string, any>[]; total: number; complete: boolean }> {
166
+ const rows: Record<string, any>[] = []
167
+ let total = 0
168
+ for (let page = 1; rows.length < MAX_READ_ROWS; page++) {
169
+ const answer = await run(target.query, {
170
+ filters,
171
+ ...(search ? { search } : {}),
172
+ pagination: { page, limit: READ_PAGE },
173
+ ...(target.sortings ? { sortings: target.sortings } : {})
174
+ })
175
+ if (answer.errors?.length) throw new Error(answer.errors.map(one => one.message).join('; '))
176
+ const read = target.rowsOf(answer.data)
177
+ total = Number(read?.total) || 0
178
+ const items = read?.rows ?? []
179
+ rows.push(...items.slice(0, MAX_READ_ROWS - rows.length).map(item => rowOf(target, item)))
180
+ if (items.length < READ_PAGE || rows.length >= total) break
181
+ }
182
+ return { rows, total, complete: rows.length >= total }
183
+ }
184
+
185
+ export interface ReadGroup {
186
+ key: string
187
+ count: number
188
+ sums: Record<string, number>
189
+ }
190
+
191
+ /** The sums of the number columns marked total - the server's, never the model's. */
192
+ export function sumsOf(target: ReadTarget, rows: Record<string, any>[]): Record<string, number> {
193
+ const sums: Record<string, number> = {}
194
+ for (const column of target.columns.filter(one => one.total && one.type === 'number')) {
195
+ sums[column.name] = Math.round(rows.reduce((sum, row) => sum + (typeof row[column.name] === 'number' ? row[column.name] : 0), 0) * 100) / 100
196
+ }
197
+ return sums
198
+ }
199
+
200
+ /** The rows grouped by one column - a date column by its month - each with its count and sums, largest first. */
201
+ export function groupsOf(target: ReadTarget, rows: Record<string, any>[], by: string): ReadGroup[] | undefined {
202
+ const column = target.columns.find(one => one.name === by)
203
+ if (!column) return undefined
204
+ const groups = new Map<string, Record<string, any>[]>()
205
+ for (const row of rows) {
206
+ const value = row[by]
207
+ const key = value === null || value === undefined ? '' : column.type === 'date' ? String(value).slice(0, 7) : String(value)
208
+ groups.set(key, [...(groups.get(key) ?? []), row])
209
+ }
210
+ const list = [...groups].map(([key, members]) => ({ key, count: members.length, sums: sumsOf(target, members) }))
211
+ const first = target.columns.find(one => one.total)?.name
212
+ return column.type === 'date'
213
+ ? list.sort((a, b) => a.key.localeCompare(b.key))
214
+ : list.sort((a, b) => (first ? Math.abs(b.sums[first] ?? 0) - Math.abs(a.sums[first] ?? 0) : b.count - a.count))
215
+ }
216
+
217
+ /** The address of the target's list screen with the conditions it takes, and the conditions it does not. */
218
+ export function screenAddress(target: ReadTarget, criteria: Record<string, unknown>): { href: string; applied: string[]; notApplied: string[] } | undefined {
219
+ const screen = target.screen
220
+ if (!screen) return undefined
221
+ const params = new URLSearchParams()
222
+ for (const [name, value] of Object.entries(screen.params(criteria))) if (value !== undefined && value !== null && value !== '') params.set(name, String(value))
223
+ const given = Object.keys(criteria)
224
+ const query = params.toString()
225
+ return {
226
+ href: query ? `${screen.route}?${query}` : screen.route,
227
+ applied: given.filter(name => screen.takes.includes(name)),
228
+ notApplied: given.filter(name => !screen.takes.includes(name))
229
+ }
230
+ }
@@ -0,0 +1,212 @@
1
+ /*
2
+ * The tools of an AI 조회 target (operato-application/design/ai/read-targets.md §4, §5).
3
+ *
4
+ * query<X> reads the rows through the application's list query as the person, and tells the model the count, the
5
+ * sums, the groups and a few rows. A longer result goes on the AI 작업판 as a proposal the server builds from the rows
6
+ * themselves - the table is never written by the model. open<X>Screen reads nothing: it hands the card the address
7
+ * of the application's list screen with the conditions it takes.
8
+ */
9
+ import { registerToolCategory, type ToolCategory, type ToolSpec } from '@things-factory/ai-client-base'
10
+
11
+ import { rootFieldOf } from '../data-entry/entry-target.js'
12
+ import type { GraphqlRunner } from '../data-entry/entry-update.js'
13
+ import { runAsCaller } from '../data-entry/entry-tools.js'
14
+ import { normalizeWorkspace, workspaceContents } from '../workspace/workspace-blocks.js'
15
+ import {
16
+ declareReadTarget,
17
+ filtersOf,
18
+ groupsOf,
19
+ queryToolName,
20
+ readCategoryName,
21
+ readCriteria,
22
+ readRows,
23
+ ROWS_FOR_MODEL,
24
+ screenAddress,
25
+ screenToolName,
26
+ sumsOf,
27
+ type ReadCriterion,
28
+ type ReadTarget
29
+ } from './read-target.js'
30
+
31
+ /** The reader's words for a key - the key's own default when the translator has none. */
32
+ const wordsOf = (context: any) => (key: string | undefined, fallback: string) => {
33
+ if (!key || typeof context?.t !== 'function') return fallback
34
+ try {
35
+ const said = context.t(key)
36
+ return said && said !== key ? String(said) : fallback
37
+ } catch {
38
+ return fallback
39
+ }
40
+ }
41
+
42
+ function criterionSchema(criterion: ReadCriterion): any {
43
+ /* One type per field - Gemini's function schema refuses a list of types (2026-10-01). */
44
+ const type = criterion.type === 'number' ? 'number' : criterion.type === 'integer' ? 'integer' : criterion.type === 'boolean' ? 'boolean' : 'string'
45
+ const said = [criterion.description, criterion.type === 'date' ? 'YYYY-MM-DD' : undefined, criterion.type === 'enum' ? `one of: ${criterion.values!.join(', ')}` : undefined]
46
+ .filter(Boolean)
47
+ .join('. ')
48
+ return { type, ...(said ? { description: said } : {}) }
49
+ }
50
+
51
+ export async function queryRecords(target: ReadTarget, args: any, context: any, run: GraphqlRunner) {
52
+ const { criteria, refused } = readCriteria(target, args)
53
+ if (refused.length) {
54
+ return { rejected: true, error: 'condition-unreadable', refused, message: `these conditions do not fit their type: ${refused.map(one => `${one.name} (${one.code})`).join(', ')}. Fix them and call again.` }
55
+ }
56
+ let read
57
+ try {
58
+ read = await readRows(target, filtersOf(target, criteria), run, typeof criteria.text === 'string' && target.search ? criteria.text : undefined)
59
+ } catch (error: any) {
60
+ return { rejected: true, error: 'query-failed', message: `the list could not be read: ${error?.message ?? error}` }
61
+ }
62
+ const { rows, total, complete } = read
63
+ const sums = sumsOf(target, rows)
64
+ const groupBy = typeof args?.groupBy === 'string' && args.groupBy ? args.groupBy : undefined
65
+ const groups = groupBy ? groupsOf(target, rows, groupBy) : undefined
66
+ const words = wordsOf(context)
67
+ const label = words(target.labelKey, target.key)
68
+
69
+ const said = {
70
+ target: target.key,
71
+ criteria,
72
+ total,
73
+ read: rows.length,
74
+ complete,
75
+ sums,
76
+ ...(groupBy ? (groups ? { groupBy, groups: groups.slice(0, 50), ...(groups.length > 50 ? { moreGroups: groups.length - 50 } : {}) } : { groupBy, groupRefused: 'no such column' }) : {}),
77
+ rows: rows.slice(0, ROWS_FOR_MODEL),
78
+ ...(rows.length > ROWS_FOR_MODEL ? { rowsNotShown: rows.length - ROWS_FOR_MODEL } : {})
79
+ }
80
+ const incomplete = complete
81
+ ? ''
82
+ : ` Only ${rows.length} of ${total} rows were read; the sums and groups are of those rows, not of the list - say so, and ask the person to narrow the conditions.`
83
+
84
+ if (rows.length === 1 && args?.show !== 'workspace') {
85
+ return { ...said, record: rows[0], message: 'one record - answer from its fields; say a field it does not have as not recorded.' }
86
+ }
87
+ if (rows.length <= ROWS_FOR_MODEL && args?.show !== 'workspace') {
88
+ return { ...said, message: `${rows.length} rows of ${total}.${incomplete} Answer from these rows; every number you say comes from them.` }
89
+ }
90
+
91
+ /* The workspace is built here from the rows as read - the model never copies the table. */
92
+ const columns = target.columns.map(column => ({ name: column.name, label: words(column.labelKey, column.name), type: column.type }))
93
+ const totalColumns = target.columns.filter(one => one.total)
94
+ const title = typeof args?.title === 'string' && args.title.trim() ? args.title.trim() : `${label} · ${rows.length}`
95
+ const { workspace } = normalizeWorkspace({
96
+ name: typeof args?.name === 'string' && args.name ? args.name : target.key.replace(/\./g, '-'),
97
+ title,
98
+ ...(complete ? {} : { summary: `${total} / ${rows.length}` }),
99
+ blocks: [
100
+ {
101
+ kind: 'metrics',
102
+ items: [{ label: words('ai-assistant.read.count', 'rows'), value: String(rows.length), ...(complete ? {} : { note: `/ ${total}` }) }, ...totalColumns.map(column => ({ label: words(column.labelKey, column.name), value: String(sums[column.name]) }))]
103
+ },
104
+ ...(groups
105
+ ? [
106
+ {
107
+ kind: 'table',
108
+ caption: words(target.columns.find(one => one.name === groupBy)?.labelKey, groupBy!),
109
+ columns: [{ name: 'key', label: words(target.columns.find(one => one.name === groupBy)?.labelKey, groupBy!), type: 'string' }, { name: 'count', label: words('ai-assistant.read.count', 'rows'), type: 'number' }, ...totalColumns.map(column => ({ name: column.name, label: words(column.labelKey, column.name), type: 'number' }))],
110
+ rows: groups.map(group => ({ key: group.key, count: group.count, ...group.sums }))
111
+ }
112
+ ]
113
+ : []),
114
+ { kind: 'table', caption: label, columns, rows }
115
+ ]
116
+ })
117
+ return {
118
+ proposed: true,
119
+ kind: 'workspace',
120
+ icon: 'table_view',
121
+ label: title,
122
+ ...said,
123
+ forScreen: { workspace, contents: workspaceContents(workspace!) },
124
+ message: `${rows.length} rows of ${total} are on the AI 작업판 as read - the person opens it from the card.${incomplete} Say the point in one or two lines from the sums, groups and rows above; do not write the table out.`
125
+ }
126
+ }
127
+
128
+ export function openScreen(target: ReadTarget, args: any, context: any) {
129
+ const { criteria, refused } = readCriteria(target, args)
130
+ if (refused.length) return { rejected: true, error: 'condition-unreadable', refused, message: 'fix the conditions and call again.' }
131
+ const address = screenAddress(target, criteria)
132
+ if (!address) return { rejected: true, error: 'no-screen', message: 'this list has no screen to open.' }
133
+ const words = wordsOf(context)
134
+ return {
135
+ proposed: true,
136
+ kind: 'open-page',
137
+ icon: 'open_in_new',
138
+ label: words(target.screen!.labelKey ?? target.labelKey, target.key),
139
+ target: target.key,
140
+ href: address.href,
141
+ applied: address.applied,
142
+ notApplied: address.notApplied,
143
+ /* The card says them in the reader's words. */
144
+ notAppliedLabels: address.notApplied.map(name => words(target.criteria.find(one => one.name === name)?.labelKey ?? (name === 'text' || name === 'id' ? `ai-assistant.read.${name}` : undefined), name)),
145
+ message:
146
+ 'the card opens the screen when the person presses it.' +
147
+ (address.notApplied.length ? ` The screen does not take ${address.notApplied.join(', ')} - say so.` : '')
148
+ }
149
+ }
150
+
151
+ export function readCategoryOf(target: ReadTarget, run: (context: any) => GraphqlRunner = runAsCaller): ToolCategory {
152
+ const door = rootFieldOf(target.query, 'query')
153
+ const conditions = {
154
+ ...Object.fromEntries(target.criteria.map(criterion => [criterion.name, criterionSchema(criterion)])),
155
+ ...(target.search ? { text: { type: 'string', description: `words to find - ${target.search.description}` } } : {})
156
+ }
157
+ const specs: ToolSpec[] = [
158
+ {
159
+ kind: 'read',
160
+ name: queryToolName(target.key),
161
+ /* The person must be able to read the list on its screen - the tool is not a second way in. */
162
+ doors: [door],
163
+ description:
164
+ `Read ${target.description} Set the conditions the question names. Returns the count, the sums, ` +
165
+ `groups when groupBy is given (a date column groups by month) and the first ${ROWS_FOR_MODEL} rows; more rows go on the AI 작업판 as read.`,
166
+ schema: {
167
+ type: 'object',
168
+ properties: {
169
+ id: { type: 'string', description: 'One record by its id, from an earlier answer - its detail.' },
170
+ ...conditions,
171
+ groupBy: { type: 'string', description: `One column to group by: ${target.columns.map(one => one.name).join(', ')}.` },
172
+ show: { type: 'string', enum: ['answer', 'workspace'], description: 'workspace to put even a short result on the AI 작업판.' },
173
+ title: { type: 'string', description: 'The workspace title, in the person\'s language.' },
174
+ name: { type: 'string', description: 'The workspace key; the same key again makes a new version.' }
175
+ }
176
+ },
177
+ builder: (args: any, context: any) => queryRecords(target, args, context, run(context))
178
+ } as ToolSpec,
179
+ ...(target.screen
180
+ ? [
181
+ {
182
+ kind: 'read',
183
+ name: screenToolName(target.key),
184
+ doors: [door],
185
+ description: `Offer the person the screen that lists ${target.description} with these conditions. Reads nothing. The screen takes: ${target.screen.takes.join(', ')}.`,
186
+ schema: { type: 'object', properties: conditions },
187
+ builder: (args: any, context: any) => openScreen(target, args, context)
188
+ } as ToolSpec
189
+ ]
190
+ : [])
191
+ ]
192
+ return {
193
+ name: readCategoryName(target.key),
194
+ description: `data read: ${target.key}`,
195
+ guidance: [
196
+ `- To answer from ${target.key} records - a list, or one record found by its name, code or id - call ${queryToolName(target.key)} with the conditions the question names. Every number you say comes from its result - never add up rows yourself; use its sums and groups.`,
197
+ `- A list, a summary by item or month, or a comparison: call it with groupBy, and let a long result go on the AI 작업판 - then answer in one or two lines.`,
198
+ `- When the result says complete: false, say how many of how many were read and ask to narrow - never call partial sums the total.`,
199
+ ...(target.screen ? [`- When the person wants to work on the records themselves (edit, sort, export), call ${screenToolName(target.key)}; say which conditions the screen does not take.`] : [])
200
+ ].join('\n'),
201
+ specs
202
+ }
203
+ }
204
+
205
+ /**
206
+ * What an application calls at boot to let the assistant read one of its lists. A mode opens it by naming the key
207
+ * in `readTargets`.
208
+ */
209
+ export function registerReadTarget(target: ReadTarget): void {
210
+ declareReadTarget(target)
211
+ registerToolCategory(readCategoryOf(target))
212
+ }
@@ -28,6 +28,10 @@ export * from './tool-access.js'
28
28
  /* Data entry from material - an app registers what it can enter; a mode names it (design/ai/data-entry.md). */
29
29
  export * from './data-entry/entry-target.js'
30
30
  export { registerEntryTarget, entryCategoryOf } from './data-entry/entry-tools.js'
31
+ /* Reading an application's lists - an app registers what it lets read; a mode names it (design/ai/read-targets.md). */
32
+ export * from './data-read/read-target.js'
33
+ export { registerReadTarget, readCategoryOf } from './data-read/read-tools.js'
34
+ export * from './data-read/list-read.js'
31
35
  /* The AI 작업판 - large results on a page of their own (design/ai/workspace.md). */
32
36
  export * from './workspace/workspace-blocks.js'
33
37
  /* 무엇이 근거인가 — 도구 결과 밖의 셋(프롬프트 · 대화 · 화면 스냅숏). */
@@ -5,6 +5,9 @@
5
5
  import { readFileSync } from 'fs'
6
6
  import { join } from 'path'
7
7
 
8
+ const mockNotify = jest.fn()
9
+ jest.mock('@operato/layout', () => ({ notify: (...args: any[]) => mockNotify(...args) }))
10
+
8
11
  import { runProposal, setEntryProposalHandler } from '../client/utils/assistant-proposals'
9
12
  import {
10
13
  entryGroupOf,
@@ -78,6 +81,34 @@ describe('the entry card', () => {
78
81
  expect(outcome).toMatchObject({ verdict: 'accepted', applied: 1, missed: 0 })
79
82
  })
80
83
 
84
+ it('a closed door emits one generic notification and keeps its refused verdict', async () => {
85
+ const refusal = { message: 'required', extensions: { code: 'FORBIDDEN', because: 'role', operation: 'mutation', requires: { category: 'warehouse', privilege: 'mutation' } }, path: ['addExpenseLine'] }
86
+ const report = jest.fn()
87
+ const handler = entryProposalHandler(async () => ({ verdict: 'refused', errorCode: 'door-closed', applied: 0, missed: 0, refusal }), t, () => undefined, report)
88
+ const context = { sessionId: 's', confirm: async () => true, notify: () => {} }
89
+ expect(await handler(card('k'), context)).toMatchObject({ verdict: 'refused', errorCode: 'door-closed', applied: 0 })
90
+ expect(report.mock.calls).toEqual([[{ level: 'error', message: 'required', ex: [refusal] }]])
91
+ const broken = entryProposalHandler(async () => ({ verdict: 'refused', errorCode: 'door-closed', refusal }), t, () => undefined, () => { throw new Error('toast unavailable') })
92
+ expect(await broken(card('k'), context)).toMatchObject({ verdict: 'refused', errorCode: 'door-closed' })
93
+ const rejected = entryProposalHandler(async () => ({ verdict: 'refused', errorCode: 'door-closed', refusal }), t, () => undefined, async () => { throw new Error('async delivery unavailable') })
94
+ expect(await rejected(card('k'), context)).toMatchObject({ verdict: 'refused', errorCode: 'door-closed' })
95
+ })
96
+
97
+ it('successful and stale-review answers emit no refusal notification', async () => {
98
+ const report = jest.fn()
99
+ for (const answer of [{ verdict: 'accepted', applied: 1 }, { verdict: 'refused', errorCode: 'review-stale' }] as EntryApplyAnswer[]) {
100
+ await entryProposalHandler(async () => answer, t, () => undefined, report)(card('k'), { sessionId: 's', confirm: async () => true, notify: () => {} })
101
+ }
102
+ expect(report).not.toHaveBeenCalled()
103
+ })
104
+
105
+ it('the default transport passes the serialized refusal to layout, with no explicit action', async () => {
106
+ mockNotify.mockClear()
107
+ const refusal = { message: 'required', extensions: { code: 'FORBIDDEN' }, path: ['addExpenseLine'] }
108
+ await entryProposalHandler(async () => ({ verdict: 'refused', errorCode: 'door-closed', refusal }), t)(card('k'), { sessionId: 's', confirm: async () => true, notify: () => {} })
109
+ expect(mockNotify.mock.calls).toEqual([[{ level: 'error', message: 'required', ex: [refusal] }]])
110
+ })
111
+
81
112
  it('the chat draws the review and names the button by the rows it enters', () => {
82
113
  const chat = readFileSync(join(__dirname, '..', 'client', 'components', 'assistant-chat.ts'), 'utf8')
83
114
  expect(chat).toContain('<ox-assistant-entry-review .proposal=${p}>')
@@ -107,4 +138,3 @@ describe('the entry card', () => {
107
138
  expect(entryReadyCount(p)).toBe(2)
108
139
  })
109
140
  })
110
-
@@ -0,0 +1,31 @@
1
+ /*
2
+ * The screen card (design/ai/read-targets.md §5) - it opens an address of the application only, and says the
3
+ * conditions the screen does not take. The chat's wiring is read as text: importing it pulls the shell.
4
+ */
5
+ import { readFileSync } from 'fs'
6
+ import { join } from 'path'
7
+
8
+ import { isAppAddress, isOpenPageProposal, openPageNote } from '../client/utils/open-page'
9
+
10
+ const t = (key: string, options: any = {}) => String(options.defaultValue ?? key).replace(/\{(\w+)\}/g, (_, name) => String(options[name] ?? ''))
11
+
12
+ describe('the screen card', () => {
13
+ it('★ opens an address of the application - never another origin or a script', () => {
14
+ expect(isAppAddress('cash-transaction-list?flow=EXPENSE')).toBe(true)
15
+ for (const href of ['https://evil.example/x', '//evil.example/x', 'javascript:alert(1)', ' JavaScript:alert(1)', '', 42]) expect(isAppAddress(href)).toBe(false)
16
+ expect(isOpenPageProposal({ kind: 'open-page', href: 'javascript:alert(1)' })).toBe(false)
17
+ })
18
+
19
+ it('★ says the conditions the screen does not take', () => {
20
+ expect(openPageNote({ notAppliedLabels: ['기간', '금액'] }, t)).toBe('the screen does not take: 기간, 금액')
21
+ expect(openPageNote({ notAppliedLabels: [] }, t)).toBe('')
22
+ })
23
+
24
+ it('the chat draws it before the generic run button, and opens it through the dock', () => {
25
+ const chat = readFileSync(join(__dirname, '../client/components/assistant-chat.ts'), 'utf8')
26
+ const cards = chat.slice(chat.indexOf('if (isWorkspaceProposal(p))'), chat.indexOf('const card = proposalCardState('))
27
+ expect(cards).toMatch(/if \(isOpenPageProposal\(p\)\) return this\.renderOpenPageCard\(p\)/)
28
+ const card = chat.slice(chat.indexOf('private renderOpenPageCard('), chat.indexOf('private renderWorkspaceCard('))
29
+ expect(card).toMatch(/new CustomEvent\('assistant-open-page', \{ detail: \{ href: p\.href \}/)
30
+ })
31
+ })
@@ -249,6 +249,20 @@
249
249
  "ai-assistant.workspace.versions": "versions",
250
250
  "ai-assistant.workspace.version": "version {version} of {of}",
251
251
  "ai-assistant.workspace.open": "open in workspace",
252
+ "ai-assistant.screen.open": "open the screen",
253
+ "ai-assistant.screen.not-applied": "the screen does not take: {conditions}",
254
+ "ai-assistant.read.count": "rows",
255
+ "ai-assistant.read.from": "from",
256
+ "ai-assistant.read.to": "to",
257
+ "ai-assistant.read.year": "year",
258
+ "ai-assistant.read.month": "month",
259
+ "ai-assistant.read.flow": "in or out",
260
+ "ai-assistant.read.period": "month",
261
+ "ai-assistant.read.status": "status",
262
+ "ai-assistant.read.min-amount": "minimum amount",
263
+ "ai-assistant.read.max-amount": "maximum amount",
264
+ "ai-assistant.read.text": "search words",
265
+ "ai-assistant.read.id": "record",
252
266
  "ai-assistant.workspace.contains-table": "{count} tables",
253
267
  "ai-assistant.workspace.contains-chart": "{count} charts",
254
268
  "ai-assistant.workspace.contains-metrics": "{count} figures",