hiveagents-runtime 0.0.0-stage → 0.1.0-beta.3
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 +202 -0
- package/README.md +89 -2
- package/dist/adapter-kit.d.ts +37 -0
- package/dist/adapter-kit.js +34 -0
- package/dist/adapter-kit.js.map +1 -0
- package/dist/agent-Bj5YPrO7.d.ts +169 -0
- package/dist/agent-D6OXR7UF.js +24 -0
- package/dist/agent-D6OXR7UF.js.map +1 -0
- package/dist/agent-readiness-KSGNKTGK.js +19 -0
- package/dist/agent-readiness-KSGNKTGK.js.map +1 -0
- package/dist/capture-runtime-GP6NZ2ee.d.ts +54 -0
- package/dist/chunk-2RK74GCA.js +2397 -0
- package/dist/chunk-2RK74GCA.js.map +1 -0
- package/dist/chunk-3TIYA3K5.js +55 -0
- package/dist/chunk-3TIYA3K5.js.map +1 -0
- package/dist/chunk-6FIXXWNM.js +1 -0
- package/dist/chunk-6FIXXWNM.js.map +1 -0
- package/dist/chunk-6XIJW65Q.js +52 -0
- package/dist/chunk-6XIJW65Q.js.map +1 -0
- package/dist/chunk-7LDQKJKI.js +248 -0
- package/dist/chunk-7LDQKJKI.js.map +1 -0
- package/dist/chunk-CPN4DOXH.js +115 -0
- package/dist/chunk-CPN4DOXH.js.map +1 -0
- package/dist/chunk-DAXPAV2L.js +810 -0
- package/dist/chunk-DAXPAV2L.js.map +1 -0
- package/dist/chunk-DQEMIGKC.js +291 -0
- package/dist/chunk-DQEMIGKC.js.map +1 -0
- package/dist/chunk-DZFFGUIA.js +81 -0
- package/dist/chunk-DZFFGUIA.js.map +1 -0
- package/dist/chunk-EEUYQFCP.js +106 -0
- package/dist/chunk-EEUYQFCP.js.map +1 -0
- package/dist/chunk-G6JV7WV6.js +521 -0
- package/dist/chunk-G6JV7WV6.js.map +1 -0
- package/dist/chunk-GFVYNPLS.js +118 -0
- package/dist/chunk-GFVYNPLS.js.map +1 -0
- package/dist/chunk-GS5U3KUN.js +201 -0
- package/dist/chunk-GS5U3KUN.js.map +1 -0
- package/dist/chunk-HB7FBSH2.js +960 -0
- package/dist/chunk-HB7FBSH2.js.map +1 -0
- package/dist/chunk-HZFZX5A3.js +21 -0
- package/dist/chunk-HZFZX5A3.js.map +1 -0
- package/dist/chunk-J7VAYJKM.js +595 -0
- package/dist/chunk-J7VAYJKM.js.map +1 -0
- package/dist/chunk-NCNSHOF7.js +52 -0
- package/dist/chunk-NCNSHOF7.js.map +1 -0
- package/dist/chunk-RH5A5U7G.js +202 -0
- package/dist/chunk-RH5A5U7G.js.map +1 -0
- package/dist/chunk-RX3XZENU.js +385 -0
- package/dist/chunk-RX3XZENU.js.map +1 -0
- package/dist/chunk-RXU2Q2HF.js +49 -0
- package/dist/chunk-RXU2Q2HF.js.map +1 -0
- package/dist/chunk-TG7NTMTR.js +208 -0
- package/dist/chunk-TG7NTMTR.js.map +1 -0
- package/dist/chunk-TWGEYWMO.js +1217 -0
- package/dist/chunk-TWGEYWMO.js.map +1 -0
- package/dist/chunk-UZPDDQVJ.js +2910 -0
- package/dist/chunk-UZPDDQVJ.js.map +1 -0
- package/dist/chunk-WMKO5XOE.js +601 -0
- package/dist/chunk-WMKO5XOE.js.map +1 -0
- package/dist/chunk-WOQBVJH5.js +175 -0
- package/dist/chunk-WOQBVJH5.js.map +1 -0
- package/dist/chunk-WVT5SEKC.js +581 -0
- package/dist/chunk-WVT5SEKC.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +26 -0
- package/dist/cli.js.map +1 -0
- package/dist/errors-BNHvvjn9.d.ts +98 -0
- package/dist/execution-halt-B8G0fOKS.d.ts +12 -0
- package/dist/execution-types-ClYYqPQP.d.ts +239 -0
- package/dist/host-ledger-VPRWVVOS.js +25 -0
- package/dist/host-ledger-VPRWVVOS.js.map +1 -0
- package/dist/hosted-runtime.d.ts +168 -0
- package/dist/hosted-runtime.js +858 -0
- package/dist/hosted-runtime.js.map +1 -0
- package/dist/index-B86C6VAD.d.ts +41 -0
- package/dist/index.d.ts +344 -0
- package/dist/index.js +8825 -0
- package/dist/index.js.map +1 -0
- package/dist/memory-items-BSTC0_R0.d.ts +28 -0
- package/dist/memory-tools.d.ts +222 -0
- package/dist/memory-tools.js +923 -0
- package/dist/memory-tools.js.map +1 -0
- package/dist/orchestration/dynamic.d.ts +854 -0
- package/dist/orchestration/dynamic.js +3150 -0
- package/dist/orchestration/dynamic.js.map +1 -0
- package/dist/orchestration/graph.d.ts +11 -0
- package/dist/orchestration/graph.js +9 -0
- package/dist/orchestration/graph.js.map +1 -0
- package/dist/orchestration/index.d.ts +2385 -0
- package/dist/orchestration/index.js +6409 -0
- package/dist/orchestration/index.js.map +1 -0
- package/dist/orchestration/log.d.ts +301 -0
- package/dist/orchestration/log.js +3058 -0
- package/dist/orchestration/log.js.map +1 -0
- package/dist/orchestration/memory.d.ts +711 -0
- package/dist/orchestration/memory.js +27 -0
- package/dist/orchestration/memory.js.map +1 -0
- package/dist/provider-DX5Mf0uq.d.ts +151 -0
- package/dist/routing/index.d.ts +29 -0
- package/dist/routing/index.js +386 -0
- package/dist/routing/index.js.map +1 -0
- package/dist/routing/learning/index.d.ts +433 -0
- package/dist/routing/learning/index.js +2502 -0
- package/dist/routing/learning/index.js.map +1 -0
- package/dist/runtime-BSjrnxeF.d.ts +283 -0
- package/dist/runtime-OISPXS4I.js +19 -0
- package/dist/runtime-OISPXS4I.js.map +1 -0
- package/dist/store-types-2YdceOMy.d.ts +78 -0
- package/dist/types-BB7KqceP.d.ts +52 -0
- package/dist/types-CIqkKXix.d.ts +86 -0
- package/dist/types-DTFc1qO6.d.ts +1065 -0
- package/dist/types-DYex3p7_.d.ts +88 -0
- package/docs/licenses/ruflo-memory-MIT.txt +21 -0
- package/docs/releases/0.1.0-beta.3.md +13 -0
- package/package.json +114 -4
|
@@ -0,0 +1,858 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildEnvironment
|
|
3
|
+
} from "./chunk-3TIYA3K5.js";
|
|
4
|
+
import {
|
|
5
|
+
Runtime,
|
|
6
|
+
createClaudeProvider,
|
|
7
|
+
createCodexProvider
|
|
8
|
+
} from "./chunk-2RK74GCA.js";
|
|
9
|
+
import "./chunk-J7VAYJKM.js";
|
|
10
|
+
import {
|
|
11
|
+
validateProviderId
|
|
12
|
+
} from "./chunk-G6JV7WV6.js";
|
|
13
|
+
import "./chunk-6FIXXWNM.js";
|
|
14
|
+
import {
|
|
15
|
+
isSafeSessionId
|
|
16
|
+
} from "./chunk-TWGEYWMO.js";
|
|
17
|
+
import "./chunk-GS5U3KUN.js";
|
|
18
|
+
import "./chunk-EEUYQFCP.js";
|
|
19
|
+
import "./chunk-RX3XZENU.js";
|
|
20
|
+
import "./chunk-7LDQKJKI.js";
|
|
21
|
+
import {
|
|
22
|
+
ExecutionHaltedError
|
|
23
|
+
} from "./chunk-NCNSHOF7.js";
|
|
24
|
+
import {
|
|
25
|
+
AbortError,
|
|
26
|
+
AdmissionRefusedError,
|
|
27
|
+
NotAuthenticatedError,
|
|
28
|
+
OutputLimitError,
|
|
29
|
+
ProviderUnavailableError,
|
|
30
|
+
TimeoutError,
|
|
31
|
+
UnknownModelError,
|
|
32
|
+
UnsupportedCapabilityError,
|
|
33
|
+
UsageLimitError
|
|
34
|
+
} from "./chunk-TG7NTMTR.js";
|
|
35
|
+
|
|
36
|
+
// src/hosted/json.ts
|
|
37
|
+
import { createHash } from "node:crypto";
|
|
38
|
+
import { types } from "node:util";
|
|
39
|
+
var HOSTED_BOUNDS = Object.freeze({ metadataBytes: 2 * 1024 * 1024, valueBytes: 256 * 1024 * 1024, nodes: 1e6, depth: 128, promptBytes: 16 * 1024 * 1024, pending: 32 });
|
|
40
|
+
function hostedHalt(reason = "HOSTED_PROTOCOL_INVALID", cause) {
|
|
41
|
+
return new ExecutionHaltedError({ sanitizedDiagnostics: { reason } }, cause === void 0 ? void 0 : { cause });
|
|
42
|
+
}
|
|
43
|
+
function invalid() {
|
|
44
|
+
throw hostedHalt();
|
|
45
|
+
}
|
|
46
|
+
function record(value, fields, optional = []) {
|
|
47
|
+
if (!value || typeof value !== "object" || types.isProxy(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
|
|
48
|
+
invalid();
|
|
49
|
+
const result2 = /* @__PURE__ */ Object.create(null);
|
|
50
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
51
|
+
const d = Object.getOwnPropertyDescriptor(value, key);
|
|
52
|
+
if (typeof key !== "string" || !fields.includes(key) || !Object.hasOwn(d, "value"))
|
|
53
|
+
invalid();
|
|
54
|
+
result2[key] = d.value;
|
|
55
|
+
}
|
|
56
|
+
for (const key of fields)
|
|
57
|
+
if (!optional.includes(key) && !Object.hasOwn(result2, key))
|
|
58
|
+
invalid();
|
|
59
|
+
return result2;
|
|
60
|
+
}
|
|
61
|
+
function integer(value, min = 1, max = 2 ** 31 - 1) {
|
|
62
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max)
|
|
63
|
+
invalid();
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
function text(value, max = 4096) {
|
|
67
|
+
if (typeof value !== "string" || value.length > max || value.includes("\0"))
|
|
68
|
+
invalid();
|
|
69
|
+
return value;
|
|
70
|
+
}
|
|
71
|
+
function id(value) {
|
|
72
|
+
const s = text(value, 64);
|
|
73
|
+
if (!/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(s))
|
|
74
|
+
invalid();
|
|
75
|
+
return s;
|
|
76
|
+
}
|
|
77
|
+
function digest(value) {
|
|
78
|
+
const s = text(value, 64);
|
|
79
|
+
if (!/^[a-f0-9]{64}$/.test(s))
|
|
80
|
+
invalid();
|
|
81
|
+
return s;
|
|
82
|
+
}
|
|
83
|
+
function absolute(value) {
|
|
84
|
+
const s = text(value);
|
|
85
|
+
if (!s.startsWith("/") || s.split("/").includes("..") || s.split("/").includes("."))
|
|
86
|
+
invalid();
|
|
87
|
+
return s;
|
|
88
|
+
}
|
|
89
|
+
function array(value, max = 128) {
|
|
90
|
+
if (!value || typeof value !== "object" || types.isProxy(value) || !Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype)
|
|
91
|
+
invalid();
|
|
92
|
+
const length = Object.getOwnPropertyDescriptor(value, "length").value;
|
|
93
|
+
if (length > max || Reflect.ownKeys(value).length !== length + 1)
|
|
94
|
+
invalid();
|
|
95
|
+
const values = [];
|
|
96
|
+
for (let i = 0; i < length; i++) {
|
|
97
|
+
const d = Object.getOwnPropertyDescriptor(value, String(i));
|
|
98
|
+
if (!d || !Object.hasOwn(d, "value") || !d.enumerable)
|
|
99
|
+
invalid();
|
|
100
|
+
values.push(d.value);
|
|
101
|
+
}
|
|
102
|
+
return values;
|
|
103
|
+
}
|
|
104
|
+
function strings(value, max = 128) {
|
|
105
|
+
return array(value, max).map((v) => text(v));
|
|
106
|
+
}
|
|
107
|
+
function inspect(value, maxBytes, freeze) {
|
|
108
|
+
const hash = createHash("sha256"), ancestors = /* @__PURE__ */ new Set();
|
|
109
|
+
let bytes = 0, nodes = 0;
|
|
110
|
+
const write = (s) => {
|
|
111
|
+
bytes += Buffer.byteLength(s);
|
|
112
|
+
if (bytes > maxBytes)
|
|
113
|
+
invalid();
|
|
114
|
+
hash.update(s);
|
|
115
|
+
};
|
|
116
|
+
const string = (s) => {
|
|
117
|
+
write('"');
|
|
118
|
+
for (let offset = 0; offset < s.length; ) {
|
|
119
|
+
let end = Math.min(s.length, offset + 8192);
|
|
120
|
+
if (end < s.length && s.charCodeAt(end - 1) >= 55296 && s.charCodeAt(end - 1) <= 56319 && s.charCodeAt(end) >= 56320 && s.charCodeAt(end) <= 57343)
|
|
121
|
+
end--;
|
|
122
|
+
write(JSON.stringify(s.slice(offset, end)).slice(1, -1));
|
|
123
|
+
offset = end;
|
|
124
|
+
}
|
|
125
|
+
write('"');
|
|
126
|
+
};
|
|
127
|
+
const visit = (v, depth) => {
|
|
128
|
+
if (++nodes > HOSTED_BOUNDS.nodes || depth > HOSTED_BOUNDS.depth)
|
|
129
|
+
invalid();
|
|
130
|
+
if (v === null || typeof v === "boolean") {
|
|
131
|
+
write(String(v));
|
|
132
|
+
return v;
|
|
133
|
+
}
|
|
134
|
+
if (typeof v === "string") {
|
|
135
|
+
string(v);
|
|
136
|
+
return v;
|
|
137
|
+
}
|
|
138
|
+
if (typeof v === "number" && Number.isFinite(v)) {
|
|
139
|
+
write(JSON.stringify(v));
|
|
140
|
+
return v;
|
|
141
|
+
}
|
|
142
|
+
if (!v || typeof v !== "object" || types.isProxy(v) || ancestors.has(v))
|
|
143
|
+
invalid();
|
|
144
|
+
const array2 = Array.isArray(v), prototype = Object.getPrototypeOf(v);
|
|
145
|
+
if (array2 ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null)
|
|
146
|
+
invalid();
|
|
147
|
+
const keys = Reflect.ownKeys(v);
|
|
148
|
+
if (keys.length > HOSTED_BOUNDS.nodes || keys.some((k) => typeof k !== "string"))
|
|
149
|
+
invalid();
|
|
150
|
+
ancestors.add(v);
|
|
151
|
+
const get = (k) => {
|
|
152
|
+
const d = Object.getOwnPropertyDescriptor(v, k);
|
|
153
|
+
if (!d || !Object.hasOwn(d, "value") || !d.enumerable)
|
|
154
|
+
invalid();
|
|
155
|
+
return d.value;
|
|
156
|
+
};
|
|
157
|
+
let result2;
|
|
158
|
+
if (array2) {
|
|
159
|
+
const n = Object.getOwnPropertyDescriptor(v, "length").value;
|
|
160
|
+
if (keys.length !== n + 1 || n > HOSTED_BOUNDS.nodes)
|
|
161
|
+
invalid();
|
|
162
|
+
const items = [];
|
|
163
|
+
write("[");
|
|
164
|
+
for (let i = 0; i < n; i++) {
|
|
165
|
+
if (i)
|
|
166
|
+
write(",");
|
|
167
|
+
const item2 = get(String(i));
|
|
168
|
+
items.push(item2 === void 0 ? null : visit(item2, depth + 1));
|
|
169
|
+
}
|
|
170
|
+
write("]");
|
|
171
|
+
result2 = items;
|
|
172
|
+
} else {
|
|
173
|
+
const data = /* @__PURE__ */ Object.create(null);
|
|
174
|
+
write("{");
|
|
175
|
+
let count = 0;
|
|
176
|
+
for (const key of keys.sort()) {
|
|
177
|
+
const item2 = get(key);
|
|
178
|
+
if (item2 === void 0)
|
|
179
|
+
continue;
|
|
180
|
+
if (count++)
|
|
181
|
+
write(",");
|
|
182
|
+
string(key);
|
|
183
|
+
write(":");
|
|
184
|
+
data[key] = visit(item2, depth + 1);
|
|
185
|
+
}
|
|
186
|
+
write("}");
|
|
187
|
+
result2 = data;
|
|
188
|
+
}
|
|
189
|
+
ancestors.delete(v);
|
|
190
|
+
if (freeze)
|
|
191
|
+
Object.freeze(result2);
|
|
192
|
+
return result2;
|
|
193
|
+
};
|
|
194
|
+
return { value: visit(value, 1), digest: hash.digest("hex") };
|
|
195
|
+
}
|
|
196
|
+
function hostedDigest(value) {
|
|
197
|
+
return inspect(value, HOSTED_BOUNDS.valueBytes, false).digest;
|
|
198
|
+
}
|
|
199
|
+
function snapshot(value, maxBytes = HOSTED_BOUNDS.valueBytes, freeze = false) {
|
|
200
|
+
return inspect(value, integer(maxBytes, 1, HOSTED_BOUNDS.valueBytes), freeze).value;
|
|
201
|
+
}
|
|
202
|
+
function channelId(value) {
|
|
203
|
+
const s = text(value, 32);
|
|
204
|
+
if (!/^[a-f0-9]{32}$/.test(s)) invalid();
|
|
205
|
+
return s;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// src/hosted/validation.ts
|
|
209
|
+
function captureHostedDescriptor(input) {
|
|
210
|
+
const value = snapshot(input, HOSTED_BOUNDS.metadataBytes, true), r = record(value, ["schemaVersion", "provider", "bindingId", "bindingDigest", "token", "adapterVersion", "modelCatalog", "execCapabilities", "target", "probeRecipeId", "limits", "recipes"]);
|
|
211
|
+
if (r.schemaVersion !== 1)
|
|
212
|
+
invalid();
|
|
213
|
+
validateProviderId(text(r.provider, 64));
|
|
214
|
+
id(r.bindingId);
|
|
215
|
+
digest(r.bindingDigest);
|
|
216
|
+
id(r.probeRecipeId);
|
|
217
|
+
if (!/^[a-zA-Z][a-zA-Z0-9]*V[1-9][0-9]*$/.test(text(r.token, 64)))
|
|
218
|
+
invalid();
|
|
219
|
+
text(r.adapterVersion, 128);
|
|
220
|
+
const target = record(r.target, ["command", "argsPrefix", "executableDigest", "identityFiles"]);
|
|
221
|
+
absolute(target.command);
|
|
222
|
+
strings(target.argsPrefix);
|
|
223
|
+
digest(target.executableDigest);
|
|
224
|
+
for (const file of strings(target.identityFiles))
|
|
225
|
+
absolute(file);
|
|
226
|
+
const limits = record(r.limits, ["maxTurnMs", "maxProbeMs", "maxOutputBytes"]);
|
|
227
|
+
integer(limits.maxTurnMs);
|
|
228
|
+
integer(limits.maxProbeMs);
|
|
229
|
+
integer(limits.maxOutputBytes, 1, 64 * 1024 * 1024);
|
|
230
|
+
if (!Array.isArray(r.modelCatalog) || !r.modelCatalog.length || r.modelCatalog.length > 1024 || !Array.isArray(r.recipes) || !r.recipes.length || r.recipes.length > 128)
|
|
231
|
+
invalid();
|
|
232
|
+
const models = /* @__PURE__ */ new Set();
|
|
233
|
+
for (const model of r.modelCatalog) {
|
|
234
|
+
const m = record(model, ["id", "provider", "aliases", "source", "availability", "displayName", "contextWindow", "maxOutputTokens", "supportedEffort"], ["displayName", "contextWindow", "maxOutputTokens", "supportedEffort"]);
|
|
235
|
+
if (m.provider !== r.provider || !text(m.id, 512) || models.has(m.id))
|
|
236
|
+
invalid();
|
|
237
|
+
models.add(m.id);
|
|
238
|
+
strings(m.aliases);
|
|
239
|
+
if (!["agent-sdk", "app-server", "compatibility-catalog", "explicit"].includes(m.source) || !["available", "unavailable", "unverified"].includes(m.availability))
|
|
240
|
+
invalid();
|
|
241
|
+
}
|
|
242
|
+
const ids = /* @__PURE__ */ new Set();
|
|
243
|
+
for (const recipe of r.recipes) {
|
|
244
|
+
const p = record(recipe, ["recipeId", "recipeDigest", "contextArgs", "permissionArgs", "providerOptionsDigest", "clientEnvironmentPolicyDigest", "environmentPolicyId", "modelIds", "efforts", "allowInstructions", "cwdRoots"]);
|
|
245
|
+
const key = id(p.recipeId);
|
|
246
|
+
if (ids.has(key))
|
|
247
|
+
invalid();
|
|
248
|
+
ids.add(key);
|
|
249
|
+
digest(p.recipeDigest);
|
|
250
|
+
strings(p.contextArgs);
|
|
251
|
+
strings(p.permissionArgs);
|
|
252
|
+
digest(p.providerOptionsDigest);
|
|
253
|
+
digest(p.clientEnvironmentPolicyDigest);
|
|
254
|
+
text(p.environmentPolicyId, 128);
|
|
255
|
+
if (typeof p.allowInstructions !== "boolean" || strings(p.modelIds).some((m) => !models.has(m)))
|
|
256
|
+
invalid();
|
|
257
|
+
strings(p.efforts);
|
|
258
|
+
for (const root of strings(p.cwdRoots))
|
|
259
|
+
absolute(root);
|
|
260
|
+
}
|
|
261
|
+
if (!ids.has(r.probeRecipeId))
|
|
262
|
+
invalid();
|
|
263
|
+
const caps = record(r.execCapabilities, Object.keys(r.execCapabilities));
|
|
264
|
+
for (const support of Object.values(caps))
|
|
265
|
+
if (!["supported", "partial", "unsupported", "unverified"].includes(support))
|
|
266
|
+
invalid();
|
|
267
|
+
return value;
|
|
268
|
+
}
|
|
269
|
+
function captureHostedContext(input) {
|
|
270
|
+
const r = record(input, ["schemaVersion", "channelId", "systemId", "generation", "dataDirectory", "descriptors", "client"]);
|
|
271
|
+
if (r.schemaVersion !== 1)
|
|
272
|
+
invalid();
|
|
273
|
+
channelId(r.channelId);
|
|
274
|
+
text(r.systemId, 128);
|
|
275
|
+
integer(r.generation);
|
|
276
|
+
absolute(r.dataDirectory);
|
|
277
|
+
const values = array(r.descriptors, 32);
|
|
278
|
+
if (!values.length)
|
|
279
|
+
invalid();
|
|
280
|
+
const descriptors = values.map(captureHostedDescriptor), providers = /* @__PURE__ */ new Set(), bindings = /* @__PURE__ */ new Set();
|
|
281
|
+
for (const d of descriptors) {
|
|
282
|
+
if (providers.has(d.provider) || bindings.has(d.bindingId))
|
|
283
|
+
invalid();
|
|
284
|
+
providers.add(d.provider);
|
|
285
|
+
bindings.add(d.bindingId);
|
|
286
|
+
}
|
|
287
|
+
return { r, descriptors: Object.freeze(descriptors) };
|
|
288
|
+
}
|
|
289
|
+
var base = ["schemaVersion", "channelId", "systemId", "generation", "bindingId", "requestId", "remainingMs"];
|
|
290
|
+
function captureHostedRequest(input) {
|
|
291
|
+
const method2 = record(input, [...base, "method", "recipeId", "cwd", "turn", "operationId", "targetRequestId", "turnId", "semanticDigest", "intentId"], ["recipeId", "cwd", "turn", "operationId", "targetRequestId", "turnId", "semanticDigest", "intentId"]).method;
|
|
292
|
+
const extra = ["detect", "auth", "models", "compatibility"].includes(method2) ? ["recipeId", "cwd"] : ["execute", "stream-open"].includes(method2) ? ["recipeId", "turn"] : ["stream-next", "stream-return", "stream-throw", "status"].includes(method2) ? ["operationId"] : method2 === "cancel" ? ["targetRequestId"] : method2 === "intent-begin" ? ["turnId", "semanticDigest"] : method2 === "intent-finish" ? ["intentId"] : invalid();
|
|
293
|
+
const r = record(input, [...base, "method", ...extra]);
|
|
294
|
+
if (r.schemaVersion !== 1)
|
|
295
|
+
invalid();
|
|
296
|
+
channelId(r.channelId);
|
|
297
|
+
text(r.systemId, 128);
|
|
298
|
+
integer(r.generation);
|
|
299
|
+
id(r.bindingId);
|
|
300
|
+
id(r.requestId);
|
|
301
|
+
integer(r.remainingMs);
|
|
302
|
+
for (const k of ["recipeId", "operationId", "targetRequestId", "turnId", "intentId"])
|
|
303
|
+
if (r[k] !== void 0)
|
|
304
|
+
id(r[k]);
|
|
305
|
+
if (r.semanticDigest !== void 0)
|
|
306
|
+
digest(r.semanticDigest);
|
|
307
|
+
if (r.cwd !== void 0)
|
|
308
|
+
absolute(r.cwd);
|
|
309
|
+
if (r.turn !== void 0) {
|
|
310
|
+
const t = record(r.turn, ["mode", "modelId", "cwd", "prompt", "timeoutMs", "maxOutputBytes", "sessionId", "instructions", "effort", "outputSchema", "intentId", "priority"], ["sessionId", "instructions", "effort", "outputSchema", "intentId", "priority"]);
|
|
311
|
+
if (!["open", "resume", "fork", "one-shot"].includes(t.mode))
|
|
312
|
+
invalid();
|
|
313
|
+
text(t.modelId, 512);
|
|
314
|
+
absolute(t.cwd);
|
|
315
|
+
if (typeof t.prompt !== "string" || Buffer.byteLength(t.prompt) > HOSTED_BOUNDS.promptBytes)
|
|
316
|
+
invalid();
|
|
317
|
+
integer(t.timeoutMs);
|
|
318
|
+
integer(t.maxOutputBytes, 1, 64 * 1024 * 1024);
|
|
319
|
+
if (t.sessionId !== void 0 && !isSafeSessionId(t.sessionId))
|
|
320
|
+
invalid();
|
|
321
|
+
if (t.outputSchema !== void 0 && (t.outputSchema === null || typeof t.outputSchema !== "object" || Array.isArray(t.outputSchema)))
|
|
322
|
+
invalid();
|
|
323
|
+
if (t.instructions !== void 0)
|
|
324
|
+
text(t.instructions, 1024 * 1024);
|
|
325
|
+
if (t.effort !== void 0)
|
|
326
|
+
text(t.effort, 128);
|
|
327
|
+
if (t.intentId !== void 0)
|
|
328
|
+
id(t.intentId);
|
|
329
|
+
if (t.priority !== void 0 && t.priority !== "low")
|
|
330
|
+
invalid();
|
|
331
|
+
}
|
|
332
|
+
return snapshot(r, 32 * 1024 * 1024, true);
|
|
333
|
+
}
|
|
334
|
+
function captureHostedReply(input) {
|
|
335
|
+
const r = record(input, ["schemaVersion", "channelId", "systemId", "generation", "bindingId", "requestId", "ok", "data", "error"], ["data", "error"]);
|
|
336
|
+
if (r.schemaVersion !== 1)
|
|
337
|
+
invalid();
|
|
338
|
+
channelId(r.channelId);
|
|
339
|
+
text(r.systemId, 128);
|
|
340
|
+
integer(r.generation);
|
|
341
|
+
id(r.bindingId);
|
|
342
|
+
id(r.requestId);
|
|
343
|
+
if (r.ok === true) {
|
|
344
|
+
record(r, ["schemaVersion", "channelId", "systemId", "generation", "bindingId", "requestId", "ok", "data"]);
|
|
345
|
+
} else if (r.ok === false) {
|
|
346
|
+
record(r, ["schemaVersion", "channelId", "systemId", "generation", "bindingId", "requestId", "ok", "error"]);
|
|
347
|
+
const e = record(r.error, ["code", "receiptDigest", "reason"], ["receiptDigest", "reason"]);
|
|
348
|
+
if (!["ADMISSION_REFUSED", "EXECUTION_HALTED", "USAGE_LIMIT", "UNSUPPORTED_CAPABILITY", "INVALID_RUNTIME_PROTOCOL", "ABORTED", "TIMEOUT", "OUTPUT_LIMIT", "PROVIDER_UNAVAILABLE", "NOT_AUTHENTICATED"].includes(e.code))
|
|
349
|
+
invalid();
|
|
350
|
+
if (e.code === "ADMISSION_REFUSED") {
|
|
351
|
+
record(e, ["code", "reason", "receiptDigest"]);
|
|
352
|
+
digest(e.receiptDigest);
|
|
353
|
+
if (!["concurrency-limit", "hourly-limit", "daily-limit", "quota-cooldown", "wait-timeout"].includes(e.reason))
|
|
354
|
+
invalid();
|
|
355
|
+
} else
|
|
356
|
+
record(e, ["code", "receiptDigest"], ["receiptDigest"]);
|
|
357
|
+
if (e.receiptDigest !== void 0)
|
|
358
|
+
digest(e.receiptDigest);
|
|
359
|
+
} else
|
|
360
|
+
invalid();
|
|
361
|
+
return snapshot(r);
|
|
362
|
+
}
|
|
363
|
+
function sameTarget(value, d) {
|
|
364
|
+
const r = record(value, ["command", "argsPrefix"]);
|
|
365
|
+
return r.command === d.target.command && JSON.stringify(strings(r.argsPrefix)) === JSON.stringify(d.target.argsPrefix);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// src/hosted/client.ts
|
|
369
|
+
import { randomUUID } from "node:crypto";
|
|
370
|
+
import { types as types2 } from "node:util";
|
|
371
|
+
function method(value, key) {
|
|
372
|
+
if (!value || typeof value !== "object" || types2.isProxy(value))
|
|
373
|
+
invalid();
|
|
374
|
+
let current = value;
|
|
375
|
+
for (let depth = 0; current && depth < 8; depth++, current = Object.getPrototypeOf(current)) {
|
|
376
|
+
if (types2.isProxy(current))
|
|
377
|
+
invalid();
|
|
378
|
+
const d = Object.getOwnPropertyDescriptor(current, key);
|
|
379
|
+
if (d) {
|
|
380
|
+
if (!Object.hasOwn(d, "value") || typeof d.value !== "function")
|
|
381
|
+
invalid();
|
|
382
|
+
return d.value.bind(value);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
return invalid();
|
|
386
|
+
}
|
|
387
|
+
function createHostedCaller(context) {
|
|
388
|
+
const call = method(context.client, "call"), close = method(context.client, "close");
|
|
389
|
+
let pending = 0, closed = false;
|
|
390
|
+
const stop = (cause) => {
|
|
391
|
+
if (!closed) {
|
|
392
|
+
closed = true;
|
|
393
|
+
try {
|
|
394
|
+
close();
|
|
395
|
+
} catch {
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
throw hostedHalt("HOSTED_CHANNEL_UNKNOWN", cause);
|
|
399
|
+
};
|
|
400
|
+
return async (bindingId, body, remainingMs, signal2) => {
|
|
401
|
+
if (closed)
|
|
402
|
+
throw hostedHalt("HOSTED_CHANNEL_CLOSED");
|
|
403
|
+
if (signal2?.aborted)
|
|
404
|
+
throw signal2.reason ?? new AbortError({ retryable: false });
|
|
405
|
+
if (pending >= HOSTED_BOUNDS.pending)
|
|
406
|
+
throw hostedHalt("HOSTED_PENDING_LIMIT");
|
|
407
|
+
const request = captureHostedRequest({ schemaVersion: 1, channelId: context.channelId, systemId: context.systemId, generation: context.generation, bindingId, requestId: randomUUID(), remainingMs, ...body });
|
|
408
|
+
pending++;
|
|
409
|
+
let reply;
|
|
410
|
+
try {
|
|
411
|
+
const work = call(request, { remainingMs, ...signal2 === void 0 ? {} : { signal: signal2 } });
|
|
412
|
+
if (!types2.isPromise(work) || Object.getPrototypeOf(work) !== Promise.prototype || Object.hasOwn(work, "constructor") || Object.hasOwn(work, "then"))
|
|
413
|
+
stop();
|
|
414
|
+
reply = captureHostedReply(await work);
|
|
415
|
+
for (const key of ["channelId", "systemId", "generation", "bindingId", "requestId"])
|
|
416
|
+
if (reply[key] !== request[key])
|
|
417
|
+
stop();
|
|
418
|
+
} catch (error) {
|
|
419
|
+
return stop(error);
|
|
420
|
+
} finally {
|
|
421
|
+
pending--;
|
|
422
|
+
}
|
|
423
|
+
if (reply.ok)
|
|
424
|
+
return reply.data;
|
|
425
|
+
const code = reply.error.code;
|
|
426
|
+
if (code === "EXECUTION_HALTED" || code === "INVALID_RUNTIME_PROTOCOL")
|
|
427
|
+
throw hostedHalt(code);
|
|
428
|
+
const provider = context.descriptors.find((d) => d.bindingId === bindingId)?.provider;
|
|
429
|
+
if (!provider)
|
|
430
|
+
invalid();
|
|
431
|
+
const errorContext = { provider, transport: "exec", retryable: false, ...reply.error.receiptDigest === void 0 ? {} : { sanitizedDiagnostics: { receiptDigest: reply.error.receiptDigest } } };
|
|
432
|
+
if (reply.error.code === "ADMISSION_REFUSED")
|
|
433
|
+
throw new AdmissionRefusedError(provider, { reason: reply.error.reason, receiptDigest: reply.error.receiptDigest });
|
|
434
|
+
const constructors = { USAGE_LIMIT: UsageLimitError, ABORTED: AbortError, TIMEOUT: TimeoutError, OUTPUT_LIMIT: OutputLimitError, UNSUPPORTED_CAPABILITY: UnsupportedCapabilityError, PROVIDER_UNAVAILABLE: ProviderUnavailableError };
|
|
435
|
+
if (code === "NOT_AUTHENTICATED")
|
|
436
|
+
throw new NotAuthenticatedError(provider, errorContext);
|
|
437
|
+
throw new constructors[code](errorContext);
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// src/hosted/recipes.ts
|
|
442
|
+
import { relative } from "node:path";
|
|
443
|
+
function createRecipeMatcher(d) {
|
|
444
|
+
const base2 = { ...process.env }, environments = /* @__PURE__ */ new Map();
|
|
445
|
+
const remember = (policy) => {
|
|
446
|
+
const digest2 = hostedDigest(policy), ids = d.recipes.filter((r) => r.clientEnvironmentPolicyDigest === digest2).map((r) => r.recipeId);
|
|
447
|
+
if (!ids.length)
|
|
448
|
+
invalid();
|
|
449
|
+
const envDigest = hostedDigest(buildEnvironment(policy, base2));
|
|
450
|
+
environments.set(envDigest, new Set(ids));
|
|
451
|
+
};
|
|
452
|
+
for (const mode of ["inherit", "minimal", "explicit"])
|
|
453
|
+
if (d.recipes.some((r) => r.clientEnvironmentPolicyDigest === hostedDigest({ mode })))
|
|
454
|
+
remember({ mode });
|
|
455
|
+
const cwdAllowed = (r, cwd) => r.cwdRoots.some((root) => {
|
|
456
|
+
const rel = relative(root, cwd);
|
|
457
|
+
return rel === "" || !rel.startsWith("../") && rel !== ".." && !rel.startsWith("/");
|
|
458
|
+
});
|
|
459
|
+
const select = (env, turn, full) => {
|
|
460
|
+
const envIds = environments.get(hostedDigest(env));
|
|
461
|
+
if (!envIds)
|
|
462
|
+
invalid();
|
|
463
|
+
const found = d.recipes.filter((r) => envIds.has(r.recipeId) && (!turn || cwdAllowed(r, turn.cwd) && hostedDigest(turn.contextArgs) === hostedDigest(r.contextArgs) && hostedDigest(turn.providerOptions ?? {}) === r.providerOptionsDigest) && (!full || hostedDigest(full.permissionArgs) === hostedDigest(r.permissionArgs) && r.modelIds.includes(full.modelId) && (!full.effort || r.efforts.includes(full.effort)) && (!full.instructions || r.allowInstructions)));
|
|
464
|
+
if (!found.length || new Set(found.map((r) => r.environmentPolicyId)).size !== 1)
|
|
465
|
+
invalid();
|
|
466
|
+
return found[0];
|
|
467
|
+
};
|
|
468
|
+
return {
|
|
469
|
+
validate(options) {
|
|
470
|
+
remember(snapshot(options.environment ?? { mode: options.context?.profile === void 0 || options.context.profile === "native" ? "inherit" : "minimal" }));
|
|
471
|
+
},
|
|
472
|
+
probe: (env, turn) => select(env, turn),
|
|
473
|
+
turn: (turn) => select(turn.env, turn, turn)
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// src/hosted/proxy.ts
|
|
478
|
+
function result(value) {
|
|
479
|
+
const r = record(value, ["completed", "failed", "refused", "sessionId", "turnId", "text", "output", "usage", "events", "failure", "terminalEvent", "nativeEvents"], ["sessionId", "turnId", "output", "usage", "failure", "terminalEvent"]);
|
|
480
|
+
if (typeof r.completed !== "boolean" || typeof r.failed !== "boolean" || typeof r.refused !== "boolean" || typeof r.text !== "string" || !Array.isArray(r.events) || !Array.isArray(r.nativeEvents))
|
|
481
|
+
invalid();
|
|
482
|
+
if (r.sessionId !== void 0 && !isSafeSessionId(r.sessionId))
|
|
483
|
+
invalid();
|
|
484
|
+
if (r.turnId !== void 0)
|
|
485
|
+
text(r.turnId, 512);
|
|
486
|
+
if (r.failure !== void 0) {
|
|
487
|
+
const f = record(r.failure, ["kind", "message", "rawCode", "reason", "retryAt"], ["rawCode", "reason", "retryAt"]);
|
|
488
|
+
if (f.retryAt !== void 0 && (f.kind !== "usage-limit" || typeof f.retryAt !== "number" || !Number.isSafeInteger(f.retryAt) || f.retryAt < 0 || f.retryAt > 864e13)) invalid();
|
|
489
|
+
if (!["not-authenticated", "unknown-model", "model-unavailable", "usage-limit", "untrusted-workspace", "session-not-found", "provider-unavailable", "protocol"].includes(f.kind))
|
|
490
|
+
invalid();
|
|
491
|
+
text(f.message, 8192);
|
|
492
|
+
}
|
|
493
|
+
return r;
|
|
494
|
+
}
|
|
495
|
+
function item(value) {
|
|
496
|
+
const r = record(value, ["kind", "sessionId", "event", "result"], ["sessionId", "event", "result"]);
|
|
497
|
+
if (r.kind === "session") {
|
|
498
|
+
record(r, ["kind", "sessionId"]);
|
|
499
|
+
if (!isSafeSessionId(r.sessionId))
|
|
500
|
+
invalid();
|
|
501
|
+
} else if (r.kind === "event") {
|
|
502
|
+
record(r, ["kind", "event"]);
|
|
503
|
+
record(r.event, Object.keys(r.event));
|
|
504
|
+
} else if (r.kind === "result") {
|
|
505
|
+
record(r, ["kind", "result"]);
|
|
506
|
+
result(r.result);
|
|
507
|
+
} else
|
|
508
|
+
invalid();
|
|
509
|
+
return r;
|
|
510
|
+
}
|
|
511
|
+
function createHostedAdapter(d, call, intent, dataDirectory) {
|
|
512
|
+
const matcher = createRecipeMatcher(d), probeMs = (c) => integer(Math.min(d.limits.maxProbeMs, c ? c.remainingMs() : d.limits.maxProbeMs));
|
|
513
|
+
const prepare = (input) => {
|
|
514
|
+
const r = record(input, ["mode", "modelId", "cwd", "prompt", "env", "contextArgs", "permissionArgs", "timeoutMs", "maxOutputBytes", "awaitSettlement", "requireSubscription", "sessionId", "instructions", "effort", "outputSchema", "signal", "providerOptions"], ["awaitSettlement", "requireSubscription", "sessionId", "instructions", "effort", "outputSchema", "signal", "providerOptions"]);
|
|
515
|
+
const copied = snapshot(Object.fromEntries(Object.entries(r).filter(([key]) => key !== "signal")));
|
|
516
|
+
const recipe = matcher.turn(copied), turn = {
|
|
517
|
+
mode: copied.mode,
|
|
518
|
+
modelId: copied.modelId,
|
|
519
|
+
cwd: copied.cwd,
|
|
520
|
+
prompt: copied.prompt,
|
|
521
|
+
timeoutMs: Math.min(integer(copied.timeoutMs), d.limits.maxTurnMs),
|
|
522
|
+
maxOutputBytes: Math.min(integer(copied.maxOutputBytes), d.limits.maxOutputBytes),
|
|
523
|
+
...copied.sessionId === void 0 ? {} : { sessionId: copied.sessionId },
|
|
524
|
+
...copied.instructions === void 0 ? {} : { instructions: copied.instructions },
|
|
525
|
+
...copied.effort === void 0 ? {} : { effort: copied.effort },
|
|
526
|
+
...copied.outputSchema === void 0 ? {} : { outputSchema: copied.outputSchema }
|
|
527
|
+
};
|
|
528
|
+
return { intent: intent.capture(), recipeId: recipe.recipeId, turn, signal: r.signal, deadline: performance.now() + turn.timeoutMs };
|
|
529
|
+
};
|
|
530
|
+
const adapter = {
|
|
531
|
+
id: d.provider,
|
|
532
|
+
async detect(env, c) {
|
|
533
|
+
matcher.probe(env);
|
|
534
|
+
const raw = await call(d.bindingId, { method: "detect", recipeId: d.probeRecipeId, cwd: dataDirectory }, probeMs(c), c?.signal);
|
|
535
|
+
const r = record(raw, ["installed", "launchTarget", "identityFiles", "path", "realpath", "version"], ["launchTarget", "identityFiles", "path", "realpath", "version"]);
|
|
536
|
+
if (typeof r.installed !== "boolean")
|
|
537
|
+
invalid();
|
|
538
|
+
if (r.installed) {
|
|
539
|
+
if (!sameTarget(r.launchTarget, d) || r.path !== d.target.command || r.realpath !== d.target.command)
|
|
540
|
+
invalid();
|
|
541
|
+
}
|
|
542
|
+
if (r.version !== void 0)
|
|
543
|
+
text(r.version, 128);
|
|
544
|
+
if (r.identityFiles !== void 0 && JSON.stringify(strings(r.identityFiles)) !== JSON.stringify(d.target.identityFiles))
|
|
545
|
+
invalid();
|
|
546
|
+
return r;
|
|
547
|
+
},
|
|
548
|
+
async auth(env, c, turn) {
|
|
549
|
+
const recipe = matcher.probe(env, turn), raw = await call(d.bindingId, { method: "auth", recipeId: recipe.recipeId, cwd: turn?.cwd ?? dataDirectory }, probeMs(c), c?.signal);
|
|
550
|
+
const r = record(raw, ["authenticated", "source", "state", "evidence", "account"], ["state", "evidence", "account"]);
|
|
551
|
+
if (typeof r.authenticated !== "boolean" || !["subscription", "api-key", "cloud-provider", "oauth", "oss", "unknown"].includes(r.source))
|
|
552
|
+
invalid();
|
|
553
|
+
if (r.state !== void 0 && !["authenticated", "not-authenticated", "unknown"].includes(r.state))
|
|
554
|
+
invalid();
|
|
555
|
+
if (r.evidence !== void 0 && !["provider-status", "local-configuration", "turn-result"].includes(r.evidence))
|
|
556
|
+
invalid();
|
|
557
|
+
return r;
|
|
558
|
+
},
|
|
559
|
+
async models() {
|
|
560
|
+
return structuredClone(d.modelCatalog);
|
|
561
|
+
},
|
|
562
|
+
async compatibility(env, _version, c) {
|
|
563
|
+
matcher.probe(env);
|
|
564
|
+
const raw = await call(d.bindingId, { method: "compatibility", recipeId: d.probeRecipeId, cwd: dataDirectory }, probeMs(c), c?.signal);
|
|
565
|
+
const r = record(raw, ["provider", "cliVersion", "transport", "evidence", "features", "missingFlags", "knownIssues", "responsePolicy"], ["responsePolicy"]);
|
|
566
|
+
if (r.provider !== d.provider || r.transport !== "exec" || !["live-contract", "help-probe", "unverified"].includes(r.evidence))
|
|
567
|
+
invalid();
|
|
568
|
+
text(r.cliVersion, 128);
|
|
569
|
+
strings(r.missingFlags);
|
|
570
|
+
strings(r.knownIssues);
|
|
571
|
+
const caps = record(r.features, Object.keys(r.features));
|
|
572
|
+
for (const v of Object.values(caps))
|
|
573
|
+
if (!["supported", "partial", "unsupported", "unverified"].includes(v))
|
|
574
|
+
invalid();
|
|
575
|
+
return r;
|
|
576
|
+
},
|
|
577
|
+
async execute(input) {
|
|
578
|
+
const p = prepare(input), scope = await intent.open(p.intent, d.bindingId, p.turn, p.deadline, p.signal);
|
|
579
|
+
try {
|
|
580
|
+
return result(await call(d.bindingId, { method: "execute", recipeId: p.recipeId, turn: scope.turn }, scope.remaining(), scope.signal));
|
|
581
|
+
} finally {
|
|
582
|
+
scope.finish();
|
|
583
|
+
}
|
|
584
|
+
},
|
|
585
|
+
stream(input) {
|
|
586
|
+
const p = prepare(input);
|
|
587
|
+
let opened, pending = false, finished = false, scope;
|
|
588
|
+
const remaining = () => scope?.remaining() ?? integer(Math.ceil(p.deadline - performance.now()));
|
|
589
|
+
const open = () => opened ??= (async () => {
|
|
590
|
+
scope = await intent.open(p.intent, d.bindingId, p.turn, p.deadline, p.signal);
|
|
591
|
+
const r = record(await call(d.bindingId, { method: "stream-open", recipeId: p.recipeId, turn: scope.turn }, remaining(), scope.signal), ["operationId"]);
|
|
592
|
+
return id(r.operationId);
|
|
593
|
+
})();
|
|
594
|
+
const advance = async (method2) => {
|
|
595
|
+
if (pending)
|
|
596
|
+
invalid();
|
|
597
|
+
if (finished)
|
|
598
|
+
return { done: true, value: void 0 };
|
|
599
|
+
pending = true;
|
|
600
|
+
try {
|
|
601
|
+
if (method2 !== "stream-next" && !opened) {
|
|
602
|
+
finished = true;
|
|
603
|
+
scope?.finish();
|
|
604
|
+
return { done: true, value: void 0 };
|
|
605
|
+
}
|
|
606
|
+
const operationId = await open(), r = record(await call(d.bindingId, { method: method2, operationId }, remaining(), scope?.signal), ["done", "value"], ["value"]);
|
|
607
|
+
if (typeof r.done !== "boolean")
|
|
608
|
+
invalid();
|
|
609
|
+
if (r.done) {
|
|
610
|
+
finished = true;
|
|
611
|
+
scope?.finish();
|
|
612
|
+
return { done: true, value: void 0 };
|
|
613
|
+
}
|
|
614
|
+
if (method2 !== "stream-next")
|
|
615
|
+
invalid();
|
|
616
|
+
return { done: false, value: item(r.value) };
|
|
617
|
+
} catch (cause) {
|
|
618
|
+
finished = true;
|
|
619
|
+
scope?.finish();
|
|
620
|
+
throw cause;
|
|
621
|
+
} finally {
|
|
622
|
+
pending = false;
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
const iterator = { [Symbol.asyncIterator]() {
|
|
626
|
+
return iterator;
|
|
627
|
+
}, next: () => advance("stream-next"), return: () => advance("stream-return"), throw: () => advance("stream-throw") };
|
|
628
|
+
return iterator;
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
return { adapter, validate: matcher.validate };
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// src/hosted/intent.ts
|
|
635
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
636
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
637
|
+
import { types as types3 } from "node:util";
|
|
638
|
+
var ambient = new AsyncLocalStorage();
|
|
639
|
+
var runtimes = /* @__PURE__ */ new WeakMap();
|
|
640
|
+
var fail = () => hostedHalt("HOSTED_INTENT_UNKNOWN");
|
|
641
|
+
var aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted").get;
|
|
642
|
+
function signal(input) {
|
|
643
|
+
if (input === void 0)
|
|
644
|
+
return void 0;
|
|
645
|
+
if (!input || typeof input !== "object" || types3.isProxy(input))
|
|
646
|
+
throw fail();
|
|
647
|
+
try {
|
|
648
|
+
aborted.call(input);
|
|
649
|
+
} catch {
|
|
650
|
+
throw fail();
|
|
651
|
+
}
|
|
652
|
+
return input;
|
|
653
|
+
}
|
|
654
|
+
function hostedTurnSemanticDigest(t) {
|
|
655
|
+
return hostedDigest({ mode: t.mode, cwd: t.cwd, prompt: t.prompt, sessionId: t.sessionId ?? null, instructions: t.instructions ?? null, outputSchema: t.outputSchema ?? null });
|
|
656
|
+
}
|
|
657
|
+
function createHostedIntentPort(rpc, close) {
|
|
658
|
+
const port = Object.freeze({}), guard = (state) => {
|
|
659
|
+
if (state && (state.port !== port || state.closed))
|
|
660
|
+
throw fail();
|
|
661
|
+
if (state?.controller.signal.aborted)
|
|
662
|
+
throw state.controller.signal.reason;
|
|
663
|
+
};
|
|
664
|
+
const call = (binding, body, remaining, original) => {
|
|
665
|
+
const state = ambient.getStore();
|
|
666
|
+
guard(state);
|
|
667
|
+
return rpc(binding, body, state?.deadline === void 0 ? remaining : Math.min(remaining, integer(Math.ceil(state.deadline - performance.now()))), state ? AbortSignal.any([state.controller.signal, ...original ? [original] : []]) : original);
|
|
668
|
+
};
|
|
669
|
+
return Object.freeze({
|
|
670
|
+
call,
|
|
671
|
+
bind(runtime) {
|
|
672
|
+
if (runtimes.has(runtime))
|
|
673
|
+
throw fail();
|
|
674
|
+
runtimes.set(runtime, port);
|
|
675
|
+
},
|
|
676
|
+
capture() {
|
|
677
|
+
const state = ambient.getStore();
|
|
678
|
+
guard(state);
|
|
679
|
+
return state;
|
|
680
|
+
},
|
|
681
|
+
async open(state, bindingId, turn, deadline, requestSignal) {
|
|
682
|
+
guard(state);
|
|
683
|
+
if (!state)
|
|
684
|
+
return { turn, signal: requestSignal, remaining: () => integer(Math.ceil(deadline - performance.now())), finish() {
|
|
685
|
+
} };
|
|
686
|
+
const digest2 = hostedTurnSemanticDigest(turn);
|
|
687
|
+
if (state.digest !== void 0 && state.digest !== digest2)
|
|
688
|
+
throw fail();
|
|
689
|
+
state.digest = digest2;
|
|
690
|
+
state.deadline ??= deadline;
|
|
691
|
+
const remaining = () => integer(Math.ceil(Math.min(state.deadline, deadline) - performance.now())), combined = AbortSignal.any([state.controller.signal, ...requestSignal ? [requestSignal] : []]);
|
|
692
|
+
if (combined.aborted)
|
|
693
|
+
throw combined.reason;
|
|
694
|
+
state.pending++;
|
|
695
|
+
let ended = false;
|
|
696
|
+
const finish = () => {
|
|
697
|
+
if (!ended) {
|
|
698
|
+
ended = true;
|
|
699
|
+
state.pending--;
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
try {
|
|
703
|
+
state.bindingId ??= bindingId;
|
|
704
|
+
state.opened ??= (async () => {
|
|
705
|
+
const reply = record(await rpc(bindingId, { method: "intent-begin", turnId: state.turnId, semanticDigest: digest2 }, remaining(), combined), ["intentId"]);
|
|
706
|
+
state.intentId = id(reply.intentId);
|
|
707
|
+
return state.intentId;
|
|
708
|
+
})();
|
|
709
|
+
const intentId = await state.opened;
|
|
710
|
+
guard(state);
|
|
711
|
+
if (combined.aborted)
|
|
712
|
+
throw combined.reason;
|
|
713
|
+
return { turn: { ...turn, intentId, ...state.priority === void 0 ? {} : { priority: state.priority } }, signal: combined, remaining, finish };
|
|
714
|
+
} catch (cause) {
|
|
715
|
+
finish();
|
|
716
|
+
throw cause;
|
|
717
|
+
}
|
|
718
|
+
},
|
|
719
|
+
async finish(state) {
|
|
720
|
+
if (state.pending) {
|
|
721
|
+
state.controller.abort(fail());
|
|
722
|
+
close();
|
|
723
|
+
throw fail();
|
|
724
|
+
}
|
|
725
|
+
if (state.opened) {
|
|
726
|
+
const intentId = await state.opened;
|
|
727
|
+
const reply = record(await rpc(state.bindingId, { method: "intent-finish", intentId }, Math.max(1, Math.ceil((state.deadline ?? performance.now() + 1e3) - performance.now()))), ["state"]);
|
|
728
|
+
if (!["settled", "closed"].includes(reply.state))
|
|
729
|
+
throw fail();
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
var ports = /* @__PURE__ */ new WeakMap();
|
|
735
|
+
var active = /* @__PURE__ */ new WeakMap();
|
|
736
|
+
function bindHostedIntentRuntime(runtime, port) {
|
|
737
|
+
port.bind(runtime);
|
|
738
|
+
ports.set(runtimes.get(runtime), port);
|
|
739
|
+
}
|
|
740
|
+
async function withHostedTurnIntent(runtime, options, work) {
|
|
741
|
+
const key = runtime && typeof runtime === "object" && !types3.isProxy(runtime) ? runtimes.get(runtime) : void 0, port = key ? ports.get(key) : void 0;
|
|
742
|
+
if (!port || ambient.getStore() || typeof work !== "function" || (active.get(key) ?? 0) >= 32)
|
|
743
|
+
throw fail();
|
|
744
|
+
const c = record(options, ["turnId", "signal", "priority"], ["turnId", "signal", "priority"]), outer = signal(c.signal), controller = new AbortController();
|
|
745
|
+
if (c.priority !== void 0 && c.priority !== "low")
|
|
746
|
+
throw fail();
|
|
747
|
+
const state = { port: key, turnId: c.turnId === void 0 ? randomUUID2() : id(c.turnId), controller, closed: false, pending: 0, ...c.priority === void 0 ? {} : { priority: "low" } };
|
|
748
|
+
const cancel = () => controller.abort(outer.reason);
|
|
749
|
+
if (outer?.aborted)
|
|
750
|
+
throw outer.reason;
|
|
751
|
+
if (outer)
|
|
752
|
+
EventTarget.prototype.addEventListener.call(outer, "abort", cancel, { once: true });
|
|
753
|
+
active.set(key, (active.get(key) ?? 0) + 1);
|
|
754
|
+
let value, cause, failed = false;
|
|
755
|
+
try {
|
|
756
|
+
try {
|
|
757
|
+
value = await ambient.run(state, work);
|
|
758
|
+
} catch (error) {
|
|
759
|
+
failed = true;
|
|
760
|
+
cause = error;
|
|
761
|
+
}
|
|
762
|
+
state.closed = true;
|
|
763
|
+
try {
|
|
764
|
+
await port.finish(state);
|
|
765
|
+
} catch (error) {
|
|
766
|
+
throw hostedHalt("HOSTED_INTENT_UNKNOWN", error);
|
|
767
|
+
}
|
|
768
|
+
if (failed)
|
|
769
|
+
throw cause;
|
|
770
|
+
return value;
|
|
771
|
+
} finally {
|
|
772
|
+
active.set(key, active.get(key) - 1);
|
|
773
|
+
state.closed = true;
|
|
774
|
+
controller.abort(fail());
|
|
775
|
+
if (outer)
|
|
776
|
+
EventTarget.prototype.removeEventListener.call(outer, "abort", cancel);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// src/hosted/runtime.ts
|
|
781
|
+
var captureScopes = /* @__PURE__ */ new WeakMap();
|
|
782
|
+
function createHostedRunRuntime(parent, capture) {
|
|
783
|
+
const create = captureScopes.get(parent);
|
|
784
|
+
if (!create) return invalid();
|
|
785
|
+
return create(capture);
|
|
786
|
+
}
|
|
787
|
+
function createHostedRuntime(input, options = {}) {
|
|
788
|
+
const captured = captureHostedContext(input), context = { ...captured.r, descriptors: captured.descriptors };
|
|
789
|
+
const intent = createHostedIntentPort(createHostedCaller(context), method(context.client, "close")), rpc = intent.call, deny = async () => invalid();
|
|
790
|
+
const factories = /* @__PURE__ */ new Map([["claude", createClaudeProvider], ["codex", createCodexProvider]]);
|
|
791
|
+
for (const value of options.providers ?? []) {
|
|
792
|
+
const f = record(value, ["id", "create"]);
|
|
793
|
+
if (typeof f.id !== "string" || typeof f.create !== "function" || factories.has(f.id))
|
|
794
|
+
invalid();
|
|
795
|
+
factories.set(f.id, f.create);
|
|
796
|
+
}
|
|
797
|
+
const providers = context.descriptors.map((d) => {
|
|
798
|
+
const factory = factories.get(d.provider);
|
|
799
|
+
if (!factory)
|
|
800
|
+
invalid();
|
|
801
|
+
const original = factory({ runner: deny, probeRunner: deny });
|
|
802
|
+
if (original.id !== d.provider || original.exec.token !== d.token || original.exec.adapterVersion !== d.adapterVersion)
|
|
803
|
+
invalid();
|
|
804
|
+
let adapter;
|
|
805
|
+
const proxy = createHostedAdapter(d, rpc, intent, context.dataDirectory);
|
|
806
|
+
adapter = proxy.adapter;
|
|
807
|
+
const registration = {
|
|
808
|
+
apiVersion: 1,
|
|
809
|
+
id: d.provider,
|
|
810
|
+
exec: { adapter, token: d.token, adapterVersion: d.adapterVersion, withTarget: (target) => {
|
|
811
|
+
if (!sameTarget(target, d))
|
|
812
|
+
invalid();
|
|
813
|
+
return adapter;
|
|
814
|
+
} },
|
|
815
|
+
modelCatalog: d.modelCatalog,
|
|
816
|
+
execCapabilities: d.execCapabilities,
|
|
817
|
+
resolveModel: (nativeId) => {
|
|
818
|
+
const model = d.modelCatalog.find((m) => m.id === nativeId);
|
|
819
|
+
if (!model)
|
|
820
|
+
throw new UnknownModelError(nativeId);
|
|
821
|
+
return structuredClone(model);
|
|
822
|
+
},
|
|
823
|
+
translateContext: (requested) => original.translateContext(requested),
|
|
824
|
+
translatePermissions: (requested, transport) => {
|
|
825
|
+
if (transport !== "exec")
|
|
826
|
+
throw new UnsupportedCapabilityError({ provider: d.provider, retryable: false });
|
|
827
|
+
return original.translatePermissions(requested, transport);
|
|
828
|
+
},
|
|
829
|
+
validateOptions: (agentOptions, transport) => {
|
|
830
|
+
if (transport !== "exec")
|
|
831
|
+
throw new UnsupportedCapabilityError({ provider: d.provider, retryable: false });
|
|
832
|
+
original.validateOptions(agentOptions, transport);
|
|
833
|
+
proxy.validate(agentOptions);
|
|
834
|
+
}
|
|
835
|
+
};
|
|
836
|
+
return registration;
|
|
837
|
+
});
|
|
838
|
+
const runtime = new Runtime({ providers });
|
|
839
|
+
bindHostedIntentRuntime(runtime, intent);
|
|
840
|
+
captureScopes.set(runtime, (capture) => {
|
|
841
|
+
if (capture.identity.systemId !== context.systemId || capture.identity.generation !== context.generation) return invalid();
|
|
842
|
+
const scoped = new Runtime({ providers, capture });
|
|
843
|
+
bindHostedIntentRuntime(scoped, intent);
|
|
844
|
+
return scoped;
|
|
845
|
+
});
|
|
846
|
+
return runtime;
|
|
847
|
+
}
|
|
848
|
+
export {
|
|
849
|
+
captureHostedDescriptor,
|
|
850
|
+
captureHostedReply,
|
|
851
|
+
captureHostedRequest,
|
|
852
|
+
createHostedRunRuntime,
|
|
853
|
+
createHostedRuntime,
|
|
854
|
+
createRecipeMatcher,
|
|
855
|
+
hostedDigest,
|
|
856
|
+
withHostedTurnIntent
|
|
857
|
+
};
|
|
858
|
+
//# sourceMappingURL=hosted-runtime.js.map
|