@animalabs/agent-framework 0.13.0 → 0.14.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.
Files changed (44) hide show
  1. package/dist/src/framework.d.ts +31 -4
  2. package/dist/src/framework.d.ts.map +1 -1
  3. package/dist/src/framework.js +327 -49
  4. package/dist/src/framework.js.map +1 -1
  5. package/dist/src/gate/event-gate.d.ts +55 -1
  6. package/dist/src/gate/event-gate.d.ts.map +1 -1
  7. package/dist/src/gate/event-gate.js +41 -1
  8. package/dist/src/gate/event-gate.js.map +1 -1
  9. package/dist/src/gate/index.d.ts +1 -1
  10. package/dist/src/gate/index.d.ts.map +1 -1
  11. package/dist/src/gate/index.js +1 -1
  12. package/dist/src/gate/index.js.map +1 -1
  13. package/dist/src/index.d.ts +1 -1
  14. package/dist/src/index.d.ts.map +1 -1
  15. package/dist/src/index.js.map +1 -1
  16. package/dist/src/tool-image-ledger.d.ts +175 -0
  17. package/dist/src/tool-image-ledger.d.ts.map +1 -0
  18. package/dist/src/tool-image-ledger.js +257 -0
  19. package/dist/src/tool-image-ledger.js.map +1 -0
  20. package/dist/src/tool-result-history.d.ts +15 -2
  21. package/dist/src/tool-result-history.d.ts.map +1 -1
  22. package/dist/src/tool-result-history.js +16 -9
  23. package/dist/src/tool-result-history.js.map +1 -1
  24. package/dist/src/types/agent.d.ts +10 -0
  25. package/dist/src/types/agent.d.ts.map +1 -1
  26. package/dist/test/event-gate.test.js +84 -1
  27. package/dist/test/event-gate.test.js.map +1 -1
  28. package/dist/test/puppet-tool-call.test.js +1 -0
  29. package/dist/test/puppet-tool-call.test.js.map +1 -1
  30. package/dist/test/save-recent-image.test.d.ts +26 -0
  31. package/dist/test/save-recent-image.test.d.ts.map +1 -0
  32. package/dist/test/save-recent-image.test.js +707 -0
  33. package/dist/test/save-recent-image.test.js.map +1 -0
  34. package/dist/test/turn-trigger-provenance.test.js +17 -0
  35. package/dist/test/turn-trigger-provenance.test.js.map +1 -1
  36. package/dist/tsconfig.tsbuildinfo +1 -1
  37. package/package.json +1 -1
  38. package/src/framework.ts +389 -54
  39. package/src/gate/event-gate.ts +71 -3
  40. package/src/gate/index.ts +1 -1
  41. package/src/index.ts +1 -1
  42. package/src/tool-image-ledger.ts +334 -0
  43. package/src/tool-result-history.ts +30 -9
  44. package/src/types/agent.ts +10 -0
@@ -78,6 +78,37 @@ interface PendingEvent {
78
78
  * metadata carries one — batched-wake lines render this instead of the raw
79
79
  * composite channel id. */
80
80
  channelLabel?: string;
81
+ /** Author id of the event (discord snowflake etc.), when the metadata carries
82
+ * one — a debounced wake names the newest such author as its counterparty. */
83
+ authorId?: string;
84
+ /** MCPL server id the event came from — the namespace for the counterparty
85
+ * (`<serverId>:user:<id>`), same as the direct channel-incoming path. */
86
+ serverId?: string;
87
+ /** `chat:addressed` (mention / reply-to-bot / DM): an addressed event outranks
88
+ * newer ambient chatter when a batched wake picks its provenance — the same
89
+ * rule the framework applies to the turn's speech locus. */
90
+ addressed: boolean;
91
+ }
92
+
93
+ /**
94
+ * Where a gate-requested wake came from, handed to the framework alongside the
95
+ * reason so the turn's InferenceRequest can carry it (host telemetry stamps
96
+ * "who woke the agent" from it). Ids only, never content or display names.
97
+ */
98
+ export interface WakeProvenance {
99
+ /** Composite channel id of the chosen event — telemetry only, never a
100
+ * speech locus. Omitted for `mcpl:push-event` events, whose channel ids
101
+ * are raw server ids (unroutable and a second spelling of the same
102
+ * channel); the framework derives the composite id on the direct path. */
103
+ channelId?: string;
104
+ /** Server-namespaced author id: `<serverId>:user:<id>` (falls back to the
105
+ * channel id's first segment only when the event carried no server id). */
106
+ counterparty?: string;
107
+ /** True when the chosen event was `chat:addressed`. */
108
+ addressed?: boolean;
109
+ /** Timestamp (ms) of the chosen event, so a consumer coalescing several
110
+ * requests can order by event recency, not by flush order. */
111
+ at?: number;
81
112
  }
