@heddleagent/execution-host-client 6.0.0 → 6.2.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 +76 -14
- package/dist/agentcore/agentcore-execution-host.d.ts +17 -0
- package/dist/agentcore/agentcore-execution-host.d.ts.map +1 -0
- package/dist/agentcore/agentcore-execution-host.js +201 -0
- package/dist/agentcore/agentcore-execution-host.js.map +1 -0
- package/dist/agentcore/index.d.ts +3 -0
- package/dist/agentcore/index.d.ts.map +1 -0
- package/dist/agentcore/index.js +2 -0
- package/dist/agentcore/index.js.map +1 -0
- package/dist/agentcore/types.d.ts +14 -0
- package/dist/agentcore/types.d.ts.map +1 -0
- package/dist/agentcore/types.js +2 -0
- package/dist/agentcore/types.js.map +1 -0
- package/dist/authority/jose-execution-authority.js +2 -2
- package/dist/authority/jose-execution-authority.js.map +1 -1
- package/dist/contracts/index.d.ts +106 -3
- package/dist/contracts/index.d.ts.map +1 -1
- package/dist/contracts/index.js +67 -2
- package/dist/contracts/index.js.map +1 -1
- package/dist/conversation/index.d.ts +1 -1
- package/dist/conversation/index.d.ts.map +1 -1
- package/dist/conversation/index.js.map +1 -1
- package/dist/conversation/types.d.ts +4 -2
- package/dist/conversation/types.d.ts.map +1 -1
- package/dist/conversation/types.js.map +1 -1
- package/dist/heartbeat/hosted-heartbeat-agent-execution-transport.d.ts +14 -0
- package/dist/heartbeat/hosted-heartbeat-agent-execution-transport.d.ts.map +1 -0
- package/dist/heartbeat/hosted-heartbeat-agent-execution-transport.js +38 -0
- package/dist/heartbeat/hosted-heartbeat-agent-execution-transport.js.map +1 -0
- package/dist/heartbeat/hosted-heartbeat-task-service.d.ts +22 -0
- package/dist/heartbeat/hosted-heartbeat-task-service.d.ts.map +1 -0
- package/dist/heartbeat/hosted-heartbeat-task-service.js +96 -0
- package/dist/heartbeat/hosted-heartbeat-task-service.js.map +1 -0
- package/dist/heartbeat/index.d.ts +5 -0
- package/dist/heartbeat/index.d.ts.map +1 -0
- package/dist/heartbeat/index.js +4 -0
- package/dist/heartbeat/index.js.map +1 -0
- package/dist/heartbeat/types.d.ts +83 -0
- package/dist/heartbeat/types.d.ts.map +1 -0
- package/dist/heartbeat/types.js +17 -0
- package/dist/heartbeat/types.js.map +1 -0
- package/dist/http-sse/direct-http-execution-host.d.ts +4 -3
- package/dist/http-sse/direct-http-execution-host.d.ts.map +1 -1
- package/dist/http-sse/direct-http-execution-host.js +56 -21
- package/dist/http-sse/direct-http-execution-host.js.map +1 -1
- package/dist/http-sse/index.d.ts +1 -1
- package/dist/http-sse/index.d.ts.map +1 -1
- package/dist/http-sse/index.js.map +1 -1
- package/dist/http-sse/types.d.ts +11 -1
- package/dist/http-sse/types.d.ts.map +1 -1
- package/dist/http-sse/types.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +11 -1
- package/spec/v1/README.md +14 -4
- package/spec/v1/fixtures/manifest.json +12 -0
- package/spec/v1/fixtures/valid-heartbeat-request.json +23 -0
- package/spec/v1/fixtures/valid-heartbeat-result.sse +13 -0
- package/spec/v1/openapi.json +513 -6
- package/spec/v1/schema-bundle.json +499 -2
package/README.md
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
# `@heddleagent/execution-host-client`
|
|
2
2
|
|
|
3
|
-
`@heddleagent/execution-host-client` is the
|
|
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.
|
|
9
|
-
> `@roackb2/heddle-adopter@5.13.0` coordinate
|
|
10
|
-
>
|
|
8
|
+
> **Current availability:** stable version `6.2.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
|
|
22
|
-
Terraform, product MCP tools, or product logic. It uses the
|
|
23
|
-
|
|
24
|
-
|
|
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
|
|
|
@@ -30,9 +30,11 @@ reference edges.
|
|
|
30
30
|
| `@heddleagent/execution-host-client/contracts` | Runtime-validated v1 request, stream, identity, capability, and header contracts |
|
|
31
31
|
| `@heddleagent/execution-host-client/authority` | ES256 execution assertion and optional MCP capability issuance plus public JWKS projection |
|
|
32
32
|
| `@heddleagent/execution-host-client/conversation` | Turn orchestration across authority, model credentials, optional MCP policy, an `ExecutionHost`, and an optional adopter-implemented durable lifecycle store |
|
|
33
|
+
| `@heddleagent/execution-host-client/heartbeat` | Remote heartbeat orchestration that keeps durable task authority in a coordinator while a compatible Execution Host runs the agent cycle |
|
|
33
34
|
| `@heddleagent/execution-host-client/mcp` | Independent capability verification at the adopter's MCP edge |
|
|
34
35
|
| `@heddleagent/execution-host-client/mcp/node` | Stateless official-SDK Streamable HTTP lifecycle around adopter-defined toolsets |
|
|
35
|
-
| `@heddleagent/execution-host-client/http-sse` | Transport-neutral
|
|
36
|
+
| `@heddleagent/execution-host-client/http-sse` | Transport-neutral conversation and heartbeat ports plus the strict direct-development HTTP/SSE client |
|
|
37
|
+
| `@heddleagent/execution-host-client/agentcore` | Official AWS AgentCore/SigV4 implementation of the same conversation and heartbeat ports |
|
|
36
38
|
| `@heddleagent/execution-host-client/testing` | Node-only loopback v1 fixture plus durable-turn store conformance for real adapters |
|
|
37
39
|
| `@heddleagent/execution-host-client/node` | Optional Node JWKS/conversation HTTP edge plus safe local signing-key helpers |
|
|
38
40
|
|
|
@@ -53,7 +55,8 @@ The adopter still owns:
|
|
|
53
55
|
allocation, the lifecycle-store implementation/schema/migrations, retention,
|
|
54
56
|
and history queries;
|
|
55
57
|
- implementing and hosting product MCP tools against its own APIs and data;
|
|
56
|
-
- choosing
|
|
58
|
+
- choosing and provisioning its AgentCore Runtime, applying results, and
|
|
59
|
+
rendering UI.
|
|
57
60
|
|
|
58
61
|
## Issue one invocation's authority
|
|
59
62
|
|
|
@@ -225,11 +228,32 @@ const productMcp = new NodeStreamableHttpMcpService({
|
|
|
225
228
|
Use the lower-level `NodeMcpToolset` interface only when a tool needs custom MCP
|
|
226
229
|
content or lifecycle semantics.
|
|
227
230
|
|
|
228
|
-
## Invoke
|
|
231
|
+
## Invoke an Execution Host
|
|
229
232
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
+
Use the official AgentCore client for a Runtime deployed in the adopter's AWS
|
|
234
|
+
account. It uses the normal AWS credential chain, signs the required Heddle
|
|
235
|
+
authority headers, streams the response through the same strict protocol
|
|
236
|
+
validation as the direct client, and deliberately makes only one ambiguous
|
|
237
|
+
streaming attempt.
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
import {
|
|
241
|
+
AgentCoreExecutionHost,
|
|
242
|
+
} from '@heddleagent/execution-host-client/agentcore'
|
|
243
|
+
|
|
244
|
+
const host = new AgentCoreExecutionHost({
|
|
245
|
+
region: process.env.AWS_REGION!,
|
|
246
|
+
runtimeArn: process.env.AGENTCORE_RUNTIME_ARN!,
|
|
247
|
+
qualifier: process.env.AGENTCORE_RUNTIME_QUALIFIER,
|
|
248
|
+
})
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
The product still owns the AWS account, Runtime deployment, IAM policy,
|
|
252
|
+
configuration, and credentials environment. Heddle owns only the reusable
|
|
253
|
+
invocation transport.
|
|
254
|
+
|
|
255
|
+
For local development and reviewed direct HTTPS deployments, use the direct
|
|
256
|
+
client:
|
|
233
257
|
|
|
234
258
|
```ts
|
|
235
259
|
import { DirectHttpExecutionHost } from '@heddleagent/execution-host-client/http-sse'
|
|
@@ -255,6 +279,44 @@ The client refuses redirects, bounds parser and error bodies, validates ordered
|
|
|
255
279
|
SSE identity, streams accepted/activity events incrementally, and withholds the
|
|
256
280
|
terminal event until clean EOF. It never retries an ambiguous invocation.
|
|
257
281
|
|
|
282
|
+
## Delegate heartbeat agent cycles
|
|
283
|
+
|
|
284
|
+
For autonomous work, keep the durable task store and scheduler in one
|
|
285
|
+
long-running coordinator. Inject the hosted transport only at the point where
|
|
286
|
+
the scheduler would otherwise run the local heartbeat agent:
|
|
287
|
+
|
|
288
|
+
```ts
|
|
289
|
+
import { HeartbeatSchedulerService } from '@heddleagent/runtime/advanced'
|
|
290
|
+
import {
|
|
291
|
+
HostedHeartbeatAgentExecutionTransport,
|
|
292
|
+
HostedHeartbeatTaskService,
|
|
293
|
+
} from '@heddleagent/execution-host-client/heartbeat'
|
|
294
|
+
|
|
295
|
+
const hostedHeartbeat = new HostedHeartbeatTaskService({
|
|
296
|
+
authority,
|
|
297
|
+
executionHost: agentCoreExecutionHost,
|
|
298
|
+
modelCredentials,
|
|
299
|
+
mcp: { allowedTools: ['read_workspace_snapshot'] },
|
|
300
|
+
})
|
|
301
|
+
const agentExecutionTransport = new HostedHeartbeatAgentExecutionTransport({
|
|
302
|
+
runner: hostedHeartbeat,
|
|
303
|
+
resolveInvocationContext: ({ taskId, executionId, signal }) => (
|
|
304
|
+
resolveAuthorizedHeartbeatInvocation({ taskId, executionId, signal })
|
|
305
|
+
),
|
|
306
|
+
})
|
|
307
|
+
|
|
308
|
+
const scheduler = HeartbeatSchedulerService.start({
|
|
309
|
+
store: heddleHeartbeatStore,
|
|
310
|
+
agentExecutionTransport,
|
|
311
|
+
})
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
The coordinator still owns task lookup, claims, checkpoint loading, cancellation,
|
|
315
|
+
claim-fenced settlement, history, and recovery. The Runtime receives a bounded
|
|
316
|
+
task/checkpoint request plus invocation-scoped authority and model credentials;
|
|
317
|
+
it receives no Heddle database credential. Omitting `agentExecutionTransport`
|
|
318
|
+
preserves the existing in-process runner.
|
|
319
|
+
|
|
258
320
|
## Verify an adopter integration locally
|
|
259
321
|
|
|
260
322
|
The explicit `testing` subpath provides a real loopback implementation of the
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type ExecutionHostHeartbeatStreamEvent, type ExecutionHostStreamEvent } from '../contracts/index.js';
|
|
2
|
+
import { type ExecutionHost, type ExecutionHostConversationTurn, type ExecutionHostHeartbeatTask, type HeartbeatExecutionHost } 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, HeartbeatExecutionHost {
|
|
9
|
+
#private;
|
|
10
|
+
constructor(config: AgentCoreExecutionHostConfig);
|
|
11
|
+
streamConversationTurn(input: ExecutionHostConversationTurn): AsyncIterable<ExecutionHostStreamEvent>;
|
|
12
|
+
streamHeartbeatTask(input: ExecutionHostHeartbeatTask): AsyncIterable<ExecutionHostHeartbeatStreamEvent>;
|
|
13
|
+
close(): void;
|
|
14
|
+
}
|
|
15
|
+
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"];
|
|
16
|
+
export declare const AGENTCORE_EXCLUDED_HEADER_NAMES: readonly ["x-heddle-execution-host-local-token"];
|
|
17
|
+
//# 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,iCAAiC,EACtC,KAAK,wBAAwB,EAC9B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAEL,KAAK,aAAa,EAClB,KAAK,6BAA6B,EAClC,KAAK,0BAA0B,EAC/B,KAAK,sBAAsB,EAC5B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EACV,4BAA4B,EAE7B,MAAM,YAAY,CAAC;AAoBpB;;;GAGG;AACH,qBAAa,sBACb,YAAW,aAAa,EAAE,sBAAsB;;gBAMlC,MAAM,EAAE,4BAA4B;IAgBhD,sBAAsB,CACpB,KAAK,EAAE,6BAA6B,GACnC,aAAa,CAAC,wBAAwB,CAAC;IAK1C,mBAAmB,CACjB,KAAK,EAAE,0BAA0B,GAChC,aAAa,CAAC,iCAAiC,CAAC;IAKnD,KAAK,IAAI,IAAI;CAiEd;AAsGD,eAAO,MAAM,gCAAgC,mIAIlC,CAAC;AAEZ,eAAO,MAAM,+BAA+B,kDAEjC,CAAC"}
|
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
streamHeartbeatTask(input) {
|
|
51
|
+
assertAgentCoreRuntimeSessionId(input.runtimeSessionId);
|
|
52
|
+
return this.#wire.streamHeartbeatTask(input);
|
|
53
|
+
}
|
|
54
|
+
close() {
|
|
55
|
+
this.#client.destroy?.();
|
|
56
|
+
}
|
|
57
|
+
async #invoke(init) {
|
|
58
|
+
if (init?.method !== 'POST' || typeof init.body !== 'string') {
|
|
59
|
+
throw new Error('AgentCore wire bridge received an invalid request.');
|
|
60
|
+
}
|
|
61
|
+
const headers = new Headers(init.headers);
|
|
62
|
+
const runtimeSessionId = requireHeader(headers, AGENTCORE_RUNTIME_SESSION_HEADER);
|
|
63
|
+
const customHeaders = Object.fromEntries([
|
|
64
|
+
[
|
|
65
|
+
EXECUTION_ASSERTION_HEADER,
|
|
66
|
+
requireHeader(headers, EXECUTION_ASSERTION_HEADER),
|
|
67
|
+
],
|
|
68
|
+
[MODEL_API_KEY_HEADER, requireHeader(headers, MODEL_API_KEY_HEADER)],
|
|
69
|
+
...(headers.has(MCP_CAPABILITY_HEADER)
|
|
70
|
+
? [[MCP_CAPABILITY_HEADER, headers.get(MCP_CAPABILITY_HEADER)]]
|
|
71
|
+
: []),
|
|
72
|
+
]);
|
|
73
|
+
const command = new InvokeAgentRuntimeCommand({
|
|
74
|
+
agentRuntimeArn: this.#runtimeArn,
|
|
75
|
+
runtimeSessionId,
|
|
76
|
+
qualifier: this.#qualifier,
|
|
77
|
+
contentType: CONTENT_TYPE,
|
|
78
|
+
accept: ACCEPT,
|
|
79
|
+
payload: new TextEncoder().encode(init.body),
|
|
80
|
+
});
|
|
81
|
+
addSignedCustomHeaders(command, customHeaders);
|
|
82
|
+
const signal = init.signal ?? undefined;
|
|
83
|
+
try {
|
|
84
|
+
const output = await this.#client.send(command, { abortSignal: signal });
|
|
85
|
+
return new Response(output.response ? toReadableStream(output.response) : null, {
|
|
86
|
+
status: output.statusCode ?? output.$metadata.httpStatusCode ?? 200,
|
|
87
|
+
headers: {
|
|
88
|
+
'content-type': output.contentType ?? 'application/octet-stream',
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (signal?.aborted) {
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
const status = readServiceStatus(error);
|
|
97
|
+
if (!status) {
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
const code = SERVICE_ERROR_CODES.get(readErrorName(error)) ?? 'unknown';
|
|
101
|
+
return new Response(JSON.stringify({
|
|
102
|
+
error: {
|
|
103
|
+
code,
|
|
104
|
+
message: 'AgentCore rejected the invocation.',
|
|
105
|
+
},
|
|
106
|
+
}), {
|
|
107
|
+
status,
|
|
108
|
+
headers: { 'content-type': CONTENT_TYPE },
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function assertAgentCoreRuntimeSessionId(value) {
|
|
114
|
+
if (value.length < MIN_RUNTIME_SESSION_ID_LENGTH
|
|
115
|
+
|| value.length > MAX_RUNTIME_SESSION_ID_LENGTH
|
|
116
|
+
|| !RUNTIME_SESSION_ID_PATTERN.test(value)) {
|
|
117
|
+
throw new Error('AgentCore runtime session ID is not provider-compatible.');
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function addSignedCustomHeaders(command, headers) {
|
|
121
|
+
command.middlewareStack.add((next) => async (args) => {
|
|
122
|
+
if (!HttpRequest.isInstance(args.request)) {
|
|
123
|
+
throw new Error('AgentCore invocation did not produce an HTTP request.');
|
|
124
|
+
}
|
|
125
|
+
Object.assign(args.request.headers, headers);
|
|
126
|
+
return await next(args);
|
|
127
|
+
}, {
|
|
128
|
+
step: 'build',
|
|
129
|
+
priority: 'low',
|
|
130
|
+
name: 'heddleAgentCoreCustomHeaders',
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
function requireHeader(headers, name) {
|
|
134
|
+
const value = headers.get(name);
|
|
135
|
+
if (!value) {
|
|
136
|
+
throw new Error('AgentCore wire bridge omitted required authority.');
|
|
137
|
+
}
|
|
138
|
+
return value;
|
|
139
|
+
}
|
|
140
|
+
function toReadableStream(source) {
|
|
141
|
+
if (source instanceof Blob) {
|
|
142
|
+
return source.stream();
|
|
143
|
+
}
|
|
144
|
+
if (source instanceof ReadableStream) {
|
|
145
|
+
return source;
|
|
146
|
+
}
|
|
147
|
+
if (!isAsyncIterable(source)) {
|
|
148
|
+
throw new Error('AgentCore returned an unsupported stream type.');
|
|
149
|
+
}
|
|
150
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
151
|
+
return new ReadableStream({
|
|
152
|
+
async pull(controller) {
|
|
153
|
+
try {
|
|
154
|
+
const item = await iterator.next();
|
|
155
|
+
if (item.done) {
|
|
156
|
+
controller.close();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (!(item.value instanceof Uint8Array)) {
|
|
160
|
+
throw new Error('AgentCore returned a non-binary stream chunk.');
|
|
161
|
+
}
|
|
162
|
+
controller.enqueue(item.value);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
controller.error(error);
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
async cancel() {
|
|
169
|
+
await iterator.return?.();
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
function isAsyncIterable(value) {
|
|
174
|
+
return Boolean(value
|
|
175
|
+
&& typeof value === 'object'
|
|
176
|
+
&& Symbol.asyncIterator in value
|
|
177
|
+
&& typeof value[Symbol.asyncIterator] === 'function');
|
|
178
|
+
}
|
|
179
|
+
function readServiceStatus(error) {
|
|
180
|
+
if (!error || typeof error !== 'object' || !('$metadata' in error)) {
|
|
181
|
+
return undefined;
|
|
182
|
+
}
|
|
183
|
+
const metadata = error
|
|
184
|
+
.$metadata;
|
|
185
|
+
const status = metadata?.httpStatusCode;
|
|
186
|
+
return typeof status === 'number' && status >= 400 && status <= 599
|
|
187
|
+
? status
|
|
188
|
+
: undefined;
|
|
189
|
+
}
|
|
190
|
+
function readErrorName(error) {
|
|
191
|
+
return error instanceof Error ? error.name : '';
|
|
192
|
+
}
|
|
193
|
+
export const AGENTCORE_FORWARDED_HEADER_NAMES = Object.freeze([
|
|
194
|
+
EXECUTION_ASSERTION_HEADER,
|
|
195
|
+
MCP_CAPABILITY_HEADER,
|
|
196
|
+
MODEL_API_KEY_HEADER,
|
|
197
|
+
]);
|
|
198
|
+
export const AGENTCORE_EXCLUDED_HEADER_NAMES = Object.freeze([
|
|
199
|
+
EXECUTION_HOST_LOCAL_TOKEN_HEADER,
|
|
200
|
+
]);
|
|
201
|
+
//# 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,GAGrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,uBAAuB,GAKxB,MAAM,sBAAsB,CAAC;AAM9B,MAAM,YAAY,GAAG,kBAAkB,CAAC;AACxC,MAAM,MAAM,GAAG,mBAAmB,CAAC;AACnC,MAAM,6BAA6B,GAAG,EAAE,CAAC;AACzC,MAAM,6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KAAK,KAAK,QAAQ,IAAI,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 ExecutionHostHeartbeatStreamEvent,\n type ExecutionHostStreamEvent,\n} from '../contracts/index.js';\nimport {\n DirectHttpExecutionHost,\n type ExecutionHost,\n type ExecutionHostConversationTurn,\n type ExecutionHostHeartbeatTask,\n type HeartbeatExecutionHost,\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\nimplements ExecutionHost, HeartbeatExecutionHost {\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 streamHeartbeatTask(\n input: ExecutionHostHeartbeatTask,\n ): AsyncIterable<ExecutionHostHeartbeatStreamEvent> {\n assertAgentCoreRuntimeSessionId(input.runtimeSessionId);\n return this.#wire.streamHeartbeatTask(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 @@
|
|
|
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 @@
|
|
|
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 @@
|
|
|
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"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { CompactSign, SignJWT, compactVerify, exportJWK, } from 'jose';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import {
|
|
4
|
+
import { EXECUTION_ASSERTION_TYPE, EXECUTION_CONTRACT_VERSION, ExecutionScopeSchema, HostedExecutionWorkflowSchema, JwtAudienceSchema, JwtIssuerSchema, MCP_CAPABILITY_TYPE, McpAllowedToolsSchema, McpServerIdSchema, OpaqueIdSchema, RuntimeSessionIdSchema, } from '../contracts/index.js';
|
|
5
5
|
const SIGNING_ALGORITHM = 'ES256';
|
|
6
6
|
const ExecutionAuthorityMcpConfigSchema = z.object({
|
|
7
7
|
audience: JwtAudienceSchema,
|
|
@@ -39,7 +39,7 @@ const ExecutionAuthorityIssueInputSchema = z.object({
|
|
|
39
39
|
scope: ExecutionIssueScopeSchema,
|
|
40
40
|
runtimeSessionId: RuntimeSessionIdSchema,
|
|
41
41
|
invocationId: OpaqueIdSchema,
|
|
42
|
-
workflow:
|
|
42
|
+
workflow: HostedExecutionWorkflowSchema,
|
|
43
43
|
mcp: z.object({
|
|
44
44
|
allowedTools: McpAllowedToolsSchema,
|
|
45
45
|
}).strict().optional(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jose-execution-authority.js","sourceRoot":"","sources":["../../src/authority/jose-execution-authority.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACL,WAAW,EACX,OAAO,EACP,aAAa,EACb,SAAS,GAIV,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,0BAA0B,EAC1B,wBAAwB,EACxB,0BAA0B,EAC1B,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,EACf,mBAAmB,EACnB,qBAAqB,EACrB,iBAAiB,EACjB,cAAc,EACd,sBAAsB,GAEvB,MAA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AAI,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;AACtD,CAAC;AAED,SAAS,gBAAgB,CACvB,MAAsD;IAEtD,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACtE,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,oBAAoB,CAC3B,QAA0C;IAE1C,MAAM,KAAK,GAAmB,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IACnE,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAG;QACtB,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC;YACd,GAAG,QAAQ,CAAC,GAAG;YACf,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;SAC5D,CAAC;QACF,CAAC,CAAC,SAAS,CAAC;IACd,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,QAAQ,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AACxE,CAAC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport {\n CompactSign,\n SignJWT,\n compactVerify,\n exportJWK,\n type CryptoKey,\n type JWK,\n type JSONWebKeySet,\n} from 'jose';\nimport { z } from 'zod';\nimport {\n CONVERSATION_TURN_WORKFLOW,\n EXECUTION_ASSERTION_TYPE,\n EXECUTION_CONTRACT_VERSION,\n ExecutionScopeSchema,\n JwtAudienceSchema,\n JwtIssuerSchema,\n MCP_CAPABILITY_TYPE,\n McpAllowedToolsSchema,\n McpServerIdSchema,\n OpaqueIdSchema,\n RuntimeSessionIdSchema,\n type ExecutionScope,\n} from '../contracts/index.js';\nimport type {\n ExecutionAuthority,\n ExecutionAuthorityConfig,\n ExecutionAuthorityIssueInput,\n ExecutionAuthorityKeyPair,\n IssuedExecutionAuthority,\n IssuedExecutionAuthorityMetadata,\n JoseExecutionAuthorityOptions,\n} from './types.js';\n\nconst SIGNING_ALGORITHM = 'ES256';\nconst ExecutionAuthorityMcpConfigSchema = z.object({\n audience: JwtAudienceSchema,\n serverId: McpServerIdSchema,\n ttlSeconds: z.number().int().min(1).max(15 * 60),\n}).strict();\nconst ExecutionAuthorityConfigSchema = z.object({\n issuer: JwtIssuerSchema,\n adopterId: OpaqueIdSchema,\n executionAudience: JwtAudienceSchema,\n keyId: OpaqueIdSchema,\n executionTtlSeconds: z.number().int().min(1).max(15 * 60),\n mcp: ExecutionAuthorityMcpConfigSchema.optional(),\n}).strict().superRefine((config, context) => {\n if (!config.mcp) {\n return;\n }\n if (config.executionAudience === config.mcp.audience) {\n context.addIssue({\n code: 'custom',\n path: ['mcp', 'audience'],\n message: 'must be distinct from the execution audience',\n });\n }\n if (config.mcp.ttlSeconds < config.executionTtlSeconds) {\n context.addIssue({\n code: 'custom',\n path: ['mcp', 'ttlSeconds'],\n message: 'must not expire before execution admission authority',\n });\n }\n});\nconst ExecutionIssueScopeSchema = ExecutionScopeSchema.omit({ adopterId: true });\nconst ExecutionAuthorityIssueInputSchema = z.object({\n scope: ExecutionIssueScopeSchema,\n runtimeSessionId: RuntimeSessionIdSchema,\n invocationId: OpaqueIdSchema,\n workflow: z.literal(CONVERSATION_TURN_WORKFLOW),\n mcp: z.object({\n allowedTools: McpAllowedToolsSchema,\n }).strict().optional(),\n}).strict();\nconst PublicP256JwkSchema = z.object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n x: z.string().regex(/^[A-Za-z0-9_-]+$/),\n y: z.string().regex(/^[A-Za-z0-9_-]+$/),\n}).passthrough().superRefine((jwk, context) => {\n const privateFields = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'];\n if (privateFields.some((field) => field in jwk)) {\n context.addIssue({\n code: 'custom',\n message: 'must not contain private key material',\n });\n }\n});\n\n/**\n * ES256 reference adapter for issuing one invocation's admission assertion and\n * optional product-MCP capability.\n */\nexport class JoseExecutionAuthority implements ExecutionAuthority {\n readonly #config: z.infer<typeof ExecutionAuthorityConfigSchema>;\n readonly #privateKey: CryptoKey;\n readonly #publicJwk: Readonly<JWK>;\n readonly #now: () => Date;\n readonly #createCapabilityId: () => string;\n\n private constructor(\n config: ExecutionAuthorityConfig,\n key: { privateKey: CryptoKey; publicJwk: JWK },\n options: JoseExecutionAuthorityOptions,\n ) {\n this.#config = deepFreezeConfig(ExecutionAuthorityConfigSchema.parse(config));\n assertPrivateSigningKey(key.privateKey);\n this.#privateKey = key.privateKey;\n this.#publicJwk = projectPublicJwk(key.publicJwk, this.#config.keyId);\n this.#now = options.now ?? (() => new Date());\n this.#createCapabilityId = options.createCapabilityId ?? randomUUID;\n }\n\n static async create(\n config: ExecutionAuthorityConfig,\n keyPair: ExecutionAuthorityKeyPair,\n options: JoseExecutionAuthorityOptions = {},\n ): Promise<JoseExecutionAuthority> {\n assertPrivateSigningKey(keyPair.privateKey);\n assertPublicVerificationKey(keyPair.publicKey);\n await assertMatchingKeyPair(keyPair);\n return new JoseExecutionAuthority(\n config,\n {\n privateKey: keyPair.privateKey,\n publicJwk: await exportJWK(keyPair.publicKey),\n },\n options,\n );\n }\n\n async issue(\n input: ExecutionAuthorityIssueInput,\n ): Promise<IssuedExecutionAuthority> {\n const authority = ExecutionAuthorityIssueInputSchema.parse(input);\n if (authority.mcp && !this.#config.mcp) {\n throw new Error(\n 'Execution authority cannot issue an MCP capability without MCP deployment configuration.',\n );\n }\n\n const issuedAt = toEpochSeconds(this.#now());\n const executionExpiresAt = issuedAt + this.#config.executionTtlSeconds;\n const executionAssertion = await this.#signExecutionAssertion(\n authority,\n issuedAt,\n executionExpiresAt,\n );\n\n const mcp = authority.mcp && this.#config.mcp\n ? await this.#issueMcpCapability(\n { ...authority, mcp: authority.mcp },\n issuedAt,\n )\n : undefined;\n\n return new ProtectedIssuedExecutionAuthority(\n executionAssertion,\n mcp?.assertion,\n freezeIssuedMetadata({\n scope: {\n adopterId: this.#config.adopterId,\n ...authority.scope,\n },\n runtimeSessionId: authority.runtimeSessionId,\n invocationId: authority.invocationId,\n workflow: authority.workflow,\n issuedAt: toIsoTimestamp(issuedAt),\n executionExpiresAt: toIsoTimestamp(executionExpiresAt),\n ...(mcp ? { mcp: mcp.metadata } : {}),\n }),\n );\n }\n\n publicJwks(): JSONWebKeySet {\n return { keys: [{ ...this.#publicJwk }] };\n }\n\n #signExecutionAssertion(\n input: z.infer<typeof ExecutionAuthorityIssueInputSchema>,\n issuedAt: number,\n expiresAt: number,\n ): Promise<string> {\n return new SignJWT({\n contractVersion: EXECUTION_CONTRACT_VERSION,\n adopterId: this.#config.adopterId,\n tenantId: input.scope.tenantId,\n productSessionId: input.scope.productSessionId,\n runtimeSessionId: input.runtimeSessionId,\n workflow: input.workflow,\n })\n .setProtectedHeader({\n alg: SIGNING_ALGORITHM,\n kid: this.#config.keyId,\n typ: EXECUTION_ASSERTION_TYPE,\n })\n .setIssuer(this.#config.issuer)\n .setAudience(this.#config.executionAudience)\n .setSubject(input.scope.subjectId)\n .setJti(input.invocationId)\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAt)\n .sign(this.#privateKey);\n }\n\n async #issueMcpCapability(\n input: z.infer<typeof ExecutionAuthorityIssueInputSchema> & {\n mcp: { allowedTools: string[] };\n },\n issuedAt: number,\n ): Promise<{\n assertion: string;\n metadata: NonNullable<IssuedExecutionAuthorityMetadata['mcp']>;\n }> {\n const mcpConfig = this.#config.mcp!;\n const capabilityId = OpaqueIdSchema.parse(this.#createCapabilityId());\n if (capabilityId === input.invocationId) {\n throw new Error(\n 'MCP capability identity must be distinct from the invocation identity.',\n );\n }\n const expiresAt = issuedAt + mcpConfig.ttlSeconds;\n const assertion = await new SignJWT({\n contractVersion: EXECUTION_CONTRACT_VERSION,\n adopterId: this.#config.adopterId,\n tenantId: input.scope.tenantId,\n productSessionId: input.scope.productSessionId,\n runtimeSessionId: input.runtimeSessionId,\n invocationId: input.invocationId,\n workflow: input.workflow,\n serverId: mcpConfig.serverId,\n allowedTools: [...input.mcp.allowedTools],\n })\n .setProtectedHeader({\n alg: SIGNING_ALGORITHM,\n kid: this.#config.keyId,\n typ: MCP_CAPABILITY_TYPE,\n })\n .setIssuer(this.#config.issuer)\n .setAudience(mcpConfig.audience)\n .setSubject(input.scope.subjectId)\n .setJti(capabilityId)\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAt)\n .sign(this.#privateKey);\n\n return {\n assertion,\n metadata: {\n capabilityId,\n serverId: mcpConfig.serverId,\n allowedTools: Object.freeze([...input.mcp.allowedTools]),\n expiresAt: toIsoTimestamp(expiresAt),\n },\n };\n }\n}\n\nclass ProtectedIssuedExecutionAuthority implements IssuedExecutionAuthority {\n readonly metadata: IssuedExecutionAuthorityMetadata;\n readonly #executionAssertion: string;\n readonly #mcpCapability: string | undefined;\n\n constructor(\n executionAssertion: string,\n mcpCapability: string | undefined,\n metadata: IssuedExecutionAuthorityMetadata,\n ) {\n this.#executionAssertion = executionAssertion;\n this.#mcpCapability = mcpCapability;\n this.metadata = metadata;\n }\n\n executionAssertion(): string {\n return this.#executionAssertion;\n }\n\n mcpCapability(): string | undefined {\n return this.#mcpCapability;\n }\n\n toJSON(): IssuedExecutionAuthorityMetadata {\n return this.metadata;\n }\n}\n\nfunction projectPublicJwk(jwk: JWK, keyId: string): Readonly<JWK> {\n const parsed = PublicP256JwkSchema.parse(jwk);\n return Object.freeze({\n kty: parsed.kty,\n crv: parsed.crv,\n x: parsed.x,\n y: parsed.y,\n alg: SIGNING_ALGORITHM,\n kid: keyId,\n use: 'sig',\n });\n}\n\nfunction assertPrivateSigningKey(key: CryptoKey): void {\n const algorithm = key.algorithm as { name: string; namedCurve?: string };\n const accepted = key.type === 'private'\n && algorithm.name === 'ECDSA'\n && algorithm.namedCurve === 'P-256'\n && key.usages.includes('sign');\n if (!accepted) {\n throw new Error(\n 'Execution authority requires an ES256 private signing key.',\n );\n }\n}\n\nfunction assertPublicVerificationKey(key: CryptoKey): void {\n const algorithm = key.algorithm as { name: string; namedCurve?: string };\n const accepted = key.type === 'public'\n && algorithm.name === 'ECDSA'\n && algorithm.namedCurve === 'P-256'\n && key.usages.includes('verify');\n if (!accepted) {\n throw new Error(\n 'Execution authority requires an ES256 public verification key.',\n );\n }\n}\n\nasync function assertMatchingKeyPair(\n keyPair: ExecutionAuthorityKeyPair,\n): Promise<void> {\n try {\n const probe = await new CompactSign(\n new TextEncoder().encode('heddle-adopter-execution-authority-key-pair'),\n )\n .setProtectedHeader({ alg: SIGNING_ALGORITHM })\n .sign(keyPair.privateKey);\n await compactVerify(probe, keyPair.publicKey, {\n algorithms: [SIGNING_ALGORITHM],\n });\n } catch {\n throw new Error('Execution authority signing keys do not match.');\n }\n}\n\nfunction toEpochSeconds(value: Date): number {\n const seconds = Math.floor(value.getTime() / 1_000);\n if (!Number.isSafeInteger(seconds) || seconds < 0) {\n throw new Error('Execution authority could not resolve a valid issue time.');\n }\n return seconds;\n}\n\nfunction toIsoTimestamp(epochSeconds: number): string {\n return new Date(epochSeconds * 1_000).toISOString();\n}\n\nfunction deepFreezeConfig(\n config: z.infer<typeof ExecutionAuthorityConfigSchema>,\n): z.infer<typeof ExecutionAuthorityConfigSchema> {\n const mcp = config.mcp ? Object.freeze({ ...config.mcp }) : undefined;\n return Object.freeze({ ...config, ...(mcp ? { mcp } : {}) });\n}\n\nfunction freezeIssuedMetadata(\n metadata: IssuedExecutionAuthorityMetadata,\n): IssuedExecutionAuthorityMetadata {\n const scope: ExecutionScope = Object.freeze({ ...metadata.scope });\n const mcp = metadata.mcp\n ? Object.freeze({\n ...metadata.mcp,\n allowedTools: Object.freeze([...metadata.mcp.allowedTools]),\n })\n : undefined;\n return Object.freeze({ ...metadata, scope, ...(mcp ? { mcp } : {}) });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"jose-execution-authority.js","sourceRoot":"","sources":["../../src/authority/jose-execution-authority.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACL,WAAW,EACX,OAAO,EACP,aAAa,EACb,SAAS,GAIV,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,wBAAwB,EACxB,0BAA0B,EAC1B,oBAAoB,EACpB,6BAA6B,EAC7B,iBAAiB,EACjB,eAAe,EACf,mBAAmB,EACnB,qBAAqB,EACrB,iBAAiB,EACjB,cAAc,EACd,sBAAsB,GAEvB,MAAM,uBAAuB,CAAC;AAW/B,MAAM,iBAAiB,GAAG,OAAO,CAAC;AAClC,MAAM,iCAAiC,GAAG,CAAC,CAAC,MAAM,CAAC;IACjD,QAAQ,EAAE,iBAAiB;IAC3B,QAAQ,EAAE,iBAAiB;IAC3B,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC;CACjD,CAAC,CAAC,MAAM,EAAE,CAAC;AACZ,MAAM,8BAA8B,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9C,MAAM,EAAE,eAAe;IACvB,SAAS,EAAE,cAAc;IACzB,iBAAiB,EAAE,iBAAiB;IACpC,KAAK,EAAE,cAAc;IACrB,mBAAmB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAA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MAAM,CAAC;YACd,GAAG,QAAQ,CAAC,GAAG;YACf,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;SAC5D,CAAC;QACF,CAAC,CAAC,SAAS,CAAC;IACd,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,QAAQ,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AACxE,CAAC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport {\n CompactSign,\n SignJWT,\n compactVerify,\n exportJWK,\n type CryptoKey,\n type JWK,\n type JSONWebKeySet,\n} from 'jose';\nimport { z } from 'zod';\nimport {\n EXECUTION_ASSERTION_TYPE,\n EXECUTION_CONTRACT_VERSION,\n ExecutionScopeSchema,\n HostedExecutionWorkflowSchema,\n JwtAudienceSchema,\n JwtIssuerSchema,\n MCP_CAPABILITY_TYPE,\n McpAllowedToolsSchema,\n McpServerIdSchema,\n OpaqueIdSchema,\n RuntimeSessionIdSchema,\n type ExecutionScope,\n} from '../contracts/index.js';\nimport type {\n ExecutionAuthority,\n ExecutionAuthorityConfig,\n ExecutionAuthorityIssueInput,\n ExecutionAuthorityKeyPair,\n IssuedExecutionAuthority,\n IssuedExecutionAuthorityMetadata,\n JoseExecutionAuthorityOptions,\n} from './types.js';\n\nconst SIGNING_ALGORITHM = 'ES256';\nconst ExecutionAuthorityMcpConfigSchema = z.object({\n audience: JwtAudienceSchema,\n serverId: McpServerIdSchema,\n ttlSeconds: z.number().int().min(1).max(15 * 60),\n}).strict();\nconst ExecutionAuthorityConfigSchema = z.object({\n issuer: JwtIssuerSchema,\n adopterId: OpaqueIdSchema,\n executionAudience: JwtAudienceSchema,\n keyId: OpaqueIdSchema,\n executionTtlSeconds: z.number().int().min(1).max(15 * 60),\n mcp: ExecutionAuthorityMcpConfigSchema.optional(),\n}).strict().superRefine((config, context) => {\n if (!config.mcp) {\n return;\n }\n if (config.executionAudience === config.mcp.audience) {\n context.addIssue({\n code: 'custom',\n path: ['mcp', 'audience'],\n message: 'must be distinct from the execution audience',\n });\n }\n if (config.mcp.ttlSeconds < config.executionTtlSeconds) {\n context.addIssue({\n code: 'custom',\n path: ['mcp', 'ttlSeconds'],\n message: 'must not expire before execution admission authority',\n });\n }\n});\nconst ExecutionIssueScopeSchema = ExecutionScopeSchema.omit({ adopterId: true });\nconst ExecutionAuthorityIssueInputSchema = z.object({\n scope: ExecutionIssueScopeSchema,\n runtimeSessionId: RuntimeSessionIdSchema,\n invocationId: OpaqueIdSchema,\n workflow: HostedExecutionWorkflowSchema,\n mcp: z.object({\n allowedTools: McpAllowedToolsSchema,\n }).strict().optional(),\n}).strict();\nconst PublicP256JwkSchema = z.object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n x: z.string().regex(/^[A-Za-z0-9_-]+$/),\n y: z.string().regex(/^[A-Za-z0-9_-]+$/),\n}).passthrough().superRefine((jwk, context) => {\n const privateFields = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'];\n if (privateFields.some((field) => field in jwk)) {\n context.addIssue({\n code: 'custom',\n message: 'must not contain private key material',\n });\n }\n});\n\n/**\n * ES256 reference adapter for issuing one invocation's admission assertion and\n * optional product-MCP capability.\n */\nexport class JoseExecutionAuthority implements ExecutionAuthority {\n readonly #config: z.infer<typeof ExecutionAuthorityConfigSchema>;\n readonly #privateKey: CryptoKey;\n readonly #publicJwk: Readonly<JWK>;\n readonly #now: () => Date;\n readonly #createCapabilityId: () => string;\n\n private constructor(\n config: ExecutionAuthorityConfig,\n key: { privateKey: CryptoKey; publicJwk: JWK },\n options: JoseExecutionAuthorityOptions,\n ) {\n this.#config = deepFreezeConfig(ExecutionAuthorityConfigSchema.parse(config));\n assertPrivateSigningKey(key.privateKey);\n this.#privateKey = key.privateKey;\n this.#publicJwk = projectPublicJwk(key.publicJwk, this.#config.keyId);\n this.#now = options.now ?? (() => new Date());\n this.#createCapabilityId = options.createCapabilityId ?? randomUUID;\n }\n\n static async create(\n config: ExecutionAuthorityConfig,\n keyPair: ExecutionAuthorityKeyPair,\n options: JoseExecutionAuthorityOptions = {},\n ): Promise<JoseExecutionAuthority> {\n assertPrivateSigningKey(keyPair.privateKey);\n assertPublicVerificationKey(keyPair.publicKey);\n await assertMatchingKeyPair(keyPair);\n return new JoseExecutionAuthority(\n config,\n {\n privateKey: keyPair.privateKey,\n publicJwk: await exportJWK(keyPair.publicKey),\n },\n options,\n );\n }\n\n async issue(\n input: ExecutionAuthorityIssueInput,\n ): Promise<IssuedExecutionAuthority> {\n const authority = ExecutionAuthorityIssueInputSchema.parse(input);\n if (authority.mcp && !this.#config.mcp) {\n throw new Error(\n 'Execution authority cannot issue an MCP capability without MCP deployment configuration.',\n );\n }\n\n const issuedAt = toEpochSeconds(this.#now());\n const executionExpiresAt = issuedAt + this.#config.executionTtlSeconds;\n const executionAssertion = await this.#signExecutionAssertion(\n authority,\n issuedAt,\n executionExpiresAt,\n );\n\n const mcp = authority.mcp && this.#config.mcp\n ? await this.#issueMcpCapability(\n { ...authority, mcp: authority.mcp },\n issuedAt,\n )\n : undefined;\n\n return new ProtectedIssuedExecutionAuthority(\n executionAssertion,\n mcp?.assertion,\n freezeIssuedMetadata({\n scope: {\n adopterId: this.#config.adopterId,\n ...authority.scope,\n },\n runtimeSessionId: authority.runtimeSessionId,\n invocationId: authority.invocationId,\n workflow: authority.workflow,\n issuedAt: toIsoTimestamp(issuedAt),\n executionExpiresAt: toIsoTimestamp(executionExpiresAt),\n ...(mcp ? { mcp: mcp.metadata } : {}),\n }),\n );\n }\n\n publicJwks(): JSONWebKeySet {\n return { keys: [{ ...this.#publicJwk }] };\n }\n\n #signExecutionAssertion(\n input: z.infer<typeof ExecutionAuthorityIssueInputSchema>,\n issuedAt: number,\n expiresAt: number,\n ): Promise<string> {\n return new SignJWT({\n contractVersion: EXECUTION_CONTRACT_VERSION,\n adopterId: this.#config.adopterId,\n tenantId: input.scope.tenantId,\n productSessionId: input.scope.productSessionId,\n runtimeSessionId: input.runtimeSessionId,\n workflow: input.workflow,\n })\n .setProtectedHeader({\n alg: SIGNING_ALGORITHM,\n kid: this.#config.keyId,\n typ: EXECUTION_ASSERTION_TYPE,\n })\n .setIssuer(this.#config.issuer)\n .setAudience(this.#config.executionAudience)\n .setSubject(input.scope.subjectId)\n .setJti(input.invocationId)\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAt)\n .sign(this.#privateKey);\n }\n\n async #issueMcpCapability(\n input: z.infer<typeof ExecutionAuthorityIssueInputSchema> & {\n mcp: { allowedTools: string[] };\n },\n issuedAt: number,\n ): Promise<{\n assertion: string;\n metadata: NonNullable<IssuedExecutionAuthorityMetadata['mcp']>;\n }> {\n const mcpConfig = this.#config.mcp!;\n const capabilityId = OpaqueIdSchema.parse(this.#createCapabilityId());\n if (capabilityId === input.invocationId) {\n throw new Error(\n 'MCP capability identity must be distinct from the invocation identity.',\n );\n }\n const expiresAt = issuedAt + mcpConfig.ttlSeconds;\n const assertion = await new SignJWT({\n contractVersion: EXECUTION_CONTRACT_VERSION,\n adopterId: this.#config.adopterId,\n tenantId: input.scope.tenantId,\n productSessionId: input.scope.productSessionId,\n runtimeSessionId: input.runtimeSessionId,\n invocationId: input.invocationId,\n workflow: input.workflow,\n serverId: mcpConfig.serverId,\n allowedTools: [...input.mcp.allowedTools],\n })\n .setProtectedHeader({\n alg: SIGNING_ALGORITHM,\n kid: this.#config.keyId,\n typ: MCP_CAPABILITY_TYPE,\n })\n .setIssuer(this.#config.issuer)\n .setAudience(mcpConfig.audience)\n .setSubject(input.scope.subjectId)\n .setJti(capabilityId)\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAt)\n .sign(this.#privateKey);\n\n return {\n assertion,\n metadata: {\n capabilityId,\n serverId: mcpConfig.serverId,\n allowedTools: Object.freeze([...input.mcp.allowedTools]),\n expiresAt: toIsoTimestamp(expiresAt),\n },\n };\n }\n}\n\nclass ProtectedIssuedExecutionAuthority implements IssuedExecutionAuthority {\n readonly metadata: IssuedExecutionAuthorityMetadata;\n readonly #executionAssertion: string;\n readonly #mcpCapability: string | undefined;\n\n constructor(\n executionAssertion: string,\n mcpCapability: string | undefined,\n metadata: IssuedExecutionAuthorityMetadata,\n ) {\n this.#executionAssertion = executionAssertion;\n this.#mcpCapability = mcpCapability;\n this.metadata = metadata;\n }\n\n executionAssertion(): string {\n return this.#executionAssertion;\n }\n\n mcpCapability(): string | undefined {\n return this.#mcpCapability;\n }\n\n toJSON(): IssuedExecutionAuthorityMetadata {\n return this.metadata;\n }\n}\n\nfunction projectPublicJwk(jwk: JWK, keyId: string): Readonly<JWK> {\n const parsed = PublicP256JwkSchema.parse(jwk);\n return Object.freeze({\n kty: parsed.kty,\n crv: parsed.crv,\n x: parsed.x,\n y: parsed.y,\n alg: SIGNING_ALGORITHM,\n kid: keyId,\n use: 'sig',\n });\n}\n\nfunction assertPrivateSigningKey(key: CryptoKey): void {\n const algorithm = key.algorithm as { name: string; namedCurve?: string };\n const accepted = key.type === 'private'\n && algorithm.name === 'ECDSA'\n && algorithm.namedCurve === 'P-256'\n && key.usages.includes('sign');\n if (!accepted) {\n throw new Error(\n 'Execution authority requires an ES256 private signing key.',\n );\n }\n}\n\nfunction assertPublicVerificationKey(key: CryptoKey): void {\n const algorithm = key.algorithm as { name: string; namedCurve?: string };\n const accepted = key.type === 'public'\n && algorithm.name === 'ECDSA'\n && algorithm.namedCurve === 'P-256'\n && key.usages.includes('verify');\n if (!accepted) {\n throw new Error(\n 'Execution authority requires an ES256 public verification key.',\n );\n }\n}\n\nasync function assertMatchingKeyPair(\n keyPair: ExecutionAuthorityKeyPair,\n): Promise<void> {\n try {\n const probe = await new CompactSign(\n new TextEncoder().encode('heddle-adopter-execution-authority-key-pair'),\n )\n .setProtectedHeader({ alg: SIGNING_ALGORITHM })\n .sign(keyPair.privateKey);\n await compactVerify(probe, keyPair.publicKey, {\n algorithms: [SIGNING_ALGORITHM],\n });\n } catch {\n throw new Error('Execution authority signing keys do not match.');\n }\n}\n\nfunction toEpochSeconds(value: Date): number {\n const seconds = Math.floor(value.getTime() / 1_000);\n if (!Number.isSafeInteger(seconds) || seconds < 0) {\n throw new Error('Execution authority could not resolve a valid issue time.');\n }\n return seconds;\n}\n\nfunction toIsoTimestamp(epochSeconds: number): string {\n return new Date(epochSeconds * 1_000).toISOString();\n}\n\nfunction deepFreezeConfig(\n config: z.infer<typeof ExecutionAuthorityConfigSchema>,\n): z.infer<typeof ExecutionAuthorityConfigSchema> {\n const mcp = config.mcp ? Object.freeze({ ...config.mcp }) : undefined;\n return Object.freeze({ ...config, ...(mcp ? { mcp } : {}) });\n}\n\nfunction freezeIssuedMetadata(\n metadata: IssuedExecutionAuthorityMetadata,\n): IssuedExecutionAuthorityMetadata {\n const scope: ExecutionScope = Object.freeze({ ...metadata.scope });\n const mcp = metadata.mcp\n ? Object.freeze({\n ...metadata.mcp,\n allowedTools: Object.freeze([...metadata.mcp.allowedTools]),\n })\n : undefined;\n return Object.freeze({ ...metadata, scope, ...(mcp ? { mcp } : {}) });\n}\n"]}
|