agent-framework-js 0.1.2 → 0.3.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/CHANGELOG.md +100 -0
- package/README.md +45 -0
- package/dist/agents/index.cjs +7 -7
- package/dist/agents/index.d.cts +6 -6
- package/dist/agents/index.d.ts +6 -6
- package/dist/agents/index.js +2 -2
- package/dist/{chunk-YKZJRE32.cjs → chunk-2WBJEXNY.cjs} +4 -4
- package/dist/{chunk-YKZJRE32.cjs.map → chunk-2WBJEXNY.cjs.map} +1 -1
- package/dist/{chunk-VLSVL5N2.js → chunk-55NB43FN.js} +3 -3
- package/dist/{chunk-VLSVL5N2.js.map → chunk-55NB43FN.js.map} +1 -1
- package/dist/{chunk-YBFLWRO5.cjs → chunk-FDCTSJMB.cjs} +21 -16
- package/dist/chunk-FDCTSJMB.cjs.map +1 -0
- package/dist/{chunk-LMN75W3W.cjs → chunk-I55OVD23.cjs} +4 -3
- package/dist/chunk-I55OVD23.cjs.map +1 -0
- package/dist/{chunk-QJ5XHA6S.cjs → chunk-IHMPSELC.cjs} +4 -4
- package/dist/{chunk-QJ5XHA6S.cjs.map → chunk-IHMPSELC.cjs.map} +1 -1
- package/dist/{chunk-RD5YUB2E.js → chunk-KOPGBIES.js} +15 -10
- package/dist/chunk-KOPGBIES.js.map +1 -0
- package/dist/{chunk-XPXTXOYQ.js → chunk-LC54DGGR.js} +4 -3
- package/dist/chunk-LC54DGGR.js.map +1 -0
- package/dist/{chunk-V472N2PK.js → chunk-PYIZ4PT3.js} +3 -3
- package/dist/{chunk-V472N2PK.js.map → chunk-PYIZ4PT3.js.map} +1 -1
- package/dist/chunk-QD2FFISV.js +327 -0
- package/dist/chunk-QD2FFISV.js.map +1 -0
- package/dist/chunk-XMDGLQFL.cjs +333 -0
- package/dist/chunk-XMDGLQFL.cjs.map +1 -0
- package/dist/declarative/index.cjs +4 -4
- package/dist/declarative/index.d.cts +6 -6
- package/dist/declarative/index.d.ts +6 -6
- package/dist/declarative/index.js +3 -3
- package/dist/{index-D7-znzrc.d.ts → index-C22fqyZQ.d.ts} +7 -5
- package/dist/{index-DdYZeNIu.d.cts → index-b1oTo3Lv.d.cts} +7 -5
- package/dist/index.cjs +34 -30
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +6 -6
- package/dist/mcp/index.d.cts +2 -2
- package/dist/mcp/index.d.ts +2 -2
- package/dist/middleware/index.d.cts +7 -7
- package/dist/middleware/index.d.ts +7 -7
- package/dist/persistence/index.cjs +5 -5
- package/dist/persistence/index.d.cts +3 -3
- package/dist/persistence/index.d.ts +3 -3
- package/dist/persistence/index.js +2 -2
- package/dist/provider-B807EuDV.d.cts +132 -0
- package/dist/provider-CvU3I-Xo.d.ts +132 -0
- package/dist/providers/index.cjs +9 -5
- package/dist/providers/index.d.cts +58 -14
- package/dist/providers/index.d.ts +58 -14
- package/dist/providers/index.js +1 -1
- package/dist/{registry-D4fThGiN.d.cts → registry-BCkSIe0E.d.cts} +2 -2
- package/dist/{registry-CpO0yH5v.d.ts → registry-D-CmT0gk.d.ts} +2 -2
- package/dist/{thread-CWVzTyti.d.ts → thread-BzwE1OnJ.d.cts} +4 -2
- package/dist/{thread-Dfo9LLf7.d.cts → thread-COljUAtD.d.ts} +4 -2
- package/dist/{tool-BZg_znMZ.d.cts → tool-D9Uodu9Y.d.cts} +1 -1
- package/dist/{tool-CSCC87OD.d.ts → tool-LPMc4QQd.d.ts} +1 -1
- package/dist/tools/index.d.cts +4 -4
- package/dist/tools/index.d.ts +4 -4
- package/dist/{types-Cn1g9Tg4.d.cts → types-AlvjoTyS.d.cts} +24 -1
- package/dist/{types-Cn1g9Tg4.d.ts → types-AlvjoTyS.d.ts} +24 -1
- package/dist/workflows/index.d.cts +6 -6
- package/dist/workflows/index.d.ts +6 -6
- package/package.json +4 -4
- package/AGENT_USAGE.md +0 -207
- package/dist/chunk-LMN75W3W.cjs.map +0 -1
- package/dist/chunk-RD5YUB2E.js.map +0 -1
- package/dist/chunk-TLACSVEZ.cjs +0 -201
- package/dist/chunk-TLACSVEZ.cjs.map +0 -1
- package/dist/chunk-UVWQWOLO.js +0 -196
- package/dist/chunk-UVWQWOLO.js.map +0 -1
- package/dist/chunk-XPXTXOYQ.js.map +0 -1
- package/dist/chunk-YBFLWRO5.cjs.map +0 -1
- package/dist/provider-CMAymr1b.d.cts +0 -82
- package/dist/provider-osAtfZ7x.d.ts +0 -82
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.3.0] - 2026-06-16
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **Provider tool calling compatibility (Copilot / OpenAI / Anthropic-via-Copilot).** The
|
|
15
|
+
OpenAI-compatible transport now:
|
|
16
|
+
- **Sanitizes tool names on the wire** to `^[a-zA-Z0-9_-]+$` (dotted MCP names like
|
|
17
|
+
`webiq.browse` → `webiq_browse`) and translates the model's tool-call name back to the
|
|
18
|
+
registry key, so namespaced tools no longer 400. Registry keys and the `server.tool`
|
|
19
|
+
namespacing are unchanged.
|
|
20
|
+
- **Emits assistant `tool_calls` with `content: null`** for tool-call turns. The run loop now
|
|
21
|
+
persists `toolCalls` (and any opaque reasoning blob) on the assistant `Message`, so strict
|
|
22
|
+
providers (e.g. Anthropic) receive a `tool_use` paired with each tool result instead of
|
|
23
|
+
rejecting orphaned tool messages.
|
|
24
|
+
- **Accumulates streamed `delta.tool_calls[]` keyed by `index`** (fragments may start at a
|
|
25
|
+
non-zero index when reasoning occupies 0/1), surfacing them as `tool-call` chunks and in the
|
|
26
|
+
final `done` response.
|
|
27
|
+
- **Transparently re-requests in streaming mode** from `generate` when a reasoning model reports
|
|
28
|
+
`finish_reason: "tool_calls"` without a `tool_calls` array, and **fails loud with a typed
|
|
29
|
+
`ProviderError`** if none materialize (previously the agent stopped silently).
|
|
30
|
+
|
|
31
|
+
### Added
|
|
32
|
+
|
|
33
|
+
- `createCopilotProvider` now sends the **required Copilot identification headers**
|
|
34
|
+
(`Editor-Version`, `Editor-Plugin-Version`, `Copilot-Integration-Id`, `Openai-Intent`) by
|
|
35
|
+
default; they are overridable via the new `headers` option.
|
|
36
|
+
- `createOpenAICompatibleProvider` gains a `headers` option to merge extra request headers
|
|
37
|
+
(the `authorization` header is always credential-derived).
|
|
38
|
+
- `Message` gains optional `toolCalls` and `reasoningOpaque`; `GenerateResponse` gains
|
|
39
|
+
`reasoningOpaque` for thinking continuity. All additive and backward compatible.
|
|
40
|
+
|
|
41
|
+
## [0.2.0] - 2026-06-16
|
|
42
|
+
|
|
43
|
+
### Added
|
|
44
|
+
|
|
45
|
+
- **Multi-model providers**: providers can now be configured with multiple models via `models`
|
|
46
|
+
(with an optional `defaultModel`) — GitHub Copilot commonly exposes several, while
|
|
47
|
+
OpenAI-compatible endpoints stay single-model via the `capabilities` shorthand. Select a model
|
|
48
|
+
per request (`generate({ ..., model })`) or per agent (`createAgent({ ..., model })`). The
|
|
49
|
+
`Provider` interface gains `models` and `model(name?)`, and `resolveModels()` is exported.
|
|
50
|
+
Backward compatible: existing single-`capabilities` usage is unchanged.
|
|
51
|
+
|
|
52
|
+
### Changed
|
|
53
|
+
|
|
54
|
+
- The agent-facing usage guide is now shipped as a loadable skill at
|
|
55
|
+
`.github/skills/agent-framework-usage/SKILL.md` (replacing the former `AGENT_USAGE.md`). All
|
|
56
|
+
references (copilot-instructions, CONTRIBUTING, constitution, package.json) were updated and the
|
|
57
|
+
README now points to the skill.
|
|
58
|
+
|
|
59
|
+
## [0.1.2] - 2026-06-16
|
|
60
|
+
|
|
61
|
+
### Changed
|
|
62
|
+
|
|
63
|
+
- Release pipeline switched to npm **trusted publishing (OIDC)** — token-free publishes
|
|
64
|
+
with provenance from GitHub Actions.
|
|
65
|
+
|
|
66
|
+
## [0.1.1] - 2026-06-16
|
|
67
|
+
|
|
68
|
+
### Added
|
|
69
|
+
|
|
70
|
+
- npm publish metadata: `repository`, `bugs`, `homepage`, `publishConfig` (public access,
|
|
71
|
+
provenance), and a `prepublishOnly` build/test guard.
|
|
72
|
+
|
|
73
|
+
## [0.1.0] - 2026-06-16
|
|
74
|
+
|
|
75
|
+
### Added
|
|
76
|
+
|
|
77
|
+
- Initial release of `agent-framework-js`, a modular, tree-shakeable agent framework for
|
|
78
|
+
no-backend deployments (browser, edge, Node).
|
|
79
|
+
- **Agents**: create/run, streaming, reasoning output, multimodal (text + image) input gating,
|
|
80
|
+
conversation threads with automatic compaction.
|
|
81
|
+
- **Providers**: GitHub Copilot and OpenAI-compatible (e.g. LM Studio) behind a pluggable
|
|
82
|
+
abstraction, caller-injected credentials, exponential-backoff retry.
|
|
83
|
+
- **Tools**: uniform JSON-Schema tool contract, argument validation, source namespacing,
|
|
84
|
+
per-tool enable/disable, per-call timeout, bounded tool-call loop with self-correction.
|
|
85
|
+
- **MCP**: remote (HTTP/SSE) transport everywhere and stdio in Node, adapted onto the tool
|
|
86
|
+
contract with runtime capability gating.
|
|
87
|
+
- **Skills**: progressive disclosure with a client-side keyword index.
|
|
88
|
+
- **Workflows**: sequential, concurrent, handoff, and group patterns; completion signal +
|
|
89
|
+
max-rounds cap; fail-soft/fail-fast policy; bounded concurrency; human-in-the-loop
|
|
90
|
+
yield/resume; fail-closed checkpoints.
|
|
91
|
+
- **Middleware**: request/response pipeline around provider calls.
|
|
92
|
+
- **Persistence**: pluggable store with in-memory and browser (localStorage/IndexedDB) adapters.
|
|
93
|
+
- **Observability**: OpenTelemetry spans with centralized secret redaction.
|
|
94
|
+
- **Declarative**: YAML/JSON agent definitions with format auto-detection.
|
|
95
|
+
- Dual ESM + CJS build with TypeScript types and deep-import subpaths for tree-shaking.
|
|
96
|
+
|
|
97
|
+
[Unreleased]: https://github.com/Varun-Patkar/agent-framework-js/compare/v0.1.2...HEAD
|
|
98
|
+
[0.1.2]: https://github.com/Varun-Patkar/agent-framework-js/compare/v0.1.1...v0.1.2
|
|
99
|
+
[0.1.1]: https://github.com/Varun-Patkar/agent-framework-js/releases/tag/v0.1.1
|
|
100
|
+
[0.1.0]: https://github.com/Varun-Patkar/agent-framework-js/tree/v0.1.1
|
package/README.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# agent-framework-js
|
|
2
2
|
|
|
3
|
+
[](https://www.npmjs.com/package/agent-framework-js)
|
|
4
|
+
[](https://github.com/Varun-Patkar/agent-framework-js/actions/workflows/ci.yml)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
[](https://www.npmjs.com/package/agent-framework-js)
|
|
7
|
+
[](https://www.npmjs.com/package/agent-framework-js)
|
|
8
|
+
|
|
3
9
|
A modular, tree-shakeable JavaScript/TypeScript framework for building and orchestrating AI agents
|
|
4
10
|
in **no-backend** deployments — browser, edge runtimes (e.g. Vercel without serverless functions),
|
|
5
11
|
and Node. It mirrors the in-scope capability set of Microsoft Agent Framework: agents, code tools,
|
|
@@ -36,6 +42,36 @@ const res = await agent.run("Say hello.");
|
|
|
36
42
|
console.log(res.status, res.output);
|
|
37
43
|
```
|
|
38
44
|
|
|
45
|
+
### Multiple models (e.g. GitHub Copilot)
|
|
46
|
+
|
|
47
|
+
A provider can expose several models. Supply `models` (with an optional `defaultModel`), then pick
|
|
48
|
+
one per agent (`model`) or per request. OpenAI-compatible endpoints are usually single-model, so the
|
|
49
|
+
`capabilities` shorthand still works there.
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { createAgent, createCopilotProvider } from "agent-framework-js";
|
|
53
|
+
|
|
54
|
+
const copilot = createCopilotProvider({
|
|
55
|
+
getCredential: () => myCopilotToken,
|
|
56
|
+
models: [
|
|
57
|
+
{ model: "gpt-4o", maxInputTokens: 128000, maxOutputTokens: 16000, supportsVision: true },
|
|
58
|
+
{ model: "o3-mini", maxInputTokens: 200000, maxOutputTokens: 100000, supportsReasoning: true },
|
|
59
|
+
],
|
|
60
|
+
defaultModel: "gpt-4o",
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// Per agent — capabilities (vision/reasoning/context) follow the chosen model:
|
|
64
|
+
const reasoner = createAgent({
|
|
65
|
+
name: "Thinker",
|
|
66
|
+
instructions: "Reason.",
|
|
67
|
+
provider: copilot,
|
|
68
|
+
model: "o3-mini",
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
// Per request:
|
|
72
|
+
await copilot.generate({ messages, model: "o3-mini" });
|
|
73
|
+
```
|
|
74
|
+
|
|
39
75
|
Prefer **deep imports** for the smallest bundle: `agent-framework-js/agents`,
|
|
40
76
|
`/providers`, `/tools`, `/mcp`, `/skills`, `/workflows`, `/middleware`, `/persistence`,
|
|
41
77
|
`/observability`, `/declarative`.
|
|
@@ -94,6 +130,15 @@ npm run lint
|
|
|
94
130
|
npm run typecheck
|
|
95
131
|
```
|
|
96
132
|
|
|
133
|
+
## Agent usage guide
|
|
134
|
+
|
|
135
|
+
A complete, agent-facing usage guide is bundled as a skill at
|
|
136
|
+
[.github/skills/agent-framework-usage/SKILL.md](.github/skills/agent-framework-usage/SKILL.md). Any
|
|
137
|
+
AI coding agent working in this repository can load that skill to understand how to install,
|
|
138
|
+
configure, and use the entire public API (providers, agents, tools, MCP, skills, workflows,
|
|
139
|
+
persistence, observability, declarative agents, safeguards, and the typed error model). It is kept in
|
|
140
|
+
sync with the implemented surface.
|
|
141
|
+
|
|
97
142
|
## License
|
|
98
143
|
|
|
99
144
|
MIT
|
package/dist/agents/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
require('../chunk-5M6ER4ZX.cjs');
|
|
4
|
-
var
|
|
4
|
+
var chunkFDCTSJMB_cjs = require('../chunk-FDCTSJMB.cjs');
|
|
5
5
|
require('../chunk-WSMYH2IN.cjs');
|
|
6
6
|
require('../chunk-TAMJ5HSR.cjs');
|
|
7
7
|
require('../chunk-FSDMBWQV.cjs');
|
|
8
|
-
var
|
|
8
|
+
var chunkI55OVD23_cjs = require('../chunk-I55OVD23.cjs');
|
|
9
9
|
require('../chunk-MQ2XTH3S.cjs');
|
|
10
10
|
require('../chunk-IJASUMIQ.cjs');
|
|
11
11
|
|
|
@@ -13,23 +13,23 @@ require('../chunk-IJASUMIQ.cjs');
|
|
|
13
13
|
|
|
14
14
|
Object.defineProperty(exports, "buildMessages", {
|
|
15
15
|
enumerable: true,
|
|
16
|
-
get: function () { return
|
|
16
|
+
get: function () { return chunkFDCTSJMB_cjs.buildMessages; }
|
|
17
17
|
});
|
|
18
18
|
Object.defineProperty(exports, "createAgent", {
|
|
19
19
|
enumerable: true,
|
|
20
|
-
get: function () { return
|
|
20
|
+
get: function () { return chunkFDCTSJMB_cjs.createAgent; }
|
|
21
21
|
});
|
|
22
22
|
Object.defineProperty(exports, "runLoop", {
|
|
23
23
|
enumerable: true,
|
|
24
|
-
get: function () { return
|
|
24
|
+
get: function () { return chunkFDCTSJMB_cjs.runLoop; }
|
|
25
25
|
});
|
|
26
26
|
Object.defineProperty(exports, "Thread", {
|
|
27
27
|
enumerable: true,
|
|
28
|
-
get: function () { return
|
|
28
|
+
get: function () { return chunkI55OVD23_cjs.Thread; }
|
|
29
29
|
});
|
|
30
30
|
Object.defineProperty(exports, "estimateTokens", {
|
|
31
31
|
enumerable: true,
|
|
32
|
-
get: function () { return
|
|
32
|
+
get: function () { return chunkI55OVD23_cjs.estimateTokens; }
|
|
33
33
|
});
|
|
34
34
|
//# sourceMappingURL=index.cjs.map
|
|
35
35
|
//# sourceMappingURL=index.cjs.map
|
package/dist/agents/index.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { A as Agent, a as AgentConfig, b as AgentInput, G as GenerateFn, L as LoopOptions, c as LoopResult, R as RunChunk, e as RunOptions, f as RunResult, g as RunStatus, h as buildMessages, j as createAgent, r as runLoop } from '../index-
|
|
2
|
-
export { T as Thread, a as ThreadOptions, e as estimateTokens } from '../thread-
|
|
3
|
-
export { C as ContentPart } from '../types-
|
|
1
|
+
export { A as Agent, a as AgentConfig, b as AgentInput, G as GenerateFn, L as LoopOptions, c as LoopResult, R as RunChunk, e as RunOptions, f as RunResult, g as RunStatus, h as buildMessages, j as createAgent, r as runLoop } from '../index-b1oTo3Lv.cjs';
|
|
2
|
+
export { T as Thread, a as ThreadOptions, e as estimateTokens } from '../thread-BzwE1OnJ.cjs';
|
|
3
|
+
export { C as ContentPart } from '../types-AlvjoTyS.cjs';
|
|
4
4
|
import '../errors-CjVz4W_5.cjs';
|
|
5
|
-
import '../provider-
|
|
6
|
-
import '../tool-
|
|
5
|
+
import '../provider-B807EuDV.cjs';
|
|
6
|
+
import '../tool-D9Uodu9Y.cjs';
|
|
7
7
|
import '../skill-DfNChtJN.cjs';
|
|
8
|
-
import '../registry-
|
|
8
|
+
import '../registry-BCkSIe0E.cjs';
|
package/dist/agents/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { A as Agent, a as AgentConfig, b as AgentInput, G as GenerateFn, L as LoopOptions, c as LoopResult, R as RunChunk, e as RunOptions, f as RunResult, g as RunStatus, h as buildMessages, j as createAgent, r as runLoop } from '../index-
|
|
2
|
-
export { T as Thread, a as ThreadOptions, e as estimateTokens } from '../thread-
|
|
3
|
-
export { C as ContentPart } from '../types-
|
|
1
|
+
export { A as Agent, a as AgentConfig, b as AgentInput, G as GenerateFn, L as LoopOptions, c as LoopResult, R as RunChunk, e as RunOptions, f as RunResult, g as RunStatus, h as buildMessages, j as createAgent, r as runLoop } from '../index-C22fqyZQ.js';
|
|
2
|
+
export { T as Thread, a as ThreadOptions, e as estimateTokens } from '../thread-COljUAtD.js';
|
|
3
|
+
export { C as ContentPart } from '../types-AlvjoTyS.js';
|
|
4
4
|
import '../errors-CjVz4W_5.js';
|
|
5
|
-
import '../provider-
|
|
6
|
-
import '../tool-
|
|
5
|
+
import '../provider-CvU3I-Xo.js';
|
|
6
|
+
import '../tool-LPMc4QQd.js';
|
|
7
7
|
import '../skill-DfNChtJN.js';
|
|
8
|
-
import '../registry-
|
|
8
|
+
import '../registry-D-CmT0gk.js';
|
package/dist/agents/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import '../chunk-MCLVWCOB.js';
|
|
2
|
-
export { buildMessages, createAgent, runLoop } from '../chunk-
|
|
2
|
+
export { buildMessages, createAgent, runLoop } from '../chunk-KOPGBIES.js';
|
|
3
3
|
import '../chunk-YCBDEEAV.js';
|
|
4
4
|
import '../chunk-HGEPXJDG.js';
|
|
5
5
|
import '../chunk-7ZXUIHLH.js';
|
|
6
|
-
export { Thread, estimateTokens } from '../chunk-
|
|
6
|
+
export { Thread, estimateTokens } from '../chunk-LC54DGGR.js';
|
|
7
7
|
import '../chunk-IXV4UIF5.js';
|
|
8
8
|
import '../chunk-DEABART4.js';
|
|
9
9
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkFDCTSJMB_cjs = require('./chunk-FDCTSJMB.cjs');
|
|
4
4
|
var chunkMQ2XTH3S_cjs = require('./chunk-MQ2XTH3S.cjs');
|
|
5
5
|
|
|
6
6
|
// src/declarative/loader.ts
|
|
@@ -35,7 +35,7 @@ async function loadAgentDefinition(source, deps) {
|
|
|
35
35
|
const provider = deps.providerFactory(parsed.provider, deps.getCredential);
|
|
36
36
|
const tools = (parsed.tools ?? []).map((name) => deps.tools?.[name]).filter((t) => !!t);
|
|
37
37
|
const skills = (parsed.skills ?? []).map((name) => deps.skills?.[name]).filter((s) => !!s);
|
|
38
|
-
return
|
|
38
|
+
return chunkFDCTSJMB_cjs.createAgent({
|
|
39
39
|
name: parsed.name,
|
|
40
40
|
instructions: parsed.instructions,
|
|
41
41
|
provider,
|
|
@@ -46,5 +46,5 @@ async function loadAgentDefinition(source, deps) {
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
exports.loadAgentDefinition = loadAgentDefinition;
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
50
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-2WBJEXNY.cjs.map
|
|
50
|
+
//# sourceMappingURL=chunk-2WBJEXNY.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/declarative/loader.ts"],"names":["ValidationError","createAgent"],"mappings":";;;;;;AA+CA,SAAS,cAAc,MAAA,EAAyB;AAC/C,EAAA,MAAM,CAAA,GAAI,OAAO,SAAA,EAAU;AAC3B,EAAA,OAAO,EAAE,UAAA,CAAW,GAAG,CAAA,IAAK,CAAA,CAAE,WAAW,GAAG,CAAA;AAC7C;AAEA,eAAe,MAAM,MAAA,EAAkC;AACtD,EAAA,IAAI,aAAA,CAAc,MAAM,CAAA,EAAG;AAC1B,IAAA,IAAI;AACH,MAAA,OAAO,IAAA,CAAK,MAAM,MAAM,CAAA;AAAA,IACzB,SAAS,CAAA,EAAG;AACX,MAAA,MAAM,IAAIA,iCAAA,CAAgB,CAAA,yBAAA,EAA6B,CAAA,CAAY,OAAO,CAAA,CAAE,CAAA;AAAA,IAC7E;AAAA,EACD;AAEA,EAAA,MAAM,IAAA,GAAO,MAAM,OAAO,MAAM,CAAA;AAChC,EAAA,IAAI;AACH,IAAA,OAAO,IAAA,CAAK,MAAM,MAAM,CAAA;AAAA,EACzB,SAAS,CAAA,EAAG;AACX,IAAA,MAAM,IAAIA,iCAAA,CAAgB,CAAA,yBAAA,EAA6B,CAAA,CAAY,OAAO,CAAA,CAAE,CAAA;AAAA,EAC7E;AACD;AAEA,SAAS,iBAAiB,KAAA,EAAkD;AAC3E,EAAA,MAAM,CAAA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AC,EAC9B,GAAA,CAAI,CAAC,IAAA,KAAS,IAAA,CAAK,KAAA,GAAQ,IAAI,CAAC,CAAA,CAChC,MAAA,CAAO,CAAC,CAAA,KAAiB,CAAC,CAAC,CAAC,CAAA;AAC9B,EAAA,MAAM,UAAU,MAAA,CAAO,MAAA,IAAU,EAAC,EAChC,GAAA,CAAI,CAAC,IAAA,KAAS,IAAA,CAAK,MAAA,GAAS,IAAI,CAAC,CAAA,CACjC,MAAA,CAAO,CAAC,CAAA,KAAkB,CAAC,CAAC,CAAC,CAAA;AAE/B,EAAA,OAAOC,6BAAA,CAAY;AAAA,IAClB,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,cAAc,MAAA,CAAO,YAAA;AAAA,IACrB,QAAA;AAAA,IACA,KAAA;AAAA,IACA,MAAA;AAAA,IACA,eAAe,MAAA,CAAO;AAAA,GACtB,CAAA;AACF","file":"chunk-2WBJEXNY.cjs","sourcesContent":["/**\n * Declarative agent definitions. Agents can be defined in YAML or JSON against a\n * single shared schema; the loader auto-detects the format (the YAML parser is\n * lazy-loaded so JSON-only/browser use pays no cost) and builds an equivalent\n * runnable agent. Credentials are still injected via callback, never embedded.\n * (FR-027, FR-005a)\n *\n * @packageDocumentation\n */\n\nimport type { ModelCapabilities } from \"../core/types.js\";\nimport type { Provider } from \"../providers/provider.js\";\nimport type { Tool } from \"../tools/tool.js\";\nimport type { Skill } from \"../skills/skill.js\";\nimport { createAgent, type Agent } from \"../agents/agent.js\";\nimport { ValidationError } from \"../core/errors.js\";\n\n/** Provider section of a declarative definition. */\nexport interface ProviderDefinition extends ModelCapabilities {\n\ttype: \"copilot\" | \"openai-compatible\";\n\tbaseUrl?: string;\n}\n\n/** A declarative agent definition (shared by YAML and JSON). */\nexport interface AgentDefinition {\n\tname: string;\n\tinstructions: string;\n\tprovider: ProviderDefinition;\n\t/** Names referencing tools provided in `deps.tools`. */\n\ttools?: string[];\n\t/** Names referencing skills provided in `deps.skills`. */\n\tskills?: string[];\n\tmaxIterations?: number;\n}\n\n/** Dependencies the loader needs to construct a live agent. */\nexport interface LoaderDeps {\n\t/** Build a provider from the definition + injected credential. */\n\tproviderFactory: (def: ProviderDefinition, getCredential: () => string | Promise<string>) => Provider;\n\t/** Credential callback — never embedded in the definition. (FR-005a) */\n\tgetCredential: () => string | Promise<string>;\n\t/** Registered tools available for reference by name. */\n\ttools?: Record<string, Tool>;\n\t/** Registered skills available for reference by name. */\n\tskills?: Record<string, Skill>;\n}\n\nfunction looksLikeJson(source: string): boolean {\n\tconst t = source.trimStart();\n\treturn t.startsWith(\"{\") || t.startsWith(\"[\");\n}\n\nasync function parse(source: string): Promise<unknown> {\n\tif (looksLikeJson(source)) {\n\t\ttry {\n\t\t\treturn JSON.parse(source);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(`Invalid JSON definition: ${(e as Error).message}`);\n\t\t}\n\t}\n\t// Lazy-load the YAML parser only when needed. (FR-027)\n\tconst YAML = await import(\"yaml\");\n\ttry {\n\t\treturn YAML.parse(source);\n\t} catch (e) {\n\t\tthrow new ValidationError(`Invalid YAML definition: ${(e as Error).message}`);\n\t}\n}\n\nfunction assertDefinition(value: unknown): asserts value is AgentDefinition {\n\tconst d = value as Partial<AgentDefinition>;\n\tif (!d || typeof d.name !== \"string\" || typeof d.instructions !== \"string\" || !d.provider) {\n\t\tthrow new ValidationError(\"Definition must include name, instructions, and provider\");\n\t}\n}\n\n/**\n * Load an agent from a YAML or JSON definition string.\n *\n * @example\n * ```ts\n * const agent = await loadAgentDefinition(yamlOrJson, {\n * providerFactory,\n * getCredential: () => process.env.LMSTUDIO_KEY ?? \"\",\n * });\n * ```\n */\nexport async function loadAgentDefinition(source: string, deps: LoaderDeps): Promise<Agent> {\n\tconst parsed = await parse(source);\n\tassertDefinition(parsed);\n\n\tconst provider = deps.providerFactory(parsed.provider, deps.getCredential);\n\tconst tools = (parsed.tools ?? [])\n\t\t.map((name) => deps.tools?.[name])\n\t\t.filter((t): t is Tool => !!t);\n\tconst skills = (parsed.skills ?? [])\n\t\t.map((name) => deps.skills?.[name])\n\t\t.filter((s): s is Skill => !!s);\n\n\treturn createAgent({\n\t\tname: parsed.name,\n\t\tinstructions: parsed.instructions,\n\t\tprovider,\n\t\ttools,\n\t\tskills,\n\t\tmaxIterations: parsed.maxIterations,\n\t});\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createAgent } from './chunk-
|
|
1
|
+
import { createAgent } from './chunk-KOPGBIES.js';
|
|
2
2
|
import { ValidationError } from './chunk-IXV4UIF5.js';
|
|
3
3
|
|
|
4
4
|
// src/declarative/loader.ts
|
|
@@ -44,5 +44,5 @@ async function loadAgentDefinition(source, deps) {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
export { loadAgentDefinition };
|
|
47
|
-
//# sourceMappingURL=chunk-
|
|
48
|
-
//# sourceMappingURL=chunk-
|
|
47
|
+
//# sourceMappingURL=chunk-55NB43FN.js.map
|
|
48
|
+
//# sourceMappingURL=chunk-55NB43FN.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/declarative/loader.ts"],"names":[],"mappings":";;;;AA+CA,SAAS,cAAc,MAAA,EAAyB;AAC/C,EAAA,MAAM,CAAA,GAAI,OAAO,SAAA,EAAU;AAC3B,EAAA,OAAO,EAAE,UAAA,CAAW,GAAG,CAAA,IAAK,CAAA,CAAE,WAAW,GAAG,CAAA;AAC7C;AAEA,eAAe,MAAM,MAAA,EAAkC;AACtD,EAAA,IAAI,aAAA,CAAc,MAAM,CAAA,EAAG;AAC1B,IAAA,IAAI;AACH,MAAA,OAAO,IAAA,CAAK,MAAM,MAAM,CAAA;AAAA,IACzB,SAAS,CAAA,EAAG;AACX,MAAA,MAAM,IAAI,eAAA,CAAgB,CAAA,yBAAA,EAA6B,CAAA,CAAY,OAAO,CAAA,CAAE,CAAA;AAAA,IAC7E;AAAA,EACD;AAEA,EAAA,MAAM,IAAA,GAAO,MAAM,OAAO,MAAM,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;AAC3F,EAAA,MAAM,MAAA,GAAS,MAAM,KAAA,CAAM,MAAM,CAAA;AACjC,EAAA,gBAAA,CAAiB,MAAM,CAAA;AAEvB,EAAA,MAAM,WAAW,IAAA,CAAK,eAAA,CAAgB,MAAA,CAAO,QAAA,EAAU,KAAK,aAAa,CAAA;AACzE,EAAA,MAAM,SAAS,MAAA,CAAO,KAAA,IAAS,EAAC,EAC9B,GAAA,CAAI,CAAC,IAAA,KAAS,IAAA,CAAK,KAAA,GAAQ,IAAI,CAAC,CAAA,CAChC,MAAA,CAAO,CAAC,CAAA,KAAiB,CAAC,CAAC,CAAC,CAAA;AAC9B,EAAA,MAAM,UAAU,MAAA,CAAO,MAAA,IAAU,EAAC,EAChC,GAAA,CAAI,CAAC,IAAA,KAAS,IAAA,CAAK,MAAA,GAAS,IAAI,CAAC,CAAA,CACjC,MAAA,CAAO,CAAC,CAAA,KAAkB,CAAC,CAAC,CAAC,CAAA;AAE/B,EAAA,OAAO,WAAA,CAAY;AAAA,IAClB,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,cAAc,MAAA,CAAO,YAAA;AAAA,IACrB,QAAA;AAAA,IACA,KAAA;AAAA,IACA,MAAA;AAAA,IACA,eAAe,MAAA,CAAO;AAAA,GACtB,CAAA;AACF","file":"chunk-55NB43FN.js","sourcesContent":["/**\n * Declarative agent definitions. Agents can be defined in YAML or JSON against a\n * single shared schema; the loader auto-detects the format (the YAML parser is\n * lazy-loaded so JSON-only/browser use pays no cost) and builds an equivalent\n * runnable agent. Credentials are still injected via callback, never embedded.\n * (FR-027, FR-005a)\n *\n * @packageDocumentation\n */\n\nimport type { ModelCapabilities } from \"../core/types.js\";\nimport type { Provider } from \"../providers/provider.js\";\nimport type { Tool } from \"../tools/tool.js\";\nimport type { Skill } from \"../skills/skill.js\";\nimport { createAgent, type Agent } from \"../agents/agent.js\";\nimport { ValidationError } from \"../core/errors.js\";\n\n/** Provider section of a declarative definition. */\nexport interface ProviderDefinition extends ModelCapabilities {\n\ttype: \"copilot\" | \"openai-compatible\";\n\tbaseUrl?: string;\n}\n\n/** A declarative agent definition (shared by YAML and JSON). */\nexport interface AgentDefinition {\n\tname: string;\n\tinstructions: string;\n\tprovider: ProviderDefinition;\n\t/** Names referencing tools provided in `deps.tools`. */\n\ttools?: string[];\n\t/** Names referencing skills provided in `deps.skills`. */\n\tskills?: string[];\n\tmaxIterations?: number;\n}\n\n/** Dependencies the loader needs to construct a live agent. */\nexport interface LoaderDeps {\n\t/** Build a provider from the definition + injected credential. */\n\tproviderFactory: (def: ProviderDefinition, getCredential: () => string | Promise<string>) => Provider;\n\t/** Credential callback — never embedded in the definition. (FR-005a) */\n\tgetCredential: () => string | Promise<string>;\n\t/** Registered tools available for reference by name. */\n\ttools?: Record<string, Tool>;\n\t/** Registered skills available for reference by name. */\n\tskills?: Record<string, Skill>;\n}\n\nfunction looksLikeJson(source: string): boolean {\n\tconst t = source.trimStart();\n\treturn t.startsWith(\"{\") || t.startsWith(\"[\");\n}\n\nasync function parse(source: string): Promise<unknown> {\n\tif (looksLikeJson(source)) {\n\t\ttry {\n\t\t\treturn JSON.parse(source);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(`Invalid JSON definition: ${(e as Error).message}`);\n\t\t}\n\t}\n\t// Lazy-load the YAML parser only when needed. (FR-027)\n\tconst YAML = await import(\"yaml\");\n\ttry {\n\t\treturn YAML.parse(source);\n\t} catch (e) {\n\t\tthrow new ValidationError(`Invalid YAML definition: ${(e as Error).message}`);\n\t}\n}\n\nfunction assertDefinition(value: unknown): asserts value is AgentDefinition {\n\tconst d = value as Partial<AgentDefinition>;\n\tif (!d || typeof d.name !== \"string\" || typeof d.instructions !== \"string\" || !d.provider) {\n\t\tthrow new ValidationError(\"Definition must include name, instructions, and provider\");\n\t}\n}\n\n/**\n * Load an agent from a YAML or JSON definition string.\n *\n * @example\n * ```ts\n * const agent = await loadAgentDefinition(yamlOrJson, {\n * providerFactory,\n * getCredential: () => process.env.LMSTUDIO_KEY ?? \"\",\n * });\n * ```\n */\nexport async function loadAgentDefinition(source: string, deps: LoaderDeps): Promise<Agent> {\n\tconst parsed = await parse(source);\n\tassertDefinition(parsed);\n\n\tconst provider = deps.providerFactory(parsed.provider, deps.getCredential);\n\tconst tools = (parsed.tools ?? [])\n\t\t.map((name) => deps.tools?.[name])\n\t\t.filter((t): t is Tool => !!t);\n\tconst skills = (parsed.skills ?? [])\n\t\t.map((name) => deps.skills?.[name])\n\t\t.filter((s): s is Skill => !!s);\n\n\treturn createAgent({\n\t\tname: parsed.name,\n\t\tinstructions: parsed.instructions,\n\t\tprovider,\n\t\ttools,\n\t\tskills,\n\t\tmaxIterations: parsed.maxIterations,\n\t});\n}\n"]}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
var chunkWSMYH2IN_cjs = require('./chunk-WSMYH2IN.cjs');
|
|
4
4
|
var chunkTAMJ5HSR_cjs = require('./chunk-TAMJ5HSR.cjs');
|
|
5
5
|
var chunkFSDMBWQV_cjs = require('./chunk-FSDMBWQV.cjs');
|
|
6
|
-
var
|
|
6
|
+
var chunkI55OVD23_cjs = require('./chunk-I55OVD23.cjs');
|
|
7
7
|
var chunkMQ2XTH3S_cjs = require('./chunk-MQ2XTH3S.cjs');
|
|
8
8
|
|
|
9
9
|
// src/agents/loop.ts
|
|
@@ -31,7 +31,9 @@ async function runLoop(generate, registry, messages, options) {
|
|
|
31
31
|
}
|
|
32
32
|
working.push({
|
|
33
33
|
role: "assistant",
|
|
34
|
-
parts: response.text ? [{ type: "text", text: response.text }] : []
|
|
34
|
+
parts: response.text ? [{ type: "text", text: response.text }] : [],
|
|
35
|
+
toolCalls: response.toolCalls,
|
|
36
|
+
...response.reasoningOpaque ? { reasoningOpaque: response.reasoningOpaque } : {}
|
|
35
37
|
});
|
|
36
38
|
for (const call of response.toolCalls) {
|
|
37
39
|
const result = await registry.invoke(call.name, call.arguments, options?.toolTimeoutMs);
|
|
@@ -46,12 +48,12 @@ async function runLoop(generate, registry, messages, options) {
|
|
|
46
48
|
}
|
|
47
49
|
}
|
|
48
50
|
function buildMessages(instructions, input) {
|
|
49
|
-
return [
|
|
51
|
+
return [chunkI55OVD23_cjs.textMessage("system", instructions), ...input];
|
|
50
52
|
}
|
|
51
53
|
|
|
52
54
|
// src/agents/agent.ts
|
|
53
55
|
function normalizeInput(input) {
|
|
54
|
-
if (typeof input === "string") return [
|
|
56
|
+
if (typeof input === "string") return [chunkI55OVD23_cjs.textMessage("user", input)];
|
|
55
57
|
return Array.isArray(input) ? input : [input];
|
|
56
58
|
}
|
|
57
59
|
function promptText(messages) {
|
|
@@ -61,8 +63,9 @@ function createAgent(config) {
|
|
|
61
63
|
const registry = new chunkTAMJ5HSR_cjs.ToolRegistry(config.tools ?? []);
|
|
62
64
|
const skillIndex = new chunkWSMYH2IN_cjs.SkillIndex(config.skills ?? []);
|
|
63
65
|
const middleware = config.middleware ?? [];
|
|
66
|
+
const modelCaps = () => config.provider.model(config.model);
|
|
64
67
|
function gateVision(messages) {
|
|
65
|
-
if (!
|
|
68
|
+
if (!modelCaps().supportsVision && messages.some(chunkI55OVD23_cjs.hasImage)) {
|
|
66
69
|
throw new chunkMQ2XTH3S_cjs.ProviderError(
|
|
67
70
|
"Image input was provided but the configured model does not support vision",
|
|
68
71
|
"client"
|
|
@@ -74,7 +77,7 @@ function createAgent(config) {
|
|
|
74
77
|
const selected = skillIndex.select(promptText(userMessages));
|
|
75
78
|
if (selected.length === 0) return userMessages;
|
|
76
79
|
const contents = await Promise.all(selected.map((s) => skillIndex.load(s)));
|
|
77
|
-
const skillBlock =
|
|
80
|
+
const skillBlock = chunkI55OVD23_cjs.textMessage(
|
|
78
81
|
"system",
|
|
79
82
|
`Relevant skill knowledge:
|
|
80
83
|
${contents.join("\n\n")}`
|
|
@@ -84,7 +87,7 @@ ${contents.join("\n\n")}`
|
|
|
84
87
|
async function callProvider(req) {
|
|
85
88
|
const ctx = {
|
|
86
89
|
agentName: config.name,
|
|
87
|
-
request: req
|
|
90
|
+
request: { ...req, model: req.model ?? config.model }
|
|
88
91
|
};
|
|
89
92
|
const pipeline = chunkFSDMBWQV_cjs.composeMiddleware(middleware, (c) => config.provider.generate(c.request));
|
|
90
93
|
return pipeline(ctx);
|
|
@@ -92,12 +95,13 @@ ${contents.join("\n\n")}`
|
|
|
92
95
|
async function prepare(input, opts) {
|
|
93
96
|
const userMessages = normalizeInput(input);
|
|
94
97
|
gateVision(userMessages);
|
|
95
|
-
const thread = opts?.thread ?? new
|
|
98
|
+
const thread = opts?.thread ?? new chunkI55OVD23_cjs.Thread(void 0, [chunkI55OVD23_cjs.textMessage("system", config.instructions)]);
|
|
96
99
|
const withSkills = await injectSkills(userMessages);
|
|
97
100
|
for (const m of withSkills) thread.add(m);
|
|
98
101
|
await thread.maybeCompact(config.provider, {
|
|
99
102
|
compactionThreshold: config.compactionThreshold,
|
|
100
|
-
compactionModel: config.compactionModel
|
|
103
|
+
compactionModel: config.compactionModel,
|
|
104
|
+
modelCapabilities: modelCaps()
|
|
101
105
|
});
|
|
102
106
|
return thread;
|
|
103
107
|
}
|
|
@@ -107,7 +111,7 @@ ${contents.join("\n\n")}`
|
|
|
107
111
|
thread = await prepare(input, opts);
|
|
108
112
|
} catch (e) {
|
|
109
113
|
if (e instanceof chunkMQ2XTH3S_cjs.ProviderError) {
|
|
110
|
-
return { output: "", status: "failed", partial: false, error: e, thread: opts?.thread ?? new
|
|
114
|
+
return { output: "", status: "failed", partial: false, error: e, thread: opts?.thread ?? new chunkI55OVD23_cjs.Thread() };
|
|
111
115
|
}
|
|
112
116
|
throw e;
|
|
113
117
|
}
|
|
@@ -122,7 +126,7 @@ ${contents.join("\n\n")}`
|
|
|
122
126
|
}
|
|
123
127
|
return {
|
|
124
128
|
output: loop.final.text,
|
|
125
|
-
reasoning:
|
|
129
|
+
reasoning: modelCaps().supportsReasoning ? loop.final.reasoning : void 0,
|
|
126
130
|
status: loop.status,
|
|
127
131
|
partial: loop.status === "incomplete",
|
|
128
132
|
thread
|
|
@@ -140,7 +144,7 @@ ${contents.join("\n\n")}`
|
|
|
140
144
|
thread = await prepare(input, opts);
|
|
141
145
|
} catch (e) {
|
|
142
146
|
if (e instanceof chunkMQ2XTH3S_cjs.ProviderError) {
|
|
143
|
-
yield { type: "done", result: { output: "", status: "failed", partial: false, error: e, thread: opts?.thread ?? new
|
|
147
|
+
yield { type: "done", result: { output: "", status: "failed", partial: false, error: e, thread: opts?.thread ?? new chunkI55OVD23_cjs.Thread() } };
|
|
144
148
|
return;
|
|
145
149
|
}
|
|
146
150
|
throw e;
|
|
@@ -151,12 +155,13 @@ ${contents.join("\n\n")}`
|
|
|
151
155
|
for await (const chunk of config.provider.generateStream({
|
|
152
156
|
messages: thread.messages,
|
|
153
157
|
tools: registry.specs(),
|
|
158
|
+
model: config.model,
|
|
154
159
|
signal: opts?.signal
|
|
155
160
|
})) {
|
|
156
161
|
if (chunk.type === "text") {
|
|
157
162
|
text += chunk.text;
|
|
158
163
|
yield { type: "text", text: chunk.text };
|
|
159
|
-
} else if (chunk.type === "reasoning" &&
|
|
164
|
+
} else if (chunk.type === "reasoning" && modelCaps().supportsReasoning) {
|
|
160
165
|
reasoning += chunk.text;
|
|
161
166
|
yield { type: "reasoning", text: chunk.text };
|
|
162
167
|
} else if (chunk.type === "done") {
|
|
@@ -177,7 +182,7 @@ ${contents.join("\n\n")}`
|
|
|
177
182
|
type: "done",
|
|
178
183
|
result: {
|
|
179
184
|
output: text,
|
|
180
|
-
reasoning:
|
|
185
|
+
reasoning: modelCaps().supportsReasoning ? reasoning || void 0 : void 0,
|
|
181
186
|
status: "completed",
|
|
182
187
|
partial: false,
|
|
183
188
|
thread
|
|
@@ -190,5 +195,5 @@ ${contents.join("\n\n")}`
|
|
|
190
195
|
exports.buildMessages = buildMessages;
|
|
191
196
|
exports.createAgent = createAgent;
|
|
192
197
|
exports.runLoop = runLoop;
|
|
193
|
-
//# sourceMappingURL=chunk-
|
|
194
|
-
//# sourceMappingURL=chunk-
|
|
198
|
+
//# sourceMappingURL=chunk-FDCTSJMB.cjs.map
|
|
199
|
+
//# sourceMappingURL=chunk-FDCTSJMB.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/loop.ts","../src/agents/agent.ts"],"names":["textMessage","ToolRegistry","SkillIndex","hasImage","ProviderError","composeMiddleware","Thread"],"mappings":";;;;;;;;;AA4CA,eAAsB,OAAA,CACrB,QAAA,EACA,QAAA,EACA,QAAA,EACA,OAAA,EACsB;AACtB,EAAA,MAAM,aAAA,GAAgB,SAAS,aAAA,IAAiB,EAAA;AAChD,EAAA,MAAM,OAAA,GAAU,CAAC,GAAG,QAAQ,CAAA;AAC5B,EAAA,IAAI,SAAA,GAAY,CAAA;AAEhB,EAAA,WAAU;AACT,IAAA,IAAI,aAAA,KAAkB,EAAA,IAAM,SAAA,IAAa,aAAA,EAAe;AACvD,MAAA,OAAO;AAAA,QACN,QAAA,EAAU,OAAA;AAAA,QACV,KAAA,EAAO,EAAE,IAAA,EAAM,EAAA,EAAG;AAAA,QAClB,MAAA,EAAQ;AAAA,OACT;AAAA,IACD;AACA,IAAA,SAAA,EAAA;AAEA,IAAA,MAAM,KAAA,GAAQ,SAAS,KAAA,EAAM;AAC7B,IAAA,MAAM,QAAA,GAAW,MAAM,QAAA,CAAS;AAAA,MAC/B,QAAA,EAAU,OAAA;AAAA,MACV,KAAA,EAAO,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,KAAA,GAAQ,MAAA;AAAA,MAClC,QAAQ,OAAA,EAAS;AAAA,KACjB,CAAA;AAED,IAAA,IAAI,CAAC,QAAA,CAAS,SAAA,IAAa,QAAA,CAAS,SAAA,CAAU,WAAW,CAAA,EAAG;AAC3D,MAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,KAAA,EAAO,QAAA,EAAU,QAAQ,WAAA,EAAY;AAAA,IAClE;AAKA,IAAA,OAAA,CAAQ,IAAA,CAAK;AAAA,MACZ,IAAA,EAAM,WAA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AM,MAAA,CAAO,IAAA,EAAM,KAAK,SAAA,EAAU;AAC5C","file":"chunk-FDCTSJMB.cjs","sourcesContent":["/**\n * The agent run loop: drives provider calls, executes requested tool calls,\n * feeds typed results (including errors, for self-correction) back to the model,\n * and stops on a final answer, the iteration cap, or an abort. (FR-011a, FR-012b)\n *\n * @packageDocumentation\n */\n\nimport type { Message } from \"../core/types.js\";\nimport { textMessage } from \"../core/types.js\";\nimport type { GenerateRequest, GenerateResponse } from \"../providers/provider.js\";\nimport type { ToolRegistry } from \"../tools/registry.js\";\n\n/** Outcome status of a run. */\nexport type RunStatus = \"completed\" | \"failed\" | \"incomplete\" | \"limit-exceeded\";\n\n/** A function that produces a model response (optionally through middleware). */\nexport type GenerateFn = (req: GenerateRequest) => Promise<GenerateResponse>;\n\n/** Settings controlling the loop. */\nexport interface LoopOptions {\n\t/** Maximum iterations; -1 means unlimited. Default 10. (FR-012b) */\n\tmaxIterations?: number;\n\t/** Per-tool-call timeout in ms. (FR-012c) */\n\ttoolTimeoutMs?: number;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Result of running the loop. */\nexport interface LoopResult {\n\tmessages: Message[];\n\tfinal: GenerateResponse;\n\tstatus: RunStatus;\n}\n\n/**\n * Execute the tool-call loop against a generate function and tool registry.\n *\n * @param generate - Produces a model response (typically the middleware pipeline).\n * @param registry - Tools available to the agent (may be empty).\n * @param messages - Initial conversation (system + user, etc.).\n * @param options - Loop tuning.\n */\nexport async function runLoop(\n\tgenerate: GenerateFn,\n\tregistry: ToolRegistry,\n\tmessages: Message[],\n\toptions?: LoopOptions,\n): Promise<LoopResult> {\n\tconst maxIterations = options?.maxIterations ?? 10;\n\tconst working = [...messages];\n\tlet iteration = 0;\n\n\tfor (; ;) {\n\t\tif (maxIterations !== -1 && iteration >= maxIterations) {\n\t\t\treturn {\n\t\t\t\tmessages: working,\n\t\t\t\tfinal: { text: \"\" },\n\t\t\t\tstatus: \"limit-exceeded\",\n\t\t\t};\n\t\t}\n\t\titeration++;\n\n\t\tconst specs = registry.specs();\n\t\tconst response = await generate({\n\t\t\tmessages: working,\n\t\t\ttools: specs.length > 0 ? specs : undefined,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tif (!response.toolCalls || response.toolCalls.length === 0) {\n\t\t\treturn { messages: working, final: response, status: \"completed\" };\n\t\t}\n\n\t\t// Record the assistant's tool-call turn, preserving the tool calls (so strict\n\t\t// providers can pair each result with its call) and any opaque reasoning blob\n\t\t// (for thinking continuity across turns).\n\t\tworking.push({\n\t\t\trole: \"assistant\",\n\t\t\tparts: response.text ? [{ type: \"text\", text: response.text }] : [],\n\t\t\ttoolCalls: response.toolCalls,\n\t\t\t...(response.reasoningOpaque ? { reasoningOpaque: response.reasoningOpaque } : {}),\n\t\t});\n\n\t\t// Execute each requested tool and feed results (or typed errors) back.\n\t\tfor (const call of response.toolCalls) {\n\t\t\tconst result = await registry.invoke(call.name, call.arguments, options?.toolTimeoutMs);\n\t\t\tconst payload = result.error\n\t\t\t\t? `ERROR (${result.error.reason}): ${result.error.message}`\n\t\t\t\t: JSON.stringify(result.value ?? null);\n\t\t\tworking.push({\n\t\t\t\trole: \"tool\",\n\t\t\t\tname: call.name,\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\tparts: [{ type: \"text\", text: payload }],\n\t\t\t});\n\t\t}\n\t}\n}\n\n/** Build the initial message list from instructions + input. */\nexport function buildMessages(instructions: string, input: Message[]): Message[] {\n\treturn [textMessage(\"system\", instructions), ...input];\n}\n","/**\n * The agent: a configured actor that runs against a provider, optionally using\n * tools and skills, with streaming, reasoning output, multimodal input gating,\n * conversation threads with compaction, and a middleware pipeline.\n *\n * @packageDocumentation\n */\n\nimport type { Message, ContentPart } from \"../core/types.js\";\nimport { hasImage, textMessage } from \"../core/types.js\";\nimport { ProviderError } from \"../core/errors.js\";\nimport type { Provider, GenerateResponse, GenerateRequest } from \"../providers/provider.js\";\nimport { ToolRegistry } from \"../tools/registry.js\";\nimport type { Tool } from \"../tools/tool.js\";\nimport type { Skill } from \"../skills/skill.js\";\nimport { SkillIndex } from \"../skills/index.js\";\nimport type { Middleware, MiddlewareContext } from \"../middleware/middleware.js\";\nimport { composeMiddleware } from \"../middleware/middleware.js\";\nimport { Thread, type ThreadOptions } from \"./thread.js\";\nimport { runLoop, type RunStatus } from \"./loop.js\";\n\n/** Configuration for {@link createAgent}. */\nexport interface AgentConfig {\n\tname: string;\n\tinstructions: string;\n\tprovider: Provider;\n\t/** Which of the provider's models to use; defaults to the provider's default model. */\n\tmodel?: string;\n\ttools?: Tool[];\n\tskills?: Skill[];\n\t/** Max tool-call iterations per run; -1 = unlimited. Default 10. (FR-012b) */\n\tmaxIterations?: number;\n\t/** Per-tool-call timeout in ms. (FR-012c) */\n\ttoolTimeoutMs?: number;\n\t/** Compaction threshold as a fraction of maxInputTokens. Default 0.9. (FR-004a) */\n\tcompactionThreshold?: number;\n\t/** Optional override model for compaction summaries. (FR-004b) */\n\tcompactionModel?: Provider;\n\t/** Middleware applied around provider calls. (FR-023) */\n\tmiddleware?: Middleware[];\n}\n\n/** Options for a single run. */\nexport interface RunOptions {\n\t/** Continue an existing conversation. (FR-004) */\n\tthread?: Thread;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** The result of a non-streaming run. */\nexport interface RunResult {\n\toutput: string;\n\t/** Reasoning content — only for reasoning-capable models. (FR-003a) */\n\treasoning?: string;\n\tstatus: RunStatus;\n\t/** True when the run was interrupted before completing. (FR-003b) */\n\tpartial: boolean;\n\terror?: ProviderError;\n\t/** The thread used/updated by this run. */\n\tthread: Thread;\n}\n\n/** Streamed run chunk. */\nexport type RunChunk =\n\t| { type: \"text\"; text: string }\n\t| { type: \"reasoning\"; text: string }\n\t| { type: \"done\"; result: RunResult };\n\n/** Agent input: plain text or structured (multimodal) messages. (FR-002) */\nexport type AgentInput = string | Message | Message[];\n\n/** A runnable agent. */\nexport interface Agent {\n\treadonly name: string;\n\trun(input: AgentInput, opts?: RunOptions): Promise<RunResult>;\n\trunStream(input: AgentInput, opts?: RunOptions): AsyncIterable<RunChunk>;\n}\n\nfunction normalizeInput(input: AgentInput): Message[] {\n\tif (typeof input === \"string\") return [textMessage(\"user\", input)];\n\treturn Array.isArray(input) ? input : [input];\n}\n\nfunction promptText(messages: Message[]): string {\n\treturn messages\n\t\t.flatMap((m) => m.parts)\n\t\t.filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n\t\t.map((p) => p.text)\n\t\t.join(\" \");\n}\n\n/**\n * Create an agent.\n *\n * @example\n * ```ts\n * const agent = createAgent({ name: \"Helper\", instructions: \"Be concise.\", provider });\n * const res = await agent.run(\"Say hello.\");\n * console.log(res.status, res.output);\n * ```\n */\nexport function createAgent(config: AgentConfig): Agent {\n\tconst registry = new ToolRegistry(config.tools ?? []);\n\tconst skillIndex = new SkillIndex(config.skills ?? []);\n\tconst middleware = config.middleware ?? [];\n\t/** Capabilities of the model this agent uses (selected from the provider). */\n\tconst modelCaps = () => config.provider.model(config.model);\n\n\tfunction gateVision(messages: Message[]): void {\n\t\tif (!modelCaps().supportsVision && messages.some(hasImage)) {\n\t\t\tthrow new ProviderError(\n\t\t\t\t\"Image input was provided but the configured model does not support vision\",\n\t\t\t\t\"client\",\n\t\t\t);\n\t\t}\n\t}\n\n\tasync function injectSkills(userMessages: Message[]): Promise<Message[]> {\n\t\tif ((config.skills ?? []).length === 0) return userMessages;\n\t\tconst selected = skillIndex.select(promptText(userMessages));\n\t\tif (selected.length === 0) return userMessages;\n\t\tconst contents = await Promise.all(selected.map((s) => skillIndex.load(s)));\n\t\tconst skillBlock = textMessage(\n\t\t\t\"system\",\n\t\t\t`Relevant skill knowledge:\\n${contents.join(\"\\n\\n\")}`,\n\t\t);\n\t\treturn [skillBlock, ...userMessages];\n\t}\n\n\tasync function callProvider(req: GenerateRequest): Promise<GenerateResponse> {\n\t\tconst ctx: MiddlewareContext = {\n\t\t\tagentName: config.name,\n\t\t\trequest: { ...req, model: req.model ?? config.model },\n\t\t};\n\t\tconst pipeline = composeMiddleware(middleware, (c) => config.provider.generate(c.request));\n\t\treturn pipeline(ctx);\n\t}\n\n\tasync function prepare(input: AgentInput, opts?: RunOptions): Promise<Thread> {\n\t\tconst userMessages = normalizeInput(input);\n\t\tgateVision(userMessages);\n\t\tconst thread =\n\t\t\topts?.thread ??\n\t\t\tnew Thread(undefined, [textMessage(\"system\", config.instructions)]);\n\t\tconst withSkills = await injectSkills(userMessages);\n\t\tfor (const m of withSkills) thread.add(m);\n\t\tawait thread.maybeCompact(config.provider, {\n\t\t\tcompactionThreshold: config.compactionThreshold,\n\t\t\tcompactionModel: config.compactionModel,\n\t\t\tmodelCapabilities: modelCaps(),\n\t\t} satisfies ThreadOptions);\n\t\treturn thread;\n\t}\n\n\tasync function run(input: AgentInput, opts?: RunOptions): Promise<RunResult> {\n\t\tlet thread: Thread;\n\t\ttry {\n\t\t\tthread = await prepare(input, opts);\n\t\t} catch (e) {\n\t\t\tif (e instanceof ProviderError) {\n\t\t\t\treturn { output: \"\", status: \"failed\", partial: false, error: e, thread: opts?.thread ?? new Thread() };\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\n\t\ttry {\n\t\t\tconst loop = await runLoop(callProvider, registry, thread.messages, {\n\t\t\t\tmaxIterations: config.maxIterations,\n\t\t\t\ttoolTimeoutMs: config.toolTimeoutMs,\n\t\t\t\tsignal: opts?.signal,\n\t\t\t});\n\t\t\tif (loop.final.text) {\n\t\t\t\tthread.add({ role: \"assistant\", parts: [{ type: \"text\", text: loop.final.text }] });\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: loop.final.text,\n\t\t\t\treasoning: modelCaps().supportsReasoning ? loop.final.reasoning : undefined,\n\t\t\t\tstatus: loop.status,\n\t\t\t\tpartial: loop.status === \"incomplete\",\n\t\t\t\tthread,\n\t\t\t};\n\t\t} catch (e) {\n\t\t\tif (e instanceof ProviderError) {\n\t\t\t\treturn { output: \"\", status: \"failed\", partial: false, error: e, thread };\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tasync function* runStream(input: AgentInput, opts?: RunOptions): AsyncIterable<RunChunk> {\n\t\t// Streaming path: single provider streaming call (tool loops use non-streaming\n\t\t// internally). Suitable for the common single-turn streaming case.\n\t\tlet thread: Thread;\n\t\ttry {\n\t\t\tthread = await prepare(input, opts);\n\t\t} catch (e) {\n\t\t\tif (e instanceof ProviderError) {\n\t\t\t\tyield { type: \"done\", result: { output: \"\", status: \"failed\", partial: false, error: e, thread: opts?.thread ?? new Thread() } };\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\n\t\tlet text = \"\";\n\t\tlet reasoning = \"\";\n\t\ttry {\n\t\t\tfor await (const chunk of config.provider.generateStream({\n\t\t\t\tmessages: thread.messages,\n\t\t\t\ttools: registry.specs(),\n\t\t\t\tmodel: config.model,\n\t\t\t\tsignal: opts?.signal,\n\t\t\t})) {\n\t\t\t\tif (chunk.type === \"text\") {\n\t\t\t\t\ttext += chunk.text;\n\t\t\t\t\tyield { type: \"text\", text: chunk.text };\n\t\t\t\t} else if (chunk.type === \"reasoning\" && modelCaps().supportsReasoning) {\n\t\t\t\t\treasoning += chunk.text;\n\t\t\t\t\tyield { type: \"reasoning\", text: chunk.text };\n\t\t\t\t} else if (chunk.type === \"done\") {\n\t\t\t\t\ttext = chunk.response.text || text;\n\t\t\t\t\treasoning = chunk.response.reasoning || reasoning;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconst error = e instanceof ProviderError ? e : new ProviderError((e as Error).message, \"transient\");\n\t\t\tyield {\n\t\t\t\ttype: \"done\",\n\t\t\t\tresult: { output: text, status: \"incomplete\", partial: true, error, thread },\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\n\t\tif (text) thread.add({ role: \"assistant\", parts: [{ type: \"text\", text }] });\n\t\tyield {\n\t\t\ttype: \"done\",\n\t\t\tresult: {\n\t\t\t\toutput: text,\n\t\t\t\treasoning: modelCaps().supportsReasoning ? reasoning || undefined : undefined,\n\t\t\t\tstatus: \"completed\",\n\t\t\t\tpartial: false,\n\t\t\t\tthread,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn { name: config.name, run, runStream };\n}\n\nexport type { ContentPart };\n"]}
|
|
@@ -47,7 +47,8 @@ var Thread = class _Thread {
|
|
|
47
47
|
*/
|
|
48
48
|
async maybeCompact(provider, options) {
|
|
49
49
|
const threshold = options?.compactionThreshold ?? 0.9;
|
|
50
|
-
const
|
|
50
|
+
const caps = options?.modelCapabilities ?? provider.capabilities;
|
|
51
|
+
const limit = caps.maxInputTokens * threshold;
|
|
51
52
|
if (estimateTokens(this.messages) < limit) return false;
|
|
52
53
|
const summarizer = options?.compactionModel ?? provider;
|
|
53
54
|
const system = this.messages.filter((m) => m.role === "system");
|
|
@@ -83,5 +84,5 @@ exports.estimateTokens = estimateTokens;
|
|
|
83
84
|
exports.hasImage = hasImage;
|
|
84
85
|
exports.messageText = messageText;
|
|
85
86
|
exports.textMessage = textMessage;
|
|
86
|
-
//# sourceMappingURL=chunk-
|
|
87
|
-
//# sourceMappingURL=chunk-
|
|
87
|
+
//# sourceMappingURL=chunk-I55OVD23.cjs.map
|
|
88
|
+
//# sourceMappingURL=chunk-I55OVD23.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types.ts","../src/agents/thread.ts"],"names":[],"mappings":";;;AAiFO,SAAS,WAAA,CAAY,MAAY,IAAA,EAAuB;AAC9D,EAAA,OAAO,EAAE,MAAM,KAAA,EAAO,CAAC,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAA,EAAM,CAAA,EAAE;AAChD;AAGO,SAAS,SAAS,OAAA,EAA2B;AACnD,EAAA,OAAO,QAAQ,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,OAAO,CAAA;AACpD;AAGO,SAAS,YAAY,OAAA,EAA0B;AACrD,EAAA,OAAO,QAAQ,K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AU,CAAA,iCAAA,EAAoC,OAAA,CAAQ,IAAI,CAAA,CAAE,CAAA;AAAA,MACxE,GAAG;AAAA,KACJ;AACA,IAAA,IAAA,CAAK,SAAA,GAAY,IAAA;AACjB,IAAA,OAAO,IAAA;AAAA,EACR;AACD;AAEA,SAAS,cAAA,GAAyB;AACjC,EAAA,MAAM,IAAK,UAAA,CAAmC,MAAA;AAC9C,EAAA,IAAI,CAAA,EAAG,UAAA,EAAY,OAAO,CAAA,CAAE,UAAA,EAAW;AACvC,EAAA,OAAO,CAAA,OAAA,EAAU,IAAA,CAAK,MAAA,EAAO,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA,EAAI,IAAA,CAAK,KAAK,CAAA,CAAA;AACnE","file":"chunk-I55OVD23.cjs","sourcesContent":["/**\n * Shared content, message, and model-capability types used across the framework.\n *\n * These are the lowest-level building blocks: every higher-level module (agents,\n * providers, tools, workflows) speaks in terms of {@link Message} and\n * {@link ContentPart}. Keeping them dependency-free keeps the core tree-shakeable.\n *\n * @packageDocumentation\n */\n\n/** A JSON Schema object (draft 2020-12 compatible), as popularized by MCP. */\nexport type JSONSchema = Record<string, unknown>;\n\n/** Role of a message in a conversation. */\nexport type Role = \"system\" | \"user\" | \"assistant\" | \"tool\";\n\n/** A single piece of message content. Images are only valid for vision-capable models. */\nexport type ContentPart =\n\t| { type: \"text\"; text: string }\n\t| { type: \"image\"; data: string; mimeType: string };\n\n/**\n * A tool call recorded on an assistant message. Round-tripped to providers that\n * require the assistant turn to declare its `tool_calls` (e.g. Anthropic via\n * Copilot) so the following `tool` results have a matching `tool_use`. (FR-012)\n */\nexport interface MessageToolCall {\n\t/** Provider-assigned call id, linking the assistant call to its tool result. */\n\tid: string;\n\t/** Namespaced tool name (registry key). */\n\tname: string;\n\t/** Raw JSON arguments the model supplied. */\n\targuments: unknown;\n}\n\n/**\n * A conversation message.\n *\n * @example\n * ```ts\n * const msg: Message = { role: \"user\", parts: [{ type: \"text\", text: \"Hi\" }] };\n * ```\n */\nexport interface Message {\n\trole: Role;\n\tparts: ContentPart[];\n\t/** Optional tool-call linkage for assistant/tool messages. */\n\ttoolCallId?: string;\n\t/** Optional display name (e.g., the tool name for a tool message). */\n\tname?: string;\n\t/**\n\t * Tool calls requested by an assistant turn. Persisted so providers that\n\t * require it (e.g. Anthropic) receive `tool_calls` paired with the tool results.\n\t */\n\ttoolCalls?: MessageToolCall[];\n\t/**\n\t * Opaque reasoning blob carried across turns for thinking-capable models, so\n\t * reasoning continuity is preserved without exposing the contents. (FR-003a)\n\t */\n\treasoningOpaque?: string;\n}\n\n/**\n * Per-model capabilities supplied by the caller. The framework cannot reliably\n * discover these for arbitrary OpenAI-compatible/LM Studio models, so they are\n * provided explicitly. (FR-007a)\n */\nexport interface ModelCapabilities {\n\t/** Model id/name. */\n\tmodel: string;\n\t/** Maximum input/context tokens; drives compaction threshold. */\n\tmaxInputTokens: number;\n\t/** Maximum output tokens. */\n\tmaxOutputTokens: number;\n\t/** Whether the model accepts image input. Defaults to false. */\n\tsupportsVision?: boolean;\n\t/** Whether the model emits separate reasoning/thinking content. Defaults to false. */\n\tsupportsReasoning?: boolean;\n}\n\n/** Convenience: build a user message from a plain string. */\nexport function textMessage(role: Role, text: string): Message {\n\treturn { role, parts: [{ type: \"text\", text }] };\n}\n\n/** Returns true if a message contains any image content part. */\nexport function hasImage(message: Message): boolean {\n\treturn message.parts.some((p) => p.type === \"image\");\n}\n\n/** Extract the concatenated text from a message. */\nexport function messageText(message: Message): string {\n\treturn message.parts\n\t\t.filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n\t\t.map((p) => p.text)\n\t\t.join(\"\");\n}\n","/**\n * Conversation thread with automatic compaction. When a thread approaches the\n * model's input-token budget it is summarized into a compact form so the\n * conversation can continue. (FR-004, FR-004a, FR-004b)\n *\n * @packageDocumentation\n */\n\nimport type { Message, ModelCapabilities } from \"../core/types.js\";\nimport { messageText, textMessage } from \"../core/types.js\";\nimport type { Provider } from \"../providers/provider.js\";\n\n/** Options controlling a thread's compaction behavior. */\nexport interface ThreadOptions {\n\t/** Fraction of `maxInputTokens` at which compaction triggers. Default 0.9. */\n\tcompactionThreshold?: number;\n\t/** Provider used to summarize; defaults to the agent's own provider. (FR-004b) */\n\tcompactionModel?: Provider;\n\t/** Capabilities of the model in use; defaults to the provider's default model. */\n\tmodelCapabilities?: ModelCapabilities;\n}\n\n/** Rough token estimate (~4 chars/token) — avoids a tokenizer dependency. */\nexport function estimateTokens(messages: Message[]): number {\n\tconst chars = messages.reduce((sum, m) => sum + messageText(m).length, 0);\n\treturn Math.ceil(chars / 4);\n}\n\n/** A multi-turn conversation that preserves context and compacts when large. */\nexport class Thread {\n\treadonly id: string;\n\tmessages: Message[];\n\t/** Whether the thread has been compacted at least once. */\n\tcompacted = false;\n\n\tconstructor(id?: string, messages: Message[] = []) {\n\t\tthis.id = id ?? cryptoRandomId();\n\t\tthis.messages = messages;\n\t}\n\n\t/** Append a message. */\n\tadd(message: Message): void {\n\t\tthis.messages.push(message);\n\t}\n\n\t/** Serializable snapshot for persistence. */\n\ttoJSON(): { id: string; messages: Message[]; compacted: boolean } {\n\t\treturn { id: this.id, messages: this.messages, compacted: this.compacted };\n\t}\n\n\t/** Restore a thread from a snapshot. */\n\tstatic fromJSON(data: { id: string; messages: Message[]; compacted?: boolean }): Thread {\n\t\tconst t = new Thread(data.id, data.messages);\n\t\tt.compacted = data.compacted ?? false;\n\t\treturn t;\n\t}\n\n\t/**\n\t * Compact the thread if it exceeds the threshold. System messages and the most\n\t * recent turn are preserved; older turns are summarized via the model.\n\t *\n\t * @returns true if compaction occurred.\n\t */\n\tasync maybeCompact(provider: Provider, options?: ThreadOptions): Promise<boolean> {\n\t\tconst threshold = options?.compactionThreshold ?? 0.9;\n\t\tconst caps = options?.modelCapabilities ?? provider.capabilities;\n\t\tconst limit = caps.maxInputTokens * threshold;\n\t\tif (estimateTokens(this.messages) < limit) return false;\n\n\t\tconst summarizer = options?.compactionModel ?? provider;\n\t\tconst system = this.messages.filter((m) => m.role === \"system\");\n\t\tconst recent = this.messages.slice(-2);\n\t\tconst toSummarize = this.messages.filter((m) => m.role !== \"system\").slice(0, -2);\n\t\tif (toSummarize.length === 0) return false;\n\n\t\tconst summary = await summarizer.generate({\n\t\t\tmessages: [\n\t\t\t\ttextMessage(\n\t\t\t\t\t\"system\",\n\t\t\t\t\t\"Summarize the following conversation compactly, preserving facts, decisions, and open questions.\",\n\t\t\t\t),\n\t\t\t\ttextMessage(\"user\", toSummarize.map((m) => `${m.role}: ${messageText(m)}`).join(\"\\n\")),\n\t\t\t],\n\t\t});\n\n\t\tthis.messages = [\n\t\t\t...system,\n\t\t\ttextMessage(\"system\", `Summary of earlier conversation: ${summary.text}`),\n\t\t\t...recent,\n\t\t];\n\t\tthis.compacted = true;\n\t\treturn true;\n\t}\n}\n\nfunction cryptoRandomId(): string {\n\tconst c = (globalThis as { crypto?: Crypto }).crypto;\n\tif (c?.randomUUID) return c.randomUUID();\n\treturn `thread-${Math.random().toString(36).slice(2)}-${Date.now()}`;\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkI55OVD23_cjs = require('./chunk-I55OVD23.cjs');
|
|
4
4
|
var chunkFOTCUNP5_cjs = require('./chunk-FOTCUNP5.cjs');
|
|
5
5
|
|
|
6
6
|
// src/persistence/store.ts
|
|
@@ -12,7 +12,7 @@ var ThreadPersistence = {
|
|
|
12
12
|
/** Load and rehydrate a thread, or undefined if absent. */
|
|
13
13
|
async load(store, id) {
|
|
14
14
|
const data = await store.get(`thread:${id}`);
|
|
15
|
-
return data ?
|
|
15
|
+
return data ? chunkI55OVD23_cjs.Thread.fromJSON(data) : void 0;
|
|
16
16
|
}
|
|
17
17
|
};
|
|
18
18
|
|
|
@@ -91,5 +91,5 @@ function indexedDbStore(ns) {
|
|
|
91
91
|
exports.ThreadPersistence = ThreadPersistence;
|
|
92
92
|
exports.createBrowserStore = createBrowserStore;
|
|
93
93
|
exports.createMemoryStore = createMemoryStore;
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
95
|
-
//# sourceMappingURL=chunk-
|
|
94
|
+
//# sourceMappingURL=chunk-IHMPSELC.cjs.map
|
|
95
|
+
//# sourceMappingURL=chunk-IHMPSELC.cjs.map
|