@thoughtminers/agent-runtime-core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +31 -0
- package/dist/agent.d.ts +65 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +324 -0
- package/dist/agent.js.map +1 -0
- package/dist/context/budget.d.ts +23 -0
- package/dist/context/budget.d.ts.map +1 -0
- package/dist/context/budget.js +18 -0
- package/dist/context/budget.js.map +1 -0
- package/dist/context/replay.d.ts +66 -0
- package/dist/context/replay.d.ts.map +1 -0
- package/dist/context/replay.js +171 -0
- package/dist/context/replay.js.map +1 -0
- package/dist/context/summarize.d.ts +12 -0
- package/dist/context/summarize.d.ts.map +1 -0
- package/dist/context/summarize.js +38 -0
- package/dist/context/summarize.js.map +1 -0
- package/dist/generate.d.ts +13 -0
- package/dist/generate.d.ts.map +1 -0
- package/dist/generate.js +69 -0
- package/dist/generate.js.map +1 -0
- package/dist/hooks.d.ts +53 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +76 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/lock/memory.d.ts +12 -0
- package/dist/lock/memory.d.ts.map +1 -0
- package/dist/lock/memory.js +46 -0
- package/dist/lock/memory.js.map +1 -0
- package/dist/loop.d.ts +53 -0
- package/dist/loop.d.ts.map +1 -0
- package/dist/loop.js +165 -0
- package/dist/loop.js.map +1 -0
- package/dist/provider/mock.d.ts +22 -0
- package/dist/provider/mock.d.ts.map +1 -0
- package/dist/provider/mock.js +68 -0
- package/dist/provider/mock.js.map +1 -0
- package/dist/store/conformance.d.ts +9 -0
- package/dist/store/conformance.d.ts.map +1 -0
- package/dist/store/conformance.js +109 -0
- package/dist/store/conformance.js.map +1 -0
- package/dist/store/memory.d.ts +11 -0
- package/dist/store/memory.d.ts.map +1 -0
- package/dist/store/memory.js +94 -0
- package/dist/store/memory.js.map +1 -0
- package/dist/types/events.d.ts +51 -0
- package/dist/types/events.d.ts.map +1 -0
- package/dist/types/events.js +2 -0
- package/dist/types/events.js.map +1 -0
- package/dist/types/hooks.d.ts +96 -0
- package/dist/types/hooks.d.ts.map +1 -0
- package/dist/types/hooks.js +2 -0
- package/dist/types/hooks.js.map +1 -0
- package/dist/types/lock.d.ts +18 -0
- package/dist/types/lock.d.ts.map +1 -0
- package/dist/types/lock.js +11 -0
- package/dist/types/lock.js.map +1 -0
- package/dist/types/provider.d.ts +73 -0
- package/dist/types/provider.d.ts.map +1 -0
- package/dist/types/provider.js +2 -0
- package/dist/types/provider.js.map +1 -0
- package/dist/types/store.d.ts +76 -0
- package/dist/types/store.d.ts.map +1 -0
- package/dist/types/store.js +2 -0
- package/dist/types/store.js.map +1 -0
- package/dist/types/tools.d.ts +49 -0
- package/dist/types/tools.d.ts.map +1 -0
- package/dist/types/tools.js +2 -0
- package/dist/types/tools.js.map +1 -0
- package/dist/types/turns.d.ts +47 -0
- package/dist/types/turns.d.ts.map +1 -0
- package/dist/types/turns.js +7 -0
- package/dist/types/turns.js.map +1 -0
- package/dist/util.d.ts +10 -0
- package/dist/util.d.ts.map +1 -0
- package/dist/util.js +37 -0
- package/dist/util.js.map +1 -0
- package/package.json +38 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 thoughtminers
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# @thoughtminers/agent-runtime-core
|
|
2
|
+
|
|
3
|
+
The zero-dependency agent harness: types, loop, hooks, streaming, abort,
|
|
4
|
+
replay-time context compaction, idempotency, and supersede locking. Imports
|
|
5
|
+
only `node:*` builtins (lint-enforced).
|
|
6
|
+
|
|
7
|
+
See the [repo README](../../README.md) for the full picture. Quick map:
|
|
8
|
+
|
|
9
|
+
| Export | Role |
|
|
10
|
+
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
|
|
11
|
+
| `createAgent(config)` → `{ stream, handle }` | The orchestrator. `stream()` is the primitive; `handle()` collects it. |
|
|
12
|
+
| `Provider` / `ProviderEvent` | The single-turn streaming seam an adapter implements. |
|
|
13
|
+
| `Tool` / `LazyTool` (`CompactionPolicy`) | Model-invoked steps; compaction is data resolved by name at replay. |
|
|
14
|
+
| `PreHook` / `PostHook` (`blocking\|async`, `streamable\|terminal`) | Harness-invoked steps around the loop. |
|
|
15
|
+
| `ConversationStore` (+ `runStoreConformance`) | Two-table storage seam; the conformance suite is the executable spec for adapters. |
|
|
16
|
+
| `Lock` / `Lease` | Per-conversation supersede serialization. `createInMemoryLock()` in-process; `noopLock` default. |
|
|
17
|
+
| `createMockProvider` / `createInMemoryStore` | Deterministic test doubles (used by this package's own 48 tests). |
|
|
18
|
+
| `replayTranscript` / `packByBudget` / `computeBudget` | The context pipeline, exposed for advanced use. |
|
|
19
|
+
|
|
20
|
+
## Behavioral contracts worth knowing
|
|
21
|
+
|
|
22
|
+
- Abort (`AbortSignal`) is checked at every loop boundary and forwarded to the
|
|
23
|
+
provider and every tool; on abort the delivered partial is persisted and the
|
|
24
|
+
run's trace rows are flagged `interrupted`.
|
|
25
|
+
- Parallel tool calls are all answered before the next provider call, as
|
|
26
|
+
consecutive `tool_result` turns (renderers group them into one message).
|
|
27
|
+
- The final allowed turn injects a wrap-up note and forces `toolChoice: 'none'`.
|
|
28
|
+
- An async hook's return value is ignored and its errors are swallowed+logged —
|
|
29
|
+
it can never affect the run (TypeScript's void-assignability makes this a
|
|
30
|
+
runtime guarantee rather than a compile error; the other illegal states are
|
|
31
|
+
compile errors — see `test-d/`).
|
package/dist/agent.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { AgentEvent } from './types/events.js';
|
|
2
|
+
import type { Logger, PostHook, PreHook, StepContext } from './types/hooks.js';
|
|
3
|
+
import type { Lock } from './types/lock.js';
|
|
4
|
+
import type { Provider } from './types/provider.js';
|
|
5
|
+
import type { ConversationStore } from './types/store.js';
|
|
6
|
+
import type { AnyTool } from './types/tools.js';
|
|
7
|
+
import type { Turn } from './types/turns.js';
|
|
8
|
+
/**
|
|
9
|
+
* Tier-2 context overflow seam: invoked when tier-1 (declarative replay
|
|
10
|
+
* compaction + whole-turn packing) still can't fit. See context/summarize.ts.
|
|
11
|
+
*/
|
|
12
|
+
export type TierTwoSummarizer<Ctx = unknown> = (overflowTurns: Turn[], step: StepContext<Ctx>) => Promise<Turn>;
|
|
13
|
+
export interface AgentConfig<Ctx = unknown> {
|
|
14
|
+
provider: Provider;
|
|
15
|
+
model: string;
|
|
16
|
+
/** Default 4096. */
|
|
17
|
+
maxOutputTokens?: number;
|
|
18
|
+
system: string | ((ctx: Ctx) => string | Promise<string>);
|
|
19
|
+
tools?: AnyTool<Ctx>[];
|
|
20
|
+
preHooks?: PreHook<Ctx>[];
|
|
21
|
+
postHooks?: PostHook<Ctx>[];
|
|
22
|
+
/** Default: createInMemoryStore(). */
|
|
23
|
+
store?: ConversationStore;
|
|
24
|
+
/** Default: noopLock (no serialization). Use createInMemoryLock() or a distributed adapter. */
|
|
25
|
+
lock?: Lock;
|
|
26
|
+
/** Default 10. */
|
|
27
|
+
maxTurns?: number;
|
|
28
|
+
/** Fraction of the context window held back from the budget. Default 0.10. */
|
|
29
|
+
safetyMargin?: number;
|
|
30
|
+
summarizer?: TierTwoSummarizer<Ctx>;
|
|
31
|
+
log?: Logger;
|
|
32
|
+
/** Injectable clock — keeps compaction deterministic in tests. */
|
|
33
|
+
now?: () => number;
|
|
34
|
+
newId?: () => string;
|
|
35
|
+
}
|
|
36
|
+
export interface InboundMessage<Ctx = unknown> {
|
|
37
|
+
conversationId: string;
|
|
38
|
+
text: string;
|
|
39
|
+
ctx: Ctx;
|
|
40
|
+
/** Transport message id — idempotency key (duplicates short-circuit). */
|
|
41
|
+
externalMessageId?: string;
|
|
42
|
+
/** Combined with the lease's supersede signal via AbortSignal.any. */
|
|
43
|
+
signal?: AbortSignal;
|
|
44
|
+
}
|
|
45
|
+
export interface AgentResult {
|
|
46
|
+
response: string;
|
|
47
|
+
interrupted: boolean;
|
|
48
|
+
halted: boolean;
|
|
49
|
+
turns: number;
|
|
50
|
+
events: AgentEvent[];
|
|
51
|
+
}
|
|
52
|
+
export interface Agent<Ctx = unknown> {
|
|
53
|
+
/** The primitive: the full run as an event stream. */
|
|
54
|
+
stream(msg: InboundMessage<Ctx>): AsyncIterable<AgentEvent>;
|
|
55
|
+
/** handle() = collect(stream()). */
|
|
56
|
+
handle(msg: InboundMessage<Ctx>): Promise<AgentResult>;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Well-known state key: blocking pre-hooks may push strings here
|
|
60
|
+
* (enrichment — URL summaries, attachment digests, ...). They are injected
|
|
61
|
+
* into the model context as an EPHEMERAL user turn, never persisted.
|
|
62
|
+
*/
|
|
63
|
+
export declare const CONTEXT_NOTES_KEY = "contextNotes";
|
|
64
|
+
export declare const createAgent: <Ctx = unknown>(config: AgentConfig<Ctx>) => Agent<Ctx>;
|
|
65
|
+
//# sourceMappingURL=agent.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAGV,MAAM,EACN,QAAQ,EACR,OAAO,EACP,WAAW,EACZ,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAG7C;;;GAGG;AACH,MAAM,MAAM,iBAAiB,CAAC,GAAG,GAAG,OAAO,IAAI,CAC7C,aAAa,EAAE,IAAI,EAAE,EACrB,IAAI,EAAE,WAAW,CAAC,GAAG,CAAC,KACnB,OAAO,CAAC,IAAI,CAAC,CAAC;AAEnB,MAAM,WAAW,WAAW,CAAC,GAAG,GAAG,OAAO;IACxC,QAAQ,EAAE,QAAQ,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,oBAAoB;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,MAAM,GAAG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aAAa,CAAC,UAAU,CAAC,CAAC;IAC5D,oCAAoC;IACpC,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;CACxD;AAED;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;AAiBhD,eAAO,MAAM,WAAW,GAAI,GAAG,GAAG,OAAO,EAAE,QAAQ,WAAW,CAAC,GAAG,CAAC,KAAG,KAAK,CAAC,GAAG,CA2T9E,CAAC"}
|
package/dist/agent.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { computeBudget } from './context/budget.js';
|
|
3
|
+
import { replayTranscript } from './context/replay.js';
|
|
4
|
+
import { generate } from './generate.js';
|
|
5
|
+
import { applyStreamableTransforms, fireAsyncPostHooks, makeFrozenStep, planPostHooks, runPreHooks, runTerminalPostHooks, } from './hooks.js';
|
|
6
|
+
import { noopLock } from './lock/memory.js';
|
|
7
|
+
import { runLoop, toToolSpecs } from './loop.js';
|
|
8
|
+
import { createInMemoryStore } from './store/memory.js';
|
|
9
|
+
import { consoleLogger, isAbortError, throwIfAborted } from './util.js';
|
|
10
|
+
/**
|
|
11
|
+
* Well-known state key: blocking pre-hooks may push strings here
|
|
12
|
+
* (enrichment — URL summaries, attachment digests, ...). They are injected
|
|
13
|
+
* into the model context as an EPHEMERAL user turn, never persisted.
|
|
14
|
+
*/
|
|
15
|
+
export const CONTEXT_NOTES_KEY = 'contextNotes';
|
|
16
|
+
/**
|
|
17
|
+
* Insert the ephemeral context-notes turn (pre-hook enrichment) immediately
|
|
18
|
+
* BEFORE the current user message — injected into the wire, never persisted.
|
|
19
|
+
*/
|
|
20
|
+
const injectContextNotes = (turns, state) => {
|
|
21
|
+
const notes = state[CONTEXT_NOTES_KEY];
|
|
22
|
+
if (!Array.isArray(notes) || notes.length === 0)
|
|
23
|
+
return turns;
|
|
24
|
+
const noteTurn = { role: 'user', content: `[Context]\n${notes.join('\n')}` };
|
|
25
|
+
const last = turns.at(-1);
|
|
26
|
+
if (last && last.role === 'user') {
|
|
27
|
+
return [...turns.slice(0, -1), noteTurn, last];
|
|
28
|
+
}
|
|
29
|
+
return [...turns, noteTurn];
|
|
30
|
+
};
|
|
31
|
+
export const createAgent = (config) => {
|
|
32
|
+
const store = config.store ?? createInMemoryStore();
|
|
33
|
+
const lock = config.lock ?? noopLock;
|
|
34
|
+
const log = config.log ?? consoleLogger;
|
|
35
|
+
const newId = config.newId ?? randomUUID;
|
|
36
|
+
const now = config.now ?? Date.now;
|
|
37
|
+
const maxOutputTokens = config.maxOutputTokens ?? 4096;
|
|
38
|
+
const maxTurns = config.maxTurns ?? 10;
|
|
39
|
+
async function* stream(msg) {
|
|
40
|
+
const runId = newId();
|
|
41
|
+
yield { type: 'run_start', runId, conversationId: msg.conversationId };
|
|
42
|
+
// Idempotency: a duplicate delivery short-circuits without touching the model.
|
|
43
|
+
if (msg.externalMessageId !== undefined &&
|
|
44
|
+
(await store.seen(msg.conversationId, msg.externalMessageId))) {
|
|
45
|
+
yield { type: 'done', response: '', interrupted: false, halted: true, turns: 0 };
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
// Persist the inbound message BEFORE claiming the lock, so a run that
|
|
49
|
+
// supersedes this one still answers it (fuller-context contract).
|
|
50
|
+
await store.appendMessage({
|
|
51
|
+
conversationId: msg.conversationId,
|
|
52
|
+
role: 'user',
|
|
53
|
+
content: msg.text,
|
|
54
|
+
externalMessageId: msg.externalMessageId ?? null,
|
|
55
|
+
});
|
|
56
|
+
await store.appendTrace({
|
|
57
|
+
conversationId: msg.conversationId,
|
|
58
|
+
runId,
|
|
59
|
+
role: 'user',
|
|
60
|
+
content: msg.text,
|
|
61
|
+
toolCalls: null,
|
|
62
|
+
model: null,
|
|
63
|
+
usage: null,
|
|
64
|
+
latencyMs: null,
|
|
65
|
+
});
|
|
66
|
+
const lease = await lock.claim(msg.conversationId);
|
|
67
|
+
const signal = msg.signal ? AbortSignal.any([lease.signal, msg.signal]) : lease.signal;
|
|
68
|
+
/** Text actually delivered to the consumer so far (post-transform). */
|
|
69
|
+
let delivered = '';
|
|
70
|
+
let turnsSeen = 0;
|
|
71
|
+
try {
|
|
72
|
+
throwIfAborted(signal);
|
|
73
|
+
const system = typeof config.system === 'function' ? await config.system(msg.ctx) : config.system;
|
|
74
|
+
const state = {};
|
|
75
|
+
const llmForModel = (hookModel) => async (req) => {
|
|
76
|
+
const result = await generate(config.provider, {
|
|
77
|
+
model: req.model ?? hookModel ?? config.model,
|
|
78
|
+
maxOutputTokens: req.maxOutputTokens ?? 1024,
|
|
79
|
+
...(req.system !== undefined ? { system: req.system } : {}),
|
|
80
|
+
turns: [{ role: 'user', content: req.prompt }],
|
|
81
|
+
}, { signal });
|
|
82
|
+
return result.text;
|
|
83
|
+
};
|
|
84
|
+
const liveStep = (model) => ({
|
|
85
|
+
conversationId: msg.conversationId,
|
|
86
|
+
runId,
|
|
87
|
+
input: msg.text,
|
|
88
|
+
state,
|
|
89
|
+
ctx: msg.ctx,
|
|
90
|
+
llm: llmForModel(model),
|
|
91
|
+
store,
|
|
92
|
+
signal,
|
|
93
|
+
log,
|
|
94
|
+
});
|
|
95
|
+
const steps = {
|
|
96
|
+
live: liveStep,
|
|
97
|
+
frozen: (model) => makeFrozenStep(liveStep(model)),
|
|
98
|
+
};
|
|
99
|
+
// ── Pre-hooks ─────────────────────────────────────────────────────────
|
|
100
|
+
const preGen = runPreHooks(config.preHooks ?? [], steps, log);
|
|
101
|
+
let preResult;
|
|
102
|
+
while (true) {
|
|
103
|
+
const n = await preGen.next();
|
|
104
|
+
if (n.done) {
|
|
105
|
+
preResult = n.value;
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
yield n.value;
|
|
109
|
+
}
|
|
110
|
+
if (preResult.action !== 'continue') {
|
|
111
|
+
const response = preResult.response;
|
|
112
|
+
await store.appendMessage({
|
|
113
|
+
conversationId: msg.conversationId,
|
|
114
|
+
role: 'assistant',
|
|
115
|
+
content: response,
|
|
116
|
+
externalMessageId: null,
|
|
117
|
+
});
|
|
118
|
+
// Keep the trace complete: the canned reply is part of what the model
|
|
119
|
+
// must see on the next run.
|
|
120
|
+
await store.appendTrace({
|
|
121
|
+
conversationId: msg.conversationId,
|
|
122
|
+
runId,
|
|
123
|
+
role: 'assistant',
|
|
124
|
+
content: response,
|
|
125
|
+
toolCalls: null,
|
|
126
|
+
model: null,
|
|
127
|
+
usage: null,
|
|
128
|
+
latencyMs: null,
|
|
129
|
+
});
|
|
130
|
+
yield { type: 'text_delta', text: response };
|
|
131
|
+
yield { type: 'done', response, interrupted: false, halted: true, turns: 0 };
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
// ── Context assembly: replay the trace with compaction + packing ─────
|
|
135
|
+
const history = await store.loadHistory(msg.conversationId);
|
|
136
|
+
const tools = config.tools ?? [];
|
|
137
|
+
const budget = computeBudget({
|
|
138
|
+
contextWindow: config.provider.contextWindow(config.model),
|
|
139
|
+
system,
|
|
140
|
+
maxOutputTokens,
|
|
141
|
+
toolSpecs: toToolSpecs(tools),
|
|
142
|
+
safetyMargin: config.safetyMargin ?? 0.1,
|
|
143
|
+
});
|
|
144
|
+
const lazyCtx = {
|
|
145
|
+
conversationId: msg.conversationId,
|
|
146
|
+
ctx: msg.ctx,
|
|
147
|
+
signal,
|
|
148
|
+
log,
|
|
149
|
+
};
|
|
150
|
+
const packed = await replayTranscript({
|
|
151
|
+
trace: history.trace,
|
|
152
|
+
tools,
|
|
153
|
+
now: now(),
|
|
154
|
+
currentRunId: runId,
|
|
155
|
+
lazyCtx,
|
|
156
|
+
budget,
|
|
157
|
+
});
|
|
158
|
+
let initialTurns = packed.turns;
|
|
159
|
+
if (packed.dropped.length > 0 && config.summarizer) {
|
|
160
|
+
// Tier-2: summarize what tier-1 packing had to drop.
|
|
161
|
+
const summaryTurn = await config.summarizer(packed.dropped, liveStep());
|
|
162
|
+
initialTurns = [summaryTurn, ...initialTurns];
|
|
163
|
+
}
|
|
164
|
+
initialTurns = injectContextNotes(initialTurns, state);
|
|
165
|
+
// ── The loop (with streamable transforms / buffer mode at this seam) ──
|
|
166
|
+
const plan = planPostHooks(config.postHooks ?? []);
|
|
167
|
+
let bufferedText = '';
|
|
168
|
+
const loopGen = runLoop({
|
|
169
|
+
provider: config.provider,
|
|
170
|
+
model: config.model,
|
|
171
|
+
maxOutputTokens,
|
|
172
|
+
system,
|
|
173
|
+
initialTurns,
|
|
174
|
+
tools: config.tools ?? [],
|
|
175
|
+
maxTurns,
|
|
176
|
+
signal,
|
|
177
|
+
now,
|
|
178
|
+
makeStep: () => liveStep(),
|
|
179
|
+
persistAssistantTrace: async (row) => {
|
|
180
|
+
await store.appendTrace({
|
|
181
|
+
conversationId: msg.conversationId,
|
|
182
|
+
runId,
|
|
183
|
+
role: 'assistant',
|
|
184
|
+
content: row.content,
|
|
185
|
+
toolCalls: row.toolCalls,
|
|
186
|
+
model: config.model,
|
|
187
|
+
usage: row.usage,
|
|
188
|
+
latencyMs: row.latencyMs,
|
|
189
|
+
});
|
|
190
|
+
},
|
|
191
|
+
});
|
|
192
|
+
let loopResult;
|
|
193
|
+
while (true) {
|
|
194
|
+
const n = await loopGen.next();
|
|
195
|
+
if (n.done) {
|
|
196
|
+
loopResult = n.value;
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
const ev = n.value;
|
|
200
|
+
if (ev.type === 'turn_end')
|
|
201
|
+
turnsSeen++;
|
|
202
|
+
if (ev.type === 'text_delta') {
|
|
203
|
+
const transformed = await applyStreamableTransforms(ev.text, plan, steps);
|
|
204
|
+
if (transformed.length === 0)
|
|
205
|
+
continue;
|
|
206
|
+
if (plan.bufferMode) {
|
|
207
|
+
bufferedText += transformed;
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
delivered += transformed;
|
|
211
|
+
yield { type: 'text_delta', text: transformed };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
yield ev;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
// ── Terminal post-hooks (buffer mode only, by construction) ──────────
|
|
219
|
+
let finalText = plan.bufferMode ? bufferedText : delivered;
|
|
220
|
+
let halted = false;
|
|
221
|
+
const termGen = runTerminalPostHooks(finalText, plan, steps);
|
|
222
|
+
while (true) {
|
|
223
|
+
const n = await termGen.next();
|
|
224
|
+
if (n.done) {
|
|
225
|
+
finalText = n.value.text;
|
|
226
|
+
halted = n.value.halted;
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
yield n.value;
|
|
230
|
+
}
|
|
231
|
+
if (plan.bufferMode && finalText.length > 0) {
|
|
232
|
+
delivered = finalText;
|
|
233
|
+
yield { type: 'text_delta', text: finalText };
|
|
234
|
+
}
|
|
235
|
+
// ── Persist the user-facing reply ────────────────────────────────────
|
|
236
|
+
if (finalText.length > 0) {
|
|
237
|
+
await store.appendMessage({
|
|
238
|
+
conversationId: msg.conversationId,
|
|
239
|
+
role: 'assistant',
|
|
240
|
+
content: finalText,
|
|
241
|
+
externalMessageId: null,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
// ── Async post-hooks (fire-and-forget, final text known) ─────────────
|
|
245
|
+
for (const hook of plan.async) {
|
|
246
|
+
yield { type: 'hook_start', phase: 'post', hook: hook.name };
|
|
247
|
+
}
|
|
248
|
+
fireAsyncPostHooks(finalText, plan, steps, log);
|
|
249
|
+
yield {
|
|
250
|
+
type: 'done',
|
|
251
|
+
response: finalText,
|
|
252
|
+
interrupted: false,
|
|
253
|
+
halted,
|
|
254
|
+
turns: loopResult.turns,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
if (isAbortError(err)) {
|
|
259
|
+
if (delivered.length > 0) {
|
|
260
|
+
// History must match what the user actually saw: persist the partial.
|
|
261
|
+
await store.appendMessage({
|
|
262
|
+
conversationId: msg.conversationId,
|
|
263
|
+
role: 'assistant',
|
|
264
|
+
content: delivered,
|
|
265
|
+
externalMessageId: null,
|
|
266
|
+
interrupted: true,
|
|
267
|
+
});
|
|
268
|
+
// Mirror it into the trace unless the loop already persisted an
|
|
269
|
+
// assistant row for this run (e.g. abort during tool execution).
|
|
270
|
+
const h = await store.loadHistory(msg.conversationId);
|
|
271
|
+
const hasAssistantRow = h.trace.some((t) => t.runId === runId && t.role === 'assistant');
|
|
272
|
+
if (!hasAssistantRow) {
|
|
273
|
+
await store.appendTrace({
|
|
274
|
+
conversationId: msg.conversationId,
|
|
275
|
+
runId,
|
|
276
|
+
role: 'assistant',
|
|
277
|
+
content: delivered,
|
|
278
|
+
toolCalls: null,
|
|
279
|
+
model: config.model,
|
|
280
|
+
usage: null,
|
|
281
|
+
latencyMs: null,
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
await store.markRunInterrupted(runId);
|
|
286
|
+
yield {
|
|
287
|
+
type: 'done',
|
|
288
|
+
response: delivered,
|
|
289
|
+
interrupted: true,
|
|
290
|
+
halted: false,
|
|
291
|
+
turns: turnsSeen,
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
yield { type: 'error', message: err instanceof Error ? err.message : String(err) };
|
|
296
|
+
throw err;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
finally {
|
|
300
|
+
await lease.release();
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
const handle = async (msg) => {
|
|
304
|
+
const events = [];
|
|
305
|
+
let result = null;
|
|
306
|
+
for await (const ev of stream(msg)) {
|
|
307
|
+
events.push(ev);
|
|
308
|
+
if (ev.type === 'done') {
|
|
309
|
+
result = {
|
|
310
|
+
response: ev.response,
|
|
311
|
+
interrupted: ev.interrupted,
|
|
312
|
+
halted: ev.halted,
|
|
313
|
+
turns: ev.turns,
|
|
314
|
+
events,
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
if (!result)
|
|
319
|
+
throw new Error('agent stream ended without a done event');
|
|
320
|
+
return result;
|
|
321
|
+
};
|
|
322
|
+
return { stream, handle };
|
|
323
|
+
};
|
|
324
|
+
//# sourceMappingURL=agent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,cAAc,EACd,aAAa,EACb,WAAW,EACX,oBAAoB,GAErB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAexD,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AA4DxE;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,cAAc,CAAC;AAEhD;;;GAGG;AACH,MAAM,kBAAkB,GAAG,CAAC,KAAa,EAAE,KAA8B,EAAU,EAAE;IACnF,MAAM,KAAK,GAAG,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACvC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,QAAQ,GAAS,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC;IAC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C,CAAC;IAEF,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC5B,CAAC,CAAC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ToolSpec } from '../types/provider.js';
|
|
2
|
+
import type { Turn } from '../types/turns.js';
|
|
3
|
+
/**
|
|
4
|
+
* chars/4 heuristic. Deliberately cheap: the 10% safety margin in the budget
|
|
5
|
+
* is what makes this estimate safe. Providers may expose an accurate
|
|
6
|
+
* countTokens; the harness never requires it.
|
|
7
|
+
*/
|
|
8
|
+
export declare const estimateTokens: (text: string) => number;
|
|
9
|
+
export declare const estimateTurnTokens: (turn: Turn) => number;
|
|
10
|
+
export interface BudgetOptions {
|
|
11
|
+
contextWindow: number;
|
|
12
|
+
system: string;
|
|
13
|
+
maxOutputTokens: number;
|
|
14
|
+
toolSpecs: ToolSpec[];
|
|
15
|
+
/** Fraction of the window held back as slack for the estimator. */
|
|
16
|
+
safetyMargin: number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Token budget available to HISTORY:
|
|
20
|
+
* window − system − output reservation − tool schemas − safety margin.
|
|
21
|
+
*/
|
|
22
|
+
export declare const computeBudget: (opts: BudgetOptions) => number;
|
|
23
|
+
//# sourceMappingURL=budget.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"budget.d.ts","sourceRoot":"","sources":["../../src/context/budget.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAE9C;;;;GAIG;AACH,eAAO,MAAM,cAAc,GAAI,MAAM,MAAM,KAAG,MAAoC,CAAC;AAEnF,eAAO,MAAM,kBAAkB,GAAI,MAAM,IAAI,KAAG,MAA8C,CAAC;AAE/F,MAAM,WAAW,aAAa;IAC5B,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,QAAQ,EAAE,CAAC;IACtB,mEAAmE;IACnE,YAAY,EAAE,MAAM,CAAC;CACtB;AAED;;;GAGG;AACH,eAAO,MAAM,aAAa,GAAI,MAAM,aAAa,KAAG,MAMnD,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chars/4 heuristic. Deliberately cheap: the 10% safety margin in the budget
|
|
3
|
+
* is what makes this estimate safe. Providers may expose an accurate
|
|
4
|
+
* countTokens; the harness never requires it.
|
|
5
|
+
*/
|
|
6
|
+
export const estimateTokens = (text) => Math.ceil(text.length / 4);
|
|
7
|
+
export const estimateTurnTokens = (turn) => estimateTokens(JSON.stringify(turn));
|
|
8
|
+
/**
|
|
9
|
+
* Token budget available to HISTORY:
|
|
10
|
+
* window − system − output reservation − tool schemas − safety margin.
|
|
11
|
+
*/
|
|
12
|
+
export const computeBudget = (opts) => {
|
|
13
|
+
const margin = Math.floor(opts.contextWindow * opts.safetyMargin);
|
|
14
|
+
const toolTokens = estimateTokens(JSON.stringify(opts.toolSpecs));
|
|
15
|
+
const budget = opts.contextWindow - estimateTokens(opts.system) - opts.maxOutputTokens - toolTokens - margin;
|
|
16
|
+
return Math.max(budget, 0);
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=budget.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"budget.js","sourceRoot":"","sources":["../../src/context/budget.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,IAAY,EAAU,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAEnF,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,IAAU,EAAU,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;AAW/F;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,IAAmB,EAAU,EAAE;IAC3D,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC;IAClE,MAAM,UAAU,GAAG,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAClE,MAAM,MAAM,GACV,IAAI,CAAC,aAAa,GAAG,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,eAAe,GAAG,UAAU,GAAG,MAAM,CAAC;IAChG,OAAO,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AAC7B,CAAC,CAAC"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { LazyContext } from '../types/hooks.js';
|
|
2
|
+
import type { TraceRecord } from '../types/store.js';
|
|
3
|
+
import type { AnyTool } from '../types/tools.js';
|
|
4
|
+
import type { Turn } from '../types/turns.js';
|
|
5
|
+
/**
|
|
6
|
+
* The replay pipeline: turn the append-only trace back into model context.
|
|
7
|
+
* Three passes:
|
|
8
|
+
* 1. expandAndCompact — one trace row → 1..N turns, applying each tool
|
|
9
|
+
* call's CompactionPolicy (resolved by NAME — pure data, retroactive).
|
|
10
|
+
* 2. rehydrate — re-run side-effect-free lazyload tools whose result
|
|
11
|
+
* survived compaction verbatim, splicing fresh values in.
|
|
12
|
+
* 3. packByBudget — include whole RUN blocks newest→oldest until the
|
|
13
|
+
* budget is exhausted, then restore chronological order.
|
|
14
|
+
*
|
|
15
|
+
* Passes 1 and 3 are pure (`now` is injected → deterministic tests);
|
|
16
|
+
* pass 2 executes lazy tools only.
|
|
17
|
+
*/
|
|
18
|
+
interface PreparedTurn {
|
|
19
|
+
turn: Turn;
|
|
20
|
+
/** Present iff a lazyload stub survived verbatim → re-execute at replay. */
|
|
21
|
+
rehydration?: {
|
|
22
|
+
name: string;
|
|
23
|
+
input: unknown;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export interface RunBlock {
|
|
27
|
+
runId: string;
|
|
28
|
+
turns: PreparedTurn[];
|
|
29
|
+
}
|
|
30
|
+
/** Pass 1: trace rows → run blocks with compaction applied. Pure. */
|
|
31
|
+
export declare const expandAndCompact: <Ctx>(trace: TraceRecord[], tools: AnyTool<Ctx>[], now: number, currentRunId?: string) => RunBlock[];
|
|
32
|
+
/**
|
|
33
|
+
* Pass 2: re-run each surviving lazyload tool and splice its fresh result in.
|
|
34
|
+
* Failure keeps the "lazy result unavailable" stub — never throws.
|
|
35
|
+
* (Expired/dropped calls lost their rehydration marker in pass 1 and are
|
|
36
|
+
* never re-executed.)
|
|
37
|
+
*/
|
|
38
|
+
export declare const rehydrate: <Ctx>(blocks: RunBlock[], tools: AnyTool<Ctx>[], lazyCtx: LazyContext<Ctx>) => Promise<void>;
|
|
39
|
+
export interface PackedContext {
|
|
40
|
+
turns: Turn[];
|
|
41
|
+
/** Chronological turns that did NOT fit — tier-2 summarizer input. */
|
|
42
|
+
dropped: Turn[];
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Pass 3: include whole run blocks newest→oldest while they fit, then restore
|
|
46
|
+
* chronological order. Whole-block granularity keeps every assistant toolCalls
|
|
47
|
+
* turn paired with its tool_result turns (providers reject orphans).
|
|
48
|
+
* The NEWEST block is always included, even over budget — dropping the current
|
|
49
|
+
* user message would break the request (tier-2 summarization is the pressure
|
|
50
|
+
* valve, provider-side limits the backstop).
|
|
51
|
+
* The final window is advanced to start on a user turn.
|
|
52
|
+
*/
|
|
53
|
+
export declare const packByBudget: (blocks: RunBlock[], budget: number) => PackedContext;
|
|
54
|
+
export interface ReplayOptions<Ctx> {
|
|
55
|
+
trace: TraceRecord[];
|
|
56
|
+
tools: AnyTool<Ctx>[];
|
|
57
|
+
now: number;
|
|
58
|
+
/** The in-flight run — its `drop`-policy tool results stay verbatim. */
|
|
59
|
+
currentRunId?: string;
|
|
60
|
+
lazyCtx: LazyContext<Ctx>;
|
|
61
|
+
budget: number;
|
|
62
|
+
}
|
|
63
|
+
/** Full replay: expandAndCompact → rehydrate → packByBudget. */
|
|
64
|
+
export declare const replayTranscript: <Ctx>(opts: ReplayOptions<Ctx>) => Promise<PackedContext>;
|
|
65
|
+
export {};
|
|
66
|
+
//# sourceMappingURL=replay.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"replay.d.ts","sourceRoot":"","sources":["../../src/context/replay.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,EAAiB,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAG9C;;;;;;;;;;;;GAYG;AAEH,UAAU,YAAY;IACpB,IAAI,EAAE,IAAI,CAAC;IACX,4EAA4E;IAC5E,WAAW,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,CAAC;CAChD;AAED,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,YAAY,EAAE,CAAC;CACvB;AA4DD,qEAAqE;AACrE,eAAO,MAAM,gBAAgB,GAAI,GAAG,EAClC,OAAO,WAAW,EAAE,EACpB,OAAO,OAAO,CAAC,GAAG,CAAC,EAAE,EACrB,KAAK,MAAM,EACX,eAAe,MAAM,KACpB,QAAQ,EAwDV,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,SAAS,GAAU,GAAG,EACjC,QAAQ,QAAQ,EAAE,EAClB,OAAO,OAAO,CAAC,GAAG,CAAC,EAAE,EACrB,SAAS,WAAW,CAAC,GAAG,CAAC,KACxB,OAAO,CAAC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