@heddleagent/execution-host-client 6.0.0 → 6.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/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # `@heddleagent/execution-host-client`
2
2
 
3
- `@heddleagent/execution-host-client` is the lightweight backend-side SDK for
3
+ `@heddleagent/execution-host-client` is the backend-side SDK for
4
4
  products that invoke a separately deployed Heddle Execution Host. It lets an
5
5
  adopter keep its own language stack, authentication, database, product policy,
6
6
  MCP tools, and UI while reusing the security-sensitive v1 contract machinery.
7
7
 
8
- > **Current availability:** stable version `6.0.0`. The former
9
- > `@roackb2/heddle-adopter@5.13.0` coordinate remains installable during
10
- > migration. Heddle does not currently distribute
8
+ > **Current availability:** stable version `6.1.0`. The former
9
+ > `@roackb2/heddle-adopter@5.13.0` coordinate is deprecated and remains
10
+ > installable only for existing consumers. Heddle does not currently distribute
11
11
  > the compatible Execution Host implementation or offer a hosted service. The
12
12
  > public surface documents and tests the adopter boundary without implying a
13
13
  > generally available deployment.
@@ -18,10 +18,10 @@ Install the package:
18
18
  npm install @heddleagent/execution-host-client
19
19
  ```
20
20
 
21
- The package does **not** contain Heddle's agent loop, AgentCore deployment,
22
- Terraform, product MCP tools, or product logic. It uses the official MCP SDK,
23
- plus `jose`, `zod`, `dayjs`, and `eventsource-parser`, for its optional
24
- reference edges.
21
+ The package does **not** contain Heddle's agent loop, AgentCore Runtime
22
+ deployment, Terraform, product MCP tools, or product logic. It uses the
23
+ modular AWS SDK for its AgentCore transport and the official MCP SDK, plus
24
+ `jose`, `zod`, `dayjs`, and `eventsource-parser`, for its other edges.
25
25
 
26
26
  ## What it owns
27
27
 
@@ -33,6 +33,7 @@ reference edges.
33
33
  | `@heddleagent/execution-host-client/mcp` | Independent capability verification at the adopter's MCP edge |
34
34
  | `@heddleagent/execution-host-client/mcp/node` | Stateless official-SDK Streamable HTTP lifecycle around adopter-defined toolsets |
35
35
  | `@heddleagent/execution-host-client/http-sse` | Transport-neutral `ExecutionHost` port and strict direct-development HTTP/SSE client |
36
+ | `@heddleagent/execution-host-client/agentcore` | Official AWS AgentCore/SigV4 implementation of the same `ExecutionHost` port |
36
37
  | `@heddleagent/execution-host-client/testing` | Node-only loopback v1 fixture plus durable-turn store conformance for real adapters |
37
38
  | `@heddleagent/execution-host-client/node` | Optional Node JWKS/conversation HTTP edge plus safe local signing-key helpers |
38
39
 
@@ -53,7 +54,8 @@ The adopter still owns:
53
54
  allocation, the lifecycle-store implementation/schema/migrations, retention,
54
55
  and history queries;
55
56
  - implementing and hosting product MCP tools against its own APIs and data;
56
- - choosing an AgentCore/SigV4 transport, applying results, and rendering UI.
57
+ - choosing and provisioning its AgentCore Runtime, applying results, and
58
+ rendering UI.
57
59
 
58
60
  ## Issue one invocation's authority
59
61
 
@@ -225,11 +227,32 @@ const productMcp = new NodeStreamableHttpMcpService({
225
227
  Use the lower-level `NodeMcpToolset` interface only when a tool needs custom MCP
226
228
  content or lifecycle semantics.
227
229
 
228
- ## Invoke the direct development host
230
+ ## Invoke an Execution Host
229
231
 
230
- The direct client is useful for local and reviewed HTTPS deployments. A
231
- managed AgentCore deployment should supply a separate SigV4/AWS SDK transport
232
- which implements the same `ExecutionHost` port.
232
+ Use the official AgentCore client for a Runtime deployed in the adopter's AWS
233
+ account. It uses the normal AWS credential chain, signs the required Heddle
234
+ authority headers, streams the response through the same strict protocol
235
+ validation as the direct client, and deliberately makes only one ambiguous
236
+ streaming attempt.
237
+
238
+ ```ts
239
+ import {
240
+ AgentCoreExecutionHost,
241
+ } from '@heddleagent/execution-host-client/agentcore'
242
+
243
+ const host = new AgentCoreExecutionHost({
244
+ region: process.env.AWS_REGION!,
245
+ runtimeArn: process.env.AGENTCORE_RUNTIME_ARN!,
246
+ qualifier: process.env.AGENTCORE_RUNTIME_QUALIFIER,
247
+ })
248
+ ```
249
+
250
+ The product still owns the AWS account, Runtime deployment, IAM policy,
251
+ configuration, and credentials environment. Heddle owns only the reusable
252
+ invocation transport.
253
+
254
+ For local development and reviewed direct HTTPS deployments, use the direct
255
+ client:
233
256
 
234
257
  ```ts
