alibabacloud-agentcore-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +189 -0
- package/dist/access-key-CkoHq3S8.d.cts +30 -0
- package/dist/access-key-CkoHq3S8.d.ts +30 -0
- package/dist/agent-sa-token-DD1Sb8P1.d.cts +14 -0
- package/dist/agent-sa-token-DD1Sb8P1.d.ts +14 -0
- package/dist/auth/index.cjs +36 -0
- package/dist/auth/index.cjs.map +1 -0
- package/dist/auth/index.d.cts +34 -0
- package/dist/auth/index.d.ts +34 -0
- package/dist/auth/index.js +36 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/bound-credentials-C1fM0thh.d.cts +39 -0
- package/dist/bound-credentials-DqT64Q2s.d.ts +39 -0
- package/dist/chunk-2E5EWEDG.cjs +142 -0
- package/dist/chunk-2E5EWEDG.cjs.map +1 -0
- package/dist/chunk-55XZZRKO.js +220 -0
- package/dist/chunk-55XZZRKO.js.map +1 -0
- package/dist/chunk-5JXA7JPS.js +29 -0
- package/dist/chunk-5JXA7JPS.js.map +1 -0
- package/dist/chunk-5RKN46UU.cjs +139 -0
- package/dist/chunk-5RKN46UU.cjs.map +1 -0
- package/dist/chunk-5ZOLHQXO.js +296 -0
- package/dist/chunk-5ZOLHQXO.js.map +1 -0
- package/dist/chunk-7Y263YIW.js +298 -0
- package/dist/chunk-7Y263YIW.js.map +1 -0
- package/dist/chunk-A3PF2SPD.cjs +141 -0
- package/dist/chunk-A3PF2SPD.cjs.map +1 -0
- package/dist/chunk-A3WMLVJC.cjs +141 -0
- package/dist/chunk-A3WMLVJC.cjs.map +1 -0
- package/dist/chunk-BVZ7H2F5.cjs +582 -0
- package/dist/chunk-BVZ7H2F5.cjs.map +1 -0
- package/dist/chunk-EGUKJE3Z.cjs +24 -0
- package/dist/chunk-EGUKJE3Z.cjs.map +1 -0
- package/dist/chunk-EKXZKKJJ.js +24 -0
- package/dist/chunk-EKXZKKJJ.js.map +1 -0
- package/dist/chunk-GYLT23D3.js +110 -0
- package/dist/chunk-GYLT23D3.js.map +1 -0
- package/dist/chunk-IF7LMBXC.js +306 -0
- package/dist/chunk-IF7LMBXC.js.map +1 -0
- package/dist/chunk-IUCLCPVV.js +113 -0
- package/dist/chunk-IUCLCPVV.js.map +1 -0
- package/dist/chunk-JSP7ZROS.cjs +95 -0
- package/dist/chunk-JSP7ZROS.cjs.map +1 -0
- package/dist/chunk-JW62DVIC.js +238 -0
- package/dist/chunk-JW62DVIC.js.map +1 -0
- package/dist/chunk-K3TE7625.js +139 -0
- package/dist/chunk-K3TE7625.js.map +1 -0
- package/dist/chunk-LE5P3SJW.cjs +16 -0
- package/dist/chunk-LE5P3SJW.cjs.map +1 -0
- package/dist/chunk-LXHW6OT4.cjs +77 -0
- package/dist/chunk-LXHW6OT4.cjs.map +1 -0
- package/dist/chunk-MICRSJ6R.js +48 -0
- package/dist/chunk-MICRSJ6R.js.map +1 -0
- package/dist/chunk-MWAHO47B.cjs +220 -0
- package/dist/chunk-MWAHO47B.cjs.map +1 -0
- package/dist/chunk-MZ5UWGXS.js +95 -0
- package/dist/chunk-MZ5UWGXS.js.map +1 -0
- package/dist/chunk-NZL3VPJ2.js +16 -0
- package/dist/chunk-NZL3VPJ2.js.map +1 -0
- package/dist/chunk-PC4FM2RP.cjs +180 -0
- package/dist/chunk-PC4FM2RP.cjs.map +1 -0
- package/dist/chunk-PKYET77D.cjs +296 -0
- package/dist/chunk-PKYET77D.cjs.map +1 -0
- package/dist/chunk-PTJPB27L.js +31 -0
- package/dist/chunk-PTJPB27L.js.map +1 -0
- package/dist/chunk-QIZO3A4Y.cjs +306 -0
- package/dist/chunk-QIZO3A4Y.cjs.map +1 -0
- package/dist/chunk-RBAY4MO2.js +202 -0
- package/dist/chunk-RBAY4MO2.js.map +1 -0
- package/dist/chunk-RHY7Y43E.js +582 -0
- package/dist/chunk-RHY7Y43E.js.map +1 -0
- package/dist/chunk-RQRI6RCG.cjs +238 -0
- package/dist/chunk-RQRI6RCG.cjs.map +1 -0
- package/dist/chunk-RYXL25AI.js +141 -0
- package/dist/chunk-RYXL25AI.js.map +1 -0
- package/dist/chunk-RZNQGEGJ.cjs +113 -0
- package/dist/chunk-RZNQGEGJ.cjs.map +1 -0
- package/dist/chunk-S7PWSJNP.cjs +48 -0
- package/dist/chunk-S7PWSJNP.cjs.map +1 -0
- package/dist/chunk-TWEO5XVM.cjs +298 -0
- package/dist/chunk-TWEO5XVM.cjs.map +1 -0
- package/dist/chunk-UBP5CHU7.js +142 -0
- package/dist/chunk-UBP5CHU7.js.map +1 -0
- package/dist/chunk-ULJTQSLE.cjs +35 -0
- package/dist/chunk-ULJTQSLE.cjs.map +1 -0
- package/dist/chunk-UWPKFJYM.js +77 -0
- package/dist/chunk-UWPKFJYM.js.map +1 -0
- package/dist/chunk-WKZUYPDS.js +180 -0
- package/dist/chunk-WKZUYPDS.js.map +1 -0
- package/dist/chunk-YZP55W7S.cjs +29 -0
- package/dist/chunk-YZP55W7S.cjs.map +1 -0
- package/dist/chunk-ZELRQU4J.cjs +31 -0
- package/dist/chunk-ZELRQU4J.cjs.map +1 -0
- package/dist/chunk-ZLKYXRNM.js +141 -0
- package/dist/chunk-ZLKYXRNM.js.map +1 -0
- package/dist/chunk-ZLQ2IBTC.cjs +110 -0
- package/dist/chunk-ZLQ2IBTC.cjs.map +1 -0
- package/dist/chunk-ZTWLCHCO.cjs +202 -0
- package/dist/chunk-ZTWLCHCO.cjs.map +1 -0
- package/dist/chunk-ZWQBAJ5O.js +35 -0
- package/dist/chunk-ZWQBAJ5O.js.map +1 -0
- package/dist/client-DDU4-ygJ.d.cts +72 -0
- package/dist/client-pDzS7EZR.d.ts +72 -0
- package/dist/collaboration/index.cjs +44 -0
- package/dist/collaboration/index.cjs.map +1 -0
- package/dist/collaboration/index.d.cts +73 -0
- package/dist/collaboration/index.d.ts +73 -0
- package/dist/collaboration/index.js +44 -0
- package/dist/collaboration/index.js.map +1 -0
- package/dist/common-BSXkQfxI.d.cts +25 -0
- package/dist/common-BSXkQfxI.d.ts +25 -0
- package/dist/common-DRdI-75k.d.ts +8 -0
- package/dist/common-_vxreiEW.d.cts +8 -0
- package/dist/config-CMkmMtx1.d.cts +20 -0
- package/dist/config-CMkmMtx1.d.ts +20 -0
- package/dist/context-M9rOTifU.d.cts +12 -0
- package/dist/context-M9rOTifU.d.ts +12 -0
- package/dist/controller-DWs3Sy04.d.cts +9 -0
- package/dist/controller-DmI4L4sP.d.ts +9 -0
- package/dist/controlplane/index.cjs +13 -0
- package/dist/controlplane/index.cjs.map +1 -0
- package/dist/controlplane/index.d.cts +66 -0
- package/dist/controlplane/index.d.ts +66 -0
- package/dist/controlplane/index.js +13 -0
- package/dist/controlplane/index.js.map +1 -0
- package/dist/errors-BjGO6N10.d.ts +93 -0
- package/dist/errors-D9OtcR-o.d.cts +93 -0
- package/dist/event-converters-BIn8odqo.d.ts +38 -0
- package/dist/event-converters-Cn_NeGyQ.d.cts +38 -0
- package/dist/google-adk-model-N47R7GB2.js +208 -0
- package/dist/google-adk-model-N47R7GB2.js.map +1 -0
- package/dist/google-adk-model-PDBKY5YZ.cjs +208 -0
- package/dist/google-adk-model-PDBKY5YZ.cjs.map +1 -0
- package/dist/index.cjs +322 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +78 -0
- package/dist/index.d.ts +78 -0
- package/dist/index.js +322 -0
- package/dist/index.js.map +1 -0
- package/dist/integrations/ai-sdk.cjs +15 -0
- package/dist/integrations/ai-sdk.cjs.map +1 -0
- package/dist/integrations/ai-sdk.d.cts +21 -0
- package/dist/integrations/ai-sdk.d.ts +21 -0
- package/dist/integrations/ai-sdk.js +15 -0
- package/dist/integrations/ai-sdk.js.map +1 -0
- package/dist/integrations/google-adk.cjs +90 -0
- package/dist/integrations/google-adk.cjs.map +1 -0
- package/dist/integrations/google-adk.d.cts +46 -0
- package/dist/integrations/google-adk.d.ts +46 -0
- package/dist/integrations/google-adk.js +90 -0
- package/dist/integrations/google-adk.js.map +1 -0
- package/dist/integrations/langchain.cjs +95 -0
- package/dist/integrations/langchain.cjs.map +1 -0
- package/dist/integrations/langchain.d.cts +52 -0
- package/dist/integrations/langchain.d.ts +52 -0
- package/dist/integrations/langchain.js +95 -0
- package/dist/integrations/langchain.js.map +1 -0
- package/dist/integrations/langgraph.cjs +30 -0
- package/dist/integrations/langgraph.cjs.map +1 -0
- package/dist/integrations/langgraph.d.cts +53 -0
- package/dist/integrations/langgraph.d.ts +53 -0
- package/dist/integrations/langgraph.js +30 -0
- package/dist/integrations/langgraph.js.map +1 -0
- package/dist/integrations/mastra.cjs +108 -0
- package/dist/integrations/mastra.cjs.map +1 -0
- package/dist/integrations/mastra.d.cts +47 -0
- package/dist/integrations/mastra.d.ts +47 -0
- package/dist/integrations/mastra.js +108 -0
- package/dist/integrations/mastra.js.map +1 -0
- package/dist/langchain-adapter-DFJdEX04.d.cts +47 -0
- package/dist/langchain-adapter-DJsyjm5V.d.ts +47 -0
- package/dist/langchain-provider-NF5GIDQV.cjs +227 -0
- package/dist/langchain-provider-NF5GIDQV.cjs.map +1 -0
- package/dist/langchain-provider-PHL4UWNF.js +227 -0
- package/dist/langchain-provider-PHL4UWNF.js.map +1 -0
- package/dist/loader-DrIQ37nm.d.ts +38 -0
- package/dist/loader-eWuJ2GSL.d.cts +38 -0
- package/dist/logging-C8GLLg1f.d.cts +9 -0
- package/dist/logging-C8GLLg1f.d.ts +9 -0
- package/dist/managed-CwLx9h4C.d.cts +32 -0
- package/dist/managed-D9eQK1ut.d.ts +32 -0
- package/dist/mcp/index.cjs +12 -0
- package/dist/mcp/index.cjs.map +1 -0
- package/dist/mcp/index.d.cts +62 -0
- package/dist/mcp/index.d.ts +62 -0
- package/dist/mcp/index.js +12 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/memory/index.cjs +12 -0
- package/dist/memory/index.cjs.map +1 -0
- package/dist/memory/index.d.cts +113 -0
- package/dist/memory/index.d.ts +113 -0
- package/dist/memory/index.js +12 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/model/index.cjs +16 -0
- package/dist/model/index.cjs.map +1 -0
- package/dist/model/index.d.cts +129 -0
- package/dist/model/index.d.ts +129 -0
- package/dist/model/index.js +16 -0
- package/dist/model/index.js.map +1 -0
- package/dist/model-CkYHzHPk.d.cts +50 -0
- package/dist/model-CkYHzHPk.d.ts +50 -0
- package/dist/runtime/index.cjs +49 -0
- package/dist/runtime/index.cjs.map +1 -0
- package/dist/runtime/index.d.cts +73 -0
- package/dist/runtime/index.d.ts +73 -0
- package/dist/runtime/index.js +49 -0
- package/dist/runtime/index.js.map +1 -0
- package/dist/server/index.cjs +604 -0
- package/dist/server/index.cjs.map +1 -0
- package/dist/server/index.d.cts +69 -0
- package/dist/server/index.d.ts +69 -0
- package/dist/server/index.js +604 -0
- package/dist/server/index.js.map +1 -0
- package/dist/skill/index.cjs +14 -0
- package/dist/skill/index.cjs.map +1 -0
- package/dist/skill/index.d.cts +16 -0
- package/dist/skill/index.d.ts +16 -0
- package/dist/skill/index.js +14 -0
- package/dist/skill/index.js.map +1 -0
- package/package.json +292 -0
|
@@ -0,0 +1,604 @@
|
|
|
1
|
+
import {
|
|
2
|
+
RequestContext,
|
|
3
|
+
useContext
|
|
4
|
+
} from "../chunk-ZWQBAJ5O.js";
|
|
5
|
+
import {
|
|
6
|
+
parseCollaborationContext,
|
|
7
|
+
useCollaborationContext
|
|
8
|
+
} from "../chunk-RYXL25AI.js";
|
|
9
|
+
import {
|
|
10
|
+
nullLogger
|
|
11
|
+
} from "../chunk-NZL3VPJ2.js";
|
|
12
|
+
import {
|
|
13
|
+
AgentEvent,
|
|
14
|
+
EventType
|
|
15
|
+
} from "../chunk-PTJPB27L.js";
|
|
16
|
+
import {
|
|
17
|
+
AgentCoreError,
|
|
18
|
+
ConfigError,
|
|
19
|
+
ContextError
|
|
20
|
+
} from "../chunk-MZ5UWGXS.js";
|
|
21
|
+
|
|
22
|
+
// src/server/app.ts
|
|
23
|
+
import { Hono as Hono3 } from "hono";
|
|
24
|
+
import { serve } from "@hono/node-server";
|
|
25
|
+
|
|
26
|
+
// src/server/invoker.ts
|
|
27
|
+
var AgentInvoker = class {
|
|
28
|
+
constructor(handler, logger = nullLogger) {
|
|
29
|
+
this.handler = handler;
|
|
30
|
+
this.logger = logger;
|
|
31
|
+
}
|
|
32
|
+
handler;
|
|
33
|
+
logger;
|
|
34
|
+
get configured() {
|
|
35
|
+
return this.handler !== void 0;
|
|
36
|
+
}
|
|
37
|
+
setHandler(handler) {
|
|
38
|
+
this.handler = handler;
|
|
39
|
+
}
|
|
40
|
+
async *invokeStream(request) {
|
|
41
|
+
if (!this.handler) throw new Error("AgentCore handler is not configured");
|
|
42
|
+
const context = new RequestContext(Object.fromEntries(request.rawRequest.headers));
|
|
43
|
+
const fields = {
|
|
44
|
+
protocol: request.protocol,
|
|
45
|
+
requestId: context.headers["x-request-id"],
|
|
46
|
+
sessionId: context.headers["x-agentcore-session-id"]
|
|
47
|
+
};
|
|
48
|
+
this.logger.info("agentcore.server.invoke.started", fields);
|
|
49
|
+
try {
|
|
50
|
+
request.signal.throwIfAborted();
|
|
51
|
+
const collaboration = parseCollaborationContext(context.headers);
|
|
52
|
+
const run = (callback) => useContext(context, () => useCollaborationContext(collaboration, callback));
|
|
53
|
+
const result = await run(() => this.handler(request, context));
|
|
54
|
+
const iterator = iterate(result)[Symbol.asyncIterator]();
|
|
55
|
+
try {
|
|
56
|
+
for (; ; ) {
|
|
57
|
+
request.signal.throwIfAborted();
|
|
58
|
+
const item = await run(() => iterator.next());
|
|
59
|
+
if (item.done) break;
|
|
60
|
+
request.signal.throwIfAborted();
|
|
61
|
+
const event = normalize(item.value);
|
|
62
|
+
if (event) yield event;
|
|
63
|
+
}
|
|
64
|
+
} finally {
|
|
65
|
+
await run(() => iterator.return?.(void 0));
|
|
66
|
+
}
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (request.signal.aborted) this.logger.info("agentcore.server.invoke.cancelled", fields);
|
|
69
|
+
else this.logger.error("agentcore.server.invoke.failed", { ...fields, ...failureFields(error) });
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
this.logger.info("agentcore.server.invoke.succeeded", fields);
|
|
73
|
+
}
|
|
74
|
+
async invoke(request) {
|
|
75
|
+
const events = [];
|
|
76
|
+
for await (const event of this.invokeStream(request)) events.push(event);
|
|
77
|
+
return events;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
async function* iterate(result) {
|
|
81
|
+
if (result != null && typeof result === "object" && Symbol.asyncIterator in result) yield* result;
|
|
82
|
+
else if (result != null && typeof result === "object" && Symbol.iterator in result) yield* result;
|
|
83
|
+
else yield result;
|
|
84
|
+
}
|
|
85
|
+
function normalize(value) {
|
|
86
|
+
if (value == null || value === "") return;
|
|
87
|
+
if (typeof value === "string") return new AgentEvent(EventType.TEXT, { delta: value });
|
|
88
|
+
if (!(value instanceof AgentEvent)) throw new TypeError("handler must return text, AgentEvent, or an event iterable");
|
|
89
|
+
if (value.event !== EventType.TOOL_CALL) return value;
|
|
90
|
+
const args = value.data.args ?? "";
|
|
91
|
+
return new AgentEvent(EventType.TOOL_CALL_CHUNK, {
|
|
92
|
+
id: value.data.id ?? "",
|
|
93
|
+
name: value.data.name ?? "",
|
|
94
|
+
args_delta: typeof args === "string" ? args : JSON.stringify(args)
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
function errorCode(error) {
|
|
98
|
+
return error instanceof AgentCoreError ? error.code : "INTERNAL_ERROR";
|
|
99
|
+
}
|
|
100
|
+
function failureFields(error) {
|
|
101
|
+
return {
|
|
102
|
+
code: errorCode(error),
|
|
103
|
+
errorType: error instanceof Error ? error.name : typeof error,
|
|
104
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
105
|
+
stack: error instanceof Error ? error.stack : void 0
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/server/openai.ts
|
|
110
|
+
import { randomUUID } from "crypto";
|
|
111
|
+
import { Hono } from "hono";
|
|
112
|
+
|
|
113
|
+
// src/server/sse.ts
|
|
114
|
+
import { streamSSE } from "hono/streaming";
|
|
115
|
+
var HEARTBEAT_INTERVAL_MS = 15e3;
|
|
116
|
+
function sse(value) {
|
|
117
|
+
return `data: ${JSON.stringify(value)}
|
|
118
|
+
|
|
119
|
+
`;
|
|
120
|
+
}
|
|
121
|
+
async function* withHeartbeat(source) {
|
|
122
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
123
|
+
let pending = iterator.next();
|
|
124
|
+
try {
|
|
125
|
+
for (; ; ) {
|
|
126
|
+
let timer;
|
|
127
|
+
const heartbeat = /* @__PURE__ */ Symbol();
|
|
128
|
+
const tick = new Promise((resolve) => {
|
|
129
|
+
timer = setTimeout(() => resolve(heartbeat), HEARTBEAT_INTERVAL_MS);
|
|
130
|
+
});
|
|
131
|
+
let item;
|
|
132
|
+
try {
|
|
133
|
+
item = await Promise.race([pending, tick]);
|
|
134
|
+
} finally {
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
}
|
|
137
|
+
if (item === heartbeat) {
|
|
138
|
+
yield ": ping\n\n";
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (item.done) return;
|
|
142
|
+
yield item.value;
|
|
143
|
+
pending = iterator.next();
|
|
144
|
+
}
|
|
145
|
+
} finally {
|
|
146
|
+
await iterator.return?.();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function eventStream(c, producer) {
|
|
150
|
+
c.header("X-Accel-Buffering", "no");
|
|
151
|
+
return streamSSE(c, async (stream) => {
|
|
152
|
+
const cancelled = new AbortController();
|
|
153
|
+
stream.onAbort(() => cancelled.abort());
|
|
154
|
+
const signal = AbortSignal.any([c.req.raw.signal, cancelled.signal]);
|
|
155
|
+
try {
|
|
156
|
+
for await (const frame of withHeartbeat(producer(signal))) {
|
|
157
|
+
if (signal.aborted) break;
|
|
158
|
+
await stream.write(frame);
|
|
159
|
+
}
|
|
160
|
+
} catch (error) {
|
|
161
|
+
if (!signal.aborted) throw error;
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/server/openai.ts
|
|
167
|
+
var OpenAIProtocolHandler = class {
|
|
168
|
+
constructor(prefix = "/openai/v1", modelName = "agentcore") {
|
|
169
|
+
this.prefix = prefix;
|
|
170
|
+
this.modelName = modelName;
|
|
171
|
+
}
|
|
172
|
+
prefix;
|
|
173
|
+
modelName;
|
|
174
|
+
name = "openai_chat_completions";
|
|
175
|
+
routes(invoker) {
|
|
176
|
+
const app = new Hono();
|
|
177
|
+
app.get(`${this.prefix}/models`, (c) => c.json({ object: "list", data: [{
|
|
178
|
+
id: this.modelName,
|
|
179
|
+
object: "model",
|
|
180
|
+
created: Math.floor(Date.now() / 1e3),
|
|
181
|
+
owned_by: "agentcore"
|
|
182
|
+
}] }));
|
|
183
|
+
app.post(`${this.prefix}/chat/completions`, async (c) => {
|
|
184
|
+
if (!invoker.configured) return c.json({ error: { message: "handler is not configured", type: "server_error" } }, 503);
|
|
185
|
+
let request;
|
|
186
|
+
try {
|
|
187
|
+
request = parseOpenAI(c.req.raw, await c.req.json());
|
|
188
|
+
} catch {
|
|
189
|
+
return c.json({ error: { message: "invalid request", type: "invalid_request_error" } }, 400);
|
|
190
|
+
}
|
|
191
|
+
const model = text(request.rawPayload.model) || this.modelName;
|
|
192
|
+
if (request.stream) return eventStream(c, (signal) => formatStream(invoker, { ...request, signal }, model));
|
|
193
|
+
try {
|
|
194
|
+
const state = new CompletionState();
|
|
195
|
+
for (const event of await invoker.invoke(request)) {
|
|
196
|
+
if (event.event === EventType.ERROR) throw new Error("agent reported an error");
|
|
197
|
+
state.consume(event);
|
|
198
|
+
}
|
|
199
|
+
return c.json({ ...completion(model), object: "chat.completion", choices: [{
|
|
200
|
+
index: 0,
|
|
201
|
+
message: {
|
|
202
|
+
role: "assistant",
|
|
203
|
+
content: state.content.join("") || null,
|
|
204
|
+
...state.reasoning.length ? { reasoning_content: state.reasoning.join("") } : {},
|
|
205
|
+
...state.calls.size ? { tool_calls: [...state.calls.values()].map(({ id, name, args }) => ({
|
|
206
|
+
id,
|
|
207
|
+
type: "function",
|
|
208
|
+
function: { name, arguments: args }
|
|
209
|
+
})) } : {}
|
|
210
|
+
},
|
|
211
|
+
finish_reason: state.finishReason
|
|
212
|
+
}] });
|
|
213
|
+
} catch (error) {
|
|
214
|
+
const invalid = error instanceof ConfigError || error instanceof ContextError;
|
|
215
|
+
return c.json(
|
|
216
|
+
{ error: {
|
|
217
|
+
message: error instanceof AgentCoreError ? error.message : "handler failed",
|
|
218
|
+
type: invalid ? "invalid_request_error" : "server_error",
|
|
219
|
+
code: errorCode(error)
|
|
220
|
+
} },
|
|
221
|
+
invalid ? 400 : error instanceof AgentCoreError ? 502 : 500
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
return app;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
function parseOpenAI(rawRequest, value) {
|
|
229
|
+
const payload = object(value);
|
|
230
|
+
if (!Array.isArray(payload.messages)) throw new Error("messages must be an array");
|
|
231
|
+
const messages = payload.messages.map((value2) => {
|
|
232
|
+
const item = object(value2);
|
|
233
|
+
if (!["developer", "system", "user", "assistant", "tool"].includes(String(item.role))) throw new Error("invalid role");
|
|
234
|
+
let toolCalls;
|
|
235
|
+
if (item.tool_calls != null) {
|
|
236
|
+
if (!Array.isArray(item.tool_calls)) throw new Error("invalid tool_calls");
|
|
237
|
+
toolCalls = item.tool_calls.map((value3) => {
|
|
238
|
+
const call = object(value3);
|
|
239
|
+
if (!text(call.id)) throw new Error("tool id is required");
|
|
240
|
+
return { id: call.id, type: text(call.type) || "function", function: object(call.function) };
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
return {
|
|
244
|
+
role: item.role,
|
|
245
|
+
content: item.content,
|
|
246
|
+
id: text(item.id),
|
|
247
|
+
name: text(item.name),
|
|
248
|
+
toolCalls,
|
|
249
|
+
toolCallId: text(item.tool_call_id)
|
|
250
|
+
};
|
|
251
|
+
});
|
|
252
|
+
let tools;
|
|
253
|
+
if (payload.tools != null) {
|
|
254
|
+
if (!Array.isArray(payload.tools)) throw new Error("tools must be an array");
|
|
255
|
+
tools = payload.tools.map((value2) => {
|
|
256
|
+
const item = object(value2), fn = object(item.function);
|
|
257
|
+
if ((item.type ?? "function") !== "function" || !text(fn.name)) throw new Error("invalid function tool");
|
|
258
|
+
if (fn.description !== void 0 && typeof fn.description !== "string") throw new Error("invalid description");
|
|
259
|
+
return { name: fn.name, description: fn.description ?? "", parameters: object(fn.parameters ?? {}) };
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
return {
|
|
263
|
+
protocol: "openai",
|
|
264
|
+
messages,
|
|
265
|
+
tools,
|
|
266
|
+
stream: payload.stream === true,
|
|
267
|
+
rawRequest,
|
|
268
|
+
rawPayload: payload,
|
|
269
|
+
signal: rawRequest.signal
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
function object(value) {
|
|
273
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("object required");
|
|
274
|
+
return value;
|
|
275
|
+
}
|
|
276
|
+
function text(value) {
|
|
277
|
+
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
278
|
+
}
|
|
279
|
+
function completion(model) {
|
|
280
|
+
return { id: `chatcmpl-${randomUUID()}`, created: Math.floor(Date.now() / 1e3), model };
|
|
281
|
+
}
|
|
282
|
+
var CompletionState = class {
|
|
283
|
+
content = [];
|
|
284
|
+
reasoning = [];
|
|
285
|
+
calls = /* @__PURE__ */ new Map();
|
|
286
|
+
get finishReason() {
|
|
287
|
+
return this.calls.size ? "tool_calls" : "stop";
|
|
288
|
+
}
|
|
289
|
+
consume(event) {
|
|
290
|
+
const data = event.data;
|
|
291
|
+
if (event.event === EventType.TEXT || event.event === EventType.REASONING) {
|
|
292
|
+
if (typeof data.delta !== "string" || !data.delta) return [];
|
|
293
|
+
(event.event === EventType.TEXT ? this.content : this.reasoning).push(data.delta);
|
|
294
|
+
return [{ [event.event === EventType.TEXT ? "content" : "reasoning_content"]: data.delta }];
|
|
295
|
+
}
|
|
296
|
+
if (event.event !== EventType.TOOL_CALL_CHUNK || typeof data.id !== "string" || !data.id) return [];
|
|
297
|
+
const deltas = [];
|
|
298
|
+
let call = this.calls.get(data.id);
|
|
299
|
+
if (!call) {
|
|
300
|
+
call = { id: data.id, index: this.calls.size, name: text(data.name) || "", args: "" };
|
|
301
|
+
this.calls.set(call.id, call);
|
|
302
|
+
deltas.push({ tool_calls: [{ index: call.index, id: call.id, type: "function", function: { name: call.name, arguments: "" } }] });
|
|
303
|
+
}
|
|
304
|
+
if (text(data.name)) call.name = text(data.name);
|
|
305
|
+
if (typeof data.args_delta === "string" && data.args_delta) {
|
|
306
|
+
call.args += data.args_delta;
|
|
307
|
+
deltas.push({ tool_calls: [{ index: call.index, function: { arguments: data.args_delta } }] });
|
|
308
|
+
}
|
|
309
|
+
return deltas;
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
async function* formatStream(invoker, request, model) {
|
|
313
|
+
const base = { ...completion(model), object: "chat.completion.chunk" }, state = new CompletionState();
|
|
314
|
+
const chunk = (delta, finishReason = null) => sse({
|
|
315
|
+
...base,
|
|
316
|
+
choices: [{ index: 0, delta, finish_reason: finishReason }]
|
|
317
|
+
});
|
|
318
|
+
yield chunk({ role: "assistant" });
|
|
319
|
+
let failed = false;
|
|
320
|
+
try {
|
|
321
|
+
for await (const event of invoker.invokeStream(request)) {
|
|
322
|
+
if (event.event === EventType.ERROR) {
|
|
323
|
+
yield sse({ error: { message: "handler failed", type: "server_error" } });
|
|
324
|
+
failed = true;
|
|
325
|
+
break;
|
|
326
|
+
}
|
|
327
|
+
for (const delta of state.consume(event)) yield chunk(delta);
|
|
328
|
+
}
|
|
329
|
+
} catch (error) {
|
|
330
|
+
if (request.signal.aborted) return;
|
|
331
|
+
invoker.logger.error("agentcore.server.openai.stream.failed", { ...failureFields(error), requestId: request.rawRequest.headers.get("x-request-id") ?? void 0 });
|
|
332
|
+
yield sse({ error: { message: "handler failed", type: "server_error", code: errorCode(error) } });
|
|
333
|
+
failed = true;
|
|
334
|
+
}
|
|
335
|
+
if (!failed) yield chunk({}, state.finishReason);
|
|
336
|
+
yield "data: [DONE]\n\n";
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// src/server/agui.ts
|
|
340
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
341
|
+
import { Hono as Hono2 } from "hono";
|
|
342
|
+
import { RunAgentInputSchema } from "@ag-ui/core";
|
|
343
|
+
var AGUIProtocolHandler = class {
|
|
344
|
+
constructor(prefix = "/ag-ui/agent") {
|
|
345
|
+
this.prefix = prefix;
|
|
346
|
+
}
|
|
347
|
+
prefix;
|
|
348
|
+
name = "ag-ui";
|
|
349
|
+
routes(invoker) {
|
|
350
|
+
const app = new Hono2();
|
|
351
|
+
app.post(this.prefix, async (c) => {
|
|
352
|
+
if (!invoker.configured) return c.json({ error: { code: "HANDLER_NOT_CONFIGURED" } }, 503);
|
|
353
|
+
let request, threadId, runId;
|
|
354
|
+
try {
|
|
355
|
+
const payload = await c.req.json();
|
|
356
|
+
const parsed = RunAgentInputSchema.parse(payload);
|
|
357
|
+
threadId = parsed.threadId;
|
|
358
|
+
runId = parsed.runId;
|
|
359
|
+
const messages = parsed.messages.map((message) => ({
|
|
360
|
+
role: message.role,
|
|
361
|
+
id: message.id,
|
|
362
|
+
name: "name" in message ? message.name : void 0,
|
|
363
|
+
content: "content" in message ? message.content : void 0,
|
|
364
|
+
toolCalls: "toolCalls" in message ? message.toolCalls : void 0,
|
|
365
|
+
toolCallId: "toolCallId" in message ? message.toolCallId : void 0
|
|
366
|
+
}));
|
|
367
|
+
const tools = parsed.tools.map((tool) => {
|
|
368
|
+
if (!tool.parameters || typeof tool.parameters !== "object" || Array.isArray(tool.parameters)) throw new Error("tool parameters must be an object");
|
|
369
|
+
return { name: tool.name, description: tool.description, parameters: tool.parameters };
|
|
370
|
+
});
|
|
371
|
+
request = {
|
|
372
|
+
protocol: "agui",
|
|
373
|
+
messages,
|
|
374
|
+
tools,
|
|
375
|
+
stream: true,
|
|
376
|
+
rawRequest: c.req.raw,
|
|
377
|
+
rawPayload: payload,
|
|
378
|
+
signal: c.req.raw.signal
|
|
379
|
+
};
|
|
380
|
+
} catch {
|
|
381
|
+
return eventStream(c, async function* () {
|
|
382
|
+
yield sse({ type: "RUN_ERROR", message: "invalid request", code: "INVALID_REQUEST" });
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
return eventStream(c, (signal) => formatStream2(invoker, { ...request, signal }, threadId, runId));
|
|
386
|
+
});
|
|
387
|
+
return app;
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
var StreamState = class {
|
|
391
|
+
textId;
|
|
392
|
+
reasoningId;
|
|
393
|
+
tools = /* @__PURE__ */ new Set();
|
|
394
|
+
toolIds = /* @__PURE__ */ new Set();
|
|
395
|
+
textIds = /* @__PURE__ */ new Set();
|
|
396
|
+
reasoningIds = /* @__PURE__ */ new Set();
|
|
397
|
+
finishIdentified(reasoning, messageId) {
|
|
398
|
+
const active = reasoning ? this.reasoningIds : this.textIds;
|
|
399
|
+
return (messageId === void 0 ? [...active] : [messageId]).flatMap((id) => {
|
|
400
|
+
if (!active.delete(id)) return [];
|
|
401
|
+
return reasoning ? [{ type: "REASONING_MESSAGE_END", messageId: id }, { type: "REASONING_END", messageId: id }] : [{ type: "TEXT_MESSAGE_END", messageId: id }];
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
finishText() {
|
|
405
|
+
if (!this.textId) return [];
|
|
406
|
+
const messageId = this.textId;
|
|
407
|
+
this.textId = void 0;
|
|
408
|
+
return [{ type: "TEXT_MESSAGE_END", messageId }];
|
|
409
|
+
}
|
|
410
|
+
finishReasoning() {
|
|
411
|
+
if (!this.reasoningId) return [];
|
|
412
|
+
const messageId = this.reasoningId;
|
|
413
|
+
this.reasoningId = void 0;
|
|
414
|
+
return [{ type: "REASONING_MESSAGE_END", messageId }, { type: "REASONING_END", messageId }];
|
|
415
|
+
}
|
|
416
|
+
finishTool(toolCallId) {
|
|
417
|
+
return this.tools.delete(toolCallId) ? [{ type: "TOOL_CALL_END", toolCallId }] : [];
|
|
418
|
+
}
|
|
419
|
+
finishTools() {
|
|
420
|
+
return [...this.tools].flatMap((id) => this.finishTool(id));
|
|
421
|
+
}
|
|
422
|
+
consume(event) {
|
|
423
|
+
const data = event.data;
|
|
424
|
+
const identity = typeof data.message_id === "string" ? data.message_id : void 0;
|
|
425
|
+
if (event.event === EventType.TEXT_END) return [...identity === void 0 ? this.finishText() : [], ...this.finishIdentified(false, identity)];
|
|
426
|
+
if (event.event === EventType.REASONING_END) return [...identity === void 0 ? this.finishReasoning() : [], ...this.finishIdentified(true, identity)];
|
|
427
|
+
if (event.event === EventType.TEXT || event.event === EventType.REASONING) {
|
|
428
|
+
const reasoning = event.event === EventType.REASONING;
|
|
429
|
+
const events = [...reasoning ? this.finishText() : this.finishReasoning(), ...this.finishTools()];
|
|
430
|
+
if (identity) events.push(...reasoning ? this.finishReasoning() : this.finishText());
|
|
431
|
+
const active = reasoning ? this.reasoningIds : this.textIds;
|
|
432
|
+
let messageId = identity ?? (reasoning ? this.reasoningId : this.textId);
|
|
433
|
+
if (identity ? !active.has(identity) : !messageId) {
|
|
434
|
+
messageId ??= randomUUID2();
|
|
435
|
+
if (identity) active.add(identity);
|
|
436
|
+
else if (reasoning) this.reasoningId = messageId;
|
|
437
|
+
else this.textId = messageId;
|
|
438
|
+
if (reasoning) {
|
|
439
|
+
events.push({ type: "REASONING_START", messageId });
|
|
440
|
+
}
|
|
441
|
+
events.push({
|
|
442
|
+
type: reasoning ? "REASONING_MESSAGE_START" : "TEXT_MESSAGE_START",
|
|
443
|
+
messageId,
|
|
444
|
+
role: reasoning ? "reasoning" : "assistant"
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
if (typeof data.delta === "string" && data.delta) events.push({
|
|
448
|
+
type: reasoning ? "REASONING_MESSAGE_CONTENT" : "TEXT_MESSAGE_CONTENT",
|
|
449
|
+
messageId,
|
|
450
|
+
delta: data.delta
|
|
451
|
+
});
|
|
452
|
+
return events;
|
|
453
|
+
}
|
|
454
|
+
if (event.event === EventType.TOOL_CALL_CHUNK || event.event === EventType.TOOL_RESULT) {
|
|
455
|
+
if (typeof data.id !== "string" || !data.id) return [];
|
|
456
|
+
const toolCallId = data.id, events = [...this.finishText(), ...this.finishReasoning()];
|
|
457
|
+
if (!this.toolIds.has(toolCallId)) {
|
|
458
|
+
this.tools.add(toolCallId);
|
|
459
|
+
this.toolIds.add(toolCallId);
|
|
460
|
+
events.push({ type: "TOOL_CALL_START", toolCallId, toolCallName: data.name ?? "" });
|
|
461
|
+
}
|
|
462
|
+
if (event.event === EventType.TOOL_CALL_CHUNK) {
|
|
463
|
+
if (typeof data.args_delta === "string" && data.args_delta) events.push({ type: "TOOL_CALL_ARGS", toolCallId, delta: data.args_delta });
|
|
464
|
+
} else {
|
|
465
|
+
events.push(...this.finishTool(toolCallId));
|
|
466
|
+
events.push({
|
|
467
|
+
type: "TOOL_CALL_RESULT",
|
|
468
|
+
toolCallId,
|
|
469
|
+
messageId: `tool-result-${toolCallId}`,
|
|
470
|
+
role: "tool",
|
|
471
|
+
content: typeof data.result === "string" ? data.result : JSON.stringify(data.result ?? "")
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
return events;
|
|
475
|
+
}
|
|
476
|
+
return [event.toJSON()];
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
async function* formatStream2(invoker, request, threadId, runId) {
|
|
480
|
+
const state = new StreamState();
|
|
481
|
+
yield sse({ type: "RUN_STARTED", threadId, runId });
|
|
482
|
+
try {
|
|
483
|
+
for await (const event of invoker.invokeStream(request)) {
|
|
484
|
+
if (event.event === EventType.ERROR) {
|
|
485
|
+
yield sse({ type: "RUN_ERROR", message: event.data.message || "agent failed", code: event.data.code });
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
for (const encoded of state.consume(event)) yield sse(encoded);
|
|
489
|
+
}
|
|
490
|
+
} catch (error) {
|
|
491
|
+
if (request.signal.aborted) return;
|
|
492
|
+
invoker.logger.error("agentcore.server.agui.stream.failed", {
|
|
493
|
+
...failureFields(error),
|
|
494
|
+
threadId,
|
|
495
|
+
runId,
|
|
496
|
+
requestId: request.rawRequest.headers.get("x-request-id") ?? void 0
|
|
497
|
+
});
|
|
498
|
+
yield sse({ type: "RUN_ERROR", message: "handler failed", code: errorCode(error) });
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
for (const encoded of [
|
|
502
|
+
...state.finishReasoning(),
|
|
503
|
+
...state.finishTools(),
|
|
504
|
+
...state.finishText(),
|
|
505
|
+
...state.finishIdentified(false),
|
|
506
|
+
...state.finishIdentified(true)
|
|
507
|
+
]) yield sse(encoded);
|
|
508
|
+
yield sse({ type: "RUN_FINISHED", threadId, runId });
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// src/server/app.ts
|
|
512
|
+
var AgentCoreServer = class {
|
|
513
|
+
constructor(options = {}) {
|
|
514
|
+
this.options = options;
|
|
515
|
+
this.logger = options.logger ?? nullLogger;
|
|
516
|
+
this.invoker = new AgentInvoker(options.invoke, this.logger);
|
|
517
|
+
this.app.get("/healthz", (c) => c.json({ status: "ok" }));
|
|
518
|
+
this.app.get("/readyz", async (c) => {
|
|
519
|
+
let ready = false;
|
|
520
|
+
try {
|
|
521
|
+
ready = options.readiness ? await options.readiness() : this.invoker.configured;
|
|
522
|
+
} catch (error) {
|
|
523
|
+
this.logger.warn("agentcore.server.readiness.failed", failureFields(error));
|
|
524
|
+
}
|
|
525
|
+
return c.json({ ready }, ready ? 200 : 503);
|
|
526
|
+
});
|
|
527
|
+
for (const protocol of options.protocols ?? [new OpenAIProtocolHandler(), new AGUIProtocolHandler()]) {
|
|
528
|
+
this.app.route("/", protocol.routes(this.invoker));
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
options;
|
|
532
|
+
app = new Hono3();
|
|
533
|
+
invoker;
|
|
534
|
+
logger;
|
|
535
|
+
server;
|
|
536
|
+
starting;
|
|
537
|
+
stopping;
|
|
538
|
+
invoke(handler) {
|
|
539
|
+
this.invoker.setHandler(handler);
|
|
540
|
+
}
|
|
541
|
+
start(options = {}) {
|
|
542
|
+
if (this.stopping) return Promise.reject(new Error("AgentCore server is closed"));
|
|
543
|
+
if (this.starting) return this.starting;
|
|
544
|
+
this.starting = this.listen(options).catch((error) => {
|
|
545
|
+
this.starting = void 0;
|
|
546
|
+
throw error;
|
|
547
|
+
});
|
|
548
|
+
return this.starting;
|
|
549
|
+
}
|
|
550
|
+
async listen(options) {
|
|
551
|
+
this.logger.info("agentcore.server.lifecycle.startup.started");
|
|
552
|
+
let initialized = false;
|
|
553
|
+
try {
|
|
554
|
+
await this.options.startup?.();
|
|
555
|
+
initialized = true;
|
|
556
|
+
const address = await new Promise((resolve, reject) => {
|
|
557
|
+
const server = serve({ fetch: this.app.fetch, port: options.port ?? 9e3, hostname: options.hostname ?? "0.0.0.0" }, resolve);
|
|
558
|
+
this.server = server;
|
|
559
|
+
server.once("error", reject);
|
|
560
|
+
});
|
|
561
|
+
this.logger.info("agentcore.server.lifecycle.startup.succeeded", { port: address.port });
|
|
562
|
+
return `http://${address.family === "IPv6" ? `[${address.address}]` : address.address}:${address.port}`;
|
|
563
|
+
} catch (error) {
|
|
564
|
+
this.logger.error("agentcore.server.lifecycle.startup.failed", failureFields(error));
|
|
565
|
+
this.server = void 0;
|
|
566
|
+
if (initialized) {
|
|
567
|
+
try {
|
|
568
|
+
await this.options.shutdown?.();
|
|
569
|
+
} catch (cleanupError) {
|
|
570
|
+
this.logger.error("agentcore.server.lifecycle.shutdown.failed", failureFields(cleanupError));
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
throw error;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
/** Stop accepting traffic, drain requests, then release application resources. */
|
|
577
|
+
close() {
|
|
578
|
+
if (this.stopping) return this.stopping;
|
|
579
|
+
this.stopping = this.stop();
|
|
580
|
+
return this.stopping;
|
|
581
|
+
}
|
|
582
|
+
async stop() {
|
|
583
|
+
await this.starting?.catch(() => void 0);
|
|
584
|
+
if (!this.server?.listening) return;
|
|
585
|
+
this.logger.info("agentcore.server.lifecycle.shutdown.started");
|
|
586
|
+
await new Promise((resolve, reject) => this.server.close((error) => error ? reject(error) : resolve()));
|
|
587
|
+
try {
|
|
588
|
+
await this.options.shutdown?.();
|
|
589
|
+
} catch (error) {
|
|
590
|
+
this.logger.error("agentcore.server.lifecycle.shutdown.failed", failureFields(error));
|
|
591
|
+
throw error;
|
|
592
|
+
}
|
|
593
|
+
this.logger.info("agentcore.server.lifecycle.shutdown.succeeded");
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
export {
|
|
597
|
+
AGUIProtocolHandler,
|
|
598
|
+
AgentCoreServer,
|
|
599
|
+
AgentEvent,
|
|
600
|
+
AgentInvoker,
|
|
601
|
+
EventType,
|
|
602
|
+
OpenAIProtocolHandler
|
|
603
|
+
};
|
|
604
|
+
//# sourceMappingURL=index.js.map
|