opc-agent 3.0.0 → 4.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.
- package/README.md +30 -24
- package/dist/channels/dingtalk.d.ts +17 -0
- package/dist/channels/dingtalk.js +38 -0
- package/dist/channels/googlechat.d.ts +14 -0
- package/dist/channels/googlechat.js +37 -0
- package/dist/channels/imessage.d.ts +13 -0
- package/dist/channels/imessage.js +28 -0
- package/dist/channels/irc.d.ts +20 -0
- package/dist/channels/irc.js +71 -0
- package/dist/channels/line.d.ts +14 -0
- package/dist/channels/line.js +28 -0
- package/dist/channels/matrix.d.ts +15 -0
- package/dist/channels/matrix.js +28 -0
- package/dist/channels/mattermost.d.ts +18 -0
- package/dist/channels/mattermost.js +49 -0
- package/dist/channels/msteams.d.ts +14 -0
- package/dist/channels/msteams.js +28 -0
- package/dist/channels/nostr.d.ts +14 -0
- package/dist/channels/nostr.js +28 -0
- package/dist/channels/qq.d.ts +15 -0
- package/dist/channels/qq.js +28 -0
- package/dist/channels/signal.d.ts +14 -0
- package/dist/channels/signal.js +28 -0
- package/dist/channels/sms.d.ts +15 -0
- package/dist/channels/sms.js +28 -0
- package/dist/channels/twitch.d.ts +17 -0
- package/dist/channels/twitch.js +59 -0
- package/dist/channels/voice-call.d.ts +27 -0
- package/dist/channels/voice-call.js +82 -0
- package/dist/channels/whatsapp.d.ts +14 -0
- package/dist/channels/whatsapp.js +28 -0
- package/dist/cli.js +36 -0
- package/dist/core/api-server.d.ts +25 -0
- package/dist/core/api-server.js +286 -0
- package/dist/core/audio.d.ts +50 -0
- package/dist/core/audio.js +68 -0
- package/dist/core/context-discovery.d.ts +16 -0
- package/dist/core/context-discovery.js +107 -0
- package/dist/core/context-refs.d.ts +29 -0
- package/dist/core/context-refs.js +162 -0
- package/dist/core/gateway.d.ts +53 -0
- package/dist/core/gateway.js +80 -0
- package/dist/core/heartbeat.d.ts +19 -0
- package/dist/core/heartbeat.js +50 -0
- package/dist/core/hooks.d.ts +28 -0
- package/dist/core/hooks.js +82 -0
- package/dist/core/ide-bridge.d.ts +53 -0
- package/dist/core/ide-bridge.js +97 -0
- package/dist/core/node-network.d.ts +23 -0
- package/dist/core/node-network.js +77 -0
- package/dist/core/profiles.d.ts +27 -0
- package/dist/core/profiles.js +131 -0
- package/dist/core/sandbox.d.ts +25 -0
- package/dist/core/sandbox.js +84 -1
- package/dist/core/session-manager.d.ts +33 -0
- package/dist/core/session-manager.js +157 -0
- package/dist/core/vision.d.ts +45 -0
- package/dist/core/vision.js +177 -0
- package/dist/index.d.ts +64 -1
- package/dist/index.js +86 -3
- package/dist/memory/context-compressor.d.ts +43 -0
- package/dist/memory/context-compressor.js +167 -0
- package/dist/memory/index.d.ts +4 -0
- package/dist/memory/index.js +5 -1
- package/dist/memory/user-profiler.d.ts +50 -0
- package/dist/memory/user-profiler.js +201 -0
- package/dist/schema/oad.d.ts +12 -12
- package/dist/security/approvals.d.ts +53 -0
- package/dist/security/approvals.js +115 -0
- package/dist/security/elevated.d.ts +41 -0
- package/dist/security/elevated.js +89 -0
- package/dist/security/index.d.ts +6 -0
- package/dist/security/index.js +7 -1
- package/dist/security/secrets.d.ts +34 -0
- package/dist/security/secrets.js +115 -0
- package/dist/tools/builtin/browser.d.ts +47 -0
- package/dist/tools/builtin/browser.js +284 -0
- package/dist/tools/builtin/home-assistant.d.ts +12 -0
- package/dist/tools/builtin/home-assistant.js +126 -0
- package/dist/tools/builtin/index.d.ts +6 -1
- package/dist/tools/builtin/index.js +18 -2
- package/dist/tools/builtin/rl-tools.d.ts +13 -0
- package/dist/tools/builtin/rl-tools.js +228 -0
- package/dist/tools/builtin/vision.d.ts +6 -0
- package/dist/tools/builtin/vision.js +61 -0
- package/package.json +3 -3
- package/src/channels/dingtalk.ts +46 -0
- package/src/channels/googlechat.ts +42 -0
- package/src/channels/imessage.ts +32 -0
- package/src/channels/irc.ts +82 -0
- package/src/channels/line.ts +33 -0
- package/src/channels/matrix.ts +34 -0
- package/src/channels/mattermost.ts +57 -0
- package/src/channels/msteams.ts +33 -0
- package/src/channels/nostr.ts +33 -0
- package/src/channels/qq.ts +34 -0
- package/src/channels/signal.ts +33 -0
- package/src/channels/sms.ts +34 -0
- package/src/channels/twitch.ts +65 -0
- package/src/channels/voice-call.ts +100 -0
- package/src/channels/whatsapp.ts +33 -0
- package/src/cli.ts +40 -0
- package/src/core/api-server.ts +277 -0
- package/src/core/audio.ts +98 -0
- package/src/core/context-discovery.ts +85 -0
- package/src/core/context-refs.ts +140 -0
- package/src/core/gateway.ts +106 -0
- package/src/core/heartbeat.ts +51 -0
- package/src/core/hooks.ts +105 -0
- package/src/core/ide-bridge.ts +133 -0
- package/src/core/node-network.ts +86 -0
- package/src/core/profiles.ts +122 -0
- package/src/core/sandbox.ts +100 -0
- package/src/core/session-manager.ts +137 -0
- package/src/core/vision.ts +180 -0
- package/src/index.ts +84 -1
- package/src/memory/context-compressor.ts +189 -0
- package/src/memory/index.ts +4 -0
- package/src/memory/user-profiler.ts +215 -0
- package/src/security/approvals.ts +143 -0
- package/src/security/elevated.ts +105 -0
- package/src/security/index.ts +6 -0
- package/src/security/secrets.ts +129 -0
- package/src/tools/builtin/browser.ts +299 -0
- package/src/tools/builtin/home-assistant.ts +116 -0
- package/src/tools/builtin/index.ts +9 -2
- package/src/tools/builtin/rl-tools.ts +243 -0
- package/src/tools/builtin/vision.ts +64 -0
- package/tests/api-server.test.ts +148 -0
- package/tests/approvals.test.ts +89 -0
- package/tests/audio.test.ts +40 -0
- package/tests/browser.test.ts +179 -0
- package/tests/builtin-tools.test.ts +83 -83
- package/tests/channels-extra.test.ts +45 -0
- package/tests/context-compressor.test.ts +172 -0
- package/tests/context-refs.test.ts +121 -0
- package/tests/elevated.test.ts +69 -0
- package/tests/gateway.test.ts +63 -71
- package/tests/home-assistant.test.ts +40 -0
- package/tests/hooks.test.ts +79 -0
- package/tests/ide-bridge.test.ts +38 -0
- package/tests/node-network.test.ts +74 -0
- package/tests/profiles.test.ts +61 -0
- package/tests/rl-tools.test.ts +93 -0
- package/tests/sandbox-manager.test.ts +46 -0
- package/tests/secrets.test.ts +107 -0
- package/tests/tools/builtin-extended.test.ts +138 -138
- package/tests/user-profiler.test.ts +169 -0
- package/tests/v090-features.test.ts +254 -0
- package/tests/vision.test.ts +61 -0
- package/tests/voice-call.test.ts +47 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
|
|
4
|
+
// ─── Types ───────────────────────────────────────────────────
|
|
5
|
+
|
|
6
|
+
export interface ImageInput {
|
|
7
|
+
type: 'base64' | 'url' | 'file';
|
|
8
|
+
data: string;
|
|
9
|
+
mimeType?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface VisionResult {
|
|
13
|
+
description: string;
|
|
14
|
+
text_content?: string;
|
|
15
|
+
objects?: string[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// ─── MIME detection from magic bytes ─────────────────────────
|
|
19
|
+
|
|
20
|
+
const MAGIC_BYTES: Array<{ bytes: number[]; mime: string }> = [
|
|
21
|
+
{ bytes: [0x89, 0x50, 0x4E, 0x47], mime: 'image/png' },
|
|
22
|
+
{ bytes: [0xFF, 0xD8, 0xFF], mime: 'image/jpeg' },
|
|
23
|
+
{ bytes: [0x47, 0x49, 0x46, 0x38], mime: 'image/gif' },
|
|
24
|
+
{ bytes: [0x52, 0x49, 0x46, 0x46], mime: 'image/webp' }, // RIFF header (WebP)
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
export function detectMimeType(buffer: Buffer): string {
|
|
28
|
+
for (const { bytes, mime } of MAGIC_BYTES) {
|
|
29
|
+
if (bytes.every((b, i) => buffer[i] === b)) {
|
|
30
|
+
return mime;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return 'application/octet-stream';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ─── VisionManager ───────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
export interface VisionManagerConfig {
|
|
39
|
+
model?: string;
|
|
40
|
+
apiKey?: string;
|
|
41
|
+
baseURL?: string;
|
|
42
|
+
maxImageSize?: number; // bytes, default 20MB
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class VisionManager {
|
|
46
|
+
private config: VisionManagerConfig;
|
|
47
|
+
|
|
48
|
+
constructor(config: VisionManagerConfig = {}) {
|
|
49
|
+
this.config = {
|
|
50
|
+
model: config.model ?? 'gpt-4o',
|
|
51
|
+
apiKey: config.apiKey ?? process.env.OPENAI_API_KEY ?? '',
|
|
52
|
+
baseURL: config.baseURL ?? 'https://api.openai.com/v1',
|
|
53
|
+
maxImageSize: config.maxImageSize ?? 20 * 1024 * 1024,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Load image data as base64, detecting MIME type.
|
|
59
|
+
*/
|
|
60
|
+
async loadImage(input: ImageInput): Promise<{ base64: string; mimeType: string }> {
|
|
61
|
+
if (input.type === 'base64') {
|
|
62
|
+
const buf = Buffer.from(input.data, 'base64');
|
|
63
|
+
return { base64: input.data, mimeType: input.mimeType ?? detectMimeType(buf) };
|
|
64
|
+
}
|
|
65
|
+
if (input.type === 'file') {
|
|
66
|
+
const buf = fs.readFileSync(input.data);
|
|
67
|
+
if (buf.length > this.config.maxImageSize!) {
|
|
68
|
+
throw new Error(`Image exceeds max size: ${buf.length} > ${this.config.maxImageSize}`);
|
|
69
|
+
}
|
|
70
|
+
return { base64: buf.toString('base64'), mimeType: input.mimeType ?? detectMimeType(buf) };
|
|
71
|
+
}
|
|
72
|
+
// URL — return as-is for API
|
|
73
|
+
return { base64: '', mimeType: input.mimeType ?? 'image/jpeg' };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Prepare messages in OpenAI multimodal format.
|
|
78
|
+
*/
|
|
79
|
+
prepareMessage(images: ImageInput[], text: string): Array<Record<string, unknown>> {
|
|
80
|
+
const content: Array<Record<string, unknown>> = [];
|
|
81
|
+
if (text) {
|
|
82
|
+
content.push({ type: 'text', text });
|
|
83
|
+
}
|
|
84
|
+
for (const img of images) {
|
|
85
|
+
if (img.type === 'url') {
|
|
86
|
+
content.push({
|
|
87
|
+
type: 'image_url',
|
|
88
|
+
image_url: { url: img.data },
|
|
89
|
+
});
|
|
90
|
+
} else {
|
|
91
|
+
// base64 or file — will need to be loaded first
|
|
92
|
+
const mime = img.mimeType ?? 'image/jpeg';
|
|
93
|
+
const data = img.type === 'base64' ? img.data : fs.readFileSync(img.data).toString('base64');
|
|
94
|
+
content.push({
|
|
95
|
+
type: 'image_url',
|
|
96
|
+
image_url: { url: `data:${mime};base64,${data}` },
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return [{ role: 'user', content }];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Analyze an image with optional prompt.
|
|
105
|
+
*/
|
|
106
|
+
async analyze(image: ImageInput, prompt?: string): Promise<VisionResult> {
|
|
107
|
+
const messages = this.prepareMessage([image], prompt ?? 'Describe this image in detail.');
|
|
108
|
+
|
|
109
|
+
if (!this.config.apiKey) {
|
|
110
|
+
throw new Error('Vision API key not configured. Set OPENAI_API_KEY or pass apiKey in config.');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const response = await fetch(`${this.config.baseURL}/chat/completions`, {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
headers: {
|
|
116
|
+
'Content-Type': 'application/json',
|
|
117
|
+
'Authorization': `Bearer ${this.config.apiKey}`,
|
|
118
|
+
},
|
|
119
|
+
body: JSON.stringify({
|
|
120
|
+
model: this.config.model,
|
|
121
|
+
messages,
|
|
122
|
+
max_tokens: 1000,
|
|
123
|
+
}),
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
if (!response.ok) {
|
|
127
|
+
throw new Error(`Vision API error: ${response.status} ${response.statusText}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const data = await response.json() as any;
|
|
131
|
+
const text = data.choices?.[0]?.message?.content ?? '';
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
description: text,
|
|
135
|
+
text_content: undefined,
|
|
136
|
+
objects: [],
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Extract text (OCR) from an image.
|
|
142
|
+
*/
|
|
143
|
+
async extractText(image: ImageInput): Promise<string> {
|
|
144
|
+
const result = await this.analyze(image, 'Extract all visible text from this image. Return only the text, nothing else.');
|
|
145
|
+
return result.description;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Compare multiple images.
|
|
150
|
+
*/
|
|
151
|
+
async compareImages(images: ImageInput[], prompt?: string): Promise<string> {
|
|
152
|
+
if (images.length < 2) throw new Error('Need at least 2 images to compare');
|
|
153
|
+
|
|
154
|
+
const messages = this.prepareMessage(images, prompt ?? 'Compare these images and describe the differences.');
|
|
155
|
+
|
|
156
|
+
if (!this.config.apiKey) {
|
|
157
|
+
throw new Error('Vision API key not configured.');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const response = await fetch(`${this.config.baseURL}/chat/completions`, {
|
|
161
|
+
method: 'POST',
|
|
162
|
+
headers: {
|
|
163
|
+
'Content-Type': 'application/json',
|
|
164
|
+
'Authorization': `Bearer ${this.config.apiKey}`,
|
|
165
|
+
},
|
|
166
|
+
body: JSON.stringify({
|
|
167
|
+
model: this.config.model,
|
|
168
|
+
messages,
|
|
169
|
+
max_tokens: 1000,
|
|
170
|
+
}),
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
if (!response.ok) {
|
|
174
|
+
throw new Error(`Vision API error: ${response.status} ${response.statusText}`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const data = await response.json() as any;
|
|
178
|
+
return data.choices?.[0]?.message?.content ?? '';
|
|
179
|
+
}
|
|
180
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -78,6 +78,26 @@ export { TextAnalysisTool } from './tools/text-analysis';
|
|
|
78
78
|
export { HttpSkill } from './skills/http';
|
|
79
79
|
export { WebhookTriggerSkill } from './skills/webhook-trigger';
|
|
80
80
|
export type { WebhookTarget } from './skills/webhook-trigger';
|
|
81
|
+
|
|
82
|
+
// v0.9.0 channels
|
|
83
|
+
export { DingTalkChannel } from './channels/dingtalk';
|
|
84
|
+
export type { DingTalkChannelConfig } from './channels/dingtalk';
|
|
85
|
+
export { MattermostChannel } from './channels/mattermost';
|
|
86
|
+
export type { MattermostChannelConfig } from './channels/mattermost';
|
|
87
|
+
export { GoogleChatChannel } from './channels/googlechat';
|
|
88
|
+
export type { GoogleChatChannelConfig } from './channels/googlechat';
|
|
89
|
+
export { TwitchChannel } from './channels/twitch';
|
|
90
|
+
export type { TwitchChannelConfig } from './channels/twitch';
|
|
91
|
+
export { IRCChannel } from './channels/irc';
|
|
92
|
+
export type { IRCChannelConfig } from './channels/irc';
|
|
93
|
+
|
|
94
|
+
// v0.9.0 core
|
|
95
|
+
export { ContextDiscovery } from './core/context-discovery';
|
|
96
|
+
export type { ContextFile } from './core/context-discovery';
|
|
97
|
+
export { SessionManager } from './core/session-manager';
|
|
98
|
+
export type { Session } from './core/session-manager';
|
|
99
|
+
export { HeartbeatManager } from './core/heartbeat';
|
|
100
|
+
export type { HeartbeatConfig } from './core/heartbeat';
|
|
81
101
|
export { SchedulerSkill } from './skills/scheduler';
|
|
82
102
|
export type { ScheduledTask } from './skills/scheduler';
|
|
83
103
|
export { DocumentSkill } from './skills/document';
|
|
@@ -111,6 +131,20 @@ export { contentFilterPlugin, createContentFilterPlugin } from './plugins/conten
|
|
|
111
131
|
export { GuardrailManager, createGuardrailsFromConfig } from './security/guardrails';
|
|
112
132
|
export type { GuardrailConfig, GuardrailRule, GuardrailResult, GuardrailViolation } from './security/guardrails';
|
|
113
133
|
|
|
134
|
+
// v3.1.0 — Exec Approvals + Elevated + Secrets
|
|
135
|
+
export { ExecApprovalManager } from './security/approvals';
|
|
136
|
+
export type { ExecApprovalPolicy, ExecApprovalRequest, ExecApprovalHistory, ApprovalRequestCallback } from './security/approvals';
|
|
137
|
+
export { ElevatedManager } from './security/elevated';
|
|
138
|
+
export type { ElevationMode, ElevationAuditEntry } from './security/elevated';
|
|
139
|
+
export { SecretsManager } from './security/secrets';
|
|
140
|
+
export type { SecretsStore } from './security/secrets';
|
|
141
|
+
|
|
142
|
+
// v3.1.0 — Hooks + Audio
|
|
143
|
+
export { HookManager, ALL_HOOK_EVENTS } from './core/hooks';
|
|
144
|
+
export type { HookEvent, HookContext, HookHandler } from './core/hooks';
|
|
145
|
+
export { AudioProcessor } from './core/audio';
|
|
146
|
+
export type { AudioFormat, TranscribeOptions, SynthesizeOptions, TranscribeResult, SynthesizeResult } from './core/audio';
|
|
147
|
+
|
|
114
148
|
// v1.1.0 modules
|
|
115
149
|
export { FeishuChannel } from './channels/feishu';
|
|
116
150
|
export type { FeishuChannelConfig } from './channels/feishu';
|
|
@@ -142,7 +176,7 @@ export { Scheduler, parseCron, cronMatches } from './core/scheduler';
|
|
|
142
176
|
export type { CronJob, JobHandler } from './core/scheduler';
|
|
143
177
|
|
|
144
178
|
// v1.5.0 — built-in tools + MCP client
|
|
145
|
-
export { getBuiltinTools, getBuiltinToolsByName } from './tools/builtin';
|
|
179
|
+
export { getBuiltinTools, getBuiltinToolsByName, rlTools, homeAssistantTools, configureHomeAssistant } from './tools/builtin';
|
|
146
180
|
export { MCPClient } from './tools/mcp-client';
|
|
147
181
|
export type { MCPServerConfig } from './tools/mcp-client';
|
|
148
182
|
|
|
@@ -186,6 +220,55 @@ export type {
|
|
|
186
220
|
StepStartedEvent, StepFinishedEvent, CustomEvent,
|
|
187
221
|
} from './protocols/agui';
|
|
188
222
|
|
|
223
|
+
// v2.1.0 — API Server + Context References
|
|
224
|
+
export { APIServer } from './core/api-server';
|
|
225
|
+
export type { APIServerConfig } from './core/api-server';
|
|
226
|
+
export { ContextRefResolver } from './core/context-refs';
|
|
227
|
+
export type { ContextRef, RefType } from './core/context-refs';
|
|
228
|
+
|
|
229
|
+
// v2.2.0 — Vision
|
|
230
|
+
export { VisionManager, detectMimeType } from './core/vision';
|
|
231
|
+
export type { ImageInput, VisionResult, VisionManagerConfig } from './core/vision';
|
|
232
|
+
export { visionTools, visionAnalyzeTool, visionExtractTextTool, visionCompareTool } from './tools/builtin/vision';
|
|
233
|
+
|
|
234
|
+
// v2.2.0 — Additional channels
|
|
235
|
+
export { WhatsAppChannel } from './channels/whatsapp';
|
|
236
|
+
export type { WhatsAppChannelConfig } from './channels/whatsapp';
|
|
237
|
+
export { SignalChannel } from './channels/signal';
|
|
238
|
+
export type { SignalChannelConfig } from './channels/signal';
|
|
239
|
+
export { MatrixChannel } from './channels/matrix';
|
|
240
|
+
export type { MatrixChannelConfig } from './channels/matrix';
|
|
241
|
+
export { IMessageChannel } from './channels/imessage';
|
|
242
|
+
export type { IMessageChannelConfig } from './channels/imessage';
|
|
243
|
+
export { LINEChannel } from './channels/line';
|
|
244
|
+
export type { LINEChannelConfig } from './channels/line';
|
|
245
|
+
export { MSTeamsChannel } from './channels/msteams';
|
|
246
|
+
export type { MSTeamsChannelConfig } from './channels/msteams';
|
|
247
|
+
export { QQChannel } from './channels/qq';
|
|
248
|
+
export type { QQChannelConfig } from './channels/qq';
|
|
249
|
+
export { NostrChannel } from './channels/nostr';
|
|
250
|
+
export type { NostrChannelConfig } from './channels/nostr';
|
|
251
|
+
export { SMSChannel } from './channels/sms';
|
|
252
|
+
export type { SMSChannelConfig } from './channels/sms';
|
|
253
|
+
|
|
254
|
+
// v2.3.0 — Voice Calls + IDE + Node Network + Gateway
|
|
255
|
+
export { VoiceCallManager } from './channels/voice-call';
|
|
256
|
+
export type { VoiceCallConfig } from './channels/voice-call';
|
|
257
|
+
export { IDEBridge } from './core/ide-bridge';
|
|
258
|
+
export type { IDEConfig, Diagnostic, TextEdit, Range, SearchOptions, SearchResult } from './core/ide-bridge';
|
|
259
|
+
export { NodeNetwork } from './core/node-network';
|
|
260
|
+
export type { RemoteNode } from './core/node-network';
|
|
261
|
+
export { Gateway } from './core/gateway';
|
|
262
|
+
export type { AgentConfig as GatewayAgentConfig, ChannelConfig as GatewayChannelConfig, GatewayConfig } from './core/gateway';
|
|
263
|
+
|
|
264
|
+
// v2.2.0 — Remote Sandbox
|
|
265
|
+
export { SandboxManager } from './core/sandbox';
|
|
266
|
+
export type { RemoteSandboxConfig, ExecResult } from './core/sandbox';
|
|
267
|
+
|
|
268
|
+
// v2.2.0 — Profiles
|
|
269
|
+
export { ProfileManager } from './core/profiles';
|
|
270
|
+
export type { Profile, ProfileConfig } from './core/profiles';
|
|
271
|
+
|
|
189
272
|
// v2.0.0 - Pre-built tool integrations (20 tools)
|
|
190
273
|
export {
|
|
191
274
|
SlackTool, EmailSendTool, WebhookTool,
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import type { Message } from '../core/types';
|
|
2
|
+
|
|
3
|
+
export interface CompressorConfig {
|
|
4
|
+
maxTokens: number;
|
|
5
|
+
compressThreshold: number;
|
|
6
|
+
preserveRecent: number;
|
|
7
|
+
brain?: any;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface CompressResult {
|
|
11
|
+
messages: Message[];
|
|
12
|
+
learnedCount: number;
|
|
13
|
+
savedTokens: number;
|
|
14
|
+
summary: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const DEFAULT_CONFIG: CompressorConfig = {
|
|
18
|
+
maxTokens: 8000,
|
|
19
|
+
compressThreshold: 0.8,
|
|
20
|
+
preserveRecent: 10,
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Context compression with optional DeepBrain memory offloading.
|
|
25
|
+
*/
|
|
26
|
+
export class ContextCompressor {
|
|
27
|
+
private config: CompressorConfig;
|
|
28
|
+
|
|
29
|
+
constructor(config: Partial<CompressorConfig> = {}) {
|
|
30
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Estimate token count using language-aware heuristic.
|
|
35
|
+
* English: ~1 token per 4 chars. Chinese: ~1 token per 2 chars.
|
|
36
|
+
*/
|
|
37
|
+
estimateTokens(text: string): number {
|
|
38
|
+
let tokens = 0;
|
|
39
|
+
for (const char of text) {
|
|
40
|
+
// CJK Unicode range detection
|
|
41
|
+
const code = char.codePointAt(0) ?? 0;
|
|
42
|
+
if (
|
|
43
|
+
(code >= 0x4e00 && code <= 0x9fff) || // CJK Unified
|
|
44
|
+
(code >= 0x3400 && code <= 0x4dbf) || // CJK Extension A
|
|
45
|
+
(code >= 0x3000 && code <= 0x303f) // CJK Punctuation
|
|
46
|
+
) {
|
|
47
|
+
tokens += 0.5; // 1 token per 2 chars
|
|
48
|
+
} else {
|
|
49
|
+
tokens += 0.25; // 1 token per 4 chars
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return Math.ceil(tokens);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private estimateMessagesTokens(messages: Message[]): number {
|
|
56
|
+
return messages.reduce((sum, m) => sum + this.estimateTokens(m.content), 0);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Extract key insights from messages for brain storage.
|
|
61
|
+
*/
|
|
62
|
+
private extractInsights(messages: Message[]): Array<{ content: string; type: string }> {
|
|
63
|
+
const insights: Array<{ content: string; type: string }> = [];
|
|
64
|
+
for (const msg of messages) {
|
|
65
|
+
const c = msg.content;
|
|
66
|
+
// Decisions
|
|
67
|
+
if (/\b(decided|decision|choose|chose|will use|going with|let's go|确定|决定)\b/i.test(c)) {
|
|
68
|
+
insights.push({ content: c.slice(0, 500), type: 'decision' });
|
|
69
|
+
}
|
|
70
|
+
// Facts / definitions
|
|
71
|
+
else if (/\b(is defined as|means|equals|refers to|是指|定义)\b/i.test(c)) {
|
|
72
|
+
insights.push({ content: c.slice(0, 500), type: 'fact' });
|
|
73
|
+
}
|
|
74
|
+
// Preferences
|
|
75
|
+
else if (/\b(prefer|like|want|don't like|不喜欢|喜欢|偏好)\b/i.test(c)) {
|
|
76
|
+
insights.push({ content: c.slice(0, 500), type: 'preference' });
|
|
77
|
+
}
|
|
78
|
+
// Code snippets
|
|
79
|
+
else if (/```[\s\S]{20,}```/.test(c)) {
|
|
80
|
+
insights.push({ content: c.slice(0, 800), type: 'code' });
|
|
81
|
+
}
|
|
82
|
+
// Long assistant messages likely contain useful info
|
|
83
|
+
else if (msg.role === 'assistant' && c.length > 200) {
|
|
84
|
+
insights.push({ content: c.slice(0, 500), type: 'knowledge' });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return insights;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Generate a simple summary from messages (no-brain fallback).
|
|
92
|
+
*/
|
|
93
|
+
private summarize(messages: Message[]): string {
|
|
94
|
+
const topics = new Set<string>();
|
|
95
|
+
const keyLines: string[] = [];
|
|
96
|
+
|
|
97
|
+
for (const msg of messages) {
|
|
98
|
+
// Extract first meaningful sentence
|
|
99
|
+
const firstLine = msg.content.split(/[.\n!?。!?]/)[0]?.trim();
|
|
100
|
+
if (firstLine && firstLine.length > 10 && firstLine.length < 200) {
|
|
101
|
+
if (keyLines.length < 5) keyLines.push(`[${msg.role}] ${firstLine}`);
|
|
102
|
+
}
|
|
103
|
+
// Extract topic words (capitalized words, Chinese phrases)
|
|
104
|
+
const words = msg.content.match(/[A-Z][a-z]{2,}/g) ?? [];
|
|
105
|
+
words.forEach(w => topics.add(w));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const topicStr = [...topics].slice(0, 10).join(', ');
|
|
109
|
+
const linesStr = keyLines.join('; ');
|
|
110
|
+
return `Topics: ${topicStr || 'general discussion'}. Key points: ${linesStr || 'varied conversation'}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Compress messages when token count exceeds threshold.
|
|
115
|
+
*/
|
|
116
|
+
async compress(messages: Message[], config?: Partial<CompressorConfig>): Promise<CompressResult> {
|
|
117
|
+
const cfg = { ...this.config, ...config };
|
|
118
|
+
const totalTokens = this.estimateMessagesTokens(messages);
|
|
119
|
+
const threshold = cfg.maxTokens * cfg.compressThreshold;
|
|
120
|
+
|
|
121
|
+
// Under threshold — return as-is
|
|
122
|
+
if (totalTokens <= threshold) {
|
|
123
|
+
return {
|
|
124
|
+
messages: [...messages],
|
|
125
|
+
learnedCount: 0,
|
|
126
|
+
savedTokens: 0,
|
|
127
|
+
summary: '',
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const recentCount = Math.min(cfg.preserveRecent, messages.length);
|
|
132
|
+
const splitIdx = messages.length - recentCount;
|
|
133
|
+
const oldMessages = messages.slice(0, splitIdx);
|
|
134
|
+
const recentMessages = messages.slice(splitIdx);
|
|
135
|
+
|
|
136
|
+
if (oldMessages.length === 0) {
|
|
137
|
+
return { messages: [...messages], learnedCount: 0, savedTokens: 0, summary: '' };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const oldTokens = this.estimateMessagesTokens(oldMessages);
|
|
141
|
+
let learnedCount = 0;
|
|
142
|
+
let summary: string;
|
|
143
|
+
|
|
144
|
+
if (cfg.brain) {
|
|
145
|
+
// Extract and learn insights
|
|
146
|
+
const insights = this.extractInsights(oldMessages);
|
|
147
|
+
for (const insight of insights) {
|
|
148
|
+
try {
|
|
149
|
+
await cfg.brain.learn(insight.content, { insight_type: insight.type });
|
|
150
|
+
learnedCount++;
|
|
151
|
+
} catch { /* non-critical */ }
|
|
152
|
+
}
|
|
153
|
+
summary = `${oldMessages.length} messages compressed. Extracted ${learnedCount} insights (${insights.map(i => i.type).filter((v, i, a) => a.indexOf(v) === i).join(', ')}).`;
|
|
154
|
+
} else {
|
|
155
|
+
summary = this.summarize(oldMessages);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const compressionMessage: Message = {
|
|
159
|
+
id: `compressed-${Date.now()}`,
|
|
160
|
+
role: 'system',
|
|
161
|
+
content: `[Context compressed: ${oldMessages.length} messages → ${summary}${cfg.brain ? ' Details stored in Brain, use recall() to retrieve.' : ''}]`,
|
|
162
|
+
timestamp: Date.now(),
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
messages: [compressionMessage, ...recentMessages],
|
|
167
|
+
learnedCount,
|
|
168
|
+
savedTokens: oldTokens - this.estimateTokens(compressionMessage.content),
|
|
169
|
+
summary,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Restore context from brain for a given query.
|
|
175
|
+
*/
|
|
176
|
+
async restore(query: string, brain: any): Promise<string[]> {
|
|
177
|
+
if (!brain?.recall) return [];
|
|
178
|
+
try {
|
|
179
|
+
const results = await brain.recall(query);
|
|
180
|
+
if (Array.isArray(results)) {
|
|
181
|
+
return results.map((r: any) => typeof r === 'string' ? r : r.content ?? JSON.stringify(r));
|
|
182
|
+
}
|
|
183
|
+
if (typeof results === 'string') return [results];
|
|
184
|
+
return [];
|
|
185
|
+
} catch {
|
|
186
|
+
return [];
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
package/src/memory/index.ts
CHANGED
|
@@ -2,6 +2,10 @@ import type { Message, MemoryStore } from '../core/types';
|
|
|
2
2
|
|
|
3
3
|
export { BrainSeedLoader, KnowledgeEvolver } from './seed-loader';
|
|
4
4
|
export type { BrainSeedConfig, SeedPage, SeedResult, PromotionResult, PromotionCandidate } from './seed-loader';
|
|
5
|
+
export { ContextCompressor } from './context-compressor';
|
|
6
|
+
export type { CompressorConfig, CompressResult } from './context-compressor';
|
|
7
|
+
export { UserProfiler } from './user-profiler';
|
|
8
|
+
export type { UserProfile } from './user-profiler';
|
|
5
9
|
|
|
6
10
|
export class InMemoryStore implements MemoryStore {
|
|
7
11
|
private store: Map<string, unknown> = new Map();
|