@frontera-sdk/knowledge 0.0.0-stage → 1.53.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +176 -2
- package/package.json +83 -4
- package/src/errors.ts +89 -0
- package/src/hooks.ts +46 -0
- package/src/knowledge-client.ts +155 -0
- package/src/provider.tsx +20 -0
- package/src/routes.ts +55 -0
- package/src/types.ts +187 -0
- package/src/upload-files.ts +133 -0
- package/src/wait-until-ready.ts +120 -0
- package/src/wire-types.ts +588 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Sebati
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,177 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @frontera-sdk/knowledge
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A typed client for Frontera Knowledge. From a backend, a script or an App it
|
|
4
|
+
creates knowledge bases, adds files and waits until they are read, searches
|
|
5
|
+
with citations, reads a document's pages for quoting, chooses the knowledge
|
|
6
|
+
bases an Agent searches, and manages sources.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
bun add @frontera-sdk/knowledge @frontera-sdk/core
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Choose a credential
|
|
13
|
+
|
|
14
|
+
The credential decides who acts and what they reach. The package sends what
|
|
15
|
+
you give it, and the platform decides.
|
|
16
|
+
|
|
17
|
+
| Caller | Credential | Acts as | Reaches |
|
|
18
|
+
| --- | --- | --- | --- |
|
|
19
|
+
| A backend or a script | A workspace key (`sk-ws-…`) created with the **Knowledge** purpose | Its workspace | The workspace's own knowledge bases, to read and change, and organization knowledge bases shared with the workspace, to read |
|
|
20
|
+
| An App | The App's token, which the App runtime provides | The person using the App, in the App's workspace | What that person reads and adds there |
|
|
21
|
+
| A person at a terminal | Their own sign-in | That person | What they may do, including sources |
|
|
22
|
+
|
|
23
|
+
A workspace key created for another purpose, such as Platform access, is
|
|
24
|
+
refused with the reason `knowledge_key_required`. An organization key is
|
|
25
|
+
refused everywhere in Knowledge with `credential_not_allowed`. An organization
|
|
26
|
+
key stands at no workspace, and organization knowledge bases are shared and
|
|
27
|
+
changed by Knowledge stewards, who are people. Sources are managed only by a
|
|
28
|
+
person signed in, because their credentials reach another system.
|
|
29
|
+
|
|
30
|
+
## Create a knowledge base and add a file
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { FronteraClient } from '@frontera-sdk/core/client'
|
|
34
|
+
import { KnowledgeClient } from '@frontera-sdk/knowledge/knowledge-client'
|
|
35
|
+
|
|
36
|
+
const knowledge = new KnowledgeClient(new FronteraClient({
|
|
37
|
+
apiBaseUrl: 'https://api.example.com',
|
|
38
|
+
credential: { kind: 'apiKey', key: process.env.FRONTERA_KNOWLEDGE_KEY! },
|
|
39
|
+
}))
|
|
40
|
+
|
|
41
|
+
const base = await knowledge.bases.create({ name: 'Policies' })
|
|
42
|
+
const { document, duplicate } = await knowledge.documents.upload(base.id, new File([bytes], 'leave-policy.pdf'))
|
|
43
|
+
const { documents, missing } = await knowledge.documents.waitUntilReady([document.id])
|
|
44
|
+
console.log(documents[0]?.status) // 'ready', 'failed' or 'blocked'
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Sending the same bytes to the same knowledge base again answers the document
|
|
48
|
+
they made, with `duplicate: true`, so you can send a file again after a timeout
|
|
49
|
+
or a crash without making a copy. A file is checked for malware first
|
|
50
|
+
(`scanning`), then read (`pending`, `processing`). `blocked` means it failed
|
|
51
|
+
the malware check and was removed. `waitUntilReady` never throws for a failed
|
|
52
|
+
or blocked document. It throws `KNOWLEDGE_WAIT_TIMEOUT` after ten minutes by
|
|
53
|
+
default.
|
|
54
|
+
|
|
55
|
+
A file may be at most 50 MB. `documents.list(baseId, { limit: 100 })` answers a
|
|
56
|
+
page, newest first, and `nextCursor` for the next one.
|
|
57
|
+
|
|
58
|
+
## Add a folder
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { uploadFiles } from '@frontera-sdk/knowledge/upload-files'
|
|
62
|
+
|
|
63
|
+
const outcomes = await uploadFiles(knowledge, base.id, files, { wait: true })
|
|
64
|
+
for (const outcome of outcomes) {
|
|
65
|
+
if (outcome.outcome === 'refused') console.log(outcome.path, outcome.reason, outcome.message)
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`files` is a list, or an async iterable, of `{ path, file }`. The last part of
|
|
70
|
+
`path` is the file name Knowledge reads the type from. Four files are sent at a
|
|
71
|
+
time. A network failure or a server error is tried again up to three times. A
|
|
72
|
+
refusal, such as a file type Knowledge cannot read, is not tried again. While
|
|
73
|
+
Knowledge is still reading many earlier files it answers `busy`, and
|
|
74
|
+
`uploadFiles` waits as long as it is told to before it sends again. With
|
|
75
|
+
`wait`, each outcome carries the settled document, and a file whose upload did
|
|
76
|
+
not get it stored is sent once more.
|
|
77
|
+
|
|
78
|
+
## Search and cite
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const { results } = await knowledge.search({ query: 'annual leave', limit: 5, includeText: true })
|
|
82
|
+
for (const citation of results) {
|
|
83
|
+
console.log(citation.title, citation.page, citation.openUrl)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const text = await knowledge.documents.text(results[0]!.documentId, { fromPage: 3, toPage: 4 })
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Each result names its document, its knowledge base and its page. `snippet` is
|
|
90
|
+
HTML-escaped with `<mark>` around the matched words. `openUrl` is the
|
|
91
|
+
document's page on the platform, for a person who may read it. `includeText`
|
|
92
|
+
adds each passage's whole text, for a program that writes its own answer.
|
|
93
|
+
`documents.text` answers a ready document's text page by page, and `nextPage`
|
|
94
|
+
when it stopped at `maxChars`.
|
|
95
|
+
|
|
96
|
+
## Choose an Agent's knowledge bases
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
const { bases } = await knowledge.agents.bases(agentId)
|
|
100
|
+
await knowledge.agents.setBases(agentId, [base.id])
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Manage a source
|
|
104
|
+
|
|
105
|
+
Sources need a person's sign-in. The organization's policy decides which
|
|
106
|
+
knowledge bases may have them.
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
const source = await knowledge.sources.add(base.id, {
|
|
110
|
+
kind: 'api_pull',
|
|
111
|
+
name: 'Help centre',
|
|
112
|
+
config: {
|
|
113
|
+
listUrl: 'https://help.example.com/api/articles',
|
|
114
|
+
itemsAt: 'articles',
|
|
115
|
+
paging: { kind: 'next_url', at: 'next_page' },
|
|
116
|
+
changes: { kind: 'full' },
|
|
117
|
+
fields: { id: 'id', title: 'title', updatedAt: 'updated_at', content: { kind: 'inline', at: 'body', format: 'html' } },
|
|
118
|
+
},
|
|
119
|
+
auth: { kind: 'bearer' },
|
|
120
|
+
credential: process.env.HELP_CENTRE_TOKEN,
|
|
121
|
+
})
|
|
122
|
+
await knowledge.sources.sync(source.id)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
`sources.test(baseId, input, { detect: true })` reads the first page as the
|
|
126
|
+
source would be added and stores nothing. `sources.removedDocuments(baseId)`
|
|
127
|
+
lists the documents a source no longer has, and
|
|
128
|
+
`sources.deleteRemovedDocuments` deletes them before their retention ends.
|
|
129
|
+
|
|
130
|
+
## Handle a refusal
|
|
131
|
+
|
|
132
|
+
Every refusal carries one reason from a closed list,
|
|
133
|
+
`KNOWLEDGE_REFUSAL_REASONS`. Branch on the reason. The message is written for
|
|
134
|
+
people.
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import { refusalReason, retryAfterSeconds } from '@frontera-sdk/knowledge/errors'
|
|
138
|
+
|
|
139
|
+
try {
|
|
140
|
+
await knowledge.documents.upload(base.id, file)
|
|
141
|
+
} catch (error) {
|
|
142
|
+
switch (refusalReason(error)) {
|
|
143
|
+
case 'file_type':
|
|
144
|
+
case 'file_too_large':
|
|
145
|
+
break // skip this file
|
|
146
|
+
case 'busy':
|
|
147
|
+
await new Promise((resolve) => setTimeout(resolve, (retryAfterSeconds(error) ?? 30) * 1000))
|
|
148
|
+
break
|
|
149
|
+
case 'knowledge_off':
|
|
150
|
+
throw new Error('Knowledge is not turned on for this deployment. Ask your administrator to turn it on.')
|
|
151
|
+
default:
|
|
152
|
+
throw error
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
`refusalReason` answers `undefined` for an error that is not a Knowledge
|
|
158
|
+
refusal, such as a network failure.
|
|
159
|
+
|
|
160
|
+
## Use it in an App
|
|
161
|
+
|
|
162
|
+
```tsx
|
|
163
|
+
import { createFronteraApp } from '@frontera-sdk/core/create-frontera-app'
|
|
164
|
+
import { knowledgeProvider } from '@frontera-sdk/knowledge/provider'
|
|
165
|
+
import { useKnowledgeClient, useKnowledgeSearch } from '@frontera-sdk/knowledge/hooks'
|
|
166
|
+
|
|
167
|
+
createFronteraApp(<App />, { providers: [knowledgeProvider] })
|
|
168
|
+
|
|
169
|
+
function Answers({ query }: { query: string }) {
|
|
170
|
+
const search = useKnowledgeSearch({ query, limit: 5 })
|
|
171
|
+
return <ul>{search.data?.results.map((citation) => <li key={citation.passageId ?? citation.documentId}>{citation.title}</li>)}</ul>
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`useKnowledgeDocument(id)` reads one document, and `useKnowledgeClient()` gives
|
|
176
|
+
the client for uploads and anything else. An App does not create, rename or
|
|
177
|
+
delete knowledge bases, or choose an Agent's knowledge bases.
|
package/package.json
CHANGED
|
@@ -1,6 +1,85 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frontera-sdk/knowledge",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.53.17",
|
|
4
|
+
"description": "Typed client for Frontera Knowledge: knowledge bases, documents, uploads, search with citations and sources, from a backend, a script or an App.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"frontera",
|
|
7
|
+
"knowledge",
|
|
8
|
+
"search",
|
|
9
|
+
"sdk"
|
|
10
|
+
],
|
|
11
|
+
"license": "Apache-2.0",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"files": [
|
|
14
|
+
"src",
|
|
15
|
+
"!src/__tests__",
|
|
16
|
+
"!src/**/*.test.ts",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"exports": {
|
|
24
|
+
"./types": {
|
|
25
|
+
"types": "./src/types.ts",
|
|
26
|
+
"import": "./src/types.ts"
|
|
27
|
+
},
|
|
28
|
+
"./errors": {
|
|
29
|
+
"types": "./src/errors.ts",
|
|
30
|
+
"import": "./src/errors.ts"
|
|
31
|
+
},
|
|
32
|
+
"./routes": {
|
|
33
|
+
"types": "./src/routes.ts",
|
|
34
|
+
"import": "./src/routes.ts"
|
|
35
|
+
},
|
|
36
|
+
"./knowledge-client": {
|
|
37
|
+
"types": "./src/knowledge-client.ts",
|
|
38
|
+
"import": "./src/knowledge-client.ts"
|
|
39
|
+
},
|
|
40
|
+
"./wait-until-ready": {
|
|
41
|
+
"types": "./src/wait-until-ready.ts",
|
|
42
|
+
"import": "./src/wait-until-ready.ts"
|
|
43
|
+
},
|
|
44
|
+
"./upload-files": {
|
|
45
|
+
"types": "./src/upload-files.ts",
|
|
46
|
+
"import": "./src/upload-files.ts"
|
|
47
|
+
},
|
|
48
|
+
"./hooks": {
|
|
49
|
+
"types": "./src/hooks.ts",
|
|
50
|
+
"import": "./src/hooks.ts"
|
|
51
|
+
},
|
|
52
|
+
"./provider": {
|
|
53
|
+
"types": "./src/provider.tsx",
|
|
54
|
+
"import": "./src/provider.tsx"
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"scripts": {
|
|
58
|
+
"test": "bun test",
|
|
59
|
+
"typecheck": "../../node_modules/typescript7/bin/tsc --noEmit"
|
|
60
|
+
},
|
|
61
|
+
"dependencies": {
|
|
62
|
+
"@frontera-sdk/core": "1.53.17"
|
|
63
|
+
},
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"@tanstack/react-query": "^5.90.21",
|
|
66
|
+
"react": "^19.0.0"
|
|
67
|
+
},
|
|
68
|
+
"peerDependenciesMeta": {
|
|
69
|
+
"@tanstack/react-query": {
|
|
70
|
+
"optional": true
|
|
71
|
+
},
|
|
72
|
+
"react": {
|
|
73
|
+
"optional": true
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
"devDependencies": {
|
|
77
|
+
"@happy-dom/global-registrator": "^20.11.1",
|
|
78
|
+
"@tanstack/react-query": "^5.90.21",
|
|
79
|
+
"@types/bun": "^1.3.14",
|
|
80
|
+
"@types/react": "^19",
|
|
81
|
+
"react": "19.2.5",
|
|
82
|
+
"react-dom": "19.2.5",
|
|
83
|
+
"typescript": "^5.9.3"
|
|
84
|
+
}
|
|
85
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { FronteraError } from '@frontera-sdk/core/errors'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Why Knowledge refused a request: one closed list the platform sends as
|
|
5
|
+
* `details.reason` on every refusal, so a program branches on the reason while
|
|
6
|
+
* the message stays written for people. The service's contract test keeps this
|
|
7
|
+
* copy equal to the platform's list. A release may add a reason; none is
|
|
8
|
+
* renamed or removed.
|
|
9
|
+
*/
|
|
10
|
+
export const KNOWLEDGE_REFUSAL_REASONS = [
|
|
11
|
+
/** Knowledge does not run on this deployment. */
|
|
12
|
+
'knowledge_off',
|
|
13
|
+
/** No credential, or one the platform does not accept. */
|
|
14
|
+
'sign_in_required',
|
|
15
|
+
/** A workspace key without the Knowledge purpose. */
|
|
16
|
+
'knowledge_key_required',
|
|
17
|
+
/** This kind of credential cannot use this route, such as a key on sharing or an organization key anywhere. */
|
|
18
|
+
'credential_not_allowed',
|
|
19
|
+
/** The caller lacks the permission this change or view needs. */
|
|
20
|
+
'not_permitted',
|
|
21
|
+
/** An organization knowledge base changes only through a Knowledge steward at the organization level. */
|
|
22
|
+
'steward_only',
|
|
23
|
+
/** No such base, document, Agent or workspace, or one the caller cannot read from its place. */
|
|
24
|
+
'not_found',
|
|
25
|
+
/** The request's path, query or body is not one this route accepts. */
|
|
26
|
+
'invalid_request',
|
|
27
|
+
/** Knowledge cannot read this file type. */
|
|
28
|
+
'file_type',
|
|
29
|
+
/** The file is larger than Knowledge accepts. */
|
|
30
|
+
'file_too_large',
|
|
31
|
+
/** The organization has chosen no model for preparing content, so nothing can be added. */
|
|
32
|
+
'embedding_not_chosen',
|
|
33
|
+
/** The file failed the malware check and was removed. */
|
|
34
|
+
'blocked',
|
|
35
|
+
/** The document is already waiting to be read. */
|
|
36
|
+
'already_waiting',
|
|
37
|
+
/** The document has nothing to show in the viewer yet. */
|
|
38
|
+
'no_preview',
|
|
39
|
+
/** A workspace knowledge base stays in its workspace. */
|
|
40
|
+
'not_shareable',
|
|
41
|
+
/** The request conflicts with the current state in another way. */
|
|
42
|
+
'conflict',
|
|
43
|
+
/** A part Knowledge needs is unavailable for now; try again later. */
|
|
44
|
+
'unavailable',
|
|
45
|
+
/** The organization has many files waiting to be read; send again after `retryAfterSeconds`, which `Retry-After` also gives. */
|
|
46
|
+
'busy',
|
|
47
|
+
/** The server failed. */
|
|
48
|
+
'server_error',
|
|
49
|
+
/** The organization's source policy does not allow sources on this base's layer. */
|
|
50
|
+
'sources_off',
|
|
51
|
+
/** A change moves where a source's credential would be sent, so it needs the credential again. */
|
|
52
|
+
'credential_required',
|
|
53
|
+
/** The person asked too often, such as Test connection more than ten times a minute or while two of theirs still run; try again after `retryAfterSeconds`, which `Retry-After` also gives. */
|
|
54
|
+
'too_many_requests',
|
|
55
|
+
/** The source is syncing now, so it cannot be synced again until the sync ends. */
|
|
56
|
+
'sync_running',
|
|
57
|
+
/** The source is paused; it syncs again once it is resumed. */
|
|
58
|
+
'source_paused',
|
|
59
|
+
/** The source is being removed. */
|
|
60
|
+
'source_removing',
|
|
61
|
+
] as const
|
|
62
|
+
|
|
63
|
+
export type KnowledgeRefusalReason = (typeof KNOWLEDGE_REFUSAL_REASONS)[number]
|
|
64
|
+
|
|
65
|
+
const REASONS: ReadonlySet<string> = new Set(KNOWLEDGE_REFUSAL_REASONS)
|
|
66
|
+
|
|
67
|
+
function refusalDetails(error: unknown): { reason?: unknown; retryAfterSeconds?: unknown } | undefined {
|
|
68
|
+
// By shape rather than `instanceof`: an App can bundle a second copy of the core package.
|
|
69
|
+
if (!(error instanceof Error) || typeof (error as Partial<FronteraError>).code !== 'string') return undefined
|
|
70
|
+
const body = (error as FronteraError).details as { details?: unknown } | undefined
|
|
71
|
+
const details = body?.details
|
|
72
|
+
return typeof details === 'object' && details !== null ? (details as { reason?: unknown; retryAfterSeconds?: unknown }) : undefined
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The reason Knowledge gave for refusing the request that threw `error`, or
|
|
77
|
+
* undefined when it is not a Knowledge refusal (a network failure, say) or
|
|
78
|
+
* names a reason this version of the package does not know yet.
|
|
79
|
+
*/
|
|
80
|
+
export function refusalReason(error: unknown): KnowledgeRefusalReason | undefined {
|
|
81
|
+
const reason = refusalDetails(error)?.reason
|
|
82
|
+
return typeof reason === 'string' && REASONS.has(reason) ? (reason as KnowledgeRefusalReason) : undefined
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** For `busy` and `too_many_requests`: how many seconds to wait before sending again. */
|
|
86
|
+
export function retryAfterSeconds(error: unknown): number | undefined {
|
|
87
|
+
const seconds = refusalDetails(error)?.retryAfterSeconds
|
|
88
|
+
return typeof seconds === 'number' ? seconds : undefined
|
|
89
|
+
}
|
package/src/hooks.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createContext, useContext } from 'react'
|
|
2
|
+
import { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query'
|
|
3
|
+
|
|
4
|
+
import type { KnowledgeClient } from './knowledge-client'
|
|
5
|
+
import type { KnowledgeDocumentDetails, SearchRequest, SearchResponse } from './types'
|
|
6
|
+
|
|
7
|
+
/** Query keys, so an App can invalidate after an upload. */
|
|
8
|
+
export const knowledgeKeys = {
|
|
9
|
+
all: ['frontera-knowledge'] as const,
|
|
10
|
+
search: (request: SearchRequest) => ['frontera-knowledge', 'search', request] as const,
|
|
11
|
+
document: (id: string) => ['frontera-knowledge', 'document', id] as const,
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const FronteraKnowledgeContext = createContext<KnowledgeClient | null>(null)
|
|
15
|
+
|
|
16
|
+
/** The App's Knowledge client, for uploads, statuses and anything the hooks do not cover. */
|
|
17
|
+
export function useKnowledgeClient(): KnowledgeClient {
|
|
18
|
+
const client = useContext(FronteraKnowledgeContext)
|
|
19
|
+
if (!client) throw new Error('No KnowledgeClient in context. Add knowledgeProvider to the providers of createFronteraApp or FronteraAppProvider.')
|
|
20
|
+
return client
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type ReadOptions<TData> = Omit<UseQueryOptions<TData, Error>, 'queryKey' | 'queryFn'>
|
|
24
|
+
|
|
25
|
+
/** Search results for `request`, or nothing while it is null or its query is empty. */
|
|
26
|
+
export function useKnowledgeSearch(request: SearchRequest | null, options: ReadOptions<SearchResponse> = {}): UseQueryResult<SearchResponse, Error> {
|
|
27
|
+
const client = useKnowledgeClient()
|
|
28
|
+
const asked = request && request.query.trim() ? request : null
|
|
29
|
+
return useQuery({
|
|
30
|
+
queryKey: knowledgeKeys.search(asked ?? { query: '' }),
|
|
31
|
+
queryFn: ({ signal }) => client.search(asked!, signal),
|
|
32
|
+
...options,
|
|
33
|
+
enabled: asked ? (options.enabled ?? true) : false,
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** One document with its base, for a citation's details; disabled while `id` is missing. */
|
|
38
|
+
export function useKnowledgeDocument(id: string | null | undefined, options: ReadOptions<KnowledgeDocumentDetails> = {}): UseQueryResult<KnowledgeDocumentDetails, Error> {
|
|
39
|
+
const client = useKnowledgeClient()
|
|
40
|
+
return useQuery({
|
|
41
|
+
queryKey: knowledgeKeys.document(id ?? ''),
|
|
42
|
+
queryFn: () => client.documents.get(id!),
|
|
43
|
+
...options,
|
|
44
|
+
enabled: id ? (options.enabled ?? true) : false,
|
|
45
|
+
})
|
|
46
|
+
}
|