@cuylabs/agent-foundry-agentserver-invocations 4.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 +201 -0
- package/README.md +76 -0
- package/dist/index.d.ts +301 -0
- package/dist/index.js +682 -0
- package/package.json +61 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# @cuylabs/agent-foundry-agentserver-invocations
|
|
2
|
+
|
|
3
|
+
TypeScript counterpart to Python `azure-ai-agentserver-invocations`.
|
|
4
|
+
|
|
5
|
+
This is the low-level Foundry Agent Server **Invocations** protocol host. It
|
|
6
|
+
does not depend on `@cuylabs/agent-core`; consumers can implement a raw
|
|
7
|
+
`InvocationHandler` and serve the hosted-agent `/invocations` contract directly.
|
|
8
|
+
Use `@cuylabs/agent-foundry-hosting` when you want the higher-level
|
|
9
|
+
`@cuylabs/agent-core` adapter.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install @cuylabs/agent-foundry-agentserver-invocations express
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Quick Start
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import {
|
|
21
|
+
InvocationHandler,
|
|
22
|
+
runInvocationsServer,
|
|
23
|
+
type InvocationContext,
|
|
24
|
+
} from "@cuylabs/agent-foundry-agentserver-invocations";
|
|
25
|
+
import type { Request, Response } from "express";
|
|
26
|
+
|
|
27
|
+
class HelloHandler extends InvocationHandler {
|
|
28
|
+
async handle(_req: Request, res: Response, ctx: InvocationContext) {
|
|
29
|
+
res.setHeader("Content-Type", "text/event-stream");
|
|
30
|
+
res.write(`data: ${JSON.stringify({ type: "token", content: "hello" })}\n\n`);
|
|
31
|
+
res.write(
|
|
32
|
+
`data: ${JSON.stringify({
|
|
33
|
+
type: "done",
|
|
34
|
+
invocation_id: ctx.invocationId,
|
|
35
|
+
session_id: ctx.sessionId,
|
|
36
|
+
full_text: "hello",
|
|
37
|
+
})}\n\n`,
|
|
38
|
+
);
|
|
39
|
+
res.end();
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
await runInvocationsServer({
|
|
44
|
+
handler: () => new HelloHandler(),
|
|
45
|
+
port: 8088,
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## HTTP Surface
|
|
50
|
+
|
|
51
|
+
| Method | Path | Description |
|
|
52
|
+
| --- | --- | --- |
|
|
53
|
+
| `POST` | `/invocations` | Invoke the agent |
|
|
54
|
+
| `GET` | `/invocations/{invocationId}` | Optional LRO status |
|
|
55
|
+
| `DELETE` | `/invocations/{invocationId}` | Optional LRO cancel |
|
|
56
|
+
| `POST` | `/invocations/{invocationId}/cancel` | Optional cancel alias used by Foundry HITL samples |
|
|
57
|
+
| `GET` | `/invocations/docs/openapi.json` | OpenAPI spec |
|
|
58
|
+
| `GET` | `/healthz` | Liveness probe |
|
|
59
|
+
| `GET` | `/readiness` | Foundry readiness probe |
|
|
60
|
+
| `GET` | `/readyz` | Readiness alias |
|
|
61
|
+
|
|
62
|
+
## Python Mapping
|
|
63
|
+
|
|
64
|
+
This package maps to:
|
|
65
|
+
|
|
66
|
+
```text
|
|
67
|
+
azure-ai-agentserver-invocations
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
It intentionally does not map to:
|
|
71
|
+
|
|
72
|
+
```text
|
|
73
|
+
agent-framework-foundry-hosting
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
That higher layer is represented by `@cuylabs/agent-foundry-hosting`.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { Request, Response, Express } from 'express';
|
|
2
|
+
import { Server } from 'node:http';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Shared types for the Foundry Invocations protocol.
|
|
6
|
+
*
|
|
7
|
+
* The protocol contract:
|
|
8
|
+
*
|
|
9
|
+
* - `POST /invocations` with a JSON body or plain-text body. The session
|
|
10
|
+
* identity comes from the `agent_session_id` query string, the
|
|
11
|
+
* `x-foundry-agent-session-id` / `x-ms-agent-session-id` headers, or the
|
|
12
|
+
* `FOUNDRY_AGENT_SESSION_ID` env var (in that order). The invocation
|
|
13
|
+
* identity comes from `x-foundry-invocation-id` / `x-ms-invocation-id` or
|
|
14
|
+
* is generated.
|
|
15
|
+
* - Response is either JSON or `text/event-stream`. The default in this
|
|
16
|
+
* package is SSE.
|
|
17
|
+
*
|
|
18
|
+
* Mirrors:
|
|
19
|
+
* - Python `agent-framework-foundry-hosting._invocations` (the
|
|
20
|
+
* `InvocationsHostServer`).
|
|
21
|
+
* - The `InvocationContext` exposed by `azure.ai.agentserver.invocations`
|
|
22
|
+
* via `request.state.session_id` / `request.state.invocation_id`.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Resolved invocation identity, derived from query/headers/env.
|
|
27
|
+
*
|
|
28
|
+
* Matches the C# `InvocationContext` shape exposed by
|
|
29
|
+
* `Azure.AI.AgentServer.Invocations`, and the Python `request.state.*` keys
|
|
30
|
+
* exposed by `azure.ai.agentserver.invocations`.
|
|
31
|
+
*/
|
|
32
|
+
interface InvocationContext {
|
|
33
|
+
/** The session identifier; multi-turn conversations share this value. */
|
|
34
|
+
readonly sessionId: string;
|
|
35
|
+
/** Per-call identifier; useful for trace correlation and idempotency. */
|
|
36
|
+
readonly invocationId: string;
|
|
37
|
+
/** Per-request correlation identifier returned as `x-request-id`. */
|
|
38
|
+
readonly requestId: string;
|
|
39
|
+
/**
|
|
40
|
+
* Free-form attributes the host extracted from the incoming request.
|
|
41
|
+
*
|
|
42
|
+
* Currently includes `userAgent`, `forwardedFor`, and Foundry isolation
|
|
43
|
+
* keys when supplied by the caller.
|
|
44
|
+
*/
|
|
45
|
+
readonly attributes: Readonly<Record<string, string>>;
|
|
46
|
+
/**
|
|
47
|
+
* Aborted when the underlying HTTP request is closed by the client. Use
|
|
48
|
+
* this to short-circuit work that should not outlive the caller.
|
|
49
|
+
*/
|
|
50
|
+
readonly signal: AbortSignal;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Normalized request payload extracted from the body.
|
|
54
|
+
*
|
|
55
|
+
* The Foundry portal posts plain text bodies, JSON `{ message: "..." }`,
|
|
56
|
+
* JSON `{ input: "..." }`, JSON `{ decision: "allow|deny|remember" }`, and
|
|
57
|
+
* JSON `{ response: "..." }` — the `agent-core` bridge in particular routes
|
|
58
|
+
* those through `pendingInput` resolution. We accept all of them here.
|
|
59
|
+
*/
|
|
60
|
+
interface InvocationPayload {
|
|
61
|
+
/** A new turn message. */
|
|
62
|
+
readonly message?: string;
|
|
63
|
+
/** Optional system prompt override. */
|
|
64
|
+
readonly system?: string;
|
|
65
|
+
/** Resolved approval action, when the body matched a known alias. */
|
|
66
|
+
readonly approvalAction?: "allow" | "deny" | "remember";
|
|
67
|
+
/** Resolved free-text human response. */
|
|
68
|
+
readonly humanResponse?: string;
|
|
69
|
+
/** The raw decoded body — JSON object/array/string or the raw text. */
|
|
70
|
+
readonly raw: unknown;
|
|
71
|
+
}
|
|
72
|
+
interface ParsedInvocationRequest extends InvocationPayload {
|
|
73
|
+
readonly sessionId: string;
|
|
74
|
+
readonly invocationId: string;
|
|
75
|
+
readonly attributes: Record<string, string>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Optional handler hooks. `handle` is the only method you must implement.
|
|
79
|
+
*
|
|
80
|
+
* Mirrors the C# `InvocationHandler` abstract class:
|
|
81
|
+
* - `HandleAsync` ↔ `handle`
|
|
82
|
+
* - `GetAsync` ↔ `getStatus`
|
|
83
|
+
* - `CancelAsync` ↔ `cancel`
|
|
84
|
+
* - `GetOpenApiAsync` ↔ `getOpenApi`
|
|
85
|
+
*
|
|
86
|
+
* The Python `@app.invoke_handler` / `@app.get_invocation_handler` /
|
|
87
|
+
* `@app.cancel_invocation_handler` decorators map to the same hooks.
|
|
88
|
+
*/
|
|
89
|
+
declare abstract class InvocationHandler {
|
|
90
|
+
/**
|
|
91
|
+
* Handle a single `POST /invocations` request.
|
|
92
|
+
*
|
|
93
|
+
* Implementations should write the response themselves — typically as
|
|
94
|
+
* `text/event-stream` SSE, but JSON is allowed too. Use the helpers in
|
|
95
|
+
* `./sse.js` (`writeSseFrame`, `writeDoneFrame`, `agentEventToSseFrame`)
|
|
96
|
+
* if you want SSE without rolling your own framing.
|
|
97
|
+
*/
|
|
98
|
+
abstract handle(req: Request, res: Response, ctx: InvocationContext): Promise<void>;
|
|
99
|
+
/**
|
|
100
|
+
* Optional: handle `GET /invocations/{invocationId}` status polls for
|
|
101
|
+
* long-running operations. Default behavior is `404`.
|
|
102
|
+
*/
|
|
103
|
+
getStatus?(invocationId: string, req: Request, res: Response): Promise<void> | void;
|
|
104
|
+
/**
|
|
105
|
+
* Optional: handle `DELETE /invocations/{invocationId}` cancellation for
|
|
106
|
+
* long-running operations. Default behavior is `404`.
|
|
107
|
+
*/
|
|
108
|
+
cancel?(invocationId: string, req: Request, res: Response): Promise<void> | void;
|
|
109
|
+
/**
|
|
110
|
+
* Optional: override the response of `GET /invocations/docs/openapi.json`.
|
|
111
|
+
* If absent, the host renders a generated spec.
|
|
112
|
+
*/
|
|
113
|
+
getOpenApi?(): unknown;
|
|
114
|
+
/**
|
|
115
|
+
* Optional: release resources held by a singleton handler when the host
|
|
116
|
+
* shuts down. Factories are not closed automatically because the host does
|
|
117
|
+
* not own their lifetime.
|
|
118
|
+
*/
|
|
119
|
+
close?(): Promise<void> | void;
|
|
120
|
+
}
|
|
121
|
+
type InvocationHandlerFactory = () => InvocationHandler;
|
|
122
|
+
/**
|
|
123
|
+
* Configurable per-handler hook used by the host to instantiate a handler
|
|
124
|
+
* per request (matching the C# DI-style scoped behavior) or once at startup
|
|
125
|
+
* (matching a singleton). Pass an instance for singleton, a factory for
|
|
126
|
+
* per-request.
|
|
127
|
+
*/
|
|
128
|
+
type InvocationHandlerInput = InvocationHandler | InvocationHandlerFactory;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Payload parser for the Foundry Invocations protocol.
|
|
132
|
+
*
|
|
133
|
+
* Accepts:
|
|
134
|
+
*
|
|
135
|
+
* - JSON `{ "message": "..." }` (canonical)
|
|
136
|
+
* - JSON `{ "input": "..." }` (Foundry portal alternate)
|
|
137
|
+
* - JSON `{ "input": { "message": "..." } | { "text": "..." } }` (nested)
|
|
138
|
+
* - JSON `{ "text": "..." }`
|
|
139
|
+
* - JSON `{ "decision": "allow|deny|remember", ... }` (HITL approval)
|
|
140
|
+
* - JSON `{ "response": "..." }` (HITL human input)
|
|
141
|
+
* - Plain text body (the Foundry portal sends these too)
|
|
142
|
+
*
|
|
143
|
+
* Unknown JSON shapes are passed through as `raw` for handlers that want to
|
|
144
|
+
* inspect them directly.
|
|
145
|
+
*
|
|
146
|
+
* The session identity resolution mirrors the Python and C# behavior:
|
|
147
|
+
* `agent_session_id` query string, then the foundry/ms session headers,
|
|
148
|
+
* then `FOUNDRY_AGENT_SESSION_ID`, then the caller-provided default, then a
|
|
149
|
+
* generated id.
|
|
150
|
+
*/
|
|
151
|
+
|
|
152
|
+
interface ParsePayloadOptions {
|
|
153
|
+
/** Default session id when none is supplied. Defaults to a generated id. */
|
|
154
|
+
defaultSessionId?: string;
|
|
155
|
+
/** Default invocation id when none is supplied. Defaults to a generated id. */
|
|
156
|
+
defaultInvocationId?: string;
|
|
157
|
+
/**
|
|
158
|
+
* Whether to trust the `FOUNDRY_AGENT_SESSION_ID` env var as the last
|
|
159
|
+
* fallback. Defaults to `true`.
|
|
160
|
+
*/
|
|
161
|
+
honorEnvSessionId?: boolean;
|
|
162
|
+
}
|
|
163
|
+
declare function parseInvocationRequest(req: Request, options?: ParsePayloadOptions): ParsedInvocationRequest;
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Server-Sent Events helpers for the Foundry Invocations protocol.
|
|
167
|
+
*
|
|
168
|
+
* The token / done frame shapes match the Python and C# `bring-your-own/invocations/hello-world`
|
|
169
|
+
* samples byte-for-byte:
|
|
170
|
+
*
|
|
171
|
+
* data: {"type":"token","content":"..."}\n\n
|
|
172
|
+
* data: {"type":"done","invocation_id":"...","session_id":"...","full_text":"..."}\n\n
|
|
173
|
+
*
|
|
174
|
+
* Foundry portal clients expect these exact `type` discriminators.
|
|
175
|
+
*/
|
|
176
|
+
|
|
177
|
+
interface SseInvocationState {
|
|
178
|
+
invocationId: string;
|
|
179
|
+
sessionId: string;
|
|
180
|
+
fullText: string;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Set the canonical SSE response headers and flush them so reverse proxies
|
|
184
|
+
* (Front Door, App Gateway, nginx) start streaming immediately.
|
|
185
|
+
*/
|
|
186
|
+
declare function startSseResponse(res: Response): void;
|
|
187
|
+
/** Encode a JSON payload as a single SSE `data:` frame (with trailing `\n\n`). */
|
|
188
|
+
declare function sseFrame(payload: unknown): string;
|
|
189
|
+
/**
|
|
190
|
+
* Write a token frame. Mutates `state.fullText` so the matching `done` frame
|
|
191
|
+
* carries the full assembled reply.
|
|
192
|
+
*/
|
|
193
|
+
declare function writeTokenFrame(res: Response, state: SseInvocationState, content: string): void;
|
|
194
|
+
/**
|
|
195
|
+
* Write the terminal `done` frame. Always call this exactly once before
|
|
196
|
+
* `res.end()`; downstream consumers (the Foundry portal, Slack gateways) use
|
|
197
|
+
* it as the end-of-turn marker.
|
|
198
|
+
*/
|
|
199
|
+
declare function writeDoneFrame(res: Response, state: SseInvocationState): void;
|
|
200
|
+
/** Write an error frame (callers usually follow with a `done` frame and `res.end()`). */
|
|
201
|
+
declare function writeErrorFrame(res: Response, message: string): void;
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Generated OpenAPI 3.0 spec for the Foundry Invocations protocol surface.
|
|
205
|
+
*
|
|
206
|
+
* Served at `GET /invocations/docs/openapi.json` to satisfy the Foundry
|
|
207
|
+
* platform's optional discovery contract.
|
|
208
|
+
*/
|
|
209
|
+
interface OpenApiSpecOptions {
|
|
210
|
+
title?: string;
|
|
211
|
+
description?: string;
|
|
212
|
+
version?: string;
|
|
213
|
+
appName?: string;
|
|
214
|
+
}
|
|
215
|
+
declare function buildInvocationsOpenApiSpec(options?: OpenApiSpecOptions): Record<string, unknown>;
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Express-based host for the Foundry Invocations protocol.
|
|
219
|
+
*
|
|
220
|
+
* Exposes:
|
|
221
|
+
*
|
|
222
|
+
* - `POST /invocations` — handler entry point
|
|
223
|
+
* - `GET /invocations/{invocationId}` — optional LRO status
|
|
224
|
+
* - `DELETE /invocations/{invocationId}` — optional LRO cancel
|
|
225
|
+
* - `POST /invocations/{invocationId}/cancel` — optional LRO cancel
|
|
226
|
+
* - `GET /invocations/docs/openapi.json` — generated OpenAPI spec
|
|
227
|
+
* - `GET /healthz` — liveness
|
|
228
|
+
* - `GET /readiness` — readiness
|
|
229
|
+
* - `GET /readyz` — readiness alias
|
|
230
|
+
* - `GET /` — identity payload
|
|
231
|
+
*
|
|
232
|
+
* Handler resolution:
|
|
233
|
+
*
|
|
234
|
+
* - Pass an `InvocationHandler` instance to share it across requests
|
|
235
|
+
* (singleton).
|
|
236
|
+
* - Pass an `() => InvocationHandler` factory to build one per request
|
|
237
|
+
* (matching the C# DI scoped behavior).
|
|
238
|
+
*
|
|
239
|
+
* Mirrors the C# `InvocationsServer.Run<HandlerType>(configure: ...)`
|
|
240
|
+
* one-liner and the Python `app = InvocationAgentServerHost(); app.run()`
|
|
241
|
+
* pattern.
|
|
242
|
+
*/
|
|
243
|
+
|
|
244
|
+
interface InvocationsServerOptions {
|
|
245
|
+
/** Required: the handler (singleton) or factory (per-request). */
|
|
246
|
+
handler: InvocationHandlerInput;
|
|
247
|
+
/** Defaults to `8088`, matching the Python and C# samples. */
|
|
248
|
+
port?: number;
|
|
249
|
+
/** Defaults to `0.0.0.0`. */
|
|
250
|
+
host?: string;
|
|
251
|
+
/** Friendly app name surfaced via `GET /` and the OpenAPI doc. */
|
|
252
|
+
appName?: string;
|
|
253
|
+
/** OpenAPI document overrides (or full replacement via `handler.getOpenApi`). */
|
|
254
|
+
openapi?: OpenApiSpecOptions;
|
|
255
|
+
/** Maximum request body size; defaults to `"1mb"`. */
|
|
256
|
+
bodyLimit?: string;
|
|
257
|
+
/**
|
|
258
|
+
* If `true`, log a single line per HTTP request (method, path, status,
|
|
259
|
+
* duration). Defaults to `true`. Set `false` to silence in low-noise
|
|
260
|
+
* environments.
|
|
261
|
+
*/
|
|
262
|
+
requestLogging?: boolean;
|
|
263
|
+
/**
|
|
264
|
+
* Trust proxy setting forwarded to Express. Defaults to `1` so
|
|
265
|
+
* `req.ip` and `x-forwarded-*` headers work behind Front Door / App
|
|
266
|
+
* Gateway.
|
|
267
|
+
*/
|
|
268
|
+
trustProxy?: boolean | number | string;
|
|
269
|
+
/** Optional logger. Falls back to `console`. */
|
|
270
|
+
logger?: InvocationsServerLogger;
|
|
271
|
+
}
|
|
272
|
+
interface InvocationsServerLogger {
|
|
273
|
+
info(message: string, meta?: Record<string, unknown>): void;
|
|
274
|
+
warn(message: string, meta?: Record<string, unknown>): void;
|
|
275
|
+
error(message: string, meta?: Record<string, unknown>): void;
|
|
276
|
+
debug?(message: string, meta?: Record<string, unknown>): void;
|
|
277
|
+
}
|
|
278
|
+
interface InvocationsServer {
|
|
279
|
+
readonly app: Express;
|
|
280
|
+
readonly server: Server;
|
|
281
|
+
readonly port: number;
|
|
282
|
+
readonly host: string;
|
|
283
|
+
/** Stop accepting new connections and wait for in-flight requests. */
|
|
284
|
+
close(): Promise<void>;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Build a fully-configured Express app for the Invocations protocol without
|
|
288
|
+
* binding it to a port. Useful when you want to mount the host inside an
|
|
289
|
+
* existing Express tree, or in tests.
|
|
290
|
+
*/
|
|
291
|
+
declare function createInvocationsApp(options: InvocationsServerOptions): Express;
|
|
292
|
+
/**
|
|
293
|
+
* Start the host on a TCP port. The default port `8088` matches the Python
|
|
294
|
+
* and C# `bring-your-own/invocations/hello-world` Dockerfiles and the
|
|
295
|
+
* Foundry hosted-agent contract.
|
|
296
|
+
*
|
|
297
|
+
* Returns a handle with `close()` for graceful shutdown.
|
|
298
|
+
*/
|
|
299
|
+
declare function runInvocationsServer(options: InvocationsServerOptions): Promise<InvocationsServer>;
|
|
300
|
+
|
|
301
|
+
export { type InvocationContext, InvocationHandler, type InvocationHandlerFactory, type InvocationHandlerInput, type InvocationPayload, type InvocationsServer, type InvocationsServerLogger, type InvocationsServerOptions, type OpenApiSpecOptions, type ParsePayloadOptions, type ParsedInvocationRequest, type SseInvocationState, buildInvocationsOpenApiSpec, createInvocationsApp, parseInvocationRequest, runInvocationsServer, sseFrame, startSseResponse, writeDoneFrame, writeErrorFrame, writeTokenFrame };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,682 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
var InvocationHandler = class {
|
|
3
|
+
};
|
|
4
|
+
|
|
5
|
+
// src/payload.ts
|
|
6
|
+
import {
|
|
7
|
+
INVOCATION_ID_HEADERS,
|
|
8
|
+
SESSION_ID_HEADERS,
|
|
9
|
+
resolveInvocationIdentity
|
|
10
|
+
} from "@cuylabs/agent-foundry-agentserver-core";
|
|
11
|
+
var APPROVAL_ALLOW = /* @__PURE__ */ new Set(["allow", "approve", "approved", "yes", "y"]);
|
|
12
|
+
var APPROVAL_DENY = /* @__PURE__ */ new Set(["deny", "reject", "rejected", "no", "n"]);
|
|
13
|
+
var APPROVAL_REMEMBER = /* @__PURE__ */ new Set([
|
|
14
|
+
"remember",
|
|
15
|
+
"always",
|
|
16
|
+
"approve always",
|
|
17
|
+
"allow always"
|
|
18
|
+
]);
|
|
19
|
+
function parseInvocationRequest(req, options = {}) {
|
|
20
|
+
const rawBody = readRawBody(req);
|
|
21
|
+
const raw = parseJsonOrText(rawBody);
|
|
22
|
+
const payload = normalizePayload(raw);
|
|
23
|
+
const identity = resolveInvocationIdentity({
|
|
24
|
+
header: (name) => req.header(name),
|
|
25
|
+
query: (name) => req.query[name],
|
|
26
|
+
defaultSessionId: options.defaultSessionId,
|
|
27
|
+
defaultInvocationId: options.defaultInvocationId,
|
|
28
|
+
honorEnvSessionId: options.honorEnvSessionId
|
|
29
|
+
});
|
|
30
|
+
return {
|
|
31
|
+
...payload,
|
|
32
|
+
sessionId: identity.sessionId,
|
|
33
|
+
invocationId: identity.invocationId,
|
|
34
|
+
attributes: collectAttributes(req)
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function readRawBody(req) {
|
|
38
|
+
const body = req.body;
|
|
39
|
+
if (Buffer.isBuffer(body)) {
|
|
40
|
+
return body.toString("utf8");
|
|
41
|
+
}
|
|
42
|
+
if (typeof body === "string") {
|
|
43
|
+
return body;
|
|
44
|
+
}
|
|
45
|
+
if (body && typeof body === "object") {
|
|
46
|
+
return JSON.stringify(body);
|
|
47
|
+
}
|
|
48
|
+
return "";
|
|
49
|
+
}
|
|
50
|
+
function parseJsonOrText(body) {
|
|
51
|
+
const normalized = body.trim();
|
|
52
|
+
if (!normalized) {
|
|
53
|
+
return {};
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
return JSON.parse(normalized);
|
|
57
|
+
} catch {
|
|
58
|
+
return normalized;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function normalizePayload(raw) {
|
|
62
|
+
if (typeof raw === "string") {
|
|
63
|
+
return { message: raw, raw };
|
|
64
|
+
}
|
|
65
|
+
if (!isRecord(raw)) {
|
|
66
|
+
return { raw };
|
|
67
|
+
}
|
|
68
|
+
const action = normalizeApprovalAction(
|
|
69
|
+
stringFromObject(raw, "decision") ?? stringFromObject(raw, "approval") ?? stringFromObject(raw, "action")
|
|
70
|
+
);
|
|
71
|
+
const humanResponse = stringFromObject(raw, "response") ?? stringFromObject(raw, "human_response") ?? stringFromObject(raw, "humanResponse");
|
|
72
|
+
return {
|
|
73
|
+
message: stringFromObject(raw, "message") ?? stringFromObject(raw, "input") ?? stringFromObject(raw, "text") ?? messageFromNestedInput(raw),
|
|
74
|
+
system: stringFromObject(raw, "system"),
|
|
75
|
+
...action ? { approvalAction: action } : {},
|
|
76
|
+
...humanResponse ? { humanResponse } : {},
|
|
77
|
+
raw
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function messageFromNestedInput(raw) {
|
|
81
|
+
const input = raw.input;
|
|
82
|
+
if (isRecord(input)) {
|
|
83
|
+
return stringFromObject(input, "message") ?? stringFromObject(input, "text");
|
|
84
|
+
}
|
|
85
|
+
return void 0;
|
|
86
|
+
}
|
|
87
|
+
function normalizeApprovalAction(value) {
|
|
88
|
+
const normalized = value?.trim().toLowerCase();
|
|
89
|
+
if (!normalized) {
|
|
90
|
+
return void 0;
|
|
91
|
+
}
|
|
92
|
+
if (APPROVAL_ALLOW.has(normalized)) {
|
|
93
|
+
return "allow";
|
|
94
|
+
}
|
|
95
|
+
if (APPROVAL_DENY.has(normalized)) {
|
|
96
|
+
return "deny";
|
|
97
|
+
}
|
|
98
|
+
if (APPROVAL_REMEMBER.has(normalized)) {
|
|
99
|
+
return "remember";
|
|
100
|
+
}
|
|
101
|
+
return void 0;
|
|
102
|
+
}
|
|
103
|
+
function stringFromObject(value, property) {
|
|
104
|
+
if (!isRecord(value)) {
|
|
105
|
+
return void 0;
|
|
106
|
+
}
|
|
107
|
+
const item = value[property];
|
|
108
|
+
return typeof item === "string" && item.trim() ? item.trim() : void 0;
|
|
109
|
+
}
|
|
110
|
+
function collectAttributes(req) {
|
|
111
|
+
const attrs = {};
|
|
112
|
+
const ua = req.header("user-agent");
|
|
113
|
+
if (ua) attrs.userAgent = ua;
|
|
114
|
+
const fwd = req.header("x-forwarded-for");
|
|
115
|
+
if (fwd) attrs.forwardedFor = fwd;
|
|
116
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
117
|
+
if (typeof value !== "string") continue;
|
|
118
|
+
if ((key.startsWith("x-foundry-") || key.startsWith("x-ms-")) && !SESSION_ID_HEADERS.includes(
|
|
119
|
+
key
|
|
120
|
+
) && !INVOCATION_ID_HEADERS.includes(
|
|
121
|
+
key
|
|
122
|
+
)) {
|
|
123
|
+
attrs[key] = value;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return attrs;
|
|
127
|
+
}
|
|
128
|
+
function isRecord(value) {
|
|
129
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/sse.ts
|
|
133
|
+
function startSseResponse(res) {
|
|
134
|
+
res.status(200);
|
|
135
|
+
res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
|
|
136
|
+
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
137
|
+
res.setHeader("Connection", "keep-alive");
|
|
138
|
+
res.setHeader("X-Accel-Buffering", "no");
|
|
139
|
+
res.flushHeaders?.();
|
|
140
|
+
}
|
|
141
|
+
function sseFrame(payload) {
|
|
142
|
+
return `data: ${JSON.stringify(payload)}
|
|
143
|
+
|
|
144
|
+
`;
|
|
145
|
+
}
|
|
146
|
+
function writeTokenFrame(res, state, content) {
|
|
147
|
+
state.fullText += content;
|
|
148
|
+
res.write(sseFrame({ type: "token", content }));
|
|
149
|
+
}
|
|
150
|
+
function writeDoneFrame(res, state) {
|
|
151
|
+
res.write(
|
|
152
|
+
sseFrame({
|
|
153
|
+
type: "done",
|
|
154
|
+
invocation_id: state.invocationId,
|
|
155
|
+
session_id: state.sessionId,
|
|
156
|
+
full_text: state.fullText
|
|
157
|
+
})
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
function writeErrorFrame(res, message) {
|
|
161
|
+
res.write(sseFrame({ type: "error", message }));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// src/openapi.ts
|
|
165
|
+
function buildInvocationsOpenApiSpec(options = {}) {
|
|
166
|
+
const title = options.title ?? options.appName ?? "Foundry Invocations Host";
|
|
167
|
+
const version = options.version ?? "1.0.0";
|
|
168
|
+
const description = options.description ?? "Foundry Agent Server Invocations-protocol HTTP surface.";
|
|
169
|
+
return {
|
|
170
|
+
openapi: "3.0.0",
|
|
171
|
+
info: { title, version, description },
|
|
172
|
+
paths: {
|
|
173
|
+
"/healthz": {
|
|
174
|
+
get: {
|
|
175
|
+
summary: "Liveness probe",
|
|
176
|
+
responses: {
|
|
177
|
+
"200": { description: "Process is alive." }
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
"/readiness": {
|
|
182
|
+
get: {
|
|
183
|
+
summary: "Readiness probe (canonical \u2014 matches Foundry hosted-agent samples)",
|
|
184
|
+
responses: {
|
|
185
|
+
"200": { description: "Host is ready to accept invocations." }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
"/readyz": {
|
|
190
|
+
get: {
|
|
191
|
+
summary: "Readiness probe (Kubernetes-style alias of /readiness)",
|
|
192
|
+
responses: {
|
|
193
|
+
"200": { description: "Host is ready to accept invocations." }
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
},
|
|
197
|
+
"/invocations": {
|
|
198
|
+
post: {
|
|
199
|
+
summary: "Invoke the hosted agent",
|
|
200
|
+
parameters: [
|
|
201
|
+
{
|
|
202
|
+
name: "agent_session_id",
|
|
203
|
+
in: "query",
|
|
204
|
+
required: false,
|
|
205
|
+
description: "Multi-turn session identifier. Falls back to the x-foundry-agent-session-id header or FOUNDRY_AGENT_SESSION_ID env var.",
|
|
206
|
+
schema: { type: "string" }
|
|
207
|
+
}
|
|
208
|
+
],
|
|
209
|
+
requestBody: {
|
|
210
|
+
required: true,
|
|
211
|
+
content: {
|
|
212
|
+
"application/json": {
|
|
213
|
+
schema: {
|
|
214
|
+
type: "object",
|
|
215
|
+
properties: {
|
|
216
|
+
message: { type: "string" },
|
|
217
|
+
input: { type: "string" },
|
|
218
|
+
text: { type: "string" },
|
|
219
|
+
system: { type: "string" },
|
|
220
|
+
decision: {
|
|
221
|
+
type: "string",
|
|
222
|
+
enum: ["allow", "deny", "remember"]
|
|
223
|
+
},
|
|
224
|
+
response: { type: "string" }
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
"text/plain": {
|
|
229
|
+
schema: { type: "string" }
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
responses: {
|
|
234
|
+
"200": {
|
|
235
|
+
description: 'SSE stream of agent events. The terminal frame is `{ "type": "done", ... }`.',
|
|
236
|
+
content: {
|
|
237
|
+
"text/event-stream": {
|
|
238
|
+
schema: { type: "string" }
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
"400": {
|
|
243
|
+
description: "Invalid request payload."
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
"/invocations/{invocationId}": {
|
|
249
|
+
get: {
|
|
250
|
+
summary: "Long-running invocation status (optional; 404 unless the handler implements `getStatus`)",
|
|
251
|
+
parameters: [
|
|
252
|
+
{
|
|
253
|
+
name: "invocationId",
|
|
254
|
+
in: "path",
|
|
255
|
+
required: true,
|
|
256
|
+
schema: { type: "string" }
|
|
257
|
+
}
|
|
258
|
+
],
|
|
259
|
+
responses: {
|
|
260
|
+
"200": { description: "Status payload." },
|
|
261
|
+
"404": { description: "Not implemented or unknown invocation." }
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
delete: {
|
|
265
|
+
summary: "Cancel a long-running invocation (optional; 404 unless the handler implements `cancel`)",
|
|
266
|
+
parameters: [
|
|
267
|
+
{
|
|
268
|
+
name: "invocationId",
|
|
269
|
+
in: "path",
|
|
270
|
+
required: true,
|
|
271
|
+
schema: { type: "string" }
|
|
272
|
+
}
|
|
273
|
+
],
|
|
274
|
+
responses: {
|
|
275
|
+
"200": { description: "Cancellation acknowledged." },
|
|
276
|
+
"404": { description: "Not implemented or unknown invocation." }
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
},
|
|
280
|
+
"/invocations/{invocationId}/cancel": {
|
|
281
|
+
post: {
|
|
282
|
+
summary: "Cancel a long-running invocation (Foundry HITL sample convention; equivalent to DELETE /invocations/{invocationId})",
|
|
283
|
+
parameters: [
|
|
284
|
+
{
|
|
285
|
+
name: "invocationId",
|
|
286
|
+
in: "path",
|
|
287
|
+
required: true,
|
|
288
|
+
schema: { type: "string" }
|
|
289
|
+
}
|
|
290
|
+
],
|
|
291
|
+
responses: {
|
|
292
|
+
"200": { description: "Cancellation acknowledged." },
|
|
293
|
+
"404": { description: "Not implemented or unknown invocation." }
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
},
|
|
297
|
+
"/invocations/docs/openapi.json": {
|
|
298
|
+
get: {
|
|
299
|
+
summary: "OpenAPI document",
|
|
300
|
+
responses: {
|
|
301
|
+
"200": {
|
|
302
|
+
description: "OpenAPI spec for this Invocations host.",
|
|
303
|
+
content: {
|
|
304
|
+
"application/json": {
|
|
305
|
+
schema: { type: "object" }
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// src/host.ts
|
|
317
|
+
import express from "express";
|
|
318
|
+
import {
|
|
319
|
+
CHAT_ISOLATION_HEADER,
|
|
320
|
+
INVOCATION_ID_HEADER,
|
|
321
|
+
REQUEST_ID_HEADER,
|
|
322
|
+
SESSION_ID_HEADER,
|
|
323
|
+
USER_ISOLATION_HEADER,
|
|
324
|
+
AGENTSERVER_CORE_PACKAGE_VERSION,
|
|
325
|
+
buildPlatformServerHeader,
|
|
326
|
+
createErrorBody,
|
|
327
|
+
resolveAgentServerConfig,
|
|
328
|
+
resolveInvocationIdentity as resolveInvocationIdentity2,
|
|
329
|
+
resolveRequestId,
|
|
330
|
+
sanitizeProtocolId
|
|
331
|
+
} from "@cuylabs/agent-foundry-agentserver-core";
|
|
332
|
+
|
|
333
|
+
// src/package-version.ts
|
|
334
|
+
import { createRequire } from "module";
|
|
335
|
+
var require2 = createRequire(import.meta.url);
|
|
336
|
+
function readPackageVersion() {
|
|
337
|
+
const packageJson = require2("../package.json");
|
|
338
|
+
return typeof packageJson.version === "string" && packageJson.version.trim() ? packageJson.version : "0.0.0";
|
|
339
|
+
}
|
|
340
|
+
var AGENTSERVER_INVOCATIONS_PACKAGE_VERSION = readPackageVersion();
|
|
341
|
+
|
|
342
|
+
// src/host.ts
|
|
343
|
+
var DEFAULT_HOST = "0.0.0.0";
|
|
344
|
+
var DEFAULT_BODY_LIMIT = "1mb";
|
|
345
|
+
function createInvocationsApp(options) {
|
|
346
|
+
const logger = options.logger ?? defaultLogger();
|
|
347
|
+
const trustProxy = options.trustProxy ?? 1;
|
|
348
|
+
const bodyLimit = options.bodyLimit ?? DEFAULT_BODY_LIMIT;
|
|
349
|
+
const appName = options.appName ?? "foundry-invocations-host";
|
|
350
|
+
const requestLogging = options.requestLogging !== false;
|
|
351
|
+
const platformServer = buildPlatformServerHeader([
|
|
352
|
+
{
|
|
353
|
+
name: "azure-ai-agentserver-core",
|
|
354
|
+
version: AGENTSERVER_CORE_PACKAGE_VERSION
|
|
355
|
+
},
|
|
356
|
+
{
|
|
357
|
+
name: "azure-ai-agentserver-invocations",
|
|
358
|
+
version: AGENTSERVER_INVOCATIONS_PACKAGE_VERSION
|
|
359
|
+
}
|
|
360
|
+
]);
|
|
361
|
+
const app = express();
|
|
362
|
+
app.disable("x-powered-by");
|
|
363
|
+
app.set("trust proxy", trustProxy);
|
|
364
|
+
app.use(express.raw({ type: "*/*", limit: bodyLimit }));
|
|
365
|
+
app.use((req, res, next) => {
|
|
366
|
+
const requestId = resolveRequestId((name) => req.header(name));
|
|
367
|
+
req.agentServerRequestId = requestId;
|
|
368
|
+
addProtectedHeaders(res, {
|
|
369
|
+
[REQUEST_ID_HEADER]: requestId,
|
|
370
|
+
"x-platform-server": platformServer
|
|
371
|
+
});
|
|
372
|
+
next();
|
|
373
|
+
});
|
|
374
|
+
if (requestLogging) {
|
|
375
|
+
app.use(loggingMiddleware(logger));
|
|
376
|
+
}
|
|
377
|
+
const handlerProvider = makeHandlerProvider(options.handler);
|
|
378
|
+
app.get("/", (_req, res) => {
|
|
379
|
+
res.json({
|
|
380
|
+
app: appName,
|
|
381
|
+
host: "foundry-invocations",
|
|
382
|
+
protocol: "invocations",
|
|
383
|
+
protocolVersion: "1.0.0",
|
|
384
|
+
endpoint: "/invocations",
|
|
385
|
+
readiness: "/readiness",
|
|
386
|
+
liveness: "/healthz",
|
|
387
|
+
openapi: "/invocations/docs/openapi.json"
|
|
388
|
+
});
|
|
389
|
+
});
|
|
390
|
+
app.get("/healthz", (_req, res) => {
|
|
391
|
+
res.json({ ok: true });
|
|
392
|
+
});
|
|
393
|
+
const readinessHandler = (_req, res) => {
|
|
394
|
+
res.json({ ok: true, app: appName });
|
|
395
|
+
};
|
|
396
|
+
app.get("/readiness", readinessHandler);
|
|
397
|
+
app.get("/readyz", readinessHandler);
|
|
398
|
+
app.get("/invocations/docs/openapi.json", (_req, res) => {
|
|
399
|
+
const handler = handlerProvider();
|
|
400
|
+
const override = handler.getOpenApi?.();
|
|
401
|
+
res.json(
|
|
402
|
+
override ?? buildInvocationsOpenApiSpec({ ...options.openapi, appName })
|
|
403
|
+
);
|
|
404
|
+
});
|
|
405
|
+
app.post("/invocations", async (req, res) => {
|
|
406
|
+
let handler;
|
|
407
|
+
try {
|
|
408
|
+
handler = handlerProvider();
|
|
409
|
+
} catch (error) {
|
|
410
|
+
logger.error("Failed to construct InvocationHandler", {
|
|
411
|
+
error: formatError(error)
|
|
412
|
+
});
|
|
413
|
+
res.status(500).json(
|
|
414
|
+
createErrorBody(
|
|
415
|
+
"handler_construction_failed",
|
|
416
|
+
error instanceof Error ? error.message : String(error)
|
|
417
|
+
)
|
|
418
|
+
);
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
const ctx = buildContextFromRequest(req, res);
|
|
422
|
+
try {
|
|
423
|
+
await handler.handle(req, res, ctx);
|
|
424
|
+
} catch (error) {
|
|
425
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
426
|
+
logger.error("Invocation handler threw", {
|
|
427
|
+
error: formatError(error),
|
|
428
|
+
invocationId: ctx.invocationId,
|
|
429
|
+
sessionId: ctx.sessionId
|
|
430
|
+
});
|
|
431
|
+
if (!res.headersSent) {
|
|
432
|
+
res.status(500).json(createErrorBody("handler_failed", message));
|
|
433
|
+
} else {
|
|
434
|
+
try {
|
|
435
|
+
res.write(`data: ${JSON.stringify({ type: "error", message })}
|
|
436
|
+
|
|
437
|
+
`);
|
|
438
|
+
} catch {
|
|
439
|
+
}
|
|
440
|
+
res.end();
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
app.get("/invocations/:invocationId", async (req, res) => {
|
|
445
|
+
const handler = handlerProvider();
|
|
446
|
+
if (!handler.getStatus) {
|
|
447
|
+
res.status(404).json(
|
|
448
|
+
createErrorBody(
|
|
449
|
+
"not_implemented",
|
|
450
|
+
"This handler does not expose long-running invocation status."
|
|
451
|
+
)
|
|
452
|
+
);
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
try {
|
|
456
|
+
await handler.getStatus(req.params.invocationId ?? "", req, res);
|
|
457
|
+
} catch (error) {
|
|
458
|
+
handleHandlerError(res, error, logger, "getStatus");
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
const cancelHandler = async (req, res) => {
|
|
462
|
+
const handler = handlerProvider();
|
|
463
|
+
if (!handler.cancel) {
|
|
464
|
+
res.status(404).json(
|
|
465
|
+
createErrorBody(
|
|
466
|
+
"not_implemented",
|
|
467
|
+
"This handler does not expose long-running invocation cancellation."
|
|
468
|
+
)
|
|
469
|
+
);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
try {
|
|
473
|
+
await handler.cancel(req.params.invocationId, req, res);
|
|
474
|
+
} catch (error) {
|
|
475
|
+
handleHandlerError(res, error, logger, "cancel");
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
app.delete("/invocations/:invocationId", cancelHandler);
|
|
479
|
+
app.post("/invocations/:invocationId/cancel", cancelHandler);
|
|
480
|
+
app.all("/invocations", methodNotAllowed(["POST"]));
|
|
481
|
+
app.all("/invocations/docs/openapi.json", methodNotAllowed(["GET"]));
|
|
482
|
+
app.all("/invocations/:invocationId/cancel", methodNotAllowed(["POST"]));
|
|
483
|
+
app.all("/invocations/:invocationId", methodNotAllowed(["GET", "DELETE"]));
|
|
484
|
+
app.all("/readiness", methodNotAllowed(["GET"]));
|
|
485
|
+
app.all("/readyz", methodNotAllowed(["GET"]));
|
|
486
|
+
app.all("/healthz", methodNotAllowed(["GET"]));
|
|
487
|
+
app.use(notFoundMiddleware());
|
|
488
|
+
app.use(errorMiddleware(logger));
|
|
489
|
+
return app;
|
|
490
|
+
}
|
|
491
|
+
async function runInvocationsServer(options) {
|
|
492
|
+
const app = createInvocationsApp(options);
|
|
493
|
+
const port = resolveAgentServerConfig({ port: options.port }).port;
|
|
494
|
+
const host = options.host ?? DEFAULT_HOST;
|
|
495
|
+
const logger = options.logger ?? defaultLogger();
|
|
496
|
+
const appName = options.appName ?? "foundry-invocations-host";
|
|
497
|
+
const server = await new Promise((resolve, reject) => {
|
|
498
|
+
const httpServer = app.listen(port, host, () => {
|
|
499
|
+
logger.info(
|
|
500
|
+
`${appName} listening on http://${host}:${port}/invocations`
|
|
501
|
+
);
|
|
502
|
+
resolve(httpServer);
|
|
503
|
+
}).on("error", reject);
|
|
504
|
+
});
|
|
505
|
+
return {
|
|
506
|
+
app,
|
|
507
|
+
server,
|
|
508
|
+
port,
|
|
509
|
+
host,
|
|
510
|
+
async close() {
|
|
511
|
+
await new Promise((resolve, reject) => {
|
|
512
|
+
server.close((error) => {
|
|
513
|
+
if (!error || error.code === "ERR_SERVER_NOT_RUNNING") {
|
|
514
|
+
resolve();
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
reject(error);
|
|
518
|
+
});
|
|
519
|
+
});
|
|
520
|
+
if (options.handler instanceof InvocationHandler) {
|
|
521
|
+
await options.handler.close?.();
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
function makeHandlerProvider(input) {
|
|
527
|
+
if (typeof input === "function") {
|
|
528
|
+
return input;
|
|
529
|
+
}
|
|
530
|
+
return () => input;
|
|
531
|
+
}
|
|
532
|
+
function buildContextFromRequest(req, res) {
|
|
533
|
+
const identity = resolveInvocationIdentity2({
|
|
534
|
+
header: (name) => req.header(name),
|
|
535
|
+
query: (name) => req.query[name]
|
|
536
|
+
});
|
|
537
|
+
const requestId = req.agentServerRequestId ?? resolveRequestId((name) => req.header(name));
|
|
538
|
+
addProtectedHeaders(res, {
|
|
539
|
+
[INVOCATION_ID_HEADER]: identity.invocationId,
|
|
540
|
+
[SESSION_ID_HEADER]: identity.sessionId
|
|
541
|
+
});
|
|
542
|
+
const controller = new AbortController();
|
|
543
|
+
res.on("close", () => controller.abort());
|
|
544
|
+
const attributes = {};
|
|
545
|
+
const ua = req.header("user-agent");
|
|
546
|
+
if (ua) attributes.userAgent = ua;
|
|
547
|
+
const fwd = req.header("x-forwarded-for");
|
|
548
|
+
if (fwd) attributes.forwardedFor = fwd;
|
|
549
|
+
const userIsolationKey = req.header(USER_ISOLATION_HEADER);
|
|
550
|
+
if (userIsolationKey) attributes.userIsolationKey = userIsolationKey;
|
|
551
|
+
const chatIsolationKey = req.header(CHAT_ISOLATION_HEADER);
|
|
552
|
+
if (chatIsolationKey) attributes.chatIsolationKey = chatIsolationKey;
|
|
553
|
+
return {
|
|
554
|
+
sessionId: identity.sessionId,
|
|
555
|
+
invocationId: identity.invocationId,
|
|
556
|
+
requestId,
|
|
557
|
+
attributes,
|
|
558
|
+
signal: controller.signal
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
function loggingMiddleware(logger) {
|
|
562
|
+
return (req, res, next) => {
|
|
563
|
+
const start = Date.now();
|
|
564
|
+
res.on("finish", () => {
|
|
565
|
+
logger.info("http request", {
|
|
566
|
+
method: req.method,
|
|
567
|
+
path: req.path,
|
|
568
|
+
statusCode: res.statusCode,
|
|
569
|
+
durationMs: Date.now() - start,
|
|
570
|
+
requestId: req.agentServerRequestId,
|
|
571
|
+
clientRequestId: req.header("x-ms-client-request-id")
|
|
572
|
+
});
|
|
573
|
+
});
|
|
574
|
+
next();
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
function notFoundMiddleware() {
|
|
578
|
+
return (_req, res, _next) => {
|
|
579
|
+
res.status(404).json(createErrorBody("not_found", "No route matched this path."));
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
function errorMiddleware(logger) {
|
|
583
|
+
return (err, _req, res, _next) => {
|
|
584
|
+
logger.error("Unhandled middleware error", { error: formatError(err) });
|
|
585
|
+
if (res.headersSent) {
|
|
586
|
+
res.end();
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
res.status(500).json(
|
|
590
|
+
createErrorBody(
|
|
591
|
+
"internal_error",
|
|
592
|
+
err instanceof Error ? err.message : String(err)
|
|
593
|
+
)
|
|
594
|
+
);
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
function handleHandlerError(res, error, logger, hookName) {
|
|
598
|
+
logger.error(`Invocation handler hook ${hookName} threw`, {
|
|
599
|
+
error: formatError(error)
|
|
600
|
+
});
|
|
601
|
+
if (res.headersSent) {
|
|
602
|
+
res.end();
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
res.status(500).json(
|
|
606
|
+
createErrorBody(
|
|
607
|
+
`${hookName}_failed`,
|
|
608
|
+
error instanceof Error ? error.message : String(error)
|
|
609
|
+
)
|
|
610
|
+
);
|
|
611
|
+
}
|
|
612
|
+
function formatError(error) {
|
|
613
|
+
if (error instanceof Error) {
|
|
614
|
+
return error.stack ?? error.message;
|
|
615
|
+
}
|
|
616
|
+
return String(error);
|
|
617
|
+
}
|
|
618
|
+
function addProtectedHeaders(res, headers) {
|
|
619
|
+
const protectedRes = res;
|
|
620
|
+
if (!protectedRes.__agentServerProtectedHeaders) {
|
|
621
|
+
const protectedHeaders = /* @__PURE__ */ new Map();
|
|
622
|
+
const originalSetHeader2 = res.setHeader.bind(res);
|
|
623
|
+
protectedRes.__agentServerProtectedHeaders = protectedHeaders;
|
|
624
|
+
protectedRes.__agentServerOriginalSetHeader = originalSetHeader2;
|
|
625
|
+
res.setHeader = ((name, value) => {
|
|
626
|
+
const protectedValue = protectedHeaders.get(name.toLowerCase());
|
|
627
|
+
if (protectedValue !== void 0) {
|
|
628
|
+
return originalSetHeader2(name, protectedValue);
|
|
629
|
+
}
|
|
630
|
+
return originalSetHeader2(name, value);
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
const originalSetHeader = protectedRes.__agentServerOriginalSetHeader ?? res.setHeader.bind(res);
|
|
634
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
635
|
+
const safeValue = name.toLowerCase() === INVOCATION_ID_HEADER || name.toLowerCase() === SESSION_ID_HEADER ? sanitizeProtocolId(value, value) : value;
|
|
636
|
+
protectedRes.__agentServerProtectedHeaders.set(
|
|
637
|
+
name.toLowerCase(),
|
|
638
|
+
safeValue
|
|
639
|
+
);
|
|
640
|
+
originalSetHeader(name, safeValue);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
function methodNotAllowed(allowedMethods) {
|
|
644
|
+
return (_req, res) => {
|
|
645
|
+
res.setHeader("Allow", allowedMethods.join(", "));
|
|
646
|
+
res.status(405).json(
|
|
647
|
+
createErrorBody(
|
|
648
|
+
"method_not_allowed",
|
|
649
|
+
`Allowed methods: ${allowedMethods.join(", ")}`
|
|
650
|
+
)
|
|
651
|
+
);
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
function defaultLogger() {
|
|
655
|
+
return {
|
|
656
|
+
info: (message, meta) => {
|
|
657
|
+
if (meta) {
|
|
658
|
+
console.log(`[invocations] ${message}`, meta);
|
|
659
|
+
} else {
|
|
660
|
+
console.log(`[invocations] ${message}`);
|
|
661
|
+
}
|
|
662
|
+
},
|
|
663
|
+
warn: (message, meta) => {
|
|
664
|
+
console.warn(`[invocations] ${message}`, meta ?? "");
|
|
665
|
+
},
|
|
666
|
+
error: (message, meta) => {
|
|
667
|
+
console.error(`[invocations] ${message}`, meta ?? "");
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
export {
|
|
672
|
+
InvocationHandler,
|
|
673
|
+
buildInvocationsOpenApiSpec,
|
|
674
|
+
createInvocationsApp,
|
|
675
|
+
parseInvocationRequest,
|
|
676
|
+
runInvocationsServer,
|
|
677
|
+
sseFrame,
|
|
678
|
+
startSseResponse,
|
|
679
|
+
writeDoneFrame,
|
|
680
|
+
writeErrorFrame,
|
|
681
|
+
writeTokenFrame
|
|
682
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cuylabs/agent-foundry-agentserver-invocations",
|
|
3
|
+
"version": "4.1.0",
|
|
4
|
+
"description": "TypeScript Foundry Agent Server Invocations-protocol host (mirrors azure-ai-agentserver-invocations)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"express": "^5.0.0",
|
|
21
|
+
"@cuylabs/agent-foundry-agentserver-core": "^4.1.0"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@types/express": "^5.0.0",
|
|
25
|
+
"@types/node": "^22.0.0",
|
|
26
|
+
"tsup": "^8.0.0",
|
|
27
|
+
"typescript": "^5.7.0",
|
|
28
|
+
"vitest": "^4.0.18"
|
|
29
|
+
},
|
|
30
|
+
"keywords": [
|
|
31
|
+
"agent",
|
|
32
|
+
"azure",
|
|
33
|
+
"foundry",
|
|
34
|
+
"hosted-agent",
|
|
35
|
+
"invocations-protocol",
|
|
36
|
+
"agentserver",
|
|
37
|
+
"express",
|
|
38
|
+
"sse"
|
|
39
|
+
],
|
|
40
|
+
"author": "cuylabs",
|
|
41
|
+
"license": "Apache-2.0",
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "https://github.com/cuylabs-ai/agents-ts.git",
|
|
45
|
+
"directory": "packages/agent-foundry-agentserver-invocations"
|
|
46
|
+
},
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=20"
|
|
49
|
+
},
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"build": "tsup src/index.ts --format esm --dts --clean",
|
|
55
|
+
"dev": "tsup src/index.ts --format esm --dts --watch",
|
|
56
|
+
"typecheck": "tsc --noEmit",
|
|
57
|
+
"test": "vitest run",
|
|
58
|
+
"test:watch": "vitest",
|
|
59
|
+
"clean": "rm -rf dist"
|
|
60
|
+
}
|
|
61
|
+
}
|