network-ai 5.13.4 → 5.15.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/INTEGRATION_GUIDE.md +6 -3
- package/QUICKSTART.md +9 -4
- package/README.md +72 -15
- package/SKILL.md +1 -1
- package/bin/cli.ts +73 -0
- package/bin/mcp-server.ts +24 -1
- package/dist/adapters/claude-agent-sdk-adapter.d.ts +100 -0
- package/dist/adapters/claude-agent-sdk-adapter.d.ts.map +1 -0
- package/dist/adapters/claude-agent-sdk-adapter.js +204 -0
- package/dist/adapters/claude-agent-sdk-adapter.js.map +1 -0
- package/dist/adapters/gemini-adapter.d.ts +124 -0
- package/dist/adapters/gemini-adapter.d.ts.map +1 -0
- package/dist/adapters/gemini-adapter.js +239 -0
- package/dist/adapters/gemini-adapter.js.map +1 -0
- package/dist/adapters/index.d.ts +6 -0
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +10 -1
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/openai-responses-adapter.d.ts +119 -0
- package/dist/adapters/openai-responses-adapter.d.ts.map +1 -0
- package/dist/adapters/openai-responses-adapter.js +235 -0
- package/dist/adapters/openai-responses-adapter.js.map +1 -0
- package/dist/bin/cli.js +72 -0
- package/dist/bin/cli.js.map +1 -1
- package/dist/bin/mcp-server.js +22 -1
- package/dist/bin/mcp-server.js.map +1 -1
- package/dist/esm/adapters/claude-agent-sdk-adapter.js +204 -0
- package/dist/esm/adapters/claude-agent-sdk-adapter.js.map +1 -0
- package/dist/esm/adapters/gemini-adapter.js +239 -0
- package/dist/esm/adapters/gemini-adapter.js.map +1 -0
- package/dist/esm/adapters/index.js +10 -1
- package/dist/esm/adapters/index.js.map +1 -1
- package/dist/esm/adapters/openai-responses-adapter.js +235 -0
- package/dist/esm/adapters/openai-responses-adapter.js.map +1 -0
- package/dist/esm/index.js +20 -5
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/lib/a2a-server.js +293 -0
- package/dist/esm/lib/a2a-server.js.map +1 -0
- package/dist/esm/lib/claude-hooks.js +307 -0
- package/dist/esm/lib/claude-hooks.js.map +1 -0
- package/dist/esm/lib/context-composer.js +332 -0
- package/dist/esm/lib/context-composer.js.map +1 -0
- package/dist/esm/lib/mcp-elicitation.js +198 -0
- package/dist/esm/lib/mcp-elicitation.js.map +1 -0
- package/dist/esm/lib/mcp-tools-context.js +266 -0
- package/dist/esm/lib/mcp-tools-context.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20 -5
- package/dist/index.js.map +1 -1
- package/dist/lib/a2a-server.d.ts +120 -0
- package/dist/lib/a2a-server.d.ts.map +1 -0
- package/dist/lib/a2a-server.js +293 -0
- package/dist/lib/a2a-server.js.map +1 -0
- package/dist/lib/claude-hooks.d.ts +150 -0
- package/dist/lib/claude-hooks.d.ts.map +1 -0
- package/dist/lib/claude-hooks.js +307 -0
- package/dist/lib/claude-hooks.js.map +1 -0
- package/dist/lib/context-composer.d.ts +187 -0
- package/dist/lib/context-composer.d.ts.map +1 -0
- package/dist/lib/context-composer.js +332 -0
- package/dist/lib/context-composer.js.map +1 -0
- package/dist/lib/mcp-elicitation.d.ts +116 -0
- package/dist/lib/mcp-elicitation.d.ts.map +1 -0
- package/dist/lib/mcp-elicitation.js +198 -0
- package/dist/lib/mcp-elicitation.js.map +1 -0
- package/dist/lib/mcp-tools-context.d.ts +77 -0
- package/dist/lib/mcp-tools-context.d.ts.map +1 -0
- package/dist/lib/mcp-tools-context.js +266 -0
- package/dist/lib/mcp-tools-context.js.map +1 -0
- package/package.json +2 -2
- package/scripts/clawhub-publish.js +14 -1
- package/socket.json +1 -1
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Claude Code Hooks Bridge — AuthGuardian-gated tool calls for coding agents.
|
|
4
|
+
*
|
|
5
|
+
* Claude Code (and other hook-capable agent CLIs) can call an external
|
|
6
|
+
* command on every tool use (PreToolUse / PostToolUse hooks). This module
|
|
7
|
+
* turns Network-AI into that command: every tool call an agent makes is
|
|
8
|
+
* audited — and optionally permission-gated — through the same
|
|
9
|
+
* `AuthGuardian` weighted scoring used for swarm agents (justification 40%,
|
|
10
|
+
* trust 30%, risk 30%).
|
|
11
|
+
*
|
|
12
|
+
* Two modes:
|
|
13
|
+
* - `'observe'` (default) — every tool call is audit-logged, nothing is
|
|
14
|
+
* blocked. Zero-risk visibility into what the agent is doing.
|
|
15
|
+
* - `'enforce'` — tool calls are mapped to Network-AI resource types
|
|
16
|
+
* (Bash → SHELL_EXEC, Write/Edit → FILE_SYSTEM, WebFetch →
|
|
17
|
+
* EXTERNAL_SERVICE, …) and must pass `AuthGuardian.requestPermission()`.
|
|
18
|
+
* Denied calls return `'ask'` (escalate to the human) or `'deny'`.
|
|
19
|
+
*
|
|
20
|
+
* Wire-up (Claude Code `settings.json`):
|
|
21
|
+
* ```json
|
|
22
|
+
* {
|
|
23
|
+
* "hooks": {
|
|
24
|
+
* "PreToolUse": [{
|
|
25
|
+
* "matcher": "Bash|Write|Edit|WebFetch",
|
|
26
|
+
* "hooks": [{ "type": "command",
|
|
27
|
+
* "command": "npx -y -p network-ai network-ai hook pre-tool-use --mode enforce" }]
|
|
28
|
+
* }]
|
|
29
|
+
* }
|
|
30
|
+
* }
|
|
31
|
+
* ```
|
|
32
|
+
* See `examples/claude-code-hooks.json` for a complete config.
|
|
33
|
+
*
|
|
34
|
+
* @module ClaudeHooks
|
|
35
|
+
* @version 1.0.0
|
|
36
|
+
*/
|
|
37
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
38
|
+
if (k2 === undefined) k2 = k;
|
|
39
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
40
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
41
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
42
|
+
}
|
|
43
|
+
Object.defineProperty(o, k2, desc);
|
|
44
|
+
}) : (function(o, m, k, k2) {
|
|
45
|
+
if (k2 === undefined) k2 = k;
|
|
46
|
+
o[k2] = m[k];
|
|
47
|
+
}));
|
|
48
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
49
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
50
|
+
}) : function(o, v) {
|
|
51
|
+
o["default"] = v;
|
|
52
|
+
});
|
|
53
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
54
|
+
var ownKeys = function(o) {
|
|
55
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
56
|
+
var ar = [];
|
|
57
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
58
|
+
return ar;
|
|
59
|
+
};
|
|
60
|
+
return ownKeys(o);
|
|
61
|
+
};
|
|
62
|
+
return function (mod) {
|
|
63
|
+
if (mod && mod.__esModule) return mod;
|
|
64
|
+
var result = {};
|
|
65
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
66
|
+
__setModuleDefault(result, mod);
|
|
67
|
+
return result;
|
|
68
|
+
};
|
|
69
|
+
})();
|
|
70
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
71
|
+
exports.ClaudeHookBridge = exports.DEFAULT_TOOL_RESOURCE_MAP = void 0;
|
|
72
|
+
const fs = __importStar(require("fs"));
|
|
73
|
+
const path = __importStar(require("path"));
|
|
74
|
+
const auth_guardian_1 = require("./auth-guardian");
|
|
75
|
+
// ============================================================================
|
|
76
|
+
// DEFAULTS
|
|
77
|
+
// ============================================================================
|
|
78
|
+
/**
|
|
79
|
+
* Default mapping from Claude Code tool names to Network-AI resource types.
|
|
80
|
+
* MCP tools (`mcp__*`) and unknown tools map to EXTERNAL_SERVICE.
|
|
81
|
+
*/
|
|
82
|
+
exports.DEFAULT_TOOL_RESOURCE_MAP = {
|
|
83
|
+
Bash: 'SHELL_EXEC',
|
|
84
|
+
BashOutput: 'SHELL_EXEC',
|
|
85
|
+
KillShell: 'SHELL_EXEC',
|
|
86
|
+
Write: 'FILE_SYSTEM',
|
|
87
|
+
Edit: 'FILE_SYSTEM',
|
|
88
|
+
MultiEdit: 'FILE_SYSTEM',
|
|
89
|
+
NotebookEdit: 'FILE_SYSTEM',
|
|
90
|
+
Read: 'FILE_SYSTEM',
|
|
91
|
+
Glob: 'FILE_SYSTEM',
|
|
92
|
+
Grep: 'FILE_SYSTEM',
|
|
93
|
+
WebFetch: 'EXTERNAL_SERVICE',
|
|
94
|
+
WebSearch: 'EXTERNAL_SERVICE',
|
|
95
|
+
Task: 'EXTERNAL_SERVICE',
|
|
96
|
+
};
|
|
97
|
+
/** Justification templates per resource type — phrased to carry the
|
|
98
|
+
* resource-relevant context AuthGuardian's scorer checks for. */
|
|
99
|
+
const JUSTIFICATION_TEMPLATES = {
|
|
100
|
+
SHELL_EXEC: (tool, target) => `Execute shell command via ${tool} in order to complete the current coding task: ${target}`,
|
|
101
|
+
FILE_SYSTEM: (tool, target) => `Access workspace file via ${tool} in order to complete the current coding task: ${target}`,
|
|
102
|
+
GIT: (tool, target) => `Perform git repository operation via ${tool} in order to complete the current coding task: ${target}`,
|
|
103
|
+
EXTERNAL_SERVICE: (tool, target) => `Fetch external api endpoint via ${tool} in order to complete the current coding task: ${target}`,
|
|
104
|
+
};
|
|
105
|
+
// ============================================================================
|
|
106
|
+
// HELPERS
|
|
107
|
+
// ============================================================================
|
|
108
|
+
/** Extract the most meaningful target string from a tool input */
|
|
109
|
+
function extractTarget(toolName, toolInput) {
|
|
110
|
+
if (!toolInput)
|
|
111
|
+
return toolName;
|
|
112
|
+
const candidates = ['command', 'file_path', 'filePath', 'path', 'url', 'query', 'pattern', 'prompt'];
|
|
113
|
+
for (const key of candidates) {
|
|
114
|
+
const v = toolInput[key];
|
|
115
|
+
if (typeof v === 'string' && v.length > 0)
|
|
116
|
+
return v.slice(0, 500);
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
return JSON.stringify(toolInput).slice(0, 300);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return toolName;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** Test a tool name / target against a pattern list */
|
|
126
|
+
function matchesAny(patterns, toolName, target) {
|
|
127
|
+
if (!patterns || patterns.length === 0)
|
|
128
|
+
return false;
|
|
129
|
+
for (const p of patterns) {
|
|
130
|
+
const re = typeof p === 'string' ? new RegExp(p, 'i') : p;
|
|
131
|
+
if (re.test(toolName) || re.test(target))
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
// ============================================================================
|
|
137
|
+
// CLAUDE HOOK BRIDGE
|
|
138
|
+
// ============================================================================
|
|
139
|
+
/**
|
|
140
|
+
* Bridges coding-agent hook events (Claude Code PreToolUse / PostToolUse)
|
|
141
|
+
* into Network-AI's AuthGuardian permission system and audit trail.
|
|
142
|
+
*/
|
|
143
|
+
class ClaudeHookBridge {
|
|
144
|
+
guardian;
|
|
145
|
+
agentId;
|
|
146
|
+
mode;
|
|
147
|
+
denyPatterns;
|
|
148
|
+
allowPatterns;
|
|
149
|
+
toolResourceMap;
|
|
150
|
+
blockedDecision;
|
|
151
|
+
auditLogPath;
|
|
152
|
+
onAudit;
|
|
153
|
+
constructor(options = {}) {
|
|
154
|
+
this.agentId = options.agentId ?? 'claude-code';
|
|
155
|
+
this.mode = options.mode ?? 'observe';
|
|
156
|
+
this.denyPatterns = options.denyPatterns ?? [];
|
|
157
|
+
this.allowPatterns = options.allowPatterns ?? [];
|
|
158
|
+
this.toolResourceMap = { ...exports.DEFAULT_TOOL_RESOURCE_MAP, ...(options.toolResourceMap ?? {}) };
|
|
159
|
+
this.blockedDecision = options.blockedDecision ?? 'ask';
|
|
160
|
+
this.auditLogPath = options.auditLogPath ? path.resolve(options.auditLogPath) : null;
|
|
161
|
+
this.onAudit = options.onAudit ?? null;
|
|
162
|
+
if (options.guardian) {
|
|
163
|
+
this.guardian = options.guardian;
|
|
164
|
+
}
|
|
165
|
+
else if (this.mode === 'enforce') {
|
|
166
|
+
// Auto-create a guardian with a trust identity for this agent.
|
|
167
|
+
this.guardian = new auth_guardian_1.AuthGuardian({
|
|
168
|
+
trustLevels: [{
|
|
169
|
+
agentId: this.agentId,
|
|
170
|
+
trustLevel: options.trustLevel ?? 0.7,
|
|
171
|
+
allowedNamespaces: ['*'],
|
|
172
|
+
allowedResources: ['*'],
|
|
173
|
+
}],
|
|
174
|
+
...(options.guardianAuditLogPath ? { auditLogPath: options.guardianAuditLogPath } : {}),
|
|
175
|
+
...(options.trustConfigPath ? { trustConfigPath: options.trustConfigPath } : {}),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
this.guardian = null;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Parse a raw hook stdin payload. Tolerates a leading UTF-8 BOM (some
|
|
184
|
+
* shells prepend one when piping). Throws on malformed JSON or a payload
|
|
185
|
+
* that is not an object.
|
|
186
|
+
*/
|
|
187
|
+
static parseInput(raw) {
|
|
188
|
+
let parsed;
|
|
189
|
+
try {
|
|
190
|
+
parsed = JSON.parse(raw.replace(/^\uFEFF/, '').trim());
|
|
191
|
+
}
|
|
192
|
+
catch (err) {
|
|
193
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
194
|
+
throw new Error(`ClaudeHookBridge: invalid hook input JSON — ${detail}`);
|
|
195
|
+
}
|
|
196
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
197
|
+
throw new Error('ClaudeHookBridge: hook input must be a JSON object');
|
|
198
|
+
}
|
|
199
|
+
const obj = parsed;
|
|
200
|
+
if (typeof obj['hook_event_name'] !== 'string') {
|
|
201
|
+
throw new Error('ClaudeHookBridge: hook input missing hook_event_name');
|
|
202
|
+
}
|
|
203
|
+
return obj;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Handle a PreToolUse event: decide allow / deny / ask.
|
|
207
|
+
*
|
|
208
|
+
* Decision order: denyPatterns → allowPatterns → observe-mode allow →
|
|
209
|
+
* AuthGuardian permission request (enforce mode).
|
|
210
|
+
*/
|
|
211
|
+
async handlePreToolUse(input) {
|
|
212
|
+
const toolName = input.tool_name ?? 'unknown';
|
|
213
|
+
const target = extractTarget(toolName, input.tool_input);
|
|
214
|
+
// 1. Hard deny list
|
|
215
|
+
if (matchesAny(this.denyPatterns, toolName, target)) {
|
|
216
|
+
return this.decide(input, toolName, target, 'deny', `Blocked by Network-AI deny pattern (tool: ${toolName})`);
|
|
217
|
+
}
|
|
218
|
+
// 2. Explicit allow list
|
|
219
|
+
if (matchesAny(this.allowPatterns, toolName, target)) {
|
|
220
|
+
return this.decide(input, toolName, target, 'allow', `Allowed by Network-AI allow pattern (tool: ${toolName})`);
|
|
221
|
+
}
|
|
222
|
+
// 3. Observe mode: audit, never block
|
|
223
|
+
if (this.mode === 'observe' || !this.guardian) {
|
|
224
|
+
return this.decide(input, toolName, target, 'allow', 'Network-AI observe mode — call audited, not gated');
|
|
225
|
+
}
|
|
226
|
+
// 4. Enforce mode: AuthGuardian weighted permission scoring
|
|
227
|
+
const resourceType = this.toolResourceMap[toolName]
|
|
228
|
+
?? (toolName.startsWith('mcp__') ? 'EXTERNAL_SERVICE' : 'EXTERNAL_SERVICE');
|
|
229
|
+
const template = JUSTIFICATION_TEMPLATES[resourceType] ?? JUSTIFICATION_TEMPLATES['EXTERNAL_SERVICE'];
|
|
230
|
+
const justification = template(toolName, target);
|
|
231
|
+
const grant = await this.guardian.requestPermission(this.agentId, resourceType, justification, toolName);
|
|
232
|
+
if (grant.granted) {
|
|
233
|
+
return this.decide(input, toolName, target, 'allow', `AuthGuardian granted ${resourceType} (restrictions: ${grant.restrictions.join(', ') || 'none'})`);
|
|
234
|
+
}
|
|
235
|
+
return this.decide(input, toolName, target, this.blockedDecision, `AuthGuardian denied ${resourceType}: ${grant.reason ?? 'permission not granted'}`);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Handle a PostToolUse event: audit the completed call. Never blocks.
|
|
239
|
+
* Returns an empty object (the hook-protocol no-op).
|
|
240
|
+
*/
|
|
241
|
+
async handlePostToolUse(input) {
|
|
242
|
+
const toolName = input.tool_name ?? 'unknown';
|
|
243
|
+
const target = extractTarget(toolName, input.tool_input);
|
|
244
|
+
this.audit({
|
|
245
|
+
timestamp: new Date().toISOString(),
|
|
246
|
+
event: 'PostToolUse',
|
|
247
|
+
toolName,
|
|
248
|
+
target,
|
|
249
|
+
sessionId: input.session_id,
|
|
250
|
+
agentId: this.agentId,
|
|
251
|
+
mode: this.mode,
|
|
252
|
+
});
|
|
253
|
+
return {};
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Dispatch a hook input by its `hook_event_name`.
|
|
257
|
+
*/
|
|
258
|
+
async handle(input) {
|
|
259
|
+
if (input.hook_event_name === 'PreToolUse')
|
|
260
|
+
return this.handlePreToolUse(input);
|
|
261
|
+
if (input.hook_event_name === 'PostToolUse')
|
|
262
|
+
return this.handlePostToolUse(input);
|
|
263
|
+
throw new Error(`ClaudeHookBridge: unsupported hook event "${input.hook_event_name}"`);
|
|
264
|
+
}
|
|
265
|
+
// --------------------------------------------------------------------------
|
|
266
|
+
// Internals
|
|
267
|
+
// --------------------------------------------------------------------------
|
|
268
|
+
decide(input, toolName, target, decision, reason) {
|
|
269
|
+
this.audit({
|
|
270
|
+
timestamp: new Date().toISOString(),
|
|
271
|
+
event: 'PreToolUse',
|
|
272
|
+
toolName,
|
|
273
|
+
target,
|
|
274
|
+
decision,
|
|
275
|
+
reason,
|
|
276
|
+
sessionId: input.session_id,
|
|
277
|
+
agentId: this.agentId,
|
|
278
|
+
mode: this.mode,
|
|
279
|
+
});
|
|
280
|
+
return {
|
|
281
|
+
hookSpecificOutput: {
|
|
282
|
+
hookEventName: 'PreToolUse',
|
|
283
|
+
permissionDecision: decision,
|
|
284
|
+
permissionDecisionReason: reason,
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
audit(entry) {
|
|
289
|
+
try {
|
|
290
|
+
this.onAudit?.(entry);
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
/* observer errors must never break the hook */
|
|
294
|
+
}
|
|
295
|
+
if (this.auditLogPath) {
|
|
296
|
+
try {
|
|
297
|
+
fs.mkdirSync(path.dirname(this.auditLogPath), { recursive: true });
|
|
298
|
+
fs.appendFileSync(this.auditLogPath, JSON.stringify(entry) + '\n', 'utf8');
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
/* audit-write failures must never break the hook */
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
exports.ClaudeHookBridge = ClaudeHookBridge;
|
|
307
|
+
//# sourceMappingURL=claude-hooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claude-hooks.js","sourceRoot":"","sources":["../../lib/claude-hooks.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,uCAAyB;AACzB,2CAA6B;AAC7B,mDAA+C;AAgF/C,+EAA+E;AAC/E,WAAW;AACX,+EAA+E;AAE/E;;;GAGG;AACU,QAAA,yBAAyB,GAA2B;IAC/D,IAAI,EAAE,YAAY;IAClB,UAAU,EAAE,YAAY;IACxB,SAAS,EAAE,YAAY;IACvB,KAAK,EAAE,aAAa;IACpB,IAAI,EAAE,aAAa;IACnB,SAAS,EAAE,aAAa;IACxB,YAAY,EAAE,aAAa;IAC3B,IAAI,EAAE,aAAa;IACnB,IAAI,EAAE,aAAa;IACnB,IAAI,EAAE,aAAa;IACnB,QAAQ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,aAAa,EAAE,YAAY;gBAC3B,kBAAkB,EAAE,QAAQ;gBAC5B,wBAAwB,EAAE,MAAM;aACjC;SACF,CAAC;IACJ,CAAC;IAEO,KAAK,CAAC,KAAqB;QACjC,IAAI,CAAC;YACH,IAAI,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC;QACxB,CAAC;QAAC,MAAM,CAAC;YACP,+CAA+C;QACjD,CAAC;QACD,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,IAAI,CAAC;gBACH,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;gBACnE,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,CAAC;YAC7E,CAAC;YAAC,MAAM,CAAC;gBACP,oDAAoD;YACtD,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAvLD,4CAuLC"}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Context Composer — token-budgeted, relevance-ranked context assembly.
|
|
3
|
+
*
|
|
4
|
+
* Agents have large context windows but a much smaller *effective reasoning*
|
|
5
|
+
* window: irrelevant, stale, or noisy context degrades output quality long
|
|
6
|
+
* before the hard token limit ("context rot"). This module assembles the
|
|
7
|
+
* context block for an LLM call from candidate sources (blackboard entries,
|
|
8
|
+
* project context, memory recall) under a **hard token budget**, ranked by:
|
|
9
|
+
*
|
|
10
|
+
* score = w.relevance × relevance + w.recency × recency + w.affinity × affinity
|
|
11
|
+
*
|
|
12
|
+
* - **relevance** — semantic similarity to the task via a pluggable
|
|
13
|
+
* {@link SemanticRanker} (BYOE — e.g. wrap `SemanticMemory`), with a
|
|
14
|
+
* deterministic lexical-overlap fallback when no ranker is supplied;
|
|
15
|
+
* - **recency** — exponential half-life decay on the entry timestamp
|
|
16
|
+
* (the same math `EpisodicMemory` uses);
|
|
17
|
+
* - **affinity** — scope-tag match on the key (same substring semantics as
|
|
18
|
+
* `ContextThrottler`).
|
|
19
|
+
*
|
|
20
|
+
* Pinned sources (task-critical instructions, Layer-3 project context) are
|
|
21
|
+
* always included first. Assembly is position-aware by default: the
|
|
22
|
+
* strongest items are placed at the start *and end* of the block, weakest in
|
|
23
|
+
* the middle — mitigating "lost in the middle" attention decay.
|
|
24
|
+
*
|
|
25
|
+
* The result carries full observability metadata: what was included,
|
|
26
|
+
* what was excluded and why, token usage, and budget utilization.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* const composer = new ContextComposer();
|
|
31
|
+
* const sources = ContextComposer.fromSnapshot(blackboard.getScopedSnapshot('analyst'));
|
|
32
|
+
* const pack = await composer.compose(sources, {
|
|
33
|
+
* task: 'Summarize Q3 revenue anomalies',
|
|
34
|
+
* budgetTokens: 2000,
|
|
35
|
+
* scopeTags: ['analytics', 'task'],
|
|
36
|
+
* });
|
|
37
|
+
* llmPrompt = `${instructions}\n\n${pack.text}`;
|
|
38
|
+
* ```
|
|
39
|
+
*
|
|
40
|
+
* @module ContextComposer
|
|
41
|
+
* @version 1.0.0
|
|
42
|
+
*/
|
|
43
|
+
/**
|
|
44
|
+
* Estimate the token count of a text without a tokenizer dependency.
|
|
45
|
+
*
|
|
46
|
+
* Uses the ~4-characters-per-token heuristic blended with a word count
|
|
47
|
+
* (English prose averages ~0.75 tokens/word; code and JSON run denser).
|
|
48
|
+
* Accurate to roughly ±15% across prose/code/JSON — sufficient for budget
|
|
49
|
+
* enforcement, not for billing.
|
|
50
|
+
*/
|
|
51
|
+
export declare function estimateTokens(text: string): number;
|
|
52
|
+
/** One candidate context item offered to the composer. */
|
|
53
|
+
export interface ContextSource {
|
|
54
|
+
/** Unique identifier (blackboard key, memory id, …) */
|
|
55
|
+
key: string;
|
|
56
|
+
/** Rendered text content of this item */
|
|
57
|
+
text: string;
|
|
58
|
+
/** Agent that produced the item, when known */
|
|
59
|
+
sourceAgent?: string;
|
|
60
|
+
/** ISO timestamp of the item, when known (drives recency decay) */
|
|
61
|
+
timestamp?: string;
|
|
62
|
+
/** TTL in seconds (`null`/`undefined` = no expiry) — expired items are dropped */
|
|
63
|
+
ttl?: number | null;
|
|
64
|
+
/** Pinned items bypass ranking and are always included first (budget permitting) */
|
|
65
|
+
pinned?: boolean;
|
|
66
|
+
}
|
|
67
|
+
/** A source annotated with its ranking scores. */
|
|
68
|
+
export interface RankedContextItem extends ContextSource {
|
|
69
|
+
/** Semantic (or lexical-fallback) relevance to the task, 0–1 */
|
|
70
|
+
relevance: number;
|
|
71
|
+
/** Recency after half-life decay, 0–1 */
|
|
72
|
+
recency: number;
|
|
73
|
+
/** Scope-tag affinity, 0–1 */
|
|
74
|
+
affinity: number;
|
|
75
|
+
/** Weighted total score, 0–1 */
|
|
76
|
+
score: number;
|
|
77
|
+
/** Estimated token cost of this item's rendered block */
|
|
78
|
+
tokens: number;
|
|
79
|
+
}
|
|
80
|
+
/** Why an item was left out of the composed pack. */
|
|
81
|
+
export type ExclusionReason = 'budget' | 'score' | 'stale' | 'empty';
|
|
82
|
+
/** An excluded item and the reason it was dropped. */
|
|
83
|
+
export interface ExcludedItem {
|
|
84
|
+
key: string;
|
|
85
|
+
reason: ExclusionReason;
|
|
86
|
+
score?: number;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Pluggable semantic ranker: given the task text and candidate items,
|
|
90
|
+
* return a map of key → similarity score (0–1). Missing keys fall back to
|
|
91
|
+
* lexical scoring. BYOE — bring your own embeddings.
|
|
92
|
+
*/
|
|
93
|
+
export type SemanticRanker = (query: string, items: ReadonlyArray<{
|
|
94
|
+
key: string;
|
|
95
|
+
text: string;
|
|
96
|
+
}>) => Promise<Map<string, number>>;
|
|
97
|
+
/** Scoring weights (normalized internally; defaults: 0.5 / 0.3 / 0.2). */
|
|
98
|
+
export interface ScoreWeights {
|
|
99
|
+
relevance?: number;
|
|
100
|
+
recency?: number;
|
|
101
|
+
affinity?: number;
|
|
102
|
+
}
|
|
103
|
+
/** Options for a single {@link ContextComposer.compose} call. */
|
|
104
|
+
export interface ComposeOptions {
|
|
105
|
+
/** The task/query driving relevance ranking (required) */
|
|
106
|
+
task: string;
|
|
107
|
+
/** Hard token budget for the entire composed block (required, > 0) */
|
|
108
|
+
budgetTokens: number;
|
|
109
|
+
/** Scope tags for affinity scoring (ContextThrottler semantics: substring match on key) */
|
|
110
|
+
scopeTags?: string[];
|
|
111
|
+
/** Score weights — merged over the composer defaults */
|
|
112
|
+
weights?: ScoreWeights;
|
|
113
|
+
/** Recency half-life in ms (default: composer default, 30 min) */
|
|
114
|
+
halfLifeMs?: number;
|
|
115
|
+
/** Items scoring below this are excluded outright (default 0.05) */
|
|
116
|
+
minScore?: number;
|
|
117
|
+
/** Hard cap on the number of included items (0 = unlimited) */
|
|
118
|
+
maxItems?: number;
|
|
119
|
+
/** Override the composer-level semantic ranker for this call */
|
|
120
|
+
ranker?: SemanticRanker;
|
|
121
|
+
/**
|
|
122
|
+
* Position-aware assembly (default true): strongest items at the start
|
|
123
|
+
* AND end of the block, weakest in the middle.
|
|
124
|
+
*/
|
|
125
|
+
positionAware?: boolean;
|
|
126
|
+
}
|
|
127
|
+
/** The assembled, budget-enforced context pack. */
|
|
128
|
+
export interface ComposedContext {
|
|
129
|
+
/** Final assembled context block, ready to inject into a prompt */
|
|
130
|
+
text: string;
|
|
131
|
+
/** Items included, in ranked order (not layout order) */
|
|
132
|
+
included: RankedContextItem[];
|
|
133
|
+
/** Items excluded, with reasons */
|
|
134
|
+
excluded: ExcludedItem[];
|
|
135
|
+
/** The budget that was enforced */
|
|
136
|
+
budgetTokens: number;
|
|
137
|
+
/** Estimated tokens used by `text` */
|
|
138
|
+
usedTokens: number;
|
|
139
|
+
/** usedTokens / budgetTokens (0–1) */
|
|
140
|
+
utilization: number;
|
|
141
|
+
}
|
|
142
|
+
/** Constructor options for {@link ContextComposer}. */
|
|
143
|
+
export interface ContextComposerOptions {
|
|
144
|
+
/** Default half-life for recency decay in ms (default: 1_800_000 = 30 min) */
|
|
145
|
+
halfLifeMs?: number;
|
|
146
|
+
/** Default scoring weights */
|
|
147
|
+
weights?: ScoreWeights;
|
|
148
|
+
/** Default semantic ranker (BYOE) */
|
|
149
|
+
ranker?: SemanticRanker;
|
|
150
|
+
}
|
|
151
|
+
/** Minimal `SemanticMemory`-compatible search surface. */
|
|
152
|
+
export interface SemanticSearchLike {
|
|
153
|
+
search(query: string, topK?: number, threshold?: number): Promise<Array<{
|
|
154
|
+
key: string;
|
|
155
|
+
score: number;
|
|
156
|
+
}>>;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Adapt a `SemanticMemory` instance (or anything with a compatible
|
|
160
|
+
* `search()`) into a {@link SemanticRanker}. Items the memory does not know
|
|
161
|
+
* about simply fall back to lexical scoring.
|
|
162
|
+
*/
|
|
163
|
+
export declare function createSemanticMemoryRanker(memory: SemanticSearchLike): SemanticRanker;
|
|
164
|
+
/**
|
|
165
|
+
* Assembles token-budgeted, relevance-ranked context packs from candidate
|
|
166
|
+
* sources. See the module docs for the ranking model.
|
|
167
|
+
*/
|
|
168
|
+
export declare class ContextComposer {
|
|
169
|
+
private readonly halfLifeMs;
|
|
170
|
+
private readonly weights;
|
|
171
|
+
private readonly ranker;
|
|
172
|
+
constructor(options?: ContextComposerOptions);
|
|
173
|
+
/**
|
|
174
|
+
* Convert a blackboard snapshot (`getSnapshot()` / `getScopedSnapshot()`
|
|
175
|
+
* shape) into {@link ContextSource} candidates. Values are rendered as
|
|
176
|
+
* strings (JSON for objects) and truncated to `maxValueChars`.
|
|
177
|
+
*/
|
|
178
|
+
static fromSnapshot(snapshot: Record<string, unknown>, options?: {
|
|
179
|
+
maxValueChars?: number;
|
|
180
|
+
}): ContextSource[];
|
|
181
|
+
/**
|
|
182
|
+
* Rank the candidate sources against the task and assemble the largest
|
|
183
|
+
* high-signal context block that fits the token budget.
|
|
184
|
+
*/
|
|
185
|
+
compose(sources: ContextSource[], options: ComposeOptions): Promise<ComposedContext>;
|
|
186
|
+
}
|
|
187
|
+
//# sourceMappingURL=context-composer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-composer.d.ts","sourceRoot":"","sources":["../../lib/context-composer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAMH;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMnD;AAMD,0DAA0D;AAC1D,MAAM,WAAW,aAAa;IAC5B,uDAAuD;IACvD,GAAG,EAAE,MAAM,CAAC;IACZ,yCAAyC;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,+CAA+C;IAC/C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mEAAmE;IACnE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kFAAkF;IAClF,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,oFAAoF;IACpF,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,kDAAkD;AAClD,MAAM,WAAW,iBAAkB,SAAQ,aAAa;IACtD,gEAAgE;IAChE,SAAS,EAAE,MAAM,CAAC;IAClB,yCAAyC;IACzC,OAAO,EAAE,MAAM,CAAC;IAChB,8BAA8B;IAC9B,QAAQ,EAAE,MAAM,CAAC;IACjB,gCAAgC;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,yDAAyD;IACzD,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,qDAAqD;AACrD,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,CAAC;AAErE,sDAAsD;AACtD,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,eAAe,CAAC;IACx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