@ever-works/memory-pipeline-modifier 1.0.0 → 1.0.3
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/dist/index.cjs +453 -0
- package/dist/index.d.cts +133 -0
- package/dist/index.d.ts +133 -0
- package/dist/index.js +424 -0
- package/package.json +83 -73
- package/LICENSE +0 -661
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
FETCH_CONTEXT_STEP_ID: () => FETCH_CONTEXT_STEP_ID,
|
|
24
|
+
MemoryPipelineModifierPlugin: () => MemoryPipelineModifierPlugin,
|
|
25
|
+
SAVE_MEMORY_STEP_ID: () => SAVE_MEMORY_STEP_ID,
|
|
26
|
+
default: () => MemoryPipelineModifierPlugin
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(index_exports);
|
|
29
|
+
|
|
30
|
+
// src/memory-pipeline-modifier.plugin.ts
|
|
31
|
+
var FETCH_CONTEXT_STEP_ID = "memory-fetch-context";
|
|
32
|
+
var SAVE_MEMORY_STEP_ID = "memory-save";
|
|
33
|
+
var DEFAULT_PURPOSE = "work-generation";
|
|
34
|
+
var DEFAULT_MAX_CONTEXT_TOKENS = 1500;
|
|
35
|
+
var CHAT_TEMPLATE_MARKER_PATTERN = /\[INST\]|\[\/INST\]|<\|im_start\|>|<\|im_end\|>|<\|system\|>/gi;
|
|
36
|
+
function neutralizeMemoryField(value) {
|
|
37
|
+
return value.replace(/\r?\n|\r/g, " ").replace(CHAT_TEMPLATE_MARKER_PATTERN, "");
|
|
38
|
+
}
|
|
39
|
+
var MemoryPipelineModifierPlugin = class {
|
|
40
|
+
constructor() {
|
|
41
|
+
this.id = "memory-pipeline-modifier";
|
|
42
|
+
this.name = "Agent Memory Hooks";
|
|
43
|
+
this.version = "1.0.0";
|
|
44
|
+
this.category = "utility";
|
|
45
|
+
this.capabilities = ["pipeline-modifier"];
|
|
46
|
+
this.configurationMode = "hybrid";
|
|
47
|
+
// Step-orchestratable pipelines only. Self-managed pipelines
|
|
48
|
+
// (claude-code, codex, opencode, etc.) bypass modifier injection
|
|
49
|
+
// because they route through `FullPipelineExecutorService`, so
|
|
50
|
+
// listing them here would be silently ineffective (Codex P2 on
|
|
51
|
+
// PR #1081). Enumerate explicitly instead of `['*']` so it's
|
|
52
|
+
// obvious which pipelines pick this up.
|
|
53
|
+
this.targetPipelines = ["standard-pipeline", "agent-pipeline"];
|
|
54
|
+
this.settingsSchema = {
|
|
55
|
+
type: "object",
|
|
56
|
+
properties: {
|
|
57
|
+
enabled: {
|
|
58
|
+
type: "boolean",
|
|
59
|
+
title: "Enable agent-memory hooks for this Work",
|
|
60
|
+
description: "Inject persistent memory hooks into the Work's pipeline. When on, the pipeline fetches prior observations at the start and saves a digest at the end. Requires an agent-memory provider to be enabled (default: @ever-works/agentmemory-plugin).",
|
|
61
|
+
default: false,
|
|
62
|
+
"x-scope": "work"
|
|
63
|
+
},
|
|
64
|
+
purpose: {
|
|
65
|
+
type: "string",
|
|
66
|
+
title: "Context purpose",
|
|
67
|
+
description: 'Hint passed to the memory backend to bias the retrieved context (e.g. "work-generation", "fix-bug", "research"). Backends that support purpose-aware retrieval will use it.',
|
|
68
|
+
default: DEFAULT_PURPOSE,
|
|
69
|
+
"x-scope": "work"
|
|
70
|
+
},
|
|
71
|
+
maxContextTokens: {
|
|
72
|
+
type: "number",
|
|
73
|
+
title: "Max context tokens",
|
|
74
|
+
description: "Upper bound on the size of the injected memory context payload.",
|
|
75
|
+
default: DEFAULT_MAX_CONTEXT_TOKENS,
|
|
76
|
+
minimum: 100,
|
|
77
|
+
maximum: 32e3,
|
|
78
|
+
"x-scope": "work"
|
|
79
|
+
},
|
|
80
|
+
saveSummary: {
|
|
81
|
+
type: "boolean",
|
|
82
|
+
title: "Save a summary at the end of the run",
|
|
83
|
+
description: "When on, the last pipeline step saves a short observation about what was generated so the next run can recall it.",
|
|
84
|
+
default: true,
|
|
85
|
+
"x-scope": "work"
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
required: []
|
|
89
|
+
};
|
|
90
|
+
this.context = null;
|
|
91
|
+
}
|
|
92
|
+
// ── IPlugin lifecycle ──────────────────────────────────────────────
|
|
93
|
+
async onLoad(context) {
|
|
94
|
+
this.context = context;
|
|
95
|
+
context.logger.log("memory-pipeline-modifier plugin loaded");
|
|
96
|
+
}
|
|
97
|
+
async onUnload() {
|
|
98
|
+
this.context = null;
|
|
99
|
+
}
|
|
100
|
+
async healthCheck() {
|
|
101
|
+
return {
|
|
102
|
+
status: "healthy",
|
|
103
|
+
message: "memory-pipeline-modifier plugin is ready",
|
|
104
|
+
checkedAt: Date.now()
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
async validateSettings(settings) {
|
|
108
|
+
const maxTokens = settings.maxContextTokens;
|
|
109
|
+
if (maxTokens !== void 0 && (typeof maxTokens !== "number" || maxTokens < 100 || maxTokens > 32e3)) {
|
|
110
|
+
return {
|
|
111
|
+
valid: false,
|
|
112
|
+
errors: [
|
|
113
|
+
{ path: "maxContextTokens", message: "`maxContextTokens` must be a number between 100 and 32000" }
|
|
114
|
+
]
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
return { valid: true };
|
|
118
|
+
}
|
|
119
|
+
getManifest() {
|
|
120
|
+
return {
|
|
121
|
+
id: this.id,
|
|
122
|
+
name: this.name,
|
|
123
|
+
version: this.version,
|
|
124
|
+
description: "Injects persistent memory hooks into any work-generation pipeline \u2014 fetches prior context at the start, saves a digest at the end. Requires an agent-memory provider.",
|
|
125
|
+
category: this.category,
|
|
126
|
+
capabilities: [...this.capabilities],
|
|
127
|
+
author: { name: "Ever Works Team" },
|
|
128
|
+
license: "AGPL-3.0",
|
|
129
|
+
builtIn: true,
|
|
130
|
+
autoEnable: false,
|
|
131
|
+
visibility: "public"
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
// ── IPipelineModifierPlugin ────────────────────────────────────────
|
|
135
|
+
getStepDefinitions() {
|
|
136
|
+
return [
|
|
137
|
+
{
|
|
138
|
+
id: FETCH_CONTEXT_STEP_ID,
|
|
139
|
+
name: "Fetch agent-memory context",
|
|
140
|
+
description: "Retrieve persistent context for this Work from the agent-memory store.",
|
|
141
|
+
position: { type: "first" },
|
|
142
|
+
optional: true,
|
|
143
|
+
parallelizable: false,
|
|
144
|
+
provides: ["memoryContext"]
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
id: SAVE_MEMORY_STEP_ID,
|
|
148
|
+
name: "Save agent-memory observation",
|
|
149
|
+
description: "Persist a short digest of this run to the agent-memory store for next time.",
|
|
150
|
+
position: { type: "last" },
|
|
151
|
+
optional: true,
|
|
152
|
+
parallelizable: false
|
|
153
|
+
}
|
|
154
|
+
];
|
|
155
|
+
}
|
|
156
|
+
async canSkip(context) {
|
|
157
|
+
const settings = this.resolveSettings(context);
|
|
158
|
+
return settings.enabled !== true;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* KB option B (PR #1087). The pipeline-builder calls this BEFORE
|
|
162
|
+
* injecting our steps, so disabling the modifier here means zero
|
|
163
|
+
* overhead on the host pipeline — no STEP_STARTED events, no step
|
|
164
|
+
* metrics, no executor branching. Decision is purely settings-based,
|
|
165
|
+
* matching the existing `canSkip(context)` semantics.
|
|
166
|
+
*/
|
|
167
|
+
async canSkipAtBuildTime(input) {
|
|
168
|
+
return input.settings.enabled !== true;
|
|
169
|
+
}
|
|
170
|
+
async execute(context, options, _onProgress) {
|
|
171
|
+
const rawSettings = options?.settings ?? {};
|
|
172
|
+
const stepId = rawSettings.stepId;
|
|
173
|
+
const execContext = rawSettings.execContext;
|
|
174
|
+
const settings = this.resolveSettings(context, rawSettings);
|
|
175
|
+
if (!stepId) {
|
|
176
|
+
throw new Error(
|
|
177
|
+
"memory-pipeline-modifier: `options.settings.stepId` is required (set by step-pipeline-executor)."
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
const logger = execContext?.logger ?? console;
|
|
181
|
+
if (settings.enabled !== true) {
|
|
182
|
+
return context;
|
|
183
|
+
}
|
|
184
|
+
const memoryFacade = execContext?.agentMemoryFacade;
|
|
185
|
+
if (!memoryFacade) {
|
|
186
|
+
logger.warn(
|
|
187
|
+
`memory-pipeline-modifier: no agent-memory facade on execContext \u2014 install and enable an agent-memory provider (e.g. @ever-works/agentmemory-plugin). Step "${stepId}" no-ops.`
|
|
188
|
+
);
|
|
189
|
+
return context;
|
|
190
|
+
}
|
|
191
|
+
context.__memoryModifierExecContext = execContext;
|
|
192
|
+
if (stepId === FETCH_CONTEXT_STEP_ID) {
|
|
193
|
+
return await this.runFetchContext(context, memoryFacade, settings, logger);
|
|
194
|
+
}
|
|
195
|
+
if (stepId === SAVE_MEMORY_STEP_ID) {
|
|
196
|
+
return await this.runSaveMemory(context, memoryFacade, settings, logger);
|
|
197
|
+
}
|
|
198
|
+
throw new Error(`memory-pipeline-modifier: unknown stepId "${stepId}"`);
|
|
199
|
+
}
|
|
200
|
+
async validate(_context) {
|
|
201
|
+
return { valid: true };
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Called by the step-pipeline-executor when the host pipeline fails
|
|
205
|
+
* or is cancelled. The `last`-positioned `memory-save` step never
|
|
206
|
+
* fires in that case (the executor breaks out of the step loop
|
|
207
|
+
* before reaching `last`), so we use rollback to persist a digest
|
|
208
|
+
* tagged `failed` / `cancelled` instead.
|
|
209
|
+
*
|
|
210
|
+
* Note: the rollback interface doesn't include `options` / `execContext`,
|
|
211
|
+
* so we recover the bound memory facade by reading it from the
|
|
212
|
+
* context bag where `execute()` stashed it on its first run. If the
|
|
213
|
+
* fetch-context step never ran (e.g. modifier disabled, or the
|
|
214
|
+
* pipeline failed before group 0), there's nothing stashed and we
|
|
215
|
+
* no-op silently.
|
|
216
|
+
*/
|
|
217
|
+
async rollback(context, error) {
|
|
218
|
+
const settings = this.resolveSettings(context);
|
|
219
|
+
if (settings.enabled !== true) return;
|
|
220
|
+
const execContext = context.__memoryModifierExecContext;
|
|
221
|
+
const memoryFacade = execContext?.agentMemoryFacade;
|
|
222
|
+
const logger = execContext?.logger ?? console;
|
|
223
|
+
if (!memoryFacade) {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
if (settings.saveSummary === false) {
|
|
227
|
+
await this.closeSelfOpenedSession(context, memoryFacade, logger);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
const work = context.work;
|
|
232
|
+
const items = context.items;
|
|
233
|
+
const isCancellation = this.looksLikeCancellation(error);
|
|
234
|
+
const summary = this.buildFailureSummary(work, items, error, isCancellation);
|
|
235
|
+
const tags = this.buildFailureTags(work, isCancellation);
|
|
236
|
+
const sessionId = this.resolveSessionId(context);
|
|
237
|
+
const record = await memoryFacade.saveMemory(
|
|
238
|
+
{
|
|
239
|
+
content: summary,
|
|
240
|
+
tags,
|
|
241
|
+
projectId: work?.slug ?? work?.id,
|
|
242
|
+
...sessionId ? { sessionId } : {},
|
|
243
|
+
metadata: {
|
|
244
|
+
workId: work?.id,
|
|
245
|
+
workSlug: work?.slug,
|
|
246
|
+
itemCount: Array.isArray(items) ? items.length : void 0,
|
|
247
|
+
errorMessage: error.message,
|
|
248
|
+
errorName: error.name,
|
|
249
|
+
failedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
{ userId: "bound", workId: "bound" }
|
|
253
|
+
);
|
|
254
|
+
logger.log(
|
|
255
|
+
`memory-rollback: saved ${isCancellation ? "cancellation" : "failure"} observation ${record.id} for Work "${work?.slug ?? work?.id ?? "?"}"`
|
|
256
|
+
);
|
|
257
|
+
} catch (rollbackError) {
|
|
258
|
+
const message = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
|
|
259
|
+
logger.warn(`memory-rollback: failed to save failure observation \u2014 ${message}`);
|
|
260
|
+
} finally {
|
|
261
|
+
await this.closeSelfOpenedSession(context, memoryFacade, logger);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
// ── session lifecycle ──────────────────────────────────────────────
|
|
265
|
+
/**
|
|
266
|
+
* Resolve the agent-memory session id to associate this run's
|
|
267
|
+
* reads/writes with, WITHOUT opening a new one:
|
|
268
|
+
*
|
|
269
|
+
* 1. An orchestrator-supplied session (`execContext.memorySessionId`,
|
|
270
|
+
* forwarded by the pipeline executor from
|
|
271
|
+
* `PipelineExecutionOptions.memorySessionId`) always wins — the
|
|
272
|
+
* caller owns that session's lifecycle, so we never close it.
|
|
273
|
+
* 2. Otherwise a session this modifier opened earlier in the same
|
|
274
|
+
* run (stashed on the context bag by `ensureSessionId`).
|
|
275
|
+
*
|
|
276
|
+
* Returns `undefined` when neither exists yet.
|
|
277
|
+
*/
|
|
278
|
+
resolveSessionId(context) {
|
|
279
|
+
const execContext = context.__memoryModifierExecContext;
|
|
280
|
+
if (execContext?.memorySessionId) return execContext.memorySessionId;
|
|
281
|
+
return context.__memoryModifierSessionId;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Resolve an existing session id or, when none is supplied by an
|
|
285
|
+
* orchestrator, open a per-run session of our own so that the
|
|
286
|
+
* fetch-context read, the save digest, and any failure rollback all
|
|
287
|
+
* land on the SAME `agent_memory_sessions` row. Called from the
|
|
288
|
+
* first-position fetch step so the session exists for the whole run.
|
|
289
|
+
*
|
|
290
|
+
* Best-effort: a failure to open is swallowed (memory must never crash
|
|
291
|
+
* the host pipeline) and the run continues session-less.
|
|
292
|
+
*/
|
|
293
|
+
async ensureSessionId(context, memoryFacade, logger) {
|
|
294
|
+
const existing = this.resolveSessionId(context);
|
|
295
|
+
if (existing) return existing;
|
|
296
|
+
try {
|
|
297
|
+
const work = context.work;
|
|
298
|
+
const session = await memoryFacade.openSession(
|
|
299
|
+
// Open in the SAME project namespace the fetch/save/rollback
|
|
300
|
+
// calls use (`work.slug ?? work.id`) so the session row and
|
|
301
|
+
// its memory entries live together (Codex P2 on PR #1113).
|
|
302
|
+
{ projectId: work?.slug ?? work?.id, source: this.id, workId: work?.id, workSlug: work?.slug },
|
|
303
|
+
// Bound facade ignores its facadeOptions — pass placeholder.
|
|
304
|
+
{ userId: "bound", workId: "bound" }
|
|
305
|
+
);
|
|
306
|
+
if (session?.id) {
|
|
307
|
+
context.__memoryModifierSessionId = session.id;
|
|
308
|
+
context.__memoryModifierSessionSelfOpened = true;
|
|
309
|
+
logger.log(`memory-session: opened session ${session.id} for Work "${work?.slug ?? work?.id ?? "?"}"`);
|
|
310
|
+
return session.id;
|
|
311
|
+
}
|
|
312
|
+
} catch (error) {
|
|
313
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
314
|
+
logger.warn(`memory-session: failed to open session \u2014 ${message}`);
|
|
315
|
+
}
|
|
316
|
+
return void 0;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Close the session this modifier opened, exactly once, at the end of
|
|
320
|
+
* the run (success digest, save-disabled exit, or failure rollback).
|
|
321
|
+
* No-ops when the session was supplied by an orchestrator (it owns the
|
|
322
|
+
* lifecycle) or when we never opened one. Best-effort.
|
|
323
|
+
*/
|
|
324
|
+
async closeSelfOpenedSession(context, memoryFacade, logger) {
|
|
325
|
+
if (context.__memoryModifierSessionSelfOpened !== true) return;
|
|
326
|
+
const sessionId = context.__memoryModifierSessionId;
|
|
327
|
+
context.__memoryModifierSessionSelfOpened = false;
|
|
328
|
+
if (!sessionId) return;
|
|
329
|
+
try {
|
|
330
|
+
await memoryFacade.closeSession(sessionId, { userId: "bound", workId: "bound" });
|
|
331
|
+
logger.log(`memory-session: closed session ${sessionId}`);
|
|
332
|
+
} catch (error) {
|
|
333
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
334
|
+
logger.warn(`memory-session: failed to close session ${sessionId} \u2014 ${message}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
// ── step implementations ───────────────────────────────────────────
|
|
338
|
+
async runFetchContext(context, memoryFacade, settings, logger) {
|
|
339
|
+
try {
|
|
340
|
+
const work = context.work;
|
|
341
|
+
const request = context.request;
|
|
342
|
+
const sessionId = await this.ensureSessionId(context, memoryFacade, logger);
|
|
343
|
+
const ctx = await memoryFacade.buildContext(
|
|
344
|
+
{
|
|
345
|
+
query: request?.prompt,
|
|
346
|
+
purpose: settings.purpose ?? DEFAULT_PURPOSE,
|
|
347
|
+
projectId: work?.slug ?? work?.id,
|
|
348
|
+
maxTokens: settings.maxContextTokens ?? DEFAULT_MAX_CONTEXT_TOKENS,
|
|
349
|
+
...sessionId ? { sessionId } : {}
|
|
350
|
+
},
|
|
351
|
+
// Bound facade ignores its facadeOptions — pass placeholder.
|
|
352
|
+
{ userId: "bound", workId: "bound" }
|
|
353
|
+
);
|
|
354
|
+
if (ctx?.content) {
|
|
355
|
+
context.memoryContext = ctx;
|
|
356
|
+
logger.log(
|
|
357
|
+
`memory-fetch-context: injected ${ctx.approxTokens ?? "~"} tokens of prior memory for Work "${work?.slug ?? work?.id ?? "?"}"`
|
|
358
|
+
);
|
|
359
|
+
} else {
|
|
360
|
+
logger.log("memory-fetch-context: no prior memory found");
|
|
361
|
+
}
|
|
362
|
+
return context;
|
|
363
|
+
} catch (error) {
|
|
364
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
365
|
+
logger.warn(`memory-fetch-context: failed to fetch context \u2014 ${message}`);
|
|
366
|
+
return context;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
async runSaveMemory(context, memoryFacade, settings, logger) {
|
|
370
|
+
if (settings.saveSummary === false) {
|
|
371
|
+
logger.log("memory-save: saveSummary disabled \u2014 skipping");
|
|
372
|
+
await this.closeSelfOpenedSession(context, memoryFacade, logger);
|
|
373
|
+
return context;
|
|
374
|
+
}
|
|
375
|
+
try {
|
|
376
|
+
const work = context.work;
|
|
377
|
+
const items = context.items;
|
|
378
|
+
const summary = this.buildSummary(work, items);
|
|
379
|
+
const tags = this.buildTags(work);
|
|
380
|
+
const sessionId = this.resolveSessionId(context);
|
|
381
|
+
const record = await memoryFacade.saveMemory(
|
|
382
|
+
{
|
|
383
|
+
content: summary,
|
|
384
|
+
tags,
|
|
385
|
+
projectId: work?.slug ?? work?.id,
|
|
386
|
+
...sessionId ? { sessionId } : {},
|
|
387
|
+
metadata: {
|
|
388
|
+
workId: work?.id,
|
|
389
|
+
workSlug: work?.slug,
|
|
390
|
+
itemCount: Array.isArray(items) ? items.length : void 0,
|
|
391
|
+
completedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
392
|
+
}
|
|
393
|
+
},
|
|
394
|
+
{ userId: "bound", workId: "bound" }
|
|
395
|
+
);
|
|
396
|
+
logger.log(`memory-save: saved observation ${record.id} for Work "${work?.slug ?? work?.id ?? "?"}"`);
|
|
397
|
+
await this.closeSelfOpenedSession(context, memoryFacade, logger);
|
|
398
|
+
return context;
|
|
399
|
+
} catch (error) {
|
|
400
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
401
|
+
logger.warn(`memory-save: failed to save observation \u2014 ${message}`);
|
|
402
|
+
await this.closeSelfOpenedSession(context, memoryFacade, logger);
|
|
403
|
+
return context;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
// ── helpers ────────────────────────────────────────────────────────
|
|
407
|
+
resolveSettings(context, override) {
|
|
408
|
+
const fromContext = context.stepSettings?.[this.id];
|
|
409
|
+
const merged = { ...fromContext ?? {}, ...override ?? {} };
|
|
410
|
+
const out = {};
|
|
411
|
+
if (typeof merged.enabled === "boolean") out.enabled = merged.enabled;
|
|
412
|
+
if (typeof merged.purpose === "string" && merged.purpose) out.purpose = merged.purpose;
|
|
413
|
+
if (typeof merged.maxContextTokens === "number") out.maxContextTokens = merged.maxContextTokens;
|
|
414
|
+
if (typeof merged.saveSummary === "boolean") out.saveSummary = merged.saveSummary;
|
|
415
|
+
return out;
|
|
416
|
+
}
|
|
417
|
+
buildSummary(work, items) {
|
|
418
|
+
const workLabel = neutralizeMemoryField(work?.name ?? work?.slug ?? work?.id ?? "unknown Work");
|
|
419
|
+
const count = Array.isArray(items) ? items.length : 0;
|
|
420
|
+
return `Work "${workLabel}" \u2014 pipeline completed with ${count} item${count === 1 ? "" : "s"}.`;
|
|
421
|
+
}
|
|
422
|
+
buildTags(work) {
|
|
423
|
+
const tags = ["pipeline-run"];
|
|
424
|
+
if (work?.slug) tags.push(`work:${work.slug}`);
|
|
425
|
+
else if (work?.id) tags.push(`work-id:${work.id}`);
|
|
426
|
+
return tags;
|
|
427
|
+
}
|
|
428
|
+
buildFailureSummary(work, items, error, isCancellation) {
|
|
429
|
+
const workLabel = neutralizeMemoryField(work?.name ?? work?.slug ?? work?.id ?? "unknown Work");
|
|
430
|
+
const count = Array.isArray(items) ? items.length : 0;
|
|
431
|
+
const verb = isCancellation ? "cancelled" : "failed";
|
|
432
|
+
const trimmedMessage = neutralizeMemoryField(error.message ?? "").slice(0, 240);
|
|
433
|
+
const itemNote = count > 0 ? ` (${count} item${count === 1 ? "" : "s"} produced before stop)` : "";
|
|
434
|
+
return `Work "${workLabel}" \u2014 pipeline ${verb}${itemNote}: ${trimmedMessage}`;
|
|
435
|
+
}
|
|
436
|
+
buildFailureTags(work, isCancellation) {
|
|
437
|
+
let tags = ["pipeline-run", isCancellation ? "cancelled" : "failed"];
|
|
438
|
+
if (work?.slug) tags.push(`work:${work.slug}`);
|
|
439
|
+
else if (work?.id) tags.push(`work-id:${work.id}`);
|
|
440
|
+
return tags;
|
|
441
|
+
}
|
|
442
|
+
looksLikeCancellation(error) {
|
|
443
|
+
const name = error.name?.toLowerCase() ?? "";
|
|
444
|
+
const message = error.message?.toLowerCase() ?? "";
|
|
445
|
+
return name === "aborterror" || message.includes("cancelled") || message.includes("canceled");
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
449
|
+
0 && (module.exports = {
|
|
450
|
+
FETCH_CONTEXT_STEP_ID,
|
|
451
|
+
MemoryPipelineModifierPlugin,
|
|
452
|
+
SAVE_MEMORY_STEP_ID
|
|
453
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { IPlugin, IPipelineModifierPlugin, PluginCategory, JsonSchema, PluginContext, PluginHealthCheck, ValidationResult, PluginManifest, PipelineStepDefinition, IPipelineContext, ModifierBuildTimeCheck, StepExecutionOptions, StepProgressCallback } from '@ever-works/plugin';
|
|
2
|
+
|
|
3
|
+
/** Step injected at the START of every pipeline run — fetches prior
|
|
4
|
+
* agent-memory context relevant to the Work and stashes it on the
|
|
5
|
+
* pipeline context for downstream steps to pick up. */
|
|
6
|
+
declare const FETCH_CONTEXT_STEP_ID = "memory-fetch-context";
|
|
7
|
+
/** Step injected at the END of every pipeline run — saves a short
|
|
8
|
+
* observation summarising what was generated, so the next run can
|
|
9
|
+
* retrieve it. */
|
|
10
|
+
declare const SAVE_MEMORY_STEP_ID = "memory-save";
|
|
11
|
+
/** Settings the modifier reads after the facade resolves the
|
|
12
|
+
* user/work/admin hierarchy. */
|
|
13
|
+
interface MemoryPipelineModifierSettings {
|
|
14
|
+
enabled?: boolean;
|
|
15
|
+
purpose?: string;
|
|
16
|
+
maxContextTokens?: number;
|
|
17
|
+
saveSummary?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Agent-memory pipeline modifier.
|
|
21
|
+
*
|
|
22
|
+
* Adds two steps to any pipeline (target `['*']`):
|
|
23
|
+
*
|
|
24
|
+
* 1. `memory-fetch-context` (position: first) — calls
|
|
25
|
+
* `agentMemoryFacade.buildContext({...})` to get a digest of
|
|
26
|
+
* previously-saved observations for the same project / work, then
|
|
27
|
+
* attaches the result to the pipeline context as
|
|
28
|
+
* `context.memoryContext` so downstream steps that know how to use
|
|
29
|
+
* it can splice it into their prompts.
|
|
30
|
+
*
|
|
31
|
+
* 2. `memory-save` (position: last) — calls
|
|
32
|
+
* `agentMemoryFacade.saveMemory({...})` with a short summary of
|
|
33
|
+
* the run (item counts + any error / cancellation signal). Future
|
|
34
|
+
* runs of the same Work pick this up via step 1.
|
|
35
|
+
*
|
|
36
|
+
* Opt-in: the modifier's `canSkip()` returns `true` unless the
|
|
37
|
+
* `enabled: boolean` setting is set on the Work (off by default). When
|
|
38
|
+
* the resolved agent-memory facade is missing — e.g. the operator
|
|
39
|
+
* hasn't installed `@ever-works/agentmemory-plugin` yet — the steps
|
|
40
|
+
* log a warning and no-op rather than failing the whole pipeline.
|
|
41
|
+
*
|
|
42
|
+
* The modifier itself implements `IPipelineModifierPlugin` and
|
|
43
|
+
* dispatches in `execute()` based on `options.settings.stepId`, which
|
|
44
|
+
* the step-pipeline executor wires through.
|
|
45
|
+
*/
|
|
46
|
+
declare class MemoryPipelineModifierPlugin implements IPlugin, IPipelineModifierPlugin {
|
|
47
|
+
readonly id = "memory-pipeline-modifier";
|
|
48
|
+
readonly name = "Agent Memory Hooks";
|
|
49
|
+
readonly version = "1.0.0";
|
|
50
|
+
readonly category: PluginCategory;
|
|
51
|
+
readonly capabilities: readonly ["pipeline-modifier"];
|
|
52
|
+
readonly configurationMode: "hybrid";
|
|
53
|
+
readonly targetPipelines: readonly ["standard-pipeline", "agent-pipeline"];
|
|
54
|
+
readonly settingsSchema: JsonSchema;
|
|
55
|
+
private context;
|
|
56
|
+
onLoad(context: PluginContext): Promise<void>;
|
|
57
|
+
onUnload(): Promise<void>;
|
|
58
|
+
healthCheck(): Promise<PluginHealthCheck>;
|
|
59
|
+
validateSettings(settings: Record<string, unknown>): Promise<ValidationResult>;
|
|
60
|
+
getManifest(): PluginManifest;
|
|
61
|
+
getStepDefinitions(): PipelineStepDefinition[];
|
|
62
|
+
canSkip(context: IPipelineContext): Promise<boolean>;
|
|
63
|
+
/**
|
|
64
|
+
* KB option B (PR #1087). The pipeline-builder calls this BEFORE
|
|
65
|
+
* injecting our steps, so disabling the modifier here means zero
|
|
66
|
+
* overhead on the host pipeline — no STEP_STARTED events, no step
|
|
67
|
+
* metrics, no executor branching. Decision is purely settings-based,
|
|
68
|
+
* matching the existing `canSkip(context)` semantics.
|
|
69
|
+
*/
|
|
70
|
+
canSkipAtBuildTime(input: ModifierBuildTimeCheck): Promise<boolean>;
|
|
71
|
+
execute(context: IPipelineContext, options?: StepExecutionOptions, _onProgress?: StepProgressCallback): Promise<IPipelineContext>;
|
|
72
|
+
validate(_context: IPipelineContext): Promise<{
|
|
73
|
+
valid: boolean;
|
|
74
|
+
error?: string;
|
|
75
|
+
}>;
|
|
76
|
+
/**
|
|
77
|
+
* Called by the step-pipeline-executor when the host pipeline fails
|
|
78
|
+
* or is cancelled. The `last`-positioned `memory-save` step never
|
|
79
|
+
* fires in that case (the executor breaks out of the step loop
|
|
80
|
+
* before reaching `last`), so we use rollback to persist a digest
|
|
81
|
+
* tagged `failed` / `cancelled` instead.
|
|
82
|
+
*
|
|
83
|
+
* Note: the rollback interface doesn't include `options` / `execContext`,
|
|
84
|
+
* so we recover the bound memory facade by reading it from the
|
|
85
|
+
* context bag where `execute()` stashed it on its first run. If the
|
|
86
|
+
* fetch-context step never ran (e.g. modifier disabled, or the
|
|
87
|
+
* pipeline failed before group 0), there's nothing stashed and we
|
|
88
|
+
* no-op silently.
|
|
89
|
+
*/
|
|
90
|
+
rollback(context: IPipelineContext, error: Error): Promise<void>;
|
|
91
|
+
/**
|
|
92
|
+
* Resolve the agent-memory session id to associate this run's
|
|
93
|
+
* reads/writes with, WITHOUT opening a new one:
|
|
94
|
+
*
|
|
95
|
+
* 1. An orchestrator-supplied session (`execContext.memorySessionId`,
|
|
96
|
+
* forwarded by the pipeline executor from
|
|
97
|
+
* `PipelineExecutionOptions.memorySessionId`) always wins — the
|
|
98
|
+
* caller owns that session's lifecycle, so we never close it.
|
|
99
|
+
* 2. Otherwise a session this modifier opened earlier in the same
|
|
100
|
+
* run (stashed on the context bag by `ensureSessionId`).
|
|
101
|
+
*
|
|
102
|
+
* Returns `undefined` when neither exists yet.
|
|
103
|
+
*/
|
|
104
|
+
private resolveSessionId;
|
|
105
|
+
/**
|
|
106
|
+
* Resolve an existing session id or, when none is supplied by an
|
|
107
|
+
* orchestrator, open a per-run session of our own so that the
|
|
108
|
+
* fetch-context read, the save digest, and any failure rollback all
|
|
109
|
+
* land on the SAME `agent_memory_sessions` row. Called from the
|
|
110
|
+
* first-position fetch step so the session exists for the whole run.
|
|
111
|
+
*
|
|
112
|
+
* Best-effort: a failure to open is swallowed (memory must never crash
|
|
113
|
+
* the host pipeline) and the run continues session-less.
|
|
114
|
+
*/
|
|
115
|
+
private ensureSessionId;
|
|
116
|
+
/**
|
|
117
|
+
* Close the session this modifier opened, exactly once, at the end of
|
|
118
|
+
* the run (success digest, save-disabled exit, or failure rollback).
|
|
119
|
+
* No-ops when the session was supplied by an orchestrator (it owns the
|
|
120
|
+
* lifecycle) or when we never opened one. Best-effort.
|
|
121
|
+
*/
|
|
122
|
+
private closeSelfOpenedSession;
|
|
123
|
+
private runFetchContext;
|
|
124
|
+
private runSaveMemory;
|
|
125
|
+
private resolveSettings;
|
|
126
|
+
private buildSummary;
|
|
127
|
+
private buildTags;
|
|
128
|
+
private buildFailureSummary;
|
|
129
|
+
private buildFailureTags;
|
|
130
|
+
private looksLikeCancellation;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export { FETCH_CONTEXT_STEP_ID, MemoryPipelineModifierPlugin, type MemoryPipelineModifierSettings, SAVE_MEMORY_STEP_ID, MemoryPipelineModifierPlugin as default };
|