@engramind/client 0.0.0-stage → 0.1.1
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/CHANGELOG.md +18 -0
- package/LICENSE +9 -0
- package/README.md +231 -2
- package/dist/ai.d.ts +22 -0
- package/dist/ai.js +61 -0
- package/dist/ai.js.map +1 -0
- package/dist/chunk-THVEWMKQ.js +193 -0
- package/dist/chunk-THVEWMKQ.js.map +1 -0
- package/dist/client-Q0QFU2A6.d.ts +215 -0
- package/dist/events-DYEjIvxs.d.ts +117 -0
- package/dist/index.d.ts +149 -0
- package/dist/index.js +132 -0
- package/dist/index.js.map +1 -0
- package/dist/react.d.ts +1687 -0
- package/dist/react.js +7163 -0
- package/dist/react.js.map +1 -0
- package/dist/server.d.ts +225 -0
- package/dist/server.js +553 -0
- package/dist/server.js.map +1 -0
- package/dist/types-BnU5iHwB.d.ts +439 -0
- package/package.json +108 -4
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { a as EngramindMethod, E as EngramindClient } from './client-Q0QFU2A6.js';
|
|
2
|
+
export { C as CallOptions, b as CategoryInput, c as ChannelQuery, d as EngramindClientOptions, M as MemoryQuery, Q as Query, e as buildUrl, f as createEngramindClient, g as debugUrl } from './client-Q0QFU2A6.js';
|
|
3
|
+
import { L as LiveEvent, W as WebhookEvent } from './events-DYEjIvxs.js';
|
|
4
|
+
export { C as ConsumptionEvent, a as ConsumptionGrouperOptions, E as EngramindError, b as EngramindErrorBody, c as WebhookEventType, d as clientStatus, e as createConsumptionGrouper, f as engramindCodeOf, i as isConsumedEvent, g as isMemoryChange, m as mergeConsumption, n as notConfiguredError, p as proxyMaskedError, t as toEngramindError, h as toLiveEvent, u as unreachableError } from './events-DYEjIvxs.js';
|
|
5
|
+
import { h as ContextView } from './types-BnU5iHwB.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Rotas do proxy da lib: o caminho do REST do Engramind sem o `/v1` (`channels/eng%2Fglobal/archive`).
|
|
9
|
+
* `app` é o que o token de app pode fazer (matriz do guia `tokens-e-escopos`); `manager` acrescenta o que
|
|
10
|
+
* o gestor da rede usa nas telas (apps, criar/editar/excluir canais, configurações por canal).
|
|
11
|
+
*/
|
|
12
|
+
type ProxyMode = "app" | "manager";
|
|
13
|
+
interface ProxyRoute {
|
|
14
|
+
method: EngramindMethod;
|
|
15
|
+
/** Segmentos; `:nome` casa um segmento qualquer. */
|
|
16
|
+
pattern: string;
|
|
17
|
+
modes: readonly ProxyMode[];
|
|
18
|
+
/** Operação do Engramind (auditoria do app e testes). */
|
|
19
|
+
operation: string;
|
|
20
|
+
}
|
|
21
|
+
declare const PROXY_ROUTES: readonly ProxyRoute[];
|
|
22
|
+
interface RouteMatch {
|
|
23
|
+
route: ProxyRoute;
|
|
24
|
+
params: Record<string, string>;
|
|
25
|
+
/** Caminho do Engramind (`/v1/...`) com os segmentos recodificados. */
|
|
26
|
+
path: string;
|
|
27
|
+
}
|
|
28
|
+
/** Casa método + segmentos (já decodificados) com uma rota permitida no modo. */
|
|
29
|
+
declare function matchProxyRoute(method: string, segments: readonly string[], mode: ProxyMode): RouteMatch | null;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Proxy HTTP pronto para os componentes da lib: o app monta numa rota (ex.: catch-all do Next.js
|
|
33
|
+
* `app/api/engramind/[...path]/route.ts`) **atrás do próprio login** — a lib não verifica usuário. Repassa
|
|
34
|
+
* só as rotas do modo (`app`: as do token de app; `manager`: também as do gestor), com o token do
|
|
35
|
+
* servidor; a resposta é `{ success: true, data }` ou `{ success: false, error, code, details }` e nunca
|
|
36
|
+
* traz o token configurado. No modo app, `issue_token` só emite `kind: agent`.
|
|
37
|
+
*/
|
|
38
|
+
interface ProxyMutation {
|
|
39
|
+
operation: string;
|
|
40
|
+
method: EngramindMethod;
|
|
41
|
+
params: Record<string, string>;
|
|
42
|
+
/** Corpo enviado (o app decide o que audita; segredos de token emitido não passam por aqui). */
|
|
43
|
+
body: unknown;
|
|
44
|
+
result: unknown;
|
|
45
|
+
}
|
|
46
|
+
interface EngramindProxyOptions {
|
|
47
|
+
/** Cliente do Engramind (ou uma função que o monta a cada requisição, ex.: lendo a configuração). */
|
|
48
|
+
client: EngramindClient | (() => EngramindClient | null | Promise<EngramindClient | null>);
|
|
49
|
+
mode?: ProxyMode;
|
|
50
|
+
/** Prefixo da rota no app (ex.: `/api/engramind`); o resto do caminho é a rota do Engramind. */
|
|
51
|
+
basePath: string;
|
|
52
|
+
/** Depois de cada mutação bem-sucedida (auditoria do app). */
|
|
53
|
+
onMutation?: (mutation: ProxyMutation) => void | Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Token de agente emitido ou rotacionado: o segredo aparece só nesta resposta. O app pode gravá-lo onde
|
|
56
|
+
* quiser (ex.: cofre do servidor); o diálogo da lib também o mostra uma única vez.
|
|
57
|
+
*/
|
|
58
|
+
onTokenIssued?: (secret: string, token: {
|
|
59
|
+
id: string;
|
|
60
|
+
agent: string | null;
|
|
61
|
+
app: string | null;
|
|
62
|
+
kind: string;
|
|
63
|
+
operation: "issue_token" | "rotate_token";
|
|
64
|
+
}) => void | Promise<void>;
|
|
65
|
+
onError?: (error: unknown, route: ProxyRoute | null) => void;
|
|
66
|
+
}
|
|
67
|
+
declare function errorResponse(error: unknown): Response;
|
|
68
|
+
/** Segmentos depois do `basePath`, decodificados (`channels/eng%2Fglobal` → `["channels", "eng/global"]`). */
|
|
69
|
+
declare function proxySegments(pathname: string, basePath: string): string[] | null;
|
|
70
|
+
declare function createEngramindProxy(options: EngramindProxyOptions): (request: Request) => Promise<Response>;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Barramento dos eventos ao vivo (webhook → SSE). O padrão vive **no processo**: só os navegadores
|
|
74
|
+
* ligados à instância que recebeu o webhook são avisados. Com várias instâncias, passe um `Broadcaster`
|
|
75
|
+
* (ex.: Redis pub/sub, Postgres `NOTIFY`, Pusher) que entregue o evento a todas.
|
|
76
|
+
*/
|
|
77
|
+
type LiveListener = (event: LiveEvent) => void;
|
|
78
|
+
interface Broadcaster {
|
|
79
|
+
publish(event: LiveEvent): void | Promise<void>;
|
|
80
|
+
subscribe(listener: LiveListener): () => void;
|
|
81
|
+
}
|
|
82
|
+
interface EventBus {
|
|
83
|
+
publish(event: LiveEvent): Promise<void>;
|
|
84
|
+
subscribe(listener: LiveListener): () => void;
|
|
85
|
+
/** Navegadores ligados nesta instância. */
|
|
86
|
+
readonly size: number;
|
|
87
|
+
}
|
|
88
|
+
declare function createEventBus(options?: {
|
|
89
|
+
broadcaster?: Broadcaster;
|
|
90
|
+
onError?: (error: unknown) => void;
|
|
91
|
+
}): EventBus;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Contexto das memórias por agente (`get_context`) com cache por `version` (`If-None-Match` → `304`).
|
|
95
|
+
* Os eventos `memory.*`, `channel.updated` e `subscription.updated` marcam os canais como sujos;
|
|
96
|
+
* **`memory.consumed` não** (só avisa que memórias foram entregues). Se o Engramind cair, devolve o
|
|
97
|
+
* último bloco (`stale: true`). Guarde o bloco na parte estável do prompt.
|
|
98
|
+
*/
|
|
99
|
+
interface ContextEntry {
|
|
100
|
+
content: string;
|
|
101
|
+
version: string;
|
|
102
|
+
counts: ContextView["counts"];
|
|
103
|
+
format: string;
|
|
104
|
+
fetchedAt: number;
|
|
105
|
+
dirty: boolean;
|
|
106
|
+
}
|
|
107
|
+
/** Onde o bloco fica (padrão: memória do processo). Troque por Redis/banco para várias instâncias. */
|
|
108
|
+
interface ContextStore {
|
|
109
|
+
get(key: string): ContextEntry | null | Promise<ContextEntry | null>;
|
|
110
|
+
set(key: string, entry: ContextEntry): void | Promise<void>;
|
|
111
|
+
/** Chaves guardadas (para marcar os canais sujos). */
|
|
112
|
+
keys(): string[] | Promise<string[]>;
|
|
113
|
+
}
|
|
114
|
+
declare function createMemoryContextStore(): ContextStore;
|
|
115
|
+
interface ContextResult {
|
|
116
|
+
block: string;
|
|
117
|
+
version: string | null;
|
|
118
|
+
/** `live` (lido agora ou `304`), `cache` (Engramind indisponível: último bloco) ou `none`. */
|
|
119
|
+
source: "live" | "cache" | "none";
|
|
120
|
+
stale: boolean;
|
|
121
|
+
counts: ContextView["counts"] | null;
|
|
122
|
+
error: string | null;
|
|
123
|
+
}
|
|
124
|
+
interface ContextCacheOptions {
|
|
125
|
+
/** Cliente com o token **do agente** (o contexto é o do agente). */
|
|
126
|
+
client: (agent: string) => EngramindClient | null | Promise<EngramindClient | null>;
|
|
127
|
+
store?: ContextStore;
|
|
128
|
+
format?: string;
|
|
129
|
+
/**
|
|
130
|
+
* `always` (padrão): toda chamada revalida com `If-None-Match` (o `304` custa poucos bytes).
|
|
131
|
+
* `on-dirty`: só chama o Engramind quando um evento sujou um canal do bloco ou depois de `maxAgeMs`.
|
|
132
|
+
*/
|
|
133
|
+
revalidate?: "always" | "on-dirty";
|
|
134
|
+
maxAgeMs?: number;
|
|
135
|
+
onError?: (error: unknown, agent: string) => void;
|
|
136
|
+
}
|
|
137
|
+
declare const contextKey: (agent: string, channels: readonly string[], format: string) => string;
|
|
138
|
+
/** O evento muda o contexto do canal? (`memory.consumed` não muda.) */
|
|
139
|
+
declare function invalidatesContext(event: Pick<WebhookEvent, "type">): boolean;
|
|
140
|
+
declare function createContextCache(options: ContextCacheOptions): {
|
|
141
|
+
/** Webhook recebido: suja o contexto dos canais afetados (nunca por `memory.consumed`). */
|
|
142
|
+
handleEvent(event: Pick<WebhookEvent, "type" | "channel">): void;
|
|
143
|
+
getContext(agent: string, input?: {
|
|
144
|
+
channels?: readonly string[];
|
|
145
|
+
focus?: string;
|
|
146
|
+
}): Promise<ContextResult>;
|
|
147
|
+
/** Bloco guardado (sem chamar o Engramind). */
|
|
148
|
+
peek: (agent: string, channels?: readonly string[]) => Promise<ContextEntry | null>;
|
|
149
|
+
};
|
|
150
|
+
type ContextCache = ReturnType<typeof createContextCache>;
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Webhook do Engramind (`POST <webhook_url>`): valida `Engramind-Signature` (`t=<unix>,v1=<hex>`,
|
|
154
|
+
* HMAC-SHA256 do segredo sobre `t + "." + corpo bruto`, janela de 300 s, comparação em tempo constante),
|
|
155
|
+
* descarta o `id` repetido (as retentativas repetem o corpo), marca o contexto do canal como sujo (menos
|
|
156
|
+
* `memory.consumed`) e republica no SSE só ids, slugs e tipos. Assinatura inválida: `401` sem corpo.
|
|
157
|
+
*/
|
|
158
|
+
declare const WEBHOOK_TOLERANCE_SECONDS = 300;
|
|
159
|
+
declare function parseSignatureHeader(header: string | null): {
|
|
160
|
+
t: number;
|
|
161
|
+
v1: string[];
|
|
162
|
+
} | null;
|
|
163
|
+
declare function signWebhook(secret: string, timestamp: number, body: string): string;
|
|
164
|
+
declare function verifyWebhookSignature(header: string | null, body: string, secret: string, options?: {
|
|
165
|
+
now?: number;
|
|
166
|
+
toleranceSeconds?: number;
|
|
167
|
+
}): boolean;
|
|
168
|
+
/** Registro dos `id` já processados (retentativas do Engramind). */
|
|
169
|
+
interface DedupeStore {
|
|
170
|
+
/** `true` se o `id` já foi visto (e o marca como visto). */
|
|
171
|
+
seen(id: string): boolean | Promise<boolean>;
|
|
172
|
+
}
|
|
173
|
+
/** Padrão em memória: lembra os últimos `max` ids por `ttlMs` (24 h). */
|
|
174
|
+
declare function createMemoryDedupe(options?: {
|
|
175
|
+
ttlMs?: number;
|
|
176
|
+
max?: number;
|
|
177
|
+
}): DedupeStore;
|
|
178
|
+
interface WebhookHandlerOptions {
|
|
179
|
+
/** Segredo do webhook do app (o mesmo gravado no Engramind por `update_app_webhook`). */
|
|
180
|
+
secret: string | (() => string | null | Promise<string | null>);
|
|
181
|
+
bus?: EventBus;
|
|
182
|
+
dedupe?: DedupeStore;
|
|
183
|
+
/** Contexto em cache dos agentes do app: marca os canais sujos. */
|
|
184
|
+
context?: ContextCache;
|
|
185
|
+
/** Depois de validar (ex.: auditoria, outro tempo real do app). Uma falha não muda a resposta. */
|
|
186
|
+
onEvent?: (event: WebhookEvent) => void | Promise<void>;
|
|
187
|
+
onError?: (error: unknown) => void;
|
|
188
|
+
toleranceSeconds?: number;
|
|
189
|
+
}
|
|
190
|
+
declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Endpoint SSE dos componentes (`EventSource`): repassa os eventos do barramento como
|
|
194
|
+
* `event: engramind` com só ids, slugs e tipos, e um comentário de vida a cada `heartbeatMs`. O app monta
|
|
195
|
+
* **atrás do próprio login**; ao cair, o navegador reconecta e relê as telas.
|
|
196
|
+
*/
|
|
197
|
+
interface SseOptions {
|
|
198
|
+
bus: EventBus;
|
|
199
|
+
heartbeatMs?: number;
|
|
200
|
+
/** Filtra o que cada navegador recebe (ex.: por app ou canal). */
|
|
201
|
+
filter?: (event: LiveEvent, request: Request) => boolean;
|
|
202
|
+
}
|
|
203
|
+
declare const formatSse: (event: string, data: unknown) => string;
|
|
204
|
+
declare function createSseHandler(options: SseOptions): (request: Request) => Response;
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Configuração de MCP pronta para registrar o Engramind num agente: `POST /mcp` com o token **do agente**
|
|
208
|
+
* e o cabeçalho `Engramind-Channels` (canais do projeto). `tools/list` já mostra só o que o token pode
|
|
209
|
+
* usar; repasse ao agente só as ferramentas que a sua política permite.
|
|
210
|
+
*/
|
|
211
|
+
interface EngramindMcpConfig {
|
|
212
|
+
type: "http";
|
|
213
|
+
url: string;
|
|
214
|
+
headers: Record<string, string>;
|
|
215
|
+
}
|
|
216
|
+
declare function engramindMcpConfig(input: {
|
|
217
|
+
baseUrl: string;
|
|
218
|
+
agentToken: string;
|
|
219
|
+
channels?: readonly string[];
|
|
220
|
+
}): EngramindMcpConfig;
|
|
221
|
+
/** Ferramentas de leitura e de escrita do MCP do Engramind (para filtrar o `tools/list`). */
|
|
222
|
+
declare const MCP_READ_TOOLS: readonly ["get_context", "search_memories", "get_memory", "get_hints", "list_memories", "list_categories"];
|
|
223
|
+
declare const MCP_WRITE_TOOLS: readonly ["create_memory", "update_memory"];
|
|
224
|
+
|
|
225
|
+
export { type Broadcaster, type ContextCache, type ContextCacheOptions, type ContextEntry, type ContextResult, type ContextStore, type DedupeStore, EngramindClient, type EngramindMcpConfig, EngramindMethod, type EngramindProxyOptions, type EventBus, LiveEvent, type LiveListener, MCP_READ_TOOLS, MCP_WRITE_TOOLS, PROXY_ROUTES, type ProxyMode, type ProxyMutation, type ProxyRoute, type RouteMatch, type SseOptions, WEBHOOK_TOLERANCE_SECONDS, WebhookEvent, type WebhookHandlerOptions, contextKey, createContextCache, createEngramindProxy, createEventBus, createMemoryContextStore, createMemoryDedupe, createSseHandler, createWebhookHandler, engramindMcpConfig, errorResponse, formatSse, invalidatesContext, matchProxyRoute, parseSignatureHeader, proxySegments, signWebhook, verifyWebhookSignature };
|