@goondan/openharness-base 0.1.8 → 0.1.9

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,84 @@
1
+ import { Extension, LlmChatOptions, Message, ToolDefinition } from '@goondan/openharness-types';
2
+
3
+ /**
4
+ * BasicSystemPrompt extension — prepends a system message to the conversation
5
+ * at the start of every turn.
6
+ *
7
+ * Uses a fixed message ID so the system prompt is only appended once;
8
+ * subsequent turns detect the existing message and skip the append.
9
+ *
10
+ * Priority 10 (HIGH) ensures it runs before other turn middleware.
11
+ */
12
+ declare function BasicSystemPrompt(text: string): Extension;
13
+
14
+ /**
15
+ * MessageWindow extension — truncates conversation history to keep only
16
+ * the most recent `maxMessages` messages before each step.
17
+ */
18
+ declare function MessageWindow(config: {
19
+ maxMessages: number;
20
+ }): Extension;
21
+
22
+ /**
23
+ * CompactionSummarize extension — when message count exceeds `threshold`,
24
+ * removes the oldest messages and replaces them with an LLM-generated summary.
25
+ *
26
+ * By default, uses the agent's own LLM (`ctx.llm`) to produce the summary.
27
+ * A custom `summarizer` callback can override this for advanced use cases
28
+ * (e.g. using a cheaper model, external API, or deterministic logic).
29
+ *
30
+ * @param config.threshold - Trigger compaction when messages exceed this count.
31
+ * @param config.summaryPrompt - Custom system prompt for the LLM summarizer.
32
+ * @param config.summarizer - Optional override: produce summary text from messages.
33
+ */
34
+ declare function CompactionSummarize(config: {
35
+ threshold: number;
36
+ summaryPrompt?: string;
37
+ /** LLM options for the summarization call (e.g. model override for cheaper summarization). */
38
+ llmOptions?: LlmChatOptions;
39
+ summarizer?: (messages: Message[]) => Promise<string>;
40
+ }): Extension;
41
+
42
+ /**
43
+ * Logging extension — subscribes to core events and logs them.
44
+ */
45
+ declare function Logging(config?: {
46
+ logger?: (msg: string) => void;
47
+ }): Extension;
48
+
49
+ /**
50
+ * ToolSearch extension — registers a meta-tool `search_tools` that searches
51
+ * registered tool names and descriptions by keyword.
52
+ */
53
+ declare function ToolSearch(): Extension;
54
+
55
+ /**
56
+ * RequiredToolsGuard extension — blocks a turn if any required tools are
57
+ * not registered.
58
+ */
59
+ declare function RequiredToolsGuard(config: {
60
+ tools: string[];
61
+ }): Extension;
62
+
63
+ interface BashToolConfig {
64
+ timeout?: number;
65
+ maxBuffer?: number;
66
+ }
67
+ declare function BashTool(config?: BashToolConfig): ToolDefinition;
68
+
69
+ declare function FileReadTool(): ToolDefinition;
70
+ declare function FileWriteTool(): ToolDefinition;
71
+ declare function FileListTool(): ToolDefinition;
72
+
73
+ declare function HttpFetchTool(): ToolDefinition;
74
+
75
+ declare function JsonQueryTool(): ToolDefinition;
76
+
77
+ declare function TextTransformTool(): ToolDefinition;
78
+
79
+ interface WaitToolConfig {
80
+ maxMs?: number;
81
+ }
82
+ declare function WaitTool(config?: WaitToolConfig): ToolDefinition;
83
+
84
+ export { BashTool, type BashToolConfig, BasicSystemPrompt, CompactionSummarize, FileListTool, FileReadTool, FileWriteTool, HttpFetchTool, JsonQueryTool, Logging, MessageWindow, RequiredToolsGuard, TextTransformTool, ToolSearch, WaitTool, type WaitToolConfig };
package/dist/index.js ADDED
@@ -0,0 +1,537 @@
1
+ // src/extensions/basic-system-prompt.ts
2
+ var SYSTEM_MESSAGE_ID = "sys-basic-system-prompt";
3
+ function BasicSystemPrompt(text) {
4
+ return {
5
+ name: "basic-system-prompt",
6
+ register(api) {
7
+ api.pipeline.register(
8
+ "turn",
9
+ async (ctx, next) => {
10
+ const alreadyExists = ctx.conversation.messages.some(
11
+ (m) => m.id === SYSTEM_MESSAGE_ID
12
+ );
13
+ if (!alreadyExists) {
14
+ ctx.conversation.emit({
15
+ type: "append",
16
+ message: {
17
+ id: SYSTEM_MESSAGE_ID,
18
+ data: {
19
+ role: "system",
20
+ content: text
21
+ },
22
+ metadata: {
23
+ __createdBy: "basic-system-prompt"
24
+ }
25
+ }
26
+ });
27
+ }
28
+ return next();
29
+ },
30
+ { priority: 10 }
31
+ );
32
+ }
33
+ };
34
+ }
35
+
36
+ // src/extensions/message-window.ts
37
+ function MessageWindow(config) {
38
+ return {
39
+ name: "message-window",
40
+ register(api) {
41
+ api.pipeline.register("step", async (ctx, next) => {
42
+ if (ctx.conversation.messages.length > config.maxMessages) {
43
+ ctx.conversation.emit({
44
+ type: "truncate",
45
+ keepLast: config.maxMessages
46
+ });
47
+ }
48
+ return next();
49
+ });
50
+ }
51
+ };
52
+ }
53
+
54
+ // src/extensions/compaction-summarize.ts
55
+ import { randomUUID } from "crypto";
56
+ var DEFAULT_SUMMARY_PROMPT = "You are a conversation compactor. Summarize the following messages into a concise summary that preserves all important context, decisions, facts, and action items. Be thorough but brief. Output only the summary text, nothing else.";
57
+ function messageToText(m) {
58
+ const role = m.data.role;
59
+ const content = typeof m.data.content === "string" ? m.data.content : JSON.stringify(m.data.content);
60
+ return `[${role}]: ${content}`;
61
+ }
62
+ function CompactionSummarize(config) {
63
+ return {
64
+ name: "compaction-summarize",
65
+ register(api) {
66
+ api.pipeline.register("step", async (ctx, next) => {
67
+ const messages = ctx.conversation.messages;
68
+ if (messages.length > config.threshold) {
69
+ const keepCount = Math.floor(config.threshold / 2);
70
+ const removeCount = messages.length - keepCount;
71
+ const toRemove = messages.slice(0, removeCount);
72
+ let summaryText;
73
+ if (config.summarizer) {
74
+ summaryText = await config.summarizer([...toRemove]);
75
+ } else {
76
+ const transcript = toRemove.map(messageToText).join("\n");
77
+ const prompt = config.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT;
78
+ const llmResponse = await ctx.llm.chat(
79
+ [
80
+ { id: `compaction-sys-${randomUUID()}`, data: { role: "system", content: prompt }, metadata: {} },
81
+ { id: `compaction-usr-${randomUUID()}`, data: { role: "user", content: transcript }, metadata: {} }
82
+ ],
83
+ [],
84
+ // no tools needed for summarization
85
+ ctx.abortSignal,
86
+ config.llmOptions
87
+ );
88
+ summaryText = llmResponse.text ?? transcript;
89
+ }
90
+ const [firstToRemove, ...restToRemove] = toRemove;
91
+ ctx.conversation.emit({
92
+ type: "remove",
93
+ messageId: firstToRemove.id
94
+ });
95
+ for (const msg of restToRemove) {
96
+ ctx.conversation.emit({ type: "remove", messageId: msg.id });
97
+ }
98
+ ctx.conversation.emit({
99
+ type: "append",
100
+ message: {
101
+ id: `summary-${randomUUID()}`,
102
+ data: {
103
+ role: "system",
104
+ content: `[Summary of earlier conversation]: ${summaryText}`
105
+ },
106
+ metadata: {
107
+ __createdBy: "compaction-summarize"
108
+ }
109
+ }
110
+ });
111
+ }
112
+ return next();
113
+ });
114
+ }
115
+ };
116
+ }
117
+
118
+ // src/extensions/logging.ts
119
+ function Logging(config) {
120
+ const log = config?.logger ?? console.log;
121
+ return {
122
+ name: "logging",
123
+ register(api) {
124
+ api.on("turn.start", (payload) => {
125
+ log(`[turn.start] ${JSON.stringify(payload)}`);
126
+ });
127
+ api.on("turn.done", (payload) => {
128
+ log(`[turn.done] ${JSON.stringify(payload)}`);
129
+ });
130
+ api.on("turn.error", (payload) => {
131
+ log(`[turn.error] ${JSON.stringify(payload)}`);
132
+ });
133
+ api.on("step.start", (payload) => {
134
+ log(`[step.start] ${JSON.stringify(payload)}`);
135
+ });
136
+ api.on("step.done", (payload) => {
137
+ log(`[step.done] ${JSON.stringify(payload)}`);
138
+ });
139
+ api.on("tool.start", (payload) => {
140
+ log(`[tool.start] ${JSON.stringify(payload)}`);
141
+ });
142
+ api.on("tool.done", (payload) => {
143
+ log(`[tool.done] ${JSON.stringify(payload)}`);
144
+ });
145
+ }
146
+ };
147
+ }
148
+
149
+ // src/extensions/tool-search.ts
150
+ function ToolSearch() {
151
+ return {
152
+ name: "tool-search",
153
+ register(api) {
154
+ api.tools.register({
155
+ name: "search_tools",
156
+ description: "Search registered tools by keyword in name or description.",
157
+ parameters: {
158
+ type: "object",
159
+ properties: {
160
+ query: {
161
+ type: "string",
162
+ description: "Keyword to search for in tool names and descriptions."
163
+ }
164
+ },
165
+ required: ["query"]
166
+ },
167
+ handler: async (args) => {
168
+ const query = args["query"].toLowerCase();
169
+ const allTools = api.tools.list();
170
+ const matching = allTools.filter(
171
+ (t) => t.name.toLowerCase().includes(query) || t.description.toLowerCase().includes(query)
172
+ );
173
+ return { type: "json", data: matching };
174
+ }
175
+ });
176
+ }
177
+ };
178
+ }
179
+
180
+ // src/extensions/required-tools-guard.ts
181
+ function RequiredToolsGuard(config) {
182
+ return {
183
+ name: "required-tools-guard",
184
+ register(api) {
185
+ api.pipeline.register("turn", async (ctx, next) => {
186
+ const registered = api.tools.list().map((t) => t.name);
187
+ const missing = config.tools.filter((name) => !registered.includes(name));
188
+ if (missing.length > 0) {
189
+ throw new Error(
190
+ `RequiredToolsGuard: missing required tools: ${missing.join(", ")}`
191
+ );
192
+ }
193
+ return next();
194
+ });
195
+ }
196
+ };
197
+ }
198
+
199
+ // src/tools/bash.ts
200
+ import { exec } from "child_process";
201
+ function BashTool(config = {}) {
202
+ const { timeout = 3e4, maxBuffer = 1024 * 1024 } = config;
203
+ return {
204
+ name: "bash",
205
+ description: "Execute a shell command and return its output.",
206
+ parameters: {
207
+ type: "object",
208
+ properties: {
209
+ command: { type: "string", description: "The shell command to execute." },
210
+ cwd: { type: "string", description: "Optional working directory for the command." }
211
+ },
212
+ required: ["command"]
213
+ },
214
+ async handler(args, _ctx) {
215
+ const command = args["command"];
216
+ const cwd = args["cwd"];
217
+ return new Promise((resolve) => {
218
+ exec(command, { timeout, maxBuffer, cwd }, (error, stdout, stderr) => {
219
+ if (error) {
220
+ resolve({ type: "error", error: stderr || error.message });
221
+ } else {
222
+ resolve({ type: "text", text: stdout });
223
+ }
224
+ });
225
+ });
226
+ }
227
+ };
228
+ }
229
+
230
+ // src/tools/file-system.ts
231
+ import { readFile, writeFile, readdir } from "fs/promises";
232
+ function FileReadTool() {
233
+ return {
234
+ name: "file_read",
235
+ description: "Read the contents of a file.",
236
+ parameters: {
237
+ type: "object",
238
+ properties: {
239
+ path: { type: "string", description: "Absolute or relative path to the file to read." },
240
+ encoding: {
241
+ type: "string",
242
+ enum: ["utf8", "base64"],
243
+ description: "File encoding. Defaults to utf8."
244
+ }
245
+ },
246
+ required: ["path"]
247
+ },
248
+ async handler(args, _ctx) {
249
+ const filePath = args["path"];
250
+ const encoding = args["encoding"] ?? "utf8";
251
+ try {
252
+ const content = await readFile(filePath, { encoding });
253
+ return { type: "text", text: content };
254
+ } catch (err) {
255
+ return { type: "error", error: err.message };
256
+ }
257
+ }
258
+ };
259
+ }
260
+ function FileWriteTool() {
261
+ return {
262
+ name: "file_write",
263
+ description: "Write content to a file, creating or overwriting it.",
264
+ parameters: {
265
+ type: "object",
266
+ properties: {
267
+ path: { type: "string", description: "Absolute or relative path to the file to write." },
268
+ content: { type: "string", description: "The content to write to the file." }
269
+ },
270
+ required: ["path", "content"]
271
+ },
272
+ async handler(args, _ctx) {
273
+ const filePath = args["path"];
274
+ const content = args["content"];
275
+ try {
276
+ await writeFile(filePath, content, "utf8");
277
+ return { type: "text", text: `File written: ${filePath}` };
278
+ } catch (err) {
279
+ return { type: "error", error: err.message };
280
+ }
281
+ }
282
+ };
283
+ }
284
+ function FileListTool() {
285
+ return {
286
+ name: "file_list",
287
+ description: "List files and directories in a given directory.",
288
+ parameters: {
289
+ type: "object",
290
+ properties: {
291
+ path: { type: "string", description: "Absolute or relative path to the directory to list." }
292
+ },
293
+ required: ["path"]
294
+ },
295
+ async handler(args, _ctx) {
296
+ const dirPath = args["path"];
297
+ try {
298
+ const entries = await readdir(dirPath, { withFileTypes: true });
299
+ const result = entries.map((e) => ({
300
+ name: e.name,
301
+ type: e.isDirectory() ? "directory" : "file"
302
+ }));
303
+ return { type: "json", data: result };
304
+ } catch (err) {
305
+ return { type: "error", error: err.message };
306
+ }
307
+ }
308
+ };
309
+ }
310
+
311
+ // src/tools/http-fetch.ts
312
+ function HttpFetchTool() {
313
+ return {
314
+ name: "http_fetch",
315
+ description: "Perform an HTTP request and return the response.",
316
+ parameters: {
317
+ type: "object",
318
+ properties: {
319
+ url: { type: "string", description: "The URL to fetch." },
320
+ method: {
321
+ type: "string",
322
+ enum: ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"],
323
+ description: "HTTP method. Defaults to GET."
324
+ },
325
+ headers: {
326
+ type: "object",
327
+ additionalProperties: { type: "string" },
328
+ description: "Optional request headers."
329
+ },
330
+ body: { type: "string", description: "Optional request body." }
331
+ },
332
+ required: ["url"]
333
+ },
334
+ async handler(args, _ctx) {
335
+ const url = args["url"];
336
+ const method = args["method"] ?? "GET";
337
+ const headers = args["headers"] ?? {};
338
+ const body = args["body"];
339
+ try {
340
+ const response = await fetch(url, {
341
+ method,
342
+ headers,
343
+ body: body !== void 0 ? body : void 0
344
+ });
345
+ const responseHeaders = {};
346
+ response.headers.forEach((value, key) => {
347
+ responseHeaders[key] = value;
348
+ });
349
+ let responseBody;
350
+ const contentType = response.headers.get("content-type") ?? "";
351
+ if (contentType.includes("application/json")) {
352
+ responseBody = await response.json();
353
+ } else {
354
+ responseBody = await response.text();
355
+ }
356
+ return {
357
+ type: "json",
358
+ data: {
359
+ status: response.status,
360
+ headers: responseHeaders,
361
+ body: responseBody
362
+ }
363
+ };
364
+ } catch (err) {
365
+ return { type: "error", error: err.message };
366
+ }
367
+ }
368
+ };
369
+ }
370
+
371
+ // src/tools/json-query.ts
372
+ function jsonQuery(data, path) {
373
+ let normalized = path.trim();
374
+ if (normalized.startsWith("$.")) {
375
+ normalized = normalized.slice(2);
376
+ } else if (normalized === "$") {
377
+ return data;
378
+ } else if (normalized.startsWith("$")) {
379
+ normalized = normalized.slice(1);
380
+ }
381
+ if (normalized === "" || normalized === ".") {
382
+ return data;
383
+ }
384
+ const segments = [];
385
+ const normalized2 = normalized.replace(/\[(\d+)\]/g, ".$1").replace(/\[['"](.+?)['"]\]/g, ".$1");
386
+ for (const part of normalized2.split(".")) {
387
+ if (part === "") continue;
388
+ const num = Number(part);
389
+ segments.push(Number.isInteger(num) && String(num) === part ? num : part);
390
+ }
391
+ let current = data;
392
+ for (const segment of segments) {
393
+ if (current === null || current === void 0) return void 0;
394
+ if (typeof current === "object") {
395
+ current = current[segment];
396
+ } else {
397
+ return void 0;
398
+ }
399
+ }
400
+ return current;
401
+ }
402
+ function JsonQueryTool() {
403
+ return {
404
+ name: "json_query",
405
+ description: "Query JSON data using a simple JSONPath-like path expression.",
406
+ parameters: {
407
+ type: "object",
408
+ properties: {
409
+ data: { description: "The JSON data to query." },
410
+ path: {
411
+ type: "string",
412
+ description: "JSONPath-like path, e.g. $.key.nested[0].field"
413
+ }
414
+ },
415
+ required: ["data", "path"]
416
+ },
417
+ async handler(args, _ctx) {
418
+ const data = args["data"];
419
+ const path = args["path"];
420
+ try {
421
+ const result = jsonQuery(data, path);
422
+ return { type: "json", data: result };
423
+ } catch (err) {
424
+ return { type: "error", error: err.message };
425
+ }
426
+ }
427
+ };
428
+ }
429
+
430
+ // src/tools/text-transform.ts
431
+ function TextTransformTool() {
432
+ return {
433
+ name: "text_transform",
434
+ description: "Apply a transformation operation to a text string.",
435
+ parameters: {
436
+ type: "object",
437
+ properties: {
438
+ text: { type: "string", description: "The input text to transform." },
439
+ operation: {
440
+ type: "string",
441
+ enum: ["uppercase", "lowercase", "trim", "split", "replace"],
442
+ description: "The transformation to apply."
443
+ },
444
+ options: {
445
+ type: "object",
446
+ properties: {
447
+ delimiter: { type: "string", description: "Delimiter for split operation." },
448
+ find: { type: "string", description: "String to find for replace operation." },
449
+ replacement: { type: "string", description: "Replacement string for replace operation." }
450
+ }
451
+ }
452
+ },
453
+ required: ["text", "operation"]
454
+ },
455
+ async handler(args, _ctx) {
456
+ const text = args["text"];
457
+ const operation = args["operation"];
458
+ const options = args["options"] ?? {};
459
+ try {
460
+ switch (operation) {
461
+ case "uppercase":
462
+ return { type: "text", text: text.toUpperCase() };
463
+ case "lowercase":
464
+ return { type: "text", text: text.toLowerCase() };
465
+ case "trim":
466
+ return { type: "text", text: text.trim() };
467
+ case "split": {
468
+ const delimiter = options["delimiter"] ?? " ";
469
+ return { type: "json", data: text.split(delimiter) };
470
+ }
471
+ case "replace": {
472
+ const find = options["find"] ?? "";
473
+ const replacement = options["replacement"] ?? "";
474
+ return { type: "text", text: text.split(find).join(replacement) };
475
+ }
476
+ default:
477
+ return { type: "error", error: `Unknown operation: ${operation}` };
478
+ }
479
+ } catch (err) {
480
+ return { type: "error", error: err.message };
481
+ }
482
+ }
483
+ };
484
+ }
485
+
486
+ // src/tools/wait.ts
487
+ function WaitTool(config = {}) {
488
+ const { maxMs = 6e4 } = config;
489
+ return {
490
+ name: "wait",
491
+ description: "Wait for a specified number of milliseconds before continuing.",
492
+ parameters: {
493
+ type: "object",
494
+ properties: {
495
+ ms: {
496
+ type: "number",
497
+ description: "Number of milliseconds to wait.",
498
+ minimum: 0
499
+ }
500
+ },
501
+ required: ["ms"]
502
+ },
503
+ async handler(args, ctx) {
504
+ const requestedMs = args["ms"];
505
+ const ms = Math.min(requestedMs, maxMs);
506
+ await new Promise((resolve, reject) => {
507
+ const timer = setTimeout(resolve, ms);
508
+ if (ctx.abortSignal.aborted) {
509
+ clearTimeout(timer);
510
+ reject(new Error("Aborted"));
511
+ return;
512
+ }
513
+ ctx.abortSignal.addEventListener("abort", () => {
514
+ clearTimeout(timer);
515
+ reject(new Error("Aborted"));
516
+ });
517
+ });
518
+ return { type: "text", text: `Waited ${ms}ms` };
519
+ }
520
+ };
521
+ }
522
+ export {
523
+ BashTool,
524
+ BasicSystemPrompt,
525
+ CompactionSummarize,
526
+ FileListTool,
527
+ FileReadTool,
528
+ FileWriteTool,
529
+ HttpFetchTool,
530
+ JsonQueryTool,
531
+ Logging,
532
+ MessageWindow,
533
+ RequiredToolsGuard,
534
+ TextTransformTool,
535
+ ToolSearch,
536
+ WaitTool
537
+ };
package/package.json CHANGED
@@ -1,26 +1,31 @@
1
1
  {
2
2
  "name": "@goondan/openharness-base",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "type": "module",
5
+ "types": "./dist/index.d.ts",
5
6
  "exports": {
6
7
  ".": {
7
8
  "import": "./dist/index.js",
8
9
  "types": "./dist/index.d.ts"
9
10
  }
10
11
  },
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "scripts": {
16
+ "build": "tsup src/index.ts --format esm --dts",
17
+ "prepack": "pnpm build",
18
+ "test": "vitest run",
19
+ "typecheck": "tsc --noEmit",
20
+ "clean": "rm -rf dist"
21
+ },
11
22
  "dependencies": {
12
- "@goondan/openharness-types": "0.1.8"
23
+ "@goondan/openharness-types": "workspace:*"
13
24
  },
14
25
  "devDependencies": {
15
26
  "@types/node": "^25.5.0",
16
27
  "tsup": "^8.4.0",
17
28
  "typescript": "^5.7.0",
18
29
  "vitest": "^3.0.0"
19
- },
20
- "scripts": {
21
- "build": "tsup src/index.ts --format esm --dts",
22
- "test": "vitest run",
23
- "typecheck": "tsc --noEmit",
24
- "clean": "rm -rf dist"
25
30
  }
26
- }
31
+ }