82
113
 
83
114
  interface DebounceState {
@@ -149,6 +180,34 @@ function isMetadataTruthy(value: unknown): boolean {
149
180
  return Boolean(value);
150
181
  }
151
182
 
183
+ /**
184
+ * Provenance of a batched wake: the newest ADDRESSED channel-bearing event
185
+ * wins (mention / reply / DM outranks newer ambient chatter — the framework's
186
+ * own locus rule); else the newest channel-bearing event. Channel, author and
187
+ * addressed all come from that one event, so they can never disagree.
188
+ */
189
+ export function wakeProvenance(events: PendingEvent[]): WakeProvenance | undefined {
190
+ let newest: PendingEvent | undefined;
191
+ let newestAddressed: PendingEvent | undefined;
192
+ for (const e of events) {
193
+ if (!e.channelId && !e.authorId) continue;
194
+ if (!newest || e.timestamp >= newest.timestamp) newest = e;
195
+ if (e.addressed && (!newestAddressed || e.timestamp >= newestAddressed.timestamp)) newestAddressed = e;
196
+ }
197
+ const pick = newestAddressed ?? newest;
198
+ if (!pick) return undefined;
199
+ // push-event channel ids are the adapter's raw ids (a Discord snowflake):
200
+ // not a composite channel id, so not reported as one
201
+ const channelId = pick.channelId && pick.eventType !== 'mcpl:push-event' ? pick.channelId : undefined;
202
+ const ns = pick.serverId || (pick.channelId ? pick.channelId.split(':')[0] : '') || 'channel';
203
+ return {
204
+ ...(channelId ? { channelId } : {}),
205
+ ...(pick.authorId ? { counterparty: `${ns}:user:${pick.authorId}` } : {}),
206
+ ...(pick.addressed ? { addressed: true } : {}),
207
+ at: pick.timestamp,
208
+ };
209
+ }
210
+
152
211
  /** Compact, log-friendly serialization of a GateBehavior. */
153
212
  function formatBehavior(b: import('./types.js').GateBehavior): string {
154
213
  if (typeof b === 'string') return b;
@@ -522,7 +581,7 @@ export class EventGate {
522
581
  /** Registry agent to deliver into; absent = primary (historical). */
523
582
  forAgent?: string,
524
583
  ) => unknown;
525
- private requestInferenceFn: (agentName: string, reason: string, source: string) => void;
584
+ private requestInferenceFn: (agentName: string, reason: string, source: string, provenance?: WakeProvenance) => void;
526
585
  private getAgentNamesFn: () => string[];
527
586
  /** Clock injection — keeps the new rate_limit / passive_sample paths
528
587
  * testable without monkey-patching Date.now globally. */
@@ -539,7 +598,7 @@ export class EventGate {
539
598
  metadata?: Record<string, unknown>,
540
599
  forAgent?: string,
541
600
  ) => unknown;
542
- requestInference: (agentName: string, reason: string, source: string) => void;
601
+ requestInference: (agentName: string, reason: string, source: string, provenance?: WakeProvenance) => void;
543
602
  getAgentNames: () => string[];
544
603
  /** Optional clock — defaults to Date.now. Tests inject for deterministic time. */
545
604
  now?: () => number;
@@ -1385,6 +1444,9 @@ export class EventGate {
1385
1444
  typeof info.metadata?.channelName === 'string' && info.metadata.channelName
1386
1445
  ? (info.metadata.channelName as string)
1387
1446
  : undefined,
1447
+ authorId: this.extractAuthorId(info.metadata) ?? undefined,
1448
+ serverId: info.serverId || undefined,
1449
+ addressed: Array.isArray(info.tags) && info.tags.includes('chat:addressed'),
1388
1450
  };
1389
1451
 
1390
1452
  const existing = this.debounceTimers.get(policy.name);
@@ -1472,8 +1534,14 @@ export class EventGate {
1472
1534
  policies: policyNames,
1473
1535
  });
1474
1536
 
1537
+ // Provenance of the batched wake (telemetry: who/where woke the agent):
1538
+ // the newest ADDRESSED event first, else the newest event naming a
1539
+ // channel or an author; channel + author + addressed from that ONE
1540
+ // event. It does not set the turn's speech locus — the framework keeps
1541
+ // its own routing rule for that.
1542
+ const provenance = wakeProvenance(events);
1475
1543
  for (const agentName of this.getAgentNamesFn()) {
1476
- this.requestInferenceFn(agentName, 'gate:debounce', 'gate');
1544
+ this.requestInferenceFn(agentName, 'gate:debounce', 'gate', provenance);
1477
1545
  }
1478
1546
  }
