@isparling/engram-omp 0.1.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/LICENSE ADDED
@@ -0,0 +1,187 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # @isparling/engram-omp
2
+
3
+ Oh My Pi extension for Engram knowledge capture. It translates Oh My Pi
4
+ lifecycle events into calls to the independently installed `engram` CLI; it
5
+ contains no pack implementation or private knowledge.
6
+
7
+ ```sh
8
+ npm install @isparling/engram-omp @isparling/engram-harness @isparling/engram-cli
9
+ ```
10
+
11
+ ```ts
12
+ import engramExtension from "@isparling/engram-omp";
13
+ ```
14
+
15
+ The independently installed `@isparling/engram-cli` is required for normal
16
+ knowledge capture: the extension shells out to it for both turn-end
17
+ extraction and the `engram_capture` tool, and does not perform any
18
+ transaction work itself.
19
+
20
+ - [INSTALL.md](https://github.com/isparling/engram/blob/main/harness/omp/INSTALL.md) — installing and configuring the extension.
21
+ - [SPEC.md](https://github.com/isparling/engram/blob/main/harness/omp/SPEC.md) — extension behavior and scope.
@@ -0,0 +1,409 @@
1
+ /**
2
+ * Oh My Pi extension for engram knowledge capture.
3
+ *
4
+ * Hooks into the agent lifecycle to extract structured knowledge candidates
5
+ * from settled turns, and registers a voluntary `engram_capture` tool for
6
+ * mid-turn capture.
7
+ *
8
+ * ## Installation
9
+ *
10
+ * Install `@isparling/engram-omp` and point Oh My Pi at it via `--extension`
11
+ * or settings:
12
+ *
13
+ * extensions:
14
+ * - @isparling/engram-omp
15
+ *
16
+ * ## Configuration
17
+ *
18
+ * Environment variables read at session start:
19
+ *
20
+ * ENGRAM_BINDING_REGISTRY (required) path to the engram binding registry
21
+ * ENGRAM_CLI (optional) path to engram CLI binary (default: "engram")
22
+ *
23
+ * ## Design
24
+ *
25
+ * Two capture paths, both converging on the engram transaction pipeline:
26
+ *
27
+ * Hook (agent_end): receives raw turn transcript → builds TurnContext →
28
+ * pipes to `engram capture-from-turn` → pack's
29
+ * extractCandidates() → LLM extraction → submit
30
+ * Tool (engram_capture): agent provides structured kind/statement/topics →
31
+ * builds KnowledgeEnvelopeInput → writes to temp
32
+ * file → calls `engram knowledge submit` → direct
33
+ * submission, no extraction
34
+ *
35
+ * The extension is deliberately thin: it normalizes Oh My Pi events and
36
+ * shells out to the engram CLI for all pack operations. This avoids
37
+ * import-resolution issues between Oh My Pi's extension runtime and
38
+ * engram's separate module layout.
39
+ *
40
+ * @module
41
+ */
42
+
43
+ import { chmod, mkdtemp, open, rm } from "node:fs/promises";
44
+ import { tmpdir } from "node:os";
45
+ import { join } from "node:path";
46
+ import { fileURLToPath } from "node:url";
47
+ import type { HostSessionProvenance, TurnContext, TurnToolCall } from "@isparling/engram-harness/knowledge-types";
48
+
49
+ // ---------------------------------------------------------------------------
50
+ // ExtensionAPI types — mirrors the real omp type from
51
+ // @oh-my-pi/pi-coding-agent/src/extensibility/extensions/types.ts
52
+ // ---------------------------------------------------------------------------
53
+
54
+ export interface ExtensionAPI {
55
+ on(event: "agent_end", handler: (event: AgentEndEvent, ctx: ExtensionContext) => void | Promise<void>): void;
56
+ registerTool(tool: ToolDefinition): void;
57
+ logger: { info: (message: string) => void; warn: (message: string) => void };
58
+ }
59
+
60
+ export interface AgentEndEvent {
61
+ type: "agent_end";
62
+ messages: unknown[];
63
+ willContinue?: boolean;
64
+ sessionId?: string;
65
+ turnIndex?: number;
66
+ timestamp?: string;
67
+ }
68
+
69
+ export interface ExtensionContext {
70
+ sessionId: string;
71
+ cwd: string;
72
+ }
73
+
74
+ export interface ToolDefinition {
75
+ name: string;
76
+ description: string;
77
+ parameters: unknown;
78
+ handler: (params: Record<string, unknown>) => Promise<Record<string, unknown>>;
79
+ }
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // CLI format helpers
83
+ // ---------------------------------------------------------------------------
84
+
85
+ /**
86
+ * Normalize a candidate envelope to CLI IO format.
87
+ *
88
+ * The CLI's `validateKnowledgeEnvelope` expects `submitted_at` (snake_case,
89
+ * YYYY-MM-DD) and rejects `submittedAt` (camelCase) as an unknown field.
90
+ * This helper strips the camelCase variant, sets the snake_case variant,
91
+ * and returns a plain Record suitable for JSON.stringify.
92
+ */
93
+ function toCliCandidate(input: object): Record<string, unknown> {
94
+ const raw = input as Record<string, unknown>;
95
+ const rawDate = raw.submittedAt ?? raw.submitted_at;
96
+ const out: Record<string, unknown> = {};
97
+ for (const key of Object.keys(raw)) {
98
+ if (key !== "submittedAt") out[key] = raw[key];
99
+ }
100
+ out.submitted_at = rawDate !== undefined
101
+ ? String(rawDate).slice(0, 10)
102
+ : new Date().toISOString().slice(0, 10);
103
+ return out;
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // Extension factory
108
+ // ---------------------------------------------------------------------------
109
+
110
+ /**
111
+ * Resolve the engram CLI binary to shell out to.
112
+ *
113
+ * Priority: an explicit ENGRAM_CLI, then the sibling @isparling/engram-cli
114
+ * package when it is installed alongside @isparling/engram-omp, then the
115
+ * `engram` command on PATH.
116
+ */
117
+ function resolveCliPath(): string {
118
+ const explicit = process.env.ENGRAM_CLI;
119
+ if (explicit !== undefined && explicit.length > 0) return explicit;
120
+ try {
121
+ return fileURLToPath(import.meta.resolve("@isparling/engram-cli/bin/engram"));
122
+ } catch {
123
+ return "engram";
124
+ }
125
+ }
126
+
127
+ export default async function engramExtension(api: ExtensionAPI): Promise<void> {
128
+ const cliPath = resolveCliPath();
129
+ const registryPath = process.env.ENGRAM_BINDING_REGISTRY;
130
+
131
+ if (registryPath === undefined || registryPath.length === 0) {
132
+ api.logger.warn("[engram] ENGRAM_BINDING_REGISTRY not set — knowledge capture disabled");
133
+ return;
134
+ }
135
+
136
+ const bindingRegistryPath = registryPath;
137
+
138
+
139
+ // Session identifier — captured from the first agent_end event's ctx.
140
+ // Before that, CLI calls will use "pending" which won't resolve a space;
141
+ // the first agent_end event resolves it.
142
+ let hostSessionId: string | undefined;
143
+
144
+ /** Build env for CLI calls, including the session id resolveActiveSpace requires. */
145
+ function cliEnv(): Record<string, string> {
146
+ return {
147
+ ...(process.env as Record<string, string>),
148
+ ENGRAM_BINDING_REGISTRY: bindingRegistryPath,
149
+ ENGRAM_HOST_SESSION_ID: hostSessionId ?? "pending",
150
+ };
151
+ }
152
+
153
+ // Cached extraction pack id — resolved lazily once a real session id is known.
154
+ let extractionPackId = "work-pack";
155
+ let extractionPackVersion = "0.1.0";
156
+ let extractionSpaceId = "current";
157
+ let resolvedPackId = false;
158
+
159
+ /** Resolve the extraction pack from the active space. Called once on first agent_end. */
160
+ async function resolveExtractionPack(): Promise<void> {
161
+ if (hostSessionId === undefined || resolvedPackId) return;
162
+ try {
163
+ const proc = Bun.spawn([cliPath, "space", "status"], {
164
+ stdout: "pipe",
165
+ stderr: "pipe",
166
+ env: cliEnv(),
167
+ });
168
+ const exitCode = await proc.exited;
169
+ if (exitCode !== 0) return;
170
+ const stdout = await new Response(proc.stdout).text();
171
+ const status = JSON.parse(stdout) as Record<string, unknown>;
172
+ const activeSpaces = status.active_spaces as Record<string, Record<string, unknown>> | undefined;
173
+ if (activeSpaces === undefined) return;
174
+ const space = activeSpaces[hostSessionId];
175
+ if (space === undefined) return;
176
+ extractionSpaceId = String(space.space_id ?? "current");
177
+ const packs = space.packs as Array<Record<string, unknown>> | undefined;
178
+ if (packs === undefined) return;
179
+ const extractPack = packs.find((p) => p.extract === true);
180
+ if (extractPack === undefined) return;
181
+ extractionPackId = String(extractPack.id);
182
+ extractionPackVersion = String(extractPack.version);
183
+ resolvedPackId = true;
184
+ } catch {
185
+ // Keep defaults
186
+ }
187
+ }
188
+
189
+
190
+ // -----------------------------------------------------------------------
191
+ // Structural capture: agent_end hook
192
+ // -----------------------------------------------------------------------
193
+ api.on("agent_end", async (event: AgentEndEvent, ctx: ExtensionContext) => {
194
+ // Capture the real session id from the first event; resolves the
195
+ // extraction pack lazily now that we can query the right space.
196
+ hostSessionId = ctx.sessionId;
197
+ await resolveExtractionPack();
198
+
199
+ // Guard: skip auto-retry/continuation settles
200
+ if (event.willContinue === true) return;
201
+ if (!Array.isArray(event.messages) || event.messages.length === 0) return;
202
+
203
+ const turn = buildTurnContext(event);
204
+ if (turn === undefined) return;
205
+
206
+
207
+ // CLI fallback path
208
+ try {
209
+ const proc = Bun.spawn([cliPath, "capture-from-turn"], {
210
+ stdin: "pipe",
211
+ stdout: "pipe",
212
+ stderr: "pipe",
213
+ env: cliEnv(),
214
+ });
215
+ await proc.stdin.write(JSON.stringify(turn) + "\n");
216
+ await proc.stdin.end();
217
+
218
+ const exitCode = await proc.exited;
219
+ if (exitCode !== 0) {
220
+ const stdout = await new Response(proc.stdout).text();
221
+ const stderr = await new Response(proc.stderr).text();
222
+ api.logger.warn(`[engram] capture-from-turn failed (exit ${exitCode}): ${(stdout || stderr).slice(0, 500)}`);
223
+ }
224
+ } catch (err) {
225
+ api.logger.warn(`[engram] failed to invoke engram CLI: ${err}`);
226
+ }
227
+ });
228
+
229
+ // -----------------------------------------------------------------------
230
+ // Status tool: report loaded pack and mode
231
+ // -----------------------------------------------------------------------
232
+ api.registerTool({
233
+ name: "engram_status",
234
+ description: "Report the binding-selected pack identity and CLI mode.",
235
+ parameters: { type: "object", properties: {} },
236
+ handler: async () => ({
237
+ pack_id: resolvedPackId ? extractionPackId : null,
238
+ pack_version: resolvedPackId ? extractionPackVersion : null,
239
+ mode: "cli",
240
+ }),
241
+ });
242
+
243
+ // -----------------------------------------------------------------------
244
+ // Voluntary capture: engram_capture tool
245
+ // -----------------------------------------------------------------------
246
+ api.registerTool({
247
+ name: "engram_capture",
248
+ description: `Submit a structured knowledge observation from the current session.
249
+ Use this to record decisions, outcomes, risks, or notable events mid-turn
250
+ rather than waiting for end-of-turn extraction. Bypasses the pack's
251
+ extraction pipeline — the agent provides the classification directly.
252
+
253
+ Parameters:
254
+ - kind: one of "evidence", "claim", "interpretation", "decision", "recommendation"
255
+ - statement: free-form description of the observation
256
+ - scope_topics: array of topic tags (e.g. ["work:decision", "work:architecture"])
257
+ - subjects: array of subject identifiers (optional)`,
258
+ parameters: {
259
+ type: "object",
260
+ properties: {
261
+ kind: { type: "string", enum: ["evidence", "claim", "interpretation", "decision", "recommendation"] },
262
+ statement: { type: "string", minLength: 1 },
263
+ scope_topics: { type: "array", items: { type: "string" }, default: [] },
264
+ subjects: { type: "array", items: { type: "string" }, default: [] },
265
+ },
266
+ required: ["kind", "statement"],
267
+ },
268
+ handler: async (params: Record<string, unknown>) => {
269
+ const id = `capture-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
270
+ const envelope = {
271
+ id,
272
+ kind: String(params.kind ?? "claim"),
273
+ status: "candidate" as const,
274
+ disposition: "new" as const,
275
+ scope: {
276
+ space: extractionSpaceId,
277
+ subjects: Array.isArray(params.subjects) ? params.subjects.map(String) : [],
278
+ topics: Array.isArray(params.scope_topics) ? params.scope_topics.map(String) : [],
279
+ contexts: [] as string[],
280
+ dimensions: {} as Record<string, string[]>,
281
+ },
282
+ pack: { id: extractionPackId, version: extractionPackVersion },
283
+ sources: [{ type: "engram-capture-tool" as const, ref: `session:${registryPath}` }],
284
+ session: { id: hostSessionId ?? "pending", host: "omp" as const },
285
+ submittedAt: new Date().toISOString(),
286
+ details: {} as Record<string, unknown>,
287
+ statement: String(params.statement ?? ""),
288
+ };
289
+
290
+
291
+ const cliCandidate = toCliCandidate(envelope);
292
+ let candidateDir: string | undefined;
293
+ try {
294
+ candidateDir = await mkdtemp(join(tmpdir(), "engram-candidate-"));
295
+ await chmod(candidateDir, 0o700);
296
+ const tmpFile = join(candidateDir, "candidate.json");
297
+ const file = await open(tmpFile, "wx", 0o600);
298
+ try {
299
+ await file.writeFile(JSON.stringify(cliCandidate), "utf8");
300
+ } finally {
301
+ await file.close();
302
+ }
303
+ const proc = Bun.spawn([cliPath, "knowledge", "submit", "--candidate", tmpFile], {
304
+ stdout: "pipe",
305
+ stderr: "pipe",
306
+ env: cliEnv(),
307
+ });
308
+ const exitCode = await proc.exited;
309
+ const stdout = await new Response(proc.stdout).text();
310
+ const stderr = await new Response(proc.stderr).text();
311
+ if (exitCode === 0) return { status: "submitted", detail: stdout, id };
312
+ return { status: "error", detail: (stdout || stderr).slice(0, 1000), id };
313
+ } catch (error) {
314
+ return { status: "error", detail: String(error).slice(0, 1000), id };
315
+ } finally {
316
+ if (candidateDir !== undefined) await rm(candidateDir, { recursive: true, force: true });
317
+ }
318
+ },
319
+ });
320
+ }
321
+
322
+ // ---------------------------------------------------------------------------
323
+ // TurnContext builder
324
+ // ---------------------------------------------------------------------------
325
+
326
+ function buildTurnContext(event: AgentEndEvent): TurnContext | undefined {
327
+ const messages = event.messages;
328
+ if (!Array.isArray(messages) || messages.length === 0) return undefined;
329
+
330
+ const session: HostSessionProvenance = {
331
+ id: String(event.sessionId ?? "unknown"),
332
+ host: "omp",
333
+ };
334
+
335
+ const turnIndex = typeof event.turnIndex === "number" ? event.turnIndex : 0;
336
+ const timestamp = event.timestamp ?? new Date().toISOString();
337
+
338
+ const narrativeParts: string[] = [];
339
+ const toolCalls: TurnToolCall[] = [];
340
+
341
+ for (const raw of messages as Array<Record<string, unknown>>) {
342
+ const role = String(raw.role ?? "");
343
+ const content = extractTextContent(raw);
344
+
345
+ if (role === "user") {
346
+ narrativeParts.push(`User: ${content}`);
347
+ } else if (role === "assistant") {
348
+ narrativeParts.push(`Assistant: ${content}`);
349
+ const toolCallsData = raw.tool_calls ?? raw.toolCalls;
350
+ if (Array.isArray(toolCallsData)) {
351
+ for (const tc of toolCallsData) {
352
+ const tcr = tc as Record<string, unknown>;
353
+ const toolName = String(tcr.name ?? (tcr.function as Record<string, unknown>)?.name ?? "unknown");
354
+ const toolInput = tcr.input ?? (tcr.function as Record<string, unknown>)?.arguments ?? {};
355
+ toolCalls.push({
356
+ tool: toolName,
357
+ input: typeof toolInput === "string" ? { raw: toolInput } : (toolInput as Record<string, unknown>),
358
+ result: undefined,
359
+ });
360
+ }
361
+ }
362
+ if (content.length > 0) {
363
+ toolCalls.push({ tool: "respond", input: { content: content.slice(0, 200) }, result: undefined });
364
+ }
365
+ } else if (role === "tool" || role === "tool_result") {
366
+ const toolName = String(raw.name ?? raw.tool_name ?? "tool");
367
+ const result = raw.content ?? raw.result;
368
+ narrativeParts.push(`Tool ${toolName}: returned`);
369
+ const pending = [...toolCalls].reverse().find((tc) => tc.tool === toolName && tc.result === undefined);
370
+ if (pending) {
371
+ pending.result = typeof result === "string" ? result.slice(0, 500) : result;
372
+ } else {
373
+ toolCalls.push({
374
+ tool: toolName,
375
+ input: {},
376
+ result: typeof result === "string" ? result.slice(0, 500) : result,
377
+ });
378
+ }
379
+ }
380
+ }
381
+
382
+ return {
383
+ session,
384
+ turnIndex,
385
+ timestamp: String(timestamp ?? new Date().toISOString()),
386
+ narrative: narrativeParts.join("\n"),
387
+ toolCalls,
388
+ };
389
+ }
390
+
391
+ function extractTextContent(msg: Record<string, unknown>): string {
392
+ if (typeof msg.content === "string") return msg.content;
393
+ if (Array.isArray(msg.content)) {
394
+ return msg.content
395
+ .map((block: Record<string, unknown>) => {
396
+ if (block.type === "text" && typeof block.text === "string") return block.text;
397
+ if (block.type === "text" && typeof block.content === "string") return block.content;
398
+ return "";
399
+ })
400
+ .filter(Boolean)
401
+ .join("\n");
402
+ }
403
+ if (typeof msg.content === "object" && msg.content !== null) {
404
+ const inner = msg.content as Record<string, unknown>;
405
+ if (typeof inner.text === "string") return inner.text;
406
+ if (typeof inner.content === "string") return inner.content;
407
+ }
408
+ return "";
409
+ }
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "@isparling/engram-omp",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "description": "Oh My Pi extension for Engram knowledge capture.",
8
+ "exports": {
9
+ ".": { "import": "./omp-extension.ts" },
10
+ "./types": { "import": "./omp-extension.ts" }
11
+ },
12
+ "files": ["omp-extension.ts", "README.md"],
13
+ "peerDependencies": {
14
+ "@isparling/engram-harness": "^0.1.0"
15
+ },
16
+ "publishConfig": { "access": "public" }
17
+ }