@jwitmann/operator-deepseek 0.0.0-stage → 0.4.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/dist/tool.js ADDED
@@ -0,0 +1,708 @@
1
+ // ../core/src/utils.ts
2
+ function success(value) {
3
+ return { ok: true, value };
4
+ }
5
+ function failure(error) {
6
+ return { ok: false, error };
7
+ }
8
+ function hasNodeErrorCode(error, code) {
9
+ return error instanceof Error && "code" in error && error.code === code;
10
+ }
11
+ function getErrorMessage(error) {
12
+ return error instanceof Error ? error.message : String(error);
13
+ }
14
+ function isRecord(value) {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16
+ }
17
+ function readString(value, key) {
18
+ const field = value[key];
19
+ return typeof field === "string" ? field : null;
20
+ }
21
+
22
+ // ../core/src/context/compiler.ts
23
+ var TOKEN_RE = /[a-zA-Z]+|[0-9]+|[^\sa-zA-Z0-9]|\s+/g;
24
+ var ANSI_RE = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;
25
+ var CONTROL_RE = /[\x00-\x08\x0b-\x1f\x7f-\x9f]/g;
26
+ function isHighSurrogate(code) {
27
+ return code >= 55296 && code <= 56319;
28
+ }
29
+ function completeCodePointAtEnd(text) {
30
+ return isHighSurrogate(text.charCodeAt(text.length - 1)) ? text.slice(0, -1) : text;
31
+ }
32
+ function tokenize(text) {
33
+ return text.match(TOKEN_RE) ?? [];
34
+ }
35
+ function isCjkChar(char) {
36
+ const code = char.codePointAt(0) ?? -1;
37
+ return code >= 13312 && code <= 19903 || code >= 19968 && code <= 40959 || code >= 63744 && code <= 64255 || code >= 12288 && code <= 12351 || code >= 65280 && code <= 65519 || code >= 12352 && code <= 12543 || code >= 12784 && code <= 12799 || code >= 44032 && code <= 55215 || code >= 4352 && code <= 4607 || code >= 3584 && code <= 3711 || code >= 3712 && code <= 3839 || code >= 2304 && code <= 2431 || code >= 2432 && code <= 2559 || code >= 2560 && code <= 2687 || code >= 2688 && code <= 2815 || code >= 2816 && code <= 2943 || code >= 2944 && code <= 3071 || code >= 3072 && code <= 3199 || code >= 3200 && code <= 3327 || code >= 3328 && code <= 3455 || code >= 3456 && code <= 3583 || code >= 4096 && code <= 4255 || code >= 6016 && code <= 6143;
38
+ }
39
+ function estimateDeepSeekTokens(text) {
40
+ let nonCjk = 0;
41
+ let cjk = 0;
42
+ for (const char of text) {
43
+ if (isCjkChar(char))
44
+ cjk += 1;
45
+ else
46
+ nonCjk += 1;
47
+ }
48
+ return (nonCjk * 3 + cjk * 6) / 10;
49
+ }
50
+ function countTokens(text) {
51
+ let count = 0;
52
+ for (const token of tokenize(text))
53
+ if (token.trim().length > 0)
54
+ count += 1;
55
+ return count;
56
+ }
57
+ function estimateEntryTokens(text) {
58
+ return Math.max(countTokens(text), Math.ceil(estimateDeepSeekTokens(text)));
59
+ }
60
+ function sanitize(text) {
61
+ let out = text;
62
+ if (out.includes("\r"))
63
+ out = out.replaceAll("\r", "");
64
+ if (out.includes("\x1B"))
65
+ out = out.replace(ANSI_RE, "");
66
+ return out.replace(CONTROL_RE, "");
67
+ }
68
+ function truncateTokens(text, limit, ref) {
69
+ const tokens = tokenize(text);
70
+ let count = 0;
71
+ let cut = tokens.length;
72
+ for (let index = 0;index < tokens.length; index += 1) {
73
+ const token = tokens[index] ?? "";
74
+ if (token.trim().length === 0)
75
+ continue;
76
+ count += 1;
77
+ if (count > limit) {
78
+ cut = index;
79
+ break;
80
+ }
81
+ }
82
+ let out = cut >= tokens.length ? text : tokens.slice(0, cut).join("");
83
+ let truncated = cut < tokens.length;
84
+ const maxChars = Math.max(32, limit * 4);
85
+ if (out.length > maxChars) {
86
+ out = completeCodePointAtEnd(out.slice(0, maxChars));
87
+ truncated = true;
88
+ } else if (truncated) {
89
+ out = completeCodePointAtEnd(out);
90
+ }
91
+ if (!truncated)
92
+ return { text, truncated: false };
93
+ out = out.replace(/\s+$/u, "");
94
+ const note = ref === null ? "...(truncated)" : `...(truncated from ${ref})`;
95
+ return { text: out + note, truncated: true };
96
+ }
97
+ function projectToolResultText(blocks) {
98
+ const parts = [];
99
+ if (!Array.isArray(blocks))
100
+ return "";
101
+ for (const block of blocks) {
102
+ if (block === null || block === undefined)
103
+ continue;
104
+ if (!isRecord(block))
105
+ continue;
106
+ if (block.type === "text") {
107
+ const raw = block.text;
108
+ const text = sanitize(typeof raw === "string" ? raw : "");
109
+ if (text.length > 0)
110
+ parts.push(text);
111
+ } else if (block.type === "image")
112
+ parts.push("[image]");
113
+ else if (block.type === "document")
114
+ parts.push("[document]");
115
+ else
116
+ parts.push(`[${String(block.type)}]`);
117
+ }
118
+ return parts.join(`
119
+ `);
120
+ }
121
+ function isCheckpointSource(source) {
122
+ if (!isRecord(source))
123
+ return false;
124
+ if (source.kind === "compact-checkpoint")
125
+ return true;
126
+ return source.kind === "plugin" && source.plugin === "compact";
127
+ }
128
+ var LOW_VALUE_KINDS = new Set(["result", "tool", "media", "note"]);
129
+
130
+ // ../core/src/context/session-compat.ts
131
+ var warnSink = null;
132
+ var warned = new Set;
133
+ function warnOnce(message) {
134
+ if (warned.has(message))
135
+ return;
136
+ warned.add(message);
137
+ try {
138
+ warnSink?.(`[dsh-compaction-vcc] ${message}`);
139
+ } catch {}
140
+ }
141
+ function sessionEvents(session) {
142
+ if (session === null || session === undefined)
143
+ return [];
144
+ if (typeof session !== "object")
145
+ return [];
146
+ const candidate = session;
147
+ if (typeof candidate.snapshotEvents === "function") {
148
+ const events = candidate.snapshotEvents();
149
+ if (events === null || events === undefined) {
150
+ warnOnce("snapshotEvents() returned no array; treating the log as empty");
151
+ return [];
152
+ }
153
+ return events;
154
+ }
155
+ if (candidate.events !== null && candidate.events !== undefined)
156
+ return candidate.events;
157
+ warnOnce("session exposes neither snapshotEvents() nor events; the durable log is unreadable on this host — compaction will not run");
158
+ return [];
159
+ }
160
+ function sessionEventAt(session, seq) {
161
+ if (session === null || session === undefined)
162
+ return;
163
+ if (typeof session !== "object")
164
+ return;
165
+ const candidate = session;
166
+ if (typeof candidate.eventAt === "function") {
167
+ const event = candidate.eventAt(seq);
168
+ return event === null || event === undefined ? undefined : event;
169
+ }
170
+ const events = candidate.events;
171
+ if (events === null || events === undefined)
172
+ return;
173
+ const positional = events[seq];
174
+ if (positional !== undefined && positional?.seq === seq)
175
+ return positional;
176
+ for (const event of events) {
177
+ if (event?.seq === seq)
178
+ return event;
179
+ }
180
+ return positional;
181
+ }
182
+
183
+ // ../core/src/context/recall.ts
184
+ var DEFAULT_MAX_RECALL_TOKENS = 16000;
185
+ var MAX_RECALL_SPAN = 1000;
186
+ function parseSeqSpec(input) {
187
+ const selections = [];
188
+ const errors = [];
189
+ const raw = String(input ?? "").trim();
190
+ if (raw.length === 0)
191
+ return { selections, errors: ["missing seq selection"] };
192
+ for (const part of raw.split(",")) {
193
+ let token = part.trim();
194
+ if (token.length === 0)
195
+ continue;
196
+ token = token.replace(/^\((.*)\)$/u, "$1").trim();
197
+ const match = /^(?:seqs?\s+)?(\d+)(?:\s*-\s*(\d+))?$/iu.exec(token);
198
+ if (match === null) {
199
+ errors.push(`invalid seq selection "${part}"`);
200
+ continue;
201
+ }
202
+ const start = Number(match[1]);
203
+ const end = match[2] === undefined ? start : Number(match[2]);
204
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) {
205
+ errors.push(`seq selection "${part}" is outside the safe integer range`);
206
+ continue;
207
+ }
208
+ if (start < 1) {
209
+ errors.push(`invalid seq selection "${part}" (seq starts at 1)`);
210
+ continue;
211
+ }
212
+ if (end < start) {
213
+ errors.push(`invalid seq range "${part}" (end before start)`);
214
+ continue;
215
+ }
216
+ if (end - start + 1 > MAX_RECALL_SPAN) {
217
+ errors.push(`seq range "${part}" is wider than the ${MAX_RECALL_SPAN}-seq limit`);
218
+ continue;
219
+ }
220
+ selections.push({ start, end });
221
+ }
222
+ return { selections, errors };
223
+ }
224
+ function projectMessageText(message) {
225
+ const parts = [];
226
+ const content = message.content ?? [];
227
+ for (const block of content) {
228
+ if (block === null || block === undefined)
229
+ continue;
230
+ switch (block.type) {
231
+ case "text":
232
+ if (block.text !== undefined && block.text.length > 0)
233
+ parts.push(sanitize(block.text));
234
+ break;
235
+ case "reasoning":
236
+ if (block.text !== undefined && block.text.length > 0) {
237
+ parts.push(`[reasoning]
238
+ ${sanitize(block.text)}`);
239
+ }
240
+ break;
241
+ case "tool-call":
242
+ parts.push(`[tool-call ${block.name ?? "unknown"}]
243
+ ${sanitize(block.arguments ?? "")}`);
244
+ break;
245
+ case "tool-result":
246
+ parts.push(`[tool-result]
247
+ ${projectToolResultText(block.content ?? [])}`);
248
+ break;
249
+ case "image":
250
+ parts.push("[image]");
251
+ break;
252
+ case "document":
253
+ parts.push("[document]");
254
+ break;
255
+ default:
256
+ parts.push(`[${String(block.type)}]`);
257
+ }
258
+ }
259
+ return parts.join(`
260
+ `);
261
+ }
262
+ function expandSelections(selections) {
263
+ const seqs = [];
264
+ const seen = new Set;
265
+ for (const selection of selections) {
266
+ const start = selection?.start;
267
+ const end = selection?.end;
268
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end))
269
+ continue;
270
+ if (start === undefined || end === undefined)
271
+ continue;
272
+ for (let seq = start;seq <= end; seq += 1) {
273
+ if (seen.has(seq))
274
+ continue;
275
+ seen.add(seq);
276
+ seqs.push(seq);
277
+ }
278
+ }
279
+ return seqs;
280
+ }
281
+ function eventSource(event) {
282
+ if (!isRecord(event.data))
283
+ return;
284
+ const source = event.data.source;
285
+ return isRecord(source) ? source : undefined;
286
+ }
287
+ function findCheckpointSeqs(session) {
288
+ const seqs = [];
289
+ for (const event of sessionEvents(session)) {
290
+ if (event.type === "user/message" && isCheckpointSource(eventSource(event))) {
291
+ seqs.push(event.seq);
292
+ }
293
+ }
294
+ return seqs;
295
+ }
296
+ function deriveSessionMessage(session, event) {
297
+ if (!isRecord(session))
298
+ return null;
299
+ const derive = session.deriveEventMessage;
300
+ if (typeof derive !== "function")
301
+ return null;
302
+ const message = Reflect.apply(derive, session, [event]);
303
+ if (!isRecord(message))
304
+ return null;
305
+ const role = message.role;
306
+ const content = message.content;
307
+ if (typeof role !== "string" || !Array.isArray(content))
308
+ return null;
309
+ return { role, content };
310
+ }
311
+ function resolveRecallReference(session, type, id) {
312
+ const raw = String(id ?? "").trim();
313
+ if (type === "seq")
314
+ return parseSeqSpec(raw);
315
+ if (type === "result") {
316
+ const token = raw.replace(/^\((.*)\)$/u, "$1").trim().replace(/^result\s+/iu, "");
317
+ const match = /^(\d+)$/u.exec(token);
318
+ if (match === null) {
319
+ return {
320
+ selections: [],
321
+ errors: [`invalid result reference "${id}" (expected a seq like "3" or "result 3")`]
322
+ };
323
+ }
324
+ const seq = Number(match[1]);
325
+ const event = sessionEventAt(session, seq);
326
+ if (event === undefined || event.seq !== seq) {
327
+ return { selections: [], errors: [`result seq ${seq} not found in this session`] };
328
+ }
329
+ if (event.type !== "tool/result") {
330
+ return { selections: [], errors: [`seq ${seq} is not a tool result (it is ${event.type})`] };
331
+ }
332
+ return { selections: [{ start: seq, end: seq }], errors: [] };
333
+ }
334
+ if (type === "checkpoint") {
335
+ const token = raw.replace(/^\((.*)\)$/u, "$1").trim();
336
+ const bySeq = /^seqs?\s+(\d+)$/iu.exec(token);
337
+ if (bySeq !== null) {
338
+ const seq = Number(bySeq[1]);
339
+ const event = sessionEventAt(session, seq);
340
+ if (event === undefined || event.seq !== seq) {
341
+ return { selections: [], errors: [`checkpoint seq ${seq} not found in this session`] };
342
+ }
343
+ if (!isCheckpointSource(eventSource(event))) {
344
+ return { selections: [], errors: [`seq ${seq} is not a checkpoint node`] };
345
+ }
346
+ return { selections: [{ start: seq, end: seq }], errors: [] };
347
+ }
348
+ const ordinal = token.replace(/^checkpoint\s+/iu, "");
349
+ const match = /^(\d+)$/u.exec(ordinal);
350
+ if (match === null) {
351
+ return {
352
+ selections: [],
353
+ errors: [
354
+ `invalid checkpoint reference "${id}" (expected an ordinal like "1" or "checkpoint 1", or a "seq N" pointer)`
355
+ ]
356
+ };
357
+ }
358
+ const index = Number(match[1]);
359
+ if (!Number.isSafeInteger(index) || index < 1) {
360
+ return { selections: [], errors: [`invalid checkpoint ordinal "${id}"`] };
361
+ }
362
+ const checkpointSeqs = findCheckpointSeqs(session);
363
+ const seq = checkpointSeqs[index - 1];
364
+ if (seq === undefined) {
365
+ return {
366
+ selections: [],
367
+ errors: [
368
+ `checkpoint ${index} not found (this session has ${checkpointSeqs.length} checkpoint(s))`
369
+ ]
370
+ };
371
+ }
372
+ return { selections: [{ start: seq, end: seq }], errors: [] };
373
+ }
374
+ return {
375
+ selections: [],
376
+ errors: [`invalid recall type "${String(type)}" (expected "seq", "result", or "checkpoint")`]
377
+ };
378
+ }
379
+ function recallSession(session, selections, config) {
380
+ const maxRecallTokens = config.maxRecallTokens;
381
+ const requested = expandSelections(selections);
382
+ const entries = [];
383
+ const seqs = [];
384
+ let budget = maxRecallTokens;
385
+ let truncated = false;
386
+ let missing = 0;
387
+ let skipped = 0;
388
+ for (let index = 0;index < requested.length; index += 1) {
389
+ const seq = requested[index];
390
+ if (seq === undefined)
391
+ continue;
392
+ if (budget <= 0) {
393
+ skipped = requested.length - index;
394
+ truncated = true;
395
+ break;
396
+ }
397
+ const event = sessionEventAt(session, seq);
398
+ if (event === undefined || event.seq !== seq) {
399
+ missing += 1;
400
+ entries.push({ seq, text: `[seq ${seq}: not found in this session]` });
401
+ continue;
402
+ }
403
+ const message = deriveSessionMessage(session, event);
404
+ const body = message !== null ? `[seq ${seq}: ${message.role}]
405
+ ${projectMessageText(message)}` : `[seq ${seq}: ${event.type}]
406
+ ${JSON.stringify(event.data ?? null).slice(0, maxRecallTokens * 4)}`;
407
+ const kept = truncateTokens(body, budget, "recall budget");
408
+ budget -= estimateEntryTokens(kept.text);
409
+ if (kept.truncated)
410
+ truncated = true;
411
+ entries.push({ seq, text: kept.text, truncated: kept.truncated });
412
+ seqs.push(seq);
413
+ }
414
+ if (skipped > 0) {
415
+ const firstSkipped = requested[requested.length - skipped];
416
+ entries.push({
417
+ seq: firstSkipped ?? 0,
418
+ text: `[recall budget exhausted: ${skipped} further requested seq(s) not included]`
419
+ });
420
+ }
421
+ return {
422
+ text: entries.map((entry) => entry.text).join(`
423
+
424
+ `),
425
+ entries,
426
+ seqs,
427
+ recalled: seqs.length,
428
+ missing,
429
+ skipped,
430
+ truncated,
431
+ tokens: entries.reduce((total, entry) => total + estimateEntryTokens(entry.text), 0)
432
+ };
433
+ }
434
+
435
+ // ../core/src/context/search.ts
436
+ var DEFAULT_MAX_SEARCH_HITS = 50;
437
+ var MAX_LINES_PER_HIT = 10;
438
+
439
+ class InvalidSearchPatternError extends Error {
440
+ source;
441
+ constructor(source, reason) {
442
+ super(`invalid search pattern ${JSON.stringify(String(source))}: ${reason}`);
443
+ this.name = "InvalidSearchPatternError";
444
+ this.source = String(source);
445
+ }
446
+ }
447
+ function compileSearchPattern(source) {
448
+ const trimmed = String(source ?? "").trim();
449
+ if (trimmed.length === 0)
450
+ throw new InvalidSearchPatternError(source, "pattern is empty");
451
+ try {
452
+ return new RegExp(trimmed, "iu");
453
+ } catch (error) {
454
+ throw new InvalidSearchPatternError(source, error instanceof Error ? error.message : String(error));
455
+ }
456
+ }
457
+ function searchSession(session, patternSource, config) {
458
+ const pattern = compileSearchPattern(patternSource);
459
+ const maxHits = config.maxSearchHits;
460
+ const maxTokens = config.maxRecallTokens;
461
+ const events = sessionEvents(session);
462
+ const hits = [];
463
+ let totalMatches = 0;
464
+ let budget = maxTokens;
465
+ let truncated = false;
466
+ for (let seq = 0;seq < events.length; seq += 1) {
467
+ const event = events[seq];
468
+ if (event === undefined || event.seq !== seq)
469
+ continue;
470
+ const message = deriveSessionMessage(session, event);
471
+ const body = message !== null ? projectMessageText(message) : `[${event.type}]
472
+ ${JSON.stringify(event.data ?? null)}`;
473
+ const lines = body.split(`
474
+ `);
475
+ const matched = [];
476
+ for (let index = 0;index < lines.length; index += 1) {
477
+ const line = lines[index] ?? "";
478
+ if (pattern.test(line))
479
+ matched.push({ line: index + 1, text: sanitize(line) });
480
+ }
481
+ if (matched.length === 0)
482
+ continue;
483
+ totalMatches += 1;
484
+ if (hits.length >= maxHits || budget <= 0) {
485
+ truncated = true;
486
+ continue;
487
+ }
488
+ const header = `[seq ${seq}: ${message !== null ? message.role : event.type}]`;
489
+ const shown = matched.slice(0, MAX_LINES_PER_HIT);
490
+ const more = matched.length - shown.length;
491
+ const block = [
492
+ header,
493
+ ...shown.map((match) => ` ${match.line}: ${match.text}`),
494
+ ...more > 0 ? [` ...(${more} more matching lines in this event)`] : []
495
+ ].join(`
496
+ `);
497
+ const kept = truncateTokens(block, budget, "search budget");
498
+ budget -= estimateEntryTokens(kept.text);
499
+ if (kept.truncated)
500
+ truncated = true;
501
+ hits.push({ seq, kind: message !== null ? message.role : event.type, text: kept.text });
502
+ }
503
+ const omitted = totalMatches - hits.length;
504
+ const lines = [
505
+ `[search "${pattern.source}": ${totalMatches} matching event(s)]`,
506
+ ...hits.map((hit) => hit.text),
507
+ ...omitted > 0 ? [`[${omitted} more matching event(s) omitted — narrow the pattern or use recall]`] : [],
508
+ ...truncated ? ["[search budget exhausted; some hits were cut]"] : []
509
+ ];
510
+ if (hits.length > 0)
511
+ lines.push("[use recall with a (seq N) pointer to restore any hit's full original content]");
512
+ const text = lines.join(`
513
+
514
+ `);
515
+ return {
516
+ pattern: pattern.source,
517
+ totalMatches,
518
+ hits,
519
+ omitted,
520
+ truncated,
521
+ tokens: hits.reduce((total, hit) => total + estimateEntryTokens(hit.text), 0),
522
+ text
523
+ };
524
+ }
525
+
526
+ // src/tool.ts
527
+ import { defineTool } from "@deepseek-ai/dsh-tools";
528
+ var name = "tool-recall";
529
+ var inject = ["tools"];
530
+ function apply(context) {
531
+ const scoped = context;
532
+ scoped.effect(() => {
533
+ const disposers = [
534
+ scoped.tools.register(defineRecallTool()),
535
+ scoped.tools.register(defineSearchTool())
536
+ ];
537
+ return () => {
538
+ for (const dispose of disposers)
539
+ dispose();
540
+ };
541
+ });
542
+ }
543
+ var RECALL_DESCRIPTION = "Restore the exact original content of earlier events in THIS conversation by a typed reference. " + 'type "seq" with a seq selection like "3-7" restores those events; type "result" with the "result N" ' + 'pointer from a tool-call one-liner restores that tool result; type "checkpoint" with an ordinal like "1" ' + '(1 = oldest, as in a "[checkpoint N]" elision line) restores that whole checkpoint. ' + "The durable log is append-only, so recalled content is always the original tokens, including content " + "elided by compaction checkpoints. To find events by keyword or regex instead, use operator-search.";
544
+ var SEARCH_DESCRIPTION = "Search THIS conversation's durable event log by keyword or regular expression (case-insensitive). " + "Every recorded event is searchable, including content elided by compaction checkpoints. " + "Returns the matching events with their (seq N) numbers and the matching lines. " + "Then call operator-recall with a (seq N) pointer to restore any hit's full exact original content.";
545
+ function emptyRecall(text) {
546
+ return { text, recalled: 0, missing: 0, skipped: 0, truncated: false, tokens: 0 };
547
+ }
548
+ function emptySearch(pattern, text) {
549
+ return { text, pattern, totalMatches: 0, omitted: 0, truncated: false, tokens: 0 };
550
+ }
551
+ function formatRecallReply(type, id, recalled) {
552
+ const label = `**operator-recall ${type} ${id}** (${recalled.recalled} event(s), ${recalled.tokens} tokens` + `${recalled.missing > 0 ? `, ${recalled.missing} missing` : ""}` + `${recalled.truncated ? ", budget-truncated" : ""})`;
553
+ return `${label}
554
+
555
+ ${recalled.text}`;
556
+ }
557
+ function formatSearchReply(pattern, found) {
558
+ return `**operator-search ${pattern}** (${found.totalMatches} matching event(s))
559
+
560
+ ${found.text}`;
561
+ }
562
+ function readSession(agent) {
563
+ if (!isRecord(agent))
564
+ return null;
565
+ return agent.session ?? null;
566
+ }
567
+ function defineRecallTool() {
568
+ return defineTool({
569
+ name: "operator-recall",
570
+ description: RECALL_DESCRIPTION,
571
+ parameters: {
572
+ type: {
573
+ type: "string",
574
+ required: true,
575
+ enum: ["seq", "result", "checkpoint"],
576
+ description: 'Reference type: "seq" for events by sequence number, "result" for a tool result by its `result N` pointer, "checkpoint" for a whole checkpoint by ordinal or seq.'
577
+ },
578
+ id: {
579
+ type: "string",
580
+ required: true,
581
+ description: 'Type-dependent reference: "3-7" / "seq 12" for seq; "result 3" or "3" for result; "1" / "checkpoint 1" or "seq 12345" for checkpoint.'
582
+ }
583
+ },
584
+ output: {
585
+ schema: {
586
+ type: "object",
587
+ additionalProperties: false,
588
+ properties: {
589
+ text: { type: "string", required: true },
590
+ recalled: { type: "integer", required: true },
591
+ missing: { type: "integer", required: true },
592
+ skipped: { type: "integer", required: true },
593
+ truncated: { type: "boolean", required: true },
594
+ tokens: { type: "integer", required: true }
595
+ }
596
+ },
597
+ render: (_args, value) => [{ type: "text", text: value.text }]
598
+ },
599
+ async execute(args, exec) {
600
+ if (args.type !== "seq" && args.type !== "result" && args.type !== "checkpoint") {
601
+ return emptyRecall("Missing or invalid input: type must be one of seq, result, checkpoint.");
602
+ }
603
+ if (typeof args.id !== "string" || args.id.trim() === "") {
604
+ return emptyRecall("Missing required input: id.");
605
+ }
606
+ const session = readSession(exec.agent);
607
+ if (session === null) {
608
+ return emptyRecall("recall requires a calling agent with a session.");
609
+ }
610
+ try {
611
+ const resolved = resolveRecallReference(session, args.type, args.id);
612
+ if (resolved.errors.length > 0 || resolved.selections.length === 0) {
613
+ return emptyRecall(resolved.errors.length > 0 ? resolved.errors.join("; ") : "Nothing to recall.");
614
+ }
615
+ const recalled = recallSession(session, resolved.selections, {
616
+ maxRecallTokens: DEFAULT_MAX_RECALL_TOKENS
617
+ });
618
+ return {
619
+ text: formatRecallReply(args.type, args.id, recalled),
620
+ recalled: recalled.recalled,
621
+ missing: recalled.missing,
622
+ skipped: recalled.skipped,
623
+ truncated: recalled.truncated,
624
+ tokens: recalled.tokens
625
+ };
626
+ } catch {
627
+ return emptyRecall("Could not read the session log.");
628
+ }
629
+ },
630
+ presentCall: (args) => ({
631
+ card: "generic",
632
+ title: "Recall events",
633
+ kind: "read",
634
+ rawInput: `${args.type} ${args.id}`
635
+ })
636
+ });
637
+ }
638
+ function defineSearchTool() {
639
+ return defineTool({
640
+ name: "operator-search",
641
+ description: SEARCH_DESCRIPTION,
642
+ parameters: {
643
+ pattern: {
644
+ type: "string",
645
+ required: true,
646
+ description: "Keyword or regular expression to search for (case-insensitive). Escape regex special characters."
647
+ }
648
+ },
649
+ output: {
650
+ schema: {
651
+ type: "object",
652
+ additionalProperties: false,
653
+ properties: {
654
+ text: { type: "string", required: true },
655
+ pattern: { type: "string", required: true },
656
+ totalMatches: { type: "integer", required: true },
657
+ omitted: { type: "integer", required: true },
658
+ truncated: { type: "boolean", required: true },
659
+ tokens: { type: "integer", required: true }
660
+ }
661
+ },
662
+ render: (_args, value) => [{ type: "text", text: value.text }]
663
+ },
664
+ async execute(args, exec) {
665
+ if (typeof args.pattern !== "string" || args.pattern.trim() === "") {
666
+ return emptySearch("", "Missing required input: pattern.");
667
+ }
668
+ const session = readSession(exec.agent);
669
+ if (session === null) {
670
+ return emptySearch(args.pattern, "search requires a calling agent with a session.");
671
+ }
672
+ try {
673
+ const found = searchSession(session, args.pattern, {
674
+ maxSearchHits: DEFAULT_MAX_SEARCH_HITS,
675
+ maxRecallTokens: DEFAULT_MAX_RECALL_TOKENS
676
+ });
677
+ return {
678
+ text: formatSearchReply(args.pattern, found),
679
+ pattern: found.pattern,
680
+ totalMatches: found.totalMatches,
681
+ omitted: found.omitted,
682
+ truncated: found.truncated,
683
+ tokens: found.tokens
684
+ };
685
+ } catch (error) {
686
+ if (error instanceof InvalidSearchPatternError) {
687
+ return emptySearch(args.pattern, `Invalid search pattern: ${error.source}.`);
688
+ }
689
+ return emptySearch(args.pattern, "Could not read the session log.");
690
+ }
691
+ },
692
+ presentCall: (args) => ({
693
+ card: "generic",
694
+ title: "Search history",
695
+ kind: "read",
696
+ rawInput: args.pattern
697
+ })
698
+ });
699
+ }
700
+ export {
701
+ apply,
702
+ defineRecallTool,
703
+ defineSearchTool,
704
+ inject,
705
+ name
706
+ };
707
+
708
+ //# debugId=DC9EC42D892DC67264756E2164756E21