alibabacloud-agentcore-sdk 0.1.2 → 0.1.3
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 +1 -0
- package/dist/auth/index.cjs +6 -7
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.js +5 -6
- package/dist/{chunk-RZNQGEGJ.cjs → chunk-25KH5XKG.cjs} +6 -6
- package/dist/{chunk-RZNQGEGJ.cjs.map → chunk-25KH5XKG.cjs.map} +1 -1
- package/dist/{chunk-A3WMLVJC.cjs → chunk-2TRT7RSV.cjs} +5 -7
- package/dist/chunk-2TRT7RSV.cjs.map +1 -0
- package/dist/{chunk-K3TE7625.js → chunk-3JXIMUUY.js} +2 -2
- package/dist/{chunk-LXHW6OT4.cjs → chunk-5P5SJLNH.cjs} +17 -15
- package/dist/chunk-5P5SJLNH.cjs.map +1 -0
- package/dist/{chunk-TWEO5XVM.cjs → chunk-5S55CTNM.cjs} +18 -20
- package/dist/chunk-5S55CTNM.cjs.map +1 -0
- package/dist/{chunk-JW62DVIC.js → chunk-5UQIUMSF.js} +3 -5
- package/dist/{chunk-JW62DVIC.js.map → chunk-5UQIUMSF.js.map} +1 -1
- package/dist/{chunk-IF7LMBXC.js → chunk-6EJFZSYH.js} +18 -14
- package/dist/chunk-6EJFZSYH.js.map +1 -0
- package/dist/{chunk-ZWQBAJ5O.js → chunk-6NNPSP3O.js} +2 -2
- package/dist/{chunk-IUCLCPVV.js → chunk-76NTQYJB.js} +3 -3
- package/dist/{chunk-7Y263YIW.js → chunk-7AJ2V7RN.js} +5 -7
- package/dist/{chunk-7Y263YIW.js.map → chunk-7AJ2V7RN.js.map} +1 -1
- package/dist/{chunk-5ZOLHQXO.js → chunk-7UBN3SJI.js} +7 -9
- package/dist/{chunk-5ZOLHQXO.js.map → chunk-7UBN3SJI.js.map} +1 -1
- package/dist/{chunk-MZ5UWGXS.js → chunk-AEQ76QIO.js} +33 -5
- package/dist/chunk-AEQ76QIO.js.map +1 -0
- package/dist/{chunk-UBP5CHU7.js → chunk-AX3NM2DK.js} +5 -7
- package/dist/{chunk-UBP5CHU7.js.map → chunk-AX3NM2DK.js.map} +1 -1
- package/dist/{chunk-55XZZRKO.js → chunk-D45QSOR4.js} +4 -6
- package/dist/{chunk-55XZZRKO.js.map → chunk-D45QSOR4.js.map} +1 -1
- package/dist/{chunk-MICRSJ6R.js → chunk-EKLTJ65H.js} +2 -2
- package/dist/{chunk-RBAY4MO2.js → chunk-FG7K3EF7.js} +6 -8
- package/dist/{chunk-RBAY4MO2.js.map → chunk-FG7K3EF7.js.map} +1 -1
- package/dist/{chunk-ZLQ2IBTC.cjs → chunk-GOJ4Q4QW.cjs} +12 -12
- package/dist/{chunk-ZLQ2IBTC.cjs.map → chunk-GOJ4Q4QW.cjs.map} +1 -1
- package/dist/{chunk-UWPKFJYM.js → chunk-HMKA537A.js} +11 -9
- package/dist/{chunk-UWPKFJYM.js.map → chunk-HMKA537A.js.map} +1 -1
- package/dist/{chunk-GYLT23D3.js → chunk-IJ4VJIQV.js} +5 -5
- package/dist/{chunk-PKYET77D.cjs → chunk-JK6KPDVW.cjs} +39 -41
- package/dist/chunk-JK6KPDVW.cjs.map +1 -0
- package/dist/{chunk-2E5EWEDG.cjs → chunk-KQTZUIMI.cjs} +10 -12
- package/dist/chunk-KQTZUIMI.cjs.map +1 -0
- package/dist/{chunk-ZLKYXRNM.js → chunk-KTKZCLYB.js} +3 -5
- package/dist/{chunk-ZLKYXRNM.js.map → chunk-KTKZCLYB.js.map} +1 -1
- package/dist/{chunk-RHY7Y43E.js → chunk-L74ASQWF.js} +8 -9
- package/dist/chunk-L74ASQWF.js.map +1 -0
- package/dist/{chunk-S7PWSJNP.cjs → chunk-LQM754U3.cjs} +5 -5
- package/dist/{chunk-S7PWSJNP.cjs.map → chunk-LQM754U3.cjs.map} +1 -1
- package/dist/{chunk-5JXA7JPS.js → chunk-NRYDUATX.js} +2 -2
- package/dist/{chunk-A3PF2SPD.cjs → chunk-NWWTBPYG.cjs} +5 -5
- package/dist/{chunk-A3PF2SPD.cjs.map → chunk-NWWTBPYG.cjs.map} +1 -1
- package/dist/{chunk-5RKN46UU.cjs → chunk-NXMTTQQK.cjs} +15 -15
- package/dist/{chunk-5RKN46UU.cjs.map → chunk-NXMTTQQK.cjs.map} +1 -1
- package/dist/{chunk-RYXL25AI.js → chunk-PS3EAUMK.js} +2 -2
- package/dist/{chunk-QIZO3A4Y.cjs → chunk-QT736X32.cjs} +43 -39
- package/dist/chunk-QT736X32.cjs.map +1 -0
- package/dist/{chunk-ULJTQSLE.cjs → chunk-R7NVBTPK.cjs} +3 -3
- package/dist/{chunk-ULJTQSLE.cjs.map → chunk-R7NVBTPK.cjs.map} +1 -1
- package/dist/{chunk-YZP55W7S.cjs → chunk-RJCDBVZ6.cjs} +3 -3
- package/dist/{chunk-YZP55W7S.cjs.map → chunk-RJCDBVZ6.cjs.map} +1 -1
- package/dist/{chunk-ZTWLCHCO.cjs → chunk-UKRJR66Y.cjs} +24 -26
- package/dist/chunk-UKRJR66Y.cjs.map +1 -0
- package/dist/{chunk-MWAHO47B.cjs → chunk-UMTUXOKE.cjs} +25 -27
- package/dist/chunk-UMTUXOKE.cjs.map +1 -0
- package/dist/{chunk-JSP7ZROS.cjs → chunk-V4A6MJ42.cjs} +36 -8
- package/dist/chunk-V4A6MJ42.cjs.map +1 -0
- package/dist/{chunk-BVZ7H2F5.cjs → chunk-VYOJJECB.cjs} +55 -56
- package/dist/chunk-VYOJJECB.cjs.map +1 -0
- package/dist/{chunk-RQRI6RCG.cjs → chunk-ZXPTDLXJ.cjs} +12 -14
- package/dist/chunk-ZXPTDLXJ.cjs.map +1 -0
- package/dist/collaboration/index.cjs +3 -3
- package/dist/collaboration/index.d.cts +2 -2
- package/dist/collaboration/index.d.ts +2 -2
- package/dist/collaboration/index.js +2 -2
- package/dist/controlplane/index.cjs +7 -8
- package/dist/controlplane/index.cjs.map +1 -1
- package/dist/controlplane/index.js +6 -7
- package/dist/{errors-D9OtcR-o.d.cts → errors-BGfCbCgs.d.cts} +4 -1
- package/dist/{errors-BjGO6N10.d.ts → errors-D_809AqR.d.ts} +4 -1
- package/dist/{google-adk-model-N47R7GB2.js → google-adk-model-V7SC6RQD.js} +3 -3
- package/dist/{google-adk-model-PDBKY5YZ.cjs → google-adk-model-WYWEQI4R.cjs} +13 -13
- package/dist/{google-adk-model-PDBKY5YZ.cjs.map → google-adk-model-WYWEQI4R.cjs.map} +1 -1
- package/dist/index.cjs +33 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +15 -17
- package/dist/index.js.map +1 -1
- package/dist/integrations/ai-sdk.cjs +3 -3
- package/dist/integrations/ai-sdk.js +2 -2
- package/dist/integrations/google-adk.cjs +13 -14
- package/dist/integrations/google-adk.cjs.map +1 -1
- package/dist/integrations/google-adk.js +9 -10
- package/dist/integrations/google-adk.js.map +1 -1
- package/dist/integrations/langchain.cjs +18 -19
- package/dist/integrations/langchain.cjs.map +1 -1
- package/dist/integrations/langchain.js +11 -12
- package/dist/integrations/langchain.js.map +1 -1
- package/dist/integrations/langgraph.cjs +10 -11
- package/dist/integrations/langgraph.cjs.map +1 -1
- package/dist/integrations/langgraph.js +9 -10
- package/dist/integrations/mastra.cjs +14 -15
- package/dist/integrations/mastra.cjs.map +1 -1
- package/dist/integrations/mastra.js +8 -9
- package/dist/integrations/mastra.js.map +1 -1
- package/dist/{langchain-provider-NF5GIDQV.cjs → langchain-provider-EBQPAP6O.cjs} +10 -10
- package/dist/{langchain-provider-NF5GIDQV.cjs.map → langchain-provider-EBQPAP6O.cjs.map} +1 -1
- package/dist/{langchain-provider-PHL4UWNF.js → langchain-provider-MWLP3I7S.js} +2 -2
- package/dist/mcp/index.cjs +3 -4
- package/dist/mcp/index.cjs.map +1 -1
- package/dist/mcp/index.js +2 -3
- package/dist/memory/index.cjs +6 -7
- package/dist/memory/index.cjs.map +1 -1
- package/dist/memory/index.js +5 -6
- package/dist/model/index.cjs +4 -5
- package/dist/model/index.cjs.map +1 -1
- package/dist/model/index.js +3 -4
- package/dist/runtime/index.cjs +7 -8
- package/dist/runtime/index.cjs.map +1 -1
- package/dist/runtime/index.js +6 -7
- package/dist/server/index.cjs +13 -15
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.js +5 -7
- package/dist/server/index.js.map +1 -1
- package/dist/skill/index.cjs +4 -5
- package/dist/skill/index.cjs.map +1 -1
- package/dist/skill/index.js +3 -4
- package/package.json +1 -1
- package/dist/chunk-2E5EWEDG.cjs.map +0 -1
- package/dist/chunk-A3WMLVJC.cjs.map +0 -1
- package/dist/chunk-BVZ7H2F5.cjs.map +0 -1
- package/dist/chunk-IF7LMBXC.js.map +0 -1
- package/dist/chunk-JSP7ZROS.cjs.map +0 -1
- package/dist/chunk-LE5P3SJW.cjs +0 -16
- package/dist/chunk-LE5P3SJW.cjs.map +0 -1
- package/dist/chunk-LXHW6OT4.cjs.map +0 -1
- package/dist/chunk-MWAHO47B.cjs.map +0 -1
- package/dist/chunk-MZ5UWGXS.js.map +0 -1
- package/dist/chunk-NZL3VPJ2.js +0 -16
- package/dist/chunk-NZL3VPJ2.js.map +0 -1
- package/dist/chunk-PKYET77D.cjs.map +0 -1
- package/dist/chunk-QIZO3A4Y.cjs.map +0 -1
- package/dist/chunk-RHY7Y43E.js.map +0 -1
- package/dist/chunk-RQRI6RCG.cjs.map +0 -1
- package/dist/chunk-TWEO5XVM.cjs.map +0 -1
- package/dist/chunk-ZTWLCHCO.cjs.map +0 -1
- /package/dist/{chunk-K3TE7625.js.map → chunk-3JXIMUUY.js.map} +0 -0
- /package/dist/{chunk-ZWQBAJ5O.js.map → chunk-6NNPSP3O.js.map} +0 -0
- /package/dist/{chunk-IUCLCPVV.js.map → chunk-76NTQYJB.js.map} +0 -0
- /package/dist/{chunk-MICRSJ6R.js.map → chunk-EKLTJ65H.js.map} +0 -0
- /package/dist/{chunk-GYLT23D3.js.map → chunk-IJ4VJIQV.js.map} +0 -0
- /package/dist/{chunk-5JXA7JPS.js.map → chunk-NRYDUATX.js.map} +0 -0
- /package/dist/{chunk-RYXL25AI.js.map → chunk-PS3EAUMK.js.map} +0 -0
- /package/dist/{google-adk-model-N47R7GB2.js.map → google-adk-model-V7SC6RQD.js.map} +0 -0
- /package/dist/{langchain-provider-PHL4UWNF.js.map → langchain-provider-MWLP3I7S.js.map} +0 -0
|
@@ -3,13 +3,13 @@ import {
|
|
|
3
3
|
recordMemory,
|
|
4
4
|
referenceText,
|
|
5
5
|
validateTopK
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-HMKA537A.js";
|
|
7
7
|
import {
|
|
8
8
|
skillTools
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-KTKZCLYB.js";
|
|
10
10
|
import {
|
|
11
11
|
MemoryValidationError
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-AEQ76QIO.js";
|
|
13
13
|
|
|
14
14
|
// src/integrations/langgraph.ts
|
|
15
15
|
import { SystemMessage } from "@langchain/core/messages";
|
|
@@ -18,7 +18,7 @@ import { SystemMessage } from "@langchain/core/messages";
|
|
|
18
18
|
import { tool } from "@langchain/core/tools";
|
|
19
19
|
async function model(client, options = {}) {
|
|
20
20
|
if ("languageModel" in client) {
|
|
21
|
-
const { ProviderChatModel } = await import("./langchain-provider-
|
|
21
|
+
const { ProviderChatModel } = await import("./langchain-provider-MWLP3I7S.js");
|
|
22
22
|
return new ProviderChatModel(client, options);
|
|
23
23
|
}
|
|
24
24
|
const { provider, model: model2, baseURL, maxTokens } = client.settings;
|
|
@@ -107,4 +107,4 @@ export {
|
|
|
107
107
|
AgentCoreMemoryNodes,
|
|
108
108
|
withMemory
|
|
109
109
|
};
|
|
110
|
-
//# sourceMappingURL=chunk-
|
|
110
|
+
//# sourceMappingURL=chunk-IJ4VJIQV.js.map
|
|
@@ -1,40 +1,38 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkRJCDBVZ6cjs = require('./chunk-RJCDBVZ6.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunk25KH5XKGcjs = require('./chunk-25KH5XKG.cjs');
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
var
|
|
10
|
+
var _chunkNXMTTQQKcjs = require('./chunk-NXMTTQQK.cjs');
|
|
11
11
|
|
|
12
12
|
|
|
13
|
-
var _chunkLE5P3SJWcjs = require('./chunk-LE5P3SJW.cjs');
|
|
14
13
|
|
|
15
14
|
|
|
16
15
|
|
|
17
16
|
|
|
18
17
|
|
|
19
|
-
|
|
20
|
-
var _chunkJSP7ZROScjs = require('./chunk-JSP7ZROS.cjs');
|
|
18
|
+
var _chunkV4A6MJ42cjs = require('./chunk-V4A6MJ42.cjs');
|
|
21
19
|
|
|
22
20
|
// src/controlplane/client.ts
|
|
23
21
|
var _agentcore20260804 = require('@alicloud/agentcore20260804'); var models = _interopRequireWildcard(_agentcore20260804);
|
|
24
22
|
var _openapicore = require('@alicloud/openapi-core');
|
|
25
23
|
var _typescript = require('@darabonba/typescript');
|
|
26
24
|
var GeneratedClient = typeof models.default === "function" ? models.default : models.default.default;
|
|
27
|
-
function exact(items, field, name, label, ErrorType =
|
|
25
|
+
function exact(items, field, name, label, ErrorType = _chunkV4A6MJ42cjs.ResourceNotConfiguredError) {
|
|
28
26
|
const matches = items.filter((item) => item[field] === name);
|
|
29
27
|
if (!matches.length) throw new ErrorType(`${label} ${JSON.stringify(name)} does not exist`);
|
|
30
|
-
if (matches.length !== 1) throw new (0,
|
|
28
|
+
if (matches.length !== 1) throw new (0, _chunkV4A6MJ42cjs.ConfigError)(`${label} ${JSON.stringify(name)} is not unique`);
|
|
31
29
|
return matches[0];
|
|
32
30
|
}
|
|
33
31
|
function errorField(error, key) {
|
|
34
32
|
return error && typeof error === "object" ? error[key] : void 0;
|
|
35
33
|
}
|
|
36
34
|
function responseBody(body) {
|
|
37
|
-
if (body === void 0) throw new (0,
|
|
35
|
+
if (body === void 0) throw new (0, _chunkV4A6MJ42cjs.ConfigError)("AgentCore returned an empty control-plane response");
|
|
38
36
|
return body;
|
|
39
37
|
}
|
|
40
38
|
function endpointFailure(error) {
|
|
@@ -45,17 +43,17 @@ function endpointFailure(error) {
|
|
|
45
43
|
var AgentCoreControlPlane = (_class = class {
|
|
46
44
|
constructor(options) {;_class.prototype.__init.call(this);
|
|
47
45
|
this.options = options;
|
|
48
|
-
this.workspaceId =
|
|
49
|
-
this.regionId =
|
|
50
|
-
if (!options.accessKeyCredential && !options.resourceSTSProvider) throw new (0,
|
|
46
|
+
this.workspaceId = _chunkNXMTTQQKcjs.requiredString.call(void 0, options.workspaceId, "workspaceId");
|
|
47
|
+
this.regionId = _chunkNXMTTQQKcjs.requiredString.call(void 0, options.regionId, "regionId");
|
|
48
|
+
if (!options.accessKeyCredential && !options.resourceSTSProvider) throw new (0, _chunkV4A6MJ42cjs.ConfigError)("AgentCore control plane requires an AccessKey credential source");
|
|
51
49
|
if (options.endpoint !== void 0) {
|
|
52
50
|
const value = options.endpoint.trim();
|
|
53
|
-
const url = new URL(
|
|
54
|
-
if (url.pathname !== "/") throw new (0,
|
|
51
|
+
const url = new URL(_chunkNXMTTQQKcjs.httpUrl.call(void 0, value.includes("://") ? value : `https://${value}`, "AgentCore control endpoint"));
|
|
52
|
+
if (url.pathname !== "/") throw new (0, _chunkV4A6MJ42cjs.ConfigError)("AgentCore control endpoint must not contain a path");
|
|
55
53
|
this.endpoint = url.host;
|
|
56
54
|
this.protocol = url.protocol.slice(0, -1);
|
|
57
55
|
}
|
|
58
|
-
this.logger = _nullishCoalesce(options.logger, () => (
|
|
56
|
+
this.logger = _nullishCoalesce(options.logger, () => ( _chunkV4A6MJ42cjs.nullLogger));
|
|
59
57
|
}
|
|
60
58
|
|
|
61
59
|
|
|
@@ -80,8 +78,8 @@ var AgentCoreControlPlane = (_class = class {
|
|
|
80
78
|
connections.push(..._nullishCoalesce(body.items, () => ( [])));
|
|
81
79
|
nextToken = body.nextToken;
|
|
82
80
|
} while (nextToken);
|
|
83
|
-
const connection = exact(connections, "name", connectionName, "model connection",
|
|
84
|
-
const connectionId =
|
|
81
|
+
const connection = exact(connections, "name", connectionName, "model connection", _chunkV4A6MJ42cjs.ModelConnectionNotFoundError);
|
|
82
|
+
const connectionId = _chunkNXMTTQQKcjs.requiredString.call(void 0, connection.connectionId, "connectionId");
|
|
85
83
|
const available = [];
|
|
86
84
|
do {
|
|
87
85
|
const response = await this.invoke(client, "ListModels", () => client.listModelsWithOptions(
|
|
@@ -97,17 +95,17 @@ var AgentCoreControlPlane = (_class = class {
|
|
|
97
95
|
let model;
|
|
98
96
|
if (modelName !== void 0) model = exact(available, "modelName", modelName, "model");
|
|
99
97
|
else {
|
|
100
|
-
if (available.length !== 1) throw new (0,
|
|
98
|
+
if (available.length !== 1) throw new (0, _chunkV4A6MJ42cjs.ResourceNotConfiguredError)(`model connection ${JSON.stringify(connectionName)} requires an explicit model name`);
|
|
101
99
|
model = available[0];
|
|
102
100
|
}
|
|
103
101
|
const capabilities = Object.fromEntries(Object.entries(_nullishCoalesce(model.capabilities, () => ( {}))).filter((entry) => typeof entry[1] === "boolean"));
|
|
104
102
|
const descriptor = Object.freeze({
|
|
105
103
|
connectionId,
|
|
106
|
-
connectionName:
|
|
104
|
+
connectionName: _chunkNXMTTQQKcjs.requiredString.call(void 0, connection.name, "connection name"),
|
|
107
105
|
protocol: _nullishCoalesce(connection.protocol, () => ( "")),
|
|
108
106
|
providerType: _nullishCoalesce(connection.providerType, () => ( "")),
|
|
109
|
-
modelId:
|
|
110
|
-
modelName:
|
|
107
|
+
modelId: _chunkNXMTTQQKcjs.requiredString.call(void 0, model.modelId, "modelId"),
|
|
108
|
+
modelName: _chunkNXMTTQQKcjs.requiredString.call(void 0, model.modelName, "modelName"),
|
|
111
109
|
contextSize: model.contextSize,
|
|
112
110
|
maxTokens: model.maxTokens,
|
|
113
111
|
capabilities: Object.freeze(capabilities)
|
|
@@ -130,10 +128,10 @@ var AgentCoreControlPlane = (_class = class {
|
|
|
130
128
|
items.push(..._nullishCoalesce(body.items, () => ( [])));
|
|
131
129
|
nextToken = body.nextToken;
|
|
132
130
|
} while (nextToken);
|
|
133
|
-
const item = exact(items, "name", name, "MCP server",
|
|
131
|
+
const item = exact(items, "name", name, "MCP server", _chunkV4A6MJ42cjs.MCPServerNotFoundError);
|
|
134
132
|
const descriptor = Object.freeze({
|
|
135
|
-
mcpServerId:
|
|
136
|
-
name:
|
|
133
|
+
mcpServerId: _chunkNXMTTQQKcjs.requiredString.call(void 0, item.mcpServerId, "mcpServerId"),
|
|
134
|
+
name: _chunkNXMTTQQKcjs.requiredString.call(void 0, item.name, "MCP name"),
|
|
137
135
|
protocol: _nullishCoalesce(item.protocol, () => ( "")),
|
|
138
136
|
type: _nullishCoalesce(item.type, () => ( "")),
|
|
139
137
|
status: _nullishCoalesce(item.status, () => ( ""))
|
|
@@ -157,7 +155,7 @@ var AgentCoreControlPlane = (_class = class {
|
|
|
157
155
|
this.runtimeOptions()
|
|
158
156
|
));
|
|
159
157
|
const downloadURL = responseBody(response.body).data;
|
|
160
|
-
if (typeof downloadURL !== "string") throw new (0,
|
|
158
|
+
if (typeof downloadURL !== "string") throw new (0, _chunkV4A6MJ42cjs.ConfigError)("AgentCore returned an invalid Skill download URL");
|
|
161
159
|
return { version: resolvedVersion, archive: await this.downloadSkill(downloadURL) };
|
|
162
160
|
}
|
|
163
161
|
close() {
|
|
@@ -188,11 +186,11 @@ var AgentCoreControlPlane = (_class = class {
|
|
|
188
186
|
const item = exact(items, "name", name, "credential");
|
|
189
187
|
const refs = _nullishCoalesce(item.resourceRefs, () => ( []));
|
|
190
188
|
return {
|
|
191
|
-
credentialId:
|
|
192
|
-
name:
|
|
193
|
-
credentialType:
|
|
189
|
+
credentialId: _chunkNXMTTQQKcjs.requiredString.call(void 0, item.credentialId, "credentialId"),
|
|
190
|
+
name: _chunkNXMTTQQKcjs.requiredString.call(void 0, item.name, "name"),
|
|
191
|
+
credentialType: _chunkNXMTTQQKcjs.requiredString.call(void 0, item.credentialType, "credentialType"),
|
|
194
192
|
resourceScope: String(_nullishCoalesce(item.resourceScope, () => ( ""))),
|
|
195
|
-
resourceRefs: refs.map((ref) => ({ resourceType:
|
|
193
|
+
resourceRefs: refs.map((ref) => ({ resourceType: _chunkNXMTTQQKcjs.requiredString.call(void 0, ref.resourceType, "resourceType"), resourceId: _chunkNXMTTQQKcjs.requiredString.call(void 0, ref.resourceId, "resourceId") }))
|
|
196
194
|
};
|
|
197
195
|
}
|
|
198
196
|
runtimeOptions() {
|
|
@@ -200,7 +198,7 @@ var AgentCoreControlPlane = (_class = class {
|
|
|
200
198
|
}
|
|
201
199
|
async client() {
|
|
202
200
|
this.lifetime.signal.throwIfAborted();
|
|
203
|
-
const credential = await _asyncNullishCoalesce(this.options.accessKeyCredential, async () => ( await this.options.resourceSTSProvider.get(
|
|
201
|
+
const credential = await _asyncNullishCoalesce(this.options.accessKeyCredential, async () => ( await this.options.resourceSTSProvider.get(_chunk25KH5XKGcjs.HIGH_CODE_SDK_PURPOSE)));
|
|
204
202
|
return new GeneratedClient(new _openapicore.$OpenApiUtil.Config({
|
|
205
203
|
accessKeyId: credential.accessKeyId,
|
|
206
204
|
accessKeySecret: credential.accessKeySecret,
|
|
@@ -225,13 +223,13 @@ var AgentCoreControlPlane = (_class = class {
|
|
|
225
223
|
code: String(_nullishCoalesce(errorField(cause, "code"), () => ( "-"))),
|
|
226
224
|
requestId: String(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(errorField(cause, "requestId"), () => ( errorField(data, "RequestId"))), () => ( errorField(data, "requestId"))), () => ( "-")))
|
|
227
225
|
});
|
|
228
|
-
throw new (0,
|
|
226
|
+
throw new (0, _chunkV4A6MJ42cjs.InvocationError)("AgentCore control-plane request failed", { cause });
|
|
229
227
|
}
|
|
230
228
|
};
|
|
231
229
|
try {
|
|
232
230
|
return await invoke();
|
|
233
231
|
} catch (error) {
|
|
234
|
-
if (!(error instanceof
|
|
232
|
+
if (!(error instanceof _chunkV4A6MJ42cjs.InvocationError) || this.endpoint || client._endpoint !== `agentcore.${this.regionId}.aliyuncs.com` || !endpointFailure(error.cause)) throw error;
|
|
235
233
|
const host = `agentcore-vpc.${this.regionId}.aliyuncs.com`;
|
|
236
234
|
this.logger.warn("agentcore.control_plane.endpoint.fallback", { operation, fromHost: client._endpoint, toHost: host });
|
|
237
235
|
client._endpoint = host;
|
|
@@ -245,9 +243,9 @@ var AgentCoreControlPlane = (_class = class {
|
|
|
245
243
|
try {
|
|
246
244
|
original = new URL(value);
|
|
247
245
|
} catch (e) {
|
|
248
|
-
throw new (0,
|
|
246
|
+
throw new (0, _chunkV4A6MJ42cjs.ConfigError)("AgentCore returned an invalid Skill download URL");
|
|
249
247
|
}
|
|
250
|
-
if (!["http:", "https:"].includes(original.protocol) || original.username || original.password) throw new (0,
|
|
248
|
+
if (!["http:", "https:"].includes(original.protocol) || original.username || original.password) throw new (0, _chunkV4A6MJ42cjs.ConfigError)("AgentCore returned an invalid Skill download URL");
|
|
251
249
|
let candidate = original;
|
|
252
250
|
for (; ; ) {
|
|
253
251
|
this.lifetime.signal.throwIfAborted();
|
|
@@ -255,30 +253,30 @@ var AgentCoreControlPlane = (_class = class {
|
|
|
255
253
|
try {
|
|
256
254
|
const response = await fetch(candidate, { redirect: "manual", signal: AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(3e4)]) });
|
|
257
255
|
if (response.ok) {
|
|
258
|
-
const archive = await
|
|
259
|
-
if (!archive.length) throw new (0,
|
|
256
|
+
const archive = await _chunkRJCDBVZ6cjs.readBytes.call(void 0, response, 10 * 1024 * 1024, "Skill archive");
|
|
257
|
+
if (!archive.length) throw new (0, _chunkV4A6MJ42cjs.ConfigError)("Skill package is empty");
|
|
260
258
|
return archive;
|
|
261
259
|
}
|
|
262
260
|
status = response.status;
|
|
263
261
|
await _optionalChain([response, 'access', _ => _.body, 'optionalAccess', _2 => _2.cancel, 'call', _3 => _3()]);
|
|
264
262
|
} catch (error) {
|
|
265
263
|
this.lifetime.signal.throwIfAborted();
|
|
266
|
-
if (error instanceof
|
|
264
|
+
if (error instanceof _chunkV4A6MJ42cjs.ConfigError) throw error;
|
|
267
265
|
}
|
|
268
266
|
this.logger.warn("agentcore.control_plane.skill.download.failed", { host: candidate.host, path: candidate.pathname, status });
|
|
269
267
|
const fallback = candidate === original && (status === void 0 || status >= 500 && status < 600) ? internalOSSURL(original) : void 0;
|
|
270
|
-
if (!fallback) throw new (0,
|
|
268
|
+
if (!fallback) throw new (0, _chunkV4A6MJ42cjs.InvocationError)(status ? `Skill package download failed with HTTP ${status}` : "Skill package download failed");
|
|
271
269
|
this.logger.warn("agentcore.control_plane.skill.download.fallback", { fromHost: candidate.host, toHost: fallback.host });
|
|
272
270
|
candidate = fallback;
|
|
273
271
|
}
|
|
274
272
|
}
|
|
275
273
|
}, _class);
|
|
276
274
|
function latestVersion(data) {
|
|
277
|
-
if (!data) throw new (0,
|
|
275
|
+
if (!data) throw new (0, _chunkV4A6MJ42cjs.ResourceNotConfiguredError)("AgentCore Skill does not exist");
|
|
278
276
|
for (const [label, value] of Object.entries(_nullishCoalesce(data.labels, () => ( {})))) if (label.toLowerCase() === "latest" && value) return value;
|
|
279
277
|
const online = (_nullishCoalesce(data.versions, () => ( []))).filter((v) => _optionalChain([v, 'access', _4 => _4.status, 'optionalAccess', _5 => _5.toLowerCase, 'call', _6 => _6()]) === "online" && v.version);
|
|
280
278
|
online.sort((a, b) => (_nullishCoalesce(b.updateTime, () => ( -1))) - (_nullishCoalesce(a.updateTime, () => ( -1))) || (_nullishCoalesce(b.version, () => ( ""))).localeCompare(_nullishCoalesce(a.version, () => ( ""))));
|
|
281
|
-
if (!_optionalChain([online, 'access', _7 => _7[0], 'optionalAccess', _8 => _8.version])) throw new (0,
|
|
279
|
+
if (!_optionalChain([online, 'access', _7 => _7[0], 'optionalAccess', _8 => _8.version])) throw new (0, _chunkV4A6MJ42cjs.ResourceNotConfiguredError)("AgentCore Skill has no online version");
|
|
282
280
|
return online[0].version;
|
|
283
281
|
}
|
|
284
282
|
function internalOSSURL(url) {
|
|
@@ -293,4 +291,4 @@ function internalOSSURL(url) {
|
|
|
293
291
|
|
|
294
292
|
|
|
295
293
|
exports.AgentCoreControlPlane = AgentCoreControlPlane;
|
|
296
|
-
//# sourceMappingURL=chunk-
|
|
294
|
+
//# sourceMappingURL=chunk-JK6KPDVW.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-JK6KPDVW.cjs","../src/controlplane/client.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACnBA,0HAAgC;AAChC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AAA;AACjG,EAAA;AACF,IAAA;AACJ,IAAA;AACD,IAAA;AACL,MAAA;AAAyC,MAAA;AAA2C,MAAA;AAC7F,MAAA;AAA0C,MAAA;AAAmC,MAAA;AAC5F,IAAA;AACJ,EAAA;AAC+F,EAAA;AACzD,IAAA;AACT,IAAA;AACP,MAAA;AACd,MAAA;AAAoB,QAAA;AACV,MAAA;AACmB,QAAA;AACd,QAAA;AAA4C,UAAA;AAAwB,UAAA;AAClD,UAAA;AAAsD,UAAA;AAC1D,UAAA;AAC9B,QAAA;AACyB,QAAA;AAC5B,MAAA;AACF,IAAA;AACI,IAAA;AAAsB,MAAA;AACZ,IAAA;AACW,MAAA;AACY,MAAA;AAClB,MAAA;AACE,MAAA;AACS,MAAA;AAA6B,MAAA;AAAa,MAAA;AACxE,IAAA;AACF,EAAA;AAEgE,EAAA;AAC1D,IAAA;AACA,IAAA;AAA0B,MAAA;AAAW,IAAA;AAAwB,MAAA;AAAqD,IAAA;AACpF,IAAA;AAClB,IAAA;AACP,IAAA;AAC6B,MAAA;AAChC,MAAA;AACA,MAAA;AAC2B,QAAA;AACZ,QAAA;AACiB,UAAA;AACD,UAAA;AACxB,UAAA;AACT,QAAA;AACkB,QAAA;AAAoC,QAAA;AACxC,MAAA;AACsB,QAAA;AACF,QAAA;AACpC,MAAA;AACiB,MAAA;AACc,MAAA;AACN,MAAA;AACR,MAAA;AACL,MAAA;AACd,IAAA;AACF,EAAA;AACF;AAE6E;AACtD,EAAA;AACe,EAAA;AACC,EAAA;AACE,EAAA;AACJ,EAAA;AAClB,EAAA;AACnB;AAE0D;AAC1C,EAAA;AACmB,EAAA;AACL,EAAA;AACF,EAAA;AAA4C,EAAA;AAAiC,EAAA;AACzG;AD8B4C;AACA;AACA;AACA","file":"/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-JK6KPDVW.cjs","sourcesContent":[null,"import Client, * as models from '@alicloud/agentcore20260804';\nimport { $OpenApiUtil } from '@alicloud/openapi-core';\nimport { RuntimeOptions } from '@darabonba/typescript';\nimport { AccessKeyCredential, type CredentialProvider } from '../auth/access-key';\nimport { HIGH_CODE_SDK_PURPOSE } from '../auth/resource-sts';\nimport { ConfigError, InvocationError, MCPServerNotFoundError, ModelConnectionNotFoundError, ResourceNotConfiguredError } from '../errors';\nimport { readBytes } from '../http';\nimport { nullLogger, type Logger } from '../logging';\nimport { httpUrl, requiredString } from '../runtime/config';\n\n// The generated package is CJS: native ESM sees module.exports as the default.\nconst GeneratedClient = typeof Client === 'function' ? Client : (Client as unknown as { default: typeof Client }).default;\n\nexport interface ModelDescriptor {\n readonly connectionId: string;\n readonly connectionName: string;\n readonly protocol: string;\n readonly providerType: string;\n readonly modelId: string;\n readonly modelName: string;\n readonly contextSize?: number;\n readonly maxTokens?: number;\n readonly capabilities: Readonly<Record<string, boolean>>;\n}\nexport interface MCPDescriptor {\n readonly mcpServerId: string;\n readonly name: string;\n readonly protocol: string;\n readonly type: string;\n readonly status: string;\n}\nexport interface SkillArtifact { version: string; archive: Uint8Array; }\nexport interface CredentialMetadata {\n readonly credentialId: string;\n readonly name: string;\n readonly credentialType: string;\n readonly resourceScope: string;\n readonly resourceRefs: ReadonlyArray<{ resourceType: string; resourceId: string }>;\n}\nexport interface ControlPlaneOptions {\n workspaceId: string;\n regionId: string;\n accessKeyCredential?: AccessKeyCredential;\n resourceSTSProvider?: CredentialProvider;\n endpoint?: string;\n logger?: Logger;\n}\n\nfunction exact<T>(items: T[], field: keyof T, name: string, label: string, ErrorType: typeof ResourceNotConfiguredError = ResourceNotConfiguredError): T {\n const matches = items.filter((item) => item[field] === name);\n if (!matches.length) throw new ErrorType(`${label} ${JSON.stringify(name)} does not exist`);\n if (matches.length !== 1) throw new ConfigError(`${label} ${JSON.stringify(name)} is not unique`);\n return matches[0]!;\n}\n\nfunction errorField(error: unknown, key: string): unknown {\n return error && typeof error === 'object' ? (error as Record<string, unknown>)[key] : undefined;\n}\nfunction responseBody<T>(body: T | undefined): T {\n if (body === undefined) throw new ConfigError('AgentCore returned an empty control-plane response');\n return body;\n}\nfunction endpointFailure(error: unknown): boolean {\n const status = errorField(error, 'statusCode');\n const code = errorField(error, 'code');\n return (typeof status === 'number' && status >= 500 && status < 600) ||\n ['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ESOCKETTIMEDOUT'].includes(String(code)) ||\n errorField(error, 'name') === 'TimeoutError';\n}\n\nexport class AgentCoreControlPlane {\n readonly workspaceId: string;\n readonly regionId: string;\n private readonly endpoint?: string;\n private readonly protocol?: string;\n private discoveredEndpoint?: string;\n private readonly logger: Logger;\n private readonly lifetime = new AbortController();\n\n constructor(private readonly options: ControlPlaneOptions) {\n this.workspaceId = requiredString(options.workspaceId, 'workspaceId');\n this.regionId = requiredString(options.regionId, 'regionId');\n if (!options.accessKeyCredential && !options.resourceSTSProvider) throw new ConfigError('AgentCore control plane requires an AccessKey credential source');\n if (options.endpoint !== undefined) {\n const value = options.endpoint.trim();\n const url = new URL(httpUrl(value.includes('://') ? value : `https://${value}`, 'AgentCore control endpoint'));\n if (url.pathname !== '/') throw new ConfigError('AgentCore control endpoint must not contain a path');\n this.endpoint = url.host; this.protocol = url.protocol.slice(0, -1);\n }\n this.logger = options.logger ?? nullLogger;\n }\n\n async resolveModel(connectionName: string, modelName?: string): Promise<ModelDescriptor> {\n const client = await this.client();\n const connections: models.ListModelConnectionsResponseBodyItems[] = [];\n let nextToken: string | undefined;\n do {\n const response = await this.invoke(client, 'ListModelConnections', () => client.listModelConnectionsWithOptions(this.workspaceId,\n new models.ListModelConnectionsRequest({ name: connectionName, searchType: 'accurate', maxResults: 100, nextToken }), {}, this.runtimeOptions()));\n const body = responseBody(response.body);\n connections.push(...(body.items ?? [])); nextToken = body.nextToken;\n } while (nextToken);\n const connection = exact(connections, 'name', connectionName, 'model connection', ModelConnectionNotFoundError);\n const connectionId = requiredString(connection.connectionId, 'connectionId');\n const available: models.ListModelsResponseBodyItems[] = [];\n do {\n const response = await this.invoke(client, 'ListModels', () => client.listModelsWithOptions(this.workspaceId,\n new models.ListModelsRequest({ connectionId, modelName, maxResults: 100, nextToken }), {}, this.runtimeOptions()));\n const body = responseBody(response.body);\n available.push(...(body.items ?? [])); nextToken = body.nextToken;\n } while (nextToken);\n let model: models.ListModelsResponseBodyItems;\n if (modelName !== undefined) model = exact(available, 'modelName', modelName, 'model');\n else {\n if (available.length !== 1) throw new ResourceNotConfiguredError(`model connection ${JSON.stringify(connectionName)} requires an explicit model name`);\n model = available[0]!;\n }\n const capabilities = Object.fromEntries(Object.entries(model.capabilities ?? {}).filter((entry): entry is [string, boolean] => typeof entry[1] === 'boolean'));\n const descriptor = Object.freeze({ connectionId, connectionName: requiredString(connection.name, 'connection name'),\n protocol: connection.protocol ?? '', providerType: connection.providerType ?? '',\n modelId: requiredString(model.modelId, 'modelId'), modelName: requiredString(model.modelName, 'modelName'),\n contextSize: model.contextSize, maxTokens: model.maxTokens, capabilities: Object.freeze(capabilities),\n });\n this.logger.info('agentcore.control_plane.model.resolve.succeeded', { connectionName, connectionId, modelName: descriptor.modelName });\n return descriptor;\n }\n\n async resolveMCP(name: string): Promise<MCPDescriptor> {\n const client = await this.client();\n const items: models.ListMcpsResponseBodyItems[] = [];\n let nextToken: string | undefined;\n do {\n const response = await this.invoke(client, 'ListMcps', () => client.listMcpsWithOptions(this.workspaceId,\n new models.ListMcpsRequest({ name, searchType: 'accurate', maxResults: 100, nextToken }), {}, this.runtimeOptions()));\n const body = responseBody(response.body);\n items.push(...(body.items ?? [])); nextToken = body.nextToken;\n } while (nextToken);\n const item = exact(items, 'name', name, 'MCP server', MCPServerNotFoundError);\n const descriptor = Object.freeze({ mcpServerId: requiredString(item.mcpServerId, 'mcpServerId'),\n name: requiredString(item.name, 'MCP name'), protocol: item.protocol ?? '', type: item.type ?? '', status: item.status ?? '',\n });\n this.logger.info('agentcore.control_plane.mcp.resolve.succeeded', { name, mcpServerId: descriptor.mcpServerId, protocol: descriptor.protocol });\n return descriptor;\n }\n\n async getSkill(name: string, version?: string): Promise<SkillArtifact> {\n const client = await this.client();\n if (version === undefined) {\n const detail = await this.invoke(client, 'GetSkillDetail', () => client.getSkillDetailWithOptions(this.workspaceId, name, new models.GetSkillDetailRequest({}), {}, this.runtimeOptions()));\n version = latestVersion(responseBody(detail.body).data);\n }\n const resolvedVersion = version;\n const response = await this.invoke(client, 'DownloadSkillVersionViaOss', () => client.downloadSkillVersionViaOssWithOptions(this.workspaceId, name, resolvedVersion,\n new models.DownloadSkillVersionViaOssRequest({}), {}, this.runtimeOptions()));\n const downloadURL = responseBody(response.body).data;\n if (typeof downloadURL !== 'string') throw new ConfigError('AgentCore returned an invalid Skill download URL');\n return { version: resolvedVersion, archive: await this.downloadSkill(downloadURL) };\n }\n\n close(): void { this.lifetime.abort(); }\n\n async resolveCredential(name: string): Promise<CredentialMetadata> {\n const client = await this.client();\n const params = new $OpenApiUtil.Params({ action: 'ListCredentials', version: '2026-08-04', protocol: 'HTTPS',\n pathname: `/workspaces/${encodeURIComponent(this.workspaceId)}/credentials`, method: 'GET', authType: 'AK',\n style: 'ROA', reqBodyType: 'json', bodyType: 'json' });\n const items: Record<string, unknown>[] = [];\n let nextToken: string | undefined;\n do {\n const request = new $OpenApiUtil.OpenApiRequest({ query: { name, maxResults: '100', ...(nextToken ? { nextToken } : {}) } });\n const response = await this.invoke(client, 'ListCredentials', () => client.callApi(params, request, this.runtimeOptions()));\n const body = responseBody(response.body);\n items.push(...(body.items ?? [])); nextToken = body.nextToken;\n } while (nextToken);\n const item = exact(items, 'name', name, 'credential');\n const refs = (item.resourceRefs ?? []) as Array<Record<string, unknown>>;\n return {\n credentialId: requiredString(item.credentialId, 'credentialId'), name: requiredString(item.name, 'name'),\n credentialType: requiredString(item.credentialType, 'credentialType'), resourceScope: String(item.resourceScope ?? ''),\n resourceRefs: refs.map((ref) => ({ resourceType: requiredString(ref.resourceType, 'resourceType'), resourceId: requiredString(ref.resourceId, 'resourceId') })),\n };\n }\n\n private runtimeOptions(): RuntimeOptions { return new RuntimeOptions({ autoretry: false, connectTimeout: 10_000, readTimeout: 30_000 }); }\n private async client(): Promise<Client> {\n this.lifetime.signal.throwIfAborted();\n const credential = this.options.accessKeyCredential ?? await this.options.resourceSTSProvider!.get(HIGH_CODE_SDK_PURPOSE);\n return new GeneratedClient(new $OpenApiUtil.Config({\n accessKeyId: credential.accessKeyId, accessKeySecret: credential.accessKeySecret, securityToken: credential.securityToken,\n regionId: this.regionId, endpoint: this.endpoint ?? this.discoveredEndpoint, protocol: this.protocol,\n }));\n }\n private async invoke<T>(client: Client, operation: string, call: () => Promise<T>): Promise<T> {\n this.lifetime.signal.throwIfAborted();\n const invoke = async () => {\n this.logger.debug('agentcore.control_plane.request.started', { operation, host: client._endpoint });\n try { return await call(); }\n catch (cause) {\n const data = errorField(cause, 'data');\n this.logger.warn('agentcore.control_plane.request.failed', { operation, host: client._endpoint,\n status: String(errorField(cause, 'statusCode') ?? '-'), code: String(errorField(cause, 'code') ?? '-'),\n requestId: String(errorField(cause, 'requestId') ?? errorField(data, 'RequestId') ?? errorField(data, 'requestId') ?? '-'),\n });\n throw new InvocationError('AgentCore control-plane request failed', { cause });\n }\n };\n try { return await invoke(); }\n catch (error) {\n if (!(error instanceof InvocationError) || this.endpoint || client._endpoint !== `agentcore.${this.regionId}.aliyuncs.com` || !endpointFailure(error.cause)) throw error;\n const host = `agentcore-vpc.${this.regionId}.aliyuncs.com`;\n this.logger.warn('agentcore.control_plane.endpoint.fallback', { operation, fromHost: client._endpoint, toHost: host });\n client._endpoint = host;\n const result = await invoke(); this.discoveredEndpoint = host; return result;\n }\n }\n\n private async downloadSkill(value: string): Promise<Uint8Array> {\n let original: URL;\n try { original = new URL(value); } catch { throw new ConfigError('AgentCore returned an invalid Skill download URL'); }\n if (!['http:', 'https:'].includes(original.protocol) || original.username || original.password) throw new ConfigError('AgentCore returned an invalid Skill download URL');\n let candidate = original;\n for (;;) {\n this.lifetime.signal.throwIfAborted();\n let status: number | undefined;\n try {\n const response = await fetch(candidate, { redirect: 'manual', signal: AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(30_000)]) });\n if (response.ok) {\n const archive = await readBytes(response, 10 * 1024 * 1024, 'Skill archive');\n if (!archive.length) throw new ConfigError('Skill package is empty');\n return archive;\n }\n status = response.status; await response.body?.cancel();\n } catch (error) {\n this.lifetime.signal.throwIfAborted();\n if (error instanceof ConfigError) throw error;\n }\n this.logger.warn('agentcore.control_plane.skill.download.failed', { host: candidate.host, path: candidate.pathname, status });\n const fallback = candidate === original && (status === undefined || status >= 500 && status < 600) ? internalOSSURL(original) : undefined;\n if (!fallback) throw new InvocationError(status ? `Skill package download failed with HTTP ${status}` : 'Skill package download failed');\n this.logger.warn('agentcore.control_plane.skill.download.fallback', { fromHost: candidate.host, toHost: fallback.host });\n candidate = fallback;\n }\n }\n}\n\nfunction latestVersion(data?: models.GetSkillDetailResponseBodyData): string {\n if (!data) throw new ResourceNotConfiguredError('AgentCore Skill does not exist');\n for (const [label, value] of Object.entries(data.labels ?? {})) if (label.toLowerCase() === 'latest' && value) return value;\n const online = (data.versions ?? []).filter((v) => v.status?.toLowerCase() === 'online' && v.version);\n online.sort((a, b) => (b.updateTime ?? -1) - (a.updateTime ?? -1) || (b.version ?? '').localeCompare(a.version ?? ''));\n if (!online[0]?.version) throw new ResourceNotConfiguredError('AgentCore Skill has no online version');\n return online[0].version;\n}\n\nexport function internalOSSURL(url: URL): URL | undefined {\n const match = /^([a-z0-9-]+)\\.(oss-[a-z]+-[a-z0-9-]+)\\.aliyuncs\\.com$/.exec(url.hostname);\n if (!match || match[2]!.endsWith('-internal') || match[2]!.startsWith('oss-accelerate') || url.username || url.password) return undefined;\n if (url.searchParams.getAll('x-oss-additional-headers').some((v) => v.split(';').includes('host'))) return undefined;\n const result = new URL(url); result.hostname = `${match[1]}.${match[2]}-internal.aliyuncs.com`; return result;\n}\n"]}
|
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkNXMTTQQKcjs = require('./chunk-NXMTTQQK.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var _chunkLE5P3SJWcjs = require('./chunk-LE5P3SJW.cjs');
|
|
7
6
|
|
|
8
7
|
|
|
9
|
-
|
|
10
|
-
var _chunkJSP7ZROScjs = require('./chunk-JSP7ZROS.cjs');
|
|
8
|
+
var _chunkV4A6MJ42cjs = require('./chunk-V4A6MJ42.cjs');
|
|
11
9
|
|
|
12
10
|
// src/auth/agent-sa-token.ts
|
|
13
11
|
var _promises = require('fs/promises');
|
|
@@ -22,13 +20,13 @@ var AgentSATokenProvider = class {
|
|
|
22
20
|
try {
|
|
23
21
|
token = await _promises.readFile.call(void 0, this.path, "utf8");
|
|
24
22
|
} catch (cause) {
|
|
25
|
-
throw new (0,
|
|
23
|
+
throw new (0, _chunkV4A6MJ42cjs.AuthenticationError)("cannot read the Agent SA token file", { cause });
|
|
26
24
|
}
|
|
27
25
|
return validToken(token);
|
|
28
26
|
}
|
|
29
27
|
};
|
|
30
28
|
function validToken(token) {
|
|
31
|
-
if (typeof token !== "string" || !token.trim()) throw new (0,
|
|
29
|
+
if (typeof token !== "string" || !token.trim()) throw new (0, _chunkV4A6MJ42cjs.AuthenticationError)("the Agent SA token source returned an empty token");
|
|
32
30
|
return token.trim();
|
|
33
31
|
}
|
|
34
32
|
async function getAgentSAToken(source) {
|
|
@@ -43,13 +41,13 @@ var _promises3 = require('timers/promises');
|
|
|
43
41
|
var ControllerClient = (_class = class {
|
|
44
42
|
constructor(endpoint, saTokens, options = {}) {;_class.prototype.__init.call(this);
|
|
45
43
|
this.saTokens = saTokens;
|
|
46
|
-
this.endpoint =
|
|
44
|
+
this.endpoint = _chunkNXMTTQQKcjs.httpUrl.call(void 0, endpoint, "Controller endpoint");
|
|
47
45
|
this.timeoutMs = _nullishCoalesce(options.timeoutMs, () => ( 1e4));
|
|
48
46
|
this.maxAttempts = _nullishCoalesce(options.maxAttempts, () => ( 3));
|
|
49
47
|
if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isInteger(this.maxAttempts) || this.maxAttempts < 1) {
|
|
50
48
|
throw new TypeError("timeoutMs and maxAttempts must be positive");
|
|
51
49
|
}
|
|
52
|
-
this.logger = _nullishCoalesce(options.logger, () => (
|
|
50
|
+
this.logger = _nullishCoalesce(options.logger, () => ( _chunkV4A6MJ42cjs.nullLogger));
|
|
53
51
|
}
|
|
54
52
|
|
|
55
53
|
|
|
@@ -68,7 +66,7 @@ var ControllerClient = (_class = class {
|
|
|
68
66
|
response = await this.request(path, token, purpose);
|
|
69
67
|
}
|
|
70
68
|
}
|
|
71
|
-
if (response.status === 401) throw new (0,
|
|
69
|
+
if (response.status === 401) throw new (0, _chunkV4A6MJ42cjs.AuthenticationError)("Controller rejected the Agent SA token");
|
|
72
70
|
return response;
|
|
73
71
|
}
|
|
74
72
|
close() {
|
|
@@ -99,7 +97,7 @@ var ControllerClient = (_class = class {
|
|
|
99
97
|
} catch (cause) {
|
|
100
98
|
this.lifetime.signal.throwIfAborted();
|
|
101
99
|
this.logger.warn("agentcore.controller.request.failed", { ...fields, attempt, reason: "transport_error" });
|
|
102
|
-
if (attempt === this.maxAttempts) throw new (0,
|
|
100
|
+
if (attempt === this.maxAttempts) throw new (0, _chunkV4A6MJ42cjs.CredentialExchangeError)("cannot reach the AgentCore Controller", { cause });
|
|
103
101
|
await _promises3.setTimeout.call(void 0, 50 * 2 ** (attempt - 1), void 0, { signal: this.lifetime.signal });
|
|
104
102
|
continue;
|
|
105
103
|
} finally {
|
|
@@ -128,7 +126,7 @@ var ControllerClient = (_class = class {
|
|
|
128
126
|
if (![500, 502, 503, 504].includes(response.status) || attempt === this.maxAttempts) return result;
|
|
129
127
|
await _promises3.setTimeout.call(void 0, 50 * 2 ** (attempt - 1), void 0, { signal: this.lifetime.signal });
|
|
130
128
|
}
|
|
131
|
-
throw new (0,
|
|
129
|
+
throw new (0, _chunkV4A6MJ42cjs.CredentialExchangeError)("Controller request did not complete");
|
|
132
130
|
}
|
|
133
131
|
}, _class);
|
|
134
132
|
|
|
@@ -139,4 +137,4 @@ var ControllerClient = (_class = class {
|
|
|
139
137
|
|
|
140
138
|
|
|
141
139
|
exports.DEFAULT_AGENT_SA_TOKEN_PATH = DEFAULT_AGENT_SA_TOKEN_PATH; exports.AgentSATokenProvider = AgentSATokenProvider; exports.getAgentSAToken = getAgentSAToken; exports.refreshAgentSAToken = refreshAgentSAToken; exports.ControllerClient = ControllerClient;
|
|
142
|
-
//# sourceMappingURL=chunk-
|
|
140
|
+
//# sourceMappingURL=chunk-KQTZUIMI.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-KQTZUIMI.cjs","../src/auth/agent-sa-token.ts","../src/auth/controller.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACTA,uCAAyB;AAGlB,IAAM,4BAAA,EAA8B,gCAAA;AAMpC,IAAM,qBAAA,EAAN,MAAyD;AAAA,EAC9D,WAAA,CAAqB,KAAA,EAAO,2BAAA,EAA6B;AAApC,IAAA,IAAA,CAAA,KAAA,EAAA,IAAA;AAAA,EAAqC;AAAA,E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AAAA,IACF;AACA,IAAA,GAAA,CAAI,QAAA,CAAS,OAAA,IAAW,GAAA,EAAK,MAAM,IAAI,0CAAA,CAAoB,wCAAwC,CAAA;AACnG,IAAA,OAAO,QAAA;AAAA,EACT;AAAA,EAEA,KAAA,CAAA,EAAc;AAAE,IAAA,IAAA,CAAK,QAAA,CAAS,KAAA,CAAM,CAAA;AAAA,EAAG;AAAA,EAEvC,MAAc,OAAA,CAAQ,IAAA,EAAc,KAAA,EAAe,OAAA,EAAkF;AACnI,IAAA,MAAM,IAAA,EAAM,IAAI,GAAA,CAAI,CAAA,EAAA;AACC,IAAA;AACJ,IAAA;AACA,IAAA;AACE,IAAA;AACH,MAAA;AACI,MAAA;AACd,MAAA;AACA,MAAA;AACY,MAAA;AACF,MAAA;AACC,MAAA;AACX,MAAA;AACe,QAAA;AACP,UAAA;AAAmB,UAAA;AAA0C,UAAA;AAC3D,UAAA;AAAU,UAAA;AACrB,QAAA;AACY,QAAA;AACC,MAAA;AACA,QAAA;AACG,QAAA;AACD,QAAA;AACC,QAAA;AACjB,QAAA;AACA,MAAA;AAAuB,QAAA;AAAQ,MAAA;AAC7B,MAAA;AACA,MAAA;AAAiB,QAAA;AAAqB,MAAA;AAAY,QAAA;AAAW,MAAA;AAE9C,MAAA;AACH,MAAA;AAGC,MAAA;AACA,MAAA;AACH,QAAA;AACL,QAAA;AACT,MAAA;AACiB,MAAA;AACZ,QAAA;AAAyB,QAAA;AAAQ,QAAA;AAAS,QAAA;AAClC,QAAA;AACZ,MAAA;AACe,MAAA;AACC,MAAA;AACnB,IAAA;AACU,IAAA;AACZ,EAAA;AACF;AFgCyB;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-KQTZUIMI.cjs","sourcesContent":[null,"import { readFile } from 'node:fs/promises';\nimport { AuthenticationError } from '../errors';\n\nexport const DEFAULT_AGENT_SA_TOKEN_PATH = '/var/run/agentcore/agent/token';\nexport interface AgentSATokenSource {\n get(): string | Promise<string>;\n refresh?(current: string): string | Promise<string>;\n}\n\nexport class AgentSATokenProvider implements AgentSATokenSource {\n constructor(readonly path = DEFAULT_AGENT_SA_TOKEN_PATH) {}\n async get(): Promise<string> {\n let token: string;\n try { token = await readFile(this.path, 'utf8'); } catch (cause) {\n throw new AuthenticationError('cannot read the Agent SA token file', { cause });\n }\n return validToken(token);\n }\n}\n\nfunction validToken(token: string): string {\n if (typeof token !== 'string' || !token.trim()) throw new AuthenticationError('the Agent SA token source returned an empty token');\n return token.trim();\n}\nexport async function getAgentSAToken(source: AgentSATokenSource): Promise<string> {\n return validToken(await source.get());\n}\nexport async function refreshAgentSAToken(source: AgentSATokenSource, current: string): Promise<string> {\n return validToken(await (source.refresh ? source.refresh(current) : source.get()));\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport { AuthenticationError, CredentialExchangeError } from '../errors';\nimport { nullLogger, type Logger } from '../logging';\nimport { httpUrl } from '../runtime/config';\nimport { getAgentSAToken, refreshAgentSAToken, type AgentSATokenSource } from './agent-sa-token';\n\nexport interface ControllerOptions {\n timeoutMs?: number;\n maxAttempts?: number;\n logger?: Logger;\n}\ninterface ControllerResponse {\n status: number;\n payload: unknown;\n message?: string;\n}\n\n// Shared transport only for the Controller's idempotent credential exchanges.\nexport class ControllerClient {\n private readonly endpoint: string;\n private readonly timeoutMs: number;\n private readonly maxAttempts: number;\n private readonly logger: Logger;\n private readonly lifetime = new AbortController();\n\n constructor(endpoint: string, private readonly saTokens: AgentSATokenSource, options: ControllerOptions = {}) {\n this.endpoint = httpUrl(endpoint, 'Controller endpoint');\n this.timeoutMs = options.timeoutMs ?? 10_000;\n this.maxAttempts = options.maxAttempts ?? 3;\n if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isInteger(this.maxAttempts) || this.maxAttempts < 1) {\n throw new TypeError('timeoutMs and maxAttempts must be positive');\n }\n this.logger = options.logger ?? nullLogger;\n }\n\n async post(path: string, purpose?: string | Readonly<Record<string, string>>): Promise<ControllerResponse> {\n let token = await getAgentSAToken(this.saTokens);\n let response = await this.request(path, token, purpose);\n if (response.status === 401) {\n const rotated = await refreshAgentSAToken(this.saTokens, token);\n this.logger.warn('agentcore.controller.sa_rejected', { rotated: rotated !== token });\n if (rotated !== token) {\n token = rotated;\n response = await this.request(path, token, purpose);\n }\n }\n if (response.status === 401) throw new AuthenticationError('Controller rejected the Agent SA token');\n return response;\n }\n\n close(): void { this.lifetime.abort(); }\n\n private async request(path: string, token: string, purpose?: string | Readonly<Record<string, string>>): Promise<ControllerResponse> {\n const url = new URL(`${this.endpoint}${path}`);\n const query = typeof purpose === 'string' ? { purpose } : purpose;\n for (const [key, value] of Object.entries(query ?? {})) url.searchParams.set(key, value);\n const fields = { url: `${url.origin}${url.pathname}`, purpose: query?.purpose ?? 'default' };\n for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n this.lifetime.signal.throwIfAborted();\n this.logger.debug('agentcore.controller.request.started', { ...fields, attempt });\n let response: Response;\n let text: string;\n const timeout = new AbortController();\n const timer = setTimeout(() => timeout.abort(), this.timeoutMs);\n const signal = AbortSignal.any([this.lifetime.signal, timeout.signal]);\n try {\n response = await fetch(url, {\n method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: '',\n redirect: 'manual', signal,\n });\n text = await response.text();\n } catch (cause) {\n this.lifetime.signal.throwIfAborted();\n this.logger.warn('agentcore.controller.request.failed', { ...fields, attempt, reason: 'transport_error' });\n if (attempt === this.maxAttempts) throw new CredentialExchangeError('cannot reach the AgentCore Controller', { cause });\n await sleep(50 * 2 ** (attempt - 1), undefined, { signal: this.lifetime.signal });\n continue;\n } finally { clearTimeout(timer); }\n let payload: unknown;\n try { payload = JSON.parse(text); } catch { payload = undefined; }\n // Never log a successful credential response, headers, or arbitrary JSON fields.\n const rawMessage = payload && typeof payload === 'object' && 'message' in payload ? payload.message : undefined;\n const message = typeof rawMessage === 'string'\n ? rawMessage.split(token).join('<redacted>').replace(/Bearer\\s+\\S+/gi, 'Bearer <redacted>').replace(/\\s+/g, ' ').slice(0, 1024)\n : undefined;\n const result = { status: response.status, payload, message };\n if (response.ok) {\n this.logger.debug('agentcore.controller.request.succeeded', { ...fields, status: response.status });\n return result;\n }\n this.logger.warn('agentcore.controller.request.failed', {\n ...fields, status: response.status, attempt, message,\n requestId: response.headers.get('x-acs-request-id') ?? response.headers.get('x-request-id') ?? undefined,\n });\n if (![500, 502, 503, 504].includes(response.status) || attempt === this.maxAttempts) return result;\n await sleep(50 * 2 ** (attempt - 1), undefined, { signal: this.lifetime.signal });\n }\n throw new CredentialExchangeError('Controller request did not complete');\n }\n}\n"]}
|
|
@@ -2,11 +2,9 @@ import {
|
|
|
2
2
|
Tool
|
|
3
3
|
} from "./chunk-EKXZKKJJ.js";
|
|
4
4
|
import {
|
|
5
|
+
ConfigError,
|
|
5
6
|
nullLogger
|
|
6
|
-
} from "./chunk-
|
|
7
|
-
import {
|
|
8
|
-
ConfigError
|
|
9
|
-
} from "./chunk-MZ5UWGXS.js";
|
|
7
|
+
} from "./chunk-AEQ76QIO.js";
|
|
10
8
|
|
|
11
9
|
// src/skill/tools.ts
|
|
12
10
|
import { spawn } from "child_process";
|
|
@@ -138,4 +136,4 @@ function runCommand(command, cwd, timeout) {
|
|
|
138
136
|
export {
|
|
139
137
|
skillTools
|
|
140
138
|
};
|
|
141
|
-
//# sourceMappingURL=chunk-
|
|
139
|
+
//# sourceMappingURL=chunk-KTKZCLYB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/skill/tools.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { ConfigError } from '../errors';\nimport { Tool, type ToolArguments } from '../integrations/common';\nimport { nullLogger, type Logger } from '../logging';\nimport type { Skill } from './loader';\n\nexport interface SkillToolsOptions {\n commandApproval?: (command: string, cwd: string) => boolean | Promise<boolean>;\n commandTimeoutSeconds?: number;\n logger?: Logger;\n}\nexport function skillTools(skills: readonly Skill[], options: SkillToolsOptions = {}): Tool[] {\n const timeout = options.commandTimeoutSeconds ?? 300;\n if (!Number.isInteger(timeout) || timeout <= 0) throw new ConfigError('command timeout must be a positive integer');\n const selected = new Map(skills.map((skill) => [skill.name, skill]));\n if (selected.size !== skills.length) throw new ConfigError('selected Skills must have unique names');\n const missing = (name: unknown) => JSON.stringify({ error: `Skill '${String(name)}' not found. Available skills: ${[...selected.keys()].join(', ') || 'none'}` });\n const tools = [new Tool({\n name: 'load_skills', description: `Load skill instructions for the agent. Call without arguments to list all available skills, or with a skill name to get detailed instructions.\\n\\nAvailable skills:\\n${skills.map((s) => `- ${s.name}: ${s.description}`).join('\\n')}`,\n parameters: { type: 'object', properties: { name: { type: 'string', description: 'The name of the skill to load. If omitted, returns all available skills.' } } },\n invoke: async ({ name }) => {\n if (name === undefined || name === null || name === '') return JSON.stringify({ skills: skills.map(({ name, description }) => ({ name, description })) });\n const skill = typeof name === 'string' ? selected.get(name) : undefined;\n if (!skill) return missing(name);\n return JSON.stringify({ name: skill.name, description: skill.description, instruction: skill.instruction, files: await list(skill.root) });\n },\n }), new Tool({\n name: 'read_skill_file', description: \"Read a file from a skill's directory, or list the directory when the relative path points to a directory.\",\n parameters: { type: 'object', properties: { name: { type: 'string' }, relative_path: { type: 'string' } }, required: ['name', 'relative_path'] },\n invoke: async ({ name, relative_path: resource }) => {\n const skill = typeof name === 'string' ? selected.get(name) : undefined;\n if (!skill) return missing(name);\n if (typeof resource !== 'string') return JSON.stringify({ error: 'relative_path must be a string' });\n try {\n if (isAbsolute(resource) || resource.split(/[\\\\/]/).includes('..')) throw new Error('Path is outside the skill directory. Access denied.');\n const path = join(skill.root, resource); const target = await realpath(path); const root = await realpath(skill.root);\n const relation = relative(root, target);\n if (relation === '..' || relation.startsWith(`..${sep}`) || isAbsolute(relation) || (await lstat(path)).isSymbolicLink()) throw new Error('Path is outside the skill directory. Access denied.');\n if ((await stat(path)).isDirectory()) return JSON.stringify({ files: await list(path) });\n return JSON.stringify({ content: new TextDecoder('utf8', { fatal: true }).decode(await readFile(path)) });\n } catch (error) { return JSON.stringify({ error: error instanceof Error ? error.message : 'Failed to read skill file' }); }\n },\n })];\n if ((process.env.ALLOW_EXECUTE_COMMAND ?? 'true').toLowerCase() !== 'false') tools.push(new Tool({\n name: 'execute_command', description: 'Execute a shell command in the Agent container for a selected Skill. Before calling this tool, display the exact command and ask the user for confirmation. Returns stdout, stderr, exit_code, and timeout status.',\n parameters: { type: 'object', properties: { command: { type: 'string' }, cwd: { type: 'string', description: 'Optional working directory.' }, timeout: { type: 'integer', description: 'Optional timeout in seconds.' } }, required: ['command'] },\n invoke: (args) => execute(args, defaultDirectory(skills), timeout, options),\n }));\n return tools;\n}\nasync function list(root: string): Promise<string[]> {\n return (await readdir(root, { withFileTypes: true })).filter((e) => !e.name.startsWith('.')).map((e) => e.name + (e.isDirectory() ? '/' : '')).sort();\n}\nfunction defaultDirectory(skills: readonly Skill[]): string {\n if (skills.length === 1) return skills[0]!.root;\n if (skills.length && skills[0]!.workspaceId && skills.every((s) => s.source === 'agentcore' && s.workspaceId === skills[0]!.workspaceId)) {\n let common = resolve(skills[0]!.root);\n for (const skill of skills.slice(1)) while (relative(common, skill.root).startsWith(`..${sep}`) || relative(common, skill.root) === '..') common = dirname(common);\n return common;\n }\n if (skills.length && skills.every((s) => dirname(s.root) === dirname(skills[0]!.root))) return dirname(skills[0]!.root);\n return process.cwd();\n}\nasync function execute(args: ToolArguments, defaultCwd: string, defaultTimeout: number, options: SkillToolsOptions): Promise<string> {\n const { command, cwd = defaultCwd, timeout = defaultTimeout } = args;\n if (typeof command !== 'string' || !command) return JSON.stringify({ error: 'command must be a non-empty string' });\n if (typeof timeout !== 'number' || !Number.isInteger(timeout) || timeout <= 0) return JSON.stringify({ error: 'timeout must be a positive integer' });\n try {\n if (typeof cwd !== 'string' || !(await stat(cwd)).isDirectory()) throw new Error('Working directory does not exist');\n if (options.commandApproval && !await options.commandApproval(command, cwd)) return JSON.stringify({ error: 'Command execution rejected by user.' });\n const logger = options.logger ?? nullLogger;\n logger.info('agentcore.skill.command.started', { cwd, timeout_seconds: timeout });\n const result = await runCommand(command, cwd, timeout);\n logger.info('agentcore.skill.command.completed', { cwd, exit_code: result.exit_code, timed_out: result.timed_out });\n return JSON.stringify(result);\n } catch (error) { return JSON.stringify({ error: error instanceof Error ? error.message : 'Failed to execute command' }); }\n}\nfunction runCommand(command: string, cwd: string, timeout: number): Promise<{ stdout: string; stderr: string; exit_code: number; timed_out: boolean }> {\n return new Promise((accept, reject) => {\n const child = spawn(command, { shell: true, cwd, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] });\n const limit = 100 * 1024;\n const output = [Buffer.alloc(0), Buffer.alloc(0)]; const truncated = [false, false];\n for (const [index, stream] of [child.stdout, child.stderr].entries()) stream.on('data', (chunk: Buffer) => {\n const remaining = limit - output[index]!.length;\n if (chunk.length > remaining) truncated[index] = true;\n if (remaining > 0) output[index] = Buffer.concat([output[index]!, chunk.subarray(0, remaining)]);\n });\n let timedOut = false; let killTimer: ReturnType<typeof setTimeout> | undefined;\n const signal = (value: NodeJS.Signals) => {\n if (!child.pid) return;\n try { if (process.platform === 'win32') child.kill(value); else process.kill(-child.pid, value); }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') child.kill(value); }\n };\n const timer = setTimeout(() => { timedOut = true; signal('SIGTERM'); killTimer = setTimeout(() => signal('SIGKILL'), 100); }, timeout * 1000);\n child.on('error', (error) => { clearTimeout(timer); clearTimeout(killTimer); reject(error); });\n child.on('close', (code) => {\n clearTimeout(timer);\n // Even if the shell exits first, kill any remaining children of a timed-out command.\n if (timedOut) { clearTimeout(killTimer); signal('SIGKILL'); }\n const text = (index: number) => output[index]!.toString('utf8') + (truncated[index] ? `\\n... [output truncated, exceeded ${limit} bytes]` : '');\n accept(timedOut ? { stdout: '', stderr: `Command timed out after ${timeout} seconds.`, exit_code: -1, timed_out: true }\n : { stdout: text(0), stderr: text(1), exit_code: code ?? -1, timed_out: false });\n });\n });\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,OAAO,UAAU,SAAS,UAAU,YAAY;AACzD,SAAS,SAAS,YAAY,MAAM,UAAU,SAAS,WAAW;AAW3D,SAAS,WAAW,QAA0B,UAA6B,CAAC,GAAW;AAC5F,QAAM,UAAU,QAAQ,yBAAyB;AACjD,MAAI,CAAC,OAAO,UAAU,OAAO,KAAK,WAAW,EAAG,OAAM,IAAI,YAAY,4CAA4C;AAClH,QAAM,WAAW,IAAI,IAAI,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,MAAM,KAAK,CAAC,CAAC;AACnE,MAAI,SAAS,SAAS,OAAO,OAAQ,OAAM,IAAI,YAAY,wCAAwC;AACnG,QAAM,UAAU,CAAC,SAAkB,KAAK,UAAU,EAAE,OAAO,UAAU,OAAO,IAAI,CAAC,kCAAkC,CAAC,GAAG,SAAS,KAAK,CAAC,EAAE,KAAK,IAAI,KAAK,MAAM,GAAG,CAAC;AAChK,QAAM,QAAQ,CAAC,IAAI,KAAK;AAAA,IACtB,MAAM;AAAA,IAAe,aAAa;AAAA;AAAA;AAAA,EAAwK,OAAO,IAAI,CAAC,MAAM,KAAK,EAAE,IAAI,KAAK,EAAE,WAAW,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA,IACvQ,YAAY,EAAE,MAAM,UAAU,YAAY,EAAE,MAAM,EAAE,MAAM,UAAU,aAAa,2EAA2E,EAAE,EAAE;AAAA,IAChK,QAAQ,OAAO,EAAE,KAAK,MAAM;AAC1B,UAAI,SAAS,UAAa,SAAS,QAAQ,SAAS,GAAI,QAAO,KAAK,UAAU,EAAE,QAAQ,OAAO,IAAI,CAAC,EAAE,MAAAA,OAAM,YAAY,OAAO,EAAE,MAAAA,OAAM,YAAY,EAAE,EAAE,C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G,aAAO,KAAK;AAAA,IAAG,CAAC;AAC7F,UAAM,GAAG,SAAS,CAAC,SAAS;AAC1B,mBAAa,KAAK;AAElB,UAAI,UAAU;AAAE,qBAAa,SAAS;AAAG,eAAO,SAAS;AAAA,MAAG;AAC5D,YAAM,OAAO,CAAC,UAAkB,OAAO,KAAK,EAAG,SAAS,MAAM,KAAK,UAAU,KAAK,IAAI;AAAA,kCAAqC,KAAK,YAAY;AAC5I,aAAO,WAAW,EAAE,QAAQ,IAAI,QAAQ,2BAA2B,OAAO,aAAa,WAAW,IAAI,WAAW,KAAK,IAClH,EAAE,QAAQ,KAAK,CAAC,GAAG,QAAQ,KAAK,CAAC,GAAG,WAAW,QAAQ,IAAI,WAAW,MAAM,CAAC;AAAA,IACnF,CAAC;AAAA,EACH,CAAC;AACH;","names":["name"]}
|
|
1
|
+
{"version":3,"sources":["../src/skill/tools.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { ConfigError } from '../errors';\nimport { Tool, type ToolArguments } from '../integrations/common';\nimport { nullLogger, type Logger } from '../logging';\nimport type { Skill } from './loader';\n\nexport interface SkillToolsOptions {\n commandApproval?: (command: string, cwd: string) => boolean | Promise<boolean>;\n commandTimeoutSeconds?: number;\n logger?: Logger;\n}\nexport function skillTools(skills: readonly Skill[], options: SkillToolsOptions = {}): Tool[] {\n const timeout = options.commandTimeoutSeconds ?? 300;\n if (!Number.isInteger(timeout) || timeout <= 0) throw new ConfigError('command timeout must be a positive integer');\n const selected = new Map(skills.map((skill) => [skill.name, skill]));\n if (selected.size !== skills.length) throw new ConfigError('selected Skills must have unique names');\n const missing = (name: unknown) => JSON.stringify({ error: `Skill '${String(name)}' not found. Available skills: ${[...selected.keys()].join(', ') || 'none'}` });\n const tools = [new Tool({\n name: 'load_skills', description: `Load skill instructions for the agent. Call without arguments to list all available skills, or with a skill name to get detailed instructions.\\n\\nAvailable skills:\\n${skills.map((s) => `- ${s.name}: ${s.description}`).join('\\n')}`,\n parameters: { type: 'object', properties: { name: { type: 'string', description: 'The name of the skill to load. If omitted, returns all available skills.' } } },\n invoke: async ({ name }) => {\n if (name === undefined || name === null || name === '') return JSON.stringify({ skills: skills.map(({ name, description }) => ({ name, description })) });\n const skill = typeof name === 'string' ? selected.get(name) : undefined;\n if (!skill) return missing(name);\n return JSON.stringify({ name: skill.name, description: skill.description, instruction: skill.instruction, files: await list(skill.root) });\n },\n }), new Tool({\n name: 'read_skill_file', description: \"Read a file from a skill's directory, or list the directory when the relative path points to a directory.\",\n parameters: { type: 'object', properties: { name: { type: 'string' }, relative_path: { type: 'string' } }, required: ['name', 'relative_path'] },\n invoke: async ({ name, relative_path: resource }) => {\n const skill = typeof name === 'string' ? selected.get(name) : undefined;\n if (!skill) return missing(name);\n if (typeof resource !== 'string') return JSON.stringify({ error: 'relative_path must be a string' });\n try {\n if (isAbsolute(resource) || resource.split(/[\\\\/]/).includes('..')) throw new Error('Path is outside the skill directory. Access denied.');\n const path = join(skill.root, resource); const target = await realpath(path); const root = await realpath(skill.root);\n const relation = relative(root, target);\n if (relation === '..' || relation.startsWith(`..${sep}`) || isAbsolute(relation) || (await lstat(path)).isSymbolicLink()) throw new Error('Path is outside the skill directory. Access denied.');\n if ((await stat(path)).isDirectory()) return JSON.stringify({ files: await list(path) });\n return JSON.stringify({ content: new TextDecoder('utf8', { fatal: true }).decode(await readFile(path)) });\n } catch (error) { return JSON.stringify({ error: error instanceof Error ? error.message : 'Failed to read skill file' }); }\n },\n })];\n if ((process.env.ALLOW_EXECUTE_COMMAND ?? 'true').toLowerCase() !== 'false') tools.push(new Tool({\n name: 'execute_command', description: 'Execute a shell command in the Agent container for a selected Skill. Before calling this tool, display the exact command and ask the user for confirmation. Returns stdout, stderr, exit_code, and timeout status.',\n parameters: { type: 'object', properties: { command: { type: 'string' }, cwd: { type: 'string', description: 'Optional working directory.' }, timeout: { type: 'integer', description: 'Optional timeout in seconds.' } }, required: ['command'] },\n invoke: (args) => execute(args, defaultDirectory(skills), timeout, options),\n }));\n return tools;\n}\nasync function list(root: string): Promise<string[]> {\n return (await readdir(root, { withFileTypes: true })).filter((e) => !e.name.startsWith('.')).map((e) => e.name + (e.isDirectory() ? '/' : '')).sort();\n}\nfunction defaultDirectory(skills: readonly Skill[]): string {\n if (skills.length === 1) return skills[0]!.root;\n if (skills.length && skills[0]!.workspaceId && skills.every((s) => s.source === 'agentcore' && s.workspaceId === skills[0]!.workspaceId)) {\n let common = resolve(skills[0]!.root);\n for (const skill of skills.slice(1)) while (relative(common, skill.root).startsWith(`..${sep}`) || relative(common, skill.root) === '..') common = dirname(common);\n return common;\n }\n if (skills.length && skills.every((s) => dirname(s.root) === dirname(skills[0]!.root))) return dirname(skills[0]!.root);\n return process.cwd();\n}\nasync function execute(args: ToolArguments, defaultCwd: string, defaultTimeout: number, options: SkillToolsOptions): Promise<string> {\n const { command, cwd = defaultCwd, timeout = defaultTimeout } = args;\n if (typeof command !== 'string' || !command) return JSON.stringify({ error: 'command must be a non-empty string' });\n if (typeof timeout !== 'number' || !Number.isInteger(timeout) || timeout <= 0) return JSON.stringify({ error: 'timeout must be a positive integer' });\n try {\n if (typeof cwd !== 'string' || !(await stat(cwd)).isDirectory()) throw new Error('Working directory does not exist');\n if (options.commandApproval && !await options.commandApproval(command, cwd)) return JSON.stringify({ error: 'Command execution rejected by user.' });\n const logger = options.logger ?? nullLogger;\n logger.info('agentcore.skill.command.started', { cwd, timeout_seconds: timeout });\n const result = await runCommand(command, cwd, timeout);\n logger.info('agentcore.skill.command.completed', { cwd, exit_code: result.exit_code, timed_out: result.timed_out });\n return JSON.stringify(result);\n } catch (error) { return JSON.stringify({ error: error instanceof Error ? error.message : 'Failed to execute command' }); }\n}\nfunction runCommand(command: string, cwd: string, timeout: number): Promise<{ stdout: string; stderr: string; exit_code: number; timed_out: boolean }> {\n return new Promise((accept, reject) => {\n const child = spawn(command, { shell: true, cwd, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] });\n const limit = 100 * 1024;\n const output = [Buffer.alloc(0), Buffer.alloc(0)]; const truncated = [false, false];\n for (const [index, stream] of [child.stdout, child.stderr].entries()) stream.on('data', (chunk: Buffer) => {\n const remaining = limit - output[index]!.length;\n if (chunk.length > remaining) truncated[index] = true;\n if (remaining > 0) output[index] = Buffer.concat([output[index]!, chunk.subarray(0, remaining)]);\n });\n let timedOut = false; let killTimer: ReturnType<typeof setTimeout> | undefined;\n const signal = (value: NodeJS.Signals) => {\n if (!child.pid) return;\n try { if (process.platform === 'win32') child.kill(value); else process.kill(-child.pid, value); }\n catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') child.kill(value); }\n };\n const timer = setTimeout(() => { timedOut = true; signal('SIGTERM'); killTimer = setTimeout(() => signal('SIGKILL'), 100); }, timeout * 1000);\n child.on('error', (error) => { clearTimeout(timer); clearTimeout(killTimer); reject(error); });\n child.on('close', (code) => {\n clearTimeout(timer);\n // Even if the shell exits first, kill any remaining children of a timed-out command.\n if (timedOut) { clearTimeout(killTimer); signal('SIGKILL'); }\n const text = (index: number) => output[index]!.toString('utf8') + (truncated[index] ? `\\n... [output truncated, exceeded ${limit} bytes]` : '');\n accept(timedOut ? { stdout: '', stderr: `Command timed out after ${timeout} seconds.`, exit_code: -1, timed_out: true }\n : { stdout: text(0), stderr: text(1), exit_code: code ?? -1, timed_out: false });\n });\n });\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,OAAO,UAAU,SAAS,UAAU,YAAY;AACzD,SAAS,SAAS,YAAY,MAAM,UAAU,SAAS,WAAW;AAW3D,SAAS,WAAW,QAA0B,UAA6B,CAAC,GAAW;AAC5F,QAAM,UAAU,QAAQ,yBAAyB;AACjD,MAAI,CAAC,OAAO,UAAU,OAAO,KAAK,WAAW,EAAG,OAAM,IAAI,YAAY,4CAA4C;AAClH,QAAM,WAAW,IAAI,IAA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AAW,MAAM,CAAC;AAAA,IACnF,CAAC;AAAA,EACH,CAAC;AACH;","names":["name"]}
|
|
@@ -1,25 +1,23 @@
|
|
|
1
1
|
import {
|
|
2
2
|
readBytes
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-NRYDUATX.js";
|
|
4
4
|
import {
|
|
5
5
|
AgentSATokenProvider,
|
|
6
6
|
ControllerClient
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-AX3NM2DK.js";
|
|
8
8
|
import {
|
|
9
9
|
DEFAULT_CONFIG_PATH,
|
|
10
10
|
httpUrl,
|
|
11
11
|
object,
|
|
12
12
|
parseAgentConfig,
|
|
13
13
|
requiredString
|
|
14
|
-
} from "./chunk-
|
|
15
|
-
import {
|
|
16
|
-
nullLogger
|
|
17
|
-
} from "./chunk-NZL3VPJ2.js";
|
|
14
|
+
} from "./chunk-3JXIMUUY.js";
|
|
18
15
|
import {
|
|
19
16
|
AuthenticationError,
|
|
20
17
|
ConfigError,
|
|
21
|
-
CredentialExchangeError
|
|
22
|
-
|
|
18
|
+
CredentialExchangeError,
|
|
19
|
+
nullLogger
|
|
20
|
+
} from "./chunk-AEQ76QIO.js";
|
|
23
21
|
|
|
24
22
|
// src/runtime/environment.ts
|
|
25
23
|
import { readFile } from "fs/promises";
|
|
@@ -88,6 +86,7 @@ var RuntimeEnvironmentProvider = class {
|
|
|
88
86
|
try {
|
|
89
87
|
text = await readFile(this.path, "utf8");
|
|
90
88
|
} catch (cause) {
|
|
89
|
+
if (cause.code === "ENOENT") return {};
|
|
91
90
|
throw new ConfigError("cannot read AgentCore runtime env", { cause });
|
|
92
91
|
}
|
|
93
92
|
return parseRuntimeEnvironment(text);
|
|
@@ -579,4 +578,4 @@ export {
|
|
|
579
578
|
DebugRuntimeSource,
|
|
580
579
|
createRuntimeSource
|
|
581
580
|
};
|
|
582
|
-
//# sourceMappingURL=chunk-
|
|
581
|
+
//# sourceMappingURL=chunk-L74ASQWF.js.map
|