235
258
  import { DirectHttpExecutionHost } from '@heddleagent/execution-host-client/http-sse'
@@ -0,0 +1,16 @@
1
+ import { type ExecutionHostStreamEvent } from '../contracts/index.js';
2
+ import { type ExecutionHost, type ExecutionHostConversationTurn } from '../http-sse/index.js';
3
+ import type { AgentCoreExecutionHostConfig } from './types.js';
4
+ /**
5
+ * Invokes one compatible Heddle Execution Host through AWS AgentCore while
6
+ * reusing the package's strict request and SSE protocol validation.
7
+ */
8
+ export declare class AgentCoreExecutionHost implements ExecutionHost {
9
+ #private;
10
+ constructor(config: AgentCoreExecutionHostConfig);
11
+ streamConversationTurn(input: ExecutionHostConversationTurn): AsyncIterable<ExecutionHostStreamEvent>;
12
+ close(): void;
13
+ }
14
+ export declare const AGENTCORE_FORWARDED_HEADER_NAMES: readonly ["x-heddle-execution-host-assertion", "x-heddle-execution-host-mcp-capability", "x-heddle-execution-host-model-api-key"];
15
+ export declare const AGENTCORE_EXCLUDED_HEADER_NAMES: readonly ["x-heddle-execution-host-local-token"];
16
+ //# sourceMappingURL=agentcore-execution-host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agentcore-execution-host.d.ts","sourceRoot":"","sources":["../../src/agentcore/agentcore-execution-host.ts"],"names":[],"mappings":"AAMA,OAAO,EAML,KAAK,wBAAwB,EAC9B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAEL,KAAK,aAAa,EAClB,KAAK,6BAA6B,EACnC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EACV,4BAA4B,EAE7B,MAAM,YAAY,CAAC;AAoBpB;;;GAGG;AACH,qBAAa,sBAAuB,YAAW,aAAa;;gBAM9C,MAAM,EAAE,4BAA4B;IAgBhD,sBAAsB,CACpB,KAAK,EAAE,6BAA6B,GACnC,aAAa,CAAC,wBAAwB,CAAC;IAK1C,KAAK,IAAI,IAAI;CAiEd;AAsGD,eAAO,MAAM,gCAAgC,mIAIlC,CAAC;AAEZ,eAAO,MAAM,+BAA+B,kDAEjC,CAAC"}
@@ -0,0 +1,197 @@
1
+ import { BedrockAgentCoreClient, InvokeAgentRuntimeCommand, } from '@aws-sdk/client-bedrock-agentcore';
2
+ import { HttpRequest } from '@smithy/protocol-http';
3
+ import { AGENTCORE_RUNTIME_SESSION_HEADER, EXECUTION_ASSERTION_HEADER, EXECUTION_HOST_LOCAL_TOKEN_HEADER, MCP_CAPABILITY_HEADER, MODEL_API_KEY_HEADER, } from '../contracts/index.js';
4
+ import { DirectHttpExecutionHost, } from '../http-sse/index.js';
5
+ const CONTENT_TYPE = 'application/json';
6
+ const ACCEPT = 'text/event-stream';
7
+ const MIN_RUNTIME_SESSION_ID_LENGTH = 33;
8
+ const MAX_RUNTIME_SESSION_ID_LENGTH = 256;
9
+ const RUNTIME_SESSION_ID_PATTERN = /^[A-Za-z0-9](?:-*[A-Za-z0-9])+$/;
10
+ const WIRE_BRIDGE_URL = new URL('http://127.0.0.1/agentcore-bridge');
11
+ const NON_FORWARDED_LOCAL_TOKEN = 'agentcore-bridge-token-never-forwarded';
12
+ const SERVICE_ERROR_CODES = new Map([
13
+ ['AccessDeniedException', 'access_denied'],
14
+ ['InternalServerException', 'runtime_internal'],
15
+ ['ResourceNotFoundException', 'runtime_not_found'],
16
+ ['RetryableConflictException', 'runtime_conflict'],
17
+ ['RuntimeClientError', 'runtime_client_error'],
18
+ ['ServiceQuotaExceededException', 'quota_exceeded'],
19
+ ['ThrottlingException', 'throttled'],
20
+ ['ValidationException', 'invalid_request'],
21
+ ]);
22
+ /**
23
+ * Invokes one compatible Heddle Execution Host through AWS AgentCore while
24
+ * reusing the package's strict request and SSE protocol validation.
25
+ */
26
+ export class AgentCoreExecutionHost {
27
+ #client;
28
+ #runtimeArn;
29
+ #qualifier;
30
+ #wire;
31
+ constructor(config) {
32
+ this.#runtimeArn = config.runtimeArn;
33
+ this.#qualifier = config.qualifier;
34
+ this.#client = config.client ?? new BedrockAgentCoreClient({
35
+ region: config.region,
36
+ // Invocation settlement is ambiguous after a transport interruption.
37
+ // Product policy, not the AWS client, decides whether a turn may retry.
38
+ maxAttempts: 1,
39
+ });
40
+ this.#wire = new DirectHttpExecutionHost({
41
+ baseUrl: WIRE_BRIDGE_URL,
42
+ localToken: NON_FORWARDED_LOCAL_TOKEN,
43
+ fetch: (_input, init) => this.#invoke(init),
44
+ });
45
+ }
46
+ streamConversationTurn(input) {
47
+ assertAgentCoreRuntimeSessionId(input.runtimeSessionId);
48
+ return this.#wire.streamConversationTurn(input);
49
+ }
50
+ close() {
51
+ this.#client.destroy?.();
52
+ }
53
+ async #invoke(init) {
54
+ if (init?.method !== 'POST' || typeof init.body !== 'string') {
55
+ throw new Error('AgentCore wire bridge received an invalid request.');
56
+ }
57
+ const headers = new Headers(init.headers);
58
+ const runtimeSessionId = requireHeader(headers, AGENTCORE_RUNTIME_SESSION_HEADER);
59
+ const customHeaders = Object.fromEntries([
60
+ [
61
+ EXECUTION_ASSERTION_HEADER,
62
+ requireHeader(headers, EXECUTION_ASSERTION_HEADER),
63
+ ],
64
+ [MODEL_API_KEY_HEADER, requireHeader(headers, MODEL_API_KEY_HEADER)],
65
+ ...(headers.has(MCP_CAPABILITY_HEADER)
66
+ ? [[MCP_CAPABILITY_HEADER, headers.get(MCP_CAPABILITY_HEADER)]]
67
+ : []),
68
+ ]);
69
+ const command = new InvokeAgentRuntimeCommand({
70
+ agentRuntimeArn: this.#runtimeArn,
71
+ runtimeSessionId,
72
+ qualifier: this.#qualifier,
73
+ contentType: CONTENT_TYPE,
74
+ accept: ACCEPT,
75
+ payload: new TextEncoder().encode(init.body),
76
+ });
77
+ addSignedCustomHeaders(command, customHeaders);
78
+ const signal = init.signal ?? undefined;
79
+ try {
80
+ const output = await this.#client.send(command, { abortSignal: signal });
81
+ return new Response(output.response ? toReadableStream(output.response) : null, {
82
+ status: output.statusCode ?? output.$metadata.httpStatusCode ?? 200,
83
+ headers: {
84
+ 'content-type': output.contentType ?? 'application/octet-stream',
85
+ },
86
+ });
87
+ }
88
+ catch (error) {
89
+ if (signal?.aborted) {
90
+ throw error;
91
+ }
92
+ const status = readServiceStatus(error);
93
+ if (!status) {
94
+ throw error;
95
+ }
96
+ const code = SERVICE_ERROR_CODES.get(readErrorName(error)) ?? 'unknown';
97
+ return new Response(JSON.stringify({
98
+ error: {
99
+ code,
100
+ message: 'AgentCore rejected the invocation.',
101
+ },
102
+ }), {
103
+ status,
104
+ headers: { 'content-type': CONTENT_TYPE },
105
+ });
106
+ }
107
+ }
108
+ }
109
+ function assertAgentCoreRuntimeSessionId(value) {
110
+ if (value.length < MIN_RUNTIME_SESSION_ID_LENGTH
111
+ || value.length > MAX_RUNTIME_SESSION_ID_LENGTH
112
+ || !RUNTIME_SESSION_ID_PATTERN.test(value)) {
113
+ throw new Error('AgentCore runtime session ID is not provider-compatible.');
114
+ }
115
+ }
116
+ function addSignedCustomHeaders(command, headers) {
117
+ command.middlewareStack.add((next) => async (args) => {
118
+ if (!HttpRequest.isInstance(args.request)) {
119
+ throw new Error('AgentCore invocation did not produce an HTTP request.');
120
+ }
121
+ Object.assign(args.request.headers, headers);
122
+ return await next(args);
123
+ }, {
124
+ step: 'build',
125
+ priority: 'low',
126
+ name: 'heddleAgentCoreCustomHeaders',
127
+ });
128
+ }
129
+ function requireHeader(headers, name) {
130
+ const value = headers.get(name);
131
+ if (!value) {
132
+ throw new Error('AgentCore wire bridge omitted required authority.');
133
+ }
134
+ return value;
135
+ }
136
+ function toReadableStream(source) {
137
+ if (source instanceof Blob) {
138
+ return source.stream();
139
+ }
140
+ if (source instanceof ReadableStream) {
141
+ return source;
142
+ }
143
+ if (!isAsyncIterable(source)) {
144
+ throw new Error('AgentCore returned an unsupported stream type.');
145
+ }
146
+ const iterator = source[Symbol.asyncIterator]();
147
+ return new ReadableStream({
148
+ async pull(controller) {
149
+ try {
150
+ const item = await iterator.next();
151
+ if (item.done) {
152
+ controller.close();
153
+ return;
154
+ }
155
+ if (!(item.value instanceof Uint8Array)) {
156
+ throw new Error('AgentCore returned a non-binary stream chunk.');
157
+ }
158
+ controller.enqueue(item.value);
159
+ }
160
+ catch (error) {
161
+ controller.error(error);
162
+ }
163
+ },
164
+ async cancel() {
165
+ await iterator.return?.();
166
+ },
167
+ });
168
+ }
169
+ function isAsyncIterable(value) {
170
+ return Boolean(value
171
+ && typeof value === 'object'
172
+ && Symbol.asyncIterator in value
173
+ && typeof value[Symbol.asyncIterator] === 'function');
174
+ }
175
+ function readServiceStatus(error) {
176
+ if (!error || typeof error !== 'object' || !('$metadata' in error)) {
177
+ return undefined;
178
+ }
179
+ const metadata = error
180
+ .$metadata;
181
+ const status = metadata?.httpStatusCode;
182
+ return typeof status === 'number' && status >= 400 && status <= 599
183
+ ? status
184
+ : undefined;
185
+ }
186
+ function readErrorName(error) {
187
+ return error instanceof Error ? error.name : '';
188
+ }
189
+ export const AGENTCORE_FORWARDED_HEADER_NAMES = Object.freeze([
190
+ EXECUTION_ASSERTION_HEADER,
191
+ MCP_CAPABILITY_HEADER,
192
+ MODEL_API_KEY_HEADER,
193
+ ]);
194
+ export const AGENTCORE_EXCLUDED_HEADER_NAMES = Object.freeze([
195
+ EXECUTION_HOST_LOCAL_TOKEN_HEADER,
196
+ ]);
197
+ //# sourceMappingURL=agentcore-execution-host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agentcore-execution-host.js","sourceRoot":"","sources":["../../src/agentcore/agentcore-execution-host.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,yBAAyB,GAE1B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,iCAAiC,EACjC,qBAAqB,EACrB,oBAAoB,GAErB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,uBAAuB,GAGxB,MAAM,sBAAs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,CAAC,CAAC,WAAW,IAAI,KAAK,CAAC,EAAE,CAAC;QACnE,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,QAAQ,GAAI,KAAsD;SACrE,SAAS,CAAC;IACb,MAAM,MAAM,GAAG,QAAQ,EAAE,cAAc,CAAC;IACxC,OAAO,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG;QACjE,CAAC,CAAC,MAAM;QACR,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;AAClD,CAAC;AAED,MAAM,CAAC,MAAM,gCAAgC,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5D,0BAA0B;IAC1B,qBAAqB;IACrB,oBAAoB;CACZ,CAAC,CAAC;AAEZ,MAAM,CAAC,MAAM,+BAA+B,GAAG,MAAM,CAAC,MAAM,CAAC;IAC3D,iCAAiC;CACzB,CAAC,CAAC","sourcesContent":["import {\n BedrockAgentCoreClient,\n InvokeAgentRuntimeCommand,\n type InvokeAgentRuntimeCommandOutput,\n} from '@aws-sdk/client-bedrock-agentcore';\nimport { HttpRequest } from '@smithy/protocol-http';\nimport {\n AGENTCORE_RUNTIME_SESSION_HEADER,\n EXECUTION_ASSERTION_HEADER,\n EXECUTION_HOST_LOCAL_TOKEN_HEADER,\n MCP_CAPABILITY_HEADER,\n MODEL_API_KEY_HEADER,\n type ExecutionHostStreamEvent,\n} from '../contracts/index.js';\nimport {\n DirectHttpExecutionHost,\n type ExecutionHost,\n type ExecutionHostConversationTurn,\n} from '../http-sse/index.js';\nimport type {\n AgentCoreExecutionHostConfig,\n AgentCoreRuntimeClient,\n} from './types.js';\n\nconst CONTENT_TYPE = 'application/json';\nconst ACCEPT = 'text/event-stream';\nconst MIN_RUNTIME_SESSION_ID_LENGTH = 33;\nconst MAX_RUNTIME_SESSION_ID_LENGTH = 256;\nconst RUNTIME_SESSION_ID_PATTERN = /^[A-Za-z0-9](?:-*[A-Za-z0-9])+$/;\nconst WIRE_BRIDGE_URL = new URL('http://127.0.0.1/agentcore-bridge');\nconst NON_FORWARDED_LOCAL_TOKEN = 'agentcore-bridge-token-never-forwarded';\nconst SERVICE_ERROR_CODES = new Map<string, string>([\n ['AccessDeniedException', 'access_denied'],\n ['InternalServerException', 'runtime_internal'],\n ['ResourceNotFoundException', 'runtime_not_found'],\n ['RetryableConflictException', 'runtime_conflict'],\n ['RuntimeClientError', 'runtime_client_error'],\n ['ServiceQuotaExceededException', 'quota_exceeded'],\n ['ThrottlingException', 'throttled'],\n ['ValidationException', 'invalid_request'],\n]);\n\n/**\n * Invokes one compatible Heddle Execution Host through AWS AgentCore while\n * reusing the package's strict request and SSE protocol validation.\n */\nexport class AgentCoreExecutionHost implements ExecutionHost {\n readonly #client: AgentCoreRuntimeClient;\n readonly #runtimeArn: string;\n readonly #qualifier?: string;\n readonly #wire: DirectHttpExecutionHost;\n\n constructor(config: AgentCoreExecutionHostConfig) {\n this.#runtimeArn = config.runtimeArn;\n this.#qualifier = config.qualifier;\n this.#client = config.client ?? new BedrockAgentCoreClient({\n region: config.region,\n // Invocation settlement is ambiguous after a transport interruption.\n // Product policy, not the AWS client, decides whether a turn may retry.\n maxAttempts: 1,\n });\n this.#wire = new DirectHttpExecutionHost({\n baseUrl: WIRE_BRIDGE_URL,\n localToken: NON_FORWARDED_LOCAL_TOKEN,\n fetch: (_input, init) => this.#invoke(init),\n });\n }\n\n streamConversationTurn(\n input: ExecutionHostConversationTurn,\n ): AsyncIterable<ExecutionHostStreamEvent> {\n assertAgentCoreRuntimeSessionId(input.runtimeSessionId);\n return this.#wire.streamConversationTurn(input);\n }\n\n close(): void {\n this.#client.destroy?.();\n }\n\n async #invoke(init?: RequestInit): Promise<Response> {\n if (init?.method !== 'POST' || typeof init.body !== 'string') {\n throw new Error('AgentCore wire bridge received an invalid request.');\n }\n const headers = new Headers(init.headers);\n const runtimeSessionId = requireHeader(\n headers,\n AGENTCORE_RUNTIME_SESSION_HEADER,\n );\n const customHeaders = Object.fromEntries([\n [\n EXECUTION_ASSERTION_HEADER,\n requireHeader(headers, EXECUTION_ASSERTION_HEADER),\n ],\n [MODEL_API_KEY_HEADER, requireHeader(headers, MODEL_API_KEY_HEADER)],\n ...(headers.has(MCP_CAPABILITY_HEADER)\n ? [[MCP_CAPABILITY_HEADER, headers.get(MCP_CAPABILITY_HEADER)!]]\n : []),\n ]);\n const command = new InvokeAgentRuntimeCommand({\n agentRuntimeArn: this.#runtimeArn,\n runtimeSessionId,\n qualifier: this.#qualifier,\n contentType: CONTENT_TYPE,\n accept: ACCEPT,\n payload: new TextEncoder().encode(init.body),\n });\n addSignedCustomHeaders(command, customHeaders);\n const signal = init.signal ?? undefined;\n\n try {\n const output = await this.#client.send(command, { abortSignal: signal });\n return new Response(\n output.response ? toReadableStream(output.response) : null,\n {\n status: output.statusCode ?? output.$metadata.httpStatusCode ?? 200,\n headers: {\n 'content-type': output.contentType ?? 'application/octet-stream',\n },\n },\n );\n } catch (error) {\n if (signal?.aborted) {\n throw error;\n }\n const status = readServiceStatus(error);\n if (!status) {\n throw error;\n }\n const code = SERVICE_ERROR_CODES.get(readErrorName(error)) ?? 'unknown';\n return new Response(JSON.stringify({\n error: {\n code,\n message: 'AgentCore rejected the invocation.',\n },\n }), {\n status,\n headers: { 'content-type': CONTENT_TYPE },\n });\n }\n }\n}\n\nfunction assertAgentCoreRuntimeSessionId(value: string): void {\n if (\n value.length < MIN_RUNTIME_SESSION_ID_LENGTH\n || value.length > MAX_RUNTIME_SESSION_ID_LENGTH\n || !RUNTIME_SESSION_ID_PATTERN.test(value)\n ) {\n throw new Error('AgentCore runtime session ID is not provider-compatible.');\n }\n}\n\nfunction addSignedCustomHeaders(\n command: InvokeAgentRuntimeCommand,\n headers: Readonly<Record<string, string>>,\n): void {\n command.middlewareStack.add(\n (next) => async (args) => {\n if (!HttpRequest.isInstance(args.request)) {\n throw new Error('AgentCore invocation did not produce an HTTP request.');\n }\n Object.assign(args.request.headers, headers);\n return await next(args);\n },\n {\n step: 'build',\n priority: 'low',\n name: 'heddleAgentCoreCustomHeaders',\n },\n );\n}\n\nfunction requireHeader(headers: Headers, name: string): string {\n const value = headers.get(name);\n if (!value) {\n throw new Error('AgentCore wire bridge omitted required authority.');\n }\n return value;\n}\n\nfunction toReadableStream(\n source: NonNullable<InvokeAgentRuntimeCommandOutput['response']>,\n): ReadableStream<Uint8Array> {\n if (source instanceof Blob) {\n return source.stream();\n }\n if (source instanceof ReadableStream) {\n return source;\n }\n if (!isAsyncIterable(source)) {\n throw new Error('AgentCore returned an unsupported stream type.');\n }\n const iterator = source[Symbol.asyncIterator]();\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const item = await iterator.next();\n if (item.done) {\n controller.close();\n return;\n }\n if (!(item.value instanceof Uint8Array)) {\n throw new Error('AgentCore returned a non-binary stream chunk.');\n }\n controller.enqueue(item.value);\n } catch (error) {\n controller.error(error);\n }\n },\n async cancel() {\n await iterator.return?.();\n },\n });\n}\n\nfunction isAsyncIterable(\n value: unknown,\n): value is AsyncIterable<Uint8Array> {\n return Boolean(\n value\n && typeof value === 'object'\n && Symbol.asyncIterator in value\n && typeof value[Symbol.asyncIterator] === 'function',\n );\n}\n\nfunction readServiceStatus(error: unknown): number | undefined {\n if (!error || typeof error !== 'object' || !('$metadata' in error)) {\n return undefined;\n }\n const metadata = (error as { $metadata?: { httpStatusCode?: unknown } })\n .$metadata;\n const status = metadata?.httpStatusCode;\n return typeof status === 'number' && status >= 400 && status <= 599\n ? status\n : undefined;\n}\n\nfunction readErrorName(error: unknown): string {\n return error instanceof Error ? error.name : '';\n}\n\nexport const AGENTCORE_FORWARDED_HEADER_NAMES = Object.freeze([\n EXECUTION_ASSERTION_HEADER,\n MCP_CAPABILITY_HEADER,\n MODEL_API_KEY_HEADER,\n] as const);\n\nexport const AGENTCORE_EXCLUDED_HEADER_NAMES = Object.freeze([\n EXECUTION_HOST_LOCAL_TOKEN_HEADER,\n] as const);\n"]}
@@ -0,0 +1,3 @@
1
+ export { AGENTCORE_EXCLUDED_HEADER_NAMES, AGENTCORE_FORWARDED_HEADER_NAMES, AgentCoreExecutionHost, } from './agentcore-execution-host.js';
2
+ export type { AgentCoreExecutionHostConfig, AgentCoreRuntimeClient, } from './types.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/agentcore/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,EAChC,sBAAsB,GACvB,MAAM,+BAA+B,CAAC;AACvC,YAAY,EACV,4BAA4B,EAC5B,sBAAsB,GACvB,MAAM,YAAY,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { AGENTCORE_EXCLUDED_HEADER_NAMES, AGENTCORE_FORWARDED_HEADER_NAMES, AgentCoreExecutionHost, } from './agentcore-execution-host.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/agentcore/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,EAChC,sBAAsB,GACvB,MAAM,+BAA+B,CAAC","sourcesContent":["export {\n AGENTCORE_EXCLUDED_HEADER_NAMES,\n AGENTCORE_FORWARDED_HEADER_NAMES,\n AgentCoreExecutionHost,\n} from './agentcore-execution-host.js';\nexport type {\n AgentCoreExecutionHostConfig,\n AgentCoreRuntimeClient,\n} from './types.js';\n"]}
@@ -0,0 +1,14 @@
1
+ import type { InvokeAgentRuntimeCommand, InvokeAgentRuntimeCommandOutput } from '@aws-sdk/client-bedrock-agentcore';
2
+ export interface AgentCoreRuntimeClient {
3
+ send(command: InvokeAgentRuntimeCommand, options?: {
4
+ abortSignal?: AbortSignal;
5
+ }): Promise<InvokeAgentRuntimeCommandOutput>;
6
+ destroy?(): void;
7
+ }
8
+ export type AgentCoreExecutionHostConfig = {
9
+ region: string;
10
+ runtimeArn: string;
11
+ qualifier?: string;
12
+ client?: AgentCoreRuntimeClient;
13
+ };
14
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/agentcore/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,yBAAyB,EACzB,+BAA+B,EAChC,MAAM,mCAAmC,CAAC;AAE3C,MAAM,WAAW,sBAAsB;IACrC,IAAI,CACF,OAAO,EAAE,yBAAyB,EAClC,OAAO,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,WAAW,CAAA;KAAE,GACtC,OAAO,CAAC,+BAA+B,CAAC,CAAC;IAC5C,OAAO,CAAC,IAAI,IAAI,CAAC;CAClB;AAED,MAAM,MAAM,4BAA4B,GAAG;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,sBAAsB,CAAC;CACjC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/agentcore/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n InvokeAgentRuntimeCommand,\n InvokeAgentRuntimeCommandOutput,\n} from '@aws-sdk/client-bedrock-agentcore';\n\nexport interface AgentCoreRuntimeClient {\n send(\n command: InvokeAgentRuntimeCommand,\n options?: { abortSignal?: AbortSignal },\n ): Promise<InvokeAgentRuntimeCommandOutput>;\n destroy?(): void;\n}\n\nexport type AgentCoreExecutionHostConfig = {\n region: string;\n runtimeArn: string;\n qualifier?: string;\n client?: AgentCoreRuntimeClient;\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heddleagent/execution-host-client",
3
- "version": "6.0.0",
3
+ "version": "6.1.0",
4
4
  "description": "Backend contracts, execution authority, lifecycle services, and clients for compatible Heddle Execution Hosts",
5
5
  "author": "Jay / Fienna Liang <roackb2@gmail.com>",
6
6
  "license": "MIT",
@@ -54,6 +54,10 @@
54
54
  "types": "./dist/http-sse/index.d.ts",
55
55
  "import": "./dist/http-sse/index.js"
56
56
  },
57
+ "./agentcore": {
58
+ "types": "./dist/agentcore/index.d.ts",
59
+ "import": "./dist/agentcore/index.js"
60
+ },
57
61
  "./testing": {
58
62
  "types": "./dist/testing/index.d.ts",
59
63
  "import": "./dist/testing/index.js"
@@ -83,7 +87,9 @@
83
87
  "streaming"
84
88
  ],
85
89
  "dependencies": {
90
+ "@aws-sdk/client-bedrock-agentcore": "^3.1107.0",
86
91
  "@modelcontextprotocol/sdk": "^1.29.0",
92
+ "@smithy/protocol-http": "^5.5.16",
87
93
  "dayjs": "^1.11.20",
88
94
  "eventsource-parser": "^3.1.0",
89
95
  "jose": "^6.2.8",