1479
1547
 
package/src/gate/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { EventGate } from './event-gate.js';
1
+ export { EventGate, wakeProvenance, type WakeProvenance } from './event-gate.js';
2
2
  export type {
3
3
  GateConfig,
4
4
  GateOptions,
package/src/index.ts CHANGED
@@ -76,7 +76,7 @@ export type {
76
76
  export type { SessionUsage, AgentUsage, SessionUsageSnapshot, UsageUpdatedEvent } from './usage/index.js';
77
77
 
78
78
  // EventGate
79
- export { EventGate } from './gate/index.js';
79
+ export { EventGate, type WakeProvenance } from './gate/index.js';
80
80
  export type { GateConfig, GateOptions, GatePolicy, GatePolicyMatch, GateBehavior } from './gate/index.js';
81
81
 
82
82
  // MCPL channel registry (exposed for modules that need channel-level operations)
@@ -0,0 +1,334 @@
1
+ /**
2
+ * Per-agent retention of tool-result images, with provenance (issue #104).
3
+ *
4
+ * History keeps a compact text placeholder for every image a tool returns —
5
+ * the bytes only ever ride the live wire copy of that one turn. That policy
6
+ * is right (megabytes of base64 in the persisted window would be sliced,
7
+ * compressed, and replayed forever), but it left `save_recent_image` with no
8
+ * way to reach an image the resident had just seen: the scanner walked past
9
+ * the byteless placeholder and quietly saved whichever OLDER attachment came
10
+ * next, under the filename the resident chose for the new one.
11
+ *
12
+ * This ledger is the missing half. At ingestion every tool-result image is
13
+ * retained here under a stable per-agent ref (`img_k7x3q2_7`) bound to the
14
+ * exact tool call and block it came from, with its digest. The ref carries a
15
+ * per-ledger nonce: ledgers live and die with the process, but the persisted
16
+ * store keeps yesterday's placeholders visible in context, so a bare sequence
17
+ * number would let a stale `img_7` resolve to whatever this process minted
18
+ * seventh. A stale ref must resolve `unknown`, never to other bytes.
19
+ *
20
+ * The history placeholder carries the ref, so the ordered inventory
21
+ * `save_recent_image` walks can
22
+ * include tool images at their true position — and when the bytes behind a
23
+ * ref are gone (bounded eviction, or a restart: the ledger is in-memory by
24
+ * design, so it never adds to blob growth), the save fails AT THAT INDEX with
25
+ * a specific error instead of sliding to an older image. Silent substitution
26
+ * of bytes from another surface is the failure this exists to end.
27
+ */
28
+
29
+ import { createHash, randomBytes } from 'node:crypto';
30
+ import { safeSlice } from './safe-slice.js';
31
+
32
+ export interface RetainedToolImage {
33
+ /** Stable per-ledger handle (`img_<nonce>_<seq>`), minted once per (toolCallId, blockIndex). */
34
+ ref: string;
35
+ toolCallId: string;
36
+ toolName: string;
37
+ /** Position of the image block inside the tool result's content array. */
38
+ blockIndex: number;
39
+ mediaType: string;
40
+ byteSize: number;
41
+ sha256: string;
42
+ retainedAt: number;
43
+ }
44
+
45
+ /** A retained image whose bytes are still held. */
46
+ export interface RetainedToolImageWithData extends RetainedToolImage {
47
+ /** Base64 payload, exactly as the tool returned it. */
48
+ data: string;
49
+ }
50
+
51
+ export type ToolImageLookup =
52
+ | { status: 'retained'; image: RetainedToolImageWithData }
53
+ /** The ref was issued by this ledger but its bytes were evicted (bounded budget). */
54
+ | { status: 'evicted'; image: RetainedToolImage }
55
+ /** Never issued by this ledger — a typo, or a ref minted before a restart. */
56
+ | { status: 'unknown' };
57
+
58
+ export interface ToolImageLedgerOptions {
59
+ /** Total base64 chars held across retained images (≈ bytes × 4/3). */
60
+ maxChars?: number;
61
+ /** Maximum number of images whose bytes are held. */
62
+ maxEntries?: number;
63
+ }
64
+
65
+ /** 96 MB of base64 ≈ 72 MB of image bytes — a few dozen world snapshots. */
66
+ export const DEFAULT_TOOL_IMAGE_LEDGER_MAX_CHARS = 96 * 1024 * 1024;
67
+ export const DEFAULT_TOOL_IMAGE_LEDGER_MAX_ENTRIES = 64;
68
+
69
+ export class ToolImageLedger {
70
+ /** Namespace for every ref this ledger mints; a fresh ledger (new process,
71
+ * agent re-registration) never shares one with its predecessors. */
72
+ readonly nonce: string = mintLedgerNonce();
73
+ private nextSeq = 1;
74
+ /** Insertion-ordered (oldest first) — eviction pops from the front. */
75
+ private readonly retained = new Map<string, RetainedToolImageWithData>();
76
+ /** Provenance for every ref ever issued, bytes or not (bounded separately). */
77
+ private readonly issued = new Map<string, RetainedToolImage>();
78
+ private readonly refByKey = new Map<string, string>();
79
+ private heldChars = 0;
80
+ private readonly maxChars: number;
81
+ private readonly maxEntries: number;
82
+
83
+ constructor(options: ToolImageLedgerOptions = {}) {
84
+ this.maxChars = options.maxChars ?? DEFAULT_TOOL_IMAGE_LEDGER_MAX_CHARS;
85
+ this.maxEntries = options.maxEntries ?? DEFAULT_TOOL_IMAGE_LEDGER_MAX_ENTRIES;
86
+ }
87
+
88
+ /**
89
+ * Retain one image block from a tool result. Idempotent per
90
+ * (toolCallId, blockIndex) for as long as that block's provenance record
91
+ * is held (bounded — see trimProvenance): within that window the same
92
+ * block always yields the same ref, so a result serialized twice (or
93
+ * retained early in a tool batch, then serialized at commit) agrees with
94
+ * itself. A block re-serialized after its record aged out mints a fresh
95
+ * ref; the old one resolves `evicted`/`unknown`, never to other bytes.
96
+ */
97
+ retain(source: {
98
+ toolCallId: string;
99
+ toolName: string;
100
+ blockIndex: number;
101
+ data: string;
102
+ mediaType: string;
103
+ }): RetainedToolImage {
104
+ const key = `${source.toolCallId}:${source.blockIndex}`;
105
+ const existingRef = this.refByKey.get(key);
106
+ if (existingRef !== undefined) {
107
+ const known = this.issued.get(existingRef);
108
+ if (known) return known;
109
+ }
110
+ const ref = `img_${this.nonce}_${this.nextSeq++}`;
111
+ // Digest without materializing the whole decoded image: a 96MB base64
112
+ // field would otherwise transiently allocate ~72MB more and the ledger
113
+ // would be the one asking for it. Chunked decode keeps the peak small.
114
+ const { byteSize, sha256 } = digestBase64(source.data);
115
+ const image: RetainedToolImageWithData = {
116
+ ref,
117
+ toolCallId: source.toolCallId,
118
+ toolName: source.toolName,
119
+ blockIndex: source.blockIndex,
120
+ // Tools send mime types unvalidated; the placeholder grammar is
121
+ // lowercase, so normalize here and at format time (same rule) or an
122
+ // `Image/PNG` would write a placeholder that never re-parses — an
123
+ // invisible slot, i.e. a silent index slide.
124
+ mediaType: normalizeMediaType(source.mediaType),
125
+ byteSize,
126
+ sha256,
127
+ retainedAt: Date.now(),
128
+ data: source.data,
129
+ };
130
+ const { data: _data, ...provenance } = image;
131
+ this.refByKey.set(key, ref);
132
+ this.issued.set(ref, provenance);
133
+ // A single image over the whole budget is issued (so the placeholder is
134
+ // honest about its provenance) but never held.
135
+ if (source.data.length <= this.maxChars) {
136
+ this.retained.set(ref, image);
137
+ this.heldChars += source.data.length;
138
+ this.evictOverBudget();
139
+ }
140
+ this.trimProvenance();
141
+ return provenance;
142
+ }
143
+
144
+ lookup(ref: string): ToolImageLookup {
145
+ const held = this.retained.get(ref);
146
+ if (held) return { status: 'retained', image: held };
147
+ const known = this.issued.get(ref);
148
+ if (known) return { status: 'evicted', image: known };
149
+ return { status: 'unknown' };
150
+ }
151
+
152
+ /** Ref already minted for this block, if any (no retention side effect). */
153
+ refFor(toolCallId: string, blockIndex: number): string | undefined {
154
+ return this.refByKey.get(`${toolCallId}:${blockIndex}`);
155
+ }
156
+
157
+ /** Count of images whose bytes are currently held. */
158
+ get size(): number {
159
+ return this.retained.size;
160
+ }
161
+
162
+ private evictOverBudget(): void {
163
+ for (const [ref, image] of this.retained) {
164
+ if (this.retained.size <= this.maxEntries && this.heldChars <= this.maxChars) break;
165
+ this.retained.delete(ref);
166
+ this.heldChars -= image.data.length;
167
+ }
168
+ }
169
+
170
+ /** Provenance for evicted refs is kept for a while so the error can name
171
+ * the tool call; bounded so a long-lived agent can't grow it forever. */
172
+ private trimProvenance(): void {
173
+ const keep = Math.max(this.maxEntries * 4, 256);
174
+ while (this.issued.size > keep) {
175
+ const oldest = this.issued.keys().next().value;
176
+ if (oldest === undefined) break;
177
+ const image = this.issued.get(oldest);
178
+ this.issued.delete(oldest);
179
+ if (image) this.refByKey.delete(`${image.toolCallId}:${image.blockIndex}`);
180
+ }
181
+ }
182
+ }
183
+
184
+ /** Six random base36 chars — one per ledger lifetime, embedded in every ref. */
185
+ function mintLedgerNonce(): string {
186
+ return randomBytes(4).readUInt32BE(0).toString(36).padStart(6, '0').slice(-6);
187
+ }
188
+
189
+ /** Grammar of a ref this module mints: `img_<ledger nonce>_<sequence>`. */
190
+ export const TOOL_IMAGE_REF_RE = /^img_[0-9a-z]+_\d+$/;
191
+
192
+ /** RFC 6838 type/subtype token characters (lowercased); no parameters. */
193
+ const MEDIA_TYPE_ESSENCE_RE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/;
194
+ export const FALLBACK_MEDIA_TYPE = 'application/octet-stream';
195
+
196
+ /**
197
+ * The one spelling the placeholder grammar accepts: trimmed, lowercased, the
198
+ * `type/subtype` essence only (parameters such as `; charset=binary` are
199
+ * dropped), and — because `mimeType` arrives from external MCPL servers
200
+ * unvalidated — anything that still is not a well-formed type/subtype falls
201
+ * back to `application/octet-stream`. The invariant this buys: the
202
+ * serializer can NEVER write a placeholder that does not re-parse, so a
203
+ * strange mime can never produce an invisible slot (a silent index slide).
204
+ */
205
+ export function normalizeMediaType(mediaType: string): string {
206
+ const essence = mediaType.split(';', 1)[0]!.trim().toLowerCase();
207
+ return MEDIA_TYPE_ESSENCE_RE.test(essence) ? essence : FALLBACK_MEDIA_TYPE;
208
+ }
209
+
210
+ /** History placeholder for a retained tool image: `[image: image/png, ~691KB, ref img_7]`. */
211
+ export function formatToolImagePlaceholder(mediaType: string, sizeLabel: string, ref: string | null): string {
212
+ const mime = normalizeMediaType(mediaType);
213
+ return ref === null
214
+ ? `[image: ${mime}, ${sizeLabel}]`
215
+ : `[image: ${mime}, ${sizeLabel}, ref ${ref}]`;
216
+ }
217
+
218
+ export type ParsedImagePlaceholder =
219
+ /** An inline tool image the serializer replaced with a placeholder. */
220
+ | {
221
+ kind: 'inline';
222
+ mediaType: string;
223
+ sizeLabel: string;
224
+ /** null for placeholders written before retention existed (unsaveable). */
225
+ ref: string | null;
226
+ /** Character offset in the scanned text — for ordering within a block. */
227
+ offset: number;
228
+ /** The placeholder exactly as it appears in the text. */
229
+ text: string;
230
+ }
231
+ /** An RFC-005 reference stub whose testimony says image — bytes live
232
+ * behind fetch_reference, never in this ledger. Occupies a slot so the
233
+ * index cannot slide past it. */
234
+ | {
235
+ kind: 'reference';
236
+ refId: string;
237
+ /** Mime sniffed from the stub text; null when the stub names none. */
238
+ mediaType: string | null;
239
+ offset: number;
240
+ /** The stub line exactly as it appears in the text. */
241
+ text: string;
242
+ };
243
+
244
+ const PLACEHOLDER_RE = /\[image: ([a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+), (~?[\d.]+(?:B|KB|MB))(?:, ref (img_[0-9a-z]+_\d+))?\]/g;
245
+ /** `[ref_1_ab3d] cam.png — image/png, 1.2MB claimed — from tool result — …` (one line). */
246
+ const REFERENCE_STUB_RE = /^\[(ref_[0-9a-z]+_[0-9a-z]+)\] ([^\n]*)$/gm;
247
+ const IMAGE_MIME_RE = /\bimage\/[a-z0-9!#$&^_.+-]+/i;
248
+
249
+ /**
250
+ * Every image slot in a stored tool-result string, in text order: inline
251
+ * placeholders and image-typed reference stubs. Text-derived and therefore
252
+ * untrusted — a tool result can quote someone else's placeholder verbatim —
253
+ * so the caller MUST cross-check a resolved ref's provenance against the
254
+ * tool_result block it was found in before handing out bytes.
255
+ */
256
+ export function parseImagePlaceholders(text: string): ParsedImagePlaceholder[] {
257
+ const out: ParsedImagePlaceholder[] = [];
258
+ for (const m of text.matchAll(PLACEHOLDER_RE)) {
259
+ out.push({ kind: 'inline', mediaType: m[1]!, sizeLabel: m[2]!, ref: m[3] ?? null, offset: m.index ?? 0, text: m[0] });
260
+ }
261
+ for (const m of text.matchAll(REFERENCE_STUB_RE)) {
262
+ const mime = m[2]!.match(IMAGE_MIME_RE);
263
+ out.push({ kind: 'reference', refId: m[1]!, mediaType: mime ? mime[0].toLowerCase() : null, offset: m.index ?? 0, text: m[0] });
264
+ }
265
+ out.sort((a, b) => a.offset - b.offset);
266
+ return out;
267
+ }
268
+
269
+ /**
270
+ * Cut `text` to at most `cap` chars WITHOUT losing or splitting an image
271
+ * slot. The stored tool_result text is the only place the inventory
272
+ * discovers tool images, while the live wire still delivers every image
273
+ * regardless of text length — so a slot dropped by truncation is an image
274
+ * the resident saw that the index silently slides past (the #104 failure,
275
+ * one representation over). Returns the head to keep and the slots that
276
+ * fell at or past the cut, to be re-appended verbatim after the truncation
277
+ * notice. A slot straddling the cut moves the cut back to its start, so the
278
+ * head never contains a partial slot (a partial reference-stub line would
279
+ * otherwise still re-parse and be counted twice).
280
+ */
281
+ export function splitPreservingImageSlots(text: string, cap: number): { head: string; tail: string[] } {
282
+ const slots = parseImagePlaceholders(text);
283
+ let cutAt = cap;
284
+ for (const slot of slots) {
285
+ if (slot.offset < cutAt && slot.offset + slot.text.length > cutAt) cutAt = slot.offset;
286
+ }
287
+ return {
288
+ head: safeSlice(text, 0, cutAt),
289
+ tail: slots.filter((slot) => slot.offset >= cutAt).map((slot) => slot.text),
290
+ };
291
+ }
292
+
293
+ /** Text to append after a truncation notice so the preserved slots stay
294
+ * parseable (each reference stub on its own line). Empty when none. */
295
+ export function formatPreservedImageSlots(tail: string[]): string {
296
+ if (tail.length === 0) return '';
297
+ return `\n[${tail.length} image slot(s) fell past the cut; kept here in order so save_recent_image still counts them:]\n`
298
+ + tail.join('\n');
299
+ }
300
+
301
+ export function sha256Hex(bytes: Buffer): string {
302
+ return createHash('sha256').update(bytes).digest('hex');
303
+ }
304
+
305
+ /** Only the base64 alphabet, with nothing but trailing `=` padding after it. */
306
+ function isCleanBase64(data: string): boolean {
307
+ const m = /[^A-Za-z0-9+/]/.exec(data);
308
+ if (!m) return true;
309
+ const rest = data.length - m.index;
310
+ return rest <= 2 && /^=+$/.test(data.slice(m.index));
311
+ }
312
+
313
+ /**
314
+ * Byte length and SHA-256 of a base64 payload, decoded in 4-char-aligned
315
+ * chunks so the peak allocation stays at one chunk rather than the whole
316
+ * image. Falls back to a whole decode when the string carries whitespace
317
+ * or embedded padding (chunk alignment would no longer be trustworthy) —
318
+ * the digest must describe exactly the bytes a later whole decode writes.
319
+ */
320
+ function digestBase64(data: string): { byteSize: number; sha256: string } {
321
+ if (!isCleanBase64(data)) {
322
+ const bytes = Buffer.from(data, 'base64');
323
+ return { byteSize: bytes.byteLength, sha256: sha256Hex(bytes) };
324
+ }
325
+ const CHUNK = 1 << 20; // multiple of 4
326
+ const hash = createHash('sha256');
327
+ let byteSize = 0;
328
+ for (let i = 0; i < data.length; i += CHUNK) {
329
+ const bytes = Buffer.from(data.slice(i, i + CHUNK), 'base64');
330
+ hash.update(bytes);
331
+ byteSize += bytes.byteLength;
332
+ }
333
+ return { byteSize, sha256: hash.digest('hex') };
334
+ }
@@ -14,8 +14,18 @@
14
14
  * For anything else it falls back to JSON.
15
15
  */
16
16
 
17
- import { safeSlice } from './safe-slice.js';
18
17
  import { INLINE_WITHHELD_TEXT, isInlineContradiction, referenceStubOrNull } from './mcpl/references.js';
18
+ import { formatPreservedImageSlots, formatToolImagePlaceholder, splitPreservingImageSlots } from './tool-image-ledger.js';
19
+
20
+ export interface HistorySerializeOptions {
21
+ /**
22
+ * Called for every image block the serializer replaces with a placeholder
23
+ * (issue #104). Returns the retention ref to embed in the placeholder —
24
+ * `[image: image/png, ~691KB, ref img_7]` — so the image keeps a saveable
25
+ * handle in history; null leaves the legacy ref-less form.
26
+ */
27
+ imageRef?: (blockIndex: number, image: { data: string; mimeType: string }) => string | null;
28
+ }
19
29
 
20
30
  /**
21
31
  * House-safe default inline cap (chars) for tool results, error results, and
@@ -36,17 +46,24 @@ import { INLINE_WITHHELD_TEXT, isInlineContradiction, referenceStubOrNull } from
36
46
  */
37
47
  export const DEFAULT_TOOL_RESULT_INLINE_MAX_CHARS = 24000;
38
48
 
39
- export function toolResultDataToHistoryString(data: unknown, maxChars?: number): string {
40
- const fromArray = tryHistoryStringFromContentArray(data);
49
+ export function toolResultDataToHistoryString(
50
+ data: unknown,
51
+ maxChars?: number,
52
+ options?: HistorySerializeOptions,
53
+ ): string {
54
+ const fromArray = tryHistoryStringFromContentArray(data, options);
41
55
  const str = fromArray ?? JSON.stringify(data);
42
56
  return maxChars ? truncateForHistory(str, maxChars) : str;
43
57
  }
44
58
 
45
- /** Bounded copy of an arbitrary string with the standard truncation notice. */
59
+ /** Bounded copy of an arbitrary string with the standard truncation notice.
60
+ * Image slots past the cut are re-appended, never dropped (issue #104). */
46
61
  export function truncateForHistory(str: string, maxChars: number): string {
47
62
  if (str.length <= maxChars) return str;
48
- return safeSlice(str, 0, maxChars)
49
- + '\n\n[truncated — original was ' + str.length + ' chars]';
63
+ const { head, tail } = splitPreservingImageSlots(str, maxChars);
64
+ return head
65
+ + '\n\n[truncated — original was ' + str.length + ' chars]'
66
+ + formatPreservedImageSlots(tail);
50
67
  }
51
68
 
52
69
  /**
@@ -54,10 +71,10 @@ export function truncateForHistory(str: string, maxChars: number): string {
54
71
  * recognize, return a history-safe string (images → placeholders). Otherwise
55
72
  * return `null` to defer to the caller's fallback (JSON, usually).
56
73
  */
57
- function tryHistoryStringFromContentArray(data: unknown): string | null {
74
+ function tryHistoryStringFromContentArray(data: unknown, options?: HistorySerializeOptions): string | null {
58
75
  if (!Array.isArray(data)) return null;
59
76
  const parts: string[] = [];
60
- for (const raw of data) {
77
+ for (const [blockIndex, raw] of data.entries()) {
61
78
  if (!raw || typeof raw !== 'object') return null;
62
79
  const b = raw as { type?: unknown; text?: unknown; data?: unknown; mimeType?: unknown };
63
80
  if (b.type === 'text' && typeof b.text === 'string') {
@@ -69,10 +86,14 @@ function tryHistoryStringFromContentArray(data: unknown): string | null {
69
86
  } else if (b.type === 'image' && typeof b.data === 'string' && typeof b.mimeType === 'string') {
70
87
  // Decoded byte estimate from base64 length (3/4 ratio, rounded).
71
88
  const approxBytes = Math.floor(b.data.length * 3 / 4);
72
- parts.push(`[image: ${b.mimeType}, ${formatSize(approxBytes)}]`);
89
+ const ref = options?.imageRef?.(blockIndex, { data: b.data, mimeType: b.mimeType }) ?? null;
90
+ parts.push(formatToolImagePlaceholder(b.mimeType, formatSize(approxBytes), ref));
73
91
  } else if (b.type === 'resource' || ((b.type === 'image' || b.type === 'audio') && typeof (b as { uri?: unknown }).uri === 'string')) {
74
92
  // RFC-005 reference block: a bounded stub, never the raw block JSON
75
93
  // (which used to inline the URI — and the whole array — into history).
94
+ // Image-typed stubs still occupy a slot in save_recent_image's
95
+ // inventory (a failing one — bytes live behind fetch_reference), so
96
+ // the index never slides past an image the resident saw.
76
97
  const stub = referenceStubOrNull(b, 'from tool result');
77
98
  if (stub === null) return null;
78
99
  parts.push(stub);
@@ -326,4 +326,14 @@ export interface InferenceRequest {
326
326
  * so a household ledger can say who woke whom; carries no content.
327
327
  */
328
328
  counterparty?: string;
329
+ /**
330
+ * Where the wake came from, for telemetry ONLY — never a speech locus.
331
+ * Set by the EventGate for batched wakes (composite channel id of the
332
+ * chosen event when the event carried one; push-event raw ids are not
333
+ * used). Routing keeps reading `channelId`, which only the direct channel
334
+ * paths set from normalized ids — a gate wake leaves it unset, as before.
335
+ */
336
+ wakeChannelId?: string;
337
+ /** Timestamp of the event the wake provenance was taken from (ms). */
338
+ wakeAt?: number;
329
339
  }