alibabacloud-agentcore-sdk 0.1.2 → 0.1.4
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 +15 -2
- 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-UWPKFJYM.js → chunk-45S6S5WI.js} +13 -11
- package/dist/chunk-45S6S5WI.js.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-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-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-GYLT23D3.js → chunk-NI3U6RZL.js} +5 -5
- 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-IF7LMBXC.js → chunk-PHVKSATD.js} +60 -16
- package/dist/chunk-PHVKSATD.js.map +1 -0
- package/dist/{chunk-RYXL25AI.js → chunk-PS3EAUMK.js} +2 -2
- 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-LXHW6OT4.cjs → chunk-T26WN7TD.cjs} +19 -17
- package/dist/chunk-T26WN7TD.cjs.map +1 -0
- 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-ZLQ2IBTC.cjs → chunk-WRRIPTJP.cjs} +12 -12
- package/dist/{chunk-ZLQ2IBTC.cjs.map → chunk-WRRIPTJP.cjs.map} +1 -1
- package/dist/{chunk-QIZO3A4Y.cjs → chunk-ZIXZWQSP.cjs} +85 -41
- package/dist/chunk-ZIXZWQSP.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 +14 -15
- package/dist/integrations/google-adk.cjs.map +1 -1
- package/dist/integrations/google-adk.js +10 -11
- 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.d.cts +3 -2
- package/dist/integrations/langchain.d.ts +3 -2
- 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.d.cts +3 -2
- package/dist/integrations/langgraph.d.ts +3 -2
- 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-adapter-DJsyjm5V.d.ts → langchain-adapter-CaTCXaeo.d.ts} +4 -2
- package/dist/{langchain-adapter-DFJdEX04.d.cts → langchain-adapter-DtxU7oAi.d.cts} +4 -2
- package/dist/{langchain-provider-PHL4UWNF.js → langchain-provider-JFWLKOGL.js} +26 -2
- package/dist/langchain-provider-JFWLKOGL.js.map +1 -0
- package/dist/{langchain-provider-NF5GIDQV.cjs → langchain-provider-UKO27CQA.cjs} +38 -14
- package/dist/langchain-provider-UKO27CQA.cjs.map +1 -0
- 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.d.cts +24 -2
- package/dist/memory/index.d.ts +24 -2
- 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-UWPKFJYM.js.map +0 -1
- package/dist/chunk-ZTWLCHCO.cjs.map +0 -1
- package/dist/langchain-provider-NF5GIDQV.cjs.map +0 -1
- package/dist/langchain-provider-PHL4UWNF.js.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-NI3U6RZL.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
|
@@ -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,EAArC;AAAA,EACrB,MAAM,GAAA,CAAA,EAAuB;AAC3B,IAAA,IAAI,KAAA;AACJ,IAAA,IAAI;AAAE,MAAA,MAAA,EAAQ,MAAM,gCAAA,IAAS,CAAK,IAAA,EAAM,MAAM,CAAA;AAAA,IAAG,EAAA,MAAA,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AA,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,U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AAkB,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,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,UA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
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/runtime/environment.ts","../src/runtime/managed.ts","../src/runtime/debug.ts","../src/runtime/control-config.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { ConfigError } from '../errors';\nimport { httpUrl, requiredString } from './config';\n\nexport const DEFAULT_ENV_PATH = '/var/run/agentcore/agent/env';\nexport interface RuntimeEnvironment {\n controllerUrl: string;\n agentSATokenFile: string;\n controlPlaneEndpoint?: string;\n}\n\n// Tokenize shell quoting, but deliberately do not evaluate expansions or commands.\nfunction words(line: string): string[] {\n const parts: string[] = [];\n let word = '';\n let quote = '';\n let started = false;\n for (let i = 0; i < line.length; i++) {\n const char = line[i]!;\n if (quote === \"'\") {\n if (char === quote) quote = ''; else word += char;\n } else if (char === '\\\\') {\n const next = line[++i];\n if (next === undefined) throw new Error('incomplete escape');\n if (quote === '\"' && next !== '\"' && next !== '\\\\') word += '\\\\';\n word += next;\n started = true;\n } else if (quote) {\n if (char === quote) quote = ''; else word += char;\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n started = true;\n } else if (/\\s/.test(char)) {\n if (started) { parts.push(word); word = ''; started = false; }\n } else {\n word += char;\n started = true;\n }\n }\n if (quote) throw new Error('unclosed quote');\n if (started) parts.push(word);\n return parts;\n}\n\nexport function parseRuntimeEnvironment(text: string): Record<string, string> {\n const values: Record<string, string> = Object.create(null) as Record<string, string>;\n for (const [index, raw] of text.split(/\\r?\\n/).entries()) {\n const line = raw.trim();\n if (!line || line.startsWith('#')) continue;\n try {\n const parts = words(line);\n if (parts.length !== 2 || parts[0] !== 'export') throw new Error('expected export');\n const match = /^([A-Za-z_][A-Za-z0-9_]*)=([\\s\\S]*)$/.exec(parts[1]!);\n if (!match || Object.hasOwn(values, match[1]!)) throw new Error('invalid assignment');\n values[match[1]!] = match[2]!;\n } catch { throw new ConfigError(`invalid runtime env at line ${index + 1}`); }\n }\n return values;\n}\n\nexport class RuntimeEnvironmentProvider {\n constructor(readonly path = DEFAULT_ENV_PATH) {}\n async read(): Promise<Record<string, string>> {\n let text: string;\n try { text = await readFile(this.path, 'utf8'); } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw new ConfigError('cannot read AgentCore runtime env', { cause });\n }\n return parseRuntimeEnvironment(text);\n }\n async snapshot(): Promise<RuntimeEnvironment> {\n const values = await this.read();\n const endpoint = values.AGENTCORE_CONTROL_ENDPOINT || process.env.AGENTCORE_CONTROL_ENDPOINT;\n return {\n controllerUrl: httpUrl(values.AGENTCORE_CONTROLLER_URL || values.AGENTTEAMS_CONTROLLER_URL, 'runtime Controller URL'),\n agentSATokenFile: requiredString(values.AGENTCORE_AUTH_TOKEN_FILE || values.AGENTTEAMS_AUTH_TOKEN_FILE, 'runtime SA token file'),\n controlPlaneEndpoint: endpoint?.trim() || undefined,\n };\n }\n async value(name: string): Promise<string> {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new ConfigError('runtime environment name is invalid');\n const values = await this.read();\n return requiredString(values[name] || process.env[name], `runtime env ${name}`);\n }\n async taskServiceEndpoint(): Promise<string> {\n const values = await this.read();\n const endpoint = values.AGENTCORE_TASK_SERVICE_ENDPOINT || process.env.AGENTCORE_TASK_SERVICE_ENDPOINT;\n if (endpoint?.trim()) return httpUrl(endpoint, 'Task Service endpoint');\n const gateway = httpUrl(values.AGENTTEAMS_MATRIX_URL || process.env.AGENTTEAMS_MATRIX_URL, 'Task Service endpoint');\n return gateway.endsWith('/agentteams-app') ? gateway : `${gateway}/agentteams-app`;\n }\n}\n","import { access, readFile } from 'node:fs/promises';\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { ConfigError } from '../errors';\nimport { AgentSATokenProvider, type AgentSATokenSource } from '../auth/agent-sa-token';\nimport { nullLogger, type Logger } from '../logging';\nimport { DEFAULT_CONFIG_PATH, parseAgentConfig, type AgentConfig } from './config';\nimport { DEFAULT_ENV_PATH, RuntimeEnvironmentProvider } from './environment';\n\nexport interface RuntimeBindings {\n config: AgentConfig;\n controllerEndpoint?: string;\n controlPlaneEndpoint?: string;\n agentSATokens?: AgentSATokenSource;\n}\nexport interface RuntimeSource {\n resolve(): Promise<RuntimeBindings>;\n close(): void | Promise<void>;\n}\nexport interface ManagedRuntimeOptions {\n configPath?: string;\n envPath?: string;\n controlPlaneEndpoint?: string;\n logger?: Logger;\n}\n\nexport class ManagedRuntimeSource implements RuntimeSource {\n private bindings?: RuntimeBindings;\n private pending?: Promise<RuntimeBindings>;\n private readonly lifetime = new AbortController();\n constructor(private readonly options: ManagedRuntimeOptions = {}) {}\n\n async resolve(): Promise<RuntimeBindings> {\n this.lifetime.signal.throwIfAborted();\n if (this.bindings) return this.bindings;\n if (this.pending) return this.pending;\n const request = this.load();\n this.pending = request;\n try { this.bindings = await request; return this.bindings; }\n finally { this.pending = undefined; }\n }\n close(): void { this.lifetime.abort(); }\n\n private async load(): Promise<RuntimeBindings> {\n const configPath = this.options.configPath || process.env.AGENTCORE_CONFIG_PATH || DEFAULT_CONFIG_PATH;\n const rawTimeout = process.env.AGENTCORE_CONFIG_WAIT_TIMEOUT ?? '10';\n if (!/^\\d+$/.test(rawTimeout) || !Number.isSafeInteger(Number(rawTimeout))) {\n throw new ConfigError('AGENTCORE_CONFIG_WAIT_TIMEOUT must be a non-negative integer');\n }\n const deadline = performance.now() + Number(rawTimeout) * 1000;\n let config: AgentConfig;\n const logger = this.options.logger ?? nullLogger;\n for (;;) {\n this.lifetime.signal.throwIfAborted();\n let data: Buffer;\n try { data = await readFile(configPath); } catch (cause) {\n const remaining = deadline - performance.now();\n if (!(cause && typeof cause === 'object' && 'code' in cause && cause.code === 'ENOENT') || remaining <= 0) {\n throw new ConfigError('cannot read agent.yaml', { cause });\n }\n logger.info('agentcore.runtime.config.waiting_for_mount', { path: configPath, retryInMs: Math.min(500, remaining) });\n await sleep(Math.min(500, remaining), undefined, { signal: this.lifetime.signal });\n continue;\n }\n config = parseAgentConfig(data);\n break;\n }\n const configuredEnv = this.options.envPath || process.env.AGENTCORE_ENV_PATH;\n const envPath = configuredEnv || DEFAULT_ENV_PATH;\n let hasEnvironment = Boolean(configuredEnv);\n if (!hasEnvironment) {\n try { await access(envPath); hasEnvironment = true; } catch (cause) {\n if (!(cause && typeof cause === 'object' && 'code' in cause && cause.code === 'ENOENT')) {\n throw new ConfigError('cannot access AgentCore runtime env', { cause });\n }\n }\n }\n const environment = hasEnvironment ? await new RuntimeEnvironmentProvider(envPath).snapshot() : undefined;\n const bindings = {\n config,\n controllerEndpoint: environment?.controllerUrl,\n controlPlaneEndpoint: this.options.controlPlaneEndpoint ?? environment?.controlPlaneEndpoint ?? process.env.AGENTCORE_CONTROL_ENDPOINT,\n agentSATokens: environment ? new AgentSATokenProvider(environment.agentSATokenFile) : undefined,\n };\n this.lifetime.signal.throwIfAborted();\n logger.info('agentcore.runtime.source.resolved', { mode: 'managed', envLoaded: hasEnvironment, workspaceId: config.workspaceId });\n return bindings;\n }\n}\n","import { inspect } from 'node:util';\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { AuthenticationError, ConfigError } from '../errors';\nimport { nullLogger, type Logger } from '../logging';\nimport { ControllerClient, type ControllerOptions } from '../auth/controller';\nimport type { AgentSATokenSource } from '../auth/agent-sa-token';\nimport { httpUrl, object, requiredString, type AgentConfig } from './config';\nimport { ControlConfigLoader } from './control-config';\nimport { ManagedRuntimeSource, type ManagedRuntimeOptions, type RuntimeBindings, type RuntimeSource } from './managed';\n\nexport class DebugToken {\n readonly product = 'agentcore';\n #jwtToken: string;\n constructor(jwtToken: string, readonly controllerUrl: string, readonly modelGatewayUrl: string, readonly matrixUrl: string) { this.#jwtToken = jwtToken; }\n get jwtToken(): string { return this.#jwtToken; }\n [inspect.custom](): string { return 'DebugToken(product=agentcore, <redacted>)'; }\n toJSON(): string { return this[inspect.custom](); }\n}\n\nexport function parseDebugToken(value: string): DebugToken {\n try {\n const encoded = value.trim();\n if (!encoded || encoded.length > 350_000 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) throw new Error('base64');\n const raw = Buffer.from(encoded, 'base64');\n if (raw.length > 256 * 1024) throw new Error('size');\n const data = object(JSON.parse(new TextDecoder('utf8', { fatal: true }).decode(raw)), 'debug token');\n if (data.product !== 'agentcore') throw new Error('product');\n const controller = httpUrl(data.controllerUrl, 'controllerUrl');\n if (new URL(controller).pathname !== '/') throw new Error('controllerUrl path');\n return new DebugToken(requiredString(data.jwtToken, 'jwtToken'), controller,\n httpUrl(data.modelGatewayUrl, 'modelGatewayUrl'), httpUrl(data.matrixUrl, 'matrixUrl'));\n } catch { throw new ConfigError('AGENTCORE_DEBUG_TOKEN is invalid'); }\n}\n\nclass DebugTokenExchangeUnavailable extends AuthenticationError {}\n\nexport interface DebugRuntimeOptions extends ControllerOptions { controlPlaneEndpoint?: string; }\n\nexport class DebugRuntimeSource implements RuntimeSource, AgentSATokenSource {\n #jwtToken: string;\n #saToken?: string;\n private saExpiresAt = 0;\n private jwtExpiresAt = 0;\n private bindings?: RuntimeBindings;\n private resolving?: Promise<RuntimeBindings>;\n private exchanging?: Promise<string>;\n private refreshTimer?: ReturnType<typeof setTimeout>;\n private readonly lifetime = new AbortController();\n private readonly configLoader: ControlConfigLoader;\n private readonly controller: ControllerClient;\n private readonly logger: Logger;\n\n constructor(private readonly token: DebugToken, private readonly options: DebugRuntimeOptions = {}) {\n this.#jwtToken = token.jwtToken;\n this.configLoader = new ControlConfigLoader(token.controllerUrl, this, options);\n this.controller = new ControllerClient(token.controllerUrl, this, options);\n this.logger = options.logger ?? nullLogger;\n }\n get matrixUrl(): string { return this.token.matrixUrl; }\n\n async resolve(): Promise<RuntimeBindings> {\n this.lifetime.signal.throwIfAborted();\n if (this.bindings) return this.bindings;\n if (this.resolving) return this.resolving;\n const request = this.load();\n this.resolving = request;\n try { this.bindings = await request; return this.bindings; }\n finally { this.resolving = undefined; }\n }\n async get(): Promise<string> {\n this.lifetime.signal.throwIfAborted();\n if (this.#saToken && this.saExpiresAt > Date.now() + 60_000) return this.#saToken;\n return this.exchange();\n }\n async refresh(current: string): Promise<string> {\n this.lifetime.signal.throwIfAborted();\n if (this.#saToken && this.#saToken !== current) return this.#saToken;\n return this.exchange();\n }\n async loadTeamsConfig(): Promise<Uint8Array | undefined> { await this.resolve(); return this.configLoader.loadTeams(); }\n async exchangeMatrixToken(): Promise<string> {\n const response = await this.controller.post('/api/v1/credentials/matrix-token');\n if (response.status < 200 || response.status >= 300) throw new AuthenticationError(`Controller Matrix token request failed with HTTP ${response.status}`);\n try { return requiredString(object(response.payload, 'Matrix token').access_token, 'access_token'); }\n catch { throw new AuthenticationError('Controller returned an invalid Matrix token response'); }\n }\n close(): void {\n this.lifetime.abort();\n if (this.refreshTimer) clearTimeout(this.refreshTimer);\n this.configLoader.close(); this.controller.close(); this.#saToken = undefined; this.#jwtToken = '';\n }\n [inspect.custom](): string { return 'DebugRuntimeSource(<redacted>)'; }\n toJSON(): string { return this[inspect.custom](); }\n\n private async load(): Promise<RuntimeBindings> {\n const config = await this.configLoader.load();\n this.lifetime.signal.throwIfAborted();\n const override = (mounted: string) => {\n const gateway = new URL(this.token.modelGatewayUrl);\n const runtime = new URL(mounted);\n if (runtime.pathname !== '/') gateway.pathname = runtime.pathname;\n return gateway.toString().replace(/\\/+$/, '');\n };\n const projected: AgentConfig = Object.freeze({ ...config,\n modelGatewayUrl: override(config.modelGatewayUrl), mcpGatewayUrl: override(config.mcpGatewayUrl),\n });\n this.logger.info('agentcore.runtime.source.resolved', { mode: 'debug', workspaceId: config.workspaceId });\n return { config: projected, controllerEndpoint: this.token.controllerUrl,\n controlPlaneEndpoint: this.options.controlPlaneEndpoint, agentSATokens: this };\n }\n\n private async exchange(): Promise<string> {\n this.lifetime.signal.throwIfAborted();\n if (this.exchanging) return this.exchanging;\n const request = this.requestToken().then((data) => {\n this.lifetime.signal.throwIfAborted();\n this.#saToken = data.token; this.saExpiresAt = data.expiresAt;\n this.#jwtToken = data.jwtToken; this.jwtExpiresAt = data.jwtExpiresAt;\n this.scheduleRefresh();\n this.logger.info('agentcore.runtime.debug.sa_exchange.succeeded', {\n expiration: new Date(this.saExpiresAt).toISOString(), jwtExpiration: new Date(this.jwtExpiresAt).toISOString(),\n });\n return this.#saToken;\n });\n this.exchanging = request;\n try { return await request; } finally { this.exchanging = undefined; }\n }\n\n private scheduleRefresh(delay = Math.max(1000, this.jwtExpiresAt - Date.now() - 300_000)): void {\n if (this.refreshTimer) clearTimeout(this.refreshTimer);\n if (this.lifetime.signal.aborted) return;\n this.refreshTimer = setTimeout(() => { void this.backgroundRefresh(); }, delay);\n this.refreshTimer.unref();\n }\n private async backgroundRefresh(): Promise<void> {\n if (this.lifetime.signal.aborted || this.jwtExpiresAt <= Date.now()) return;\n try { await this.exchange(); }\n catch (error) {\n if (this.lifetime.signal.aborted) return;\n const remaining = this.jwtExpiresAt - Date.now();\n this.logger.warn('agentcore.runtime.debug.jwt_refresh.failed', { reason: error instanceof DebugTokenExchangeUnavailable ? 'temporarily_unavailable' : 'authentication_failed' });\n if (error instanceof DebugTokenExchangeUnavailable && remaining > 1000) this.scheduleRefresh(Math.min(30_000, remaining / 2));\n }\n }\n\n private async requestToken(): Promise<{ token: string; expiresAt: number; jwtToken: string; jwtExpiresAt: number }> {\n const url = `${this.token.controllerUrl}/api/v1/edge/token`;\n for (let attempt = 1; attempt <= (this.options.maxAttempts ?? 3); attempt++) {\n let response: Response;\n let payload: unknown;\n try {\n response = await fetch(url, {\n method: 'POST', headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ jwtToken: this.#jwtToken }), redirect: 'manual',\n signal: AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(this.options.timeoutMs ?? 10_000)]),\n });\n const text = await response.text();\n try { payload = JSON.parse(text); } catch { payload = undefined; }\n } catch {\n this.lifetime.signal.throwIfAborted();\n if (attempt === (this.options.maxAttempts ?? 3)) throw new DebugTokenExchangeUnavailable('cannot reach the AgentCore Controller');\n this.logger.warn('agentcore.runtime.debug.sa_exchange.retry', { url, attempt, reason: 'transport_error' });\n await sleep(50 * 2 ** (attempt - 1), undefined, { signal: this.lifetime.signal }); continue;\n }\n if ([500, 502, 503, 504].includes(response.status)) {\n if (attempt === (this.options.maxAttempts ?? 3)) throw new DebugTokenExchangeUnavailable('Controller debug token service is unavailable');\n this.logger.warn('agentcore.runtime.debug.sa_exchange.retry', { url, attempt, status: response.status });\n await sleep(50 * 2 ** (attempt - 1), undefined, { signal: this.lifetime.signal }); continue;\n }\n if ([401, 403].includes(response.status)) throw new AuthenticationError('Controller rejected the AgentCore debug token');\n if (!response.ok) throw new AuthenticationError(`Controller debug token exchange failed with HTTP ${response.status}`);\n try {\n const data = object(payload, 'debug token response');\n const token = requiredString(data.token, 'token'); const jwtToken = requiredString(data.jwtToken, 'jwtToken');\n const expiresAt = Date.parse(requiredString(data.expiresAt, 'expiresAt'));\n const jwtExpiresAt = Date.parse(requiredString(data.jwtExpiresAt, 'jwtExpiresAt'));\n if (!(expiresAt > Date.now()) || !(jwtExpiresAt > Date.now())) throw new Error('expiry');\n return { token, jwtToken, expiresAt, jwtExpiresAt };\n } catch { throw new AuthenticationError('Controller returned an invalid debug token response'); }\n }\n throw new DebugTokenExchangeUnavailable('Controller debug token service is unavailable');\n }\n}\n\nexport function createRuntimeSource(options: ManagedRuntimeOptions = {}): RuntimeSource {\n const raw = process.env.AGENTCORE_DEBUG_TOKEN?.trim();\n if (raw) return new DebugRuntimeSource(parseDebugToken(raw), {\n controlPlaneEndpoint: options.controlPlaneEndpoint ?? process.env.AGENTCORE_CONTROL_ENDPOINT,\n logger: options.logger,\n });\n return new ManagedRuntimeSource(options);\n}\n","import { createHmac } from 'node:crypto';\nimport { isIP } from 'node:net';\nimport { AuthenticationError, ConfigError, CredentialExchangeError } from '../errors';\nimport { ControllerClient, type ControllerOptions } from '../auth/controller';\nimport type { AgentSATokenSource } from '../auth/agent-sa-token';\nimport { readBytes } from '../http';\nimport { nullLogger, type Logger } from '../logging';\nimport { httpUrl, object, parseAgentConfig, requiredString, type AgentConfig } from './config';\n\ninterface ControlCredential {\n accessKeyId: string;\n accessKeySecret: string;\n securityToken: string;\n expiration: number;\n ossEndpoint: string;\n ossBucket: string;\n agentConfigPath: string;\n teamsConfigPath?: string;\n}\n\nfunction objectKey(value: unknown, field: string): string {\n const key = requiredString(value, field);\n if (/[\\\\\\r\\n]/.test(key) || key.split('/').some((p) => !p || p === '.' || p === '..')) {\n throw new CredentialExchangeError(`Controller returned an invalid ${field}`);\n }\n return key;\n}\n\nexport class ControlConfigLoader {\n private readonly controller: ControllerClient;\n private readonly logger: Logger;\n private readonly lifetime = new AbortController();\n #credential?: ControlCredential;\n private pending?: Promise<ControlCredential>;\n constructor(endpoint: string, source: AgentSATokenSource, private readonly options: ControllerOptions = {}) {\n this.controller = new ControllerClient(endpoint, source, options);\n this.logger = options.logger ?? nullLogger;\n }\n\n async load(): Promise<AgentConfig> {\n const credential = await this.credential();\n const data = await this.download(credential, credential.agentConfigPath);\n return parseAgentConfig(data!);\n }\n\n async loadTeams(): Promise<Uint8Array | undefined> {\n let credential = await this.credential();\n if (!credential.teamsConfigPath) credential = await this.credential(true);\n return credential.teamsConfigPath ? this.download(credential, credential.teamsConfigPath, true) : undefined;\n }\n\n close(): void { this.controller.close(); this.lifetime.abort(); this.#credential = undefined; }\n\n private async credential(force = false): Promise<ControlCredential> {\n this.lifetime.signal.throwIfAborted();\n if (!force && this.#credential && this.#credential.expiration > Date.now() + 60_000) return this.#credential;\n if (this.pending) return this.pending;\n const request = this.exchange();\n this.pending = request;\n try { this.#credential = await request; return this.#credential; }\n finally { this.pending = undefined; }\n }\n\n private async exchange(): Promise<ControlCredential> {\n const response = await this.controller.post('/api/v1/credentials/sts', { purpose: 'oss', target: 'control' });\n if (response.status === 401) throw new AuthenticationError('Controller rejected the Agent SA token');\n if (response.status < 200 || response.status >= 300) throw new CredentialExchangeError(`Controller control-config STS failed with HTTP ${response.status}`);\n try {\n const data = object(response.payload, 'control-config STS');\n const read = (field: string) => requiredString(data[field], field);\n const endpoint = read('oss_endpoint');\n const ossEndpoint = httpUrl(endpoint.includes('://') ? endpoint : `https://${endpoint}`, 'OSS endpoint');\n if (new URL(ossEndpoint).pathname !== '/') throw new Error('OSS endpoint path');\n const ossBucket = read('oss_bucket');\n if (!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(ossBucket)) throw new Error('OSS bucket');\n const expiration = Date.parse(read('expiration'));\n if (!(expiration > Date.now())) throw new Error('expired control-config STS');\n return {\n accessKeyId: read('access_key_id'), accessKeySecret: read('access_key_secret'), securityToken: read('security_token'),\n expiration, ossEndpoint, ossBucket,\n agentConfigPath: objectKey(data.agent_config_path, 'agent_config_path'),\n teamsConfigPath: data.teams_config_path == null ? undefined : objectKey(data.teams_config_path, 'teams_config_path'),\n };\n } catch { throw new CredentialExchangeError('Controller returned an invalid control-config STS response'); }\n }\n\n private async download(credential: ControlCredential, key: string, missingOK = false): Promise<Uint8Array | undefined> {\n const original = new URL(credential.ossEndpoint);\n const candidates = [original];\n if (/^(?:[a-z0-9-]+\\.)?oss-.+-internal\\.aliyuncs\\.com$/.test(original.hostname)) {\n const fallback = new URL(original); fallback.hostname = fallback.hostname.replace('-internal.aliyuncs.com', '.aliyuncs.com');\n candidates.push(fallback);\n }\n let lastStatus: number | undefined;\n for (const endpoint of candidates) {\n this.lifetime.signal.throwIfAborted();\n const url = new URL(endpoint);\n const pathStyle = url.hostname === 'localhost' || isIP(url.hostname.replace(/^\\[|\\]$/g, '')) !== 0;\n if (!pathStyle && !url.hostname.startsWith(`${credential.ossBucket}.`)) url.hostname = `${credential.ossBucket}.${url.hostname}`;\n const encodedKey = key.split('/').map((part) => encodeURIComponent(part).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)).join('/');\n url.pathname = `${pathStyle ? `/${credential.ossBucket}` : ''}/${encodedKey}`;\n const date = new Date().toUTCString();\n const canonical = `GET\\n\\n\\n${date}\\nx-oss-security-token:${credential.securityToken}\\n/${credential.ossBucket}/${key}`;\n const signature = createHmac('sha1', credential.accessKeySecret).update(canonical).digest('base64');\n this.logger.debug('agentcore.control_config.download.started', { host: url.host, path: url.pathname });\n try {\n const response = await fetch(url, {\n headers: { Date: date, Authorization: `OSS ${credential.accessKeyId}:${signature}`, 'x-oss-security-token': credential.securityToken },\n redirect: 'manual', signal: AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(this.options.timeoutMs ?? 10_000)]),\n });\n if (response.ok) {\n const data = await readBytes(response, 1024 * 1024, 'runtime config');\n this.logger.info('agentcore.control_config.download.succeeded', { host: url.host, bytes: data.length });\n return data;\n }\n lastStatus = response.status;\n await response.body?.cancel();\n if (missingOK && response.status === 404) return undefined;\n this.logger.warn('agentcore.control_config.download.failed', { host: url.host, status: response.status });\n } catch (error) {\n this.lifetime.signal.throwIfAborted();\n if (error instanceof ConfigError) throw error;\n this.logger.warn('agentcore.control_config.download.failed', { host: url.host, reason: 'transport_error' });\n }\n }\n throw new ConfigError(lastStatus ? `AgentCore configuration download failed with HTTP ${lastStatus}` : 'cannot reach the AgentCore configuration store');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAIlB,IAAM,mBAAmB;AAQhC,SAAS,MAAM,MAAwB;AACrC,QAAM,QAAkB,CAAC;AACzB,MAAI,OAAO;AACX,MAAI,QAAQ;AACZ,MAAI,UAAU;AACd,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,OAAO,KAAK,CAAC;AACnB,QAAI,UAAU,KAAK;AACjB,UAAI,SAAS,MAAO,SAAQ;AAAA,UAAS,SAAQ;AAAA,IAC/C,WAAW,SAAS,MAAM;AACxB,YAAM,OAAO,KAAK,EAAE,CAAC;AACrB,UAAI,SAAS,OAAW,OAAM,IAAI,MAAM,mBAAmB;AAC3D,UAAI,UAAU,OAAO,SAAS,OAAO,SAAS,KAAM,SAAQ;AAC5D,cAAQ;AACR,gBAAU;AAAA,IACZ,WAAW,OAAO;AAChB,UAAI,SAAS,MAAO,SAAQ;AAAA,UAAS,SAAQ;AAAA,IAC/C,WAAW,SAAS,OAAO,SAAS,KAAK;AACvC,cAAQ;AACR,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AAAE,cAAM,IAAI,oBAAoB,qDAAqD;AAAA,MAAG;AAAA,IAClG;AACA,UAAM,IAAI,8BAA8B,+CAA+C;AAAA,EACzF;AACF;AAEO,SAAS,oBAAoB,UAAiC,CAAC,GAAkB;AACtF,QAAM,MAAM,QAAQ,IAAI,uBAAuB,KAAK;AACpD,MAAI,IAAK,QAAO,IAAI,mBAAmB,gBAAgB,GAAG,GAAG;AAAA,IAC3D,sBAAsB,QAAQ,wBAAwB,QAAQ,IAAI;AAAA,IAClE,QAAQ,QAAQ;AAAA,EAClB,CAAC;AACD,SAAO,IAAI,qBAAqB,OAAO;AACzC;","names":["readFile","readFile","sleep","sleep"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkV4A6MJ42cjs = require('./chunk-V4A6MJ42.cjs');
|
|
4
4
|
|
|
5
5
|
// src/integrations/ai-sdk.ts
|
|
6
6
|
var _openaicompatible = require('@ai-sdk/openai-compatible');
|
|
@@ -9,14 +9,14 @@ var _anthropic = require('@ai-sdk/anthropic');
|
|
|
9
9
|
var _ai = require('ai');
|
|
10
10
|
function languageModel(client, options = {}) {
|
|
11
11
|
if ("languageModel" in client) {
|
|
12
|
-
if (options.api) throw new (0,
|
|
12
|
+
if (options.api) throw new (0, _chunkV4A6MJ42cjs.ConfigError)("select the API when constructing the direct provider model");
|
|
13
13
|
return client.languageModel;
|
|
14
14
|
}
|
|
15
15
|
const { provider, baseURL, model, maxTokens } = client.settings;
|
|
16
16
|
const fetch = client.httpFetch.bind(client);
|
|
17
17
|
let result;
|
|
18
18
|
if (provider === "anthropic") {
|
|
19
|
-
if (options.api === "responses") throw new (0,
|
|
19
|
+
if (options.api === "responses") throw new (0, _chunkV4A6MJ42cjs.ConfigError)("Anthropic protocol does not publish Responses API");
|
|
20
20
|
result = _anthropic.createAnthropic.call(void 0, { baseURL: `${baseURL.replace(/\/+$/, "")}/v1`, apiKey: "agentcore-transport", fetch })(model);
|
|
21
21
|
} else if (options.api === "responses") {
|
|
22
22
|
result = _openai.createOpenAI.call(void 0, { baseURL, apiKey: "agentcore-transport", fetch }).responses(model);
|
|
@@ -31,7 +31,7 @@ function languageModel(client, options = {}) {
|
|
|
31
31
|
function tools(items) {
|
|
32
32
|
const result = /* @__PURE__ */ Object.create(null);
|
|
33
33
|
for (const item of items) {
|
|
34
|
-
if (Object.hasOwn(result, item.name)) throw new (0,
|
|
34
|
+
if (Object.hasOwn(result, item.name)) throw new (0, _chunkV4A6MJ42cjs.ConfigError)(`duplicate tool name: ${item.name}`);
|
|
35
35
|
result[item.name] = _ai.tool.call(void 0, {
|
|
36
36
|
description: item.description,
|
|
37
37
|
inputSchema: _ai.jsonSchema.call(void 0, item.parameters),
|
|
@@ -45,4 +45,4 @@ function tools(items) {
|
|
|
45
45
|
|
|
46
46
|
|
|
47
47
|
exports.languageModel = languageModel; exports.tools = tools;
|
|
48
|
-
//# sourceMappingURL=chunk-
|
|
48
|
+
//# sourceMappingURL=chunk-LQM754U3.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-LQM754U3.cjs","../src/integrations/ai-sdk.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACJA,6DAAuC;AACvC,wCAA6B;AAC7B,8CAAgC;AAEhC,wBAA6F;AAOtF,SAAS,aAAA,CAAc,MAAA,EAA2C,QAAA,EAA0C,CAAC,CAAA,EAAoB;AACtI,EAAA,GAAA,CAAI,gBAAA,GAAmB,MAAA,EAAQ;AAC7B,IAAA,GAAA,CAAI,OAAA,CAAQ,GAAA,EAAK,MAAM,IAAI,kCAAA,CAAY,4DAA4D,CAAA;AACnG,IAAA,OAAO,MAAA,CAAO,aAAA;AAAA,EAChB;AACA,EAAA,MAAM,EAAE,QAAA,EAAU,OAAA,EAAS,KAAA,EAAO,UAAU,EAAA,EAAI,MAAA,CAAO,QAAA;AACvD,EAAA,MAAM,MAAA,EAAQ,MAAA,CAAO,SAAA,CAAU,IAAA,CAAK,MAAM,CAAA;AAC1C,EAAA,IAAI,MAAA;AACJ,EAAA,GAAA,CAAI,SAAA,IAAa,WAAA,EAAa;AAC5B,IAAA,GAAA,CAAI,OAAA,CAAQ,IAAA,IAAQ,WAAA,EAAa,MAAM,IAAI,kCAAA,CAAY,mDAAmD,CAAA;AAC1G,IAAA,OAAA,EAAS,wCAAA,EAAkB,OAAA,EAAS,CAAA,EAAA;AACX,EAAA;AACQ,IAAA;AAC5B,EAAA;AAE6B,IAAA;AACpC,EAAA;AAE0C,EAAA;AACjC,IAAA;AAAoB,IAAA;AAC5B,EAAA;AACH;AAGuD;AACtB,EAAA;AACL,EAAA;AACc,IAAA;AACb,IAAA;AACL,MAAA;AAC0B,MAAA;AACd,MAAA;AAC/B,IAAA;AACH,EAAA;AACO,EAAA;AACT;ADJyC;AACA;AACA;AACA;AACA","file":"/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-LQM754U3.cjs","sourcesContent":[null,"import { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createAnthropic } from '@ai-sdk/anthropic';\nimport type { LanguageModelV3 } from '@ai-sdk/provider';\nimport { defaultSettingsMiddleware, jsonSchema, tool, wrapLanguageModel, type ToolSet } from 'ai';\nimport { ConfigError } from '../errors';\nimport type { ModelClient } from '../model/client';\nimport type { ProviderModelClient } from '../model/provider';\nimport type { Tool, ToolArguments } from './common';\n\n/** The caller owns the ModelClient (or its Core); this adapter does not close it. */\nexport function languageModel(client: ModelClient | ProviderModelClient, options: { api?: 'chat' | 'responses' } = {}): LanguageModelV3 {\n if ('languageModel' in client) {\n if (options.api) throw new ConfigError('select the API when constructing the direct provider model');\n return client.languageModel;\n }\n const { provider, baseURL, model, maxTokens } = client.settings;\n const fetch = client.httpFetch.bind(client);\n let result: LanguageModelV3;\n if (provider === 'anthropic') {\n if (options.api === 'responses') throw new ConfigError('Anthropic protocol does not publish Responses API');\n result = createAnthropic({ baseURL: `${baseURL.replace(/\\/+$/, '')}/v1`, apiKey: 'agentcore-transport', fetch })(model);\n } else if (options.api === 'responses') {\n result = createOpenAI({ baseURL, apiKey: 'agentcore-transport', fetch }).responses(model);\n } else {\n // Forward explicitly requested schemas; the backend decides model support.\n result = createOpenAICompatible({ name: 'agentcore', baseURL, fetch, supportsStructuredOutputs: true }).chatModel(model);\n }\n // A descriptor supplies defaults, not a limit on explicit per-call settings.\n return maxTokens === undefined ? result : wrapLanguageModel({\n model: result, middleware: defaultSettingsMiddleware({ settings: { maxOutputTokens: maxTokens } }),\n });\n}\n\n/** MCP and Skill tools share the same canonical Tool representation. */\nexport function tools(items: readonly Tool[]): ToolSet {\n const result: ToolSet = Object.create(null) as ToolSet;\n for (const item of items) {\n if (Object.hasOwn(result, item.name)) throw new ConfigError(`duplicate tool name: ${item.name}`);\n result[item.name] = tool({\n description: item.description,\n inputSchema: jsonSchema<ToolArguments>(item.parameters),\n execute: (arguments_) => item.invoke(arguments_),\n });\n }\n return result;\n}\nexport { AISDKEventConverter as AgentCoreConverter } from './event-converters';\n"]}
|
|
@@ -3,13 +3,13 @@ import {
|
|
|
3
3
|
recordMemory,
|
|
4
4
|
referenceText,
|
|
5
5
|
validateTopK
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-45S6S5WI.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-JFWLKOGL.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-NI3U6RZL.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ConfigError
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-AEQ76QIO.js";
|
|
4
4
|
|
|
5
5
|
// src/http.ts
|
|
6
6
|
async function readBytes(response, maxBytes, label) {
|
|
@@ -26,4 +26,4 @@ async function readBytes(response, maxBytes, label) {
|
|
|
26
26
|
export {
|
|
27
27
|
readBytes
|
|
28
28
|
};
|
|
29
|
-
//# sourceMappingURL=chunk-
|
|
29
|
+
//# sourceMappingURL=chunk-NRYDUATX.js.map
|
|
@@ -2,18 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
|
|
5
|
-
var
|
|
5
|
+
var _chunkV4A6MJ42cjs = require('./chunk-V4A6MJ42.cjs');
|
|
6
6
|
|
|
7
7
|
// src/collaboration/errors.ts
|
|
8
|
-
var CollaborationError = (_class = class extends
|
|
8
|
+
var CollaborationError = (_class = class extends _chunkV4A6MJ42cjs.AgentCoreError {constructor(...args) { super(...args); _class.prototype.__init.call(this);_class.prototype.__init2.call(this); }
|
|
9
9
|
__init() {this.code = "COLLABORATION_ERROR"}
|
|
10
10
|
__init2() {this.retryable = false}
|
|
11
11
|
}, _class);
|
|
12
|
-
var CollaborationConfigError = (_class2 = class extends
|
|
12
|
+
var CollaborationConfigError = (_class2 = class extends _chunkV4A6MJ42cjs.ConfigError {constructor(...args2) { super(...args2); _class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this); }
|
|
13
13
|
__init3() {this.code = "COLLABORATION_CONFIG_INVALID"}
|
|
14
14
|
__init4() {this.retryable = true}
|
|
15
15
|
}, _class2);
|
|
16
|
-
var CollaborationContextError = (_class3 = class extends
|
|
16
|
+
var CollaborationContextError = (_class3 = class extends _chunkV4A6MJ42cjs.ContextError {constructor(...args3) { super(...args3); _class3.prototype.__init5.call(this);_class3.prototype.__init6.call(this); }
|
|
17
17
|
__init5() {this.code = "COLLABORATION_CONTEXT_INVALID"}
|
|
18
18
|
__init6() {this.retryable = false}
|
|
19
19
|
}, _class3);
|
|
@@ -138,4 +138,4 @@ function parseCollaborationContext(headers) {
|
|
|
138
138
|
|
|
139
139
|
|
|
140
140
|
exports.CollaborationError = CollaborationError; exports.CollaborationConfigError = CollaborationConfigError; exports.CollaborationContextError = CollaborationContextError; exports.CollaborationDisabledError = CollaborationDisabledError; exports.CollaborationContextRequiredError = CollaborationContextRequiredError; exports.CollaborationTeamUnavailableError = CollaborationTeamUnavailableError; exports.CollaborationRoleUnsupportedError = CollaborationRoleUnsupportedError; exports.CollaborationToolArgumentError = CollaborationToolArgumentError; exports.CollaborationTaskUnauthorizedError = CollaborationTaskUnauthorizedError; exports.CollaborationTaskInvalidError = CollaborationTaskInvalidError; exports.CollaborationTaskNotFoundError = CollaborationTaskNotFoundError; exports.CollaborationTaskConflictError = CollaborationTaskConflictError; exports.CollaborationFileTooLargeError = CollaborationFileTooLargeError; exports.CollaborationTaskUnavailableError = CollaborationTaskUnavailableError; exports.CollaborationTurnContext = CollaborationTurnContext; exports.currentCollaborationContext = currentCollaborationContext; exports.useCollaborationContext = useCollaborationContext; exports.bindCollaborationContext = bindCollaborationContext; exports.parseCollaborationContext = parseCollaborationContext;
|
|
141
|
-
//# sourceMappingURL=chunk-
|
|
141
|
+
//# sourceMappingURL=chunk-NWWTBPYG.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-NWWTBPYG.cjs","../src/collaboration/errors.ts","../src/collaboration/context.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACJO,IAAM,mBAAA,YAAN,MAAA,QAAiC,iCAAe;AAAA,iBACnC,KAAA,EAAe,sBAAA;AAAA,kBACxB,UAAA,EAAqB,MAAA;AAChC,UAAA;AACO,IAAM,yBAAA,aAAN,MAAA,QAAuC,8BAAY;AAAA,kBACtC,KAAA,EAAO,+BAAA;AAAA,kBAChB,UAAA,EAAY,KAAA;AACvB,WAAA;AACO,IAAM,0BAAA,aAAN,MAAA,QAAwC,+BAAa;AAAA,kBACxC,KAAA,EAAO,gCAAA;AAAA,kBAChB,UAAA,EAAY,MAAA;AACvB,WAAA;AACO,IAAM,2BAAA,aAAN,MAAA,QAAyC,mBAAmB;AAAA,kBAAoB,KAAA,EAAO,yBAAA;AAA0B,WAAA;AACjH,IAAM,kCAAA,aAAN,MAAA,QAAgD,mBAAmB;AAAA,kBAAoB,KAAA,EAAO,iCAAA;AAAkC,WAAA;AAChI,IAAM,kCAAA,aAAN,MAAA,QAAgD,mBAAmB;AAAA,kBAAoB,KAAA,EAAO,iCAAA;AAAkC,WAAA;AAChI,IAAM,kCAAA,aAAN,MAAA,QAAgD,mBAAmB;AAAA,mBAAoB,KAAA,EAAO,iCAAA;AAAkC,WAAA;AAChI,IAAM,+BAAA,aAAN,MAAA,QAA6C,mBAAmB;AA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M,IAAI,yBAAA,CAA0B,2CAA2C,CAAA;AACzI,EAAA,OAAO,IAAI,wBAAA;AAAA,oBAAyB,UAAA,mBAAW,wBAAwB,CAAA,6BAAG,IAAA,mBAAK,IAAA,GAAK,KAAA,CAAA;AAAA,IAClF,KAAA,CAAM,QAAA,EAAU,KAAA,IAAS,MAAM,CAAA;AAAA,IAAG,KAAA,CAAM,QAAQ,CAAA;AAAA,IAAI,KAAA,CAAM,SAAS,CAAA;AAAA,IAAI;AAAA,EAAI,CAAA;AAC/E;AF4EA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,4xCAAC","file":"/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-NWWTBPYG.cjs","sourcesContent":[null,"import { AgentCoreError, ConfigError, ContextError } from '../errors';\n\nexport class CollaborationError extends AgentCoreError {\n override readonly code: string = 'COLLABORATION_ERROR';\n readonly retryable: boolean = false;\n}\nexport class CollaborationConfigError extends ConfigError {\n override readonly code = 'COLLABORATION_CONFIG_INVALID';\n readonly retryable = true;\n}\nexport class CollaborationContextError extends ContextError {\n override readonly code = 'COLLABORATION_CONTEXT_INVALID';\n readonly retryable = false;\n}\nexport class CollaborationDisabledError extends CollaborationError { override readonly code = 'COLLABORATION_DISABLED'; }\nexport class CollaborationContextRequiredError extends CollaborationError { override readonly code = 'COLLABORATION_CONTEXT_REQUIRED'; }\nexport class CollaborationTeamUnavailableError extends CollaborationError { override readonly code = 'COLLABORATION_TEAM_UNAVAILABLE'; }\nexport class CollaborationRoleUnsupportedError extends CollaborationError { override readonly code = 'COLLABORATION_ROLE_UNSUPPORTED'; }\nexport class CollaborationToolArgumentError extends CollaborationError { override readonly code = 'COLLABORATION_ARGUMENT_INVALID'; }\nexport class CollaborationTaskUnauthorizedError extends CollaborationError { override readonly code = 'COLLABORATION_TASK_UNAUTHORIZED'; }\nexport class CollaborationTaskInvalidError extends CollaborationError { override readonly code = 'COLLABORATION_TASK_INVALID'; }\nexport class CollaborationTaskNotFoundError extends CollaborationError { override readonly code = 'COLLABORATION_TASK_NOT_FOUND'; }\nexport class CollaborationTaskConflictError extends CollaborationError { override readonly code = 'COLLABORATION_TASK_CONFLICT'; }\nexport class CollaborationFileTooLargeError extends CollaborationError { override readonly code = 'COLLABORATION_FILE_TOO_LARGE'; }\nexport class CollaborationTaskUnavailableError extends CollaborationError {\n override readonly code = 'COLLABORATION_TASK_UNAVAILABLE';\n override readonly retryable = true;\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { inspect } from 'node:util';\nimport { CollaborationContextError, CollaborationContextRequiredError } from './errors';\n\nexport class CollaborationTurnContext {\n constructor(readonly sessionId: string | undefined, readonly teamId: string | undefined,\n readonly roomId: string, readonly eventId: string, readonly roomKind: 'dm' | 'group' | 'task') { Object.freeze(this); }\n [inspect.custom](): string { return 'CollaborationTurnContext(<redacted>)'; }\n toJSON(): string { return this[inspect.custom](); }\n}\nconst context = new AsyncLocalStorage<CollaborationTurnContext | undefined>();\nexport function currentCollaborationContext(required?: true): CollaborationTurnContext;\nexport function currentCollaborationContext(required: false): CollaborationTurnContext | undefined;\nexport function currentCollaborationContext(required = true): CollaborationTurnContext | undefined {\n const value = context.getStore();\n if (!value && required) throw new CollaborationContextRequiredError('No collaboration request context is active.');\n return value;\n}\nexport function useCollaborationContext<T>(value: CollaborationTurnContext | undefined, callback: () => T): T { return context.run(value, callback); }\nexport function bindCollaborationContext<T>(headers: Readonly<Record<string, string>>, callback: () => T): T {\n return useCollaborationContext(parseCollaborationContext(headers), callback);\n}\nexport function parseCollaborationContext(headers: Readonly<Record<string, string>>): CollaborationTurnContext | undefined {\n const normalized = Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));\n const encoded = normalized['x-agentcore-collaboration-context'];\n if (encoded === undefined) return;\n let data: Record<string, unknown>;\n try {\n if (!encoded || encoded.length > 8192 || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(encoded) || encoded.replace(/=+$/, '').length % 4 === 1) throw new Error('base64');\n data = JSON.parse(new TextDecoder('utf8', { fatal: true }).decode(Buffer.from(encoded, 'base64url')));\n if (!data || Array.isArray(data) || data.version !== 1) throw new Error('schema');\n } catch { throw new CollaborationContextError('collaboration context header is invalid'); }\n const field = (name: string, required = true): string | undefined => {\n const value = data[name];\n if (value == null && !required) return;\n if (typeof value !== 'string' || !value.trim() || value.length > 1024) throw new CollaborationContextError(`collaboration context ${name} is invalid`);\n return value.trim();\n };\n const kind = field('roomKind');\n if (kind !== 'dm' && kind !== 'group' && kind !== 'task') throw new CollaborationContextError('collaboration context roomKind is invalid');\n return new CollaborationTurnContext(normalized['x-agentcore-session-id']?.trim() || undefined,\n field('teamId', kind === 'task'), field('roomId')!, field('eventId')!, kind);\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkV4A6MJ42cjs = require('./chunk-V4A6MJ42.cjs');
|
|
4
4
|
|
|
5
5
|
// src/runtime/config.ts
|
|
6
6
|
var _promises = require('fs/promises');
|
|
@@ -8,13 +8,13 @@ var _yaml = require('yaml');
|
|
|
8
8
|
var DEFAULT_CONFIG_PATH = "/var/run/agentcore/agent/agent.yaml";
|
|
9
9
|
function object(value, label) {
|
|
10
10
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
11
|
-
throw new (0,
|
|
11
|
+
throw new (0, _chunkV4A6MJ42cjs.ConfigError)(`${label} must be an object`);
|
|
12
12
|
}
|
|
13
13
|
return value;
|
|
14
14
|
}
|
|
15
15
|
function requiredString(value, label) {
|
|
16
16
|
if (typeof value !== "string" || !value.trim()) {
|
|
17
|
-
throw new (0,
|
|
17
|
+
throw new (0, _chunkV4A6MJ42cjs.ConfigError)(`${label} must be a non-empty string`);
|
|
18
18
|
}
|
|
19
19
|
return value.trim();
|
|
20
20
|
}
|
|
@@ -24,10 +24,10 @@ function httpUrl(value, label) {
|
|
|
24
24
|
try {
|
|
25
25
|
url = new URL(text);
|
|
26
26
|
} catch (e) {
|
|
27
|
-
throw new (0,
|
|
27
|
+
throw new (0, _chunkV4A6MJ42cjs.ConfigError)(`${label} must be an absolute HTTP(S) URL`);
|
|
28
28
|
}
|
|
29
29
|
if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.search || url.hash) {
|
|
30
|
-
throw new (0,
|
|
30
|
+
throw new (0, _chunkV4A6MJ42cjs.ConfigError)(`${label} must be HTTP(S) without user info, query, or fragment`);
|
|
31
31
|
}
|
|
32
32
|
return text.replace(/\/+$/, "");
|
|
33
33
|
}
|
|
@@ -50,13 +50,13 @@ function rejectInlineCredentials(value, label) {
|
|
|
50
50
|
value.forEach((item, i) => rejectInlineCredentials(item, `${label}[${i}]`));
|
|
51
51
|
} else if (value && typeof value === "object") {
|
|
52
52
|
for (const [key, item] of Object.entries(value)) {
|
|
53
|
-
if (sensitive.has(key.toLowerCase())) throw new (0,
|
|
53
|
+
if (sensitive.has(key.toLowerCase())) throw new (0, _chunkV4A6MJ42cjs.ConfigError)(`${label}.${key} must not contain inline credentials`);
|
|
54
54
|
rejectInlineCredentials(item, `${label}.${key}`);
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
58
|
function parseAgentConfig(data) {
|
|
59
|
-
if (Buffer.byteLength(data) > 1024 * 1024) throw new (0,
|
|
59
|
+
if (Buffer.byteLength(data) > 1024 * 1024) throw new (0, _chunkV4A6MJ42cjs.ConfigError)("agent.yaml exceeds the 1 MiB size limit");
|
|
60
60
|
let value;
|
|
61
61
|
try {
|
|
62
62
|
const text = typeof data === "string" ? data : new TextDecoder("utf-8", { fatal: true }).decode(data);
|
|
@@ -77,14 +77,14 @@ function parseAgentConfig(data) {
|
|
|
77
77
|
});
|
|
78
78
|
value = doc.toJS();
|
|
79
79
|
} catch (e2) {
|
|
80
|
-
throw new (0,
|
|
80
|
+
throw new (0, _chunkV4A6MJ42cjs.ConfigError)("invalid agent.yaml (UTF-8 YAML, unique string keys, no anchors or aliases required)");
|
|
81
81
|
}
|
|
82
82
|
return parseAgentConfigMapping(value);
|
|
83
83
|
}
|
|
84
84
|
function parseAgentConfigMapping(value) {
|
|
85
85
|
const root = object(value, "agent.yaml");
|
|
86
86
|
if (root.apiVersion !== "agentteams.io/v1alpha1" || root.kind !== "AgentConfig") {
|
|
87
|
-
throw new (0,
|
|
87
|
+
throw new (0, _chunkV4A6MJ42cjs.ConfigError)("unsupported agent.yaml apiVersion or kind");
|
|
88
88
|
}
|
|
89
89
|
const metadata = object(root.metadata, "metadata");
|
|
90
90
|
const spec = object(root.spec, "spec");
|
|
@@ -93,17 +93,17 @@ function parseAgentConfigMapping(value) {
|
|
|
93
93
|
rejectInlineCredentials(model, "spec.model");
|
|
94
94
|
rejectInlineCredentials(mcp, "spec.mcp");
|
|
95
95
|
const rawHeaders = object(spec.credentials, "spec.credentials").header;
|
|
96
|
-
if (!Array.isArray(rawHeaders) || !rawHeaders.length) throw new (0,
|
|
96
|
+
if (!Array.isArray(rawHeaders) || !rawHeaders.length) throw new (0, _chunkV4A6MJ42cjs.ConfigError)("spec.credentials.header must be a non-empty list");
|
|
97
97
|
const headers = {};
|
|
98
98
|
for (const raw of rawHeaders) {
|
|
99
99
|
const header = object(raw, "gateway header");
|
|
100
100
|
const key = requiredString(header.key, "header.key").toLowerCase();
|
|
101
101
|
const val = requiredString(header.value, "header.value");
|
|
102
|
-
if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(key) || /[\r\n]/.test(val)) throw new (0,
|
|
103
|
-
if (Object.hasOwn(headers, key)) throw new (0,
|
|
102
|
+
if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(key) || /[\r\n]/.test(val)) throw new (0, _chunkV4A6MJ42cjs.ConfigError)("invalid gateway header");
|
|
103
|
+
if (Object.hasOwn(headers, key)) throw new (0, _chunkV4A6MJ42cjs.ConfigError)(`duplicate gateway header: ${key}`);
|
|
104
104
|
Object.defineProperty(headers, key, { value: val, enumerable: true });
|
|
105
105
|
}
|
|
106
|
-
if (!/^bearer\s+\S/i.test(_nullishCoalesce(headers.authorization, () => ( "")))) throw new (0,
|
|
106
|
+
if (!/^bearer\s+\S/i.test(_nullishCoalesce(headers.authorization, () => ( "")))) throw new (0, _chunkV4A6MJ42cjs.ConfigError)("spec.credentials.header requires a Bearer Authorization header");
|
|
107
107
|
const runtimeName = requiredString(metadata.runtimeName, "metadata.runtimeName");
|
|
108
108
|
return Object.freeze({
|
|
109
109
|
apiVersion: root.apiVersion,
|
|
@@ -122,7 +122,7 @@ async function loadAgentConfig(path = process.env.AGENTCORE_CONFIG_PATH || DEFAU
|
|
|
122
122
|
try {
|
|
123
123
|
data = await _promises.readFile.call(void 0, path);
|
|
124
124
|
} catch (cause) {
|
|
125
|
-
throw new (0,
|
|
125
|
+
throw new (0, _chunkV4A6MJ42cjs.ConfigError)("cannot read agent.yaml", { cause });
|
|
126
126
|
}
|
|
127
127
|
return parseAgentConfig(data);
|
|
128
128
|
}
|
|
@@ -136,4 +136,4 @@ async function loadAgentConfig(path = process.env.AGENTCORE_CONFIG_PATH || DEFAU
|
|
|
136
136
|
|
|
137
137
|
|
|
138
138
|
exports.DEFAULT_CONFIG_PATH = DEFAULT_CONFIG_PATH; exports.object = object; exports.requiredString = requiredString; exports.httpUrl = httpUrl; exports.parseAgentConfig = parseAgentConfig; exports.parseAgentConfigMapping = parseAgentConfigMapping; exports.loadAgentConfig = loadAgentConfig;
|
|
139
|
-
//# sourceMappingURL=chunk-
|
|
139
|
+
//# sourceMappingURL=chunk-NXMTTQQK.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-NXMTTQQK.cjs","../src/runtime/config.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACJA,uCAAyB;AACzB,4BAAqC;AAG9B,IAAM,oBAAA,EAAsB,qCAAA;AAa5B,SAAS,MAAA,CAAO,KAAA,EAAgB,KAAA,EAAwC;AAC7E,EAAA,GAAA,CAAI,CAAC,MAAA,GAAS,OAAO,MAAA,IAAU,SAAA,GAAY,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AAC/D,IAAA,MAAM,IAAI,kCAAA,CAAY,CAAA,EAAA;AACxB,EAAA;AACO,EAAA;AACT;AAE+B;AACR,EAAA;AACG,IAAA;AACxB,EAAA;AACkB,EAAA;AACpB;AAEwC;AACzB,EAAA;AACT,EAAA;AACA,EAAA;AAAoB,IAAA;AAAW,EAAA;AAAwB,IAAA;AAA6C,EAAA;AAC/E,EAAA;AACD,IAAA;AACxB,EAAA;AACoB,EAAA;AACtB;AAEkB;AAAS,EAAA;AAAU,EAAA;AAAW,EAAA;AAAiB,EAAA;AAAe,EAAA;AAC9E,EAAA;AAAU,EAAA;AAAU,EAAA;AAAW,EAAA;AAAY,EAAA;AAAU,EAAA;AAAiB,EAAA;AAAQ;AACvE;AACgB,EAAA;AACA,IAAA;AACH,EAAA;AACG,IAAA;AACD,MAAA;AAClB,MAAA;AACF,IAAA;AACF,EAAA;AACF;AAEiC;AACT,EAAA;AAClB,EAAA;AACA,EAAA;AACkB,IAAA;AACR,IAAA;AACW,IAAA;AACZ,IAAA;AACD,MAAA;AAAkB,QAAA;AAAe,MAAA;AACxB,MAAA;AAAkB,QAAA;AAAqD,MAAA;AACvE,MAAA;AACE,QAAA;AACC,UAAA;AAClB,QAAA;AACF,MAAA;AACD,IAAA;AACgB,IAAA;AACX,EAAA;AAEgB,IAAA;AACxB,EAAA;AACO,EAAA;AACT;AAEgB;AACM,EAAA;AACI,EAAA;AACA,IAAA;AACxB,EAAA;AACwB,EAAA;AACC,EAAA;AACJ,EAAA;AACG,EAAA;AACA,EAAA;AACA,EAAA;AACL,EAAA;AACA,EAAA;AACsB,EAAA;AACvB,EAAA;AACM,IAAA;AACV,IAAA;AACA,IAAA;AACP,IAAA;AACa,IAAA;AACI,IAAA;AACxB,EAAA;AACqB,EAAA;AACD,EAAA;AACC,EAAA;AACF,IAAA;AAAuB,IAAA;AACjB,IAAA;AACvB,IAAA;AACa,IAAA;AACH,IAAA;AACO,IAAA;AACM,IAAA;AACA,IAAA;AACxB,EAAA;AACH;AAEsB;AAChB,EAAA;AACA,EAAA;AAAwB,IAAA;AAAuB,EAAA;AAC3B,IAAA;AACxB,EAAA;AACwB,EAAA;AAC1B;ADQ2B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-NXMTTQQK.cjs","sourcesContent":[null,"import { readFile } from 'node:fs/promises';\nimport { parseDocument, visit } from 'yaml';\nimport { ConfigError } from '../errors';\n\nexport const DEFAULT_CONFIG_PATH = '/var/run/agentcore/agent/agent.yaml';\nexport interface AgentConfig {\n readonly apiVersion: string;\n readonly kind: string;\n readonly name: string;\n readonly runtimeName: string;\n readonly workspaceId: string;\n readonly regionId: string;\n readonly modelGatewayUrl: string;\n readonly mcpGatewayUrl: string;\n readonly gatewayHeaders: Readonly<Record<string, string>>;\n}\n\nexport function object(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ConfigError(`${label} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nexport function requiredString(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value.trim()) {\n throw new ConfigError(`${label} must be a non-empty string`);\n }\n return value.trim();\n}\n\nexport function httpUrl(value: unknown, label: string): string {\n const text = requiredString(value, label);\n let url: URL;\n try { url = new URL(text); } catch { throw new ConfigError(`${label} must be an absolute HTTP(S) URL`); }\n if (!['http:', 'https:'].includes(url.protocol) || !url.hostname || url.username || url.password || url.search || url.hash) {\n throw new ConfigError(`${label} must be HTTP(S) without user info, query, or fragment`);\n }\n return text.replace(/\\/+$/, '');\n}\n\nconst sensitive = new Set(['apikey', 'api_key', 'authorization', 'accesskeyid', 'accesskeysecret',\n 'cookie', 'header', 'headers', 'password', 'secret', 'securitytoken', 'token']);\nfunction rejectInlineCredentials(value: unknown, label: string): void {\n if (Array.isArray(value)) {\n value.forEach((item, i) => rejectInlineCredentials(item, `${label}[${i}]`));\n } else if (value && typeof value === 'object') {\n for (const [key, item] of Object.entries(value)) {\n if (sensitive.has(key.toLowerCase())) throw new ConfigError(`${label}.${key} must not contain inline credentials`);\n rejectInlineCredentials(item, `${label}.${key}`);\n }\n }\n}\n\nexport function parseAgentConfig(data: string | Uint8Array): AgentConfig {\n if (Buffer.byteLength(data) > 1024 * 1024) throw new ConfigError('agent.yaml exceeds the 1 MiB size limit');\n let value: unknown;\n try {\n const text = typeof data === 'string' ? data : new TextDecoder('utf-8', { fatal: true }).decode(data);\n const doc = parseDocument(text, { uniqueKeys: true });\n if (doc.errors.length) throw new Error('invalid YAML');\n visit(doc, {\n Alias() { throw new Error('YAML alias'); },\n Node(_key, node) { if ('anchor' in node && node.anchor) throw new Error('YAML anchor'); },\n Pair(_key, pair) {\n if (!pair.key || typeof pair.key !== 'object' || !('value' in pair.key) || typeof pair.key.value !== 'string') {\n throw new Error('non-string YAML key');\n }\n },\n });\n value = doc.toJS();\n } catch {\n // YAML errors may contain a source excerpt with Consumer credentials.\n throw new ConfigError('invalid agent.yaml (UTF-8 YAML, unique string keys, no anchors or aliases required)');\n }\n return parseAgentConfigMapping(value);\n}\n\nexport function parseAgentConfigMapping(value: unknown): AgentConfig {\n const root = object(value, 'agent.yaml');\n if (root.apiVersion !== 'agentteams.io/v1alpha1' || root.kind !== 'AgentConfig') {\n throw new ConfigError('unsupported agent.yaml apiVersion or kind');\n }\n const metadata = object(root.metadata, 'metadata');\n const spec = object(root.spec, 'spec');\n const model = object(spec.model, 'spec.model');\n const mcp = object(spec.mcp, 'spec.mcp');\n rejectInlineCredentials(model, 'spec.model');\n rejectInlineCredentials(mcp, 'spec.mcp');\n const rawHeaders = object(spec.credentials, 'spec.credentials').header;\n if (!Array.isArray(rawHeaders) || !rawHeaders.length) throw new ConfigError('spec.credentials.header must be a non-empty list');\n const headers: Record<string, string> = {};\n for (const raw of rawHeaders) {\n const header = object(raw, 'gateway header');\n const key = requiredString(header.key, 'header.key').toLowerCase();\n const val = requiredString(header.value, 'header.value');\n if (!/^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/.test(key) || /[\\r\\n]/.test(val)) throw new ConfigError('invalid gateway header');\n if (Object.hasOwn(headers, key)) throw new ConfigError(`duplicate gateway header: ${key}`);\n Object.defineProperty(headers, key, { value: val, enumerable: true });\n }\n if (!/^bearer\\s+\\S/i.test(headers.authorization ?? '')) throw new ConfigError('spec.credentials.header requires a Bearer Authorization header');\n const runtimeName = requiredString(metadata.runtimeName, 'metadata.runtimeName');\n return Object.freeze({\n apiVersion: root.apiVersion, kind: root.kind,\n name: metadata.name == null ? runtimeName : requiredString(metadata.name, 'metadata.name'),\n runtimeName,\n workspaceId: requiredString(metadata.workspaceId, 'metadata.workspaceId'),\n regionId: requiredString(metadata.regionId, 'metadata.regionId'),\n modelGatewayUrl: httpUrl(model.gatewayUrl, 'spec.model.gatewayUrl'),\n mcpGatewayUrl: httpUrl(mcp.gatewayUrl, 'spec.mcp.gatewayUrl'),\n gatewayHeaders: Object.freeze(headers),\n });\n}\n\nexport async function loadAgentConfig(path = process.env.AGENTCORE_CONFIG_PATH || DEFAULT_CONFIG_PATH): Promise<AgentConfig> {\n let data: Buffer;\n try { data = await readFile(path); } catch (cause) {\n throw new ConfigError('cannot read agent.yaml', { cause });\n }\n return parseAgentConfig(data);\n}\n"]}
|