marona 2.7.0 → 2.8.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/CHANGELOG.md +8 -0
- package/README.md +120 -6
- package/dist/b2a-codec.js +1 -1
- package/dist/b2a-content.d.ts +0 -1
- package/dist/b2a-content.d.ts.map +1 -1
- package/dist/b2a-content.js +4 -57
- package/dist/b2a-content.js.map +1 -1
- package/dist/b2a-runner.d.ts +4 -0
- package/dist/b2a-runner.d.ts.map +1 -1
- package/dist/b2a-runner.js +31 -0
- package/dist/b2a-runner.js.map +1 -1
- package/dist/d2a.d.ts +162 -0
- package/dist/d2a.d.ts.map +1 -0
- package/dist/d2a.js +621 -0
- package/dist/d2a.js.map +1 -0
- package/dist/index.d.ts +11 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -8
- package/dist/index.js.map +1 -1
- package/dist/message-content.d.ts +6 -0
- package/dist/message-content.d.ts.map +1 -0
- package/dist/message-content.js +57 -0
- package/dist/message-content.js.map +1 -0
- package/dist/protocols.d.ts +33 -0
- package/dist/protocols.d.ts.map +1 -1
- package/dist/protocols.js +203 -1
- package/dist/protocols.js.map +1 -1
- package/package.json +2 -2
package/dist/d2a.js
ADDED
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
import { validateMessageContent, validateMessageStream } from './message-content.js';
|
|
2
|
+
import { matchesSchema } from './schema.js';
|
|
3
|
+
import { nativeProtocolBinding, protocolResult } from './index.js';
|
|
4
|
+
export const D2A_VERSION = '1.0';
|
|
5
|
+
const statuses = new Set(['accepted', 'executing', 'succeeded', 'rejected', 'failed', 'cancelled', 'expired', 'unknown']);
|
|
6
|
+
export class D2AProtocolError extends Error {
|
|
7
|
+
}
|
|
8
|
+
export class D2ARunError extends D2AProtocolError {
|
|
9
|
+
event;
|
|
10
|
+
result;
|
|
11
|
+
constructor(event, result) {
|
|
12
|
+
super(`D2A run requires attention: ${event.type}`);
|
|
13
|
+
this.event = event;
|
|
14
|
+
this.result = result;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function d2aObject(value) {
|
|
18
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
19
|
+
throw new D2AProtocolError('Expected a JSON object');
|
|
20
|
+
const seen = new Set();
|
|
21
|
+
const check = (node) => {
|
|
22
|
+
if (node === null || typeof node === 'string' || typeof node === 'boolean')
|
|
23
|
+
return;
|
|
24
|
+
if (typeof node === 'number' && Number.isFinite(node))
|
|
25
|
+
return;
|
|
26
|
+
if (typeof node !== 'object' || !node)
|
|
27
|
+
throw new D2AProtocolError('Values must be finite JSON');
|
|
28
|
+
if (!Array.isArray(node) && Object.getPrototypeOf(node) !== Object.prototype && Object.getPrototypeOf(node) !== null)
|
|
29
|
+
throw new D2AProtocolError('Values must be plain JSON');
|
|
30
|
+
if (seen.has(node))
|
|
31
|
+
throw new D2AProtocolError('JSON values cannot contain cycles');
|
|
32
|
+
seen.add(node);
|
|
33
|
+
Object.values(node).forEach(check);
|
|
34
|
+
seen.delete(node);
|
|
35
|
+
};
|
|
36
|
+
check(value);
|
|
37
|
+
return structuredClone(value);
|
|
38
|
+
}
|
|
39
|
+
function nonempty(value, field) {
|
|
40
|
+
if (typeof value !== 'string' || !value.trim())
|
|
41
|
+
throw new D2AProtocolError(`${field} is required`);
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
/** Same immutable envelope in either direction. Only action messages can invoke devices. */
|
|
45
|
+
export class D2AMessage {
|
|
46
|
+
value;
|
|
47
|
+
constructor(options) {
|
|
48
|
+
const value = { protocol: 'd2a', version: D2A_VERSION, type: 'message', source: options.source,
|
|
49
|
+
message_id: options.messageId ?? crypto.randomUUID(), timestamp: new Date().toISOString(),
|
|
50
|
+
payload: { ...options.payload, kind: options.kind, content: options.content } };
|
|
51
|
+
if (options.target !== undefined)
|
|
52
|
+
value.target = options.target;
|
|
53
|
+
if (options.correlationId !== undefined)
|
|
54
|
+
value.correlation_id = options.correlationId;
|
|
55
|
+
if (options.expiresAt !== undefined)
|
|
56
|
+
value.expires_at = options.expiresAt;
|
|
57
|
+
this.value = D2AMessage.validate(value);
|
|
58
|
+
}
|
|
59
|
+
static validate(input) {
|
|
60
|
+
const value = d2aObject(input), payload = d2aObject(value.payload);
|
|
61
|
+
if (value.protocol !== 'd2a' || value.version !== D2A_VERSION || value.type !== 'message')
|
|
62
|
+
throw new D2AProtocolError('Unsupported D2A envelope');
|
|
63
|
+
const fields = new Set(['protocol', 'version', 'type', 'source', 'target', 'message_id', 'timestamp', 'session_id', 'sequence', 'correlation_id', 'expires_at', 'stream', 'payload']);
|
|
64
|
+
if (Object.keys(value).some(key => !fields.has(key)))
|
|
65
|
+
throw new D2AProtocolError('Unknown envelope field');
|
|
66
|
+
if (Object.hasOwn(value, 'session_id') !== Object.hasOwn(value, 'sequence'))
|
|
67
|
+
throw new D2AProtocolError('session_id and sequence must be supplied together');
|
|
68
|
+
for (const key of ['source', 'target', 'message_id', 'session_id', 'correlation_id'])
|
|
69
|
+
if (typeof value[key] === 'string' && String(value[key]).length > 256)
|
|
70
|
+
throw new D2AProtocolError('Identifier exceeds 256 characters');
|
|
71
|
+
for (const key of ['source', 'message_id', 'timestamp'])
|
|
72
|
+
nonempty(value[key], key);
|
|
73
|
+
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(String(value.timestamp)) || !Number.isFinite(Date.parse(String(value.timestamp))))
|
|
74
|
+
throw new D2AProtocolError('Invalid timestamp');
|
|
75
|
+
if (value.expires_at !== undefined && !Number.isFinite(Date.parse(String(value.expires_at))))
|
|
76
|
+
throw new D2AProtocolError('Invalid expiry');
|
|
77
|
+
for (const key of ['target', 'session_id', 'correlation_id'])
|
|
78
|
+
if (value[key] !== undefined)
|
|
79
|
+
nonempty(value[key], key);
|
|
80
|
+
if (value.sequence !== undefined && (!Number.isSafeInteger(value.sequence) || Number(value.sequence) < 1))
|
|
81
|
+
throw new D2AProtocolError('Invalid sequence');
|
|
82
|
+
if (!['observation', 'state', 'action', 'feedback', 'coordination'].includes(String(payload.kind)))
|
|
83
|
+
throw new D2AProtocolError('Invalid message kind');
|
|
84
|
+
validateMessageContent(payload.content, message => { throw new D2AProtocolError(message); }, ['action', 'feedback', 'coordination'].includes(String(payload.kind)));
|
|
85
|
+
for (const block of payload.content)
|
|
86
|
+
if (block.uri !== undefined && new URL(String(block.uri)).protocol !== 'https:')
|
|
87
|
+
throw new D2AProtocolError('Device resources require HTTPS');
|
|
88
|
+
if (value.stream !== undefined)
|
|
89
|
+
validateMessageStream(d2aObject(value.stream), message => { throw new D2AProtocolError(message); }, 256);
|
|
90
|
+
for (const key of ['execute', 'approved'])
|
|
91
|
+
if (payload[key] !== undefined && typeof payload[key] !== 'boolean')
|
|
92
|
+
throw new D2AProtocolError(`${key} must be boolean`);
|
|
93
|
+
if (payload.kind === 'action') {
|
|
94
|
+
if (value.source !== 'agent')
|
|
95
|
+
throw new D2AProtocolError('Action source must be agent');
|
|
96
|
+
nonempty(value.target, 'target');
|
|
97
|
+
nonempty(payload.action_id, 'action_id');
|
|
98
|
+
nonempty(payload.capability, 'capability');
|
|
99
|
+
d2aObject(payload.arguments);
|
|
100
|
+
}
|
|
101
|
+
if (payload.kind === 'feedback') {
|
|
102
|
+
if (!Object.hasOwn(payload, 'result'))
|
|
103
|
+
throw new D2AProtocolError('Feedback requires result');
|
|
104
|
+
nonempty(payload.action_id, 'action_id');
|
|
105
|
+
if (!statuses.has(String(payload.status)))
|
|
106
|
+
throw new D2AProtocolError('Invalid action status');
|
|
107
|
+
}
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
static fromJSON(value) { const message = Object.create(D2AMessage.prototype); Object.defineProperty(message, 'value', { value: D2AMessage.validate(value) }); return message; }
|
|
111
|
+
static observation(source, content) { return new D2AMessage({ source, kind: 'observation', content }); }
|
|
112
|
+
static action(target, capability, args, options = {}) {
|
|
113
|
+
return new D2AMessage({ source: 'agent', target, kind: 'action', content: [{ type: 'control', data: args }], expiresAt: options.expiresAt,
|
|
114
|
+
payload: { action_id: options.actionId ?? crypto.randomUUID(), capability, arguments: args, ...(options.expectedRevision === undefined ? {} : { expected_revision: options.expectedRevision }) } });
|
|
115
|
+
}
|
|
116
|
+
static feedback(action, status, result) {
|
|
117
|
+
const body = action.toJSON(), p = d2aObject(body.payload);
|
|
118
|
+
return new D2AMessage({ source: String(body.target), target: String(body.source), kind: 'feedback', correlationId: String(body.message_id),
|
|
119
|
+
content: [{ type: 'd2a:result', data: result }], payload: { action_id: p.action_id, status, result, execute: false } });
|
|
120
|
+
}
|
|
121
|
+
toJSON() { return structuredClone(this.value); }
|
|
122
|
+
bind(sessionId, sequence) { return D2AMessage.fromJSON({ ...this.value, session_id: sessionId, sequence }); }
|
|
123
|
+
}
|
|
124
|
+
/** Vendor independent provider. MCP command tools require a genuine event stream adapter. */
|
|
125
|
+
export class D2ADevice {
|
|
126
|
+
options;
|
|
127
|
+
url;
|
|
128
|
+
fetcher;
|
|
129
|
+
constructor(url, options) {
|
|
130
|
+
this.options = options;
|
|
131
|
+
const parsed = new URL(url);
|
|
132
|
+
if (!['https:', 'http:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.search || parsed.hash || parsed.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname))
|
|
133
|
+
throw new D2AProtocolError('Device endpoint requires HTTPS (HTTP is allowed on loopback)');
|
|
134
|
+
nonempty(options.token, 'token');
|
|
135
|
+
this.url = parsed.toString().replace(/\/$/, '');
|
|
136
|
+
this.fetcher = options.fetch ?? globalThis.fetch;
|
|
137
|
+
if (options.transport && !['http', 'mcp'].includes(options.transport))
|
|
138
|
+
throw new D2AProtocolError('Invalid transport');
|
|
139
|
+
if (options.timeoutMs !== undefined && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0))
|
|
140
|
+
throw new D2AProtocolError('Invalid timeout');
|
|
141
|
+
if (options.transport === 'mcp' && !options.events)
|
|
142
|
+
throw new D2AProtocolError('MCP providers require a persistent events adapter');
|
|
143
|
+
}
|
|
144
|
+
async request(method, path, body) {
|
|
145
|
+
const response = await this.fetcher(this.url + path, { method, redirect: 'error', signal: AbortSignal.timeout(this.options.timeoutMs ?? 60000),
|
|
146
|
+
headers: { Authorization: `Bearer ${this.options.token}`, 'Content-Type': 'application/json', Accept: 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
|
147
|
+
if (!response.ok)
|
|
148
|
+
throw new D2AProtocolError(`Device service returned HTTP ${response.status}`);
|
|
149
|
+
return d2aObject(await response.json());
|
|
150
|
+
}
|
|
151
|
+
async call(operation, args, method, path, body) {
|
|
152
|
+
if (this.options.transport !== 'mcp')
|
|
153
|
+
return this.request(method, path, body);
|
|
154
|
+
const headers = { Authorization: `Bearer ${this.options.token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' };
|
|
155
|
+
const post = async (payload) => {
|
|
156
|
+
const response = await this.fetcher(this.url, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(this.options.timeoutMs ?? 60000), headers, body: JSON.stringify(payload) });
|
|
157
|
+
if (!response.ok)
|
|
158
|
+
throw new D2AProtocolError(`MCP service returned HTTP ${response.status}`);
|
|
159
|
+
return response;
|
|
160
|
+
};
|
|
161
|
+
const rpc = async (response, id) => {
|
|
162
|
+
let value;
|
|
163
|
+
if (response.headers.get('content-type')?.includes('text/event-stream')) {
|
|
164
|
+
for await (const frame of readD2ASSE(response))
|
|
165
|
+
if (frame.id === id) {
|
|
166
|
+
value = frame;
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
else
|
|
171
|
+
value = d2aObject(await response.json());
|
|
172
|
+
if (!value || value.id !== id || value.error)
|
|
173
|
+
throw new D2AProtocolError('MCP request failed');
|
|
174
|
+
return d2aObject(value.result);
|
|
175
|
+
};
|
|
176
|
+
try {
|
|
177
|
+
const response = await post({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'marona', version: '1.0' } } });
|
|
178
|
+
const session = response.headers.get('mcp-session-id');
|
|
179
|
+
if (session)
|
|
180
|
+
headers['Mcp-Session-Id'] = session;
|
|
181
|
+
const initialized = await rpc(response, 1), version = String(initialized.protocolVersion);
|
|
182
|
+
if (!['2025-11-25', '2025-06-18', '2025-03-26'].includes(version))
|
|
183
|
+
throw new D2AProtocolError('Unsupported MCP version');
|
|
184
|
+
headers['MCP-Protocol-Version'] = version;
|
|
185
|
+
await (await post({ jsonrpc: '2.0', method: 'notifications/initialized' })).body?.cancel();
|
|
186
|
+
const result = await rpc(await post({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: operation, arguments: args } }), 2);
|
|
187
|
+
if (result.isError)
|
|
188
|
+
throw new D2AProtocolError('Device MCP tool failed');
|
|
189
|
+
const structured = d2aObject(result.structuredContent);
|
|
190
|
+
if (structured.success === false)
|
|
191
|
+
throw new D2AProtocolError('Device MCP tool failed');
|
|
192
|
+
return structured.success === true ? d2aObject(structured.data) : structured;
|
|
193
|
+
}
|
|
194
|
+
finally {
|
|
195
|
+
if (headers['Mcp-Session-Id'])
|
|
196
|
+
try {
|
|
197
|
+
await (await this.fetcher(this.url, { method: 'DELETE', headers, redirect: 'error', signal: AbortSignal.timeout(1000) })).body?.cancel();
|
|
198
|
+
}
|
|
199
|
+
catch { }
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
async discover() { return validateDevices(await this.call('discover', {}, 'GET', '/v1/devices')); }
|
|
203
|
+
async *events(sessionId, cursor, signal) {
|
|
204
|
+
if (this.options.events) {
|
|
205
|
+
yield* this.options.events(sessionId, cursor, signal);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const query = new URLSearchParams({ session_id: sessionId });
|
|
209
|
+
if (cursor)
|
|
210
|
+
query.set('cursor', cursor);
|
|
211
|
+
const response = await this.fetcher(`${this.url}/v1/events?${query}`, { headers: { Authorization: `Bearer ${this.options.token}`, Accept: 'text/event-stream' }, signal, redirect: 'error' });
|
|
212
|
+
if (!response.ok)
|
|
213
|
+
throw new D2AProtocolError(`Device events returned HTTP ${response.status}`);
|
|
214
|
+
for await (const value of readD2ASSE(response))
|
|
215
|
+
yield D2AMessage.fromJSON(value.message ?? value);
|
|
216
|
+
}
|
|
217
|
+
async execute(message) { return D2AMessage.fromJSON(await this.call('execute', { message: message.toJSON() }, 'POST', '/v1/actions', message.toJSON())); }
|
|
218
|
+
async getAction(actionId) { return D2AMessage.fromJSON(await this.call('get_action', { action_id: nonempty(actionId, 'actionId') }, 'GET', `/v1/actions/${encodeURIComponent(actionId)}`)); }
|
|
219
|
+
async cancel(actionId) { return D2AMessage.fromJSON(await this.call('cancel', { action_id: nonempty(actionId, 'actionId') }, 'POST', `/v1/actions/${encodeURIComponent(actionId)}/cancel`, {})); }
|
|
220
|
+
}
|
|
221
|
+
/** Bounded SSE framing; stream lifetime is controlled by its owner, not a generation deadline. */
|
|
222
|
+
export async function* readD2ASSE(response) {
|
|
223
|
+
if (!response.headers.get('content-type')?.includes('text/event-stream') || !response.body)
|
|
224
|
+
throw new D2AProtocolError('Expected an SSE stream');
|
|
225
|
+
const reader = response.body.getReader(), decoder = new TextDecoder();
|
|
226
|
+
let pending = '', data = [];
|
|
227
|
+
try {
|
|
228
|
+
while (true) {
|
|
229
|
+
const { done, value } = await reader.read();
|
|
230
|
+
if (done)
|
|
231
|
+
break;
|
|
232
|
+
pending += decoder.decode(value, { stream: true });
|
|
233
|
+
if (pending.length + data.join('\n').length > 1048576)
|
|
234
|
+
throw new D2AProtocolError('SSE frame exceeds 1 MiB');
|
|
235
|
+
let end;
|
|
236
|
+
while ((end = pending.indexOf('\n')) >= 0) {
|
|
237
|
+
const line = pending.slice(0, end).replace(/\r$/, '');
|
|
238
|
+
pending = pending.slice(end + 1);
|
|
239
|
+
if (line === '') {
|
|
240
|
+
if (data.length) {
|
|
241
|
+
yield d2aObject(JSON.parse(data.join('\n')));
|
|
242
|
+
data = [];
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
else if (line.startsWith('data:'))
|
|
246
|
+
data.push(line.slice(5).replace(/^ /, ''));
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
finally {
|
|
251
|
+
await reader.cancel().catch(() => { });
|
|
252
|
+
reader.releaseLock();
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
function validateDevices(value) {
|
|
256
|
+
const body = d2aObject(value);
|
|
257
|
+
if (!Array.isArray(body.devices) || body.devices.length > 1024)
|
|
258
|
+
throw new D2AProtocolError('Invalid device discovery');
|
|
259
|
+
const ids = new Set();
|
|
260
|
+
for (const raw of body.devices) {
|
|
261
|
+
const device = d2aObject(raw);
|
|
262
|
+
const id = nonempty(device.id, 'device.id');
|
|
263
|
+
nonempty(device.kind, 'device.kind');
|
|
264
|
+
if (ids.has(id))
|
|
265
|
+
throw new D2AProtocolError('Duplicate device');
|
|
266
|
+
ids.add(id);
|
|
267
|
+
if (!Array.isArray(device.capabilities))
|
|
268
|
+
throw new D2AProtocolError('Device capabilities are required');
|
|
269
|
+
const names = new Set();
|
|
270
|
+
for (const rawCap of device.capabilities) {
|
|
271
|
+
const cap = d2aObject(rawCap), name = nonempty(cap.name, 'capability.name');
|
|
272
|
+
if (names.has(name))
|
|
273
|
+
throw new D2AProtocolError('Duplicate capability');
|
|
274
|
+
names.add(name);
|
|
275
|
+
matchesSchema(d2aObject(cap.input_schema), {});
|
|
276
|
+
if (cap.output_schema)
|
|
277
|
+
matchesSchema(d2aObject(cap.output_schema), {});
|
|
278
|
+
if (cap.requires_approval !== undefined && typeof cap.requires_approval !== 'boolean')
|
|
279
|
+
throw new D2AProtocolError('Invalid approval requirement');
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return body;
|
|
283
|
+
}
|
|
284
|
+
export class D2A {
|
|
285
|
+
options;
|
|
286
|
+
name = 'd2a';
|
|
287
|
+
discovered;
|
|
288
|
+
context;
|
|
289
|
+
policy;
|
|
290
|
+
constructor(options) {
|
|
291
|
+
this.options = options;
|
|
292
|
+
for (const method of ['discover', 'events', 'execute', 'getAction', 'cancel'])
|
|
293
|
+
if (typeof options.provider?.[method] !== 'function')
|
|
294
|
+
throw new D2AProtocolError(`Provider requires ${method}`);
|
|
295
|
+
this.context = d2aObject(options.context ?? {});
|
|
296
|
+
this.policy = { allow_actions: options.policy?.allowActions ?? false, allowed_devices: [...(options.policy?.allowedDevices ?? [])], allowed_capabilities: [...(options.policy?.allowedCapabilities ?? [])] };
|
|
297
|
+
}
|
|
298
|
+
async prepare() { this.discovered = validateDevices(await this.options.provider.discover()); }
|
|
299
|
+
capabilities() { return { devices: this.discovered?.devices ?? [], policy: this.policy }; }
|
|
300
|
+
async connect(agent, options) { return this.open(agent, options, true); }
|
|
301
|
+
async open(agent, options, ingest) {
|
|
302
|
+
nonempty(options.userId, 'userId');
|
|
303
|
+
nonempty(options.sessionId, 'sessionId');
|
|
304
|
+
if (!this.discovered)
|
|
305
|
+
await this.prepare();
|
|
306
|
+
const binding = nativeProtocolBinding(agent, options);
|
|
307
|
+
const snapshot = d2aObject(await binding.request('POST', '/runtime/d2a/sessions', { protocol_version: D2A_VERSION, user_id: options.userId, session_id: options.sessionId, agent: binding.configuration, devices: this.discovered.devices, context: this.context, policy: this.policy }));
|
|
308
|
+
const session = new D2ASession(agent, this, binding, snapshot, options.sessionId, this.discovered.devices);
|
|
309
|
+
if (ingest)
|
|
310
|
+
session.start();
|
|
311
|
+
return session;
|
|
312
|
+
}
|
|
313
|
+
async run(agent, input, options) {
|
|
314
|
+
const session = await this.open(agent, options, false);
|
|
315
|
+
try {
|
|
316
|
+
await session.send(d2aObject(input));
|
|
317
|
+
for await (const event of session) {
|
|
318
|
+
if (['run.failed', 'run.pending', 'run.input_required'].includes(event.type))
|
|
319
|
+
throw new D2ARunError(event, session.completedResult);
|
|
320
|
+
if (event.type === 'run.completed') {
|
|
321
|
+
if (!session.completedResult)
|
|
322
|
+
throw new D2AProtocolError('No completed agent response');
|
|
323
|
+
return session.completedResult;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
throw new D2AProtocolError('Session ended before completion');
|
|
327
|
+
}
|
|
328
|
+
finally {
|
|
329
|
+
await session.close();
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
/** Persistent ordered device stream. Actions are reserved by the runtime before execution. */
|
|
334
|
+
export class D2ASession {
|
|
335
|
+
agent;
|
|
336
|
+
config;
|
|
337
|
+
binding;
|
|
338
|
+
snapshot;
|
|
339
|
+
sessionId;
|
|
340
|
+
devices;
|
|
341
|
+
protocolSessionId;
|
|
342
|
+
completedResult;
|
|
343
|
+
queue = [];
|
|
344
|
+
waiters = new Set();
|
|
345
|
+
space = new Set();
|
|
346
|
+
closed = false;
|
|
347
|
+
failure;
|
|
348
|
+
abort = new AbortController();
|
|
349
|
+
task;
|
|
350
|
+
tail = Promise.resolve();
|
|
351
|
+
actions = new Map();
|
|
352
|
+
actionRequests = new Map();
|
|
353
|
+
sending = false;
|
|
354
|
+
constructor(agent, config, binding, snapshot, sessionId, devices) {
|
|
355
|
+
this.agent = agent;
|
|
356
|
+
this.config = config;
|
|
357
|
+
this.binding = binding;
|
|
358
|
+
this.snapshot = snapshot;
|
|
359
|
+
this.sessionId = sessionId;
|
|
360
|
+
this.devices = devices;
|
|
361
|
+
this.protocolSessionId = nonempty(snapshot.session_id, 'session_id');
|
|
362
|
+
if (snapshot.protocol !== 'd2a' || snapshot.state !== 'active')
|
|
363
|
+
throw new D2AProtocolError('Invalid native session');
|
|
364
|
+
}
|
|
365
|
+
path() { return `/runtime/d2a/sessions/${encodeURIComponent(this.protocolSessionId)}`; }
|
|
366
|
+
wake() { this.waiters.forEach(fn => fn()); this.waiters.clear(); }
|
|
367
|
+
async emit(event) {
|
|
368
|
+
while (this.queue.length >= 256 && !this.closed)
|
|
369
|
+
await new Promise(resolve => this.space.add(resolve));
|
|
370
|
+
if (!this.closed) {
|
|
371
|
+
this.queue.push(event);
|
|
372
|
+
this.wake();
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
/** @internal */ start() {
|
|
376
|
+
this.task = (async () => {
|
|
377
|
+
for await (const message of this.config.options.provider.events(this.sessionId, undefined, this.abort.signal)) {
|
|
378
|
+
if (this.closed)
|
|
379
|
+
break;
|
|
380
|
+
await this.serial(async () => { this.validateProviderEvent(message); await this.submit(message, true); });
|
|
381
|
+
}
|
|
382
|
+
})().catch(error => {
|
|
383
|
+
if (!this.closed) {
|
|
384
|
+
this.failure = error;
|
|
385
|
+
this.wake();
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
validateProviderEvent(message) {
|
|
390
|
+
const body = message.toJSON(), payload = d2aObject(body.payload);
|
|
391
|
+
if (body.source === 'agent' || !this.devices.some(device => device.id === body.source) || !['observation', 'state', 'feedback'].includes(String(payload.kind)))
|
|
392
|
+
throw new D2AProtocolError('Provider events must come from an advertised device');
|
|
393
|
+
if (['routes', 'coordination', 'approved'].some(key => Object.hasOwn(payload, key)))
|
|
394
|
+
throw new D2AProtocolError('Provider events cannot contain routing or approval authority');
|
|
395
|
+
if (payload.kind === 'feedback')
|
|
396
|
+
this.validateFeedback(message);
|
|
397
|
+
}
|
|
398
|
+
validateFeedback(message) {
|
|
399
|
+
const body = message.toJSON(), payload = d2aObject(body.payload), request = this.actionRequests.get(String(payload.action_id));
|
|
400
|
+
if (!request || body.source !== request.toJSON().target || payload.kind !== 'feedback')
|
|
401
|
+
throw new D2AProtocolError('Feedback does not match a session action');
|
|
402
|
+
const action = d2aObject(request.toJSON().payload), device = this.devices.find(device => device.id === body.source), capability = device?.capabilities.find(cap => cap.name === action.capability);
|
|
403
|
+
if (payload.status === 'succeeded' && capability?.output_schema && !matchesSchema(capability.output_schema, payload.result))
|
|
404
|
+
throw new D2AProtocolError('Action result does not match capability schema');
|
|
405
|
+
}
|
|
406
|
+
serial(work) { const task = this.tail.then(work); this.tail = task.catch(() => { }); return task; }
|
|
407
|
+
async send(input) {
|
|
408
|
+
if (this.sending)
|
|
409
|
+
throw new D2AProtocolError('Wait for completion before sending another message');
|
|
410
|
+
const message = D2AMessage.fromJSON(input);
|
|
411
|
+
this.completedResult = undefined;
|
|
412
|
+
this.sending = true;
|
|
413
|
+
let accepted;
|
|
414
|
+
const ready = new Promise(resolve => { accepted = resolve; });
|
|
415
|
+
void this.serial(() => this.submit(message, true, accepted)).catch(error => { this.failure = error; this.wake(); }).finally(() => { this.sending = false; accepted(); });
|
|
416
|
+
await ready;
|
|
417
|
+
if (this.failure)
|
|
418
|
+
throw this.failure;
|
|
419
|
+
}
|
|
420
|
+
accepts(input) { return input.protocol === 'd2a'; }
|
|
421
|
+
async deliverFeedback(input) {
|
|
422
|
+
const payload = d2aObject(input.payload), content = Array.isArray(payload.content) ? payload.content : [];
|
|
423
|
+
await this.deliver(new D2AMessage({ source: 'agent', kind: 'coordination', content: content, correlationId: String(input.message_id), payload: { execute: false, protocol_feedback: input } }).toJSON());
|
|
424
|
+
}
|
|
425
|
+
async deliver(input) { let feedback; await this.serial(async () => { feedback = await this.submit(D2AMessage.fromJSON(input), false); }); return feedback; }
|
|
426
|
+
async submit(message, stream, accepted) {
|
|
427
|
+
if (this.closed)
|
|
428
|
+
throw new D2AProtocolError('Session is closed');
|
|
429
|
+
this.snapshot = d2aObject(await this.binding.request('GET', this.path()));
|
|
430
|
+
if (this.snapshot.state !== 'active')
|
|
431
|
+
throw new D2AProtocolError('Session is inactive');
|
|
432
|
+
const bound = message.bind(this.protocolSessionId, Number(this.snapshot.next_sequence));
|
|
433
|
+
let exchange;
|
|
434
|
+
const seen = new Set();
|
|
435
|
+
let feedback;
|
|
436
|
+
const outcomes = [];
|
|
437
|
+
const accept = async (value) => {
|
|
438
|
+
const body = d2aObject(value);
|
|
439
|
+
if (body.type === 'protocol.route') {
|
|
440
|
+
await this.emit({ type: 'protocol.route', data: d2aObject(body.data) });
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
const event = D2AMessage.fromJSON(body), raw = event.toJSON(), id = String(raw.message_id);
|
|
444
|
+
if (seen.has(id))
|
|
445
|
+
return;
|
|
446
|
+
seen.add(id);
|
|
447
|
+
const payload = d2aObject(raw.payload);
|
|
448
|
+
if (raw.stream && d2aObject(raw.stream).final === false) {
|
|
449
|
+
await this.emit({ type: 'message', data: raw, message: event });
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
await this.emit({ type: 'message', data: raw, message: event });
|
|
453
|
+
if (Array.isArray(payload.routes))
|
|
454
|
+
for (const route of payload.routes) {
|
|
455
|
+
const frame = d2aObject(route);
|
|
456
|
+
await this.emit({ type: 'protocol.route', data: d2aObject(frame.data ?? frame) });
|
|
457
|
+
}
|
|
458
|
+
if (payload.response) {
|
|
459
|
+
this.completedResult = protocolResult(this.agent, { ...payload, status: payload.status ?? 'completed' });
|
|
460
|
+
if (this.completedResult) {
|
|
461
|
+
this.completedResult = { ...this.completedResult, protocol: 'd2a' };
|
|
462
|
+
await this.emit({ type: 'agent.response', data: payload, output: this.completedResult.output });
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
if (payload.kind === 'feedback') {
|
|
466
|
+
feedback = raw;
|
|
467
|
+
outcomes.push(raw);
|
|
468
|
+
await this.emit({ type: 'action.feedback', data: raw, message: event });
|
|
469
|
+
}
|
|
470
|
+
else if (payload.kind === 'coordination' && payload.status === 'approval_required') {
|
|
471
|
+
feedback = raw;
|
|
472
|
+
outcomes.push(raw);
|
|
473
|
+
}
|
|
474
|
+
else if (raw.source === 'agent' && payload.kind === 'action') {
|
|
475
|
+
feedback = await this.execute(event);
|
|
476
|
+
outcomes.push(feedback);
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
if (stream) {
|
|
480
|
+
for await (const frame of this.binding.stream(this.path() + '/messages/stream', bound.toJSON(), this.abort.signal)) {
|
|
481
|
+
if (frame.type === 'stream.started')
|
|
482
|
+
accepted?.();
|
|
483
|
+
else if (frame.type === 'message') {
|
|
484
|
+
accepted?.();
|
|
485
|
+
await accept(frame.message ?? frame);
|
|
486
|
+
}
|
|
487
|
+
else if (frame.type === 'protocol.route')
|
|
488
|
+
await accept(frame);
|
|
489
|
+
else if (frame.type === 'exchange.completed')
|
|
490
|
+
exchange = d2aObject(frame.exchange);
|
|
491
|
+
else if (frame.type === 'stream.failed')
|
|
492
|
+
throw new D2AProtocolError('D2A stream failed; actions were not replayed');
|
|
493
|
+
}
|
|
494
|
+
if (!exchange)
|
|
495
|
+
throw new D2AProtocolError('D2A stream ended without completion');
|
|
496
|
+
}
|
|
497
|
+
else
|
|
498
|
+
exchange = d2aObject(await this.binding.request('POST', this.path() + '/messages', bound.toJSON()));
|
|
499
|
+
if (exchange.session_id !== this.protocolSessionId)
|
|
500
|
+
throw new D2AProtocolError('Native session mismatch');
|
|
501
|
+
this.snapshot = d2aObject(exchange.session);
|
|
502
|
+
for (const event of (exchange.events ?? []))
|
|
503
|
+
await accept(event);
|
|
504
|
+
this.sending = false;
|
|
505
|
+
const states = outcomes.map(value => d2aObject(value.payload).status);
|
|
506
|
+
const outcomeType = states.includes('approval_required') ? 'run.input_required' : states.some(status => ['accepted', 'executing'].includes(String(status))) ? 'run.pending' : states.some(status => status !== 'succeeded') ? 'run.failed' : 'run.completed';
|
|
507
|
+
if (stream)
|
|
508
|
+
await this.emit({ type: outcomeType, data: { actions: outcomes }, output: this.completedResult?.output });
|
|
509
|
+
return feedback;
|
|
510
|
+
}
|
|
511
|
+
async execute(action) {
|
|
512
|
+
const raw = action.toJSON(), payload = d2aObject(raw.payload), id = String(payload.action_id), target = String(raw.target);
|
|
513
|
+
let feedback = this.actions.get(id);
|
|
514
|
+
if (!feedback) {
|
|
515
|
+
if (this.actions.size >= 4096)
|
|
516
|
+
throw new D2AProtocolError('Action retention limit reached; open a new session');
|
|
517
|
+
this.snapshot = d2aObject(await this.binding.request('GET', this.path()));
|
|
518
|
+
const currentDevices = validateDevices({ devices: this.snapshot.devices ?? this.devices }).devices;
|
|
519
|
+
const device = currentDevices.find(v => v.id === target), cap = device?.capabilities.find(v => v.name === payload.capability), policy = this.config.policy;
|
|
520
|
+
let reason;
|
|
521
|
+
if (this.snapshot.state !== 'active')
|
|
522
|
+
reason = 'Session is inactive';
|
|
523
|
+
else if (!policy.allow_actions)
|
|
524
|
+
reason = 'Actions are disabled';
|
|
525
|
+
else if (!device || !cap)
|
|
526
|
+
reason = 'Unknown device capability';
|
|
527
|
+
else if (policy.allowed_devices.length && !policy.allowed_devices.includes(target) || policy.allowed_capabilities.length && !policy.allowed_capabilities.includes(String(payload.capability)))
|
|
528
|
+
reason = 'Capability is outside policy';
|
|
529
|
+
else if (cap.requires_approval && payload.approved !== true)
|
|
530
|
+
reason = 'Approval is required';
|
|
531
|
+
else if (raw.expires_at && Date.parse(String(raw.expires_at)) <= Date.now())
|
|
532
|
+
reason = 'Action expired';
|
|
533
|
+
else if (payload.expected_revision !== undefined && payload.expected_revision !== device.revision)
|
|
534
|
+
reason = 'Device revision changed';
|
|
535
|
+
else if (!matchesSchema(cap.input_schema, payload.arguments))
|
|
536
|
+
reason = 'Arguments do not match capability schema';
|
|
537
|
+
this.actionRequests.set(id, action);
|
|
538
|
+
feedback = D2AMessage.feedback(action, reason ? 'rejected' : 'unknown', { reason: reason ?? 'Execution outcome not yet known' });
|
|
539
|
+
this.actions.set(id, feedback);
|
|
540
|
+
if (!reason) {
|
|
541
|
+
try {
|
|
542
|
+
feedback = await this.config.options.provider.execute(action);
|
|
543
|
+
const body = feedback.toJSON(), p = d2aObject(body.payload);
|
|
544
|
+
if (p.kind !== 'feedback' || p.action_id !== id || body.source !== target)
|
|
545
|
+
throw new D2AProtocolError('Action feedback identity mismatch');
|
|
546
|
+
if (p.status === 'succeeded' && cap?.output_schema && !matchesSchema(cap.output_schema, p.result))
|
|
547
|
+
throw new D2AProtocolError('Action result does not match schema');
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
feedback = D2AMessage.feedback(action, 'unknown', { reason: 'Provider disconnected or returned invalid feedback; reconcile by action ID' });
|
|
551
|
+
}
|
|
552
|
+
this.actions.set(id, feedback);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
const body = feedback.toJSON();
|
|
556
|
+
body.payload = { ...d2aObject(body.payload), execute: false };
|
|
557
|
+
this.snapshot = d2aObject(await this.binding.request('GET', this.path()));
|
|
558
|
+
const bound = D2AMessage.fromJSON(body).bind(this.protocolSessionId, Number(this.snapshot.next_sequence));
|
|
559
|
+
const exchange = d2aObject(await this.binding.request('POST', this.path() + '/messages', bound.toJSON()));
|
|
560
|
+
this.snapshot = d2aObject(exchange.session);
|
|
561
|
+
await this.emit({ type: 'action.feedback', data: body, message: feedback });
|
|
562
|
+
return body;
|
|
563
|
+
}
|
|
564
|
+
async approveAction(actionId, approved) {
|
|
565
|
+
await this.serial(async () => {
|
|
566
|
+
const exchange = d2aObject(await this.binding.request('POST', this.path() + '/actions/' + encodeURIComponent(nonempty(actionId, 'actionId')) + '/approve', { approved }));
|
|
567
|
+
this.snapshot = d2aObject(exchange.session);
|
|
568
|
+
for (const raw of (exchange.events ?? [])) {
|
|
569
|
+
const message = D2AMessage.fromJSON(raw);
|
|
570
|
+
const body = message.toJSON();
|
|
571
|
+
if (body.source === 'agent' && d2aObject(body.payload).kind === 'action')
|
|
572
|
+
await this.execute(message);
|
|
573
|
+
else
|
|
574
|
+
await this.emit({ type: 'message', data: body, message });
|
|
575
|
+
}
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
async reconcile(actionId, cancel) {
|
|
579
|
+
return this.serial(async () => {
|
|
580
|
+
const prior = this.actions.get(actionId);
|
|
581
|
+
if (!prior)
|
|
582
|
+
throw new D2AProtocolError('Unknown session action');
|
|
583
|
+
const feedback = await (cancel ? this.config.options.provider.cancel(actionId) : this.config.options.provider.getAction(actionId));
|
|
584
|
+
const body = feedback.toJSON(), payload = d2aObject(body.payload);
|
|
585
|
+
this.validateFeedback(feedback);
|
|
586
|
+
if (payload.kind !== 'feedback' || payload.action_id !== actionId || body.source !== prior.toJSON().source)
|
|
587
|
+
throw new D2AProtocolError('Action feedback mismatch');
|
|
588
|
+
body.payload = { ...payload, execute: false };
|
|
589
|
+
await this.submit(D2AMessage.fromJSON(body), false);
|
|
590
|
+
this.actions.set(actionId, feedback);
|
|
591
|
+
return feedback;
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
getAction(actionId) { return this.reconcile(actionId, false); }
|
|
595
|
+
cancel(actionId) { return this.reconcile(actionId, true); }
|
|
596
|
+
async close() {
|
|
597
|
+
if (this.closed)
|
|
598
|
+
return;
|
|
599
|
+
this.closed = true;
|
|
600
|
+
this.abort.abort();
|
|
601
|
+
this.wake();
|
|
602
|
+
this.space.forEach(fn => fn());
|
|
603
|
+
this.space.clear();
|
|
604
|
+
await this.binding.request('DELETE', this.path());
|
|
605
|
+
}
|
|
606
|
+
async *[Symbol.asyncIterator]() {
|
|
607
|
+
while (!this.closed) {
|
|
608
|
+
const event = this.queue.shift();
|
|
609
|
+
if (event) {
|
|
610
|
+
this.space.forEach(fn => fn());
|
|
611
|
+
this.space.clear();
|
|
612
|
+
yield event;
|
|
613
|
+
}
|
|
614
|
+
else if (this.failure)
|
|
615
|
+
throw this.failure;
|
|
616
|
+
else
|
|
617
|
+
await new Promise(resolve => this.waiters.add(resolve));
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
//# sourceMappingURL=d2a.js.map
|