@lloyal-labs/lloyal-agents 1.0.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 (46) hide show
  1. package/README.md +280 -0
  2. package/dist/Tool.d.ts +65 -0
  3. package/dist/Tool.d.ts.map +1 -0
  4. package/dist/Tool.js +59 -0
  5. package/dist/Tool.js.map +1 -0
  6. package/dist/agent-pool.d.ts +114 -0
  7. package/dist/agent-pool.d.ts.map +1 -0
  8. package/dist/agent-pool.js +528 -0
  9. package/dist/agent-pool.js.map +1 -0
  10. package/dist/context.d.ts +33 -0
  11. package/dist/context.d.ts.map +1 -0
  12. package/dist/context.js +33 -0
  13. package/dist/context.js.map +1 -0
  14. package/dist/diverge.d.ts +39 -0
  15. package/dist/diverge.d.ts.map +1 -0
  16. package/dist/diverge.js +148 -0
  17. package/dist/diverge.js.map +1 -0
  18. package/dist/generate.d.ts +30 -0
  19. package/dist/generate.d.ts.map +1 -0
  20. package/dist/generate.js +58 -0
  21. package/dist/generate.js.map +1 -0
  22. package/dist/index.d.ts +15 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +28 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/init.d.ts +58 -0
  27. package/dist/init.d.ts.map +1 -0
  28. package/dist/init.js +57 -0
  29. package/dist/init.js.map +1 -0
  30. package/dist/run-agents.d.ts +39 -0
  31. package/dist/run-agents.d.ts.map +1 -0
  32. package/dist/run-agents.js +46 -0
  33. package/dist/run-agents.js.map +1 -0
  34. package/dist/shared-root.d.ts +55 -0
  35. package/dist/shared-root.d.ts.map +1 -0
  36. package/dist/shared-root.js +62 -0
  37. package/dist/shared-root.js.map +1 -0
  38. package/dist/toolkit.d.ts +38 -0
  39. package/dist/toolkit.d.ts.map +1 -0
  40. package/dist/toolkit.js +31 -0
  41. package/dist/toolkit.js.map +1 -0
  42. package/dist/types.d.ts +380 -0
  43. package/dist/types.d.ts.map +1 -0
  44. package/dist/types.js +3 -0
  45. package/dist/types.js.map +1 -0
  46. package/package.json +40 -0
