@nhtio/adk 0.1.0-master-16963fb8 → 0.1.0-master-eee043dc
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/CHANGELOG.md +87 -0
- package/batteries/llm/bedrock_converse/adapter.cjs +157 -16
- package/batteries/llm/bedrock_converse/adapter.cjs.map +1 -1
- package/batteries/llm/bedrock_converse/adapter.mjs +157 -16
- package/batteries/llm/bedrock_converse/adapter.mjs.map +1 -1
- package/batteries/llm/bedrock_converse.cjs +1 -1
- package/batteries/llm/bedrock_converse.mjs +1 -1
- package/batteries/llm/claude_code_cli/adapter.cjs +59 -18
- package/batteries/llm/claude_code_cli/adapter.cjs.map +1 -1
- package/batteries/llm/claude_code_cli/adapter.mjs +59 -18
- package/batteries/llm/claude_code_cli/adapter.mjs.map +1 -1
- package/batteries/llm/claude_code_cli/line_queue.d.ts +39 -0
- package/batteries/llm/claude_code_cli/message_id_state.d.ts +48 -0
- package/batteries/llm/claude_code_cli/types.d.ts +76 -0
- package/batteries/llm/claude_code_cli/validation.cjs +3 -0
- package/batteries/llm/claude_code_cli/validation.cjs.map +1 -1
- package/batteries/llm/claude_code_cli/validation.mjs +3 -0
- package/batteries/llm/claude_code_cli/validation.mjs.map +1 -1
- package/batteries/llm/claude_code_cli/wire.cjs.map +1 -1
- package/batteries/llm/claude_code_cli/wire.d.ts +45 -1
- package/batteries/llm/claude_code_cli/wire.mjs.map +1 -1
- package/batteries/llm/claude_code_cli/wrapper.d.ts +5 -4
- package/batteries/llm/gemini_generate_content/adapter.cjs +154 -13
- package/batteries/llm/gemini_generate_content/adapter.cjs.map +1 -1
- package/batteries/llm/gemini_generate_content/adapter.mjs +154 -13
- package/batteries/llm/gemini_generate_content/adapter.mjs.map +1 -1
- package/batteries/media/lint.cjs +1 -1
- package/batteries/media/lint.mjs +1 -1
- package/batteries/orchestration/executor.cjs +1 -1
- package/batteries/orchestration/executor.mjs +1 -1
- package/batteries/orchestration/forge.cjs +1 -1
- package/batteries/orchestration/forge.mjs +1 -1
- package/batteries/orchestration.cjs +5 -5
- package/batteries/orchestration.mjs +5 -5
- package/batteries/skills.cjs +1 -1
- package/batteries/skills.mjs +1 -1
- package/batteries/tools/scrapper.cjs +1 -1
- package/batteries/tools/scrapper.mjs +1 -1
- package/batteries/tools/searxng.cjs +1 -1
- package/batteries/tools/searxng.mjs +1 -1
- package/batteries/tools.cjs +2 -2
- package/batteries/tools.mjs +2 -2
- package/batteries/tts/native/adapter.cjs +1 -1
- package/batteries/tts/native/adapter.mjs +1 -1
- package/batteries/tts/native.cjs +1 -1
- package/batteries/tts/native.mjs +1 -1
- package/batteries/validation.cjs +1 -1
- package/batteries/validation.mjs +1 -1
- package/batteries/vector/chroma.cjs +1 -1
- package/batteries/vector/chroma.mjs +1 -1
- package/batteries/vector/clickhouse.cjs +1 -1
- package/batteries/vector/clickhouse.mjs +1 -1
- package/batteries/vector/cloudflare.cjs +1 -1
- package/batteries/vector/cloudflare.mjs +1 -1
- package/batteries/vector/conformance.cjs +59 -0
- package/batteries/vector/conformance.cjs.map +1 -1
- package/batteries/vector/conformance.mjs +59 -0
- package/batteries/vector/conformance.mjs.map +1 -1
- package/batteries/vector/couchbase.cjs +1 -1
- package/batteries/vector/couchbase.mjs +1 -1
- package/batteries/vector/duckdb.cjs +1 -1
- package/batteries/vector/duckdb.mjs +1 -1
- package/batteries/vector/elasticsearch.cjs +1 -1
- package/batteries/vector/elasticsearch.mjs +1 -1
- package/batteries/vector/hnswlib.cjs +1 -1
- package/batteries/vector/hnswlib.mjs +1 -1
- package/batteries/vector/in_memory.cjs +1 -1
- package/batteries/vector/in_memory.mjs +1 -1
- package/batteries/vector/lancedb.cjs +2 -2
- package/batteries/vector/lancedb.cjs.map +1 -1
- package/batteries/vector/lancedb.mjs +2 -2
- package/batteries/vector/lancedb.mjs.map +1 -1
- package/batteries/vector/mariadb.cjs +1 -1
- package/batteries/vector/mariadb.mjs +1 -1
- package/batteries/vector/milvus.cjs +1 -1
- package/batteries/vector/milvus.mjs +1 -1
- package/batteries/vector/opensearch.cjs +1 -1
- package/batteries/vector/opensearch.mjs +1 -1
- package/batteries/vector/oracle23ai.cjs +1 -1
- package/batteries/vector/oracle23ai.mjs +1 -1
- package/batteries/vector/orama.cjs +1 -1
- package/batteries/vector/orama.mjs +1 -1
- package/batteries/vector/pgvector.cjs +1 -1
- package/batteries/vector/pgvector.mjs +1 -1
- package/batteries/vector/pinecone.cjs +1 -1
- package/batteries/vector/pinecone.mjs +1 -1
- package/batteries/vector/qdrant.cjs +1 -1
- package/batteries/vector/qdrant.mjs +1 -1
- package/batteries/vector/redis.cjs +1 -1
- package/batteries/vector/redis.mjs +1 -1
- package/batteries/vector/s3vectors.cjs +1 -1
- package/batteries/vector/s3vectors.mjs +1 -1
- package/batteries/vector/sqlite_vec/index.d.ts +1 -1
- package/batteries/vector/sqlite_vec.cjs +20 -31
- package/batteries/vector/sqlite_vec.cjs.map +1 -1
- package/batteries/vector/sqlite_vec.mjs +20 -31
- package/batteries/vector/sqlite_vec.mjs.map +1 -1
- package/batteries/vector/typesense.cjs +1 -1
- package/batteries/vector/typesense.mjs +1 -1
- package/batteries/vector/vespa.cjs +1 -1
- package/batteries/vector/vespa.mjs +1 -1
- package/batteries/vector/weaviate.cjs +1 -1
- package/batteries/vector/weaviate.mjs +1 -1
- package/batteries/vector.cjs +1 -1
- package/batteries/vector.mjs +1 -1
- package/batteries.cjs +5 -5
- package/batteries.mjs +5 -5
- package/claude-code-cli-wrapper.cjs +104 -22
- package/claude-code-cli-wrapper.cjs.map +1 -1
- package/claude-code-cli-wrapper.mjs +104 -22
- package/claude-code-cli-wrapper.mjs.map +1 -1
- package/eslint/rules.cjs +1 -1
- package/eslint/rules.mjs +1 -1
- package/eslint.cjs +2 -2
- package/eslint.mjs +2 -2
- package/index.cjs +1 -1
- package/index.mjs +1 -1
- package/mcp/adk-docs-corpus.json +1 -4
- package/package.json +458 -458
- package/{scrapper-DiQ5FfDL.mjs → scrapper-BCdUm8c8.mjs} +2 -2
- package/{scrapper-DiQ5FfDL.mjs.map → scrapper-BCdUm8c8.mjs.map} +1 -1
- package/{scrapper-B8xG9lTD.cjs → scrapper-DlfxIYIo.cjs} +2 -2
- package/{scrapper-B8xG9lTD.cjs.map → scrapper-DlfxIYIo.cjs.map} +1 -1
- package/{searxng-BFTJ6rTE.mjs → searxng-B-LdaVUP.mjs} +2 -2
- package/{searxng-BFTJ6rTE.mjs.map → searxng-B-LdaVUP.mjs.map} +1 -1
- package/{searxng-EJhWRnIE.cjs → searxng-BbDk6GON.cjs} +2 -2
- package/{searxng-EJhWRnIE.cjs.map → searxng-BbDk6GON.cjs.map} +1 -1
- package/server.json +2 -2
- package/skills/adk-assembly/SKILL.md +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -15,6 +15,93 @@ you *when* you got it, not *what changed*: a `^` range will float across battery
|
|
|
15
15
|
breaking changes, so pin an exact version if you need stability and read the entry before
|
|
16
16
|
upgrading.
|
|
17
17
|
|
|
18
|
+
## 2026-09-28
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
|
|
22
|
+
- **`@nhtio/adk/batteries/vector/sqlite_vec` — `renameCollection` now throws instead of leaving a
|
|
23
|
+
collection that can't be searched** (closes issue #41). A collection is a `vec0` virtual table
|
|
24
|
+
plus shadow tables sqlite-vec creates alongside it (`<name>_chunks`, `_info`, `_rowids`,
|
|
25
|
+
`_vector_chunks00`). The adapter renamed the owning table and its `__meta` table with plain
|
|
26
|
+
`ALTER TABLE`. sqlite-vec 0.1.9 implements no `xRename` hook, so that succeeds but renames only
|
|
27
|
+
the virtual table's own entry and never moves its shadow tables, and a "successful" rename left
|
|
28
|
+
a collection that failed every subsequent search with `no such table: main.<new>_chunks`, with
|
|
29
|
+
no error at rename time. Finishing the job by hand isn't
|
|
30
|
+
possible either: the core shadow tables (`_chunks`, `_info`, `_rowids`) reject a direct rename
|
|
31
|
+
outright (`table <name>_chunks may not be altered`). `capabilities.rename` is now `false` and
|
|
32
|
+
`renameCollection` throws `E_VECTOR_STORE_UNSUPPORTED_OPERATION` up front, before touching anything.
|
|
33
|
+
**Callers who renamed a sqlite_vec collection previously got a broken collection with no indication
|
|
34
|
+
anything was wrong; they now get a clear error at the call site instead.** The workaround is the same
|
|
35
|
+
shape as any backend without in-place rename: create the new collection, copy the records across
|
|
36
|
+
with a filter scan (`.select('id', 'vector', 'document', 'metadata')`), verify the copy is complete,
|
|
37
|
+
then drop the old one — see the sqlite_vec entry in
|
|
38
|
+
[the adapter matrix](docs/batteries/vector/adapters.md) for the exact snippet and the requirement to
|
|
39
|
+
stop writes to the source for the whole operation. While in there, every SQL identifier the adapter
|
|
40
|
+
interpolates (collection and `__meta`
|
|
41
|
+
table names, across create/drop/upsert/search/delete) is now escaped against embedded double
|
|
42
|
+
quotes, so a collection name containing a `"` no longer produces a broken statement.
|
|
43
|
+
- **`@nhtio/adk/batteries/vector/lancedb` — `capabilities.rename` is now `false`, matching
|
|
44
|
+
`renameCollection`'s existing behavior** (closes issue #41). The adapter's `renameCollection`
|
|
45
|
+
always threw `E_VECTOR_STORE_UNSUPPORTED_OPERATION` — `connection.renameTable` is a LanceDB Cloud
|
|
46
|
+
feature that LanceDB OSS (what this adapter drives) rejects with `LanceDBError: not supported:
|
|
47
|
+
rename_table is not supported in LanceDB OSS` — but `capabilities.rename` still advertised `true`,
|
|
48
|
+
so a caller checking the capability before calling would wrongly conclude rename was safe to try.
|
|
49
|
+
|
|
50
|
+
### Internal
|
|
51
|
+
|
|
52
|
+
- **The vector-store conformance suite now exercises `renameCollection` against
|
|
53
|
+
`capabilities.rename`.** Every adapter advertising `rename: true` renames a live collection with
|
|
54
|
+
records in it and confirms the old name is gone, the new name is searchable, and further writes
|
|
55
|
+
land; every adapter advertising `rename: false` is confirmed to reject the call.
|
|
56
|
+
|
|
57
|
+
## 2026-09-25
|
|
58
|
+
|
|
59
|
+
### Fixed
|
|
60
|
+
|
|
61
|
+
- **`@nhtio/adk/batteries/llm/claude_code_cli` — the dispatch no longer hangs after `result` under
|
|
62
|
+
an Electron host** (closes issue #42). In an Electron main process the adapter spawned the
|
|
63
|
+
wrapper with Electron's own binary. Measured with bare Electron: without `ELECTRON_RUN_AS_NODE`,
|
|
64
|
+
or with the `RunAsNode` fuse off, that binary's event loop never drained, so the wrapper never
|
|
65
|
+
exited and the executor, which waited for that exit, never settled. The adapter now settles on
|
|
66
|
+
the terminal `result` event without waiting for the wrapper to exit, and shuts the wrapper down
|
|
67
|
+
in the background: `SIGTERM`, a bounded wait, then `SIGKILL`, then a kill of the `claude`
|
|
68
|
+
process group, so a force-killed wrapper cannot orphan it. The wrapper now waits for its pending
|
|
69
|
+
stdout writes before `process.exit(0)` instead of relying on the loop draining. Its 5-second
|
|
70
|
+
backstop stays armed through that wait, and it tolerates `EPIPE`. When the host is Electron
|
|
71
|
+
(`process.versions.electron`), the adapter sets `ELECTRON_RUN_AS_NODE=1` on the wrapper, and the
|
|
72
|
+
wrapper strips it again before spawning `claude`. New options: `autoDetectElectronHost`
|
|
73
|
+
(default `true`) turns this off; `wrapperExecPath` runs the wrapper with a different runtime,
|
|
74
|
+
such as a real `node`; `wrapperEnv` adds or overrides wrapper environment variables. An Electron
|
|
75
|
+
build with the `RunAsNode` fuse **off** cannot act as Node at all. It still settles now, but
|
|
76
|
+
set `wrapperExecPath` to a Node binary for the wrapper to run properly.
|
|
77
|
+
- **`@nhtio/adk/batteries/llm/claude_code_cli` — assistant message and thought ids no longer
|
|
78
|
+
collide** (closes issue #43). The wrapper named every assistant message `"message"`, and ids
|
|
79
|
+
restarted on every spawn, so the second dispatch iteration of a turn hit core's `stream
|
|
80
|
+
"message" is already complete` guard. Ids are now namespaced per executor invocation and
|
|
81
|
+
numbered per message within a spawn. The wrapper also handles its `claude` stdout lines
|
|
82
|
+
strictly in order: before, lines that arrived in one chunk could interleave their handlers and
|
|
83
|
+
mis-assign ids. Trade-off: a wrapper stdout write that never completes now also holds back the
|
|
84
|
+
lines after it, `result` included; `streamIdleTimeoutMs` still nacks that dispatch.
|
|
85
|
+
- **`@nhtio/adk/batteries/llm/gemini_generate_content` and `…/bedrock_converse` — the `retry`
|
|
86
|
+
option is now applied** (closes issues #44 and #45). Both adapters validated `retry` but always
|
|
87
|
+
sent exactly one request. They now retry transport failures, per-attempt timeouts and
|
|
88
|
+
`retriableStatuses` responses, using the same backoff, jitter and `Retry-After` handling as the
|
|
89
|
+
other HTTP batteries. Vendor rejections that no retry can fix fail at once: Gemini's
|
|
90
|
+
`thought_signature` error, and Bedrock's `toolConfig` and message-alternation errors. The
|
|
91
|
+
defaults match the sibling batteries (`maxAttempts: 1`, `baseDelayMs: 500`, `maxDelayMs:
|
|
92
|
+
30000`, `retriableStatuses: [429, 502, 503, 504]`, `honorRetryAfter: true`), so a caller who
|
|
93
|
+
doesn't set `retry` still gets a single attempt. `timeoutMs` now also covers reading the
|
|
94
|
+
response body, and each attempt's abort-signal link is disposed so listeners don't pile up on
|
|
95
|
+
the caller's signal.
|
|
96
|
+
|
|
97
|
+
### Internal
|
|
98
|
+
|
|
99
|
+
- **CI — the Node and browser smoke checks now run on merge requests.** Both
|
|
100
|
+
`Core … Functionality Smoke Check` jobs were master-only and skipped on merge commits, so no
|
|
101
|
+
release path ever ran them (a release lands as a merge commit). They now use the same MR-gated
|
|
102
|
+
rules as the other gates. The browser smoke also installs the `@toon-format/toon` peer, which
|
|
103
|
+
its `toon_to_json` converter spec needs.
|
|
104
|
+
|
|
18
105
|
## 2026-09-24
|
|
19
106
|
|
|
20
107
|
### Fixed
|
|
@@ -7,11 +7,12 @@ const require_thought = require("../../../thought-Dp3sMWW6.cjs");
|
|
|
7
7
|
const require_tool_call = require("../../../tool_call-B9px4W9k.cjs");
|
|
8
8
|
require("../../../common-CqetsItm.cjs");
|
|
9
9
|
require("../../../guards.cjs");
|
|
10
|
+
const require_lib_utils_retry = require("../../../lib/utils/retry.cjs");
|
|
10
11
|
const require_tool_parsers = require("../../../tool_parsers-8_qO0a_F.cjs");
|
|
11
12
|
const require_helpers = require("../../../helpers-DPlh_7Bn.cjs");
|
|
12
13
|
const require_batteries_llm_bedrock_converse_exceptions = require("./exceptions.cjs");
|
|
13
|
-
const require_batteries_llm_bedrock_converse_validation = require("./validation.cjs");
|
|
14
14
|
const require_batteries_llm_bedrock_converse_helpers = require("./helpers.cjs");
|
|
15
|
+
const require_batteries_llm_bedrock_converse_validation = require("./validation.cjs");
|
|
15
16
|
let luxon = require("luxon");
|
|
16
17
|
let js_sha256 = require("js-sha256");
|
|
17
18
|
let uuid = require("uuid");
|
|
@@ -206,32 +207,172 @@ var BedrockConverseAdapter = class BedrockConverseAdapter {
|
|
|
206
207
|
const url = `${base}/model/${encodeURIComponent(merged.model)}/${action}`;
|
|
207
208
|
const headers = { "Content-Type": "application/json" };
|
|
208
209
|
if (merged.apiKey) headers.Authorization = `Bearer ${merged.apiKey}`;
|
|
210
|
+
const retryCfg = {
|
|
211
|
+
maxAttempts: merged.retry?.maxAttempts ?? 1,
|
|
212
|
+
baseDelayMs: merged.retry?.baseDelayMs ?? 500,
|
|
213
|
+
maxDelayMs: merged.retry?.maxDelayMs ?? 3e4,
|
|
214
|
+
retriableStatuses: merged.retry?.retriableStatuses ?? [
|
|
215
|
+
429,
|
|
216
|
+
502,
|
|
217
|
+
503,
|
|
218
|
+
504
|
|
219
|
+
],
|
|
220
|
+
honorRetryAfter: merged.retry?.honorRetryAfter ?? true
|
|
221
|
+
};
|
|
209
222
|
const doFetch = merged.fetch ?? globalThis.fetch;
|
|
223
|
+
const maxAttempts = retryCfg.maxAttempts ?? 1;
|
|
224
|
+
let res;
|
|
225
|
+
let attempt = 1;
|
|
226
|
+
let disposeLink = () => {};
|
|
227
|
+
let rawText = "";
|
|
210
228
|
let parsed;
|
|
211
229
|
try {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
signal:
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
if (
|
|
221
|
-
|
|
230
|
+
while (attempt <= maxAttempts) {
|
|
231
|
+
if (ctx.abortSignal.aborted) return;
|
|
232
|
+
const internalController = new AbortController();
|
|
233
|
+
disposeLink();
|
|
234
|
+
const { signal: linkedSignal, dispose: disposeCurrentLink } = require_lib_utils_retry.linkAbortSignals([ctx.abortSignal, internalController.signal]);
|
|
235
|
+
disposeLink = disposeCurrentLink;
|
|
236
|
+
let timeoutHandle;
|
|
237
|
+
const timeoutMs = merged.timeoutMs ?? 0;
|
|
238
|
+
if (timeoutMs > 0) timeoutHandle = setTimeout(() => internalController.abort(), timeoutMs);
|
|
239
|
+
try {
|
|
240
|
+
res = await doFetch(url, {
|
|
241
|
+
method: "POST",
|
|
242
|
+
headers,
|
|
243
|
+
body: JSON.stringify(body),
|
|
244
|
+
signal: linkedSignal
|
|
245
|
+
});
|
|
246
|
+
rawText = await res.text();
|
|
247
|
+
if (timeoutHandle !== void 0) clearTimeout(timeoutHandle);
|
|
248
|
+
} catch (err) {
|
|
249
|
+
if (timeoutHandle !== void 0) clearTimeout(timeoutHandle);
|
|
250
|
+
if (ctx.abortSignal.aborted) return;
|
|
251
|
+
if (internalController.signal.aborted) {
|
|
252
|
+
helpers.log.warn({
|
|
253
|
+
kind: "request-timeout",
|
|
254
|
+
message: `Request timed out after ${timeoutMs}ms on attempt ${attempt}/${maxAttempts}`,
|
|
255
|
+
payload: {
|
|
256
|
+
timeoutMs,
|
|
257
|
+
attempt,
|
|
258
|
+
maxAttempts
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
if (attempt < maxAttempts) {
|
|
262
|
+
const delay = require_lib_utils_retry.computeBackoff(attempt, retryCfg);
|
|
263
|
+
helpers.log.debug({
|
|
264
|
+
kind: "retry-attempt",
|
|
265
|
+
message: `Retrying after request timeout in ~${delay}ms (attempt ${attempt + 1}/${maxAttempts})`,
|
|
266
|
+
payload: {
|
|
267
|
+
reason: "request-timeout",
|
|
268
|
+
delayMs: delay,
|
|
269
|
+
attempt: attempt + 1,
|
|
270
|
+
maxAttempts
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
await require_lib_utils_retry.sleepWithJitter(delay, ctx.abortSignal);
|
|
274
|
+
attempt += 1;
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
ctx.nack(new require_batteries_llm_bedrock_converse_exceptions.E_CONVERSE_STREAM_ERROR([`Request timed out after ${timeoutMs}ms`]));
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
helpers.log.error({
|
|
281
|
+
kind: "transport-error",
|
|
282
|
+
message: `Transport failure on attempt ${attempt}/${maxAttempts}: ${require_guards.isError(err) ? err.message : String(err)}`,
|
|
283
|
+
payload: {
|
|
284
|
+
attempt,
|
|
285
|
+
maxAttempts,
|
|
286
|
+
detail: require_guards.isError(err) ? err.message : String(err)
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
if (attempt < maxAttempts) {
|
|
290
|
+
const delay = require_lib_utils_retry.computeBackoff(attempt, retryCfg);
|
|
291
|
+
helpers.log.debug({
|
|
292
|
+
kind: "retry-attempt",
|
|
293
|
+
message: `Retrying after transport failure in ~${delay}ms (attempt ${attempt + 1}/${maxAttempts})`,
|
|
294
|
+
payload: {
|
|
295
|
+
reason: "transport-error",
|
|
296
|
+
delayMs: delay,
|
|
297
|
+
attempt: attempt + 1,
|
|
298
|
+
maxAttempts
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
await require_lib_utils_retry.sleepWithJitter(delay, ctx.abortSignal);
|
|
302
|
+
attempt += 1;
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
ctx.nack(new require_batteries_llm_bedrock_converse_exceptions.E_CONVERSE_STREAM_ERROR([require_guards.isError(err) ? err.message : String(err)]));
|
|
222
306
|
return;
|
|
223
307
|
}
|
|
224
|
-
if (
|
|
225
|
-
|
|
308
|
+
if (!res.ok) {
|
|
309
|
+
if (/toolConfig/i.test(rawText)) {
|
|
310
|
+
ctx.nack(new require_batteries_llm_bedrock_converse_exceptions.E_CONVERSE_MISSING_TOOL_CONFIG([rawText.slice(0, 400)]));
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
if (/alternat|consecutive|must alternate/i.test(rawText)) {
|
|
314
|
+
ctx.nack(new require_batteries_llm_bedrock_converse_exceptions.E_CONVERSE_ALTERNATION_VIOLATION([rawText.slice(0, 400)]));
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
const status = res.status;
|
|
318
|
+
const retriable = (retryCfg.retriableStatuses ?? [
|
|
319
|
+
429,
|
|
320
|
+
502,
|
|
321
|
+
503,
|
|
322
|
+
504
|
|
323
|
+
]).includes(status);
|
|
324
|
+
if (retriable && attempt < maxAttempts) {
|
|
325
|
+
let delay = require_lib_utils_retry.computeBackoff(attempt, retryCfg);
|
|
326
|
+
let retryAfterMs;
|
|
327
|
+
if (retryCfg.honorRetryAfter !== false) {
|
|
328
|
+
const ra = res.headers.get("Retry-After");
|
|
329
|
+
if (ra) {
|
|
330
|
+
const raMs = require_lib_utils_retry.parseRetryAfter(ra);
|
|
331
|
+
if (raMs > 0) {
|
|
332
|
+
retryAfterMs = raMs;
|
|
333
|
+
delay = Math.min(Math.max(delay, raMs), retryCfg.maxDelayMs ?? 3e4);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
helpers.log.warn({
|
|
338
|
+
kind: "retry-attempt",
|
|
339
|
+
message: `HTTP ${status} on attempt ${attempt}/${maxAttempts}; retrying in ~${delay}ms`,
|
|
340
|
+
payload: {
|
|
341
|
+
reason: "http-status",
|
|
342
|
+
status,
|
|
343
|
+
delayMs: delay,
|
|
344
|
+
...retryAfterMs !== void 0 ? { retryAfterMs } : {},
|
|
345
|
+
attempt: attempt + 1,
|
|
346
|
+
maxAttempts
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
await require_lib_utils_retry.sleepWithJitter(delay, ctx.abortSignal);
|
|
350
|
+
attempt += 1;
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
helpers.log.error({
|
|
354
|
+
kind: "http-error",
|
|
355
|
+
message: `HTTP ${status} (terminal): ${rawText.slice(0, 256)}`,
|
|
356
|
+
payload: {
|
|
357
|
+
status,
|
|
358
|
+
body: rawText,
|
|
359
|
+
attempt,
|
|
360
|
+
maxAttempts,
|
|
361
|
+
retriable
|
|
362
|
+
}
|
|
363
|
+
});
|
|
364
|
+
ctx.nack(new require_batteries_llm_bedrock_converse_exceptions.E_CONVERSE_REQUEST_FAILED([status, rawText.slice(0, 400)]));
|
|
226
365
|
return;
|
|
227
366
|
}
|
|
228
|
-
|
|
229
|
-
return;
|
|
367
|
+
break;
|
|
230
368
|
}
|
|
231
|
-
|
|
369
|
+
if (!res) return;
|
|
370
|
+
parsed = JSON.parse(rawText);
|
|
232
371
|
} catch (err) {
|
|
233
372
|
ctx.nack(new require_batteries_llm_bedrock_converse_exceptions.E_CONVERSE_STREAM_ERROR([require_guards.isError(err) ? err.message : String(err)]));
|
|
234
373
|
return;
|
|
374
|
+
} finally {
|
|
375
|
+
disposeLink();
|
|
235
376
|
}
|
|
236
377
|
const { text, reasoning, toolUses, stopReason } = require_batteries_llm_bedrock_converse_helpers.extractConverseGeneration(parsed);
|
|
237
378
|
const responseId = (0, uuid.v6)();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.cjs","names":["#baseline"],"sources":["../../../../src/batteries/llm/bedrock_converse/adapter.ts"],"sourcesContent":["/**\n * Cross-environment executor adapter for AWS Bedrock's native Converse API.\n *\n * @module @nhtio/adk/batteries/llm/bedrock_converse/adapter\n *\n * @remarks\n * Targets `POST {baseURL}/model/{modelId}/converse` (and `/converse-stream` when `stream` is set)\n * over plain HTTPS with a Bedrock API key (`Authorization: Bearer ABSK…`). Deliberately NO AWS SDK\n * and no SigV4 signer: the battery must stay cross-environment and dependency-light, and a bearer\n * key removes the only reason to pull in a signer.\n *\n * Why a native battery rather than pointing `openai_chat_completions` at a Converse-backed gateway:\n * Converse is a content-BLOCK protocol with strict role alternation, a required `toolConfig`\n * whenever tool blocks appear, and tool results carried on `user` turns. A gateway must repair all\n * of that on your behalf — most notably by MERGING consecutive same-role turns — and that repair is\n * invisible in the response. For ordinary use it is fine; for anything that needs to know what the\n * VENDOR received it is fatal, because a gateway's fix is indistinguishable from vendor tolerance.\n * See the validation battery's \"Which API surface a rule applies to\" guide, and\n * {@link BedrockConverseAdapterOptions.alternationPolicy} for the `'reject'` escape hatch that lets\n * Converse's own error surface.\n *\n * Options layer as in every other battery: constructor baseline → `executor()` overrides →\n * per-iteration `ctx.stash.bedrockConverse`, re-validated each iteration.\n */\n\nimport { DateTime } from 'luxon'\nimport { sha256 } from 'js-sha256'\nimport { v6 as uuidv6 } from 'uuid'\nimport { validateOptions } from './validation'\nimport { normalizeToolName } from '../chat_common/helpers'\nimport { isError, isObject, isInstanceOf } from '@nhtio/adk/guards'\nimport { resolveToolCallParser } from '../chat_common/tool_parsers'\nimport { canonicalStringify } from '../../../lib/utils/canonical_json'\nimport { Media, Message, Thought, Tokenizable, ToolCall } from '@nhtio/adk/common'\nimport {\n DEFAULT_CONVERSE_BUCKET_ORDER,\n buildConverseRequest,\n extractConverseGeneration,\n mediaToConverseImage,\n renderConverseToolResult,\n toolsToConverseTools,\n} from './helpers'\nimport {\n E_BEDROCK_CONVERSE_CONTEXT_OVERFLOW,\n E_INVALID_BEDROCK_CONVERSE_OPTIONS,\n E_CONVERSE_ALTERNATION_VIOLATION,\n E_CONVERSE_INVALID_TOOL_INPUT,\n E_CONVERSE_MISSING_TOOL_CONFIG,\n E_CONVERSE_REQUEST_FAILED,\n E_CONVERSE_STREAM_ERROR,\n} from './exceptions'\nimport {\n descriptionToChatCompletionsJsonSchema,\n filterThoughts,\n renderChatCompletionsSystemPrompt,\n renderFirstPartyRetrievables,\n renderMemories,\n renderRetrievableSafetyDirective,\n renderRetrievables,\n renderStandingInstructions,\n renderThirdPartyPrivateRetrievables,\n renderThirdPartyPublicRetrievables,\n renderThought,\n renderTrustedContent,\n renderUntrustedContent,\n} from '../chat_common/helpers'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { TokenEncoding, TokenEncodingId } from '@nhtio/adk/types'\nimport type { DispatchExecutorFn, DispatchExecutorHelpers } from '@nhtio/adk/types'\nimport type { ArtifactTool, Memory, SpooledArtifact, Tool } from '@nhtio/adk/common'\nimport type {\n BedrockConverseAdapterOptions,\n BedrockConverseHelpers,\n ConverseResponse,\n} from './types'\n\nconst nowIso = (): string => DateTime.now().toISO() ?? new Date().toISOString()\n\nconst DEFAULT_REGION = 'us-east-1'\n\nconst estimateTokensOf = async (\n value: { estimateTokens: (encoding: TokenEncoding) => number | Promise<number> },\n encoding: TokenEncodingId\n): Promise<number> => Promise.resolve(value.estimateTokens(encoding as TokenEncoding))\n\nconst computeChecksum = (tool: string, args: Record<string, unknown>): string =>\n sha256(`${tool}:${canonicalStringify(args)}`)\n\n/** Merge the three option layers, later winning. */\nconst mergeOptions = (\n ...layers: Array<Partial<BedrockConverseAdapterOptions> | undefined>\n): Partial<BedrockConverseAdapterOptions> => {\n const out: Record<string, unknown> = {}\n for (const layer of layers) {\n if (!layer) continue\n for (const [k, v] of Object.entries(layer)) if (v !== undefined) out[k] = v\n }\n return out as Partial<BedrockConverseAdapterOptions>\n}\n\n/** Fill every injectable helper, preferring the caller's override. */\nconst resolveHelpers = (\n overrides: Partial<BedrockConverseHelpers> | undefined\n): BedrockConverseHelpers => {\n const src = (overrides ?? {}) as Record<string, unknown>\n const pick = <T>(key: string, fallback: T): T => (src[key] as T | undefined) ?? fallback\n return {\n descriptionToChatCompletionsJsonSchema: pick(\n 'descriptionToChatCompletionsJsonSchema',\n descriptionToChatCompletionsJsonSchema\n ),\n renderUntrustedContent: pick('renderUntrustedContent', renderUntrustedContent),\n renderTrustedContent: pick('renderTrustedContent', renderTrustedContent),\n renderStandingInstructions: pick('renderStandingInstructions', renderStandingInstructions),\n renderMemories: pick('renderMemories', renderMemories),\n renderRetrievables: pick('renderRetrievables', renderRetrievables),\n renderRetrievableSafetyDirective: pick(\n 'renderRetrievableSafetyDirective',\n renderRetrievableSafetyDirective\n ),\n renderFirstPartyRetrievables: pick(\n 'renderFirstPartyRetrievables',\n renderFirstPartyRetrievables\n ),\n renderThirdPartyPublicRetrievables: pick(\n 'renderThirdPartyPublicRetrievables',\n renderThirdPartyPublicRetrievables\n ),\n renderThirdPartyPrivateRetrievables: pick(\n 'renderThirdPartyPrivateRetrievables',\n renderThirdPartyPrivateRetrievables\n ),\n renderThought: pick('renderThought', renderThought),\n filterThoughts: pick('filterThoughts', filterThoughts),\n renderChatCompletionsSystemPrompt: pick(\n 'renderChatCompletionsSystemPrompt',\n renderChatCompletionsSystemPrompt\n ),\n toolsToConverseTools: pick('toolsToConverseTools', toolsToConverseTools),\n renderConverseToolResult: pick('renderConverseToolResult', renderConverseToolResult),\n buildConverseRequest: pick('buildConverseRequest', buildConverseRequest),\n } as BedrockConverseHelpers\n}\n\n/**\n * Native Bedrock Converse executor adapter.\n *\n * @example\n * ```ts\n * const adapter = new BedrockConverseAdapter({\n * model: 'us.amazon.nova-2-lite-v1:0',\n * apiKey: process.env.AWS_BEARER_TOKEN_BEDROCK,\n * region: 'us-east-1',\n * })\n * const runner = new TurnRunner({ executorCallback: adapter.executor(), ... })\n * ```\n */\nexport class BedrockConverseAdapter {\n /** Per-iteration override key on `ctx.stash`. */\n public static readonly STASH_KEY = 'bedrockConverse' as const\n\n readonly #baseline: BedrockConverseAdapterOptions\n\n /**\n * @param options - Constructor-baseline options, re-validated each iteration after overrides merge.\n * @throws {@link E_INVALID_BEDROCK_CONVERSE_OPTIONS} when `options` is invalid.\n */\n constructor(options: unknown) {\n this.#baseline = validateOptions(options)\n }\n\n /** Narrowing guard for cross-realm instances. */\n public static isBedrockConverseAdapter(value: unknown): value is BedrockConverseAdapter {\n return isInstanceOf(value, 'BedrockConverseAdapter', BedrockConverseAdapter)\n }\n\n /**\n * Build a {@link DispatchExecutorFn} bound to the baseline plus optional executor-scope overrides.\n *\n * @param overrides - Higher precedence than the baseline, lower than `ctx.stash`.\n */\n executor(overrides?: Partial<BedrockConverseAdapterOptions>): DispatchExecutorFn {\n const baseline = this.#baseline\n const adapterClass = BedrockConverseAdapter\n return async (ctx: DispatchContext, helpers: DispatchExecutorHelpers): Promise<void> => {\n const warn = (message: string): void => {\n helpers.log.warn({ kind: 'helper-warning', message })\n }\n\n const stashRaw = ctx.stash.get(adapterClass.STASH_KEY, {}) as unknown\n const stashOverrides = isObject(stashRaw)\n ? (stashRaw as Partial<BedrockConverseAdapterOptions>)\n : {}\n const merged = validateOptions(mergeOptions(baseline, overrides, stashOverrides))\n if (\n merged.tokenEncoding !== undefined &&\n merged.tokenEncoding !== null &&\n merged.contextWindow === undefined\n ) {\n throw new E_INVALID_BEDROCK_CONVERSE_OPTIONS([\n 'tokenEncoding is non-null but contextWindow is undefined',\n ])\n }\n const resolved = resolveHelpers(merged.helpers)\n const selfIdentity = 'assistant'\n const dispatchStreamId = uuidv6()\n\n // Converse wants toolResult.content[] blocks, so results render ahead of assembly.\n const renderedToolCallResults = new Map<\n ToolCall,\n Array<{ text?: string; json?: Record<string, unknown> }>\n >()\n for (const tc of ctx.turnToolCalls) {\n renderedToolCallResults.set(\n tc,\n await resolved.renderConverseToolResult({\n toolCall: tc,\n results: tc.results as never,\n tool: ctx.tools.get(tc.tool) as Tool | ArtifactTool | undefined,\n renderUntrustedContent: resolved.renderUntrustedContent,\n renderTrustedContent: resolved.renderTrustedContent,\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n warn,\n })\n )\n }\n\n if (\n merged.tokenEncoding !== undefined &&\n merged.tokenEncoding !== null &&\n merged.contextWindow !== undefined\n ) {\n const encoding = merged.tokenEncoding\n let total = await estimateTokensOf(ctx.systemPrompt, encoding)\n for (const value of ctx.standingInstructions)\n total += await estimateTokensOf(value, encoding)\n for (const memory of ctx.turnMemories as Set<Memory>)\n total += await estimateTokensOf(memory.content, encoding)\n for (const retrievable of ctx.turnRetrievables)\n total += await estimateTokensOf(\n retrievable.inline\n ? (retrievable.content as any)\n : new Tokenizable(`[Reference available: ${retrievable.id}]`),\n encoding\n )\n for (const message of ctx.turnMessages) {\n if (message.content !== undefined)\n total += await estimateTokensOf(message.content, encoding)\n }\n for (const thought of ctx.turnThoughts)\n total += await estimateTokensOf(thought.content, encoding)\n for (const result of renderedToolCallResults.values()) {\n total += await estimateTokensOf(new Tokenizable(JSON.stringify(result)), encoding)\n }\n const tools = ctx.tools.visible()\n if (tools.length > 0) {\n // Tool DECLARATIONS: the Bedrock wire ships tools as an array, which the PROVIDER\n // serializes server-side into the model's own format. Tally the tokens of the wire\n // tools JSON (`JSON.stringify`) as an honest FLOOR — a truthful lower bound. We add\n // a safe 10% margin to cover JSON structural overhead and nested formatting.\n const toolTokens = await estimateTokensOf(\n new Tokenizable(JSON.stringify(resolved.toolsToConverseTools(tools))),\n encoding\n )\n total += Math.ceil(toolTokens * 1.1)\n }\n if (total + (merged.maxTokens ?? 0) > merged.contextWindow) {\n throw new E_BEDROCK_CONVERSE_CONTEXT_OVERFLOW([\n total + (merged.maxTokens ?? 0),\n merged.contextWindow,\n encoding,\n ])\n }\n }\n\n const request = await resolved.buildConverseRequest({\n systemPrompt: ctx.systemPrompt,\n standingInstructions: ctx.standingInstructions,\n memories: ctx.turnMemories,\n retrievables: ctx.turnRetrievables,\n messages: ctx.turnMessages,\n thoughts: ctx.turnThoughts,\n toolCalls: ctx.turnToolCalls,\n tools: ctx.tools,\n renderedToolCallResults,\n bucketOrder: merged.bucketOrder ?? (DEFAULT_CONVERSE_BUCKET_ORDER as never),\n selfIdentity,\n thoughtSurfacing: merged.thoughtSurfacing ?? 'all-self',\n replayCompatibility: [],\n alternationPolicy: merged.alternationPolicy ?? 'merge',\n helpers: resolved,\n decodeMedia: mediaToConverseImage,\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy,\n warn,\n })\n\n const inferenceConfig = {\n ...(merged.maxTokens !== undefined ? { maxTokens: merged.maxTokens } : {}),\n ...(merged.temperature !== undefined ? { temperature: merged.temperature } : {}),\n ...(merged.topP !== undefined ? { topP: merged.topP } : {}),\n ...(merged.stopSequences ? { stopSequences: merged.stopSequences } : {}),\n }\n const body = {\n ...request,\n ...(merged.toolChoice && request.toolConfig\n ? { toolConfig: { ...request.toolConfig, toolChoice: merged.toolChoice } }\n : {}),\n ...(Object.keys(inferenceConfig).length > 0 ? { inferenceConfig } : {}),\n ...(merged.additionalModelRequestFields\n ? { additionalModelRequestFields: merged.additionalModelRequestFields }\n : {}),\n }\n\n // The EXACT body about to be POSTed. An ADK-control key — stripped from the wire request.\n if (merged.onPromptAssembled) {\n try {\n merged.onPromptAssembled({\n battery: 'bedrock_converse',\n kind: 'request-body',\n messages: body.messages,\n tools: body.toolConfig?.tools,\n requestBody: body,\n streamed: merged.stream === true,\n streamId: dispatchStreamId,\n })\n } catch {\n /* observer errors are non-fatal */\n }\n }\n\n const base = (\n merged.baseURL ?? `https://bedrock-runtime.${merged.region ?? DEFAULT_REGION}.amazonaws.com`\n ).replace(/\\/$/, '')\n const action = merged.stream === true ? 'converse-stream' : 'converse'\n // The model id contains ':' and '.', both legal in a path segment but worth encoding so a\n // future id with a reserved character does not silently reshape the URL.\n const url = `${base}/model/${encodeURIComponent(merged.model)}/${action}`\n const headers: Record<string, string> = { 'Content-Type': 'application/json' }\n if (merged.apiKey) headers.Authorization = `Bearer ${merged.apiKey}`\n\n const doFetch = merged.fetch ?? globalThis.fetch\n let parsed: ConverseResponse\n try {\n const res = await doFetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: merged.timeoutMs ? AbortSignal.timeout(merged.timeoutMs) : ctx.abortSignal,\n })\n const text = await res.text()\n if (!res.ok) {\n // Classify the two Converse-specific rejections: both are actionable, and both otherwise\n // arrive as an undifferentiated ValidationException.\n if (/toolConfig/i.test(text)) {\n ctx.nack(new E_CONVERSE_MISSING_TOOL_CONFIG([text.slice(0, 400)]))\n return\n }\n if (/alternat|consecutive|must alternate/i.test(text)) {\n ctx.nack(new E_CONVERSE_ALTERNATION_VIOLATION([text.slice(0, 400)]))\n return\n }\n ctx.nack(new E_CONVERSE_REQUEST_FAILED([res.status, text.slice(0, 400)]))\n return\n }\n parsed = JSON.parse(text) as ConverseResponse\n } catch (err) {\n ctx.nack(new E_CONVERSE_STREAM_ERROR([isError(err) ? err.message : String(err)]))\n return\n }\n\n const { text, reasoning, toolUses, stopReason } = extractConverseGeneration(parsed)\n const responseId = uuidv6()\n\n if (text.length > 0) {\n const messageId = `${responseId}:message`\n helpers.reportMessage(messageId, text, { isComplete: true })\n await ctx.storeMessage(\n new Message({\n id: messageId,\n role: 'assistant',\n content: text,\n identity: selfIdentity,\n createdAt: nowIso(),\n updatedAt: nowIso(),\n })\n )\n }\n if (reasoning.length > 0) {\n const thoughtId = `${responseId}:thought`\n helpers.reportThought(thoughtId, reasoning, { isComplete: true })\n await ctx.storeThought(\n new Thought({\n id: thoughtId,\n content: reasoning,\n identity: selfIdentity,\n createdAt: nowIso(),\n updatedAt: nowIso(),\n })\n )\n }\n\n // Fallback recovery is consulted ONLY when the provider returned no structured tool use, so\n // a native toolUse always wins over a parsed one.\n const calls = toolUses.map((t) => ({ id: t.toolUseId, name: t.name, args: t.input }))\n if (calls.length === 0 && merged.localToolCallParser !== undefined && text.length > 0) {\n const parser = resolveToolCallParser(merged.localToolCallParser)\n const recovered = parser(text, { toolNames: ctx.tools.all().map((t) => t.name) })\n for (const call of recovered.calls) {\n calls.push({\n id: uuidv6(),\n name: call.name,\n args: (call.arguments ?? {}) as Record<string, unknown>,\n })\n }\n }\n\n if (merged.onRawGeneration) {\n try {\n merged.onRawGeneration({\n rawText: text,\n cleanedText: text,\n reasoning: reasoning.length > 0 ? [reasoning] : [],\n toolCalls: calls.map((c) => ({ name: c.name, arguments: c.args as never })),\n streamed: merged.stream === true,\n streamId: dispatchStreamId,\n })\n } catch {\n /* observer errors are non-fatal */\n }\n }\n\n if (calls.length === 0) {\n helpers.log.trace({\n kind: 'converse-finish',\n message: `generation ended with stopReason=${stopReason ?? 'unknown'} and no tool use`,\n payload: { stopReason: stopReason ?? 'unknown' },\n })\n if (merged.autoAck) ctx.ack()\n return\n }\n\n for (const call of calls) {\n if (ctx.abortSignal.aborted) return\n // Resolve once at ingress; Converse sanitises only when rendering, so this preserves the\n // filtered id consistently for reporting, persistence, and any spool key.\n const callId = merged.toolCallIdFilter?.(call.id, ctx) ?? call.id\n const toolName = normalizeToolName(call.name)\n const tool = ctx.tools.get(toolName) as Tool | ArtifactTool | undefined\n const completedAt = nowIso()\n\n if (!isObject(call.args)) {\n const results = new Tokenizable(\n new E_CONVERSE_INVALID_TOOL_INPUT([JSON.stringify(call.args)]).message\n )\n helpers.reportToolCall(callId, { tool: toolName, args: {} })\n helpers.reportToolCall(callId, { results, isError: true, isComplete: true })\n await ctx.storeToolCall(\n new ToolCall({\n id: callId,\n tool: toolName,\n args: {},\n checksum: computeChecksum(toolName, {}),\n isComplete: true,\n isError: true,\n results,\n createdAt: completedAt,\n updatedAt: completedAt,\n completedAt,\n })\n )\n continue\n }\n\n if (!tool) {\n const available = ctx.tools\n .all()\n .map((t) => t.name)\n .sort()\n const results = new Tokenizable(\n available.length > 0\n ? `Tool not found: ${toolName}. Available tools: ${available.join(', ')}.`\n : `Tool not found: ${toolName}. No tools are available this turn.`\n )\n helpers.reportToolCall(callId, { tool: toolName, args: call.args })\n helpers.reportToolCall(callId, { results, isError: true, isComplete: true })\n await ctx.storeToolCall(\n new ToolCall({\n id: callId,\n tool: toolName,\n args: call.args,\n checksum: computeChecksum(toolName, call.args),\n isComplete: true,\n isError: true,\n results,\n createdAt: completedAt,\n updatedAt: completedAt,\n completedAt,\n })\n )\n continue\n }\n\n helpers.reportToolCall(callId, { tool: tool.name, args: call.args })\n let results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[] =\n new Tokenizable('')\n let isToolError = false\n try {\n const raw = await tool.executor(ctx)(call.args)\n results = Tokenizable.isTokenizable(raw)\n ? raw\n : new Tokenizable(typeof raw === 'string' ? raw : JSON.stringify(raw ?? ''))\n } catch (err) {\n isToolError = true\n results = new Tokenizable(isError(err) ? err.message : String(err))\n }\n const finishedAt = nowIso()\n helpers.reportToolCall(callId, { results, isError: isToolError, isComplete: true })\n await ctx.storeToolCall(\n new ToolCall({\n id: callId,\n tool: tool.name,\n args: call.args,\n checksum: computeChecksum(tool.name, call.args),\n isComplete: true,\n isError: isToolError,\n results,\n createdAt: finishedAt,\n updatedAt: finishedAt,\n completedAt: finishedAt,\n })\n )\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,IAAM,eAAuB,MAAA,SAAS,IAAI,EAAE,MAAM,sBAAK,IAAI,KAAK,GAAE,YAAY;AAE9E,IAAM,iBAAiB;AAEvB,IAAM,mBAAmB,OACvB,OACA,aACoB,QAAQ,QAAQ,MAAM,eAAe,QAAyB,CAAC;AAErF,IAAM,mBAAmB,MAAc,UAAA,GAAA,UAAA,QAC9B,GAAG,KAAK,GAAG,yBAAA,mBAAmB,IAAI,GAAG;;AAG9C,IAAM,gBACJ,GAAG,WACwC;CAC3C,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,CAAC,OAAO;EACZ,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,KAAK,GAAG,IAAI,MAAM,KAAA,GAAW,IAAI,KAAK;CAC5E;CACA,OAAO;AACT;;AAGA,IAAM,kBACJ,cAC2B;CAC3B,MAAM,MAAO,aAAa,CAAC;CAC3B,MAAM,QAAW,KAAa,aAAoB,IAAI,QAA0B;CAChF,OAAO;EACL,wCAAwC,KACtC,0CACA,gBAAA,sCACF;EACA,wBAAwB,KAAK,0BAA0B,gBAAA,sBAAsB;EAC7E,sBAAsB,KAAK,wBAAwB,gBAAA,oBAAoB;EACvE,4BAA4B,KAAK,8BAA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|
1
|
+
{"version":3,"file":"adapter.cjs","names":["#baseline"],"sources":["../../../../src/batteries/llm/bedrock_converse/adapter.ts"],"sourcesContent":["/**\n * Cross-environment executor adapter for AWS Bedrock's native Converse API.\n *\n * @module @nhtio/adk/batteries/llm/bedrock_converse/adapter\n *\n * @remarks\n * Targets `POST {baseURL}/model/{modelId}/converse` (and `/converse-stream` when `stream` is set)\n * over plain HTTPS with a Bedrock API key (`Authorization: Bearer ABSK…`). Deliberately NO AWS SDK\n * and no SigV4 signer: the battery must stay cross-environment and dependency-light, and a bearer\n * key removes the only reason to pull in a signer.\n *\n * Why a native battery rather than pointing `openai_chat_completions` at a Converse-backed gateway:\n * Converse is a content-BLOCK protocol with strict role alternation, a required `toolConfig`\n * whenever tool blocks appear, and tool results carried on `user` turns. A gateway must repair all\n * of that on your behalf — most notably by MERGING consecutive same-role turns — and that repair is\n * invisible in the response. For ordinary use it is fine; for anything that needs to know what the\n * VENDOR received it is fatal, because a gateway's fix is indistinguishable from vendor tolerance.\n * See the validation battery's \"Which API surface a rule applies to\" guide, and\n * {@link BedrockConverseAdapterOptions.alternationPolicy} for the `'reject'` escape hatch that lets\n * Converse's own error surface.\n *\n * Options layer as in every other battery: constructor baseline → `executor()` overrides →\n * per-iteration `ctx.stash.bedrockConverse`, re-validated each iteration.\n */\n\nimport { DateTime } from 'luxon'\nimport { sha256 } from 'js-sha256'\nimport { v6 as uuidv6 } from 'uuid'\nimport { validateOptions } from './validation'\nimport { normalizeToolName } from '../chat_common/helpers'\nimport { isError, isObject, isInstanceOf } from '@nhtio/adk/guards'\nimport { resolveToolCallParser } from '../chat_common/tool_parsers'\nimport { canonicalStringify } from '../../../lib/utils/canonical_json'\nimport { Media, Message, Thought, Tokenizable, ToolCall } from '@nhtio/adk/common'\nimport {\n computeBackoff,\n sleepWithJitter,\n parseRetryAfter,\n linkAbortSignals,\n} from '../../../lib/utils/retry'\nimport {\n DEFAULT_CONVERSE_BUCKET_ORDER,\n buildConverseRequest,\n extractConverseGeneration,\n mediaToConverseImage,\n renderConverseToolResult,\n toolsToConverseTools,\n} from './helpers'\nimport {\n E_BEDROCK_CONVERSE_CONTEXT_OVERFLOW,\n E_INVALID_BEDROCK_CONVERSE_OPTIONS,\n E_CONVERSE_ALTERNATION_VIOLATION,\n E_CONVERSE_INVALID_TOOL_INPUT,\n E_CONVERSE_MISSING_TOOL_CONFIG,\n E_CONVERSE_REQUEST_FAILED,\n E_CONVERSE_STREAM_ERROR,\n} from './exceptions'\nimport {\n descriptionToChatCompletionsJsonSchema,\n filterThoughts,\n renderChatCompletionsSystemPrompt,\n renderFirstPartyRetrievables,\n renderMemories,\n renderRetrievableSafetyDirective,\n renderRetrievables,\n renderStandingInstructions,\n renderThirdPartyPrivateRetrievables,\n renderThirdPartyPublicRetrievables,\n renderThought,\n renderTrustedContent,\n renderUntrustedContent,\n} from '../chat_common/helpers'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { TokenEncoding, TokenEncodingId } from '@nhtio/adk/types'\nimport type { DispatchExecutorFn, DispatchExecutorHelpers } from '@nhtio/adk/types'\nimport type { ArtifactTool, Memory, SpooledArtifact, Tool } from '@nhtio/adk/common'\nimport type {\n BedrockConverseAdapterOptions,\n BedrockConverseHelpers,\n ChatCompletionsRetryConfig,\n ConverseResponse,\n} from './types'\n\nconst nowIso = (): string => DateTime.now().toISO() ?? new Date().toISOString()\n\nconst DEFAULT_REGION = 'us-east-1'\n\nconst estimateTokensOf = async (\n value: { estimateTokens: (encoding: TokenEncoding) => number | Promise<number> },\n encoding: TokenEncodingId\n): Promise<number> => Promise.resolve(value.estimateTokens(encoding as TokenEncoding))\n\nconst computeChecksum = (tool: string, args: Record<string, unknown>): string =>\n sha256(`${tool}:${canonicalStringify(args)}`)\n\n/** Merge the three option layers, later winning. */\nconst mergeOptions = (\n ...layers: Array<Partial<BedrockConverseAdapterOptions> | undefined>\n): Partial<BedrockConverseAdapterOptions> => {\n const out: Record<string, unknown> = {}\n for (const layer of layers) {\n if (!layer) continue\n for (const [k, v] of Object.entries(layer)) if (v !== undefined) out[k] = v\n }\n return out as Partial<BedrockConverseAdapterOptions>\n}\n\n/** Fill every injectable helper, preferring the caller's override. */\nconst resolveHelpers = (\n overrides: Partial<BedrockConverseHelpers> | undefined\n): BedrockConverseHelpers => {\n const src = (overrides ?? {}) as Record<string, unknown>\n const pick = <T>(key: string, fallback: T): T => (src[key] as T | undefined) ?? fallback\n return {\n descriptionToChatCompletionsJsonSchema: pick(\n 'descriptionToChatCompletionsJsonSchema',\n descriptionToChatCompletionsJsonSchema\n ),\n renderUntrustedContent: pick('renderUntrustedContent', renderUntrustedContent),\n renderTrustedContent: pick('renderTrustedContent', renderTrustedContent),\n renderStandingInstructions: pick('renderStandingInstructions', renderStandingInstructions),\n renderMemories: pick('renderMemories', renderMemories),\n renderRetrievables: pick('renderRetrievables', renderRetrievables),\n renderRetrievableSafetyDirective: pick(\n 'renderRetrievableSafetyDirective',\n renderRetrievableSafetyDirective\n ),\n renderFirstPartyRetrievables: pick(\n 'renderFirstPartyRetrievables',\n renderFirstPartyRetrievables\n ),\n renderThirdPartyPublicRetrievables: pick(\n 'renderThirdPartyPublicRetrievables',\n renderThirdPartyPublicRetrievables\n ),\n renderThirdPartyPrivateRetrievables: pick(\n 'renderThirdPartyPrivateRetrievables',\n renderThirdPartyPrivateRetrievables\n ),\n renderThought: pick('renderThought', renderThought),\n filterThoughts: pick('filterThoughts', filterThoughts),\n renderChatCompletionsSystemPrompt: pick(\n 'renderChatCompletionsSystemPrompt',\n renderChatCompletionsSystemPrompt\n ),\n toolsToConverseTools: pick('toolsToConverseTools', toolsToConverseTools),\n renderConverseToolResult: pick('renderConverseToolResult', renderConverseToolResult),\n buildConverseRequest: pick('buildConverseRequest', buildConverseRequest),\n } as BedrockConverseHelpers\n}\n\n/**\n * Native Bedrock Converse executor adapter.\n *\n * @example\n * ```ts\n * const adapter = new BedrockConverseAdapter({\n * model: 'us.amazon.nova-2-lite-v1:0',\n * apiKey: process.env.AWS_BEARER_TOKEN_BEDROCK,\n * region: 'us-east-1',\n * })\n * const runner = new TurnRunner({ executorCallback: adapter.executor(), ... })\n * ```\n */\nexport class BedrockConverseAdapter {\n /** Per-iteration override key on `ctx.stash`. */\n public static readonly STASH_KEY = 'bedrockConverse' as const\n\n readonly #baseline: BedrockConverseAdapterOptions\n\n /**\n * @param options - Constructor-baseline options, re-validated each iteration after overrides merge.\n * @throws {@link E_INVALID_BEDROCK_CONVERSE_OPTIONS} when `options` is invalid.\n */\n constructor(options: unknown) {\n this.#baseline = validateOptions(options)\n }\n\n /** Narrowing guard for cross-realm instances. */\n public static isBedrockConverseAdapter(value: unknown): value is BedrockConverseAdapter {\n return isInstanceOf(value, 'BedrockConverseAdapter', BedrockConverseAdapter)\n }\n\n /**\n * Build a {@link DispatchExecutorFn} bound to the baseline plus optional executor-scope overrides.\n *\n * @param overrides - Higher precedence than the baseline, lower than `ctx.stash`.\n */\n executor(overrides?: Partial<BedrockConverseAdapterOptions>): DispatchExecutorFn {\n const baseline = this.#baseline\n const adapterClass = BedrockConverseAdapter\n return async (ctx: DispatchContext, helpers: DispatchExecutorHelpers): Promise<void> => {\n const warn = (message: string): void => {\n helpers.log.warn({ kind: 'helper-warning', message })\n }\n\n const stashRaw = ctx.stash.get(adapterClass.STASH_KEY, {}) as unknown\n const stashOverrides = isObject(stashRaw)\n ? (stashRaw as Partial<BedrockConverseAdapterOptions>)\n : {}\n const merged = validateOptions(mergeOptions(baseline, overrides, stashOverrides))\n if (\n merged.tokenEncoding !== undefined &&\n merged.tokenEncoding !== null &&\n merged.contextWindow === undefined\n ) {\n throw new E_INVALID_BEDROCK_CONVERSE_OPTIONS([\n 'tokenEncoding is non-null but contextWindow is undefined',\n ])\n }\n const resolved = resolveHelpers(merged.helpers)\n const selfIdentity = 'assistant'\n const dispatchStreamId = uuidv6()\n\n // Converse wants toolResult.content[] blocks, so results render ahead of assembly.\n const renderedToolCallResults = new Map<\n ToolCall,\n Array<{ text?: string; json?: Record<string, unknown> }>\n >()\n for (const tc of ctx.turnToolCalls) {\n renderedToolCallResults.set(\n tc,\n await resolved.renderConverseToolResult({\n toolCall: tc,\n results: tc.results as never,\n tool: ctx.tools.get(tc.tool) as Tool | ArtifactTool | undefined,\n renderUntrustedContent: resolved.renderUntrustedContent,\n renderTrustedContent: resolved.renderTrustedContent,\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n warn,\n })\n )\n }\n\n if (\n merged.tokenEncoding !== undefined &&\n merged.tokenEncoding !== null &&\n merged.contextWindow !== undefined\n ) {\n const encoding = merged.tokenEncoding\n let total = await estimateTokensOf(ctx.systemPrompt, encoding)\n for (const value of ctx.standingInstructions)\n total += await estimateTokensOf(value, encoding)\n for (const memory of ctx.turnMemories as Set<Memory>)\n total += await estimateTokensOf(memory.content, encoding)\n for (const retrievable of ctx.turnRetrievables)\n total += await estimateTokensOf(\n retrievable.inline\n ? (retrievable.content as any)\n : new Tokenizable(`[Reference available: ${retrievable.id}]`),\n encoding\n )\n for (const message of ctx.turnMessages) {\n if (message.content !== undefined)\n total += await estimateTokensOf(message.content, encoding)\n }\n for (const thought of ctx.turnThoughts)\n total += await estimateTokensOf(thought.content, encoding)\n for (const result of renderedToolCallResults.values()) {\n total += await estimateTokensOf(new Tokenizable(JSON.stringify(result)), encoding)\n }\n const tools = ctx.tools.visible()\n if (tools.length > 0) {\n // Tool DECLARATIONS: the Bedrock wire ships tools as an array, which the PROVIDER\n // serializes server-side into the model's own format. Tally the tokens of the wire\n // tools JSON (`JSON.stringify`) as an honest FLOOR — a truthful lower bound. We add\n // a safe 10% margin to cover JSON structural overhead and nested formatting.\n const toolTokens = await estimateTokensOf(\n new Tokenizable(JSON.stringify(resolved.toolsToConverseTools(tools))),\n encoding\n )\n total += Math.ceil(toolTokens * 1.1)\n }\n if (total + (merged.maxTokens ?? 0) > merged.contextWindow) {\n throw new E_BEDROCK_CONVERSE_CONTEXT_OVERFLOW([\n total + (merged.maxTokens ?? 0),\n merged.contextWindow,\n encoding,\n ])\n }\n }\n\n const request = await resolved.buildConverseRequest({\n systemPrompt: ctx.systemPrompt,\n standingInstructions: ctx.standingInstructions,\n memories: ctx.turnMemories,\n retrievables: ctx.turnRetrievables,\n messages: ctx.turnMessages,\n thoughts: ctx.turnThoughts,\n toolCalls: ctx.turnToolCalls,\n tools: ctx.tools,\n renderedToolCallResults,\n bucketOrder: merged.bucketOrder ?? (DEFAULT_CONVERSE_BUCKET_ORDER as never),\n selfIdentity,\n thoughtSurfacing: merged.thoughtSurfacing ?? 'all-self',\n replayCompatibility: [],\n alternationPolicy: merged.alternationPolicy ?? 'merge',\n helpers: resolved,\n decodeMedia: mediaToConverseImage,\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy,\n warn,\n })\n\n const inferenceConfig = {\n ...(merged.maxTokens !== undefined ? { maxTokens: merged.maxTokens } : {}),\n ...(merged.temperature !== undefined ? { temperature: merged.temperature } : {}),\n ...(merged.topP !== undefined ? { topP: merged.topP } : {}),\n ...(merged.stopSequences ? { stopSequences: merged.stopSequences } : {}),\n }\n const body = {\n ...request,\n ...(merged.toolChoice && request.toolConfig\n ? { toolConfig: { ...request.toolConfig, toolChoice: merged.toolChoice } }\n : {}),\n ...(Object.keys(inferenceConfig).length > 0 ? { inferenceConfig } : {}),\n ...(merged.additionalModelRequestFields\n ? { additionalModelRequestFields: merged.additionalModelRequestFields }\n : {}),\n }\n\n // The EXACT body about to be POSTed. An ADK-control key — stripped from the wire request.\n if (merged.onPromptAssembled) {\n try {\n merged.onPromptAssembled({\n battery: 'bedrock_converse',\n kind: 'request-body',\n messages: body.messages,\n tools: body.toolConfig?.tools,\n requestBody: body,\n streamed: merged.stream === true,\n streamId: dispatchStreamId,\n })\n } catch {\n /* observer errors are non-fatal */\n }\n }\n\n const base = (\n merged.baseURL ?? `https://bedrock-runtime.${merged.region ?? DEFAULT_REGION}.amazonaws.com`\n ).replace(/\\/$/, '')\n const action = merged.stream === true ? 'converse-stream' : 'converse'\n // The model id contains ':' and '.', both legal in a path segment but worth encoding so a\n // future id with a reserved character does not silently reshape the URL.\n const url = `${base}/model/${encodeURIComponent(merged.model)}/${action}`\n const headers: Record<string, string> = { 'Content-Type': 'application/json' }\n if (merged.apiKey) headers.Authorization = `Bearer ${merged.apiKey}`\n\n // retry / timeout loop — mirrors openai_chat_completions/adapter.ts and\n // anthropic_messages/adapter.ts: same defaults, same backoff, same Retry-After handling,\n // same log shape. This battery has no dedicated request-timeout exception class, so an\n // exhausted timeout and an exhausted generic transport failure both nack with the\n // existing E_CONVERSE_STREAM_ERROR — only the log `kind` distinguishes them. No SigV4\n // signing to recompute per attempt: this battery sends only a static bearer key (see the\n // module docstring above), so there is nothing request-specific to re-derive on retry.\n const retryCfg: ChatCompletionsRetryConfig = {\n maxAttempts: merged.retry?.maxAttempts ?? 1,\n baseDelayMs: merged.retry?.baseDelayMs ?? 500,\n maxDelayMs: merged.retry?.maxDelayMs ?? 30_000,\n retriableStatuses: merged.retry?.retriableStatuses ?? [429, 502, 503, 504],\n honorRetryAfter: merged.retry?.honorRetryAfter ?? true,\n }\n\n const doFetch = merged.fetch ?? globalThis.fetch\n const maxAttempts = retryCfg.maxAttempts ?? 1\n\n let res: Response | undefined\n let attempt = 1\n // Each retry attempt re-links to the long-lived ctx.abortSignal — dispose the PRIOR\n // attempt's link before making a new one, else N retries leave N stale listeners on\n // ctx.abortSignal for the rest of the turn. The outer `finally` below disposes the LAST\n // attempt's link too, on every exit path (success, terminal error, or abort) — without it\n // the fallback path's listener (used when native AbortSignal.any is unavailable) never\n // detaches from ctx.abortSignal after the final attempt.\n let disposeLink: () => void = () => {}\n let rawText = ''\n let parsed: ConverseResponse\n try {\n while (attempt <= maxAttempts) {\n if (ctx.abortSignal.aborted) return\n\n const internalController = new AbortController()\n disposeLink()\n const { signal: linkedSignal, dispose: disposeCurrentLink } = linkAbortSignals([\n ctx.abortSignal,\n internalController.signal,\n ])\n disposeLink = disposeCurrentLink\n // Start the per-attempt timer only AFTER the signal link is built. `disposeLink()` and\n // `linkAbortSignals()` can throw synchronously; if the timer were already running, the\n // outer `finally` would dispose the link but leave this attempt's timer armed. Nothing\n // that can throw runs between this `setTimeout` and the `try` below, whose completion\n // and rejection paths both clear it.\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined\n const timeoutMs = merged.timeoutMs ?? 0\n if (timeoutMs > 0) {\n timeoutHandle = setTimeout(() => internalController.abort(), timeoutMs)\n }\n\n try {\n // The per-attempt timeout/abort link must stay live through BOTH the fetch call and\n // the body read below — this battery has no incremental SSE parsing, so `res.text()`\n // buffering the entire body is the only phase a stalled upstream can hang in, and it\n // needs the same bound the fetch phase gets (previously the timeout was cleared right\n // after headers arrived, leaving the body read unbounded).\n res = await doFetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: linkedSignal,\n })\n rawText = await res.text()\n if (timeoutHandle !== undefined) clearTimeout(timeoutHandle)\n } catch (err) {\n if (timeoutHandle !== undefined) clearTimeout(timeoutHandle)\n if (ctx.abortSignal.aborted) return\n if (internalController.signal.aborted) {\n helpers.log.warn({\n kind: 'request-timeout',\n message: `Request timed out after ${timeoutMs}ms on attempt ${attempt}/${maxAttempts}`,\n payload: { timeoutMs, attempt, maxAttempts },\n })\n if (attempt < maxAttempts) {\n const delay = computeBackoff(attempt, retryCfg)\n helpers.log.debug({\n kind: 'retry-attempt',\n message: `Retrying after request timeout in ~${delay}ms (attempt ${attempt + 1}/${maxAttempts})`,\n payload: {\n reason: 'request-timeout',\n delayMs: delay,\n attempt: attempt + 1,\n maxAttempts,\n },\n })\n await sleepWithJitter(delay, ctx.abortSignal)\n attempt += 1\n continue\n }\n ctx.nack(new E_CONVERSE_STREAM_ERROR([`Request timed out after ${timeoutMs}ms`]))\n return\n }\n helpers.log.error({\n kind: 'transport-error',\n message: `Transport failure on attempt ${attempt}/${maxAttempts}: ${isError(err) ? err.message : String(err)}`,\n payload: {\n attempt,\n maxAttempts,\n detail: isError(err) ? err.message : String(err),\n },\n })\n if (attempt < maxAttempts) {\n const delay = computeBackoff(attempt, retryCfg)\n helpers.log.debug({\n kind: 'retry-attempt',\n message: `Retrying after transport failure in ~${delay}ms (attempt ${attempt + 1}/${maxAttempts})`,\n payload: {\n reason: 'transport-error',\n delayMs: delay,\n attempt: attempt + 1,\n maxAttempts,\n },\n })\n await sleepWithJitter(delay, ctx.abortSignal)\n attempt += 1\n continue\n }\n ctx.nack(new E_CONVERSE_STREAM_ERROR([isError(err) ? err.message : String(err)]))\n return\n }\n\n if (!res.ok) {\n // Classify the two Converse-specific rejections BEFORE the generic retriable-status\n // check — both are terminal and actionable regardless of status code, and both\n // otherwise arrive as an undifferentiated ValidationException.\n if (/toolConfig/i.test(rawText)) {\n ctx.nack(new E_CONVERSE_MISSING_TOOL_CONFIG([rawText.slice(0, 400)]))\n return\n }\n if (/alternat|consecutive|must alternate/i.test(rawText)) {\n ctx.nack(new E_CONVERSE_ALTERNATION_VIOLATION([rawText.slice(0, 400)]))\n return\n }\n const status = res.status\n const retriable = (retryCfg.retriableStatuses ?? [429, 502, 503, 504]).includes(status)\n if (retriable && attempt < maxAttempts) {\n let delay = computeBackoff(attempt, retryCfg)\n let retryAfterMs: number | undefined\n if (retryCfg.honorRetryAfter !== false) {\n const ra = res.headers.get('Retry-After')\n if (ra) {\n const raMs = parseRetryAfter(ra)\n if (raMs > 0) {\n retryAfterMs = raMs\n delay = Math.min(Math.max(delay, raMs), retryCfg.maxDelayMs ?? 30_000)\n }\n }\n }\n helpers.log.warn({\n kind: 'retry-attempt',\n message: `HTTP ${status} on attempt ${attempt}/${maxAttempts}; retrying in ~${delay}ms`,\n payload: {\n reason: 'http-status',\n status,\n delayMs: delay,\n ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),\n attempt: attempt + 1,\n maxAttempts,\n },\n })\n await sleepWithJitter(delay, ctx.abortSignal)\n attempt += 1\n continue\n }\n helpers.log.error({\n kind: 'http-error',\n message: `HTTP ${status} (terminal): ${rawText.slice(0, 256)}`,\n payload: { status, body: rawText, attempt, maxAttempts, retriable },\n })\n ctx.nack(new E_CONVERSE_REQUEST_FAILED([status, rawText.slice(0, 400)]))\n return\n }\n break\n }\n if (!res) return\n parsed = JSON.parse(rawText) as ConverseResponse\n } catch (err) {\n ctx.nack(new E_CONVERSE_STREAM_ERROR([isError(err) ? err.message : String(err)]))\n return\n } finally {\n // Runs on every exit from the loop above — success, an early `return` inside a `try`\n // still runs its enclosing `finally` — so the LAST attempt's link is disposed too, not\n // just the intermediate ones handled by the per-iteration `disposeLink()` call.\n disposeLink()\n }\n\n const { text, reasoning, toolUses, stopReason } = extractConverseGeneration(parsed)\n const responseId = uuidv6()\n\n if (text.length > 0) {\n const messageId = `${responseId}:message`\n helpers.reportMessage(messageId, text, { isComplete: true })\n await ctx.storeMessage(\n new Message({\n id: messageId,\n role: 'assistant',\n content: text,\n identity: selfIdentity,\n createdAt: nowIso(),\n updatedAt: nowIso(),\n })\n )\n }\n if (reasoning.length > 0) {\n const thoughtId = `${responseId}:thought`\n helpers.reportThought(thoughtId, reasoning, { isComplete: true })\n await ctx.storeThought(\n new Thought({\n id: thoughtId,\n content: reasoning,\n identity: selfIdentity,\n createdAt: nowIso(),\n updatedAt: nowIso(),\n })\n )\n }\n\n // Fallback recovery is consulted ONLY when the provider returned no structured tool use, so\n // a native toolUse always wins over a parsed one.\n const calls = toolUses.map((t) => ({ id: t.toolUseId, name: t.name, args: t.input }))\n if (calls.length === 0 && merged.localToolCallParser !== undefined && text.length > 0) {\n const parser = resolveToolCallParser(merged.localToolCallParser)\n const recovered = parser(text, { toolNames: ctx.tools.all().map((t) => t.name) })\n for (const call of recovered.calls) {\n calls.push({\n id: uuidv6(),\n name: call.name,\n args: (call.arguments ?? {}) as Record<string, unknown>,\n })\n }\n }\n\n if (merged.onRawGeneration) {\n try {\n merged.onRawGeneration({\n rawText: text,\n cleanedText: text,\n reasoning: reasoning.length > 0 ? [reasoning] : [],\n toolCalls: calls.map((c) => ({ name: c.name, arguments: c.args as never })),\n streamed: merged.stream === true,\n streamId: dispatchStreamId,\n })\n } catch {\n /* observer errors are non-fatal */\n }\n }\n\n if (calls.length === 0) {\n helpers.log.trace({\n kind: 'converse-finish',\n message: `generation ended with stopReason=${stopReason ?? 'unknown'} and no tool use`,\n payload: { stopReason: stopReason ?? 'unknown' },\n })\n if (merged.autoAck) ctx.ack()\n return\n }\n\n for (const call of calls) {\n if (ctx.abortSignal.aborted) return\n // Resolve once at ingress; Converse sanitises only when rendering, so this preserves the\n // filtered id consistently for reporting, persistence, and any spool key.\n const callId = merged.toolCallIdFilter?.(call.id, ctx) ?? call.id\n const toolName = normalizeToolName(call.name)\n const tool = ctx.tools.get(toolName) as Tool | ArtifactTool | undefined\n const completedAt = nowIso()\n\n if (!isObject(call.args)) {\n const results = new Tokenizable(\n new E_CONVERSE_INVALID_TOOL_INPUT([JSON.stringify(call.args)]).message\n )\n helpers.reportToolCall(callId, { tool: toolName, args: {} })\n helpers.reportToolCall(callId, { results, isError: true, isComplete: true })\n await ctx.storeToolCall(\n new ToolCall({\n id: callId,\n tool: toolName,\n args: {},\n checksum: computeChecksum(toolName, {}),\n isComplete: true,\n isError: true,\n results,\n createdAt: completedAt,\n updatedAt: completedAt,\n completedAt,\n })\n )\n continue\n }\n\n if (!tool) {\n const available = ctx.tools\n .all()\n .map((t) => t.name)\n .sort()\n const results = new Tokenizable(\n available.length > 0\n ? `Tool not found: ${toolName}. Available tools: ${available.join(', ')}.`\n : `Tool not found: ${toolName}. No tools are available this turn.`\n )\n helpers.reportToolCall(callId, { tool: toolName, args: call.args })\n helpers.reportToolCall(callId, { results, isError: true, isComplete: true })\n await ctx.storeToolCall(\n new ToolCall({\n id: callId,\n tool: toolName,\n args: call.args,\n checksum: computeChecksum(toolName, call.args),\n isComplete: true,\n isError: true,\n results,\n createdAt: completedAt,\n updatedAt: completedAt,\n completedAt,\n })\n )\n continue\n }\n\n helpers.reportToolCall(callId, { tool: tool.name, args: call.args })\n let results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[] =\n new Tokenizable('')\n let isToolError = false\n try {\n const raw = await tool.executor(ctx)(call.args)\n results = Tokenizable.isTokenizable(raw)\n ? raw\n : new Tokenizable(typeof raw === 'string' ? raw : JSON.stringify(raw ?? ''))\n } catch (err) {\n isToolError = true\n results = new Tokenizable(isError(err) ? err.message : String(err))\n }\n const finishedAt = nowIso()\n helpers.reportToolCall(callId, { results, isError: isToolError, isComplete: true })\n await ctx.storeToolCall(\n new ToolCall({\n id: callId,\n tool: tool.name,\n args: call.args,\n checksum: computeChecksum(tool.name, call.args),\n isComplete: true,\n isError: isToolError,\n results,\n createdAt: finishedAt,\n updatedAt: finishedAt,\n completedAt: finishedAt,\n })\n )\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,IAAM,eAAuB,MAAA,SAAS,IAAI,EAAE,MAAM,sBAAK,IAAI,KAAK,GAAE,YAAY;AAE9E,IAAM,iBAAiB;AAEvB,IAAM,mBAAmB,OACvB,OACA,aACoB,QAAQ,QAAQ,MAAM,eAAe,QAAyB,CAAC;AAErF,IAAM,mBAAmB,MAAc,UAAA,GAAA,UAAA,QAC9B,GAAG,KAAK,GAAG,yBAAA,mBAAmB,IAAI,GAAG;;AAG9C,IAAM,gBACJ,GAAG,WACwC;CAC3C,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,CAAC,OAAO;EACZ,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,KAAK,GAAG,IAAI,MAAM,KAAA,GAAW,IAAI,KAAK;CAC5E;CACA,OAAO;AACT;;AAGA,IAAM,kBACJ,cAC2B;CAC3B,MAAM,MAAO,aAAa,CAAC;CAC3B,MAAM,QAAW,KAAa,aAAoB,IAAI,QAA0B;CAChF,OAAO;EACL,wCAAwC,KACtC,0CACA,gBAAA,sCACF;EACA,wBAAwB,KAAK,0BAA0B,gBAAA,sB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