@lloyal-labs/lloyal-agents 1.5.8 → 2.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 (68) hide show
  1. package/README.md +81 -97
  2. package/dist/Agent.d.ts +60 -1
  3. package/dist/Agent.d.ts.map +1 -1
  4. package/dist/Agent.js +87 -1
  5. package/dist/Agent.js.map +1 -1
  6. package/dist/AgentPolicy.d.ts +52 -16
  7. package/dist/AgentPolicy.d.ts.map +1 -1
  8. package/dist/AgentPolicy.js +114 -43
  9. package/dist/AgentPolicy.js.map +1 -1
  10. package/dist/agent-pool.d.ts +17 -5
  11. package/dist/agent-pool.d.ts.map +1 -1
  12. package/dist/agent-pool.js +707 -417
  13. package/dist/agent-pool.js.map +1 -1
  14. package/dist/combinators.d.ts +29 -0
  15. package/dist/combinators.d.ts.map +1 -0
  16. package/dist/combinators.js +37 -0
  17. package/dist/combinators.js.map +1 -0
  18. package/dist/context.d.ts +18 -1
  19. package/dist/context.d.ts.map +1 -1
  20. package/dist/context.js +18 -1
  21. package/dist/context.js.map +1 -1
  22. package/dist/create-agent-pool.d.ts +96 -0
  23. package/dist/create-agent-pool.d.ts.map +1 -0
  24. package/dist/create-agent-pool.js +84 -0
  25. package/dist/create-agent-pool.js.map +1 -0
  26. package/dist/index.d.ts +10 -5
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +17 -8
  29. package/dist/index.js.map +1 -1
  30. package/dist/orchestrators.d.ts +161 -0
  31. package/dist/orchestrators.d.ts.map +1 -0
  32. package/dist/orchestrators.js +173 -0
  33. package/dist/orchestrators.js.map +1 -0
  34. package/dist/replay.d.ts +96 -0
  35. package/dist/replay.d.ts.map +1 -0
  36. package/dist/replay.js +108 -0
  37. package/dist/replay.js.map +1 -0
  38. package/dist/shared-root.d.ts +56 -18
  39. package/dist/shared-root.d.ts.map +1 -1
  40. package/dist/shared-root.js +79 -52
  41. package/dist/shared-root.js.map +1 -1
  42. package/dist/source.d.ts.map +1 -1
  43. package/dist/source.js.map +1 -1
  44. package/dist/trace-types.d.ts +23 -2
  45. package/dist/trace-types.d.ts.map +1 -1
  46. package/dist/trace-writer.d.ts +4 -1
  47. package/dist/trace-writer.d.ts.map +1 -1
  48. package/dist/trace-writer.js +6 -2
  49. package/dist/trace-writer.js.map +1 -1
  50. package/dist/types.d.ts +42 -5
  51. package/dist/types.d.ts.map +1 -1
  52. package/dist/use-agent.d.ts +92 -0
  53. package/dist/use-agent.d.ts.map +1 -0
  54. package/dist/use-agent.js +127 -0
  55. package/dist/use-agent.js.map +1 -0
  56. package/package.json +5 -5
  57. package/dist/generate.d.ts +0 -77
  58. package/dist/generate.d.ts.map +0 -1
  59. package/dist/generate.js +0 -166
  60. package/dist/generate.js.map +0 -1
  61. package/dist/run-agents.d.ts +0 -39
  62. package/dist/run-agents.d.ts.map +0 -1
  63. package/dist/run-agents.js +0 -46
  64. package/dist/run-agents.js.map +0 -1
  65. package/dist/spawn-agents.d.ts +0 -104
  66. package/dist/spawn-agents.d.ts.map +0 -1
  67. package/dist/spawn-agents.js +0 -255
  68. package/dist/spawn-agents.js.map +0 -1
package/README.md CHANGED
@@ -1,14 +1,14 @@
1
1
  # @lloyal-labs/lloyal-agents
2
2
 
