@yukino.js/yukino 0.0.13 → 0.0.15
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 +13 -11
- package/dist/a2a-ANR7PFD4.js +15 -0
- package/dist/acp-4E7R254I.js +14 -0
- package/dist/{anthropic-74ALYMH2.js → anthropic-ZO73YJFY.js} +1 -1
- package/dist/browser/dist/index.html +44 -0
- package/dist/browser/dist/static/index.css +2 -0
- package/dist/browser/dist/static/index.js +203 -0
- package/dist/bwrap-LVIPV72Q.js +0 -0
- package/dist/chunk-3KKA6537.js +0 -0
- package/dist/chunk-3RH3COZW.js +365 -0
- package/dist/chunk-4JHZPFU6.js +67 -0
- package/dist/chunk-7MKA3SHV.js +0 -0
- package/dist/{chunk-OREDGNI6.js → chunk-B2RNOTT5.js} +1 -1
- package/dist/{chunk-APJAUOF6.js → chunk-C56EKYBO.js} +1 -1
- package/dist/{chunk-WGFROGUC.js → chunk-CKOUBYG6.js} +0 -0
- package/dist/{chunk-6JUOKMSJ.js → chunk-CW6G3RYM.js} +1 -1
- package/dist/{chunk-556TRLPT.js → chunk-CWWRUTF2.js} +1 -1
- package/dist/chunk-DVB57IVG.js +18 -0
- package/dist/chunk-ETZPOVUC.js +4 -0
- package/dist/chunk-F3JTT3TI.js +110 -0
- package/dist/chunk-FC2LG24U.js +4 -0
- package/dist/chunk-FNQMXCCE.js +4 -0
- package/dist/chunk-HWCLMDQF.js +0 -0
- package/dist/chunk-I74AL3PF.js +0 -0
- package/dist/chunk-IOMQY54U.js +967 -0
- package/dist/chunk-IQT2IFSO.js +4 -0
- package/dist/chunk-K45OXLJJ.js +16 -0
- package/dist/chunk-KJJYW5IY.js +0 -0
- package/dist/chunk-LCWNSYZU.js +0 -0
- package/dist/chunk-LR4ZNAAM.js +4 -0
- package/dist/chunk-LTMY67B2.js +5 -0
- package/dist/chunk-MDPSQ6L7.js +0 -0
- package/dist/chunk-MQAQBW7F.js +0 -0
- package/dist/{chunk-NEU4ER5V.js → chunk-NSNTZXFL.js} +1 -1
- package/dist/chunk-P6DHMU7R.js +0 -0
- package/dist/chunk-VCIRD267.js +0 -0
- package/dist/chunk-VM4YKTHC.js +0 -0
- package/dist/chunk-VU3JWAJR.js +0 -0
- package/dist/chunk-W4GMCNWF.js +0 -0
- package/dist/chunk-XY7ZFVZL.js +4 -0
- package/dist/devtools-UVGRIXO2.js +0 -0
- package/dist/{esm-HW2JMFYC.js → esm-2JJG3HR7.js} +1 -1
- package/dist/esm-7DWXO52B.js +4 -0
- package/dist/{esm-6L5BJ5GT.js → esm-EOOB75BT.js} +1 -1
- package/dist/{esm-DIYJ5HX6.js → esm-H73EL6IR.js} +1 -1
- package/dist/{esm-YKAO4ES6.js → esm-IBZKE3IU.js} +1 -1
- package/dist/esm-W4NAAZTQ.js +225 -0
- package/dist/{esm-RPR2GBJ2.js → esm-Y237QNPJ.js} +1 -1
- package/dist/getMachineId-bsd-A3UCSHLE.js +4 -0
- package/dist/getMachineId-bsd-E27XJQLX.js +0 -0
- package/dist/getMachineId-darwin-35UPAIXP.js +0 -0
- package/dist/getMachineId-darwin-MWJEU7OI.js +5 -0
- package/dist/getMachineId-linux-FNSLKUDN.js +4 -0
- package/dist/getMachineId-linux-MKXIYT6A.js +0 -0
- package/dist/getMachineId-unsupported-PKQWB2OJ.js +4 -0
- package/dist/getMachineId-unsupported-ZXVGGFX2.js +0 -0
- package/dist/getMachineId-win-3A667JT3.js +4 -0
- package/dist/getMachineId-win-RNVIYJG5.js +0 -0
- package/dist/lib/{anthropic-EQRUGP2C.js → anthropic-SQBOFRPQ.js} +4 -4
- package/dist/lib/{chunk-EGT7BJRD.js → chunk-AW2577J5.js} +2 -2
- package/dist/lib/{chunk-JYCSWXCR.js → chunk-GPJL4PLE.js} +2 -2
- package/dist/lib/{chunk-UBVKYJFI.js → chunk-IHVYAEY2.js} +1058 -522
- package/dist/lib/{chunk-CDMR25FD.js → chunk-U3OT4POQ.js} +3 -3
- package/dist/lib/{chunk-HUTUNNDX.js → chunk-WNGF7243.js} +0 -1
- package/dist/lib/{chunk-FUJDUZTH.js → chunk-WXR5HNB4.js} +1 -1
- package/dist/lib/{chunk-WWCSFKMR.js → chunk-XS3GONYN.js} +2 -11
- package/dist/lib/index.d.ts +98 -282
- package/dist/lib/index.js +1092 -2409
- package/dist/lib/{openai-B3I5WBFT.js → openai-UV4KFNQV.js} +3 -3
- package/dist/lib/{providers-EJ4VBHNP.js → providers-77VBEX3K.js} +2 -2
- package/dist/lib/{tool-filter-TURPCYFR.js → tool-filter-MLYQGWM5.js} +3 -3
- package/dist/{main-JEEKFCGX.js → main-653YZQHY.js} +228 -232
- package/dist/main.js +2 -2
- package/dist/node-634LOHDX.js +0 -0
- package/dist/{openai-7C6BVQ7M.js → openai-FKLMHNNC.js} +1 -1
- package/dist/providers-4IU7SUEQ.js +4 -0
- package/dist/seatbelt-UO7HGD4Z.js +0 -0
- package/dist/server-4NHV4RJL.js +4 -0
- package/dist/slim-Q56GHZZP.js +0 -0
- package/dist/{src-JBRNH4FA.js → src-DEVJGNXS.js} +1 -1
- package/dist/{src-X6JWWHHT.js → src-EMFESWQS.js} +1 -1
- package/dist/{src-R4BSSIJJ.js → src-GG4YROJH.js} +1 -1
- package/dist/{src-43CPCEK2.js → src-JFAO2DGP.js} +1 -1
- package/dist/tool-filter-LJTLMGFP.js +4 -0
- package/dist/turndown.es-NQ3KDXM7.js +0 -0
- package/package.json +22 -21
- package/dist/a2a-DKWMWGID.js +0 -14
- package/dist/acp-RL6DKS3R.js +0 -14
- package/dist/chunk-2LHY3FND.js +0 -67
- package/dist/chunk-3QL446GD.js +0 -4
- package/dist/chunk-6FSIG63T.js +0 -364
- package/dist/chunk-A5G5NTDB.js +0 -1015
- package/dist/chunk-A7CJPQC5.js +0 -5
- package/dist/chunk-AGSYLE4E.js +0 -16
- package/dist/chunk-CJSMVCUF.js +0 -6
- package/dist/chunk-CU3IISCC.js +0 -4
- package/dist/chunk-HMZQYFYG.js +0 -4
- package/dist/chunk-JFKC4VCA.js +0 -4
- package/dist/chunk-KCMBAHWU.js +0 -4
- package/dist/chunk-SCR7NDDL.js +0 -63
- package/dist/esm-57CJEGGK.js +0 -4
- package/dist/esm-YOQPBF42.js +0 -225
- package/dist/fe/dist/index.html +0 -21
- package/dist/fe/dist/static/index.css +0 -2
- package/dist/fe/dist/static/index.js +0 -203
- package/dist/providers-U23PWAHG.js +0 -4
- package/dist/server-EOSEQPNY.js +0 -4
- package/dist/tool-filter-UDSHRE5F.js +0 -4
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Yukino is a terminal-based AI coding agent. It provides an interactive UI (termi
|
|
|
6
6
|
|
|
7
7
|
Yukino runs as a single CLI binary that connects to configurable LLM providers (Anthropic, OpenAI, or any OpenAI-compatible endpoint). It renders a rich terminal interface using React and Ink, giving you streaming responses, tool execution feedback, permission prompts, and slash commands in a single pane.
|
|
8
8
|
|
|
9
|
-
Beyond interactive use, Yukino supports a non-interactive print mode for scripting, a remote mode that serves a browser-based chat UI over WebSocket, an ACP (Agent Client Protocol) mode for editor integration, an A2A (Agent2Agent) server mode for agent-to-agent integration, and team coordination where one leader agent manages multiple teammates
|
|
9
|
+
Beyond interactive use, Yukino supports a non-interactive print mode for scripting, a remote mode that serves a browser-based chat UI over WebSocket, an ACP (Agent Client Protocol) mode for editor integration, an A2A (Agent2Agent) server mode for agent-to-agent integration, and team coordination where one leader agent manages multiple teammates running in the same process and working in parallel.
|
|
10
10
|
|
|
11
11
|
## Features
|
|
12
12
|
|
|
@@ -106,7 +106,7 @@ yukino --version
|
|
|
106
106
|
|
|
107
107
|
The command checks npm's `latest` dist-tag by default. Use `--tag=canary` (or `--tag canary`) to check another dist-tag. If its version is newer according to SemVer, the command installs that exact version using the package manager that provides the current installation. For example, `0.0.14-canary` is newer than `0.0.13-dev`. Equal or older versions are not installed. Both one-line installers use npm, so their installations support `yukino update` too. Source checkouts must be updated from the repository.
|
|
108
108
|
|
|
109
|
-
The TUI checks npm's `latest` dist-tag for a newer release asynchronously and shows a `yukino update` hint when one is available. Network errors do not interrupt the UI. Set `YUKINO_SKIP_VERSION_CHECK=1` to disable automatic checks; explicit `yukino update` still checks for updates.
|
|
109
|
+
The TUI checks npm's `latest` dist-tag for a newer release asynchronously and shows a `yukino update` hint on entry when one is available. The hint disappears after the first input submission or when a session is resumed; late check results stay hidden during the conversation. Available updates are shown again on the last line of the exit summary. Network errors do not interrupt the UI. Set `YUKINO_SKIP_VERSION_CHECK=1` to disable automatic checks; explicit `yukino update` still checks for updates.
|
|
110
110
|
|
|
111
111
|
Or run directly from the monorepo:
|
|
112
112
|
|
|
@@ -335,7 +335,7 @@ hooks:
|
|
|
335
335
|
|
|
336
336
|
Main agents, subagents, and teammates use the same path sandbox policy: read-only tools can access paths outside the working directory without path approval. Writes outside the agent's working directory, the system temp directory, or an explicitly allowed root require approval unless an explicit allow rule applies. `bypassPermissions` disables this path sandbox; switching back restores it. Explicit deny/ask rules and an agent's own plan approval lock still apply. The OS-level Bash sandbox is separate and remains controlled by the `sandbox` configuration or the TUI's `/sandbox` command.
|
|
337
337
|
|
|
338
|
-
Sandbox configuration applies to TUI, print, Remote/ACP/A2A, and
|
|
338
|
+
Sandbox configuration applies to TUI, print, Remote/ACP/A2A, and in-process teammates. Enabling it fails closed when the native backend is unavailable. `bypassPermissions` does not disable it. Relative allow/deny write paths resolve against the command's execution directory; home-relative paths use the same resolver as file tools. The policy confines Bash writes and optionally disables all network access; it does not wrap PowerShell, LSP, or MCP executables.
|
|
339
339
|
|
|
340
340
|
Provider fields:
|
|
341
341
|
|
|
@@ -484,7 +484,7 @@ lsp_servers:
|
|
|
484
484
|
|
|
485
485
|
`LSP` supports definition, references, hover, document/workspace symbols, implementation, type definition, call hierarchy preparation and incoming/outgoing calls, and diagnostics. Input positions are 1-based UTF-16; returned ranges follow the [LSP specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/) (0-based UTF-16). File content is synchronized before queries. A push-diagnostics response with `pending: true` means no current report arrived within the bounded wait, not that the file has no errors. Servers without versioned diagnostic notifications cannot guarantee detection of delayed stale reports.
|
|
486
486
|
|
|
487
|
-
The tool requests only read-only operations and rejects server-requested workspace edits and commands. Configured executables are trusted local programs, like stdio MCP servers: they run with the user's OS privileges, outside the Bash OS sandbox. Configure only servers you trust. Queries honor Yukino's read-tool permission rules
|
|
487
|
+
The tool requests only read-only operations and rejects server-requested workspace edits and commands. Configured executables are trusted local programs, like stdio MCP servers: they run with the user's OS privileges, outside the Bash OS sandbox. Configure only servers you trust. Queries honor Yukino's read-tool permission rules and the agent's effective permission mode. Servers are shut down at host exit, with forced process-tree cleanup if necessary.
|
|
488
488
|
|
|
489
489
|
### Tasks, TODOs, and background work
|
|
490
490
|
|
|
@@ -497,19 +497,21 @@ Task tracking and task execution are separate:
|
|
|
497
497
|
- Interactive/Remote/ACP/A2A private lists persist per session in `~/.yukino/sessions/artifacts/<session-id>/tasks.json`, with a stored next-ID counter so deleting or clearing items never reuses IDs on resume. Shared boards use project-scoped team storage. Corrupt or inconsistent stores fail explicitly, without migration, auto-repair, or stale-state fallback. Storage and tool schemas have changed; old task files are not supported. Print mode's private checklist lasts for that invocation. The terminal's TODO progress follows the same private list or shared board as its Task tools, including teammate updates, blocked items, and cancelled items. When every item is completed, the progress line hides after five seconds without deleting tasks or resetting IDs. Adding or reopening an unfinished item shows it again and cancels the pending hide. Switching sessions or boards starts a fresh completion countdown.
|
|
498
498
|
- `Agent` executes delegated work. Background Agent/Bash/PowerShell invocations return runtime task IDs, distinct from TODO IDs. `TaskOutput` inspects one of these IDs or waits once (`wait: true`, `timeout_ms: 0..60000`). It does not consume automatic completion notifications or stop a task on timeout. Prefer notifications over polling. `TaskStop` remains the explicit cancellation mechanism.
|
|
499
499
|
|
|
500
|
-
The common built-in registry is used by terminal, print, Remote/ACP/A2A, and
|
|
500
|
+
The common built-in registry is used by terminal, print, Remote/ACP/A2A, and in-process teammates. Delegation, coordinator, and per-agent tool restrictions still filter that registry.
|
|
501
501
|
|
|
502
502
|
### Worker lifecycle
|
|
503
503
|
|
|
504
|
-
Ordinary subagents run once. On completion, failure, or interruption, the host waits for their owned background commands to stop and releases their scoped tool registry. Parent-owned LSP/MCP tools are borrowed, not shut down by a child. Finished
|
|
504
|
+
Ordinary subagents run once. On completion, failure, or interruption, the host waits for their owned background commands to stop and releases their scoped tool registry. Parent-owned LSP/MCP tools are borrowed, not shut down by a child. Background task records and subagent transcripts persist under `~/.yukino/sessions/artifacts/`; `TaskOutput` includes the transcript path and timestamps. Finished results remain queryable from disk after the in-memory retention limit, and delivered notifications are recorded in the leader's session. Resuming restores terminal outcomes and reports abandoned running tasks as interrupted failures. Iteration-limit and model failures preserve partial text alongside the error and transcript. Cancellation callbacks are discarded when runners settle. A fork cannot create or replace teams, or stop parent-owned work.
|
|
505
505
|
|
|
506
506
|
An explicit `run_in_background: false` overrides a predefined agent's `background: true`; when omitted, the definition supplies the default. Forks default to foreground execution. Role files accept a UTF-8 BOM before frontmatter. Delegated agents cannot manage the main session's persistent goal.
|
|
507
507
|
|
|
508
508
|
Persistent teammates become idle after each turn. They keep conversation and private checklist context for follow-up assignments, but must send findings with `SendMessage`; final text is not automatically forwarded to the leader. They exit on explicit shutdown, cancellation, failure, or loss of the leader. Exit clears live permission/cancellation references, releases owned tools, and resets unfinished owned tasks to unassigned/pending. Completed and cancelled records remain intact. Teammate task ownership is not released merely because a turn becomes idle.
|
|
509
509
|
|
|
510
|
-
The team retains at most 200 terminated member summaries; running and idle members are never evicted. Fully cleaned-up failed/stopped member names can be reused. Agent definitions inherit the parent's live
|
|
510
|
+
The team retains at most 200 terminated member summaries; running and idle members are never evicted. Fully cleaned-up failed/stopped member names can be reused. Agent definitions support `permission_mode: default | acceptEdits | plan | bypassPermissions`. Omitted modes inherit the parent's live mode. Parent `acceptEdits` and `bypassPermissions` override configured child modes; a child cannot enable bypass unless the parent already uses it. Child mode changes never change the parent. Plan mode blocks mutations, even through allow rules or sandbox auto-allow, except the declared plan file and internal coordination tools. `max_turns` must be a positive integer. Built-in explore uses the selected parent model unless explicitly overridden.
|
|
511
511
|
|
|
512
|
-
|
|
512
|
+
Teammates run only in-process and route permission requests through the main session. Requests identify the agent and working directory; remembered permission patterns apply to all agents in the project. When its effective mode is `plan`, a teammate requested with `plan_mode_required` submits its plan at turn completion; the runtime automatically approves it without leader review and resumes in the leader's current mode (`default` when the leader remains in `plan`). Plan approval does not authorize subsequent tool calls. Stopped teammates release their task ownership; restored sessions mark old runtimes inactive and reclaim unfinished work. Edited worktrees are retained for explicit integration, not deleted as part of runtime cleanup. Starting an Agent under a different team name never implicitly destroys another existing team.
|
|
513
|
+
|
|
514
|
+
Bash and PowerShell commands recognized by `isSafeCommand` can run in parallel. Unrecognized commands and file mutations share a process-wide FIFO queue keyed by canonical working directory, so agents in the same workspace cannot perform these operations simultaneously. Independent worktree directories have independent queues. Queued operations can be cancelled and recheck permissions before starting. Background commands hold their workspace slot until the tracked shell exits; moving a command to the background does not release it.
|
|
513
515
|
|
|
514
516
|
`WebSearch` directly requests Bing's public search pages and extracts organic result titles, source URLs, and snippets. It requires no search API key, subscription, or paid search API. Bing receives the query, requested result count, and market selection, together with ordinary HTTP request information. Requests are cancellable, limited to 25 seconds and 2 MiB, and model output is capped at 100,000 characters. Bing may return fewer results than requested. Network failures, rate limits, CAPTCHA, and unrecognized page layouts are reported as tool errors, distinct from an explicit empty search. `allowed_domains` and `blocked_domains` are mutually exclusive hostname lists, applied locally to decoded result URLs with exact-host/subdomain matching. Filtering can reduce the number of results; it does not ask Bing to search again. No session ID, provider/model, or workspace metadata is transmitted. Never include private source code or secrets in queries; treat results as untrusted content and cite source URLs. Use `WebFetch` to read a source page; search snippets are not full-page content.
|
|
515
517
|
|
|
@@ -649,7 +651,7 @@ Use the mouse wheel or trackpad to scroll conversation history in the terminal's
|
|
|
649
651
|
|
|
650
652
|
**Design tradeoff:** Yukino uses the terminal's primary screen, with fullscreen/alternate-screen rendering and mouse capture removed. Completed messages are appended to native scrollback, preserving normal selection, copying, pasting, and wheel/trackpad history scrolling without translating scrolling into prompt-history navigation. Yukino gives up its own conversation viewport, scrollbar, click-to-latest indicator, and conversation-navigation key bindings. Scrolling and whether new output follows the bottom are controlled by the terminal; the input and footer scroll out of view while reading older history. The live area remains responsive and shows the tail of running output; the complete assistant response is printed when it finishes. Ctrl+O reprints the current transcript with expanded/collapsed details, and resume/rewind prints the restored transcript; earlier printed lines remain terminal history. Scrollback retention, selection behavior, copy/paste shortcuts, and selection stability during live redraws depend on the terminal.
|
|
651
653
|
|
|
652
|
-
Terminal resizing redraws the live area without clearing or replaying completed messages, preserving the terminal's native reading position and scrollback anchors. Historical output keeps its printed line breaks and uses the terminal's own reflow; previously printed cards are not rebuilt or stretched to fill a wider terminal.
|
|
654
|
+
Terminal resizing redraws the live area without clearing or replaying completed messages, preserving the terminal's native reading position and scrollback anchors. Historical output keeps its printed line breaks and uses the terminal's own reflow; previously printed cards are not rebuilt or stretched to fill a wider terminal. Streaming and completed Markdown tables use grids with wrapped cells, falling back to wrapped raw Markdown when the columns cannot fit their widest characters. Printed table grids follow native history reflow when the terminal narrows. Background padding does not add extra wrapped rows when the terminal narrows. The input, status, live text, running tool cards, and newly completed messages use the current width. Resize redraws are coalesced. Apple Terminal's reflowed live rows and cleared gaps are tracked so repeated width and height changes restore the input and footer without leaving old status lines behind.
|
|
653
655
|
|
|
654
656
|
Pastes longer than 10 lines or 1,000 characters collapse to `[paste #1 +124 lines]` or `[paste #1 1234 chars]`. Clipboard images appear as `[Image #1]`. Arrow keys move across each placeholder as a unit, and Backspace/Delete remove it as a unit. Placeholders survive dialog switches; submitting restores the full text and image attachments.
|
|
655
657
|
|
|
@@ -667,10 +669,10 @@ Besides the `yukino` CLI, the package ships a library entry for embedding Yukino
|
|
|
667
669
|
The library entry is terminal-independent by contract: it must never reach `src/ui/**` or a ui-only dependency, so a host without a TTY (a server, an editor extension, a test harness) can import it. `pnpm build` enforces that contract:
|
|
668
670
|
|
|
669
671
|
- **ui-only dependency ban** — the `ban-ui-only-deps` plugin in `tsup.config.ts` fails the build when a bundle-reachable module imports one of the ui-only packages (`ink`, `react`, `chalk`, `ansi-escapes`, …) or a path inside `src/ui`. The list is declared once in `tsup.config.ts` and re-derived from the actual import sites by `tests/build-guards.test.ts`, which fails if the two drift apart.
|
|
670
|
-
- **`react` is banned, `react-dom` never appears** — the barrel does not re-export `src/ui/**`, so `react` is reached exclusively from the terminal layer; `react-dom` is imported only by the standalone browser bundle (`src/remote/
|
|
672
|
+
- **`react` is banned, `react-dom` never appears** — the barrel does not re-export `src/ui/**`, so `react` is reached exclusively from the terminal layer; `react-dom` is imported only by the standalone browser bundle (`src/remote/browser`, built separately via `pnpm build:browser`), which is not part of the library graph.
|
|
671
673
|
- **Ambiguous export scan** — once the bundle is written, the build runs the TypeScript ambiguous-export check (`TS2308`) over the library graph. A name exported by two `export *` sources is dropped by the bundler without any warning; the scan turns that into a build failure instead of a quietly smaller public API.
|
|
672
674
|
|
|
673
|
-
In a long-lived host process, prefer the composable modules (`Agent`, `ToolRegistry`, …) over the process-level entry points (`print-mode`, `recover
|
|
675
|
+
In a long-lived host process, prefer the composable modules (`Agent`, `ToolRegistry`, …) over the process-level entry points (`print-mode`, `recover`), which own process lifecycle — `recover` installs crash logging to `~/.yukino/crash.log` and calls `process.exit()`, and `print-mode` exits on invalid flags.
|
|
674
676
|
|
|
675
677
|
## Terminal Rendering Tests
|
|
676
678
|
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __yukinoCreateRequire } from "node:module";
|
|
3
|
+
const require = __yukinoCreateRequire(import.meta.url);
|
|
4
|
+
import{a as ct,b as Dr,g as Mr}from"./chunk-3RH3COZW.js";import"./chunk-IOMQY54U.js";import"./chunk-KJJYW5IY.js";import"./chunk-I74AL3PF.js";import"./chunk-CW6G3RYM.js";import{b as Cr,c as Rr,d as Ur,e as Jr}from"./chunk-B2RNOTT5.js";import{h as Ir}from"./chunk-LTMY67B2.js";import{k as wr,q as xr,s as Pr}from"./chunk-F3JTT3TI.js";import"./chunk-C56EKYBO.js";import"./chunk-MQAQBW7F.js";import"./chunk-CKOUBYG6.js";import"./chunk-VU3JWAJR.js";import"./chunk-DVB57IVG.js";import{r as fe}from"./chunk-HWCLMDQF.js";import"./chunk-LCWNSYZU.js";import"./chunk-XY7ZFVZL.js";import{a as Ar}from"./chunk-CWWRUTF2.js";import{C}from"./chunk-W4GMCNWF.js";import"./chunk-VM4YKTHC.js";import"./chunk-ETZPOVUC.js";import"./chunk-LR4ZNAAM.js";import"./chunk-K45OXLJJ.js";import"./chunk-IQT2IFSO.js";import"./chunk-VCIRD267.js";import{d as Lt,e as ft}from"./chunk-7MKA3SHV.js";var Da={};Lt(Da,{parseA2aAddress:()=>xa,runA2aServer:()=>kr,startA2aServer:()=>Pa});import{createServer as Wo}from"http";var Ma=class{request;taskId;contextId;context;task;referenceTasks;constructor(t,e,r,i,a,n){if(!t.message)throw new Error("RequestContext requires request.message to be set.");this.request=structuredClone(t),this.taskId=e,this.contextId=r,this.context=i,this.task=a,this.referenceTasks=n}get userMessage(){return this.request.message}},w={message:t=>({kind:"message",data:t}),task:t=>({kind:"task",data:t}),statusUpdate:t=>({kind:"statusUpdate",data:t}),artifactUpdate:t=>({kind:"artifactUpdate",data:t})};function ge(t){throw new Error(`Unhandled event kind: ${t.kind}`)}var Br=typeof CustomEvent<"u"?CustomEvent:class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail??null}};function Lr(t){return t instanceof Br}var La=class extends EventTarget{eventListeners=new Map;finishedListeners=new Map;publish(t){this.dispatchEvent(new Br("event",{detail:t}))}finished(){this.dispatchEvent(new Event("finished"))}on(t,e){return t==="event"?this.addEventListenerInternal(e):this.addFinishedListenerInternal(e),this}off(t,e){return t==="event"?this.removeEventListenerInternal(e):this.removeFinishedListenerInternal(e),this}once(t,e){return t==="event"?this.addEventListenerOnceInternal(e):this.addFinishedListenerOnceInternal(e),this}removeAllListeners(t){if(t===void 0||t==="event"){for(let e of this.eventListeners.values())for(let r of e)this.removeEventListener("event",r);this.eventListeners.clear()}if(t===void 0||t==="finished"){for(let e of this.finishedListeners.values())for(let r of e)this.removeEventListener("finished",r);this.finishedListeners.clear()}return this}trackListener(t,e,r){let i=t.get(e);i?i.push(r):t.set(e,[r])}untrackWrappedListener(t,e,r){let i=t.get(e);if(i&&i.length>0){let a=i.indexOf(r);a!==-1&&(i.splice(a,1),i.length===0&&t.delete(e))}}addEventListenerInternal(t){let e=r=>{if(!Lr(r))throw new Error('Internal error: expected CustomEvent for "event" type');t.call(this,r.detail)};this.trackListener(this.eventListeners,t,e),this.addEventListener("event",e)}removeEventListenerInternal(t){let e=this.eventListeners.get(t);if(e&&e.length>0){let r=e.pop();e.length===0&&this.eventListeners.delete(t),this.removeEventListener("event",r)}}addEventListenerOnceInternal(t){let e=r=>{if(!Lr(r))throw new Error('Internal error: expected CustomEvent for "event" type');this.untrackWrappedListener(this.eventListeners,t,e),t.call(this,r.detail)};this.trackListener(this.eventListeners,t,e),this.addEventListener("event",e,{once:!0})}addFinishedListenerInternal(t){let e=()=>{t.call(this)};this.trackListener(this.finishedListeners,t,e),this.addEventListener("finished",e)}removeFinishedListenerInternal(t){let e=this.finishedListeners.get(t);if(e&&e.length>0){let r=e.pop();e.length===0&&this.finishedListeners.delete(t),this.removeEventListener("finished",r)}}addFinishedListenerOnceInternal(t){let e=()=>{this.untrackWrappedListener(this.finishedListeners,t,e),t.call(this)};this.trackListener(this.finishedListeners,t,e),this.addEventListener("finished",e,{once:!0})}},$a={createFrom:(t,e)=>t?.includes(e)?t:[...t??[],e],parseServiceParameter:t=>{if(!t)return[];let e=new Set(t.split(",").map(r=>r.trim()).filter(r=>r.length>0));return Array.from(e)},toServiceParameter:t=>t.join(",")},za="0.3";var qa=class{_requestedExtensions;_user;_requestedVersion;_tenant;_activatedExtensions;_state;constructor(t){this._requestedExtensions=t?.requestedExtensions,this._user=t?.user,this._tenant=t?.tenant,this._requestedVersion=t?.requestedVersion||za,this._state=t?.state??new Map}get tenant(){return this._tenant}setTenant(t){if(this._tenant!==void 0)throw new Error("Tenant is already set.");this._tenant=t}get user(){return this._user}get activatedExtensions(){return this._activatedExtensions}get requestedExtensions(){return this._requestedExtensions}get requestedVersion(){return this._requestedVersion}get state(){return this._state}addActivatedExtension(t){this._activatedExtensions=$a.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function Ne(t){return t.user?.userName||"unknown"}var Fa="a2a-protocol.org",Ba="type.googleapis.com/google.rpc.ErrorInfo",Hr=Symbol.for("@a2a-js/sdk.A2AError"),Ft=class Kr extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(Hr in e))return!1;if(this===Kr)return!0;for(let r=Object.getPrototypeOf(e);r!==null;r=Object.getPrototypeOf(r))if(r.constructor?.name===this.name)return!0;return!1}constructor(e){let r=typeof e=="string"?{message:e}:e;super(r?.message??"An unexpected error occurred.",r?.cause!==void 0?{cause:r.cause}:void 0),this.name=new.target.name,r?.metadata&&Object.keys(r.metadata).length>0&&(this.metadata=r.metadata)}toErrorInfo(){return{"@type":Ba,reason:this.reason,domain:Fa,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(Ft.prototype,Hr,{value:!0});var Vr=[{name:"TaskNotFoundError",reason:"TASK_NOT_FOUND",defaultMessage:"Task not found"},{name:"TaskNotCancelableError",reason:"TASK_NOT_CANCELABLE",defaultMessage:"Task cannot be canceled"},{name:"PushNotificationNotSupportedError",reason:"PUSH_NOTIFICATION_NOT_SUPPORTED",defaultMessage:"Push Notification is not supported"},{name:"UnsupportedOperationError",reason:"UNSUPPORTED_OPERATION",defaultMessage:"This operation is not supported"},{name:"ContentTypeNotSupportedError",reason:"CONTENT_TYPE_NOT_SUPPORTED",defaultMessage:"Incompatible content types"},{name:"InvalidAgentResponseError",reason:"INVALID_AGENT_RESPONSE",defaultMessage:"Invalid agent response type"},{name:"ExtendedAgentCardNotConfiguredError",reason:"EXTENDED_AGENT_CARD_NOT_CONFIGURED",defaultMessage:"Extended Agent Card not configured"},{name:"ExtensionSupportRequiredError",reason:"EXTENSION_SUPPORT_REQUIRED",defaultMessage:"Extension support required"},{name:"VersionNotSupportedError",reason:"VERSION_NOT_SUPPORTED",defaultMessage:"Version not supported"},{name:"RequestMalformedError",reason:"INVALID_PARAMS",defaultMessage:"Request malformed"}],b=Object.freeze(Object.fromEntries(Vr.map(t=>[t.name,t]))),rl=Object.freeze(Object.fromEntries(Vr.map(t=>[t.reason,t])));function j(t){return{[t.name]:class extends Ft{reason=t.reason;constructor(r){r===void 0?super({message:t.defaultMessage}):typeof r=="string"?super({message:r}):super({message:t.defaultMessage,...r})}}}[t.name]}var H=j(b.TaskNotFoundError),me=j(b.TaskNotCancelableError),At=j(b.PushNotificationNotSupportedError),ot=j(b.UnsupportedOperationError),Gr=j(b.ContentTypeNotSupportedError),Ha=j(b.InvalidAgentResponseError),Qr=j(b.ExtendedAgentCardNotConfiguredError),Yr=j(b.ExtensionSupportRequiredError),Ka=j(b.VersionNotSupportedError),q=j(b.RequestMalformedError),Wr=Object.freeze({TaskNotFoundError:H,TaskNotCancelableError:me,PushNotificationNotSupportedError:At,UnsupportedOperationError:ot,ContentTypeNotSupportedError:Gr,InvalidAgentResponseError:Ha,ExtendedAgentCardNotConfiguredError:Qr,ExtensionSupportRequiredError:Yr,VersionNotSupportedError:Ka,RequestMalformedError:q});function $r(t){if(t instanceof Error)return t.message;if(t==null)return String(t);if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}var K={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,CONFLICT:409,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501},Z={OK:"OK",CANCELLED:"CANCELLED",UNKNOWN:"UNKNOWN",INVALID_ARGUMENT:"INVALID_ARGUMENT",DEADLINE_EXCEEDED:"DEADLINE_EXCEEDED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",PERMISSION_DENIED:"PERMISSION_DENIED",RESOURCE_EXHAUSTED:"RESOURCE_EXHAUSTED",FAILED_PRECONDITION:"FAILED_PRECONDITION",ABORTED:"ABORTED",OUT_OF_RANGE:"OUT_OF_RANGE",UNIMPLEMENTED:"UNIMPLEMENTED",INTERNAL:"INTERNAL",UNAVAILABLE:"UNAVAILABLE",DATA_LOSS:"DATA_LOSS",UNAUTHENTICATED:"UNAUTHENTICATED"},Va=Object.freeze({TaskNotFoundError:K.NOT_FOUND,TaskNotCancelableError:K.BAD_REQUEST,PushNotificationNotSupportedError:K.BAD_REQUEST,UnsupportedOperationError:K.BAD_REQUEST,ContentTypeNotSupportedError:K.BAD_REQUEST,InvalidAgentResponseError:K.INTERNAL_SERVER_ERROR,ExtendedAgentCardNotConfiguredError:K.BAD_REQUEST,ExtensionSupportRequiredError:K.BAD_REQUEST,VersionNotSupportedError:K.BAD_REQUEST,RequestMalformedError:K.BAD_REQUEST}),il=Object.freeze({TaskNotFoundError:Z.NOT_FOUND,TaskNotCancelableError:Z.FAILED_PRECONDITION,PushNotificationNotSupportedError:Z.FAILED_PRECONDITION,UnsupportedOperationError:Z.FAILED_PRECONDITION,ContentTypeNotSupportedError:Z.INVALID_ARGUMENT,InvalidAgentResponseError:Z.INTERNAL,ExtendedAgentCardNotConfiguredError:Z.FAILED_PRECONDITION,ExtensionSupportRequiredError:Z.FAILED_PRECONDITION,VersionNotSupportedError:Z.FAILED_PRECONDITION,RequestMalformedError:Z.INVALID_ARGUMENT});function tt(t){let e=Wr[t],r=Va[t]??K.INTERNAL_SERVER_ERROR;return{[`Rest${t}`]:class extends e{transport="rest";statusCode;headers;constructor(a){super(a),this.name=t,this.statusCode=a?.statusCode??r,a?.headers&&(this.headers=a.headers)}}}[`Rest${t}`]}var Ga=tt("TaskNotFoundError"),Qa=tt("TaskNotCancelableError"),Ya=tt("PushNotificationNotSupportedError"),Wa=tt("UnsupportedOperationError"),Xa=tt("ContentTypeNotSupportedError"),Za=tt("InvalidAgentResponseError"),ba=tt("ExtendedAgentCardNotConfiguredError"),ja=tt("ExtensionSupportRequiredError"),tn=tt("VersionNotSupportedError"),en=tt("RequestMalformedError"),al=Object.freeze({TaskNotFoundError:Ga,TaskNotCancelableError:Qa,PushNotificationNotSupportedError:Ya,UnsupportedOperationError:Wa,ContentTypeNotSupportedError:Xa,InvalidAgentResponseError:Za,ExtendedAgentCardNotConfiguredError:ba,ExtensionSupportRequiredError:ja,VersionNotSupportedError:tn,RequestMalformedError:en}),M={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TASK_NOT_FOUND:-32001,TASK_NOT_CANCELABLE:-32002,PUSH_NOTIFICATION_NOT_SUPPORTED:-32003,UNSUPPORTED_OPERATION:-32004,CONTENT_TYPE_NOT_SUPPORTED:-32005,INVALID_AGENT_RESPONSE:-32006,EXTENDED_CARD_NOT_CONFIGURED:-32007,EXTENSION_SUPPORT_REQUIRED:-32008,VERSION_NOT_SUPPORTED:-32009},Xr=Object.freeze({TaskNotFoundError:M.TASK_NOT_FOUND,TaskNotCancelableError:M.TASK_NOT_CANCELABLE,PushNotificationNotSupportedError:M.PUSH_NOTIFICATION_NOT_SUPPORTED,UnsupportedOperationError:M.UNSUPPORTED_OPERATION,ContentTypeNotSupportedError:M.CONTENT_TYPE_NOT_SUPPORTED,InvalidAgentResponseError:M.INVALID_AGENT_RESPONSE,ExtendedAgentCardNotConfiguredError:M.EXTENDED_CARD_NOT_CONFIGURED,ExtensionSupportRequiredError:M.EXTENSION_SUPPORT_REQUIRED,VersionNotSupportedError:M.VERSION_NOT_SUPPORTED,RequestMalformedError:M.INVALID_PARAMS}),nl=Object.freeze(Object.fromEntries(Object.entries(Xr).map(([t,e])=>[e,t])));function et(t){let e=Wr[t],r=Xr[t]??M.INTERNAL_ERROR;return{[`JsonRpc${t}`]:class extends e{transport="jsonrpc";envelopeCode;data;constructor(a){super(a),this.name=t,this.envelopeCode=a?.envelopeCode??r,a?.data!==void 0&&(this.data=a.data)}}}[`JsonRpc${t}`]}var rn=et("TaskNotFoundError"),an=et("TaskNotCancelableError"),nn=et("PushNotificationNotSupportedError"),sn=et("UnsupportedOperationError"),on=et("ContentTypeNotSupportedError"),ln=et("InvalidAgentResponseError"),dn=et("ExtendedAgentCardNotConfiguredError"),un=et("ExtensionSupportRequiredError"),fn=et("VersionNotSupportedError"),cn=et("RequestMalformedError"),sl=Object.freeze({TaskNotFoundError:rn,TaskNotCancelableError:an,PushNotificationNotSupportedError:nn,UnsupportedOperationError:sn,ContentTypeNotSupportedError:on,InvalidAgentResponseError:ln,ExtendedAgentCardNotConfiguredError:dn,ExtensionSupportRequiredError:un,VersionNotSupportedError:fn,RequestMalformedError:cn});var ol={[M.PARSE_ERROR]:"RequestMalformedError",[M.INVALID_REQUEST]:"RequestMalformedError",[M.METHOD_NOT_FOUND]:"RequestMalformedError"};function hn(t){switch(t){case 0:case"TASK_STATE_UNSPECIFIED":return 0;case 1:case"TASK_STATE_SUBMITTED":return 1;case 2:case"TASK_STATE_WORKING":return 2;case 3:case"TASK_STATE_COMPLETED":return 3;case 4:case"TASK_STATE_FAILED":return 4;case 5:case"TASK_STATE_CANCELED":return 5;case 6:case"TASK_STATE_INPUT_REQUIRED":return 6;case 7:case"TASK_STATE_REJECTED":return 7;case 8:case"TASK_STATE_AUTH_REQUIRED":return 8;default:return-1}}function pn(t){switch(t){case 0:return"TASK_STATE_UNSPECIFIED";case 1:return"TASK_STATE_SUBMITTED";case 2:return"TASK_STATE_WORKING";case 3:return"TASK_STATE_COMPLETED";case 4:return"TASK_STATE_FAILED";case 5:return"TASK_STATE_CANCELED";case 6:return"TASK_STATE_INPUT_REQUIRED";case 7:return"TASK_STATE_REJECTED";case 8:return"TASK_STATE_AUTH_REQUIRED";default:return"UNRECOGNIZED"}}function Sn(t){switch(t){case 0:case"ROLE_UNSPECIFIED":return 0;case 1:case"ROLE_USER":return 1;case 2:case"ROLE_AGENT":return 2;default:return-1}}function Tn(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var zr={fromJSON(t){return{id:y(t.id)?globalThis.String(t.id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",status:y(t.status)?Bt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>Kt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>ht.fromJSON(e)):[],metadata:pt(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=Bt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>Kt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>ht.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Bt={fromJSON(t){return{state:y(t.state)?hn(t.state):0,message:y(t.message)?ht.fromJSON(t.message):void 0,timestamp:y(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=pn(t.state)),t.message!==void 0&&(e.message=ht.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Ht={fromJSON(t){return{content:y(t.text)?{$case:"text",value:globalThis.String(t.text)}:y(t.raw)?{$case:"raw",value:Buffer.from(mn(t.raw))}:y(t.url)?{$case:"url",value:globalThis.String(t.url)}:y(t.data)?{$case:"data",value:t.data}:void 0,metadata:pt(t.metadata)?t.metadata:void 0,filename:y(t.filename)?globalThis.String(t.filename):"",mediaType:y(t.mediaType)?globalThis.String(t.mediaType):y(t.media_type)?globalThis.String(t.media_type):""}},toJSON(t){let e={};return t.content?.$case==="text"?e.text=t.content.value:t.content?.$case==="raw"?e.raw=Nn(t.content.value):t.content?.$case==="url"?e.url=t.content.value:t.content?.$case==="data"&&(e.data=t.content.value),t.metadata!==void 0&&(e.metadata=t.metadata),t.filename!==""&&(e.filename=t.filename),t.mediaType!==""&&(e.mediaType=t.mediaType),e}},ht={fromJSON(t){return{messageId:y(t.messageId)?globalThis.String(t.messageId):y(t.message_id)?globalThis.String(t.message_id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",taskId:y(t.taskId)?globalThis.String(t.taskId):y(t.task_id)?globalThis.String(t.task_id):"",role:y(t.role)?Sn(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Ht.fromJSON(e)):[],metadata:pt(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[],referenceTaskIds:globalThis.Array.isArray(t?.referenceTaskIds)?t.referenceTaskIds.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.reference_task_ids)?t.reference_task_ids.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.messageId!==""&&(e.messageId=t.messageId),t.contextId!==""&&(e.contextId=t.contextId),t.taskId!==""&&(e.taskId=t.taskId),t.role!==0&&(e.role=Tn(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Ht.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),t.referenceTaskIds?.length&&(e.referenceTaskIds=t.referenceTaskIds),e}},Kt={fromJSON(t){return{artifactId:y(t.artifactId)?globalThis.String(t.artifactId):y(t.artifact_id)?globalThis.String(t.artifact_id):"",name:y(t.name)?globalThis.String(t.name):"",description:y(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Ht.fromJSON(e)):[],metadata:pt(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.artifactId!==""&&(e.artifactId=t.artifactId),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.parts?.length&&(e.parts=t.parts.map(r=>Ht.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},ce={fromJSON(t){return{taskId:y(t.taskId)?globalThis.String(t.taskId):y(t.task_id)?globalThis.String(t.task_id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",status:y(t.status)?Bt.fromJSON(t.status):void 0,metadata:pt(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=Bt.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},he={fromJSON(t){return{taskId:y(t.taskId)?globalThis.String(t.taskId):y(t.task_id)?globalThis.String(t.task_id):"",contextId:y(t.contextId)?globalThis.String(t.contextId):y(t.context_id)?globalThis.String(t.context_id):"",artifact:y(t.artifact)?Kt.fromJSON(t.artifact):void 0,append:y(t.append)?globalThis.Boolean(t.append):!1,lastChunk:y(t.lastChunk)?globalThis.Boolean(t.lastChunk):y(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:pt(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.artifact!==void 0&&(e.artifact=Kt.toJSON(t.artifact)),t.append!==!1&&(e.append=t.append),t.lastChunk!==!1&&(e.lastChunk=t.lastChunk),t.metadata!==void 0&&(e.metadata=t.metadata),e}};var gn={fromJSON(t){return{payload:y(t.task)?{$case:"task",value:zr.fromJSON(t.task)}:y(t.message)?{$case:"message",value:ht.fromJSON(t.message)}:y(t.statusUpdate)?{$case:"statusUpdate",value:ce.fromJSON(t.statusUpdate)}:y(t.status_update)?{$case:"statusUpdate",value:ce.fromJSON(t.status_update)}:y(t.artifactUpdate)?{$case:"artifactUpdate",value:he.fromJSON(t.artifactUpdate)}:y(t.artifact_update)?{$case:"artifactUpdate",value:he.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=zr.toJSON(t.payload.value):t.payload?.$case==="message"?e.message=ht.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=ce.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=he.toJSON(t.payload.value)),e}};function mn(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Nn(t){return globalThis.Buffer.from(t).toString("base64")}function pt(t){return typeof t=="object"&&t!==null}function y(t){return t!=null}var En="1.0",Zr="0.3",vn="application/a2a+json",br=50,ll=4*1024*1024,It=[3,4,5,7],On=[0,1,2,3,4,5,6,7,8],jr=[6],ti=[8],yn=[...jr,...ti];function qr(t){return"status"in t}function Fr(t,e){return{tenant:t.tenant??"",owner:e(t)}}function _n(t,e){return Buffer.from(`${t}|${e}`).toString("base64")}function kn(t){try{let[e,...r]=Buffer.from(t,"base64").toString("utf-8").split("|");if(r.length===0)throw new q("Invalid page token format.");return{timestamp:e,id:r.join("|")}}catch(e){throw e instanceof q?e:new q("Token is not a valid base64-encoded cursor.")}}var Ee=class{_store=new Map;_ownerResolver;constructor(t){this._ownerResolver=t}getBucket(t){let{tenant:e,owner:r}=Fr(t,this._ownerResolver);return this._store.get(e)?.get(r)}getOrCreateBucket(t){let{tenant:e,owner:r}=Fr(t,this._ownerResolver),i=this._store.get(e);i||(i=new Map,this._store.set(e,i));let a=i.get(r);return a||(a=new Map,i.set(r,a)),a}},pe=new qa,ve=class{_scopedBuses;constructor(t=Ne){this._scopedBuses=new Ee(t)}createOrGetByTaskId(t,e){let r=this._scopedBuses.getOrCreateBucket(e??pe),i=r.get(t);return i||(i=new La,r.set(t,i)),i}getByTaskId(t,e){return this._scopedBuses.getBucket(e??pe)?.get(t)}cleanupByTaskId(t,e){let r=this._scopedBuses.getBucket(e??pe);r?.get(t)?.removeAllListeners(),r?.delete(t)}},$t=class{eventBus;eventQueue=[];resolvePromise;stopped=!1;constructor(t){this.eventBus=t,this.eventBus.on("event",this.handleEvent),this.eventBus.on("finished",this.handleFinished)}handleEvent=t=>{this.stopped||(this.eventQueue.push(t),this.resolvePromise&&(this.resolvePromise(),this.resolvePromise=void 0))};handleFinished=()=>{this.stop()};async*events(){for(;!this.stopped||this.eventQueue.length>0;)if(this.eventQueue.length>0){let t=this.eventQueue.shift();if(yield t,t.kind==="message"||t.kind==="statusUpdate"&&t.data.status&&(It.includes(t.data.status.state)||jr.includes(t.data.status.state))){this.handleFinished();break}}else this.stopped||await new Promise(t=>{this.resolvePromise=t})}stop(){this.stopped=!0,this.resolvePromise&&(this.resolvePromise(),this.resolvePromise=void 0),this.eventBus.off("event",this.handleEvent),this.eventBus.off("finished",this.handleFinished)}},zt=new Map;function Se(t,e){let r=t.tenant??"",i=t.user?.userName??"";return`${r}\0${i}\0${e}`}async function Te(t,e){let i=(zt.get(t)??Promise.resolve()).then(e,e);zt.set(t,i);let a=()=>{zt.get(t)===i&&zt.delete(t)};return i.then(a,a),i}var qt=class{taskStore;serverCallContext;currentTask;latestUserMessage;finalMessageResult;lastSeenTaskId;constructor(t,e){this.taskStore=t,this.serverCallContext=e}setContext(t){this.latestUserMessage=structuredClone(t)}async processEvent(t){switch(t.kind){case"message":{this.finalMessageResult=structuredClone(t.data);break}case"task":{let e=t.data;if(!e.id){await this.processTaskEventLocked(e);break}await Te(Se(this.serverCallContext,e.id),()=>this.processTaskEventLocked(e));break}case"statusUpdate":{let e=t.data;if(!e.taskId){await this.applyStatusUpdate(e);break}await Te(Se(this.serverCallContext,e.taskId),()=>this.applyStatusUpdate(e));break}case"artifactUpdate":{let e=t.data;if(!e.taskId){await this.applyArtifactUpdate(e);break}await Te(Se(this.serverCallContext,e.taskId),()=>this.applyArtifactUpdate(e));break}default:ge(t)}}notePersistedTaskId(t){t&&(this.lastSeenTaskId&&this.lastSeenTaskId!==t&&console.warn(`ResultManager: event for task ${t} arrived after processing events for ${this.lastSeenTaskId}. This indicates the executor switched tasks mid-stream, which is not expected in normal operation.`),this.lastSeenTaskId=t)}async processTaskEventLocked(t){this.notePersistedTaskId(t.id);let e=t.id?await this.taskStore.load(t.id,this.serverCallContext):void 0,r=structuredClone(t);if(e&&e.id===t.id&&((!r.history||r.history.length===0)&&e.history&&(r.history=structuredClone(e.history)),r.artifacts=this.mergeArtifacts(e.artifacts,t.artifacts),(e.metadata||t.metadata)&&(r.metadata={...structuredClone(e.metadata??{}),...structuredClone(t.metadata??{})})),this.latestUserMessage){let i=this.latestUserMessage;r.history?.find(a=>a.messageId===i.messageId)||(r.history=[structuredClone(i),...r.history||[]])}this.currentTask=r,await this.saveCurrentTask()}async loadPersistedTask(t,e){if(!t)return;let r=await this.taskStore.load(t,this.serverCallContext);return r||console.warn(`ResultManager: Received ${e} for unknown task ${t}`),r}async applyStatusUpdate(t){this.notePersistedTaskId(t.taskId);let e=await this.loadPersistedTask(t.taskId,"status update");if(!e||e.id!==t.taskId){this.currentTask=e;return}let r=e.status?.state;if(r!==void 0&&It.includes(r)&&t.status?.state!==r){console.warn(`ResultManager: ignoring status update ${t.status?.state} for terminal task ${e.id} (${r})`),this.currentTask=e;return}e.status=structuredClone(t.status),t.metadata&&(e.metadata={...e.metadata,...structuredClone(t.metadata)});let i=t.status?.message;i&&(e.history?.find(a=>a.messageId===i.messageId)||(e.history=[...e.history||[],structuredClone(i)])),this.currentTask=e,await this.saveCurrentTask()}async applyArtifactUpdate(t){let e=t.artifact;if(!e)return;this.notePersistedTaskId(t.taskId);let r=await this.loadPersistedTask(t.taskId,"artifact update");if(!r||r.id!==t.taskId){this.currentTask=r;return}r.artifacts||(r.artifacts=[]);let i=r.artifacts.findIndex(a=>a.artifactId===e.artifactId);if(i!==-1)if(t.append){let a=r.artifacts[i];a.parts=[...a.parts||[],...structuredClone(e.parts||[])],e.description&&(a.description=e.description),e.name&&(a.name=e.name),e.metadata&&(a.metadata={...a.metadata,...structuredClone(e.metadata)})}else r.artifacts[i]=structuredClone(e);else r.artifacts.push(structuredClone(e));t.metadata&&(r.metadata={...r.metadata,...structuredClone(t.metadata)}),this.currentTask=r,await this.saveCurrentTask()}mergeArtifacts(t,e){if(!t||t.length===0)return e?structuredClone(e):[];if(!e||e.length===0)return structuredClone(t);let r=new Map;for(let n of e)r.set(n.artifactId,n);let i=t.map(n=>structuredClone(r.get(n.artifactId)??n)),a=new Set(t.map(n=>n.artifactId));for(let n of e)a.has(n.artifactId)||i.push(structuredClone(n));return i}async saveCurrentTask(){this.currentTask&&await this.taskStore.save(this.currentTask,this.serverCallContext)}getFinalResult(){return this.finalMessageResult?this.finalMessageResult:this.currentTask}getCurrentTask(){return this.currentTask}},An=class{_scopedStore;constructor(t=Ne){this._scopedStore=new Ee(t)}async save(t,e,r){let i=this._scopedStore.getOrCreateBucket(e),a=i.get(t)||[];r.id||(r.id=crypto.randomUUID());let n=e.requestedVersion||Zr,o=a.findIndex(d=>d.config.id===r.id);o!==-1&&a.splice(o,1),a.push({config:structuredClone(r),wireVersion:n}),i.set(t,a)}async load(t,e){let r=this._scopedStore.getBucket(e)?.get(t);return r?r.map(i=>structuredClone(i.config)):[]}async loadWithMetadata(t,e){let r=this._scopedStore.getBucket(e)?.get(t);return r?r.map(i=>structuredClone(i)):[]}async delete(t,e,r){r===void 0&&(r=t);let i=this._scopedStore.getBucket(e);if(!i)return;let a=i.get(t);if(!a)return;let n=a.findIndex(o=>o.config.id===r);n!==-1&&a.splice(n,1),a.length===0&&i.delete(t)}},In=class{serialize(t,e){return{body:JSON.stringify(gn.toJSON(t)),contentType:vn}}},Cn=class{pushNotificationStore;notificationChain;options;serializers;fallbackSerializer;warnedMissingSerializers=new Set;constructor(t,e={}){this.pushNotificationStore=t,this.notificationChain=new Map,this.options={timeout:e.timeout??5e3,tokenHeaderName:e.tokenHeaderName??"X-A2A-Notification-Token"};let r=new In;if(this.serializers=new Map([["1.0",r]]),e.serializers)for(let[i,a]of Object.entries(e.serializers))a&&this.serializers.set(i,a);this.fallbackSerializer=this.serializers.get("1.0")??r}async send(t,e,r){let i=this._getTaskId(t);if(!i)return;let a=await this._loadStoredConfigs(i,e);if(!a||a.length===0)return;let o=(this.notificationChain.get(i)??Promise.resolve()).catch(()=>{}).then(async()=>{let d=a.map(async f=>{try{await this._dispatchNotification(t,f,i,r)}catch(T){console.error(`Error sending push notification for task_id=${i} to URL: ${f.config.url}. Error:`,T)}});await Promise.all(d)});return this.notificationChain.set(i,o),o.finally(()=>{this.notificationChain.get(i)===o&&this.notificationChain.delete(i)})}_getTaskId(t){let e=t.payload;if(!e)throw new Error("StreamResponse payload is undefined");switch(e.$case){case"task":return e.value.id;case"statusUpdate":case"artifactUpdate":case"message":return e.value.taskId;default:{let r=e;throw new Error(`Unknown payload case: ${r.$case}`)}}}async _loadStoredConfigs(t,e){if(this.pushNotificationStore.loadWithMetadata)return await this.pushNotificationStore.loadWithMetadata(t,e);let r=await this.pushNotificationStore.load(t,e),i=e.requestedVersion||Zr;return r.map(a=>({config:a,wireVersion:i}))}_resolveSerializer(t){let e=this.serializers.get(t);return e||(this.warnedMissingSerializers.has(t)||(this.warnedMissingSerializers.add(t),console.warn(`No push notification serializer registered for wire version '${t}'; falling back to '${En}'. Register one via DefaultPushNotificationSenderOptions.serializers to silence this warning.`)),this.fallbackSerializer)}_buildAuthHeaders(t){let e={};return t.authentication?.scheme&&t.authentication?.credentials?e.Authorization=`${t.authentication.scheme} ${t.authentication.credentials}`:t.token&&(e[this.options.tokenHeaderName]=t.token),e}async _dispatchNotification(t,e,r,i){let{config:a,wireVersion:n}=e,o=a.url,d=new AbortController,f=setTimeout(()=>d.abort(),this.options.timeout);try{let T=this._resolveSerializer(n),{body:p,contentType:O}=T.serialize(t,i),u=await fetch(o,{method:"POST",headers:{"Content-Type":O,...this._buildAuthHeaders(a)},body:p,signal:d.signal});if(!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);console.info(`Push notification sent for task_id=${r} to URL: ${o}`)}finally{clearTimeout(f)}}},ei=class{agentCard;taskStore;agentExecutor;eventBusManager;pushNotificationStore;pushNotificationSender;extendedAgentCardProvider;agentCardSignatureGenerator;keepBusAliveStates;validateInputModes;constructor(t,e,r,i=new ve,a,n,o,d,f={}){this.agentCard=t,this.taskStore=e,this.agentExecutor=r,this.eventBusManager=i,this.extendedAgentCardProvider=o,this.agentCardSignatureGenerator=d,this.keepBusAliveStates=new Set(f.keepBusAliveStates??yn),this.validateInputModes=f.validateInputModes??!1,t.capabilities?.pushNotifications&&(this.pushNotificationStore=a||new An,this.pushNotificationSender=n||new Cn(this.pushNotificationStore))}async getAgentCard(){return this.agentCardSignatureGenerator?this.agentCardSignatureGenerator(this.agentCard):this.agentCard}async getAuthenticatedExtendedAgentCard(t,e){if(!this.agentCard.capabilities?.extendedAgentCard)throw new ot("Agent does not support authenticated extended card.");if(!this.extendedAgentCardProvider)throw new Qr;let r;return typeof this.extendedAgentCardProvider=="function"?r=await this.extendedAgentCardProvider(e):e.user?.isAuthenticated?r=this.extendedAgentCardProvider:r=this.agentCard,this.agentCardSignatureGenerator?this.agentCardSignatureGenerator(r):r}_validateInputModes(t,e){let r=e.defaultInputModes??[];if(!(!this.validateInputModes||r.length===0)){for(let i of t.parts??[])if(i.mediaType&&!r.includes(i.mediaType))throw new Gr(`Media type '${i.mediaType}' is not supported. Supported media types: ${r.join(", ")}.`)}}async _createRequestContext(t,e){let r=t.message;if(!r)throw new q("request.message is required.");let i,a,n=await this.getAgentCard();this._validateInputModes(r,n);let o=n.capabilities?.extensions??[],d=new Set(e.requestedExtensions??[]),f=o.filter(h=>h.required&&!d.has(h.uri)).map(h=>h.uri);if(f.length>0)throw new Yr(`Client must declare support for required extensions: ${f.join(", ")}`);if(r.taskId){if(this._requireValidTaskId(r.taskId),i=await this.taskStore.load(r.taskId,e),!i)throw new H(`Task not found: ${r.taskId}`);if(i.status?.state!==void 0&&It.includes(i.status.state))throw new ot(`Task ${i.id} is in a terminal state (${i.status.state}) and cannot be modified.`);if(r.contextId&&i.contextId&&r.contextId!==i.contextId)throw new q(`contextId mismatch: message contextId '${r.contextId}' does not match task '${i.id}' contextId '${i.contextId}'`);i.history=[...i.history||[],r],await this.taskStore.save(i,e)}let T=r.taskId||crypto.randomUUID(),p=r.referenceTaskIds||[];if(p.length>0){a=[];for(let h of p){let g=await this.taskStore.load(h,e);g?a.push(g):console.warn(`Reference task ${h} not found.`)}}let O=r.contextId||i?.contextId||crypto.randomUUID();if(e.requestedExtensions){let h=new Set(o.map(g=>g.uri));e.setRequestedExtensions(e.requestedExtensions.filter(g=>h.has(g)))}let u={...r,contextId:O,taskId:T},N={...t,message:u};return new Ma(N,T,O,e,i,a)}async _processEvents(t,e,r,i,a){let n=!1,o=!1;try{for await(let d of r.events()){await e.processEvent(d);try{let f=await this._mapEventToStreamResponse(d,i);await this._sendPushNotificationIfNeeded(i,f,structuredClone(e.getCurrentTask()))}catch(f){console.error(`Error sending push notification: ${f}`)}if(a?.firstResultResolver&&!n){let f;if(d.kind==="message")f=d.data;else if(d.kind==="task")f=d.data;else{let T=e.getFinalResult();T&&("messageId"in T||"id"in T)&&(f=T)}f&&(a.firstResultResolver(f),n=!0)}if(a?.authRequiredSnapshotResolver&&!o&&d.kind==="statusUpdate"&&d.data.status&&ti.includes(d.data.status.state)){let f=e.getCurrentTask();f&&(a.authRequiredSnapshotResolver(structuredClone(f)),o=!0,n=!0)}}a?.firstResultResolver&&a?.firstResultRejector&&!n&&a.firstResultRejector(new q("Execution finished before a message or task was produced."))}catch(d){console.error(`Event processing loop failed for task ${t}:`,d),await this._handleProcessingError(d,e,n,t,a?.firstResultRejector)}finally{r.stop()}}_continueDraining(t,e){e.catch(r=>{console.error(`Background AUTH_REQUIRED drain failed for task ${t}:`,r instanceof Error?r.message:r)})}_runExecutor(t,e,r,i){let a=Rn(e);this.agentExecutor.execute(r,e).catch(n=>{let o=$r(n);console.error(`Agent execution failed for message ${i.messageId}:`,n);let d={id:r.taskId,contextId:i.contextId,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:r.taskId,contextId:i.contextId,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},artifacts:[],history:r.task?.history?[...r.task.history]:[],metadata:{}};i&&!d.history?.find(f=>f.messageId===i.messageId)&&d.history?.push(i),e.publish(w.task(d)),e.publish(w.statusUpdate({taskId:d.id,contextId:d.contextId,status:d.status,metadata:{}}))}).finally(()=>{this._settleBus(t,e,a(),r.context)})}_settleBus(t,e,r,i){this.eventBusManager.settleByTaskId?.(t,e,r,i)||r!==void 0&&this.keepBusAliveStates.has(r)||(e.finished(),this.eventBusManager.cleanupByTaskId(t,i))}_runStreamExecutor(t,e,r){let i=r.userMessage,a=Un(e);this.agentExecutor.execute(r,e).catch(n=>{let o=$r(n);console.error(`Agent execution failed for stream message ${i.messageId}:`,n);let d=a().task,f=d?.id??r.taskId,T=d?.contextId??i.contextId;if(!d){let O={id:r.taskId,contextId:i.contextId,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:r.taskId,contextId:i.contextId,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},artifacts:[],history:r.task?.history?[...r.task.history]:[],metadata:{}};i&&!O.history?.find(u=>u.messageId===i.messageId)&&O.history?.push(i),e.publish(w.task(O))}let p={taskId:f,contextId:T,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:f,contextId:T,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},metadata:{}};e.publish(w.statusUpdate(p))}).finally(()=>{this._settleBus(t,e,a().state,r.context)})}async sendMessage(t,e){let r=t.message;if(!r?.messageId)throw new q("message.messageId is required.");let i=t.configuration?.returnImmediately!==!0,a=new qt(this.taskStore,e);a.setContext(r);let n=await this._createRequestContext(t,e),o=n.taskId,d=n.userMessage;if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let O=structuredClone(t.configuration.taskPushNotificationConfig);O.taskId=o,await this.pushNotificationStore?.save(o,e,O)}let f=this.eventBusManager.createOrGetByTaskId(o,e),T=new $t(f);this._runExecutor(o,f,n,d);let p=t.configuration;return i?new Promise((O,u)=>{let N=this._processEvents(o,a,T,e,{authRequiredSnapshotResolver:h=>{this._applyHistoryLengthSemantics(h,p??{}),O(h),this._continueDraining(o,N)},firstResultRejector:u});N.then(()=>{let h=a.getFinalResult();if(!h){u(new Ft("Agent execution finished without a result, and no task context found."));return}qr(h)&&this._applyHistoryLengthSemantics(h,p??{}),O(h)}).catch(u)}):new Promise((O,u)=>{this._processEvents(o,a,T,e,{firstResultResolver:N=>{qr(N)&&this._applyHistoryLengthSemantics(N,p??{}),O(N)},firstResultRejector:u})})}async*sendMessageStream(t,e){if(!this.agentCard.capabilities?.streaming)throw new ot("Streaming is not supported.");let r=t.message;if(!r?.messageId)throw new q("message.messageId is required for streaming.");let i=new qt(this.taskStore,e);i.setContext(r);let a=await this._createRequestContext(t,e),n=a.taskId,o=this.eventBusManager.createOrGetByTaskId(n,e),d=new $t(o);if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let T=structuredClone(t.configuration.taskPushNotificationConfig);T.taskId=n,await this.pushNotificationStore?.save(n,e,T)}this._runStreamExecutor(n,o,a);let f="undetermined";try{for await(let T of d.events()){f=this._advanceStreamPattern(T,f),await i.processEvent(T);let p=await this._mapEventToStreamResponse(T,e);p.payload?.$case==="task"&&this._applyHistoryLengthSemantics(p.payload.value,t.configuration??{}),await this._sendPushNotificationIfNeeded(e,p,i.getCurrentTask()),yield p}}finally{d.stop()}}async getTask(t,e){let r=t.id;this._requireValidTaskId(r);let i=await this.taskStore.load(r,e);if(!i)throw new H(`Task not found: ${t.id}`);return this._applyHistoryLengthSemantics(i,t),i}async listTasks(t,e){let r=t.pageSize??br;if(!Number.isInteger(r)||r<1||r>100)throw new q("pageSize must be between 1 and 100");if(t.status!==void 0&&!On.includes(t.status))throw new q(`Invalid status filter: ${String(t.status)}`);if(t.statusTimestampAfter&&isNaN(Date.parse(t.statusTimestampAfter)))throw new q("statusTimestampAfter must be a valid ISO 8601 date string");let i=await this.taskStore.list({...t,pageSize:r},e);for(let a of i.tasks)this._applyHistoryLengthSemantics(a,t);return i}async cancelTask(t,e){let r=t.id;this._requireValidTaskId(r);let i=await this.taskStore.load(r,e);if(!i)throw new H(`Task not found: ${t.id}`);let a=i.status?.state;if(a===5)return i;if(a!==void 0&&It.includes(a))throw new me(`Task not cancelable: ${t.id}`);let n=this.eventBusManager.getByTaskId(r,e);if(n){let d=new $t(n);await this.agentExecutor.cancelTask(r,n),await this._processEvents(r,new qt(this.taskStore,e),d,e)}else{let d={role:2,messageId:crypto.randomUUID(),taskId:i.id,contextId:i.contextId,parts:[{content:{$case:"text",value:"Task cancellation requested by user."},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]};await new qt(this.taskStore,e).processEvent(w.statusUpdate({taskId:i.id,contextId:i.contextId,status:{state:5,message:d,timestamp:new Date().toISOString()},metadata:{}}))}let o=await this.taskStore.load(r,e);if(!o)throw new Ft(`Task ${t.id} not found after cancellation.`);if(o.status.state!=5)throw new me(`Task not cancelable: ${t.id}`);return o}async createTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new At;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new H(`Task not found: ${r}`);return await this.pushNotificationStore?.save(r,e,t),structuredClone(t)}async getTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new At;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new H(`Task not found: ${r}`);let a=await this.pushNotificationStore?.load(r,e)||[];if(a.length===0)throw new H(`Push notification config not found for task ${r}.`);let n=a.find(o=>o.id===t.id);if(!n)throw new H(`Push notification config with id '${t.id}' not found for task ${r}.`);return n}async listTaskPushNotificationConfigs(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new At;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new H(`Task not found: ${r}`);return{configs:await this.pushNotificationStore?.load(r,e)||[],nextPageToken:""}}async deleteTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new At;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new H(`Task not found: ${r}`);await this.pushNotificationStore?.delete(r,e,t.id)}async*resubscribe(t,e){if(!this.agentCard.capabilities?.streaming)throw new ot("Streaming (and thus resubscription) is not supported.");let r=t.id;this._requireValidTaskId(r);let i=this.eventBusManager.getByTaskId(r,e),a=i?new $t(i):void 0;try{let n=await this.taskStore.load(r,e);if(!n)throw new H(`Task not found: ${r}`);if(n.status?.state!==void 0&&It.includes(n.status.state))throw new ot(`Task ${r} is in a terminal state (${n.status.state}) and cannot be subscribed to.`);if(yield{payload:{$case:"task",value:n}},!a)return;for await(let o of a.events())switch(o.kind){case"statusUpdate":o.data.taskId===r&&(yield{payload:{$case:"statusUpdate",value:o.data}});break;case"artifactUpdate":o.data.taskId===r&&(yield{payload:{$case:"artifactUpdate",value:o.data}});break;case"task":o.data.id===r&&(yield{payload:{$case:"task",value:o.data}});break;case"message":break;default:ge(o)}}finally{a?.stop()}}async _mapEventToStreamResponse(t,e){switch(t.kind){case"task":{let r=t.data.id;return{payload:{$case:"task",value:await this.taskStore.load(r,e).catch(a=>(console.warn("Failed to load full task from store, falling back to event data:",a),null))||t.data}}}case"message":return{payload:{$case:"message",value:t.data}};case"statusUpdate":return{payload:{$case:"statusUpdate",value:t.data}};case"artifactUpdate":return{payload:{$case:"artifactUpdate",value:t.data}};default:ge(t)}}async _sendPushNotificationIfNeeded(t,e,r){this.agentCard.capabilities?.pushNotifications&&this.pushNotificationSender&&this.pushNotificationSender.send(e,t,r).catch(i=>{console.error("Failed to send push notification:",i)})}async _handleProcessingError(t,e,r,i,a){if(a&&!r){a(t);return}if(!a)throw t;let n=e.getCurrentTask(),o=t instanceof Error&&t.message||"Unknown error";if(n){let d={taskId:n.id,contextId:n.contextId,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:n.id,contextId:n.contextId,parts:[{content:{$case:"text",value:`Event processing loop failed: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},metadata:{}};try{await e.processEvent(w.statusUpdate(d))}catch(f){console.error(`Event processing loop failed for task ${i}: ${f instanceof Error&&f.message||"Unknown error"}`)}}else console.error(`Event processing loop failed for task ${i}: ${o}`)}_advanceStreamPattern(t,e){switch(e){case"undetermined":if(t.kind==="message")return"message-only";if(t.kind==="task")return"task-lifecycle";throw new ot(`Received ${t.kind} before initial 'Message'/'Task' event.`);case"message-only":throw new ot(`Received ${t.kind} after message-only response.`);case"task-lifecycle":if(t.kind!=="statusUpdate"&&t.kind!=="artifactUpdate")throw new ot(`Stream ordering violation: received ${t.kind} in task lifecycle stream.`);return e}}_requireValidTaskId(t){if(!t||t.trim()==="")throw new q("Task ID is required")}_applyHistoryLengthSemantics(t,e){e.historyLength!==void 0&&(e.historyLength<=0?t.history=[]:t.history=(t.history??[]).slice(-e.historyLength))}};function Rn(t){let e,r=i=>{(i.kind==="task"&&i.data.status?.state!==void 0||i.kind==="statusUpdate"&&i.data.status?.state!==void 0)&&(e=i.data.status.state)};return t.on("event",r),()=>(t.off("event",r),e)}function Un(t){let e,r,i=a=>{a.kind==="task"?(e=a.data,a.data.status?.state!==void 0&&(r=a.data.status.state)):a.kind==="statusUpdate"&&a.data.status?.state!==void 0&&(r=a.data.status.state)};return t.on("event",i),()=>(t.off("event",i),{task:e,state:r})}var ri=class{_scopedStore;constructor(t=Ne){this._scopedStore=new Ee(t)}async load(t,e){let r=this._scopedStore.getBucket(e)?.get(t);return r?structuredClone(r):void 0}async save(t,e){this._scopedStore.getOrCreateBucket(e).set(t.id,structuredClone(t))}async list(t,e){let{contextId:r,status:i,pageSize:a=br,pageToken:n,statusTimestampAfter:o,includeArtifacts:d=!1}=t,f=this._scopedStore.getBucket(e),T=f?Array.from(f.values()):[];if(r&&(T=T.filter(h=>h.contextId===r)),i!==void 0&&i!==0&&(T=T.filter(h=>h.status?.state===i)),o){let h=new Date(o).getTime();T=T.filter(g=>g.status?.timestamp&&new Date(g.status.timestamp).getTime()>h)}T.sort((h,g)=>{let _=h.status?.timestamp||"",R=g.status?.timestamp||"";return R!==_?R.localeCompare(_):g.id.localeCompare(h.id)});let p=T.length;if(n){let h=kn(n),g=T.findIndex(_=>(_.status?.timestamp||"")===h.timestamp&&_.id===h.id);g!==-1?T=T.slice(g+1):T=[]}let O=T.slice(0,a),u=O.map(h=>{let g=structuredClone(h);return d||(g.artifacts=[]),g}),N="";if(O.length>0&&T.length>O.length){let h=O[O.length-1];N=_n(h.status?.timestamp||"",h.id)}return{tasks:u,nextPageToken:N,pageSize:a,totalSize:p}}};var Qe=ft(ct(),1);var Na=ft(ct(),1),Ea=ft(ct(),1),er=ft(ct(),1),rr=ft(ct(),1);import go from"crypto";import mo from"crypto";var Jn=class{get isAuthenticated(){return!1}get userName(){return""}},ir={noAuthentication:()=>Promise.resolve(new Jn)};async function*ar(t){let e=!1;try{for(;;){let r;try{r=await t.next()}catch(i){throw e=!0,i}if(r.done)return;yield r.value}}finally{e||await t.return?.()}}function nr(t){switch(t){case 0:case"TASK_STATE_UNSPECIFIED":return 0;case 1:case"TASK_STATE_SUBMITTED":return 1;case 2:case"TASK_STATE_WORKING":return 2;case 3:case"TASK_STATE_COMPLETED":return 3;case 4:case"TASK_STATE_FAILED":return 4;case 5:case"TASK_STATE_CANCELED":return 5;case 6:case"TASK_STATE_INPUT_REQUIRED":return 6;case 7:case"TASK_STATE_REJECTED":return 7;case 8:case"TASK_STATE_AUTH_REQUIRED":return 8;default:return-1}}function Li(t){switch(t){case 0:return"TASK_STATE_UNSPECIFIED";case 1:return"TASK_STATE_SUBMITTED";case 2:return"TASK_STATE_WORKING";case 3:return"TASK_STATE_COMPLETED";case 4:return"TASK_STATE_FAILED";case 5:return"TASK_STATE_CANCELED";case 6:return"TASK_STATE_INPUT_REQUIRED";case 7:return"TASK_STATE_REJECTED";case 8:return"TASK_STATE_AUTH_REQUIRED";default:return"UNRECOGNIZED"}}function wn(t){switch(t){case 0:case"ROLE_UNSPECIFIED":return 0;case 1:case"ROLE_USER":return 1;case 2:case"ROLE_AGENT":return 2;default:return-1}}function xn(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var ii={fromJSON(t){return{acceptedOutputModes:globalThis.Array.isArray(t?.acceptedOutputModes)?t.acceptedOutputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.accepted_output_modes)?t.accepted_output_modes.map(e=>globalThis.String(e)):[],taskPushNotificationConfig:s(t.taskPushNotificationConfig)?Q.fromJSON(t.taskPushNotificationConfig):s(t.task_push_notification_config)?Q.fromJSON(t.task_push_notification_config):void 0,historyLength:s(t.historyLength)?globalThis.Number(t.historyLength):s(t.history_length)?globalThis.Number(t.history_length):void 0,returnImmediately:s(t.returnImmediately)?globalThis.Boolean(t.returnImmediately):s(t.return_immediately)?globalThis.Boolean(t.return_immediately):!1}},toJSON(t){let e={};return t.acceptedOutputModes?.length&&(e.acceptedOutputModes=t.acceptedOutputModes),t.taskPushNotificationConfig!==void 0&&(e.taskPushNotificationConfig=Q.toJSON(t.taskPushNotificationConfig)),t.historyLength!==void 0&&(e.historyLength=Math.round(t.historyLength)),t.returnImmediately!==!1&&(e.returnImmediately=t.returnImmediately),e}},G={fromJSON(t){return{id:s(t.id)?globalThis.String(t.id):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",status:s(t.status)?Qt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>Wt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>Y.fromJSON(e)):[],metadata:J(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=Qt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>Wt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>Y.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Qt={fromJSON(t){return{state:s(t.state)?nr(t.state):0,message:s(t.message)?Y.fromJSON(t.message):void 0,timestamp:s(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=Li(t.state)),t.message!==void 0&&(e.message=Y.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Yt={fromJSON(t){return{content:s(t.text)?{$case:"text",value:globalThis.String(t.text)}:s(t.raw)?{$case:"raw",value:Buffer.from(Hn(t.raw))}:s(t.url)?{$case:"url",value:globalThis.String(t.url)}:s(t.data)?{$case:"data",value:t.data}:void 0,metadata:J(t.metadata)?t.metadata:void 0,filename:s(t.filename)?globalThis.String(t.filename):"",mediaType:s(t.mediaType)?globalThis.String(t.mediaType):s(t.media_type)?globalThis.String(t.media_type):""}},toJSON(t){let e={};return t.content?.$case==="text"?e.text=t.content.value:t.content?.$case==="raw"?e.raw=Kn(t.content.value):t.content?.$case==="url"?e.url=t.content.value:t.content?.$case==="data"&&(e.data=t.content.value),t.metadata!==void 0&&(e.metadata=t.metadata),t.filename!==""&&(e.filename=t.filename),t.mediaType!==""&&(e.mediaType=t.mediaType),e}},Y={fromJSON(t){return{messageId:s(t.messageId)?globalThis.String(t.messageId):s(t.message_id)?globalThis.String(t.message_id):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",role:s(t.role)?wn(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Yt.fromJSON(e)):[],metadata:J(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[],referenceTaskIds:globalThis.Array.isArray(t?.referenceTaskIds)?t.referenceTaskIds.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.reference_task_ids)?t.reference_task_ids.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.messageId!==""&&(e.messageId=t.messageId),t.contextId!==""&&(e.contextId=t.contextId),t.taskId!==""&&(e.taskId=t.taskId),t.role!==0&&(e.role=xn(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Yt.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),t.referenceTaskIds?.length&&(e.referenceTaskIds=t.referenceTaskIds),e}},Wt={fromJSON(t){return{artifactId:s(t.artifactId)?globalThis.String(t.artifactId):s(t.artifact_id)?globalThis.String(t.artifact_id):"",name:s(t.name)?globalThis.String(t.name):"",description:s(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Yt.fromJSON(e)):[],metadata:J(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.artifactId!==""&&(e.artifactId=t.artifactId),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.parts?.length&&(e.parts=t.parts.map(r=>Yt.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},Oe={fromJSON(t){return{taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",status:s(t.status)?Qt.fromJSON(t.status):void 0,metadata:J(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=Qt.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},ye={fromJSON(t){return{taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",artifact:s(t.artifact)?Wt.fromJSON(t.artifact):void 0,append:s(t.append)?globalThis.Boolean(t.append):!1,lastChunk:s(t.lastChunk)?globalThis.Boolean(t.lastChunk):s(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:J(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.artifact!==void 0&&(e.artifact=Wt.toJSON(t.artifact)),t.append!==!1&&(e.append=t.append),t.lastChunk!==!1&&(e.lastChunk=t.lastChunk),t.metadata!==void 0&&(e.metadata=t.metadata),e}},ai={fromJSON(t){return{scheme:s(t.scheme)?globalThis.String(t.scheme):"",credentials:s(t.credentials)?globalThis.String(t.credentials):""}},toJSON(t){let e={};return t.scheme!==""&&(e.scheme=t.scheme),t.credentials!==""&&(e.credentials=t.credentials),e}},_e={fromJSON(t){return{url:s(t.url)?globalThis.String(t.url):"",protocolBinding:s(t.protocolBinding)?globalThis.String(t.protocolBinding):s(t.protocol_binding)?globalThis.String(t.protocol_binding):"",tenant:s(t.tenant)?globalThis.String(t.tenant):"",protocolVersion:s(t.protocolVersion)?globalThis.String(t.protocolVersion):s(t.protocol_version)?globalThis.String(t.protocol_version):""}},toJSON(t){let e={};return t.url!==""&&(e.url=t.url),t.protocolBinding!==""&&(e.protocolBinding=t.protocolBinding),t.tenant!==""&&(e.tenant=t.tenant),t.protocolVersion!==""&&(e.protocolVersion=t.protocolVersion),e}},$i={fromJSON(t){return{name:s(t.name)?globalThis.String(t.name):"",description:s(t.description)?globalThis.String(t.description):"",supportedInterfaces:globalThis.Array.isArray(t?.supportedInterfaces)?t.supportedInterfaces.map(e=>_e.fromJSON(e)):globalThis.Array.isArray(t?.supported_interfaces)?t.supported_interfaces.map(e=>_e.fromJSON(e)):[],provider:s(t.provider)?ni.fromJSON(t.provider):void 0,version:s(t.version)?globalThis.String(t.version):"",documentationUrl:s(t.documentationUrl)?globalThis.String(t.documentationUrl):s(t.documentation_url)?globalThis.String(t.documentation_url):void 0,capabilities:s(t.capabilities)?si.fromJSON(t.capabilities):void 0,securitySchemes:J(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=ke.fromJSON(i),e),{}):J(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=ke.fromJSON(i),e),{}):{},securityRequirements:globalThis.Array.isArray(t?.securityRequirements)?t.securityRequirements.map(e=>Tt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>Tt.fromJSON(e)):[],defaultInputModes:globalThis.Array.isArray(t?.defaultInputModes)?t.defaultInputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.default_input_modes)?t.default_input_modes.map(e=>globalThis.String(e)):[],defaultOutputModes:globalThis.Array.isArray(t?.defaultOutputModes)?t.defaultOutputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.default_output_modes)?t.default_output_modes.map(e=>globalThis.String(e)):[],skills:globalThis.Array.isArray(t?.skills)?t.skills.map(e=>li.fromJSON(e)):[],signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>di.fromJSON(e)):[],iconUrl:s(t.iconUrl)?globalThis.String(t.iconUrl):s(t.icon_url)?globalThis.String(t.icon_url):void 0}},toJSON(t){let e={};if(t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.supportedInterfaces?.length&&(e.supportedInterfaces=t.supportedInterfaces.map(r=>_e.toJSON(r))),t.provider!==void 0&&(e.provider=ni.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==void 0&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=si.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=ke.toJSON(n)}),e.securitySchemes=i}}return t.securityRequirements?.length&&(e.securityRequirements=t.securityRequirements.map(r=>Tt.toJSON(r))),t.defaultInputModes?.length&&(e.defaultInputModes=t.defaultInputModes),t.defaultOutputModes?.length&&(e.defaultOutputModes=t.defaultOutputModes),t.skills?.length&&(e.skills=t.skills.map(r=>li.toJSON(r))),t.signatures?.length&&(e.signatures=t.signatures.map(r=>di.toJSON(r))),t.iconUrl!==void 0&&(e.iconUrl=t.iconUrl),e}},ni={fromJSON(t){return{url:s(t.url)?globalThis.String(t.url):"",organization:s(t.organization)?globalThis.String(t.organization):""}},toJSON(t){let e={};return t.url!==""&&(e.url=t.url),t.organization!==""&&(e.organization=t.organization),e}},si={fromJSON(t){return{streaming:s(t.streaming)?globalThis.Boolean(t.streaming):void 0,pushNotifications:s(t.pushNotifications)?globalThis.Boolean(t.pushNotifications):s(t.push_notifications)?globalThis.Boolean(t.push_notifications):void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>oi.fromJSON(e)):[],extendedAgentCard:s(t.extendedAgentCard)?globalThis.Boolean(t.extendedAgentCard):s(t.extended_agent_card)?globalThis.Boolean(t.extended_agent_card):void 0}},toJSON(t){let e={};return t.streaming!==void 0&&(e.streaming=t.streaming),t.pushNotifications!==void 0&&(e.pushNotifications=t.pushNotifications),t.extensions?.length&&(e.extensions=t.extensions.map(r=>oi.toJSON(r))),t.extendedAgentCard!==void 0&&(e.extendedAgentCard=t.extendedAgentCard),e}},oi={fromJSON(t){return{uri:s(t.uri)?globalThis.String(t.uri):"",description:s(t.description)?globalThis.String(t.description):"",required:s(t.required)?globalThis.Boolean(t.required):!1,params:J(t.params)?t.params:void 0}},toJSON(t){let e={};return t.uri!==""&&(e.uri=t.uri),t.description!==""&&(e.description=t.description),t.required!==!1&&(e.required=t.required),t.params!==void 0&&(e.params=t.params),e}},li={fromJSON(t){return{id:s(t.id)?globalThis.String(t.id):"",name:s(t.name)?globalThis.String(t.name):"",description:s(t.description)?globalThis.String(t.description):"",tags:globalThis.Array.isArray(t?.tags)?t.tags.map(e=>globalThis.String(e)):[],examples:globalThis.Array.isArray(t?.examples)?t.examples.map(e=>globalThis.String(e)):[],inputModes:globalThis.Array.isArray(t?.inputModes)?t.inputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.input_modes)?t.input_modes.map(e=>globalThis.String(e)):[],outputModes:globalThis.Array.isArray(t?.outputModes)?t.outputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.output_modes)?t.output_modes.map(e=>globalThis.String(e)):[],securityRequirements:globalThis.Array.isArray(t?.securityRequirements)?t.securityRequirements.map(e=>Tt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>Tt.fromJSON(e)):[]}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.tags?.length&&(e.tags=t.tags),t.examples?.length&&(e.examples=t.examples),t.inputModes?.length&&(e.inputModes=t.inputModes),t.outputModes?.length&&(e.outputModes=t.outputModes),t.securityRequirements?.length&&(e.securityRequirements=t.securityRequirements.map(r=>Tt.toJSON(r))),e}},di={fromJSON(t){return{protected:s(t.protected)?globalThis.String(t.protected):"",signature:s(t.signature)?globalThis.String(t.signature):"",header:J(t.header)?t.header:void 0}},toJSON(t){let e={};return t.protected!==""&&(e.protected=t.protected),t.signature!==""&&(e.signature=t.signature),t.header!==void 0&&(e.header=t.header),e}},Q={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",url:s(t.url)?globalThis.String(t.url):"",token:s(t.token)?globalThis.String(t.token):"",authentication:s(t.authentication)?ai.fromJSON(t.authentication):void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.id!==""&&(e.id=t.id),t.taskId!==""&&(e.taskId=t.taskId),t.url!==""&&(e.url=t.url),t.token!==""&&(e.token=t.token),t.authentication!==void 0&&(e.authentication=ai.toJSON(t.authentication)),e}},ui={fromJSON(t){return{list:globalThis.Array.isArray(t?.list)?t.list.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.list?.length&&(e.list=t.list),e}},Tt={fromJSON(t){return{schemes:J(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=ui.fromJSON(i),e),{}):{}}},toJSON(t){let e={};if(t.schemes){let r=globalThis.Object.entries(t.schemes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=ui.toJSON(n)}),e.schemes=i}}return e}},ke={fromJSON(t){return{scheme:s(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:Ae.fromJSON(t.apiKeySecurityScheme)}:s(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:Ae.fromJSON(t.api_key_security_scheme)}:s(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:Ie.fromJSON(t.httpAuthSecurityScheme)}:s(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:Ie.fromJSON(t.http_auth_security_scheme)}:s(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:Ce.fromJSON(t.oauth2SecurityScheme)}:s(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:Ce.fromJSON(t.oauth2_security_scheme)}:s(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:Re.fromJSON(t.openIdConnectSecurityScheme)}:s(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:Re.fromJSON(t.open_id_connect_security_scheme)}:s(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:Ue.fromJSON(t.mtlsSecurityScheme)}:s(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:Ue.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=Ae.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=Ie.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=Ce.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=Re.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=Ue.toJSON(t.scheme.value)),e}},Ae={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",location:s(t.location)?globalThis.String(t.location):"",name:s(t.name)?globalThis.String(t.name):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.location!==""&&(e.location=t.location),t.name!==""&&(e.name=t.name),e}},Ie={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",scheme:s(t.scheme)?globalThis.String(t.scheme):"",bearerFormat:s(t.bearerFormat)?globalThis.String(t.bearerFormat):s(t.bearer_format)?globalThis.String(t.bearer_format):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.scheme!==""&&(e.scheme=t.scheme),t.bearerFormat!==""&&(e.bearerFormat=t.bearerFormat),e}},Ce={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",flows:s(t.flows)?fi.fromJSON(t.flows):void 0,oauth2MetadataUrl:s(t.oauth2MetadataUrl)?globalThis.String(t.oauth2MetadataUrl):s(t.oauth2_metadata_url)?globalThis.String(t.oauth2_metadata_url):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.flows!==void 0&&(e.flows=fi.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},Re={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",openIdConnectUrl:s(t.openIdConnectUrl)?globalThis.String(t.openIdConnectUrl):s(t.open_id_connect_url)?globalThis.String(t.open_id_connect_url):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.openIdConnectUrl!==""&&(e.openIdConnectUrl=t.openIdConnectUrl),e}},Ue={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},fi={fromJSON(t){return{flow:s(t.authorizationCode)?{$case:"authorizationCode",value:Je.fromJSON(t.authorizationCode)}:s(t.authorization_code)?{$case:"authorizationCode",value:Je.fromJSON(t.authorization_code)}:s(t.clientCredentials)?{$case:"clientCredentials",value:we.fromJSON(t.clientCredentials)}:s(t.client_credentials)?{$case:"clientCredentials",value:we.fromJSON(t.client_credentials)}:s(t.implicit)?{$case:"implicit",value:ci.fromJSON(t.implicit)}:s(t.password)?{$case:"password",value:hi.fromJSON(t.password)}:s(t.deviceCode)?{$case:"deviceCode",value:xe.fromJSON(t.deviceCode)}:s(t.device_code)?{$case:"deviceCode",value:xe.fromJSON(t.device_code)}:void 0}},toJSON(t){let e={};return t.flow?.$case==="authorizationCode"?e.authorizationCode=Je.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=we.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=ci.toJSON(t.flow.value):t.flow?.$case==="password"?e.password=hi.toJSON(t.flow.value):t.flow?.$case==="deviceCode"&&(e.deviceCode=xe.toJSON(t.flow.value)),e}},Je={fromJSON(t){return{authorizationUrl:s(t.authorizationUrl)?globalThis.String(t.authorizationUrl):s(t.authorization_url)?globalThis.String(t.authorization_url):"",tokenUrl:s(t.tokenUrl)?globalThis.String(t.tokenUrl):s(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:s(t.refreshUrl)?globalThis.String(t.refreshUrl):s(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:J(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{},pkceRequired:s(t.pkceRequired)?globalThis.Boolean(t.pkceRequired):s(t.pkce_required)?globalThis.Boolean(t.pkce_required):!1}},toJSON(t){let e={};if(t.authorizationUrl!==""&&(e.authorizationUrl=t.authorizationUrl),t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=n}),e.scopes=i}}return t.pkceRequired!==!1&&(e.pkceRequired=t.pkceRequired),e}},we={fromJSON(t){return{tokenUrl:s(t.tokenUrl)?globalThis.String(t.tokenUrl):s(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:s(t.refreshUrl)?globalThis.String(t.refreshUrl):s(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:J(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=n}),e.scopes=i}}return e}},ci={fromJSON(t){return{authorizationUrl:s(t.authorizationUrl)?globalThis.String(t.authorizationUrl):s(t.authorization_url)?globalThis.String(t.authorization_url):"",refreshUrl:s(t.refreshUrl)?globalThis.String(t.refreshUrl):s(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:J(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.authorizationUrl!==""&&(e.authorizationUrl=t.authorizationUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=n}),e.scopes=i}}return e}},hi={fromJSON(t){return{tokenUrl:s(t.tokenUrl)?globalThis.String(t.tokenUrl):s(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:s(t.refreshUrl)?globalThis.String(t.refreshUrl):s(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:J(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=n}),e.scopes=i}}return e}},xe={fromJSON(t){return{deviceAuthorizationUrl:s(t.deviceAuthorizationUrl)?globalThis.String(t.deviceAuthorizationUrl):s(t.device_authorization_url)?globalThis.String(t.device_authorization_url):"",tokenUrl:s(t.tokenUrl)?globalThis.String(t.tokenUrl):s(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:s(t.refreshUrl)?globalThis.String(t.refreshUrl):s(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:J(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.deviceAuthorizationUrl!==""&&(e.deviceAuthorizationUrl=t.deviceAuthorizationUrl),t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=n}),e.scopes=i}}return e}},Xt={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",message:s(t.message)?Y.fromJSON(t.message):void 0,configuration:s(t.configuration)?ii.fromJSON(t.configuration):void 0,metadata:J(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.message!==void 0&&(e.message=Y.toJSON(t.message)),t.configuration!==void 0&&(e.configuration=ii.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Pn={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):"",historyLength:s(t.historyLength)?globalThis.Number(t.historyLength):s(t.history_length)?globalThis.Number(t.history_length):void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.id!==""&&(e.id=t.id),t.historyLength!==void 0&&(e.historyLength=Math.round(t.historyLength)),e}},Dn={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",contextId:s(t.contextId)?globalThis.String(t.contextId):s(t.context_id)?globalThis.String(t.context_id):"",status:s(t.status)?nr(t.status):0,pageSize:s(t.pageSize)?globalThis.Number(t.pageSize):s(t.page_size)?globalThis.Number(t.page_size):void 0,pageToken:s(t.pageToken)?globalThis.String(t.pageToken):s(t.page_token)?globalThis.String(t.page_token):"",historyLength:s(t.historyLength)?globalThis.Number(t.historyLength):s(t.history_length)?globalThis.Number(t.history_length):void 0,statusTimestampAfter:s(t.statusTimestampAfter)?globalThis.String(t.statusTimestampAfter):s(t.status_timestamp_after)?globalThis.String(t.status_timestamp_after):void 0,includeArtifacts:s(t.includeArtifacts)?globalThis.Boolean(t.includeArtifacts):s(t.include_artifacts)?globalThis.Boolean(t.include_artifacts):void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.contextId!==""&&(e.contextId=t.contextId),t.status!==0&&(e.status=Li(t.status)),t.pageSize!==void 0&&(e.pageSize=Math.round(t.pageSize)),t.pageToken!==""&&(e.pageToken=t.pageToken),t.historyLength!==void 0&&(e.historyLength=Math.round(t.historyLength)),t.statusTimestampAfter!==void 0&&(e.statusTimestampAfter=t.statusTimestampAfter),t.includeArtifacts!==void 0&&(e.includeArtifacts=t.includeArtifacts),e}},zi={fromJSON(t){return{tasks:globalThis.Array.isArray(t?.tasks)?t.tasks.map(e=>G.fromJSON(e)):[],nextPageToken:s(t.nextPageToken)?globalThis.String(t.nextPageToken):s(t.next_page_token)?globalThis.String(t.next_page_token):"",pageSize:s(t.pageSize)?globalThis.Number(t.pageSize):s(t.page_size)?globalThis.Number(t.page_size):0,totalSize:s(t.totalSize)?globalThis.Number(t.totalSize):s(t.total_size)?globalThis.Number(t.total_size):0}},toJSON(t){let e={};return t.tasks?.length&&(e.tasks=t.tasks.map(r=>G.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),t.pageSize!==0&&(e.pageSize=Math.round(t.pageSize)),t.totalSize!==0&&(e.totalSize=Math.round(t.totalSize)),e}},Mn={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):"",metadata:J(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.id!==""&&(e.id=t.id),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Ln={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",id:s(t.id)?globalThis.String(t.id):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.taskId!==""&&(e.taskId=t.taskId),t.id!==""&&(e.id=t.id),e}},$n={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",id:s(t.id)?globalThis.String(t.id):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.taskId!==""&&(e.taskId=t.taskId),t.id!==""&&(e.id=t.id),e}},zn={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.id!==""&&(e.id=t.id),e}},qn={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",taskId:s(t.taskId)?globalThis.String(t.taskId):s(t.task_id)?globalThis.String(t.task_id):"",pageSize:s(t.pageSize)?globalThis.Number(t.pageSize):s(t.page_size)?globalThis.Number(t.page_size):0,pageToken:s(t.pageToken)?globalThis.String(t.pageToken):s(t.page_token)?globalThis.String(t.page_token):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),t.taskId!==""&&(e.taskId=t.taskId),t.pageSize!==0&&(e.pageSize=Math.round(t.pageSize)),t.pageToken!==""&&(e.pageToken=t.pageToken),e}},Fn={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),e}},Bn={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:G.fromJSON(t.task)}:s(t.message)?{$case:"message",value:Y.fromJSON(t.message)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=G.toJSON(t.payload.value):t.payload?.$case==="message"&&(e.message=Y.toJSON(t.payload.value)),e}},Ye={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:G.fromJSON(t.task)}:s(t.message)?{$case:"message",value:Y.fromJSON(t.message)}:s(t.statusUpdate)?{$case:"statusUpdate",value:Oe.fromJSON(t.statusUpdate)}:s(t.status_update)?{$case:"statusUpdate",value:Oe.fromJSON(t.status_update)}:s(t.artifactUpdate)?{$case:"artifactUpdate",value:ye.fromJSON(t.artifactUpdate)}:s(t.artifact_update)?{$case:"artifactUpdate",value:ye.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=G.toJSON(t.payload.value):t.payload?.$case==="message"?e.message=Y.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=Oe.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=ye.toJSON(t.payload.value)),e}},qi={fromJSON(t){return{configs:globalThis.Array.isArray(t?.configs)?t.configs.map(e=>Q.fromJSON(e)):[],nextPageToken:s(t.nextPageToken)?globalThis.String(t.nextPageToken):s(t.next_page_token)?globalThis.String(t.next_page_token):""}},toJSON(t){let e={};return t.configs?.length&&(e.configs=t.configs.map(r=>Q.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),e}};function Hn(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Kn(t){return globalThis.Buffer.from(t).toString("base64")}function J(t){return typeof t=="object"&&t!==null}function s(t){return t!=null}var gt="A2A-Extensions",rt="A2A-Version",Vn="1.0",Ot="0.3",sr="application/json",We="application/a2a+json",se={createFrom:(t,e)=>t?.includes(e)?t:[...t??[],e],parseServiceParameter:t=>{if(!t)return[];let e=new Set(t.split(",").map(r=>r.trim()).filter(r=>r.length>0));return Array.from(e)},toServiceParameter:t=>t.join(",")},Zt={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"};function dt(t){return`data: ${JSON.stringify(t)}
|
|
5
|
+
|
|
6
|
+
`}function bt(t){return`event: error
|
|
7
|
+
data: ${JSON.stringify(t)}
|
|
8
|
+
|
|
9
|
+
`}var kl=4*1024*1024;function Fi(t,e){let r=zi.toJSON(t),{tasks:i,nextPageToken:a,pageSize:n,totalSize:o,...d}=r,f=i??[];return{tasks:e?.includeArtifacts?f.map(Gn):f,nextPageToken:a??"",pageSize:n??0,totalSize:o??0,...d}}function Gn(t){if(typeof t!="object"||t===null)return t;let e=t;return e.artifacts!==void 0?e:{...e,artifacts:[]}}var Qn="a2a-protocol.org",Yn="type.googleapis.com/google.rpc.ErrorInfo",Bi=Symbol.for("@a2a-js/sdk.A2AError"),W=class Hi extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(Bi in e))return!1;if(this===Hi)return!0;for(let r=Object.getPrototypeOf(e);r!==null;r=Object.getPrototypeOf(r))if(r.constructor?.name===this.name)return!0;return!1}constructor(e){let r=typeof e=="string"?{message:e}:e;super(r?.message??"An unexpected error occurred.",r?.cause!==void 0?{cause:r.cause}:void 0),this.name=new.target.name,r?.metadata&&Object.keys(r.metadata).length>0&&(this.metadata=r.metadata)}toErrorInfo(){return{"@type":Yn,reason:this.reason,domain:Qn,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(W.prototype,Bi,{value:!0});var Ki=[{name:"TaskNotFoundError",reason:"TASK_NOT_FOUND",defaultMessage:"Task not found"},{name:"TaskNotCancelableError",reason:"TASK_NOT_CANCELABLE",defaultMessage:"Task cannot be canceled"},{name:"PushNotificationNotSupportedError",reason:"PUSH_NOTIFICATION_NOT_SUPPORTED",defaultMessage:"Push Notification is not supported"},{name:"UnsupportedOperationError",reason:"UNSUPPORTED_OPERATION",defaultMessage:"This operation is not supported"},{name:"ContentTypeNotSupportedError",reason:"CONTENT_TYPE_NOT_SUPPORTED",defaultMessage:"Incompatible content types"},{name:"InvalidAgentResponseError",reason:"INVALID_AGENT_RESPONSE",defaultMessage:"Invalid agent response type"},{name:"ExtendedAgentCardNotConfiguredError",reason:"EXTENDED_AGENT_CARD_NOT_CONFIGURED",defaultMessage:"Extended Agent Card not configured"},{name:"ExtensionSupportRequiredError",reason:"EXTENSION_SUPPORT_REQUIRED",defaultMessage:"Extension support required"},{name:"VersionNotSupportedError",reason:"VERSION_NOT_SUPPORTED",defaultMessage:"Version not supported"},{name:"RequestMalformedError",reason:"INVALID_PARAMS",defaultMessage:"Request malformed"}],X=Object.freeze(Object.fromEntries(Ki.map(t=>[t.name,t]))),Al=Object.freeze(Object.fromEntries(Ki.map(t=>[t.reason,t])));function it(t){return{[t.name]:class extends W{reason=t.reason;constructor(r){r===void 0?super({message:t.defaultMessage}):typeof r=="string"?super({message:r}):super({message:t.defaultMessage,...r})}}}[t.name]}var Vi=it(X.TaskNotFoundError),Gi=it(X.TaskNotCancelableError),or=it(X.PushNotificationNotSupportedError),Qi=it(X.UnsupportedOperationError),lr=it(X.ContentTypeNotSupportedError),Wn=it(X.InvalidAgentResponseError),Yi=it(X.ExtendedAgentCardNotConfiguredError),Xn=it(X.ExtensionSupportRequiredError),oe=it(X.VersionNotSupportedError),L=it(X.RequestMalformedError),dr=Object.freeze({TaskNotFoundError:Vi,TaskNotCancelableError:Gi,PushNotificationNotSupportedError:or,UnsupportedOperationError:Qi,ContentTypeNotSupportedError:lr,InvalidAgentResponseError:Wn,ExtendedAgentCardNotConfiguredError:Yi,ExtensionSupportRequiredError:Xn,VersionNotSupportedError:oe,RequestMalformedError:L}),v={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,CONFLICT:409,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501},P={OK:"OK",CANCELLED:"CANCELLED",UNKNOWN:"UNKNOWN",INVALID_ARGUMENT:"INVALID_ARGUMENT",DEADLINE_EXCEEDED:"DEADLINE_EXCEEDED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",PERMISSION_DENIED:"PERMISSION_DENIED",RESOURCE_EXHAUSTED:"RESOURCE_EXHAUSTED",FAILED_PRECONDITION:"FAILED_PRECONDITION",ABORTED:"ABORTED",OUT_OF_RANGE:"OUT_OF_RANGE",UNIMPLEMENTED:"UNIMPLEMENTED",INTERNAL:"INTERNAL",UNAVAILABLE:"UNAVAILABLE",DATA_LOSS:"DATA_LOSS",UNAUTHENTICATED:"UNAUTHENTICATED"},Wi=Object.freeze({TaskNotFoundError:v.NOT_FOUND,TaskNotCancelableError:v.BAD_REQUEST,PushNotificationNotSupportedError:v.BAD_REQUEST,UnsupportedOperationError:v.BAD_REQUEST,ContentTypeNotSupportedError:v.BAD_REQUEST,InvalidAgentResponseError:v.INTERNAL_SERVER_ERROR,ExtendedAgentCardNotConfiguredError:v.BAD_REQUEST,ExtensionSupportRequiredError:v.BAD_REQUEST,VersionNotSupportedError:v.BAD_REQUEST,RequestMalformedError:v.BAD_REQUEST}),Zn=Object.freeze({TaskNotFoundError:P.NOT_FOUND,TaskNotCancelableError:P.FAILED_PRECONDITION,PushNotificationNotSupportedError:P.FAILED_PRECONDITION,UnsupportedOperationError:P.FAILED_PRECONDITION,ContentTypeNotSupportedError:P.INVALID_ARGUMENT,InvalidAgentResponseError:P.INTERNAL,ExtendedAgentCardNotConfiguredError:P.FAILED_PRECONDITION,ExtensionSupportRequiredError:P.FAILED_PRECONDITION,VersionNotSupportedError:P.FAILED_PRECONDITION,RequestMalformedError:P.INVALID_ARGUMENT});function bn(t){return t instanceof W&&t.transport==="rest"}function at(t){let e=dr[t],r=Wi[t]??v.INTERNAL_SERVER_ERROR;return{[`Rest${t}`]:class extends e{transport="rest";statusCode;headers;constructor(a){super(a),this.name=t,this.statusCode=a?.statusCode??r,a?.headers&&(this.headers=a.headers)}}}[`Rest${t}`]}var jn=at("TaskNotFoundError"),ts=at("TaskNotCancelableError"),es=at("PushNotificationNotSupportedError"),rs=at("UnsupportedOperationError"),is=at("ContentTypeNotSupportedError"),as=at("InvalidAgentResponseError"),ns=at("ExtendedAgentCardNotConfiguredError"),ss=at("ExtensionSupportRequiredError"),os=at("VersionNotSupportedError"),ls=at("RequestMalformedError"),Il=Object.freeze({TaskNotFoundError:jn,TaskNotCancelableError:ts,PushNotificationNotSupportedError:es,UnsupportedOperationError:rs,ContentTypeNotSupportedError:is,InvalidAgentResponseError:as,ExtendedAgentCardNotConfiguredError:ns,ExtensionSupportRequiredError:ss,VersionNotSupportedError:os,RequestMalformedError:ls});function Vt(t){return bn(t)?t.statusCode:t instanceof W?Wi[t.name]??500:v.INTERNAL_SERVER_ERROR}function Ut(t,e){let r=t instanceof Error?t.message:"An unexpected error occurred.",i=[],a=P.UNKNOWN;return t instanceof W?(i.push(t.toErrorInfo()),a=Zn[t.name]??P.UNKNOWN):e===v.NOT_FOUND?a=P.NOT_FOUND:e===v.INTERNAL_SERVER_ERROR?a=P.INTERNAL:e===v.BAD_REQUEST&&(a=P.INVALID_ARGUMENT),{error:{code:e,status:a,message:r,details:i}}}var U={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TASK_NOT_FOUND:-32001,TASK_NOT_CANCELABLE:-32002,PUSH_NOTIFICATION_NOT_SUPPORTED:-32003,UNSUPPORTED_OPERATION:-32004,CONTENT_TYPE_NOT_SUPPORTED:-32005,INVALID_AGENT_RESPONSE:-32006,EXTENDED_CARD_NOT_CONFIGURED:-32007,EXTENSION_SUPPORT_REQUIRED:-32008,VERSION_NOT_SUPPORTED:-32009},le=Object.freeze({TaskNotFoundError:U.TASK_NOT_FOUND,TaskNotCancelableError:U.TASK_NOT_CANCELABLE,PushNotificationNotSupportedError:U.PUSH_NOTIFICATION_NOT_SUPPORTED,UnsupportedOperationError:U.UNSUPPORTED_OPERATION,ContentTypeNotSupportedError:U.CONTENT_TYPE_NOT_SUPPORTED,InvalidAgentResponseError:U.INVALID_AGENT_RESPONSE,ExtendedAgentCardNotConfiguredError:U.EXTENDED_CARD_NOT_CONFIGURED,ExtensionSupportRequiredError:U.EXTENSION_SUPPORT_REQUIRED,VersionNotSupportedError:U.VERSION_NOT_SUPPORTED,RequestMalformedError:U.INVALID_PARAMS}),ds=Object.freeze(Object.fromEntries(Object.entries(le).map(([t,e])=>[e,t])));function ur(t){return t instanceof W&&t.transport==="jsonrpc"}function nt(t){let e=dr[t],r=le[t]??U.INTERNAL_ERROR;return{[`JsonRpc${t}`]:class extends e{transport="jsonrpc";envelopeCode;data;constructor(a){super(a),this.name=t,this.envelopeCode=a?.envelopeCode??r,a?.data!==void 0&&(this.data=a.data)}}}[`JsonRpc${t}`]}var us=nt("TaskNotFoundError"),fs=nt("TaskNotCancelableError"),cs=nt("PushNotificationNotSupportedError"),fr=nt("UnsupportedOperationError"),hs=nt("ContentTypeNotSupportedError"),ps=nt("InvalidAgentResponseError"),Ss=nt("ExtendedAgentCardNotConfiguredError"),Ts=nt("ExtensionSupportRequiredError"),gs=nt("VersionNotSupportedError"),xt=nt("RequestMalformedError"),ms=Object.freeze({TaskNotFoundError:us,TaskNotCancelableError:fs,PushNotificationNotSupportedError:cs,UnsupportedOperationError:fr,ContentTypeNotSupportedError:hs,InvalidAgentResponseError:ps,ExtendedAgentCardNotConfiguredError:Ss,ExtensionSupportRequiredError:Ts,VersionNotSupportedError:gs,RequestMalformedError:xt}),Xi=class extends W{transport="jsonrpc";envelopeCode;data;errorResponse;constructor(t){super({message:t.error.message}),this.name="JsonRpcTransportError",this.envelopeCode=t.error.code,t.error.data!==void 0&&(this.data=t.error.data),this.errorResponse=t}};function Ns(t){if(ur(t)){let r=X[t.name];return{code:t.envelopeCode,message:t.message,...r?{data:[t.toErrorInfo()]}:{}}}if(t instanceof W)return{code:le[t.name]??U.INTERNAL_ERROR,message:t.message,data:[t.toErrorInfo()]};let e=t instanceof Error&&t.message||"An unexpected error occurred.";return{code:U.INTERNAL_ERROR,message:e}}var Cl={[U.PARSE_ERROR]:"RequestMalformedError",[U.INVALID_REQUEST]:"RequestMalformedError",[U.METHOD_NOT_FOUND]:"RequestMalformedError"},Xe=class Ze{requestHandler;constructor(e){this.requestHandler=e}async handle(e,r){let i={jsonrpc:"2.0",method:""};try{if(typeof e=="string")i=JSON.parse(e);else if(typeof e=="object"&&e!==null)i=e;else throw new L("Invalid request body type.");if(!this.isRequestValid(i))throw new L("Invalid JSON-RPC Request.")}catch(o){let d=Ze.mapToJSONRPCError(o instanceof SyntaxError?new L(o.message||"Failed to parse JSON request."):o);return{jsonrpc:"2.0",id:i.id??null,error:d}}let{method:a,id:n=null}=i;try{if(a!=="GetExtendedAgentCard"&&!this.paramsAreValid(i.params))throw new L("Invalid method parameters.");let o=i.params?.tenant;if(o&&r.setTenant(o),a==="SendStreamingMessage"||a==="SubscribeToTask"){let d=i.params,f=a==="SendStreamingMessage"?this.requestHandler.sendMessageStream(Xt.fromJSON(d),r):this.requestHandler.resubscribe(zn.fromJSON(d),r);return(async function*(){for await(let p of f)yield{jsonrpc:"2.0",id:n,result:Ye.toJSON(p)}})()}else{let d;switch(a){case"SendMessage":{let f=await this.requestHandler.sendMessage(Xt.fromJSON(i.params),r);d="messageId"in f?{message:Y.toJSON(f)}:{task:G.toJSON(f)};break}case"GetTask":d=G.toJSON(await this.requestHandler.getTask(Pn.fromJSON(i.params),r));break;case"ListTasks":{let f=Dn.fromJSON(i.params);d=Fi(await this.requestHandler.listTasks(f,r),{includeArtifacts:f.includeArtifacts});break}case"CancelTask":d=G.toJSON(await this.requestHandler.cancelTask(Mn.fromJSON(i.params),r));break;case"CreateTaskPushNotificationConfig":{d=Q.toJSON(await this.requestHandler.createTaskPushNotificationConfig(Q.fromJSON(i.params),r));break}case"GetTaskPushNotificationConfig":d=Q.toJSON(await this.requestHandler.getTaskPushNotificationConfig(Ln.fromJSON(i.params),r));break;case"DeleteTaskPushNotificationConfig":await this.requestHandler.deleteTaskPushNotificationConfig($n.fromJSON(i.params),r),d=null;break;case"ListTaskPushNotificationConfigs":d=qi.toJSON(await this.requestHandler.listTaskPushNotificationConfigs(qn.fromJSON(i.params),r));break;case"GetExtendedAgentCard":d=$i.toJSON(await this.requestHandler.getAuthenticatedExtendedAgentCard(Fn.fromJSON(i.params??{}),r));break;default:return{jsonrpc:"2.0",id:n,error:{code:U.METHOD_NOT_FOUND,message:"Invalid method."}}}return{jsonrpc:"2.0",id:n,result:d}}}catch(o){return{jsonrpc:"2.0",id:n,error:Ze.mapToJSONRPCError(o)}}}isRequestValid(e){if(e.jsonrpc!=="2.0")return!1;if("id"in e){let r=e.id,i=typeof r=="string",a=typeof r=="number"&&Number.isInteger(r);if(!i&&!a&&!(r===null))return!1}return!(!e.method||typeof e.method!="string")}paramsAreValid(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;for(let r of Object.keys(e))if(r==="")return!1;return!0}static mapToJSONRPCError(e){return Ns(e)}},Es="0.3",vs="headers",cr=({extensions:t,user:e,headers:r,requestedVersion:i,tenant:a})=>{let n=new Map([[vs,r]]);return new Os({requestedExtensions:t,user:e,state:n,requestedVersion:i,tenant:a})},Os=class{_requestedExtensions;_user;_requestedVersion;_tenant;_activatedExtensions;_state;constructor(t){this._requestedExtensions=t?.requestedExtensions,this._user=t?.user,this._tenant=t?.tenant,this._requestedVersion=t?.requestedVersion||Es,this._state=t?.state??new Map}get tenant(){return this._tenant}setTenant(t){if(this._tenant!==void 0)throw new Error("Tenant is already set.");this._tenant=t}get user(){return this._user}get activatedExtensions(){return this._activatedExtensions}get requestedExtensions(){return this._requestedExtensions}get requestedVersion(){return this._requestedVersion}get state(){return this._state}addActivatedExtension(t){this._activatedExtensions=se.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function ys(t,e){let r=new Set;for(let i of t.supportedInterfaces??[])e&&i.protocolBinding!==e||i.protocolVersion&&r.add(i.protocolVersion);return r}function hr(t,e,r){let i=ys(e,r);if(!i.has(t))throw new oe(`The requested A2A protocol version '${t}' is not supported. Supported versions: ${[...i].join(", ")}`)}var Zi=Ot,_s=Vn;function Pe(t){let e=t.trim();if(e==="")return;let r=e.split(".");if(r.length===0)return;let i=Number.parseInt(r[0],10);if(!Number.isFinite(i)||i<0)return;let a=r[1],n=a===void 0?0:Number.parseInt(a,10);if(!(!Number.isFinite(n)||n<0))return{major:i,minor:n}}function pi(t,e){return t.major!==e.major?t.major-e.major:t.minor-e.minor}function pr(t){if(!t||t.trim()==="")return!0;let e=Pe(t);if(!e)return!1;let r=Pe(Zi),i=Pe(_s);return!r||!i?!1:pi(e,r)>=0&&pi(e,i)<0}function ks(t,e,r){let i=ds[t];return i?r===void 0?new dr[i]({message:e}):new ms[i]({message:e,envelopeCode:t,data:r}):t===U.METHOD_NOT_FOUND?new fr({message:e,envelopeCode:t,data:r}):t===U.PARSE_ERROR||t===U.INVALID_REQUEST?new xt({message:e,envelopeCode:t,data:r}):new Xi({jsonrpc:"2.0",id:null,error:{code:t,message:e,data:r}})}var S=ks;Object.defineProperty(S,Symbol.hasInstance,{value:t=>t instanceof W});S.parseError=(t,e)=>new xt({message:t,envelopeCode:U.PARSE_ERROR,data:e});S.invalidRequest=(t,e)=>new xt({message:t,envelopeCode:U.INVALID_REQUEST,data:e});S.methodNotFound=t=>new fr({message:`Method not found: ${t}`,envelopeCode:U.METHOD_NOT_FOUND});S.invalidParams=(t,e)=>e===void 0?new L({message:t}):new xt({message:t,envelopeCode:U.INVALID_PARAMS,data:e});S.internalError=(t,e)=>new Xi({jsonrpc:"2.0",id:null,error:{code:U.INTERNAL_ERROR,message:t,...e!==void 0?{data:e}:{}}});S.taskNotFound=t=>new Vi({message:`Task not found: ${t}`});S.taskNotCancelable=t=>new Gi({message:`Task not cancelable: ${t}`});S.pushNotificationNotSupported=()=>new or;S.unsupportedOperation=t=>new Qi({message:`Unsupported operation: ${t}`});S.authenticatedExtendedCardNotConfigured=()=>new Yi({message:"Extended card not configured."});function V(t){return t!==void 0&&t!==""?t:void 0}function bi(t){return Object.fromEntries(Object.entries(t.schemes).map(([e,r])=>[e,[...r.list]]))}function As(t){let e={type:"apiKey",name:t.name,in:t.location==="cookie"||t.location==="query"?t.location:"header"},r=V(t.description);return r!==void 0&&(e.description=r),e}function Is(t){let e={type:"http",scheme:t.scheme},r=V(t.description);r!==void 0&&(e.description=r);let i=V(t.bearerFormat);return i!==void 0&&(e.bearerFormat=i),e}function Cs(t){let e={type:"mutualTLS"},r=V(t.description);return r!==void 0&&(e.description=r),e}function Rs(t){if(!t.flows)throw S.invalidParams("OAuth2 security scheme missing flows");let e={type:"oauth2",flows:ws(t.flows)},r=V(t.description);r!==void 0&&(e.description=r);let i=V(t.oauth2MetadataUrl);return i!==void 0&&(e.oauth2MetadataUrl=i),e}function Us(t){let e={type:"openIdConnect",openIdConnectUrl:t.openIdConnectUrl},r=V(t.description);return r!==void 0&&(e.description=r),e}function Js(t){let e=t.scheme;if(!e)throw S.invalidParams("Invalid v1.0 SecurityScheme: missing inner scheme");switch(e.$case){case"apiKeySecurityScheme":return As(e.value);case"httpAuthSecurityScheme":return Is(e.value);case"mtlsSecurityScheme":return Cs(e.value);case"oauth2SecurityScheme":return Rs(e.value);case"openIdConnectSecurityScheme":return Us(e.value);default:throw S.invalidParams(`Unsupported v1.0 SecurityScheme $case: ${e.$case??"unknown"}`)}}function ws(t){let e={},r=t.flow;if(!r)return e;switch(r.$case){case"authorizationCode":{let i=r.value;e.authorizationCode={authorizationUrl:i.authorizationUrl,tokenUrl:i.tokenUrl,scopes:{...i.scopes}};let a=V(i.refreshUrl);a!==void 0&&(e.authorizationCode.refreshUrl=a);break}case"clientCredentials":{let i=r.value;e.clientCredentials={tokenUrl:i.tokenUrl,scopes:{...i.scopes}};let a=V(i.refreshUrl);a!==void 0&&(e.clientCredentials.refreshUrl=a);break}case"implicit":{let i=r.value;e.implicit={authorizationUrl:i.authorizationUrl,scopes:{...i.scopes}};let a=V(i.refreshUrl);a!==void 0&&(e.implicit.refreshUrl=a);break}case"password":{let i=r.value;e.password={tokenUrl:i.tokenUrl,scopes:{...i.scopes}};let a=V(i.refreshUrl);a!==void 0&&(e.password.refreshUrl=a);break}default:break}return e}function $(t){return t===void 0?void 0:structuredClone(t)}function mt(t,e){if(!Array.isArray(t))throw S.invalidParams(`${e} is required and must be an array`);return t}function xs(t){return t!==void 0&&t!==""?t:void 0}function Ps(t){return{url:t.url,transport:t.protocolBinding}}function Ds(t){return{url:t.url,organization:t.organization}}function Ms(t){let e={uri:t.uri},r=xs(t.description);r!==void 0&&(e.description=r),e.required=t.required;let i=$(t.params);return i!==void 0&&(e.params=i),e}function Ls(t){let e={};return t.streaming!==void 0&&(e.streaming=t.streaming),t.pushNotifications!==void 0&&(e.pushNotifications=t.pushNotifications),t.extensions&&t.extensions.length>0&&(e.extensions=t.extensions.map(Ms)),e}function $s(t){let e={id:t.id,name:t.name,description:t.description,tags:[...mt(t.tags,"skill.tags")]};return t.examples&&t.examples.length>0&&(e.examples=[...t.examples]),t.inputModes&&t.inputModes.length>0&&(e.inputModes=[...t.inputModes]),t.outputModes&&t.outputModes.length>0&&(e.outputModes=[...t.outputModes]),t.securityRequirements&&t.securityRequirements.length>0&&(e.security=t.securityRequirements.map(bi)),e}function zs(t){let e={protected:t.protected,signature:t.signature},r=$(t.header);return r!==void 0&&(e.header=r),e}function Sr(t,e){let r=t.supportedInterfaces??[],i=r.filter(O=>!O.protocolVersion||pr(O.protocolVersion));if(i.length===0)throw new oe("AgentCard must have at least one interface with a protocol version in [0.3, 1.0).");let a=i[0],n=i.slice(1).map(Ps),o=t.capabilities?Ls(t.capabilities):{},d=t.capabilities&&t.capabilities.extendedAgentCard!==void 0?t.capabilities.extendedAgentCard:void 0,f=t.securitySchemes&&Object.keys(t.securitySchemes).length>0?Object.fromEntries(Object.entries(t.securitySchemes).map(([O,u])=>[O,Js(u)])):void 0,T=a.protocolVersion||Zi,p={name:t.name,description:t.description,version:t.version,url:a.url,preferredTransport:a.protocolBinding,protocolVersion:T,capabilities:o,defaultInputModes:[...mt(t.defaultInputModes,"agentCard.defaultInputModes")],defaultOutputModes:[...mt(t.defaultOutputModes,"agentCard.defaultOutputModes")],skills:mt(t.skills,"agentCard.skills").map($s)};return n.length>0&&(p.additionalInterfaces=n),t.provider&&(p.provider=Ds(t.provider)),t.documentationUrl!==void 0&&t.documentationUrl!==""&&(p.documentationUrl=t.documentationUrl),t.iconUrl!==void 0&&t.iconUrl!==""&&(p.iconUrl=t.iconUrl),d!==void 0&&(p.supportsAuthenticatedExtendedCard=d),f!==void 0&&(p.securitySchemes=f),t.securityRequirements&&t.securityRequirements.length>0&&(p.security=t.securityRequirements.map(bi)),t.signatures&&t.signatures.length>0&&(p.signatures=t.signatures.map(zs)),e?.embedV1Interfaces&&r.length>0&&(p.supportedInterfaces=structuredClone(r)),p}function ji(t){if(ur(t))return{code:t.envelopeCode,message:t.message,...t.data!==void 0?{data:t.data}:{}};if(t instanceof W)return{code:le[t.name]??U.INTERNAL_ERROR,message:t.message};let e=t instanceof Error&&t.message||"An unexpected error occurred.";return{code:U.INTERNAL_ERROR,message:e}}var qs=Object.freeze({unknown:0,submitted:1,working:2,completed:3,failed:4,canceled:5,"input-required":6,rejected:7,"auth-required":8}),Fs=new Map(Object.entries(qs).map(([t,e])=>[e,t]));function Bs(t){return Fs.get(t)??"unknown"}function Hs(t){return t==="user"?1:t==="agent"?2:0}function Ks(t){return t===1?"user":"agent"}var be="data_part_compat";function ta(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!Buffer.isBuffer(t)}function Vs(t){if(t===null||Array.isArray(t))return!0;let e=typeof t;return e==="string"||e==="number"||e==="boolean"}function Gs(t){if(typeof t!="object"||t===null||Array.isArray(t))throw S.invalidParams("Each part must be an object");if(t.kind==="text")return{content:{$case:"text",value:t.text},metadata:$(t.metadata),filename:"",mediaType:""};if(t.kind==="file"){let e=t.file,r=e.mimeType??"",i=e.name??"",a=$(t.metadata);if("bytes"in e)return{content:{$case:"raw",value:Buffer.from(e.bytes,"base64")},metadata:a,filename:i,mediaType:r};if("uri"in e)return{content:{$case:"url",value:e.uri},metadata:a,filename:i,mediaType:r};throw S.invalidParams("Invalid file part: missing `bytes` or `uri`")}if(t.kind==="data"){let e=$(t.metadata),r=t.data,i=e;return e!==void 0&&e[be]===!0&&(ta(t.data)&&"value"in t.data&&(r=t.data.value),delete e[be],i=Object.keys(e).length>0?e:void 0),{content:{$case:"data",value:r},metadata:i,filename:"",mediaType:""}}throw S.invalidParams(`Invalid v0.3 part kind: ${t.kind??"undefined"}`)}function ea(t){let e=t.content,r=$(t.metadata);if(!e)throw S.invalidParams("Invalid v1.0 part: missing content");if(e.$case==="text"){let i={kind:"text",text:e.value};return r!==void 0&&(i.metadata=r),i}if(e.$case==="raw"||e.$case==="url"){let i=t.mediaType!==""?t.mediaType:void 0,a=t.filename!==""?t.filename:void 0,n;if(e.$case==="raw"){let f={bytes:(Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value)).toString("base64")};i!==void 0&&(f.mimeType=i),a!==void 0&&(f.name=a),n=f}else{let d={uri:e.value};i!==void 0&&(d.mimeType=i),a!==void 0&&(d.name=a),n=d}let o={kind:"file",file:n};return r!==void 0&&(o.metadata=r),o}if(e.$case==="data"){let i=e.value;if(ta(i)){let a={kind:"data",data:i};return r!==void 0&&(a.metadata=r),a}if(Vs(i)){let a={value:i},n=r??{};return n[be]=!0,{kind:"data",data:a,metadata:n}}throw S.invalidParams("Cannot translate v1 data part to v0.3: value is neither a plain object nor a wrap-eligible primitive / array / null (e.g., Symbol, function, bigint, undefined, Buffer). Primitives, arrays, and null are wrapped as { value: ... } with data_part_compat=true; all other non-plain-object values are rejected.")}throw S.invalidParams(`Invalid v1.0 part content type: ${e.$case??"unknown"}`)}function Si(t){return t==null||t===""?void 0:t}function Ti(t){return t==null||t.length===0?void 0:[...t]}function Qs(t){if(typeof t!="object"||t===null)throw S.invalidParams("message must be an object");if(typeof t.messageId!="string"||t.messageId==="")throw S.invalidParams("message.messageId is required");if(t.role!=="user"&&t.role!=="agent")throw S.invalidParams('message.role must be "user" or "agent"');if(!Array.isArray(t.parts))throw S.invalidParams("message.parts must be an array");return{messageId:t.messageId,contextId:t.contextId??"",taskId:t.taskId??"",role:Hs(t.role),parts:t.parts.map(Gs),metadata:$(t.metadata),extensions:t.extensions?[...t.extensions]:[],referenceTaskIds:t.referenceTaskIds?[...t.referenceTaskIds]:[]}}function Pt(t){let e={kind:"message",messageId:t.messageId,role:Ks(t.role),parts:mt(t.parts,"message.parts").map(ea)},r=Si(t.contextId);r!==void 0&&(e.contextId=r);let i=Si(t.taskId);i!==void 0&&(e.taskId=i);let a=$(t.metadata);a!==void 0&&(e.metadata=a);let n=Ti(t.extensions);n!==void 0&&(e.extensions=n);let o=Ti(t.referenceTaskIds);return o!==void 0&&(e.referenceTaskIds=o),e}function je(t){return t!==void 0&&t!==""?t:void 0}function ra(t){return t.schemes&&t.schemes.length>1&&console.warn(`toCoreAuthenticationInfo: Lossy conversion from v0.3 PushNotificationAuthenticationInfo to v1.0 AuthenticationInfo. Multiple schemes declared (${t.schemes.join(", ")}), but only the first one ('${t.schemes[0]}') will be kept.`),{scheme:t.schemes&&t.schemes.length>0?t.schemes[0]:"",credentials:t.credentials??""}}function Ys(t){let e={schemes:t.scheme!==""?[t.scheme]:[]},r=je(t.credentials);return r!==void 0&&(e.credentials=r),e}function Ws(t,e=""){return{tenant:e,taskId:"",id:t.id??"",url:t.url,token:t.token??"",authentication:t.authentication?ra(t.authentication):void 0}}function Xs(t){let e={url:t.url},r=je(t.id);r!==void 0&&(e.id=r);let i=je(t.token);return i!==void 0&&(e.token=i),t.authentication&&(e.authentication=Ys(t.authentication)),e}function ia(t,e=""){return{tenant:e,taskId:t.taskId,id:t.pushNotificationConfig.id??"",url:t.pushNotificationConfig.url,token:t.pushNotificationConfig.token??"",authentication:t.pushNotificationConfig.authentication?ra(t.pushNotificationConfig.authentication):void 0}}function Nt(t){return{taskId:t.taskId,pushNotificationConfig:Xs(t)}}function gi(t){return t==null||t===""?void 0:t}function Zs(t){return t==null||t.length===0?void 0:[...t]}function aa(t){let e={artifactId:t.artifactId,parts:mt(t.parts,"artifact.parts").map(ea)},r=gi(t.name);r!==void 0&&(e.name=r);let i=gi(t.description);i!==void 0&&(e.description=i);let a=$(t.metadata);a!==void 0&&(e.metadata=a);let n=Zs(t.extensions);return n!==void 0&&(e.extensions=n),e}var bs=new Set(["completed","canceled","failed","rejected"]);function na(t){let e={state:Bs(t.state)};return t.message&&(e.message=Pt(t.message)),t.timestamp!==void 0&&t.timestamp!==""&&(e.timestamp=t.timestamp),e}function ut(t){let e={kind:"task",id:t.id,contextId:t.contextId,status:t.status?na(t.status):{state:"unknown"}};t.history&&t.history.length>0&&(e.history=t.history.map(Pt)),t.artifacts&&t.artifacts.length>0&&(e.artifacts=t.artifacts.map(aa));let r=$(t.metadata);return r!==void 0&&(e.metadata=r),e}function js(t){let e=t.status?na(t.status):{state:"unknown"},r={kind:"status-update",taskId:t.taskId,contextId:t.contextId,status:e,final:bs.has(e.state)},i=$(t.metadata);return i!==void 0&&(r.metadata=i),r}function to(t){if(!t.artifact)throw S.invalidParams("Invalid TaskArtifactUpdateEvent: missing artifact");let e={kind:"artifact-update",taskId:t.taskId,contextId:t.contextId,artifact:aa(t.artifact),append:t.append,lastChunk:t.lastChunk},r=$(t.metadata);return r!==void 0&&(e.metadata=r),e}function eo(t){return{acceptedOutputModes:t.acceptedOutputModes?[...t.acceptedOutputModes]:[],taskPushNotificationConfig:t.pushNotificationConfig?Ws(t.pushNotificationConfig):void 0,historyLength:t.historyLength,returnImmediately:t.blocking===void 0?!0:!t.blocking}}function jt(t,e=""){return{tenant:e,message:Qs(t.params.message),configuration:t.params.configuration?eo(t.params.configuration):void 0,metadata:$(t.params.metadata)}}function sa(t,e=null){let r=t.payload;if(!r)throw S.internalError("StreamResponse missing payload");let i;switch(r.$case){case"message":i=Pt(r.value);break;case"task":i=ut(r.value);break;case"statusUpdate":i=js(r.value);break;case"artifactUpdate":i=to(r.value);break;default:throw S.internalError("StreamResponse has unknown payload case")}return{id:e,jsonrpc:"2.0",result:i}}function ro(t,e=""){return{tenant:e,id:t.params.id,historyLength:t.params.historyLength}}function io(t,e=""){return{tenant:e,id:t.params.id,metadata:$(t.params.metadata)}}function ao(t,e=""){return{tenant:e,id:t.params.id}}function no(t,e=""){return ia(t.params,e)}function so(t,e=""){let r=t.params,i="pushNotificationConfigId"in r?r.pushNotificationConfigId:void 0;return{tenant:e,taskId:r.id,id:i??""}}function oo(t,e=""){return{tenant:e,taskId:t.params.id,id:t.params.pushNotificationConfigId}}function lo(t,e=""){return{tenant:e,taskId:t.params.id,pageSize:0,pageToken:""}}function uo(t,e=null){return{id:e,jsonrpc:"2.0",result:t.configs.map(r=>Nt(r))}}function fo(t,e=""){return{tenant:e}}var mi=class tr{requestHandler;constructor(e){this.requestHandler=e}async handle(e,r){let i={jsonrpc:"2.0",method:""};try{if(typeof e=="string")i=JSON.parse(e);else if(typeof e=="object"&&e!==null)i=e;else throw S.invalidRequest("Invalid request body type.");if(!this.isRequestValid(i))throw S.invalidRequest("Invalid JSON-RPC Request.")}catch(o){let d=tr.mapToLegacyJSONRPCError(o instanceof SyntaxError?S.invalidRequest(o.message||"Failed to parse JSON request."):o);return{jsonrpc:"2.0",id:i.id??null,error:d}}let{method:a,id:n=null}=i;try{if(a!=="agent/getAuthenticatedExtendedCard"&&!this.paramsAreValid(i.params))throw S.invalidParams("Invalid method parameters.");if(a==="message/stream"||a==="tasks/resubscribe"){if(!(await this.requestHandler.getAgentCard()).capabilities?.streaming)throw S.unsupportedOperation(`Method ${a} requires streaming capability.`);let f=a==="message/stream"?this.requestHandler.sendMessageStream(jt(i),r):this.requestHandler.resubscribe(ao(i),r);return(async function*(){for await(let p of f)yield sa(p,n)})()}let o;switch(a){case"message/send":{let d=await this.requestHandler.sendMessage(jt(i),r);o="messageId"in d?Pt(d):ut(d);break}case"tasks/get":o=ut(await this.requestHandler.getTask(ro(i),r));break;case"tasks/cancel":o=ut(await this.requestHandler.cancelTask(io(i),r));break;case"tasks/pushNotificationConfig/set":o=Nt(await this.requestHandler.createTaskPushNotificationConfig(no(i),r));break;case"tasks/pushNotificationConfig/get":o=Nt(await this.requestHandler.getTaskPushNotificationConfig(so(i),r));break;case"tasks/pushNotificationConfig/list":{o=uo(await this.requestHandler.listTaskPushNotificationConfigs(lo(i),r),n).result;break}case"tasks/pushNotificationConfig/delete":await this.requestHandler.deleteTaskPushNotificationConfig(oo(i),r),o=null;break;case"agent/getAuthenticatedExtendedCard":o=Sr(await this.requestHandler.getAuthenticatedExtendedAgentCard(fo(i),r));break;default:throw S.methodNotFound(a)}return{jsonrpc:"2.0",id:n,result:o}}catch(o){return{jsonrpc:"2.0",id:n,error:tr.mapToLegacyJSONRPCError(o)}}}isRequestValid(e){if(e.jsonrpc!=="2.0")return!1;if("id"in e){let r=e.id,i=typeof r=="string",a=typeof r=="number"&&Number.isInteger(r);if(!i&&!a&&!(r===null))return!1}return!(!e.method||typeof e.method!="string")}paramsAreValid(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;for(let r of Object.keys(e))if(r==="")return!1;return!0}static mapToLegacyJSONRPCError(e){return ji(e)}},co={[-32700]:v.BAD_REQUEST,[-32600]:v.BAD_REQUEST,[-32601]:v.NOT_IMPLEMENTED,[-32602]:v.BAD_REQUEST,[-32603]:v.INTERNAL_SERVER_ERROR,[-32001]:v.NOT_FOUND,[-32002]:v.BAD_REQUEST,[-32003]:v.BAD_REQUEST,[-32004]:v.BAD_REQUEST,[-32005]:v.BAD_REQUEST,[-32006]:v.INTERNAL_SERVER_ERROR,[-32007]:v.BAD_REQUEST};function Ni(t){if(ur(t)){let e=co[t.envelopeCode];if(e!==void 0)return e}return Vt(t)}function Et(t){return ji(t)}var ho=class Gt{requestHandler;constructor(e){this.requestHandler=e}async getAgentCard(){return this.requestHandler.getAgentCard()}async getAuthenticatedExtendedAgentCard(e){let r=await this.requestHandler.getAuthenticatedExtendedAgentCard({tenant:e.tenant??""},e);return Sr(r)}validateMessageSendParams(e){if(!e.message)throw S.invalidParams("message is required");if(!e.message.messageId)throw S.invalidParams("message.messageId is required")}async sendMessage(e,r){this.validateMessageSendParams(e);let i=jt(Ei(e,"message/send"),r.tenant??""),a=await this.requestHandler.sendMessage(i,r);return"messageId"in a?Pt(a):ut(a)}async sendMessageStream(e,r){await this.requireCapability("streaming"),this.validateMessageSendParams(e);let i=jt(Ei(e,"message/stream"),r.tenant??""),a=this.requestHandler.sendMessageStream(i,r);return Gt.translateStream(a)}async getTask(e,r,i){let a={id:e,tenant:r.tenant??""};i!==void 0&&(a.historyLength=this.parseHistoryLength(i));let n=await this.requestHandler.getTask(a,r);return ut(n)}async cancelTask(e,r){let i=await this.requestHandler.cancelTask({id:e,tenant:r.tenant??"",metadata:{}},r);return ut(i)}async resubscribe(e,r){await this.requireCapability("streaming");let i=this.requestHandler.resubscribe({id:e,tenant:r.tenant??""},r);return Gt.translateStream(i)}async setTaskPushNotificationConfig(e,r){if(await this.requireCapability("pushNotifications"),!e.taskId)throw S.invalidParams("taskId is required");if(!e.pushNotificationConfig)throw S.invalidParams("pushNotificationConfig is required");let i=ia(e,r.tenant??""),a=await this.requestHandler.createTaskPushNotificationConfig(i,r);return Nt(a)}async listTaskPushNotificationConfigs(e,r){return(await this.requestHandler.listTaskPushNotificationConfigs({taskId:e,pageSize:0,pageToken:"",tenant:r.tenant??""},r)).configs.map(a=>Nt(a))}async getTaskPushNotificationConfig(e,r,i){let a=await this.requestHandler.getTaskPushNotificationConfig({taskId:e,id:r,tenant:i.tenant??""},i);return Nt(a)}async deleteTaskPushNotificationConfig(e,r,i){await this.requestHandler.deleteTaskPushNotificationConfig({taskId:e,id:r,tenant:i.tenant??""},i)}static async*translateStream(e){for await(let r of e)yield sa(r,null).result}static CAPABILITY_ERRORS={streaming:()=>S.unsupportedOperation("Agent does not support streaming"),pushNotifications:()=>S.pushNotificationNotSupported()};async requireCapability(e){if(!(await this.getAgentCard()).capabilities?.[e])throw Gt.CAPABILITY_ERRORS[e]()}parseHistoryLength(e){if(e==null)throw S.invalidParams("historyLength is required");let r=parseInt(String(e),10);if(isNaN(r))throw S.invalidParams("historyLength must be a valid integer");if(r<0)throw S.invalidParams("historyLength must be non-negative");return r}static mapToLegacyHTTPError(e){return Et(e)}};function Ei(t,e){return{jsonrpc:"2.0",id:0,method:e,params:t}}var te="X-A2A-Extensions",Jt="application/json",oa="message/send",la="message/stream",da="tasks/get",ua="tasks/cancel",Tr="tasks/resubscribe",fa="tasks/pushNotificationConfig/set",ca="tasks/pushNotificationConfig/get",ha="tasks/pushNotificationConfig/list",pa="tasks/pushNotificationConfig/delete",Sa="agent/getAuthenticatedExtendedCard",Ta=Object.freeze({[oa]:"SendMessage",[la]:"SendStreamingMessage",[da]:"GetTask",[ua]:"CancelTask",[Tr]:"SubscribeToTask",[fa]:"CreateTaskPushNotificationConfig",[ca]:"GetTaskPushNotificationConfig",[ha]:"ListTaskPushNotificationConfigs",[pa]:"DeleteTaskPushNotificationConfig",[Sa]:"GetExtendedAgentCard"}),Rl=Object.freeze(Object.fromEntries(Object.entries(Ta).map(([t,e])=>[e,t]))),ga=Object.freeze({[oa]:"SendMessage",[la]:"SendStreamingMessage",[da]:"GetTask",[ua]:"CancelTask",[Tr]:"TaskSubscription",[fa]:"CreateTaskPushNotificationConfig",[ca]:"GetTaskPushNotificationConfig",[ha]:"ListTaskPushNotificationConfig",[pa]:"DeleteTaskPushNotificationConfig",[Sa]:"GetAgentCard"}),Ul=Object.freeze(Object.fromEntries(Object.entries(ga).map(([t,e])=>[e,t]))),po=Object.freeze(Object.fromEntries(Object.entries(ga).map(([t,e])=>[e,Ta[t]]))),Jl=Object.freeze(Object.fromEntries(Object.entries(po).map(([t,e])=>[e,t])));function ma(t){let e=new Xe(t.requestHandler),r=t.legacyCompat?.enabled?new mi(t.requestHandler):void 0,i=Qe.default.Router();return i.use(So),i.use(Qe.default.json(),To),i.post("/",async(a,n)=>{let o=r!==void 0&&(a.header(rt)||Ot)===Ot,d=o?mi.mapToLegacyJSONRPCError:Xe.mapToJSONRPCError;try{let f=await t.userBuilder(a),T=a.header(rt)||void 0,p=o?a.header(te)??a.header(gt):a.header(gt),u=(t.contextBuilder??cr)({extensions:se.parseServiceParameter(p),user:f,headers:a.headers,requestedVersion:T}),N=await t.requestHandler.getAgentCard();hr(u.requestedVersion,N,"JSONRPC");let g=await(o?r:e).handle(a.body,u);if(u.activatedExtensions&&n.setHeader(o?te:gt,Array.from(u.activatedExtensions)),typeof g?.[Symbol.asyncIterator]=="function"){let _=g;if(o&&a.body?.method===Tr){Object.entries(Zt).forEach(([m,k])=>{n.setHeader(m,k)}),n.flushHeaders();try{for await(let m of _)n.write(dt(m))}catch(m){console.error(`Error during SSE streaming (request ${a.body?.id}):`,m);let k={jsonrpc:"2.0",id:a.body?.id||null,error:d(m)};n.writableEnded||n.write(bt(k))}finally{n.writableEnded||n.end()}return}let c=_[Symbol.asyncIterator](),E;try{E=await c.next()}catch(m){console.error(`Pre-stream error for request ${a.body?.id}:`,m);let k={jsonrpc:"2.0",id:a.body?.id||null,error:d(m)};n.status(200).json(k);return}Object.entries(Zt).forEach(([m,k])=>{n.setHeader(m,k)}),n.flushHeaders();try{E.done||n.write(dt(E.value));for await(let m of ar(c))n.write(dt(m))}catch(m){console.error(`Error during SSE streaming (request ${a.body?.id}):`,m);let k={jsonrpc:"2.0",id:a.body?.id||null,error:d(m)};n.headersSent?n.write(bt(k)):n.status(500).json(k)}finally{n.writableEnded||n.end()}}else{let _=g;n.status(200).json(_)}}catch(f){console.error("Unhandled error in JSON-RPC POST handler:",f);let T=d(f),p={jsonrpc:"2.0",id:a.body?.id||null,error:T};if(n.headersSent)n.writableEnded||n.end();else{let O=T.code===U.INTERNAL_ERROR;n.status(O?500:200).json(p)}}}),i}var So=(t,e,r)=>{let i=t.header("content-type");if(!i){r();return}if(i.split(";",1)[0].trim().toLowerCase()===sr){r();return}let n={jsonrpc:"2.0",id:null,error:Xe.mapToJSONRPCError(new lr(`Unsupported Content-Type "${i}"; expected application/json.`))};e.status(200).json(n)},To=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t){let a={jsonrpc:"2.0",id:null,error:{code:U.PARSE_ERROR,message:"Invalid JSON payload."}};return r.status(200).json(a)}i(t)};function No(t){return`W/"${mo.createHash("sha256").update(t).digest("hex").slice(0,16)}"`}function Eo(t){let e=Ea.default.Router(),r=t.cache?.maxAge??3600,i=typeof t.agentCardProvider=="function"?t.agentCardProvider:t.agentCardProvider.getAgentCard.bind(t.agentCardProvider);return e.use((a,n,o)=>{let d=a.header(rt)||Ot;pr(d)?o():o("router")}),e.get("/",async(a,n)=>{try{let o=await i(),d;try{d=Sr(o,{embedV1Interfaces:!0})}catch(p){if(p instanceof oe){n.append("Vary",rt),n.status(v.BAD_REQUEST).setHeader("Content-Type",Jt).json(Et(p));return}throw p}let f=JSON.stringify(d),T=No(f);if(n.setHeader("ETag",T),n.append("Vary",rt),r>0?n.setHeader("Cache-Control",`public, max-age=${r}`):n.setHeader("Cache-Control","no-cache"),a.fresh){n.status(304).end();return}n.setHeader("Content-Type",Jt),n.status(v.OK).send(f)}catch(o){console.error("Error fetching legacy agent card:",o),n.append("Vary",rt),n.status(500).setHeader("Content-Type",Jt).json({error:"Failed to retrieve agent card"})}}),e}function vo(t){switch(t){case 0:case"TASK_STATE_UNSPECIFIED":return 0;case 1:case"TASK_STATE_SUBMITTED":return 1;case 2:case"TASK_STATE_WORKING":return 2;case 3:case"TASK_STATE_COMPLETED":return 3;case 4:case"TASK_STATE_FAILED":return 4;case 5:case"TASK_STATE_CANCELLED":return 5;case 6:case"TASK_STATE_INPUT_REQUIRED":return 6;case 7:case"TASK_STATE_REJECTED":return 7;case 8:case"TASK_STATE_AUTH_REQUIRED":return 8;default:return-1}}function Oo(t){switch(t){case 0:return"TASK_STATE_UNSPECIFIED";case 1:return"TASK_STATE_SUBMITTED";case 2:return"TASK_STATE_WORKING";case 3:return"TASK_STATE_COMPLETED";case 4:return"TASK_STATE_FAILED";case 5:return"TASK_STATE_CANCELLED";case 6:return"TASK_STATE_INPUT_REQUIRED";case 7:return"TASK_STATE_REJECTED";case 8:return"TASK_STATE_AUTH_REQUIRED";default:return"UNRECOGNIZED"}}function yo(t){switch(t){case 0:case"ROLE_UNSPECIFIED":return 0;case 1:case"ROLE_USER":return 1;case 2:case"ROLE_AGENT":return 2;default:return-1}}function _o(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var vi={fromJSON(t){return{acceptedOutputModes:globalThis.Array.isArray(t?.acceptedOutputModes)?t.acceptedOutputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.accepted_output_modes)?t.accepted_output_modes.map(e=>globalThis.String(e)):[],pushNotification:l(t.pushNotification)?vt.fromJSON(t.pushNotification):l(t.push_notification)?vt.fromJSON(t.push_notification):void 0,historyLength:l(t.historyLength)?globalThis.Number(t.historyLength):l(t.history_length)?globalThis.Number(t.history_length):0,blocking:l(t.blocking)?globalThis.Boolean(t.blocking):!1}},toJSON(t){let e={};return t.acceptedOutputModes?.length&&(e.acceptedOutputModes=t.acceptedOutputModes),t.pushNotification!==void 0&&(e.pushNotification=vt.toJSON(t.pushNotification)),t.historyLength!==0&&(e.historyLength=Math.round(t.historyLength)),t.blocking!==!1&&(e.blocking=t.blocking),e}},wt={fromJSON(t){return{id:l(t.id)?globalThis.String(t.id):"",contextId:l(t.contextId)?globalThis.String(t.contextId):l(t.context_id)?globalThis.String(t.context_id):"",status:l(t.status)?ee.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>ie.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>z.fromJSON(e)):[],metadata:x(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=ee.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>ie.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>z.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},ee={fromJSON(t){return{state:l(t.state)?vo(t.state):0,update:l(t.message)?z.fromJSON(t.message):l(t.update)?z.fromJSON(t.update):void 0,timestamp:l(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=Oo(t.state)),t.update!==void 0&&(e.message=z.toJSON(t.update)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},re={fromJSON(t){return{part:l(t.text)?{$case:"text",value:globalThis.String(t.text)}:l(t.file)?{$case:"file",value:Oi.fromJSON(t.file)}:l(t.data)?{$case:"data",value:yi.fromJSON(t.data)}:void 0}},toJSON(t){let e={};return t.part?.$case==="text"?e.text=t.part.value:t.part?.$case==="file"?e.file=Oi.toJSON(t.part.value):t.part?.$case==="data"&&(e.data=yi.toJSON(t.part.value)),e}},Oi={fromJSON(t){return{file:l(t.fileWithUri)?{$case:"fileWithUri",value:globalThis.String(t.fileWithUri)}:l(t.file_with_uri)?{$case:"fileWithUri",value:globalThis.String(t.file_with_uri)}:l(t.fileWithBytes)?{$case:"fileWithBytes",value:Buffer.from(Pi(t.fileWithBytes))}:l(t.file_with_bytes)?{$case:"fileWithBytes",value:Buffer.from(Pi(t.file_with_bytes))}:void 0,mimeType:l(t.mimeType)?globalThis.String(t.mimeType):l(t.mime_type)?globalThis.String(t.mime_type):""}},toJSON(t){let e={};return t.file?.$case==="fileWithUri"?e.fileWithUri=t.file.value:t.file?.$case==="fileWithBytes"&&(e.fileWithBytes=Uo(t.file.value)),t.mimeType!==""&&(e.mimeType=t.mimeType),e}},yi={fromJSON(t){return{data:x(t.data)?t.data:void 0}},toJSON(t){let e={};return t.data!==void 0&&(e.data=t.data),e}},z={fromJSON(t){return{messageId:l(t.messageId)?globalThis.String(t.messageId):l(t.message_id)?globalThis.String(t.message_id):"",contextId:l(t.contextId)?globalThis.String(t.contextId):l(t.context_id)?globalThis.String(t.context_id):"",taskId:l(t.taskId)?globalThis.String(t.taskId):l(t.task_id)?globalThis.String(t.task_id):"",role:l(t.role)?yo(t.role):0,content:globalThis.Array.isArray(t?.content)?t.content.map(e=>re.fromJSON(e)):[],metadata:x(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.messageId!==""&&(e.messageId=t.messageId),t.contextId!==""&&(e.contextId=t.contextId),t.taskId!==""&&(e.taskId=t.taskId),t.role!==0&&(e.role=_o(t.role)),t.content?.length&&(e.content=t.content.map(r=>re.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},ie={fromJSON(t){return{artifactId:l(t.artifactId)?globalThis.String(t.artifactId):l(t.artifact_id)?globalThis.String(t.artifact_id):"",name:l(t.name)?globalThis.String(t.name):"",description:l(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>re.fromJSON(e)):[],metadata:x(t.metadata)?t.metadata:void 0,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.artifactId!==""&&(e.artifactId=t.artifactId),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.parts?.length&&(e.parts=t.parts.map(r=>re.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},De={fromJSON(t){return{taskId:l(t.taskId)?globalThis.String(t.taskId):l(t.task_id)?globalThis.String(t.task_id):"",contextId:l(t.contextId)?globalThis.String(t.contextId):l(t.context_id)?globalThis.String(t.context_id):"",status:l(t.status)?ee.fromJSON(t.status):void 0,final:l(t.final)?globalThis.Boolean(t.final):!1,metadata:x(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.status!==void 0&&(e.status=ee.toJSON(t.status)),t.final!==!1&&(e.final=t.final),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Me={fromJSON(t){return{taskId:l(t.taskId)?globalThis.String(t.taskId):l(t.task_id)?globalThis.String(t.task_id):"",contextId:l(t.contextId)?globalThis.String(t.contextId):l(t.context_id)?globalThis.String(t.context_id):"",artifact:l(t.artifact)?ie.fromJSON(t.artifact):void 0,append:l(t.append)?globalThis.Boolean(t.append):!1,lastChunk:l(t.lastChunk)?globalThis.Boolean(t.lastChunk):l(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:x(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.taskId!==""&&(e.taskId=t.taskId),t.contextId!==""&&(e.contextId=t.contextId),t.artifact!==void 0&&(e.artifact=ie.toJSON(t.artifact)),t.append!==!1&&(e.append=t.append),t.lastChunk!==!1&&(e.lastChunk=t.lastChunk),t.metadata!==void 0&&(e.metadata=t.metadata),e}},vt={fromJSON(t){return{id:l(t.id)?globalThis.String(t.id):"",url:l(t.url)?globalThis.String(t.url):"",token:l(t.token)?globalThis.String(t.token):"",authentication:l(t.authentication)?_i.fromJSON(t.authentication):void 0}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.url!==""&&(e.url=t.url),t.token!==""&&(e.token=t.token),t.authentication!==void 0&&(e.authentication=_i.toJSON(t.authentication)),e}},_i={fromJSON(t){return{schemes:globalThis.Array.isArray(t?.schemes)?t.schemes.map(e=>globalThis.String(e)):[],credentials:l(t.credentials)?globalThis.String(t.credentials):""}},toJSON(t){let e={};return t.schemes?.length&&(e.schemes=t.schemes),t.credentials!==""&&(e.credentials=t.credentials),e}},Le={fromJSON(t){return{url:l(t.url)?globalThis.String(t.url):"",transport:l(t.transport)?globalThis.String(t.transport):""}},toJSON(t){let e={};return t.url!==""&&(e.url=t.url),t.transport!==""&&(e.transport=t.transport),e}},ko={fromJSON(t){return{protocolVersion:l(t.protocolVersion)?globalThis.String(t.protocolVersion):l(t.protocol_version)?globalThis.String(t.protocol_version):"",name:l(t.name)?globalThis.String(t.name):"",description:l(t.description)?globalThis.String(t.description):"",url:l(t.url)?globalThis.String(t.url):"",preferredTransport:l(t.preferredTransport)?globalThis.String(t.preferredTransport):l(t.preferred_transport)?globalThis.String(t.preferred_transport):"",additionalInterfaces:globalThis.Array.isArray(t?.additionalInterfaces)?t.additionalInterfaces.map(e=>Le.fromJSON(e)):globalThis.Array.isArray(t?.additional_interfaces)?t.additional_interfaces.map(e=>Le.fromJSON(e)):[],provider:l(t.provider)?ki.fromJSON(t.provider):void 0,version:l(t.version)?globalThis.String(t.version):"",documentationUrl:l(t.documentationUrl)?globalThis.String(t.documentationUrl):l(t.documentation_url)?globalThis.String(t.documentation_url):"",capabilities:l(t.capabilities)?Ai.fromJSON(t.capabilities):void 0,securitySchemes:x(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=$e.fromJSON(i),e),{}):x(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=$e.fromJSON(i),e),{}):{},security:globalThis.Array.isArray(t?.security)?t.security.map(e=>ne.fromJSON(e)):[],defaultInputModes:globalThis.Array.isArray(t?.defaultInputModes)?t.defaultInputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.default_input_modes)?t.default_input_modes.map(e=>globalThis.String(e)):[],defaultOutputModes:globalThis.Array.isArray(t?.defaultOutputModes)?t.defaultOutputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.default_output_modes)?t.default_output_modes.map(e=>globalThis.String(e)):[],skills:globalThis.Array.isArray(t?.skills)?t.skills.map(e=>Ci.fromJSON(e)):[],supportsAuthenticatedExtendedCard:l(t.supportsAuthenticatedExtendedCard)?globalThis.Boolean(t.supportsAuthenticatedExtendedCard):l(t.supports_authenticated_extended_card)?globalThis.Boolean(t.supports_authenticated_extended_card):!1,signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>Ri.fromJSON(e)):[]}},toJSON(t){let e={};if(t.protocolVersion!==""&&(e.protocolVersion=t.protocolVersion),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.url!==""&&(e.url=t.url),t.preferredTransport!==""&&(e.preferredTransport=t.preferredTransport),t.additionalInterfaces?.length&&(e.additionalInterfaces=t.additionalInterfaces.map(r=>Le.toJSON(r))),t.provider!==void 0&&(e.provider=ki.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==""&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=Ai.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);r.length>0&&(e.securitySchemes={},r.forEach(([i,a])=>{e.securitySchemes[i]=$e.toJSON(a)}))}return t.security?.length&&(e.security=t.security.map(r=>ne.toJSON(r))),t.defaultInputModes?.length&&(e.defaultInputModes=t.defaultInputModes),t.defaultOutputModes?.length&&(e.defaultOutputModes=t.defaultOutputModes),t.skills?.length&&(e.skills=t.skills.map(r=>Ci.toJSON(r))),t.supportsAuthenticatedExtendedCard!==!1&&(e.supportsAuthenticatedExtendedCard=t.supportsAuthenticatedExtendedCard),t.signatures?.length&&(e.signatures=t.signatures.map(r=>Ri.toJSON(r))),e}},ki={fromJSON(t){return{url:l(t.url)?globalThis.String(t.url):"",organization:l(t.organization)?globalThis.String(t.organization):""}},toJSON(t){let e={};return t.url!==""&&(e.url=t.url),t.organization!==""&&(e.organization=t.organization),e}},Ai={fromJSON(t){return{streaming:l(t.streaming)?globalThis.Boolean(t.streaming):!1,pushNotifications:l(t.pushNotifications)?globalThis.Boolean(t.pushNotifications):l(t.push_notifications)?globalThis.Boolean(t.push_notifications):!1,extensions:globalThis.Array.isArray(t?.extensions)?t.extensions.map(e=>Ii.fromJSON(e)):[]}},toJSON(t){let e={};return t.streaming!==!1&&(e.streaming=t.streaming),t.pushNotifications!==!1&&(e.pushNotifications=t.pushNotifications),t.extensions?.length&&(e.extensions=t.extensions.map(r=>Ii.toJSON(r))),e}},Ii={fromJSON(t){return{uri:l(t.uri)?globalThis.String(t.uri):"",description:l(t.description)?globalThis.String(t.description):"",required:l(t.required)?globalThis.Boolean(t.required):!1,params:x(t.params)?t.params:void 0}},toJSON(t){let e={};return t.uri!==""&&(e.uri=t.uri),t.description!==""&&(e.description=t.description),t.required!==!1&&(e.required=t.required),t.params!==void 0&&(e.params=t.params),e}},Ci={fromJSON(t){return{id:l(t.id)?globalThis.String(t.id):"",name:l(t.name)?globalThis.String(t.name):"",description:l(t.description)?globalThis.String(t.description):"",tags:globalThis.Array.isArray(t?.tags)?t.tags.map(e=>globalThis.String(e)):[],examples:globalThis.Array.isArray(t?.examples)?t.examples.map(e=>globalThis.String(e)):[],inputModes:globalThis.Array.isArray(t?.inputModes)?t.inputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.input_modes)?t.input_modes.map(e=>globalThis.String(e)):[],outputModes:globalThis.Array.isArray(t?.outputModes)?t.outputModes.map(e=>globalThis.String(e)):globalThis.Array.isArray(t?.output_modes)?t.output_modes.map(e=>globalThis.String(e)):[],security:globalThis.Array.isArray(t?.security)?t.security.map(e=>ne.fromJSON(e)):[]}},toJSON(t){let e={};return t.id!==""&&(e.id=t.id),t.name!==""&&(e.name=t.name),t.description!==""&&(e.description=t.description),t.tags?.length&&(e.tags=t.tags),t.examples?.length&&(e.examples=t.examples),t.inputModes?.length&&(e.inputModes=t.inputModes),t.outputModes?.length&&(e.outputModes=t.outputModes),t.security?.length&&(e.security=t.security.map(r=>ne.toJSON(r))),e}},Ri={fromJSON(t){return{protected:l(t.protected)?globalThis.String(t.protected):"",signature:l(t.signature)?globalThis.String(t.signature):"",header:x(t.header)?t.header:void 0}},toJSON(t){let e={};return t.protected!==""&&(e.protected=t.protected),t.signature!==""&&(e.signature=t.signature),t.header!==void 0&&(e.header=t.header),e}},ae={fromJSON(t){return{name:l(t.name)?globalThis.String(t.name):"",pushNotificationConfig:l(t.pushNotificationConfig)?vt.fromJSON(t.pushNotificationConfig):l(t.push_notification_config)?vt.fromJSON(t.push_notification_config):void 0}},toJSON(t){let e={};return t.name!==""&&(e.name=t.name),t.pushNotificationConfig!==void 0&&(e.pushNotificationConfig=vt.toJSON(t.pushNotificationConfig)),e}},Ui={fromJSON(t){return{list:globalThis.Array.isArray(t?.list)?t.list.map(e=>globalThis.String(e)):[]}},toJSON(t){let e={};return t.list?.length&&(e.list=t.list),e}},ne={fromJSON(t){return{schemes:x(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=Ui.fromJSON(i),e),{}):{}}},toJSON(t){let e={};if(t.schemes){let r=globalThis.Object.entries(t.schemes);r.length>0&&(e.schemes={},r.forEach(([i,a])=>{e.schemes[i]=Ui.toJSON(a)}))}return e}},$e={fromJSON(t){return{scheme:l(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:ze.fromJSON(t.apiKeySecurityScheme)}:l(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:ze.fromJSON(t.api_key_security_scheme)}:l(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:qe.fromJSON(t.httpAuthSecurityScheme)}:l(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:qe.fromJSON(t.http_auth_security_scheme)}:l(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:Fe.fromJSON(t.oauth2SecurityScheme)}:l(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:Fe.fromJSON(t.oauth2_security_scheme)}:l(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:Be.fromJSON(t.openIdConnectSecurityScheme)}:l(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:Be.fromJSON(t.open_id_connect_security_scheme)}:l(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:He.fromJSON(t.mtlsSecurityScheme)}:l(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:He.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=ze.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=qe.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=Fe.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=Be.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=He.toJSON(t.scheme.value)),e}},ze={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):"",location:l(t.location)?globalThis.String(t.location):"",name:l(t.name)?globalThis.String(t.name):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.location!==""&&(e.location=t.location),t.name!==""&&(e.name=t.name),e}},qe={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):"",scheme:l(t.scheme)?globalThis.String(t.scheme):"",bearerFormat:l(t.bearerFormat)?globalThis.String(t.bearerFormat):l(t.bearer_format)?globalThis.String(t.bearer_format):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.scheme!==""&&(e.scheme=t.scheme),t.bearerFormat!==""&&(e.bearerFormat=t.bearerFormat),e}},Fe={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):"",flows:l(t.flows)?Ji.fromJSON(t.flows):void 0,oauth2MetadataUrl:l(t.oauth2MetadataUrl)?globalThis.String(t.oauth2MetadataUrl):l(t.oauth2_metadata_url)?globalThis.String(t.oauth2_metadata_url):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.flows!==void 0&&(e.flows=Ji.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},Be={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):"",openIdConnectUrl:l(t.openIdConnectUrl)?globalThis.String(t.openIdConnectUrl):l(t.open_id_connect_url)?globalThis.String(t.open_id_connect_url):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),t.openIdConnectUrl!==""&&(e.openIdConnectUrl=t.openIdConnectUrl),e}},He={fromJSON(t){return{description:l(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},Ji={fromJSON(t){return{flow:l(t.authorizationCode)?{$case:"authorizationCode",value:Ke.fromJSON(t.authorizationCode)}:l(t.authorization_code)?{$case:"authorizationCode",value:Ke.fromJSON(t.authorization_code)}:l(t.clientCredentials)?{$case:"clientCredentials",value:Ve.fromJSON(t.clientCredentials)}:l(t.client_credentials)?{$case:"clientCredentials",value:Ve.fromJSON(t.client_credentials)}:l(t.implicit)?{$case:"implicit",value:wi.fromJSON(t.implicit)}:l(t.password)?{$case:"password",value:xi.fromJSON(t.password)}:void 0}},toJSON(t){let e={};return t.flow?.$case==="authorizationCode"?e.authorizationCode=Ke.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=Ve.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=wi.toJSON(t.flow.value):t.flow?.$case==="password"&&(e.password=xi.toJSON(t.flow.value)),e}},Ke={fromJSON(t){return{authorizationUrl:l(t.authorizationUrl)?globalThis.String(t.authorizationUrl):l(t.authorization_url)?globalThis.String(t.authorization_url):"",tokenUrl:l(t.tokenUrl)?globalThis.String(t.tokenUrl):l(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:l(t.refreshUrl)?globalThis.String(t.refreshUrl):l(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:x(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.authorizationUrl!==""&&(e.authorizationUrl=t.authorizationUrl),t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},Ve={fromJSON(t){return{tokenUrl:l(t.tokenUrl)?globalThis.String(t.tokenUrl):l(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:l(t.refreshUrl)?globalThis.String(t.refreshUrl):l(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:x(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},wi={fromJSON(t){return{authorizationUrl:l(t.authorizationUrl)?globalThis.String(t.authorizationUrl):l(t.authorization_url)?globalThis.String(t.authorization_url):"",refreshUrl:l(t.refreshUrl)?globalThis.String(t.refreshUrl):l(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:x(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.authorizationUrl!==""&&(e.authorizationUrl=t.authorizationUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},xi={fromJSON(t){return{tokenUrl:l(t.tokenUrl)?globalThis.String(t.tokenUrl):l(t.token_url)?globalThis.String(t.token_url):"",refreshUrl:l(t.refreshUrl)?globalThis.String(t.refreshUrl):l(t.refresh_url)?globalThis.String(t.refresh_url):"",scopes:x(t.scopes)?globalThis.Object.entries(t.scopes).reduce((e,[r,i])=>(e[r]=globalThis.String(i),e),{}):{}}},toJSON(t){let e={};if(t.tokenUrl!==""&&(e.tokenUrl=t.tokenUrl),t.refreshUrl!==""&&(e.refreshUrl=t.refreshUrl),t.scopes){let r=globalThis.Object.entries(t.scopes);r.length>0&&(e.scopes={},r.forEach(([i,a])=>{e.scopes[i]=a}))}return e}},Ao={fromJSON(t){return{request:l(t.message)?z.fromJSON(t.message):l(t.request)?z.fromJSON(t.request):void 0,configuration:l(t.configuration)?vi.fromJSON(t.configuration):void 0,metadata:x(t.metadata)?t.metadata:void 0}},toJSON(t){let e={};return t.request!==void 0&&(e.message=z.toJSON(t.request)),t.configuration!==void 0&&(e.configuration=vi.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Io={fromJSON(t){return{payload:l(t.task)?{$case:"task",value:wt.fromJSON(t.task)}:l(t.message)?{$case:"msg",value:z.fromJSON(t.message)}:l(t.msg)?{$case:"msg",value:z.fromJSON(t.msg)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=wt.toJSON(t.payload.value):t.payload?.$case==="msg"&&(e.message=z.toJSON(t.payload.value)),e}},Co={fromJSON(t){return{payload:l(t.task)?{$case:"task",value:wt.fromJSON(t.task)}:l(t.message)?{$case:"msg",value:z.fromJSON(t.message)}:l(t.msg)?{$case:"msg",value:z.fromJSON(t.msg)}:l(t.statusUpdate)?{$case:"statusUpdate",value:De.fromJSON(t.statusUpdate)}:l(t.status_update)?{$case:"statusUpdate",value:De.fromJSON(t.status_update)}:l(t.artifactUpdate)?{$case:"artifactUpdate",value:Me.fromJSON(t.artifactUpdate)}:l(t.artifact_update)?{$case:"artifactUpdate",value:Me.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=wt.toJSON(t.payload.value):t.payload?.$case==="msg"?e.message=z.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=De.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=Me.toJSON(t.payload.value)),e}},Ro={fromJSON(t){return{configs:globalThis.Array.isArray(t?.configs)?t.configs.map(e=>ae.fromJSON(e)):[],nextPageToken:l(t.nextPageToken)?globalThis.String(t.nextPageToken):l(t.next_page_token)?globalThis.String(t.next_page_token):""}},toJSON(t){let e={};return t.configs?.length&&(e.configs=t.configs.map(r=>ae.toJSON(r))),t.nextPageToken!==""&&(e.nextPageToken=t.nextPageToken),e}};function Pi(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Uo(t){return globalThis.Buffer.from(t).toString("base64")}function x(t){return typeof t=="object"&&t!==null}function l(t){return t!=null}var Jo=/^tasks\/([^/]+)\/pushNotificationConfigs\/([^/]+)$/,wo=/^tasks\/([^/]+)(?:\/|$)/,Ct=t=>{let e=t.match(wo);if(!e)throw S.invalidParams(`Invalid or missing task ID in: "${t}"`);return e[1]},Rt=t=>`tasks/${t}`,Di=t=>{let e=t.match(Jo);if(!e)throw S.invalidParams(`Invalid or missing config ID in: "${t}"`);return{taskId:e[1],configId:e[2]}},Ge=(t,e)=>`tasks/${t}/pushNotificationConfigs/${e}`,Mi=class A{static taskQueryParams(e){return{id:Ct(e.name),historyLength:e.historyLength}}static taskIdParams(e){return{id:Ct(e.name)}}static getTaskPushNotificationConfigParams(e){let{taskId:r,configId:i}=Di(e.name);return{id:r,pushNotificationConfigId:i}}static listTaskPushNotificationConfigParams(e){return{id:Ct(e.parent)}}static createTaskPushNotificationConfig(e){if(!e.config?.pushNotificationConfig)throw S.invalidParams("Request must include a `config` object with a `pushNotificationConfig`");return{taskId:Ct(e.parent),pushNotificationConfig:A.pushNotificationConfig(e.config.pushNotificationConfig)}}static deleteTaskPushNotificationConfigParams(e){let{taskId:r,configId:i}=Di(e.name);return{id:r,pushNotificationConfigId:i}}static message(e){if(e)return{kind:"message",messageId:e.messageId,parts:e.content.map(r=>A.part(r)),contextId:e.contextId||void 0,taskId:e.taskId||void 0,role:A.role(e.role),metadata:e.metadata,extensions:e.extensions}}static role(e){switch(e){case 2:return"agent";case 1:return"user";default:throw S.invalidParams(`Invalid role: ${e}`)}}static messageSendConfiguration(e){if(e)return{blocking:e.blocking,acceptedOutputModes:e.acceptedOutputModes,pushNotificationConfig:A.pushNotificationConfig(e.pushNotification)}}static pushNotificationConfig(e){if(e)return{id:e.id,url:e.url,token:e.token||void 0,authentication:A.pushNotificationAuthenticationInfo(e.authentication)}}static pushNotificationAuthenticationInfo(e){if(e)return{schemes:e.schemes,credentials:e.credentials}}static part(e){if(e.part?.$case==="text")return{kind:"text",text:e.part.value};if(e.part?.$case==="file"){let r=e.part.value;if(r.file?.$case==="fileWithUri")return{kind:"file",file:{uri:r.file.value,mimeType:r.mimeType}};if(r.file?.$case==="fileWithBytes")return{kind:"file",file:{bytes:Buffer.from(r.file.value).toString("base64"),mimeType:r.mimeType}};throw S.invalidParams("Invalid file part type")}if(e.part?.$case==="data")return{kind:"data",data:e.part.value.data??{}};throw S.invalidParams("Invalid part type")}static messageSendParams(e){if(!e.request)throw S.invalidParams("SendMessageRequest missing message");return{message:A.message(e.request),configuration:A.messageSendConfiguration(e.configuration),metadata:e.metadata}}static sendMessageResult(e){if(e.payload?.$case==="task")return A.task(e.payload.value);if(e.payload?.$case==="msg")return A.message(e.payload.value);throw S.invalidParams("Invalid SendMessageResponse: missing result")}static task(e){if(!e.status)throw S.internalError("Task missing status");return{kind:"task",id:e.id,status:A.taskStatus(e.status),contextId:e.contextId,artifacts:e.artifacts?.map(r=>A.artifact(r)),history:e.history?.map(r=>A.message(r)),metadata:e.metadata}}static taskStatus(e){return{message:A.message(e.update),state:A.taskState(e.state),timestamp:e.timestamp}}static taskState(e){switch(e){case 1:return"submitted";case 2:return"working";case 6:return"input-required";case 3:return"completed";case 5:return"canceled";case 4:return"failed";case 7:return"rejected";case 8:return"auth-required";case 0:return"unknown";default:throw S.invalidParams(`Invalid task state: ${e}`)}}static artifact(e){return{artifactId:e.artifactId,name:e.name||void 0,description:e.description||void 0,parts:e.parts.map(r=>A.part(r)),metadata:e.metadata}}static taskPushNotificationConfig(e){if(!e.pushNotificationConfig)throw S.invalidParams("TaskPushNotificationConfig missing pushNotificationConfig");return{taskId:Ct(e.name),pushNotificationConfig:A.pushNotificationConfig(e.pushNotificationConfig)}}static listTaskPushNotificationConfig(e){return e.configs.map(r=>A.taskPushNotificationConfig(r))}static agentCard(e){return{additionalInterfaces:e.additionalInterfaces?.map(r=>A.agentInterface(r)),capabilities:e.capabilities?A.agentCapabilities(e.capabilities):{},defaultInputModes:e.defaultInputModes,defaultOutputModes:e.defaultOutputModes,description:e.description,documentationUrl:e.documentationUrl||void 0,name:e.name,preferredTransport:e.preferredTransport,provider:e.provider?A.agentProvider(e.provider):void 0,protocolVersion:e.protocolVersion,security:e.security?.map(r=>A.security(r)),securitySchemes:e.securitySchemes?Object.fromEntries(Object.entries(e.securitySchemes).map(([r,i])=>[r,A.securityScheme(i)])):{},skills:e.skills.map(r=>A.skills(r)),signatures:e.signatures?.map(r=>A.agentCardSignature(r)),supportsAuthenticatedExtendedCard:e.supportsAuthenticatedExtendedCard,url:e.url,version:e.version}}static agentCapabilities(e){return{extensions:e.extensions?.map(r=>A.agentExtension(r)),pushNotifications:e.pushNotifications,streaming:e.streaming}}static agentExtension(e){return{uri:e.uri,description:e.description||void 0,required:e.required,params:e.params}}static agentInterface(e){return{transport:e.transport,url:e.url}}static agentProvider(e){return{organization:e.organization,url:e.url}}static security(e){return Object.fromEntries(Object.entries(e.schemes)?.map(([r,i])=>[r,i.list]))}static securityScheme(e){switch(e.scheme?.$case){case"apiKeySecurityScheme":return{type:"apiKey",name:e.scheme.value.name,in:e.scheme.value.location,description:e.scheme.value.description||void 0};case"httpAuthSecurityScheme":return{type:"http",scheme:e.scheme.value.scheme,bearerFormat:e.scheme.value.bearerFormat||void 0,description:e.scheme.value.description||void 0};case"mtlsSecurityScheme":return{type:"mutualTLS",description:e.scheme.value.description||void 0};case"oauth2SecurityScheme":if(!e.scheme.value.flows)throw S.internalError("OAuth2 security scheme missing flows");return{type:"oauth2",description:e.scheme.value.description||void 0,flows:A.oauthFlows(e.scheme.value.flows),oauth2MetadataUrl:e.scheme.value.oauth2MetadataUrl||void 0};case"openIdConnectSecurityScheme":return{type:"openIdConnect",description:e.scheme.value.description||void 0,openIdConnectUrl:e.scheme.value.openIdConnectUrl};default:throw S.internalError("Unsupported security scheme type")}}static oauthFlows(e){switch(e.flow?.$case){case"implicit":return{implicit:{authorizationUrl:e.flow.value.authorizationUrl,scopes:e.flow.value.scopes,refreshUrl:e.flow.value.refreshUrl||void 0}};case"password":return{password:{refreshUrl:e.flow.value.refreshUrl||void 0,scopes:e.flow.value.scopes,tokenUrl:e.flow.value.tokenUrl}};case"authorizationCode":return{authorizationCode:{refreshUrl:e.flow.value.refreshUrl||void 0,authorizationUrl:e.flow.value.authorizationUrl,scopes:e.flow.value.scopes,tokenUrl:e.flow.value.tokenUrl}};case"clientCredentials":return{clientCredentials:{refreshUrl:e.flow.value.refreshUrl||void 0,scopes:e.flow.value.scopes,tokenUrl:e.flow.value.tokenUrl}};default:throw S.internalError("Unsupported OAuth flows")}}static skills(e){return{id:e.id,name:e.name,description:e.description,tags:e.tags,examples:e.examples,inputModes:e.inputModes,outputModes:e.outputModes,security:e.security?.map(r=>A.security(r))}}static agentCardSignature(e){return{protected:e.protected,signature:e.signature,header:e.header}}static taskStatusUpdateEvent(e){if(!e.status)throw S.invalidParams("Invalid TaskStatusUpdateEvent: missing status");return{kind:"status-update",taskId:e.taskId,status:A.taskStatus(e.status),contextId:e.contextId,metadata:e.metadata,final:e.final}}static taskArtifactUpdateEvent(e){if(!e.artifact)throw S.invalidParams("Invalid TaskArtifactUpdateEvent: missing artifact");return{kind:"artifact-update",taskId:e.taskId,artifact:A.artifact(e.artifact),contextId:e.contextId,metadata:e.metadata,lastChunk:e.lastChunk}}static messageStreamResult(e){switch(e.payload?.$case){case"msg":return A.message(e.payload.value);case"task":return A.task(e.payload.value);case"statusUpdate":return A.taskStatusUpdateEvent(e.payload.value);case"artifactUpdate":return A.taskArtifactUpdateEvent(e.payload.value);default:throw S.internalError("Invalid event type in StreamResponse")}}},St=class I{static agentCard(e){return{protocolVersion:e.protocolVersion,name:e.name,description:e.description,url:e.url,preferredTransport:e.preferredTransport??"",additionalInterfaces:e.additionalInterfaces?.map(r=>I.agentInterface(r))??[],provider:I.agentProvider(e.provider),version:e.version,documentationUrl:e.documentationUrl??"",capabilities:I.agentCapabilities(e.capabilities),securitySchemes:e.securitySchemes?Object.fromEntries(Object.entries(e.securitySchemes).map(([r,i])=>[r,I.securityScheme(i)])):{},security:e.security?.map(r=>I.security(r))??[],defaultInputModes:e.defaultInputModes,defaultOutputModes:e.defaultOutputModes,skills:e.skills.map(r=>I.agentSkill(r)),supportsAuthenticatedExtendedCard:e.supportsAuthenticatedExtendedCard??!1,signatures:e.signatures?.map(r=>I.agentCardSignature(r))??[]}}static agentCardSignature(e){return{protected:e.protected,signature:e.signature,header:e.header}}static agentSkill(e){return{id:e.id,name:e.name,description:e.description,tags:e.tags??[],examples:e.examples??[],inputModes:e.inputModes??[],outputModes:e.outputModes??[],security:e.security?e.security.map(r=>I.security(r)):[]}}static security(e){return{schemes:Object.fromEntries(Object.entries(e).map(([r,i])=>[r,{list:i}]))}}static securityScheme(e){switch(e.type){case"apiKey":return{scheme:{$case:"apiKeySecurityScheme",value:{name:e.name,location:e.in,description:e.description??""}}};case"http":return{scheme:{$case:"httpAuthSecurityScheme",value:{description:e.description??"",scheme:e.scheme,bearerFormat:e.bearerFormat??""}}};case"mutualTLS":return{scheme:{$case:"mtlsSecurityScheme",value:{description:e.description??""}}};case"oauth2":return{scheme:{$case:"oauth2SecurityScheme",value:{description:e.description??"",flows:I.oauthFlows(e.flows),oauth2MetadataUrl:e.oauth2MetadataUrl??""}}};case"openIdConnect":return{scheme:{$case:"openIdConnectSecurityScheme",value:{description:e.description??"",openIdConnectUrl:e.openIdConnectUrl}}};default:throw S.internalError("Unsupported security scheme type")}}static oauthFlows(e){if(e.implicit)return{flow:{$case:"implicit",value:{authorizationUrl:e.implicit.authorizationUrl,scopes:e.implicit.scopes,refreshUrl:e.implicit.refreshUrl??""}}};if(e.password)return{flow:{$case:"password",value:{tokenUrl:e.password.tokenUrl,scopes:e.password.scopes,refreshUrl:e.password.refreshUrl??""}}};if(e.clientCredentials)return{flow:{$case:"clientCredentials",value:{tokenUrl:e.clientCredentials.tokenUrl,scopes:e.clientCredentials.scopes,refreshUrl:e.clientCredentials.refreshUrl??""}}};if(e.authorizationCode)return{flow:{$case:"authorizationCode",value:{authorizationUrl:e.authorizationCode.authorizationUrl,tokenUrl:e.authorizationCode.tokenUrl,scopes:e.authorizationCode.scopes,refreshUrl:e.authorizationCode.refreshUrl??""}}};throw S.internalError("Unsupported OAuth flows")}static agentInterface(e){return{transport:e.transport,url:e.url}}static agentProvider(e){if(e)return{url:e.url,organization:e.organization}}static agentCapabilities(e){return e?{streaming:e.streaming??!1,pushNotifications:e.pushNotifications??!1,extensions:e.extensions?e.extensions.map(r=>I.agentExtension(r)):[]}:{streaming:!1,pushNotifications:!1,extensions:[]}}static agentExtension(e){return{uri:e.uri,description:e.description??"",required:e.required??!1,params:e.params}}static listTaskPushNotificationConfig(e){return{configs:e.map(r=>I.taskPushNotificationConfig(r)),nextPageToken:""}}static getTaskPushNotificationConfigParams(e){return{name:Ge(e.id,e.pushNotificationConfigId??"")}}static listTaskPushNotificationConfigParams(e){return{parent:Rt(e.id),pageToken:"",pageSize:0}}static deleteTaskPushNotificationConfigParams(e){return{name:Ge(e.id,e.pushNotificationConfigId)}}static taskPushNotificationConfig(e){return{name:Ge(e.taskId,e.pushNotificationConfig.id??""),pushNotificationConfig:I.pushNotificationConfig(e.pushNotificationConfig)}}static taskPushNotificationConfigCreate(e){return{parent:Rt(e.taskId),config:I.taskPushNotificationConfig(e),configId:e.pushNotificationConfig.id??""}}static pushNotificationConfig(e){if(e)return{id:e.id??"",url:e.url,token:e.token??"",authentication:I.pushNotificationAuthenticationInfo(e.authentication)}}static pushNotificationAuthenticationInfo(e){if(e)return{schemes:e.schemes,credentials:e.credentials??""}}static messageStreamResult(e){if(e.kind==="message")return{payload:{$case:"msg",value:I.message(e)}};if(e.kind==="task")return{payload:{$case:"task",value:I.task(e)}};if(e.kind==="status-update")return{payload:{$case:"statusUpdate",value:I.taskStatusUpdateEvent(e)}};if(e.kind==="artifact-update")return{payload:{$case:"artifactUpdate",value:I.taskArtifactUpdateEvent(e)}};throw S.internalError("Invalid event type")}static taskStatusUpdateEvent(e){return{taskId:e.taskId,status:I.taskStatus(e.status),contextId:e.contextId,metadata:e.metadata,final:e.final}}static taskArtifactUpdateEvent(e){return{taskId:e.taskId,artifact:I.artifact(e.artifact),contextId:e.contextId,metadata:e.metadata,append:e.append??!1,lastChunk:e.lastChunk??!1}}static messageSendResult(e){if(e.kind){if(e.kind==="message")return{payload:{$case:"msg",value:I.message(e)}};if(e.kind==="task")return{payload:{$case:"task",value:I.task(e)}}}}static message(e){if(e)return{messageId:e.messageId,content:e.parts.map(r=>I.part(r)),contextId:e.contextId??"",taskId:e.taskId??"",role:I.role(e.role),metadata:e.metadata,extensions:e.extensions??[]}}static role(e){switch(e){case"agent":return 2;case"user":return 1;default:throw S.internalError("Invalid role")}}static task(e){return{id:e.id,contextId:e.contextId,status:I.taskStatus(e.status),artifacts:e.artifacts?.map(r=>I.artifact(r))??[],history:e.history?.map(r=>I.message(r)).filter(r=>!!r)??[],metadata:e.metadata}}static taskStatus(e){return{state:I.taskState(e.state),update:I.message(e.message),timestamp:e.timestamp}}static artifact(e){return{artifactId:e.artifactId,name:e.name??"",description:e.description??"",parts:e.parts.map(r=>I.part(r)),metadata:e.metadata,extensions:e.extensions?e.extensions:[]}}static taskState(e){switch(e){case"submitted":return 1;case"working":return 2;case"input-required":return 6;case"rejected":return 7;case"auth-required":return 8;case"completed":return 3;case"failed":return 4;case"canceled":return 5;case"unknown":return 0;default:return-1}}static part(e){if(e.kind==="text")return{part:{$case:"text",value:e.text}};if(e.kind==="file"){let r;if("uri"in e.file)r={file:{$case:"fileWithUri",value:e.file.uri},mimeType:e.file.mimeType??""};else if("bytes"in e.file)r={file:{$case:"fileWithBytes",value:Buffer.from(e.file.bytes,"base64")},mimeType:e.file.mimeType??""};else throw S.internalError("Invalid file part");return{part:{$case:"file",value:r}}}if(e.kind==="data")return{part:{$case:"data",value:{data:e.data}}};throw S.internalError("Invalid part type")}static messageSendParams(e){return{request:I.message(e.message),configuration:I.configuration(e.configuration),metadata:e.metadata}}static configuration(e){if(e)return{blocking:e.blocking??!1,acceptedOutputModes:e.acceptedOutputModes??[],pushNotification:I.pushNotificationConfig(e.pushNotificationConfig),historyLength:e.historyLength??0}}static taskQueryParams(e){return{name:Rt(e.id),historyLength:e.historyLength??0}}static cancelTaskRequest(e){return{name:Rt(e.id)}}static taskIdParams(e){return{name:Rt(e.id)}}static getAgentCardRequest(){return{}}},xo=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t)return r.status(v.BAD_REQUEST).json(Et(S.parseError("Invalid JSON payload.")));i(t)};function Po(t){let e=er.default.Router(),r=new ho(t.requestHandler);e.use((c,E,m)=>{let k=c.header(rt)||Ot;pr(k)?m():m("router")}),e.use((c,E,m)=>{E.setHeader("Content-Type",Jt),m()},er.default.json({type:Jt,strict:!1}),xo);let i=async c=>{let E=await t.userBuilder(c),m=c.header(rt)||Ot,D=(t.contextBuilder??cr)({extensions:se.parseServiceParameter(c.header(te)??c.header(gt)),user:E,headers:c.headers,requestedVersion:m,tenant:c.params.tenant||void 0}),B=await r.getAgentCard();return hr(D.requestedVersion,B,"HTTP+JSON"),D},a=(c,E)=>{E.activatedExtensions&&c.setHeader(te,Array.from(E.activatedExtensions))},n=(c,E,m,k)=>{a(c,m),c.status(E),E===v.NO_CONTENT?c.end():c.json(k)},o=c=>{let E=St.messageSendResult(c);if(!E)throw S.internalError("sendMessage produced no result.");return Io.toJSON(E)},d=c=>wt.toJSON(St.task(c)),f=c=>ae.toJSON(St.taskPushNotificationConfig(c)),T=c=>ko.toJSON(St.agentCard(c)),p=c=>Ro.toJSON({configs:c.map(E=>St.taskPushNotificationConfig(E)),nextPageToken:""}),O=c=>{let E=Ao.fromJSON(c??{});return Mi.messageSendParams(E)},u=c=>{let E=ae.fromJSON(c??{});return Mi.taskPushNotificationConfig(E)},N=c=>{let E=St.messageStreamResult(c);if(!E)throw S.internalError("Stream produced an unrepresentable event.");return Co.toJSON(E)},h=async(c,E,m)=>{let k=E[Symbol.asyncIterator](),D;try{D=await k.next()}catch(B){a(c,m);let ue=Ni(B);c.status(ue).json(Et(B));return}Object.entries(Zt).forEach(([B,ue])=>{c.setHeader(B,ue)}),a(c,m),c.flushHeaders();try{D.done||c.write(dt(N(D.value)));for await(let B of ar(k))c.write(dt(N(B)))}catch(B){console.error("Legacy SSE streaming error:",B),c.writableEnded||c.write(bt(Et(B)))}finally{c.writableEnded||c.end()}},g=(c,E)=>{if(c.headersSent){c.writableEnded||c.end();return}let m=Ni(E);c.status(m).json(Et(E))},_=c=>async(E,m)=>{try{await c(E,m)}catch(k){g(m,k)}};e.get("/v1/card",_(async(c,E)=>{let m=await i(c),k=await r.getAuthenticatedExtendedAgentCard(m);n(E,v.OK,m,T(k))})),e.post("/v1/message\\:send",_(async(c,E)=>{let m=await i(c),k=O(c.body),D=await r.sendMessage(k,m);n(E,v.CREATED,m,o(D))})),e.post("/v1/message\\:stream",_(async(c,E)=>{let m=await i(c),k=O(c.body),D=await r.sendMessageStream(k,m);await h(E,D,m)})),e.post("/v1/tasks/:taskId\\:cancel",_(async(c,E)=>{let m=await i(c),k=await r.cancelTask(c.params.taskId,m);n(E,v.OK,m,d(k))}));let R=_(async(c,E)=>{let m=await i(c),k=await r.resubscribe(c.params.taskId,m);await h(E,k,m)});return e.get("/v1/tasks/:taskId\\:subscribe",R),e.post("/v1/tasks/:taskId\\:subscribe",R),e.get("/v1/tasks/:taskId",_(async(c,E)=>{let m=await i(c),k=c.query.historyLength??c.query.history_length,D=await r.getTask(c.params.taskId,m,k);n(E,v.OK,m,d(D))})),e.post("/v1/tasks/:taskId/pushNotificationConfigs",_(async(c,E)=>{let m=await i(c),k=u(c.body),D=await r.setTaskPushNotificationConfig(k,m);n(E,v.CREATED,m,f(D))})),e.get("/v1/tasks/:taskId/pushNotificationConfigs",_(async(c,E)=>{let m=await i(c),k=await r.listTaskPushNotificationConfigs(c.params.taskId,m);n(E,v.OK,m,p(k))})),e.get("/v1/tasks/:taskId/pushNotificationConfigs/:configId",_(async(c,E)=>{let m=await i(c),k=await r.getTaskPushNotificationConfig(c.params.taskId,c.params.configId,m);n(E,v.OK,m,f(k))})),e.delete("/v1/tasks/:taskId/pushNotificationConfigs/:configId",_(async(c,E)=>{let m=await i(c);await r.deleteTaskPushNotificationConfig(c.params.taskId,c.params.configId,m),n(E,v.NO_CONTENT,m)})),e}function Do(t){return`W/"${go.createHash("sha256").update(t).digest("hex").slice(0,16)}"`}function va(t){let e=Na.default.Router(),r=t.cache?.maxAge??3600,i=typeof t.agentCardProvider=="function"?t.agentCardProvider:t.agentCardProvider.getAgentCard.bind(t.agentCardProvider);return t.legacyCompat?.enabled&&e.use(Eo(t)),e.get("/",async(a,n)=>{try{let o=await i(),d=JSON.stringify(o),f=Do(d);if(n.setHeader("ETag",f),t.legacyCompat?.enabled&&n.append("Vary",rt),r>0?n.setHeader("Cache-Control",`public, max-age=${r}`):n.setHeader("Cache-Control","no-cache"),a.fresh){n.status(304).end();return}n.setHeader("Content-Type","application/json"),n.status(200).send(d)}catch(o){console.error("Error fetching agent card:",o),n.status(500).json({error:"Failed to retrieve agent card"})}}),e}function Oa(t){return t==="true"||t===!0}var Mo=class ya{requestHandler;constructor(e){this.requestHandler=e}async getAgentCard(){return this.requestHandler.getAgentCard()}async getAuthenticatedExtendedAgentCard(e,r){return this.requestHandler.getAuthenticatedExtendedAgentCard(e,r)}validateSendMessageRequest(e){if(!e.message)throw new L("message is required");if(!e.message.messageId)throw new L("message.messageId is required")}async sendMessage(e,r){return this.validateSendMessageRequest(e),this.requestHandler.sendMessage(e,r)}async sendMessageStream(e,r){return this.validateSendMessageRequest(e),this.requestHandler.sendMessageStream(e,r)}async getTask(e,r,i,a){let n={id:e,tenant:a||""};return i!==void 0&&(n.historyLength=this.parseHistoryLength(i)),this.requestHandler.getTask(n,r)}async cancelTask(e,r,i){let a={id:e,tenant:i||"",metadata:{}};return this.requestHandler.cancelTask(a,r)}async listTasks(e,r){let i={tenant:e.tenant||"",contextId:e.contextId||"",status:e.status?nr(isNaN(Number(e.status))?e.status:Number(e.status)):0,pageSize:e.pageSize!==void 0&&e.pageSize!==""?this.parsePageSize(e.pageSize):void 0,pageToken:e.pageToken||"",historyLength:e.historyLength!==void 0&&e.historyLength!==""?this.parseHistoryLength(e.historyLength):void 0,statusTimestampAfter:e.statusTimestampAfter||void 0,includeArtifacts:Oa(e.includeArtifacts)};return this.requestHandler.listTasks(i,r)}async resubscribe(e,r,i){return this.requestHandler.resubscribe({id:e,tenant:i||""},r)}async createTaskPushNotificationConfig(e,r){return await this.requireCapability("pushNotifications"),this.requestHandler.createTaskPushNotificationConfig(e,r)}async listTaskPushNotificationConfigs(e,r,i){return await this.requestHandler.listTaskPushNotificationConfigs({taskId:e,pageSize:0,pageToken:"",tenant:i||""},r)}async getTaskPushNotificationConfig(e,r,i,a){return await this.requestHandler.getTaskPushNotificationConfig({taskId:e,id:r,tenant:a||""},i)}async deleteTaskPushNotificationConfig(e,r,i,a){await this.requestHandler.deleteTaskPushNotificationConfig({taskId:e,id:r,tenant:a||""},i)}static CAPABILITY_ERRORS={pushNotifications:()=>new or};async requireCapability(e){if(!(await this.getAgentCard()).capabilities?.[e])throw ya.CAPABILITY_ERRORS[e]()}parseHistoryLength(e){if(e==null)throw new L("historyLength is required");let r=parseInt(String(e),10);if(isNaN(r))throw new L("historyLength must be a valid integer");if(r<0)throw new L("historyLength must be non-negative");return r}parsePageSize(e){let r=parseInt(String(e),10);if(isNaN(r)||String(r)!==String(e).trim())throw new L("pageSize must be a valid integer");if(r<1||r>100)throw new L("pageSize must be between 1 and 100");return r}},Lo=class{static messageSendResult(t){if("messageId"in t)return{payload:{$case:"message",value:t}};if("artifacts"in t)return{payload:{$case:"task",value:t}};throw new W("Invalid SendMessageResult type")}},$o=(t,e,r,i)=>{if(t instanceof SyntaxError&&"body"in t)return r.status(400).json(Ut(new L("Invalid JSON payload."),400));i(t)},zo=(t,e,r)=>{let i=t.header("content-type");if(!i){r();return}let a=i.split(";",1)[0].trim().toLowerCase();if(a===sr||a===We){r();return}let n=new lr(`Unsupported Content-Type "${i}"; expected application/json or application/a2a+json.`);e.status(v.BAD_REQUEST).json(Ut(n,v.BAD_REQUEST))};function _a(t){let e=rr.default.Router(),r=new Mo(t.requestHandler);t.legacyCompat?.enabled&&e.use(Po(t)),e.use((u,N,h)=>{N.setHeader("Content-Type",We),h()},zo,rr.default.json({type:[sr,We],strict:!1}),$o);let i=async u=>{let N=await t.userBuilder(u),h=u.params.tenant||void 0,g=u.header(rt)||void 0,R=(t.contextBuilder??cr)({extensions:se.parseServiceParameter(u.header(gt)),user:N,headers:u.headers,requestedVersion:g,tenant:h}),c=await r.getAgentCard();return hr(R.requestedVersion,c,"HTTP+JSON"),R},a=(u,N)=>{N.activatedExtensions&&u.setHeader(gt,Array.from(N.activatedExtensions))},n=(u,N,h,g,_)=>{if(a(u,h),u.status(N),N===v.NO_CONTENT)u.end();else{if(!_||g===void 0)throw new Error("Bug: toJson serializer and body must be provided for non-204 responses.");u.json(_.toJSON(g))}},o=async(u,N,h)=>{let g=N[Symbol.asyncIterator](),_;try{_=await g.next()}catch(R){a(u,h);let c=Vt(R);u.status(c).json(Ut(R,c));return}Object.entries(Zt).forEach(([R,c])=>{u.setHeader(R,c)}),a(u,h),u.flushHeaders();try{if(!_.done){let R=Ye.toJSON(_.value);u.write(dt(R))}for await(let R of ar(g)){let c=Ye.toJSON(R);u.write(dt(c))}}catch(R){console.error("SSE streaming error:",R),u.writableEnded||u.write(bt(Ut(R,Vt(R))))}finally{u.writableEnded||u.end()}},d=(u,N)=>{if(u.headersSent){u.writableEnded||u.end();return}let h=Vt(N);u.status(h).json(Ut(N,h))},f=u=>async(N,h)=>{try{await u(N,h)}catch(g){d(h,g)}},T=(u,N,h)=>{let g=u.params.tenant;if(!g){h();return}let _=u.body?.tenant;_&&_!==g&&console.warn(`Tenant mismatch: URL path tenant "${g}" differs from request body tenant "${_}". Using path tenant as the canonical value.`);let R=u.query?.tenant;R&&R!==g&&console.warn(`Tenant mismatch: URL path tenant "${g}" differs from query param tenant "${R}". Using path tenant as the canonical value.`),u.body&&(u.body.tenant=g),u.query.tenant=g,h()},p=(u,N,h)=>{e[u](N,f(h)),e[u](`/:tenant${N}`,T,f(h))};p("get","/extendedAgentCard",async(u,N)=>{let h=await i(u),g=await r.getAuthenticatedExtendedAgentCard({tenant:u.query.tenant||""},h);n(N,v.OK,h,g,$i)}),p("post","/message\\:send",async(u,N)=>{let h=await i(u),g=Xt.fromJSON(u.body??{}),_=await r.sendMessage(g,h),R=Lo.messageSendResult(_);n(N,v.OK,h,R,Bn)}),p("post","/message\\:stream",async(u,N)=>{let h=await i(u),g=Xt.fromJSON(u.body??{}),_=await r.sendMessageStream(g,h);await o(N,_,h)});let O=async(u,N)=>{let h=await i(u),g=await r.resubscribe(u.params.taskId,h,u.query.tenant||"");await o(N,g,h)};return p("get","/tasks/:taskId\\:subscribe",O),p("post","/tasks/:taskId\\:subscribe",O),p("post","/tasks/:taskId\\:cancel",async(u,N)=>{let h=await i(u),g=await r.cancelTask(u.params.taskId,h,u.query.tenant||"");n(N,v.OK,h,g,G)}),p("get","/tasks/:taskId",async(u,N)=>{let h=await i(u),g=await r.getTask(u.params.taskId,h,u.query.historyLength,u.query.tenant||"");n(N,v.OK,h,g,G)}),p("get","/tasks",async(u,N)=>{let h=await i(u),g=await r.listTasks(u.query,h),_=Oa(u.query.includeArtifacts);n(N,v.OK,h,g,{...zi,toJSON:R=>Fi(R,{includeArtifacts:_})})}),p("post","/tasks/:taskId/pushNotificationConfigs",async(u,N)=>{let h=await i(u),g=Q.fromJSON({...u.body??{},taskId:u.params.taskId}),_=await r.createTaskPushNotificationConfig(g,h);n(N,v.CREATED,h,_,Q)}),p("get","/tasks/:taskId/pushNotificationConfigs",async(u,N)=>{let h=await i(u),g=await r.listTaskPushNotificationConfigs(u.params.taskId,h,u.query.tenant||"");n(N,v.OK,h,g,qi)}),p("get","/tasks/:taskId/pushNotificationConfigs/:configId",async(u,N)=>{let h=await i(u),g=await r.getTaskPushNotificationConfig(u.params.taskId,u.params.configId,h,u.query.tenant||"");n(N,v.OK,h,g,Q)}),p("delete","/tasks/:taskId/pushNotificationConfigs/:configId",async(u,N)=>{let h=await i(u);await r.deleteTaskPushNotificationConfig(u.params.taskId,u.params.configId,h,u.query.tenant||""),n(N,v.NO_CONTENT,h)}),e}var Ja=ft(ct(),1);var ka={};Lt(ka,{buildAgentCard:()=>gr});var qo="Yukino is a terminal-based AI coding agent. It reads, edits, and creates files, runs shell commands, and drives multi-step coding tasks from natural language instructions.",Fo="Executes software engineering tasks: answering questions about a codebase, writing and refactoring code, running commands, and fixing bugs.";function gr(t){return{name:"yukino",description:qo,supportedInterfaces:[{url:t,protocolBinding:"JSONRPC",protocolVersion:"1.0",tenant:""},{url:t,protocolBinding:"HTTP+JSON",protocolVersion:"1.0",tenant:""}],provider:void 0,version:Ar,capabilities:{streaming:!0,pushNotifications:!1,extensions:[]},securitySchemes:{},securityRequirements:[],defaultInputModes:["text/plain"],defaultOutputModes:["text/plain"],skills:[{id:"coding",name:"Coding",description:Fo,tags:["code","development","programming"],examples:["Fix the failing tests in this repository.","Add a dark mode toggle to the settings page."],inputModes:["text/plain"],outputModes:["text/plain"],securityRequirements:[]}],signatures:[]}}var Ua={};Lt(Ua,{DEFAULT_IDLE_TIMEOUT_MS:()=>Ra,YukinoA2aExecutor:()=>Mt,createA2aRuntime:()=>de});import{randomUUID as Yo}from"crypto";var F=(t=>(t[t.TASK_STATE_UNSPECIFIED=0]="TASK_STATE_UNSPECIFIED",t[t.TASK_STATE_SUBMITTED=1]="TASK_STATE_SUBMITTED",t[t.TASK_STATE_WORKING=2]="TASK_STATE_WORKING",t[t.TASK_STATE_COMPLETED=3]="TASK_STATE_COMPLETED",t[t.TASK_STATE_FAILED=4]="TASK_STATE_FAILED",t[t.TASK_STATE_CANCELED=5]="TASK_STATE_CANCELED",t[t.TASK_STATE_INPUT_REQUIRED=6]="TASK_STATE_INPUT_REQUIRED",t[t.TASK_STATE_REJECTED=7]="TASK_STATE_REJECTED",t[t.TASK_STATE_AUTH_REQUIRED=8]="TASK_STATE_AUTH_REQUIRED",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t))(F||{}),mr=(t=>(t[t.ROLE_UNSPECIFIED=0]="ROLE_UNSPECIFIED",t[t.ROLE_USER=1]="ROLE_USER",t[t.ROLE_AGENT=2]="ROLE_AGENT",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t))(mr||{});var Hl=4*1024*1024;var Ia={};Lt(Ia,{MAX_TOOL_OUTPUT_LENGTH:()=>Nr,PermissionRequestDataSchema:()=>Ho,PermissionResponseDataSchema:()=>Aa,ThinkingDataSchema:()=>Ko,ToolCallDataSchema:()=>Vo,ToolResultDataSchema:()=>Go,YUKINO_DATA_KEY:()=>_t,agentEventToMessage:()=>yr,agentMessage:()=>st,dataPart:()=>yt,findPermissionResponse:()=>Or,messageText:()=>vr,statusUpdate:()=>lt,taskSnapshot:()=>Dt,taskStatus:()=>Er,textPart:()=>kt});import{randomUUID as Bo}from"crypto";var _t="yukino",Ho=C.object({[_t]:C.literal("permission-request"),permissionId:C.string(),toolCallId:C.string(),toolName:C.string(),reason:C.string(),args:C.record(C.string(),C.unknown())}),Aa=C.object({[_t]:C.literal("permission-response"),permissionId:C.string(),decision:C.enum(["allow","deny","allowAlways"])}),Ko=C.object({[_t]:C.literal("thinking"),text:C.string()}),Vo=C.object({[_t]:C.literal("tool-call"),toolCallId:C.string(),toolName:C.string(),args:C.record(C.string(),C.unknown())}),Go=C.object({[_t]:C.literal("tool-result"),toolCallId:C.string(),toolName:C.string(),isError:C.boolean(),elapsed:C.number(),output:C.string()}),Nr=8e3;function kt(t){return{content:{$case:"text",value:t},metadata:void 0,filename:"",mediaType:"text/plain"}}function yt(t){return{content:{$case:"data",value:t},metadata:void 0,filename:"",mediaType:"application/json"}}function st(t,e,r){return{messageId:Bo(),contextId:e,taskId:t,role:mr.ROLE_AGENT,parts:r,metadata:void 0,extensions:[],referenceTaskIds:[]}}function Er(t,e){return{state:t,message:e,timestamp:new Date().toISOString()}}function lt(t,e,r,i){return{taskId:t,contextId:e,status:Er(r,i),metadata:void 0}}function Dt(t,e,r,i){return{id:t,contextId:e,status:Er(r,i),artifacts:[],history:[],metadata:void 0}}function vr(t){let e=[];for(let r of t.parts)r.content?.$case==="text"&&e.push(r.content.value);return e.join(`
|
|
10
|
+
|
|
11
|
+
`).trim()}function Qo(t){let e=[];for(let r of t.parts)r.content?.$case==="data"&&e.push(r.content.value);return e}function Or(t){for(let e of Qo(t)){let r=Aa.safeParse(e);if(r.success)return r.data}return null}function yr(t,e,r){switch(t.type){case"stream_text":return st(e,r,[kt(t.text)]);case"thinking_text":return st(e,r,[yt({yukino:"thinking",text:t.text})]);case"tool_use":return st(e,r,[yt({yukino:"tool-call",toolCallId:t.toolId,toolName:t.toolName,args:t.args})]);case"tool_result":{let a=t.output.length>Nr?`${t.output.slice(0,Nr)}
|
|
12
|
+
\u2026 [truncated]`:t.output;return st(e,r,[yt({yukino:"tool-result",toolCallId:t.toolId,toolName:t.toolName,isError:t.isError,elapsed:t.elapsed,output:a})])}default:return null}}async function de(t,e){let r=Ur(Jr(),t),i=Ir(r.providers,r.default_provider);if(!i)throw new Error("No provider configured.");let a=await Mr({interactionMode:"non-interactive",provider:i,cwd:t,hooks:r.hooks,mcpServers:r.mcp_servers,lspServers:r.lsp_servers,sandboxConfig:r.sandbox,enableCoordinatorMode:r.enable_coordinator_mode??!1,forkDisabled:!Cr(r),memoryEnabled:Rr(r),...e?{sessionId:e}:{}});return e&&a.conv.appendMessages(Pr(xr(t,e))),{sessionId:a.sessionId,cwd:a.cwd,run:a.run.bind(a),abort:()=>{a.abort()},dispose:async()=>{a.abort(),await Promise.allSettled([a.backgroundTaskManager.stopAll(),a.teamManager.dispose()]),await Promise.allSettled([a.mcpManager?.disconnectAll()??Promise.resolve(),a.registry.dispose()])}}}var Ra=1800*1e3,Ca="No active run is awaiting a permission response.";function _r(){let t=()=>{};return{promise:new Promise(r=>{t=r}),resolve:t}}var Mt=class{constructor(e=de,r=process.cwd(),i=Ra){this.runtimeFactory=e;this.cwd=r;this.idleTimeoutMs=i}runtimeFactory;cwd;idleTimeoutMs;sessions=new Map;permissionCounter=0;async execute(e,r){let i=e.taskId,a=e.contextId,n=e.userMessage;this.disarmIdleTimer(this.sessions.get(a));try{await this.dispatch(i,a,n,r)}finally{let o=this.sessions.get(a);o&&this.armIdleTimer(o)}}async dispatch(e,r,i,a){let n=Or(i);if(n){let u=this.sessions.get(r);if(!u){this.reject(null,a,e,r,Ca);return}await this.handlePermissionResponse(u,e,r,n,a);return}let o=vr(i);if(!o){this.reject(this.sessions.get(r)??null,a,e,r,"Message must contain text or a yukino permission-response data part.");return}let d=this.sessions.get(r);if(d?.run&&!d.run.finished){this.reject(d,a,e,r,`Context ${r} is busy with task ${d.run.taskId}. Cancel it or wait for it to finish before sending a new message.`);return}let f=d??this.createSession(r),T;try{T=await this.ensureRuntime(f)}catch(u){this.reject(f,a,e,r,fe(u));return}if(this.sessions.get(r)!==f){this.reject(null,a,e,r,"Session closed during initialization.");return}let p=f.run;if(p&&!p.finished){this.reject(f,a,e,r,`Context ${r} is busy with task ${p.taskId}. Cancel it or wait for it to finish before sending a new message.`);return}let O=this.startRun(f,T,e,r,o,a);this.consume(f,O,o),await O.settle.promise}async cancelTask(e,r){let i=this.findSessionByTask(e),a=i?.run;if(!i||!a||a.finished){let n=i?.contextId??"";r.publish(w.statusUpdate(lt(e,n,F.TASK_STATE_CANCELED,st(e,n,[kt("Task canceled by user request.")]))));return}this.disarmIdleTimer(i),a.canceled=!0,a.bus=r;for(let n of a.permissions.values())n.resolve("deny");a.permissions.clear(),a.runtime.abort(),await a.done.promise}async dispose(){let e=[...this.sessions.values()];this.sessions.clear(),await Promise.all(e.map(async r=>{if(this.disarmIdleTimer(r),!r.runtimePromise)return;let i;try{i=await r.runtimePromise}catch{return}let a=r.run;if(a&&!a.finished){a.canceled=!0;for(let n of a.permissions.values())n.resolve("deny");a.permissions.clear(),i.abort()}await i.dispose()}))}createSession(e){let r={contextId:e,sessionId:void 0,runtimePromise:null,run:null,idleTimer:null};return this.sessions.set(e,r),r}async ensureRuntime(e){e.runtimePromise??=this.runtimeFactory(this.cwd,e.sessionId).then(r=>(e.sessionId=r.sessionId,r));try{return await e.runtimePromise}catch(r){throw e.runtimePromise=null,r}}armIdleTimer(e){if(this.disarmIdleTimer(e),this.idleTimeoutMs<=0||!e.runtimePromise||e.run&&!e.run.finished)return;let r=setTimeout(()=>{e.idleTimer=null,this.evictSession(e)},this.idleTimeoutMs);r.unref(),e.idleTimer=r}disarmIdleTimer(e){e?.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=null)}evictSession(e){if(e.run&&!e.run.finished)return;let r=e.runtimePromise;e.runtimePromise=null,r&&r.then(i=>i.dispose()).catch(()=>{})}findSessionByTask(e){for(let r of this.sessions.values())if(r.run?.taskId===e)return r}async handlePermissionResponse(e,r,i,a,n){let o=e.run;if(!o||o.finished){this.reject(e,n,r,i,Ca);return}if(o.taskId!==r){this.reject(e,n,r,i,`Permission responses must be sent with taskId "${o.taskId}".`);return}let d=o.permissions.get(a.permissionId);if(!d){this.reject(e,n,r,i,`Unknown or already resolved permission id "${a.permissionId}".`);return}o.bus=n,o.permissions.delete(a.permissionId),o.settle=_r(),n.publish(w.task(Dt(r,i,F.TASK_STATE_WORKING))),d.resolve(a.decision),o.permissions.size>0&&(this.publishPendingPermissions(o,r,i),o.settle.resolve()),await o.settle.promise}startRun(e,r,i,a,n,o){this.disarmIdleTimer(e);let d={taskId:i,runtime:r,bus:o,settle:_r(),done:_r(),canceled:!1,finished:!1,stopReason:null,permissions:new Map};return e.run=d,wr(r.cwd,r.sessionId,{role:"user",content:n,timestamp:Math.floor(Date.now()/1e3)}),o.publish(w.task(Dt(i,a,F.TASK_STATE_SUBMITTED))),d}consume(e,r,i){let a=r.taskId,n=e.contextId,o=r.runtime.run(i,{onPermissionRequest:(d,f,T,p,O,u)=>this.requestPermission(r,a,n,d,f,T,p,O,u)});(async()=>{let d=null;try{for await(let f of o)f.type==="loop_complete"&&(r.stopReason=f.stopReason),f.type==="error"&&(d=f.error.message),this.publishAgentEvent(r,a,n,f)}catch(f){d=fe(f)}this.finishRun(e,r,a,n,d)})()}requestPermission(e,r,i,a,n,o,d,f,T){if(f?.aborted||e.canceled||e.finished)return Promise.resolve("deny");this.permissionCounter+=1;let p=`perm-${String(this.permissionCounter)}-${Yo().slice(0,8)}`,O={yukino:"permission-request",permissionId:p,toolCallId:d,toolName:a,reason:[T?`${T.agentName} \xB7 ${T.cwd}`:"",o.reason].filter(Boolean).join(`
|
|
13
|
+
`),args:n};return new Promise(u=>{let N=g=>{f?.removeEventListener("abort",h),u(g)},h=()=>{e.permissions.delete(p)&&(N("deny"),!e.canceled&&!e.finished&&(e.permissions.size>0?this.publishPendingPermissions(e,r,i):e.bus.publish(w.statusUpdate(lt(r,i,F.TASK_STATE_WORKING)))))};e.permissions.set(p,{data:O,resolve:N}),f?.addEventListener("abort",h,{once:!0}),this.publishPendingPermissions(e,r,i),e.settle.resolve()})}publishPendingPermissions(e,r,i){let a=[...e.permissions.values()].map(n=>yt(n.data));e.bus.publish(w.statusUpdate(lt(r,i,F.TASK_STATE_INPUT_REQUIRED,st(r,i,a))))}publishAgentEvent(e,r,i,a){let n=yr(a,r,i);n&&e.bus.publish(w.statusUpdate(lt(r,i,F.TASK_STATE_WORKING,n)))}finishRun(e,r,i,a,n){if(r.finished)return;r.finished=!0;for(let f of r.permissions.values())f.resolve("deny");r.permissions.clear();let o=this.finalState(r,n),d=n?st(i,a,[kt(n)]):void 0;r.bus.publish(w.statusUpdate(lt(i,a,o,d))),e.run===r&&(e.run=null),r.settle.resolve(),r.done.resolve(),this.armIdleTimer(e)}finalState(e,r){return e.canceled||e.stopReason==="cancelled"||e.stopReason==="interrupted"?F.TASK_STATE_CANCELED:r?F.TASK_STATE_FAILED:F.TASK_STATE_COMPLETED}reject(e,r,i,a,n){let o=st(i,a,[kt(n)]);if(e?.run&&!e.run.finished){r.publish(w.message(o));return}r.publish(w.task(Dt(i,a,F.TASK_STATE_FAILED))),r.publish(w.statusUpdate(lt(i,a,F.TASK_STATE_FAILED,o)))}};var wa=18890,Xo=`127.0.0.1:${String(wa)}`,Zo=new Set(["127.0.0.1","::1","localhost"]);function xa(t){let e=Dr(t??Xo,{defaultPort:wa,allowEphemeral:!0});if(!Zo.has(e.host))throw new Error("A2A server must listen on a loopback address.");return e}async function Pa(t={}){let{host:e,port:r}=xa(t.address),i=Wo();await bo(i,r,e);let a=i.address();if(!a||typeof a=="string")throw new Error("A2A server did not bind to a TCP address.");let o=`http://${a.family==="IPv6"?`[${a.address}]`:a.address}:${String(a.port)}/`,d=gr(o),f=new Mt(t.runtimeFactory??de,t.cwd??process.cwd()),T=new ei(d,new ri,f,new ve),p=(0,Ja.default)();p.use("/.well-known/agent-card.json",va({agentCardProvider:T})),p.use(ma({requestHandler:T,userBuilder:ir.noAuthentication})),p.use(_a({requestHandler:T,userBuilder:ir.noAuthentication})),i.on("request",p);let O=!1;return{url:o,cardUrl:`${o}.well-known/agent-card.json`,async close(){O||(O=!0,i.closeIdleConnections(),await jo(i),await f.dispose())}}}function bo(t,e,r){return new Promise((i,a)=>{let n=d=>{t.off("listening",o),a(d)},o=()=>{t.off("error",n),i()};t.once("error",n),t.once("listening",o),t.listen(e,r)})}function jo(t){return new Promise((e,r)=>{t.close(i=>{i?r(i):e()})})}async function kr(t){let e=await Pa({address:t});process.stderr.write(`A2A server listening at ${e.url}
|
|
14
|
+
`),process.stderr.write(`Agent card at ${e.cardUrl}
|
|
15
|
+
`),await new Promise(r=>{let i=()=>{process.off("SIGINT",i),process.off("SIGTERM",i),e.close().finally(r)};process.once("SIGINT",i),process.once("SIGTERM",i)})}function tl(t){let e=t.indexOf("--a2a");if(e===-1)return null;let r=t[e+1],i=r&&!r.startsWith("-")?2:1;if(t.length!==i)throw new Error("--a2a accepts only an optional port or host:port address.");return i===2?{address:r}:{}}async function ud(t){let e=tl(t);if(!e)throw new Error("A2A mode was not selected.");await kr(e.address)}export{ka as Card,Ia as Conversion,Ua as Executor,Da as Server,tl as parseA2aMode,ud as runA2a};
|