@cuylabs/agent-foundry-hosting 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 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,36 @@
1
+ # @cuylabs/agent-foundry-hosting
2
+
3
+ Foundry Hosting integration for `@cuylabs/agent-core`.
4
+
5
+ This package mirrors Python `agent-framework-foundry-hosting`. It is the
6
+ higher-level adapter layer that wires an agent framework runtime into the
7
+ lower-level Agent Server protocol packages:
8
+
9
+ ```text
10
+ @cuylabs/agent-foundry-agentserver-invocations -> azure-ai-agentserver-invocations
11
+ @cuylabs/agent-foundry-hosting -> agent-framework-foundry-hosting
12
+ ```
13
+
14
+ ## Invocations
15
+
16
+ ```ts
17
+ import { runInvocationsServer } from "@cuylabs/agent-foundry-agentserver-invocations";
18
+ import { createInvocationsHandlerForAgent } from "@cuylabs/agent-foundry-hosting/invocations";
19
+ import {
20
+ createAgentServerAdapter,
21
+ InProcessAgentServer,
22
+ } from "@cuylabs/agent-server";
23
+
24
+ const server = new InProcessAgentServer(createAgentServerAdapter(myAgent));
25
+
26
+ await runInvocationsServer({
27
+ handler: createInvocationsHandlerForAgent(server),
28
+ port: 8088,
29
+ });
30
+ ```
31
+
32
+ ## Responses
33
+
34
+ Responses hosting is not part of this package yet. Add it as an explicit
35
+ subpath once the TypeScript Responses protocol package exists, following the
36
+ same split used here: protocol host first, framework adapter second.
@@ -0,0 +1,610 @@
1
+ // src/invocations/index.ts
2
+ import {
3
+ InvocationHandler,
4
+ parseInvocationRequest,
5
+ startSseResponse,
6
+ writeDoneFrame,
7
+ writeErrorFrame
8
+ } from "@cuylabs/agent-foundry-agentserver-invocations";
9
+
10
+ // src/invocations/async-queue.ts
11
+ var AsyncQueue = class {
12
+ values = [];
13
+ waiters = [];
14
+ closed = false;
15
+ push(value, coalesce) {
16
+ if (this.closed) {
17
+ return;
18
+ }
19
+ const waiter = this.waiters.shift();
20
+ if (waiter) {
21
+ waiter({ value, done: false });
22
+ return;
23
+ }
24
+ if (coalesce && this.values.length > 0) {
25
+ const lastIndex = this.values.length - 1;
26
+ const merged = coalesce(this.values[lastIndex], value);
27
+ if (merged !== void 0) {
28
+ this.values[lastIndex] = merged;
29
+ return;
30
+ }
31
+ }
32
+ this.values.push(value);
33
+ }
34
+ close() {
35
+ if (this.closed) {
36
+ return;
37
+ }
38
+ this.closed = true;
39
+ for (const waiter of this.waiters.splice(0)) {
40
+ waiter({ value: void 0, done: true });
41
+ }
42
+ }
43
+ reset() {
44
+ this.values = [];
45
+ this.closed = false;
46
+ }
47
+ async *[Symbol.asyncIterator]() {
48
+ while (true) {
49
+ if (this.values.length > 0) {
50
+ const value = this.values.shift();
51
+ yield value;
52
+ continue;
53
+ }
54
+ if (this.closed) {
55
+ return;
56
+ }
57
+ const result = await new Promise((resolve) => {
58
+ this.waiters.push(resolve);
59
+ });
60
+ if (result.done) {
61
+ return;
62
+ }
63
+ yield result.value;
64
+ }
65
+ }
66
+ };
67
+
68
+ // src/invocations/events.ts
69
+ import {
70
+ sseFrame
71
+ } from "@cuylabs/agent-foundry-agentserver-invocations";
72
+ var PASSTHROUGH_EVENT_TYPES = /* @__PURE__ */ new Set([
73
+ "status",
74
+ "step-start",
75
+ "step-finish",
76
+ "text-start",
77
+ "text-end",
78
+ "reasoning-start",
79
+ "reasoning-delta",
80
+ "reasoning-end",
81
+ "message",
82
+ "turn-boundary",
83
+ "approval-resolved",
84
+ "human-input-resolved",
85
+ "computer-call",
86
+ "computer-result",
87
+ "intervention-applied",
88
+ "follow-up-queued",
89
+ "doom-loop",
90
+ "context-overflow",
91
+ "turn-summary",
92
+ "retry"
93
+ ]);
94
+ function agentEventToSseFrame(event, state) {
95
+ switch (event.type) {
96
+ case "text-delta":
97
+ state.fullText += event.text;
98
+ return sseFrame({ type: "token", content: event.text });
99
+ case "tool-start":
100
+ return sseFrame({
101
+ type: "tool_start",
102
+ tool_name: event.toolName,
103
+ tool_call_id: event.toolCallId
104
+ });
105
+ case "tool-result":
106
+ return sseFrame({
107
+ type: "tool_result",
108
+ tool_name: event.toolName,
109
+ tool_call_id: event.toolCallId,
110
+ result: event.result
111
+ });
112
+ case "tool-error":
113
+ return sseFrame({
114
+ type: "tool_error",
115
+ tool_name: event.toolName,
116
+ tool_call_id: event.toolCallId,
117
+ error: event.error
118
+ });
119
+ case "approval-request":
120
+ return sseFrame({
121
+ type: "approval_required",
122
+ request_id: event.request.id,
123
+ tool: event.request.tool,
124
+ risk: event.request.risk,
125
+ actions: ["allow", "deny", "remember"]
126
+ });
127
+ case "human-input-request":
128
+ return sseFrame({
129
+ type: "input_required",
130
+ request_id: event.request.id,
131
+ kind: event.request.kind
132
+ });
133
+ case "error":
134
+ return sseFrame({
135
+ type: "error",
136
+ message: event.error.message
137
+ });
138
+ case "complete":
139
+ if (event.output && !state.fullText) {
140
+ state.fullText = event.output;
141
+ }
142
+ return void 0;
143
+ default: {
144
+ const eventType = event.type ?? "unknown";
145
+ if (PASSTHROUGH_EVENT_TYPES.has(eventType)) {
146
+ return sseFrame({ type: "agent_event", event_type: eventType });
147
+ }
148
+ return sseFrame({ type: "agent_event", event_type: eventType });
149
+ }
150
+ }
151
+ }
152
+ function coalesceAgentEvents(previous, next) {
153
+ if (previous.type === "text-delta" && next.type === "text-delta") {
154
+ return {
155
+ type: "text-delta",
156
+ text: previous.text + next.text
157
+ };
158
+ }
159
+ return void 0;
160
+ }
161
+
162
+ // src/invocations/broker.ts
163
+ var DEFAULT_MESSAGES = {
164
+ emptyStartBody: 'Send a non-empty "message" or "input" string to start a new invocation.',
165
+ cancelAcknowledged: "Canceled the running request. You can send a new message now.",
166
+ cancelAlreadyDone: "The previous request is no longer running. You can send a new message now.",
167
+ approvalWaiting: 'Approval is required before I can continue. Send `{ "decision": "allow" }`, `{ "decision": "deny" }`, or `{ "decision": "remember" }` with the same session ID.',
168
+ humanInputWaiting: 'More input is required before I can continue. Send `{ "response": "..." }` with the same session ID.',
169
+ pendingInputExpired: "That pending request is no longer active.",
170
+ steerAccepted: "I added that as guidance to the running request.",
171
+ steerRejected: "The running request did not accept that guidance.",
172
+ steerSendNewMessage: "This session has a running request. Send a message to steer it or send cancel.",
173
+ cannotSteerSendCancel: "This session already has a running request. Wait for it to finish or send cancel.",
174
+ busyTurn: "This session already has a running turn. Send a decision, input response, or cancel."
175
+ };
176
+ var DEFAULT_CANCEL = /^(cancel|stop|abort|nevermind|never mind|discard|quit)\b[.!?]*$/;
177
+ var InvocationBroker = class {
178
+ activeTurns = /* @__PURE__ */ new Map();
179
+ activeTurnsBySession = /* @__PURE__ */ new Map();
180
+ logger;
181
+ server;
182
+ cancelKeywords;
183
+ messages;
184
+ unsubscribe;
185
+ constructor(options) {
186
+ this.logger = options.logger ?? defaultLogger();
187
+ this.server = options.server;
188
+ this.cancelKeywords = options.cancelKeywords ?? DEFAULT_CANCEL;
189
+ this.messages = { ...DEFAULT_MESSAGES, ...options.messages };
190
+ this.unsubscribe = this.server.subscribe((notification) => {
191
+ void this.handleNotification(notification);
192
+ });
193
+ }
194
+ async *invoke(sessionId, input) {
195
+ const active = this.activeTurnsBySession.get(sessionId);
196
+ if (active) {
197
+ yield* this.invokeActiveTurn(active, input);
198
+ return;
199
+ }
200
+ const message = input.message?.trim();
201
+ if (!message) {
202
+ yield* immediateTextResponse(this.messages.emptyStartBody);
203
+ return;
204
+ }
205
+ let turn;
206
+ try {
207
+ turn = await this.server.startTurn(sessionId, message, {
208
+ ...input.system ? { system: input.system } : {}
209
+ });
210
+ } catch (error) {
211
+ if (isRunningTurnError(error)) {
212
+ yield* immediateTextResponse(this.messages.busyTurn);
213
+ return;
214
+ }
215
+ throw error;
216
+ }
217
+ const started = {
218
+ deliveredSequences: /* @__PURE__ */ new Set(),
219
+ eventCounts: {},
220
+ queue: new AsyncQueue(),
221
+ sessionId,
222
+ startedAtMs: Date.now(),
223
+ summaryLogged: false,
224
+ textDeltaChars: 0,
225
+ textDeltaCount: 0,
226
+ turnId: turn.id
227
+ };
228
+ this.activeTurns.set(turn.id, started);
229
+ this.activeTurnsBySession.set(sessionId, started);
230
+ this.logger.info("invocation turn started", {
231
+ sessionId,
232
+ turnId: turn.id,
233
+ inputLength: message.length,
234
+ hasSystemPrompt: Boolean(input.system)
235
+ });
236
+ this.replayExistingEvents(started);
237
+ yield* this.drainActiveTurn(started);
238
+ }
239
+ close() {
240
+ this.unsubscribe();
241
+ for (const active of this.activeTurns.values()) {
242
+ this.interruptActiveTurn(active, "shutdown");
243
+ }
244
+ this.activeTurns.clear();
245
+ this.activeTurnsBySession.clear();
246
+ }
247
+ async *invokeActiveTurn(active, input) {
248
+ if (this.isCancelMessage(input.message)) {
249
+ const interrupted = this.interruptActiveTurn(active, "user-cancel");
250
+ yield* immediateTextResponse(
251
+ interrupted ? this.messages.cancelAcknowledged : this.messages.cancelAlreadyDone
252
+ );
253
+ return;
254
+ }
255
+ if (active.pendingInput) {
256
+ const resolution = resolvePendingInput(active.pendingInput, input);
257
+ if (!resolution) {
258
+ yield* immediateTextResponse(this.waitingMessage(active.pendingInput));
259
+ return;
260
+ }
261
+ active.queue = new AsyncQueue();
262
+ const accepted = this.server.respondToInputRequest(
263
+ active.pendingInput.requestId,
264
+ resolution
265
+ );
266
+ if (!accepted) {
267
+ active.pendingInput = void 0;
268
+ yield* immediateTextResponse(this.messages.pendingInputExpired);
269
+ return;
270
+ }
271
+ yield* this.drainActiveTurn(active);
272
+ return;
273
+ }
274
+ const message = input.message?.trim();
275
+ if (!message) {
276
+ yield* immediateTextResponse(this.messages.steerSendNewMessage);
277
+ return;
278
+ }
279
+ try {
280
+ const response = this.server.steerTurn(active.turnId, message);
281
+ yield* immediateTextResponse(
282
+ response.accepted ? this.messages.steerAccepted : this.messages.steerRejected
283
+ );
284
+ } catch (error) {
285
+ this.logger.warn("failed to steer invocation turn", {
286
+ error: formatError(error),
287
+ sessionId: active.sessionId,
288
+ turnId: active.turnId
289
+ });
290
+ yield* immediateTextResponse(this.messages.cannotSteerSendCancel);
291
+ }
292
+ }
293
+ async *drainActiveTurn(active) {
294
+ for await (const event of active.queue) {
295
+ yield event;
296
+ }
297
+ }
298
+ async handleNotification(notification) {
299
+ switch (notification.type) {
300
+ case "turn/event": {
301
+ const active = this.activeTurns.get(notification.turnId);
302
+ if (active) {
303
+ this.routeTurnEvent(
304
+ active,
305
+ notification.event,
306
+ notification.sequence
307
+ );
308
+ }
309
+ break;
310
+ }
311
+ case "input/request": {
312
+ const active = notification.request.turnId ? this.activeTurns.get(notification.request.turnId) : void 0;
313
+ if (active) {
314
+ active.pendingInput = {
315
+ kind: notification.request.kind,
316
+ requestId: notification.request.id
317
+ };
318
+ }
319
+ break;
320
+ }
321
+ case "input/resolved": {
322
+ const active = notification.turnId ? this.activeTurns.get(notification.turnId) : void 0;
323
+ if (active?.pendingInput?.requestId === notification.requestId) {
324
+ active.pendingInput = void 0;
325
+ }
326
+ break;
327
+ }
328
+ case "turn/completed": {
329
+ const active = this.activeTurns.get(notification.turn.id);
330
+ if (active) {
331
+ this.logTurnSummary(active, "completed", {
332
+ status: notification.turn.status,
333
+ ...notification.turn.error ? { error: notification.turn.error } : {}
334
+ });
335
+ if (notification.turn.status === "failed") {
336
+ const message = notification.turn.error?.trim() || "Turn failed without details.";
337
+ active.queue.push({
338
+ type: "error",
339
+ error: new Error(message)
340
+ });
341
+ }
342
+ active.pendingInput = void 0;
343
+ active.queue.close();
344
+ this.activeTurns.delete(active.turnId);
345
+ if (this.activeTurnsBySession.get(active.sessionId)?.turnId === active.turnId) {
346
+ this.activeTurnsBySession.delete(active.sessionId);
347
+ }
348
+ }
349
+ break;
350
+ }
351
+ default:
352
+ break;
353
+ }
354
+ }
355
+ routeTurnEvent(active, event, sequence) {
356
+ if (sequence !== void 0) {
357
+ if (active.deliveredSequences.has(sequence)) {
358
+ return;
359
+ }
360
+ active.deliveredSequences.add(sequence);
361
+ }
362
+ this.recordEvent(active, event, sequence);
363
+ active.queue.push(event, coalesceAgentEvents);
364
+ if (event.type === "approval-request") {
365
+ active.pendingInput = {
366
+ kind: "approval",
367
+ requestId: event.request.id
368
+ };
369
+ active.queue.close();
370
+ }
371
+ if (event.type === "human-input-request") {
372
+ active.pendingInput = {
373
+ kind: "human",
374
+ requestId: event.request.id
375
+ };
376
+ active.queue.close();
377
+ }
378
+ }
379
+ replayExistingEvents(active) {
380
+ const detail = this.server.getTurn(active.turnId);
381
+ if (!detail) {
382
+ return;
383
+ }
384
+ for (const record of detail.events) {
385
+ this.routeTurnEvent(active, record.event, record.sequence);
386
+ }
387
+ if (detail.status !== "running") {
388
+ active.queue.close();
389
+ }
390
+ }
391
+ interruptActiveTurn(active, reason) {
392
+ const detail = this.server.getTurn(active.turnId);
393
+ let interrupted = false;
394
+ if (detail?.status === "running") {
395
+ try {
396
+ interrupted = this.server.interruptTurn(active.turnId);
397
+ } catch (error) {
398
+ this.logger.warn("failed to interrupt invocation turn", {
399
+ error: formatError(error),
400
+ reason,
401
+ sessionId: active.sessionId,
402
+ turnId: active.turnId
403
+ });
404
+ }
405
+ }
406
+ active.pendingInput = void 0;
407
+ active.queue.close();
408
+ this.activeTurns.delete(active.turnId);
409
+ if (this.activeTurnsBySession.get(active.sessionId)?.turnId === active.turnId) {
410
+ this.activeTurnsBySession.delete(active.sessionId);
411
+ }
412
+ return interrupted;
413
+ }
414
+ recordEvent(active, event, sequence) {
415
+ active.eventCounts[event.type] = (active.eventCounts[event.type] ?? 0) + 1;
416
+ if (event.type === "text-delta") {
417
+ active.textDeltaCount += 1;
418
+ active.textDeltaChars += event.text.length;
419
+ return;
420
+ }
421
+ if (event.type === "tool-start" || event.type === "tool-result") {
422
+ this.logger.debug?.("invocation tool event", {
423
+ eventType: event.type,
424
+ sessionId: active.sessionId,
425
+ turnId: active.turnId,
426
+ sequence,
427
+ toolName: event.toolName,
428
+ toolCallId: event.toolCallId
429
+ });
430
+ }
431
+ }
432
+ logTurnSummary(active, reason, extra = {}) {
433
+ if (active.summaryLogged) {
434
+ return;
435
+ }
436
+ active.summaryLogged = true;
437
+ this.logger.info("invocation turn finished", {
438
+ reason,
439
+ sessionId: active.sessionId,
440
+ turnId: active.turnId,
441
+ durationMs: Date.now() - active.startedAtMs,
442
+ textDeltaCount: active.textDeltaCount,
443
+ textDeltaChars: active.textDeltaChars,
444
+ eventCounts: active.eventCounts,
445
+ ...extra
446
+ });
447
+ }
448
+ waitingMessage(pending) {
449
+ return pending.kind === "approval" ? this.messages.approvalWaiting : this.messages.humanInputWaiting;
450
+ }
451
+ isCancelMessage(message) {
452
+ const normalized = message?.trim().toLowerCase();
453
+ return Boolean(normalized && this.cancelKeywords.test(normalized));
454
+ }
455
+ };
456
+ function resolvePendingInput(pending, input) {
457
+ if (pending.kind === "approval") {
458
+ if (!input.approvalAction) {
459
+ return void 0;
460
+ }
461
+ return {
462
+ kind: "approval",
463
+ action: input.approvalAction
464
+ };
465
+ }
466
+ const text = input.humanResponse ?? input.message;
467
+ if (!text?.trim()) {
468
+ return void 0;
469
+ }
470
+ return {
471
+ kind: "human",
472
+ response: {
473
+ kind: "text",
474
+ text: text.trim()
475
+ }
476
+ };
477
+ }
478
+ async function* immediateTextResponse(text) {
479
+ yield { type: "text-start" };
480
+ yield { type: "text-delta", text };
481
+ yield { type: "text-end" };
482
+ yield { type: "complete", output: text };
483
+ }
484
+ function isRunningTurnError(error) {
485
+ return error instanceof Error && /already has a running turn/i.test(error.message);
486
+ }
487
+ function formatError(error) {
488
+ if (error instanceof Error) {
489
+ return error.stack ?? error.message;
490
+ }
491
+ return String(error);
492
+ }
493
+ function defaultLogger() {
494
+ return {
495
+ info: () => {
496
+ },
497
+ warn: () => {
498
+ },
499
+ error: (message, meta) => {
500
+ console.error(`[invocations:broker] ${message}`, meta ?? "");
501
+ }
502
+ };
503
+ }
504
+
505
+ // src/invocations/index.ts
506
+ function createInvocationsHandlerForAgent(server, options = {}) {
507
+ const broker = new InvocationBroker({
508
+ server,
509
+ ...options.logger ? { logger: options.logger } : {},
510
+ ...options.cancelKeywords ? { cancelKeywords: options.cancelKeywords } : {},
511
+ ...options.messages ? { messages: options.messages } : {}
512
+ });
513
+ return new AgentCoreInvocationHandler(broker, options);
514
+ }
515
+ var AgentCoreInvocationHandler = class extends InvocationHandler {
516
+ constructor(broker, options) {
517
+ super();
518
+ this.broker = broker;
519
+ this.options = options;
520
+ }
521
+ async handle(req, res, ctx) {
522
+ let parsed;
523
+ try {
524
+ parsed = parseInvocationRequest(req, {
525
+ defaultSessionId: ctx.sessionId,
526
+ defaultInvocationId: ctx.invocationId
527
+ });
528
+ } catch (error) {
529
+ const message = error instanceof Error ? error.message : String(error);
530
+ res.status(400).json({ error: "invalid_request", message });
531
+ return;
532
+ }
533
+ const sessionId = parsed.sessionId;
534
+ const invocationId = parsed.invocationId;
535
+ startSseResponse(res);
536
+ const state = {
537
+ fullText: "",
538
+ invocationId,
539
+ sessionId
540
+ };
541
+ const startedAt = Date.now();
542
+ try {
543
+ let cancelled = false;
544
+ let errorMessage;
545
+ for await (const event of this.broker.invoke(sessionId, {
546
+ message: parsed.message,
547
+ ...parsed.system ? { system: parsed.system } : {},
548
+ ...parsed.approvalAction ? { approvalAction: parsed.approvalAction } : {},
549
+ ...parsed.humanResponse ? { humanResponse: parsed.humanResponse } : {}
550
+ })) {
551
+ if (ctx.signal.aborted) {
552
+ cancelled = true;
553
+ break;
554
+ }
555
+ if (event.type === "error") {
556
+ errorMessage = event.error.message;
557
+ }
558
+ const frame = agentEventToSseFrame(event, state);
559
+ if (frame) {
560
+ res.write(frame);
561
+ }
562
+ }
563
+ if (!cancelled && !res.destroyed) {
564
+ writeDoneFrame(res, state);
565
+ res.end();
566
+ }
567
+ await this.fireOnTurnComplete({
568
+ invocationId,
569
+ sessionId,
570
+ fullText: state.fullText,
571
+ durationMs: Date.now() - startedAt,
572
+ status: cancelled ? "cancelled" : errorMessage ? "error" : "ok",
573
+ ...errorMessage ? { error: errorMessage } : {}
574
+ });
575
+ } catch (error) {
576
+ const message = error instanceof Error ? error.message : String(error);
577
+ if (!res.destroyed) {
578
+ writeErrorFrame(res, message);
579
+ writeDoneFrame(res, state);
580
+ res.end();
581
+ }
582
+ await this.fireOnTurnComplete({
583
+ invocationId,
584
+ sessionId,
585
+ fullText: state.fullText,
586
+ durationMs: Date.now() - startedAt,
587
+ status: "error",
588
+ error: message
589
+ });
590
+ }
591
+ }
592
+ close() {
593
+ this.broker.close();
594
+ }
595
+ async fireOnTurnComplete(summary) {
596
+ if (!this.options.onTurnComplete) return;
597
+ try {
598
+ await this.options.onTurnComplete(summary);
599
+ } catch {
600
+ }
601
+ }
602
+ };
603
+
604
+ export {
605
+ AsyncQueue,
606
+ agentEventToSseFrame,
607
+ coalesceAgentEvents,
608
+ InvocationBroker,
609
+ createInvocationsHandlerForAgent
610
+ };
@@ -0,0 +1,4 @@
1
+ export { CreateInvocationsHandlerOptions, TurnSummary, createInvocationsHandlerForAgent } from './invocations/index.js';
2
+ import '@cuylabs/agent-server';
3
+ import '@cuylabs/agent-foundry-agentserver-invocations';
4
+ import '@cuylabs/agent-core';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ createInvocationsHandlerForAgent
3
+ } from "./chunk-D5U6N54E.js";
4
+ export {
5
+ createInvocationsHandlerForAgent
6
+ };
@@ -0,0 +1,215 @@
1
+ import { InProcessAgentServer } from '@cuylabs/agent-server';
2
+ import { SseInvocationState, InvocationHandler } from '@cuylabs/agent-foundry-agentserver-invocations';
3
+ import { AgentEvent } from '@cuylabs/agent-core';
4
+
5
+ /**
6
+ * Bridge from a `@cuylabs/agent-server` `InProcessAgentServer` to the
7
+ * Foundry Invocations protocol.
8
+ *
9
+ * Lifted from `cdo-ai-companion-foundry-agent/src/foundry/invocation-broker.ts`
10
+ * and generalized so any consumer can drop in their own logger / cancel
11
+ * keywords / waiting messages.
12
+ *
13
+ * State machine (per `agent_session_id`):
14
+ *
15
+ * ┌──── new POST ────► start a new turn → drain events to the SSE stream
16
+ * │
17
+ * │ while a turn is running:
18
+ * │ - `{ message: "cancel" | ... }` → interrupt the turn
19
+ * │ - other `{ message }` → mid-flight steer
20
+ * │ - approval-request open?
21
+ * │ - `{ decision: "allow|deny|remember" }` → resolve
22
+ * │ - other body → "waiting" message
23
+ * │ - human-input-request open?
24
+ * │ - `{ response: "..." }` → resolve
25
+ * │ - other body → "waiting" message
26
+ */
27
+
28
+ interface InvocationBrokerLogger {
29
+ info(message: string, meta?: Record<string, unknown>): void;
30
+ warn(message: string, meta?: Record<string, unknown>): void;
31
+ error(message: string, meta?: Record<string, unknown>): void;
32
+ debug?(message: string, meta?: Record<string, unknown>): void;
33
+ }
34
+ interface InvocationBrokerOptions {
35
+ server: InProcessAgentServer;
36
+ logger?: InvocationBrokerLogger;
37
+ /**
38
+ * Pattern matched against the *full body text* (after `.trim().toLowerCase()`)
39
+ * to detect cancellation messages. Defaults to:
40
+ * `^(cancel|stop|abort|nevermind|never mind|discard|quit)\b[.!?]*$`.
41
+ */
42
+ cancelKeywords?: RegExp;
43
+ /**
44
+ * Override the SSE-stream messages used when the broker has to emit an
45
+ * immediate text reply (waiting for input, cancel acknowledgments, etc.).
46
+ */
47
+ messages?: Partial<InvocationBrokerMessages>;
48
+ }
49
+ interface InvocationBrokerMessages {
50
+ emptyStartBody: string;
51
+ cancelAcknowledged: string;
52
+ cancelAlreadyDone: string;
53
+ approvalWaiting: string;
54
+ humanInputWaiting: string;
55
+ pendingInputExpired: string;
56
+ steerAccepted: string;
57
+ steerRejected: string;
58
+ steerSendNewMessage: string;
59
+ cannotSteerSendCancel: string;
60
+ busyTurn: string;
61
+ }
62
+ interface InvocationBrokerInput {
63
+ /** Free-form user message; canonical for "start a new turn" and steering. */
64
+ message?: string;
65
+ /** Optional system prompt override applied at turn start. */
66
+ system?: string;
67
+ /** Resolved approval action for an open approval-request. */
68
+ approvalAction?: "allow" | "deny" | "remember";
69
+ /** Resolved human response for an open human-input-request. */
70
+ humanResponse?: string;
71
+ }
72
+ /**
73
+ * Keeps track of active turns across sessions, subscribes to the
74
+ * `InProcessAgentServer` notification stream, and exposes an async
75
+ * iterable of `AgentEvent`s per `invoke()` call.
76
+ */
77
+ declare class InvocationBroker {
78
+ private readonly activeTurns;
79
+ private readonly activeTurnsBySession;
80
+ private readonly logger;
81
+ private readonly server;
82
+ private readonly cancelKeywords;
83
+ private readonly messages;
84
+ private readonly unsubscribe;
85
+ constructor(options: InvocationBrokerOptions);
86
+ invoke(sessionId: string, input: InvocationBrokerInput): AsyncGenerator<AgentEvent>;
87
+ close(): void;
88
+ private invokeActiveTurn;
89
+ private drainActiveTurn;
90
+ private handleNotification;
91
+ private routeTurnEvent;
92
+ private replayExistingEvents;
93
+ private interruptActiveTurn;
94
+ private recordEvent;
95
+ private logTurnSummary;
96
+ private waitingMessage;
97
+ private isCancelMessage;
98
+ }
99
+
100
+ /**
101
+ * Lifted from `cdo-ai-companion-foundry-agent/src/streaming/async-queue.ts` —
102
+ * the same shape, with the same coalesce hook used to merge consecutive
103
+ * `text-delta` events into a single SSE frame.
104
+ *
105
+ * Used internally by the agent-core invocation broker. Exported here so
106
+ * advanced consumers of the bridge can reuse the queue if they want to
107
+ * extend the broker.
108
+ */
109
+ declare class AsyncQueue<T> implements AsyncIterable<T> {
110
+ private values;
111
+ private waiters;
112
+ private closed;
113
+ push(value: T, coalesce?: (previous: T, next: T) => T | undefined): void;
114
+ close(): void;
115
+ reset(): void;
116
+ [Symbol.asyncIterator](): AsyncIterator<T>;
117
+ }
118
+
119
+ /**
120
+ * Translate `agent-core` `AgentEvent`s into Foundry Invocations SSE frames.
121
+ *
122
+ * Lifted from `cdo-ai-companion-foundry-agent/src/foundry/sse.ts` and
123
+ * generalized:
124
+ *
125
+ * - The frame shapes (`{ type: "token", content }`, `{ type: "tool_start", ... }`,
126
+ * `{ type: "approval_required", ... }`, `{ type: "input_required", ... }`,
127
+ * `{ type: "agent_event", event_type }`) match the Python and C#
128
+ * `bring-your-own/invocations` reference handlers byte-for-byte.
129
+ * - The `done` frame is emitted by the low-level agentserver invocations
130
+ * package.
131
+ */
132
+
133
+ /**
134
+ * Encode an `AgentEvent` as a single SSE frame string. Returns `undefined`
135
+ * for events that should not be forwarded (currently `complete`, which is
136
+ * collapsed into the terminal `done` frame).
137
+ */
138
+ declare function agentEventToSseFrame(event: AgentEvent, state: SseInvocationState): string | undefined;
139
+ /** Coalesce consecutive `text-delta` events when the SSE consumer is slow. */
140
+ declare function coalesceAgentEvents(previous: AgentEvent, next: AgentEvent): AgentEvent | undefined;
141
+
142
+ /**
143
+ * @cuylabs/agent-foundry-hosting/invocations
144
+ *
145
+ * Bridge from a `@cuylabs/agent-server` `InProcessAgentServer` to the
146
+ * Foundry Invocations protocol. Returns a ready-to-use
147
+ * `InvocationHandler` that handles multi-turn conversation, mid-flight
148
+ * steering, cancellation, and HITL approval / human-input flows.
149
+ *
150
+ * ## Quick start
151
+ *
152
+ * import { runInvocationsServer } from "@cuylabs/agent-foundry-agentserver-invocations";
153
+ * import { createInvocationsHandlerForAgent } from "@cuylabs/agent-foundry-hosting/invocations";
154
+ * import {
155
+ * createAgentServerAdapter,
156
+ * InProcessAgentServer,
157
+ * } from "@cuylabs/agent-server";
158
+ *
159
+ * const server = new InProcessAgentServer(createAgentServerAdapter(myAgent));
160
+ *
161
+ * await runInvocationsServer({
162
+ * handler: createInvocationsHandlerForAgent(server),
163
+ * port: 8088,
164
+ * });
165
+ *
166
+ * The handler:
167
+ *
168
+ * - Streams `agent-core` events as SSE (`{ type: "token", content }`,
169
+ * `{ type: "tool_start", ... }`, etc).
170
+ * - Emits a terminal `{ type: "done", invocation_id, session_id, full_text }`
171
+ * frame matching the Python and C# reference samples.
172
+ * - Routes `{ "decision": "allow|deny|remember" }` bodies to any open
173
+ * `approval-request`.
174
+ * - Routes `{ "response": "..." }` bodies to any open `human-input-request`.
175
+ * - Cancels a running turn when the body is `cancel`/`stop`/`abort`/etc.
176
+ */
177
+
178
+ interface CreateInvocationsHandlerOptions {
179
+ /** Logger used by the broker. Defaults to a silent logger. */
180
+ logger?: InvocationBrokerLogger;
181
+ /**
182
+ * Replace the default cancel pattern. The pattern is matched against the
183
+ * lowercased trimmed body text.
184
+ */
185
+ cancelKeywords?: RegExp;
186
+ /**
187
+ * Override the broker's "waiting" / cancel-acknowledgment / steer reply
188
+ * messages. Useful for localization or tone matching.
189
+ */
190
+ messages?: Partial<InvocationBrokerMessages>;
191
+ /**
192
+ * Optional callback invoked at the end of every invocation with a summary
193
+ * suitable for telemetry. Errors thrown here are swallowed.
194
+ */
195
+ onTurnComplete?: (summary: TurnSummary) => void | Promise<void>;
196
+ }
197
+ interface TurnSummary {
198
+ invocationId: string;
199
+ sessionId: string;
200
+ fullText: string;
201
+ durationMs: number;
202
+ status: "ok" | "error" | "cancelled";
203
+ error?: string;
204
+ }
205
+ /**
206
+ * Build an `InvocationHandler` that drives an `InProcessAgentServer` over
207
+ * the Foundry Invocations protocol.
208
+ *
209
+ * The same broker instance is shared across requests so the multi-turn
210
+ * state (active turn per session, pending HITL inputs) survives between
211
+ * `POST /invocations` calls.
212
+ */
213
+ declare function createInvocationsHandlerForAgent(server: InProcessAgentServer, options?: CreateInvocationsHandlerOptions): InvocationHandler;
214
+
215
+ export { AsyncQueue, type CreateInvocationsHandlerOptions, InvocationBroker, type InvocationBrokerInput, type InvocationBrokerLogger, type InvocationBrokerMessages, type InvocationBrokerOptions, type TurnSummary, agentEventToSseFrame, coalesceAgentEvents, createInvocationsHandlerForAgent };
@@ -0,0 +1,14 @@
1
+ import {
2
+ AsyncQueue,
3
+ InvocationBroker,
4
+ agentEventToSseFrame,
5
+ coalesceAgentEvents,
6
+ createInvocationsHandlerForAgent
7
+ } from "../chunk-D5U6N54E.js";
8
+ export {
9
+ AsyncQueue,
10
+ InvocationBroker,
11
+ agentEventToSseFrame,
12
+ coalesceAgentEvents,
13
+ createInvocationsHandlerForAgent
14
+ };
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@cuylabs/agent-foundry-hosting",
3
+ "version": "4.1.0",
4
+ "description": "Foundry Hosting integration for @cuylabs/agent-core (agent-core ↔ Invocations protocol bridge; mirrors agent-framework-foundry-hosting)",
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
+ "./invocations": {
15
+ "types": "./dist/invocations/index.d.ts",
16
+ "import": "./dist/invocations/index.js",
17
+ "default": "./dist/invocations/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "README.md"
23
+ ],
24
+ "devDependencies": {
25
+ "@types/express": "^5.0.0",
26
+ "@types/node": "^22.0.0",
27
+ "tsup": "^8.0.0",
28
+ "typescript": "^5.7.0",
29
+ "vitest": "^4.0.18",
30
+ "@cuylabs/agent-core": "^4.1.0",
31
+ "@cuylabs/agent-server": "^4.1.0",
32
+ "@cuylabs/agent-foundry-agentserver-invocations": "^4.1.0"
33
+ },
34
+ "peerDependencies": {
35
+ "@cuylabs/agent-core": "^4.1.0",
36
+ "@cuylabs/agent-server": "^4.1.0",
37
+ "@cuylabs/agent-foundry-agentserver-invocations": "^4.1.0"
38
+ },
39
+ "keywords": [
40
+ "agent",
41
+ "azure",
42
+ "foundry",
43
+ "hosted-agent",
44
+ "agent-framework",
45
+ "invocations-protocol"
46
+ ],
47
+ "author": "cuylabs",
48
+ "license": "Apache-2.0",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "https://github.com/cuylabs-ai/agents-ts.git",
52
+ "directory": "packages/agent-foundry-hosting"
53
+ },
54
+ "engines": {
55
+ "node": ">=20"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ },
60
+ "scripts": {
61
+ "build": "tsup src/index.ts src/invocations/index.ts --format esm --dts --clean",
62
+ "dev": "tsup src/index.ts src/invocations/index.ts --format esm --dts --watch",
63
+ "typecheck": "tsc --noEmit",
64
+ "test": "vitest run",
65
+ "test:watch": "vitest",
66
+ "clean": "rm -rf dist"
67
+ }
68
+ }