3
- Continuous Context agent runtime.
3
+ Continuous Context agent runtime for the [lloyal HDK](https://github.com/lloyal-ai/hdk).
4
4
 
5
5
  `lloyal-agents` runs multi-agent inference inside the decode loop. Instead of N independent model calls rebuilding the prompt each step, all agents advance inside one continuous decode process — forked from shared KV cache state, driven through a single GPU forward pass per tick, spawning sub-agents from their own live branches at arbitrary depth.
6
6
 
7
- Built on [lloyal.node](https://github.com/lloyal-ai/lloyal.node), which provides forkable decode state and continuous tree batching over llama.cpp. `lloyal-agents` adds structured concurrency, tool dispatch, and a four-phase tick loop. Orchestration is not a layer above inference. It is inference.
7
+ Built on [lloyal.node](https://github.com/lloyal-ai/lloyal.node), which provides forkable decode state and continuous tree batching over llama.cpp. `lloyal-agents` adds structured concurrency, tool dispatch, and a five-phase tick loop. Orchestration is not a layer above inference it is inference.
8
8
 
9
9
  <picture>
10
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/lloyal-ai/sdk/main/assets/continuous-context-dark.svg">
11
- <img src="https://raw.githubusercontent.com/lloyal-ai/sdk/main/assets/continuous-context.svg" alt="Traditional Agents vs Continuous Context Agents — shared KV prefix, tool prefill, sub-agent spawning" width="100%">
10
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/lloyal-ai/hdk/main/assets/continuous-context-dark.svg">
11
+ <img src="https://raw.githubusercontent.com/lloyal-ai/hdk/main/assets/continuous-context.svg" alt="Traditional Agents vs Continuous Context Agents — shared KV prefix, tool prefill, sub-agent spawning" width="100%">
12
12
  </picture>
13
13
 
14
14
  ```bash
@@ -17,26 +17,25 @@ npm i @lloyal-labs/lloyal-agents @lloyal-labs/lloyal.node
17
17
 
18
18
  `lloyal-agents` provides the agent runtime. [`lloyal.node`](https://github.com/lloyal-ai/lloyal.node) provides the native inference backend — prebuilt binaries for macOS (Metal, CPU), Linux (CPU, CUDA, Vulkan), and Windows (CPU, CUDA, Vulkan). Both are required. GPU selection at runtime.
19
19
 
20
- The public API surface:
20
+ ## Public API
21
21
 
22
22
  ```typescript
23
23
  import {
24
- initAgents, // bootstrap: session, store, event channel
25
- generate, // single-branch grammar-constrained generation
26
- diverge, // multi-branch perplexity selection
27
- useAgentPool, // concurrent agents as an Effection resource
28
- runAgents, // same, with automatic branch cleanup
29
- withSharedRoot, // scoped shared KV prefix with guaranteed teardown
30
- createToolkit, // tool registry from Tool[] toolMap + toolsJson
31
- Ctx,
32
- Store,
33
- Events, // Effection contexts — implicit dependency resolution
24
+ initAgents, // bootstrap: session, store, event channel
25
+ useAgent, agent, // single-agent helpers
26
+ agentPool, // multi-agent pool with a swappable orchestrator
27
+ useAgentPool, // lower-level Effection resource (advanced)
28
+ diverge, // multi-branch perplexity selection
29
+ parallel, chain, fanout, dag, reduce, // orchestrators / combinators
30
+ withSharedRoot, // scoped shared KV prefix with guaranteed teardown
31
+ createToolkit, // tool registry from Tool[] → toolMap + toolsJson
32
+ Tool, Source,
33
+ DefaultAgentPolicy,
34
+ Ctx, Store, Events,
34
35
  } from "@lloyal-labs/lloyal-agents";
35
36
  ```
36
37
 
37
- That is essentially the entire framework.
38
-
39
- ### Bootstrap
38
+ ## Bootstrap
40
39
 
41
40
  ```typescript
42
41
  import { main, call } from "effection";
@@ -47,17 +46,16 @@ main(function* () {
47
46
  const ctx = yield* call(() =>
48
47
  createContext({
49
48
  modelPath: "model.gguf",
50
- nCtx: 16384,
49
+ nCtx: 32768,
51
50
  nSeqMax: 8,
52
51
  typeK: "q4_0",
53
52
  typeV: "q4_0",
54
53
  }),
55
54
  );
56
55
 
57
- const { session, events } = yield* initAgents(ctx);
58
- // Ctx, Store, Events now set — generate(), diverge(),
59
- // useAgentPool() find them automatically.
60
- // Session + context disposed on scope exit.
56
+ yield* initAgents(ctx);
57
+ // Ctx, Store, Events now set — useAgent(), agentPool(), diverge()
58
+ // find them automatically. Session + context disposed on scope exit.
61
59
  });
62
60
  ```
63
61
 
@@ -68,62 +66,52 @@ When agents fork from a common branch, they inherit its KV cache — the full at
68
66
  Everything before the frontier is shared context. Everything after is independent reasoning. The model doesn't need to be told what the other agents know — it already attended over the same prefix. Communication happened at prefill time, through the attention mechanism, with zero serialization overhead.
69
67
 
70
68
  ```typescript
71
- yield *
72
- withSharedRoot(
73
- { systemPrompt: RESEARCH_PROMPT, tools: toolsJson },
74
- function* (root, prefixLen) {
75
- // root is a prefilled branch system prompt already in KV cache.
76
- // Every agent forked from root shares that prefix.
77
- // KV saved = prefixLen × (agentCount - 1)
78
- return yield* runAgents({
79
- tasks: questions.map((q) => ({
80
- systemPrompt: RESEARCH_PROMPT,
69
+ yield* withSharedRoot(
70
+ { systemPrompt: SKILL_CATALOG, toolsJson: toolkit.toolsJson },
71
+ function* (root) {
72
+ // root is a prefilled branch — system prompt + tool schemas already in KV.
73
+ // Every agent forked from root shares that prefix.
74
+ return yield* agentPool({
75
+ orchestrate: parallel(
76
+ questions.map((q) => ({
81
77
  content: q,
82
- tools: toolsJson,
83
- parent: root,
78
+ systemPrompt: WORKER_PROMPT,
84
79
  })),
85
- tools: toolMap,
86
- });
87
- },
88
- );
80
+ ),
81
+ tools: [...sourceTools, reportTool],
82
+ parent: root,
83
+ terminalTool: "report",
84
+ });
85
+ },
86
+ );
89
87
  ```
90
88
 
91
89
  `withSharedRoot` creates the prefix, passes it to the body, and guarantees cleanup via `try/finally` — the root branch cannot leak out of the block. Effection enforces the lifetime.
92
90
 
93
- ## In-Loop Orchestration
91
+ ## Orchestrators
94
92
 
95
- All active agents advance together in a four-phase tick loop:
93
+ `agentPool` accepts an orchestrator that determines how agents are spawned and sequenced:
96
94
 
97
- **PRODUCE.** Every generating agent calls `produceSync()`synchronous sampling with no async gap between agents. This matters because it means the entire produce phase is a single uninterrupted pass over the active set.
95
+ - **`parallel(specs[])`** — agents run concurrently from the shared root.
96
+ - **`chain(specs[], factory)`** — sequential, with `extendRoot` writing each task's findings onto the spine before the next forks.
97
+ - **`fanout(landscapeSpec, domainSpecs[])`** — landscape pass that informs N parallel domain agents.
98
+ - **`dag(nodes[])`** — arbitrary acyclic graph with multi-parent edges (Task-as-Future pattern).
98
99
 
99
- **COMMIT.** One `store.commit()` call packs all produced tokens into a single `llama_batch` and dispatches once. N branches, one GPU call. No per-agent decode overhead.
100
+ Same `agentPool` call shape; the orchestrator argument changes the topology.
100
101
 
101
- **SETTLE.** Tool results that resolved during COMMIT are drained from a buffer. Each result is tokenized into a delta, budget-checked against a fresh `ContextPressure` snapshot, and batch-prefilled into the agent's branch. Grammar state resets. The agent transitions back to `generating`.
102
+ ## In-Loop Orchestration
102
103
 
103
- **DISPATCH.** Tool calls collected during PRODUCE are executed sequentially via `scoped()` + `call()`. Each tool runs to completion before the next begins — no concurrent `llama_decode` during dispatch. Tools return `Operation<unknown>`, so they can `yield*` into framework primitives like `useAgentPool` or `runAgents`, spawning recursive sub-agents within the calling agent's scope.
104
+ All active agents advance together in a five-phase tick loop:
104
105
 
105
- ```typescript
106
- // From the tick loop — Phase 1
107
- const entries: [Branch, number][] = [];
108
- for (const a of agents) {
109
- if (a.state !== "generating") continue;
110
- if (pressure.critical) {
111
- a.state = "done";
112
- continue;
113
- }
106
+ **SPAWN+EXTEND.** The rendezvous point with the orchestrator fiber. Pending agent spawns and `extendRoot` calls are queued via Effection `action()` and drained at the start of each tick — batched into a single `store.prefill()`. Single-fiber discipline preserved across concurrent orchestrator extends.
114
107
 
115
- const { token, text, isStop } = a.branch.produceSync();
116
- if (isStop) {
117
- /* parse tool calls, dispatch or finalize */ continue;
118
- }
119
- entries.push([a.branch, token]);
120
- }
108
+ **PRODUCE.** Every generating agent calls `produceSync()` synchronous sampling with no async gap between agents. The entire produce phase is a single uninterrupted pass over the active set.
121
109
 
122
- // Phase 2 single GPU dispatch
123
- if (entries.length > 0) {
124
- yield * call(() => store.commit(entries));
125
- }
126
- ```
110
+ **COMMIT.** One `store.commit()` call packs all produced tokens into a single `llama_batch` and dispatches once. N branches, one GPU call.
111
+
112
+ **SETTLE.** Tool results that resolved during the prior DISPATCH are drained from a buffer. Each result is tokenized into a delta, budget-checked against a fresh `ContextPressure` snapshot, and batch-prefilled into the agent's branch. Grammar state resets. The agent transitions back to `generating`.
113
+
114
+ **DISPATCH.** Tool calls collected during PRODUCE are executed sequentially via `scoped()` + `call()`. Each tool runs to completion before the next begins. Tools return `Operation<unknown>`, so they can `yield*` into framework primitives like `useAgent` or `agentPool`, spawning recursive sub-agents within the calling agent's scope.
127
115
 
128
116
  When no agent is generating and tools are still pending, the loop yields control until the next tool resolves. No polling. No sleep loops.
129
117
 
@@ -143,13 +131,11 @@ function* setupAgent(parent, task, ctx) {
143
131
  }
144
132
  ```
145
133
 
146
- If the scope exits — error, cancellation, normal completion — the branch is pruned. Orphaned branches are structurally impossible. Tool dispatch uses `scoped()` + `call()` each tool executes inside a scoped error boundary within the agent pool scope. If the scope tears down, pending tools are cancelled. The DAG is not imposed on the orchestration. It is intrinsic to the Effection task tree.
147
-
148
- `useAgentPool` is an Effection `resource()` — it suspends via `provide()` after all agents complete, but keeps their branches alive. The caller can fork sub-agents from any completed agent's branch. Those sub-agents inherit the parent agent's full KV state — everything it generated, every tool result it consumed, every reasoning step it took. No summarization. No context window management. The sub-agent continues from the parent's frontier.
134
+ If the scope exits — error, cancellation, normal completion — the branch is pruned. Orphaned branches are structurally impossible. Tool dispatch uses `scoped()` + `call()`; each tool executes inside a scoped error boundary within the agent pool scope. If the scope tears down, pending tools are cancelled. The DAG is not imposed on the orchestration. It is intrinsic to the Effection task tree.
149
135
 
150
- Recursive agents work at two levels. At the **harness level**, a completed pool's branches can be forked into follow-up pools sub-agents inherit the parent's full KV state and continue from the fork point. At the **model level**, a tool's `execute()` method returns `Operation<unknown>`, so it can `yield*` directly into `useAgentPool` or `runAgents`. An agent that calls such a tool spawns sub-agents mid-generation inside its own scope, inheriting its KV state, with cleanup guaranteed by structured concurrency.
136
+ `useAgentPool` is an Effection `resource()` it suspends via `provide()` after all agents complete, but keeps their branches alive. The caller can fork sub-agents from any completed agent's branch. Those sub-agents inherit the parent agent's full KV state every tool result it consumed, every reasoning step it took. No summarization. No context window management. The sub-agent continues from the parent's frontier.
151
137
 
152
- In both cases, the sub-agent sees everything the parent saw system prompt, tool calls, partial reasoning because that state is already in the KV cache at the fork point. No summarization. No context reconstruction. The sub-agent just continues from the parent's frontier.
138
+ Recursive agents work at two levels. At the **harness level**, a completed pool's branches can be forked into follow-up pools. At the **model level**, a tool's `execute()` returns `Operation<unknown>`, so it can `yield*` directly into `useAgent` or `agentPool`. An agent that calls such a tool spawns sub-agents mid-generation inside its own scope, inheriting its KV state, with cleanup guaranteed by structured concurrency. `DelegateTool` (from [`@lloyal-labs/rig`](../rig)) is the canonical implementation.
153
139
 
154
140
  There is nothing in the framework that limits depth. Agents can spawn sub-agents that spawn sub-agents. An agent pool can run inside another agent pool's scope. The structured concurrency guarantees compose at every level.
155
141
 
@@ -164,16 +150,14 @@ Enable `trace: true` on agent pools to capture entropy and surprisal on every `a
164
150
  **Multi-branch semantic comparison.** `diverge()` forks N branches from a shared frontier, generates independently, and returns all outputs with their perplexity scores:
165
151
 
166
152
  ```typescript
167
- const result =
168
- yield *
169
- diverge({
170
- parent: root, // shared frontier
171
- attempts: 3, // fork 3 branches
172
- params: { temperature: 0.7 },
173
- });
153
+ const result = yield* diverge({
154
+ parent: root, // shared frontier
155
+ attempts: 3, // fork 3 branches
156
+ params: { temperature: 0.7 },
157
+ });
174
158
  // result.best — lowest-perplexity branch, still alive
175
159
  // result.attempts — all branches with output, ppl, token count
176
- // Losers already pruned. Winner's branch is caller's responsibility.
160
+ // Losers already pruned. Winner's branch is the caller's responsibility.
177
161
  ```
178
162
 
179
163
  The harness decides how to compare. `diverge()` returns all outputs with their perplexity scores — the harness can apply any equivalence measure: bigram overlap, embedding similarity, or model-based evaluation. Where branches agree, the model is confident; where they diverge, hallucination risk is high.
@@ -182,27 +166,29 @@ This directly operationalizes the semantic entropy work from Farquhar et al. ([N
182
166
 
183
167
  ## Session Accumulation
184
168
 
185
- `Session.promote(branch)` retains only that branch and makes it the session trunk. Future queries fork from this trunk — its KV cache already contains everything the promoted branch generated, every tool result it consumed, every verification it passed.
169
+ `Session.commitTurn(query, answer)` extends the trunk with a new query–answer pair. Future queries fork from this trunk — its KV cache already contains everything the prior turn established.
170
+
171
+ A cold query starts from position 0. A warm query starts from an existing trunk. Over multiple queries, the session compounds — each turn advances the frontier, and future agents inherit the accumulated state via attention.
186
172
 
187
- A cold query starts from position 0. A warm query starts from an existing trunk. Over multiple queries, the session compounds — each promote advances the frontier, and future agents inherit the accumulated state.
173
+ The lower-level building blocks (`prefillUser`, `prefillToolResult`, `promote`) are also exposed for harnesses that orchestrate the trunk lifecycle directly.
188
174
 
189
175
  ## Context Pressure
190
176
 
191
- KV cache is finite. `ContextPressure` snapshots the remaining budget on every tick and enforces two thresholds:
177
+ KV cache is finite. `ContextPressure` snapshots the remaining budget on every tick and `DefaultAgentPolicy` enforces two thresholds:
192
178
 
193
179
  - **softLimit** (default 1024 tokens remaining): SETTLE rejects tool results that would cross this floor. PRODUCE hard-cuts agents requesting non-terminal tool calls. Terminal tools (e.g. `report`) still pass — agents can always submit findings. INIT drops agents that don't fit above this floor.
194
180
  - **hardLimit** (default 128 tokens remaining): agents killed immediately before `produceSync()`. No decode call is made below this line — it would crash.
195
181
 
196
- Tool result prefill in the SETTLE phase is budget-gated against a fresh pressure snapshot. If a tool result doesn't fit, the agent is terminated rather than risking a context overflow mid-generation. The softLimit reserves space for downstream work — reporter sub-agents, verification passes.
182
+ Tool result prefill in the SETTLE phase is budget-gated against a fresh pressure snapshot. If a tool result doesn't fit, the agent is terminated rather than risking a context overflow mid-generation. The softLimit reserves space for downstream work — synthesis passes, verification.
197
183
 
198
184
  ```typescript
199
- yield *
200
- useAgentPool({
201
- tasks,
202
- tools: toolMap,
203
- terminalTool: "report",
204
- pressure: { softLimit: 2048 }, // reserve 2K for reporters + verify
205
- });
185
+ yield* agentPool({
186
+ orchestrate: parallel(tasks),
187
+ tools, terminalTool: "report",
188
+ policy: new DefaultAgentPolicy({
189
+ budget: { context: { softLimit: 2048 } }, // reserve 2K for downstream
190
+ }),
191
+ });
206
192
  ```
207
193
 
208
194
  ## Tools
@@ -225,19 +211,13 @@ class SearchTool extends Tool<{ query: string }> {
225
211
  };
226
212
 
227
213
  *execute(args: { query: string }, context?: ToolContext): Operation<unknown> {
228
- const results = yield* call(() =>
229
- this.reranker.rank(args.query, this.chunks),
230
- );
231
- context?.onProgress?.({
232
- filled: results.length,
233
- total: this.chunks.length,
234
- });
214
+ const results = yield* call(() => this.reranker.rank(args.query, this.chunks));
235
215
  return results.slice(0, 10);
236
216
  }
237
217
  }
238
218
  ```
239
219
 
240
- `createToolkit(tools)` aggregates tools into a `{ toolMap, toolsJson }` pair — `toolMap` for runtime dispatch, `toolsJson` for prompt formatting.
220
+ `createToolkit(tools)` aggregates tools into a `{ toolMap, toolsJson }` pair — `toolMap` for runtime dispatch, `toolsJson` for prompt formatting. With `withSharedRoot({ systemPrompt, toolsJson })`, the schemas are decoded once at the root and inherited by every fork — see the [skill catalog](https://docs.lloyal.ai/reference/skill-catalog) convention for mixed-role pools.
241
221
 
242
222
  ## Events
243
223
 
@@ -253,6 +233,10 @@ The runtime emits structured events for TUI, logging, or telemetry:
253
233
  | `agent:report` | `agentId`, `findings` |
254
234
  | `agent:done` | `agentId` |
255
235
 
236
+ ## Documentation
237
+
238
+ Full positioning, mechanics, learn pages, and reference at [docs.lloyal.ai](https://docs.lloyal.ai).
239
+
256
240
  ## License
257
241
 
258
242
  Apache-2.0
package/dist/Agent.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import type { Branch } from '@lloyal-labs/sdk';
1
+ import type { Branch, SessionContext, ParseChatOutputResult } from '@lloyal-labs/sdk';
2
2
  import type { GrammarTrigger } from '@lloyal-labs/sdk';
3
+ import { type Signal } from 'effection';
3
4
  import type { TraceToken } from './types';
4
5
  /**
5
6
  * Agent status — domain language for where the agent is in its lifecycle.
@@ -33,6 +34,15 @@ export interface FormatConfig {
33
34
  grammar: string;
34
35
  grammarLazy: boolean;
35
36
  grammarTriggers: GrammarTrigger[];
37
+ /**
38
+ * Whether the template's generation prompt includes `<think>\n` prefill.
39
+ * Must match the value used in every subsequent delta builder call
40
+ * (tool_result, nudge, etc.) for this agent — otherwise the parser's
41
+ * `generation_prompt` diverges from actual KV state and reasoning
42
+ * content leaks into visible content.
43
+ * Captured once at agent setup from the pool's `enableThinking` option.
44
+ */
45
+ enableThinking: boolean;
36
46
  }
37
47
  /**
38
48
  * Metadata for a single tool invocation — what was called, how expensive
@@ -82,6 +92,8 @@ export declare class Agent {
82
92
  /** The task text this agent was assigned — used by echo detection guard */
83
93
  readonly task: string;
84
94
  private _status;
95
+ private _statusSignal;
96
+ private _startedAt;
85
97
  private _rawOutput;
86
98
  private _tokenCount;
87
99
  private _toolCallCount;
@@ -91,6 +103,9 @@ export declare class Agent {
91
103
  private _toolHistory;
92
104
  private _nestedResults;
93
105
  private _traceBuffer;
106
+ private _currentTool;
107
+ private _toolObserved;
108
+ private _parsed;
94
109
  /** The agent that called the tool which spawned this agent's pool (null for top-level) */
95
110
  readonly parent: Agent | null;
96
111
  constructor(opts: {
@@ -102,6 +117,12 @@ export declare class Agent {
102
117
  task?: string;
103
118
  });
104
119
  get status(): AgentStatus;
120
+ /**
121
+ * Signal that fires on every status transition. Used by `PoolContext.waitFor`
122
+ * to suspend until the agent reaches a terminal status. Multi-subscriber —
123
+ * every active listener receives every transition.
124
+ */
125
+ get statusSignal(): Signal<AgentStatus, void>;
105
126
  /**
106
127
  * Transition to a new status. Enforces valid transitions:
107
128
  * - idle → active (first produce)
@@ -110,17 +131,40 @@ export declare class Agent {
110
131
  * - awaiting_tool → active (tool result settled)
111
132
  * - awaiting_tool → idle (settle reject + kill)
112
133
  * - idle → disposed (branch pruned)
134
+ *
135
+ * Emits the new status via `statusSignal` for orchestrator-side observers.
113
136
  */
114
137
  transition(to: AgentStatus): void;
138
+ /**
139
+ * Wall-clock timestamp (performance.now) when the agent first became active.
140
+ * Null until the first idle→active transition. Used by policies to measure
141
+ * per-agent elapsed time independent of when the enclosing pool was created.
142
+ */
143
+ get startedAt(): number | null;
115
144
  get rawOutput(): string;
116
145
  get tokenCount(): number;
117
146
  get toolCallCount(): number;
118
147
  get turns(): number;
119
148
  get traceBuffer(): TraceToken[];
149
+ get currentTool(): string | null;
150
+ get parsed(): ParseChatOutputResult | null;
120
151
  /** Accumulate generated token text into the current turn */
121
152
  accumulateToken(text: string): void;
122
153
  /** Accumulate token with trace data */
123
154
  accumulateTokenWithTrace(text: string, entropy: number, surprisal: number): void;
155
+ /**
156
+ * Partial-parse the in-progress rawOutput to detect which tool the agent
157
+ * is generating. Uses parseChatOutput with isPartial:true — format-agnostic
158
+ * across all model families llama.cpp supports. Latches on first detection:
159
+ * subsequent calls short-circuit without parsing.
160
+ */
161
+ observe(ctx: SessionContext): void;
162
+ /**
163
+ * Strict parse at isStop — replaces the standalone parseChatOutput call in
164
+ * the pool's PRODUCE phase. Returns the full ParseChatOutputResult for
165
+ * downstream consumers (trace writer, policy.onProduced).
166
+ */
167
+ finalize(ctx: SessionContext): ParseChatOutputResult;
124
168
  /** Reset per-turn output after tool result is settled */
125
169
  resetTurn(): void;
126
170
  /** Increment turn counter */
@@ -158,6 +202,21 @@ export declare class Agent {
158
202
  get uniqueCells(): number;
159
203
  /** Whether the grammar allows free text output (not tool-call-only) */
160
204
  get grammarAllowsFreeText(): boolean;
205
+ /**
206
+ * Async iterator — delegates to Branch, accumulates state
207
+ *
208
+ * Each yielded token is already committed to KV (Branch's commit-before-yield
209
+ * semantics). Agent accumulates rawOutput and tokenCount as tokens flow.
210
+ *
211
+ * Available for Layer 1 users who create Agents directly and want to
212
+ * stream with state accumulation. The pool's tick loop does NOT use this
213
+ * iterator — it calls `produceSync()`/`store.commit()` directly for
214
+ * batched multi-agent generation.
215
+ */
216
+ [Symbol.asyncIterator](): AsyncIterableIterator<{
217
+ token: number;
218
+ text: string;
219
+ }>;
161
220
  /** Mark agent as disposed — called by pool when branch is pruned */
162
221
  dispose(): void;
163
222
  }
@@ -1 +1 @@
1
- {"version":3,"file":"Agent.d.ts","sourceRoot":"","sources":["../src/Agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAI1C;;;;;;;;;;GAUG;AACH,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,QAAQ,GAAG,eAAe,GAAG,UAAU,CAAC;AAE3E;;;;GAIG;AACH,MAAM,MAAM,YAAY,GACpB,aAAa,GACb,WAAW,GACX,YAAY,GACZ,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I1B,IAAI,WAAW,IAAI,SAAS,gBAAgB,EAAE,CAA8B;IAE5E,sDAAsD;IACtD,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI;IAM/C,gFAAgF;IAChF,IAAI,aAAa,IAAI,SAAS,MAAM,EAAE,CAAgC;IAEtE,4DAA4D;IAC5D,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI;IAIzC;;;;;;;;;;;;OAYG;IACH,aAAa,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,SAAS,CAAC,EAAE,GAAG,CAAC,EAAE;IAYzD,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,CAAyB;IACpD,IAAI,YAAY,IAAI,YAAY,GAAG,IAAI,CAA+B;IAEtE,gEAAgE;IAChE,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,GAAG,IAAI;IAOzD,IAAI,QAAQ,IAAI,MAAM,CAAiC;IACvD,IAAI,QAAQ,IAAI,MAAM,CAAiC;IACvD,qEAAqE;IACrE,IAAI,WAAW,IAAI,MAAM,CAAwD;IAEjF,uEAAuE;IACvE,IAAI,qBAAqB,IAAI,OAAO,CAEnC;IAID;;;;;;;;;;OAUG;IACI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,qBAAqB,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IASvF,oEAAoE;IACpE,OAAO,IAAI,IAAI;CAIhB"}
package/dist/Agent.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Agent = void 0;
4
+ const effection_1 = require("effection");
4
5
  // ── Agent ───────────────────────────────────────────────────
5
6
  /**
6
7
  * An agent is a branch with intent.
@@ -33,6 +34,8 @@ class Agent {
33
34
  task;
34
35
  // ── Mutable state ───────────────────────────────────────
35
36
  _status = 'idle';
37
+ _statusSignal = (0, effection_1.createSignal)();
38
+ _startedAt = null;
36
39
  _rawOutput = '';
37
40
  _tokenCount = 0;
38
41
  _toolCallCount = 0;
@@ -42,6 +45,9 @@ class Agent {
42
45
  _toolHistory = [];
43
46
  _nestedResults = [];
44
47
  _traceBuffer = [];
48
+ _currentTool = null;
49
+ _toolObserved = false;
50
+ _parsed = null;
45
51
  /** The agent that called the tool which spawned this agent's pool (null for top-level) */
46
52
  parent = null;
47
53
  // ── Constructor ─────────────────────────────────────────
@@ -55,6 +61,12 @@ class Agent {
55
61
  }
56
62
  // ── Status ──────────────────────────────────────────────
57
63
  get status() { return this._status; }
64
+ /**
65
+ * Signal that fires on every status transition. Used by `PoolContext.waitFor`
66
+ * to suspend until the agent reaches a terminal status. Multi-subscriber —
67
+ * every active listener receives every transition.
68
+ */
69
+ get statusSignal() { return this._statusSignal; }
58
70
  /**
59
71
  * Transition to a new status. Enforces valid transitions:
60
72
  * - idle → active (first produce)
@@ -63,6 +75,8 @@ class Agent {
63
75
  * - awaiting_tool → active (tool result settled)
64
76
  * - awaiting_tool → idle (settle reject + kill)
65
77
  * - idle → disposed (branch pruned)
78
+ *
79
+ * Emits the new status via `statusSignal` for orchestrator-side observers.
66
80
  */
67
81
  transition(to) {
68
82
  const from = this._status;
@@ -73,13 +87,25 @@ class Agent {
73
87
  throw new Error(`Invalid agent status transition: ${from} → ${to}`);
74
88
  }
75
89
  this._status = to;
90
+ if (to === 'active' && this._startedAt === null) {
91
+ this._startedAt = performance.now();
92
+ }
93
+ this._statusSignal.send(to);
76
94
  }
95
+ /**
96
+ * Wall-clock timestamp (performance.now) when the agent first became active.
97
+ * Null until the first idle→active transition. Used by policies to measure
98
+ * per-agent elapsed time independent of when the enclosing pool was created.
99
+ */
100
+ get startedAt() { return this._startedAt; }
77
101
  // ── Token accounting ────────────────────────────────────
78
102
  get rawOutput() { return this._rawOutput; }
79
103
  get tokenCount() { return this._tokenCount; }
80
104
  get toolCallCount() { return this._toolCallCount; }
81
105
  get turns() { return this._turns; }
82
106
  get traceBuffer() { return this._traceBuffer; }
107
+ get currentTool() { return this._currentTool; }
108
+ get parsed() { return this._parsed; }
83
109
  /** Accumulate generated token text into the current turn */
84
110
  accumulateToken(text) {
85
111
  this._rawOutput += text;
@@ -91,8 +117,49 @@ class Agent {
91
117
  this._tokenCount++;
92
118
  this._traceBuffer.push({ text, entropy, surprisal });
93
119
  }
120
+ /**
121
+ * Partial-parse the in-progress rawOutput to detect which tool the agent
122
+ * is generating. Uses parseChatOutput with isPartial:true — format-agnostic
123
+ * across all model families llama.cpp supports. Latches on first detection:
124
+ * subsequent calls short-circuit without parsing.
125
+ */
126
+ observe(ctx) {
127
+ if (this._toolObserved)
128
+ return;
129
+ this._parsed = ctx.parseChatOutput(this._rawOutput, this.fmt.format, {
130
+ reasoningFormat: this.fmt.reasoningFormat,
131
+ generationPrompt: this.fmt.generationPrompt,
132
+ parser: this.fmt.parser,
133
+ isPartial: true,
134
+ });
135
+ if (this._parsed.toolCalls.length > 0) {
136
+ this._currentTool = this._parsed.toolCalls[0].name;
137
+ this._toolObserved = true;
138
+ }
139
+ }
140
+ /**
141
+ * Strict parse at isStop — replaces the standalone parseChatOutput call in
142
+ * the pool's PRODUCE phase. Returns the full ParseChatOutputResult for
143
+ * downstream consumers (trace writer, policy.onProduced).
144
+ */
145
+ finalize(ctx) {
146
+ this._parsed = ctx.parseChatOutput(this._rawOutput, this.fmt.format, {
147
+ reasoningFormat: this.fmt.reasoningFormat,
148
+ generationPrompt: this.fmt.generationPrompt,
149
+ parser: this.fmt.parser,
150
+ });
151
+ if (!this._currentTool && this._parsed.toolCalls.length > 0) {
152
+ this._currentTool = this._parsed.toolCalls[0].name;
153
+ }
154
+ return this._parsed;
155
+ }
94
156
  /** Reset per-turn output after tool result is settled */
95
- resetTurn() { this._rawOutput = ''; }
157
+ resetTurn() {
158
+ this._rawOutput = '';
159
+ this._currentTool = null;
160
+ this._toolObserved = false;
161
+ this._parsed = null;
162
+ }
96
163
  /** Increment turn counter */
97
164
  incrementTurns() { this._turns++; }
98
165
  /** Increment tool call counter */
@@ -149,10 +216,29 @@ class Agent {
149
216
  get grammarAllowsFreeText() {
150
217
  return !this.fmt.grammarLazy || !this.fmt.grammar;
151
218
  }
219
+ // ── Async iteration ─────────────────────────────────────
220
+ /**
221
+ * Async iterator — delegates to Branch, accumulates state
222
+ *
223
+ * Each yielded token is already committed to KV (Branch's commit-before-yield
224
+ * semantics). Agent accumulates rawOutput and tokenCount as tokens flow.
225
+ *
226
+ * Available for Layer 1 users who create Agents directly and want to
227
+ * stream with state accumulation. The pool's tick loop does NOT use this
228
+ * iterator — it calls `produceSync()`/`store.commit()` directly for
229
+ * batched multi-agent generation.
230
+ */
231
+ async *[Symbol.asyncIterator]() {
232
+ for await (const produced of this.branch) {
233
+ this.accumulateToken(produced.text);
234
+ yield produced;
235
+ }
236
+ }
152
237
  // ── Lifecycle ───────────────────────────────────────────
153
238
  /** Mark agent as disposed — called by pool when branch is pruned */
154
239
  dispose() {
155
240
  this._status = 'disposed';
241
+ this._statusSignal.send('disposed');
156
242
  }
157
243
  }
158
244
  exports.Agent = Agent;
package/dist/Agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Agent.js","sourceRoot":"","sources":["../src/Agent.ts"],"names":[],"mappings":";;;AAuEA,+DAA+D;AAE/D;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,KAAK;IAChB,2DAA2D;IAE3D,+CAA+C;IACtC,EAAE,CAAS;IAEpB,uEAAuE;IAC9D,QAAQ,CAAS;IAE1B,sCAAsC;IAC7B,MAAM,CAAS;IAExB,4CAA4C;IACnC,GAAG,CAAe;IAE3B,2EAA2E;IAClE,IAAI,CAAS;IAEtB,2DAA2D;IAEnD,OAAO,GAAgB,MAAM,CAAC;IAC9B,UAAU,GAAG,EAAE,CAAC;IAChB,WAAW,GAAG,CAAC,CAAC;IAChB,cAAc,GAAG,CAAC,CAAC;IACnB,MAAM,GAAG,CAAC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