@atcn/adapter-a2a 1.5.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # @atcn/adapter-a2a
2
+
3
+ Connects [A2A](https://a2a-protocol.org) (Agent2Agent v1.0) agents to [ATCN](https://github.com/fadnisnikhil/atcn), so paid work handed from one agent to another ends up in a cost record that anyone can verify offline. ATCN only records: it never blocks, holds or releases money.
4
+
5
+ What it gives each side:
6
+
7
+ - **The agent doing the work** signs its task events as it goes (started, evidence submitted, completed) and can sign its estimate and how the task ended.
8
+ - **The agent paying for it** turns A2A tasks into delegations, matches the worker's bills to them through a declared billing reference, and records estimates, signed outcomes and sub-tasks handed further down the chain.
9
+
10
+ ```bash
11
+ npm install @atcn/adapter-a2a
12
+ ```
13
+
14
+ ## Signed task events
15
+
16
+ The working agent runs the bridge on its own task stream:
17
+
18
+ | A2A | ATCN |
19
+ | --- | --- |
20
+ | `TASK_STATE_WORKING` | `obligation.started` |
21
+ | Artifact with `metadata.atcn` (`evidence_type`, `verifier`, `deliverable_ids`) | `evidence.submitted` |
22
+ | `TASK_STATE_COMPLETED` | `completion.proposed` |
23
+ | `FAILED`, `CANCELED`, `REJECTED` | Nothing signed on the obligation (only the issuer may cancel it); the bridge returns a `terminal` action naming the subledger claim to record (`provider_failure` or `cancellation`) |
24
+
25
+ Every event is signed with the working agent's key. Clearing, payment and the task closure follow from those events.
26
+
27
+ ```ts
28
+ import { StreamResponse } from "@a2a-js/sdk";
29
+ import { A2AObligationBridge, localObligationClient, obligationIdFromMetadata } from "@atcn/adapter-a2a";
30
+
31
+ // In the working agent's AgentExecutor:
32
+ const obligationId = obligationIdFromMetadata(requestContext.userMessage.metadata);
33
+ const bridge = new A2AObligationBridge({ client: localObligationClient(network), worker: signer, obligationId });
34
+ await bridge.handle(StreamResponse.toJSON({ payload: { $case: "statusUpdate", value: statusUpdate } }));
35
+ ```
36
+
37
+ `client` is either an `AtcnClient` from `@atcn/sdk` (hosted API) or `localObligationClient(network)` for the in-memory network from `@atcn/local-runner`, which needs no account. The bridge reads A2A wire JSON, so it works with any A2A SDK; with `@a2a-js/sdk`, `StreamResponse.toJSON` produces it.
38
+
39
+ The delegating agent puts `obligationTaskMetadata(obligationId)` on the A2A message so the worker knows which obligation the task is for. `obligationTaskMetadata(obligationId, { skillId })` also names the AgentSkill it wants; the worker reads it with `skillIdFromMetadata`.
40
+
41
+ Pass `execution` to describe the run in `obligation.started`, so attestations can cite exactly which run, agent version and skill they judged:
42
+
43
+ ```ts
44
+ import { AgentCard } from "@a2a-js/sdk";
45
+
46
+ const bridge = new A2AObligationBridge({
47
+ client,
48
+ worker: signer,
49
+ obligationId,
50
+ execution: { agentCard: AgentCard.toJSON(card), skillId: skillIdFromMetadata(metadata) ?? undefined },
51
+ });
52
+ ```
53
+
54
+ The run's `execution_id` is `a2a:<task id>`. It records the A2A task and context ids, the card's `version` and digest, and the skill (namespace `a2a`). Optional `model` and `configDigest` are recorded as given; the agent declares them itself. When the obligation's terms name a skill, the network refuses a run of any other skill. After `obligation.started`, `bridge.execution` holds the descriptor; an attestation cites it as `executionBinding(bridge.execution)` from `@atcn/schema`.
55
+
56
+ ## Billing reference
57
+
58
+ An agent declares what its bills reference with the [billing-reference extension](https://github.com/fadnisnikhil/atcn/blob/main/docs/extensions/billing-ref-v1.md): `billingRefExtension({ billing_ref: "task_id", currency: "USD" })` goes in its Agent Card's `capabilities.extensions`. The buyer records the delegation with `delegationFromA2A({ card, task, currency })`, which takes `provider_job_ref` from that declaration, so the agent's charges match the delegation without a hand-written mapping. Pass `parentDelegationId` when an agent records a sub-task under its own delegation.
59
+
60
+ ## Estimates
61
+
62
+ An agent can sign its own estimate and send it in task or artifact metadata: `signedEstimateMetadata(estimate, { keyId, privateKey })`. The buyer reads it with `estimateFromMetadata` and records it with `estimateEventFromA2A(estimate, { match, binding })`. With a key binding for the agent's `key_id` it is `provider_key_signed`; without one it is relayed unsigned. Estimates are records only: nothing is reserved and they never count toward net cost. See [ESTIMATES.md](https://github.com/fadnisnikhil/atcn/blob/main/docs/ESTIMATES.md).
63
+
64
+ ## Signed outcomes
65
+
66
+ An agent signs how its task ended, over its A2A task id, its note and pointers to its evidence:
67
+
68
+ ```ts
69
+ import { signedOutcomeMetadata, terminalClaimType } from "@atcn/adapter-a2a";
70
+
71
+ // Agent side, on a failed task (the same works for "completion" or "partial_completion"):
72
+ const metadata = signedOutcomeMetadata(
73
+ { type: terminalClaimType("TASK_STATE_FAILED"), task_id: taskId, occurred_at: new Date().toISOString(), note: "index unavailable; charge refunded", evidence: [] },
74
+ { keyId: "gamma-key", privateKey },
75
+ );
76
+ ```
77
+
78
+ The buyer reads it from the status update with `outcomeFromMetadata` and records `outcomeClaimFromA2A(outcome, { binding })` on the delegation whose `provider_job_ref` is the task id. The claim is `provider_key_signed` only when the buyer bound the agent's key; the closure verifier re-checks the signature offline (check `signed_claims`). A failed or cancelled delegation that is still billed raises `charge_after_cancellation` until a refund, credit or reversal nets it to zero. The [A2A example](https://github.com/fadnisnikhil/atcn/tree/main/examples/a2a-delegation) publishes the signing key in a card extension (`npm run demo:a2a -- --search-fails`).
79
+
80
+ ## Multi-hop lineage
81
+
82
+ When an agent hands part of its task to another agent, `lineageMetadata(parentTask, agentName)` on the message that starts the sub-task carries the chain of tasks above it (`metadata.atcn.lineage`, root first; read it with `lineageFromMetadata`). The agent reports its sub-tasks back up with `downstreamMetadata(edges)`, each with the sub-agent's own signed outcome relayed unchanged. The buyer records every edge from `downstreamFromMetadata` as a child delegation (`childDelegationFromA2A(edge, { parentDelegationId, currency, providerId })`) and its outcome with `outcomeClaimFromA2A`. A sub-agent's signed outcome verifies against its own key even though the buyer never dealt with it. An edge that arrives with no outcome is a broken edge: record `brokenEdgeGap(edge, childDelegationId)` as a capture gap, and the closure shows lineage as incomplete with an `incomplete_lineage` exception.
83
+
84
+ A runnable example with two A2A agents over HTTP is in [`examples/a2a-delegation`](https://github.com/fadnisnikhil/atcn/tree/main/examples/a2a-delegation).
85
+
86
+ Part of [ATCN](https://github.com/fadnisnikhil/atcn). Apache-2.0.
@@ -0,0 +1,63 @@
1
+ import { type AgentCardExtension, type BillingRefParams } from "@atcn/schema";
2
+ import type { A2AAgentCard, A2ATask } from "./types.js";
3
+ /** The capabilities.extensions[] entry an agent adds to its Agent Card to declare what its bills reference. */
4
+ export declare function billingRefExtension(params: BillingRefParams): AgentCardExtension;
5
+ export interface DelegationFromA2AOptions {
6
+ card: A2AAgentCard;
7
+ task: Pick<A2ATask, "id" | "contextId" | "metadata">;
8
+ currency: string;
9
+ externalRef?: string;
10
+ /** The AgentSkill id the task performs; recorded in the delegation's run descriptor. */
11
+ skillId?: string;
12
+ /** The agent's ATCN agent id when it has one; otherwise the card's name identifies it. */
13
+ agentId?: string;
14
+ /** Used only when the card declares no billing-reference extension (today's hand mapping). */
15
+ fallbackProviderJobRef?: string | null;
16
+ /** The buyer's delegation this task was sent under, when an agent delegates further and records its own sub-task. */
17
+ parentDelegationId?: string;
18
+ }
19
+ /**
20
+ * A subledger delegation body for work sent to an A2A agent: provider_job_ref comes from the card's declared
21
+ * billing reference, and the run descriptor records the card's digest. Pass it to createDelegation (hosted API, SDK
22
+ * or local runner). An agent without the extension falls back to `fallbackProviderJobRef`.
23
+ */
24
+ export declare function delegationFromA2A(options: DelegationFromA2AOptions): Record<string, unknown>;
25
+ /** An agent's own estimate, as it travels in task or artifact metadata under metadata.atcn.estimate. */
26
+ export interface A2AEstimate {
27
+ source: string;
28
+ source_event_id: string;
29
+ amount_minor: number;
30
+ currency: string;
31
+ issued_at: string;
32
+ basis: string | null;
33
+ expires_at: string | null;
34
+ supersedes: string | null;
35
+ source_ref: string | null;
36
+ /** The agent's signing key and its signature over the expectation statement; absent for an unsigned estimate. */
37
+ key_id?: string;
38
+ signature?: string;
39
+ }
40
+ /**
41
+ * Agent side: metadata carrying a signed estimate. The agent signs with its own key; the buyer binds that key to
42
+ * the agent's provider record and records the estimate as provider_key_signed. Record only: nothing is reserved.
43
+ */
44
+ export declare function signedEstimateMetadata(estimate: Omit<A2AEstimate, "key_id" | "signature">, signing: {
45
+ keyId: string;
46
+ privateKey: string;
47
+ }): Record<string, unknown>;
48
+ /** The estimate in metadata.atcn.estimate, or null when there is none. */
49
+ export declare function estimateFromMetadata(metadata: Record<string, unknown> | undefined): A2AEstimate | null;
50
+ /**
51
+ * Buyer side: the financial event body for an agent's estimate, matched like a charge (usually by the delegation's
52
+ * provider_job_ref). A signed
53
+ * estimate needs the buyer's provider_id and key binding for the agent's key_id; without them the agent's estimate is
54
+ * relayed unsigned and stays buyer_recorded, so a signature by a key the buyer has not bound is never claimed.
55
+ */
56
+ export declare function estimateEventFromA2A(estimate: A2AEstimate, options: {
57
+ match: Record<string, string>;
58
+ binding?: {
59
+ provider_id: string;
60
+ binding_id: string;
61
+ key_id: string;
62
+ };
63
+ }): Record<string, unknown>;
@@ -0,0 +1,81 @@
1
+ import { BILLING_REF_EXTENSION_URI, BillingRefParamsSchema, digestOf, providerJobRefFor, } from "@atcn/schema";
2
+ import { buildExpectationStatement, signExpectation } from "@atcn/sdk";
3
+ import { A2A_SKILL_NAMESPACE, ATCN_METADATA_KEY } from "./bridge.js";
4
+ /** The capabilities.extensions[] entry an agent adds to its Agent Card to declare what its bills reference. */
5
+ export function billingRefExtension(params) {
6
+ return {
7
+ uri: BILLING_REF_EXTENSION_URI,
8
+ description: "Bills reference this value; buyers match charges to the delegated task by it",
9
+ required: false,
10
+ params: BillingRefParamsSchema.parse(params),
11
+ };
12
+ }
13
+ /**
14
+ * A subledger delegation body for work sent to an A2A agent: provider_job_ref comes from the card's declared
15
+ * billing reference, and the run descriptor records the card's digest. Pass it to createDelegation (hosted API, SDK
16
+ * or local runner). An agent without the extension falls back to `fallbackProviderJobRef`.
17
+ */
18
+ export function delegationFromA2A(options) {
19
+ const { card, task } = options;
20
+ const execution = {
21
+ execution_id: `a2a:${task.id}`,
22
+ protocol: { name: "a2a", task_id: task.id, ...(task.contextId ? { context_id: task.contextId } : {}) },
23
+ agent: { agent_id: options.agentId ?? card.name, agent_version: card.version, card_digest: digestOf(JSON.parse(JSON.stringify(card))) },
24
+ ...(options.skillId ? { skill: { namespace: A2A_SKILL_NAMESPACE, skill_id: options.skillId } } : {}),
25
+ };
26
+ return {
27
+ ...(options.externalRef ? { external_ref: options.externalRef } : {}),
28
+ ...(options.parentDelegationId ? { parent_delegation_id: options.parentDelegationId } : {}),
29
+ provider_name_stated: card.name,
30
+ provider_job_ref: providerJobRefFor(card, task) ?? options.fallbackProviderJobRef ?? null,
31
+ currency: options.currency,
32
+ execution,
33
+ };
34
+ }
35
+ /**
36
+ * Agent side: metadata carrying a signed estimate. The agent signs with its own key; the buyer binds that key to
37
+ * the agent's provider record and records the estimate as provider_key_signed. Record only: nothing is reserved.
38
+ */
39
+ export function signedEstimateMetadata(estimate, signing) {
40
+ const statement = buildExpectationStatement({
41
+ type: "estimate",
42
+ source: estimate.source,
43
+ source_event_id: estimate.source_event_id,
44
+ amount_minor: estimate.amount_minor,
45
+ currency: estimate.currency,
46
+ issued_at: estimate.issued_at,
47
+ expectation: { issued_by: "agent", source_ref: estimate.source_ref, basis: estimate.basis, expires_at: estimate.expires_at, supersedes: estimate.supersedes },
48
+ });
49
+ return { [ATCN_METADATA_KEY]: { estimate: { ...estimate, issued_at: statement.issued_at, expires_at: statement.expires_at, key_id: signing.keyId, signature: signExpectation(statement, signing.privateKey) } } };
50
+ }
51
+ /** The estimate in metadata.atcn.estimate, or null when there is none. */
52
+ export function estimateFromMetadata(metadata) {
53
+ const value = metadata?.[ATCN_METADATA_KEY]?.estimate;
54
+ return value && typeof value.amount_minor === "number" && typeof value.source_event_id === "string" ? value : null;
55
+ }
56
+ /**
57
+ * Buyer side: the financial event body for an agent's estimate, matched like a charge (usually by the delegation's
58
+ * provider_job_ref). A signed
59
+ * estimate needs the buyer's provider_id and key binding for the agent's key_id; without them the agent's estimate is
60
+ * relayed unsigned and stays buyer_recorded, so a signature by a key the buyer has not bound is never claimed.
61
+ */
62
+ export function estimateEventFromA2A(estimate, options) {
63
+ const signed = estimate.signature !== undefined && options.binding !== undefined && options.binding.key_id === estimate.key_id;
64
+ return {
65
+ type: "estimate",
66
+ source: estimate.source,
67
+ source_event_id: estimate.source_event_id,
68
+ amount_minor: estimate.amount_minor,
69
+ currency: estimate.currency,
70
+ event_date: estimate.issued_at,
71
+ match: options.match,
72
+ expectation: {
73
+ issued_by: "agent",
74
+ source_ref: estimate.source_ref,
75
+ basis: estimate.basis,
76
+ expires_at: estimate.expires_at,
77
+ supersedes: estimate.supersedes,
78
+ ...(signed ? { signer: { provider_id: options.binding.provider_id, binding_id: options.binding.binding_id, key_id: options.binding.key_id, value: estimate.signature } } : {}),
79
+ },
80
+ };
81
+ }
@@ -0,0 +1,117 @@
1
+ import { type ExecutionDescriptor, type SignedEvent } from "@atcn/schema";
2
+ import { type EventSigner } from "@atcn/sdk";
3
+ import type { A2AAgentCard, A2AStreamResponse, A2ATaskState } from "./types.js";
4
+ /** Metadata namespace the bridge reads on A2A messages, tasks and artifacts. */
5
+ export declare const ATCN_METADATA_KEY = "atcn";
6
+ /** SkillRef namespace for A2A: the skill_id is an AgentSkill id from the worker's agent card. */
7
+ export declare const A2A_SKILL_NAMESPACE = "a2a";
8
+ /**
9
+ * Evidence id derived from the obligation, the artifact id and the artifact's content digest. Every task snapshot
10
+ * (tasks/get returns all artifacts each time) yields the same id for the same artifact, so it is recorded once.
11
+ */
12
+ export declare function artifactEvidenceId(obligationId: string, artifactId: string, contentDigest: string): string;
13
+ /** Metadata a delegating agent attaches to the A2A message (or task) it sends for an ATCN obligation. */
14
+ export declare function obligationTaskMetadata(obligationId: string, options?: {
15
+ skillId?: string;
16
+ }): Record<string, unknown>;
17
+ /** The obligation id written by obligationTaskMetadata, or null when the metadata carries none. */
18
+ export declare function obligationIdFromMetadata(metadata: Record<string, unknown> | undefined): string | null;
19
+ /** The skill id written by obligationTaskMetadata, or null when the metadata names none. */
20
+ export declare function skillIdFromMetadata(metadata: Record<string, unknown> | undefined): string | null;
21
+ /**
22
+ * Artifact metadata marking an artifact as ATCN evidence. url parts must carry content_digest,
23
+ * because ATCN verifies digests of bytes the producer actually held.
24
+ */
25
+ export interface ArtifactEvidenceMetadata {
26
+ evidence_type: string;
27
+ verifier: string;
28
+ /** Every verifier that may read the evidence, when more than one does (an agent_trace for agent_trace and usage_cost). Defaults to [verifier]. */
29
+ verifiers?: string[];
30
+ deliverable_ids: string[];
31
+ content_digest?: string;
32
+ }
33
+ /** The calls the bridge makes. `AtcnClient` from @atcn/sdk has them; localObligationClient adapts the local runner. */
34
+ export interface ObligationClient {
35
+ getObligation(obligationId: string): Promise<unknown>;
36
+ appendEvent(obligationId: string, signed: SignedEvent): Promise<unknown>;
37
+ uploadBlob(bytes: Uint8Array, mediaType?: string): Promise<{
38
+ uri: string;
39
+ }>;
40
+ submitEvidence(obligationId: string, signed: SignedEvent): Promise<unknown>;
41
+ }
42
+ /** The parts of the local runner's `LocalNetwork` (@atcn/local-runner) the bridge uses. */
43
+ export interface LocalNetworkLike {
44
+ obligation(obligationId: string): {
45
+ state: string;
46
+ };
47
+ appendLifecycleEvent(body: unknown): unknown;
48
+ uploadBlob(content: Uint8Array): string;
49
+ submitEvidence(body: unknown): unknown;
50
+ }
51
+ /** Lets the bridge write to the local runner's in-memory network instead of the hosted API. */
52
+ export declare function localObligationClient(network: LocalNetworkLike): ObligationClient;
53
+ export type BridgeAction = {
54
+ kind: "event";
55
+ eventType: "obligation.started" | "completion.proposed";
56
+ eventId: string;
57
+ } | {
58
+ kind: "evidence";
59
+ artifactId: string;
60
+ evidenceId: string;
61
+ }
62
+ /** The task ended undelivered. Record `claimType` on the buyer's delegation (see outcomeClaimFromA2A); the issuer may cancel the obligation. */
63
+ | {
64
+ kind: "terminal";
65
+ state: A2ATaskState;
66
+ claimType: "provider_failure" | "cancellation";
67
+ taskId: string;
68
+ } | {
69
+ kind: "skipped";
70
+ detail: string;
71
+ };
72
+ export interface BridgeOptions {
73
+ client: ObligationClient;
74
+ /** Signer for the remote (working) agent, i.e. the obligation's counterparty. */
75
+ worker: EventSigner;
76
+ obligationId: string;
77
+ /**
78
+ * Describes the run in obligation.started, so attestations can cite it: the A2A task and context ids, the agent
79
+ * card's version and digest, and the skill. Without it, obligation.started carries no run.
80
+ */
81
+ execution?: {
82
+ agentCard: A2AAgentCard;
83
+ agentCardUrl?: string;
84
+ skillId?: string;
85
+ model?: {
86
+ provider: string;
87
+ name: string;
88
+ version: string;
89
+ };
90
+ configDigest?: string;
91
+ };
92
+ /**
93
+ * Evidence ids the obligation already holds (for example from listEvidence), so a bridge restarted mid-task skips
94
+ * them. Without it, the service refuses the repeated id ("evidence_id already registered") and records nothing twice.
95
+ */
96
+ submittedEvidenceIds?: string[];
97
+ }
98
+ /**
99
+ * Translates an A2A task stream from the worker's side into ATCN signed events:
100
+ * WORKING -> obligation.started, evidence-tagged artifacts -> evidence.submitted,
101
+ * COMPLETED -> completion.proposed. Terminal FAILED/CANCELED/REJECTED states sign nothing on the obligation (only the
102
+ * issuer may cancel it); they come back as "terminal" actions naming the subledger claim to record.
103
+ */
104
+ export declare class A2AObligationBridge {
105
+ private readonly options;
106
+ private started;
107
+ private completed;
108
+ private readonly pendingChunks;
109
+ private readonly submittedEvidenceIds;
110
+ /** The run this bridge declared in obligation.started, once it has. */
111
+ execution: ExecutionDescriptor | null;
112
+ constructor(options: BridgeOptions);
113
+ handle(response: A2AStreamResponse): Promise<BridgeAction[]>;
114
+ private onState;
115
+ private describeRun;
116
+ private onArtifact;
117
+ }
package/dist/bridge.js ADDED
@@ -0,0 +1,196 @@
1
+ import { createHash } from "node:crypto";
2
+ import { digestOf, sha256Digest } from "@atcn/schema";
3
+ import { buildEvidenceEnvelope } from "@atcn/sdk";
4
+ /** Metadata namespace the bridge reads on A2A messages, tasks and artifacts. */
5
+ export const ATCN_METADATA_KEY = "atcn";
6
+ /** SkillRef namespace for A2A: the skill_id is an AgentSkill id from the worker's agent card. */
7
+ export const A2A_SKILL_NAMESPACE = "a2a";
8
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
9
+ /**
10
+ * Evidence id derived from the obligation, the artifact id and the artifact's content digest. Every task snapshot
11
+ * (tasks/get returns all artifacts each time) yields the same id for the same artifact, so it is recorded once.
12
+ */
13
+ export function artifactEvidenceId(obligationId, artifactId, contentDigest) {
14
+ const hash = createHash("sha256").update(`${obligationId}\n${artifactId}\n${contentDigest}`).digest();
15
+ let body = "";
16
+ for (let i = 0; i < 26; i++)
17
+ body += CROCKFORD[hash[i] % 32];
18
+ return `evd_${body}`;
19
+ }
20
+ /** Metadata a delegating agent attaches to the A2A message (or task) it sends for an ATCN obligation. */
21
+ export function obligationTaskMetadata(obligationId, options = {}) {
22
+ return { [ATCN_METADATA_KEY]: { obligation_id: obligationId, ...(options.skillId ? { skill_id: options.skillId } : {}) } };
23
+ }
24
+ /** The obligation id written by obligationTaskMetadata, or null when the metadata carries none. */
25
+ export function obligationIdFromMetadata(metadata) {
26
+ const value = metadata?.[ATCN_METADATA_KEY];
27
+ return typeof value?.obligation_id === "string" ? value.obligation_id : null;
28
+ }
29
+ /** The skill id written by obligationTaskMetadata, or null when the metadata names none. */
30
+ export function skillIdFromMetadata(metadata) {
31
+ const value = metadata?.[ATCN_METADATA_KEY];
32
+ return typeof value?.skill_id === "string" ? value.skill_id : null;
33
+ }
34
+ /** Lets the bridge write to the local runner's in-memory network instead of the hosted API. */
35
+ export function localObligationClient(network) {
36
+ return {
37
+ getObligation: async (obligationId) => network.obligation(obligationId),
38
+ appendEvent: async (_obligationId, signed) => network.appendLifecycleEvent(signed),
39
+ uploadBlob: async (bytes) => ({ uri: network.uploadBlob(bytes) }),
40
+ submitEvidence: async (_obligationId, signed) => network.submitEvidence(signed),
41
+ };
42
+ }
43
+ /**
44
+ * Translates an A2A task stream from the worker's side into ATCN signed events:
45
+ * WORKING -> obligation.started, evidence-tagged artifacts -> evidence.submitted,
46
+ * COMPLETED -> completion.proposed. Terminal FAILED/CANCELED/REJECTED states sign nothing on the obligation (only the
47
+ * issuer may cancel it); they come back as "terminal" actions naming the subledger claim to record.
48
+ */
49
+ export class A2AObligationBridge {
50
+ options;
51
+ started = false;
52
+ completed = false;
53
+ pendingChunks = new Map();
54
+ submittedEvidenceIds;
55
+ /** The run this bridge declared in obligation.started, once it has. */
56
+ execution = null;
57
+ constructor(options) {
58
+ this.options = options;
59
+ this.submittedEvidenceIds = new Set(options.submittedEvidenceIds ?? []);
60
+ }
61
+ async handle(response) {
62
+ if ("task" in response) {
63
+ const actions = await this.onState(response.task.status.state, response.task.id, response.task.contextId);
64
+ for (const artifact of response.task.artifacts ?? [])
65
+ actions.push(await this.onArtifact(artifact));
66
+ return actions;
67
+ }
68
+ if ("statusUpdate" in response)
69
+ return this.onState(response.statusUpdate.status.state, response.statusUpdate.taskId, response.statusUpdate.contextId);
70
+ if ("artifactUpdate" in response) {
71
+ const update = response.artifactUpdate;
72
+ const previous = update.append ? (this.pendingChunks.get(update.artifact.artifactId) ?? []) : [];
73
+ const parts = appendParts(previous, update.artifact.parts);
74
+ if (update.lastChunk === false) {
75
+ this.pendingChunks.set(update.artifact.artifactId, parts);
76
+ return [];
77
+ }
78
+ this.pendingChunks.delete(update.artifact.artifactId);
79
+ return [await this.onArtifact({ ...update.artifact, parts })];
80
+ }
81
+ return [];
82
+ }
83
+ async onState(state, taskId, contextId) {
84
+ const { client, worker, obligationId } = this.options;
85
+ const actions = [];
86
+ if ((state === "TASK_STATE_WORKING" || state === "TASK_STATE_COMPLETED") && !this.started) {
87
+ const current = (await client.getObligation(obligationId));
88
+ if (current.state === "accepted") {
89
+ const execution = this.describeRun(taskId, contextId);
90
+ const signed = worker.sign("obligation.started", obligationId, execution ? { execution } : {});
91
+ await client.appendEvent(obligationId, signed);
92
+ this.execution = execution;
93
+ actions.push({ kind: "event", eventType: "obligation.started", eventId: signed.payload.event_id });
94
+ }
95
+ this.started = true;
96
+ }
97
+ if (state === "TASK_STATE_COMPLETED" && !this.completed) {
98
+ const signed = worker.sign("completion.proposed", obligationId, { note: "A2A task completed" });
99
+ await client.appendEvent(obligationId, signed);
100
+ this.completed = true;
101
+ actions.push({ kind: "event", eventType: "completion.proposed", eventId: signed.payload.event_id });
102
+ }
103
+ if (state === "TASK_STATE_FAILED" || state === "TASK_STATE_CANCELED" || state === "TASK_STATE_REJECTED") {
104
+ actions.push({ kind: "terminal", state, claimType: state === "TASK_STATE_FAILED" ? "provider_failure" : "cancellation", taskId });
105
+ }
106
+ return actions;
107
+ }
108
+ describeRun(taskId, contextId) {
109
+ const options = this.options.execution;
110
+ if (!options)
111
+ return null;
112
+ return {
113
+ execution_id: `a2a:${taskId}`,
114
+ protocol: { name: "a2a", task_id: taskId, ...(contextId ? { context_id: contextId } : {}) },
115
+ agent: {
116
+ agent_id: this.options.worker.actorId,
117
+ agent_version: options.agentCard.version,
118
+ card_digest: digestOf(JSON.parse(JSON.stringify(options.agentCard))),
119
+ ...(options.model ? { model: options.model } : {}),
120
+ ...(options.configDigest ? { config_digest: options.configDigest } : {}),
121
+ },
122
+ ...(options.skillId
123
+ ? { skill: { namespace: A2A_SKILL_NAMESPACE, skill_id: options.skillId, ...(options.agentCardUrl ? { agent_card_url: options.agentCardUrl } : {}) } }
124
+ : {}),
125
+ };
126
+ }
127
+ async onArtifact(artifact) {
128
+ const meta = artifact.metadata?.[ATCN_METADATA_KEY];
129
+ if (!meta)
130
+ return { kind: "skipped", detail: `artifact ${artifact.artifactId} has no ${ATCN_METADATA_KEY} evidence metadata` };
131
+ const { client, worker, obligationId } = this.options;
132
+ const part = artifact.parts[0];
133
+ if (!part || artifact.parts.length !== 1)
134
+ return { kind: "skipped", detail: `artifact ${artifact.artifactId} must have exactly one part to be evidence` };
135
+ if (part.url !== undefined && !meta.content_digest)
136
+ return { kind: "skipped", detail: `url artifact ${artifact.artifactId} needs metadata.atcn.content_digest` };
137
+ const bytes = part.url === undefined ? partBytes(part) : null;
138
+ const contentDigest = bytes ? sha256Digest(bytes) : meta.content_digest;
139
+ const evidenceId = artifactEvidenceId(obligationId, artifact.artifactId, contentDigest);
140
+ if (this.submittedEvidenceIds.has(evidenceId))
141
+ return { kind: "skipped", detail: `artifact ${artifact.artifactId} was already submitted as ${evidenceId}` };
142
+ let envelope;
143
+ if (part.url !== undefined) {
144
+ envelope = {
145
+ ...buildEvidenceEnvelope({
146
+ evidenceType: meta.evidence_type,
147
+ producerId: worker.actorId,
148
+ content: "",
149
+ uri: part.url,
150
+ retrievalMethod: "https",
151
+ mediaType: part.mediaType ?? "application/octet-stream",
152
+ verifiers: meta.verifiers ?? [meta.verifier],
153
+ deliverableIds: meta.deliverable_ids,
154
+ }),
155
+ content_digest: contentDigest,
156
+ };
157
+ }
158
+ else {
159
+ const mediaType = part.mediaType ?? (part.data !== undefined ? "application/json" : "text/plain");
160
+ const blob = await client.uploadBlob(bytes, mediaType);
161
+ envelope = buildEvidenceEnvelope({
162
+ evidenceType: meta.evidence_type,
163
+ producerId: worker.actorId,
164
+ content: bytes,
165
+ uri: blob.uri,
166
+ retrievalMethod: "atcn-blob",
167
+ mediaType,
168
+ verifiers: meta.verifiers ?? [meta.verifier],
169
+ deliverableIds: meta.deliverable_ids,
170
+ });
171
+ }
172
+ envelope = { ...envelope, evidence_id: evidenceId };
173
+ await client.submitEvidence(obligationId, worker.sign("evidence.submitted", obligationId, { envelope }));
174
+ this.submittedEvidenceIds.add(evidenceId);
175
+ return { kind: "evidence", artifactId: artifact.artifactId, evidenceId };
176
+ }
177
+ }
178
+ /** Streamed text chunks continue the previous text part; other parts are kept as they are. */
179
+ function appendParts(previous, next) {
180
+ const result = [...previous];
181
+ for (const part of next) {
182
+ const last = result.at(-1);
183
+ if (last?.text !== undefined && part.text !== undefined)
184
+ result[result.length - 1] = { ...last, text: last.text + part.text };
185
+ else
186
+ result.push(part);
187
+ }
188
+ return result;
189
+ }
190
+ function partBytes(part) {
191
+ if (part.raw !== undefined)
192
+ return new Uint8Array(Buffer.from(part.raw, "base64"));
193
+ if (part.text !== undefined)
194
+ return new TextEncoder().encode(part.text);
195
+ return new TextEncoder().encode(JSON.stringify(part.data ?? null));
196
+ }
@@ -0,0 +1,6 @@
1
+ export { A2A_SKILL_NAMESPACE, A2AObligationBridge, ATCN_METADATA_KEY, artifactEvidenceId, localObligationClient, obligationIdFromMetadata, obligationTaskMetadata, skillIdFromMetadata, type ArtifactEvidenceMetadata, type BridgeAction, type BridgeOptions, type LocalNetworkLike, type ObligationClient, } from "./bridge.js";
2
+ export { billingRefExtension, delegationFromA2A, estimateEventFromA2A, estimateFromMetadata, signedEstimateMetadata, type A2AEstimate, type DelegationFromA2AOptions, } from "./billing.js";
3
+ export { TERMINAL_CLAIM_BY_STATE, outcomeClaimFromA2A, outcomeFromMetadata, signOutcome, signedOutcomeMetadata, terminalClaimType, type A2AOutcome, } from "./outcome.js";
4
+ export { brokenEdgeGap, childDelegationFromA2A, downstreamFromMetadata, downstreamMetadata, lineageFromMetadata, lineageMetadata, type A2ADownstreamEdge, type A2ALineageHop, } from "./lineage.js";
5
+ export { BILLING_REF_EXTENSION_URI, billingRefFromAgentCard, providerJobRefFor, statedSkillPrice, type BillingRef, type BillingRefParams } from "@atcn/schema";
6
+ export type * from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { A2A_SKILL_NAMESPACE, A2AObligationBridge, ATCN_METADATA_KEY, artifactEvidenceId, localObligationClient, obligationIdFromMetadata, obligationTaskMetadata, skillIdFromMetadata, } from "./bridge.js";
2
+ export { billingRefExtension, delegationFromA2A, estimateEventFromA2A, estimateFromMetadata, signedEstimateMetadata, } from "./billing.js";
3
+ export { TERMINAL_CLAIM_BY_STATE, outcomeClaimFromA2A, outcomeFromMetadata, signOutcome, signedOutcomeMetadata, terminalClaimType, } from "./outcome.js";
4
+ export { brokenEdgeGap, childDelegationFromA2A, downstreamFromMetadata, downstreamMetadata, lineageFromMetadata, lineageMetadata, } from "./lineage.js";
5
+ export { BILLING_REF_EXTENSION_URI, billingRefFromAgentCard, providerJobRefFor, statedSkillPrice } from "@atcn/schema";
@@ -0,0 +1,48 @@
1
+ import type { A2AOutcome } from "./outcome.js";
2
+ import type { A2ATask } from "./types.js";
3
+ /**
4
+ * Multi-hop lineage over A2A. When an agent delegates part of its task to another agent, the message that starts the
5
+ * sub-task carries the chain of tasks above it (metadata.atcn.lineage), and the agent reports its sub-tasks back up
6
+ * (metadata.atcn.downstream) with each sub-agent's outcome relayed unchanged. The buyer records every reported sub-task
7
+ * as a child delegation; a sub-agent's signed outcome verifies against its own key even though the buyer never dealt
8
+ * with it, and a sub-task with no outcome is recorded as a broken edge (a capture gap) rather than silently dropped.
9
+ */
10
+ /** One hop of the chain: a task an agent was working on when it delegated further. */
11
+ export interface A2ALineageHop {
12
+ task_id: string;
13
+ context_id: string | null;
14
+ agent: string;
15
+ }
16
+ /** The chain in metadata.atcn.lineage, root first; empty when there is none. */
17
+ export declare function lineageFromMetadata(metadata: Record<string, unknown> | undefined): A2ALineageHop[];
18
+ /**
19
+ * Delegating agent's side: metadata for the message that starts a sub-task. The chain is the one the agent's own task
20
+ * arrived with, plus its own task.
21
+ */
22
+ export declare function lineageMetadata(parentTask: Pick<A2ATask, "id" | "contextId" | "metadata">, agent: string): Record<string, unknown>;
23
+ /** A sub-task an agent delegated, as it reports it upstream. outcome is the sub-agent's own (signed) outcome, or null when none arrived. */
24
+ export interface A2ADownstreamEdge {
25
+ agent: string;
26
+ task_id: string;
27
+ context_id: string | null;
28
+ outcome: A2AOutcome | null;
29
+ }
30
+ /** Delegating agent's side: task or status metadata reporting its sub-tasks. */
31
+ export declare function downstreamMetadata(edges: A2ADownstreamEdge[]): Record<string, unknown>;
32
+ /** The sub-tasks in metadata.atcn.downstream; empty when there are none. */
33
+ export declare function downstreamFromMetadata(metadata: Record<string, unknown> | undefined): A2ADownstreamEdge[];
34
+ /**
35
+ * Buyer side: the child delegation body for a reported sub-task, under the delegation of the agent that reported it.
36
+ * Pass providerId when the sub-agent is a known provider with a bound key, so its signed outcome counts.
37
+ */
38
+ export declare function childDelegationFromA2A(edge: A2ADownstreamEdge, options: {
39
+ parentDelegationId: string;
40
+ currency: string;
41
+ providerId?: string;
42
+ }): Record<string, unknown>;
43
+ /** Buyer side: the capture gap body for a sub-task that reported no outcome. */
44
+ export declare function brokenEdgeGap(edge: A2ADownstreamEdge, childDelegationId: string): {
45
+ delegation_id: string;
46
+ kind: "broken_edge";
47
+ detail: string;
48
+ };
@@ -0,0 +1,44 @@
1
+ import { ATCN_METADATA_KEY } from "./bridge.js";
2
+ /** The chain in metadata.atcn.lineage, root first; empty when there is none. */
3
+ export function lineageFromMetadata(metadata) {
4
+ const value = metadata?.[ATCN_METADATA_KEY]?.lineage;
5
+ if (!Array.isArray(value))
6
+ return [];
7
+ return value.filter((hop) => typeof hop?.task_id === "string" && typeof hop?.agent === "string");
8
+ }
9
+ /**
10
+ * Delegating agent's side: metadata for the message that starts a sub-task. The chain is the one the agent's own task
11
+ * arrived with, plus its own task.
12
+ */
13
+ export function lineageMetadata(parentTask, agent) {
14
+ const hop = { task_id: parentTask.id, context_id: parentTask.contextId ?? null, agent };
15
+ return { [ATCN_METADATA_KEY]: { lineage: [...lineageFromMetadata(parentTask.metadata), hop] } };
16
+ }
17
+ /** Delegating agent's side: task or status metadata reporting its sub-tasks. */
18
+ export function downstreamMetadata(edges) {
19
+ return { [ATCN_METADATA_KEY]: { downstream: edges } };
20
+ }
21
+ /** The sub-tasks in metadata.atcn.downstream; empty when there are none. */
22
+ export function downstreamFromMetadata(metadata) {
23
+ const value = metadata?.[ATCN_METADATA_KEY]?.downstream;
24
+ if (!Array.isArray(value))
25
+ return [];
26
+ return value.filter((edge) => typeof edge?.task_id === "string" && typeof edge?.agent === "string");
27
+ }
28
+ /**
29
+ * Buyer side: the child delegation body for a reported sub-task, under the delegation of the agent that reported it.
30
+ * Pass providerId when the sub-agent is a known provider with a bound key, so its signed outcome counts.
31
+ */
32
+ export function childDelegationFromA2A(edge, options) {
33
+ return {
34
+ parent_delegation_id: options.parentDelegationId,
35
+ ...(options.providerId ? { provider_id: options.providerId } : {}),
36
+ provider_name_stated: edge.agent,
37
+ provider_job_ref: edge.task_id,
38
+ currency: options.currency,
39
+ };
40
+ }
41
+ /** Buyer side: the capture gap body for a sub-task that reported no outcome. */
42
+ export function brokenEdgeGap(edge, childDelegationId) {
43
+ return { delegation_id: childDelegationId, kind: "broken_edge", detail: `${edge.agent} task ${edge.task_id} reported no outcome` };
44
+ }
@@ -0,0 +1,47 @@
1
+ import { type EvidenceRef, type SignedClaimType } from "@atcn/sdk";
2
+ import type { A2ATaskState } from "./types.js";
3
+ /** A2A terminal states where the work ended undelivered, and the subledger claim each one becomes. */
4
+ export declare const TERMINAL_CLAIM_BY_STATE: Partial<Record<A2ATaskState, "provider_failure" | "cancellation">>;
5
+ /** The subledger claim type for an A2A task that ended undelivered; throws for any other state. */
6
+ export declare function terminalClaimType(state: A2ATaskState): "provider_failure" | "cancellation";
7
+ /**
8
+ * An agent's statement of how its A2A task ended, as it travels under metadata.atcn.outcome: completed, partly
9
+ * completed, cancelled or failed, with pointers to its evidence.
10
+ */
11
+ export interface A2AOutcome {
12
+ type: SignedClaimType;
13
+ task_id: string;
14
+ occurred_at: string;
15
+ note: string | null;
16
+ evidence: EvidenceRef[];
17
+ /** The agent's signing key and its signature over the outcome statement; absent when unsigned. */
18
+ key_id?: string;
19
+ signature?: string;
20
+ }
21
+ /** Agent side: the outcome with the agent's signature over the A2A task id, note and evidence. */
22
+ export declare function signOutcome(outcome: Omit<A2AOutcome, "key_id" | "signature">, signing: {
23
+ keyId: string;
24
+ privateKey: string;
25
+ }): A2AOutcome;
26
+ /**
27
+ * Agent side: task or status metadata carrying a signed outcome. The buyer binds the agent's key to its provider
28
+ * record and records the claim as provider_key_signed.
29
+ */
30
+ export declare function signedOutcomeMetadata(outcome: Omit<A2AOutcome, "key_id" | "signature">, signing: {
31
+ keyId: string;
32
+ privateKey: string;
33
+ }): Record<string, unknown>;
34
+ /** The outcome in metadata.atcn.outcome, or null when there is none. */
35
+ export declare function outcomeFromMetadata(metadata: Record<string, unknown> | undefined): A2AOutcome | null;
36
+ /**
37
+ * Buyer side: the delivery claim body for an agent's outcome. Record it on the delegation whose provider_job_ref is
38
+ * the task id. A signature counts only with the buyer's key binding for the agent's key_id; otherwise the claim is
39
+ * relayed unsigned and stays buyer_recorded.
40
+ */
41
+ export declare function outcomeClaimFromA2A(outcome: A2AOutcome, options?: {
42
+ binding?: {
43
+ provider_id: string;
44
+ binding_id: string;
45
+ key_id: string;
46
+ };
47
+ }): Record<string, unknown>;
@@ -0,0 +1,49 @@
1
+ import { buildOutcomeStatement, signOutcomeStatement } from "@atcn/sdk";
2
+ import { ATCN_METADATA_KEY } from "./bridge.js";
3
+ /** A2A terminal states where the work ended undelivered, and the subledger claim each one becomes. */
4
+ export const TERMINAL_CLAIM_BY_STATE = {
5
+ TASK_STATE_FAILED: "provider_failure",
6
+ TASK_STATE_CANCELED: "cancellation",
7
+ TASK_STATE_REJECTED: "cancellation",
8
+ };
9
+ /** The subledger claim type for an A2A task that ended undelivered; throws for any other state. */
10
+ export function terminalClaimType(state) {
11
+ const type = TERMINAL_CLAIM_BY_STATE[state];
12
+ if (!type)
13
+ throw new Error(`${state} is not a terminal non-success A2A state; use TASK_STATE_FAILED, TASK_STATE_CANCELED or TASK_STATE_REJECTED`);
14
+ return type;
15
+ }
16
+ /** Agent side: the outcome with the agent's signature over the A2A task id, note and evidence. */
17
+ export function signOutcome(outcome, signing) {
18
+ const statement = buildOutcomeStatement({ type: outcome.type, provider_job_ref: outcome.task_id, occurred_at: outcome.occurred_at, note: outcome.note, evidence: outcome.evidence });
19
+ return { ...outcome, occurred_at: statement.occurred_at, key_id: signing.keyId, signature: signOutcomeStatement(statement, signing.privateKey) };
20
+ }
21
+ /**
22
+ * Agent side: task or status metadata carrying a signed outcome. The buyer binds the agent's key to its provider
23
+ * record and records the claim as provider_key_signed.
24
+ */
25
+ export function signedOutcomeMetadata(outcome, signing) {
26
+ return { [ATCN_METADATA_KEY]: { outcome: signOutcome(outcome, signing) } };
27
+ }
28
+ /** The outcome in metadata.atcn.outcome, or null when there is none. */
29
+ export function outcomeFromMetadata(metadata) {
30
+ const value = metadata?.[ATCN_METADATA_KEY]?.outcome;
31
+ return value && typeof value.task_id === "string" && typeof value.type === "string" ? value : null;
32
+ }
33
+ /**
34
+ * Buyer side: the delivery claim body for an agent's outcome. Record it on the delegation whose provider_job_ref is
35
+ * the task id. A signature counts only with the buyer's key binding for the agent's key_id; otherwise the claim is
36
+ * relayed unsigned and stays buyer_recorded.
37
+ */
38
+ export function outcomeClaimFromA2A(outcome, options = {}) {
39
+ const binding = options.binding;
40
+ const signed = outcome.signature !== undefined && binding !== undefined && binding.key_id === outcome.key_id;
41
+ return {
42
+ type: outcome.type,
43
+ asserted_by: "provider",
44
+ note: outcome.note,
45
+ occurred_at: outcome.occurred_at,
46
+ evidence: outcome.evidence,
47
+ ...(signed ? { signer: { provider_id: binding.provider_id, binding_id: binding.binding_id, key_id: binding.key_id, value: outcome.signature } } : {}),
48
+ };
49
+ }
@@ -0,0 +1,68 @@
1
+ /** A2A v1.0 shapes used by the bridge (a2a-protocol.org, camelCase JSON). */
2
+ export type A2ATaskState = "TASK_STATE_UNSPECIFIED" | "TASK_STATE_SUBMITTED" | "TASK_STATE_WORKING" | "TASK_STATE_INPUT_REQUIRED" | "TASK_STATE_AUTH_REQUIRED" | "TASK_STATE_COMPLETED" | "TASK_STATE_FAILED" | "TASK_STATE_CANCELED" | "TASK_STATE_REJECTED";
3
+ /** One unified part: exactly one of text, raw (base64 bytes), url, or data. */
4
+ export interface A2APart {
5
+ text?: string;
6
+ raw?: string;
7
+ url?: string;
8
+ data?: unknown;
9
+ filename?: string;
10
+ mediaType?: string;
11
+ metadata?: Record<string, unknown>;
12
+ }
13
+ export interface A2AArtifact {
14
+ artifactId: string;
15
+ name?: string;
16
+ description?: string;
17
+ parts: A2APart[];
18
+ metadata?: Record<string, unknown>;
19
+ }
20
+ export interface A2ATaskStatus {
21
+ state: A2ATaskState;
22
+ message?: unknown;
23
+ timestamp?: string;
24
+ }
25
+ export interface A2ATask {
26
+ id: string;
27
+ contextId: string;
28
+ status: A2ATaskStatus;
29
+ artifacts?: A2AArtifact[];
30
+ metadata?: Record<string, unknown>;
31
+ }
32
+ export interface A2ATaskStatusUpdateEvent {
33
+ taskId: string;
34
+ contextId: string;
35
+ status: A2ATaskStatus;
36
+ metadata?: Record<string, unknown>;
37
+ }
38
+ export interface A2ATaskArtifactUpdateEvent {
39
+ taskId: string;
40
+ contextId: string;
41
+ artifact: A2AArtifact;
42
+ append?: boolean;
43
+ lastChunk?: boolean;
44
+ index?: number;
45
+ metadata?: Record<string, unknown>;
46
+ }
47
+ /** The agent card fields the bridge reads, in A2A wire JSON (with @a2a-js/sdk, `AgentCard.toJSON(card)`). */
48
+ export interface A2AAgentCard {
49
+ name: string;
50
+ version: string;
51
+ skills?: {
52
+ id: string;
53
+ }[];
54
+ [field: string]: unknown;
55
+ }
56
+ /**
57
+ * Stream responses are discriminated by member name. With @a2a-js/sdk, `StreamResponse.toJSON(event)` produces
58
+ * this shape from the SDK's objects.
59
+ */
60
+ export type A2AStreamResponse = {
61
+ task: A2ATask;
62
+ } | {
63
+ message: unknown;
64
+ } | {
65
+ statusUpdate: A2ATaskStatusUpdateEvent;
66
+ } | {
67
+ artifactUpdate: A2ATaskArtifactUpdateEvent;
68
+ };
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ /** A2A v1.0 shapes used by the bridge (a2a-protocol.org, camelCase JSON). */
2
+ export {};
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@atcn/adapter-a2a",
3
+ "version": "1.5.0",
4
+ "description": "Record paid A2A (Agent2Agent) work in ATCN: signed task events, billing references, estimates, signed outcomes and sub-task lineage",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/fadnisnikhil/atcn.git",
9
+ "directory": "packages/adapter-a2a"
10
+ },
11
+ "homepage": "https://github.com/fadnisnikhil/atcn/tree/main/packages/adapter-a2a#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/fadnisnikhil/atcn/issues"
14
+ },
15
+ "type": "module",
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "main": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "atcn-source": "./src/index.ts",
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "scripts": {
32
+ "build": "tsc -p tsconfig.build.json"
33
+ },
34
+ "dependencies": {
35
+ "@atcn/schema": "1.5.0",
36
+ "@atcn/sdk": "1.5.0"
37
+ }
38
+ }