@boardwalk-labs/engine 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +69 -0
- package/bin/boardwalk-server.js +16 -0
- package/dist/agent/conversation.d.ts +42 -0
- package/dist/agent/conversation.js +4 -0
- package/dist/agent/leaf.d.ts +81 -0
- package/dist/agent/leaf.js +190 -0
- package/dist/agent/providers.d.ts +23 -0
- package/dist/agent/providers.js +347 -0
- package/dist/agent/rates.d.ts +13 -0
- package/dist/agent/rates.js +35 -0
- package/dist/agent/redact.d.ts +9 -0
- package/dist/agent/redact.js +27 -0
- package/dist/agent/resolve.d.ts +58 -0
- package/dist/agent/resolve.js +153 -0
- package/dist/agent/sse.d.ts +2 -0
- package/dist/agent/sse.js +30 -0
- package/dist/agent/tools.d.ts +57 -0
- package/dist/agent/tools.js +324 -0
- package/dist/clock.d.ts +8 -0
- package/dist/clock.js +32 -0
- package/dist/cron/cron.d.ts +34 -0
- package/dist/cron/cron.js +331 -0
- package/dist/engine.d.ts +106 -0
- package/dist/engine.js +183 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.js +40 -0
- package/dist/ids.d.ts +7 -0
- package/dist/ids.js +42 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +8 -0
- package/dist/json_value.d.ts +7 -0
- package/dist/json_value.js +29 -0
- package/dist/mcp/client.d.ts +39 -0
- package/dist/mcp/client.js +112 -0
- package/dist/mcp/jsonrpc.d.ts +57 -0
- package/dist/mcp/jsonrpc.js +117 -0
- package/dist/mcp/oauth.d.ts +72 -0
- package/dist/mcp/oauth.js +337 -0
- package/dist/mcp/token_store.d.ts +30 -0
- package/dist/mcp/token_store.js +101 -0
- package/dist/mcp/transport_http.d.ts +38 -0
- package/dist/mcp/transport_http.js +143 -0
- package/dist/mcp/transport_stdio.d.ts +27 -0
- package/dist/mcp/transport_stdio.js +94 -0
- package/dist/run/child.d.ts +1 -0
- package/dist/run/child.js +139 -0
- package/dist/run/child_host.d.ts +26 -0
- package/dist/run/child_host.js +124 -0
- package/dist/run/idempotency.d.ts +5 -0
- package/dist/run/idempotency.js +31 -0
- package/dist/run/ipc.d.ts +159 -0
- package/dist/run/ipc.js +150 -0
- package/dist/run/run_dir.d.ts +31 -0
- package/dist/run/run_dir.js +106 -0
- package/dist/run/supervisor.d.ts +107 -0
- package/dist/run/supervisor.js +676 -0
- package/dist/scheduler/scheduler.d.ts +54 -0
- package/dist/scheduler/scheduler.js +215 -0
- package/dist/server/http.d.ts +42 -0
- package/dist/server/http.js +183 -0
- package/dist/server/routes/api.d.ts +17 -0
- package/dist/server/routes/api.js +107 -0
- package/dist/server/routes/hooks.d.ts +2 -0
- package/dist/server/routes/hooks.js +88 -0
- package/dist/server/routes/router.d.ts +15 -0
- package/dist/server/routes/router.js +75 -0
- package/dist/server/routes/stream.d.ts +2 -0
- package/dist/server/routes/stream.js +79 -0
- package/dist/server/routes/ui.d.ts +2 -0
- package/dist/server/routes/ui.js +120 -0
- package/dist/server/server.d.ts +25 -0
- package/dist/server/server.js +67 -0
- package/dist/server_main.d.ts +46 -0
- package/dist/server_main.js +203 -0
- package/dist/store/migrations.d.ts +21 -0
- package/dist/store/migrations.js +159 -0
- package/dist/store/store.d.ts +194 -0
- package/dist/store/store.js +567 -0
- package/package.json +57 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# boardwalk
|
|
2
|
+
|
|
3
|
+
The open-source single-node engine for Boardwalk workflows: cron scheduling, durable run
|
|
4
|
+
semantics, SQLite run history, and a local run log — on hardware you own, with no account.
|
|
5
|
+
|
|
6
|
+
> **Status: pre-release.** This repo is being built in the open ahead of its first published
|
|
7
|
+
> release. The contracts it implements are stable (see [`@boardwalk-labs/workflow`](https://www.npmjs.com/package/@boardwalk-labs/workflow));
|
|
8
|
+
> the engine itself is under active construction. See [`SPEC.md`](./SPEC.md) for the
|
|
9
|
+
> architecture and the definition of done.
|
|
10
|
+
|
|
11
|
+
## What it is
|
|
12
|
+
|
|
13
|
+
A workflow is a plain TypeScript program. This engine runs it:
|
|
14
|
+
|
|
15
|
+
- **Server mode** — `docker run ghcr.io/boardwalk-labs/boardwalk`: a long-lived process that schedules cron
|
|
16
|
+
workflows, accepts webhooks, keeps run history in SQLite, and serves a local run log.
|
|
17
|
+
- **Embedded mode** — `@boardwalk-labs/engine` as a library: one run, in-process supervision; this is
|
|
18
|
+
what `boardwalk dev` uses.
|
|
19
|
+
|
|
20
|
+
Same engine, same semantics as the Boardwalk platform: one run = one process, `sleep` holds the
|
|
21
|
+
process, a crash restarts the run from the top, `workflows.call` re-attaches idempotently.
|
|
22
|
+
The conformance suite in this repo tests that parity.
|
|
23
|
+
|
|
24
|
+
## Quickstart
|
|
25
|
+
|
|
26
|
+
Run the server with Docker — run history and state live in the mounted data dir:
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
docker run -v ./data:/data -p 8080:8080 ghcr.io/boardwalk-labs/boardwalk
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Then open `http://localhost:8080` for the run log, or hit the JSON API
|
|
33
|
+
(`/api/workflows`, `/api/runs`). Webhook triggers land on `/hooks/<workflow>/<trigger-id>`.
|
|
34
|
+
|
|
35
|
+
### Configuration
|
|
36
|
+
|
|
37
|
+
All configuration is environment variables (a `boardwalk.toml` file is deferred — see
|
|
38
|
+
[`SPEC.md`](./SPEC.md) §2.4):
|
|
39
|
+
|
|
40
|
+
| Variable | Default | What it does |
|
|
41
|
+
| ------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------- |
|
|
42
|
+
| `BOARDWALK_DATA_DIR` | `/data` in Docker, else `./boardwalk-data` | Where everything lives: SQLite DB, run dirs, artifacts |
|
|
43
|
+
| `BOARDWALK_HOST` | `127.0.0.1` (`0.0.0.0` in Docker) | Bind address — this surface has no auth beyond webhook auth, so binding wider logs a warning |
|
|
44
|
+
| `BOARDWALK_PORT` | `8080` | Listen port (`0` picks a free port) |
|
|
45
|
+
| `BOARDWALK_DEFAULT_MODEL` | — | Model used when `agent()` omits one, e.g. `anthropic/claude-sonnet-4-5` |
|
|
46
|
+
| `BOARDWALK_PROVIDERS` | — | JSON provider table, e.g. `{"ollama":{"base_url":"http://localhost:11434/v1"}}` |
|
|
47
|
+
| `BOARDWALK_ENV_FILE` | `<data-dir>/.env`, if it exists | `.env` file backing `secrets.get` and provider API keys |
|
|
48
|
+
|
|
49
|
+
Provider API keys come from the environment (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`,
|
|
50
|
+
`GEMINI_API_KEY` for the built-ins; `api_key_env` names the variable for custom providers).
|
|
51
|
+
|
|
52
|
+
### Embedded mode
|
|
53
|
+
|
|
54
|
+
The same engine as a library — this is what `boardwalk dev` does:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { Engine } from "@boardwalk-labs/engine";
|
|
58
|
+
|
|
59
|
+
const engine = new Engine({ dataDir: "./boardwalk-data" });
|
|
60
|
+
const run = await engine.runOnce({ program: bundledProgramSource });
|
|
61
|
+
console.log(run.status, run.output);
|
|
62
|
+
engine.close();
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
For OAuth-protected MCP servers an `agent()` call connects to, `engine.authorizeMcpServer(url, { onAuthorizationUrl })` performs the one-time interactive grant; after that, runs use (and silently refresh) the stored token headlessly — see [SPEC.md §2.3](./SPEC.md).
|
|
66
|
+
|
|
67
|
+
## License
|
|
68
|
+
|
|
69
|
+
Apache-2.0 — see [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Thin launcher for `boardwalk-server` (SPEC §5). All real logic lives in compiled,
|
|
3
|
+
// type-checked, tested TypeScript (src/server_main.ts) — this shim only exists so npm `bin`
|
|
4
|
+
// and the Docker CMD share one entrypoint that resolves dist/ relative to the package.
|
|
5
|
+
import("../dist/server_main.js")
|
|
6
|
+
.then((mod) => mod.main())
|
|
7
|
+
.catch((err) => {
|
|
8
|
+
// Boot failures are usually operator config mistakes: print the message (and the
|
|
9
|
+
// EngineError hint when present), never a stack trace into engine internals.
|
|
10
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
11
|
+
process.stderr.write(`boardwalk-server: ${message}\n`);
|
|
12
|
+
if (err !== null && typeof err === "object" && typeof err.hint === "string") {
|
|
13
|
+
process.stderr.write(` hint: ${err.hint}\n`);
|
|
14
|
+
}
|
|
15
|
+
process.exit(1);
|
|
16
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** A tool the model may call, as advertised to the provider. */
|
|
2
|
+
export interface ToolSpec {
|
|
3
|
+
name: string;
|
|
4
|
+
description: string;
|
|
5
|
+
inputSchema: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
/** A tool invocation the model requested in an assistant turn. */
|
|
8
|
+
export interface ToolCallRequest {
|
|
9
|
+
/** Provider-assigned call id — echoed back with the result. */
|
|
10
|
+
id: string;
|
|
11
|
+
name: string;
|
|
12
|
+
input: Record<string, unknown>;
|
|
13
|
+
}
|
|
14
|
+
export type ChatMessage = {
|
|
15
|
+
role: "user";
|
|
16
|
+
text: string;
|
|
17
|
+
} | {
|
|
18
|
+
role: "assistant";
|
|
19
|
+
text: string;
|
|
20
|
+
toolCalls: readonly ToolCallRequest[];
|
|
21
|
+
} | {
|
|
22
|
+
role: "tool_results";
|
|
23
|
+
results: readonly ToolResultMessage[];
|
|
24
|
+
};
|
|
25
|
+
export interface ToolResultMessage {
|
|
26
|
+
/** The ToolCallRequest id this answers. */
|
|
27
|
+
id: string;
|
|
28
|
+
/** Result content, already stringified (and redacted) by the loop. */
|
|
29
|
+
content: string;
|
|
30
|
+
isError: boolean;
|
|
31
|
+
}
|
|
32
|
+
/** One model turn: final text and/or tool-call requests, plus usage. */
|
|
33
|
+
export interface ChatTurn {
|
|
34
|
+
text: string;
|
|
35
|
+
toolCalls: ToolCallRequest[];
|
|
36
|
+
usage: {
|
|
37
|
+
inputTokens?: number | undefined;
|
|
38
|
+
outputTokens?: number | undefined;
|
|
39
|
+
};
|
|
40
|
+
/** True when the model stopped to call tools (the loop continues). */
|
|
41
|
+
wantsTools: boolean;
|
|
42
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// The provider-neutral conversation model for the agent() loop. The leaf builds these;
|
|
2
|
+
// each protocol adapter maps them to its wire format. Keeping the loop neutral is what lets
|
|
3
|
+
// two adapters (Anthropic + OpenAI-compatible) cover every supported endpoint.
|
|
4
|
+
export {};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { AgentOptions, TokenUsage, ToolReturn } from "@boardwalk-labs/workflow";
|
|
2
|
+
import { type ProviderIo } from "./providers.js";
|
|
3
|
+
import type { Redactor } from "./redact.js";
|
|
4
|
+
import type { ResolvedModel } from "./resolve.js";
|
|
5
|
+
import { type McpTokenResult, type ToolSetContext } from "./tools.js";
|
|
6
|
+
/**
|
|
7
|
+
* Identity of one `agent()` leaf, carried on its `turn_started`/`turn_ended` frames so a stream
|
|
8
|
+
* consumer can tell concurrent agents apart. `agentId` is stable and run-unique (engine-assigned);
|
|
9
|
+
* `agentName` is the author's `AgentOptions.name`, present only when they set one.
|
|
10
|
+
*/
|
|
11
|
+
export interface AgentIdentity {
|
|
12
|
+
agentId: string;
|
|
13
|
+
agentName?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A leaf event body, scoped to the leaf's turn. `turn_started` itself is emitted by the
|
|
17
|
+
* supervisor when the turn opens (io.startTurn) — the leaf only emits what follows.
|
|
18
|
+
*/
|
|
19
|
+
export type LeafEventBody = ({
|
|
20
|
+
kind: "turn_ended";
|
|
21
|
+
reason: "complete" | "error";
|
|
22
|
+
usage?: TokenUsage;
|
|
23
|
+
error?: {
|
|
24
|
+
code: string;
|
|
25
|
+
message: string;
|
|
26
|
+
};
|
|
27
|
+
} & AgentIdentity) | {
|
|
28
|
+
kind: "text_start";
|
|
29
|
+
blockId: string;
|
|
30
|
+
} | {
|
|
31
|
+
kind: "text_delta";
|
|
32
|
+
blockId: string;
|
|
33
|
+
text: string;
|
|
34
|
+
} | {
|
|
35
|
+
kind: "text_end";
|
|
36
|
+
blockId: string;
|
|
37
|
+
} | {
|
|
38
|
+
kind: "tool_call_start";
|
|
39
|
+
toolCallId: string;
|
|
40
|
+
toolName: string;
|
|
41
|
+
} | {
|
|
42
|
+
kind: "tool_call_input_complete";
|
|
43
|
+
toolCallId: string;
|
|
44
|
+
input: Record<string, unknown>;
|
|
45
|
+
} | {
|
|
46
|
+
kind: "tool_call_executing";
|
|
47
|
+
toolCallId: string;
|
|
48
|
+
} | {
|
|
49
|
+
kind: "tool_call_result";
|
|
50
|
+
toolCallId: string;
|
|
51
|
+
result: ToolReturn;
|
|
52
|
+
} | {
|
|
53
|
+
kind: "tool_call_error";
|
|
54
|
+
toolCallId: string;
|
|
55
|
+
error: {
|
|
56
|
+
code: string;
|
|
57
|
+
message: string;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
export interface LeafIo {
|
|
61
|
+
/** This leaf's identity — stamped onto its turn_started (via startTurn) and turn_ended frames. */
|
|
62
|
+
identity: AgentIdentity;
|
|
63
|
+
/** Supervisor-side model resolution (config + key material never live in this process). */
|
|
64
|
+
resolve(model: string | undefined, provider: string | undefined): Promise<ResolvedModel>;
|
|
65
|
+
/** Open a new turn block; subsequent leaf events carry this turnId. */
|
|
66
|
+
startTurn(turnId: string): void;
|
|
67
|
+
emit(turnId: string, body: LeafEventBody): void;
|
|
68
|
+
/** Usage flows to the supervisor — the budget authority — after EVERY model call, so a
|
|
69
|
+
* long tool loop can be terminated mid-flight. */
|
|
70
|
+
reportUsage(modelRef: string, usage: TokenUsage): void;
|
|
71
|
+
/** Tell the engine a memory dir is in use — it auto-persists it across runs. */
|
|
72
|
+
memoryUsed(dir: string): void;
|
|
73
|
+
/** Broker an MCP OAuth bearer token from the engine (token state never lives here). */
|
|
74
|
+
mcpToken(serverUrl: string, invalidateToken?: string): Promise<McpTokenResult>;
|
|
75
|
+
redactor: Redactor;
|
|
76
|
+
/** Capability context: where the workspace and deployed skills live. */
|
|
77
|
+
capabilities: ToolSetContext;
|
|
78
|
+
provider?: ProviderIo;
|
|
79
|
+
}
|
|
80
|
+
/** Execute one agent() leaf call; resolves to final text, or the parsed object in schema mode. */
|
|
81
|
+
export declare function runAgentLeaf(prompt: string, opts: AgentOptions | undefined, io: LeafIo): Promise<unknown>;
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// The agent() leaf: a real agentic loop (SDK SPEC §2.1.1) — streamed model turns with tool
|
|
2
|
+
// use (program-defined ToolDefs + memory file tools + MCP server tools), skills loaded into
|
|
3
|
+
// context, schema output, secret redaction, and usage reporting. Runs IN THE PROGRAM PROCESS
|
|
4
|
+
// (tool `execute` must run in the trusted layer, and MCP connections live where their tools
|
|
5
|
+
// execute); model/provider/key resolution and MCP OAuth token state stay supervisor-side and
|
|
6
|
+
// arrive through `io.resolve` / `io.mcpToken`.
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { EngineError } from "../errors.js";
|
|
9
|
+
import { chatAnthropic, chatOpenAi } from "./providers.js";
|
|
10
|
+
import { assertUniqueToolNames, buildToolSet, connectMcpServers, } from "./tools.js";
|
|
11
|
+
/** Tool iterations per agent() call before the loop is declared runaway. */
|
|
12
|
+
const MAX_TOOL_ITERATIONS = 25;
|
|
13
|
+
/** Execute one agent() leaf call; resolves to final text, or the parsed object in schema mode. */
|
|
14
|
+
export async function runAgentLeaf(prompt, opts, io) {
|
|
15
|
+
const base = buildToolSet(opts, io.capabilities);
|
|
16
|
+
if (base.memoryDir !== null)
|
|
17
|
+
io.memoryUsed(base.memoryDir);
|
|
18
|
+
// MCP connections open AFTER sync validation and BEFORE the first model call; a server the
|
|
19
|
+
// call named must resolve or the leaf fails here, never silently degrading the tool set.
|
|
20
|
+
const connected = base.mcp.length === 0
|
|
21
|
+
? null
|
|
22
|
+
: await connectMcpServers(base.mcp, {
|
|
23
|
+
mcpToken: (serverUrl, invalidateToken) => io.mcpToken(serverUrl, invalidateToken),
|
|
24
|
+
redactor: io.redactor,
|
|
25
|
+
});
|
|
26
|
+
try {
|
|
27
|
+
return await runLeafWithTools(prompt, opts, io, [...base.tools, ...(connected?.tools ?? [])], base.preamble);
|
|
28
|
+
}
|
|
29
|
+
finally {
|
|
30
|
+
// Disconnect on completion AND on error — stdio servers are real child processes.
|
|
31
|
+
if (connected !== null)
|
|
32
|
+
await connected.disconnect();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async function runLeafWithTools(prompt, opts, io, tools, preamble) {
|
|
36
|
+
// Re-check across the MERGED set: a namespaced MCP tool can collide with a program tool.
|
|
37
|
+
assertUniqueToolNames(tools);
|
|
38
|
+
const resolved = await io.resolve(opts?.model, opts?.provider);
|
|
39
|
+
// The provider key (and any env-sourced custom headers) are now known to this process —
|
|
40
|
+
// make sure they can never reach the model.
|
|
41
|
+
if (resolved.apiKey !== null)
|
|
42
|
+
io.redactor.add(`api-key:${resolved.provider}`, resolved.apiKey);
|
|
43
|
+
for (const name of resolved.secretHeaderNames) {
|
|
44
|
+
const value = resolved.headers[name];
|
|
45
|
+
if (value !== undefined)
|
|
46
|
+
io.redactor.add(`header:${name}`, value);
|
|
47
|
+
}
|
|
48
|
+
const schemaInstruction = opts?.schema === undefined
|
|
49
|
+
? []
|
|
50
|
+
: [
|
|
51
|
+
`Respond with ONLY a JSON value matching this JSON Schema — no prose, no code fences:\n${JSON.stringify(opts.schema)}`,
|
|
52
|
+
];
|
|
53
|
+
const firstMessage = [...preamble, prompt, ...schemaInstruction].join("\n\n");
|
|
54
|
+
const turnId = `turn-${randomUUID()}`;
|
|
55
|
+
io.startTurn(turnId);
|
|
56
|
+
const totals = {
|
|
57
|
+
inputTokens: 0,
|
|
58
|
+
outputTokens: 0,
|
|
59
|
+
};
|
|
60
|
+
const messages = [{ role: "user", text: io.redactor.redact(firstMessage) }];
|
|
61
|
+
let finalText;
|
|
62
|
+
try {
|
|
63
|
+
finalText = await runToolLoop(messages, tools, resolved, io, turnId, totals);
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
// Redact like the tool path does: a misbehaving provider can echo request headers (the
|
|
67
|
+
// API key) into an error body, and this message persists in run_events AND — via the
|
|
68
|
+
// rethrow — in the run's failed row. The secrets invariant covers error paths too.
|
|
69
|
+
const message = io.redactor.redact(err instanceof Error ? err.message : String(err));
|
|
70
|
+
const code = err instanceof EngineError ? err.code : "PROVIDER_ERROR";
|
|
71
|
+
io.emit(turnId, {
|
|
72
|
+
kind: "turn_ended",
|
|
73
|
+
...io.identity,
|
|
74
|
+
reason: "error",
|
|
75
|
+
error: { code, message },
|
|
76
|
+
});
|
|
77
|
+
throw new EngineError(code, message, err instanceof EngineError && err.hint !== undefined
|
|
78
|
+
? io.redactor.redact(err.hint)
|
|
79
|
+
: undefined);
|
|
80
|
+
}
|
|
81
|
+
io.emit(turnId, {
|
|
82
|
+
kind: "turn_ended",
|
|
83
|
+
...io.identity,
|
|
84
|
+
reason: "complete",
|
|
85
|
+
usage: { inputTokens: totals.inputTokens, outputTokens: totals.outputTokens },
|
|
86
|
+
});
|
|
87
|
+
return opts?.schema === undefined ? finalText : parseSchemaOutput(finalText);
|
|
88
|
+
}
|
|
89
|
+
async function runToolLoop(messages, tools, resolved, io, turnId, totals) {
|
|
90
|
+
for (let iteration = 1; iteration <= MAX_TOOL_ITERATIONS; iteration++) {
|
|
91
|
+
const turn = await modelTurn(messages, tools, resolved, io, turnId, iteration);
|
|
92
|
+
totals.inputTokens += turn.usage.inputTokens ?? 0;
|
|
93
|
+
totals.outputTokens += turn.usage.outputTokens ?? 0;
|
|
94
|
+
io.reportUsage(resolved.model, turn.usage);
|
|
95
|
+
if (!turn.wantsTools || turn.toolCalls.length === 0) {
|
|
96
|
+
return turn.text;
|
|
97
|
+
}
|
|
98
|
+
messages.push({ role: "assistant", text: turn.text, toolCalls: turn.toolCalls });
|
|
99
|
+
const results = [];
|
|
100
|
+
for (const call of turn.toolCalls) {
|
|
101
|
+
results.push(await executeToolCall(call, tools, io, turnId));
|
|
102
|
+
}
|
|
103
|
+
messages.push({ role: "tool_results", results });
|
|
104
|
+
}
|
|
105
|
+
throw new EngineError("PROGRAM_ERROR", `agent() exceeded ${String(MAX_TOOL_ITERATIONS)} tool iterations without a final answer.`, "The model is looping on tool calls. Tighten the prompt, or split the work across calls.");
|
|
106
|
+
}
|
|
107
|
+
/** One model call with streamed text events (block ids are unique per iteration). */
|
|
108
|
+
async function modelTurn(messages, tools, resolved, io, turnId, iteration) {
|
|
109
|
+
const blockId = `text-${String(iteration)}`;
|
|
110
|
+
let blockOpen = false;
|
|
111
|
+
const providerIo = {
|
|
112
|
+
...io.provider,
|
|
113
|
+
onDelta: (text) => {
|
|
114
|
+
if (!blockOpen) {
|
|
115
|
+
blockOpen = true;
|
|
116
|
+
io.emit(turnId, { kind: "text_start", blockId });
|
|
117
|
+
}
|
|
118
|
+
io.emit(turnId, { kind: "text_delta", blockId, text: io.redactor.redact(text) });
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
const args = {
|
|
122
|
+
baseUrl: resolved.baseUrl,
|
|
123
|
+
apiKey: resolved.apiKey,
|
|
124
|
+
headers: resolved.headers,
|
|
125
|
+
model: resolved.model,
|
|
126
|
+
messages,
|
|
127
|
+
tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
|
|
128
|
+
};
|
|
129
|
+
const turn = resolved.protocol === "anthropic"
|
|
130
|
+
? await chatAnthropic(args, providerIo)
|
|
131
|
+
: await chatOpenAi(args, providerIo);
|
|
132
|
+
if (blockOpen)
|
|
133
|
+
io.emit(turnId, { kind: "text_end", blockId });
|
|
134
|
+
return turn;
|
|
135
|
+
}
|
|
136
|
+
/** Run one tool call; failures return to the MODEL as error results, they don't fail the run. */
|
|
137
|
+
async function executeToolCall(call, tools, io, turnId) {
|
|
138
|
+
io.emit(turnId, { kind: "tool_call_start", toolCallId: call.id, toolName: call.name });
|
|
139
|
+
io.emit(turnId, { kind: "tool_call_input_complete", toolCallId: call.id, input: call.input });
|
|
140
|
+
const tool = tools.find((t) => t.name === call.name);
|
|
141
|
+
if (tool === undefined) {
|
|
142
|
+
// The model invented a tool name — its mistake to recover from, not a run failure.
|
|
143
|
+
const message = `Unknown tool "${call.name}".`;
|
|
144
|
+
io.emit(turnId, {
|
|
145
|
+
kind: "tool_call_error",
|
|
146
|
+
toolCallId: call.id,
|
|
147
|
+
error: { code: "VALIDATION", message },
|
|
148
|
+
});
|
|
149
|
+
return { id: call.id, content: message, isError: true };
|
|
150
|
+
}
|
|
151
|
+
io.emit(turnId, { kind: "tool_call_executing", toolCallId: call.id });
|
|
152
|
+
try {
|
|
153
|
+
// Tool results enter model context → redact (MASTER_SPEC §6.2 covers tool results too).
|
|
154
|
+
const content = io.redactor.redact(await tool.execute(call.input));
|
|
155
|
+
io.emit(turnId, {
|
|
156
|
+
kind: "tool_call_result",
|
|
157
|
+
toolCallId: call.id,
|
|
158
|
+
result: { humanSummary: summarize(content) },
|
|
159
|
+
});
|
|
160
|
+
return { id: call.id, content, isError: false };
|
|
161
|
+
}
|
|
162
|
+
catch (err) {
|
|
163
|
+
const message = io.redactor.redact(err instanceof Error ? err.message : String(err));
|
|
164
|
+
const code = err instanceof EngineError ? err.code : "PROGRAM_ERROR";
|
|
165
|
+
io.emit(turnId, { kind: "tool_call_error", toolCallId: call.id, error: { code, message } });
|
|
166
|
+
return { id: call.id, content: `Tool failed: ${message}`, isError: true };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function summarize(content) {
|
|
170
|
+
const flat = content.replaceAll("\n", " ");
|
|
171
|
+
return flat.length <= 120 ? flat : `${flat.slice(0, 117)}…`;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Schema mode: parse the model's final text as JSON; a non-JSON answer fails the run (the
|
|
175
|
+
* documented contract). Code fences are stripped first — models add them despite instructions.
|
|
176
|
+
* v0 parity note: like the hosted platform today, the schema drives the PROMPT and the JSON
|
|
177
|
+
* parse; structural validation against the schema itself is a later, cross-engine decision.
|
|
178
|
+
*/
|
|
179
|
+
function parseSchemaOutput(text) {
|
|
180
|
+
const stripped = text
|
|
181
|
+
.trim()
|
|
182
|
+
.replace(/^```(?:json)?\s*\n?/i, "")
|
|
183
|
+
.replace(/\n?```\s*$/, "");
|
|
184
|
+
try {
|
|
185
|
+
return JSON.parse(stripped);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
throw new EngineError("VALIDATION", "agent() was called with a schema but the model's answer was not valid JSON.", `Answer started with: ${JSON.stringify(stripped.slice(0, 80))}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ChatMessage, ChatTurn, ToolSpec } from "./conversation.js";
|
|
2
|
+
export interface ChatArgs {
|
|
3
|
+
baseUrl: string;
|
|
4
|
+
apiKey: string | null;
|
|
5
|
+
/** Extra request headers (custom auth schemes etc.). WIN over computed auth on collision;
|
|
6
|
+
* content-type stays engine-owned. */
|
|
7
|
+
headers?: Record<string, string>;
|
|
8
|
+
/** Opaque model string, sent verbatim. */
|
|
9
|
+
model: string;
|
|
10
|
+
messages: readonly ChatMessage[];
|
|
11
|
+
tools: readonly ToolSpec[];
|
|
12
|
+
/** Anthropic requires max_tokens; this default is deliberately generous. */
|
|
13
|
+
maxTokens?: number;
|
|
14
|
+
}
|
|
15
|
+
/** Injectable effects so adapter logic is unit-testable without a network or real waits. */
|
|
16
|
+
export interface ProviderIo {
|
|
17
|
+
fetchImpl?: typeof fetch;
|
|
18
|
+
sleepImpl?: (ms: number) => Promise<void>;
|
|
19
|
+
/** Streamed text chunks, in order, as they arrive (drives text_delta events). */
|
|
20
|
+
onDelta?: (text: string) => void;
|
|
21
|
+
}
|
|
22
|
+
export declare function chatAnthropic(args: ChatArgs, io?: ProviderIo): Promise<ChatTurn>;
|
|
23
|
+
export declare function chatOpenAi(args: ChatArgs, io?: ProviderIo): Promise<ChatTurn>;
|