@sonzai-labs/openclaw-context 1.0.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.
@@ -0,0 +1,282 @@
1
+ import { Sonzai, PersonalityResponse, MoodResponse, RelationshipResponse, MemorySearchResponse, GoalsResponse, InterestsResponse, HabitsResponse } from '@sonzai-labs/agents';
2
+
3
+ /**
4
+ * OpenClaw ContextEngine plugin interfaces.
5
+ *
6
+ * Defined locally via structural typing — no OpenClaw import required.
7
+ * OpenClaw uses duck-typing for plugin registration.
8
+ */
9
+ interface ContextEngineInfo {
10
+ id: string;
11
+ name: string;
12
+ ownsCompaction: boolean;
13
+ }
14
+ interface MessageItem {
15
+ role: string;
16
+ content: string;
17
+ }
18
+ interface MessageOrigin {
19
+ label?: string;
20
+ provider?: string;
21
+ from?: string;
22
+ to?: string;
23
+ accountId?: string;
24
+ threadId?: string;
25
+ senderName?: string;
26
+ }
27
+ interface BootstrapArgs {
28
+ sessionId: string;
29
+ }
30
+ interface IngestArgs {
31
+ sessionId: string;
32
+ message: MessageItem;
33
+ isHeartbeat: boolean;
34
+ origin?: MessageOrigin;
35
+ }
36
+ interface AssembleArgs {
37
+ sessionId: string;
38
+ messages: MessageItem[];
39
+ tokenBudget: number;
40
+ origin?: MessageOrigin;
41
+ }
42
+ interface AssembleResult {
43
+ messages: MessageItem[];
44
+ estimatedTokens: number;
45
+ systemPromptAddition?: string;
46
+ }
47
+ interface CompactArgs {
48
+ sessionId: string;
49
+ force: boolean;
50
+ }
51
+ interface CompactResult {
52
+ ok: boolean;
53
+ compacted: boolean;
54
+ }
55
+ interface AfterTurnArgs {
56
+ sessionId: string;
57
+ origin?: MessageOrigin;
58
+ }
59
+ interface ContextEngine {
60
+ info: ContextEngineInfo;
61
+ bootstrap(args: BootstrapArgs): Promise<void>;
62
+ ingest(args: IngestArgs): Promise<{
63
+ ingested: boolean;
64
+ }>;
65
+ assemble(args: AssembleArgs): Promise<AssembleResult>;
66
+ compact(args: CompactArgs): Promise<CompactResult>;
67
+ afterTurn(args: AfterTurnArgs): Promise<void>;
68
+ dispose(): Promise<void>;
69
+ }
70
+ interface PluginAPI {
71
+ registerContextEngine(id: string, factory: () => ContextEngine): void;
72
+ }
73
+ interface SessionState {
74
+ agentId: string;
75
+ userId: string;
76
+ sonzaiSessionId: string;
77
+ startedAt: number;
78
+ turnCount: number;
79
+ lastProcessedIndex: number;
80
+ lastMessages: MessageItem[];
81
+ }
82
+
83
+ /**
84
+ * OpenClaw plugin entry point.
85
+ *
86
+ * Registers the "sonzai" ContextEngine with OpenClaw's plugin system.
87
+ */
88
+
89
+ declare function register(api: PluginAPI): void;
90
+
91
+ /**
92
+ * Plugin configuration — maps to `plugins.entries.sonzai` in openclaw.json
93
+ * or environment variables.
94
+ */
95
+ interface DisableMap {
96
+ mood?: boolean;
97
+ personality?: boolean;
98
+ relationships?: boolean;
99
+ memory?: boolean;
100
+ goals?: boolean;
101
+ interests?: boolean;
102
+ habits?: boolean;
103
+ }
104
+ interface SonzaiPluginConfig {
105
+ /** Sonzai API key (sk-...). Required. */
106
+ apiKey: string;
107
+ /** Pre-provisioned agent UUID. If omitted, auto-provisions from agentName. */
108
+ agentId?: string;
109
+ /** Base URL override (e.g. for staging). Defaults to https://api.sonz.ai */
110
+ baseUrl?: string;
111
+ /**
112
+ * Agent name for auto-provisioning. The backend derives a deterministic
113
+ * UUID from (tenantID + lowercase(name)), so the same API key + same name
114
+ * always maps to the same agent — no duplicates across restarts.
115
+ *
116
+ * IMPORTANT for B2B: if multiple OpenClaw instances share one API key,
117
+ * each needs a unique agentName to get its own Sonzai agent.
118
+ * Defaults to "openclaw-agent".
119
+ */
120
+ agentName?: string;
121
+ /** Default userId when session key has no peer identity (CLI 1:1). Defaults to "owner". */
122
+ defaultUserId?: string;
123
+ /** Max tokens for Sonzai context injection. Defaults to 2000. */
124
+ contextTokenBudget?: number;
125
+ /** Selectively disable context sources. */
126
+ disable?: DisableMap;
127
+ /** LLM provider for side-effect extraction (e.g. "gemini", "openai"). Uses platform default if omitted. */
128
+ extractionProvider?: string;
129
+ /** LLM model for side-effect extraction (e.g. "gemini-2.5-flash"). Uses platform default if omitted. */
130
+ extractionModel?: string;
131
+ }
132
+ interface ResolvedConfig {
133
+ apiKey: string;
134
+ agentId: string | undefined;
135
+ baseUrl: string;
136
+ agentName: string;
137
+ defaultUserId: string;
138
+ contextTokenBudget: number;
139
+ disable: DisableMap;
140
+ extractionProvider: string | undefined;
141
+ extractionModel: string | undefined;
142
+ }
143
+ /**
144
+ * Resolve configuration from explicit config, then fall back to env vars.
145
+ */
146
+ declare function resolveConfig(raw?: Partial<SonzaiPluginConfig>): ResolvedConfig;
147
+
148
+ /**
149
+ * SonzaiContextEngine — bridges OpenClaw lifecycle hooks to the
150
+ * Sonzai Mind Layer API via @sonzai-labs/agents.
151
+ */
152
+
153
+ declare class SonzaiContextEngine implements ContextEngine {
154
+ private readonly client;
155
+ private readonly config;
156
+ readonly info: ContextEngineInfo;
157
+ private readonly sessions;
158
+ private readonly agentCache;
159
+ constructor(client: Sonzai, config: ResolvedConfig);
160
+ bootstrap({ sessionId }: BootstrapArgs): Promise<void>;
161
+ ingest(_args: IngestArgs): Promise<{
162
+ ingested: boolean;
163
+ }>;
164
+ assemble({ sessionId, messages, tokenBudget, origin, }: AssembleArgs): Promise<AssembleResult>;
165
+ compact({ sessionId }: CompactArgs): Promise<CompactResult>;
166
+ afterTurn({ sessionId }: AfterTurnArgs): Promise<void>;
167
+ dispose(): Promise<void>;
168
+ /**
169
+ * Resolve the Sonzai agent ID: use config if provided, otherwise
170
+ * auto-provision via the idempotent create endpoint.
171
+ *
172
+ * Idempotency guarantee: the backend derives a deterministic UUID v5 from
173
+ * `SHA1(namespace, tenantID + "/" + lowercase(name))`. Same API key (tenant)
174
+ * + same name → same UUID on every call, even across restarts or pod
175
+ * replacements.
176
+ *
177
+ * The name used is always `config.agentName` (default: "openclaw-agent").
178
+ * This is stable because it comes from the plugin config / env var, not
179
+ * from any runtime state like pod IDs or session UUIDs.
180
+ *
181
+ * If a B2B client needs multiple distinct agents under one API key, they
182
+ * set a unique `agentName` per OpenClaw instance in their config.
183
+ */
184
+ private resolveAgentId;
185
+ }
186
+
187
+ /**
188
+ * Extracts user identity from OpenClaw session keys.
189
+ *
190
+ * Session key formats:
191
+ * CLI 1:1 — agent:<agentId>:<mainKey>
192
+ * DM — agent:<agentId>:<channel>:direct:<peerId>
193
+ * Group — agent:<agentId>:<channel>:group:<groupId>
194
+ * Cron — cron:<jobId>
195
+ * Webhook — hook:<uuid>
196
+ */
197
+ interface ParsedSessionKey {
198
+ /** The agentId segment from the session key (may differ from configured agentId). */
199
+ agentId: string | null;
200
+ /** Resolved userId for Sonzai SDK calls. */
201
+ userId: string;
202
+ /** Channel identifier (e.g. "telegram", "discord"), if present. */
203
+ channel: string | null;
204
+ /** How this session was identified. */
205
+ sessionType: "cli" | "dm" | "group" | "cron" | "webhook" | "unknown";
206
+ }
207
+ declare function parseSessionKey(sessionId: string, defaultUserId: string): ParsedSessionKey;
208
+
209
+ /**
210
+ * Transforms Sonzai API responses into a formatted systemPromptAddition
211
+ * string for OpenClaw context injection.
212
+ */
213
+
214
+ interface ContextSources {
215
+ personality?: PersonalityResponse;
216
+ mood?: MoodResponse;
217
+ relationships?: RelationshipResponse;
218
+ memories?: MemorySearchResponse;
219
+ goals?: GoalsResponse;
220
+ interests?: InterestsResponse;
221
+ habits?: HabitsResponse;
222
+ }
223
+ /**
224
+ * Build the systemPromptAddition from all available context sources.
225
+ * Returns an empty string if no data is available.
226
+ */
227
+ declare function buildSystemPromptAddition(sources: ContextSources, tokenBudget: number): string;
228
+ /**
229
+ * Rough token estimate: ~4 chars per token, erring on overestimation.
230
+ */
231
+ declare function estimateTokens(text: string): number;
232
+
233
+ /**
234
+ * Lightweight in-memory TTL cache.
235
+ *
236
+ * Used to avoid re-fetching slow-changing data (personality, agent profile)
237
+ * on every assemble() call.
238
+ */
239
+ declare class SessionCache<T> {
240
+ private readonly ttlMs;
241
+ private readonly store;
242
+ constructor(ttlMs: number);
243
+ get(key: string): T | undefined;
244
+ set(key: string, value: T): void;
245
+ delete(key: string): void;
246
+ clear(): void;
247
+ }
248
+
249
+ /**
250
+ * Interactive and programmatic setup for the Sonzai OpenClaw plugin.
251
+ *
252
+ * Interactive: `npx @sonzai-labs/openclaw-context setup`
253
+ * Programmatic: `import { setup } from "@sonzai-labs/openclaw-context"`
254
+ */
255
+ interface SetupOptions {
256
+ /** Sonzai API key. */
257
+ apiKey: string;
258
+ /** Agent name (deterministic ID derived from tenant + name). */
259
+ agentName?: string;
260
+ /** Pre-existing agent ID (skips agent provisioning). */
261
+ agentId?: string;
262
+ /** Base URL override. */
263
+ baseUrl?: string;
264
+ /** Path to openclaw.json. Defaults to ./openclaw.json */
265
+ configPath?: string;
266
+ /** If true, writes to openclaw.json. If false, returns config object only. */
267
+ writeConfig?: boolean;
268
+ }
269
+ interface SetupResult {
270
+ agentId: string;
271
+ agentName: string;
272
+ config: Record<string, unknown>;
273
+ configPath?: string;
274
+ written: boolean;
275
+ }
276
+ /**
277
+ * Programmatic setup — validates API key, provisions agent, optionally
278
+ * writes openclaw.json. Designed for B2B automation scripts.
279
+ */
280
+ declare function setup(options: SetupOptions): Promise<SetupResult>;
281
+
282
+ export { type AfterTurnArgs, type AssembleArgs, type AssembleResult, type BootstrapArgs, type CompactArgs, type CompactResult, type ContextEngine, type ContextEngineInfo, type ContextSources, type DisableMap, type IngestArgs, type MessageItem, type MessageOrigin, type ParsedSessionKey, type PluginAPI, type ResolvedConfig, SessionCache, type SessionState, type SetupOptions, type SetupResult, SonzaiContextEngine, type SonzaiPluginConfig, buildSystemPromptAddition, register as default, estimateTokens, parseSessionKey, resolveConfig, setup };