@yukino.js/yukino 0.0.12 → 0.0.13-dev
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 +5 -62
- package/dist/{a2a-RMMY65QU.js → a2a-DG2JNM3U.js} +1 -1
- package/dist/{acp-WY6JO5LK.js → acp-DCZDS6FQ.js} +1 -1
- package/dist/{anthropic-55TYAIKB.js → anthropic-5BTWVZVT.js} +1 -1
- package/dist/{chunk-HTLXOBAC.js → chunk-5DK2M7VI.js} +1 -1
- package/dist/{chunk-33HUTVDG.js → chunk-AZQD75PX.js} +1 -1
- package/dist/{chunk-IX65B3M7.js → chunk-BDLFNDC4.js} +1 -1
- package/dist/{chunk-V7Q2SA7H.js → chunk-COHBT6M7.js} +181 -175
- package/dist/{chunk-D4MZQCMB.js → chunk-CW5XFH7H.js} +2 -2
- package/dist/{chunk-7TZ52NFW.js → chunk-IWMCIYOG.js} +1 -1
- package/dist/{chunk-SYKQXO6W.js → chunk-SZXXASVH.js} +1 -1
- package/dist/{chunk-PWLFGDME.js → chunk-UGX62ZSO.js} +1 -1
- package/dist/lib/{chunk-WL3ML2TB.js → chunk-EGJKLA2W.js} +1 -1
- package/dist/lib/index.d.ts +12 -14
- package/dist/lib/index.js +199 -113
- package/dist/lib/{providers-DPVHJZAX.js → providers-MOCB6Y5L.js} +1 -1
- package/dist/{main-L3JP6JDZ.js → main-IA22XMQR.js} +162 -163
- package/dist/main.js +2 -2
- package/dist/{providers-VFEHLGQG.js → providers-DXQRJUIY.js} +1 -1
- package/dist/{server-F4PJ3W62.js → server-QS7CX37F.js} +1 -1
- package/dist/{tool-filter-5WW6YGKC.js → tool-filter-KDQMXIDC.js} +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -334,7 +334,7 @@ hooks:
|
|
|
334
334
|
|
|
335
335
|
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.
|
|
336
336
|
|
|
337
|
-
Sandbox configuration applies to TUI, print, Remote/ACP/A2A, and separate teammate hosts. 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
|
|
337
|
+
Sandbox configuration applies to TUI, print, Remote/ACP/A2A, and separate teammate hosts. 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.
|
|
338
338
|
|
|
339
339
|
Provider fields:
|
|
340
340
|
|
|
@@ -440,7 +440,7 @@ Before export, Yukino removes request bodies and cookies, redacts credential fie
|
|
|
440
440
|
|
|
441
441
|
### Project-level MCP servers (.mcp.json)
|
|
442
442
|
|
|
443
|
-
In addition to `mcp_servers` in `config.yaml`, Yukino reads a project-level `.mcp.json` from the working directory, using the
|
|
443
|
+
In addition to `mcp_servers` in `config.yaml`, Yukino reads a project-level `.mcp.json` from the working directory, using the following format:
|
|
444
444
|
|
|
445
445
|
```json
|
|
446
446
|
{
|
|
@@ -503,13 +503,13 @@ Ordinary subagents run once. On completion, failure, or interruption, the host w
|
|
|
503
503
|
|
|
504
504
|
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.
|
|
505
505
|
|
|
506
|
-
Persistent teammates
|
|
506
|
+
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.
|
|
507
507
|
|
|
508
508
|
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 permission mode; `permission_mode` in role frontmatter accepts only `plan` to enforce an immutable read-only role, not a permission override. `max_turns` must be a positive integer. Built-in explore uses the selected parent model unless explicitly overridden.
|
|
509
509
|
|
|
510
510
|
Separate teammate processes register their PID for liveness checks and handle SIGINT, SIGTERM, and SIGHUP through the same cleanup path. The leader reclaims tasks after detecting a dead worker, including on restore. Tmux/iTerm workers receive a shutdown grace period; an iTerm worker that remains alive is terminated by its registered PID. 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.
|
|
511
511
|
|
|
512
|
-
`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
|
|
512
|
+
`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.
|
|
513
513
|
|
|
514
514
|
`WebFetch` cancels discarded response bodies and honors cancellation even for cached pages. Direct HTTP/HTTPS access, including project intranet endpoints, remains supported.
|
|
515
515
|
|
|
@@ -624,7 +624,7 @@ Inside the UI, these commands are available:
|
|
|
624
624
|
|
|
625
625
|
### User Bash Commands
|
|
626
626
|
|
|
627
|
-
Start the main terminal input with `!` or `!!` to execute Bash directly, without calling the model.
|
|
627
|
+
Start the main terminal input with `!` or `!!` to execute Bash directly, without calling the model. `! git status` includes the command and result in the next model context; `!! pnpm test` excludes both from model context. Commands are literal shell input: `@` references, slash commands, and skills are not expanded. Plan feedback and other dialogs do not interpret these prefixes.
|
|
628
628
|
|
|
629
629
|
The command runs in the current workspace with Yukino's Bash timeout and output limits. Output appears while it runs, and Ctrl+O expands the tool card. Results retain at most the last 2,000 lines / 50 KiB; larger output is saved to a file whose path appears in the result. Prompt history supports recalling commands. Both modes persist their cards for `/resume` and checkpoint rewind, while `!!` results remain excluded when rebuilding model context. Agent permission modes (including Plan) do not restrict commands explicitly entered by the user; an enabled OS sandbox still applies and fails closed if unavailable.
|
|
630
630
|
|
|
@@ -677,60 +677,3 @@ In a long-lived host process, prefer the composable modules (`Agent`, `ToolRegis
|
|
|
677
677
|
Run `pnpm exec vitest run tests/ui-cursor.test.ts tests/ui-terminal-resize.test.ts tests/terminal-output.test.ts` to check terminal cells, CJK and emoji widths, combining characters, cursor placement, ANSI colors, fragmented UTF-8 output, native scrollback anchors, and resize redraws. These tests exercise the primary screen without mouse capture. The emulator does not validate font rendering, pixel appearance, native selection, or OS clipboard behavior; those still need testing in the target terminal. Unicode width policies, especially for complex emoji sequences, can differ between terminals.
|
|
678
678
|
|
|
679
679
|
Runtime text measurement stays on `string-width`, which already uses `get-east-asian-width` and handles ANSI stripping and grapheme clusters. The xterm packages are development dependencies.
|
|
680
|
-
|
|
681
|
-
## Pi Capability Comparison
|
|
682
|
-
|
|
683
|
-
The reference is the local Pi checkout at commit `200387122ca450d6387f033949423114a270b96c`. This comparison includes the coding-agent package, its extension examples and experimental modes, and its TUI dependency. It distinguishes shared behavior from Yukino's product choices; it does not describe every package or third-party extension in Pi's ecosystem.
|
|
684
|
-
|
|
685
|
-
| Shared capability | Pi reference | Yukino outcome |
|
|
686
|
-
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
687
|
-
| Text and image reads | [read tool](../../submodule/pi/packages/coding-agent/src/core/tools/read.ts) | Async, cancellable reads; image format detection now also works without image extensions. Keep zero-based offsets, numbered text output, and read-state tracking. |
|
|
688
|
-
| Batched edits and writes | [edit tool](../../submodule/pi/packages/coding-agent/src/core/tools/edit.ts) | Preserve disjoint-edit validation, fuzzy matching, BOM/CRLF, mutation queues, and stale-file checks. Writes now use async I/O and recheck cancellation and file state after directory creation. |
|
|
689
|
-
| Search | [grep tool](../../submodule/pi/packages/coding-agent/src/core/tools/grep.ts) | Add UTF-8 byte limits, long-line previews, accurate truncation notices, and cancellation. Preserve Unicode matching, hidden-file discovery, traversal bounds, and Glob's modification-time ordering. |
|
|
690
|
-
| Path handling | [path utilities](../../submodule/pi/packages/coding-agent/src/core/tools/path-utils.ts) | Resolve home-relative paths through one helper shared with permissions, preventing checks and execution from targeting different files. |
|
|
691
|
-
| Bash and PowerShell | [tools](../../submodule/pi/packages/coding-agent/src/core/tools) | Existing process-tree cancellation, output limits, spill/readback, and shutdown tests retained. Yukino's explicit background tasks, timeout backgrounding, and TaskOutput are intentional differences. |
|
|
692
|
-
| Model streaming and recovery | [agent session](../../submodule/pi/packages/coding-agent/src/core/agent-session.ts) | Classify HTTP 408/5xx separately; share bounded retries for network/server/rate-limit failures. Preserve deterministic error handling and partial output without replaying already-visible content. Reject streams without a completion event. |
|
|
693
|
-
| Context compaction | [compaction](../../submodule/pi/packages/coding-agent/src/core/compaction/compaction.ts) | Retry transient summary failures, discard partial attempts, require successful completion, and preserve history on failure. Existing tool-pair boundaries and resumable compaction records remain protected. |
|
|
694
|
-
| Sessions and rewind | [session manager](../../submodule/pi/packages/coding-agent/src/core/session-manager.ts) | Retain JSONL locks, malformed-record recovery, compaction replay, multimedia restoration, expiry, and file-history rewind. Pi's session tree and Yukino's linear log/file snapshots are different designs. |
|
|
695
|
-
| Skills | [skill discovery](../../submodule/pi/packages/coding-agent/src/core/skills.ts) | Discover nested groups, stop at skill roots, guard symlink cycles, and watch grouping directories for additions. Preserve project-over-user precedence, explicitly declared hidden roots, and inline/fork execution. |
|
|
696
|
-
| Prompt commands | [prompt templates](../../submodule/pi/packages/coding-agent/src/core/prompt-templates.ts) | Add BOM support, quoted positional arguments, defaults, slices, and single-pass substitution. Preserve raw `$ARGUMENTS` and built-in command routing. |
|
|
697
|
-
| Instructions, settings, models | [resource loader](../../submodule/pi/packages/coding-agent/src/core/resource-loader.ts) | Retain instruction hierarchy/includes, provider selection, model discovery, thinking controls, and configuration validation. YAML configuration and precedence rules remain Yukino choices. |
|
|
698
|
-
| MCP | [MCP integration](../../submodule/pi/packages/coding-agent/src/extensions/mcp) | Retain transport, pagination, structured content, cancellation, connection cleanup, transactional reload, and cache-aware tool loading. User MCP configuration wins over project configuration by design. |
|
|
699
|
-
| Hooks and permissions | [extensions](../../submodule/pi/packages/coding-agent/examples/extensions) | Preserve Yukino's configured hook lifecycle, permission modes, plan locks, and inherited child boundaries. Pi's permission-gate and sandbox examples supply relevant ideas, not a replacement for these policies. |
|
|
700
|
-
| TUI, resizing, scrolling | [ScrollView](../../submodule/pi/packages/tui/src/components/scroll-view.ts) | Keep bottom-follow/manual reading position and responsive composer/cursor behavior. Batch thinking with text, cancel stale refreshes, and sanitize raw terminal controls/expand tabs before display measurements. |
|
|
701
|
-
| Print/JSON and embedding | [print mode](../../submodule/pi/packages/coding-agent/src/modes/print-mode.ts) | Emit incremental JSONL and pair same-name tools by call ID. Preserve signal exit codes and cancel children during result waits. Keep the terminal-independent library build contract. |
|
|
702
|
-
| Subagents and planning | [subagent example](../../submodule/pi/packages/coding-agent/examples/extensions/subagent), [durable](../../submodule/pi/packages/coding-agent/src/experimental/durable/README.md), [vacation](../../submodule/pi/packages/coding-agent/src/experimental/vacation/README.md) | Pi has relevant implementations. Retain Yukino's foreground concurrency, background notifications, child permissions, and lifecycle ownership; these are not capabilities wholly absent from Pi. |
|
|
703
|
-
|
|
704
|
-
Regression coverage includes concurrent same-file mutations and tool-result ordering, permission inheritance and plan locks, cancelled/failed streams and compaction, session recovery and rewind, MCP lifecycle, subagent/team cleanup, terminal widths/heights and cursor positions, bottom-follow/manual scrolling, and Remote/ACP/A2A boundaries. Passing automated checks establishes coverage of these contracts; real terminal behavior still depends on the emulator and terminal capabilities.
|
|
705
|
-
|
|
706
|
-
### Yukino Features Without a Direct Counterpart in the Reviewed Package
|
|
707
|
-
|
|
708
|
-
- Persistent leader/teammate workflows combining shared task ownership, file mailboxes, coordinator tool filtering, teammate plan approval, and in-process/tmux/iTerm backends. Pi has subagents, parallel durable tasks, and an experimental coordinator that routes server messages; those do not provide this same team workflow.
|
|
709
|
-
- Native ACP and A2A protocol hosts, and the bundled browser chat application. Pi's RPC/experimental server architecture remains useful as a reference for shared streaming and lifecycle concerns.
|
|
710
|
-
- Built-in read-only LSP queries and ComputerUse actions with provider-specific response handling.
|
|
711
|
-
- Cross-session memory extraction, recall, and consolidation, beyond per-session instructions and compaction.
|
|
712
|
-
- Structured code-review selection, validated findings, relocation/filtering, reports, and revision workflows. Pi's reviewer-agent example overlaps with review delegation, rather than this full pipeline.
|
|
713
|
-
- Built-in WebSearch and WebFetch tools. Pi can add web capabilities through MCP, extensions, or shell tools; that differs from these built-in tool implementations.
|
|
714
|
-
- Agent-run OpenTelemetry/Langfuse instrumentation and Sentry reporting. A Sentry MCP configuration example in Pi is a tool connection, not application error instrumentation.
|
|
715
|
-
|
|
716
|
-
Some further Yukino integrations have partial references: four permission modes with read-before-edit/stale-file gates and parent/child plan locks; file snapshots and persisted conversation rewind; and worktree creation/cleanup owned by agent tasks. Pi has permission/sandbox and git-checkpoint examples and can operate inside worktrees. Those are useful references, but they do not implement the same combined contracts. OAuth/model breadth, a session-tree UI, and Pi's extension/package ecosystem are Pi capabilities outside the shared surface audited here.
|
|
717
|
-
|
|
718
|
-
## Claude Code Capability Comparison
|
|
719
|
-
|
|
720
|
-
This audit uses the local checkout at `/Users/user/Downloads/claude-code`, revision `77a7934e15d69da13879112ed7db695c9ee7a52a`. References below are paths inside that checkout. Findings concern the inspected implementation, including its fork-specific integrations, rather than every released Claude Code version. Existing correct behavior is retained; a different product contract alone is not a defect.
|
|
721
|
-
|
|
722
|
-
| Capability | Claude Code reference | Defects fixed or capability added | Yukino design retained |
|
|
723
|
-
| ------------------------------------ | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
724
|
-
| Predefined/fork/background subagents | `docs/agent/sub-agents.mdx`, `docs/features/fork-subagent.md`, builtin `AgentTool` | Explicit foreground requests now override a predefined background default; role frontmatter accepts BOM; invalid background types fail explicitly. | Fork selection, parallel foreground reads/delegation, serialized conflicting mutations, inherited permissions, owned background cleanup, and independent task lists remain. |
|
|
725
|
-
| Plan | `docs/safety/plan-mode.mdx`, builtin `ExitPlanModeTool` | Plan paths belong to each checker/session instead of global process state. Exit checks the calling agent's live mode and its own non-empty plan, preventing cross-session reuse and empty approvals. | `/plan` remains user-controlled. Plan/explore roles remain locked read-only; teammate implementation still requires the leader's matching approval. Resume starts with a fresh plan owner. |
|
|
726
|
-
| Persistent goals | `src/services/goal`, `src/hooks/useGoalContinuation.ts`, builtin `GoalTool` | Added `/goal`, persisted session state, continuation, budgets, active time, completion and consecutive blocker audits, clear tombstones, resume/rewind reload, and host command handling. | User steering takes priority. No auto-run in Plan mode, after interruption/error, or merely on startup. Replacement and continuation-limit reset are explicit user actions. Budget reports use stored state without another model call. |
|
|
727
|
-
| OS sandbox | `src/utils/sandbox/sandbox-adapter.ts` | Print, Remote/ACP/A2A, and separate teammates now receive sandbox configuration; relative write roots resolve against command cwd; owned Bash backends are disposed. | Native Seatbelt/bubblewrap wrappers fail closed. Bash-only write confinement and a network boolean remain a deliberately smaller policy than Claude's proxy/domain/read restrictions. Permission bypass does not bypass the OS wrapper. |
|
|
728
|
-
| Checkpoints | `src/utils/fileHistory.ts` | Capture a checkpoint before the first agent request, including failed/interrupted first runs. Rewind compares binary bytes rather than decoded strings. | Persistent linear conversation/file snapshots, transcript coordinates, deletion recovery, partial-failure retry, and edited-worktree retention remain. Checkpoints cover Yukino-managed file edits, not arbitrary shell or desktop side effects. |
|
|
729
|
-
| Agent teams | `src/utils/teammateMailbox.ts`, builtin `SendMessageTool`, `src/utils/swarm/backends` | Invalid mailbox data now fails explicitly and preserves the original file instead of silently overwriting it as an empty inbox; failed atomic writes clean up temporary files. | Shared task claims/dependencies/owners use cross-process locks; request IDs and leader-only plan approval, coordinator filtering, persistent idle teammates, and in-process/tmux/iTerm backends remain. Separate processes retain PID/liveness/shutdown handling. |
|
|
730
|
-
| LSP | `src/services/lsp`, builtin `LSPTool` | A2A now forwards the configured language servers, matching other hosts. | Read-only queries, UTF-16 positions, request queueing, cancellation, document versions, server restart, and rejection of server-initiated edits remain. LSP/MCP executables are trusted local programs outside the Bash sandbox. |
|
|
731
|
-
| ComputerUse | `src/utils/computerUse/computerUseLock.ts`, builtin computer-use tools | Add a cross-process device lock per call/action batch, release it on exit/failure, and release Linux modifiers even after cancellation or partial key-down failure. | Coordinate conversion, screenshot/zoom handling, platform helpers, permissions, and provider safety/output handling remain. The lock protects an action batch; it is not Claude's full turn/session lease. |
|
|
732
|
-
| Long-term memory | `src/services/extractMemories`, `src/memdir/findRelevantMemories.ts`, `src/services/autoDream` | Failed/partial extraction and incomplete/cancelled recall cannot publish partial model selections. Recall deduplicates valid paths and enforces the five-memory limit. | Project/user scopes, index limits, origin metadata, permissions, extraction throttling, consolidation lock and rollback remain. Yukino's scheduling/storage contracts are independent of Claude's cloud/team memory services. |
|
|
733
|
-
| WebSearch/WebFetch | builtin `WebSearchTool`, `WebFetchTool`, Bing search adapter | Use Bing public-page search without a paid search API, decode result redirects, and retain validated domain filters. Report blocked or unrecognized pages as errors. WebFetch cancels unused bodies, rechecks cancellation, and refreshes replacement cache entries. | Search and direct HTTP/HTTPS fetch remain independent of the model provider. Local result filtering can return fewer hits; intranet fetches remain supported. Search returns snippets; use WebFetch for page content. No model summarizer is imposed. |
|
|
734
|
-
| Observability | `src/utils/telemetry/instrumentation.ts`, `src/services/langfuse`, `src/utils/sentry.ts` | Sentry export strips request bodies/cookies, scrubs credential fields and known secrets/home prefixes, and ignores cancellation errors. | Optional environment-controlled OTel/Langfuse/Sentry integrations, parent/child spans, cache-token and duration metrics, hashed session IDs, bounded flushing, and content-free OTel/Langfuse instrumentation remain. The reviewed Claude checkout does include Langfuse. |
|
|
735
|
-
|
|
736
|
-
Regression checks exercise goal state/continuation and print/remote commands, foreground/background delegation, plan isolation and locks, native sandbox argument generation and unavailable-backend rejection, shared task/approval/mailbox lifecycles, binary checkpoints, LSP transport, ComputerUse contention and modifier cleanup, memory failure paths, web cancellation/domain filtering, and telemetry redaction. Real native OS confinement, desktop permissions, and tmux/iTerm UI behavior still require platform-specific execution; mocked tool tests do not establish those live integrations.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __yukinoCreateRequire } from "node:module";
|
|
3
3
|
const require = __yukinoCreateRequire(import.meta.url);
|
|
4
|
-
import{a as Et,b as Qr,g as Yr}from"./chunk-7TZ52NFW.js";import{b as Fr,c as Br,d as Hr,e as Vr}from"./chunk-5URXBVET.js";import{p as Kr,s as Gr,u as br}from"./chunk-V7Q2SA7H.js";import"./chunk-HTLXOBAC.js";import{h as zr}from"./chunk-4CLD7LEU.js";import"./chunk-D4MZQCMB.js";import"./chunk-33HUTVDG.js";import"./chunk-MQAQBW7F.js";import"./chunk-WGFROGUC.js";import"./chunk-VU3JWAJR.js";import"./chunk-IX65B3M7.js";import{r as Oe}from"./chunk-OI2W6R6H.js";import"./chunk-JFKC4VCA.js";import"./chunk-KJJYW5IY.js";import"./chunk-I74AL3PF.js";import"./chunk-LCWNSYZU.js";import{a as qr}from"./chunk-SYKQXO6W.js";import{C as R}from"./chunk-W4GMCNWF.js";import"./chunk-VM4YKTHC.js";import"./chunk-HMZQYFYG.js";import"./chunk-3QL446GD.js";import"./chunk-AGSYLE4E.js";import"./chunk-CU3IISCC.js";import"./chunk-VCIRD267.js";import{d as Gt,e as Nt}from"./chunk-7MKA3SHV.js";var On={};Gt(On,{parseA2aAddress:()=>Nn,runA2aServer:()=>$r,startA2aServer:()=>En});import{createServer as hl}from"http";var vn=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}},x={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 Ie(t){throw new Error(`Unhandled event kind: ${t.kind}`)}var ei=typeof CustomEvent<"u"?CustomEvent:class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail??null}};function Wr(t){return t instanceof ei}var _n=class extends EventTarget{eventListeners=new Map;finishedListeners=new Map;publish(t){this.dispatchEvent(new ei("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(!Wr(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(!Wr(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})}},yn={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(",")},An="0.3";var kn=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||An,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=yn.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function Ce(t){return t.user?.userName||"unknown"}var In="a2a-protocol.org",Rn="type.googleapis.com/google.rpc.ErrorInfo",ri=Symbol.for("@a2a-js/sdk.A2AError"),Wt=class ii extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(ri in e))return!1;if(this===ii)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":Rn,reason:this.reason,domain:In,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(Wt.prototype,ri,{value:!0});var ai=[{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"}],et=Object.freeze(Object.fromEntries(ai.map(t=>[t.name,t]))),Ol=Object.freeze(Object.fromEntries(ai.map(t=>[t.reason,t])));function rt(t){return{[t.name]:class extends Wt{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 V=rt(et.TaskNotFoundError),Re=rt(et.TaskNotCancelableError),Pt=rt(et.PushNotificationNotSupportedError),St=rt(et.UnsupportedOperationError),ni=rt(et.ContentTypeNotSupportedError),Cn=rt(et.InvalidAgentResponseError),si=rt(et.ExtendedAgentCardNotConfiguredError),oi=rt(et.ExtensionSupportRequiredError),Un=rt(et.VersionNotSupportedError),F=rt(et.RequestMalformedError),di=Object.freeze({TaskNotFoundError:V,TaskNotCancelableError:Re,PushNotificationNotSupportedError:Pt,UnsupportedOperationError:St,ContentTypeNotSupportedError:ni,InvalidAgentResponseError:Cn,ExtendedAgentCardNotConfiguredError:si,ExtensionSupportRequiredError:oi,VersionNotSupportedError:Un,RequestMalformedError:F});function Xr(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},tt={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"},Jn=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}),vl=Object.freeze({TaskNotFoundError:tt.NOT_FOUND,TaskNotCancelableError:tt.FAILED_PRECONDITION,PushNotificationNotSupportedError:tt.FAILED_PRECONDITION,UnsupportedOperationError:tt.FAILED_PRECONDITION,ContentTypeNotSupportedError:tt.INVALID_ARGUMENT,InvalidAgentResponseError:tt.INTERNAL,ExtendedAgentCardNotConfiguredError:tt.FAILED_PRECONDITION,ExtensionSupportRequiredError:tt.FAILED_PRECONDITION,VersionNotSupportedError:tt.FAILED_PRECONDITION,RequestMalformedError:tt.INVALID_ARGUMENT});function it(t){let e=di[t],r=Jn[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 wn=it("TaskNotFoundError"),xn=it("TaskNotCancelableError"),Pn=it("PushNotificationNotSupportedError"),Dn=it("UnsupportedOperationError"),Mn=it("ContentTypeNotSupportedError"),Ln=it("InvalidAgentResponseError"),$n=it("ExtendedAgentCardNotConfiguredError"),qn=it("ExtensionSupportRequiredError"),zn=it("VersionNotSupportedError"),Fn=it("RequestMalformedError"),_l=Object.freeze({TaskNotFoundError:wn,TaskNotCancelableError:xn,PushNotificationNotSupportedError:Pn,UnsupportedOperationError:Dn,ContentTypeNotSupportedError:Mn,InvalidAgentResponseError:Ln,ExtendedAgentCardNotConfiguredError:$n,ExtensionSupportRequiredError:qn,VersionNotSupportedError:zn,RequestMalformedError:Fn}),L={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},li=Object.freeze({TaskNotFoundError:L.TASK_NOT_FOUND,TaskNotCancelableError:L.TASK_NOT_CANCELABLE,PushNotificationNotSupportedError:L.PUSH_NOTIFICATION_NOT_SUPPORTED,UnsupportedOperationError:L.UNSUPPORTED_OPERATION,ContentTypeNotSupportedError:L.CONTENT_TYPE_NOT_SUPPORTED,InvalidAgentResponseError:L.INVALID_AGENT_RESPONSE,ExtendedAgentCardNotConfiguredError:L.EXTENDED_CARD_NOT_CONFIGURED,ExtensionSupportRequiredError:L.EXTENSION_SUPPORT_REQUIRED,VersionNotSupportedError:L.VERSION_NOT_SUPPORTED,RequestMalformedError:L.INVALID_PARAMS}),yl=Object.freeze(Object.fromEntries(Object.entries(li).map(([t,e])=>[e,t])));function at(t){let e=di[t],r=li[t]??L.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 Bn=at("TaskNotFoundError"),Hn=at("TaskNotCancelableError"),Vn=at("PushNotificationNotSupportedError"),Kn=at("UnsupportedOperationError"),Gn=at("ContentTypeNotSupportedError"),bn=at("InvalidAgentResponseError"),Qn=at("ExtendedAgentCardNotConfiguredError"),Yn=at("ExtensionSupportRequiredError"),Wn=at("VersionNotSupportedError"),Xn=at("RequestMalformedError"),Al=Object.freeze({TaskNotFoundError:Bn,TaskNotCancelableError:Hn,PushNotificationNotSupportedError:Vn,UnsupportedOperationError:Kn,ContentTypeNotSupportedError:Gn,InvalidAgentResponseError:bn,ExtendedAgentCardNotConfiguredError:Qn,ExtensionSupportRequiredError:Yn,VersionNotSupportedError:Wn,RequestMalformedError:Xn});var kl={[L.PARSE_ERROR]:"RequestMalformedError",[L.INVALID_REQUEST]:"RequestMalformedError",[L.METHOD_NOT_FOUND]:"RequestMalformedError"};function Zn(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 jn(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 ts(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 es(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:_(t.id)?globalThis.String(t.id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",status:_(t.status)?Xt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>jt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>Ot.fromJSON(e)):[],metadata:vt(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=Xt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>jt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>Ot.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Xt={fromJSON(t){return{state:_(t.state)?Zn(t.state):0,message:_(t.message)?Ot.fromJSON(t.message):void 0,timestamp:_(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=jn(t.state)),t.message!==void 0&&(e.message=Ot.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Zt={fromJSON(t){return{content:_(t.text)?{$case:"text",value:globalThis.String(t.text)}:_(t.raw)?{$case:"raw",value:Buffer.from(is(t.raw))}:_(t.url)?{$case:"url",value:globalThis.String(t.url)}:_(t.data)?{$case:"data",value:t.data}:void 0,metadata:vt(t.metadata)?t.metadata:void 0,filename:_(t.filename)?globalThis.String(t.filename):"",mediaType:_(t.mediaType)?globalThis.String(t.mediaType):_(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=as(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}},Ot={fromJSON(t){return{messageId:_(t.messageId)?globalThis.String(t.messageId):_(t.message_id)?globalThis.String(t.message_id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",taskId:_(t.taskId)?globalThis.String(t.taskId):_(t.task_id)?globalThis.String(t.task_id):"",role:_(t.role)?ts(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Zt.fromJSON(e)):[],metadata:vt(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=es(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Zt.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}},jt={fromJSON(t){return{artifactId:_(t.artifactId)?globalThis.String(t.artifactId):_(t.artifact_id)?globalThis.String(t.artifact_id):"",name:_(t.name)?globalThis.String(t.name):"",description:_(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Zt.fromJSON(e)):[],metadata:vt(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=>Zt.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},ve={fromJSON(t){return{taskId:_(t.taskId)?globalThis.String(t.taskId):_(t.task_id)?globalThis.String(t.task_id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",status:_(t.status)?Xt.fromJSON(t.status):void 0,metadata:vt(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=Xt.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},_e={fromJSON(t){return{taskId:_(t.taskId)?globalThis.String(t.taskId):_(t.task_id)?globalThis.String(t.task_id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",artifact:_(t.artifact)?jt.fromJSON(t.artifact):void 0,append:_(t.append)?globalThis.Boolean(t.append):!1,lastChunk:_(t.lastChunk)?globalThis.Boolean(t.lastChunk):_(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:vt(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=jt.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 rs={fromJSON(t){return{payload:_(t.task)?{$case:"task",value:Zr.fromJSON(t.task)}:_(t.message)?{$case:"message",value:Ot.fromJSON(t.message)}:_(t.statusUpdate)?{$case:"statusUpdate",value:ve.fromJSON(t.statusUpdate)}:_(t.status_update)?{$case:"statusUpdate",value:ve.fromJSON(t.status_update)}:_(t.artifactUpdate)?{$case:"artifactUpdate",value:_e.fromJSON(t.artifactUpdate)}:_(t.artifact_update)?{$case:"artifactUpdate",value:_e.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=Ot.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=ve.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=_e.toJSON(t.payload.value)),e}};function is(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function as(t){return globalThis.Buffer.from(t).toString("base64")}function vt(t){return typeof t=="object"&&t!==null}function _(t){return t!=null}var ns="1.0",ui="0.3",ss="application/a2a+json",ci=50,Il=4*1024*1024,Dt=[3,4,5,7],os=[0,1,2,3,4,5,6,7,8],fi=[6],pi=[8],ds=[...fi,...pi];function jr(t){return"status"in t}function ti(t,e){return{tenant:t.tenant??"",owner:e(t)}}function ls(t,e){return Buffer.from(`${t}|${e}`).toString("base64")}function us(t){try{let[e,...r]=Buffer.from(t,"base64").toString("utf-8").split("|");if(r.length===0)throw new F("Invalid page token format.");return{timestamp:e,id:r.join("|")}}catch(e){throw e instanceof F?e:new F("Token is not a valid base64-encoded cursor.")}}var Ue=class{_store=new Map;_ownerResolver;constructor(t){this._ownerResolver=t}getBucket(t){let{tenant:e,owner:r}=ti(t,this._ownerResolver);return this._store.get(e)?.get(r)}getOrCreateBucket(t){let{tenant:e,owner:r}=ti(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}},ye=new kn,Je=class{_scopedBuses;constructor(t=Ce){this._scopedBuses=new Ue(t)}createOrGetByTaskId(t,e){let r=this._scopedBuses.getOrCreateBucket(e??ye),i=r.get(t);return i||(i=new _n,r.set(t,i)),i}getByTaskId(t,e){return this._scopedBuses.getBucket(e??ye)?.get(t)}cleanupByTaskId(t,e){let r=this._scopedBuses.getBucket(e??ye);r?.get(t)?.removeAllListeners(),r?.delete(t)}},bt=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&&(Dt.includes(t.data.status.state)||fi.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)}},Qt=new Map;function Ae(t,e){let r=t.tenant??"",i=t.user?.userName??"";return`${r}\0${i}\0${e}`}async function ke(t,e){let i=(Qt.get(t)??Promise.resolve()).then(e,e);Qt.set(t,i);let a=()=>{Qt.get(t)===i&&Qt.delete(t)};return i.then(a,a),i}var Yt=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 ke(Ae(this.serverCallContext,e.id),()=>this.processTaskEventLocked(e));break}case"statusUpdate":{let e=t.data;if(!e.taskId){await this.applyStatusUpdate(e);break}await ke(Ae(this.serverCallContext,e.taskId),()=>this.applyStatusUpdate(e));break}case"artifactUpdate":{let e=t.data;if(!e.taskId){await this.applyArtifactUpdate(e);break}await ke(Ae(this.serverCallContext,e.taskId),()=>this.applyArtifactUpdate(e));break}default:Ie(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&&Dt.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}},cs=class{_scopedStore;constructor(t=Ce){this._scopedStore=new Ue(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||ui,o=a.findIndex(l=>l.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)}},fs=class{serialize(t,e){return{body:JSON.stringify(rs.toJSON(t)),contentType:ss}}},ps=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 fs;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 l=a.map(async c=>{try{await this._dispatchNotification(t,c,i,r)}catch(S){console.error(`Error sending push notification for task_id=${i} to URL: ${c.config.url}. Error:`,S)}});await Promise.all(l)});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||ui;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 '${ns}'. 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,l=new AbortController,c=setTimeout(()=>l.abort(),this.options.timeout);try{let S=this._resolveSerializer(n),{body:T,contentType:v}=S.serialize(t,i),u=await fetch(o,{method:"POST",headers:{"Content-Type":v,...this._buildAuthHeaders(a)},body:T,signal:l.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(c)}}},hi=class{agentCard;taskStore;agentExecutor;eventBusManager;pushNotificationStore;pushNotificationSender;extendedAgentCardProvider;agentCardSignatureGenerator;keepBusAliveStates;validateInputModes;constructor(t,e,r,i=new Je,a,n,o,l,c={}){this.agentCard=t,this.taskStore=e,this.agentExecutor=r,this.eventBusManager=i,this.extendedAgentCardProvider=o,this.agentCardSignatureGenerator=l,this.keepBusAliveStates=new Set(c.keepBusAliveStates??ds),this.validateInputModes=c.validateInputModes??!1,t.capabilities?.pushNotifications&&(this.pushNotificationStore=a||new cs,this.pushNotificationSender=n||new ps(this.pushNotificationStore))}async getAgentCard(){return this.agentCardSignatureGenerator?this.agentCardSignatureGenerator(this.agentCard):this.agentCard}async getAuthenticatedExtendedAgentCard(t,e){if(!this.agentCard.capabilities?.extendedAgentCard)throw new St("Agent does not support authenticated extended card.");if(!this.extendedAgentCardProvider)throw new si;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 ni(`Media type '${i.mediaType}' is not supported. Supported media types: ${r.join(", ")}.`)}}async _createRequestContext(t,e){let r=t.message;if(!r)throw new F("request.message is required.");let i,a,n=await this.getAgentCard();this._validateInputModes(r,n);let o=n.capabilities?.extensions??[],l=new Set(e.requestedExtensions??[]),c=o.filter(p=>p.required&&!l.has(p.uri)).map(p=>p.uri);if(c.length>0)throw new oi(`Client must declare support for required extensions: ${c.join(", ")}`);if(r.taskId){if(this._requireValidTaskId(r.taskId),i=await this.taskStore.load(r.taskId,e),!i)throw new V(`Task not found: ${r.taskId}`);if(i.status?.state!==void 0&&Dt.includes(i.status.state))throw new St(`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 F(`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 S=r.taskId||crypto.randomUUID(),T=r.referenceTaskIds||[];if(T.length>0){a=[];for(let p of T){let N=await this.taskStore.load(p,e);N?a.push(N):console.warn(`Reference task ${p} not found.`)}}let v=r.contextId||i?.contextId||crypto.randomUUID();if(e.requestedExtensions){let p=new Set(o.map(N=>N.uri));e.setRequestedExtensions(e.requestedExtensions.filter(N=>p.has(N)))}let u={...r,contextId:v,taskId:S},m={...t,message:u};return new vn(m,S,v,e,i,a)}async _processEvents(t,e,r,i,a){let n=!1,o=!1;try{for await(let l of r.events()){await e.processEvent(l);try{let c=await this._mapEventToStreamResponse(l,i);await this._sendPushNotificationIfNeeded(i,c,structuredClone(e.getCurrentTask()))}catch(c){console.error(`Error sending push notification: ${c}`)}if(a?.firstResultResolver&&!n){let c;if(l.kind==="message")c=l.data;else if(l.kind==="task")c=l.data;else{let S=e.getFinalResult();S&&("messageId"in S||"id"in S)&&(c=S)}c&&(a.firstResultResolver(c),n=!0)}if(a?.authRequiredSnapshotResolver&&!o&&l.kind==="statusUpdate"&&l.data.status&&pi.includes(l.data.status.state)){let c=e.getCurrentTask();c&&(a.authRequiredSnapshotResolver(structuredClone(c)),o=!0,n=!0)}}a?.firstResultResolver&&a?.firstResultRejector&&!n&&a.firstResultRejector(new F("Execution finished before a message or task was produced."))}catch(l){console.error(`Event processing loop failed for task ${t}:`,l),await this._handleProcessingError(l,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=hs(e);this.agentExecutor.execute(r,e).catch(n=>{let o=Xr(n);console.error(`Agent execution failed for message ${i.messageId}:`,n);let l={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&&!l.history?.find(c=>c.messageId===i.messageId)&&l.history?.push(i),e.publish(x.task(l)),e.publish(x.statusUpdate({taskId:l.id,contextId:l.contextId,status:l.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=Ss(e);this.agentExecutor.execute(r,e).catch(n=>{let o=Xr(n);console.error(`Agent execution failed for stream message ${i.messageId}:`,n);let l=a().task,c=l?.id??r.taskId,S=l?.contextId??i.contextId;if(!l){let v={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&&!v.history?.find(u=>u.messageId===i.messageId)&&v.history?.push(i),e.publish(x.task(v))}let T={taskId:c,contextId:S,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:c,contextId:S,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},metadata:{}};e.publish(x.statusUpdate(T))}).finally(()=>{this._settleBus(t,e,a().state,r.context)})}async sendMessage(t,e){let r=t.message;if(!r?.messageId)throw new F("message.messageId is required.");let i=t.configuration?.returnImmediately!==!0,a=new Yt(this.taskStore,e);a.setContext(r);let n=await this._createRequestContext(t,e),o=n.taskId,l=n.userMessage;if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let v=structuredClone(t.configuration.taskPushNotificationConfig);v.taskId=o,await this.pushNotificationStore?.save(o,e,v)}let c=this.eventBusManager.createOrGetByTaskId(o,e),S=new bt(c);this._runExecutor(o,c,n,l);let T=t.configuration;return i?new Promise((v,u)=>{let m=this._processEvents(o,a,S,e,{authRequiredSnapshotResolver:p=>{this._applyHistoryLengthSemantics(p,T??{}),v(p),this._continueDraining(o,m)},firstResultRejector:u});m.then(()=>{let p=a.getFinalResult();if(!p){u(new Wt("Agent execution finished without a result, and no task context found."));return}jr(p)&&this._applyHistoryLengthSemantics(p,T??{}),v(p)}).catch(u)}):new Promise((v,u)=>{this._processEvents(o,a,S,e,{firstResultResolver:m=>{jr(m)&&this._applyHistoryLengthSemantics(m,T??{}),v(m)},firstResultRejector:u})})}async*sendMessageStream(t,e){if(!this.agentCard.capabilities?.streaming)throw new St("Streaming is not supported.");let r=t.message;if(!r?.messageId)throw new F("message.messageId is required for streaming.");let i=new Yt(this.taskStore,e);i.setContext(r);let a=await this._createRequestContext(t,e),n=a.taskId,o=this.eventBusManager.createOrGetByTaskId(n,e),l=new bt(o);if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let S=structuredClone(t.configuration.taskPushNotificationConfig);S.taskId=n,await this.pushNotificationStore?.save(n,e,S)}this._runStreamExecutor(n,o,a);let c="undetermined";try{for await(let S of l.events()){c=this._advanceStreamPattern(S,c),await i.processEvent(S);let T=await this._mapEventToStreamResponse(S,e);T.payload?.$case==="task"&&this._applyHistoryLengthSemantics(T.payload.value,t.configuration??{}),await this._sendPushNotificationIfNeeded(e,T,i.getCurrentTask()),yield T}}finally{l.stop()}}async getTask(t,e){let r=t.id;this._requireValidTaskId(r);let i=await this.taskStore.load(r,e);if(!i)throw new V(`Task not found: ${t.id}`);return this._applyHistoryLengthSemantics(i,t),i}async listTasks(t,e){let r=t.pageSize??ci;if(!Number.isInteger(r)||r<1||r>100)throw new F("pageSize must be between 1 and 100");if(t.status!==void 0&&!os.includes(t.status))throw new F(`Invalid status filter: ${String(t.status)}`);if(t.statusTimestampAfter&&isNaN(Date.parse(t.statusTimestampAfter)))throw new F("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 V(`Task not found: ${t.id}`);let a=i.status?.state;if(a===5)return i;if(a!==void 0&&Dt.includes(a))throw new Re(`Task not cancelable: ${t.id}`);let n=this.eventBusManager.getByTaskId(r,e);if(n){let l=new bt(n);await this.agentExecutor.cancelTask(r,n),await this._processEvents(r,new Yt(this.taskStore,e),l,e)}else{let l={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 Yt(this.taskStore,e).processEvent(x.statusUpdate({taskId:i.id,contextId:i.contextId,status:{state:5,message:l,timestamp:new Date().toISOString()},metadata:{}}))}let o=await this.taskStore.load(r,e);if(!o)throw new Wt(`Task ${t.id} not found after cancellation.`);if(o.status.state!=5)throw new Re(`Task not cancelable: ${t.id}`);return o}async createTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`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 Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`Task not found: ${r}`);let a=await this.pushNotificationStore?.load(r,e)||[];if(a.length===0)throw new V(`Push notification config not found for task ${r}.`);let n=a.find(o=>o.id===t.id);if(!n)throw new V(`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 Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`Task not found: ${r}`);return{configs:await this.pushNotificationStore?.load(r,e)||[],nextPageToken:""}}async deleteTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`Task not found: ${r}`);await this.pushNotificationStore?.delete(r,e,t.id)}async*resubscribe(t,e){if(!this.agentCard.capabilities?.streaming)throw new St("Streaming (and thus resubscription) is not supported.");let r=t.id;this._requireValidTaskId(r);let i=this.eventBusManager.getByTaskId(r,e),a=i?new bt(i):void 0;try{let n=await this.taskStore.load(r,e);if(!n)throw new V(`Task not found: ${r}`);if(n.status?.state!==void 0&&Dt.includes(n.status.state))throw new St(`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:Ie(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:Ie(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 l={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(x.statusUpdate(l))}catch(c){console.error(`Event processing loop failed for task ${i}: ${c instanceof Error&&c.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 St(`Received ${t.kind} before initial 'Message'/'Task' event.`);case"message-only":throw new St(`Received ${t.kind} after message-only response.`);case"task-lifecycle":if(t.kind!=="statusUpdate"&&t.kind!=="artifactUpdate")throw new St(`Stream ordering violation: received ${t.kind} in task lifecycle stream.`);return e}}_requireValidTaskId(t){if(!t||t.trim()==="")throw new F("Task ID is required")}_applyHistoryLengthSemantics(t,e){e.historyLength!==void 0&&(e.historyLength<=0?t.history=[]:t.history=(t.history??[]).slice(-e.historyLength))}};function hs(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 Ss(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 Si=class{_scopedStore;constructor(t=Ce){this._scopedStore=new Ue(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=ci,pageToken:n,statusTimestampAfter:o,includeArtifacts:l=!1}=t,c=this._scopedStore.getBucket(e),S=c?Array.from(c.values()):[];if(r&&(S=S.filter(p=>p.contextId===r)),i!==void 0&&i!==0&&(S=S.filter(p=>p.status?.state===i)),o){let p=new Date(o).getTime();S=S.filter(N=>N.status?.timestamp&&new Date(N.status.timestamp).getTime()>p)}S.sort((p,N)=>{let y=p.status?.timestamp||"",C=N.status?.timestamp||"";return C!==y?C.localeCompare(y):N.id.localeCompare(p.id)});let T=S.length;if(n){let p=us(n),N=S.findIndex(y=>(y.status?.timestamp||"")===p.timestamp&&y.id===p.id);N!==-1?S=S.slice(N+1):S=[]}let v=S.slice(0,a),u=v.map(p=>{let N=structuredClone(p);return l||(N.artifacts=[]),N}),m="";if(v.length>0&&S.length>v.length){let p=v[v.length-1];m=ls(p.status?.timestamp||"",p.id)}return{tasks:u,nextPageToken:m,pageSize:a,totalSize:T}}};var ir=Nt(Et(),1);var wa=Nt(Et(),1),xa=Nt(Et(),1),cr=Nt(Et(),1),fr=Nt(Et(),1);import rd from"crypto";import id from"crypto";var Ts=class{get isAuthenticated(){return!1}get userName(){return""}},pr={noAuthentication:()=>Promise.resolve(new Ts)};async function*hr(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 Sr(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 Wi(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 gs(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 ms(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var Ti={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}},b={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)?re.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>ae.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>Y.fromJSON(e)):[],metadata:w(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=re.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>ae.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>Y.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},re={fromJSON(t){return{state:s(t.state)?Sr(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=Wi(t.state)),t.message!==void 0&&(e.message=Y.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},ie={fromJSON(t){return{content:s(t.text)?{$case:"text",value:globalThis.String(t.text)}:s(t.raw)?{$case:"raw",value:Buffer.from(Rs(t.raw))}:s(t.url)?{$case:"url",value:globalThis.String(t.url)}:s(t.data)?{$case:"data",value:t.data}:void 0,metadata:w(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=Cs(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)?gs(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>ie.fromJSON(e)):[],metadata:w(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=ms(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>ie.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}},ae={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=>ie.fromJSON(e)):[],metadata:w(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=>ie.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},we={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)?re.fromJSON(t.status):void 0,metadata:w(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=re.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},xe={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)?ae.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:w(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=ae.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}},gi={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}},Pe={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}},Xi={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=>Pe.fromJSON(e)):globalThis.Array.isArray(t?.supported_interfaces)?t.supported_interfaces.map(e=>Pe.fromJSON(e)):[],provider:s(t.provider)?mi.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)?Ni.fromJSON(t.capabilities):void 0,securitySchemes:w(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=De.fromJSON(i),e),{}):w(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=De.fromJSON(i),e),{}):{},securityRequirements:globalThis.Array.isArray(t?.securityRequirements)?t.securityRequirements.map(e=>yt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>yt.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=>Oi.fromJSON(e)):[],signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>vi.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=>Pe.toJSON(r))),t.provider!==void 0&&(e.provider=mi.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==void 0&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=Ni.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=De.toJSON(n)}),e.securitySchemes=i}}return t.securityRequirements?.length&&(e.securityRequirements=t.securityRequirements.map(r=>yt.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=>Oi.toJSON(r))),t.signatures?.length&&(e.signatures=t.signatures.map(r=>vi.toJSON(r))),t.iconUrl!==void 0&&(e.iconUrl=t.iconUrl),e}},mi={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}},Ni={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=>Ei.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=>Ei.toJSON(r))),t.extendedAgentCard!==void 0&&(e.extendedAgentCard=t.extendedAgentCard),e}},Ei={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:w(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}},Oi={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=>yt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>yt.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=>yt.toJSON(r))),e}},vi={fromJSON(t){return{protected:s(t.protected)?globalThis.String(t.protected):"",signature:s(t.signature)?globalThis.String(t.signature):"",header:w(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)?gi.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=gi.toJSON(t.authentication)),e}},_i={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}},yt={fromJSON(t){return{schemes:w(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=_i.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]=_i.toJSON(n)}),e.schemes=i}}return e}},De={fromJSON(t){return{scheme:s(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:Me.fromJSON(t.apiKeySecurityScheme)}:s(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:Me.fromJSON(t.api_key_security_scheme)}:s(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:Le.fromJSON(t.httpAuthSecurityScheme)}:s(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:Le.fromJSON(t.http_auth_security_scheme)}:s(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:$e.fromJSON(t.oauth2SecurityScheme)}:s(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:$e.fromJSON(t.oauth2_security_scheme)}:s(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:qe.fromJSON(t.openIdConnectSecurityScheme)}:s(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:qe.fromJSON(t.open_id_connect_security_scheme)}:s(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:ze.fromJSON(t.mtlsSecurityScheme)}:s(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:ze.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=Me.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=Le.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=$e.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=qe.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=ze.toJSON(t.scheme.value)),e}},Me={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}},Le={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}},$e={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",flows:s(t.flows)?yi.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=yi.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},qe={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}},ze={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},yi={fromJSON(t){return{flow:s(t.authorizationCode)?{$case:"authorizationCode",value:Fe.fromJSON(t.authorizationCode)}:s(t.authorization_code)?{$case:"authorizationCode",value:Fe.fromJSON(t.authorization_code)}:s(t.clientCredentials)?{$case:"clientCredentials",value:Be.fromJSON(t.clientCredentials)}:s(t.client_credentials)?{$case:"clientCredentials",value:Be.fromJSON(t.client_credentials)}:s(t.implicit)?{$case:"implicit",value:Ai.fromJSON(t.implicit)}:s(t.password)?{$case:"password",value:ki.fromJSON(t.password)}:s(t.deviceCode)?{$case:"deviceCode",value:He.fromJSON(t.deviceCode)}:s(t.device_code)?{$case:"deviceCode",value:He.fromJSON(t.device_code)}:void 0}},toJSON(t){let e={};return t.flow?.$case==="authorizationCode"?e.authorizationCode=Fe.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=Be.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=Ai.toJSON(t.flow.value):t.flow?.$case==="password"?e.password=ki.toJSON(t.flow.value):t.flow?.$case==="deviceCode"&&(e.deviceCode=He.toJSON(t.flow.value)),e}},Fe={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:w(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}},Be={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:w(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}},Ai={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:w(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}},ki={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:w(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}},He={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:w(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}},ne={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)?Ti.fromJSON(t.configuration):void 0,metadata:w(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=Ti.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Ns={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}},Es={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)?Sr(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=Wi(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=>b.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=>b.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}},Os={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):"",metadata:w(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}},vs={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}},_s={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}},ys={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}},As={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}},ks={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),e}},Is={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:b.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=b.toJSON(t.payload.value):t.payload?.$case==="message"&&(e.message=Y.toJSON(t.payload.value)),e}},ar={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:b.fromJSON(t.task)}:s(t.message)?{$case:"message",value:Y.fromJSON(t.message)}:s(t.statusUpdate)?{$case:"statusUpdate",value:we.fromJSON(t.statusUpdate)}:s(t.status_update)?{$case:"statusUpdate",value:we.fromJSON(t.status_update)}:s(t.artifactUpdate)?{$case:"artifactUpdate",value:xe.fromJSON(t.artifactUpdate)}:s(t.artifact_update)?{$case:"artifactUpdate",value:xe.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=b.toJSON(t.payload.value):t.payload?.$case==="message"?e.message=Y.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=we.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=xe.toJSON(t.payload.value)),e}},ji={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 Rs(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Cs(t){return globalThis.Buffer.from(t).toString("base64")}function w(t){return typeof t=="object"&&t!==null}function s(t){return t!=null}var At="A2A-Extensions",nt="A2A-Version",Us="1.0",Ut="0.3",Tr="application/json",nr="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(",")},se={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"};function gt(t){return`data: ${JSON.stringify(t)}
|
|
4
|
+
import{a as Et,b as Qr,g as Yr}from"./chunk-IWMCIYOG.js";import{b as Fr,c as Br,d as Hr,e as Vr}from"./chunk-5URXBVET.js";import{p as Kr,s as Gr,u as br}from"./chunk-COHBT6M7.js";import"./chunk-5DK2M7VI.js";import{h as zr}from"./chunk-4CLD7LEU.js";import"./chunk-CW5XFH7H.js";import"./chunk-AZQD75PX.js";import"./chunk-MQAQBW7F.js";import"./chunk-WGFROGUC.js";import"./chunk-VU3JWAJR.js";import"./chunk-BDLFNDC4.js";import{r as Oe}from"./chunk-OI2W6R6H.js";import"./chunk-JFKC4VCA.js";import"./chunk-KJJYW5IY.js";import"./chunk-I74AL3PF.js";import"./chunk-LCWNSYZU.js";import{a as qr}from"./chunk-SZXXASVH.js";import{C as R}from"./chunk-W4GMCNWF.js";import"./chunk-VM4YKTHC.js";import"./chunk-HMZQYFYG.js";import"./chunk-3QL446GD.js";import"./chunk-AGSYLE4E.js";import"./chunk-CU3IISCC.js";import"./chunk-VCIRD267.js";import{d as Gt,e as Nt}from"./chunk-7MKA3SHV.js";var On={};Gt(On,{parseA2aAddress:()=>Nn,runA2aServer:()=>$r,startA2aServer:()=>En});import{createServer as hl}from"http";var vn=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}},x={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 Ie(t){throw new Error(`Unhandled event kind: ${t.kind}`)}var ei=typeof CustomEvent<"u"?CustomEvent:class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail??null}};function Wr(t){return t instanceof ei}var _n=class extends EventTarget{eventListeners=new Map;finishedListeners=new Map;publish(t){this.dispatchEvent(new ei("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(!Wr(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(!Wr(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})}},yn={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(",")},An="0.3";var kn=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||An,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=yn.createFrom(this._activatedExtensions,t)}setRequestedExtensions(t){this._requestedExtensions=t}};function Ce(t){return t.user?.userName||"unknown"}var In="a2a-protocol.org",Rn="type.googleapis.com/google.rpc.ErrorInfo",ri=Symbol.for("@a2a-js/sdk.A2AError"),Wt=class ii extends Error{reason="INTERNAL_ERROR";metadata;static[Symbol.hasInstance](e){if(typeof e!="object"||e===null||!(ri in e))return!1;if(this===ii)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":Rn,reason:this.reason,domain:In,...this.metadata?{metadata:this.metadata}:{}}}};Object.defineProperty(Wt.prototype,ri,{value:!0});var ai=[{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"}],et=Object.freeze(Object.fromEntries(ai.map(t=>[t.name,t]))),Ol=Object.freeze(Object.fromEntries(ai.map(t=>[t.reason,t])));function rt(t){return{[t.name]:class extends Wt{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 V=rt(et.TaskNotFoundError),Re=rt(et.TaskNotCancelableError),Pt=rt(et.PushNotificationNotSupportedError),St=rt(et.UnsupportedOperationError),ni=rt(et.ContentTypeNotSupportedError),Cn=rt(et.InvalidAgentResponseError),si=rt(et.ExtendedAgentCardNotConfiguredError),oi=rt(et.ExtensionSupportRequiredError),Un=rt(et.VersionNotSupportedError),F=rt(et.RequestMalformedError),di=Object.freeze({TaskNotFoundError:V,TaskNotCancelableError:Re,PushNotificationNotSupportedError:Pt,UnsupportedOperationError:St,ContentTypeNotSupportedError:ni,InvalidAgentResponseError:Cn,ExtendedAgentCardNotConfiguredError:si,ExtensionSupportRequiredError:oi,VersionNotSupportedError:Un,RequestMalformedError:F});function Xr(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},tt={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"},Jn=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}),vl=Object.freeze({TaskNotFoundError:tt.NOT_FOUND,TaskNotCancelableError:tt.FAILED_PRECONDITION,PushNotificationNotSupportedError:tt.FAILED_PRECONDITION,UnsupportedOperationError:tt.FAILED_PRECONDITION,ContentTypeNotSupportedError:tt.INVALID_ARGUMENT,InvalidAgentResponseError:tt.INTERNAL,ExtendedAgentCardNotConfiguredError:tt.FAILED_PRECONDITION,ExtensionSupportRequiredError:tt.FAILED_PRECONDITION,VersionNotSupportedError:tt.FAILED_PRECONDITION,RequestMalformedError:tt.INVALID_ARGUMENT});function it(t){let e=di[t],r=Jn[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 wn=it("TaskNotFoundError"),xn=it("TaskNotCancelableError"),Pn=it("PushNotificationNotSupportedError"),Dn=it("UnsupportedOperationError"),Mn=it("ContentTypeNotSupportedError"),Ln=it("InvalidAgentResponseError"),$n=it("ExtendedAgentCardNotConfiguredError"),qn=it("ExtensionSupportRequiredError"),zn=it("VersionNotSupportedError"),Fn=it("RequestMalformedError"),_l=Object.freeze({TaskNotFoundError:wn,TaskNotCancelableError:xn,PushNotificationNotSupportedError:Pn,UnsupportedOperationError:Dn,ContentTypeNotSupportedError:Mn,InvalidAgentResponseError:Ln,ExtendedAgentCardNotConfiguredError:$n,ExtensionSupportRequiredError:qn,VersionNotSupportedError:zn,RequestMalformedError:Fn}),L={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},li=Object.freeze({TaskNotFoundError:L.TASK_NOT_FOUND,TaskNotCancelableError:L.TASK_NOT_CANCELABLE,PushNotificationNotSupportedError:L.PUSH_NOTIFICATION_NOT_SUPPORTED,UnsupportedOperationError:L.UNSUPPORTED_OPERATION,ContentTypeNotSupportedError:L.CONTENT_TYPE_NOT_SUPPORTED,InvalidAgentResponseError:L.INVALID_AGENT_RESPONSE,ExtendedAgentCardNotConfiguredError:L.EXTENDED_CARD_NOT_CONFIGURED,ExtensionSupportRequiredError:L.EXTENSION_SUPPORT_REQUIRED,VersionNotSupportedError:L.VERSION_NOT_SUPPORTED,RequestMalformedError:L.INVALID_PARAMS}),yl=Object.freeze(Object.fromEntries(Object.entries(li).map(([t,e])=>[e,t])));function at(t){let e=di[t],r=li[t]??L.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 Bn=at("TaskNotFoundError"),Hn=at("TaskNotCancelableError"),Vn=at("PushNotificationNotSupportedError"),Kn=at("UnsupportedOperationError"),Gn=at("ContentTypeNotSupportedError"),bn=at("InvalidAgentResponseError"),Qn=at("ExtendedAgentCardNotConfiguredError"),Yn=at("ExtensionSupportRequiredError"),Wn=at("VersionNotSupportedError"),Xn=at("RequestMalformedError"),Al=Object.freeze({TaskNotFoundError:Bn,TaskNotCancelableError:Hn,PushNotificationNotSupportedError:Vn,UnsupportedOperationError:Kn,ContentTypeNotSupportedError:Gn,InvalidAgentResponseError:bn,ExtendedAgentCardNotConfiguredError:Qn,ExtensionSupportRequiredError:Yn,VersionNotSupportedError:Wn,RequestMalformedError:Xn});var kl={[L.PARSE_ERROR]:"RequestMalformedError",[L.INVALID_REQUEST]:"RequestMalformedError",[L.METHOD_NOT_FOUND]:"RequestMalformedError"};function Zn(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 jn(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 ts(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 es(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:_(t.id)?globalThis.String(t.id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",status:_(t.status)?Xt.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>jt.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>Ot.fromJSON(e)):[],metadata:vt(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=Xt.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>jt.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>Ot.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Xt={fromJSON(t){return{state:_(t.state)?Zn(t.state):0,message:_(t.message)?Ot.fromJSON(t.message):void 0,timestamp:_(t.timestamp)?globalThis.String(t.timestamp):void 0}},toJSON(t){let e={};return t.state!==0&&(e.state=jn(t.state)),t.message!==void 0&&(e.message=Ot.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},Zt={fromJSON(t){return{content:_(t.text)?{$case:"text",value:globalThis.String(t.text)}:_(t.raw)?{$case:"raw",value:Buffer.from(is(t.raw))}:_(t.url)?{$case:"url",value:globalThis.String(t.url)}:_(t.data)?{$case:"data",value:t.data}:void 0,metadata:vt(t.metadata)?t.metadata:void 0,filename:_(t.filename)?globalThis.String(t.filename):"",mediaType:_(t.mediaType)?globalThis.String(t.mediaType):_(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=as(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}},Ot={fromJSON(t){return{messageId:_(t.messageId)?globalThis.String(t.messageId):_(t.message_id)?globalThis.String(t.message_id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",taskId:_(t.taskId)?globalThis.String(t.taskId):_(t.task_id)?globalThis.String(t.task_id):"",role:_(t.role)?ts(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Zt.fromJSON(e)):[],metadata:vt(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=es(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>Zt.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}},jt={fromJSON(t){return{artifactId:_(t.artifactId)?globalThis.String(t.artifactId):_(t.artifact_id)?globalThis.String(t.artifact_id):"",name:_(t.name)?globalThis.String(t.name):"",description:_(t.description)?globalThis.String(t.description):"",parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>Zt.fromJSON(e)):[],metadata:vt(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=>Zt.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},ve={fromJSON(t){return{taskId:_(t.taskId)?globalThis.String(t.taskId):_(t.task_id)?globalThis.String(t.task_id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",status:_(t.status)?Xt.fromJSON(t.status):void 0,metadata:vt(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=Xt.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},_e={fromJSON(t){return{taskId:_(t.taskId)?globalThis.String(t.taskId):_(t.task_id)?globalThis.String(t.task_id):"",contextId:_(t.contextId)?globalThis.String(t.contextId):_(t.context_id)?globalThis.String(t.context_id):"",artifact:_(t.artifact)?jt.fromJSON(t.artifact):void 0,append:_(t.append)?globalThis.Boolean(t.append):!1,lastChunk:_(t.lastChunk)?globalThis.Boolean(t.lastChunk):_(t.last_chunk)?globalThis.Boolean(t.last_chunk):!1,metadata:vt(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=jt.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 rs={fromJSON(t){return{payload:_(t.task)?{$case:"task",value:Zr.fromJSON(t.task)}:_(t.message)?{$case:"message",value:Ot.fromJSON(t.message)}:_(t.statusUpdate)?{$case:"statusUpdate",value:ve.fromJSON(t.statusUpdate)}:_(t.status_update)?{$case:"statusUpdate",value:ve.fromJSON(t.status_update)}:_(t.artifactUpdate)?{$case:"artifactUpdate",value:_e.fromJSON(t.artifactUpdate)}:_(t.artifact_update)?{$case:"artifactUpdate",value:_e.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=Ot.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=ve.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=_e.toJSON(t.payload.value)),e}};function is(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function as(t){return globalThis.Buffer.from(t).toString("base64")}function vt(t){return typeof t=="object"&&t!==null}function _(t){return t!=null}var ns="1.0",ui="0.3",ss="application/a2a+json",ci=50,Il=4*1024*1024,Dt=[3,4,5,7],os=[0,1,2,3,4,5,6,7,8],fi=[6],pi=[8],ds=[...fi,...pi];function jr(t){return"status"in t}function ti(t,e){return{tenant:t.tenant??"",owner:e(t)}}function ls(t,e){return Buffer.from(`${t}|${e}`).toString("base64")}function us(t){try{let[e,...r]=Buffer.from(t,"base64").toString("utf-8").split("|");if(r.length===0)throw new F("Invalid page token format.");return{timestamp:e,id:r.join("|")}}catch(e){throw e instanceof F?e:new F("Token is not a valid base64-encoded cursor.")}}var Ue=class{_store=new Map;_ownerResolver;constructor(t){this._ownerResolver=t}getBucket(t){let{tenant:e,owner:r}=ti(t,this._ownerResolver);return this._store.get(e)?.get(r)}getOrCreateBucket(t){let{tenant:e,owner:r}=ti(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}},ye=new kn,Je=class{_scopedBuses;constructor(t=Ce){this._scopedBuses=new Ue(t)}createOrGetByTaskId(t,e){let r=this._scopedBuses.getOrCreateBucket(e??ye),i=r.get(t);return i||(i=new _n,r.set(t,i)),i}getByTaskId(t,e){return this._scopedBuses.getBucket(e??ye)?.get(t)}cleanupByTaskId(t,e){let r=this._scopedBuses.getBucket(e??ye);r?.get(t)?.removeAllListeners(),r?.delete(t)}},bt=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&&(Dt.includes(t.data.status.state)||fi.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)}},Qt=new Map;function Ae(t,e){let r=t.tenant??"",i=t.user?.userName??"";return`${r}\0${i}\0${e}`}async function ke(t,e){let i=(Qt.get(t)??Promise.resolve()).then(e,e);Qt.set(t,i);let a=()=>{Qt.get(t)===i&&Qt.delete(t)};return i.then(a,a),i}var Yt=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 ke(Ae(this.serverCallContext,e.id),()=>this.processTaskEventLocked(e));break}case"statusUpdate":{let e=t.data;if(!e.taskId){await this.applyStatusUpdate(e);break}await ke(Ae(this.serverCallContext,e.taskId),()=>this.applyStatusUpdate(e));break}case"artifactUpdate":{let e=t.data;if(!e.taskId){await this.applyArtifactUpdate(e);break}await ke(Ae(this.serverCallContext,e.taskId),()=>this.applyArtifactUpdate(e));break}default:Ie(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&&Dt.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}},cs=class{_scopedStore;constructor(t=Ce){this._scopedStore=new Ue(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||ui,o=a.findIndex(l=>l.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)}},fs=class{serialize(t,e){return{body:JSON.stringify(rs.toJSON(t)),contentType:ss}}},ps=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 fs;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 l=a.map(async c=>{try{await this._dispatchNotification(t,c,i,r)}catch(S){console.error(`Error sending push notification for task_id=${i} to URL: ${c.config.url}. Error:`,S)}});await Promise.all(l)});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||ui;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 '${ns}'. 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,l=new AbortController,c=setTimeout(()=>l.abort(),this.options.timeout);try{let S=this._resolveSerializer(n),{body:T,contentType:v}=S.serialize(t,i),u=await fetch(o,{method:"POST",headers:{"Content-Type":v,...this._buildAuthHeaders(a)},body:T,signal:l.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(c)}}},hi=class{agentCard;taskStore;agentExecutor;eventBusManager;pushNotificationStore;pushNotificationSender;extendedAgentCardProvider;agentCardSignatureGenerator;keepBusAliveStates;validateInputModes;constructor(t,e,r,i=new Je,a,n,o,l,c={}){this.agentCard=t,this.taskStore=e,this.agentExecutor=r,this.eventBusManager=i,this.extendedAgentCardProvider=o,this.agentCardSignatureGenerator=l,this.keepBusAliveStates=new Set(c.keepBusAliveStates??ds),this.validateInputModes=c.validateInputModes??!1,t.capabilities?.pushNotifications&&(this.pushNotificationStore=a||new cs,this.pushNotificationSender=n||new ps(this.pushNotificationStore))}async getAgentCard(){return this.agentCardSignatureGenerator?this.agentCardSignatureGenerator(this.agentCard):this.agentCard}async getAuthenticatedExtendedAgentCard(t,e){if(!this.agentCard.capabilities?.extendedAgentCard)throw new St("Agent does not support authenticated extended card.");if(!this.extendedAgentCardProvider)throw new si;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 ni(`Media type '${i.mediaType}' is not supported. Supported media types: ${r.join(", ")}.`)}}async _createRequestContext(t,e){let r=t.message;if(!r)throw new F("request.message is required.");let i,a,n=await this.getAgentCard();this._validateInputModes(r,n);let o=n.capabilities?.extensions??[],l=new Set(e.requestedExtensions??[]),c=o.filter(p=>p.required&&!l.has(p.uri)).map(p=>p.uri);if(c.length>0)throw new oi(`Client must declare support for required extensions: ${c.join(", ")}`);if(r.taskId){if(this._requireValidTaskId(r.taskId),i=await this.taskStore.load(r.taskId,e),!i)throw new V(`Task not found: ${r.taskId}`);if(i.status?.state!==void 0&&Dt.includes(i.status.state))throw new St(`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 F(`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 S=r.taskId||crypto.randomUUID(),T=r.referenceTaskIds||[];if(T.length>0){a=[];for(let p of T){let N=await this.taskStore.load(p,e);N?a.push(N):console.warn(`Reference task ${p} not found.`)}}let v=r.contextId||i?.contextId||crypto.randomUUID();if(e.requestedExtensions){let p=new Set(o.map(N=>N.uri));e.setRequestedExtensions(e.requestedExtensions.filter(N=>p.has(N)))}let u={...r,contextId:v,taskId:S},m={...t,message:u};return new vn(m,S,v,e,i,a)}async _processEvents(t,e,r,i,a){let n=!1,o=!1;try{for await(let l of r.events()){await e.processEvent(l);try{let c=await this._mapEventToStreamResponse(l,i);await this._sendPushNotificationIfNeeded(i,c,structuredClone(e.getCurrentTask()))}catch(c){console.error(`Error sending push notification: ${c}`)}if(a?.firstResultResolver&&!n){let c;if(l.kind==="message")c=l.data;else if(l.kind==="task")c=l.data;else{let S=e.getFinalResult();S&&("messageId"in S||"id"in S)&&(c=S)}c&&(a.firstResultResolver(c),n=!0)}if(a?.authRequiredSnapshotResolver&&!o&&l.kind==="statusUpdate"&&l.data.status&&pi.includes(l.data.status.state)){let c=e.getCurrentTask();c&&(a.authRequiredSnapshotResolver(structuredClone(c)),o=!0,n=!0)}}a?.firstResultResolver&&a?.firstResultRejector&&!n&&a.firstResultRejector(new F("Execution finished before a message or task was produced."))}catch(l){console.error(`Event processing loop failed for task ${t}:`,l),await this._handleProcessingError(l,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=hs(e);this.agentExecutor.execute(r,e).catch(n=>{let o=Xr(n);console.error(`Agent execution failed for message ${i.messageId}:`,n);let l={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&&!l.history?.find(c=>c.messageId===i.messageId)&&l.history?.push(i),e.publish(x.task(l)),e.publish(x.statusUpdate({taskId:l.id,contextId:l.contextId,status:l.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=Ss(e);this.agentExecutor.execute(r,e).catch(n=>{let o=Xr(n);console.error(`Agent execution failed for stream message ${i.messageId}:`,n);let l=a().task,c=l?.id??r.taskId,S=l?.contextId??i.contextId;if(!l){let v={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&&!v.history?.find(u=>u.messageId===i.messageId)&&v.history?.push(i),e.publish(x.task(v))}let T={taskId:c,contextId:S,status:{state:4,message:{role:2,messageId:crypto.randomUUID(),taskId:c,contextId:S,parts:[{content:{$case:"text",value:`Agent execution error: ${o}`},mediaType:"text/plain",filename:"",metadata:{}}],metadata:{},extensions:[],referenceTaskIds:[]},timestamp:new Date().toISOString()},metadata:{}};e.publish(x.statusUpdate(T))}).finally(()=>{this._settleBus(t,e,a().state,r.context)})}async sendMessage(t,e){let r=t.message;if(!r?.messageId)throw new F("message.messageId is required.");let i=t.configuration?.returnImmediately!==!0,a=new Yt(this.taskStore,e);a.setContext(r);let n=await this._createRequestContext(t,e),o=n.taskId,l=n.userMessage;if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let v=structuredClone(t.configuration.taskPushNotificationConfig);v.taskId=o,await this.pushNotificationStore?.save(o,e,v)}let c=this.eventBusManager.createOrGetByTaskId(o,e),S=new bt(c);this._runExecutor(o,c,n,l);let T=t.configuration;return i?new Promise((v,u)=>{let m=this._processEvents(o,a,S,e,{authRequiredSnapshotResolver:p=>{this._applyHistoryLengthSemantics(p,T??{}),v(p),this._continueDraining(o,m)},firstResultRejector:u});m.then(()=>{let p=a.getFinalResult();if(!p){u(new Wt("Agent execution finished without a result, and no task context found."));return}jr(p)&&this._applyHistoryLengthSemantics(p,T??{}),v(p)}).catch(u)}):new Promise((v,u)=>{this._processEvents(o,a,S,e,{firstResultResolver:m=>{jr(m)&&this._applyHistoryLengthSemantics(m,T??{}),v(m)},firstResultRejector:u})})}async*sendMessageStream(t,e){if(!this.agentCard.capabilities?.streaming)throw new St("Streaming is not supported.");let r=t.message;if(!r?.messageId)throw new F("message.messageId is required for streaming.");let i=new Yt(this.taskStore,e);i.setContext(r);let a=await this._createRequestContext(t,e),n=a.taskId,o=this.eventBusManager.createOrGetByTaskId(n,e),l=new bt(o);if(t.configuration?.taskPushNotificationConfig&&this.agentCard.capabilities?.pushNotifications){let S=structuredClone(t.configuration.taskPushNotificationConfig);S.taskId=n,await this.pushNotificationStore?.save(n,e,S)}this._runStreamExecutor(n,o,a);let c="undetermined";try{for await(let S of l.events()){c=this._advanceStreamPattern(S,c),await i.processEvent(S);let T=await this._mapEventToStreamResponse(S,e);T.payload?.$case==="task"&&this._applyHistoryLengthSemantics(T.payload.value,t.configuration??{}),await this._sendPushNotificationIfNeeded(e,T,i.getCurrentTask()),yield T}}finally{l.stop()}}async getTask(t,e){let r=t.id;this._requireValidTaskId(r);let i=await this.taskStore.load(r,e);if(!i)throw new V(`Task not found: ${t.id}`);return this._applyHistoryLengthSemantics(i,t),i}async listTasks(t,e){let r=t.pageSize??ci;if(!Number.isInteger(r)||r<1||r>100)throw new F("pageSize must be between 1 and 100");if(t.status!==void 0&&!os.includes(t.status))throw new F(`Invalid status filter: ${String(t.status)}`);if(t.statusTimestampAfter&&isNaN(Date.parse(t.statusTimestampAfter)))throw new F("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 V(`Task not found: ${t.id}`);let a=i.status?.state;if(a===5)return i;if(a!==void 0&&Dt.includes(a))throw new Re(`Task not cancelable: ${t.id}`);let n=this.eventBusManager.getByTaskId(r,e);if(n){let l=new bt(n);await this.agentExecutor.cancelTask(r,n),await this._processEvents(r,new Yt(this.taskStore,e),l,e)}else{let l={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 Yt(this.taskStore,e).processEvent(x.statusUpdate({taskId:i.id,contextId:i.contextId,status:{state:5,message:l,timestamp:new Date().toISOString()},metadata:{}}))}let o=await this.taskStore.load(r,e);if(!o)throw new Wt(`Task ${t.id} not found after cancellation.`);if(o.status.state!=5)throw new Re(`Task not cancelable: ${t.id}`);return o}async createTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`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 Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`Task not found: ${r}`);let a=await this.pushNotificationStore?.load(r,e)||[];if(a.length===0)throw new V(`Push notification config not found for task ${r}.`);let n=a.find(o=>o.id===t.id);if(!n)throw new V(`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 Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`Task not found: ${r}`);return{configs:await this.pushNotificationStore?.load(r,e)||[],nextPageToken:""}}async deleteTaskPushNotificationConfig(t,e){if(!this.agentCard.capabilities?.pushNotifications)throw new Pt;let r=t.taskId;if(this._requireValidTaskId(r),!await this.taskStore.load(r,e))throw new V(`Task not found: ${r}`);await this.pushNotificationStore?.delete(r,e,t.id)}async*resubscribe(t,e){if(!this.agentCard.capabilities?.streaming)throw new St("Streaming (and thus resubscription) is not supported.");let r=t.id;this._requireValidTaskId(r);let i=this.eventBusManager.getByTaskId(r,e),a=i?new bt(i):void 0;try{let n=await this.taskStore.load(r,e);if(!n)throw new V(`Task not found: ${r}`);if(n.status?.state!==void 0&&Dt.includes(n.status.state))throw new St(`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:Ie(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:Ie(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 l={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(x.statusUpdate(l))}catch(c){console.error(`Event processing loop failed for task ${i}: ${c instanceof Error&&c.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 St(`Received ${t.kind} before initial 'Message'/'Task' event.`);case"message-only":throw new St(`Received ${t.kind} after message-only response.`);case"task-lifecycle":if(t.kind!=="statusUpdate"&&t.kind!=="artifactUpdate")throw new St(`Stream ordering violation: received ${t.kind} in task lifecycle stream.`);return e}}_requireValidTaskId(t){if(!t||t.trim()==="")throw new F("Task ID is required")}_applyHistoryLengthSemantics(t,e){e.historyLength!==void 0&&(e.historyLength<=0?t.history=[]:t.history=(t.history??[]).slice(-e.historyLength))}};function hs(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 Ss(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 Si=class{_scopedStore;constructor(t=Ce){this._scopedStore=new Ue(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=ci,pageToken:n,statusTimestampAfter:o,includeArtifacts:l=!1}=t,c=this._scopedStore.getBucket(e),S=c?Array.from(c.values()):[];if(r&&(S=S.filter(p=>p.contextId===r)),i!==void 0&&i!==0&&(S=S.filter(p=>p.status?.state===i)),o){let p=new Date(o).getTime();S=S.filter(N=>N.status?.timestamp&&new Date(N.status.timestamp).getTime()>p)}S.sort((p,N)=>{let y=p.status?.timestamp||"",C=N.status?.timestamp||"";return C!==y?C.localeCompare(y):N.id.localeCompare(p.id)});let T=S.length;if(n){let p=us(n),N=S.findIndex(y=>(y.status?.timestamp||"")===p.timestamp&&y.id===p.id);N!==-1?S=S.slice(N+1):S=[]}let v=S.slice(0,a),u=v.map(p=>{let N=structuredClone(p);return l||(N.artifacts=[]),N}),m="";if(v.length>0&&S.length>v.length){let p=v[v.length-1];m=ls(p.status?.timestamp||"",p.id)}return{tasks:u,nextPageToken:m,pageSize:a,totalSize:T}}};var ir=Nt(Et(),1);var wa=Nt(Et(),1),xa=Nt(Et(),1),cr=Nt(Et(),1),fr=Nt(Et(),1);import rd from"crypto";import id from"crypto";var Ts=class{get isAuthenticated(){return!1}get userName(){return""}},pr={noAuthentication:()=>Promise.resolve(new Ts)};async function*hr(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 Sr(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 Wi(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 gs(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 ms(t){switch(t){case 0:return"ROLE_UNSPECIFIED";case 1:return"ROLE_USER";case 2:return"ROLE_AGENT";default:return"UNRECOGNIZED"}}var Ti={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}},b={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)?re.fromJSON(t.status):void 0,artifacts:globalThis.Array.isArray(t?.artifacts)?t.artifacts.map(e=>ae.fromJSON(e)):[],history:globalThis.Array.isArray(t?.history)?t.history.map(e=>Y.fromJSON(e)):[],metadata:w(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=re.toJSON(t.status)),t.artifacts?.length&&(e.artifacts=t.artifacts.map(r=>ae.toJSON(r))),t.history?.length&&(e.history=t.history.map(r=>Y.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),e}},re={fromJSON(t){return{state:s(t.state)?Sr(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=Wi(t.state)),t.message!==void 0&&(e.message=Y.toJSON(t.message)),t.timestamp!==void 0&&(e.timestamp=t.timestamp),e}},ie={fromJSON(t){return{content:s(t.text)?{$case:"text",value:globalThis.String(t.text)}:s(t.raw)?{$case:"raw",value:Buffer.from(Rs(t.raw))}:s(t.url)?{$case:"url",value:globalThis.String(t.url)}:s(t.data)?{$case:"data",value:t.data}:void 0,metadata:w(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=Cs(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)?gs(t.role):0,parts:globalThis.Array.isArray(t?.parts)?t.parts.map(e=>ie.fromJSON(e)):[],metadata:w(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=ms(t.role)),t.parts?.length&&(e.parts=t.parts.map(r=>ie.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}},ae={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=>ie.fromJSON(e)):[],metadata:w(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=>ie.toJSON(r))),t.metadata!==void 0&&(e.metadata=t.metadata),t.extensions?.length&&(e.extensions=t.extensions),e}},we={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)?re.fromJSON(t.status):void 0,metadata:w(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=re.toJSON(t.status)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},xe={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)?ae.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:w(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=ae.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}},gi={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}},Pe={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}},Xi={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=>Pe.fromJSON(e)):globalThis.Array.isArray(t?.supported_interfaces)?t.supported_interfaces.map(e=>Pe.fromJSON(e)):[],provider:s(t.provider)?mi.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)?Ni.fromJSON(t.capabilities):void 0,securitySchemes:w(t.securitySchemes)?globalThis.Object.entries(t.securitySchemes).reduce((e,[r,i])=>(e[r]=De.fromJSON(i),e),{}):w(t.security_schemes)?globalThis.Object.entries(t.security_schemes).reduce((e,[r,i])=>(e[r]=De.fromJSON(i),e),{}):{},securityRequirements:globalThis.Array.isArray(t?.securityRequirements)?t.securityRequirements.map(e=>yt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>yt.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=>Oi.fromJSON(e)):[],signatures:globalThis.Array.isArray(t?.signatures)?t.signatures.map(e=>vi.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=>Pe.toJSON(r))),t.provider!==void 0&&(e.provider=mi.toJSON(t.provider)),t.version!==""&&(e.version=t.version),t.documentationUrl!==void 0&&(e.documentationUrl=t.documentationUrl),t.capabilities!==void 0&&(e.capabilities=Ni.toJSON(t.capabilities)),t.securitySchemes){let r=globalThis.Object.entries(t.securitySchemes);if(r.length>0){let i={};r.forEach(([a,n])=>{i[a]=De.toJSON(n)}),e.securitySchemes=i}}return t.securityRequirements?.length&&(e.securityRequirements=t.securityRequirements.map(r=>yt.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=>Oi.toJSON(r))),t.signatures?.length&&(e.signatures=t.signatures.map(r=>vi.toJSON(r))),t.iconUrl!==void 0&&(e.iconUrl=t.iconUrl),e}},mi={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}},Ni={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=>Ei.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=>Ei.toJSON(r))),t.extendedAgentCard!==void 0&&(e.extendedAgentCard=t.extendedAgentCard),e}},Ei={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:w(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}},Oi={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=>yt.fromJSON(e)):globalThis.Array.isArray(t?.security_requirements)?t.security_requirements.map(e=>yt.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=>yt.toJSON(r))),e}},vi={fromJSON(t){return{protected:s(t.protected)?globalThis.String(t.protected):"",signature:s(t.signature)?globalThis.String(t.signature):"",header:w(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)?gi.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=gi.toJSON(t.authentication)),e}},_i={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}},yt={fromJSON(t){return{schemes:w(t.schemes)?globalThis.Object.entries(t.schemes).reduce((e,[r,i])=>(e[r]=_i.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]=_i.toJSON(n)}),e.schemes=i}}return e}},De={fromJSON(t){return{scheme:s(t.apiKeySecurityScheme)?{$case:"apiKeySecurityScheme",value:Me.fromJSON(t.apiKeySecurityScheme)}:s(t.api_key_security_scheme)?{$case:"apiKeySecurityScheme",value:Me.fromJSON(t.api_key_security_scheme)}:s(t.httpAuthSecurityScheme)?{$case:"httpAuthSecurityScheme",value:Le.fromJSON(t.httpAuthSecurityScheme)}:s(t.http_auth_security_scheme)?{$case:"httpAuthSecurityScheme",value:Le.fromJSON(t.http_auth_security_scheme)}:s(t.oauth2SecurityScheme)?{$case:"oauth2SecurityScheme",value:$e.fromJSON(t.oauth2SecurityScheme)}:s(t.oauth2_security_scheme)?{$case:"oauth2SecurityScheme",value:$e.fromJSON(t.oauth2_security_scheme)}:s(t.openIdConnectSecurityScheme)?{$case:"openIdConnectSecurityScheme",value:qe.fromJSON(t.openIdConnectSecurityScheme)}:s(t.open_id_connect_security_scheme)?{$case:"openIdConnectSecurityScheme",value:qe.fromJSON(t.open_id_connect_security_scheme)}:s(t.mtlsSecurityScheme)?{$case:"mtlsSecurityScheme",value:ze.fromJSON(t.mtlsSecurityScheme)}:s(t.mtls_security_scheme)?{$case:"mtlsSecurityScheme",value:ze.fromJSON(t.mtls_security_scheme)}:void 0}},toJSON(t){let e={};return t.scheme?.$case==="apiKeySecurityScheme"?e.apiKeySecurityScheme=Me.toJSON(t.scheme.value):t.scheme?.$case==="httpAuthSecurityScheme"?e.httpAuthSecurityScheme=Le.toJSON(t.scheme.value):t.scheme?.$case==="oauth2SecurityScheme"?e.oauth2SecurityScheme=$e.toJSON(t.scheme.value):t.scheme?.$case==="openIdConnectSecurityScheme"?e.openIdConnectSecurityScheme=qe.toJSON(t.scheme.value):t.scheme?.$case==="mtlsSecurityScheme"&&(e.mtlsSecurityScheme=ze.toJSON(t.scheme.value)),e}},Me={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}},Le={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}},$e={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):"",flows:s(t.flows)?yi.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=yi.toJSON(t.flows)),t.oauth2MetadataUrl!==""&&(e.oauth2MetadataUrl=t.oauth2MetadataUrl),e}},qe={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}},ze={fromJSON(t){return{description:s(t.description)?globalThis.String(t.description):""}},toJSON(t){let e={};return t.description!==""&&(e.description=t.description),e}},yi={fromJSON(t){return{flow:s(t.authorizationCode)?{$case:"authorizationCode",value:Fe.fromJSON(t.authorizationCode)}:s(t.authorization_code)?{$case:"authorizationCode",value:Fe.fromJSON(t.authorization_code)}:s(t.clientCredentials)?{$case:"clientCredentials",value:Be.fromJSON(t.clientCredentials)}:s(t.client_credentials)?{$case:"clientCredentials",value:Be.fromJSON(t.client_credentials)}:s(t.implicit)?{$case:"implicit",value:Ai.fromJSON(t.implicit)}:s(t.password)?{$case:"password",value:ki.fromJSON(t.password)}:s(t.deviceCode)?{$case:"deviceCode",value:He.fromJSON(t.deviceCode)}:s(t.device_code)?{$case:"deviceCode",value:He.fromJSON(t.device_code)}:void 0}},toJSON(t){let e={};return t.flow?.$case==="authorizationCode"?e.authorizationCode=Fe.toJSON(t.flow.value):t.flow?.$case==="clientCredentials"?e.clientCredentials=Be.toJSON(t.flow.value):t.flow?.$case==="implicit"?e.implicit=Ai.toJSON(t.flow.value):t.flow?.$case==="password"?e.password=ki.toJSON(t.flow.value):t.flow?.$case==="deviceCode"&&(e.deviceCode=He.toJSON(t.flow.value)),e}},Fe={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:w(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}},Be={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:w(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}},Ai={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:w(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}},ki={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:w(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}},He={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:w(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}},ne={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)?Ti.fromJSON(t.configuration):void 0,metadata:w(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=Ti.toJSON(t.configuration)),t.metadata!==void 0&&(e.metadata=t.metadata),e}},Ns={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}},Es={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)?Sr(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=Wi(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=>b.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=>b.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}},Os={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):"",id:s(t.id)?globalThis.String(t.id):"",metadata:w(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}},vs={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}},_s={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}},ys={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}},As={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}},ks={fromJSON(t){return{tenant:s(t.tenant)?globalThis.String(t.tenant):""}},toJSON(t){let e={};return t.tenant!==""&&(e.tenant=t.tenant),e}},Is={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:b.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=b.toJSON(t.payload.value):t.payload?.$case==="message"&&(e.message=Y.toJSON(t.payload.value)),e}},ar={fromJSON(t){return{payload:s(t.task)?{$case:"task",value:b.fromJSON(t.task)}:s(t.message)?{$case:"message",value:Y.fromJSON(t.message)}:s(t.statusUpdate)?{$case:"statusUpdate",value:we.fromJSON(t.statusUpdate)}:s(t.status_update)?{$case:"statusUpdate",value:we.fromJSON(t.status_update)}:s(t.artifactUpdate)?{$case:"artifactUpdate",value:xe.fromJSON(t.artifactUpdate)}:s(t.artifact_update)?{$case:"artifactUpdate",value:xe.fromJSON(t.artifact_update)}:void 0}},toJSON(t){let e={};return t.payload?.$case==="task"?e.task=b.toJSON(t.payload.value):t.payload?.$case==="message"?e.message=Y.toJSON(t.payload.value):t.payload?.$case==="statusUpdate"?e.statusUpdate=we.toJSON(t.payload.value):t.payload?.$case==="artifactUpdate"&&(e.artifactUpdate=xe.toJSON(t.payload.value)),e}},ji={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 Rs(t){return Uint8Array.from(globalThis.Buffer.from(t,"base64"))}function Cs(t){return globalThis.Buffer.from(t).toString("base64")}function w(t){return typeof t=="object"&&t!==null}function s(t){return t!=null}var At="A2A-Extensions",nt="A2A-Version",Us="1.0",Ut="0.3",Tr="application/json",nr="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(",")},se={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"};function gt(t){return`data: ${JSON.stringify(t)}
|
|
5
5
|
|
|
6
6
|
`}function oe(t){return`event: error
|
|
7
7
|
data: ${JSON.stringify(t)}
|