@nylorun/harness 0.5.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE +192 -0
  3. package/README.md +124 -0
  4. package/dist/build/adapters.d.ts +11 -0
  5. package/dist/build/adapters.js +91 -0
  6. package/dist/build/agent.d.ts +19 -0
  7. package/dist/build/agent.js +28 -0
  8. package/dist/build/assemble.d.ts +9 -0
  9. package/dist/build/assemble.js +76 -0
  10. package/dist/build/bind-tool.d.ts +4 -0
  11. package/dist/build/bind-tool.js +15 -0
  12. package/dist/build/builder.d.ts +31 -0
  13. package/dist/build/builder.js +74 -0
  14. package/dist/build/helpers.d.ts +7 -0
  15. package/dist/build/helpers.js +5 -0
  16. package/dist/build/manifest.d.ts +9 -0
  17. package/dist/build/manifest.js +15 -0
  18. package/dist/build/schema.d.ts +19 -0
  19. package/dist/build/schema.js +86 -0
  20. package/dist/errors.d.ts +17 -0
  21. package/dist/errors.js +17 -0
  22. package/dist/index.d.ts +11 -0
  23. package/dist/index.js +4 -0
  24. package/dist/model-normalize.d.ts +6 -0
  25. package/dist/model-normalize.js +211 -0
  26. package/dist/session/event-log.d.ts +11 -0
  27. package/dist/session/event-log.js +63 -0
  28. package/dist/session/input-queue.d.ts +29 -0
  29. package/dist/session/input-queue.js +78 -0
  30. package/dist/session/scheduler.d.ts +48 -0
  31. package/dist/session/scheduler.js +352 -0
  32. package/dist/session/session.d.ts +14 -0
  33. package/dist/session/session.js +55 -0
  34. package/dist/session/state.d.ts +10 -0
  35. package/dist/session/state.js +36 -0
  36. package/dist/session/submission-stream.d.ts +13 -0
  37. package/dist/session/submission-stream.js +36 -0
  38. package/dist/step/canonicalize.d.ts +21 -0
  39. package/dist/step/canonicalize.js +62 -0
  40. package/dist/step/compose.d.ts +4 -0
  41. package/dist/step/compose.js +106 -0
  42. package/dist/step/context-draft.d.ts +10 -0
  43. package/dist/step/context-draft.js +71 -0
  44. package/dist/step/model-configuration.d.ts +15 -0
  45. package/dist/step/model-configuration.js +153 -0
  46. package/dist/step/project.d.ts +2 -0
  47. package/dist/step/project.js +103 -0
  48. package/dist/step/resolve.d.ts +9 -0
  49. package/dist/step/resolve.js +16 -0
  50. package/dist/step/run.d.ts +27 -0
  51. package/dist/step/run.js +127 -0
  52. package/dist/step/seal.d.ts +31 -0
  53. package/dist/step/seal.js +108 -0
  54. package/dist/step/slot-assembly.d.ts +39 -0
  55. package/dist/step/slot-assembly.js +52 -0
  56. package/dist/step/step-context.d.ts +36 -0
  57. package/dist/step/step-context.js +255 -0
  58. package/dist/turn/plan-runner.d.ts +55 -0
  59. package/dist/turn/plan-runner.js +370 -0
  60. package/dist/turn/runner.d.ts +53 -0
  61. package/dist/turn/runner.js +128 -0
  62. package/dist/types/manifest.d.ts +22 -0
  63. package/dist/types/manifest.js +1 -0
  64. package/dist/types/middleware.d.ts +65 -0
  65. package/dist/types/middleware.js +1 -0
  66. package/dist/types/model.d.ts +166 -0
  67. package/dist/types/model.js +1 -0
  68. package/dist/types/session.d.ts +122 -0
  69. package/dist/types/session.js +1 -0
  70. package/dist/types/shared.d.ts +180 -0
  71. package/dist/types/shared.js +1 -0
  72. package/dist/types/tool.d.ts +101 -0
  73. package/dist/types/tool.js +1 -0
  74. package/dist/utils/digest.d.ts +1 -0
  75. package/dist/utils/digest.js +14 -0
  76. package/dist/utils/ids.d.ts +1 -0
  77. package/dist/utils/ids.js +3 -0
  78. package/dist/utils/immutable.d.ts +5 -0
  79. package/dist/utils/immutable.js +54 -0
  80. package/dist/utils/maps.d.ts +1 -0
  81. package/dist/utils/maps.js +37 -0
  82. package/dist/utils/observe.d.ts +8 -0
  83. package/dist/utils/observe.js +29 -0
  84. package/docs/loop.md +47 -0
  85. package/docs/model-call-projection.md +112 -0
  86. package/docs/reference.md +122 -0
  87. package/package.json +70 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@nylorun/harness` are documented in this file.
4
+
5
+ The project follows [Semantic Versioning](https://semver.org/). Before 1.0, the public API is experimental: breaking changes may occur in minor releases, while patch releases are reserved for compatible fixes.
6
+
7
+ ## [0.5.0-beta.1] - 2026-08-28
8
+
9
+ ### Breaking changes since 0.4.0-rc.1
10
+
11
+ - Replaced persistent `prefix` configuration with per-step `configuration`. Instructions, tools, model selection, and runtime context are assembled afresh for every model call; slot removal, context lifetimes, strict prefix policy, and Harness-owned drift auditing were removed. Middleware receives `turnId` and `stepId` to coordinate application-owned state.
12
+ - `model.prefix` and `model.started` were replaced by `model.requested`, emitted immediately before adapter invocation with the exact immutable `ModelCall` and JSON-safe attributed configuration/context snapshots.
13
+ - `tool()` now validates and normalizes its synchronous Zod object schema eagerly; raw tool literals retain first-bind preparation.
14
+
15
+ - Model adapters now receive the projected `ModelCall` as their first argument and `{ request, signal }` as their second. Implementations that consumed the prior request-shaped input must migrate to the projection and use `request` for the structured escape hatch.
16
+ - `InputHandle.consume()` and `AgentRunInput` were removed. Submit messages and interaction replies through the Session input API and await the returned completion handle instead.
17
+ - `session.observe()` now returns an idempotent unsubscribe function rather than the previous observer result. Observers remain live-only and do not replay history.
18
+ - Tool adapters and the tool facade removed the prior route-validation and route metadata methods. Tool definitions use `parameters` and `executeWith`; dispatch validation happens at the sealed Harness boundary.
19
+ - Harness-owned failures now use `HarnessError` with stable machine-readable codes. The prior outcome-code model has been replaced; see the migration table in the README for renamed and split codes. Foreign application, model, and adapter errors remain available as causes.
20
+
21
+ ### Added
22
+
23
+ - `ModelCall` projection, including canonical system text, transcript messages, provider tool contracts, model directive, and session id.
24
+ - Explicit abort propagation through the Model adapter context.
25
+ - Stable structured Harness errors via `HarnessError`, `HarnessErrorCode`, and `isHarnessError`.
26
+ - Parallel sibling tool execution by default, with an optional shared per-adapter `maxConcurrentCalls` limit on `.with(adapter, options)`.
27
+
28
+ ### Fixed
29
+
30
+ - Observe attributes are materialized only when a listener is registered. Transcript snapshots on `step.started` share the already-frozen step transcript rather than deep-copying it on every step.
31
+
32
+ [0.5.0-beta.1]: https://github.com/nylorun/harness/tree/main/harness
package/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ Copyright 2026 Nylo
181
+
182
+ Licensed under the Apache License, Version 2.0 (the "License");
183
+ you may not use this file except in compliance with the License.
184
+ You may obtain a copy of the License at
185
+
186
+ http://www.apache.org/licenses/LICENSE-2.0
187
+
188
+ Unless required by applicable law or agreed to in writing, software
189
+ distributed under the License is distributed on an "AS IS" BASIS,
190
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
191
+ See the License for the specific language governing permissions and
192
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,124 @@
1
+ # @nylorun/harness
2
+
3
+ `@nylorun/harness` is a small, provider-neutral agent loop. It seals one model adapter, an optional default model directive, tool adapters, and an ordered middleware onion into a fixed Agent, then runs independent in-memory Sessions. Middleware stages named changes against a session-scoped prompt-prefix state; each Model call receives an immutable canonical prefix, then its candidate is reviewed and its tool plan sealed before any adapter runs.
4
+
5
+ > **Experimental beta.** Install the current candidate with `npm install @nylorun/harness@beta`. Until 1.0, this API is intentionally experimental: minor releases may contain breaking changes, while patch releases are reserved for compatible fixes. See [CHANGELOG.md](./CHANGELOG.md) for migration notes.
6
+
7
+ ```ts
8
+ import { Agent, adapter, model, tool } from "@nylorun/harness";
9
+ import { z } from "zod";
10
+
11
+ const local = adapter({
12
+ id: "local",
13
+ async execute(call) {
14
+ return { kind: "completed" as const, output: { echoed: call.args } };
15
+ },
16
+ });
17
+
18
+ const echo = tool({
19
+ name: "echo",
20
+ description: "Echo a message",
21
+ parameters: z.object({ text: z.string() }),
22
+ executeWith: "local",
23
+ });
24
+
25
+ const example = model(async (call, { request }) => {
26
+ return request.toolResults.length === 0
27
+ ? {
28
+ output: [{ type: "tool-call", id: "call_1", name: "echo", args: { text: "hello" } }],
29
+ }
30
+ : `Completed with ${JSON.stringify(request.toolResults[0]?.output)}`;
31
+ });
32
+
33
+ const session = Agent(example, { id: "example" })
34
+ .with(local)
35
+ .use("echo", async (request, next) => {
36
+ request.configuration.tools.set("echo-tools", [echo], { order: 100 });
37
+ request.configuration.instructions.set("echo-policy", ["Echo the user text."], { order: 100 });
38
+ return next();
39
+ })
40
+ .use("turn-budget", async (request, next) => {
41
+ if (request.turnNumber > 8) {
42
+ return request.tripwire({ code: "turn.limit", message: "Limit reached" });
43
+ }
44
+ return next();
45
+ })
46
+ .build()
47
+ .run();
48
+ session.observe((event) => {
49
+ if (event.type === "model.requested") console.log("model", event.attributes);
50
+ });
51
+ session.input("Echo hello");
52
+ for await (const event of session.stream()) {
53
+ if (event.type === "final") {
54
+ console.log(event.output);
55
+ await session.stop();
56
+ }
57
+ }
58
+ ```
59
+
60
+ `Agent(model, directive?)` returns a builder. The first argument is the model callback `(call, { request, signal })`; the optional directive (`{ id?, controls?, config? }`) is seeded into every model step and can be replaced or cleared for that call. `.with(adapter, { maxConcurrentCalls? })` registers an adapter by `adapter.id` (required for tool dispatch via `executeWith`); omitted `maxConcurrentCalls` dispatches sibling `execute()` calls in parallel without a Harness cap, while a positive safe integer is a FIFO limit shared by all Sessions from that `BuiltAgent`. Adapter authors remain responsible for concurrent safety when no limit is supplied. Call order has no onion effect. `.use(middleware)` or `.use(id, middleware)` appends middleware (later is more inward); omitted ids become `middleware-1`, `middleware-2`, …. `.build()` validates ids and seals a `BuiltAgent`, or throws `AgentBuildError`. `BuiltAgent.run(options?)` creates an in-memory Session. `session.input("hello")` or `session.input({ text, metadata? })` queues a user message and returns a completion handle; while a turn is running or waiting, that message stays queued until the current turn finals, then a new turn starts. Approve and respond stay on `session.input({ kind: "approve" | "respond", ... })` — those are interaction replies, not messages. `session.interrupt("...")` queues barge-in text: if the current turn still has another step, the interrupt is claimed as that step’s arrivals (same turn, no abort of the in-flight model or tool work); if the turn already finalized, it starts a new turn like ordinary input. `session.stream()` yields the conversation (`input`, per-step `candidate`, then settlement events) — not observe events or tool results. `session.observe(listener)` adds a live, fail-open observer and returns an idempotent unsubscribe function; it does not replay earlier events. `session.stop()` ends that Session only.
61
+
62
+ ## Middleware
63
+
64
+ Middleware is the Model lifecycle:
65
+
66
+ ```ts
67
+ type StepMiddleware = (
68
+ request: StepRequest,
69
+ next: () => Promise<StepResponse>,
70
+ ) => Promise<StepResponse>;
71
+ ```
72
+
73
+ Each `StepRequest` includes opaque `sessionId`, `turnId`, and `stepId` identities, so middleware can associate application-owned state with the current execution. Draft the current call on `request.configuration`: named `instructions.set`, `tools.set`, and `model.select` / `replace` / `clear`; draft current-call tail data on `request.context.set`; or tripwire. `await next()` runs the inner onion and one Model call, then returns a branded `StepResponse`. Review that candidate (`deny`, `requireInteraction`, `requirePreflight`, `replace`, `tripwire`) and return it. Skipping `next()` is legal only by returning `request.tripwire(...)`. `void next()` is not supported.
74
+
75
+ Configuration and context are fresh assemblies for each model call. A repeated `set` for the same middleware/slot replaces that middleware’s earlier declaration in that step; nothing is retained for the next step. A middleware can declare only its own slot. Cross-cutting policy belongs in the tool-owning middleware or the host's final assembly decision; `deny()` remains available to reject a specific requested call after inspecting its arguments. Effective instruction and visible-tool order is canonical: explicit `order`, middleware registration order, slot name, then declaration order. A model directive is `{ id?, controls?, config? }`; `select` is idempotent, `replace` is the explicit override, and `clear` suppresses the Agent directive only for the current call. Duplicate tool names and invalid schemas tripwire before the Model runs. `reason` is attribution emitted to observers; Harness does not enforce drift policy.
76
+
77
+ Context is separate from the configuration digest. `context.set(slot, items, { order?, reason? })` contributes only to the current call. `run({ context })` is freshly projected as a host-attributed `type: "session"` item on every call. Applications that need state across calls own it and explicitly re-declare the model-visible portion using the request identities.
78
+
79
+ `ModelAdapter` receives a projected `ModelCall` first (`prompt`, `tools`, optional `model`, `sessionId`), then `{ request, signal }`: the structured `ModelRequest` escape hatch and its cancellation signal. `prompt` is an ordered typed list: `instructions` (system), then transcript `message` / `tool-result` items, then one `context` item when the committed snapshot is non-empty. Context is a user-role envelope around a JSON array of `{ type?, value }` — structural serialization so a value cannot mint a sibling prompt item, not a sandbox against prompt injection. Tool-result items keep `toolName` and `status`. Arrivals and toolResults stay on `request` — they are already on the transcript before invoke, so appending them would duplicate history. `turnId` and `stepId` stay on `ModelRequest` and observe events, not on `ModelCall`.
80
+
81
+ `ModelRequest.configuration` carries the selected model directive, ordered instruction text, visible provider tool contracts, contributor provenance, and logical/model/combined digests. `ModelRequest.context` is the current-step snapshot (items, contributors, digest). Immediately before invoking the adapter, Harness emits one `model.requested` event. Its `attributes.call` is the exact deeply immutable `ModelCall` supplied to the adapter; `attributes.configuration` and `attributes.context` are JSON-safe attributed snapshots. This is the immutable logical adapter-input boundary, not a provider-wire trace. Harness does not retain a baseline or audit drift; an observer such as Studio can compare these events and apply its own policy.
82
+
83
+ A successful Model return is a `ModelCandidate`: an ordered `output` of `text`, `reasoning`, and `tool-call` blocks, plus optional `finishReason`, `usage`, and `evidence`. A string return becomes one text block. Session `final` joins text blocks with `""`; reasoning is stored on the transcript candidate for observability and is never part of that string or of the tool plan. Harness projects its transcript into the portable `ModelCall` and omits reasoning when replaying assistant content. Tool-call `args` are a JSON object; `{}` is valid and is not a stand-in for parse failure. `finishReason` is `stop`, `length`, `tool-calls`, `content-filter`, or `other` — never `error` or `aborted`. Thrown `invoke` or an aborted signal stays on the `model.failed` / abort path. `evidence.extras` is for small safe fields, not raw request or response bodies. Token counts that are present must be non-negative integers; `costUsd` is optional and only when the provider supplied it.
84
+
85
+ The harness canonicalizes tool-call ids when it mints the response; `sealStep` reuses those ids. `replace` may drop calls and rewrite text or reasoning but cannot change a retained call’s name or arguments or undo an inner denial. A replace that omits `finishReason`, `usage`, or `evidence` keeps the current values.
86
+
87
+ A tripwire, invalid return, or bind failure on one Session does not stop sibling Sessions. Harness contract breaks are session-scoped. Late `setTimeout` mutations throw and emit observe events; they do not stop a settled Session.
88
+
89
+ The harness has no automatic turn, Step, or wall-clock timeout. Applications own budgets through middleware.
90
+
91
+ ## Structured errors and beta migration
92
+
93
+ Harness-created errors are `HarnessError` instances. Their `code` is stable and machine-readable; their `message` is explanatory and is not a compatibility contract. `details` contains only safe identifiers and paths, and `cause` preserves a foreign underlying error when there is one. Middleware-, model-, and adapter-originated errors remain foreign causes; application-owned tripwire and tool-result codes remain unrestricted strings.
94
+
95
+ Version 0.5.0-beta.1 replaces the following built-in outcome codes without aliases:
96
+
97
+ | Previous code / condition | 0.5 code |
98
+ | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
99
+ | `tool.duplicate-name` | `configuration.duplicate-tool-name` |
100
+ | `model.selection-conflict` | `configuration.model-selection-conflict` |
101
+ | `tool.invalid` | `tool.invalid-name`, `tool.invalid-schema`, or `adapter.not-registered` |
102
+ | `prefix.invalid` | `configuration.invalid-instructions`, `configuration.invalid-tools`, `configuration.invalid-slot`, `configuration.invalid-reason`, or `configuration.invalid-order` |
103
+ | prefix status / drift policy | Removed; compare `model.requested` events in the observing application. |
104
+ | `response.replace-invalid` | `response.invalid-replacement` |
105
+ | `model.failed` for invalid Harness-normalized candidates | `model.invalid-candidate` |
106
+ | `middleware.failed` for Harness middleware-protocol faults | `middleware.request-mutators-revoked`, `middleware.next-after-return`, or `middleware.next-called-twice` |
107
+ | `tool.execution-failed` / `tool.preflight-failed` for malformed Harness-validated adapter data | `adapter.invalid-outcome`, `tool.invalid-tool-result`, or `interaction.invalid` |
108
+ | `harness.invalid-directive` build diagnostic | `model.invalid-directive` |
109
+
110
+ Foreign model invocation failures still report `model.failed`; this distinguishes them from Harness validation failures.
111
+
112
+ ## Zod-only tool schemas
113
+
114
+ Harness `0.5.0-beta.1` accepts synchronous `z.object(...)` schemas only. Import `z` from `zod`; Harness does not re-export it. `tool()` validates and converts the schema to immutable JSON Schema when the definition is created; raw object literals are prepared on their first declaration.
115
+
116
+ ## Manifest
117
+
118
+ `agent.manifest` is a frozen description of the sealed onion, the optional default model directive, and adapters (`id` plus an optional `maxConcurrentCalls`). It has no session configuration state. Observe `model.requested` for the per-call, JSON-safe attributed assembly; executable tool validators are omitted.
119
+
120
+ The package intentionally does not own persistence, restart recovery, credentials, transports, provider-specific wire conversion, background jobs, or detached Tool work.
121
+
122
+ ## Internals
123
+
124
+ The in-memory loop is **build → session → turn → step**. Start with [docs/loop.md](./docs/loop.md). The complete [error-code and observe-event reference](./docs/reference.md) documents the stable machine-readable surfaces.
@@ -0,0 +1,11 @@
1
+ import type { AdapterExecutionOptions, ToolAdapter } from "../types/tool.js";
2
+ export interface BoundAdapterRegistration {
3
+ readonly adapter: ToolAdapter;
4
+ readonly options: AdapterExecutionOptions;
5
+ }
6
+ export interface AdapterRegistry {
7
+ readonly entries: ReadonlyMap<string, BoundAdapterRegistration>;
8
+ require<T extends ToolAdapter = ToolAdapter>(id: string): T;
9
+ execute<T>(id: string, signal: AbortSignal, task: () => Promise<T>): Promise<T>;
10
+ }
11
+ export declare function createAdapterRegistry(adapters?: readonly (BoundAdapterRegistration | ToolAdapter)[]): AdapterRegistry;
@@ -0,0 +1,91 @@
1
+ import { HarnessError } from "../errors.js";
2
+ import { createFixedMap } from "../utils/maps.js";
3
+ export function createAdapterRegistry(adapters = []) {
4
+ const entries = new Map();
5
+ const limiters = new Map();
6
+ for (const input of adapters) {
7
+ const entry = isBoundAdapterRegistration(input)
8
+ ? input
9
+ : Object.freeze({ adapter: input, options: Object.freeze({}) });
10
+ entries.set(entry.adapter.id, entry);
11
+ if (entry.options.maxConcurrentCalls !== undefined)
12
+ limiters.set(entry.adapter.id, new FifoLimiter(entry.options.maxConcurrentCalls));
13
+ }
14
+ return Object.freeze({
15
+ entries: createFixedMap(entries),
16
+ require(id) {
17
+ const entry = entries.get(id);
18
+ if (!entry)
19
+ throw new HarnessError("adapter.not-registered", `Tool adapter '${id}' is not registered`, {
20
+ details: { adapterId: id },
21
+ });
22
+ return entry.adapter;
23
+ },
24
+ async execute(id, signal, task) {
25
+ const limiter = limiters.get(id);
26
+ if (!limiter)
27
+ return task();
28
+ const release = await limiter.acquire(signal);
29
+ try {
30
+ return await task();
31
+ }
32
+ finally {
33
+ release();
34
+ }
35
+ },
36
+ });
37
+ }
38
+ function isBoundAdapterRegistration(value) {
39
+ return "adapter" in value && "options" in value;
40
+ }
41
+ class FifoLimiter {
42
+ limit;
43
+ active = 0;
44
+ waiting = [];
45
+ constructor(limit) {
46
+ this.limit = limit;
47
+ }
48
+ acquire(signal) {
49
+ if (signal.aborted)
50
+ return Promise.reject(signal.reason);
51
+ if (this.active < this.limit && this.waiting.length === 0) {
52
+ this.active += 1;
53
+ return Promise.resolve(this.release);
54
+ }
55
+ return new Promise((resolve, reject) => {
56
+ const waiter = {
57
+ resolve: () => resolve(this.release),
58
+ reject,
59
+ signal,
60
+ abort: () => {
61
+ this.remove(waiter);
62
+ reject(signal.reason);
63
+ },
64
+ };
65
+ signal.addEventListener("abort", waiter.abort, { once: true });
66
+ this.waiting.push(waiter);
67
+ });
68
+ }
69
+ release = () => {
70
+ this.active -= 1;
71
+ this.drain();
72
+ };
73
+ drain() {
74
+ while (this.active < this.limit && this.waiting.length) {
75
+ const waiter = this.waiting.shift();
76
+ waiter.signal.removeEventListener("abort", waiter.abort);
77
+ if (waiter.signal.aborted) {
78
+ waiter.reject(waiter.signal.reason);
79
+ continue;
80
+ }
81
+ this.active += 1;
82
+ waiter.resolve();
83
+ }
84
+ }
85
+ remove(waiter) {
86
+ const index = this.waiting.indexOf(waiter);
87
+ if (index !== -1)
88
+ this.waiting.splice(index, 1);
89
+ waiter.signal.removeEventListener("abort", waiter.abort);
90
+ }
91
+ }
@@ -0,0 +1,19 @@
1
+ import type { AgentManifest } from "../types/manifest.js";
2
+ import type { BoundMiddleware } from "../types/middleware.js";
3
+ import type { ModelAdapter, ModelDirective } from "../types/model.js";
4
+ import type { Session, SessionOptions } from "../types/session.js";
5
+ import type { AdapterRegistry } from "./adapters.js";
6
+ export interface LoopAgent {
7
+ readonly middleware: readonly BoundMiddleware[];
8
+ readonly invoke: ModelAdapter;
9
+ readonly directive?: ModelDirective;
10
+ readonly adapters: AdapterRegistry;
11
+ }
12
+ export declare class BuiltAgent {
13
+ #private;
14
+ readonly middleware: readonly BoundMiddleware[];
15
+ readonly manifest: AgentManifest;
16
+ private constructor();
17
+ run(options?: SessionOptions): Session;
18
+ }
19
+ export declare function bindAgent(middleware: readonly BoundMiddleware[], invoke: ModelAdapter, adapters: AdapterRegistry, manifest: AgentManifest, directive?: ModelDirective): BuiltAgent;
@@ -0,0 +1,28 @@
1
+ import { LiveSession } from "../session/session.js";
2
+ import { createId } from "../utils/ids.js";
3
+ let createBoundAgent;
4
+ export class BuiltAgent {
5
+ middleware;
6
+ manifest;
7
+ #loopAgent;
8
+ constructor(middleware, invoke, adapters, manifest, directive) {
9
+ this.middleware = middleware;
10
+ this.manifest = manifest;
11
+ this.#loopAgent = Object.freeze({
12
+ middleware,
13
+ invoke,
14
+ adapters,
15
+ ...(directive === undefined ? {} : { directive }),
16
+ });
17
+ }
18
+ static {
19
+ createBoundAgent = (middleware, invoke, adapters, manifest, directive) => new BuiltAgent(middleware, invoke, adapters, manifest, directive);
20
+ }
21
+ run(options = {}) {
22
+ const id = options.id ?? createId("session");
23
+ return new LiveSession(id, this.#loopAgent, options);
24
+ }
25
+ }
26
+ export function bindAgent(middleware, invoke, adapters, manifest, directive) {
27
+ return createBoundAgent(middleware, invoke, adapters, manifest, directive);
28
+ }
@@ -0,0 +1,9 @@
1
+ import type { BuildResult } from "../types/manifest.js";
2
+ import type { BoundMiddleware } from "../types/middleware.js";
3
+ import type { ModelAdapter, ModelDirective } from "../types/model.js";
4
+ import type { ToolAdapter } from "../types/tool.js";
5
+ import { type BuiltAgent } from "./agent.js";
6
+ export declare function assembleAgent(middleware: readonly BoundMiddleware[], invoke: ModelAdapter, adapters: readonly {
7
+ readonly adapter: ToolAdapter;
8
+ readonly options?: import("../types/tool.js").AdapterExecutionOptions;
9
+ }[], directive?: ModelDirective): BuildResult<BuiltAgent>;
@@ -0,0 +1,76 @@
1
+ import { normalizeDirective } from "../model-normalize.js";
2
+ import { isHarnessError } from "../errors.js";
3
+ import { bindAgent } from "./agent.js";
4
+ import { createAdapterRegistry } from "./adapters.js";
5
+ import { createManifest } from "./manifest.js";
6
+ const diagnostic = (code, message, extra = {}) => Object.freeze({ code, message, ...extra });
7
+ export function assembleAgent(middleware, invoke, adapters, directive) {
8
+ const diagnostics = [];
9
+ const adapterIds = new Set();
10
+ const validAdapters = [];
11
+ for (const entry of adapters) {
12
+ const adapter = entry?.adapter;
13
+ const id = adapter?.id;
14
+ if (!id)
15
+ diagnostics.push(diagnostic("adapter.invalid-id", "Adapter id must not be empty"));
16
+ else if (adapterIds.has(id))
17
+ diagnostics.push(diagnostic("adapter.duplicate-id", `Duplicate adapter id '${id}'`));
18
+ else if (typeof adapter.execute !== "function")
19
+ diagnostics.push(diagnostic("adapter.invalid", `Adapter '${id}' must provide execute()`));
20
+ else {
21
+ const limit = entry.options?.maxConcurrentCalls;
22
+ if (limit !== undefined &&
23
+ (!Number.isSafeInteger(limit) || !Number.isFinite(limit) || limit < 1)) {
24
+ diagnostics.push(diagnostic("adapter.invalid-max-concurrent-calls", `Adapter '${id}' maxConcurrentCalls must be a positive safe integer`));
25
+ continue;
26
+ }
27
+ adapterIds.add(id);
28
+ validAdapters.push(Object.freeze({
29
+ adapter,
30
+ options: Object.freeze(limit === undefined ? {} : { maxConcurrentCalls: limit }),
31
+ }));
32
+ }
33
+ }
34
+ if (typeof invoke !== "function") {
35
+ diagnostics.push(diagnostic("harness.invalid-model", "A model invoke function is required"));
36
+ }
37
+ let frozenDirective;
38
+ if (directive !== undefined) {
39
+ const normalized = normalizeDirective(directive);
40
+ if (isHarnessError(normalized))
41
+ diagnostics.push(diagnostic(normalized.code, normalized.message, {
42
+ ...(Object.keys(normalized.details).length ? { details: normalized.details } : {}),
43
+ ...(normalized.cause === undefined ? {} : { cause: normalized.cause }),
44
+ }));
45
+ else
46
+ frozenDirective = normalized;
47
+ }
48
+ const middlewareIds = new Set();
49
+ const frozen = [];
50
+ for (const item of middleware) {
51
+ if (!item.id)
52
+ diagnostics.push(diagnostic("middleware.invalid-id", "Middleware id must not be empty"));
53
+ else if (middlewareIds.has(item.id))
54
+ diagnostics.push(diagnostic("middleware.duplicate-id", `Duplicate middleware id '${item.id}'`));
55
+ else if (typeof item.handle !== "function")
56
+ diagnostics.push(diagnostic("middleware.invalid", `Middleware '${item.id}' must provide a function`));
57
+ else {
58
+ middlewareIds.add(item.id);
59
+ frozen.push(Object.freeze({
60
+ id: item.id,
61
+ handle: item.handle,
62
+ }));
63
+ }
64
+ }
65
+ if (diagnostics.length)
66
+ return Object.freeze({ ok: false, diagnostics: Object.freeze(diagnostics) });
67
+ const frozenMiddleware = Object.freeze(frozen);
68
+ const registry = createAdapterRegistry(Object.freeze(validAdapters));
69
+ const manifest = createManifest({
70
+ middleware: frozenMiddleware,
71
+ ...(frozenDirective === undefined ? {} : { directive: frozenDirective }),
72
+ adapters: registry,
73
+ });
74
+ const agent = bindAgent(frozenMiddleware, invoke, registry, manifest, frozenDirective);
75
+ return Object.freeze({ ok: true, agent, manifest });
76
+ }
@@ -0,0 +1,4 @@
1
+ import type { BoundToolDefinition, ToolDefinition } from "../types/tool.js";
2
+ import type { AdapterRegistry } from "./adapters.js";
3
+ /** Binds one Tool definition against the Agent's adapter registry. */
4
+ export declare function bindTool(item: ToolDefinition, adapters: AdapterRegistry): BoundToolDefinition;
@@ -0,0 +1,15 @@
1
+ import { HarnessError } from "../errors.js";
2
+ import { normalizedSchemaFor } from "./schema.js";
3
+ /** Binds one Tool definition against the Agent's adapter registry. */
4
+ export function bindTool(item, adapters) {
5
+ if (!item.name)
6
+ throw new HarnessError("tool.invalid-name", "Tool name must not be empty");
7
+ adapters.require(item.executeWith);
8
+ const parameters = normalizedSchemaFor(item);
9
+ return Object.freeze({
10
+ name: item.name,
11
+ ...(item.description ? { description: item.description } : {}),
12
+ parameters: parameters,
13
+ executeWith: item.executeWith,
14
+ });
15
+ }
@@ -0,0 +1,31 @@
1
+ import type { StepMiddleware } from "../types/middleware.js";
2
+ import type { ModelAdapter, ModelDirective } from "../types/model.js";
3
+ import type { BuildDiagnostic } from "../types/shared.js";
4
+ import type { AdapterExecutionOptions, ToolAdapter } from "../types/tool.js";
5
+ import { HarnessError } from "../errors.js";
6
+ import type { BuiltAgent } from "./agent.js";
7
+ export declare class AgentBuildError extends HarnessError {
8
+ readonly diagnostics: readonly BuildDiagnostic[];
9
+ constructor(diagnostics: readonly BuildDiagnostic[]);
10
+ }
11
+ export declare class AgentLifecycleError extends HarnessError {
12
+ constructor(message: string);
13
+ }
14
+ export declare function Agent(model: ModelAdapter, directive?: ModelDirective): AgentBuilder;
15
+ export declare class AgentBuilder {
16
+ private readonly invoke;
17
+ private readonly directive?;
18
+ private readonly middleware;
19
+ private readonly adapters;
20
+ private sealed;
21
+ private agent?;
22
+ private error?;
23
+ private middlewareSeq;
24
+ constructor(invoke: ModelAdapter, directive?: ModelDirective | undefined);
25
+ with(adapter: ToolAdapter, options?: AdapterExecutionOptions): this;
26
+ use(middleware: StepMiddleware): this;
27
+ use(id: string, middleware: StepMiddleware): this;
28
+ build(): BuiltAgent;
29
+ private nextMiddlewareId;
30
+ private push;
31
+ }