@@ -0,0 +1,528 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ContextPressure = void 0;
4
+ exports.useAgentPool = useAgentPool;
5
+ const effection_1 = require("effection");
6
+ const sdk_1 = require("@lloyal-labs/sdk");
7
+ const context_1 = require("./context");
8
+ const sdk_2 = require("@lloyal-labs/sdk");
9
+ /**
10
+ * Immutable KV budget snapshot for one tick of the agent loop
11
+ *
12
+ * Created from `SessionContext._storeKvPressure()` which returns
13
+ * `{ nCtx, cellsUsed, remaining }` where `remaining = nCtx - cellsUsed`.
14
+ * `cellsUsed` is a monotonic counter in `BranchStore` — it increments on
15
+ * every `decode_each` / `decode_scatter` but does **not** decrement on
16
+ * individual branch prune (only resets on bulk ops like `retainOnly` and
17
+ * `drain`). This means `remaining` is a conservative lower bound that
18
+ * becomes increasingly pessimistic as branches are pruned mid-run.
19
+ *
20
+ * Two thresholds partition `remaining` into three zones:
21
+ *
22
+ * ```
23
+ * ┌──────────────────────────────────────────────────────┐
24
+ * │ nCtx │
25
+ * │ ┌──────────┬───────────────────┬──────────────────┐ │
26
+ * │ │cellsUsed │ headroom > 0 │ softLimit │ │
27
+ * │ │ (in use) │ (new work OK) │ (reserved) │ │
28
+ * │ └──────────┴───────────────────┴──────────────────┘ │
29
+ * │ ◄── remaining ──► │ │
30
+ * │ │ │
31
+ * │ headroom = remaining - softLimit │
32
+ * │ critical = remaining < hardLimit │
33
+ * └──────────────────────────────────────────────────────┘
34
+ * ```
35
+ *
36
+ * - **headroom > 0** — room for new work (tool results, generation)
37
+ * - **headroom ≤ 0** — over budget. SETTLE rejects tool results, PRODUCE
38
+ * hard-cuts non-terminal tool calls. Terminal tools still pass.
39
+ * - **critical** — remaining below hardLimit. Agents killed before
40
+ * `produceSync()` to prevent llama_decode crashes.
41
+ *
42
+ * @category Agents
43
+ */
44
+ class ContextPressure {
45
+ /** Default softLimit: 1024 tokens reserved for downstream work */
46
+ static DEFAULT_SOFT_LIMIT = 1024;
47
+ /** Default hardLimit: 128 tokens crash-prevention floor */
48
+ static DEFAULT_HARD_LIMIT = 128;
49
+ /**
50
+ * KV slots remaining (`nCtx - cellsUsed`).
51
+ * Infinity when nCtx ≤ 0 (no context limit).
52
+ * Conservative: may undercount actual free space when branches have been
53
+ * pruned, since `cellsUsed` is monotonic.
54
+ */
55
+ remaining;
56
+ /** Remaining KV floor — tokens reserved for downstream work */
57
+ softLimit;
58
+ /** Crash-prevention floor — agents killed when remaining drops below */
59
+ hardLimit;
60
+ constructor(ctx, opts) {
61
+ const p = ctx._storeKvPressure();
62
+ this.remaining = p.nCtx <= 0 ? Infinity : p.remaining;
63
+ this.softLimit = opts?.softLimit ?? ContextPressure.DEFAULT_SOFT_LIMIT;
64
+ this.hardLimit = opts?.hardLimit ?? ContextPressure.DEFAULT_HARD_LIMIT;
65
+ }
66
+ /**
67
+ * Tokens available for new work: `remaining - softLimit`.
68
+ * Positive means room to accept tool results or continue generating.
69
+ * Negative means over budget — SETTLE rejects, PRODUCE hard-cuts.
70
+ */
71
+ get headroom() { return this.remaining - this.softLimit; }
72
+ /** `remaining < hardLimit` — agent must not call `produceSync()`. */
73
+ get critical() { return this.remaining < this.hardLimit; }
74
+ /** Can `tokenCount` tokens fit while staying above softLimit? */
75
+ canFit(tokenCount) { return tokenCount <= this.headroom; }
76
+ }
77
+ exports.ContextPressure = ContextPressure;
78
+ /**
79
+ * Fork an agent from a parent branch with its own system prompt and task.
80
+ *
81
+ * Generator — uses sync native calls so Effection sees everything.
82
+ * On scope exit (error, cancellation), `ensure()` prunes the branch
83
+ * automatically — the orphaned-branch leak is structurally impossible.
84
+ */
85
+ function* setupAgent(parent, task, ctx) {
86
+ const messages = [
87
+ { role: 'system', content: task.systemPrompt },
88
+ { role: 'user', content: task.content },
89
+ ];
90
+ const fmtOpts = task.tools ? { tools: task.tools } : {};
91
+ const fmt = ctx.formatChatSync(JSON.stringify(messages), fmtOpts);
92
+ if (task.tools && (fmt.format === sdk_1.CHAT_FORMAT_CONTENT_ONLY || fmt.format === sdk_1.CHAT_FORMAT_GENERIC)) {
93
+ // Error before fork — no branch to clean up
94
+ throw new Error('Model does not support tool calling. Please use a model with native tool support (e.g. Qwen3, Llama 3.x, Mistral).');
95
+ }
96
+ const branch = parent.forkSync();
97
+ yield* (0, effection_1.ensure)(() => { if (!branch.disposed)
98
+ branch.pruneSync(); });
99
+ const sep = ctx.getTurnSeparator();
100
+ const suffixTokens = [...sep, ...ctx.tokenizeSync(fmt.prompt, false)];
101
+ if (task.seed != null)
102
+ branch.reseedSampler(task.seed);
103
+ return {
104
+ agent: {
105
+ id: branch.handle,
106
+ parentId: parent.handle,
107
+ branch,
108
+ state: 'generating',
109
+ fmt: {
110
+ format: fmt.format,
111
+ reasoningFormat: fmt.reasoningFormat,
112
+ thinkingForcedOpen: fmt.thinkingForcedOpen,
113
+ parser: fmt.parser,
114
+ grammar: fmt.grammar,
115
+ grammarLazy: fmt.grammarLazy,
116
+ grammarTriggers: fmt.grammarTriggers,
117
+ },
118
+ rawOutput: '',
119
+ tokenCount: 0,
120
+ toolCallCount: 0,
121
+ turns: 0,
122
+ findings: null,
123
+ traceBuffer: [],
124
+ },
125
+ suffixTokens,
126
+ };
127
+ }
128
+ /**
129
+ * Concurrent agent generation loop as an Effection resource
130
+ *
131
+ * Runs N agents in parallel using a three-phase tick loop over shared
132
+ * {@link BranchStore} infrastructure. Each agent forks from a parent
133
+ * branch, generates tokens, invokes tools, and reports findings.
134
+ *
135
+ * **Three-phase tick loop:**
136
+ * 1. **PRODUCE** — sample all active agents via `produceSync()` (no async gap)
137
+ * 2. **COMMIT** — single GPU call via `store.commit()` for all produced tokens
138
+ * 3. **SETTLE** — drain settled tool results, batch prefill, reset grammars
139
+ *
140
+ * Tool dispatch uses `scope.run()` for eager start — tool executions run as
141
+ * children of the agent pool scope and are cancelled if the scope exits.
142
+ *
143
+ * **Resource semantics:** `provide()` suspends after all agents complete,
144
+ * keeping branches alive so the caller can fork from them (e.g. for
145
+ * verification). Branches are pruned when the scope exits — each branch's
146
+ * `ensure()` from `setupAgent` handles cleanup automatically.
147
+ *
148
+ * For automatic branch cleanup on return, use {@link runAgents} instead.
149
+ *
150
+ * @param opts - Pool configuration: tasks, tools, sampling params, max turns
151
+ * @returns Agent pool result with per-agent findings and aggregate statistics
152
+ *
153
+ * @example Shared root with agent pool
154
+ * ```typescript
155
+ * const pool = yield* withSharedRoot(
156
+ * { systemPrompt: RESEARCH_PROMPT, tools: toolsJson },
157
+ * function*(root) {
158
+ * return yield* useAgentPool({
159
+ * tasks: questions.map(q => ({
160
+ * systemPrompt: RESEARCH_PROMPT,
161
+ * content: q,
162
+ * tools: toolsJson,
163
+ * parent: root,
164
+ * })),
165
+ * tools: toolMap,
166
+ * maxTurns: 6,
167
+ * });
168
+ * },
169
+ * );
170
+ * ```
171
+ *
172
+ * @category Agents
173
+ */
174
+ function useAgentPool(opts) {
175
+ return (0, effection_1.resource)(function* (provide) {
176
+ const ctx = yield* context_1.Ctx.expect();
177
+ const store = yield* context_1.Store.expect();
178
+ const events = yield* context_1.Events.expect();
179
+ const scope = yield* (0, effection_1.useScope)();
180
+ // Bridge for onProgress callbacks — Signal is correct here (external callback).
181
+ // A spawned forwarder drains the bridge into the Channel with proper scope context.
182
+ const progressBridge = (0, effection_1.createSignal)();
183
+ yield* (0, effection_1.spawn)(function* () {
184
+ for (const ev of yield* (0, effection_1.each)(progressBridge)) {
185
+ yield* events.send(ev);
186
+ yield* effection_1.each.next();
187
+ }
188
+ });
189
+ const { tasks, tools, maxTurns = 100, terminalTool, trace = false, pressure: pressureOpts } = opts;
190
+ // Whether the pool's tool registry contains tools besides the terminal tool.
191
+ // When false, agents are allowed to call the terminal tool as their first
192
+ // action (e.g. reporter sub-agents that only have `report()`). When true,
193
+ // the first tool call must be a non-terminal tool to prevent agents from
194
+ // immediately reporting without doing any work.
195
+ //
196
+ // IMPORTANT: this checks the pool's `tools` registry, not individual task
197
+ // schemas (`task.tools`). A reporter pool must pass only the terminal tool
198
+ // in its registry — passing the full tool map makes this flag true and
199
+ // traps reporters in an infinite rejection loop.
200
+ const hasNonTerminalTools = terminalTool ? [...tools.keys()].some(k => k !== terminalTool) : tools.size > 0;
201
+ // ── Setup: fork branches, collect suffix tokens ──────────
202
+ // setupAgent is now a generator — each branch registers its own ensure()
203
+ // for cleanup. No manual try/finally needed here.
204
+ const agents = [];
205
+ const prefillSetup = [];
206
+ for (const task of tasks) {
207
+ const parent = task.parent;
208
+ if (!parent)
209
+ throw new Error('useAgentPool: each task must have a parent branch');
210
+ const { agent, suffixTokens } = yield* setupAgent(parent, task, ctx);
211
+ agents.push(agent);
212
+ prefillSetup.push([agent.branch, suffixTokens]);
213
+ }
214
+ // Batch prefill all agent suffixes — pressure-gated.
215
+ // Each suffix is the full formatted chat (system prompt + tools JSON +
216
+ // user message + generation prompt), tokenized via formatChatSync().
217
+ // Suffix cost is model-dependent: ~250-400 tokens per agent depending
218
+ // on chat template verbosity and tool schema size.
219
+ const initPressure = new ContextPressure(ctx, pressureOpts);
220
+ const totalSuffix = prefillSetup.reduce((s, [, t]) => s + t.length, 0);
221
+ if (!initPressure.canFit(totalSuffix)) {
222
+ // Not enough room — drop agents from the end until it fits
223
+ while (prefillSetup.length > 0) {
224
+ const needed = prefillSetup.reduce((s, [, t]) => s + t.length, 0);
225
+ if (initPressure.canFit(needed))
226
+ break;
227
+ prefillSetup.pop();
228
+ const dropped = agents.pop();
229
+ dropped.state = 'done';
230
+ }
231
+ }
232
+ if (prefillSetup.length > 0) {
233
+ yield* (0, effection_1.call)(() => store.prefill(prefillSetup));
234
+ }
235
+ // Emit spawn events — TUI uses parentAgentId to detect sub-agents
236
+ for (const a of agents) {
237
+ yield* events.send({ type: 'agent:spawn', agentId: a.id, parentAgentId: a.parentId });
238
+ }
239
+ // ── Lazy grammar setup ───────────────────────────────────
240
+ const applyLazyGrammar = (a) => {
241
+ if (a.fmt.grammar && a.fmt.grammarLazy && a.fmt.grammarTriggers.length > 0) {
242
+ const triggers = a.fmt.grammarTriggers.map(t => {
243
+ if (t.type === sdk_1.GrammarTriggerType.WORD) {
244
+ const nlIdx = t.value.indexOf('\n');
245
+ if (nlIdx >= 0 && nlIdx < t.value.length - 1) {
246
+ return { ...t, value: t.value.slice(0, nlIdx + 1) };
247
+ }
248
+ }
249
+ return t;
250
+ });
251
+ a.branch.setGrammarLazy(a.fmt.grammar, triggers);
252
+ }
253
+ };
254
+ for (const a of agents)
255
+ applyLazyGrammar(a);
256
+ // ── Tool dispatch coordination ───────────────────────────
257
+ // Plain JS buffer: spawned tool tasks push synchronously on completion.
258
+ // SETTLE drains with splice(0). Safe because generators are synchronous
259
+ // between yields — spawns can only push at yield points (during COMMIT's
260
+ // yield* call()), and SETTLE runs after COMMIT in the same tick.
261
+ const settledBuffer = [];
262
+ const agentById = new Map(agents.map(a => [a.id, a]));
263
+ // Track pending tool count for idle detection
264
+ let pendingToolCount = 0;
265
+ // Resolve function for idle wake — set when all agents stall
266
+ let wakeIdle = null;
267
+ let steps = 0;
268
+ let totalToolCalls = 0;
269
+ const counters = {
270
+ warmPrefillCalls: 0,
271
+ warmPrefillBranches: 0,
272
+ stalledTicks: 0,
273
+ maxConcurrentTools: 0,
274
+ idleTicks: 0,
275
+ };
276
+ function* dispatchTool(agent, tc) {
277
+ let toolArgs;
278
+ try {
279
+ toolArgs = JSON.parse(tc.arguments);
280
+ }
281
+ catch {
282
+ toolArgs = {};
283
+ }
284
+ const callId = tc.id || `call_${agent.toolCallCount}`;
285
+ agent.toolCallCount++;
286
+ totalToolCalls++;
287
+ agent.turns++;
288
+ agent.state = 'awaiting_tool';
289
+ yield* events.send({ type: 'agent:tool_call', agentId: agent.id, tool: tc.name, args: tc.arguments });
290
+ const tool = tools.get(tc.name);
291
+ pendingToolCount++;
292
+ counters.maxConcurrentTools = Math.max(counters.maxConcurrentTools, pendingToolCount);
293
+ // scope.run() — eager start, child of agent pool scope, cancelled if scope exits.
294
+ // spawn() is lazy (Operation), but we're in a generator — scope.run() is eager.
295
+ scope.run(function* () {
296
+ try {
297
+ const toolContext = {
298
+ onProgress: (p) => {
299
+ // Signal bridge — onProgress is an external callback, Signal.send() is correct here.
300
+ progressBridge.send({ type: 'agent:tool_progress', agentId: agent.id, tool: tc.name, filled: p.filled, total: p.total });
301
+ },
302
+ };
303
+ const result = yield* (0, effection_1.call)(() => tool ? tool.execute(toolArgs, toolContext) : Promise.resolve({ error: `Unknown tool: ${tc.name}` }));
304
+ const resultStr = JSON.stringify(result);
305
+ yield* events.send({ type: 'agent:tool_result', agentId: agent.id, tool: tc.name, result: resultStr });
306
+ const prefillTokens = (0, sdk_2.buildToolResultDelta)(ctx, resultStr, callId);
307
+ settledBuffer.push({ agentId: agent.id, prefillTokens, toolName: tc.name });
308
+ }
309
+ catch (err) {
310
+ agent.state = 'done';
311
+ agent.findings = `Tool error: ${err.message}`;
312
+ }
313
+ finally {
314
+ pendingToolCount--;
315
+ if (wakeIdle) {
316
+ wakeIdle();
317
+ wakeIdle = null;
318
+ }
319
+ }
320
+ });
321
+ }
322
+ // ── Three-phase tick loop ────────────────────────────────
323
+ for (;;) {
324
+ // -- Phase 1: PRODUCE -- sample from active agents
325
+ const pressure = new ContextPressure(ctx, pressureOpts);
326
+ if (trace && (pressure.critical || pressure.headroom < 0)) {
327
+ const p = ctx._storeKvPressure();
328
+ try {
329
+ process.stderr.write(`[PRODUCE] ${pressure.critical ? 'CRITICAL' : 'SOFT_LIMIT'} remaining=${p.remaining} headroom=${pressure.headroom} cellsUsed=${p.cellsUsed} nCtx=${p.nCtx}\n`);
330
+ }
331
+ catch { }
332
+ }
333
+ const entries = [];
334
+ for (const a of agents) {
335
+ if (a.state !== 'generating')
336
+ continue;
337
+ if (pressure.critical) {
338
+ a.state = 'done';
339
+ yield* events.send({ type: 'agent:done', agentId: a.id });
340
+ continue;
341
+ }
342
+ const { token, text, isStop } = a.branch.produceSync();
343
+ if (isStop) {
344
+ const parsed = ctx.parseChatOutput(a.rawOutput, a.fmt.format, {
345
+ reasoningFormat: a.fmt.reasoningFormat,
346
+ thinkingForcedOpen: a.fmt.thinkingForcedOpen,
347
+ parser: a.fmt.parser,
348
+ });
349
+ const tc = parsed.toolCalls[0];
350
+ if (!tc) {
351
+ a.state = 'done';
352
+ if (!a.findings && a.toolCallCount > 0 && parsed.content) {
353
+ a.findings = parsed.content;
354
+ yield* events.send({ type: 'agent:report', agentId: a.id, findings: a.findings });
355
+ }
356
+ yield* events.send({ type: 'agent:done', agentId: a.id });
357
+ continue;
358
+ }
359
+ // Over budget: deny non-terminal tool calls when the agent has
360
+ // exceeded maxTurns or KV headroom is negative. Terminal tools
361
+ // (e.g. `report()`) are always allowed through — an agent that has
362
+ // done research and wants to report should never be blocked by
363
+ // pressure, since the report call itself consumes minimal KV.
364
+ const overBudget = (a.turns >= maxTurns || pressure.headroom < 0)
365
+ && (!terminalTool || tc.name !== terminalTool);
366
+ if (overBudget) {
367
+ a.state = 'done';
368
+ yield* events.send({ type: 'agent:done', agentId: a.id });
369
+ continue;
370
+ }
371
+ // Terminal tool — intercept, extract findings, mark done.
372
+ if (terminalTool && tc.name === terminalTool) {
373
+ if (a.toolCallCount === 0 && hasNonTerminalTools) {
374
+ const callId = tc.id || `call_${a.toolCallCount}`;
375
+ const errorMsg = 'You must perform research before reporting. Call at least one tool first.';
376
+ a.turns++;
377
+ a.state = 'awaiting_tool';
378
+ pendingToolCount++;
379
+ scope.run(function* () {
380
+ try {
381
+ const prefillTokens = (0, sdk_2.buildToolResultDelta)(ctx, JSON.stringify({ error: errorMsg }), callId);
382
+ settledBuffer.push({ agentId: a.id, prefillTokens, toolName: tc.name });
383
+ }
384
+ finally {
385
+ pendingToolCount--;
386
+ if (wakeIdle) {
387
+ wakeIdle();
388
+ wakeIdle = null;
389
+ }
390
+ }
391
+ });
392
+ a.rawOutput = '';
393
+ continue;
394
+ }
395
+ try {
396
+ a.findings = JSON.parse(tc.arguments).findings;
397
+ }
398
+ catch {
399
+ a.findings = tc.arguments;
400
+ }
401
+ a.state = 'done';
402
+ a.toolCallCount++;
403
+ totalToolCalls++;
404
+ yield* events.send({ type: 'agent:tool_call', agentId: a.id, tool: tc.name, args: tc.arguments });
405
+ yield* events.send({ type: 'agent:report', agentId: a.id, findings: a.findings });
406
+ yield* events.send({ type: 'agent:done', agentId: a.id });
407
+ continue;
408
+ }
409
+ // Fire-and-forget — dispatch tool without blocking the decode loop
410
+ yield* dispatchTool(a, tc);
411
+ a.rawOutput = '';
412
+ continue;
413
+ }
414
+ entries.push([a.branch, token]);
415
+ a.rawOutput += text;
416
+ a.tokenCount++;
417
+ if (trace) {
418
+ const entropy = a.branch.modelEntropy();
419
+ const surprisal = a.branch.modelSurprisal(token);
420
+ a.traceBuffer.push({ text, entropy, surprisal });
421
+ yield* events.send({
422
+ type: 'agent:produce', agentId: a.id, text, tokenCount: a.tokenCount,
423
+ entropy, surprisal,
424
+ });
425
+ }
426
+ else {
427
+ yield* events.send({ type: 'agent:produce', agentId: a.id, text, tokenCount: a.tokenCount });
428
+ }
429
+ }
430
+ // -- Phase 2: COMMIT -- batch-decode produced tokens
431
+ if (entries.length > 0) {
432
+ yield* (0, effection_1.call)(() => store.commit(entries));
433
+ steps++;
434
+ }
435
+ // -- Phase 3: SETTLE -- drain settled tool buffer, batch prefill
436
+ const settled = settledBuffer.splice(0);
437
+ if (settled.length > 0) {
438
+ // Fresh snapshot — Phase 2 commits may have advanced positions
439
+ const settlePressure = new ContextPressure(ctx, pressureOpts);
440
+ let headroom = settlePressure.headroom;
441
+ if (trace) {
442
+ const p = ctx._storeKvPressure();
443
+ const items = settled.map(s => `${s.toolName}:${s.prefillTokens.length}`).join(', ');
444
+ try {
445
+ process.stderr.write(`[SETTLE] remaining=${p.remaining} headroom=${headroom} cellsUsed=${p.cellsUsed} nCtx=${p.nCtx} items=[${items}]\n`);
446
+ }
447
+ catch { }
448
+ }
449
+ const prefillPairs = [];
450
+ const settledAgents = [];
451
+ for (const item of settled) {
452
+ const a = agentById.get(item.agentId);
453
+ if (!a || a.state === 'done')
454
+ continue;
455
+ if (item.prefillTokens.length > headroom) {
456
+ if (trace) {
457
+ try {
458
+ process.stderr.write(`[SETTLE] REJECT ${item.toolName}:${item.prefillTokens.length} > headroom=${headroom}\n`);
459
+ }
460
+ catch { }
461
+ }
462
+ a.state = 'done';
463
+ yield* events.send({ type: 'agent:done', agentId: a.id });
464
+ continue;
465
+ }
466
+ prefillPairs.push([a.branch, item.prefillTokens]);
467
+ settledAgents.push(a);
468
+ headroom -= item.prefillTokens.length;
469
+ }
470
+ if (prefillPairs.length > 0) {
471
+ if (trace) {
472
+ const totalPrefill = prefillPairs.reduce((s, [, t]) => s + t.length, 0);
473
+ try {
474
+ process.stderr.write(`[SETTLE] PREFILL ${prefillPairs.length} branches, ${totalPrefill} tokens, headroom_after=${headroom}\n`);
475
+ }
476
+ catch { }
477
+ }
478
+ yield* (0, effection_1.call)(() => store.prefill(prefillPairs));
479
+ counters.warmPrefillCalls++;
480
+ counters.warmPrefillBranches += prefillPairs.length;
481
+ // Only NOW transition state + reset grammar
482
+ for (const a of settledAgents) {
483
+ a.state = 'generating';
484
+ a.rawOutput = '';
485
+ applyLazyGrammar(a);
486
+ }
487
+ }
488
+ }
489
+ // -- Termination + idle yield
490
+ const allDone = agents.every(a => a.state === 'done') && pendingToolCount === 0;
491
+ if (allDone)
492
+ break;
493
+ if (entries.length === 0 && pendingToolCount > 0) {
494
+ counters.stalledTicks++;
495
+ if (settled.length === 0) {
496
+ // Nothing produced, nothing settled — yield until a tool resolves
497
+ yield* (0, effection_1.action)((resolve) => {
498
+ wakeIdle = resolve;
499
+ return () => { wakeIdle = null; };
500
+ });
501
+ counters.idleTicks++;
502
+ }
503
+ }
504
+ }
505
+ // ── Provide result — suspends, branches stay alive ───────
506
+ // Branch cleanup is handled by each branch's ensure() from setupAgent —
507
+ // when this resource's scope exits, all ensure() callbacks fire.
508
+ const result = {
509
+ agents: agents.map(a => ({
510
+ agentId: a.id,
511
+ parentAgentId: a.parentId,
512
+ branch: a.branch,
513
+ findings: a.findings,
514
+ toolCallCount: a.toolCallCount,
515
+ tokenCount: a.tokenCount,
516
+ ppl: a.branch.perplexity,
517
+ samplingPpl: a.branch.samplingPerplexity,
518
+ trace: trace ? a.traceBuffer : undefined,
519
+ })),
520
+ totalTokens: agents.reduce((s, a) => s + a.tokenCount, 0),
521
+ totalToolCalls,
522
+ steps,
523
+ counters,
524
+ };
525
+ yield* provide(result);
526
+ });
527
+ }
528
+ //# sourceMappingURL=agent-pool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-pool.js","sourceRoot":"","sources":["../src/agent-pool.ts"],"names":[],"mappings":";;;AAiOA,oCAwWC;AAzkBD,yCAAgG;AAGhG,0CAAoK;AAEpK,uCAA+C;AAC/C,0CAAwD;AA6CxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAa,eAAe;IAC1B,kEAAkE;IAClE,MAAM,CAAU,kBAAkB,GAAG,IAAI,CAAC;IAC1C,2DAA2D;IAC3D,MAAM,CAAU,kBAAkB,GAAG,GAAG,CAAC;IAEzC;;;;;OAKG;IACM,SAAS,CAAS;IAC3B,+DAA+D;IACtD,SAAS,CAAS;IAC3B,wEAAwE;IAC/D,SAAS,CAAS;IAE3B,YAAY,GAAmB,EAAE,IAAyB;QACxD,MAAM,CAAC,GAAG,GAAG,CAAC,gBAAgB,EAAE,CAAC;QACjC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACtD,IAAI,CAAC,SAAS,GAAG,IAAI,EAAE,SAAS,IAAI,eAAe,CAAC,kBAAkB,CAAC;QACvE,IAAI,CAAC,SAAS,GAAG,IAAI,EAAE,SAAS,IAAI,eAAe,CAAC,kBAAkB,CAAC;IACzE,CAAC;IAED;;;;OAIG;IACH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;gBAChB,QAAQ,EAAE,CAAC,CAAC,QAAQ;gBACpB,aAAa,EAAE,CAAC,CAAC,aAAa;gBAC9B,UAAU,EAAE,CAAC,CAAC,UAAU;gBACxB,GAAG,EAAE,CAAC,CAAC,MAAM,CAAC,UAAU;gBACxB,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC,kBAAkB;gBACxC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS;aACzC,CAAC,CAAC;YACL,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC;YACzD,cAAc;YACd,KAAK;YACL,QAAQ;SACT,CAAC;QAEF,KAAK,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACzB,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,33 @@
1
+ import type { SessionContext } from '@lloyal-labs/sdk';
2
+ import type { BranchStore } from '@lloyal-labs/sdk';
3
+ import type { Channel } from 'effection';
4
+ import type { AgentEvent } from './types';
5
+ /**
6
+ * Effection context holding the active {@link SessionContext}
7
+ *
8
+ * Set by {@link initAgents} in the caller's scope. All agent operations
9
+ * (`generate`, `diverge`, `useAgentPool`, `withSharedRoot`) read from this
10
+ * context via `yield* Ctx.expect()`.
11
+ *
12
+ * @category Agents
13
+ */
14
+ export declare const Ctx: import("effection").Context<SessionContext>;
15
+ /**
16
+ * Effection context holding the active {@link BranchStore}
17
+ *
18
+ * Set by {@link initAgents}. Used by {@link diverge} and {@link useAgentPool}
19
+ * for batched commit/prefill across multiple branches.
20
+ *
21
+ * @category Agents
22
+ */
23
+ export declare const Store: import("effection").Context<BranchStore>;
24
+ /**
25
+ * Effection context holding the agent event channel
26
+ *
27
+ * Set by {@link initAgents}. {@link useAgentPool} emits {@link AgentEvent}
28
+ * values through this channel via `yield* channel.send()`.
29
+ *
30
+ * @category Agents
31
+ */
32
+ export declare const Events: import("effection").Context<Channel<AgentEvent, void>>;
33
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAE1C;;;;;;;;GAQG;AACH,eAAO,MAAM,GAAG,6CAA8C,CAAC;AAE/D;;;;;;;GAOG;AACH,eAAO,MAAM,KAAK,0CAA6C,CAAC;AAEhE;;;;;;;GAOG;AACH,eAAO,MAAM,MAAM,wDAA4D,CAAC"}
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Events = exports.Store = exports.Ctx = void 0;
4
+ const effection_1 = require("effection");
5
+ /**
6
+ * Effection context holding the active {@link SessionContext}
7
+ *
8
+ * Set by {@link initAgents} in the caller's scope. All agent operations
9
+ * (`generate`, `diverge`, `useAgentPool`, `withSharedRoot`) read from this
10
+ * context via `yield* Ctx.expect()`.
11
+ *
12
+ * @category Agents
13
+ */
14
+ exports.Ctx = (0, effection_1.createContext)('lloyal.ctx');
15
+ /**
16
+ * Effection context holding the active {@link BranchStore}
17
+ *
18
+ * Set by {@link initAgents}. Used by {@link diverge} and {@link useAgentPool}
19
+ * for batched commit/prefill across multiple branches.
20
+ *
21
+ * @category Agents
22
+ */
23
+ exports.Store = (0, effection_1.createContext)('lloyal.store');
24
+ /**
25
+ * Effection context holding the agent event channel
26
+ *
27
+ * Set by {@link initAgents}. {@link useAgentPool} emits {@link AgentEvent}
28
+ * values through this channel via `yield* channel.send()`.
29
+ *
30
+ * @category Agents
31
+ */
32
+ exports.Events = (0, effection_1.createContext)('lloyal.events');
33
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":";;;AAAA,yCAA0C;AAM1C;;;;;;;;GAQG;AACU,QAAA,GAAG,GAAG,IAAA,yBAAa,EAAiB,YAAY,CAAC,CAAC;AAE/D;;;;;;;GAOG;AACU,QAAA,KAAK,GAAG,IAAA,yBAAa,EAAc,cAAc,CAAC,CAAC;AAEhE;;;;;;;GAOG;AACU,QAAA,MAAM,GAAG,IAAA,yBAAa,EAA4B,eAAe,CAAC,CAAC"}