@nylorun/agents 0.0.0-bootstrap → 0.2.0-beta
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 +25 -0
- package/LICENSE +192 -0
- package/README.md +60 -0
- package/dist/client.d.ts +121 -0
- package/dist/client.js +103 -0
- package/dist/define.d.ts +1 -0
- package/dist/define.js +1 -0
- package/dist/execute-action.d.ts +4 -0
- package/dist/execute-action.js +190 -0
- package/dist/executor.d.ts +15 -0
- package/dist/executor.js +215 -0
- package/dist/http.d.ts +22 -0
- package/dist/http.js +81 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +5 -0
- package/dist/sse.d.ts +12 -0
- package/dist/sse.js +97 -0
- package/package.json +55 -7
- package/index.js +0 -1
- package/publish.out +0 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# @nylorun/agents
|
|
2
|
+
|
|
3
|
+
## 0.2.0-beta
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 41e613c: Ship the local SDK registry workflow with an independent SQLite Runtime, connected tool executor, authenticated Studio proxy, and a text-and-tool starter. Replace the legacy Hono starter and AG-UI transport. Require Node 24 and include the SDK in exact release compatibility pins.
|
|
8
|
+
|
|
9
|
+
Break the Harness execution import from `/engine` to `/run` and rename hosted execution APIs to durable execution APIs, including RunBinding, BoundRunOptions, and createRunState. Update all consumers without compatibility aliases; retain persisted checkpoint fields and version pins.
|
|
10
|
+
|
|
11
|
+
- 2898d02: Extract shared definitions and contracts into core and local orchestration into
|
|
12
|
+
CLI. Harness becomes execution-only; the SDK no longer installs the engine and
|
|
13
|
+
Runtime no longer depends on the SDK. Author applications through agents and
|
|
14
|
+
install cli for the unchanged nylorun commands. See the package architecture and
|
|
15
|
+
migration guide. Cloud installs published packages from npm independently.
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- Pin core to the tested release.
|
|
20
|
+
- Updated dependencies [2898d02]
|
|
21
|
+
- @nylorun/core@0.1.1-beta
|
|
22
|
+
|
|
23
|
+
## 0.1.0-beta.1
|
|
24
|
+
|
|
25
|
+
Initial session SDK and connected SSE executor.
|
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,60 @@
|
|
|
1
|
+
# @nylorun/agents
|
|
2
|
+
|
|
3
|
+
One application install provides definition authoring, a session client, and a connected customer executor. This beta is currently built locally; no packages were published in this pass. Use the workspace or install packed SDK and core artifacts together until publishing is enabled.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { Agent, createClient, connectAgents, tool } from "@nylorun/agents";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
|
|
9
|
+
const assistant = Agent({
|
|
10
|
+
id: "assistant",
|
|
11
|
+
name: "Assistant",
|
|
12
|
+
instructions: "Use the available tools.",
|
|
13
|
+
tools: [
|
|
14
|
+
tool({
|
|
15
|
+
name: "lookup",
|
|
16
|
+
input: z.object({ id: z.string() }),
|
|
17
|
+
async run({ id }, ctx) {
|
|
18
|
+
return { id, owner: ctx.info };
|
|
19
|
+
},
|
|
20
|
+
}),
|
|
21
|
+
],
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// Run these application operations on your trusted backend.
|
|
25
|
+
const client = createClient({
|
|
26
|
+
url: process.env.NYLORUN_RUNTIME_URL,
|
|
27
|
+
key: process.env.NYLORUN_SERVER_KEY,
|
|
28
|
+
});
|
|
29
|
+
await client.saveAgent(assistant, { implementationVersion: "app-1" });
|
|
30
|
+
const session = await client.createSession({
|
|
31
|
+
agentId: assistant.id,
|
|
32
|
+
ownerUserId: authenticatedUser.id,
|
|
33
|
+
});
|
|
34
|
+
await session.input("Look up item 123", { idempotencyKey: requestId });
|
|
35
|
+
const history = await session.history();
|
|
36
|
+
|
|
37
|
+
// Customer executor process: credential is separately scoped by the Runtime.
|
|
38
|
+
const connection = connectAgents({
|
|
39
|
+
agents: [assistant],
|
|
40
|
+
implementationVersion: "app-1",
|
|
41
|
+
runtime: {
|
|
42
|
+
url: process.env.NYLORUN_RUNTIME_URL,
|
|
43
|
+
key: process.env.NYLORUN_EXECUTOR_KEY,
|
|
44
|
+
},
|
|
45
|
+
onError: console.error,
|
|
46
|
+
});
|
|
47
|
+
await connection.ready;
|
|
48
|
+
// On shutdown:
|
|
49
|
+
await connection.close();
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Use `session.observe({ cursor, signal })` for resumable canonical events, `session.inspect()` for waiting/uncertain state, and `approve`, `respond`, or `cancel` with an explicit stable idempotency key. Retry the same semantic command with the same key. `ownerUserId` must come from trusted server authentication. Application credentials are not browser credentials; browser applications need an authorized backend. Definition authoring is browser-bundleable.
|
|
53
|
+
|
|
54
|
+
The Runtime destination is explicit, or defaults from `NYLORUN_RUNTIME_URL`. Application and executor keys default from `NYLORUN_SERVER_KEY` and `NYLORUN_EXECUTOR_KEY`. Implementation version defaults from `NYLORUN_IMPLEMENTATION_VERSION`, then `dev`. A host must provision executor scope for the exact agent ID, manifest hash and implementation version. Model selection and model credentials belong to the Runtime.
|
|
55
|
+
|
|
56
|
+
`connectAgents({ agents })` opens authenticated fetch SSE before discovering actions, rediscovers after reconnection, and claims only matching definitions. It renews leases while executing, then retries HTTP result delivery with the same recorded outcome and idempotency key. Reconnect delay is bounded at 30 seconds. Notifications confer no execution authority. There is no periodic action-discovery polling. Close aborts the stream, HTTP requests and lease timers and signals running functions; JavaScript cannot forcibly terminate a function that ignores its signal. The host makes expired in-flight actions uncertain instead of automatically repeating external effects.
|
|
57
|
+
|
|
58
|
+
Tools receive state, info, identity, resume, signal, approval/response helpers and memoized `step`. Step outcomes survive a persisted wait result; they do not establish exactly-once external effects after an unacknowledged crash. `sleep` and `waitFor` currently return inspectable deferred outcomes; automatic timer/event wakeups remain runtime implementation work. Remote `onModelCall` convenience and progress-event transport are not supplied in this pass. Arbitrary middleware closures are rejected for durable definitions; use before/after hooks. Agent definitions have no `.run()`; explicit local execution is available through `@nylorun/harness/run`.
|
|
59
|
+
|
|
60
|
+
The SDK depends only on core within the Nylorun packages; installing it does not install harness. Use `/define`, `/client`, or `/executor` for focused imports, or the root for convenience. Studio uses `/client`. See [the adopted host contract](../harness/HOST_CONTRACT.md) and the repository handoff for the verification boundary.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { AgentManifest, BuiltAgent, JsonValue } from "@nylorun/core/define";
|
|
2
|
+
import { type SessionCommand } from "@nylorun/core/contracts";
|
|
3
|
+
import { Transport, type Destination } from "./http.js";
|
|
4
|
+
export interface AgentSource {
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly manifest: AgentManifest;
|
|
7
|
+
readonly hash: string;
|
|
8
|
+
build?(): BuiltAgent;
|
|
9
|
+
}
|
|
10
|
+
export interface SessionView {
|
|
11
|
+
id: string;
|
|
12
|
+
agentId: string;
|
|
13
|
+
ownerUserId: string;
|
|
14
|
+
status: string;
|
|
15
|
+
activeTurnId: string | null;
|
|
16
|
+
[key: string]: unknown;
|
|
17
|
+
}
|
|
18
|
+
export declare class AgentsClient {
|
|
19
|
+
readonly transport: Transport;
|
|
20
|
+
constructor(destination?: Destination);
|
|
21
|
+
listAgents(options?: {
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
}): Promise<{
|
|
24
|
+
agents: {
|
|
25
|
+
manifest: AgentManifest;
|
|
26
|
+
}[];
|
|
27
|
+
}>;
|
|
28
|
+
listSessions(options?: {
|
|
29
|
+
agentId?: string;
|
|
30
|
+
signal?: AbortSignal;
|
|
31
|
+
}): Promise<{
|
|
32
|
+
sessions: SessionView[];
|
|
33
|
+
}>;
|
|
34
|
+
saveAgent(agent: AgentSource, options: {
|
|
35
|
+
implementationVersion: string;
|
|
36
|
+
requestId?: string;
|
|
37
|
+
}): Promise<unknown>;
|
|
38
|
+
createSession(options: {
|
|
39
|
+
id?: string;
|
|
40
|
+
agentId: string;
|
|
41
|
+
ownerUserId: string;
|
|
42
|
+
info?: Record<string, unknown>;
|
|
43
|
+
requestId?: string;
|
|
44
|
+
}): Promise<SessionClient>;
|
|
45
|
+
session(sessionId: string): SessionClient;
|
|
46
|
+
}
|
|
47
|
+
export type CommandOptions = {
|
|
48
|
+
idempotencyKey: string;
|
|
49
|
+
requestId?: string;
|
|
50
|
+
signal?: AbortSignal;
|
|
51
|
+
};
|
|
52
|
+
export declare class SessionClient {
|
|
53
|
+
private readonly transport;
|
|
54
|
+
readonly id: string;
|
|
55
|
+
constructor(transport: Transport, id: string);
|
|
56
|
+
private get path();
|
|
57
|
+
inspect(signal?: AbortSignal): Promise<SessionView>;
|
|
58
|
+
command(command: SessionCommand, signal?: AbortSignal): Promise<{
|
|
59
|
+
status: "accepted";
|
|
60
|
+
turnId: string | null;
|
|
61
|
+
cursor: string | null;
|
|
62
|
+
requestId: string;
|
|
63
|
+
}>;
|
|
64
|
+
input(content: string, options: CommandOptions): Promise<{
|
|
65
|
+
status: "accepted";
|
|
66
|
+
turnId: string | null;
|
|
67
|
+
cursor: string | null;
|
|
68
|
+
requestId: string;
|
|
69
|
+
}>;
|
|
70
|
+
approve(interactionId: string, approved: boolean, options: CommandOptions): Promise<{
|
|
71
|
+
status: "accepted";
|
|
72
|
+
turnId: string | null;
|
|
73
|
+
cursor: string | null;
|
|
74
|
+
requestId: string;
|
|
75
|
+
}>;
|
|
76
|
+
respond(interactionId: string, value: JsonValue, options: CommandOptions): Promise<{
|
|
77
|
+
status: "accepted";
|
|
78
|
+
turnId: string | null;
|
|
79
|
+
cursor: string | null;
|
|
80
|
+
requestId: string;
|
|
81
|
+
}>;
|
|
82
|
+
cancel(options: CommandOptions & {
|
|
83
|
+
reason?: string;
|
|
84
|
+
}): Promise<{
|
|
85
|
+
status: "accepted";
|
|
86
|
+
turnId: string | null;
|
|
87
|
+
cursor: string | null;
|
|
88
|
+
requestId: string;
|
|
89
|
+
}>;
|
|
90
|
+
history(options?: {
|
|
91
|
+
cursor?: string;
|
|
92
|
+
signal?: AbortSignal;
|
|
93
|
+
}): Promise<{
|
|
94
|
+
items: {
|
|
95
|
+
eventId: string;
|
|
96
|
+
sessionId: string;
|
|
97
|
+
turnId: string | null;
|
|
98
|
+
cursor: string;
|
|
99
|
+
createdAt: string;
|
|
100
|
+
type: string;
|
|
101
|
+
payload: unknown;
|
|
102
|
+
}[];
|
|
103
|
+
cursor: string | null;
|
|
104
|
+
}>;
|
|
105
|
+
observe(options?: {
|
|
106
|
+
cursor?: string;
|
|
107
|
+
signal?: AbortSignal;
|
|
108
|
+
}): AsyncGenerator<{
|
|
109
|
+
eventId: string;
|
|
110
|
+
sessionId: string;
|
|
111
|
+
turnId: string | null;
|
|
112
|
+
cursor: string;
|
|
113
|
+
createdAt: string;
|
|
114
|
+
type: string;
|
|
115
|
+
payload: unknown;
|
|
116
|
+
}, void, unknown>;
|
|
117
|
+
}
|
|
118
|
+
export declare function createClient(destination?: Destination): AgentsClient;
|
|
119
|
+
export { RuntimeError } from "./http.js";
|
|
120
|
+
export type { Destination } from "./http.js";
|
|
121
|
+
export type { LiveEvent } from "@nylorun/core/contracts";
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { LiveEventSchema, SessionItemsResponseSchema, } from "@nylorun/core/contracts";
|
|
2
|
+
import { Transport, id, segment } from "./http.js";
|
|
3
|
+
import { observeSSE } from "./sse.js";
|
|
4
|
+
export class AgentsClient {
|
|
5
|
+
transport;
|
|
6
|
+
constructor(destination = {}) {
|
|
7
|
+
this.transport = new Transport(destination);
|
|
8
|
+
}
|
|
9
|
+
listAgents(options = {}) {
|
|
10
|
+
return this.transport.json("/v1/agents", "GET", undefined, options.signal);
|
|
11
|
+
}
|
|
12
|
+
listSessions(options = {}) {
|
|
13
|
+
const query = options.agentId
|
|
14
|
+
? `?agentId=${encodeURIComponent(options.agentId)}`
|
|
15
|
+
: "";
|
|
16
|
+
return this.transport.json(`/v1/sessions${query}`, "GET", undefined, options.signal);
|
|
17
|
+
}
|
|
18
|
+
saveAgent(agent, options) {
|
|
19
|
+
return this.transport.json(`/v1/agents/${segment(agent.id)}`, "PUT", {
|
|
20
|
+
requestId: options.requestId ?? id(),
|
|
21
|
+
manifest: agent.manifest,
|
|
22
|
+
implementationVersion: options.implementationVersion,
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
async createSession(options) {
|
|
26
|
+
const sessionId = options.id ?? id();
|
|
27
|
+
await this.transport.json(`/v1/sessions/${segment(sessionId)}`, "PUT", {
|
|
28
|
+
requestId: options.requestId ?? id(),
|
|
29
|
+
agentId: options.agentId,
|
|
30
|
+
ownerUserId: options.ownerUserId,
|
|
31
|
+
...(options.info ? { info: options.info } : {}),
|
|
32
|
+
});
|
|
33
|
+
return this.session(sessionId);
|
|
34
|
+
}
|
|
35
|
+
session(sessionId) {
|
|
36
|
+
return new SessionClient(this.transport, sessionId);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export class SessionClient {
|
|
40
|
+
transport;
|
|
41
|
+
id;
|
|
42
|
+
constructor(transport, id) {
|
|
43
|
+
this.transport = transport;
|
|
44
|
+
this.id = id;
|
|
45
|
+
}
|
|
46
|
+
get path() {
|
|
47
|
+
return `/v1/sessions/${segment(this.id)}`;
|
|
48
|
+
}
|
|
49
|
+
inspect(signal) {
|
|
50
|
+
return this.transport.json(this.path, "GET", undefined, signal);
|
|
51
|
+
}
|
|
52
|
+
command(command, signal) {
|
|
53
|
+
return this.transport.json(`${this.path}/commands`, "POST", command, signal);
|
|
54
|
+
}
|
|
55
|
+
input(content, options) {
|
|
56
|
+
return this.command({
|
|
57
|
+
type: "message",
|
|
58
|
+
content,
|
|
59
|
+
requestId: options.requestId ?? id(),
|
|
60
|
+
idempotencyKey: options.idempotencyKey,
|
|
61
|
+
}, options.signal);
|
|
62
|
+
}
|
|
63
|
+
approve(interactionId, approved, options) {
|
|
64
|
+
return this.command({
|
|
65
|
+
type: "approve",
|
|
66
|
+
interactionId,
|
|
67
|
+
approved,
|
|
68
|
+
requestId: options.requestId ?? id(),
|
|
69
|
+
idempotencyKey: options.idempotencyKey,
|
|
70
|
+
}, options.signal);
|
|
71
|
+
}
|
|
72
|
+
respond(interactionId, value, options) {
|
|
73
|
+
return this.command({
|
|
74
|
+
type: "respond",
|
|
75
|
+
interactionId,
|
|
76
|
+
value,
|
|
77
|
+
requestId: options.requestId ?? id(),
|
|
78
|
+
idempotencyKey: options.idempotencyKey,
|
|
79
|
+
}, options.signal);
|
|
80
|
+
}
|
|
81
|
+
cancel(options) {
|
|
82
|
+
return this.command({
|
|
83
|
+
type: "cancel",
|
|
84
|
+
requestId: options.requestId ?? id(),
|
|
85
|
+
idempotencyKey: options.idempotencyKey,
|
|
86
|
+
...(options.reason ? { reason: options.reason } : {}),
|
|
87
|
+
}, options.signal);
|
|
88
|
+
}
|
|
89
|
+
async history(options = {}) {
|
|
90
|
+
return SessionItemsResponseSchema.parse(await this.transport.json(`${this.path}/items${options.cursor ? `?cursor=${encodeURIComponent(options.cursor)}` : ""}`, "GET", undefined, options.signal));
|
|
91
|
+
}
|
|
92
|
+
async *observe(options = {}) {
|
|
93
|
+
for await (const frame of observeSSE(this.transport, `${this.path}/events`, options)) {
|
|
94
|
+
if (frame.event === "heartbeat" || frame.event === "ready")
|
|
95
|
+
continue;
|
|
96
|
+
yield LiveEventSchema.parse(JSON.parse(frame.data));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
export function createClient(destination = {}) {
|
|
101
|
+
return new AgentsClient(destination);
|
|
102
|
+
}
|
|
103
|
+
export { RuntimeError } from "./http.js";
|
package/dist/define.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@nylorun/core/define";
|
package/dist/define.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@nylorun/core/define";
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type BuiltAgent } from "@nylorun/core/define";
|
|
2
|
+
import type { Action, ActionOutcome } from "@nylorun/core/contracts";
|
|
3
|
+
/** Executes code only after a host-issued claim. No engine dependency. */
|
|
4
|
+
export declare function executeAction(action: Action, agent: BuiltAgent, signal: AbortSignal): Promise<ActionOutcome>;
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { implementationsFor, isToolError, normalizeToolDefinition, normalizedSchemasFor, } from "@nylorun/core/define";
|
|
2
|
+
class Suspend {
|
|
3
|
+
outcome;
|
|
4
|
+
constructor(outcome) {
|
|
5
|
+
this.outcome = outcome;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
|
|
9
|
+
? value
|
|
10
|
+
: {};
|
|
11
|
+
/** Executes code only after a host-issued claim. No engine dependency. */
|
|
12
|
+
export async function executeAction(action, agent, signal) {
|
|
13
|
+
const impl = implementationsFor(agent)[action.capabilityId];
|
|
14
|
+
if (!impl)
|
|
15
|
+
throw new Error(`No capability ${action.capabilityId}`);
|
|
16
|
+
if (action.kind === "beforeModelCall") {
|
|
17
|
+
if (!impl.beforeModelCall)
|
|
18
|
+
throw new Error("Missing beforeModelCall implementation");
|
|
19
|
+
try {
|
|
20
|
+
return { value: (await impl.beforeModelCall(action.input)) ?? {} };
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
return { value: { block: message(error) } };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (action.kind === "afterModelCall") {
|
|
27
|
+
if (!impl.afterModelCall)
|
|
28
|
+
throw new Error("Missing afterModelCall implementation");
|
|
29
|
+
try {
|
|
30
|
+
return {
|
|
31
|
+
value: (await impl.afterModelCall(action.input, action.context)) ?? {},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
return { value: { block: message(error) } };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const raw = impl.tools?.[action.toolName ?? ""];
|
|
39
|
+
if (!raw)
|
|
40
|
+
throw new Error("Missing tool implementation");
|
|
41
|
+
const tool = normalizeToolDefinition(raw);
|
|
42
|
+
const schemas = normalizedSchemasFor(tool);
|
|
43
|
+
const input = schemas.inputSchema.validate(action.input);
|
|
44
|
+
if (!input.ok)
|
|
45
|
+
return {
|
|
46
|
+
value: {
|
|
47
|
+
kind: "failed",
|
|
48
|
+
code: "tool.invalid-input",
|
|
49
|
+
message: JSON.stringify(input.issues),
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
const ctx = action.context;
|
|
53
|
+
const state = { ...object(ctx.state) };
|
|
54
|
+
const statePatch = {};
|
|
55
|
+
const resume = object(ctx.resume);
|
|
56
|
+
const token = object(resume.token);
|
|
57
|
+
const memo = object(token._nylorun);
|
|
58
|
+
const steps = { ...object(memo.steps) };
|
|
59
|
+
const answers = { ...object(memo.answers) };
|
|
60
|
+
let waitIndex = 0;
|
|
61
|
+
let gateApproved = Boolean(memo.gateApproved) ||
|
|
62
|
+
Boolean(memo.approvalGate && resume.kind === "approval" && resume.approved);
|
|
63
|
+
const durableToken = (extra = {}) => ({
|
|
64
|
+
_nylorun: { steps, answers, waitIndex, gateApproved, ...extra },
|
|
65
|
+
});
|
|
66
|
+
const wait = async (kind, prompt, metadata) => {
|
|
67
|
+
const index = String(waitIndex++);
|
|
68
|
+
if (index in answers)
|
|
69
|
+
return answers[index];
|
|
70
|
+
if (!memo.approvalGate &&
|
|
71
|
+
resume.kind === kind &&
|
|
72
|
+
Number(memo.waitIndex ?? 0) === Number(index)) {
|
|
73
|
+
const answer = kind === "approval" ? Boolean(resume.approved) : resume.value;
|
|
74
|
+
answers[index] = answer;
|
|
75
|
+
return answer;
|
|
76
|
+
}
|
|
77
|
+
throw new Suspend({
|
|
78
|
+
kind: "interaction-required",
|
|
79
|
+
interaction: { kind, prompt, ...(metadata ? { metadata } : {}) },
|
|
80
|
+
token: {
|
|
81
|
+
_nylorun: { steps, answers, waitIndex: Number(index), gateApproved },
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
};
|
|
85
|
+
const context = {
|
|
86
|
+
executionId: String(ctx.executionId ?? action.sessionId),
|
|
87
|
+
turnId: String(ctx.turnId ?? action.turnId),
|
|
88
|
+
stepId: String(ctx.stepId ?? ""),
|
|
89
|
+
callId: String(ctx.callId ?? action.actionId),
|
|
90
|
+
invocationId: String(ctx.invocationId ?? action.actionId),
|
|
91
|
+
idempotencyKey: String(ctx.idempotencyKey ?? action.actionId),
|
|
92
|
+
signal,
|
|
93
|
+
info: ctx.info,
|
|
94
|
+
session: { id: action.sessionId },
|
|
95
|
+
...(ctx.resume ? { resume: ctx.resume } : {}),
|
|
96
|
+
state: {
|
|
97
|
+
get: (key) => state[key],
|
|
98
|
+
set: (key, value) => {
|
|
99
|
+
state[key] = value;
|
|
100
|
+
statePatch[key] = value;
|
|
101
|
+
},
|
|
102
|
+
entries: () => ({ ...state }),
|
|
103
|
+
},
|
|
104
|
+
progress() {
|
|
105
|
+
/* Canonical events are host-owned; progress transport is deferred. */
|
|
106
|
+
},
|
|
107
|
+
ask: (prompt, options) => wait("response", prompt, options),
|
|
108
|
+
approve: (prompt) => wait("approval", prompt),
|
|
109
|
+
sleep: async (duration) => {
|
|
110
|
+
throw new Suspend({
|
|
111
|
+
kind: "deferred",
|
|
112
|
+
token: durableToken({ wait: { kind: "sleep", duration } }),
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
waitFor: async (event, options) => {
|
|
116
|
+
throw new Suspend({
|
|
117
|
+
kind: "deferred",
|
|
118
|
+
token: durableToken({ wait: { kind: "waitFor", event, ...options } }),
|
|
119
|
+
});
|
|
120
|
+
},
|
|
121
|
+
step: async (name, fn) => {
|
|
122
|
+
if (Object.prototype.hasOwnProperty.call(steps, name))
|
|
123
|
+
return steps[name];
|
|
124
|
+
signal.throwIfAborted();
|
|
125
|
+
const value = await fn();
|
|
126
|
+
// Memoized values are durable only with a persisted action outcome. Interrupted actions stay uncertain.
|
|
127
|
+
steps[name] = JSON.parse(JSON.stringify(value ?? null));
|
|
128
|
+
return value;
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
try {
|
|
132
|
+
signal.throwIfAborted();
|
|
133
|
+
if (tool.approval && !gateApproved) {
|
|
134
|
+
const approval = await tool.approval(input.value);
|
|
135
|
+
if (approval)
|
|
136
|
+
throw new Suspend({
|
|
137
|
+
kind: "interaction-required",
|
|
138
|
+
interaction: {
|
|
139
|
+
kind: "approval",
|
|
140
|
+
prompt: typeof approval === "string" ? approval : `Approve ${tool.name}?`,
|
|
141
|
+
},
|
|
142
|
+
token: durableToken({ approvalGate: true }),
|
|
143
|
+
});
|
|
144
|
+
gateApproved = true;
|
|
145
|
+
}
|
|
146
|
+
if (resume.kind === "approval" && resume.approved === false)
|
|
147
|
+
return { value: { kind: "denied", reason: "Approval denied" } };
|
|
148
|
+
const value = await tool.execute(input.value, context);
|
|
149
|
+
const tagged = object(value);
|
|
150
|
+
let outcome;
|
|
151
|
+
if ([
|
|
152
|
+
"completed",
|
|
153
|
+
"failed",
|
|
154
|
+
"denied",
|
|
155
|
+
"interaction-required",
|
|
156
|
+
"deferred",
|
|
157
|
+
].includes(tagged.kind))
|
|
158
|
+
outcome = value;
|
|
159
|
+
else
|
|
160
|
+
outcome = { kind: "completed", output: value ?? null };
|
|
161
|
+
if (outcome.kind === "completed" && schemas.outputSchema) {
|
|
162
|
+
const parsed = schemas.outputSchema.validate(outcome.output);
|
|
163
|
+
outcome = parsed.ok
|
|
164
|
+
? { ...outcome, output: parsed.value }
|
|
165
|
+
: {
|
|
166
|
+
kind: "failed",
|
|
167
|
+
code: "tool.invalid-output",
|
|
168
|
+
message: JSON.stringify(parsed.issues),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
return { value: outcome, statePatch };
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
if (signal.aborted)
|
|
175
|
+
throw signal.reason;
|
|
176
|
+
return {
|
|
177
|
+
value: error instanceof Suspend
|
|
178
|
+
? error.outcome
|
|
179
|
+
: {
|
|
180
|
+
kind: "failed",
|
|
181
|
+
code: isToolError(error) ? error.code : "tool.execution-failed",
|
|
182
|
+
message: message(error),
|
|
183
|
+
},
|
|
184
|
+
statePatch,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function message(error) {
|
|
189
|
+
return error instanceof Error ? error.message : String(error);
|
|
190
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { AgentSource } from "./client.js";
|
|
2
|
+
import { type Destination } from "./http.js";
|
|
3
|
+
export interface ConnectOptions {
|
|
4
|
+
agents: readonly AgentSource[];
|
|
5
|
+
runtime?: Destination;
|
|
6
|
+
implementationVersion?: string;
|
|
7
|
+
onError?: (error: unknown) => void;
|
|
8
|
+
}
|
|
9
|
+
export interface AgentConnection {
|
|
10
|
+
/** Settles after authenticated SSE is established and initial discovery succeeds. */
|
|
11
|
+
readonly ready: Promise<void>;
|
|
12
|
+
/** Abort subscriptions and leases. Running user code receives an AbortSignal. */
|
|
13
|
+
close(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export declare function connectAgents(options: ConnectOptions): AgentConnection;
|
package/dist/executor.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { AgentManifestSchema, ActionSchema, ActionClaimResponseSchema, } from "@nylorun/core/contracts";
|
|
2
|
+
import { Transport, RuntimeError, delay, env, id, segment, } from "./http.js";
|
|
3
|
+
import { readSSE } from "./sse.js";
|
|
4
|
+
import { executeAction } from "./execute-action.js";
|
|
5
|
+
export function connectAgents(options) {
|
|
6
|
+
const transport = new Transport(options.runtime, "executor");
|
|
7
|
+
const version = options.implementationVersion ??
|
|
8
|
+
env("NYLORUN_IMPLEMENTATION_VERSION") ??
|
|
9
|
+
"dev";
|
|
10
|
+
const agents = new Map();
|
|
11
|
+
for (const source of options.agents) {
|
|
12
|
+
const built = source.build?.() ?? source;
|
|
13
|
+
AgentManifestSchema.parse(built.manifest);
|
|
14
|
+
if (agents.has(built.id))
|
|
15
|
+
throw new Error(`Duplicate connected agent ${built.id}`);
|
|
16
|
+
agents.set(built.id, built);
|
|
17
|
+
}
|
|
18
|
+
if (!agents.size)
|
|
19
|
+
throw new Error("connectAgents requires at least one agent");
|
|
20
|
+
const controller = new AbortController();
|
|
21
|
+
const signal = controller.signal;
|
|
22
|
+
const active = new Map();
|
|
23
|
+
let resolveReady;
|
|
24
|
+
let rejectReady;
|
|
25
|
+
const ready = new Promise((resolve, reject) => {
|
|
26
|
+
resolveReady = resolve;
|
|
27
|
+
rejectReady = reject;
|
|
28
|
+
});
|
|
29
|
+
// Avoid an unhandled rejection for callers that immediately close the handle.
|
|
30
|
+
void ready.catch(() => { });
|
|
31
|
+
const report = (error) => {
|
|
32
|
+
try {
|
|
33
|
+
options.onError?.(error);
|
|
34
|
+
}
|
|
35
|
+
catch { }
|
|
36
|
+
};
|
|
37
|
+
let discovering = false, dirty = false;
|
|
38
|
+
const discover = async () => {
|
|
39
|
+
dirty = true;
|
|
40
|
+
if (discovering)
|
|
41
|
+
return;
|
|
42
|
+
discovering = true;
|
|
43
|
+
try {
|
|
44
|
+
while (dirty && !signal.aborted) {
|
|
45
|
+
dirty = false;
|
|
46
|
+
const response = await transport.json("/v1/actions", "GET", undefined, signal);
|
|
47
|
+
for (const item of response.actions) {
|
|
48
|
+
const action = ActionSchema.parse(item);
|
|
49
|
+
const agent = agents.get(action.agentId);
|
|
50
|
+
if (!agent ||
|
|
51
|
+
agent.hash !== action.manifestHash ||
|
|
52
|
+
action.implementationVersion !== version ||
|
|
53
|
+
action.status !== "pending" ||
|
|
54
|
+
active.has(action.actionId))
|
|
55
|
+
continue;
|
|
56
|
+
const work = new AbortController();
|
|
57
|
+
active.set(action.actionId, work);
|
|
58
|
+
let delivered = false;
|
|
59
|
+
void processAction(action, agent, work)
|
|
60
|
+
.then(() => {
|
|
61
|
+
delivered = true;
|
|
62
|
+
})
|
|
63
|
+
.catch((error) => {
|
|
64
|
+
if (!signal.aborted)
|
|
65
|
+
report(error);
|
|
66
|
+
})
|
|
67
|
+
.finally(() => {
|
|
68
|
+
active.delete(action.actionId);
|
|
69
|
+
// Completion-driven discovery drains bounded server pages without periodic polling.
|
|
70
|
+
if (delivered && !signal.aborted)
|
|
71
|
+
void discover().catch(report);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
discovering = false;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
const processAction = async (action, agent, work) => {
|
|
81
|
+
const stop = () => work.abort(signal.reason);
|
|
82
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
83
|
+
let renewal;
|
|
84
|
+
let renewing = true;
|
|
85
|
+
let wakeRenewal;
|
|
86
|
+
try {
|
|
87
|
+
const claim = ActionClaimResponseSchema.parse(await transport.json(`/v1/actions/${segment(action.actionId)}/claim`, "POST", {
|
|
88
|
+
requestId: id(),
|
|
89
|
+
manifestHash: agent.hash,
|
|
90
|
+
implementationVersion: version,
|
|
91
|
+
}, work.signal));
|
|
92
|
+
if (claim.action.actionId !== action.actionId ||
|
|
93
|
+
claim.action.manifestHash !== agent.hash ||
|
|
94
|
+
claim.action.implementationVersion !== version)
|
|
95
|
+
throw new Error("Claim definition mismatch");
|
|
96
|
+
let expires = Date.parse(claim.leaseExpiresAt);
|
|
97
|
+
renewal = (async () => {
|
|
98
|
+
while (renewing && !work.signal.aborted) {
|
|
99
|
+
const remaining = expires - Date.now();
|
|
100
|
+
if (!Number.isFinite(remaining) || remaining <= 0)
|
|
101
|
+
throw new Error("Executor lease expired");
|
|
102
|
+
await new Promise((resolve) => {
|
|
103
|
+
const finish = () => {
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
work.signal.removeEventListener("abort", finish);
|
|
106
|
+
resolve();
|
|
107
|
+
};
|
|
108
|
+
const timer = setTimeout(finish, Math.max(50, Math.floor(remaining / 3)));
|
|
109
|
+
wakeRenewal = finish;
|
|
110
|
+
work.signal.addEventListener("abort", finish, { once: true });
|
|
111
|
+
});
|
|
112
|
+
if (!renewing || work.signal.aborted)
|
|
113
|
+
return;
|
|
114
|
+
const renewed = await transport.json(`/v1/actions/${segment(action.actionId)}/heartbeat`, "POST", {
|
|
115
|
+
requestId: id(),
|
|
116
|
+
claimId: claim.claimId,
|
|
117
|
+
generation: claim.generation,
|
|
118
|
+
}, work.signal);
|
|
119
|
+
expires = Date.parse(renewed.leaseExpiresAt);
|
|
120
|
+
}
|
|
121
|
+
})().catch((error) => {
|
|
122
|
+
if (renewing && !work.signal.aborted) {
|
|
123
|
+
work.abort(error);
|
|
124
|
+
report(error);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
const outcome = await executeAction(claim.action, agent, work.signal);
|
|
128
|
+
work.signal.throwIfAborted();
|
|
129
|
+
const command = {
|
|
130
|
+
type: "action_result",
|
|
131
|
+
requestId: id(),
|
|
132
|
+
idempotencyKey: `action:${action.actionId}:${claim.generation}`,
|
|
133
|
+
actionId: action.actionId,
|
|
134
|
+
claimId: claim.claimId,
|
|
135
|
+
generation: claim.generation,
|
|
136
|
+
outcome,
|
|
137
|
+
};
|
|
138
|
+
// Retrying delivery never re-invokes the tool/hook. Lost acknowledgements use the same receipt key.
|
|
139
|
+
for (let attempt = 0;; attempt++) {
|
|
140
|
+
try {
|
|
141
|
+
await transport.json(`/v1/sessions/${segment(action.sessionId)}/commands`, "POST", command, work.signal);
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (work.signal.aborted ||
|
|
146
|
+
attempt >= 4 ||
|
|
147
|
+
(error instanceof RuntimeError &&
|
|
148
|
+
error.status < 500 &&
|
|
149
|
+
![408, 429].includes(error.status)))
|
|
150
|
+
throw error;
|
|
151
|
+
await delay(Math.min(4000, 250 * 2 ** attempt), work.signal);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
renewing = false;
|
|
157
|
+
wakeRenewal?.();
|
|
158
|
+
await renewal;
|
|
159
|
+
signal.removeEventListener("abort", stop);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
const loop = (async () => {
|
|
163
|
+
let retry = 250;
|
|
164
|
+
while (!signal.aborted) {
|
|
165
|
+
const subscription = new AbortController();
|
|
166
|
+
const stop = () => subscription.abort(signal.reason);
|
|
167
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
168
|
+
try {
|
|
169
|
+
const response = await transport.request("/v1/executors/connect", {
|
|
170
|
+
signal: subscription.signal,
|
|
171
|
+
headers: { Accept: "text/event-stream" },
|
|
172
|
+
});
|
|
173
|
+
if (!response.headers.get("content-type")?.includes("text/event-stream"))
|
|
174
|
+
throw new Error("Executor endpoint did not return SSE");
|
|
175
|
+
// Subscription exists before initial discovery; notifications can safely accumulate in its stream.
|
|
176
|
+
await discover();
|
|
177
|
+
resolveReady();
|
|
178
|
+
for await (const frame of readSSE(response, subscription.signal)) {
|
|
179
|
+
retry = 250;
|
|
180
|
+
if (frame.event === "work_available" ||
|
|
181
|
+
(frame.data && JSON.parse(frame.data).type === "work_available"))
|
|
182
|
+
await discover();
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (signal.aborted)
|
|
187
|
+
break;
|
|
188
|
+
report(error);
|
|
189
|
+
if (error instanceof RuntimeError &&
|
|
190
|
+
[400, 401, 403, 404].includes(error.status)) {
|
|
191
|
+
rejectReady(error);
|
|
192
|
+
controller.abort(error);
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
subscription.abort();
|
|
198
|
+
signal.removeEventListener("abort", stop);
|
|
199
|
+
}
|
|
200
|
+
if (!signal.aborted)
|
|
201
|
+
await delay(retry, signal).catch(() => { });
|
|
202
|
+
retry = Math.min(30000, retry * 2);
|
|
203
|
+
}
|
|
204
|
+
rejectReady(signal.reason ?? new Error("Executor connection closed"));
|
|
205
|
+
})();
|
|
206
|
+
return {
|
|
207
|
+
ready,
|
|
208
|
+
async close() {
|
|
209
|
+
controller.abort(new Error("Executor connection closed"));
|
|
210
|
+
for (const work of active.values())
|
|
211
|
+
work.abort(signal.reason);
|
|
212
|
+
await loop;
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface Destination {
|
|
2
|
+
url?: string;
|
|
3
|
+
key?: string;
|
|
4
|
+
fetch?: typeof fetch;
|
|
5
|
+
}
|
|
6
|
+
export declare function env(name: string): string | undefined;
|
|
7
|
+
export declare class RuntimeError extends Error {
|
|
8
|
+
readonly status: number;
|
|
9
|
+
readonly body: unknown;
|
|
10
|
+
constructor(status: number, body: unknown);
|
|
11
|
+
}
|
|
12
|
+
export declare class Transport {
|
|
13
|
+
readonly url: string;
|
|
14
|
+
readonly key: string;
|
|
15
|
+
readonly fetcher: typeof fetch;
|
|
16
|
+
constructor(options?: Destination, role?: "server" | "executor");
|
|
17
|
+
request(path: string, init?: RequestInit): Promise<Response>;
|
|
18
|
+
json<T>(path: string, method?: string, body?: unknown, signal?: AbortSignal): Promise<T>;
|
|
19
|
+
}
|
|
20
|
+
export declare const id: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
21
|
+
export declare const segment: (value: string) => string;
|
|
22
|
+
export declare function delay(ms: number, signal: AbortSignal): Promise<void>;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export function env(name) {
|
|
2
|
+
return typeof process !== "undefined" ? process.env[name] : undefined;
|
|
3
|
+
}
|
|
4
|
+
export class RuntimeError extends Error {
|
|
5
|
+
status;
|
|
6
|
+
body;
|
|
7
|
+
constructor(status, body) {
|
|
8
|
+
super(`Runtime HTTP ${status}: ${JSON.stringify(body)}`);
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.body = body;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export class Transport {
|
|
14
|
+
url;
|
|
15
|
+
key;
|
|
16
|
+
fetcher;
|
|
17
|
+
constructor(options = {}, role = "server") {
|
|
18
|
+
const url = options.url ?? env("NYLORUN_RUNTIME_URL");
|
|
19
|
+
const key = options.key ??
|
|
20
|
+
env(role === "server" ? "NYLORUN_SERVER_KEY" : "NYLORUN_EXECUTOR_KEY");
|
|
21
|
+
if (!url || !key)
|
|
22
|
+
throw new Error(`Set Runtime url and ${role} key explicitly or via NYLORUN_RUNTIME_URL / NYLORUN_${role.toUpperCase()}_KEY`);
|
|
23
|
+
const parsed = new URL(url);
|
|
24
|
+
if (!["http:", "https:"].includes(parsed.protocol))
|
|
25
|
+
throw new Error("Runtime requires an HTTP(S) URL");
|
|
26
|
+
this.url = url.replace(/\/$/, "");
|
|
27
|
+
this.key = key;
|
|
28
|
+
this.fetcher = options.fetch ?? globalThis.fetch;
|
|
29
|
+
}
|
|
30
|
+
async request(path, init = {}) {
|
|
31
|
+
const headers = new Headers(init.headers);
|
|
32
|
+
headers.set("Authorization", `Bearer ${this.key}`);
|
|
33
|
+
if (init.body)
|
|
34
|
+
headers.set("Content-Type", "application/json");
|
|
35
|
+
const response = await this.fetcher(this.url + path, {
|
|
36
|
+
...init,
|
|
37
|
+
headers,
|
|
38
|
+
redirect: "error",
|
|
39
|
+
});
|
|
40
|
+
if (!response.ok) {
|
|
41
|
+
const text = await response.text();
|
|
42
|
+
let body = text;
|
|
43
|
+
try {
|
|
44
|
+
body = JSON.parse(text);
|
|
45
|
+
}
|
|
46
|
+
catch { }
|
|
47
|
+
throw new RuntimeError(response.status, body);
|
|
48
|
+
}
|
|
49
|
+
return response;
|
|
50
|
+
}
|
|
51
|
+
async json(path, method = "GET", body, signal) {
|
|
52
|
+
const response = await this.request(path, {
|
|
53
|
+
method,
|
|
54
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
55
|
+
signal,
|
|
56
|
+
});
|
|
57
|
+
return response.status === 204
|
|
58
|
+
? undefined
|
|
59
|
+
: response.json();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export const id = () => globalThis.crypto.randomUUID();
|
|
63
|
+
export const segment = (value) => encodeURIComponent(value);
|
|
64
|
+
export function delay(ms, signal) {
|
|
65
|
+
return new Promise((resolve, reject) => {
|
|
66
|
+
if (signal.aborted) {
|
|
67
|
+
reject(signal.reason);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const stop = () => {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
signal.removeEventListener("abort", stop);
|
|
73
|
+
reject(signal.reason);
|
|
74
|
+
};
|
|
75
|
+
const timer = setTimeout(() => {
|
|
76
|
+
signal.removeEventListener("abort", stop);
|
|
77
|
+
resolve();
|
|
78
|
+
}, ms);
|
|
79
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
80
|
+
});
|
|
81
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { Agent, AgentBuilder, AgentBuildError, AgentLifecycleError, capability, tool, defineSchema, ToolError, } from "@nylorun/core/define";
|
|
2
|
+
export type { AgentOptions, AgentManifest, BuiltAgent, ToolDefinition, ToolExecutionContext, ToolOutcome, Patch, Decision, JsonValue, JsonObject, } from "@nylorun/core/define";
|
|
3
|
+
export type { LiveEvent, SessionCommand, Action, ActionOutcome, } from "@nylorun/core/contracts";
|
|
4
|
+
export { AgentsClient, SessionClient, createClient } from "./client.js";
|
|
5
|
+
export type { AgentSource, SessionView, CommandOptions } from "./client.js";
|
|
6
|
+
export { connectAgents } from "./executor.js";
|
|
7
|
+
export type { ConnectOptions, AgentConnection } from "./executor.js";
|
|
8
|
+
export { RuntimeError } from "./http.js";
|
|
9
|
+
export type { Destination } from "./http.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// Definition authoring and wire contracts are the only harness runtime imports.
|
|
2
|
+
export { Agent, AgentBuilder, AgentBuildError, AgentLifecycleError, capability, tool, defineSchema, ToolError, } from "@nylorun/core/define";
|
|
3
|
+
export { AgentsClient, SessionClient, createClient } from "./client.js";
|
|
4
|
+
export { connectAgents } from "./executor.js";
|
|
5
|
+
export { RuntimeError } from "./http.js";
|
package/dist/sse.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type Transport } from "./http.js";
|
|
2
|
+
export interface SSEEvent {
|
|
3
|
+
event: string;
|
|
4
|
+
data: string;
|
|
5
|
+
id?: string;
|
|
6
|
+
}
|
|
7
|
+
/** Fetch-based SSE supports Authorization headers and works in browsers and Node. */
|
|
8
|
+
export declare function readSSE(response: Response, signal: AbortSignal): AsyncGenerator<SSEEvent>;
|
|
9
|
+
export declare function observeSSE(transport: Transport, path: string, options?: {
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
cursor?: string;
|
|
12
|
+
}): AsyncGenerator<SSEEvent>;
|
package/dist/sse.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { delay, RuntimeError } from "./http.js";
|
|
2
|
+
/** Fetch-based SSE supports Authorization headers and works in browsers and Node. */
|
|
3
|
+
export async function* readSSE(response, signal) {
|
|
4
|
+
if (!response.headers.get("content-type")?.includes("text/event-stream"))
|
|
5
|
+
throw new Error("Expected an SSE response");
|
|
6
|
+
if (!response.body)
|
|
7
|
+
throw new Error("SSE response has no body");
|
|
8
|
+
const reader = response.body.getReader();
|
|
9
|
+
const decoder = new TextDecoder();
|
|
10
|
+
let buffer = "";
|
|
11
|
+
let event = "message";
|
|
12
|
+
let data = [];
|
|
13
|
+
let lastId;
|
|
14
|
+
const abort = () => {
|
|
15
|
+
void reader.cancel().catch(() => { });
|
|
16
|
+
};
|
|
17
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
18
|
+
try {
|
|
19
|
+
while (!signal.aborted) {
|
|
20
|
+
const result = await reader.read();
|
|
21
|
+
if (result.done)
|
|
22
|
+
break;
|
|
23
|
+
buffer += decoder.decode(result.value, { stream: true });
|
|
24
|
+
if (buffer.length > 2_000_000)
|
|
25
|
+
throw new Error("SSE frame exceeds size limit");
|
|
26
|
+
let index;
|
|
27
|
+
while ((index = buffer.indexOf("\n")) >= 0) {
|
|
28
|
+
const line = buffer.slice(0, index).replace(/\r$/, "");
|
|
29
|
+
buffer = buffer.slice(index + 1);
|
|
30
|
+
if (line === "") {
|
|
31
|
+
if (data.length)
|
|
32
|
+
yield {
|
|
33
|
+
event,
|
|
34
|
+
data: data.join("\n"),
|
|
35
|
+
...(lastId === undefined ? {} : { id: lastId }),
|
|
36
|
+
};
|
|
37
|
+
event = "message";
|
|
38
|
+
data = [];
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (line.startsWith(":"))
|
|
42
|
+
continue;
|
|
43
|
+
const colon = line.indexOf(":");
|
|
44
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
45
|
+
const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
46
|
+
if (field === "event")
|
|
47
|
+
event = value;
|
|
48
|
+
if (field === "data")
|
|
49
|
+
data.push(value);
|
|
50
|
+
if (field === "id" && !value.includes("\0"))
|
|
51
|
+
lastId = value;
|
|
52
|
+
if (data.reduce((n, v) => n + v.length, 0) > 2_000_000)
|
|
53
|
+
throw new Error("SSE event exceeds size limit");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
signal.removeEventListener("abort", abort);
|
|
59
|
+
await reader.cancel().catch(() => { });
|
|
60
|
+
reader.releaseLock();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export async function* observeSSE(transport, path, options = {}) {
|
|
64
|
+
const controller = new AbortController();
|
|
65
|
+
const signal = options.signal ?? controller.signal;
|
|
66
|
+
let cursor = options.cursor;
|
|
67
|
+
let retry = 250;
|
|
68
|
+
while (!signal.aborted) {
|
|
69
|
+
try {
|
|
70
|
+
const response = await transport.request(path, {
|
|
71
|
+
signal,
|
|
72
|
+
headers: {
|
|
73
|
+
Accept: "text/event-stream",
|
|
74
|
+
...(cursor ? { "Last-Event-ID": cursor } : {}),
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
for await (const event of readSSE(response, signal)) {
|
|
78
|
+
retry = 250;
|
|
79
|
+
if (event.id)
|
|
80
|
+
cursor = event.id;
|
|
81
|
+
yield event;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (signal.aborted)
|
|
86
|
+
return;
|
|
87
|
+
if (error instanceof RuntimeError &&
|
|
88
|
+
error.status >= 400 &&
|
|
89
|
+
error.status < 500 &&
|
|
90
|
+
![408, 429].includes(error.status))
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
if (!signal.aborted)
|
|
94
|
+
await delay(retry, signal).catch(() => { });
|
|
95
|
+
retry = Math.min(30000, retry * 2);
|
|
96
|
+
}
|
|
97
|
+
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nylorun/agents",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0-beta",
|
|
4
|
+
"description": "Nylorun agent definitions, session client and connected executor",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist",
|
|
9
|
+
"README.md",
|
|
10
|
+
"LICENSE",
|
|
11
|
+
"CHANGELOG.md"
|
|
12
|
+
],
|
|
13
|
+
"sideEffects": false,
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"import": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./define": {
|
|
20
|
+
"types": "./dist/define.d.ts",
|
|
21
|
+
"import": "./dist/define.js"
|
|
22
|
+
},
|
|
23
|
+
"./client": {
|
|
24
|
+
"types": "./dist/client.d.ts",
|
|
25
|
+
"import": "./dist/client.js"
|
|
26
|
+
},
|
|
27
|
+
"./executor": {
|
|
28
|
+
"types": "./dist/executor.d.ts",
|
|
29
|
+
"import": "./dist/executor.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
6
32
|
"scripts": {
|
|
7
|
-
"
|
|
33
|
+
"build": "tsc -p tsconfig.json",
|
|
34
|
+
"check": "npm run build && npm test && node scripts/check-package.mjs",
|
|
35
|
+
"test": "vitest run --passWithNoTests"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@nylorun/core": "0.1.1-beta"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"zod": "^4.5.4"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
|
45
|
+
"@types/node": "^24.0.0",
|
|
46
|
+
"vitest": "^5.0.0"
|
|
47
|
+
},
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=24"
|
|
50
|
+
},
|
|
51
|
+
"repository": {
|
|
52
|
+
"type": "git",
|
|
53
|
+
"url": "git+https://github.com/nylorun/harness.git",
|
|
54
|
+
"directory": "agents"
|
|
8
55
|
},
|
|
9
|
-
"
|
|
10
|
-
|
|
11
|
-
|
|
56
|
+
"publishConfig": {
|
|
57
|
+
"access": "public",
|
|
58
|
+
"provenance": true
|
|
59
|
+
}
|
|
12
60
|
}
|
package/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {}
|
package/publish.out
DELETED
|
File without changes
|