@devicerail/tool-adapter 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 +201 -0
- package/README.md +78 -0
- package/dist/catalog.d.ts +8 -0
- package/dist/catalog.js +360 -0
- package/dist/errors.d.ts +23 -0
- package/dist/errors.js +39 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/json.d.ts +4 -0
- package/dist/json.js +127 -0
- package/dist/naming.d.ts +2 -0
- package/dist/naming.js +21 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +163 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +240 -0
- package/dist/types.d.ts +79 -0
- package/dist/types.js +1 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 DeviceRail contributors
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# `@devicerail/tool-adapter`
|
|
2
|
+
|
|
3
|
+
Provider-neutral DeviceRail Tool Catalogs for Node.js 22 and later.
|
|
4
|
+
|
|
5
|
+
The package converts the selected device's `device.capabilities` response into
|
|
6
|
+
an immutable catalog. It adds one explicit observation tool and maps every
|
|
7
|
+
portable tool name back to the original Driver action. It does not import an
|
|
8
|
+
AI SDK, translate tools into a provider-specific format, or own device and
|
|
9
|
+
Session lifecycle.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { DeviceRailClient } from "@devicerail/client";
|
|
13
|
+
import {
|
|
14
|
+
actionToolName,
|
|
15
|
+
DeviceRailToolAdapter,
|
|
16
|
+
} from "@devicerail/tool-adapter";
|
|
17
|
+
|
|
18
|
+
const client = await DeviceRailClient.spawn({ command: "devicerail-daemon", hello });
|
|
19
|
+
|
|
20
|
+
// Lifecycle remains explicit and host-owned.
|
|
21
|
+
await client.call("device.select", { deviceId: "android-1" });
|
|
22
|
+
await client.call("device.connect");
|
|
23
|
+
await client.call("session.start");
|
|
24
|
+
|
|
25
|
+
const catalog = await new DeviceRailToolAdapter(client).discover();
|
|
26
|
+
const result = await catalog.invoke(
|
|
27
|
+
{
|
|
28
|
+
arguments: { x: 320, y: 240 },
|
|
29
|
+
invocationId: "agent-call-1",
|
|
30
|
+
name: actionToolName("tap"),
|
|
31
|
+
},
|
|
32
|
+
{ actionTimeoutMs: 5_000, requestTimeoutMs: 10_000 },
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
if (result.kind === "action") {
|
|
36
|
+
console.log(result.action.after, result.action.evidence);
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`beginInvoke()` additionally exposes the exact RPC request ID and a typed
|
|
41
|
+
`cancel()` operation. Agent/provider invocation IDs remain metadata; the
|
|
42
|
+
adapter always generates a distinct UUID for the DeviceRail Action call.
|
|
43
|
+
Remote RPC and Driver failures reject unchanged rather than becoming textual
|
|
44
|
+
tool success results.
|
|
45
|
+
|
|
46
|
+
Results from injected client-compatible implementations cross the same
|
|
47
|
+
canonical method-result Schema boundary as the stock client before the
|
|
48
|
+
adapter applies its stricter Action, Observation, Evidence, and protected-data
|
|
49
|
+
semantics.
|
|
50
|
+
|
|
51
|
+
Action schemas must be pure JSON with `type: "object"` at the root. During
|
|
52
|
+
discovery, the adapter performs defensive shape checks for common JSON Schema
|
|
53
|
+
keywords and then deeply freezes an isolated schema snapshot. It accepts Draft
|
|
54
|
+
6, Draft 7, Draft 2019-09, Draft 2020-12, and compound schema documents with
|
|
55
|
+
nested resources.
|
|
56
|
+
|
|
57
|
+
The adapter does not fetch schemas, resolve references, select a dialect, or
|
|
58
|
+
claim complete meta-schema validation. `$id`, `$ref`, `$dynamicRef`, and
|
|
59
|
+
`$recursiveRef` values are preserved for the Driver/daemon validation boundary;
|
|
60
|
+
remote and currently unresolved references do not cause network access during
|
|
61
|
+
tool discovery.
|
|
62
|
+
|
|
63
|
+
Protected actions are excluded from catalogs by default. A host that
|
|
64
|
+
deliberately wants to expose actions such as Android `inputSecret` must both
|
|
65
|
+
negotiate `action.protected.v1` during `system.hello` and opt the adapter in:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
// The client's hello.features.optional must include "action.protected.v1".
|
|
69
|
+
const catalog = await new DeviceRailToolAdapter(client, {
|
|
70
|
+
includeProtectedActions: true,
|
|
71
|
+
}).discover();
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Opting in makes the protected argument visible to the Agent/provider and to
|
|
75
|
+
the JavaScript process. DeviceRail redacts its durable Action event and omits
|
|
76
|
+
the protected before/after screenshots, but the adapter cannot prevent an
|
|
77
|
+
upstream model provider, host logger, operating system, or process-memory
|
|
78
|
+
inspector from retaining the value.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { RpcId } from "@devicerail/protocol";
|
|
2
|
+
import type { DeviceRailToolAdapterOptions, DeviceRailToolCatalog, DeviceRailToolClient, ToolDiscoveryOptions, ToolInvocationHandle } from "./types.js";
|
|
3
|
+
export declare class DeviceRailToolAdapter {
|
|
4
|
+
#private;
|
|
5
|
+
constructor(client: DeviceRailToolClient, options?: DeviceRailToolAdapterOptions);
|
|
6
|
+
discover(options?: ToolDiscoveryOptions): Promise<DeviceRailToolCatalog>;
|
|
7
|
+
}
|
|
8
|
+
export declare function requestIdOf(handle: ToolInvocationHandle): RpcId;
|
package/dist/catalog.js
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { types as utilTypes } from "node:util";
|
|
3
|
+
import { ProtocolViolationError, validateRpcResult, } from "@devicerail/client";
|
|
4
|
+
import { InvalidActionSpaceError, InvalidToolArgumentsError, InvalidToolOptionsError, UnknownToolError, } from "./errors.js";
|
|
5
|
+
import { clonePureJson, deepFreezeJson } from "./json.js";
|
|
6
|
+
import { actionToolName, OBSERVATION_TOOL_NAME } from "./naming.js";
|
|
7
|
+
import { validateActionResult, validateObservationResult } from "./result.js";
|
|
8
|
+
import { validateToolInputSchema } from "./schema.js";
|
|
9
|
+
const DEFAULT_MAX_ACTIONS = 256;
|
|
10
|
+
const ACTION_PROTECTED_FEATURE = "action.protected.v1";
|
|
11
|
+
function isRecord(value) {
|
|
12
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
function positiveSafeInteger(value, name) {
|
|
15
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
|
|
16
|
+
throw new InvalidToolOptionsError(`${name} must be a positive safe integer`);
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
function isAbortSignal(value) {
|
|
21
|
+
return value instanceof AbortSignal;
|
|
22
|
+
}
|
|
23
|
+
function protectedFeatureEnabled(client) {
|
|
24
|
+
return client.enabledFeatures?.has(ACTION_PROTECTED_FEATURE) ?? false;
|
|
25
|
+
}
|
|
26
|
+
function plainOptionRecord(value, context) {
|
|
27
|
+
if (!isRecord(value) || utilTypes.isProxy(value)) {
|
|
28
|
+
throw new InvalidToolOptionsError(`${context} must be a plain object`);
|
|
29
|
+
}
|
|
30
|
+
const prototype = Object.getPrototypeOf(value);
|
|
31
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
32
|
+
throw new InvalidToolOptionsError(`${context} must be a plain object`);
|
|
33
|
+
}
|
|
34
|
+
const keys = Reflect.ownKeys(value);
|
|
35
|
+
if (keys.some((key) => typeof key !== "string")) {
|
|
36
|
+
throw new InvalidToolOptionsError(`${context} must not contain symbol properties`);
|
|
37
|
+
}
|
|
38
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
39
|
+
const record = {};
|
|
40
|
+
for (const key of keys) {
|
|
41
|
+
const descriptor = descriptors[key];
|
|
42
|
+
if (!descriptor?.enumerable || !("value" in descriptor)) {
|
|
43
|
+
throw new InvalidToolOptionsError(`${context}.${key} must be a plain data property`);
|
|
44
|
+
}
|
|
45
|
+
Object.defineProperty(record, key, {
|
|
46
|
+
configurable: true,
|
|
47
|
+
enumerable: true,
|
|
48
|
+
value: descriptor.value,
|
|
49
|
+
writable: true,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
return record;
|
|
53
|
+
}
|
|
54
|
+
function normalizeOptions(value, context, allowActionTimeout) {
|
|
55
|
+
if (value === undefined) {
|
|
56
|
+
return {};
|
|
57
|
+
}
|
|
58
|
+
const record = plainOptionRecord(value, context);
|
|
59
|
+
const allowed = new Set([
|
|
60
|
+
...(allowActionTimeout ? ["actionTimeoutMs"] : []),
|
|
61
|
+
"requestTimeoutMs",
|
|
62
|
+
"signal",
|
|
63
|
+
]);
|
|
64
|
+
for (const key of Object.keys(record)) {
|
|
65
|
+
if (!allowed.has(key)) {
|
|
66
|
+
throw new InvalidToolOptionsError(`unknown ${context.slice(0, -1)} ${key}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const actionTimeoutMs = record.actionTimeoutMs === undefined
|
|
70
|
+
? undefined
|
|
71
|
+
: positiveSafeInteger(record.actionTimeoutMs, "actionTimeoutMs");
|
|
72
|
+
const requestTimeoutMs = record.requestTimeoutMs === undefined
|
|
73
|
+
? undefined
|
|
74
|
+
: positiveSafeInteger(record.requestTimeoutMs, "requestTimeoutMs");
|
|
75
|
+
const signal = record.signal;
|
|
76
|
+
if (signal !== undefined && !isAbortSignal(signal)) {
|
|
77
|
+
throw new InvalidToolOptionsError("signal must be an AbortSignal");
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
...(actionTimeoutMs === undefined ? {} : { actionTimeoutMs }),
|
|
81
|
+
...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),
|
|
82
|
+
...(signal === undefined ? {} : { signal }),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function normalizeDiscoveryOptions(value) {
|
|
86
|
+
return normalizeOptions(value, "tool discovery options", false);
|
|
87
|
+
}
|
|
88
|
+
function normalizeInvocation(value) {
|
|
89
|
+
let errorToolName = "<unknown>";
|
|
90
|
+
if (isRecord(value) && !utilTypes.isProxy(value)) {
|
|
91
|
+
const nameDescriptor = Object.getOwnPropertyDescriptor(value, "name");
|
|
92
|
+
if (nameDescriptor?.enumerable &&
|
|
93
|
+
"value" in nameDescriptor &&
|
|
94
|
+
typeof nameDescriptor.value === "string" &&
|
|
95
|
+
nameDescriptor.value.length > 0) {
|
|
96
|
+
errorToolName = nameDescriptor.value;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const cloned = clonePureJson(value, (message) => new InvalidToolArgumentsError(errorToolName, message));
|
|
100
|
+
if (!isRecord(cloned)) {
|
|
101
|
+
throw new InvalidToolArgumentsError("<unknown>", "tool invocation must be an object");
|
|
102
|
+
}
|
|
103
|
+
const allowed = new Set(["arguments", "invocationId", "name"]);
|
|
104
|
+
for (const key of Object.keys(cloned)) {
|
|
105
|
+
if (!allowed.has(key)) {
|
|
106
|
+
throw new InvalidToolArgumentsError("<unknown>", `unknown invocation field ${key}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (typeof cloned.name !== "string" || cloned.name.length === 0) {
|
|
110
|
+
throw new InvalidToolArgumentsError("<unknown>", "tool name must be a non-empty string");
|
|
111
|
+
}
|
|
112
|
+
if (cloned.invocationId !== undefined && typeof cloned.invocationId !== "string") {
|
|
113
|
+
throw new InvalidToolArgumentsError(cloned.name, "invocationId must be a string");
|
|
114
|
+
}
|
|
115
|
+
const argumentsValue = cloned.arguments === undefined ? {} : cloned.arguments;
|
|
116
|
+
if (!isRecord(argumentsValue)) {
|
|
117
|
+
throw new InvalidToolArgumentsError(cloned.name, "arguments must be a JSON object");
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
arguments: deepFreezeJson(argumentsValue),
|
|
121
|
+
...(cloned.invocationId === undefined ? {} : { invocationId: cloned.invocationId }),
|
|
122
|
+
name: cloned.name,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function callOptions(options) {
|
|
126
|
+
return {
|
|
127
|
+
...(options.requestTimeoutMs === undefined ? {} : { timeoutMs: options.requestTimeoutMs }),
|
|
128
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function compileDefinitions(capabilities, includeObservation, includeProtectedActions, maxActions) {
|
|
132
|
+
const clonedCapabilities = clonePureJson(capabilities, (message) => new InvalidActionSpaceError(`device.capabilities: ${message}`));
|
|
133
|
+
if (!Array.isArray(clonedCapabilities)) {
|
|
134
|
+
throw new InvalidActionSpaceError("device.capabilities must return an array");
|
|
135
|
+
}
|
|
136
|
+
if (clonedCapabilities.length > maxActions) {
|
|
137
|
+
throw new InvalidActionSpaceError(`device.capabilities returned ${clonedCapabilities.length} actions; the limit is ${maxActions}`);
|
|
138
|
+
}
|
|
139
|
+
const actions = [];
|
|
140
|
+
const actionNames = new Set();
|
|
141
|
+
for (let index = 0; index < clonedCapabilities.length; index += 1) {
|
|
142
|
+
const capability = clonedCapabilities[index];
|
|
143
|
+
if (!isRecord(capability)) {
|
|
144
|
+
throw new InvalidActionSpaceError(`capability ${index} must be an object`);
|
|
145
|
+
}
|
|
146
|
+
if (typeof capability.name !== "string" || capability.name.trim().length === 0) {
|
|
147
|
+
throw new InvalidActionSpaceError(`capability ${index} has an invalid action name`);
|
|
148
|
+
}
|
|
149
|
+
if (typeof capability.description !== "string" ||
|
|
150
|
+
capability.description.trim().length === 0) {
|
|
151
|
+
throw new InvalidActionSpaceError(`capability ${capability.name} has an invalid description`);
|
|
152
|
+
}
|
|
153
|
+
if (actionNames.has(capability.name)) {
|
|
154
|
+
throw new InvalidActionSpaceError(`duplicate action name ${capability.name}`);
|
|
155
|
+
}
|
|
156
|
+
const protection = capability.protection ?? "standard";
|
|
157
|
+
if (protection !== "standard" && protection !== "protected") {
|
|
158
|
+
throw new InvalidActionSpaceError(`capability ${capability.name} has an invalid protection classification`);
|
|
159
|
+
}
|
|
160
|
+
actionNames.add(capability.name);
|
|
161
|
+
actions.push({
|
|
162
|
+
description: capability.description,
|
|
163
|
+
inputSchema: validateToolInputSchema(capability.name, capability.inputSchema),
|
|
164
|
+
name: capability.name,
|
|
165
|
+
protection,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
validateRpcResult("device.capabilities", clonedCapabilities);
|
|
170
|
+
}
|
|
171
|
+
catch (cause) {
|
|
172
|
+
if (cause instanceof ProtocolViolationError) {
|
|
173
|
+
throw new InvalidActionSpaceError(`device.capabilities: ${cause.message}`, { cause });
|
|
174
|
+
}
|
|
175
|
+
throw cause;
|
|
176
|
+
}
|
|
177
|
+
actions.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
|
|
178
|
+
const definitions = [];
|
|
179
|
+
if (includeObservation) {
|
|
180
|
+
const observation = Object.freeze({
|
|
181
|
+
description: "Capture the current DeviceRail device observation",
|
|
182
|
+
inputSchema: deepFreezeJson({ additionalProperties: false, type: "object" }),
|
|
183
|
+
kind: "observation",
|
|
184
|
+
name: OBSERVATION_TOOL_NAME,
|
|
185
|
+
});
|
|
186
|
+
definitions.push(observation);
|
|
187
|
+
}
|
|
188
|
+
const toolNames = new Set(definitions.map((definition) => definition.name));
|
|
189
|
+
for (const action of actions) {
|
|
190
|
+
if (action.protection === "protected" && !includeProtectedActions) {
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
const name = actionToolName(action.name);
|
|
194
|
+
if (toolNames.has(name)) {
|
|
195
|
+
throw new InvalidActionSpaceError(`portable tool name collision for action ${action.name}`);
|
|
196
|
+
}
|
|
197
|
+
toolNames.add(name);
|
|
198
|
+
const definition = Object.freeze({
|
|
199
|
+
actionName: action.name,
|
|
200
|
+
description: action.description,
|
|
201
|
+
inputSchema: action.inputSchema,
|
|
202
|
+
kind: "action",
|
|
203
|
+
name,
|
|
204
|
+
...(action.protection === "protected" ? { protection: "protected" } : {}),
|
|
205
|
+
});
|
|
206
|
+
definitions.push(definition);
|
|
207
|
+
}
|
|
208
|
+
return Object.freeze(definitions);
|
|
209
|
+
}
|
|
210
|
+
class ToolCatalog {
|
|
211
|
+
id = randomUUID();
|
|
212
|
+
revision;
|
|
213
|
+
tools;
|
|
214
|
+
#client;
|
|
215
|
+
#entries;
|
|
216
|
+
constructor(client, revision, tools) {
|
|
217
|
+
this.#client = client;
|
|
218
|
+
this.revision = revision;
|
|
219
|
+
this.tools = tools;
|
|
220
|
+
this.#entries = new Map(tools.map((definition) => [definition.name, { definition }]));
|
|
221
|
+
Object.freeze(this);
|
|
222
|
+
}
|
|
223
|
+
beginInvoke(rawInvocation, rawOptions) {
|
|
224
|
+
const invocation = normalizeInvocation(rawInvocation);
|
|
225
|
+
const options = normalizeOptions(rawOptions, "tool invocation options", true);
|
|
226
|
+
const entry = this.#entries.get(invocation.name);
|
|
227
|
+
if (!entry) {
|
|
228
|
+
throw new UnknownToolError(invocation.name);
|
|
229
|
+
}
|
|
230
|
+
if (entry.definition.kind === "observation") {
|
|
231
|
+
if (Object.keys(invocation.arguments).length !== 0) {
|
|
232
|
+
throw new InvalidToolArgumentsError(invocation.name, "the observation tool accepts no arguments");
|
|
233
|
+
}
|
|
234
|
+
if (options.actionTimeoutMs !== undefined) {
|
|
235
|
+
throw new InvalidToolOptionsError("actionTimeoutMs is only valid for action tools");
|
|
236
|
+
}
|
|
237
|
+
const request = this.#client.beginCall("device.observe", undefined, callOptions(options));
|
|
238
|
+
const result = request.result.then((observation) => {
|
|
239
|
+
const validated = validateObservationResult(invocation.name, observation);
|
|
240
|
+
return {
|
|
241
|
+
...(invocation.invocationId === undefined
|
|
242
|
+
? {}
|
|
243
|
+
: { invocationId: invocation.invocationId }),
|
|
244
|
+
kind: "observation",
|
|
245
|
+
observation: validated,
|
|
246
|
+
requestId: request.id,
|
|
247
|
+
toolName: invocation.name,
|
|
248
|
+
};
|
|
249
|
+
});
|
|
250
|
+
const handle = {
|
|
251
|
+
cancel: () => request.cancel(),
|
|
252
|
+
kind: "observation",
|
|
253
|
+
requestId: request.id,
|
|
254
|
+
result,
|
|
255
|
+
};
|
|
256
|
+
return handle;
|
|
257
|
+
}
|
|
258
|
+
const definition = entry.definition;
|
|
259
|
+
if (definition.protection === "protected" &&
|
|
260
|
+
!protectedFeatureEnabled(this.#client)) {
|
|
261
|
+
throw new InvalidActionSpaceError(`protected action ${definition.actionName} requires negotiated ${ACTION_PROTECTED_FEATURE}`);
|
|
262
|
+
}
|
|
263
|
+
const actionCallId = randomUUID();
|
|
264
|
+
const request = this.#client.beginCall("device.execute", {
|
|
265
|
+
...(options.actionTimeoutMs === undefined
|
|
266
|
+
? {}
|
|
267
|
+
: { actionTimeoutMs: options.actionTimeoutMs }),
|
|
268
|
+
arguments: invocation.arguments,
|
|
269
|
+
id: actionCallId,
|
|
270
|
+
name: definition.actionName,
|
|
271
|
+
}, callOptions(options));
|
|
272
|
+
const result = request.result.then((action) => {
|
|
273
|
+
const validated = validateActionResult(invocation.name, actionCallId, action, definition.protection);
|
|
274
|
+
return {
|
|
275
|
+
action: validated,
|
|
276
|
+
actionCallId,
|
|
277
|
+
actionName: definition.actionName,
|
|
278
|
+
...(invocation.invocationId === undefined
|
|
279
|
+
? {}
|
|
280
|
+
: { invocationId: invocation.invocationId }),
|
|
281
|
+
kind: "action",
|
|
282
|
+
requestId: request.id,
|
|
283
|
+
toolName: invocation.name,
|
|
284
|
+
};
|
|
285
|
+
});
|
|
286
|
+
const handle = {
|
|
287
|
+
actionCallId,
|
|
288
|
+
actionName: definition.actionName,
|
|
289
|
+
cancel: () => request.cancel(),
|
|
290
|
+
kind: "action",
|
|
291
|
+
requestId: request.id,
|
|
292
|
+
result,
|
|
293
|
+
};
|
|
294
|
+
return handle;
|
|
295
|
+
}
|
|
296
|
+
async invoke(invocation, options) {
|
|
297
|
+
return await this.beginInvoke(invocation, options).result;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
export class DeviceRailToolAdapter {
|
|
301
|
+
#client;
|
|
302
|
+
#includeObservation;
|
|
303
|
+
#includeProtectedActions;
|
|
304
|
+
#maxActions;
|
|
305
|
+
#revision = 0;
|
|
306
|
+
constructor(client, options = {}) {
|
|
307
|
+
if (!isRecord(client) ||
|
|
308
|
+
typeof client.call !== "function" ||
|
|
309
|
+
typeof client.beginCall !== "function" ||
|
|
310
|
+
(client.enabledFeatures !== undefined &&
|
|
311
|
+
(!isRecord(client.enabledFeatures) || typeof client.enabledFeatures.has !== "function"))) {
|
|
312
|
+
throw new InvalidActionSpaceError("tool adapter client must provide call() and beginCall(); enabledFeatures must be set-like when present");
|
|
313
|
+
}
|
|
314
|
+
const clonedOptions = clonePureJson(options, (message) => new InvalidActionSpaceError(`tool adapter options: ${message}`));
|
|
315
|
+
if (!isRecord(clonedOptions)) {
|
|
316
|
+
throw new InvalidActionSpaceError("tool adapter options must be an object");
|
|
317
|
+
}
|
|
318
|
+
const allowed = new Set(["includeObservation", "includeProtectedActions", "maxActions"]);
|
|
319
|
+
for (const key of Object.keys(clonedOptions)) {
|
|
320
|
+
if (!allowed.has(key)) {
|
|
321
|
+
throw new InvalidActionSpaceError(`unknown tool adapter option ${key}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (clonedOptions.includeObservation !== undefined &&
|
|
325
|
+
typeof clonedOptions.includeObservation !== "boolean") {
|
|
326
|
+
throw new InvalidActionSpaceError("includeObservation must be a boolean");
|
|
327
|
+
}
|
|
328
|
+
if (clonedOptions.includeProtectedActions !== undefined &&
|
|
329
|
+
typeof clonedOptions.includeProtectedActions !== "boolean") {
|
|
330
|
+
throw new InvalidActionSpaceError("includeProtectedActions must be a boolean");
|
|
331
|
+
}
|
|
332
|
+
const maxActions = clonedOptions.maxActions ?? DEFAULT_MAX_ACTIONS;
|
|
333
|
+
if (typeof maxActions !== "number" ||
|
|
334
|
+
!Number.isSafeInteger(maxActions) ||
|
|
335
|
+
maxActions <= 0) {
|
|
336
|
+
throw new InvalidActionSpaceError("maxActions must be a positive safe integer");
|
|
337
|
+
}
|
|
338
|
+
this.#client = client;
|
|
339
|
+
this.#includeObservation = clonedOptions.includeObservation ?? true;
|
|
340
|
+
this.#includeProtectedActions = clonedOptions.includeProtectedActions ?? false;
|
|
341
|
+
if (this.#includeProtectedActions &&
|
|
342
|
+
!protectedFeatureEnabled(this.#client)) {
|
|
343
|
+
throw new InvalidActionSpaceError(`includeProtectedActions requires negotiated ${ACTION_PROTECTED_FEATURE}`);
|
|
344
|
+
}
|
|
345
|
+
this.#maxActions = maxActions;
|
|
346
|
+
}
|
|
347
|
+
async discover(options = {}) {
|
|
348
|
+
const normalized = normalizeDiscoveryOptions(options);
|
|
349
|
+
const capabilities = await this.#client.call("device.capabilities", undefined, callOptions(normalized));
|
|
350
|
+
const tools = compileDefinitions(capabilities, this.#includeObservation, this.#includeProtectedActions, this.#maxActions);
|
|
351
|
+
if (this.#revision >= Number.MAX_SAFE_INTEGER) {
|
|
352
|
+
throw new InvalidActionSpaceError("tool catalog revision is exhausted");
|
|
353
|
+
}
|
|
354
|
+
this.#revision += 1;
|
|
355
|
+
return new ToolCatalog(this.#client, this.#revision, tools);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
export function requestIdOf(handle) {
|
|
359
|
+
return handle.requestId;
|
|
360
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export type ToolAdapterErrorCode = "invalid_action_space" | "invalid_tool_arguments" | "invalid_tool_options" | "invalid_tool_result" | "unknown_tool";
|
|
2
|
+
export declare class ToolAdapterError extends Error {
|
|
3
|
+
readonly code: ToolAdapterErrorCode;
|
|
4
|
+
constructor(code: ToolAdapterErrorCode, message: string, options?: ErrorOptions);
|
|
5
|
+
}
|
|
6
|
+
export declare class InvalidActionSpaceError extends ToolAdapterError {
|
|
7
|
+
constructor(message: string, options?: ErrorOptions);
|
|
8
|
+
}
|
|
9
|
+
export declare class UnknownToolError extends ToolAdapterError {
|
|
10
|
+
readonly toolName: string;
|
|
11
|
+
constructor(toolName: string);
|
|
12
|
+
}
|
|
13
|
+
export declare class InvalidToolArgumentsError extends ToolAdapterError {
|
|
14
|
+
readonly toolName: string;
|
|
15
|
+
constructor(toolName: string, message: string, options?: ErrorOptions);
|
|
16
|
+
}
|
|
17
|
+
export declare class InvalidToolOptionsError extends ToolAdapterError {
|
|
18
|
+
constructor(message: string);
|
|
19
|
+
}
|
|
20
|
+
export declare class InvalidToolResultError extends ToolAdapterError {
|
|
21
|
+
readonly toolName: string;
|
|
22
|
+
constructor(toolName: string, message: string);
|
|
23
|
+
}
|