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-VYOJJECB.cjs","../src/runtime/environment.ts","../src/runtime/managed.ts","../src/runtime/debug.ts","../src/runtime/control-config.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACrBA,uCAAyB;AAIlB,IAAM,iBAAA,EAAmB,8BAAA;AAQhC,SAAS,KAAA,CAAM,IAAA,EAAwB;AACrC,EAAA,MAAM,MAAA,EAAkB,CAAC,CAAA;AACzB,EAAA,IAAI,KAAA,EAAO,EAAA;AACX,EAAA,IAAI,MAAA,EAAQ,EAAA;AACZ,EAAA,IAAI,QAAA,EAAU,KAAA;AACd,EAAA,IAAA,CAAA,IAAS,EAAA,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ACd,IAAA;AAAe,MAAA;AAAW,IAAA;AAA4B,MAAA;AAAW,IAAA;AACvE,EAAA;AAE4E,EAAA;AACrB,IAAA;AACnB,IAAA;AACG,IAAA;AAA8B,MAAA;AAAW,IAAA;AACtD,IAAA;AAC1B,EAAA;AACiD,EAAA;AACe,IAAA;AAC1D,IAAA;AAAsB,MAAA;AACZ,IAAA;AACsB,MAAA;AACa,MAAA;AACgB,MAAA;AACT,MAAA;AACxD,IAAA;AACF,EAAA;AAEoH,EAAA;AAC3E,IAAA;AACuB,IAAA;AACxD,MAAA;AACA,MAAA;AACA,MAAA;AAC0B,QAAA;AAClB,UAAA;AAAsD,UAAA;AACb,UAAA;AAAa,UAAA;AACH,UAAA;AAC5D,QAAA;AACgC,QAAA;AAC7B,QAAA;AAA2B,UAAA;AAAW,QAAA;AAAY,UAAA;AAAW,QAAA;AAC3D,MAAA;AAC8B,QAAA;AACuB,QAAA;AAC1C,QAAA;AAC8C,QAAA;AAAoB,QAAA;AACrF,MAAA;AACoD,MAAA;AACS,QAAA;AAC1C,QAAA;AAC8C,QAAA;AAAoB,QAAA;AACrF,MAAA;AACoD,MAAA;AACJ,MAAA;AAC5C,MAAA;AACiD,QAAA;AACH,QAAA;AAA4D,QAAA;AAChD,QAAA;AACR,QAAA;AACO,QAAA;AACT,QAAA;AAC5C,MAAA;AAAgC,QAAA;AAAwD,MAAA;AAClG,IAAA;AACwC,IAAA;AAC1C,EAAA;AACF;AAEwF;AAClC,EAAA;AACS,EAAA;AACG,IAAA;AAC9C,IAAA;AACjB,EAAA;AACsC,EAAA;AACzC;AH0XqE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-VYOJJECB.cjs","sourcesContent":[null,"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"]}
|
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunkT26WN7TDcjs = require('./chunk-T26WN7TD.cjs');
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
var
|
|
9
|
+
var _chunk2TRT7RSVcjs = require('./chunk-2TRT7RSV.cjs');
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
var
|
|
12
|
+
var _chunkV4A6MJ42cjs = require('./chunk-V4A6MJ42.cjs');
|
|
13
13
|
|
|
14
14
|
// src/integrations/langgraph.ts
|
|
15
15
|
var _messages = require('@langchain/core/messages');
|
|
@@ -18,7 +18,7 @@ var _messages = require('@langchain/core/messages');
|
|
|
18
18
|
var _tools = require('@langchain/core/tools');
|
|
19
19
|
async function model(client, options = {}) {
|
|
20
20
|
if ("languageModel" in client) {
|
|
21
|
-
const { ProviderChatModel } = await Promise.resolve().then(() => _interopRequireWildcard(require("./langchain-provider-
|
|
21
|
+
const { ProviderChatModel } = await Promise.resolve().then(() => _interopRequireWildcard(require("./langchain-provider-UKO27CQA.cjs")));
|
|
22
22
|
return new ProviderChatModel(client, options);
|
|
23
23
|
}
|
|
24
24
|
const { provider, model: model2, baseURL, maxTokens } = client.settings;
|
|
@@ -57,7 +57,7 @@ function tools(values) {
|
|
|
57
57
|
}));
|
|
58
58
|
}
|
|
59
59
|
function skillTools2(values, options = {}) {
|
|
60
|
-
return tools(
|
|
60
|
+
return tools(_chunk2TRT7RSVcjs.skillTools.call(void 0, values, options));
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
// src/integrations/langgraph.ts
|
|
@@ -66,24 +66,24 @@ var AgentCoreMemoryNodes = class {
|
|
|
66
66
|
this.store = store;
|
|
67
67
|
this.options = options;
|
|
68
68
|
this.topK = _nullishCoalesce(options.topK, () => ( 5));
|
|
69
|
-
|
|
69
|
+
_chunkT26WN7TDcjs.validateTopK.call(void 0, this.topK);
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
|
|
73
73
|
|
|
74
74
|
async recall(state) {
|
|
75
|
-
if (state.memoryQuery === void 0) throw new (0,
|
|
76
|
-
return { memoryText: await
|
|
75
|
+
if (state.memoryQuery === void 0) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("memoryQuery is required");
|
|
76
|
+
return { memoryText: await _chunkT26WN7TDcjs.recallMemory.call(void 0, this.store, state.memoryQuery, state.memoryReadScope, { topK: this.topK, logger: this.options.logger }) };
|
|
77
77
|
}
|
|
78
78
|
async record(state) {
|
|
79
|
-
if (!Array.isArray(state.memoryMessages)) throw new (0,
|
|
80
|
-
await
|
|
79
|
+
if (!Array.isArray(state.memoryMessages)) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("memoryMessages must be an array");
|
|
80
|
+
await _chunkT26WN7TDcjs.recordMemory.call(void 0, this.store, state.memoryMessages, state.memoryWriteScope, { logger: this.options.logger });
|
|
81
81
|
return { memoryMessages: [] };
|
|
82
82
|
}
|
|
83
83
|
};
|
|
84
84
|
function withMemory(messages, memoryText) {
|
|
85
85
|
const result = [...messages];
|
|
86
|
-
const note =
|
|
86
|
+
const note = _chunkT26WN7TDcjs.referenceText.call(void 0, memoryText);
|
|
87
87
|
if (!note) return result;
|
|
88
88
|
const first = result[0];
|
|
89
89
|
if (_messages.SystemMessage.isInstance(first)) {
|
|
@@ -107,4 +107,4 @@ ${note}` : [...first.content, { type: "text", text: note }]
|
|
|
107
107
|
|
|
108
108
|
|
|
109
109
|
exports.model = model; exports.tools = tools; exports.skillTools = skillTools2; exports.AgentCoreMemoryNodes = AgentCoreMemoryNodes; exports.withMemory = withMemory;
|
|
110
|
-
//# sourceMappingURL=chunk-
|
|
110
|
+
//# sourceMappingURL=chunk-WRRIPTJP.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-WRRIPTJP.cjs","../src/integrations/langgraph.ts","../src/integrations/langchain-adapter.ts"],"names":["model","skillTools"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACbA,oDAAgD;ADehD;AACA;AEdA,8CAAmD;AAenD,MAAA,SAAsB,KAAA,CAAM,MAAA,EAA2C,QAAA,EAA4D,CAAC,CAAA,EAAG;AACrI,EAAA,GAAA,CAAI,gBAAA,GAAmB,MAAA,EAAQ;AAC7B,IAAA,MAAM,EAAE,kBAAkB,EAAA,EAAI,MAAM,4DAAA,CAAO,mCAAsB,GAAA;AACjE,IAAA,OAAO,IAAI,iBAAA,CAAkB,MAAA,EAAQ,OAAmC,CAAA;AAAA,EAC1E;AACA,EAAA,MAAM,EAAE,QAAA,EAAU,KAAA,EAAAA,MAAAA,EAAO,OAAA,EAAS,UAAU,EAAA,EAAI,MAAA,CAAO,QAAA;AACvD,EAAA,MAAM,MAAA,EAAQ,MAAA,CAAO,SAAA,CAAU,IAAA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IAAA,OAAO,EAAE,cAAA,EAAgB,CAAC,EAAE,CAAA;AAAA,EAC9B;AACF,CAAA;AAGO,SAAS,UAAA,CAAW,QAAA,EAAkC,UAAA,EAAmC;AAC9F,EAAA,MAAM,OAAA,EAAS,CAAC,GAAG,QAAQ,CAAA;AAAG,EAAA,MAAM,KAAA,EAAO,6CAAA,UAAwB,CAAA;AACnE,EAAA,GAAA,CAAI,CAAC,IAAA,EAAM,OAAO,MAAA;AAClB,EAAA,MAAM,MAAA,EAAQ,MAAA,CAAO,CAAC,CAAA;AACtB,EAAA,GAAA,CAAI,uBAAA,CAAc,UAAA,CAAW,KAAK,CAAA,EAAG;AACnC,IAAA,MAAA,CAAO,CAAC,EAAA,EAAI,IAAI,4BAAA,CAAc;AAAA,MAAE,EAAA,EAAI,KAAA,CAAM,EAAA;AAAA,MAAI,IAAA,EAAM,KAAA,CAAM,IAAA;AAAA,MAAM,iBAAA,EAAmB,KAAA,CAAM,iBAAA;AAAA,MAAmB,iBAAA,EAAmB,KAAA,CAAM,iBAAA;AAAA,MACnI,OAAA,EAAS,OAAO,KAAA,CAAM,QAAA,IAAY,SAAA,EAAW,CAAA,EAAA;AAAgB;AAAyD;AAAS,IAAA;AACtF,EAAA;AACtC,EAAA;AACT;AD0DoD;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-WRRIPTJP.cjs","sourcesContent":[null,"import { SystemMessage, type BaseMessage } from '@langchain/core/messages';\nimport { MemoryValidationError } from '../errors';\nimport type { MemoryStore, MemoryScope, MemoryMessage } from '../memory';\nimport type { Logger } from '../logging';\nimport { recallMemory, recordMemory, referenceText, validateTopK } from './memory/common';\nexport { model, tools, skillTools } from './langchain-adapter';\nexport type { LangChainModelOptions, LangChainProviderOptions } from './langchain-adapter';\n\nexport interface MemoryNodeState {\n memoryQuery?: string;\n memoryReadScope?: MemoryScope;\n memoryWriteScope?: MemoryScope;\n memoryMessages?: readonly MemoryMessage[];\n memoryText?: string;\n}\n\n/** Explicit graph nodes: the application owns state, turn boundaries and edges. */\nexport class AgentCoreMemoryNodes {\n private readonly topK: number;\n constructor(private readonly store: MemoryStore, private readonly options: { topK?: number; logger?: Logger } = {}) {\n this.topK = options.topK ?? 5; validateTopK(this.topK);\n }\n async recall(state: MemoryNodeState): Promise<{ memoryText: string }> {\n if (state.memoryQuery === undefined) throw new MemoryValidationError('memoryQuery is required');\n return { memoryText: await recallMemory(this.store, state.memoryQuery, state.memoryReadScope, { topK: this.topK, logger: this.options.logger }) };\n }\n async record(state: MemoryNodeState): Promise<{ memoryMessages: MemoryMessage[] }> {\n if (!Array.isArray(state.memoryMessages)) throw new MemoryValidationError('memoryMessages must be an array');\n await recordMemory(this.store, state.memoryMessages, state.memoryWriteScope, { logger: this.options.logger });\n return { memoryMessages: [] };\n }\n}\n\n/** Add reference data to model input without persisting it in graph history. */\nexport function withMemory(messages: readonly BaseMessage[], memoryText: string): BaseMessage[] {\n const result = [...messages]; const note = referenceText(memoryText);\n if (!note) return result;\n const first = result[0];\n if (SystemMessage.isInstance(first)) {\n result[0] = new SystemMessage({ id: first.id, name: first.name, additional_kwargs: first.additional_kwargs, response_metadata: first.response_metadata,\n content: typeof first.content === 'string' ? `${first.content}\\n\\n${note}` : [...first.content, { type: 'text', text: note }] });\n } else result.unshift(new SystemMessage(note));\n return result;\n}\nexport { LangChainEventConverter as AgentCoreConverter } from './event-converters';\n","import type { ChatOpenAIFields } from '@langchain/openai';\nimport type { ChatAnthropicInput } from '@langchain/anthropic';\nimport { tool, type StructuredToolInterface } from '@langchain/core/tools';\nimport type { JsonSchema7Type } from '@langchain/core/utils/json_schema';\nimport type { ModelClient, ProviderModelClient } from '../model';\nimport type { ProviderChatModel, LangChainProviderOptions } from './langchain-provider';\nimport type { Tool, ToolArguments } from './common';\nimport { skillTools as canonicalSkillTools, type Skill, type SkillToolsOptions } from '../skill';\n\ntype CoreOwnedFields = 'model' | 'modelName' | 'apiKey' | 'openAIApiKey' | 'anthropicApiKey'\n | 'anthropicApiUrl' | 'configuration' | 'clientOptions' | 'createClient' | 'completions' | 'responses' | 'maxRetries';\n/** Provider-specific generation options; identity and transport belong to ModelClient. */\nexport type LangChainModelOptions = Omit<ChatOpenAIFields, CoreOwnedFields> | Omit<ChatAnthropicInput, CoreOwnedFields>;\n\nexport type { LangChainProviderOptions } from './langchain-provider';\nexport function model(client: ModelClient, options?: LangChainModelOptions): Promise<import('@langchain/openai').ChatOpenAI | import('@langchain/anthropic').ChatAnthropic>;\nexport function model(client: ProviderModelClient, options?: LangChainProviderOptions): Promise<ProviderChatModel>;\nexport async function model(client: ModelClient | ProviderModelClient, options: LangChainModelOptions | LangChainProviderOptions = {}) {\n if ('languageModel' in client) {\n const { ProviderChatModel } = await import('./langchain-provider');\n return new ProviderChatModel(client, options as LangChainProviderOptions);\n }\n const { provider, model, baseURL, maxTokens } = client.settings;\n const fetch = client.httpFetch.bind(client);\n if (provider === 'anthropic') {\n const { ChatAnthropic } = await import('@langchain/anthropic');\n return new ChatAnthropic({ streamUsage: true, maxTokens,\n ...options as ChatAnthropicInput,\n model, apiKey: 'agentcore-transport', anthropicApiUrl: baseURL, maxRetries: 0,\n clientOptions: { baseURL, fetch },\n });\n }\n const { ChatOpenAI } = await import('@langchain/openai');\n return new ChatOpenAI({ streamUsage: true, useResponsesApi: false, maxTokens,\n ...options as ChatOpenAIFields,\n model, apiKey: 'agentcore-transport', maxRetries: 0, configuration: { baseURL, fetch },\n });\n}\n\n/** Keep native schema validation, ToolMessage conversion, callbacks and tool execution. */\nexport function tools(values: readonly Tool[]): StructuredToolInterface[] {\n return values.map(value => tool((args: ToolArguments) => value.invoke(args), {\n // LangChain's JSON Schema validator annotates its schema during dereferencing.\n name: value.name, description: value.description, schema: structuredClone(value.parameters) as JsonSchema7Type,\n }));\n}\nexport function skillTools(values: readonly Skill[], options: SkillToolsOptions = {}): StructuredToolInterface[] {\n return tools(canonicalSkillTools(values, options));\n}\n"]}
|
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunk25KH5XKGcjs = require('./chunk-25KH5XKG.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var _chunkLE5P3SJWcjs = require('./chunk-LE5P3SJW.cjs');
|
|
7
6
|
|
|
8
7
|
|
|
9
8
|
|
|
10
9
|
|
|
11
10
|
|
|
12
|
-
|
|
13
|
-
var _chunkJSP7ZROScjs = require('./chunk-JSP7ZROS.cjs');
|
|
11
|
+
var _chunkV4A6MJ42cjs = require('./chunk-V4A6MJ42.cjs');
|
|
14
12
|
|
|
15
13
|
// src/memory/transport.ts
|
|
16
14
|
var _agentcore20260804 = require('@alicloud/agentcore20260804'); var _agentcore202608042 = _interopRequireDefault(_agentcore20260804);
|
|
@@ -21,7 +19,7 @@ var GeneratedClient = typeof _agentcore202608042.default === "function" ? _agent
|
|
|
21
19
|
var DaraURL = _nullishCoalesce(Dara.URL, () => ( Dara.default.URL));
|
|
22
20
|
var pathComponent = (value) => DaraURL.percentEncode(value);
|
|
23
21
|
var MemoryTransport = class {
|
|
24
|
-
constructor(store, runtime, logger =
|
|
22
|
+
constructor(store, runtime, logger = _chunkV4A6MJ42cjs.nullLogger) {
|
|
25
23
|
this.store = store;
|
|
26
24
|
this.runtime = runtime;
|
|
27
25
|
this.logger = logger;
|
|
@@ -31,8 +29,8 @@ var MemoryTransport = class {
|
|
|
31
29
|
|
|
32
30
|
async request(operation, method, path, map, body, query) {
|
|
33
31
|
const runtime = await this.runtime();
|
|
34
|
-
const credential = await _asyncNullishCoalesce(runtime.accessKeyCredential, async () => ( await _optionalChain([runtime, 'access', _ => _.resourceSTS, 'optionalAccess', _2 => _2.get, 'call', _3 => _3(
|
|
35
|
-
if (!credential) throw new (0,
|
|
32
|
+
const credential = await _asyncNullishCoalesce(runtime.accessKeyCredential, async () => ( await _optionalChain([runtime, 'access', _ => _.resourceSTS, 'optionalAccess', _2 => _2.get, 'call', _3 => _3(_chunk25KH5XKGcjs.HIGH_CODE_SDK_PURPOSE)])));
|
|
33
|
+
if (!credential) throw new (0, _chunkV4A6MJ42cjs.ResourceNotConfiguredError)("AgentCore Memory data-plane credentials are not configured");
|
|
36
34
|
const url = runtime.endpoint ? new URL(runtime.endpoint.includes("://") ? runtime.endpoint : `https://${runtime.endpoint}`) : void 0;
|
|
37
35
|
const client = new GeneratedClient(new _openapicore.$OpenApiUtil.Config({
|
|
38
36
|
accessKeyId: credential.accessKeyId,
|
|
@@ -70,7 +68,7 @@ var MemoryTransport = class {
|
|
|
70
68
|
}));
|
|
71
69
|
} catch (cause) {
|
|
72
70
|
const details2 = errorDetails(cause);
|
|
73
|
-
const error = add && (details2.httpStatusCode === void 0 || details2.httpStatusCode >= 500) ? new (0,
|
|
71
|
+
const error = add && (details2.httpStatusCode === void 0 || details2.httpStatusCode >= 500) ? new (0, _chunkV4A6MJ42cjs.AddMemoriesOutcomeUnknownError)(operation, details2) : new (0, _chunkV4A6MJ42cjs.MemoryAPIError)(operation, details2);
|
|
74
72
|
this.logFailure(error);
|
|
75
73
|
throw error;
|
|
76
74
|
}
|
|
@@ -79,17 +77,25 @@ var MemoryTransport = class {
|
|
|
79
77
|
const details = {
|
|
80
78
|
serviceCode: text(payload.code),
|
|
81
79
|
httpStatusCode: _nullishCoalesce(integer(payload.httpStatusCode), () => ( integer(response.statusCode))),
|
|
82
|
-
requestId: _nullishCoalesce(text(payload.requestId), () => (
|
|
80
|
+
requestId: _nullishCoalesce(text(payload.requestId), () => ( headerRequestId(response.headers))),
|
|
81
|
+
serviceMessage: text(payload.message)
|
|
83
82
|
};
|
|
84
83
|
try {
|
|
85
84
|
if ((_nullishCoalesce(integer(response.statusCode), () => ( 0))) >= 400 || payload.success === false) {
|
|
86
|
-
throw add && (_nullishCoalesce(details.httpStatusCode, () => ( 0))) >= 500 ? new (0,
|
|
85
|
+
throw add && (_nullishCoalesce(details.httpStatusCode, () => ( 0))) >= 500 ? new (0, _chunkV4A6MJ42cjs.AddMemoriesOutcomeUnknownError)(operation, details) : new (0, _chunkV4A6MJ42cjs.MemoryAPIError)(operation, details);
|
|
87
86
|
}
|
|
88
|
-
if (payload.success !== true) throw new (0,
|
|
89
|
-
|
|
87
|
+
if (payload.success !== true) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)(operation, "body.success must be true");
|
|
88
|
+
const result = map(payload);
|
|
89
|
+
if (add && _optionalChain([body, 'optionalAccess', _8 => _8.sync]) === false) this.logger.info("agentcore.memory.request.submitted", {
|
|
90
|
+
operation,
|
|
91
|
+
memory_store_name: this.store,
|
|
92
|
+
task_id: text(record(result).taskId),
|
|
93
|
+
request_id: _nullishCoalesce(details.requestId, () => ( "-"))
|
|
94
|
+
});
|
|
95
|
+
return result;
|
|
90
96
|
} catch (cause) {
|
|
91
|
-
const error = add && cause instanceof
|
|
92
|
-
if (error instanceof
|
|
97
|
+
const error = add && cause instanceof _chunkV4A6MJ42cjs.MemoryContractError ? new (0, _chunkV4A6MJ42cjs.AddMemoriesOutcomeUnknownError)(operation, { ...details, serviceMessage: _nullishCoalesce(details.serviceMessage, () => ( cause.detail)) }) : cause;
|
|
98
|
+
if (error instanceof _chunkV4A6MJ42cjs.MemoryAPIError || error instanceof _chunkV4A6MJ42cjs.MemoryContractError) this.logFailure(error);
|
|
93
99
|
throw error;
|
|
94
100
|
}
|
|
95
101
|
}
|
|
@@ -98,9 +104,10 @@ var MemoryTransport = class {
|
|
|
98
104
|
operation: error.operation,
|
|
99
105
|
memory_store_name: this.store,
|
|
100
106
|
error_type: error.name,
|
|
101
|
-
status: error instanceof
|
|
102
|
-
service_code: error instanceof
|
|
103
|
-
request_id: error instanceof
|
|
107
|
+
status: error instanceof _chunkV4A6MJ42cjs.MemoryAPIError ? _nullishCoalesce(error.httpStatusCode, () => ( "-")) : "-",
|
|
108
|
+
service_code: error instanceof _chunkV4A6MJ42cjs.MemoryAPIError ? _nullishCoalesce(error.serviceCode, () => ( "-")) : "-",
|
|
109
|
+
request_id: error instanceof _chunkV4A6MJ42cjs.MemoryAPIError ? _nullishCoalesce(error.requestId, () => ( "-")) : "-",
|
|
110
|
+
message: error instanceof _chunkV4A6MJ42cjs.MemoryAPIError ? _nullishCoalesce(error.serviceMessage, () => ( "-")) : error.detail
|
|
104
111
|
});
|
|
105
112
|
}
|
|
106
113
|
};
|
|
@@ -108,11 +115,14 @@ function record(value) {
|
|
|
108
115
|
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
109
116
|
}
|
|
110
117
|
function text(value) {
|
|
111
|
-
return typeof value === "string" && value ? value : void 0;
|
|
118
|
+
return typeof value === "string" && value && value !== "undefined" ? value : void 0;
|
|
112
119
|
}
|
|
113
120
|
function integer(value) {
|
|
114
121
|
return typeof value === "number" && Number.isInteger(value) ? value : void 0;
|
|
115
122
|
}
|
|
123
|
+
function headerRequestId(headers) {
|
|
124
|
+
return text(_optionalChain([Object, 'access', _9 => _9.entries, 'call', _10 => _10(record(headers)), 'access', _11 => _11.find, 'call', _12 => _12(([key]) => key.toLowerCase() === "x-acs-request-id"), 'optionalAccess', _13 => _13[1]]));
|
|
125
|
+
}
|
|
116
126
|
function errorDetails(error) {
|
|
117
127
|
let current = record(error);
|
|
118
128
|
const result = {};
|
|
@@ -121,7 +131,8 @@ function errorDetails(error) {
|
|
|
121
131
|
const response = record(current.response);
|
|
122
132
|
result.serviceCode ??= _nullishCoalesce(_nullishCoalesce(text(current.code), () => ( text(data.code))), () => ( text(data.Code)));
|
|
123
133
|
result.httpStatusCode ??= _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(integer(current.statusCode), () => ( integer(data.statusCode))), () => ( integer(data.StatusCode))), () => ( integer(response.statusCode)));
|
|
124
|
-
result.requestId ??= _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(text(current.requestId), () => ( text(data.requestId))), () => ( text(data.RequestId))), () => (
|
|
134
|
+
result.requestId ??= _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(text(current.requestId), () => ( text(data.requestId))), () => ( text(data.RequestId))), () => ( headerRequestId(data.headers))), () => ( headerRequestId(response.headers)));
|
|
135
|
+
result.serviceMessage ??= _nullishCoalesce(_nullishCoalesce(text(data.message), () => ( text(data.Message))), () => ( text(current.message)));
|
|
125
136
|
if (!current.innerException) break;
|
|
126
137
|
current = record(current.innerException);
|
|
127
138
|
}
|
|
@@ -137,29 +148,58 @@ var MemoryStore = class {
|
|
|
137
148
|
this.transport = new MemoryTransport(name, options.runtime, options.logger);
|
|
138
149
|
}
|
|
139
150
|
async addMemories(options) {
|
|
151
|
+
if (options.sync !== void 0 && typeof options.sync !== "boolean") throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("sync must be a boolean");
|
|
152
|
+
const sync = _nullishCoalesce(options.sync, () => ( false));
|
|
140
153
|
const scope = validateScope(options.scope);
|
|
141
154
|
const hasText = options.text !== void 0;
|
|
142
155
|
const hasMessages = options.messages !== void 0;
|
|
143
|
-
if (hasText === hasMessages) throw new (0,
|
|
156
|
+
if (hasText === hasMessages) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("exactly one of text or messages must be provided");
|
|
144
157
|
const text2 = hasText ? required(options.text, "text") : void 0;
|
|
145
158
|
let messages;
|
|
146
159
|
if (hasMessages) {
|
|
147
|
-
if (!Array.isArray(options.messages) || !options.messages.length) throw new (0,
|
|
148
|
-
messages = options.messages.map((message) => ({ role: required(_optionalChain([message, 'optionalAccess',
|
|
160
|
+
if (!Array.isArray(options.messages) || !options.messages.length) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("messages must be a non-empty array");
|
|
161
|
+
messages = options.messages.map((message) => ({ role: required(_optionalChain([message, 'optionalAccess', _14 => _14.role]), "messages[].role"), content: required(_optionalChain([message, 'optionalAccess', _15 => _15.content]), "messages[].content") }));
|
|
149
162
|
}
|
|
150
163
|
const metadata = validateMetadata(options.metadata);
|
|
151
|
-
return this.transport.request("AddMemories", "POST", "/memories", (body) =>
|
|
164
|
+
return this.transport.request("AddMemories", "POST", "/memories", (body) => {
|
|
165
|
+
if (!sync) return Object.freeze({ taskId: string(record(body.data).taskId, "AddMemories", "data.taskId", true) });
|
|
166
|
+
return Object.freeze({ memoryIds: memoryIds(record(body.data).memories, "AddMemories") });
|
|
167
|
+
}, { scope, text: text2, messages, metadata, sync });
|
|
168
|
+
}
|
|
169
|
+
async getMemoryTask(taskId) {
|
|
170
|
+
required(taskId, "taskId");
|
|
171
|
+
return this.transport.request("GetMemoryTask", "GET", `/memory-tasks/${pathComponent(taskId)}`, (body) => {
|
|
172
|
+
const data = record(body.data);
|
|
173
|
+
const id = string(data.taskId, "GetMemoryTask", "data.taskId", true);
|
|
174
|
+
const status = string(data.status, "GetMemoryTask", "data.status", true);
|
|
175
|
+
if (!["PENDING", "RUNNING", "SUCCEEDED", "FAILED", "UNKNOWN"].includes(status)) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)("GetMemoryTask", "data.status is not a public task status");
|
|
176
|
+
let ids = Object.freeze([]);
|
|
177
|
+
let error;
|
|
178
|
+
if (status === "SUCCEEDED") {
|
|
179
|
+
if (data.error != null) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)("GetMemoryTask", "successful task contains error");
|
|
180
|
+
ids = memoryIds(data.memories, "GetMemoryTask");
|
|
181
|
+
} else if (status === "FAILED" || status === "UNKNOWN") {
|
|
182
|
+
if (data.memories != null) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)("GetMemoryTask", "failed task contains memories");
|
|
183
|
+
error = Object.freeze({
|
|
184
|
+
code: string(record(data.error).code, "GetMemoryTask", "data.error.code", true),
|
|
185
|
+
message: string(record(data.error).message, "GetMemoryTask", "data.error.message", true)
|
|
186
|
+
});
|
|
187
|
+
} else if (data.memories != null || data.error != null) {
|
|
188
|
+
throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)("GetMemoryTask", "non-terminal task contains result fields");
|
|
189
|
+
}
|
|
190
|
+
return Object.freeze({ taskId: id, status, memoryIds: ids, ...error ? { error } : {} });
|
|
191
|
+
});
|
|
152
192
|
}
|
|
153
193
|
async searchMemories(query, options = {}) {
|
|
154
194
|
required(query, "query");
|
|
155
195
|
const scope = validateScope(options.scope);
|
|
156
196
|
bounded(options.topK, "topK", 50);
|
|
157
197
|
const metadata = validateMetadata(options.metadata);
|
|
158
|
-
if (options.enableRerank !== void 0 && typeof options.enableRerank !== "boolean") throw new (0,
|
|
159
|
-
for (const key of ["minScore", "minSimilarity"]) if (options[key] !== void 0 && (typeof options[key] !== "number" || !Number.isFinite(options[key]))) throw new (0,
|
|
198
|
+
if (options.enableRerank !== void 0 && typeof options.enableRerank !== "boolean") throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("enableRerank must be a boolean");
|
|
199
|
+
for (const key of ["minScore", "minSimilarity"]) if (options[key] !== void 0 && (typeof options[key] !== "number" || !Number.isFinite(options[key]))) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)(`${key} must be a finite number`);
|
|
160
200
|
return this.transport.request("SearchMemories", "POST", "/memories/search", (body) => Object.freeze({ memories: Object.freeze(array(record(body.data).memories, "SearchMemories", "data.memories").map((item) => {
|
|
161
201
|
const hit = record(item);
|
|
162
|
-
if (typeof hit.score !== "number" || typeof hit.similarity !== "number") throw new (0,
|
|
202
|
+
if (typeof hit.score !== "number" || typeof hit.similarity !== "number") throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)("SearchMemories", "score and similarity must be numbers");
|
|
163
203
|
return Object.freeze({ memory: parseMemory(hit.memory, "SearchMemories"), score: hit.score, similarity: hit.similarity });
|
|
164
204
|
})) }), { query, scope, topK: options.topK, metadata, enableRerank: options.enableRerank, minScore: options.minScore, minSimilarity: options.minSimilarity });
|
|
165
205
|
}
|
|
@@ -183,7 +223,7 @@ var MemoryStore = class {
|
|
|
183
223
|
}
|
|
184
224
|
async updateMemory(memoryId, options) {
|
|
185
225
|
required(memoryId, "memoryId");
|
|
186
|
-
if (options.text === void 0 && options.metadata === void 0) throw new (0,
|
|
226
|
+
if (options.text === void 0 && options.metadata === void 0) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("at least one of text or metadata must be provided");
|
|
187
227
|
optional(options.text, "text");
|
|
188
228
|
const metadata = validateMetadata(options.metadata);
|
|
189
229
|
return this.transport.request("UpdateMemory", "PUT", `/memories/${pathComponent(memoryId)}`, (body) => parseMemory(body.data, "UpdateMemory"), { text: options.text, metadata });
|
|
@@ -202,7 +242,7 @@ var MemoryStore = class {
|
|
|
202
242
|
sessionId: optionalString(record(item).sessionId, "ListMemorySessions", "items[].sessionId"),
|
|
203
243
|
userId: optionalString(record(item).userId, "ListMemorySessions", "items[].userId")
|
|
204
244
|
});
|
|
205
|
-
if (session.userId === void 0 && session.agentId === void 0 && session.sessionId === void 0) throw new (0,
|
|
245
|
+
if (session.userId === void 0 && session.agentId === void 0 && session.sessionId === void 0) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)("ListMemorySessions", "items[] must contain at least one scope field");
|
|
206
246
|
return session;
|
|
207
247
|
}), void 0, { userId: options.userId, agentId: options.agentId, maxResults: options.maxResults, nextToken: options.nextToken });
|
|
208
248
|
}
|
|
@@ -211,7 +251,7 @@ var MemoryStore = class {
|
|
|
211
251
|
optionalScopeString(sessionId, "sessionId");
|
|
212
252
|
optionalScopeString(options.userId, "userId");
|
|
213
253
|
optionalScopeString(options.agentId, "agentId");
|
|
214
|
-
if (options.userId === void 0 && options.agentId === void 0) throw new (0,
|
|
254
|
+
if (options.userId === void 0 && options.agentId === void 0) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("at least one of userId or agentId must be provided");
|
|
215
255
|
validatePage(options);
|
|
216
256
|
return this.transport.request(
|
|
217
257
|
"ListMemorySessionMessages",
|
|
@@ -226,23 +266,27 @@ var MemoryStore = class {
|
|
|
226
266
|
);
|
|
227
267
|
}
|
|
228
268
|
};
|
|
269
|
+
function memoryIds(value, operation) {
|
|
270
|
+
if (!Array.isArray(value)) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)(operation, "data.memories must be an array");
|
|
271
|
+
return Object.freeze(value.map((item) => string(record(item).memoryId, operation, "data.memories[].memoryId", true)));
|
|
272
|
+
}
|
|
229
273
|
function required(value, field) {
|
|
230
|
-
if (typeof value !== "string" || !value.trim()) throw new (0,
|
|
274
|
+
if (typeof value !== "string" || !value.trim()) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)(`${field} must be a non-empty string`);
|
|
231
275
|
return value;
|
|
232
276
|
}
|
|
233
277
|
function optional(value, field) {
|
|
234
278
|
if (value !== void 0) required(value, field);
|
|
235
279
|
}
|
|
236
280
|
function bounded(value, field, maximum) {
|
|
237
|
-
if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > maximum)) throw new (0,
|
|
281
|
+
if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > maximum)) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)(`${field} must be an integer from 1 to ${maximum}`);
|
|
238
282
|
}
|
|
239
283
|
function optionalScopeString(value, field) {
|
|
240
284
|
if (value === void 0) return;
|
|
241
|
-
if (["*", "__default__"].includes(required(value, field).trim())) throw new (0,
|
|
285
|
+
if (["*", "__default__"].includes(required(value, field).trim())) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)(`${field} must not use a reserved scope value`);
|
|
242
286
|
}
|
|
243
287
|
function validateScope(scope) {
|
|
244
288
|
if (scope === void 0) return void 0;
|
|
245
|
-
if (!scope || typeof scope !== "object" || Array.isArray(scope)) throw new (0,
|
|
289
|
+
if (!scope || typeof scope !== "object" || Array.isArray(scope)) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("scope must be a MemoryScope");
|
|
246
290
|
optionalScopeString(scope.userId, "scope.userId");
|
|
247
291
|
optionalScopeString(scope.agentId, "scope.agentId");
|
|
248
292
|
optionalScopeString(scope.sessionId, "scope.sessionId");
|
|
@@ -250,20 +294,20 @@ function validateScope(scope) {
|
|
|
250
294
|
}
|
|
251
295
|
function validateMetadata(value) {
|
|
252
296
|
if (value === void 0) return void 0;
|
|
253
|
-
if (!value || typeof value !== "object" || Array.isArray(value) || Object.entries(value).some(([key, item]) => !key.trim() || typeof item !== "string")) throw new (0,
|
|
297
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.entries(value).some(([key, item]) => !key.trim() || typeof item !== "string")) throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("metadata must contain non-empty string keys and string values");
|
|
254
298
|
return { ...value };
|
|
255
299
|
}
|
|
256
300
|
function validatePage(options) {
|
|
257
301
|
bounded(options.maxResults, "maxResults", 100);
|
|
258
|
-
if (options.nextToken !== void 0 && typeof options.nextToken !== "string") throw new (0,
|
|
302
|
+
if (options.nextToken !== void 0 && typeof options.nextToken !== "string") throw new (0, _chunkV4A6MJ42cjs.MemoryValidationError)("nextToken must be a string");
|
|
259
303
|
}
|
|
260
304
|
function array(value, operation, path) {
|
|
261
305
|
if (value === void 0 || value === null) return [];
|
|
262
|
-
if (!Array.isArray(value)) throw new (0,
|
|
306
|
+
if (!Array.isArray(value)) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)(operation, `${path} must be an array`);
|
|
263
307
|
return value;
|
|
264
308
|
}
|
|
265
309
|
function string(value, operation, path, nonEmpty = false) {
|
|
266
|
-
if (typeof value !== "string" || nonEmpty && !value.trim()) throw new (0,
|
|
310
|
+
if (typeof value !== "string" || nonEmpty && !value.trim()) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)(operation, `${path} must be ${nonEmpty ? "a non-empty" : "a"} string`);
|
|
267
311
|
return value;
|
|
268
312
|
}
|
|
269
313
|
function optionalString(value, operation, path) {
|
|
@@ -274,10 +318,10 @@ function parseMemory(value, operation) {
|
|
|
274
318
|
const scope = record(item.scope);
|
|
275
319
|
const memoryId = string(item.memoryId, operation, "memory.memoryId", true);
|
|
276
320
|
const text2 = string(record(item.content).text, operation, "memory.content.text");
|
|
277
|
-
if (!item.scope || typeof item.scope !== "object" || Array.isArray(item.scope)) throw new (0,
|
|
321
|
+
if (!item.scope || typeof item.scope !== "object" || Array.isArray(item.scope)) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)(operation, "memory.scope must be an object");
|
|
278
322
|
let metadata;
|
|
279
323
|
if (item.metadata !== void 0 && item.metadata !== null) {
|
|
280
|
-
if (typeof item.metadata !== "object" || Array.isArray(item.metadata) || Object.entries(item.metadata).some(([key, value2]) => !key.trim() || typeof value2 !== "string")) throw new (0,
|
|
324
|
+
if (typeof item.metadata !== "object" || Array.isArray(item.metadata) || Object.entries(item.metadata).some(([key, value2]) => !key.trim() || typeof value2 !== "string")) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)(operation, "memory.metadata must contain string keys and values");
|
|
281
325
|
metadata = Object.freeze({ ...item.metadata });
|
|
282
326
|
}
|
|
283
327
|
return Object.freeze({
|
|
@@ -290,7 +334,7 @@ function parseMemory(value, operation) {
|
|
|
290
334
|
});
|
|
291
335
|
}
|
|
292
336
|
function page(body, operation, parse) {
|
|
293
|
-
for (const key of ["maxResults", "totalCount"]) if (body[key] !== void 0 && body[key] !== null && (typeof body[key] !== "number" || !Number.isInteger(body[key]))) throw new (0,
|
|
337
|
+
for (const key of ["maxResults", "totalCount"]) if (body[key] !== void 0 && body[key] !== null && (typeof body[key] !== "number" || !Number.isInteger(body[key]))) throw new (0, _chunkV4A6MJ42cjs.MemoryContractError)(operation, `body.${key} must be an integer`);
|
|
294
338
|
return Object.freeze({
|
|
295
339
|
items: Object.freeze(array(body.items, operation, "body.items").map(parse)),
|
|
296
340
|
maxResults: body.maxResults == null ? void 0 : body.maxResults,
|
|
@@ -303,4 +347,4 @@ function page(body, operation, parse) {
|
|
|
303
347
|
|
|
304
348
|
|
|
305
349
|
exports.MemoryStore = MemoryStore; exports.validateScope = validateScope;
|
|
306
|
-
//# sourceMappingURL=chunk-
|
|
350
|
+
//# sourceMappingURL=chunk-ZIXZWQSP.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-ZIXZWQSP.cjs","../src/memory/transport.ts","../src/memory/client.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACZA,sIAAmB;AACnB,qDAA0C;AAC1C,oGAAsB;AACtB;AAMA,IAAM,gBAAA,EAAkB,OAAO,4BAAA,IAAW,WAAA,EAAa,4BAAA,EAAU,2BAAA,CAAiD,OAAA;AAElH,IAAM,QAAA,mBAAe,IAAA,CAAA,GAAA,UAAqD,IAAA,CAAA,OAAA,CAAQ,KAAA;AAS3E,IAAM,cAAA,EAAgB,CAAC,KAAA,EAAA,GAA0B,OAAA,CAAQ,aAAA,CAAc,KAAK,CAAA;AAG5E,IAAM,gBAAA,EAAN,MAAsB;AAAA,EAC3B,WAAA,CAA6B,KAAA,EAAg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D;AAAgD,EAAA;AAAG;AACnC;AACyD,EAAA;AAChI;AACkE;AACvC,EAAA;AACiF,EAAA;AAC5G;AACuF;AACrD,EAAA;AACiE,EAAA;AACjD,EAAA;AAAqD,EAAA;AAAyD,EAAA;AAC5E,EAAA;AACpF;AACmH;AACjF,EAAA;AACyF,EAAA;AACvG,EAAA;AACpB;AACkD;AACH,EAAA;AACiE,EAAA;AAChH;AACoF;AAC/B,EAAA;AAC2C,EAAA;AACvF,EAAA;AACT;AACoG;AACwB,EAAA;AACnH,EAAA;AACT;AACsG;AAA0F,EAAA;AAAG;AAC1H;AAC9C,EAAA;AAAkC,EAAA;AACc,EAAA;AACM,EAAA;AAC0C,EAAA;AACrH,EAAA;AACuD,EAAA;AAC+D,IAAA;AACjD,IAAA;AACzE,EAAA;AACqB,EAAA;AAAE,IAAA;AAAyC,IAAA;AAAgH,IAAA;AAC9K,IAAA;AAAiF,IAAA;AAA0E,IAAA;AAAG,EAAA;AAClK;AACkH;AACW,EAAA;AACtG,EAAA;AAA4E,IAAA;AAA0D,IAAA;AAClG,IAAA;AAAgG,IAAA;AAAW,EAAA;AACtK;AF4K6H;AACA;AACA;AACA;AACA","file":"/home/runner/work/agentcore-sdk-nodejs/agentcore-sdk-nodejs/dist/chunk-ZIXZWQSP.cjs","sourcesContent":[null,"import Client from '@alicloud/agentcore20260804';\nimport { $OpenApiUtil, OpenApiUtil } from '@alicloud/openapi-core';\nimport * as Dara from '@darabonba/typescript';\nimport { RuntimeOptions } from '@darabonba/typescript';\nimport type { AccessKeyCredential, CredentialProvider } from '../auth/access-key';\nimport { HIGH_CODE_SDK_PURPOSE } from '../auth/resource-sts';\nimport { AddMemoriesOutcomeUnknownError, MemoryAPIError, MemoryContractError, ResourceNotConfiguredError, type MemoryErrorDetails } from '../errors';\nimport { nullLogger, type Logger } from '../logging';\n\nconst GeneratedClient = typeof Client === 'function' ? Client : (Client as unknown as { default: typeof Client }).default;\n// CJS exposes URL directly; native ESM only exposes it on module.exports/default.\nconst DaraURL = Dara.URL ?? (Dara as unknown as { default: typeof Dara }).default.URL;\nexport interface MemoryRuntime {\n workspaceId: string;\n regionId: string;\n endpoint?: string;\n accessKeyCredential?: AccessKeyCredential;\n resourceSTS?: CredentialProvider;\n}\nexport type MemoryOperation = 'AddMemories' | 'GetMemoryTask' | 'SearchMemories' | 'ListMemories' | 'GetMemory' | 'UpdateMemory' | 'DeleteMemory' | 'ListMemorySessions' | 'ListMemorySessionMessages';\nexport const pathComponent = (value: string): string => DaraURL.percentEncode(value);\n\n/** Memory methods absent from the public generated package, using its existing POP transport. */\nexport class MemoryTransport {\n constructor(private readonly store: string, private readonly runtime: () => Promise<MemoryRuntime>, private readonly logger: Logger = nullLogger) {}\n async request<T>(operation: MemoryOperation, method: string, path: string, map: (body: Record<string, unknown>) => T,\n body?: Record<string, unknown>, query?: Record<string, unknown>): Promise<T> {\n const runtime = await this.runtime();\n const credential = runtime.accessKeyCredential ?? await runtime.resourceSTS?.get(HIGH_CODE_SDK_PURPOSE);\n if (!credential) throw new ResourceNotConfiguredError('AgentCore Memory data-plane credentials are not configured');\n const url = runtime.endpoint ? new URL(runtime.endpoint.includes('://') ? runtime.endpoint : `https://${runtime.endpoint}`) : undefined;\n const client = new GeneratedClient(new $OpenApiUtil.Config({ accessKeyId: credential.accessKeyId, accessKeySecret: credential.accessKeySecret,\n securityToken: credential.securityToken, regionId: runtime.regionId, endpoint: url?.host, protocol: url?.protocol.slice(0, -1) }));\n const params = new $OpenApiUtil.Params({ action: operation, version: '2026-08-04', protocol: 'HTTPS',\n pathname: `/workspaces/${pathComponent(runtime.workspaceId)}/memorystores/${pathComponent(this.store)}${path}`,\n method, authType: 'AK', style: 'ROA', reqBodyType: body === undefined ? 'json' : 'formData', bodyType: 'json' });\n // The generated Python contract wraps JSON in the form field `body`.\n const request = new $OpenApiUtil.OpenApiRequest({ headers: {}, query: OpenApiUtil.query(query ?? {}),\n body: body === undefined ? undefined : { body: JSON.stringify(body) } });\n const add = operation === 'AddMemories';\n let raw: unknown;\n this.logger.debug('agentcore.memory.request.started', { operation, memory_store_name: this.store });\n try {\n // httpx also uses connectTimeout as socket inactivity timeout while awaiting the response.\n raw = await client.callApi(params, request, new RuntimeOptions({ autoretry: false, maxAttempts: 1,\n connectTimeout: add ? 120_000 : undefined, readTimeout: add ? 120_000 : undefined }));\n } catch (cause) {\n const details = errorDetails(cause);\n const error = add && (details.httpStatusCode === undefined || details.httpStatusCode >= 500)\n ? new AddMemoriesOutcomeUnknownError(operation, details) : new MemoryAPIError(operation, details);\n this.logFailure(error); throw error;\n }\n const response = record(raw); const payload = record(response.body);\n const details: MemoryErrorDetails = { serviceCode: text(payload.code), httpStatusCode: integer(payload.httpStatusCode) ?? integer(response.statusCode),\n requestId: text(payload.requestId) ?? headerRequestId(response.headers), serviceMessage: text(payload.message) };\n try {\n if ((integer(response.statusCode) ?? 0) >= 400 || payload.success === false) {\n throw add && (details.httpStatusCode ?? 0) >= 500 ? new AddMemoriesOutcomeUnknownError(operation, details) : new MemoryAPIError(operation, details);\n }\n if (payload.success !== true) throw new MemoryContractError(operation, 'body.success must be true');\n const result = map(payload);\n if (add && body?.sync === false) this.logger.info('agentcore.memory.request.submitted', {\n operation, memory_store_name: this.store, task_id: text(record(result).taskId), request_id: details.requestId ?? '-',\n });\n return result;\n } catch (cause) {\n const error = add && cause instanceof MemoryContractError\n ? new AddMemoriesOutcomeUnknownError(operation, { ...details, serviceMessage: details.serviceMessage ?? cause.detail }) : cause;\n if (error instanceof MemoryAPIError || error instanceof MemoryContractError) this.logFailure(error);\n throw error;\n }\n }\n private logFailure(error: MemoryAPIError | MemoryContractError): void {\n this.logger.warn('agentcore.memory.request.failed', { operation: error.operation, memory_store_name: this.store, error_type: error.name,\n status: error instanceof MemoryAPIError ? error.httpStatusCode ?? '-' : '-',\n service_code: error instanceof MemoryAPIError ? error.serviceCode ?? '-' : '-',\n request_id: error instanceof MemoryAPIError ? error.requestId ?? '-' : '-',\n message: error instanceof MemoryAPIError ? error.serviceMessage ?? '-' : error.detail });\n }\n}\nexport function record(value: unknown): Record<string, unknown> { return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}; }\n// The generated client stringifies missing error fields as \"undefined\".\nfunction text(value: unknown): string | undefined { return typeof value === 'string' && value && value !== 'undefined' ? value : undefined; }\nfunction integer(value: unknown): number | undefined { return typeof value === 'number' && Number.isInteger(value) ? value : undefined; }\nfunction headerRequestId(headers: unknown): string | undefined {\n return text(Object.entries(record(headers)).find(([key]) => key.toLowerCase() === 'x-acs-request-id')?.[1]);\n}\nfunction errorDetails(error: unknown): MemoryErrorDetails {\n let current = record(error); const result: MemoryErrorDetails = {};\n for (let i = 0; i < 4; i++) {\n const data = record(current.data); const response = record(current.response);\n result.serviceCode ??= text(current.code) ?? text(data.code) ?? text(data.Code);\n result.httpStatusCode ??= integer(current.statusCode) ?? integer(data.statusCode) ?? integer(data.StatusCode) ?? integer(response.statusCode);\n result.requestId ??= text(current.requestId) ?? text(data.requestId) ?? text(data.RequestId)\n ?? headerRequestId(data.headers) ?? headerRequestId(response.headers);\n result.serviceMessage ??= text(data.message) ?? text(data.Message) ?? text(current.message);\n if (!current.innerException) break;\n current = record(current.innerException);\n }\n return result;\n}\n","import { MemoryContractError, MemoryValidationError } from '../errors';\nimport type { Logger } from '../logging';\nimport { MemoryTransport, pathComponent, record, type MemoryRuntime, type MemoryOperation } from './transport';\nimport type { AddMemoriesOptions, AddMemoriesResult, AddMemoriesSubmission, MemoryTask, MemoryTaskStatus, ListMemoriesOptions, ListMemorySessionsOptions, ListMemorySessionMessagesOptions, Memory, MemoryMessage, MemoryScope, MemorySession,\n Page, PageOptions, SearchMemoriesOptions, SearchMemoriesResult, UpdateMemoryOptions } from './models';\n\n/** A local binding to an existing MemoryStore. No lookup or creation at construction. */\nexport class MemoryStore {\n readonly memoryStoreName: string;\n private readonly transport: MemoryTransport;\n constructor(name: string, options: { runtime: () => Promise<MemoryRuntime>; logger?: Logger }) {\n this.memoryStoreName = required(name, 'memoryStoreName');\n this.transport = new MemoryTransport(name, options.runtime, options.logger);\n }\n addMemories(options: AddMemoriesOptions & { sync: true }): Promise<AddMemoriesResult>;\n addMemories(options: AddMemoriesOptions & { sync?: false }): Promise<AddMemoriesSubmission>;\n addMemories(options: AddMemoriesOptions): Promise<AddMemoriesResult | AddMemoriesSubmission>;\n async addMemories(options: AddMemoriesOptions): Promise<AddMemoriesResult | AddMemoriesSubmission> {\n if (options.sync !== undefined && typeof options.sync !== 'boolean') throw new MemoryValidationError('sync must be a boolean');\n const sync = options.sync ?? false;\n const scope = validateScope(options.scope);\n const hasText = options.text !== undefined; const hasMessages = options.messages !== undefined;\n if (hasText === hasMessages) throw new MemoryValidationError('exactly one of text or messages must be provided');\n const text = hasText ? required(options.text, 'text') : undefined;\n let messages: MemoryMessage[] | undefined;\n if (hasMessages) {\n if (!Array.isArray(options.messages) || !options.messages.length) throw new MemoryValidationError('messages must be a non-empty array');\n messages = options.messages.map((message) => ({ role: required(message?.role, 'messages[].role'), content: required(message?.content, 'messages[].content') }));\n }\n const metadata = validateMetadata(options.metadata);\n return this.transport.request<AddMemoriesResult | AddMemoriesSubmission>('AddMemories', 'POST', '/memories', (body) => {\n if (!sync) return Object.freeze({ taskId: string(record(body.data).taskId, 'AddMemories', 'data.taskId', true) });\n return Object.freeze({ memoryIds: memoryIds(record(body.data).memories, 'AddMemories') });\n }, { scope, text, messages, metadata, sync });\n }\n async getMemoryTask(taskId: string): Promise<MemoryTask> {\n required(taskId, 'taskId');\n return this.transport.request('GetMemoryTask', 'GET', `/memory-tasks/${pathComponent(taskId)}`, body => {\n const data = record(body.data);\n const id = string(data.taskId, 'GetMemoryTask', 'data.taskId', true);\n const status = string(data.status, 'GetMemoryTask', 'data.status', true);\n if (!['PENDING', 'RUNNING', 'SUCCEEDED', 'FAILED', 'UNKNOWN'].includes(status)) throw new MemoryContractError('GetMemoryTask', 'data.status is not a public task status');\n let ids: readonly string[] = Object.freeze([]);\n let error: MemoryTask['error'];\n if (status === 'SUCCEEDED') {\n if (data.error != null) throw new MemoryContractError('GetMemoryTask', 'successful task contains error');\n ids = memoryIds(data.memories, 'GetMemoryTask');\n } else if (status === 'FAILED' || status === 'UNKNOWN') {\n if (data.memories != null) throw new MemoryContractError('GetMemoryTask', 'failed task contains memories');\n error = Object.freeze({ code: string(record(data.error).code, 'GetMemoryTask', 'data.error.code', true),\n message: string(record(data.error).message, 'GetMemoryTask', 'data.error.message', true) });\n } else if (data.memories != null || data.error != null) {\n throw new MemoryContractError('GetMemoryTask', 'non-terminal task contains result fields');\n }\n return Object.freeze({ taskId: id, status: status as MemoryTaskStatus, memoryIds: ids, ...(error ? { error } : {}) });\n });\n }\n async searchMemories(query: string, options: SearchMemoriesOptions = {}): Promise<SearchMemoriesResult> {\n required(query, 'query'); const scope = validateScope(options.scope);\n bounded(options.topK, 'topK', 50); const metadata = validateMetadata(options.metadata);\n if (options.enableRerank !== undefined && typeof options.enableRerank !== 'boolean') throw new MemoryValidationError('enableRerank must be a boolean');\n for (const key of ['minScore', 'minSimilarity'] as const) if (options[key] !== undefined && (typeof options[key] !== 'number' || !Number.isFinite(options[key]))) throw new MemoryValidationError(`${key} must be a finite number`);\n return this.transport.request('SearchMemories', 'POST', '/memories/search', (body) => Object.freeze({ memories: Object.freeze(array(record(body.data).memories, 'SearchMemories', 'data.memories').map((item) => {\n const hit = record(item);\n if (typeof hit.score !== 'number' || typeof hit.similarity !== 'number') throw new MemoryContractError('SearchMemories', 'score and similarity must be numbers');\n return Object.freeze({ memory: parseMemory(hit.memory, 'SearchMemories'), score: hit.score, similarity: hit.similarity });\n })) }), { query, scope, topK: options.topK, metadata, enableRerank: options.enableRerank, minScore: options.minScore, minSimilarity: options.minSimilarity });\n }\n async listMemories(options: ListMemoriesOptions = {}): Promise<Page<Memory>> {\n optionalScopeString(options.userId, 'userId'); optionalScopeString(options.agentId, 'agentId'); optionalScopeString(options.sessionId, 'sessionId');\n validatePage(options);\n return this.transport.request('ListMemories', 'GET', '/memories', (body) => page(body, 'ListMemories', (item) => parseMemory(item, 'ListMemories')),\n undefined, { userId: options.userId, agentId: options.agentId, sessionId: options.sessionId, maxResults: options.maxResults, nextToken: options.nextToken });\n }\n async getMemory(memoryId: string): Promise<Memory> {\n required(memoryId, 'memoryId');\n return this.transport.request('GetMemory', 'GET', `/memories/${pathComponent(memoryId)}`, (body) => parseMemory(body.data, 'GetMemory'));\n }\n async updateMemory(memoryId: string, options: UpdateMemoryOptions): Promise<Memory> {\n required(memoryId, 'memoryId');\n if (options.text === undefined && options.metadata === undefined) throw new MemoryValidationError('at least one of text or metadata must be provided');\n optional(options.text, 'text'); const metadata = validateMetadata(options.metadata);\n return this.transport.request('UpdateMemory', 'PUT', `/memories/${pathComponent(memoryId)}`, (body) => parseMemory(body.data, 'UpdateMemory'), { text: options.text, metadata });\n }\n async deleteMemory(memoryId: string): Promise<void> {\n required(memoryId, 'memoryId');\n return this.transport.request('DeleteMemory', 'DELETE', `/memories/${pathComponent(memoryId)}`, () => undefined);\n }\n async listMemorySessions(options: ListMemorySessionsOptions = {}): Promise<Page<MemorySession>> {\n optionalScopeString(options.userId, 'userId'); optionalScopeString(options.agentId, 'agentId'); validatePage(options);\n return this.transport.request('ListMemorySessions', 'GET', '/sessions', (body) => page(body, 'ListMemorySessions', (item) => {\n const session = Object.freeze({\n agentId: optionalString(record(item).agentId, 'ListMemorySessions', 'items[].agentId'),\n sessionId: optionalString(record(item).sessionId, 'ListMemorySessions', 'items[].sessionId'),\n userId: optionalString(record(item).userId, 'ListMemorySessions', 'items[].userId'),\n });\n if (session.userId === undefined && session.agentId === undefined && session.sessionId === undefined) throw new MemoryContractError('ListMemorySessions', 'items[] must contain at least one scope field');\n return session;\n }), undefined, { userId: options.userId, agentId: options.agentId, maxResults: options.maxResults, nextToken: options.nextToken });\n }\n async listMemorySessionMessages(sessionId: string, options: ListMemorySessionMessagesOptions = {}): Promise<Page<MemoryMessage>> {\n required(sessionId, 'sessionId'); optionalScopeString(sessionId, 'sessionId');\n optionalScopeString(options.userId, 'userId'); optionalScopeString(options.agentId, 'agentId');\n if (options.userId === undefined && options.agentId === undefined) throw new MemoryValidationError('at least one of userId or agentId must be provided');\n validatePage(options);\n return this.transport.request('ListMemorySessionMessages', 'GET', '/messages',\n (body) => page(body, 'ListMemorySessionMessages', (item) => Object.freeze({\n role: string(record(item).role, 'ListMemorySessionMessages', 'items[].role', true),\n content: string(record(item).content, 'ListMemorySessionMessages', 'items[].content', true),\n })), undefined, { userId: options.userId, agentId: options.agentId, sessionId, maxResults: options.maxResults, nextToken: options.nextToken });\n }\n}\n\nfunction memoryIds(value: unknown, operation: MemoryOperation): readonly string[] {\n if (!Array.isArray(value)) throw new MemoryContractError(operation, 'data.memories must be an array');\n return Object.freeze(value.map(item => string(record(item).memoryId, operation, 'data.memories[].memoryId', true)));\n}\n\nfunction required(value: unknown, field: string): string {\n if (typeof value !== 'string' || !value.trim()) throw new MemoryValidationError(`${field} must be a non-empty string`);\n return value;\n}\nfunction optional(value: unknown, field: string): void { if (value !== undefined) required(value, field); }\nfunction bounded(value: unknown, field: string, maximum: number): void {\n if (value !== undefined && (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > maximum)) throw new MemoryValidationError(`${field} must be an integer from 1 to ${maximum}`);\n}\nfunction optionalScopeString(value: unknown, field: string): void {\n if (value === undefined) return;\n if (['*', '__default__'].includes(required(value, field).trim())) throw new MemoryValidationError(`${field} must not use a reserved scope value`);\n}\nexport function validateScope(scope: MemoryScope | undefined): MemoryScope | undefined {\n if (scope === undefined) return undefined;\n if (!scope || typeof scope !== 'object' || Array.isArray(scope)) throw new MemoryValidationError('scope must be a MemoryScope');\n optionalScopeString(scope.userId, 'scope.userId'); optionalScopeString(scope.agentId, 'scope.agentId'); optionalScopeString(scope.sessionId, 'scope.sessionId');\n return { userId: scope.userId, agentId: scope.agentId, sessionId: scope.sessionId };\n}\nfunction validateMetadata(value: Readonly<Record<string, string>> | undefined): Record<string, string> | undefined {\n if (value === undefined) return undefined;\n if (!value || typeof value !== 'object' || Array.isArray(value) || Object.entries(value).some(([key, item]) => !key.trim() || typeof item !== 'string')) throw new MemoryValidationError('metadata must contain non-empty string keys and string values');\n return { ...value };\n}\nfunction validatePage(options: PageOptions): void {\n bounded(options.maxResults, 'maxResults', 100);\n if (options.nextToken !== undefined && typeof options.nextToken !== 'string') throw new MemoryValidationError('nextToken must be a string');\n}\nfunction array(value: unknown, operation: MemoryOperation, path: string): unknown[] {\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value)) throw new MemoryContractError(operation, `${path} must be an array`);\n return value;\n}\nfunction string(value: unknown, operation: MemoryOperation, path: string, nonEmpty = false): string {\n if (typeof value !== 'string' || (nonEmpty && !value.trim())) throw new MemoryContractError(operation, `${path} must be ${nonEmpty ? 'a non-empty' : 'a'} string`);\n return value;\n}\nfunction optionalString(value: unknown, operation: MemoryOperation, path: string): string | undefined { return value === undefined || value === null ? undefined : string(value, operation, path); }\nfunction parseMemory(value: unknown, operation: MemoryOperation): Memory {\n const item = record(value); const scope = record(item.scope);\n const memoryId = string(item.memoryId, operation, 'memory.memoryId', true);\n const text = string(record(item.content).text, operation, 'memory.content.text');\n if (!item.scope || typeof item.scope !== 'object' || Array.isArray(item.scope)) throw new MemoryContractError(operation, 'memory.scope must be an object');\n let metadata: Readonly<Record<string, string>> | undefined;\n if (item.metadata !== undefined && item.metadata !== null) {\n if (typeof item.metadata !== 'object' || Array.isArray(item.metadata) || Object.entries(item.metadata).some(([key, value]) => !key.trim() || typeof value !== 'string')) throw new MemoryContractError(operation, 'memory.metadata must contain string keys and values');\n metadata = Object.freeze({ ...item.metadata as Record<string, string> });\n }\n return Object.freeze({ memoryId, content: Object.freeze({ text }), scope: Object.freeze({ agentId: optionalString(scope.agentId, operation, 'memory.scope.agentId'), sessionId: optionalString(scope.sessionId, operation, 'memory.scope.sessionId'), userId: optionalString(scope.userId, operation, 'memory.scope.userId') }),\n metadata, createdAt: optionalString(item.createdAt, operation, 'memory.createdAt'), updatedAt: optionalString(item.updatedAt, operation, 'memory.updatedAt') });\n}\nfunction page<T>(body: Record<string, unknown>, operation: MemoryOperation, parse: (item: unknown) => T): Page<T> {\n for (const key of ['maxResults', 'totalCount']) if (body[key] !== undefined && body[key] !== null && (typeof body[key] !== 'number' || !Number.isInteger(body[key]))) throw new MemoryContractError(operation, `body.${key} must be an integer`);\n return Object.freeze({ items: Object.freeze(array(body.items, operation, 'body.items').map(parse)), maxResults: body.maxResults == null ? undefined : body.maxResults as number,\n totalCount: body.totalCount == null ? undefined : body.totalCount as number, nextToken: optionalString(body.nextToken, operation, 'body.nextToken') || undefined });\n}\n"]}
|