@hachej/boring-agent 0.4.3 → 0.4.5

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.
@@ -1,3 +1,5 @@
1
+ // Adapted from VictorTaelin/uniichat, Copyright 2026 Higher Order Company, Apache-2.0.
2
+ // Changed: Pi-native tasks, documents, message adaptation and host memory controls. See ../../NOTICE and ../../licenses/Apache-2.0.txt.
1
3
  // OptChat memory as one native pi-durable extension, opt-in per conversation.
2
4
  // The Pi transcript is the append-only log and is never rewritten. While the extension is selected, `beforeRequest` shows
3
5
  // the model one view of everything before the current turn: a tiling of the log by summary-tree nodes, one `id+n|text`
@@ -15,7 +17,17 @@ export { OptChatLog, OptChatTree, advanceFold, emptyFold, leavesOf, renderView,
15
17
  export const OptChatNodes = defineDocFamily({
16
18
  kind: 'boring.memory.optchat.nodes', version: 1, family: true, scope: 'conversation', history: 'latest', fork: 'current', initial: () => ({ nodes: {} }),
17
19
  });
18
- /** Compactor bookkeeping of one conversation: the summarizer's calls and spend, and the last failure of each node (the retry spacing reads it; no timer does). */
20
+ /** Seed memories, stored once per conversation and inherited by forks. They precede the Pi transcript in the memory only. */
21
+ export const OptChatNotes = defineDoc({
22
+ kind: 'boring.memory.optchat.notes', version: 1, scope: 'conversation', history: 'latest', fork: 'current',
23
+ initial: () => ({ seeded: false, notes: [] }),
24
+ });
25
+ /** Memory-only tombstones. Values are leaf counts, never the forgotten content. Pi's transcript is unchanged. */
26
+ export const OptChatEdits = defineDoc({
27
+ kind: 'boring.memory.optchat.edits', version: 1, scope: 'conversation', history: 'latest', fork: 'current',
28
+ initial: () => ({ revision: 0, forgotten: {} }),
29
+ });
30
+ /** Compactor bookkeeping of one conversation: calls, spend and the last failure of each node, including its retry streak. */
19
31
  export const OptChatState = defineDoc({
20
32
  kind: 'boring.memory.optchat.state', version: 1, scope: 'conversation', history: 'latest', fork: 'initial',
21
33
  initial: () => ({ calls: 0, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }, failures: {} }),
@@ -28,6 +40,7 @@ class Session {
28
40
  stored = new Map();
29
41
  tree;
30
42
  fold = emptyFold();
43
+ compactFold = emptyFold();
31
44
  /** Summary tasks may be created for leaves below this; the current turn's steps are held back while a request runs. */
32
45
  upTo = 0;
33
46
  lastRequest;
@@ -41,11 +54,33 @@ class Session {
41
54
  if (this.log.set(leaves) < before) {
42
55
  this.tree.reset();
43
56
  this.fold = emptyFold();
57
+ this.compactFold = emptyFold();
44
58
  }
45
59
  }
46
60
  }
47
61
  const message = (text) => ({ role: 'user', content: text.map(part => ({ type: 'text', text: part })), timestamp: Date.now() });
48
62
  const LIVE = ['pending', 'running', 'waiting'];
63
+ function redacted(item) {
64
+ if (item.role === 'system')
65
+ return item;
66
+ if (item.role === 'assistant')
67
+ return { ...item, content: item.content.flatMap((part) => part.type === 'toolCall'
68
+ ? [{ type: 'toolCall', id: part.id, name: 'forgotten', arguments: {} }]
69
+ : part.type === 'text' ? [{ type: 'text', text: '(forgotten)' }] : []) };
70
+ if (item.role === 'toolResult')
71
+ return { ...item, toolName: 'forgotten', content: [{ type: 'text', text: '(forgotten)' }] };
72
+ return { ...item, content: '(forgotten)' };
73
+ }
74
+ /** Pi's TextContent has no per-block cache marker. Keep the reference's four-line blocks without inventing one. */
75
+ function chatBlocks(lines) {
76
+ const rows = lines ? lines.split('\n') : [];
77
+ const blocks = ['<chat>\n'];
78
+ let i = 0;
79
+ for (; i + 4 <= rows.length; i += 4)
80
+ blocks.push(`${rows.slice(i, i + 4).join('\n')}\n`);
81
+ blocks.push(`${rows.slice(i).map(line => `${line}\n`).join('')}</chat>\n`);
82
+ return blocks;
83
+ }
49
84
  const addUsage = (sum, usage) => {
50
85
  if (!sum)
51
86
  return structuredClone(usage);
@@ -68,12 +103,17 @@ const addUsage = (sum, usage) => {
68
103
  export function createOptChatMemory(options) {
69
104
  const nodeBytes = options.nodeBytes ?? DEFAULTS.nodeBytes, viewBytes = options.viewBytes ?? DEFAULTS.viewBytes, jobs = options.jobs ?? DEFAULTS.jobs;
70
105
  const tries = options.tries ?? DEFAULTS.tries, cap = options.cap ?? DEFAULTS.cap, retryMs = options.retryMs ?? DEFAULTS.retryMs, settleMs = options.settleTimeoutMs ?? DEFAULTS.settleTimeoutMs;
106
+ const compactBytes = options.compactBytes ?? DEFAULTS.compactBytes;
71
107
  const agentName = options.agentName ?? 'OptChat';
72
108
  const extensionName = options.name ?? 'boring.memory.optchat';
73
109
  const taskKind = `${extensionName}.node`;
74
110
  const system = compactPrompt(agentName);
75
111
  const scale = scaleLine(nodeBytes);
112
+ const notes = [...(options.notes ?? [])];
113
+ const logOptions = (seed, edits) => ({ notes: seed, forgotten: edits.forgotten, ...(options.workOf ? { workOf: options.workOf } : {}) });
76
114
  const sessions = new Map();
115
+ const naps = new Map();
116
+ const retryDelay = (failure) => Math.min(60_000, retryMs * 2 ** Math.min(30, (failure.attempts ?? 1) - 1));
77
117
  const aborter = new AbortController();
78
118
  const hostContext = withAbortSignal(aborter.signal, options.context);
79
119
  const session = (id) => {
@@ -85,6 +125,8 @@ export function createOptChatMemory(options) {
85
125
  /** Read the stored summaries. Tasks write them (in this process or another, before or after a restart), so every read goes to the documents. */
86
126
  async function loadStored(s, reader, context) {
87
127
  const total = s.log.leaves.length;
128
+ s.stored.clear();
129
+ s.tree.reset();
88
130
  for (let level = 0; span(level) <= total; level++) {
89
131
  const nodes = Math.floor(total / span(level));
90
132
  for (let shard = 0; shard * SHARD < nodes; shard++) {
@@ -100,14 +142,38 @@ export function createOptChatMemory(options) {
100
142
  throw new Error(`No conversation ${String(id)}`);
101
143
  return found;
102
144
  }
145
+ /** The compactor has an independent fold. Copy before advancing: native tasks and requests can overlap. */
146
+ function compactView(s, to) {
147
+ const cached = session(s.id).compactFold;
148
+ const fold = cached.T > to ? emptyFold() : { T: cached.T, size: cached.size, parts: cached.parts.map(part => ({ ...part })) };
149
+ return advanceFold(fold, s.tree, to, compactBytes);
150
+ }
103
151
  /** Bring a session up to date with the committed context and its stored summaries. */
104
152
  async function refresh(id) {
105
153
  const s = session(id);
106
154
  const view = await (await conversationOf(id)).context(options.context);
107
- s.sync(leavesOf(view.messages, cap).leaves);
155
+ const seed = await seedNotes(id);
156
+ const edits = await memoryEdits(id);
157
+ s.sync(leavesOf(view.messages, cap, logOptions(seed, edits)).leaves);
108
158
  await loadStored(s, options.harness(), options.context);
109
159
  return s;
110
160
  }
161
+ async function memoryEdits(id) {
162
+ return await options.harness().snapshot(OptChatEdits, id, options.context) ?? { revision: 0, forgotten: {} };
163
+ }
164
+ async function seedNotes(id) {
165
+ const stored = await options.harness().snapshot(OptChatNotes, id, options.context);
166
+ if (stored?.seeded)
167
+ return stored.notes;
168
+ return (await conversationOf(id)).commit(async (tx) => {
169
+ const doc = await tx.doc(OptChatNotes, id);
170
+ if (!doc.seeded) {
171
+ doc.notes = [...notes];
172
+ doc.seeded = true;
173
+ }
174
+ return [...doc.notes];
175
+ }, options.context);
176
+ }
111
177
  // ---- The summarizer (runs inside the native task) ----------------------------------------------------------------------
112
178
  /** One node by the reference protocol (§4.2, §4.3): context first, then the step; over-long lines are resubmitted cut at the limit; the shortest wins. */
113
179
  async function askModel(job, runtimeModels, signal) {
@@ -131,7 +197,7 @@ export function createOptChatMemory(options) {
131
197
  const step = `For scale, this line is exactly ${scale.bytes} bytes:\n${scale.text}\n\n` + (job.level === 0
132
198
  ? `Compress this message into one line, in at most ${nodeBytes} bytes:\n${job.source[0]}`
133
199
  : `Merge these two lines into one, in at most ${nodeBytes} bytes:\n${lines.join('\n')}`);
134
- const conversation = [message([`<chat>\n${job.context}\n</chat>`, step])];
200
+ const conversation = [message([...chatBlocks(job.context), step])];
135
201
  const attempts = [];
136
202
  let usage, calls = 0, spender;
137
203
  try {
@@ -186,29 +252,48 @@ export function createOptChatMemory(options) {
186
252
  // A private view of this conversation: a request may be folding and rendering the shared session right now.
187
253
  const s = new Session(id, nodeBytes);
188
254
  const load = async () => {
189
- s.sync(leavesOf((await runtime.context(id, context)).messages, cap).leaves);
255
+ const seed = (await runtime.snapshot(OptChatNotes, id, context))?.notes ?? [];
256
+ const edits = await runtime.snapshot(OptChatEdits, id, context) ?? { revision: 0, forgotten: {} };
257
+ s.sync(leavesOf((await runtime.context(id, context)).messages, cap, logOptions(seed, edits)).leaves);
190
258
  await loadStored(s, runtime, context);
259
+ return edits.revision;
191
260
  };
192
- await load();
261
+ const revision = await load();
193
262
  const ready = () => s.log.fp(level, index) === of && (level === 0 || (s.tree.text(level - 1, 2 * index) !== undefined && s.tree.text(level - 1, 2 * index + 1) !== undefined));
194
263
  if (!ready() || s.tree.text(level, index) !== undefined)
195
264
  return stale(); // the history changed, a child is missing, or the node needs no summary
196
- const to = Math.min(upTo, s.log.leaves.length);
197
- if (s.fold.T > to)
198
- s.fold = emptyFold();
199
- advanceFold(s.fold, s.tree, to, viewBytes);
265
+ const to = Math.min(upTo, index * span(level));
266
+ const shared = session(id);
267
+ shared.sync(s.log.leaves);
268
+ const fold = compactView(s, to);
269
+ if (fold.size > compactBytes)
270
+ return stale(); // admission will build preceding parents before trying this node again
271
+ if (fold.T >= shared.compactFold.T)
272
+ shared.compactFold = fold;
200
273
  const source = level === 0 ? [s.log.leaves[index].line] : [s.tree.text(level - 1, 2 * index), s.tree.text(level - 1, 2 * index + 1)];
201
- const job = { conversationId: id, level, index, range: [index * span(level), (index + 1) * span(level) - 1], source, context: bareLines(s.fold, s.tree, level === 0 ? index : (index + 1) * span(level)), nodeBytes };
202
- const summary = await askModel(job, runtime.models, runtime.signal);
274
+ const job = { conversationId: id, level, index, range: [index * span(level), (index + 1) * span(level) - 1], source, context: bareLines(fold, s.tree, to), nodeBytes };
275
+ let summary;
276
+ try {
277
+ summary = await askModel(job, runtime.models, runtime.signal);
278
+ }
279
+ catch (error) {
280
+ if (runtime.signal.aborted)
281
+ throw error;
282
+ summary = { error, calls: 0 }; // model resolution can fail before any request is sent
283
+ }
203
284
  await load();
204
285
  if (!ready())
205
286
  return stale(summary); // the history changed while the model ran: its line is dropped, its spend is kept
206
287
  let firstFailure = false;
207
288
  await runtime.commit(async (tx) => {
208
289
  const state = await bookkeeping(tx, id, summary);
290
+ const edits = await tx.doc(OptChatEdits, id);
291
+ if (edits.revision !== revision)
292
+ return { status: 'terminal', outcome: { status: 'completed', result: { built: false } } };
209
293
  if (summary.text === undefined) {
210
- firstFailure = state.failures[`${level}:${index}`]?.of !== of;
211
- state.failures[`${level}:${index}`] = { at: Date.now(), of, error: String(summary.error?.message ?? summary.error) };
294
+ const previous = state.failures[`${level}:${index}`];
295
+ firstFailure = previous?.of !== of;
296
+ state.failures[`${level}:${index}`] = { at: Date.now(), of, attempts: firstFailure ? 1 : (previous?.attempts ?? 1) + 1, error: String(summary.error?.message ?? summary.error) };
212
297
  return { status: 'terminal', outcome: { status: 'failed', error: { message: state.failures[`${level}:${index}`].error } } };
213
298
  }
214
299
  const doc = await tx.doc(OptChatNodes, id, shardKey(level, index), 0);
@@ -242,6 +327,8 @@ export function createOptChatMemory(options) {
242
327
  continue;
243
328
  if (level > 0 && (s.tree.text(level - 1, 2 * index) === undefined || s.tree.text(level - 1, 2 * index + 1) === undefined))
244
329
  continue;
330
+ if (compactView(s, index * span(level)).size > compactBytes)
331
+ break;
245
332
  found.push({ level, index });
246
333
  }
247
334
  }
@@ -250,7 +337,7 @@ export function createOptChatMemory(options) {
250
337
  /**
251
338
  * Make sure every node that can be built has one live background task, up to `jobs` live tasks of the conversation. Host
252
339
  * admission only: Pi schedules and runs the tasks. One live task per node key (found by scanning native tasks in the same
253
- * commit that creates them); a node whose last failure is inside `retryMs` is left for the next trigger.
340
+ * commit that creates them); a node inside its backoff window waits for the idle admission loop.
254
341
  */
255
342
  async function admit(s, skip) {
256
343
  const wanted = candidates(s).map(({ level, index }) => ({ level, index, of: s.log.fp(level, index) }));
@@ -276,7 +363,7 @@ export function createOptChatMemory(options) {
276
363
  if (found.has(key) || skip.has(key))
277
364
  continue;
278
365
  const failure = failures[nodeKey(node.level, node.index)];
279
- if (failure && failure.of === node.of && now - failure.at < retryMs) {
366
+ if (failure && failure.of === node.of && now - failure.at < retryDelay(failure)) {
280
367
  waiting++;
281
368
  continue;
282
369
  }
@@ -301,22 +388,45 @@ export function createOptChatMemory(options) {
301
388
  cancel();
302
389
  }
303
390
  }
304
- async function nap(id) {
305
- const s = await refresh(id);
306
- s.upTo = s.log.leaves.length;
307
- const skip = new Set();
308
- for (;;) {
309
- const { live } = await admit(s, skip);
310
- if (live.size === 0)
391
+ /** Abortable host wait between admission attempts. Pi still owns each node task and its recovery. */
392
+ async function pause(ms) {
393
+ if (aborter.signal.aborted)
394
+ return;
395
+ await new Promise(resolve => {
396
+ const done = () => { clearTimeout(timer); aborter.signal.removeEventListener('abort', done); resolve(); };
397
+ const timer = setTimeout(done, Math.max(1, ms));
398
+ aborter.signal.addEventListener('abort', done, { once: true });
399
+ });
400
+ }
401
+ async function drain(id) {
402
+ while (!aborter.signal.aborted) {
403
+ const s = await refresh(id);
404
+ s.upTo = s.log.leaves.length;
405
+ const { live } = await admit(s, new Set());
406
+ if (live.size > 0) {
407
+ if (!await settleAny([...live.values()], undefined, hostContext))
408
+ return;
409
+ continue;
410
+ }
411
+ const failures = (await options.harness().snapshot(OptChatState, id, options.context))?.failures ?? {};
412
+ const delays = candidates(s).flatMap(({ level, index }) => {
413
+ const failure = failures[nodeKey(level, index)];
414
+ return failure && failure.of === s.log.fp(level, index) ? [failure.at + retryDelay(failure) - Date.now()] : [];
415
+ });
416
+ if (delays.length === 0)
311
417
  return;
312
- const done = await settleAny([...live.values()], undefined, hostContext);
313
- if (!done)
314
- return; // disposed
315
- if (!done.built)
316
- skip.add(done.key);
317
- await loadStored(s, options.harness(), options.context);
418
+ await pause(Math.min(...delays));
318
419
  }
319
420
  }
421
+ function nap(id) {
422
+ const key = String(id);
423
+ const existing = naps.get(key);
424
+ if (existing)
425
+ return existing;
426
+ const running = drain(id).finally(() => { naps.delete(key); });
427
+ naps.set(key, running);
428
+ return running;
429
+ }
320
430
  /** Wait until every line of the view is a summary (§6). Never shows cut text: on timeout the rest shows the placeholder. */
321
431
  async function settle(s, covered, context) {
322
432
  const deadline = Date.now() + settleMs, skip = new Set();
@@ -339,6 +449,45 @@ export function createOptChatMemory(options) {
339
449
  skip.add(done.key);
340
450
  }
341
451
  }
452
+ /** Context can copy an earlier fact into a later summary. Invalidate those too, atomically with the tombstone. */
453
+ async function forgetMessage(id, messageIndex) {
454
+ if (!Number.isInteger(messageIndex) || messageIndex < 0)
455
+ throw new Error('Invalid message index');
456
+ const conversation = await conversationOf(id);
457
+ const seed = await seedNotes(id);
458
+ for (;;) {
459
+ const edits = await memoryEdits(id);
460
+ const messages = (await conversation.context(options.context)).messages;
461
+ if (messageIndex >= messages.length || messages[messageIndex].role === 'system')
462
+ throw new Error('No forgettable message at that index');
463
+ const ordinal = messages.slice(0, messageIndex).filter(item => item.role !== 'system').length;
464
+ if (edits.forgotten[String(ordinal)] !== undefined)
465
+ return;
466
+ const { leaves, before } = leavesOf(messages, cap, logOptions(seed, edits));
467
+ const start = before[messageIndex], end = before[messageIndex + 1];
468
+ const changed = await conversation.commit(async (tx) => {
469
+ const doc = await tx.doc(OptChatEdits, id);
470
+ if (doc.revision !== edits.revision)
471
+ return false;
472
+ doc.forgotten[String(ordinal)] = end - start;
473
+ doc.revision++;
474
+ const state = await tx.doc(OptChatState, id);
475
+ for (let level = 0; span(level) <= leaves.length; level++) {
476
+ for (let index = Math.floor(start / span(level)); (index + 1) * span(level) <= leaves.length; index++) {
477
+ const shard = await tx.doc(OptChatNodes, id, shardKey(level, index), 0);
478
+ delete shard.nodes[String(index)];
479
+ delete state.failures[nodeKey(level, index)];
480
+ }
481
+ }
482
+ return true;
483
+ }, options.context);
484
+ if (!changed)
485
+ continue;
486
+ sessions.delete(String(id));
487
+ void nap(id).catch(() => { });
488
+ return;
489
+ }
490
+ }
342
491
  // ---- The extension -----------------------------------------------------------------------------------------------------
343
492
  const text = (value) => ({ output: [{ type: 'text', text: value }] });
344
493
  const zoomTool = defineTool({
@@ -363,30 +512,53 @@ export function createOptChatMemory(options) {
363
512
  hooks: [
364
513
  hook(GenerationTask, {
365
514
  beforeRequest: async (request, api, context) => {
366
- const { leaves, before } = leavesOf(request.messages, cap);
367
- const last = request.messages.findLastIndex(item => item.role === 'user');
368
- const covered = last < 0 ? 0 : before[last];
369
- if (covered === 0)
370
- return undefined; // nothing came before this turn
371
- const s = session(api.conversationId);
372
- s.sync(leaves);
373
- s.upTo = covered;
374
- if (s.fold.T > covered)
375
- s.fold = emptyFold();
376
- const started = Date.now();
377
- const settled = await settle(s, covered, context);
378
- const view = renderView(s.fold, s.tree);
379
- const messages = request.messages.flatMap((item, index) => {
380
- if (index < last)
381
- return item.role === 'system' ? [item] : [];
382
- if (index > last)
383
- return [item];
384
- const user = item;
385
- const body = typeof user.content === 'string' ? [{ type: 'text', text: user.content }] : user.content;
386
- return [{ ...user, content: [{ type: 'text', text: view }, ...body] }];
387
- });
388
- s.lastRequest = { at: new Date().toISOString(), covered, requestMessages: messages.length, logMessages: request.messages.length, viewBytes: byteLength(view), waitedMs: Date.now() - started, settled };
389
- return { messages };
515
+ for (;;) {
516
+ const seed = await seedNotes(api.conversationId);
517
+ const edits = await memoryEdits(api.conversationId);
518
+ const { leaves, before } = leavesOf(request.messages, cap, logOptions(seed, edits));
519
+ const last = request.messages.findLastIndex(item => item.role === 'user' || (item.role !== 'system' && options.workOf?.(item)));
520
+ const covered = last < 0 ? 0 : before[last];
521
+ if (covered === 0 && Object.keys(edits.forgotten).length === 0 && !request.messages.some(item => options.workOf?.(item)))
522
+ return undefined;
523
+ const cached = session(api.conversationId);
524
+ cached.sync(leaves);
525
+ const s = new Session(api.conversationId, nodeBytes);
526
+ s.sync(leaves);
527
+ s.upTo = covered;
528
+ if (cached.fold.T <= covered)
529
+ s.fold = { T: cached.fold.T, size: cached.fold.size, parts: cached.fold.parts.map(part => ({ ...part })) };
530
+ const started = Date.now();
531
+ const settled = await settle(s, covered, context);
532
+ if ((await memoryEdits(api.conversationId)).revision !== edits.revision)
533
+ continue;
534
+ const view = renderView(s.fold, s.tree);
535
+ const blocks = chatBlocks(view.split('\n').slice(1, -1).join('\n')).map(text => ({ type: 'text', text }));
536
+ let ordinal = 0;
537
+ const calls = new Set();
538
+ const messages = request.messages.flatMap((item, index) => {
539
+ const forgotten = item.role !== 'system' && edits.forgotten[String(ordinal++)] !== undefined;
540
+ if (index < last)
541
+ return item.role === 'system' ? [item] : [];
542
+ const retained = forgotten ? redacted(item) : item;
543
+ const work = item.role !== 'system' && options.workOf?.(item);
544
+ // A report can start midway through a tool batch. Never send results without their calls.
545
+ const normalize = (index === last && work && retained.role !== 'user') || (retained.role === 'toolResult' && !calls.has(retained.toolCallId));
546
+ const current = normalize ? message([leavesOf([retained], Infinity, { workOf: () => !!work }).leaves[0].line]) : retained;
547
+ if (current.role === 'assistant')
548
+ for (const part of current.content)
549
+ if (part.type === 'toolCall')
550
+ calls.add(part.id);
551
+ if (index > last || current.role === 'system')
552
+ return [current];
553
+ if (current.role === 'assistant')
554
+ return [{ ...current, content: [...blocks, ...current.content] }];
555
+ const body = typeof current.content === 'string' ? [{ type: 'text', text: current.content }] : current.content;
556
+ return [{ ...current, content: [...blocks, ...body] }];
557
+ });
558
+ cached.lastRequest = { at: new Date().toISOString(), covered, requestMessages: messages.length, logMessages: request.messages.length, viewBytes: byteLength(view), waitedMs: Date.now() - started, settled };
559
+ cached.fold = s.fold;
560
+ return { messages };
561
+ }
390
562
  },
391
563
  // A finished answer: once the run has committed it, create its summary tasks (background, so they never hold the run) so the next request finds its view ready.
392
564
  onYield: (_answer, api) => {
@@ -414,7 +586,7 @@ export function createOptChatMemory(options) {
414
586
  const state = await options.harness().snapshot(OptChatState, id, options.context);
415
587
  const failures = Object.entries(state?.failures ?? {}).filter(([key, failure]) => { const [level, index] = key.split(':').map(Number); return failure.of === s.log.fp(level, index); }).map(([, failure]) => failure);
416
588
  const busy = (await options.harness().inspect(options.context)).tasks.filter(task => task.record.kind === taskKind && task.record.conversationId === id).length;
417
- const retrying = failures.filter(failure => Date.now() - failure.at < retryMs).length;
589
+ const retrying = failures.filter(failure => Date.now() - failure.at < retryDelay(failure)).length;
418
590
  const latest = failures.reduce((best, failure) => !best || failure.at > best.at ? failure : best, undefined);
419
591
  return {
420
592
  leaves: s.log.leaves.length, summaries,
@@ -426,7 +598,8 @@ export function createOptChatMemory(options) {
426
598
  },
427
599
  async zoom(id, nth, n) { return zoomText((await refresh(id)).tree, nth, n); },
428
600
  async date(id, nth) { return dateText((await refresh(id)).log, nth); },
601
+ forgetMessage,
429
602
  forget(id) { sessions.delete(String(id)); },
430
- async dispose() { aborter.abort(); },
603
+ async dispose() { aborter.abort(); await Promise.allSettled(naps.values()); },
431
604
  };
432
605
  }
@@ -1,5 +1,6 @@
1
1
  import { defineExtension, defineTool } from '@earendil-works/pi-durable';
2
2
  import { Type } from '@earendil-works/pi-ai';
3
+ import { skillInFolder } from './skills.js';
3
4
  import { jsonSchemaTool } from './json-schema-tool.js';
4
5
  /*
5
6
  * Self-evolution (docs/architecture/SELF-EVOLUTION.md, laws SELF-1..4 in this package's README): an agent keeps its own standing
@@ -102,6 +103,27 @@ async function filesIn(env, directory, suffix, context) {
102
103
  return listed.error.code === 'not_found' ? 'missing' : { error: listed.error.message };
103
104
  return listed.value.filter(entry => entry.kind === 'file' && entry.name.endsWith(suffix)).map(entry => `${directory}/${entry.name}`).sort();
104
105
  }
106
+ /** Flat Markdown skills and `SKILL.md` in immediate child folders; companion files are not definitions. */
107
+ async function skillFilesIn(env, context, errors) {
108
+ const listed = await env.listDir(SKILLS, context);
109
+ if (!listed.ok) {
110
+ if (listed.error.code !== 'not_found')
111
+ errors.push({ path: SKILLS, message: listed.error.message });
112
+ return [];
113
+ }
114
+ const paths = listed.value.filter(entry => entry.kind === 'file' && entry.name.endsWith('.md')).map(entry => `${SKILLS}/${entry.name}`);
115
+ for (const entry of listed.value.filter(entry => entry.kind === 'directory')) {
116
+ const folder = `${SKILLS}/${entry.name}`;
117
+ const contents = await env.listDir(folder, context);
118
+ if (!contents.ok) {
119
+ errors.push({ path: folder, message: contents.error.message });
120
+ continue;
121
+ }
122
+ if (contents.value.some(file => file.kind === 'file' && file.name === 'SKILL.md'))
123
+ paths.push(`${folder}/SKILL.md`);
124
+ }
125
+ return paths.sort();
126
+ }
105
127
  export function createSelfEvolution(options) {
106
128
  const { name, parseSkill, skillsExtension } = options;
107
129
  const hostSkills = [...options.skills];
@@ -113,7 +135,7 @@ export function createSelfEvolution(options) {
113
135
  name: 'reload',
114
136
  description: `Apply the changes you made to your own ${AGENT_FOLDER}/ folder in the workspace, then return what was added, changed and removed and every load error. `
115
137
  + `${INSTRUCTIONS}: standing instructions for yourself, shown after the host's instructions on every request. `
116
- + `${SKILLS}/<name>.md: skills (front matter with name and description between --- lines, then the instructions), loaded with load_skill. `
138
+ + `${SKILLS}/<name>.md or ${SKILLS}/<name>/SKILL.md: skills (front matter with name and description between --- lines, then the instructions), loaded with load_skill; paths in a skill are relative to its folder and read with read. `
117
139
  + `${TOOLS}/<name>.json: your own tools, {"name": "snake_case", "description": "...", "parameters": {a JSON Schema with "type": "object"}, "run": "a command run in the workspace, for example sh ${TOOLS}/<name>.sh"}; `
118
140
  + 'the arguments arrive as one line of JSON on standard input and the command output is the result. Restore or delete the files and reload to undo a change.',
119
141
  parameters: Type.Object({}, { additionalProperties: false }),
@@ -147,10 +169,8 @@ export function createSelfEvolution(options) {
147
169
  else if (read.error.code !== 'not_found')
148
170
  errors.push({ path: INSTRUCTIONS, message: read.error.message });
149
171
  const skills = [];
150
- const skillFiles = await filesIn(env, SKILLS, '.md', context);
151
- if (typeof skillFiles === 'object' && !Array.isArray(skillFiles))
152
- errors.push({ path: SKILLS, message: skillFiles.error });
153
- for (const path of Array.isArray(skillFiles) ? skillFiles : []) {
172
+ const skillFiles = await skillFilesIn(env, context, errors);
173
+ for (const path of skillFiles) {
154
174
  const text = await env.readTextFile(path, context);
155
175
  if (!text.ok) {
156
176
  errors.push({ path, message: text.error.message });
@@ -168,7 +188,7 @@ export function createSelfEvolution(options) {
168
188
  errors.push({ path, message: `a skill named ${skill.name} already exists` });
169
189
  continue;
170
190
  }
171
- skills.push(skill);
191
+ skills.push(skillInFolder(skill, path.slice(0, path.lastIndexOf('/'))));
172
192
  }
173
193
  const available = typeof env.exec === 'function';
174
194
  const tools = [];
package/dist/skills.d.ts CHANGED
@@ -7,6 +7,7 @@ export interface Skill {
7
7
  readonly description: string;
8
8
  readonly body: string;
9
9
  }
10
+ export declare function skillInFolder(skill: Skill, folder: string): Skill;
10
11
  /** Parse a `SKILL.md`-style document: `---` front matter with `name` and `description`, then the body. */
11
12
  export declare function parseSkill(markdown: string): Skill;
12
13
  export declare function validSkill(skill: Skill): Skill;
package/dist/skills.js CHANGED
@@ -2,6 +2,11 @@ import { defineExtension, defineTool } from '@earendil-works/pi-durable';
2
2
  import { Type } from '@earendil-works/pi-ai';
3
3
  /** Names of skills and agents: a lowercase letter or digit, then lowercase letters, digits, `.`, `_` or `-` (at most 64). */
4
4
  export const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
5
+ const skillFolders = new WeakMap();
6
+ export function skillInFolder(skill, folder) {
7
+ skillFolders.set(skill, folder);
8
+ return skill;
9
+ }
5
10
  /** Parse a `SKILL.md`-style document: `---` front matter with `name` and `description`, then the body. */
6
11
  export function parseSkill(markdown) {
7
12
  const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(markdown);
@@ -23,7 +28,9 @@ export function validSkill(skill) {
23
28
  throw new TypeError(`Invalid skill name: ${skill.name}`);
24
29
  if (!skill.description.trim() || !skill.body.trim())
25
30
  throw new TypeError(`Skill ${skill.name} needs a description and a body`);
26
- return Object.freeze({ name: skill.name, description: skill.description.trim(), body: skill.body });
31
+ const valid = Object.freeze({ name: skill.name, description: skill.description.trim(), body: skill.body });
32
+ const folder = skillFolders.get(skill);
33
+ return folder === undefined ? valid : skillInFolder(valid, folder);
27
34
  }
28
35
  /** A prompt section listing the skills and a `load_skill` tool returning one body. Usable without `defineAgent`. */
29
36
  export function createSkillsExtension(name, skills) {
@@ -44,7 +51,9 @@ export function createSkillsExtension(name, skills) {
44
51
  replay: 'safe',
45
52
  execute: async (args) => {
46
53
  const skill = known.get(args.name);
47
- return { output: [{ type: 'text', text: skill ? skill.body : `Unknown skill "${args.name}". Available: ${[...known.keys()].join(', ')}` }] };
54
+ const folder = skill && skillFolders.get(skill);
55
+ const location = folder === undefined ? '' : `\n\nThis skill's folder is \`${folder}\`; paths in it are relative to that folder.`;
56
+ return { output: [{ type: 'text', text: skill ? skill.body + location : `Unknown skill "${args.name}". Available: ${[...known.keys()].join(', ')}` }] };
48
57
  },
49
58
  })],
50
59
  });