@kb-labs/agent-kernel 0.6.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,41 @@
1
+ import { KernelState, TurnInterpretation, DecisionRecord, PendingActionRecord, ToolResultArtifact, RunHandoff, PromptContextSelection, RepositoryModel, ToolCapability } from '@kb-labs/agent-contracts';
2
+ export { EvidenceRecord, KernelState, ToolResultArtifact } from '@kb-labs/agent-contracts';
3
+ import { MemoryCapability, PromptProjector } from '@kb-labs/agent-sdk';
4
+ import { LLMMessage } from '@kb-labs/sdk';
5
+
6
+ declare function createKernelState(input: {
7
+ sessionId: string;
8
+ workingDir: string;
9
+ mode: KernelState['mode'];
10
+ task: string;
11
+ }): KernelState;
12
+ declare function ingestUserTurn(state: KernelState, input: string | {
13
+ content: string;
14
+ interpretation?: TurnInterpretation | null;
15
+ }): KernelState;
16
+ declare function recordConstraint(state: KernelState, content: string): KernelState;
17
+ declare function recordCorrection(state: KernelState, content: string, invalidates?: string[]): KernelState;
18
+ declare function recordAssumption(state: KernelState, content: string): KernelState;
19
+ declare function recordDecision(state: KernelState, content: string, source?: DecisionRecord['source']): KernelState;
20
+ declare function recordOpenQuestion(state: KernelState, content: string): KernelState;
21
+ declare function recordPendingAction(state: KernelState, content: string, status?: PendingActionRecord['status']): KernelState;
22
+ declare function completePendingActions(state: KernelState, predicate: (action: PendingActionRecord) => boolean): KernelState;
23
+ declare function recordToolArtifact(state: KernelState, artifact: ToolResultArtifact): KernelState;
24
+ declare function recordRunHandoff(state: KernelState, handoff: RunHandoff): KernelState;
25
+ declare function recordRoutingHints(state: KernelState, interpretation: TurnInterpretation): KernelState;
26
+ declare function recordChildResult(state: KernelState, result: RunHandoff): KernelState;
27
+ declare function compactKernelState(state: KernelState, stats?: {
28
+ turnCount?: number;
29
+ toolCallCount?: number;
30
+ narrativeSummary?: string;
31
+ }): KernelState;
32
+ declare function applyMemoryCapabilities(state: KernelState, capabilities: ReadonlyArray<MemoryCapability>): Promise<KernelState>;
33
+ declare function projectKernelPrompt(state: KernelState, messages: LLMMessage[], projectors: ReadonlyArray<PromptProjector>, selection?: PromptContextSelection | null, context?: {
34
+ repositoryModel?: RepositoryModel | null;
35
+ toolCapabilities?: ToolCapability[];
36
+ }): Promise<string>;
37
+ declare function summarizeAssistantTurn(state: KernelState, answer: string): KernelState;
38
+ declare function isCorrectionPendingAction(action: PendingActionRecord): boolean;
39
+ declare function createDefaultPromptContextSelection(state: KernelState): PromptContextSelection;
40
+
41
+ export { applyMemoryCapabilities, compactKernelState, completePendingActions, createDefaultPromptContextSelection, createKernelState, ingestUserTurn, isCorrectionPendingAction, projectKernelPrompt, recordAssumption, recordChildResult, recordConstraint, recordCorrection, recordDecision, recordOpenQuestion, recordPendingAction, recordRoutingHints, recordRunHandoff, recordToolArtifact, summarizeAssistantTurn };
package/dist/index.js ADDED
@@ -0,0 +1,458 @@
1
+ // src/index.ts
2
+ function now() {
3
+ return (/* @__PURE__ */ new Date()).toISOString();
4
+ }
5
+ function makeId(prefix) {
6
+ return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
7
+ }
8
+ var CORRECTION_PENDING_PREFIX = "Persist user correction via memory_correction:";
9
+ function createMemory() {
10
+ return {
11
+ corrections: [],
12
+ assumptions: [],
13
+ decisions: [],
14
+ evidence: [],
15
+ openQuestions: [],
16
+ pendingActions: []
17
+ };
18
+ }
19
+ function createKernelState(input) {
20
+ const timestamp = now();
21
+ return {
22
+ version: 1,
23
+ sessionId: input.sessionId,
24
+ workingDir: input.workingDir,
25
+ mode: input.mode,
26
+ currentTask: input.task,
27
+ objective: input.task,
28
+ constraints: [],
29
+ memory: createMemory(),
30
+ childResults: [],
31
+ updatedAt: timestamp
32
+ };
33
+ }
34
+ function touch(state) {
35
+ return { ...state, updatedAt: now() };
36
+ }
37
+ function upsertSummary(state, summary) {
38
+ return {
39
+ ...state,
40
+ memory: {
41
+ ...state.memory,
42
+ latestSummary: summary
43
+ }
44
+ };
45
+ }
46
+ function ingestUserTurn(state, input) {
47
+ const content = typeof input === "string" ? input : input.content;
48
+ const interpretation = typeof input === "string" ? null : input.interpretation ?? null;
49
+ let nextState = {
50
+ ...state,
51
+ currentTask: content,
52
+ objective: state.objective || content
53
+ };
54
+ if (interpretation) {
55
+ nextState = recordRoutingHints(nextState, interpretation);
56
+ }
57
+ if (interpretation?.shouldPersist && interpretation.content) {
58
+ if (interpretation.persistStrategy === "record_directly") {
59
+ nextState = persistInterpretedMemory(nextState, interpretation);
60
+ } else {
61
+ nextState = ensurePendingCorrectionAction(nextState, interpretation.content);
62
+ }
63
+ }
64
+ return touch(nextState);
65
+ }
66
+ function recordConstraint(state, content) {
67
+ if (!content.trim()) {
68
+ return state;
69
+ }
70
+ if (state.constraints.includes(content.trim())) {
71
+ return state;
72
+ }
73
+ return touch({
74
+ ...state,
75
+ constraints: [...state.constraints, content.trim()]
76
+ });
77
+ }
78
+ function recordCorrection(state, content, invalidates = []) {
79
+ const record = {
80
+ id: makeId("corr"),
81
+ content,
82
+ timestamp: now(),
83
+ invalidates,
84
+ source: "user"
85
+ };
86
+ const assumptions = state.memory.assumptions.map(
87
+ (item) => invalidates.includes(item.id) ? {
88
+ ...item,
89
+ status: "invalidated",
90
+ invalidatedAt: record.timestamp,
91
+ invalidatedBy: record.id
92
+ } : item
93
+ );
94
+ return touch({
95
+ ...state,
96
+ memory: {
97
+ ...state.memory,
98
+ corrections: [...state.memory.corrections, record],
99
+ assumptions
100
+ }
101
+ });
102
+ }
103
+ function recordAssumption(state, content) {
104
+ const assumption = {
105
+ id: makeId("asm"),
106
+ content,
107
+ status: "active",
108
+ createdAt: now()
109
+ };
110
+ return touch({
111
+ ...state,
112
+ memory: {
113
+ ...state.memory,
114
+ assumptions: [...state.memory.assumptions, assumption]
115
+ }
116
+ });
117
+ }
118
+ function recordDecision(state, content, source = "agent") {
119
+ const decision = {
120
+ id: makeId("dec"),
121
+ content,
122
+ source,
123
+ createdAt: now()
124
+ };
125
+ return touch({
126
+ ...state,
127
+ memory: {
128
+ ...state.memory,
129
+ decisions: [...state.memory.decisions, decision].slice(-10)
130
+ }
131
+ });
132
+ }
133
+ function recordOpenQuestion(state, content) {
134
+ const question = {
135
+ id: makeId("q"),
136
+ content,
137
+ createdAt: now(),
138
+ status: "open"
139
+ };
140
+ return touch({
141
+ ...state,
142
+ memory: {
143
+ ...state.memory,
144
+ openQuestions: [...state.memory.openQuestions, question]
145
+ }
146
+ });
147
+ }
148
+ function recordPendingAction(state, content, status = "pending") {
149
+ const action = {
150
+ id: makeId("todo"),
151
+ content,
152
+ createdAt: now(),
153
+ status
154
+ };
155
+ return touch({
156
+ ...state,
157
+ memory: {
158
+ ...state.memory,
159
+ pendingActions: [...state.memory.pendingActions, action]
160
+ }
161
+ });
162
+ }
163
+ function completePendingActions(state, predicate) {
164
+ let changed = false;
165
+ const pendingActions = state.memory.pendingActions.map((action) => {
166
+ if (action.status !== "done" && predicate(action)) {
167
+ changed = true;
168
+ return { ...action, status: "done" };
169
+ }
170
+ return action;
171
+ });
172
+ return changed ? touch({
173
+ ...state,
174
+ memory: {
175
+ ...state.memory,
176
+ pendingActions
177
+ }
178
+ }) : state;
179
+ }
180
+ function recordToolArtifact(state, artifact) {
181
+ const evidence = artifact.evidence.filter((item) => item.summary.trim() || item.toolInputSummary?.trim());
182
+ if (evidence.length === 0) {
183
+ return state;
184
+ }
185
+ const deduped = [...state.memory.evidence, ...evidence].filter((item, index, all) => {
186
+ const key = `${item.toolName ?? item.source}:${item.toolInputSummary ?? ""}:${item.summary}`;
187
+ return all.findIndex(
188
+ (candidate) => `${candidate.toolName ?? candidate.source}:${candidate.toolInputSummary ?? ""}:${candidate.summary}` === key
189
+ ) === index;
190
+ });
191
+ const pinned = deduped.filter((item) => item.pinned);
192
+ const recent = deduped.filter((item) => !item.pinned).slice(-12);
193
+ const merged = [...pinned, ...recent].slice(-12);
194
+ return touch({
195
+ ...state,
196
+ memory: {
197
+ ...state.memory,
198
+ evidence: merged
199
+ }
200
+ });
201
+ }
202
+ function recordRunHandoff(state, handoff) {
203
+ return touch({
204
+ ...state,
205
+ handoff,
206
+ childResults: state.childResults
207
+ });
208
+ }
209
+ function recordRoutingHints(state, interpretation) {
210
+ const hasHints = Boolean(
211
+ interpretation.suggestedMode || interpretation.suggestedPromptProfile || interpretation.suggestedSkills?.length || interpretation.suggestedToolCapabilities?.length
212
+ );
213
+ if (!hasHints) {
214
+ return state;
215
+ }
216
+ const routingHints = {
217
+ suggestedMode: interpretation.suggestedMode,
218
+ suggestedSkills: interpretation.suggestedSkills ?? [],
219
+ suggestedPromptProfile: interpretation.suggestedPromptProfile,
220
+ suggestedToolCapabilities: interpretation.suggestedToolCapabilities ?? [],
221
+ source: "turn_interpretation",
222
+ confidence: interpretation.confidence,
223
+ updatedAt: now()
224
+ };
225
+ return touch({
226
+ ...state,
227
+ routingHints
228
+ });
229
+ }
230
+ function recordChildResult(state, result) {
231
+ return touch({
232
+ ...state,
233
+ childResults: [...state.childResults, result]
234
+ });
235
+ }
236
+ function compactKernelState(state, stats) {
237
+ const pinnedEvidence = state.memory.evidence.filter((item) => item.pinned);
238
+ const recentEvidence = state.memory.evidence.filter((item) => !item.pinned).filter((item) => !isNoiseEvidence(item, state)).slice(-8);
239
+ const compactedEvidence = [...pinnedEvidence, ...recentEvidence].filter((item, index, all) => all.findIndex((candidate) => candidate.id === item.id) === index).slice(-12);
240
+ const activeActions = state.memory.pendingActions.filter((item) => item.status !== "done");
241
+ const recentDoneActions = state.memory.pendingActions.filter((item) => item.status === "done").slice(-2);
242
+ const pendingActions = [...activeActions, ...recentDoneActions];
243
+ const childResults = state.childResults.slice(-5);
244
+ const completedActionCount = state.memory.pendingActions.filter((item) => item.status === "done").length;
245
+ const prunedEvidenceCount = Math.max(0, state.memory.evidence.length - compactedEvidence.length);
246
+ const rollup = shouldCreateRollup(state, stats) ? {
247
+ generatedAt: now(),
248
+ turnCount: stats?.turnCount,
249
+ toolCallCount: stats?.toolCallCount,
250
+ completedActionCount,
251
+ prunedEvidenceCount,
252
+ summary: createRollupSummary(state, {
253
+ ...stats,
254
+ completedActionCount,
255
+ prunedEvidenceCount
256
+ })
257
+ } : state.rollup;
258
+ return touch({
259
+ ...state,
260
+ rollup,
261
+ childResults,
262
+ memory: {
263
+ ...state.memory,
264
+ evidence: compactedEvidence,
265
+ pendingActions
266
+ }
267
+ });
268
+ }
269
+ async function applyMemoryCapabilities(state, capabilities) {
270
+ let nextState = state;
271
+ for (const capability of capabilities) {
272
+ nextState = await capability.apply(nextState);
273
+ }
274
+ return touch(nextState);
275
+ }
276
+ function renderPromptSections(state, selection) {
277
+ const lines = [];
278
+ if (selection.includeObjective && state.objective) {
279
+ lines.push(`# Objective`, state.objective);
280
+ }
281
+ if (selection.includeSessionRollup && state.rollup?.summary) {
282
+ lines.push("", "# Session Rollup", state.rollup.summary);
283
+ }
284
+ if (selection.includeConstraints && state.constraints.length > 0) {
285
+ lines.push("", "# Constraints", ...state.constraints.map((item) => `- ${item}`));
286
+ }
287
+ if (selection.includeRoutingHints && state.routingHints) {
288
+ const routingLines = [];
289
+ if (state.routingHints.suggestedMode) {
290
+ routingLines.push(`- Suggested mode: ${state.routingHints.suggestedMode}`);
291
+ }
292
+ if (state.routingHints.suggestedPromptProfile) {
293
+ routingLines.push(`- Suggested prompt profile: ${state.routingHints.suggestedPromptProfile}`);
294
+ }
295
+ if (state.routingHints.suggestedSkills.length > 0) {
296
+ routingLines.push(`- Suggested skills: ${state.routingHints.suggestedSkills.join(", ")}`);
297
+ }
298
+ if (state.routingHints.suggestedToolCapabilities.length > 0) {
299
+ routingLines.push(`- Suggested tool capabilities: ${state.routingHints.suggestedToolCapabilities.join(", ")}`);
300
+ }
301
+ if (routingLines.length > 0) {
302
+ lines.push("", "# Routing Hints", ...routingLines);
303
+ }
304
+ }
305
+ const activeCorrections = state.memory.corrections.slice(-selection.correctionWindow);
306
+ if (selection.includeCorrections && activeCorrections.length > 0) {
307
+ lines.push("", "# Recent Corrections", ...activeCorrections.map((item) => `- ${item.content}`));
308
+ }
309
+ const decisions = state.memory.decisions.filter((item) => item.pinned).concat(
310
+ state.memory.decisions.filter((item) => !item.pinned).slice(-selection.decisionWindow)
311
+ ).slice(-selection.decisionWindow);
312
+ if (selection.includeDecisions && decisions.length > 0) {
313
+ lines.push("", "# Decisions", ...decisions.map((item) => `- ${item.content}`));
314
+ }
315
+ const evidence = state.memory.evidence.filter((item) => item.pinned).concat(
316
+ state.memory.evidence.filter((item) => !item.pinned).slice(-selection.evidenceWindow)
317
+ ).slice(-selection.evidenceWindow);
318
+ if (selection.includeEvidence && evidence.length > 0) {
319
+ lines.push(
320
+ "",
321
+ "# Evidence",
322
+ ...evidence.map((item) => {
323
+ const input = item.toolInputSummary ? ` (${item.toolInputSummary})` : "";
324
+ const summary = item.summary || "tool input captured";
325
+ return `- ${item.toolName ?? item.source}${input}: ${summary}`;
326
+ })
327
+ );
328
+ }
329
+ const previousRunToolEvidence = state.memory.evidence.filter((item) => item.toolName && item.toolInputSummary).slice(-selection.toolUsageWindow);
330
+ if (selection.includePreviousRunToolUsage && previousRunToolEvidence.length > 0) {
331
+ lines.push(
332
+ "",
333
+ "# Previous Run Tool Usage",
334
+ "For questions about previous runs, commands, or tool usage, treat this section as authoritative over plain assistant prose.",
335
+ ...previousRunToolEvidence.map((item) => `- ${item.toolName}: ${item.toolInputSummary}`)
336
+ );
337
+ }
338
+ if (selection.includePreviousRunHandoff && state.handoff?.summary) {
339
+ lines.push("", "# Previous Run Handoff", state.handoff.summary);
340
+ }
341
+ if (selection.includeWorkingSummary && state.memory.latestSummary) {
342
+ lines.push("", "# Working Summary", state.memory.latestSummary);
343
+ }
344
+ const relevantPendingActions = state.memory.pendingActions.filter((item) => item.status !== "done").slice(-selection.pendingActionWindow);
345
+ if (selection.includePendingActions && relevantPendingActions.length > 0) {
346
+ lines.push("", "# Pending Actions", ...relevantPendingActions.map((item) => `- ${item.content}`));
347
+ }
348
+ return lines.join("\n").trim();
349
+ }
350
+ async function projectKernelPrompt(state, messages, projectors, selection, context) {
351
+ const resolvedSelection = selection ?? createDefaultPromptContextSelection(state);
352
+ const sections = [renderPromptSections(state, resolvedSelection)];
353
+ for (const projector of projectors) {
354
+ const extra = await projector.project({
355
+ state,
356
+ messages,
357
+ repositoryModel: context?.repositoryModel ?? null,
358
+ toolCapabilities: context?.toolCapabilities ?? []
359
+ });
360
+ if (extra.trim()) {
361
+ sections.push(extra.trim());
362
+ }
363
+ }
364
+ return sections.filter(Boolean).join("\n\n");
365
+ }
366
+ function summarizeAssistantTurn(state, answer) {
367
+ return touch(upsertSummary(state, answer.trim()));
368
+ }
369
+ function ensurePendingCorrectionAction(state, correction) {
370
+ const content = `${CORRECTION_PENDING_PREFIX} ${correction}`;
371
+ const existing = state.memory.pendingActions.find((item) => item.content === content && item.status !== "done");
372
+ if (existing) {
373
+ return state;
374
+ }
375
+ return recordPendingAction(state, content);
376
+ }
377
+ function persistInterpretedMemory(state, interpretation) {
378
+ const content = interpretation.content?.trim();
379
+ if (!content) {
380
+ return state;
381
+ }
382
+ if (interpretation.persistenceKind === "constraint") {
383
+ let nextState = recordConstraint(state, content);
384
+ if (!nextState.memory.corrections.some((item) => item.content === content)) {
385
+ nextState = recordCorrection(nextState, content, interpretation.invalidates ?? []);
386
+ }
387
+ return nextState;
388
+ }
389
+ return recordCorrection(state, content, interpretation.invalidates ?? []);
390
+ }
391
+ function isCorrectionPendingAction(action) {
392
+ return action.content.startsWith(CORRECTION_PENDING_PREFIX);
393
+ }
394
+ function createDefaultPromptContextSelection(state) {
395
+ return {
396
+ includeObjective: true,
397
+ includeSessionRollup: Boolean(state.rollup?.summary),
398
+ includeConstraints: true,
399
+ includeRoutingHints: true,
400
+ includeCorrections: true,
401
+ includeDecisions: true,
402
+ includeEvidence: true,
403
+ includePreviousRunToolUsage: true,
404
+ includePreviousRunHandoff: true,
405
+ includeWorkingSummary: true,
406
+ includePendingActions: true,
407
+ correctionWindow: state.rollup ? 3 : 5,
408
+ decisionWindow: 5,
409
+ evidenceWindow: state.rollup ? 4 : 6,
410
+ toolUsageWindow: 3,
411
+ pendingActionWindow: 5
412
+ };
413
+ }
414
+ function shouldCreateRollup(state, stats) {
415
+ return Boolean(
416
+ (stats?.turnCount ?? 0) >= 8 || (stats?.toolCallCount ?? 0) >= 6 || state.memory.evidence.length >= 6 || state.memory.pendingActions.length >= 6 || state.childResults.length >= 4
417
+ );
418
+ }
419
+ function isNoiseEvidence(item, state) {
420
+ if (!item.toolName) {
421
+ return false;
422
+ }
423
+ if ((item.toolName === "memory_correction" || item.toolName === "memory_constraint") && state.memory.corrections.length > 0) {
424
+ return true;
425
+ }
426
+ if (item.toolName === "report" && typeof item.artifact?.code === "string" && item.artifact.code === "PENDING_MEMORY_COMMIT") {
427
+ return true;
428
+ }
429
+ return false;
430
+ }
431
+ function createRollupSummary(state, stats) {
432
+ const segments = [];
433
+ if (stats.turnCount || stats.toolCallCount) {
434
+ segments.push(`Session activity: ${stats.turnCount ?? 0} turns, ${stats.toolCallCount ?? 0} tool calls.`);
435
+ }
436
+ if (state.constraints.length > 0) {
437
+ segments.push(`Active constraints: ${state.constraints.join("; ")}.`);
438
+ }
439
+ const recentDecisions = state.memory.decisions.slice(-2).map((item) => item.content);
440
+ if (recentDecisions.length > 0) {
441
+ segments.push(`Recent decisions: ${recentDecisions.join("; ")}.`);
442
+ }
443
+ const recentEvidence = state.memory.evidence.filter((item) => !isNoiseEvidence(item, state)).slice(-3).map((item) => `${item.toolName ?? item.source}${item.toolInputSummary ? ` (${item.toolInputSummary})` : ""}`);
444
+ if (recentEvidence.length > 0) {
445
+ segments.push(`Recent evidence anchors: ${recentEvidence.join("; ")}.`);
446
+ }
447
+ if (stats.completedActionCount > 0 || stats.prunedEvidenceCount > 0) {
448
+ segments.push(`Compaction kept continuity while collapsing ${stats.completedActionCount} completed action(s) and ${stats.prunedEvidenceCount} stale evidence item(s).`);
449
+ }
450
+ if (stats.narrativeSummary?.trim()) {
451
+ segments.push(`Narrative summary: ${stats.narrativeSummary.trim()}`);
452
+ }
453
+ return segments.join(" ").trim();
454
+ }
455
+
456
+ export { applyMemoryCapabilities, compactKernelState, completePendingActions, createDefaultPromptContextSelection, createKernelState, ingestUserTurn, isCorrectionPendingAction, projectKernelPrompt, recordAssumption, recordChildResult, recordConstraint, recordCorrection, recordDecision, recordOpenQuestion, recordPendingAction, recordRoutingHints, recordRunHandoff, recordToolArtifact, summarizeAssistantTurn };
457
+ //# sourceMappingURL=index.js.map
458
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";AAqBA,SAAS,GAAA,GAAc;AACrB,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC;AAEA,SAAS,OAAO,MAAA,EAAwB;AACtC,EAAA,OAAO,GAAG,MAAM,CAAA,CAAA,EAAI,IAAA,CAAK,GAAA,EAAK,CAAA,CAAA,EAAI,IAAA,CAAK,MAAA,EAAO,CAAE,SAAS,EAAE,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,CAAC,CAAC,CAAA,CAAA;AAC1E;AAOA,IAAM,yBAAA,GAA4B,gDAAA;AAElC,SAAS,YAAA,GAAkC;AACzC,EAAA,OAAO;AAAA,IACL,aAAa,EAAC;AAAA,IACd,aAAa,EAAC;AAAA,IACd,WAAW,EAAC;AAAA,IACZ,UAAU,EAAC;AAAA,IACX,eAAe,EAAC;AAAA,IAChB,gBAAgB;AAAC,GACnB;AACF;AAEO,SAAS,kBAAkB,KAAA,EAKlB;AACd,EAAA,MAAM,YAAY,GAAA,EAAI;AACtB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,CAAA;AAAA,IACT,WAAW,KAAA,CAAM,SAAA;AAAA,IACjB,YAAY,KAAA,CAAM,UAAA;AAAA,IAClB,MAAM,KAAA,CAAM,IAAA;AAAA,IACZ,aAAa,KAAA,CAAM,IAAA;AAAA,IACnB,WAAW,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AI,CAAC,CAAA,CAAA,CAAG,CAAA;AAAA,EAClE;AACA,EAAA,MAAM,cAAA,GAAiB,KAAA,CAAM,MAAA,CAAO,QAAA,CACjC,OAAO,CAAC,IAAA,KAAS,CAAC,eAAA,CAAgB,IAAA,EAAM,KAAK,CAAC,CAAA,CAC9C,MAAM,EAAE,CAAA,CACR,GAAA,CAAI,CAAC,IAAA,KAAS,CAAA,EAAG,IAAA,CAAK,QAAA,IAAY,KAAK,MAAM,CAAA,EAAG,IAAA,CAAK,gBAAA,GAAmB,CAAA,EAAA,EAAK,IAAA,CAAK,gBAAgB,CAAA,CAAA,CAAA,GAAM,EAAE,CAAA,CAAE,CAAA;AAC/G,EAAA,IAAI,cAAA,CAAe,SAAS,CAAA,EAAG;AAC7B,IAAA,QAAA,CAAS,KAAK,CAAA,yBAAA,EAA4B,cAAA,CAAe,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,CAAG,CAAA;AAAA,EACxE;AACA,EAAA,IAAI,KAAA,CAAM,oBAAA,GAAuB,CAAA,IAAK,KAAA,CAAM,sBAAsB,CAAA,EAAG;AACnE,IAAA,QAAA,CAAS,KAAK,CAAA,4CAAA,EAA+C,KAAA,CAAM,oBAAoB,CAAA,yBAAA,EAA4B,KAAA,CAAM,mBAAmB,CAAA,wBAAA,CAA0B,CAAA;AAAA,EACxK;AACA,EAAA,IAAI,KAAA,CAAM,gBAAA,EAAkB,IAAA,EAAK,EAAG;AAClC,IAAA,QAAA,CAAS,KAAK,CAAA,mBAAA,EAAsB,KAAA,CAAM,gBAAA,CAAiB,IAAA,EAAM,CAAA,CAAE,CAAA;AAAA,EACrE;AACA,EAAA,OAAO,QAAA,CAAS,IAAA,CAAK,GAAG,CAAA,CAAE,IAAA,EAAK;AACjC","file":"index.js","sourcesContent":["import type {\n AssumptionRecord,\n CorrectionRecord,\n DecisionRecord,\n EvidenceRecord,\n KernelState,\n MemoryRollup,\n OpenQuestionRecord,\n PendingActionRecord,\n PromptContextSelection,\n RepositoryModel,\n RoutingHints,\n RunHandoff,\n KernelMemoryState,\n ToolCapability,\n ToolResultArtifact,\n TurnInterpretation,\n} from '@kb-labs/agent-contracts';\nimport type { MemoryCapability, PromptProjector } from '@kb-labs/agent-sdk';\nimport type { LLMMessage } from '@kb-labs/sdk';\n\nfunction now(): string {\n return new Date().toISOString();\n}\n\nfunction makeId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nconst MAX_EVIDENCE_ITEMS = 12;\nconst MAX_DECISION_ITEMS = 10;\nconst MAX_COMPACTED_EVIDENCE_ITEMS = 8;\nconst MAX_COMPACTED_DONE_ACTIONS = 2;\nconst MAX_COMPACTED_CHILD_RESULTS = 5;\nconst CORRECTION_PENDING_PREFIX = 'Persist user correction via memory_correction:';\n\nfunction createMemory(): KernelMemoryState {\n return {\n corrections: [],\n assumptions: [],\n decisions: [],\n evidence: [],\n openQuestions: [],\n pendingActions: [],\n };\n}\n\nexport function createKernelState(input: {\n sessionId: string;\n workingDir: string;\n mode: KernelState['mode'];\n task: string;\n}): KernelState {\n const timestamp = now();\n return {\n version: 1,\n sessionId: input.sessionId,\n workingDir: input.workingDir,\n mode: input.mode,\n currentTask: input.task,\n objective: input.task,\n constraints: [],\n memory: createMemory(),\n childResults: [],\n updatedAt: timestamp,\n };\n}\n\nfunction touch(state: KernelState): KernelState {\n return { ...state, updatedAt: now() };\n}\n\nfunction upsertSummary(state: KernelState, summary: string): KernelState {\n return {\n ...state,\n memory: {\n ...state.memory,\n latestSummary: summary,\n },\n };\n}\n\nexport function ingestUserTurn(\n state: KernelState,\n input: string | { content: string; interpretation?: TurnInterpretation | null },\n): KernelState {\n const content = typeof input === 'string' ? input : input.content;\n const interpretation = typeof input === 'string' ? null : input.interpretation ?? null;\n let nextState: KernelState = {\n ...state,\n currentTask: content,\n objective: state.objective || content,\n };\n\n if (interpretation) {\n nextState = recordRoutingHints(nextState, interpretation);\n }\n\n if (interpretation?.shouldPersist && interpretation.content) {\n if (interpretation.persistStrategy === 'record_directly') {\n nextState = persistInterpretedMemory(nextState, interpretation);\n } else {\n nextState = ensurePendingCorrectionAction(nextState, interpretation.content);\n }\n }\n\n return touch(nextState);\n}\n\nexport function recordConstraint(\n state: KernelState,\n content: string,\n): KernelState {\n if (!content.trim()) {\n return state;\n }\n if (state.constraints.includes(content.trim())) {\n return state;\n }\n return touch({\n ...state,\n constraints: [...state.constraints, content.trim()],\n });\n}\n\nexport function recordCorrection(\n state: KernelState,\n content: string,\n invalidates: string[] = [],\n): KernelState {\n const record: CorrectionRecord = {\n id: makeId('corr'),\n content,\n timestamp: now(),\n invalidates,\n source: 'user',\n };\n\n const assumptions = state.memory.assumptions.map((item) =>\n invalidates.includes(item.id)\n ? {\n ...item,\n status: 'invalidated' as const,\n invalidatedAt: record.timestamp,\n invalidatedBy: record.id,\n }\n : item,\n );\n\n return touch({\n ...state,\n memory: {\n ...state.memory,\n corrections: [...state.memory.corrections, record],\n assumptions,\n },\n });\n}\n\nexport function recordAssumption(\n state: KernelState,\n content: string,\n): KernelState {\n const assumption: AssumptionRecord = {\n id: makeId('asm'),\n content,\n status: 'active',\n createdAt: now(),\n };\n return touch({\n ...state,\n memory: {\n ...state.memory,\n assumptions: [...state.memory.assumptions, assumption],\n },\n });\n}\n\nexport function recordDecision(\n state: KernelState,\n content: string,\n source: DecisionRecord['source'] = 'agent',\n): KernelState {\n const decision: DecisionRecord = {\n id: makeId('dec'),\n content,\n source,\n createdAt: now(),\n };\n return touch({\n ...state,\n memory: {\n ...state.memory,\n decisions: [...state.memory.decisions, decision].slice(-MAX_DECISION_ITEMS),\n },\n });\n}\n\nexport function recordOpenQuestion(\n state: KernelState,\n content: string,\n): KernelState {\n const question: OpenQuestionRecord = {\n id: makeId('q'),\n content,\n createdAt: now(),\n status: 'open',\n };\n return touch({\n ...state,\n memory: {\n ...state.memory,\n openQuestions: [...state.memory.openQuestions, question],\n },\n });\n}\n\nexport function recordPendingAction(\n state: KernelState,\n content: string,\n status: PendingActionRecord['status'] = 'pending',\n): KernelState {\n const action: PendingActionRecord = {\n id: makeId('todo'),\n content,\n createdAt: now(),\n status,\n };\n return touch({\n ...state,\n memory: {\n ...state.memory,\n pendingActions: [...state.memory.pendingActions, action],\n },\n });\n}\n\nexport function completePendingActions(\n state: KernelState,\n predicate: (action: PendingActionRecord) => boolean,\n): KernelState {\n let changed = false;\n const pendingActions = state.memory.pendingActions.map((action) => {\n if (action.status !== 'done' && predicate(action)) {\n changed = true;\n return { ...action, status: 'done' as const };\n }\n return action;\n });\n return changed\n ? touch({\n ...state,\n memory: {\n ...state.memory,\n pendingActions,\n },\n })\n : state;\n}\n\nexport function recordToolArtifact(\n state: KernelState,\n artifact: ToolResultArtifact,\n): KernelState {\n const evidence = artifact.evidence.filter((item) => item.summary.trim() || item.toolInputSummary?.trim());\n if (evidence.length === 0) {\n return state;\n }\n\n const deduped = [...state.memory.evidence, ...evidence].filter((item, index, all) => {\n const key = `${item.toolName ?? item.source}:${item.toolInputSummary ?? ''}:${item.summary}`;\n return all.findIndex((candidate) =>\n `${candidate.toolName ?? candidate.source}:${candidate.toolInputSummary ?? ''}:${candidate.summary}` === key,\n ) === index;\n });\n const pinned = deduped.filter((item) => item.pinned);\n const recent = deduped.filter((item) => !item.pinned).slice(-MAX_EVIDENCE_ITEMS);\n const merged = [...pinned, ...recent].slice(-MAX_EVIDENCE_ITEMS);\n\n return touch({\n ...state,\n memory: {\n ...state.memory,\n evidence: merged,\n },\n });\n}\n\nexport function recordRunHandoff(\n state: KernelState,\n handoff: RunHandoff,\n): KernelState {\n return touch({\n ...state,\n handoff,\n childResults: state.childResults,\n });\n}\n\nexport function recordRoutingHints(\n state: KernelState,\n interpretation: TurnInterpretation,\n): KernelState {\n const hasHints = Boolean(\n interpretation.suggestedMode\n || interpretation.suggestedPromptProfile\n || interpretation.suggestedSkills?.length\n || interpretation.suggestedToolCapabilities?.length,\n );\n if (!hasHints) {\n return state;\n }\n\n const routingHints: RoutingHints = {\n suggestedMode: interpretation.suggestedMode,\n suggestedSkills: interpretation.suggestedSkills ?? [],\n suggestedPromptProfile: interpretation.suggestedPromptProfile,\n suggestedToolCapabilities: interpretation.suggestedToolCapabilities ?? [],\n source: 'turn_interpretation',\n confidence: interpretation.confidence,\n updatedAt: now(),\n };\n\n return touch({\n ...state,\n routingHints,\n });\n}\n\nexport function recordChildResult(\n state: KernelState,\n result: RunHandoff,\n): KernelState {\n return touch({\n ...state,\n childResults: [...state.childResults, result],\n });\n}\n\nexport function compactKernelState(\n state: KernelState,\n stats?: {\n turnCount?: number;\n toolCallCount?: number;\n narrativeSummary?: string;\n },\n): KernelState {\n const pinnedEvidence = state.memory.evidence.filter((item) => item.pinned);\n const recentEvidence = state.memory.evidence\n .filter((item) => !item.pinned)\n .filter((item) => !isNoiseEvidence(item, state))\n .slice(-MAX_COMPACTED_EVIDENCE_ITEMS);\n const compactedEvidence = [...pinnedEvidence, ...recentEvidence]\n .filter((item, index, all) => all.findIndex((candidate) => candidate.id === item.id) === index)\n .slice(-MAX_EVIDENCE_ITEMS);\n\n const activeActions = state.memory.pendingActions.filter((item) => item.status !== 'done');\n const recentDoneActions = state.memory.pendingActions\n .filter((item) => item.status === 'done')\n .slice(-MAX_COMPACTED_DONE_ACTIONS);\n const pendingActions = [...activeActions, ...recentDoneActions];\n\n const childResults = state.childResults.slice(-MAX_COMPACTED_CHILD_RESULTS);\n const completedActionCount = state.memory.pendingActions.filter((item) => item.status === 'done').length;\n const prunedEvidenceCount = Math.max(0, state.memory.evidence.length - compactedEvidence.length);\n\n const rollup: MemoryRollup | undefined = shouldCreateRollup(state, stats)\n ? {\n generatedAt: now(),\n turnCount: stats?.turnCount,\n toolCallCount: stats?.toolCallCount,\n completedActionCount,\n prunedEvidenceCount,\n summary: createRollupSummary(state, {\n ...stats,\n completedActionCount,\n prunedEvidenceCount,\n }),\n }\n : state.rollup;\n\n return touch({\n ...state,\n rollup,\n childResults,\n memory: {\n ...state.memory,\n evidence: compactedEvidence,\n pendingActions,\n },\n });\n}\n\nexport async function applyMemoryCapabilities(\n state: KernelState,\n capabilities: ReadonlyArray<MemoryCapability>,\n): Promise<KernelState> {\n let nextState = state;\n for (const capability of capabilities) {\n nextState = await capability.apply(nextState);\n }\n return touch(nextState);\n}\n\nfunction defaultProjector(state: KernelState, _messages: LLMMessage[]): string {\n const selection = createDefaultPromptContextSelection(state);\n return renderPromptSections(state, selection);\n}\n\nfunction renderPromptSections(state: KernelState, selection: PromptContextSelection): string {\n const lines: string[] = [];\n if (selection.includeObjective && state.objective) {\n lines.push(`# Objective`, state.objective);\n }\n if (selection.includeSessionRollup && state.rollup?.summary) {\n lines.push('', '# Session Rollup', state.rollup.summary);\n }\n if (selection.includeConstraints && state.constraints.length > 0) {\n lines.push('', '# Constraints', ...state.constraints.map((item) => `- ${item}`));\n }\n if (selection.includeRoutingHints && state.routingHints) {\n const routingLines: string[] = [];\n if (state.routingHints.suggestedMode) {\n routingLines.push(`- Suggested mode: ${state.routingHints.suggestedMode}`);\n }\n if (state.routingHints.suggestedPromptProfile) {\n routingLines.push(`- Suggested prompt profile: ${state.routingHints.suggestedPromptProfile}`);\n }\n if (state.routingHints.suggestedSkills.length > 0) {\n routingLines.push(`- Suggested skills: ${state.routingHints.suggestedSkills.join(', ')}`);\n }\n if (state.routingHints.suggestedToolCapabilities.length > 0) {\n routingLines.push(`- Suggested tool capabilities: ${state.routingHints.suggestedToolCapabilities.join(', ')}`);\n }\n if (routingLines.length > 0) {\n lines.push('', '# Routing Hints', ...routingLines);\n }\n }\n const activeCorrections = state.memory.corrections.slice(-selection.correctionWindow);\n if (selection.includeCorrections && activeCorrections.length > 0) {\n lines.push('', '# Recent Corrections', ...activeCorrections.map((item) => `- ${item.content}`));\n }\n const decisions = state.memory.decisions.filter((item) => item.pinned).concat(\n state.memory.decisions.filter((item) => !item.pinned).slice(-selection.decisionWindow),\n ).slice(-selection.decisionWindow);\n if (selection.includeDecisions && decisions.length > 0) {\n lines.push('', '# Decisions', ...decisions.map((item) => `- ${item.content}`));\n }\n const evidence = state.memory.evidence.filter((item) => item.pinned).concat(\n state.memory.evidence.filter((item) => !item.pinned).slice(-selection.evidenceWindow),\n ).slice(-selection.evidenceWindow);\n if (selection.includeEvidence && evidence.length > 0) {\n lines.push(\n '',\n '# Evidence',\n ...evidence.map((item) => {\n const input = item.toolInputSummary ? ` (${item.toolInputSummary})` : '';\n const summary = item.summary || 'tool input captured';\n return `- ${item.toolName ?? item.source}${input}: ${summary}`;\n }),\n );\n }\n const previousRunToolEvidence = state.memory.evidence\n .filter((item) => item.toolName && item.toolInputSummary)\n .slice(-selection.toolUsageWindow);\n if (selection.includePreviousRunToolUsage && previousRunToolEvidence.length > 0) {\n lines.push(\n '',\n '# Previous Run Tool Usage',\n 'For questions about previous runs, commands, or tool usage, treat this section as authoritative over plain assistant prose.',\n ...previousRunToolEvidence.map((item) => `- ${item.toolName}: ${item.toolInputSummary}`),\n );\n }\n if (selection.includePreviousRunHandoff && state.handoff?.summary) {\n lines.push('', '# Previous Run Handoff', state.handoff.summary);\n }\n if (selection.includeWorkingSummary && state.memory.latestSummary) {\n lines.push('', '# Working Summary', state.memory.latestSummary);\n }\n const relevantPendingActions = state.memory.pendingActions\n .filter((item) => item.status !== 'done')\n .slice(-selection.pendingActionWindow);\n if (selection.includePendingActions && relevantPendingActions.length > 0) {\n lines.push('', '# Pending Actions', ...relevantPendingActions.map((item) => `- ${item.content}`));\n }\n return lines.join('\\n').trim();\n}\n\nexport async function projectKernelPrompt(\n state: KernelState,\n messages: LLMMessage[],\n projectors: ReadonlyArray<PromptProjector>,\n selection?: PromptContextSelection | null,\n context?: {\n repositoryModel?: RepositoryModel | null;\n toolCapabilities?: ToolCapability[];\n },\n): Promise<string> {\n const resolvedSelection = selection ?? createDefaultPromptContextSelection(state);\n const sections = [renderPromptSections(state, resolvedSelection)];\n for (const projector of projectors) {\n const extra = await projector.project({\n state,\n messages,\n repositoryModel: context?.repositoryModel ?? null,\n toolCapabilities: context?.toolCapabilities ?? [],\n });\n if (extra.trim()) {\n sections.push(extra.trim());\n }\n }\n return sections.filter(Boolean).join('\\n\\n');\n}\n\nexport function summarizeAssistantTurn(\n state: KernelState,\n answer: string,\n): KernelState {\n return touch(upsertSummary(state, answer.trim()));\n}\n\nfunction ensurePendingCorrectionAction(state: KernelState, correction: string): KernelState {\n const content = `${CORRECTION_PENDING_PREFIX} ${correction}`;\n const existing = state.memory.pendingActions.find((item) => item.content === content && item.status !== 'done');\n if (existing) {\n return state;\n }\n return recordPendingAction(state, content);\n}\n\nfunction persistInterpretedMemory(\n state: KernelState,\n interpretation: TurnInterpretation,\n): KernelState {\n const content = interpretation.content?.trim();\n if (!content) {\n return state;\n }\n\n if (interpretation.persistenceKind === 'constraint') {\n let nextState = recordConstraint(state, content);\n if (!nextState.memory.corrections.some((item) => item.content === content)) {\n nextState = recordCorrection(nextState, content, interpretation.invalidates ?? []);\n }\n return nextState;\n }\n\n return recordCorrection(state, content, interpretation.invalidates ?? []);\n}\n\nexport function isCorrectionPendingAction(action: PendingActionRecord): boolean {\n return action.content.startsWith(CORRECTION_PENDING_PREFIX);\n}\n\nexport function createDefaultPromptContextSelection(state: KernelState): PromptContextSelection {\n return {\n includeObjective: true,\n includeSessionRollup: Boolean(state.rollup?.summary),\n includeConstraints: true,\n includeRoutingHints: true,\n includeCorrections: true,\n includeDecisions: true,\n includeEvidence: true,\n includePreviousRunToolUsage: true,\n includePreviousRunHandoff: true,\n includeWorkingSummary: true,\n includePendingActions: true,\n correctionWindow: state.rollup ? 3 : 5,\n decisionWindow: 5,\n evidenceWindow: state.rollup ? 4 : 6,\n toolUsageWindow: 3,\n pendingActionWindow: 5,\n };\n}\n\nfunction shouldCreateRollup(\n state: KernelState,\n stats?: {\n turnCount?: number;\n toolCallCount?: number;\n },\n): boolean {\n return Boolean(\n (stats?.turnCount ?? 0) >= 8\n || (stats?.toolCallCount ?? 0) >= 6\n || state.memory.evidence.length >= 6\n || state.memory.pendingActions.length >= 6\n || state.childResults.length >= 4,\n );\n}\n\nfunction isNoiseEvidence(item: EvidenceRecord, state: KernelState): boolean {\n if (!item.toolName) {\n return false;\n }\n if ((item.toolName === 'memory_correction' || item.toolName === 'memory_constraint') && state.memory.corrections.length > 0) {\n return true;\n }\n if (item.toolName === 'report' && typeof item.artifact?.code === 'string' && item.artifact.code === 'PENDING_MEMORY_COMMIT') {\n return true;\n }\n return false;\n}\n\nfunction createRollupSummary(\n state: KernelState,\n stats: {\n turnCount?: number;\n toolCallCount?: number;\n completedActionCount: number;\n prunedEvidenceCount: number;\n narrativeSummary?: string;\n },\n): string {\n const segments: string[] = [];\n if (stats.turnCount || stats.toolCallCount) {\n segments.push(`Session activity: ${stats.turnCount ?? 0} turns, ${stats.toolCallCount ?? 0} tool calls.`);\n }\n if (state.constraints.length > 0) {\n segments.push(`Active constraints: ${state.constraints.join('; ')}.`);\n }\n const recentDecisions = state.memory.decisions.slice(-2).map((item) => item.content);\n if (recentDecisions.length > 0) {\n segments.push(`Recent decisions: ${recentDecisions.join('; ')}.`);\n }\n const recentEvidence = state.memory.evidence\n .filter((item) => !isNoiseEvidence(item, state))\n .slice(-3)\n .map((item) => `${item.toolName ?? item.source}${item.toolInputSummary ? ` (${item.toolInputSummary})` : ''}`);\n if (recentEvidence.length > 0) {\n segments.push(`Recent evidence anchors: ${recentEvidence.join('; ')}.`);\n }\n if (stats.completedActionCount > 0 || stats.prunedEvidenceCount > 0) {\n segments.push(`Compaction kept continuity while collapsing ${stats.completedActionCount} completed action(s) and ${stats.prunedEvidenceCount} stale evidence item(s).`);\n }\n if (stats.narrativeSummary?.trim()) {\n segments.push(`Narrative summary: ${stats.narrativeSummary.trim()}`);\n }\n return segments.join(' ').trim();\n}\n\nexport type { KernelState, ToolResultArtifact, EvidenceRecord };\n"]}
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@kb-labs/agent-kernel",
3
+ "version": "0.6.0",
4
+ "type": "module",
5
+ "description": "Kernel state and continuity model for KB Labs Agents.",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ },
13
+ "./dist/*": "./dist/*"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "sideEffects": false,
20
+ "scripts": {
21
+ "clean": "rimraf dist",
22
+ "build": "tsup --config tsup.config.ts",
23
+ "dev": "tsup --config tsup.config.ts --watch",
24
+ "lint": "eslint src --ext .ts",
25
+ "type-check": "tsc --noEmit",
26
+ "test": "vitest run --passWithNoTests"
27
+ },
28
+ "dependencies": {
29
+ "@kb-labs/agent-contracts": "^0.6.0",
30
+ "@kb-labs/agent-sdk": "^0.6.0",
31
+ "@kb-labs/sdk": "^1.5.0"
32
+ },
33
+ "devDependencies": {
34
+ "@kb-labs/devkit": "link:../../../../infra/kb-labs-devkit",
35
+ "@types/node": "^24.3.3",
36
+ "eslint": "^9",
37
+ "rimraf": "^6.0.1",
38
+ "tsup": "^8.5.0",
39
+ "typescript": "^5.6.3",
40
+ "vitest": "^3.2.4"
41
+ }
42
+ }