foldkit-agent-a2a 0.1.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 +21 -0
- package/README.md +79 -0
- package/dist/index.d.mts +181 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +309 -0
- package/dist/index.mjs.map +1 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Patrick Glenn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# `foldkit-agent-a2a`
|
|
2
|
+
|
|
3
|
+
Serves a [`foldkit-agent`](../agent) contract as an A2A agent, so another agent
|
|
4
|
+
can use the capabilities an application already exposes.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pnpm add foldkit-agent foldkit-agent-a2a
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## The Agent Card
|
|
11
|
+
|
|
12
|
+
One exposed capability is one skill:
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { AgentA2a } from 'foldkit-agent-a2a'
|
|
16
|
+
|
|
17
|
+
const card = AgentA2a.agentCard(AppAgent, {
|
|
18
|
+
name: 'Todos',
|
|
19
|
+
description: 'A todo list',
|
|
20
|
+
url: 'https://todos.example/a2a',
|
|
21
|
+
securitySchemes: { bearer: { type: 'http', scheme: 'bearer' } },
|
|
22
|
+
security: [{ bearer: [] }],
|
|
23
|
+
})
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Serve it from `AgentA2a.AGENT_CARD_PATH` (`/.well-known/agent-card.json`).
|
|
27
|
+
|
|
28
|
+
A card is static while availability is not, so a capability that only exists in
|
|
29
|
+
some Model states is tagged `conditional`, and one that runs an authorization
|
|
30
|
+
check is tagged `authorized`. Both can still refuse at call time.
|
|
31
|
+
|
|
32
|
+
## Calling a skill
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
const served = AgentA2a.handler({ agent: agentRuntime })
|
|
36
|
+
|
|
37
|
+
await served.handle({
|
|
38
|
+
jsonrpc: '2.0',
|
|
39
|
+
id: 1,
|
|
40
|
+
method: 'message/send',
|
|
41
|
+
params: {
|
|
42
|
+
message: {
|
|
43
|
+
kind: 'message',
|
|
44
|
+
role: 'user',
|
|
45
|
+
messageId: 'm-1',
|
|
46
|
+
parts: [{ kind: 'data', data: { skill: 'delete_todo', input: { id: 'todo-1' } } }],
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
})
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`tasks/get` fetches a task afterwards and `tasks/cancel` aborts one still
|
|
53
|
+
running. Tasks are held in a bounded buffer.
|
|
54
|
+
|
|
55
|
+
## Task states
|
|
56
|
+
|
|
57
|
+
The distinction that matters is **rejected** versus **failed**:
|
|
58
|
+
|
|
59
|
+
| Outcome | State |
|
|
60
|
+
| --- | --- |
|
|
61
|
+
| Unknown skill, input that fails the schema, a caller who may not | `rejected` |
|
|
62
|
+
| A declared failure Message, or a completion that timed out | `failed` |
|
|
63
|
+
| The invocation was cancelled | `canceled` |
|
|
64
|
+
| Dispatched, or completed by its success Message | `completed` |
|
|
65
|
+
|
|
66
|
+
`rejected` means the agent declined the request; `failed` means it accepted the
|
|
67
|
+
work and the work did not succeed. A client decides what to do next from that
|
|
68
|
+
difference, so collapsing them would be a bug.
|
|
69
|
+
|
|
70
|
+
A capability with no completion contract finishes at validated dispatch, so its
|
|
71
|
+
task is `completed` immediately. One that declares completion finishes when its
|
|
72
|
+
Message arrives — which is why completion tracking had to come first.
|
|
73
|
+
|
|
74
|
+
## Not implemented
|
|
75
|
+
|
|
76
|
+
`streaming` and `pushNotifications` are declared `false` on the card, and
|
|
77
|
+
`message/stream` is refused rather than answered with something a client cannot
|
|
78
|
+
consume. Multi-turn conversations, `input-required`, `auth-required`, file parts
|
|
79
|
+
and artifacts are also out of scope for now.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { Agent } from "foldkit-agent";
|
|
2
|
+
import { Schema } from "effect";
|
|
3
|
+
//#region src/types.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The bound contract, with its capability maps left open.
|
|
6
|
+
*
|
|
7
|
+
* An adapter reads names off the wire, so it works against the permissive maps
|
|
8
|
+
* rather than a particular application's.
|
|
9
|
+
*/
|
|
10
|
+
type AgentRuntime = Agent.AgentRuntime<any, any, any, any, any>;
|
|
11
|
+
type Definition = Agent.Definition<any, any, any, any, any>;
|
|
12
|
+
/**
|
|
13
|
+
* The JSON-RPC envelope A2A uses.
|
|
14
|
+
*
|
|
15
|
+
* Deliberately a local copy rather than shared with `foldkit-agent-mcp`: two
|
|
16
|
+
* protocols that happen to use the same envelope should not be coupled through
|
|
17
|
+
* it.
|
|
18
|
+
*/
|
|
19
|
+
type Id = string | number;
|
|
20
|
+
interface Success {
|
|
21
|
+
readonly jsonrpc: '2.0';
|
|
22
|
+
readonly id: Id;
|
|
23
|
+
readonly result: unknown;
|
|
24
|
+
}
|
|
25
|
+
interface Failure {
|
|
26
|
+
readonly jsonrpc: '2.0';
|
|
27
|
+
readonly id: Id | null;
|
|
28
|
+
readonly error: {
|
|
29
|
+
readonly code: number;
|
|
30
|
+
readonly message: string;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
type Response = Success | Failure;
|
|
34
|
+
/**
|
|
35
|
+
* The subset of A2A 0.3.0 task states this adapter produces.
|
|
36
|
+
*
|
|
37
|
+
* `input-required`, `auth-required` and `unknown` are spec states no dispatch
|
|
38
|
+
* here can reach, so they are left out rather than declared and never used.
|
|
39
|
+
*/
|
|
40
|
+
type TaskState = 'submitted' | 'working' | 'completed' | 'failed' | 'canceled' | 'rejected';
|
|
41
|
+
interface TaskStatus {
|
|
42
|
+
readonly state: TaskState;
|
|
43
|
+
readonly timestamp: string;
|
|
44
|
+
/** What happened, in the agent's own words. */
|
|
45
|
+
readonly message?: Message | undefined;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A part carries either text or data, and which one is not optional.
|
|
49
|
+
*
|
|
50
|
+
* A single struct with both fields optional would accept
|
|
51
|
+
* `{ kind: 'data' }` and leave every reader to re-check.
|
|
52
|
+
*/
|
|
53
|
+
declare const PartSchema: Schema.Union<readonly [Schema.Struct<{
|
|
54
|
+
readonly kind: Schema.Literal<"text">;
|
|
55
|
+
readonly text: Schema.String;
|
|
56
|
+
}>, Schema.Struct<{
|
|
57
|
+
readonly kind: Schema.Literal<"data">;
|
|
58
|
+
readonly data: Schema.$Record<Schema.String, Schema.Unknown>;
|
|
59
|
+
}>]>;
|
|
60
|
+
type Part = typeof PartSchema.Type;
|
|
61
|
+
/**
|
|
62
|
+
* `kind` is required by the spec, not decoration: `Task | Message` is a union a
|
|
63
|
+
* client discriminates on, so a message without it is not a Message.
|
|
64
|
+
*/
|
|
65
|
+
declare const MessageSchema: Schema.Struct<{
|
|
66
|
+
readonly kind: Schema.Literal<"message">;
|
|
67
|
+
readonly role: Schema.Literals<readonly ["user", "agent"]>;
|
|
68
|
+
readonly parts: Schema.$Array<Schema.Union<readonly [Schema.Struct<{
|
|
69
|
+
readonly kind: Schema.Literal<"text">;
|
|
70
|
+
readonly text: Schema.String;
|
|
71
|
+
}>, Schema.Struct<{
|
|
72
|
+
readonly kind: Schema.Literal<"data">;
|
|
73
|
+
readonly data: Schema.$Record<Schema.String, Schema.Unknown>;
|
|
74
|
+
}>]>>;
|
|
75
|
+
readonly messageId: Schema.String;
|
|
76
|
+
readonly taskId: Schema.optional<Schema.String>;
|
|
77
|
+
readonly contextId: Schema.optional<Schema.String>;
|
|
78
|
+
}>;
|
|
79
|
+
type Message = typeof MessageSchema.Type;
|
|
80
|
+
interface Task {
|
|
81
|
+
readonly kind: 'task';
|
|
82
|
+
readonly id: string;
|
|
83
|
+
readonly contextId: string;
|
|
84
|
+
readonly status: TaskStatus;
|
|
85
|
+
readonly history: ReadonlyArray<Message>;
|
|
86
|
+
}
|
|
87
|
+
//#endregion
|
|
88
|
+
//#region src/card.d.ts
|
|
89
|
+
/** Where an A2A client looks for the card. */
|
|
90
|
+
declare const AGENT_CARD_PATH = "/.well-known/agent-card.json";
|
|
91
|
+
/** One thing this agent can do. Derived from an exposed capability. */
|
|
92
|
+
interface AgentSkill {
|
|
93
|
+
readonly id: string;
|
|
94
|
+
readonly name: string;
|
|
95
|
+
readonly description: string;
|
|
96
|
+
readonly tags: ReadonlyArray<string>;
|
|
97
|
+
/**
|
|
98
|
+
* The JSON Schema for this skill's input, as the contract derived it.
|
|
99
|
+
*
|
|
100
|
+
* Deliberately beyond the spec. A 0.3.0 `AgentSkill` describes its input only
|
|
101
|
+
* in prose -- `inputModes` carries media types, not shapes -- so a caller has
|
|
102
|
+
* nothing to construct a valid request from, which is the one thing this
|
|
103
|
+
* contract already knows. The card validates because `AgentSkill` leaves
|
|
104
|
+
* `additionalProperties` unset, not because the field is sanctioned.
|
|
105
|
+
*
|
|
106
|
+
* The risk is a later spec claiming this name for something else: the card
|
|
107
|
+
* would not fail, it would quietly mean something a conforming client reads
|
|
108
|
+
* differently. The spec-legal alternative is an `AgentExtension` under
|
|
109
|
+
* `capabilities.extensions`, whose `params` would hold a skill-id-keyed map --
|
|
110
|
+
* worth moving to when a real client consumes this, or the moment A2A
|
|
111
|
+
* proposes a per-skill schema field. A conformance test pins the set of extra
|
|
112
|
+
* keys so a second one cannot appear unnoticed.
|
|
113
|
+
*/
|
|
114
|
+
readonly inputSchema: Record<string, unknown>;
|
|
115
|
+
}
|
|
116
|
+
interface AgentCard {
|
|
117
|
+
readonly protocolVersion: string;
|
|
118
|
+
readonly name: string;
|
|
119
|
+
readonly description: string;
|
|
120
|
+
/** Where this agent accepts A2A requests. */
|
|
121
|
+
readonly url: string;
|
|
122
|
+
/** The transport bound to `url`. This adapter speaks JSON-RPC and nothing else. */
|
|
123
|
+
readonly preferredTransport: 'JSONRPC';
|
|
124
|
+
readonly version: string;
|
|
125
|
+
readonly capabilities: {
|
|
126
|
+
readonly streaming: boolean;
|
|
127
|
+
readonly pushNotifications: boolean;
|
|
128
|
+
};
|
|
129
|
+
readonly defaultInputModes: ReadonlyArray<string>;
|
|
130
|
+
readonly defaultOutputModes: ReadonlyArray<string>;
|
|
131
|
+
readonly skills: ReadonlyArray<AgentSkill>;
|
|
132
|
+
readonly securitySchemes?: Record<string, unknown> | undefined;
|
|
133
|
+
readonly security?: ReadonlyArray<Record<string, ReadonlyArray<string>>> | undefined;
|
|
134
|
+
}
|
|
135
|
+
declare const A2A_VERSION = "0.3.0";
|
|
136
|
+
interface AgentCardOptions {
|
|
137
|
+
readonly name: string;
|
|
138
|
+
readonly description: string;
|
|
139
|
+
/** The endpoint that answers `message/send`. */
|
|
140
|
+
readonly url: string;
|
|
141
|
+
readonly version?: string | undefined;
|
|
142
|
+
/** Declared so a client knows how to authenticate before it calls. */
|
|
143
|
+
readonly securitySchemes?: Record<string, unknown> | undefined;
|
|
144
|
+
readonly security?: ReadonlyArray<Record<string, ReadonlyArray<string>>> | undefined;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Builds the card an A2A client fetches before calling.
|
|
148
|
+
*
|
|
149
|
+
* Skills are the exposed capabilities: the same descriptors MCP lists as tools.
|
|
150
|
+
* A capability that is only available in some Model states is tagged, because a
|
|
151
|
+
* card is static while availability is not.
|
|
152
|
+
*/
|
|
153
|
+
declare const agentCard: (definition: Definition, options: AgentCardOptions) => AgentCard;
|
|
154
|
+
//#endregion
|
|
155
|
+
//#region src/handler.d.ts
|
|
156
|
+
interface HandlerOptions {
|
|
157
|
+
readonly agent: AgentRuntime;
|
|
158
|
+
/** Tasks kept for `tasks/get`. Defaults to 200. */
|
|
159
|
+
readonly capacity?: number | undefined;
|
|
160
|
+
/** Injected for tests. */
|
|
161
|
+
readonly newId?: (() => string) | undefined;
|
|
162
|
+
readonly clock?: (() => Date) | undefined;
|
|
163
|
+
}
|
|
164
|
+
interface Handler {
|
|
165
|
+
readonly handle: (message: unknown) => Promise<Response | undefined>;
|
|
166
|
+
readonly close: () => void;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Serves a contract as an A2A agent, with no transport attached.
|
|
170
|
+
*
|
|
171
|
+
* One exposed capability is one skill. A capability with no completion contract
|
|
172
|
+
* finishes at validated dispatch, so its task is `completed` immediately; one
|
|
173
|
+
* that declares completion finishes when its Message arrives.
|
|
174
|
+
*/
|
|
175
|
+
declare const handler: (options: HandlerOptions) => Handler;
|
|
176
|
+
declare namespace agentA2a_d_exports {
|
|
177
|
+
export { A2A_VERSION, AGENT_CARD_PATH, AgentCard, AgentCardOptions, AgentSkill, Handler, HandlerOptions, agentCard, handler };
|
|
178
|
+
}
|
|
179
|
+
//#endregion
|
|
180
|
+
export { agentA2a_d_exports as AgentA2a, type Message, type Part, type Response, type Task, type TaskState, type TaskStatus };
|
|
181
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/card.ts","../src/handler.ts","../src/agentA2a.ts"],"mappings":";;;;;;;;;KASY,eAAe,MAAM;KAErB,aAAa,MAAM;;;;;;;;KASnB;UAuBK;WACN;WACA,IAAI;WACJ;;UAGM;WACN;WACA,IAAI;WACJ;aAAkB;aAAuB;;;KAGxC,WAAW,UAAU;;;;;;;KA0BrB;UAUK;WACN,OAAO;WACP;;WAEA,UAAU;;;;;;;;cASR,YAAU,OAAA,gBAAA,OAAA;;;;;;;KAQX,cAAc,WAAW;;;;;cAMxB,eAAa,OAAA;;;;;;;;;;;;;;KASd,iBAAiB,cAAc;UAK1B;WACN;WACA;WACA;WACA,QAAQ;WACR,SAAS,cAAc;;;;;cCrIrB;;UAGI;WACN;WACA;WACA;WACA,MAAM;;;;;;;;;;;;;;;;;;WAkBN,aAAa;;UAGP;WACN;WACA;WACA;;WAEA;;WAEA;WACA;WACA;aACE;aACA;;WAEF,mBAAmB;WACnB,oBAAoB;WACpB,QAAQ,cAAc;WACtB,kBAAkB;WAClB,WAAW,cAAc,eAAe;;cAGtC;UAEI;WACN;WACA;;WAEA;WACA;;WAEA,kBAAkB;WAClB,WAAW,cAAc,eAAe;;;;;;;;;cAUtC,YAAa,YAAY,YAAY,SAAS,qBAAmB;;;UCvD7D;WACN,OAAO;;WAEP;;WAEA;WACA,eAAe;;UAGT;WACN,SAAS,qBAAqB,QAAQ;WACtC;;;;;;;;;cA+CE,UAAW,SAAS,mBAAiB"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
|
+
import { Agent } from "foldkit-agent";
|
|
3
|
+
import { Effect, Schema } from "effect";
|
|
4
|
+
//#region src/card.ts
|
|
5
|
+
/** Where an A2A client looks for the card. */
|
|
6
|
+
const AGENT_CARD_PATH = "/.well-known/agent-card.json";
|
|
7
|
+
const A2A_VERSION = "0.3.0";
|
|
8
|
+
/**
|
|
9
|
+
* Builds the card an A2A client fetches before calling.
|
|
10
|
+
*
|
|
11
|
+
* Skills are the exposed capabilities: the same descriptors MCP lists as tools.
|
|
12
|
+
* A capability that is only available in some Model states is tagged, because a
|
|
13
|
+
* card is static while availability is not.
|
|
14
|
+
*/
|
|
15
|
+
const agentCard = (definition, options) => ({
|
|
16
|
+
protocolVersion: A2A_VERSION,
|
|
17
|
+
name: options.name,
|
|
18
|
+
description: options.description,
|
|
19
|
+
url: options.url,
|
|
20
|
+
preferredTransport: "JSONRPC",
|
|
21
|
+
version: options.version ?? "0.1.0",
|
|
22
|
+
capabilities: {
|
|
23
|
+
streaming: false,
|
|
24
|
+
pushNotifications: false
|
|
25
|
+
},
|
|
26
|
+
defaultInputModes: ["application/json"],
|
|
27
|
+
defaultOutputModes: ["application/json"],
|
|
28
|
+
skills: Agent.messages(definition).map((capability) => ({
|
|
29
|
+
id: capability.name,
|
|
30
|
+
name: capability.name,
|
|
31
|
+
description: capability.description,
|
|
32
|
+
tags: [...capability.modelDependent ? ["conditional"] : [], ...capability.requiresAuthorization ? ["authorized"] : []],
|
|
33
|
+
inputSchema: capability.inputSchema
|
|
34
|
+
})),
|
|
35
|
+
...options.securitySchemes === void 0 ? {} : { securitySchemes: options.securitySchemes },
|
|
36
|
+
...options.security === void 0 ? {} : { security: options.security }
|
|
37
|
+
});
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/types.ts
|
|
40
|
+
/**
|
|
41
|
+
* The envelope, decoded before anything reads a field off it.
|
|
42
|
+
*
|
|
43
|
+
* `params` stays `unknown` here: what a method requires is the method's
|
|
44
|
+
* business, and deciding it here would answer bad params with the wrong code.
|
|
45
|
+
*/
|
|
46
|
+
const RequestSchema = Schema.Struct({
|
|
47
|
+
jsonrpc: Schema.Literal("2.0"),
|
|
48
|
+
id: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
|
|
49
|
+
method: Schema.String,
|
|
50
|
+
params: Schema.optional(Schema.Unknown)
|
|
51
|
+
});
|
|
52
|
+
const code = {
|
|
53
|
+
INVALID_REQUEST: -32600,
|
|
54
|
+
METHOD_NOT_FOUND: -32601,
|
|
55
|
+
INVALID_PARAMS: -32602,
|
|
56
|
+
/** A2A: the task id is not one this agent issued. */
|
|
57
|
+
TASK_NOT_FOUND: -32001,
|
|
58
|
+
/** A2A: the task has already settled, so there is nothing left to cancel. */
|
|
59
|
+
TASK_NOT_CANCELABLE: -32002
|
|
60
|
+
};
|
|
61
|
+
const success = (id, result) => ({
|
|
62
|
+
jsonrpc: "2.0",
|
|
63
|
+
id,
|
|
64
|
+
result
|
|
65
|
+
});
|
|
66
|
+
const failure = (id, errorCode, message) => ({
|
|
67
|
+
jsonrpc: "2.0",
|
|
68
|
+
id,
|
|
69
|
+
error: {
|
|
70
|
+
code: errorCode,
|
|
71
|
+
message
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
/** States a task cannot leave. A later settle must not overwrite one. */
|
|
75
|
+
const terminal = /* @__PURE__ */ new Set([
|
|
76
|
+
"completed",
|
|
77
|
+
"failed",
|
|
78
|
+
"canceled",
|
|
79
|
+
"rejected"
|
|
80
|
+
]);
|
|
81
|
+
/**
|
|
82
|
+
* A part carries either text or data, and which one is not optional.
|
|
83
|
+
*
|
|
84
|
+
* A single struct with both fields optional would accept
|
|
85
|
+
* `{ kind: 'data' }` and leave every reader to re-check.
|
|
86
|
+
*/
|
|
87
|
+
const PartSchema = Schema.Union([Schema.Struct({
|
|
88
|
+
kind: Schema.Literal("text"),
|
|
89
|
+
text: Schema.String
|
|
90
|
+
}), Schema.Struct({
|
|
91
|
+
kind: Schema.Literal("data"),
|
|
92
|
+
data: Schema.Record(Schema.String, Schema.Unknown)
|
|
93
|
+
})]);
|
|
94
|
+
/**
|
|
95
|
+
* `kind` is required by the spec, not decoration: `Task | Message` is a union a
|
|
96
|
+
* client discriminates on, so a message without it is not a Message.
|
|
97
|
+
*/
|
|
98
|
+
const MessageSchema = Schema.Struct({
|
|
99
|
+
kind: Schema.Literal("message"),
|
|
100
|
+
role: Schema.Literals(["user", "agent"]),
|
|
101
|
+
parts: Schema.Array(PartSchema),
|
|
102
|
+
messageId: Schema.String,
|
|
103
|
+
taskId: Schema.optional(Schema.String),
|
|
104
|
+
contextId: Schema.optional(Schema.String)
|
|
105
|
+
});
|
|
106
|
+
/** What `message/send` requires of its params. */
|
|
107
|
+
const SendParamsSchema = Schema.Struct({ message: MessageSchema });
|
|
108
|
+
const text = (body) => ({
|
|
109
|
+
kind: "text",
|
|
110
|
+
text: body
|
|
111
|
+
});
|
|
112
|
+
//#endregion
|
|
113
|
+
//#region src/handler.ts
|
|
114
|
+
const randomId = () => typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `a2a-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
115
|
+
/**
|
|
116
|
+
* How a refused or finished dispatch reads as a task state.
|
|
117
|
+
*
|
|
118
|
+
* `rejected` is for a request the agent declined outright -- an unknown skill,
|
|
119
|
+
* bad input, a caller who may not. `failed` is for work that was accepted and
|
|
120
|
+
* did not succeed, which is a different thing to a client deciding what to do
|
|
121
|
+
* next.
|
|
122
|
+
*/
|
|
123
|
+
const stateFor = (failureTag) => {
|
|
124
|
+
switch (failureTag) {
|
|
125
|
+
case "AgentCancelledError": return "canceled";
|
|
126
|
+
case "AgentCompletionTimeoutError": return "failed";
|
|
127
|
+
default: return "rejected";
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
/** The capability and input a client asked for, carried in a data part. */
|
|
131
|
+
const skillFrom = (message) => {
|
|
132
|
+
const part = message.parts.find((candidate) => candidate.kind === "data");
|
|
133
|
+
if (part === void 0) return void 0;
|
|
134
|
+
const skill = part.data["skill"];
|
|
135
|
+
return typeof skill === "string" ? {
|
|
136
|
+
skill,
|
|
137
|
+
input: part.data["input"] ?? {}
|
|
138
|
+
} : void 0;
|
|
139
|
+
};
|
|
140
|
+
const decodeRequest = Schema.decodeUnknownResult(RequestSchema);
|
|
141
|
+
const decodeSendParams = Schema.decodeUnknownResult(SendParamsSchema);
|
|
142
|
+
/**
|
|
143
|
+
* Serves a contract as an A2A agent, with no transport attached.
|
|
144
|
+
*
|
|
145
|
+
* One exposed capability is one skill. A capability with no completion contract
|
|
146
|
+
* finishes at validated dispatch, so its task is `completed` immediately; one
|
|
147
|
+
* that declares completion finishes when its Message arrives.
|
|
148
|
+
*/
|
|
149
|
+
const handler = (options) => {
|
|
150
|
+
const { agent } = options;
|
|
151
|
+
const capacity = Math.max(1, options.capacity ?? 200);
|
|
152
|
+
const newId = options.newId ?? randomId;
|
|
153
|
+
const clock = options.clock ?? (() => /* @__PURE__ */ new Date());
|
|
154
|
+
const tasks = /* @__PURE__ */ new Map();
|
|
155
|
+
const running = /* @__PURE__ */ new Map();
|
|
156
|
+
const remember = (task) => {
|
|
157
|
+
tasks.set(task.id, task);
|
|
158
|
+
if (tasks.size > capacity) {
|
|
159
|
+
const oldest = tasks.keys().next().value;
|
|
160
|
+
if (oldest !== void 0) tasks.delete(oldest);
|
|
161
|
+
}
|
|
162
|
+
return task;
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* Records how a task finished, unless it already finished.
|
|
166
|
+
*
|
|
167
|
+
* A cancel lands while the dispatch is still unwinding, so the settling write
|
|
168
|
+
* arrives second and must not undo it. The task that stands is returned, so
|
|
169
|
+
* the pending `message/send` answers with the same outcome `tasks/get` shows.
|
|
170
|
+
*/
|
|
171
|
+
const settle = (task) => {
|
|
172
|
+
const current = tasks.get(task.id);
|
|
173
|
+
return current !== void 0 && terminal.has(current.status.state) ? current : remember(task);
|
|
174
|
+
};
|
|
175
|
+
const agentMessage = (body, taskId, contextId) => ({
|
|
176
|
+
kind: "message",
|
|
177
|
+
role: "agent",
|
|
178
|
+
parts: [text(body)],
|
|
179
|
+
messageId: newId(),
|
|
180
|
+
taskId,
|
|
181
|
+
contextId
|
|
182
|
+
});
|
|
183
|
+
const send = async (id, params) => {
|
|
184
|
+
const decoded = decodeSendParams(params);
|
|
185
|
+
if (decoded._tag === "Failure") return failure(id, code.INVALID_PARAMS, "message/send needs params as { message } with kind \"message\", a role, a messageId, and parts");
|
|
186
|
+
const { message } = decoded.success;
|
|
187
|
+
const asked = skillFrom(message);
|
|
188
|
+
if (asked === void 0) return failure(id, code.INVALID_PARAMS, "message/send needs a data part naming a skill, as { skill, input }");
|
|
189
|
+
const taskId = newId();
|
|
190
|
+
const contextId = message.contextId ?? newId();
|
|
191
|
+
const history = [message];
|
|
192
|
+
const controller = new AbortController();
|
|
193
|
+
running.set(taskId, controller);
|
|
194
|
+
remember({
|
|
195
|
+
kind: "task",
|
|
196
|
+
id: taskId,
|
|
197
|
+
contextId,
|
|
198
|
+
status: {
|
|
199
|
+
state: "working",
|
|
200
|
+
timestamp: clock().toISOString()
|
|
201
|
+
},
|
|
202
|
+
history
|
|
203
|
+
});
|
|
204
|
+
try {
|
|
205
|
+
const outcome = await Effect.runPromise(Effect.result(agent.messages.dispatchUnknown(asked.skill, asked.input, {
|
|
206
|
+
id: taskId,
|
|
207
|
+
transport: "a2a",
|
|
208
|
+
signal: controller.signal
|
|
209
|
+
})), { signal: controller.signal });
|
|
210
|
+
if (outcome._tag === "Failure") {
|
|
211
|
+
const error = outcome.failure;
|
|
212
|
+
return success(id, settle({
|
|
213
|
+
kind: "task",
|
|
214
|
+
id: taskId,
|
|
215
|
+
contextId,
|
|
216
|
+
status: {
|
|
217
|
+
state: stateFor(error._tag),
|
|
218
|
+
timestamp: clock().toISOString(),
|
|
219
|
+
message: agentMessage(error.message, taskId, contextId)
|
|
220
|
+
},
|
|
221
|
+
history
|
|
222
|
+
}));
|
|
223
|
+
}
|
|
224
|
+
const result = outcome.success;
|
|
225
|
+
const state = result.completion?.status === "failed" ? "failed" : "completed";
|
|
226
|
+
return success(id, settle({
|
|
227
|
+
kind: "task",
|
|
228
|
+
id: taskId,
|
|
229
|
+
contextId,
|
|
230
|
+
status: {
|
|
231
|
+
state,
|
|
232
|
+
timestamp: clock().toISOString(),
|
|
233
|
+
message: agentMessage(result.completion === void 0 ? `Dispatched ${result.tag}` : `${result.completion.status === "failed" ? "Failed" : "Completed"}: ${result.completion.message._tag}`, taskId, contextId)
|
|
234
|
+
},
|
|
235
|
+
history
|
|
236
|
+
}));
|
|
237
|
+
} catch {
|
|
238
|
+
return success(id, settle({
|
|
239
|
+
kind: "task",
|
|
240
|
+
id: taskId,
|
|
241
|
+
contextId,
|
|
242
|
+
status: {
|
|
243
|
+
state: "failed",
|
|
244
|
+
timestamp: clock().toISOString(),
|
|
245
|
+
message: agentMessage(`Skill "${asked.skill}" failed unexpectedly`, taskId, contextId)
|
|
246
|
+
},
|
|
247
|
+
history
|
|
248
|
+
}));
|
|
249
|
+
} finally {
|
|
250
|
+
running.delete(taskId);
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
const handleRequest = async (id, method, raw) => {
|
|
254
|
+
const params = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : {};
|
|
255
|
+
switch (method) {
|
|
256
|
+
case "message/send": return send(id, raw);
|
|
257
|
+
case "tasks/get": {
|
|
258
|
+
const taskId = params["id"];
|
|
259
|
+
const task = typeof taskId === "string" ? tasks.get(taskId) : void 0;
|
|
260
|
+
return task === void 0 ? failure(id, code.TASK_NOT_FOUND, "No such task") : success(id, task);
|
|
261
|
+
}
|
|
262
|
+
case "tasks/cancel": {
|
|
263
|
+
const taskId = params["id"];
|
|
264
|
+
const task = typeof taskId === "string" ? tasks.get(taskId) : void 0;
|
|
265
|
+
if (task === void 0) return failure(id, code.TASK_NOT_FOUND, "No such task");
|
|
266
|
+
if (terminal.has(task.status.state)) return failure(id, code.TASK_NOT_CANCELABLE, "Task cannot be canceled");
|
|
267
|
+
const canceled = remember({
|
|
268
|
+
...task,
|
|
269
|
+
status: {
|
|
270
|
+
state: "canceled",
|
|
271
|
+
timestamp: clock().toISOString(),
|
|
272
|
+
message: agentMessage("Canceled by the client", task.id, task.contextId)
|
|
273
|
+
}
|
|
274
|
+
});
|
|
275
|
+
running.get(task.id)?.abort();
|
|
276
|
+
return success(id, canceled);
|
|
277
|
+
}
|
|
278
|
+
case "message/stream": return failure(id, code.METHOD_NOT_FOUND, "This agent does not support streaming");
|
|
279
|
+
default: return failure(id, code.METHOD_NOT_FOUND, `Unknown method: ${method}`);
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
return {
|
|
283
|
+
handle: async (incoming) => {
|
|
284
|
+
if (Array.isArray(incoming)) return failure(null, code.INVALID_REQUEST, "Batched requests are not supported");
|
|
285
|
+
const decoded = decodeRequest(incoming);
|
|
286
|
+
if (decoded._tag === "Failure") return failure(null, code.INVALID_REQUEST, "Not a JSON-RPC 2.0 message");
|
|
287
|
+
const request = decoded.success;
|
|
288
|
+
if (request.id === void 0) return void 0;
|
|
289
|
+
return handleRequest(request.id, request.method, request.params);
|
|
290
|
+
},
|
|
291
|
+
close: () => {
|
|
292
|
+
for (const controller of running.values()) controller.abort();
|
|
293
|
+
running.clear();
|
|
294
|
+
tasks.clear();
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
};
|
|
298
|
+
//#endregion
|
|
299
|
+
//#region src/agentA2a.ts
|
|
300
|
+
var agentA2a_exports = /* @__PURE__ */ __exportAll({
|
|
301
|
+
A2A_VERSION: () => A2A_VERSION,
|
|
302
|
+
AGENT_CARD_PATH: () => AGENT_CARD_PATH,
|
|
303
|
+
agentCard: () => agentCard,
|
|
304
|
+
handler: () => handler
|
|
305
|
+
});
|
|
306
|
+
//#endregion
|
|
307
|
+
export { agentA2a_exports as AgentA2a };
|
|
308
|
+
|
|
309
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/card.ts","../src/types.ts","../src/handler.ts","../src/agentA2a.ts"],"sourcesContent":["import { Agent } from 'foldkit-agent'\nimport type { Definition } from './types.js'\n\n/** Where an A2A client looks for the card. */\nexport const AGENT_CARD_PATH = '/.well-known/agent-card.json'\n\n/** One thing this agent can do. Derived from an exposed capability. */\nexport interface AgentSkill {\n readonly id: string\n readonly name: string\n readonly description: string\n readonly tags: ReadonlyArray<string>\n /**\n * The JSON Schema for this skill's input, as the contract derived it.\n *\n * Deliberately beyond the spec. A 0.3.0 `AgentSkill` describes its input only\n * in prose -- `inputModes` carries media types, not shapes -- so a caller has\n * nothing to construct a valid request from, which is the one thing this\n * contract already knows. The card validates because `AgentSkill` leaves\n * `additionalProperties` unset, not because the field is sanctioned.\n *\n * The risk is a later spec claiming this name for something else: the card\n * would not fail, it would quietly mean something a conforming client reads\n * differently. The spec-legal alternative is an `AgentExtension` under\n * `capabilities.extensions`, whose `params` would hold a skill-id-keyed map --\n * worth moving to when a real client consumes this, or the moment A2A\n * proposes a per-skill schema field. A conformance test pins the set of extra\n * keys so a second one cannot appear unnoticed.\n */\n readonly inputSchema: Record<string, unknown>\n}\n\nexport interface AgentCard {\n readonly protocolVersion: string\n readonly name: string\n readonly description: string\n /** Where this agent accepts A2A requests. */\n readonly url: string\n /** The transport bound to `url`. This adapter speaks JSON-RPC and nothing else. */\n readonly preferredTransport: 'JSONRPC'\n readonly version: string\n readonly capabilities: {\n readonly streaming: boolean\n readonly pushNotifications: boolean\n }\n readonly defaultInputModes: ReadonlyArray<string>\n readonly defaultOutputModes: ReadonlyArray<string>\n readonly skills: ReadonlyArray<AgentSkill>\n readonly securitySchemes?: Record<string, unknown> | undefined\n readonly security?: ReadonlyArray<Record<string, ReadonlyArray<string>>> | undefined\n}\n\nexport const A2A_VERSION = '0.3.0'\n\nexport interface AgentCardOptions {\n readonly name: string\n readonly description: string\n /** The endpoint that answers `message/send`. */\n readonly url: string\n readonly version?: string | undefined\n /** Declared so a client knows how to authenticate before it calls. */\n readonly securitySchemes?: Record<string, unknown> | undefined\n readonly security?: ReadonlyArray<Record<string, ReadonlyArray<string>>> | undefined\n}\n\n/**\n * Builds the card an A2A client fetches before calling.\n *\n * Skills are the exposed capabilities: the same descriptors MCP lists as tools.\n * A capability that is only available in some Model states is tagged, because a\n * card is static while availability is not.\n */\nexport const agentCard = (definition: Definition, options: AgentCardOptions): AgentCard => ({\n protocolVersion: A2A_VERSION,\n name: options.name,\n description: options.description,\n url: options.url,\n preferredTransport: 'JSONRPC',\n version: options.version ?? '0.1.0',\n // Streaming and push notifications are not implemented; saying otherwise\n // would have clients wait for events that never arrive.\n capabilities: { streaming: false, pushNotifications: false },\n defaultInputModes: ['application/json'],\n defaultOutputModes: ['application/json'],\n skills: Agent.messages(definition).map(capability => ({\n id: capability.name,\n name: capability.name,\n description: capability.description,\n tags: [\n ...(capability.modelDependent ? ['conditional'] : []),\n ...(capability.requiresAuthorization ? ['authorized'] : []),\n ],\n inputSchema: capability.inputSchema,\n })),\n ...(options.securitySchemes === undefined ? {} : { securitySchemes: options.securitySchemes }),\n ...(options.security === undefined ? {} : { security: options.security }),\n})\n","import { Schema } from 'effect'\nimport type { Agent } from 'foldkit-agent'\n\n/**\n * The bound contract, with its capability maps left open.\n *\n * An adapter reads names off the wire, so it works against the permissive maps\n * rather than a particular application's.\n */\nexport type AgentRuntime = Agent.AgentRuntime<any, any, any, any, any>\n\nexport type Definition = Agent.Definition<any, any, any, any, any>\n\n/**\n * The JSON-RPC envelope A2A uses.\n *\n * Deliberately a local copy rather than shared with `foldkit-agent-mcp`: two\n * protocols that happen to use the same envelope should not be coupled through\n * it.\n */\nexport type Id = string | number\n\nexport interface Request {\n readonly jsonrpc: '2.0'\n readonly id: Id\n readonly method: string\n /** Unvalidated until a method decides what its own params must look like. */\n readonly params?: unknown\n}\n\n/**\n * The envelope, decoded before anything reads a field off it.\n *\n * `params` stays `unknown` here: what a method requires is the method's\n * business, and deciding it here would answer bad params with the wrong code.\n */\nexport const RequestSchema = Schema.Struct({\n jsonrpc: Schema.Literal('2.0'),\n id: Schema.optional(Schema.Union([Schema.String, Schema.Number])),\n method: Schema.String,\n params: Schema.optional(Schema.Unknown),\n})\n\nexport interface Success {\n readonly jsonrpc: '2.0'\n readonly id: Id\n readonly result: unknown\n}\n\nexport interface Failure {\n readonly jsonrpc: '2.0'\n readonly id: Id | null\n readonly error: { readonly code: number; readonly message: string }\n}\n\nexport type Response = Success | Failure\n\nexport const code = {\n INVALID_REQUEST: -32600,\n METHOD_NOT_FOUND: -32601,\n INVALID_PARAMS: -32602,\n /** A2A: the task id is not one this agent issued. */\n TASK_NOT_FOUND: -32001,\n /** A2A: the task has already settled, so there is nothing left to cancel. */\n TASK_NOT_CANCELABLE: -32002,\n} as const\n\nexport const success = (id: Id, result: unknown): Success => ({ jsonrpc: '2.0', id, result })\n\nexport const failure = (id: Id | null, errorCode: number, message: string): Failure => ({\n jsonrpc: '2.0',\n id,\n error: { code: errorCode, message },\n})\n\n/**\n * The subset of A2A 0.3.0 task states this adapter produces.\n *\n * `input-required`, `auth-required` and `unknown` are spec states no dispatch\n * here can reach, so they are left out rather than declared and never used.\n */\nexport type TaskState = 'submitted' | 'working' | 'completed' | 'failed' | 'canceled' | 'rejected'\n\n/** States a task cannot leave. A later settle must not overwrite one. */\nexport const terminal: ReadonlySet<TaskState> = new Set<TaskState>([\n 'completed',\n 'failed',\n 'canceled',\n 'rejected',\n])\n\nexport interface TaskStatus {\n readonly state: TaskState\n readonly timestamp: string\n /** What happened, in the agent's own words. */\n readonly message?: Message | undefined\n}\n\n/**\n * A part carries either text or data, and which one is not optional.\n *\n * A single struct with both fields optional would accept\n * `{ kind: 'data' }` and leave every reader to re-check.\n */\nexport const PartSchema = Schema.Union([\n Schema.Struct({ kind: Schema.Literal('text'), text: Schema.String }),\n Schema.Struct({\n kind: Schema.Literal('data'),\n data: Schema.Record(Schema.String, Schema.Unknown),\n }),\n])\n\nexport type Part = typeof PartSchema.Type\n\n/**\n * `kind` is required by the spec, not decoration: `Task | Message` is a union a\n * client discriminates on, so a message without it is not a Message.\n */\nexport const MessageSchema = Schema.Struct({\n kind: Schema.Literal('message'),\n role: Schema.Literals(['user', 'agent']),\n parts: Schema.Array(PartSchema),\n messageId: Schema.String,\n taskId: Schema.optional(Schema.String),\n contextId: Schema.optional(Schema.String),\n})\n\nexport type Message = typeof MessageSchema.Type\n\n/** What `message/send` requires of its params. */\nexport const SendParamsSchema = Schema.Struct({ message: MessageSchema })\n\nexport interface Task {\n readonly kind: 'task'\n readonly id: string\n readonly contextId: string\n readonly status: TaskStatus\n readonly history: ReadonlyArray<Message>\n}\n\nexport const text = (body: string): Part => ({ kind: 'text', text: body })\n","import { Effect, Schema } from 'effect'\nimport {\n type AgentRuntime,\n type Id,\n type Message,\n RequestSchema,\n type Response,\n SendParamsSchema,\n type Task,\n type TaskState,\n code,\n failure,\n success,\n terminal,\n text,\n} from './types.js'\n\nexport interface HandlerOptions {\n readonly agent: AgentRuntime\n /** Tasks kept for `tasks/get`. Defaults to 200. */\n readonly capacity?: number | undefined\n /** Injected for tests. */\n readonly newId?: (() => string) | undefined\n readonly clock?: (() => Date) | undefined\n}\n\nexport interface Handler {\n readonly handle: (message: unknown) => Promise<Response | undefined>\n readonly close: () => void\n}\n\nconst randomId = (): string =>\n typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n ? crypto.randomUUID()\n : `a2a-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n\n/**\n * How a refused or finished dispatch reads as a task state.\n *\n * `rejected` is for a request the agent declined outright -- an unknown skill,\n * bad input, a caller who may not. `failed` is for work that was accepted and\n * did not succeed, which is a different thing to a client deciding what to do\n * next.\n */\nconst stateFor = (failureTag: string): TaskState => {\n switch (failureTag) {\n case 'AgentCancelledError':\n return 'canceled'\n case 'AgentCompletionTimeoutError':\n return 'failed'\n default:\n return 'rejected'\n }\n}\n\n/** The capability and input a client asked for, carried in a data part. */\nconst skillFrom = (\n message: Message,\n): { readonly skill: string; readonly input: unknown } | undefined => {\n const part = message.parts.find(candidate => candidate.kind === 'data')\n if (part === undefined) return undefined\n const skill = part.data['skill']\n return typeof skill === 'string' ? { skill, input: part.data['input'] ?? {} } : undefined\n}\n\nconst decodeRequest = Schema.decodeUnknownResult(RequestSchema)\nconst decodeSendParams = Schema.decodeUnknownResult(SendParamsSchema)\n\n/**\n * Serves a contract as an A2A agent, with no transport attached.\n *\n * One exposed capability is one skill. A capability with no completion contract\n * finishes at validated dispatch, so its task is `completed` immediately; one\n * that declares completion finishes when its Message arrives.\n */\nexport const handler = (options: HandlerOptions): Handler => {\n const { agent } = options\n const capacity = Math.max(1, options.capacity ?? 200)\n const newId = options.newId ?? randomId\n const clock = options.clock ?? (() => new Date())\n\n const tasks = new Map<string, Task>()\n const running = new Map<string, AbortController>()\n\n const remember = (task: Task): Task => {\n tasks.set(task.id, task)\n if (tasks.size > capacity) {\n const oldest = tasks.keys().next().value\n if (oldest !== undefined) tasks.delete(oldest)\n }\n return task\n }\n\n /**\n * Records how a task finished, unless it already finished.\n *\n * A cancel lands while the dispatch is still unwinding, so the settling write\n * arrives second and must not undo it. The task that stands is returned, so\n * the pending `message/send` answers with the same outcome `tasks/get` shows.\n */\n const settle = (task: Task): Task => {\n const current = tasks.get(task.id)\n return current !== undefined && terminal.has(current.status.state) ? current : remember(task)\n }\n\n const agentMessage = (body: string, taskId: string, contextId: string): Message => ({\n kind: 'message',\n role: 'agent',\n parts: [text(body)],\n messageId: newId(),\n taskId,\n contextId,\n })\n\n const send = async (id: Id, params: unknown): Promise<Response> => {\n const decoded = decodeSendParams(params)\n if (decoded._tag === 'Failure') {\n return failure(\n id,\n code.INVALID_PARAMS,\n 'message/send needs params as { message } with kind \"message\", a role, a messageId, and parts',\n )\n }\n\n const { message } = decoded.success\n const asked = skillFrom(message)\n\n if (asked === undefined) {\n return failure(\n id,\n code.INVALID_PARAMS,\n 'message/send needs a data part naming a skill, as { skill, input }',\n )\n }\n\n const taskId = newId()\n const contextId = message.contextId ?? newId()\n const history: ReadonlyArray<Message> = [message]\n\n const controller = new AbortController()\n running.set(taskId, controller)\n\n // Recorded before the work starts: a task a client cannot address while it\n // runs is a task it cannot get or cancel.\n remember({\n kind: 'task',\n id: taskId,\n contextId,\n status: { state: 'working', timestamp: clock().toISOString() },\n history,\n })\n\n try {\n // The signal reaches the run as well as the invocation. The runtime now\n // races the completion wait against it, so the invocation settles on its\n // own; interrupting the fiber additionally covers what the runtime cannot\n // see -- an abort landing while Schema decoding or a suspending authorize\n // hook is still in flight.\n const outcome = await Effect.runPromise(\n Effect.result(\n agent.messages.dispatchUnknown(asked.skill, asked.input, {\n id: taskId,\n transport: 'a2a',\n signal: controller.signal,\n }),\n ),\n { signal: controller.signal },\n )\n\n if (outcome._tag === 'Failure') {\n const error = outcome.failure\n return success(\n id,\n settle({\n kind: 'task',\n id: taskId,\n contextId,\n status: {\n state: stateFor(error._tag),\n timestamp: clock().toISOString(),\n message: agentMessage(error.message, taskId, contextId),\n },\n history,\n }),\n )\n }\n\n const result = outcome.success\n // A declared failure Message is work that ran and did not succeed.\n const state: TaskState = result.completion?.status === 'failed' ? 'failed' : 'completed'\n\n return success(\n id,\n settle({\n kind: 'task',\n id: taskId,\n contextId,\n status: {\n state,\n timestamp: clock().toISOString(),\n message: agentMessage(\n result.completion === undefined\n ? `Dispatched ${result.tag}`\n : `${result.completion.status === 'failed' ? 'Failed' : 'Completed'}: ${result.completion.message._tag}`,\n taskId,\n contextId,\n ),\n },\n history,\n }),\n )\n } catch {\n return success(\n id,\n settle({\n kind: 'task',\n id: taskId,\n contextId,\n status: {\n state: 'failed',\n timestamp: clock().toISOString(),\n message: agentMessage(`Skill \"${asked.skill}\" failed unexpectedly`, taskId, contextId),\n },\n history,\n }),\n )\n } finally {\n running.delete(taskId)\n }\n }\n\n const handleRequest = async (id: Id, method: string, raw: unknown): Promise<Response> => {\n const params: Record<string, unknown> =\n typeof raw === 'object' && raw !== null && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {}\n\n switch (method) {\n case 'message/send':\n return send(id, raw)\n\n case 'tasks/get': {\n const taskId = params['id']\n const task = typeof taskId === 'string' ? tasks.get(taskId) : undefined\n return task === undefined\n ? failure(id, code.TASK_NOT_FOUND, 'No such task')\n : success(id, task)\n }\n\n case 'tasks/cancel': {\n const taskId = params['id']\n const task = typeof taskId === 'string' ? tasks.get(taskId) : undefined\n if (task === undefined) return failure(id, code.TASK_NOT_FOUND, 'No such task')\n\n if (terminal.has(task.status.state)) {\n return failure(id, code.TASK_NOT_CANCELABLE, 'Task cannot be canceled')\n }\n\n // The canceled state is recorded before the abort, so the dispatch it\n // interrupts cannot settle over it on its way out. Cancelling stops the\n // waiting, not the Messages already dispatched.\n const canceled = remember({\n ...task,\n status: {\n state: 'canceled',\n timestamp: clock().toISOString(),\n message: agentMessage('Canceled by the client', task.id, task.contextId),\n },\n })\n running.get(task.id)?.abort()\n\n return success(id, canceled)\n }\n\n // Streaming is declared unsupported on the card, so it is refused here\n // rather than answered with something a client cannot consume.\n case 'message/stream':\n return failure(id, code.METHOD_NOT_FOUND, 'This agent does not support streaming')\n\n default:\n return failure(id, code.METHOD_NOT_FOUND, `Unknown method: ${method}`)\n }\n }\n\n return {\n handle: async (incoming: unknown): Promise<Response | undefined> => {\n if (Array.isArray(incoming)) {\n return failure(null, code.INVALID_REQUEST, 'Batched requests are not supported')\n }\n\n const decoded = decodeRequest(incoming)\n if (decoded._tag === 'Failure') {\n return failure(null, code.INVALID_REQUEST, 'Not a JSON-RPC 2.0 message')\n }\n\n const request = decoded.success\n // A notification carries no id and expects no reply.\n if (request.id === undefined) return undefined\n\n return handleRequest(request.id, request.method, request.params)\n },\n\n close: () => {\n for (const controller of running.values()) controller.abort()\n running.clear()\n tasks.clear()\n },\n }\n}\n","export {\n AGENT_CARD_PATH,\n A2A_VERSION,\n agentCard,\n type AgentCard,\n type AgentCardOptions,\n type AgentSkill,\n} from './card.js'\nexport { handler, type Handler, type HandlerOptions } from './handler.js'\n"],"mappings":";;;;;AAIA,MAAa,kBAAkB;AAgD/B,MAAa,cAAc;;;;;;;;AAoB3B,MAAa,aAAa,YAAwB,aAA0C;CAC1F,iBAAiB;CACjB,MAAM,QAAQ;CACd,aAAa,QAAQ;CACrB,KAAK,QAAQ;CACb,oBAAoB;CACpB,SAAS,QAAQ,WAAW;CAG5B,cAAc;EAAE,WAAW;EAAO,mBAAmB;CAAM;CAC3D,mBAAmB,CAAC,kBAAkB;CACtC,oBAAoB,CAAC,kBAAkB;CACvC,QAAQ,MAAM,SAAS,UAAU,CAAC,CAAC,KAAI,gBAAe;EACpD,IAAI,WAAW;EACf,MAAM,WAAW;EACjB,aAAa,WAAW;EACxB,MAAM,CACJ,GAAI,WAAW,iBAAiB,CAAC,aAAa,IAAI,CAAC,GACnD,GAAI,WAAW,wBAAwB,CAAC,YAAY,IAAI,CAAC,CAC3D;EACA,aAAa,WAAW;CAC1B,EAAE;CACF,GAAI,QAAQ,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,QAAQ,gBAAgB;CAC5F,GAAI,QAAQ,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,QAAQ,SAAS;AACzE;;;;;;;;;AC5DA,MAAa,gBAAgB,OAAO,OAAO;CACzC,SAAS,OAAO,QAAQ,KAAK;CAC7B,IAAI,OAAO,SAAS,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC,CAAC;CAChE,QAAQ,OAAO;CACf,QAAQ,OAAO,SAAS,OAAO,OAAO;AACxC,CAAC;AAgBD,MAAa,OAAO;CAClB,iBAAiB;CACjB,kBAAkB;CAClB,gBAAgB;;CAEhB,gBAAgB;;CAEhB,qBAAqB;AACvB;AAEA,MAAa,WAAW,IAAQ,YAA8B;CAAE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QAAQ;EACzE;CACF;CAEA,OAAO;EACL,QAAQ,OAAO,aAAqD;GAClE,IAAI,MAAM,QAAQ,QAAQ,GACxB,OAAO,QAAQ,MAAM,KAAK,iBAAiB,oCAAoC;GAGjF,MAAM,UAAU,cAAc,QAAQ;GACtC,IAAI,QAAQ,SAAS,WACnB,OAAO,QAAQ,MAAM,KAAK,iBAAiB,4BAA4B;GAGzE,MAAM,UAAU,QAAQ;GAExB,IAAI,QAAQ,OAAO,KAAA,GAAW,OAAO,KAAA;GAErC,OAAO,cAAc,QAAQ,IAAI,QAAQ,QAAQ,QAAQ,MAAM;EACjE;EAEA,aAAa;GACX,KAAK,MAAM,cAAc,QAAQ,OAAO,GAAG,WAAW,MAAM;GAC5D,QAAQ,MAAM;GACd,MAAM,MAAM;EACd;CACF;AACF"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __exportAll = (all, no_symbols) => {
|
|
4
|
+
let target = {};
|
|
5
|
+
for (var name in all) __defProp(target, name, {
|
|
6
|
+
get: all[name],
|
|
7
|
+
enumerable: true
|
|
8
|
+
});
|
|
9
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
10
|
+
return target;
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
|
13
|
+
export { __exportAll as t };
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "foldkit-agent-a2a",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A2A adapter for foldkit-agent. Serves a Foldkit agent contract as an A2A agent.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"foldkit",
|
|
7
|
+
"effect",
|
|
8
|
+
"agents",
|
|
9
|
+
"a2a"
|
|
10
|
+
],
|
|
11
|
+
"type": "module",
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"author": "Patrick Glenn <doeixd@gmail.com>",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/doeixd/foldkit-plus.git",
|
|
17
|
+
"directory": "packages/agent-a2a"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/doeixd/foldkit-plus/tree/main/packages/agent-a2a#readme",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/doeixd/foldkit-plus/issues"
|
|
22
|
+
},
|
|
23
|
+
"sideEffects": false,
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.mts",
|
|
30
|
+
"import": "./dist/index.mjs"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"effect": "^4.0.0-rc.112",
|
|
40
|
+
"foldkit": "^0.158.2",
|
|
41
|
+
"foldkit-agent": "^0.1.0"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"effect": "4.0.0-rc.112",
|
|
45
|
+
"foldkit": "0.158.2",
|
|
46
|
+
"tsdown": "^0.23.0",
|
|
47
|
+
"typescript": "^5.7.2",
|
|
48
|
+
"foldkit-agent": "0.1.0"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "tsdown",
|
|
52
|
+
"typecheck": "tsc -b"
|
|
53
|
+
}
|
|
54
|
+
}
|