@agentproto/adapter-knowledge-gbrain-doc 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +93 -0
- package/dist/index.d.ts +236 -0
- package/dist/index.mjs +463 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +73 -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 [yyyy] [name of copyright owner]
|
|
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
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# @agentproto/adapter-knowledge-gbrain-doc
|
|
2
|
+
|
|
3
|
+
The **document-retrieval** backing for the
|
|
4
|
+
[`@agentproto/knowledge-engine`](../../packages/knowledge-engine)
|
|
5
|
+
`IKnowledgeProvider` contract.
|
|
6
|
+
|
|
7
|
+
Implements the ingest/query contract over a **gbrain** server's document API —
|
|
8
|
+
`put_page` (ingest) + `search` (query) — reached over its JSON-RPC `/mcp`
|
|
9
|
+
endpoint via pure `fetch` (no vendor SDK). gbrain fuses **lexical (tsvector) +
|
|
10
|
+
semantic** recall, so a query stamps `modeUsed: "hybrid"`.
|
|
11
|
+
|
|
12
|
+
The document-retrieval sibling of
|
|
13
|
+
[`@agentproto/adapter-knowledge-files`](../knowledge-files) (BM25),
|
|
14
|
+
[`@agentproto/adapter-knowledge-corpus`](../knowledge-corpus) (AIP-10
|
|
15
|
+
composition), and
|
|
16
|
+
[`@agentproto/adapter-knowledge-qdrant`](../knowledge-qdrant) (vector).
|
|
17
|
+
|
|
18
|
+
> **Distinct from the code-graph gbrain adapter.**
|
|
19
|
+
> [`@agentproto/adapter-code-brain-gbrain`](../code-brain-gbrain) is the
|
|
20
|
+
> **code-graph** gbrain adapter (`ICodeBrainProvider`: define / callers /
|
|
21
|
+
> callees). **This** package is the **knowledge-document** one
|
|
22
|
+
> (`IKnowledgeProvider` over gbrain's document store). Same backend, different
|
|
23
|
+
> contract — they never share a package edge; gbrain is reached only at runtime
|
|
24
|
+
> over HTTP.
|
|
25
|
+
|
|
26
|
+
> **No studio edge.** Lifted from a studio provider whose only cross-package
|
|
27
|
+
> import was a type-only import of `JsonRpcRequest` / `JsonRpcResponse` from the
|
|
28
|
+
> studio `core/protocol` package. That edge is replaced by two inline JSON-RPC
|
|
29
|
+
> interfaces — no studio dependency survives.
|
|
30
|
+
|
|
31
|
+
## What's in the box
|
|
32
|
+
|
|
33
|
+
| Export | Role |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| `GbrainDocKnowledgeAdapter` | The `IKnowledgeProvider` implementation. Config-driven — consumes a plain `GbrainDocAdapterConfig`; knows nothing about `process.env`. |
|
|
36
|
+
| `GbrainDocAdapterConfigSchema` / `parseGbrainDocAdapterConfig` | The zod config contract (endpoint, bearer token, timeout). |
|
|
37
|
+
| `extractJsonRpcPayload` | Pulls the JSON-RPC envelope out of a gbrain Streamable-HTTP (SSE) response body (exported for testing). |
|
|
38
|
+
| `loadGbrainDocKnowledgeEnv` / `gbrainDocEnvToConfig` | The typed env module — the ONE place `GBRAIN_*` is read. |
|
|
39
|
+
| `createStandaloneGbrainDocAdapter()` | Wires the typed env into a ready-to-use adapter. |
|
|
40
|
+
| provider-kit family (`KNOWLEDGE_GBRAIN_DOC_CATALOG`, `makeKnowledgeGbrainDocResolver`, `resolveKnowledgeBackend`) | Registers the `gbrain-doc` backend under the `@agentproto/adapter-knowledge-*` discovery convention. |
|
|
41
|
+
|
|
42
|
+
## Environment
|
|
43
|
+
|
|
44
|
+
| Var | Required | Default | Meaning |
|
|
45
|
+
| --- | --- | --- | --- |
|
|
46
|
+
| `GBRAIN_BEARER_TOKEN` | ✅ | — | Machine bearer token accepted by the gbrain `/mcp` endpoint (OAuth 2.1 client_credentials). Shared with the code-graph gbrain adapter's HTTP backend by design. |
|
|
47
|
+
| `GBRAIN_ENDPOINT` | | `http://127.0.0.1:3132` | gbrain HTTP base URL (the `/mcp` endpoint is appended). |
|
|
48
|
+
| `GBRAIN_HTTP_TIMEOUT_MS` | | `45000` | Per-request timeout (ms). |
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import {
|
|
54
|
+
GbrainDocKnowledgeAdapter,
|
|
55
|
+
createStandaloneGbrainDocAdapter,
|
|
56
|
+
} from "@agentproto/adapter-knowledge-gbrain-doc"
|
|
57
|
+
|
|
58
|
+
// From the ambient GBRAIN_* env:
|
|
59
|
+
const kb = createStandaloneGbrainDocAdapter()
|
|
60
|
+
|
|
61
|
+
// Or construct directly (e.g. a host resolving a per-KB config + vault secret):
|
|
62
|
+
const direct = new GbrainDocKnowledgeAdapter({
|
|
63
|
+
endpoint: "http://127.0.0.1:3132",
|
|
64
|
+
bearerToken: process.env.GBRAIN_BEARER_TOKEN!,
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
await kb.ingest({ kind: "text", uri: "doc://intro", title: "Intro", content: "…" })
|
|
68
|
+
const { hits } = await kb.query({ query: "how do I ship", topK: 5 })
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Scope
|
|
72
|
+
|
|
73
|
+
Supported: `ingest` (`put_page` a markdown doc), `query` (`search` — stamps
|
|
74
|
+
`modeUsed: "hybrid"`; `minScore` is applied client-side since gbrain `search`
|
|
75
|
+
has no server-side score floor), `listSources` / `getSource` / `deleteSource`
|
|
76
|
+
(via `list_pages` / `get_page` / `delete_page`), `healthCheck` (`GET /health`).
|
|
77
|
+
|
|
78
|
+
## Testing
|
|
79
|
+
|
|
80
|
+
Unit tests run against a mocked `globalThis.fetch` returning canned gbrain
|
|
81
|
+
Streamable-HTTP (SSE) frames — **no live gbrain** (CI-safe). They assert the
|
|
82
|
+
`put_page` / `search` request shapes and the result mapping into
|
|
83
|
+
`KnowledgeSource` / `KnowledgeHit`. A guarded live e2e (`put_page` → `search`
|
|
84
|
+
against a running gbrain) runs only when the container is reachable, mirroring
|
|
85
|
+
the code-brain gbrain adapter's guarded e2e.
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
pnpm --filter @agentproto/adapter-knowledge-gbrain-doc test
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## License
|
|
92
|
+
|
|
93
|
+
Apache-2.0
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { KnowledgeCapabilities, IKnowledgeProvider, KnowledgeIngestInput, KnowledgeSource, KnowledgeQuery, KnowledgeQueryResult, ListSourcesFilter } from '@agentproto/knowledge-engine';
|
|
3
|
+
import { AdapterCatalog, AdapterHandle, AdapterResolver } from '@agentproto/provider-kit';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* GbrainDocKnowledgeAdapter — the `IKnowledgeProvider` over gbrain's DOCUMENT
|
|
7
|
+
* API.
|
|
8
|
+
*
|
|
9
|
+
* Connects the `@agentproto/knowledge-engine` `IKnowledgeProvider` contract to a
|
|
10
|
+
* gbrain server's document surface, reached over its JSON-RPC MCP endpoint
|
|
11
|
+
* (`POST /mcp`, bearer-authenticated) via pure `fetch` — no vendor SDK. The two
|
|
12
|
+
* load-bearing tools are `put_page` (ingest) and `search` (query); the
|
|
13
|
+
* lifecycle verbs (`list_pages` / `get_page` / `delete_page`) round out the
|
|
14
|
+
* contract. Lets a host plug "my own gbrain" as a first-class knowledge engine
|
|
15
|
+
* alongside the files / corpus / qdrant backends.
|
|
16
|
+
*
|
|
17
|
+
* DISTINCT from `@agentproto/adapter-code-brain-gbrain`: that adapter is the
|
|
18
|
+
* CODE-GRAPH one (`ICodeBrainProvider`: define / callers / callees). THIS one is
|
|
19
|
+
* the KNOWLEDGE-DOC one (`IKnowledgeProvider` over gbrain's document store).
|
|
20
|
+
* Same backend, different contract — they never share a package edge; gbrain is
|
|
21
|
+
* reached only at runtime over HTTP.
|
|
22
|
+
*
|
|
23
|
+
* Lifted from the studio integration package
|
|
24
|
+
* (`packages/integration/knowledge/src/providers/gbrain-knowledge.adapter.ts`).
|
|
25
|
+
* Changes on the lift:
|
|
26
|
+
* 1. The contract + data types now come from `@agentproto/knowledge-engine`
|
|
27
|
+
* (was the studio `../base-knowledge.provider` / `../../types`).
|
|
28
|
+
* 2. The ONE cross-package edge — a type-only import of `JsonRpcRequest` /
|
|
29
|
+
* `JsonRpcResponse` from the studio `core/protocol` package
|
|
30
|
+
* (`gbrain-knowledge.adapter.ts:23`) — is replaced by the two inline
|
|
31
|
+
* interfaces below. No studio dependency survives.
|
|
32
|
+
* 3. The wire shapes are typed against the LIVE gbrain doc API (probed at
|
|
33
|
+
* build time), which drifts from the studio original:
|
|
34
|
+
* - `put_page` args are `{ slug, content }` (studio sent a `source`
|
|
35
|
+
* field; gbrain's real field is the server-stamped `source_uri`).
|
|
36
|
+
* - `search` args are `{ query, limit, offset }` (studio sent a
|
|
37
|
+
* `min_score` gbrain doesn't accept — `minScore` is applied
|
|
38
|
+
* client-side here instead).
|
|
39
|
+
* - a `search` hit carries `chunk_text` / `score` / `chunk_index`
|
|
40
|
+
* (studio expected `snippet` / `rerank_score`).
|
|
41
|
+
* Every response is zod-parsed — nothing untyped reaches a call site.
|
|
42
|
+
*
|
|
43
|
+
* Scope of this adapter:
|
|
44
|
+
* - `ingest({ kind, uri, title?, content })` — `put_page` a markdown doc
|
|
45
|
+
* - `query({ query, topK, minScore })` — `search` (gbrain fuses lexical +
|
|
46
|
+
* semantic recall, so `modeUsed` is stamped `"hybrid"`)
|
|
47
|
+
* - `listSources()` / `getSource(id)` / `deleteSource(id)` — via
|
|
48
|
+
* `list_pages` / `get_page` / `delete_page`
|
|
49
|
+
* - `healthCheck()` — `GET /health` returns OK
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
declare const GBRAIN_DOC_ENGINE_ID: "gbrain-doc";
|
|
53
|
+
declare const GbrainDocAdapterConfigSchema: z.ZodObject<{
|
|
54
|
+
endpoint: z.ZodString;
|
|
55
|
+
bearerToken: z.ZodString;
|
|
56
|
+
timeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
57
|
+
label: z.ZodOptional<z.ZodString>;
|
|
58
|
+
}, z.core.$strip>;
|
|
59
|
+
type GbrainDocAdapterConfig = z.infer<typeof GbrainDocAdapterConfigSchema>;
|
|
60
|
+
declare function parseGbrainDocAdapterConfig(raw: Readonly<Record<string, unknown>>): GbrainDocAdapterConfig;
|
|
61
|
+
declare const GBRAIN_DOC_CAPABILITIES: KnowledgeCapabilities;
|
|
62
|
+
declare class GbrainDocKnowledgeAdapter implements IKnowledgeProvider {
|
|
63
|
+
readonly id: "gbrain-doc";
|
|
64
|
+
readonly capabilities: KnowledgeCapabilities;
|
|
65
|
+
private readonly endpoint;
|
|
66
|
+
private readonly bearerToken;
|
|
67
|
+
private readonly timeoutMs;
|
|
68
|
+
private readonly label?;
|
|
69
|
+
private rpcCounter;
|
|
70
|
+
constructor(config: GbrainDocAdapterConfig);
|
|
71
|
+
ingest(input: KnowledgeIngestInput): Promise<KnowledgeSource>;
|
|
72
|
+
query(q: KnowledgeQuery): Promise<KnowledgeQueryResult>;
|
|
73
|
+
listSources(filter?: ListSourcesFilter): Promise<readonly KnowledgeSource[]>;
|
|
74
|
+
getSource(id: string): Promise<KnowledgeSource | null>;
|
|
75
|
+
deleteSource(id: string): Promise<void>;
|
|
76
|
+
healthCheck(): Promise<boolean>;
|
|
77
|
+
dispose(): Promise<void>;
|
|
78
|
+
private authHeaders;
|
|
79
|
+
private nextRpcId;
|
|
80
|
+
/** Issue one MCP `tools/call` and return the parsed result envelope. Throws a
|
|
81
|
+
* labelled error when gbrain sets `isError` (e.g. page-not-found). */
|
|
82
|
+
private callTool;
|
|
83
|
+
private rpcCall;
|
|
84
|
+
private errPrefix;
|
|
85
|
+
}
|
|
86
|
+
/** Construct a {@link GbrainDocKnowledgeAdapter} from a validated config. */
|
|
87
|
+
declare function gbrainDocKnowledgeAdapter(config: GbrainDocAdapterConfig): GbrainDocKnowledgeAdapter;
|
|
88
|
+
/**
|
|
89
|
+
* Extract the JSON-RPC envelope from a Streamable-HTTP response body. gbrain
|
|
90
|
+
* replies with SSE frames (`event: message\ndata: {…}`); the last non-empty
|
|
91
|
+
* `data:` line carries the JSON-RPC payload. A plain-JSON body (no SSE framing)
|
|
92
|
+
* is returned whole.
|
|
93
|
+
*/
|
|
94
|
+
declare function extractJsonRpcPayload(body: string): string;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Standalone wiring for {@link GbrainDocKnowledgeAdapter}.
|
|
98
|
+
*
|
|
99
|
+
* The adapter class itself is config-driven: it consumes a plain
|
|
100
|
+
* {@link GbrainDocAdapterConfig} and knows nothing about `process.env`. This
|
|
101
|
+
* module is the ONE place that binds it to the ambient environment — it reads
|
|
102
|
+
* the typed `GBRAIN_*` env (via {@link loadGbrainDocKnowledgeEnv}) and
|
|
103
|
+
* constructs an adapter from it, exactly the role the code-brain adapter's
|
|
104
|
+
* provider factories play for their backends. Hosts that already hold a config
|
|
105
|
+
* (e.g. a studio guild host resolving a per-KB `configRef` + vault secrets)
|
|
106
|
+
* should construct `GbrainDocKnowledgeAdapter` directly and skip this factory.
|
|
107
|
+
*/
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Build a {@link GbrainDocKnowledgeAdapter} from the ambient `GBRAIN_*` env.
|
|
111
|
+
* Throws (via {@link loadGbrainDocKnowledgeEnv}) when `GBRAIN_BEARER_TOKEN` is
|
|
112
|
+
* absent. Each call returns a fresh adapter — the adapter holds no warm state
|
|
113
|
+
* (stateless JSON-RPC over HTTP), so sharing an instance is a convenience, not
|
|
114
|
+
* a requirement.
|
|
115
|
+
*/
|
|
116
|
+
declare function createStandaloneGbrainDocAdapter(): GbrainDocKnowledgeAdapter;
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Typed environment module for the gbrain-doc knowledge adapter.
|
|
120
|
+
*
|
|
121
|
+
* Every `process.env` read in this package flows through here — no raw
|
|
122
|
+
* `process.env.X` at a call site (mirrors the code-brain + files + corpus +
|
|
123
|
+
* qdrant adapters' `env.ts`). The loader parses the ambient env into a typed,
|
|
124
|
+
* validated config once, so the rest of the adapter is a pure function of its
|
|
125
|
+
* inputs. This is the ONE place the gbrain-flavoured env names (`GBRAIN_*`)
|
|
126
|
+
* live, keeping the backend idiom confined to the adapter.
|
|
127
|
+
*
|
|
128
|
+
* `GBRAIN_BEARER_TOKEN` is shared with `@agentproto/adapter-code-brain-gbrain`'s
|
|
129
|
+
* HTTP backend by design — same gbrain server, same machine token — but the two
|
|
130
|
+
* adapters never share a package edge; the token only ever meets gbrain at
|
|
131
|
+
* runtime over HTTP.
|
|
132
|
+
*/
|
|
133
|
+
|
|
134
|
+
/** Config for the standalone gbrain-doc backend — a gbrain HTTP endpoint + a
|
|
135
|
+
* machine bearer token. */
|
|
136
|
+
interface GbrainDocKnowledgeEnv {
|
|
137
|
+
/** gbrain HTTP base URL (`GBRAIN_ENDPOINT`); the `/mcp` JSON-RPC endpoint is
|
|
138
|
+
* appended. Default `"http://127.0.0.1:3132"`. */
|
|
139
|
+
readonly endpoint: string;
|
|
140
|
+
/** Machine bearer token (`GBRAIN_BEARER_TOKEN`). Required — the `/mcp`
|
|
141
|
+
* endpoint is bearer-protected. */
|
|
142
|
+
readonly bearerToken: string;
|
|
143
|
+
/** Per-request timeout (ms) (`GBRAIN_HTTP_TIMEOUT_MS`). Default 45_000. */
|
|
144
|
+
readonly timeoutMs: number;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Load {@link GbrainDocKnowledgeEnv} from `process.env` with defaults.
|
|
148
|
+
*
|
|
149
|
+
* Throws when `GBRAIN_BEARER_TOKEN` is absent — the adapter cannot authenticate
|
|
150
|
+
* to the `/mcp` endpoint without it, and failing at construction time is
|
|
151
|
+
* clearer than a 401 on the first call.
|
|
152
|
+
*/
|
|
153
|
+
declare function loadGbrainDocKnowledgeEnv(): GbrainDocKnowledgeEnv;
|
|
154
|
+
/** Project the typed env into a {@link GbrainDocAdapterConfig}. */
|
|
155
|
+
declare function gbrainDocEnvToConfig(env: GbrainDocKnowledgeEnv): GbrainDocAdapterConfig;
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Family key used for the knowledge backend creds/ledger store path.
|
|
159
|
+
*
|
|
160
|
+
* The gbrain-doc engine is the document-retrieval sibling of the `files`
|
|
161
|
+
* (BM25), `corpus` (AIP-10 composition), and `qdrant` (vector) backends — same
|
|
162
|
+
* `knowledge` family, so all four surface through the same provider-kit
|
|
163
|
+
* discovery convention (`@agentproto/adapter-knowledge-*`).
|
|
164
|
+
*/
|
|
165
|
+
declare const KNOWLEDGE_FAMILY: "knowledge";
|
|
166
|
+
/** The single backend slug this adapter provides. */
|
|
167
|
+
declare const GBRAIN_DOC_SLUG: "gbrain-doc";
|
|
168
|
+
/**
|
|
169
|
+
* Static catalog of knowledge backends shipped by this adapter. The `gbrain-doc`
|
|
170
|
+
* slug resolves from THIS package (`@agentproto/adapter-knowledge-gbrain-doc`) —
|
|
171
|
+
* document retrieval over a gbrain server's `put_page` / `search` API, reached
|
|
172
|
+
* over its JSON-RPC `/mcp` endpoint via pure `fetch` (no vendor SDK). Needs a
|
|
173
|
+
* gbrain endpoint + a machine bearer token, so it requires a setup pass.
|
|
174
|
+
*
|
|
175
|
+
* DISTINCT from `@agentproto/adapter-code-brain-gbrain` (the code-graph gbrain
|
|
176
|
+
* adapter) — same backend, different contract, no shared package edge.
|
|
177
|
+
*/
|
|
178
|
+
declare const KNOWLEDGE_GBRAIN_DOC_CATALOG: AdapterCatalog;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* provider-kit family wiring for the gbrain-doc knowledge backend.
|
|
182
|
+
*
|
|
183
|
+
* The studio home-grown `createEngineRegistry`-based knowledge registry is NOT
|
|
184
|
+
* ported (it was the guild resolution layer, which stays studio-side per the
|
|
185
|
+
* Ph4 plan — the studio gbrain `descriptor` recursively resolves per-KB config
|
|
186
|
+
* + reveals the vault bearer through that registry, and the retired E2B/sandbox
|
|
187
|
+
* provisioning path stays studio-side too). Instead the gbrain-doc backend
|
|
188
|
+
* registers as a provider-kit family (`TInfo = KnowledgeGbrainDocInfo`, `THandle
|
|
189
|
+
* = KnowledgeHandle extends AdapterHandle`), reusing the exact consumer shape
|
|
190
|
+
* the code-brain + files + corpus + qdrant adapters established — catalog +
|
|
191
|
+
* resolver + a safe `info()` descriptor that NEVER carries a secret. Discovery
|
|
192
|
+
* flows through the kit's `@agentproto/adapter-knowledge-*` naming convention.
|
|
193
|
+
*
|
|
194
|
+
* gbrain-doc needs a gbrain endpoint + a bearer token, so `requiresSetup` /
|
|
195
|
+
* `authRequired` are both true and `provider()` (via
|
|
196
|
+
* {@link createStandaloneGbrainDocAdapter}) throws when `GBRAIN_BEARER_TOKEN` is
|
|
197
|
+
* absent.
|
|
198
|
+
*/
|
|
199
|
+
|
|
200
|
+
/** Safe descriptor for a knowledge backend — NEVER carries a secret. */
|
|
201
|
+
interface KnowledgeGbrainDocInfo {
|
|
202
|
+
readonly slug: string;
|
|
203
|
+
/** The retrieval engine this backend uses. */
|
|
204
|
+
readonly engine: "gbrain-doc";
|
|
205
|
+
readonly capabilities: {
|
|
206
|
+
/** True — gbrain fuses lexical + semantic document retrieval. */
|
|
207
|
+
readonly hybridSearch: boolean;
|
|
208
|
+
/** True — gbrain-doc needs a gbrain endpoint + a machine bearer token. */
|
|
209
|
+
readonly needsCreds: boolean;
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/** A resolved knowledge backend handle. */
|
|
213
|
+
interface KnowledgeHandle extends AdapterHandle {
|
|
214
|
+
/** Safe descriptor — NEVER a secret. */
|
|
215
|
+
info(): KnowledgeGbrainDocInfo;
|
|
216
|
+
/**
|
|
217
|
+
* Build the live {@link IKnowledgeProvider} from the ambient `GBRAIN_*` env.
|
|
218
|
+
* Throws when `GBRAIN_BEARER_TOKEN` is absent — construction-time failure is
|
|
219
|
+
* clearer than a 401 on the first query.
|
|
220
|
+
*/
|
|
221
|
+
provider(): IKnowledgeProvider;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Resolve a catalog slug to a concrete knowledge handle. Throws for unknown
|
|
225
|
+
* slugs so the kit's resolver wrapper folds the miss to `null`. `provider()` is
|
|
226
|
+
* lazy — the `GBRAIN_BEARER_TOKEN` requirement is enforced only when a provider
|
|
227
|
+
* is actually built, not at resolution time.
|
|
228
|
+
*/
|
|
229
|
+
declare function resolveKnowledgeBackend(slug: string): KnowledgeHandle;
|
|
230
|
+
/**
|
|
231
|
+
* Build the knowledge resolver: resolves a catalog slug to a handle, returning
|
|
232
|
+
* `null` when the slug is unknown (via the kit's wrapper).
|
|
233
|
+
*/
|
|
234
|
+
declare function makeKnowledgeGbrainDocResolver(): AdapterResolver<KnowledgeHandle>;
|
|
235
|
+
|
|
236
|
+
export { GBRAIN_DOC_CAPABILITIES, GBRAIN_DOC_ENGINE_ID, GBRAIN_DOC_SLUG, type GbrainDocAdapterConfig, GbrainDocAdapterConfigSchema, GbrainDocKnowledgeAdapter, type GbrainDocKnowledgeEnv, KNOWLEDGE_FAMILY, KNOWLEDGE_GBRAIN_DOC_CATALOG, type KnowledgeGbrainDocInfo, type KnowledgeHandle, createStandaloneGbrainDocAdapter, extractJsonRpcPayload, gbrainDocEnvToConfig, gbrainDocKnowledgeAdapter, loadGbrainDocKnowledgeEnv, makeKnowledgeGbrainDocResolver, parseGbrainDocAdapterConfig, resolveKnowledgeBackend };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { makeAdapterResolver } from '@agentproto/provider-kit';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @agentproto/adapter-knowledge-gbrain-doc v0.1.0
|
|
6
|
+
* IKnowledgeProvider over a gbrain server's document API (put_page / search)
|
|
7
|
+
* via pure fetch over its JSON-RPC /mcp endpoint, with a provider-kit family.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
var GBRAIN_DOC_ENGINE_ID = "gbrain-doc";
|
|
11
|
+
var GbrainDocAdapterConfigSchema = z.object({
|
|
12
|
+
/** Base URL of the gbrain HTTP server (no trailing slash needed). The
|
|
13
|
+
* JSON-RPC `/mcp` endpoint is appended. */
|
|
14
|
+
endpoint: z.string().url(),
|
|
15
|
+
/** Machine bearer token accepted by the gbrain server (`GBRAIN_BEARER_TOKEN`).
|
|
16
|
+
* Required — the `/mcp` endpoint is OAuth 2.1 / bearer-protected. */
|
|
17
|
+
bearerToken: z.string().min(1),
|
|
18
|
+
/** Per-request timeout (ms). Default 45_000. */
|
|
19
|
+
timeoutMs: z.number().int().positive().default(45e3),
|
|
20
|
+
/** Optional human label for logs. */
|
|
21
|
+
label: z.string().optional()
|
|
22
|
+
});
|
|
23
|
+
function parseGbrainDocAdapterConfig(raw) {
|
|
24
|
+
return GbrainDocAdapterConfigSchema.parse(raw);
|
|
25
|
+
}
|
|
26
|
+
var GBRAIN_DOC_CAPABILITIES = Object.freeze({
|
|
27
|
+
// gbrain `search` fuses lexical (tsvector) + semantic recall, so both the
|
|
28
|
+
// vector + hybrid flags are honest.
|
|
29
|
+
vectorSearch: true,
|
|
30
|
+
hybridSearch: true,
|
|
31
|
+
// This adapter drives the DOCUMENT surface (put_page / search); it does NOT
|
|
32
|
+
// reach gbrain's graph traversal (`traverse_graph` / `query`).
|
|
33
|
+
graphTraversal: false,
|
|
34
|
+
multiModal: false,
|
|
35
|
+
streaming: false,
|
|
36
|
+
citations: true,
|
|
37
|
+
// gbrain caps a `/mcp` request body at 1 MiB; keep a chunk comfortably inside.
|
|
38
|
+
maxChunkBytes: 64 * 1024
|
|
39
|
+
});
|
|
40
|
+
var mcpToolResultSchema = z.object({
|
|
41
|
+
content: z.array(z.object({ type: z.string(), text: z.string().optional() })).optional(),
|
|
42
|
+
structuredContent: z.unknown().optional(),
|
|
43
|
+
isError: z.boolean().optional()
|
|
44
|
+
});
|
|
45
|
+
var mcpEnvelopeSchema = z.object({
|
|
46
|
+
jsonrpc: z.literal("2.0").optional(),
|
|
47
|
+
id: z.union([z.number(), z.string(), z.null()]).optional(),
|
|
48
|
+
result: mcpToolResultSchema.optional(),
|
|
49
|
+
error: z.object({ code: z.number().optional(), message: z.string() }).optional()
|
|
50
|
+
});
|
|
51
|
+
var searchHitSchema = z.object({
|
|
52
|
+
slug: z.string(),
|
|
53
|
+
chunk_text: z.string().optional(),
|
|
54
|
+
chunk_index: z.number().optional(),
|
|
55
|
+
chunk_id: z.union([z.number(), z.string()]).optional(),
|
|
56
|
+
score: z.number().optional(),
|
|
57
|
+
base_score: z.number().optional()
|
|
58
|
+
}).catchall(z.unknown());
|
|
59
|
+
var searchResultSchema = z.union([
|
|
60
|
+
z.array(searchHitSchema),
|
|
61
|
+
z.object({ results: z.array(searchHitSchema) })
|
|
62
|
+
]);
|
|
63
|
+
var putPageResultSchema = z.object({
|
|
64
|
+
slug: z.string().optional(),
|
|
65
|
+
status: z.string().optional(),
|
|
66
|
+
chunks: z.number().optional()
|
|
67
|
+
}).catchall(z.unknown());
|
|
68
|
+
var pageSchema = z.object({
|
|
69
|
+
slug: z.string(),
|
|
70
|
+
type: z.string().optional(),
|
|
71
|
+
title: z.string().optional(),
|
|
72
|
+
compiled_truth: z.string().optional(),
|
|
73
|
+
source_uri: z.string().nullish(),
|
|
74
|
+
updated_at: z.string().optional(),
|
|
75
|
+
created_at: z.string().optional()
|
|
76
|
+
}).catchall(z.unknown());
|
|
77
|
+
var pageListItemSchema = z.object({
|
|
78
|
+
slug: z.string(),
|
|
79
|
+
type: z.string().optional(),
|
|
80
|
+
title: z.string().optional(),
|
|
81
|
+
updated_at: z.string().optional()
|
|
82
|
+
}).catchall(z.unknown());
|
|
83
|
+
var pageListSchema = z.union([
|
|
84
|
+
z.array(pageListItemSchema),
|
|
85
|
+
z.object({ pages: z.array(pageListItemSchema) })
|
|
86
|
+
]);
|
|
87
|
+
var GbrainDocKnowledgeAdapter = class {
|
|
88
|
+
id = GBRAIN_DOC_ENGINE_ID;
|
|
89
|
+
capabilities = GBRAIN_DOC_CAPABILITIES;
|
|
90
|
+
endpoint;
|
|
91
|
+
bearerToken;
|
|
92
|
+
timeoutMs;
|
|
93
|
+
label;
|
|
94
|
+
rpcCounter = 0;
|
|
95
|
+
constructor(config) {
|
|
96
|
+
this.endpoint = config.endpoint.replace(/\/$/, "");
|
|
97
|
+
this.bearerToken = config.bearerToken;
|
|
98
|
+
this.timeoutMs = config.timeoutMs;
|
|
99
|
+
this.label = config.label;
|
|
100
|
+
}
|
|
101
|
+
async ingest(input) {
|
|
102
|
+
const content = normalizeContent(input.content);
|
|
103
|
+
if (!content.trim()) {
|
|
104
|
+
throw new Error(
|
|
105
|
+
`GbrainDocKnowledgeAdapter: ingest payload is empty (uri=${input.uri}); gbrain put_page requires document content.`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
const slug = deriveSlug(input);
|
|
109
|
+
const result = await this.callTool("put_page", { slug, content });
|
|
110
|
+
const parsed = putPageResultSchema.parse(parseToolJson(result));
|
|
111
|
+
return {
|
|
112
|
+
id: parsed.slug ?? slug,
|
|
113
|
+
kind: input.kind,
|
|
114
|
+
uri: input.uri,
|
|
115
|
+
title: input.title,
|
|
116
|
+
bytes: byteLength(content),
|
|
117
|
+
status: "ready",
|
|
118
|
+
indexedAt: /* @__PURE__ */ new Date(),
|
|
119
|
+
metadata: {
|
|
120
|
+
...input.metadata ?? {},
|
|
121
|
+
gbrainStatus: parsed.status ?? "created_or_updated",
|
|
122
|
+
...parsed.chunks !== void 0 ? { chunks: parsed.chunks } : {}
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
async query(q) {
|
|
127
|
+
const start = Date.now();
|
|
128
|
+
if (q.mode === "none") {
|
|
129
|
+
return { engine: this.id, modeUsed: "none", hits: [], tookMs: 0 };
|
|
130
|
+
}
|
|
131
|
+
const args = { query: q.query };
|
|
132
|
+
if (q.topK !== void 0) args.limit = q.topK;
|
|
133
|
+
const result = await this.callTool("search", args);
|
|
134
|
+
const parsed = searchResultSchema.parse(parseToolJson(result));
|
|
135
|
+
const rows = Array.isArray(parsed) ? parsed : parsed.results;
|
|
136
|
+
let hits = rows.map((row, i) => searchRowToHit(row, i));
|
|
137
|
+
if (q.minScore !== void 0) {
|
|
138
|
+
const floor = q.minScore;
|
|
139
|
+
hits = hits.filter((h) => h.score >= floor);
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
engine: this.id,
|
|
143
|
+
// gbrain search fuses lexical + semantic recall — surface the real mode
|
|
144
|
+
// regardless of the caller's hint.
|
|
145
|
+
modeUsed: "hybrid",
|
|
146
|
+
hits,
|
|
147
|
+
tookMs: Date.now() - start
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
async listSources(filter) {
|
|
151
|
+
const args = {};
|
|
152
|
+
if (filter?.kind) args.type = kindToGbrainType(filter.kind);
|
|
153
|
+
const result = await this.callTool("list_pages", args);
|
|
154
|
+
const parsed = pageListSchema.parse(parseToolJson(result));
|
|
155
|
+
const rows = Array.isArray(parsed) ? parsed : parsed.pages;
|
|
156
|
+
let out = rows.map((row) => listItemToSource(row, filter?.kind));
|
|
157
|
+
if (filter?.status) out = out.filter((s) => s.status === filter.status);
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
async getSource(id) {
|
|
161
|
+
try {
|
|
162
|
+
const result = await this.callTool("get_page", { slug: id });
|
|
163
|
+
const parsed = pageSchema.parse(parseToolJson(result));
|
|
164
|
+
return pageToSource(parsed);
|
|
165
|
+
} catch (err) {
|
|
166
|
+
if (isNotFound(err)) return null;
|
|
167
|
+
throw err;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
async deleteSource(id) {
|
|
171
|
+
try {
|
|
172
|
+
await this.callTool("delete_page", { slug: id });
|
|
173
|
+
} catch (err) {
|
|
174
|
+
if (isNotFound(err)) return;
|
|
175
|
+
throw err;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async healthCheck() {
|
|
179
|
+
try {
|
|
180
|
+
const res = await fetch(`${this.endpoint}/health`, {
|
|
181
|
+
method: "GET",
|
|
182
|
+
headers: this.authHeaders()
|
|
183
|
+
});
|
|
184
|
+
return res.ok;
|
|
185
|
+
} catch {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
async dispose() {
|
|
190
|
+
}
|
|
191
|
+
// ── Internal: MCP / JSON-RPC plumbing ────────────────────────────
|
|
192
|
+
authHeaders() {
|
|
193
|
+
return {
|
|
194
|
+
Authorization: `Bearer ${this.bearerToken}`,
|
|
195
|
+
"Content-Type": "application/json",
|
|
196
|
+
// gbrain serves `/mcp` as MCP Streamable HTTP; the client MUST declare it
|
|
197
|
+
// accepts BOTH JSON and event-stream or the server answers 406.
|
|
198
|
+
Accept: "application/json, text/event-stream"
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
nextRpcId() {
|
|
202
|
+
this.rpcCounter += 1;
|
|
203
|
+
return this.rpcCounter;
|
|
204
|
+
}
|
|
205
|
+
/** Issue one MCP `tools/call` and return the parsed result envelope. Throws a
|
|
206
|
+
* labelled error when gbrain sets `isError` (e.g. page-not-found). */
|
|
207
|
+
async callTool(name, args) {
|
|
208
|
+
const envelope = await this.rpcCall("tools/call", { name, arguments: args });
|
|
209
|
+
if (envelope.error !== void 0) {
|
|
210
|
+
throw new Error(this.errPrefix(`tool ${name}: ${envelope.error.message}`));
|
|
211
|
+
}
|
|
212
|
+
const result = envelope.result;
|
|
213
|
+
if (result === void 0) {
|
|
214
|
+
throw new Error(this.errPrefix(`tool ${name} returned no result`));
|
|
215
|
+
}
|
|
216
|
+
if (result.isError) {
|
|
217
|
+
throw new Error(this.errPrefix(`tool ${name}: ${readToolError(result)}`));
|
|
218
|
+
}
|
|
219
|
+
return result;
|
|
220
|
+
}
|
|
221
|
+
async rpcCall(method, params) {
|
|
222
|
+
const body = {
|
|
223
|
+
jsonrpc: "2.0",
|
|
224
|
+
id: this.nextRpcId(),
|
|
225
|
+
method,
|
|
226
|
+
params
|
|
227
|
+
};
|
|
228
|
+
const controller = new AbortController();
|
|
229
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
230
|
+
try {
|
|
231
|
+
const res = await fetch(`${this.endpoint}/mcp`, {
|
|
232
|
+
method: "POST",
|
|
233
|
+
headers: this.authHeaders(),
|
|
234
|
+
body: JSON.stringify(body),
|
|
235
|
+
signal: controller.signal
|
|
236
|
+
});
|
|
237
|
+
if (!res.ok) {
|
|
238
|
+
const detail = await res.text().catch(() => "");
|
|
239
|
+
throw new Error(
|
|
240
|
+
this.errPrefix(
|
|
241
|
+
`${method} \u2192 HTTP ${res.status}${detail ? `: ${detail.slice(0, 300)}` : ""}`
|
|
242
|
+
)
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
const raw = await res.text();
|
|
246
|
+
return mcpEnvelopeSchema.parse(JSON.parse(extractJsonRpcPayload(raw)));
|
|
247
|
+
} finally {
|
|
248
|
+
clearTimeout(timer);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
errPrefix(msg) {
|
|
252
|
+
const labelPart = this.label ? ` (${this.label})` : "";
|
|
253
|
+
return `GbrainDocKnowledgeAdapter${labelPart}: ${msg}`;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
function gbrainDocKnowledgeAdapter(config) {
|
|
257
|
+
return new GbrainDocKnowledgeAdapter(config);
|
|
258
|
+
}
|
|
259
|
+
function extractJsonRpcPayload(body) {
|
|
260
|
+
const dataLines = body.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice("data:".length).trim()).filter((payload) => payload.length > 0);
|
|
261
|
+
const last = dataLines[dataLines.length - 1];
|
|
262
|
+
return last ?? body.trim();
|
|
263
|
+
}
|
|
264
|
+
function parseToolJson(result) {
|
|
265
|
+
if (result.structuredContent !== void 0) return result.structuredContent;
|
|
266
|
+
const first = result.content?.find((c) => c.text !== void 0 && c.text !== "");
|
|
267
|
+
if (first?.text === void 0) return null;
|
|
268
|
+
try {
|
|
269
|
+
return JSON.parse(first.text);
|
|
270
|
+
} catch {
|
|
271
|
+
return first.text;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function readToolError(result) {
|
|
275
|
+
const first = result.content?.find((c) => c.text !== void 0 && c.text !== "");
|
|
276
|
+
return first?.text ?? "unknown error";
|
|
277
|
+
}
|
|
278
|
+
function isNotFound(err) {
|
|
279
|
+
return err instanceof Error && /not.?found/i.test(err.message);
|
|
280
|
+
}
|
|
281
|
+
function searchRowToHit(row, index) {
|
|
282
|
+
const { slug, chunk_text, chunk_index, chunk_id, score, base_score, ...rest } = row;
|
|
283
|
+
const chunkIndex = chunk_index ?? index;
|
|
284
|
+
return {
|
|
285
|
+
sourceId: slug,
|
|
286
|
+
chunkId: chunk_id !== void 0 ? `${slug}#${chunk_id}` : `${slug}#${chunkIndex}`,
|
|
287
|
+
text: chunk_text ?? "",
|
|
288
|
+
score: score ?? base_score ?? 0,
|
|
289
|
+
// Round-trip every other gbrain field (title, type, page_id, source_id,
|
|
290
|
+
// evidence, …) so a hit carries full provenance to the LLM.
|
|
291
|
+
metadata: { chunkIndex, ...rest }
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
function pageToSource(page) {
|
|
295
|
+
const compiled = page.compiled_truth ?? "";
|
|
296
|
+
return {
|
|
297
|
+
id: page.slug,
|
|
298
|
+
kind: gbrainTypeToKind(page.type),
|
|
299
|
+
uri: page.source_uri ?? page.slug,
|
|
300
|
+
title: page.title,
|
|
301
|
+
bytes: byteLength(compiled),
|
|
302
|
+
status: "ready",
|
|
303
|
+
indexedAt: parseDate(page.updated_at ?? page.created_at),
|
|
304
|
+
metadata: { type: page.type ?? "note" }
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
function listItemToSource(row, hintedKind) {
|
|
308
|
+
return {
|
|
309
|
+
id: row.slug,
|
|
310
|
+
kind: hintedKind ?? gbrainTypeToKind(row.type),
|
|
311
|
+
uri: row.slug,
|
|
312
|
+
title: row.title,
|
|
313
|
+
// list_pages is a slim projection (no body) — bytes are unknown here.
|
|
314
|
+
bytes: 0,
|
|
315
|
+
status: "ready",
|
|
316
|
+
indexedAt: parseDate(row.updated_at),
|
|
317
|
+
metadata: { type: row.type ?? "note" }
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
function deriveSlug(input) {
|
|
321
|
+
if (input.title) return slugify(input.title);
|
|
322
|
+
const [pathPart = ""] = input.uri.split(/[?#]/);
|
|
323
|
+
const tail = pathPart.split("/").filter(Boolean).pop();
|
|
324
|
+
if (tail) return slugify(tail);
|
|
325
|
+
return "note";
|
|
326
|
+
}
|
|
327
|
+
function slugify(s) {
|
|
328
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "note";
|
|
329
|
+
}
|
|
330
|
+
function gbrainTypeToKind(t) {
|
|
331
|
+
if (!t) return "text";
|
|
332
|
+
if (t === "url" || t === "link") return "url";
|
|
333
|
+
if (t === "file" || t === "document" || t === "code") return "file";
|
|
334
|
+
if (t === "connector") return "connector";
|
|
335
|
+
return "text";
|
|
336
|
+
}
|
|
337
|
+
function kindToGbrainType(kind) {
|
|
338
|
+
switch (kind) {
|
|
339
|
+
case "url":
|
|
340
|
+
return "url";
|
|
341
|
+
case "file":
|
|
342
|
+
return "file";
|
|
343
|
+
case "connector":
|
|
344
|
+
return "connector";
|
|
345
|
+
case "text":
|
|
346
|
+
default:
|
|
347
|
+
return "note";
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function normalizeContent(content) {
|
|
351
|
+
if (content === void 0) return "";
|
|
352
|
+
if (typeof content === "string") return content;
|
|
353
|
+
return new TextDecoder().decode(content);
|
|
354
|
+
}
|
|
355
|
+
function byteLength(text) {
|
|
356
|
+
return new TextEncoder().encode(text).byteLength;
|
|
357
|
+
}
|
|
358
|
+
function parseDate(v) {
|
|
359
|
+
if (v === void 0) return void 0;
|
|
360
|
+
const d = new Date(v);
|
|
361
|
+
return Number.isNaN(d.getTime()) ? void 0 : d;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// src/env.ts
|
|
365
|
+
function parsePositiveInt(value, fallback) {
|
|
366
|
+
if (value === void 0 || value === "") return fallback;
|
|
367
|
+
const parsed = Number.parseInt(value, 10);
|
|
368
|
+
if (Number.isNaN(parsed) || parsed <= 0) return fallback;
|
|
369
|
+
return parsed;
|
|
370
|
+
}
|
|
371
|
+
function nonEmpty(value) {
|
|
372
|
+
if (value === void 0) return void 0;
|
|
373
|
+
const trimmed = value.trim();
|
|
374
|
+
return trimmed === "" ? void 0 : trimmed;
|
|
375
|
+
}
|
|
376
|
+
function loadGbrainDocKnowledgeEnv() {
|
|
377
|
+
const bearerToken = nonEmpty(process.env.GBRAIN_BEARER_TOKEN);
|
|
378
|
+
if (bearerToken === void 0) {
|
|
379
|
+
throw new Error(
|
|
380
|
+
"GBRAIN_BEARER_TOKEN is required for the gbrain-doc knowledge adapter; mint one via gbrain's admin API (OAuth 2.1 client_credentials) and set it in the environment."
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
return {
|
|
384
|
+
endpoint: nonEmpty(process.env.GBRAIN_ENDPOINT) ?? "http://127.0.0.1:3132",
|
|
385
|
+
bearerToken,
|
|
386
|
+
timeoutMs: parsePositiveInt(process.env.GBRAIN_HTTP_TIMEOUT_MS, 45e3)
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
function gbrainDocEnvToConfig(env) {
|
|
390
|
+
return {
|
|
391
|
+
endpoint: env.endpoint,
|
|
392
|
+
bearerToken: env.bearerToken,
|
|
393
|
+
timeoutMs: env.timeoutMs
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// src/standalone.ts
|
|
398
|
+
function createStandaloneGbrainDocAdapter() {
|
|
399
|
+
return new GbrainDocKnowledgeAdapter(
|
|
400
|
+
gbrainDocEnvToConfig(loadGbrainDocKnowledgeEnv())
|
|
401
|
+
);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// src/catalog.ts
|
|
405
|
+
var KNOWLEDGE_FAMILY = "knowledge";
|
|
406
|
+
var GBRAIN_DOC_SLUG = "gbrain-doc";
|
|
407
|
+
var KNOWLEDGE_GBRAIN_DOC_CATALOG = [
|
|
408
|
+
{
|
|
409
|
+
slug: GBRAIN_DOC_SLUG,
|
|
410
|
+
name: "gbrain (doc)",
|
|
411
|
+
description: "Document knowledge retrieval over a gbrain server's put_page / search API, reached over its JSON-RPC /mcp endpoint via pure fetch \u2014 no vendor SDK. gbrain fuses lexical (tsvector) + semantic recall. Needs a gbrain endpoint + a machine bearer token. Distinct from the code-graph gbrain adapter.",
|
|
412
|
+
packageName: "@agentproto/adapter-knowledge-gbrain-doc",
|
|
413
|
+
hint: "gbrain \xB7 doc"
|
|
414
|
+
}
|
|
415
|
+
];
|
|
416
|
+
function resolveKnowledgeBackend(slug) {
|
|
417
|
+
const catalogEntry = KNOWLEDGE_GBRAIN_DOC_CATALOG.find(
|
|
418
|
+
(entry) => entry.slug === slug
|
|
419
|
+
);
|
|
420
|
+
if (catalogEntry === void 0) {
|
|
421
|
+
throw new Error(`unknown knowledge backend slug: ${slug}`);
|
|
422
|
+
}
|
|
423
|
+
switch (slug) {
|
|
424
|
+
case GBRAIN_DOC_SLUG: {
|
|
425
|
+
return {
|
|
426
|
+
slug,
|
|
427
|
+
name: catalogEntry.name,
|
|
428
|
+
description: catalogEntry.description,
|
|
429
|
+
version: "0.1.0",
|
|
430
|
+
requiresSetup: true,
|
|
431
|
+
authRequired: true,
|
|
432
|
+
// Health probe: build from env + hit GET /health. When the env is
|
|
433
|
+
// absent, construction throws — fold that to "not reachable" rather
|
|
434
|
+
// than propagating so a listing probe stays total.
|
|
435
|
+
check: async () => {
|
|
436
|
+
try {
|
|
437
|
+
return await createStandaloneGbrainDocAdapter().healthCheck();
|
|
438
|
+
} catch {
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
},
|
|
442
|
+
info() {
|
|
443
|
+
return {
|
|
444
|
+
slug,
|
|
445
|
+
engine: "gbrain-doc",
|
|
446
|
+
capabilities: { hybridSearch: true, needsCreds: true }
|
|
447
|
+
};
|
|
448
|
+
},
|
|
449
|
+
provider: () => createStandaloneGbrainDocAdapter()
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
throw new Error(`unhandled knowledge backend slug: ${slug}`);
|
|
454
|
+
}
|
|
455
|
+
function makeKnowledgeGbrainDocResolver() {
|
|
456
|
+
return makeAdapterResolver({
|
|
457
|
+
load: async (slug) => resolveKnowledgeBackend(slug)
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export { GBRAIN_DOC_CAPABILITIES, GBRAIN_DOC_ENGINE_ID, GBRAIN_DOC_SLUG, GbrainDocAdapterConfigSchema, GbrainDocKnowledgeAdapter, KNOWLEDGE_FAMILY, KNOWLEDGE_GBRAIN_DOC_CATALOG, createStandaloneGbrainDocAdapter, extractJsonRpcPayload, gbrainDocEnvToConfig, gbrainDocKnowledgeAdapter, loadGbrainDocKnowledgeEnv, makeKnowledgeGbrainDocResolver, parseGbrainDocAdapterConfig, resolveKnowledgeBackend };
|
|
462
|
+
//# sourceMappingURL=index.mjs.map
|
|
463
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapter.ts","../src/env.ts","../src/standalone.ts","../src/catalog.ts","../src/handle.ts"],"names":[],"mappings":";;;;;;;;;AA4DO,IAAM,oBAAA,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CAAM,IAAA,KAAS;AAAA,GAC5B;AACA,EAAA,IAAI,iBAAiB,MAAA,EAAW;AAC9B,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,gCAAA,EAAmC,IAAI,CAAA,CAAE,CAAA;AAAA,EAC3D;AAEA,EAAA,QAAQ,IAAA;AAAM,IACZ,KAAK,eAAA,EAAiB;AACpB,MAAA,OAAO;AAAA,QACL,IAAA;AAAA,QACA,MAAM,YAAA,CAAa,IAAA;AAAA,QACnB,aAAa,YAAA,CAAa,WAAA;AAAA,QAC1B,OAAA,EAAS,OAAA;AAAA,QACT,aAAA,EAAe,IAAA;AAAA,QACf,YAAA,EAAc,IAAA;AAAA;AAAA;AAAA;AAAA,QAId,OAAO,YAAY;AACjB,UAAA,IAAI;AACF,YAAA,OAAO,MAAM,gCAAA,EAAiC,CAAE,WAAA,EAAY;AAAA,UAC9D,CAAA,CAAA,MAAQ;AACN,YAAA,OAAO,KAAA;AAAA,UACT;AAAA,QACF,CAAA;AAAA,QACA,IAAA,GAAO;AACL,UAAA,OAAO;AAAA,YACL,IAAA;AAAA,YACA,MAAA,EAAQ,YAAA;AAAA,YACR,YAAA,EAAc,EAAE,YAAA,EAAc,IAAA,EAAM,YAAY,IAAA;AAAK,WACvD;AAAA,QACF,CAAA;AAAA,QACA,QAAA,EAAU,MAAM,gCAAA;AAAiC,OACnD;AAAA,IACF;AAAA;AAGF,EAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kCAAA,EAAqC,IAAI,CAAA,CAAE,CAAA;AAC7D;AAMO,SAAS,8BAAA,GAAmE;AACjF,EAAA,OAAO,mBAAA,CAAqC;AAAA,IAC1C,IAAA,EAAM,OAAO,IAAA,KACX,uBAAA,CAAwB,IAAI;AAAA,GAC/B,CAAA;AACH","file":"index.mjs","sourcesContent":["/**\n * GbrainDocKnowledgeAdapter — the `IKnowledgeProvider` over gbrain's DOCUMENT\n * API.\n *\n * Connects the `@agentproto/knowledge-engine` `IKnowledgeProvider` contract to a\n * gbrain server's document surface, reached over its JSON-RPC MCP endpoint\n * (`POST /mcp`, bearer-authenticated) via pure `fetch` — no vendor SDK. The two\n * load-bearing tools are `put_page` (ingest) and `search` (query); the\n * lifecycle verbs (`list_pages` / `get_page` / `delete_page`) round out the\n * contract. Lets a host plug \"my own gbrain\" as a first-class knowledge engine\n * alongside the files / corpus / qdrant backends.\n *\n * DISTINCT from `@agentproto/adapter-code-brain-gbrain`: that adapter is the\n * CODE-GRAPH one (`ICodeBrainProvider`: define / callers / callees). THIS one is\n * the KNOWLEDGE-DOC one (`IKnowledgeProvider` over gbrain's document store).\n * Same backend, different contract — they never share a package edge; gbrain is\n * reached only at runtime over HTTP.\n *\n * Lifted from the studio integration package\n * (`packages/integration/knowledge/src/providers/gbrain-knowledge.adapter.ts`).\n * Changes on the lift:\n * 1. The contract + data types now come from `@agentproto/knowledge-engine`\n * (was the studio `../base-knowledge.provider` / `../../types`).\n * 2. The ONE cross-package edge — a type-only import of `JsonRpcRequest` /\n * `JsonRpcResponse` from the studio `core/protocol` package\n * (`gbrain-knowledge.adapter.ts:23`) — is replaced by the two inline\n * interfaces below. No studio dependency survives.\n * 3. The wire shapes are typed against the LIVE gbrain doc API (probed at\n * build time), which drifts from the studio original:\n * - `put_page` args are `{ slug, content }` (studio sent a `source`\n * field; gbrain's real field is the server-stamped `source_uri`).\n * - `search` args are `{ query, limit, offset }` (studio sent a\n * `min_score` gbrain doesn't accept — `minScore` is applied\n * client-side here instead).\n * - a `search` hit carries `chunk_text` / `score` / `chunk_index`\n * (studio expected `snippet` / `rerank_score`).\n * Every response is zod-parsed — nothing untyped reaches a call site.\n *\n * Scope of this adapter:\n * - `ingest({ kind, uri, title?, content })` — `put_page` a markdown doc\n * - `query({ query, topK, minScore })` — `search` (gbrain fuses lexical +\n * semantic recall, so `modeUsed` is stamped `\"hybrid\"`)\n * - `listSources()` / `getSource(id)` / `deleteSource(id)` — via\n * `list_pages` / `get_page` / `delete_page`\n * - `healthCheck()` — `GET /health` returns OK\n */\n\nimport { z } from \"zod\"\nimport type {\n IKnowledgeProvider,\n KnowledgeCapabilities,\n KnowledgeHit,\n KnowledgeIngestInput,\n KnowledgeQuery,\n KnowledgeQueryResult,\n KnowledgeSource,\n KnowledgeSourceKind,\n ListSourcesFilter,\n} from \"@agentproto/knowledge-engine\"\n\nexport const GBRAIN_DOC_ENGINE_ID = \"gbrain-doc\" as const\n\n// ── Inline JSON-RPC 2.0 wire types ──────────────────────────────────\n//\n// Replaces the studio adapter's ONE cross-package edge: a type-only import of\n// `JsonRpcRequest` / `JsonRpcResponse` from the studio `core/protocol` package.\n// gbrain speaks JSON-RPC 2.0 over `POST /mcp`; these two frames are all we send\n// and receive, so they inline here with zero new dependency. The response is\n// additionally zod-validated on the wire ({@link mcpEnvelopeSchema}) so nothing\n// untyped reaches a call site.\n\n/** A JSON-RPC 2.0 request frame — the body we POST to gbrain's `/mcp`. */\ninterface JsonRpcRequest<TParams = unknown> {\n readonly jsonrpc: \"2.0\"\n readonly id: number\n readonly method: string\n readonly params?: TParams\n}\n\n/** A JSON-RPC 2.0 response frame — success carries `result`, failure `error`. */\ninterface JsonRpcResponse<TResult = unknown> {\n readonly jsonrpc?: \"2.0\"\n readonly id?: number | string | null\n readonly result?: TResult\n readonly error?: { readonly code?: number; readonly message: string }\n}\n\n// ── Config ──────────────────────────────────────────────────────────\n\nexport const GbrainDocAdapterConfigSchema = z.object({\n /** Base URL of the gbrain HTTP server (no trailing slash needed). The\n * JSON-RPC `/mcp` endpoint is appended. */\n endpoint: z.string().url(),\n /** Machine bearer token accepted by the gbrain server (`GBRAIN_BEARER_TOKEN`).\n * Required — the `/mcp` endpoint is OAuth 2.1 / bearer-protected. */\n bearerToken: z.string().min(1),\n /** Per-request timeout (ms). Default 45_000. */\n timeoutMs: z.number().int().positive().default(45_000),\n /** Optional human label for logs. */\n label: z.string().optional(),\n})\n\nexport type GbrainDocAdapterConfig = z.infer<typeof GbrainDocAdapterConfigSchema>\n\nexport function parseGbrainDocAdapterConfig(\n raw: Readonly<Record<string, unknown>>,\n): GbrainDocAdapterConfig {\n return GbrainDocAdapterConfigSchema.parse(raw)\n}\n\n// ── Capabilities ────────────────────────────────────────────────────\n\nexport const GBRAIN_DOC_CAPABILITIES: KnowledgeCapabilities = Object.freeze({\n // gbrain `search` fuses lexical (tsvector) + semantic recall, so both the\n // vector + hybrid flags are honest.\n vectorSearch: true,\n hybridSearch: true,\n // This adapter drives the DOCUMENT surface (put_page / search); it does NOT\n // reach gbrain's graph traversal (`traverse_graph` / `query`).\n graphTraversal: false,\n multiModal: false,\n streaming: false,\n citations: true,\n // gbrain caps a `/mcp` request body at 1 MiB; keep a chunk comfortably inside.\n maxChunkBytes: 64 * 1024,\n})\n\n// ── Wire shapes (zod-parsed — nothing untyped reaches a call site) ───\n\n/** The MCP `tools/call` result envelope: a text block (+ optional structured\n * content) and an `isError` flag gbrain sets for e.g. page-not-found. */\nconst mcpToolResultSchema = z.object({\n content: z\n .array(z.object({ type: z.string(), text: z.string().optional() }))\n .optional(),\n structuredContent: z.unknown().optional(),\n isError: z.boolean().optional(),\n})\n\ntype McpToolResult = z.infer<typeof mcpToolResultSchema>\n\n/** The JSON-RPC envelope wrapping an MCP `tools/call` result. Mirrors the\n * inline {@link JsonRpcResponse} interface, validated on the wire. */\nconst mcpEnvelopeSchema = z.object({\n jsonrpc: z.literal(\"2.0\").optional(),\n id: z.union([z.number(), z.string(), z.null()]).optional(),\n result: mcpToolResultSchema.optional(),\n error: z\n .object({ code: z.number().optional(), message: z.string() })\n .optional(),\n})\n\n/** A single `search` hit row (gbrain doc API). Known fields are typed; the rest\n * (page_id, type, source_id, evidence, …) flow through to `metadata`. */\nconst searchHitSchema = z\n .object({\n slug: z.string(),\n chunk_text: z.string().optional(),\n chunk_index: z.number().optional(),\n chunk_id: z.union([z.number(), z.string()]).optional(),\n score: z.number().optional(),\n base_score: z.number().optional(),\n })\n .catchall(z.unknown())\n\n/** `search` returns a bare array of hits; some builds wrap it as `{ results }`.\n * Accept both. */\nconst searchResultSchema = z.union([\n z.array(searchHitSchema),\n z.object({ results: z.array(searchHitSchema) }),\n])\n\n/** `put_page` result — status + chunk count (+ passthrough backstop fields). */\nconst putPageResultSchema = z\n .object({\n slug: z.string().optional(),\n status: z.string().optional(),\n chunks: z.number().optional(),\n })\n .catchall(z.unknown())\n\n/** A `get_page` document envelope. */\nconst pageSchema = z\n .object({\n slug: z.string(),\n type: z.string().optional(),\n title: z.string().optional(),\n compiled_truth: z.string().optional(),\n source_uri: z.string().nullish(),\n updated_at: z.string().optional(),\n created_at: z.string().optional(),\n })\n .catchall(z.unknown())\n\n/** A `list_pages` row (slim: no body). */\nconst pageListItemSchema = z\n .object({\n slug: z.string(),\n type: z.string().optional(),\n title: z.string().optional(),\n updated_at: z.string().optional(),\n })\n .catchall(z.unknown())\n\nconst pageListSchema = z.union([\n z.array(pageListItemSchema),\n z.object({ pages: z.array(pageListItemSchema) }),\n])\n\n// ── Adapter ──────────────────────────────────────────────────────────\n\nexport class GbrainDocKnowledgeAdapter implements IKnowledgeProvider {\n readonly id = GBRAIN_DOC_ENGINE_ID\n readonly capabilities = GBRAIN_DOC_CAPABILITIES\n\n private readonly endpoint: string\n private readonly bearerToken: string\n private readonly timeoutMs: number\n private readonly label?: string\n\n private rpcCounter = 0\n\n constructor(config: GbrainDocAdapterConfig) {\n this.endpoint = config.endpoint.replace(/\\/$/, \"\")\n this.bearerToken = config.bearerToken\n this.timeoutMs = config.timeoutMs\n this.label = config.label\n }\n\n async ingest(input: KnowledgeIngestInput): Promise<KnowledgeSource> {\n const content = normalizeContent(input.content)\n if (!content.trim()) {\n throw new Error(\n `GbrainDocKnowledgeAdapter: ingest payload is empty (uri=${input.uri}); gbrain put_page requires document content.`,\n )\n }\n const slug = deriveSlug(input)\n // gbrain put_page takes { slug, content }. `source_uri` is SERVER-STAMPED\n // for remote callers (client value ignored), so we don't send it — the\n // caller's uri round-trips through the returned KnowledgeSource instead.\n const result = await this.callTool(\"put_page\", { slug, content })\n const parsed = putPageResultSchema.parse(parseToolJson(result))\n return {\n id: parsed.slug ?? slug,\n kind: input.kind,\n uri: input.uri,\n title: input.title,\n bytes: byteLength(content),\n status: \"ready\",\n indexedAt: new Date(),\n metadata: {\n ...(input.metadata ?? {}),\n gbrainStatus: parsed.status ?? \"created_or_updated\",\n ...(parsed.chunks !== undefined ? { chunks: parsed.chunks } : {}),\n },\n }\n }\n\n async query(q: KnowledgeQuery): Promise<KnowledgeQueryResult> {\n const start = Date.now()\n // `\"none\"` is the cold-start sentinel — skip retrieval entirely.\n if (q.mode === \"none\") {\n return { engine: this.id, modeUsed: \"none\", hits: [], tookMs: 0 }\n }\n\n const args: Record<string, number | string> = { query: q.query }\n if (q.topK !== undefined) args.limit = q.topK\n\n const result = await this.callTool(\"search\", args)\n const parsed = searchResultSchema.parse(parseToolJson(result))\n const rows = Array.isArray(parsed) ? parsed : parsed.results\n\n let hits: KnowledgeHit[] = rows.map((row, i) => searchRowToHit(row, i))\n // gbrain `search` has no server-side score floor, so honour `minScore`\n // client-side (the contract lets adapters enforce it either way).\n if (q.minScore !== undefined) {\n const floor = q.minScore\n hits = hits.filter((h) => h.score >= floor)\n }\n\n return {\n engine: this.id,\n // gbrain search fuses lexical + semantic recall — surface the real mode\n // regardless of the caller's hint.\n modeUsed: \"hybrid\",\n hits,\n tookMs: Date.now() - start,\n }\n }\n\n async listSources(\n filter?: ListSourcesFilter,\n ): Promise<readonly KnowledgeSource[]> {\n const args: Record<string, string> = {}\n if (filter?.kind) args.type = kindToGbrainType(filter.kind)\n const result = await this.callTool(\"list_pages\", args)\n const parsed = pageListSchema.parse(parseToolJson(result))\n const rows = Array.isArray(parsed) ? parsed : parsed.pages\n let out = rows.map((row) => listItemToSource(row, filter?.kind))\n // `status` isn't a gbrain list dimension — every listed page is live, so a\n // `status` filter keeps only \"ready\" (all of them) or nothing.\n if (filter?.status) out = out.filter((s) => s.status === filter.status)\n return out\n }\n\n async getSource(id: string): Promise<KnowledgeSource | null> {\n try {\n const result = await this.callTool(\"get_page\", { slug: id })\n const parsed = pageSchema.parse(parseToolJson(result))\n return pageToSource(parsed)\n } catch (err) {\n // gbrain flags a missing page with isError + a \"page_not_found\" body —\n // fold that to null; re-throw anything else.\n if (isNotFound(err)) return null\n throw err\n }\n }\n\n async deleteSource(id: string): Promise<void> {\n try {\n await this.callTool(\"delete_page\", { slug: id })\n } catch (err) {\n // Deleting an already-absent page is a no-op, not an error.\n if (isNotFound(err)) return\n throw err\n }\n }\n\n async healthCheck(): Promise<boolean> {\n try {\n const res = await fetch(`${this.endpoint}/health`, {\n method: \"GET\",\n headers: this.authHeaders(),\n })\n return res.ok\n } catch {\n return false\n }\n }\n\n async dispose(): Promise<void> {\n // No connections to tear down — gbrain calls are stateless JSON-RPC over\n // HTTP. Kept on the interface for adapters that hold long-lived clients.\n }\n\n // ── Internal: MCP / JSON-RPC plumbing ────────────────────────────\n\n private authHeaders(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.bearerToken}`,\n \"Content-Type\": \"application/json\",\n // gbrain serves `/mcp` as MCP Streamable HTTP; the client MUST declare it\n // accepts BOTH JSON and event-stream or the server answers 406.\n Accept: \"application/json, text/event-stream\",\n }\n }\n\n private nextRpcId(): number {\n this.rpcCounter += 1\n return this.rpcCounter\n }\n\n /** Issue one MCP `tools/call` and return the parsed result envelope. Throws a\n * labelled error when gbrain sets `isError` (e.g. page-not-found). */\n private async callTool(\n name: string,\n args: Readonly<Record<string, unknown>>,\n ): Promise<McpToolResult> {\n const envelope = await this.rpcCall(\"tools/call\", { name, arguments: args })\n if (envelope.error !== undefined) {\n throw new Error(this.errPrefix(`tool ${name}: ${envelope.error.message}`))\n }\n const result = envelope.result\n if (result === undefined) {\n throw new Error(this.errPrefix(`tool ${name} returned no result`))\n }\n if (result.isError) {\n throw new Error(this.errPrefix(`tool ${name}: ${readToolError(result)}`))\n }\n return result\n }\n\n private async rpcCall(\n method: string,\n params: unknown,\n ): Promise<z.infer<typeof mcpEnvelopeSchema>> {\n const body: JsonRpcRequest = {\n jsonrpc: \"2.0\",\n id: this.nextRpcId(),\n method,\n params,\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.timeoutMs)\n try {\n const res = await fetch(`${this.endpoint}/mcp`, {\n method: \"POST\",\n headers: this.authHeaders(),\n body: JSON.stringify(body),\n signal: controller.signal,\n })\n if (!res.ok) {\n const detail = await res.text().catch(() => \"\")\n throw new Error(\n this.errPrefix(\n `${method} → HTTP ${res.status}${detail ? `: ${detail.slice(0, 300)}` : \"\"}`,\n ),\n )\n }\n // gbrain replies as a Streamable-HTTP SSE frame (`data: {…}`) OR plain\n // JSON — {@link extractJsonRpcPayload} normalises both.\n const raw = await res.text()\n return mcpEnvelopeSchema.parse(JSON.parse(extractJsonRpcPayload(raw)))\n } finally {\n clearTimeout(timer)\n }\n }\n\n private errPrefix(msg: string): string {\n const labelPart = this.label ? ` (${this.label})` : \"\"\n return `GbrainDocKnowledgeAdapter${labelPart}: ${msg}`\n }\n}\n\n/** Construct a {@link GbrainDocKnowledgeAdapter} from a validated config. */\nexport function gbrainDocKnowledgeAdapter(\n config: GbrainDocAdapterConfig,\n): GbrainDocKnowledgeAdapter {\n return new GbrainDocKnowledgeAdapter(config)\n}\n\n// ── Pure helpers (no I/O) — exported where a test drives them ─────────\n\n/**\n * Extract the JSON-RPC envelope from a Streamable-HTTP response body. gbrain\n * replies with SSE frames (`event: message\\ndata: {…}`); the last non-empty\n * `data:` line carries the JSON-RPC payload. A plain-JSON body (no SSE framing)\n * is returned whole.\n */\nexport function extractJsonRpcPayload(body: string): string {\n const dataLines = body\n .split(/\\r?\\n/)\n .filter((line) => line.startsWith(\"data:\"))\n .map((line) => line.slice(\"data:\".length).trim())\n .filter((payload) => payload.length > 0)\n const last = dataLines[dataLines.length - 1]\n return last ?? body.trim()\n}\n\n/**\n * Pull the JSON payload out of an MCP tool result: prefer `structuredContent`,\n * else the first text block parsed as JSON. Returns the raw text when it isn't\n * JSON. The caller zod-parses the returned value into a concrete shape.\n */\nfunction parseToolJson(result: McpToolResult): unknown {\n if (result.structuredContent !== undefined) return result.structuredContent\n const first = result.content?.find((c) => c.text !== undefined && c.text !== \"\")\n if (first?.text === undefined) return null\n try {\n return JSON.parse(first.text)\n } catch {\n return first.text\n }\n}\n\n/** The error text gbrain packs into a `tools/call` result when `isError` is set. */\nfunction readToolError(result: McpToolResult): string {\n const first = result.content?.find((c) => c.text !== undefined && c.text !== \"\")\n return first?.text ?? \"unknown error\"\n}\n\nfunction isNotFound(err: unknown): boolean {\n return err instanceof Error && /not.?found/i.test(err.message)\n}\n\ntype SearchRow = z.infer<typeof searchHitSchema>\n\nfunction searchRowToHit(row: SearchRow, index: number): KnowledgeHit {\n const { slug, chunk_text, chunk_index, chunk_id, score, base_score, ...rest } =\n row\n const chunkIndex = chunk_index ?? index\n return {\n sourceId: slug,\n chunkId:\n chunk_id !== undefined ? `${slug}#${chunk_id}` : `${slug}#${chunkIndex}`,\n text: chunk_text ?? \"\",\n score: score ?? base_score ?? 0,\n // Round-trip every other gbrain field (title, type, page_id, source_id,\n // evidence, …) so a hit carries full provenance to the LLM.\n metadata: { chunkIndex, ...rest },\n }\n}\n\ntype PageRow = z.infer<typeof pageSchema>\n\nfunction pageToSource(page: PageRow): KnowledgeSource {\n const compiled = page.compiled_truth ?? \"\"\n return {\n id: page.slug,\n kind: gbrainTypeToKind(page.type),\n uri: page.source_uri ?? page.slug,\n title: page.title,\n bytes: byteLength(compiled),\n status: \"ready\",\n indexedAt: parseDate(page.updated_at ?? page.created_at),\n metadata: { type: page.type ?? \"note\" },\n }\n}\n\ntype PageListRow = z.infer<typeof pageListItemSchema>\n\nfunction listItemToSource(\n row: PageListRow,\n hintedKind?: KnowledgeSourceKind,\n): KnowledgeSource {\n return {\n id: row.slug,\n kind: hintedKind ?? gbrainTypeToKind(row.type),\n uri: row.slug,\n title: row.title,\n // list_pages is a slim projection (no body) — bytes are unknown here.\n bytes: 0,\n status: \"ready\",\n indexedAt: parseDate(row.updated_at),\n metadata: { type: row.type ?? \"note\" },\n }\n}\n\nfunction deriveSlug(input: KnowledgeIngestInput): string {\n if (input.title) return slugify(input.title)\n const [pathPart = \"\"] = input.uri.split(/[?#]/)\n const tail = pathPart.split(\"/\").filter(Boolean).pop()\n if (tail) return slugify(tail)\n return \"note\"\n}\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 80) || \"note\"\n )\n}\n\nfunction gbrainTypeToKind(t: string | undefined): KnowledgeSourceKind {\n if (!t) return \"text\"\n if (t === \"url\" || t === \"link\") return \"url\"\n if (t === \"file\" || t === \"document\" || t === \"code\") return \"file\"\n if (t === \"connector\") return \"connector\"\n return \"text\"\n}\n\nfunction kindToGbrainType(kind: KnowledgeSourceKind): string {\n switch (kind) {\n case \"url\":\n return \"url\"\n case \"file\":\n return \"file\"\n case \"connector\":\n return \"connector\"\n case \"text\":\n default:\n return \"note\"\n }\n}\n\nfunction normalizeContent(content: KnowledgeIngestInput[\"content\"]): string {\n if (content === undefined) return \"\"\n if (typeof content === \"string\") return content\n return new TextDecoder().decode(content)\n}\n\n/** UTF-8 byte length without a `node:buffer` edge — runs on edge runtimes too. */\nfunction byteLength(text: string): number {\n return new TextEncoder().encode(text).byteLength\n}\n\nfunction parseDate(v: string | undefined): Date | undefined {\n if (v === undefined) return undefined\n const d = new Date(v)\n return Number.isNaN(d.getTime()) ? undefined : d\n}\n","/**\n * Typed environment module for the gbrain-doc knowledge adapter.\n *\n * Every `process.env` read in this package flows through here — no raw\n * `process.env.X` at a call site (mirrors the code-brain + files + corpus +\n * qdrant adapters' `env.ts`). The loader parses the ambient env into a typed,\n * validated config once, so the rest of the adapter is a pure function of its\n * inputs. This is the ONE place the gbrain-flavoured env names (`GBRAIN_*`)\n * live, keeping the backend idiom confined to the adapter.\n *\n * `GBRAIN_BEARER_TOKEN` is shared with `@agentproto/adapter-code-brain-gbrain`'s\n * HTTP backend by design — same gbrain server, same machine token — but the two\n * adapters never share a package edge; the token only ever meets gbrain at\n * runtime over HTTP.\n */\n\nimport type { GbrainDocAdapterConfig } from \"./adapter.js\"\n\nfunction parsePositiveInt(value: string | undefined, fallback: number): number {\n if (value === undefined || value === \"\") return fallback\n const parsed = Number.parseInt(value, 10)\n if (Number.isNaN(parsed) || parsed <= 0) return fallback\n return parsed\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n if (value === undefined) return undefined\n const trimmed = value.trim()\n return trimmed === \"\" ? undefined : trimmed\n}\n\n/** Config for the standalone gbrain-doc backend — a gbrain HTTP endpoint + a\n * machine bearer token. */\nexport interface GbrainDocKnowledgeEnv {\n /** gbrain HTTP base URL (`GBRAIN_ENDPOINT`); the `/mcp` JSON-RPC endpoint is\n * appended. Default `\"http://127.0.0.1:3132\"`. */\n readonly endpoint: string\n /** Machine bearer token (`GBRAIN_BEARER_TOKEN`). Required — the `/mcp`\n * endpoint is bearer-protected. */\n readonly bearerToken: string\n /** Per-request timeout (ms) (`GBRAIN_HTTP_TIMEOUT_MS`). Default 45_000. */\n readonly timeoutMs: number\n}\n\n/**\n * Load {@link GbrainDocKnowledgeEnv} from `process.env` with defaults.\n *\n * Throws when `GBRAIN_BEARER_TOKEN` is absent — the adapter cannot authenticate\n * to the `/mcp` endpoint without it, and failing at construction time is\n * clearer than a 401 on the first call.\n */\nexport function loadGbrainDocKnowledgeEnv(): GbrainDocKnowledgeEnv {\n const bearerToken = nonEmpty(process.env.GBRAIN_BEARER_TOKEN)\n if (bearerToken === undefined) {\n throw new Error(\n \"GBRAIN_BEARER_TOKEN is required for the gbrain-doc knowledge adapter; mint one via gbrain's admin API (OAuth 2.1 client_credentials) and set it in the environment.\",\n )\n }\n return {\n endpoint: nonEmpty(process.env.GBRAIN_ENDPOINT) ?? \"http://127.0.0.1:3132\",\n bearerToken,\n timeoutMs: parsePositiveInt(process.env.GBRAIN_HTTP_TIMEOUT_MS, 45_000),\n }\n}\n\n/** Project the typed env into a {@link GbrainDocAdapterConfig}. */\nexport function gbrainDocEnvToConfig(\n env: GbrainDocKnowledgeEnv,\n): GbrainDocAdapterConfig {\n return {\n endpoint: env.endpoint,\n bearerToken: env.bearerToken,\n timeoutMs: env.timeoutMs,\n }\n}\n","/**\n * Standalone wiring for {@link GbrainDocKnowledgeAdapter}.\n *\n * The adapter class itself is config-driven: it consumes a plain\n * {@link GbrainDocAdapterConfig} and knows nothing about `process.env`. This\n * module is the ONE place that binds it to the ambient environment — it reads\n * the typed `GBRAIN_*` env (via {@link loadGbrainDocKnowledgeEnv}) and\n * constructs an adapter from it, exactly the role the code-brain adapter's\n * provider factories play for their backends. Hosts that already hold a config\n * (e.g. a studio guild host resolving a per-KB `configRef` + vault secrets)\n * should construct `GbrainDocKnowledgeAdapter` directly and skip this factory.\n */\n\nimport { GbrainDocKnowledgeAdapter } from \"./adapter.js\"\nimport { gbrainDocEnvToConfig, loadGbrainDocKnowledgeEnv } from \"./env.js\"\n\n/**\n * Build a {@link GbrainDocKnowledgeAdapter} from the ambient `GBRAIN_*` env.\n * Throws (via {@link loadGbrainDocKnowledgeEnv}) when `GBRAIN_BEARER_TOKEN` is\n * absent. Each call returns a fresh adapter — the adapter holds no warm state\n * (stateless JSON-RPC over HTTP), so sharing an instance is a convenience, not\n * a requirement.\n */\nexport function createStandaloneGbrainDocAdapter(): GbrainDocKnowledgeAdapter {\n return new GbrainDocKnowledgeAdapter(\n gbrainDocEnvToConfig(loadGbrainDocKnowledgeEnv()),\n )\n}\n","import type { AdapterCatalog } from \"@agentproto/provider-kit\"\n\n/**\n * Family key used for the knowledge backend creds/ledger store path.\n *\n * The gbrain-doc engine is the document-retrieval sibling of the `files`\n * (BM25), `corpus` (AIP-10 composition), and `qdrant` (vector) backends — same\n * `knowledge` family, so all four surface through the same provider-kit\n * discovery convention (`@agentproto/adapter-knowledge-*`).\n */\nexport const KNOWLEDGE_FAMILY = \"knowledge\" as const\n\n/** The single backend slug this adapter provides. */\nexport const GBRAIN_DOC_SLUG = \"gbrain-doc\" as const\n\n/**\n * Static catalog of knowledge backends shipped by this adapter. The `gbrain-doc`\n * slug resolves from THIS package (`@agentproto/adapter-knowledge-gbrain-doc`) —\n * document retrieval over a gbrain server's `put_page` / `search` API, reached\n * over its JSON-RPC `/mcp` endpoint via pure `fetch` (no vendor SDK). Needs a\n * gbrain endpoint + a machine bearer token, so it requires a setup pass.\n *\n * DISTINCT from `@agentproto/adapter-code-brain-gbrain` (the code-graph gbrain\n * adapter) — same backend, different contract, no shared package edge.\n */\nexport const KNOWLEDGE_GBRAIN_DOC_CATALOG: AdapterCatalog = [\n {\n slug: GBRAIN_DOC_SLUG,\n name: \"gbrain (doc)\",\n description:\n \"Document knowledge retrieval over a gbrain server's put_page / search \" +\n \"API, reached over its JSON-RPC /mcp endpoint via pure fetch — no vendor \" +\n \"SDK. gbrain fuses lexical (tsvector) + semantic recall. Needs a gbrain \" +\n \"endpoint + a machine bearer token. Distinct from the code-graph gbrain \" +\n \"adapter.\",\n packageName: \"@agentproto/adapter-knowledge-gbrain-doc\",\n hint: \"gbrain · doc\",\n },\n]\n","/**\n * provider-kit family wiring for the gbrain-doc knowledge backend.\n *\n * The studio home-grown `createEngineRegistry`-based knowledge registry is NOT\n * ported (it was the guild resolution layer, which stays studio-side per the\n * Ph4 plan — the studio gbrain `descriptor` recursively resolves per-KB config\n * + reveals the vault bearer through that registry, and the retired E2B/sandbox\n * provisioning path stays studio-side too). Instead the gbrain-doc backend\n * registers as a provider-kit family (`TInfo = KnowledgeGbrainDocInfo`, `THandle\n * = KnowledgeHandle extends AdapterHandle`), reusing the exact consumer shape\n * the code-brain + files + corpus + qdrant adapters established — catalog +\n * resolver + a safe `info()` descriptor that NEVER carries a secret. Discovery\n * flows through the kit's `@agentproto/adapter-knowledge-*` naming convention.\n *\n * gbrain-doc needs a gbrain endpoint + a bearer token, so `requiresSetup` /\n * `authRequired` are both true and `provider()` (via\n * {@link createStandaloneGbrainDocAdapter}) throws when `GBRAIN_BEARER_TOKEN` is\n * absent.\n */\n\nimport type { IKnowledgeProvider } from \"@agentproto/knowledge-engine\"\nimport {\n makeAdapterResolver,\n type AdapterHandle,\n type AdapterResolver,\n} from \"@agentproto/provider-kit\"\nimport { GBRAIN_DOC_SLUG, KNOWLEDGE_GBRAIN_DOC_CATALOG } from \"./catalog.js\"\nimport { createStandaloneGbrainDocAdapter } from \"./standalone.js\"\n\n/** Safe descriptor for a knowledge backend — NEVER carries a secret. */\nexport interface KnowledgeGbrainDocInfo {\n readonly slug: string\n /** The retrieval engine this backend uses. */\n readonly engine: \"gbrain-doc\"\n readonly capabilities: {\n /** True — gbrain fuses lexical + semantic document retrieval. */\n readonly hybridSearch: boolean\n /** True — gbrain-doc needs a gbrain endpoint + a machine bearer token. */\n readonly needsCreds: boolean\n }\n}\n\n/** A resolved knowledge backend handle. */\nexport interface KnowledgeHandle extends AdapterHandle {\n /** Safe descriptor — NEVER a secret. */\n info(): KnowledgeGbrainDocInfo\n /**\n * Build the live {@link IKnowledgeProvider} from the ambient `GBRAIN_*` env.\n * Throws when `GBRAIN_BEARER_TOKEN` is absent — construction-time failure is\n * clearer than a 401 on the first query.\n */\n provider(): IKnowledgeProvider\n}\n\n/**\n * Resolve a catalog slug to a concrete knowledge handle. Throws for unknown\n * slugs so the kit's resolver wrapper folds the miss to `null`. `provider()` is\n * lazy — the `GBRAIN_BEARER_TOKEN` requirement is enforced only when a provider\n * is actually built, not at resolution time.\n */\nexport function resolveKnowledgeBackend(slug: string): KnowledgeHandle {\n const catalogEntry = KNOWLEDGE_GBRAIN_DOC_CATALOG.find(\n (entry) => entry.slug === slug,\n )\n if (catalogEntry === undefined) {\n throw new Error(`unknown knowledge backend slug: ${slug}`)\n }\n\n switch (slug) {\n case GBRAIN_DOC_SLUG: {\n return {\n slug,\n name: catalogEntry.name,\n description: catalogEntry.description,\n version: \"0.1.0\",\n requiresSetup: true,\n authRequired: true,\n // Health probe: build from env + hit GET /health. When the env is\n // absent, construction throws — fold that to \"not reachable\" rather\n // than propagating so a listing probe stays total.\n check: async () => {\n try {\n return await createStandaloneGbrainDocAdapter().healthCheck()\n } catch {\n return false\n }\n },\n info() {\n return {\n slug,\n engine: \"gbrain-doc\",\n capabilities: { hybridSearch: true, needsCreds: true },\n }\n },\n provider: () => createStandaloneGbrainDocAdapter(),\n }\n }\n }\n\n throw new Error(`unhandled knowledge backend slug: ${slug}`)\n}\n\n/**\n * Build the knowledge resolver: resolves a catalog slug to a handle, returning\n * `null` when the slug is unknown (via the kit's wrapper).\n */\nexport function makeKnowledgeGbrainDocResolver(): AdapterResolver<KnowledgeHandle> {\n return makeAdapterResolver<KnowledgeHandle>({\n load: async (slug: string): Promise<KnowledgeHandle> =>\n resolveKnowledgeBackend(slug),\n })\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@agentproto/adapter-knowledge-gbrain-doc",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Knowledge adapter: implements @agentproto/knowledge-engine's IKnowledgeProvider over a gbrain server's document API (put_page / search) via pure fetch over its JSON-RPC /mcp endpoint. gbrain fuses lexical (tsvector) + semantic recall. Registers as a provider-kit family. No vendor SDK, no app coupling. Distinct from the code-graph gbrain adapter.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"agentproto",
|
|
7
|
+
"knowledge-engine",
|
|
8
|
+
"knowledge",
|
|
9
|
+
"retrieval",
|
|
10
|
+
"rag",
|
|
11
|
+
"gbrain",
|
|
12
|
+
"document-search",
|
|
13
|
+
"hybrid-search",
|
|
14
|
+
"adapter",
|
|
15
|
+
"provider-kit",
|
|
16
|
+
"open-standard",
|
|
17
|
+
"agentic"
|
|
18
|
+
],
|
|
19
|
+
"homepage": "https://agentproto.sh",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "https://github.com/agentproto/ts",
|
|
23
|
+
"directory": "adapters/knowledge-gbrain-doc"
|
|
24
|
+
},
|
|
25
|
+
"bugs": {
|
|
26
|
+
"url": "https://github.com/agentproto/ts/issues"
|
|
27
|
+
},
|
|
28
|
+
"license": "Apache-2.0",
|
|
29
|
+
"type": "module",
|
|
30
|
+
"main": "dist/index.mjs",
|
|
31
|
+
"module": "dist/index.mjs",
|
|
32
|
+
"types": "dist/index.d.ts",
|
|
33
|
+
"exports": {
|
|
34
|
+
".": {
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"import": "./dist/index.mjs",
|
|
37
|
+
"default": "./dist/index.mjs"
|
|
38
|
+
},
|
|
39
|
+
"./package.json": "./package.json"
|
|
40
|
+
},
|
|
41
|
+
"files": [
|
|
42
|
+
"dist",
|
|
43
|
+
"README.md",
|
|
44
|
+
"LICENSE"
|
|
45
|
+
],
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
},
|
|
49
|
+
"dependencies": {
|
|
50
|
+
"zod": "^4.4.3",
|
|
51
|
+
"@agentproto/provider-kit": "0.4.0",
|
|
52
|
+
"@agentproto/knowledge-engine": "0.2.0"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@types/node": "^25.6.2",
|
|
56
|
+
"tsup": "^8.5.1",
|
|
57
|
+
"typescript": "^5.9.3",
|
|
58
|
+
"vitest": "^3.2.4",
|
|
59
|
+
"@agentproto/tool": "0.2.1",
|
|
60
|
+
"@agentproto/tooling": "0.1.0-alpha.0"
|
|
61
|
+
},
|
|
62
|
+
"engines": {
|
|
63
|
+
"node": ">=20.9.0"
|
|
64
|
+
},
|
|
65
|
+
"scripts": {
|
|
66
|
+
"dev": "tsup --watch",
|
|
67
|
+
"build": "tsup",
|
|
68
|
+
"clean": "rm -rf dist",
|
|
69
|
+
"check-types": "tsc --noEmit",
|
|
70
|
+
"test": "vitest run",
|
|
71
|
+
"test:watch": "vitest"
|
|
72
|
+
}
|
|
73
|
+
}
|