@withgateway/sdk 0.2.3 → 0.2.5
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/dist/cli.js +13267 -5869
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +13272 -5874
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.js +83 -31
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +79 -28
- package/dist/files/index.mjs.map +1 -1
- package/dist/hooks/index.d.mts +1 -0
- package/dist/hooks/index.d.ts +1 -0
- package/dist/hooks/index.js +4355 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/index.mjs +4243 -0
- package/dist/hooks/index.mjs.map +1 -0
- package/dist/{index-Dpo-t8iO.d.ts → index-1xnxt0Cc.d.ts} +58 -2
- package/dist/index-B0R3IgsV.d.mts +1279 -0
- package/dist/index-B0R3IgsV.d.ts +1279 -0
- package/dist/{index-B5HUQQDE.d.mts → index-C1wDEwH4.d.mts} +58 -2
- package/dist/index.d.mts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +6698 -1606
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6793 -1713
- package/dist/index.mjs.map +1 -1
- package/dist/traces/index.js +72 -20
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +68 -17
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.d.mts +1 -1
- package/dist/tracing/index.d.ts +1 -1
- package/dist/tracing/index.js +47 -3
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +42 -2
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +390 -27
- package/dist/worlds/index.d.ts +390 -27
- package/dist/worlds/index.js +2291 -366
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +2281 -356
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +7 -1
- package/runtime/gatewaysdk/environment/_bundle.py +14 -24
- package/runtime/gatewaysdk/environment/_materialize.py +3 -3
- package/runtime/gatewaysdk/environment/schema/api.py +153 -20
- package/runtime/gatewaysdk/environment/schema/compiler.py +14 -0
- package/runtime/gatewaysdk/environment/schema/data.py +21 -19
- package/runtime/gatewaysdk/environment/schema/grading.py +225 -0
- package/runtime/gatewaysdk/environment/schema/host.py +171 -535
- package/runtime/gatewaysdk/environment/schema/ingest.py +3 -11
- package/runtime/gatewaysdk/environment/schema/local.py +32 -126
- package/runtime/gatewaysdk/environment/schema/platform.py +14 -22
- package/runtime/gatewaysdk/environment/schema/proof.py +237 -0
- package/runtime/gatewaysdk/environment/schema/runtime.py +686 -0
- package/runtime/gatewaysdk/environment/schema/skill.py +1 -0
- package/runtime/gatewaysdk/environment/schema/skills/hooks-getting-started/SKILL.md +156 -0
- package/runtime/gatewaysdk/environment/schema/snapshot.py +6 -5
- package/runtime/gatewaysdk/environment/schema/tasks.py +12 -2
- package/runtime/gatewaysdk/environment/schema/tools_world.py +75 -23
- package/runtime/gatewaysdk/environment/schema/verbs.py +136 -0
- package/runtime/gatewaysdk/environment/schema/workers.py +44 -13
- package/runtime/gatewaysdk/environment/world.py +391 -0
- package/skills/hooks-getting-started/SKILL.md +156 -0
|
@@ -0,0 +1,4355 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key2 of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key2) && key2 !== except)
|
|
16
|
+
__defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/hooks/index.ts
|
|
31
|
+
var hooks_exports = {};
|
|
32
|
+
__export(hooks_exports, {
|
|
33
|
+
AliasHandler: () => AliasHandler,
|
|
34
|
+
AliasMap: () => AliasMap,
|
|
35
|
+
CONTEXT_KEY: () => CONTEXT_KEY,
|
|
36
|
+
CallableTool: () => CallableTool,
|
|
37
|
+
CommandHandler: () => CommandHandler,
|
|
38
|
+
ConnectorTool: () => ConnectorTool,
|
|
39
|
+
DenyHandler: () => DenyHandler,
|
|
40
|
+
EVENTS: () => EVENTS,
|
|
41
|
+
EVENT_ALIASES: () => EVENT_ALIASES,
|
|
42
|
+
FunctionHandler: () => FunctionHandler,
|
|
43
|
+
HANDLER_TYPES: () => HANDLER_TYPES,
|
|
44
|
+
HookConfigError: () => HookConfigError,
|
|
45
|
+
HookDenied: () => HookDenied,
|
|
46
|
+
HookError: () => HookError,
|
|
47
|
+
HookRun: () => HookRun,
|
|
48
|
+
HookedSession: () => HookedSession,
|
|
49
|
+
HttpHandler: () => HttpHandler,
|
|
50
|
+
HttpTool: () => HttpTool,
|
|
51
|
+
INBOUND_KINDS: () => INBOUND_KINDS,
|
|
52
|
+
INPUT_TYPES: () => INPUT_TYPES,
|
|
53
|
+
KINDS: () => KINDS,
|
|
54
|
+
LiveToolError: () => LiveToolError,
|
|
55
|
+
LiveTools: () => LiveTools,
|
|
56
|
+
PARSE_MODES: () => PARSE_MODES,
|
|
57
|
+
RecordHandler: () => RecordHandler,
|
|
58
|
+
Recorder: () => Recorder,
|
|
59
|
+
RedactHandler: () => RedactHandler,
|
|
60
|
+
Replay: () => Replay,
|
|
61
|
+
TOOL_KINDS: () => TOOL_KINDS,
|
|
62
|
+
applyLimit: () => applyLimit,
|
|
63
|
+
applyResult: () => applyResult,
|
|
64
|
+
buildTool: () => buildTool,
|
|
65
|
+
canonical: () => canonical,
|
|
66
|
+
definition: () => definition,
|
|
67
|
+
describeHandler: () => describeHandler,
|
|
68
|
+
describeMatcher: () => describeMatcher,
|
|
69
|
+
describeTool: () => describeTool,
|
|
70
|
+
emailPairs: () => emailPairs,
|
|
71
|
+
emptyConfig: () => emptyConfig,
|
|
72
|
+
emptyLive: () => emptyLive,
|
|
73
|
+
eventToJson: () => eventToJson,
|
|
74
|
+
explodeIp: () => explodeIp,
|
|
75
|
+
findKind: () => findKind,
|
|
76
|
+
folded: () => folded,
|
|
77
|
+
genericPairs: () => genericPairs,
|
|
78
|
+
importCallable: () => importCallable,
|
|
79
|
+
inputSchema: () => inputSchema,
|
|
80
|
+
interpolateHeaders: () => interpolateHeaders,
|
|
81
|
+
interpolatePath: () => interpolatePath,
|
|
82
|
+
isGlobalIpv4: () => isGlobalIpv4,
|
|
83
|
+
jsPattern: () => jsPattern,
|
|
84
|
+
jsonPath: () => jsonPath,
|
|
85
|
+
loadHookConfig: () => loadHookConfig,
|
|
86
|
+
mapFields: () => mapFields,
|
|
87
|
+
matches: () => matches,
|
|
88
|
+
mirrorHandle: () => mirrorHandle,
|
|
89
|
+
namePairs: () => namePairs,
|
|
90
|
+
newRunKey: () => newRunKey,
|
|
91
|
+
normalizeEvent: () => normalizeEvent,
|
|
92
|
+
pageTitle: () => pageTitle,
|
|
93
|
+
parseHookConfig: () => parseHookConfig,
|
|
94
|
+
parseJson: () => parseJson,
|
|
95
|
+
parseMatcher: () => parseMatcher,
|
|
96
|
+
parseRegex: () => parseRegex,
|
|
97
|
+
parseStdout: () => parseStdout,
|
|
98
|
+
parseText: () => parseText,
|
|
99
|
+
phonePairs: () => phonePairs,
|
|
100
|
+
pyQuote: () => pyQuote,
|
|
101
|
+
readConnection: () => readConnection,
|
|
102
|
+
readable: () => readable,
|
|
103
|
+
refusalReason: () => refusalReason,
|
|
104
|
+
render: () => render,
|
|
105
|
+
resultFromJson: () => resultFromJson,
|
|
106
|
+
splitTopLevel: () => splitTopLevel,
|
|
107
|
+
stripTags: () => stripTags,
|
|
108
|
+
unescapeHtml: () => unescapeHtml,
|
|
109
|
+
vendorOf: () => vendorOf,
|
|
110
|
+
withContext: () => withContext,
|
|
111
|
+
withDefaults: () => withDefaults
|
|
112
|
+
});
|
|
113
|
+
module.exports = __toCommonJS(hooks_exports);
|
|
114
|
+
|
|
115
|
+
// src/hooks/alias.ts
|
|
116
|
+
var import_node_crypto = require("crypto");
|
|
117
|
+
var GIVEN = [
|
|
118
|
+
"John",
|
|
119
|
+
"Mary",
|
|
120
|
+
"Peter",
|
|
121
|
+
"Susan",
|
|
122
|
+
"David",
|
|
123
|
+
"Karen",
|
|
124
|
+
"Paul",
|
|
125
|
+
"Linda",
|
|
126
|
+
"Mark",
|
|
127
|
+
"Nancy",
|
|
128
|
+
"Brian",
|
|
129
|
+
"Julia",
|
|
130
|
+
"Alan",
|
|
131
|
+
"Diane",
|
|
132
|
+
"Keith",
|
|
133
|
+
"Rachel",
|
|
134
|
+
"Neil",
|
|
135
|
+
"Paula",
|
|
136
|
+
"Grant",
|
|
137
|
+
"Tessa",
|
|
138
|
+
"Victor",
|
|
139
|
+
"Marta",
|
|
140
|
+
"Owen",
|
|
141
|
+
"Irene",
|
|
142
|
+
"Hugo",
|
|
143
|
+
"Clara",
|
|
144
|
+
"Felix",
|
|
145
|
+
"Nadia",
|
|
146
|
+
"Oscar",
|
|
147
|
+
"Rita",
|
|
148
|
+
"Simon",
|
|
149
|
+
"Wendy"
|
|
150
|
+
];
|
|
151
|
+
var SURNAME = [
|
|
152
|
+
"Doe",
|
|
153
|
+
"Marsh",
|
|
154
|
+
"Calder",
|
|
155
|
+
"Whitlock",
|
|
156
|
+
"Ferris",
|
|
157
|
+
"Rowe",
|
|
158
|
+
"Danforth",
|
|
159
|
+
"Kessler",
|
|
160
|
+
"Aldridge",
|
|
161
|
+
"Vance",
|
|
162
|
+
"Norling",
|
|
163
|
+
"Pruitt",
|
|
164
|
+
"Thorne",
|
|
165
|
+
"Gallagher",
|
|
166
|
+
"Sandoval",
|
|
167
|
+
"Ibarra",
|
|
168
|
+
"Kowalski",
|
|
169
|
+
"Meunier",
|
|
170
|
+
"Okafor",
|
|
171
|
+
"Renard",
|
|
172
|
+
"Sato",
|
|
173
|
+
"Ustinov",
|
|
174
|
+
"Varela",
|
|
175
|
+
"Wexler",
|
|
176
|
+
"Yarrow",
|
|
177
|
+
"Zeller",
|
|
178
|
+
"Brannon",
|
|
179
|
+
"Caldwell",
|
|
180
|
+
"Duquette",
|
|
181
|
+
"Everitt",
|
|
182
|
+
"Fontaine",
|
|
183
|
+
"Gresham"
|
|
184
|
+
];
|
|
185
|
+
var COMPANY_HEAD = [
|
|
186
|
+
"Meridian",
|
|
187
|
+
"Larkspur",
|
|
188
|
+
"Northgate",
|
|
189
|
+
"Kestrel",
|
|
190
|
+
"Bramble",
|
|
191
|
+
"Ashgrove",
|
|
192
|
+
"Foxglove",
|
|
193
|
+
"Harrow",
|
|
194
|
+
"Juniper",
|
|
195
|
+
"Marlowe",
|
|
196
|
+
"Pinehurst",
|
|
197
|
+
"Quarry",
|
|
198
|
+
"Redstone",
|
|
199
|
+
"Saltmarsh",
|
|
200
|
+
"Tidewater",
|
|
201
|
+
"Windlass"
|
|
202
|
+
];
|
|
203
|
+
var COMPANY_TAIL = [
|
|
204
|
+
"Consulting Ltd",
|
|
205
|
+
"Holdings SA",
|
|
206
|
+
"Trading Co",
|
|
207
|
+
"Partners LLP",
|
|
208
|
+
"Ventures BV",
|
|
209
|
+
"Logistics GmbH",
|
|
210
|
+
"Advisory Pte",
|
|
211
|
+
"Capital Inc"
|
|
212
|
+
];
|
|
213
|
+
var PUBLIC_MAILBOX_DOMAINS = /* @__PURE__ */ new Set([
|
|
214
|
+
"gmail.com",
|
|
215
|
+
"googlemail.com",
|
|
216
|
+
"hotmail.com",
|
|
217
|
+
"outlook.com",
|
|
218
|
+
"live.com",
|
|
219
|
+
"msn.com",
|
|
220
|
+
"yahoo.com",
|
|
221
|
+
"yahoo.co.uk",
|
|
222
|
+
"ymail.com",
|
|
223
|
+
"aol.com",
|
|
224
|
+
"icloud.com",
|
|
225
|
+
"me.com",
|
|
226
|
+
"protonmail.com",
|
|
227
|
+
"protonmail.ch",
|
|
228
|
+
"proton.me",
|
|
229
|
+
"gmx.com",
|
|
230
|
+
"gmx.de",
|
|
231
|
+
"mail.ru",
|
|
232
|
+
"yandex.ru",
|
|
233
|
+
"qq.com",
|
|
234
|
+
"163.com",
|
|
235
|
+
"126.com",
|
|
236
|
+
"sina.com",
|
|
237
|
+
"foxmail.com",
|
|
238
|
+
"sbcglobal.net",
|
|
239
|
+
"comcast.net",
|
|
240
|
+
"verizon.net",
|
|
241
|
+
"att.net",
|
|
242
|
+
"bellsouth.net",
|
|
243
|
+
"web.de",
|
|
244
|
+
"free.fr",
|
|
245
|
+
"orange.fr",
|
|
246
|
+
"libero.it",
|
|
247
|
+
"tom.com",
|
|
248
|
+
"xmpp.jp"
|
|
249
|
+
]);
|
|
250
|
+
var KINDS = [
|
|
251
|
+
"person_name",
|
|
252
|
+
"email",
|
|
253
|
+
"username",
|
|
254
|
+
"phone",
|
|
255
|
+
"company",
|
|
256
|
+
"domain",
|
|
257
|
+
"ip",
|
|
258
|
+
"account",
|
|
259
|
+
"machine",
|
|
260
|
+
"log"
|
|
261
|
+
];
|
|
262
|
+
var SHA256_ANY_GLOBAL = /\bsha256:([0-9a-f]{64})\b/gi;
|
|
263
|
+
var SHA256_ANY = /\bsha256:([0-9a-f]{64})\b/i;
|
|
264
|
+
var INBOUND_KINDS = ["email", "phone", "ip"];
|
|
265
|
+
var KIND_PATTERNS = {
|
|
266
|
+
email: /(?<![\w.+-])[\w.+-]+@[\w-]+(?:\.[\w-]+)+(?![\w-])/g,
|
|
267
|
+
// A leading + or an area code in parentheses: a bare run of digits is a date, an
|
|
268
|
+
// id or a row count far more often than a phone number.
|
|
269
|
+
phone: /(?<![\w+(])(?:\+\d[\d\s().-]{7,}\d|\(\d{3}\)\s?\d{3}[-.\s]?\d{4})(?!\w)/g,
|
|
270
|
+
ip: /(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?![\w.])/g
|
|
271
|
+
};
|
|
272
|
+
function isGlobalIpv4(text) {
|
|
273
|
+
const quad = explodeIp(text);
|
|
274
|
+
if (!quad || quad.includes(":")) return false;
|
|
275
|
+
const [a, b, c] = quad.split(".").map(Number);
|
|
276
|
+
if (a === 0 || a === 10 || a === 127 || a >= 224) return false;
|
|
277
|
+
if (a === 100 && b >= 64 && b <= 127) return false;
|
|
278
|
+
if (a === 169 && b === 254) return false;
|
|
279
|
+
if (a === 172 && b >= 16 && b <= 31) return false;
|
|
280
|
+
if (a === 192 && b === 168) return false;
|
|
281
|
+
if (a === 192 && b === 0 && (c === 0 || c === 2)) return false;
|
|
282
|
+
if (a === 198 && (b === 18 || b === 19)) return false;
|
|
283
|
+
if (a === 198 && b === 51 && c === 100) return false;
|
|
284
|
+
if (a === 203 && b === 0 && c === 113) return false;
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
function findKind(kind, text) {
|
|
288
|
+
const pattern = KIND_PATTERNS[kind];
|
|
289
|
+
if (!pattern) return [];
|
|
290
|
+
const seen = /* @__PURE__ */ new Set();
|
|
291
|
+
const out = [];
|
|
292
|
+
for (const match of text.matchAll(pattern)) {
|
|
293
|
+
const value = match[0];
|
|
294
|
+
if (kind === "phone") {
|
|
295
|
+
const digits = value.replace(/\D/g, "").length;
|
|
296
|
+
if (digits < 10 || digits > 15) continue;
|
|
297
|
+
}
|
|
298
|
+
if (kind === "ip" && !isGlobalIpv4(value)) continue;
|
|
299
|
+
if (!seen.has(value)) {
|
|
300
|
+
seen.add(value);
|
|
301
|
+
out.push(value);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return out;
|
|
305
|
+
}
|
|
306
|
+
function newRunKey() {
|
|
307
|
+
return (0, import_node_crypto.randomBytes)(32).toString("hex");
|
|
308
|
+
}
|
|
309
|
+
function canonical(kind, value) {
|
|
310
|
+
const text = String(value).normalize("NFKC").trim();
|
|
311
|
+
if (["email", "username", "domain", "person_name", "company"].includes(kind))
|
|
312
|
+
return text.toLowerCase();
|
|
313
|
+
if (kind === "phone") return text.replace(/\D/g, "");
|
|
314
|
+
if (kind === "ip") return explodeIp(text) ?? text;
|
|
315
|
+
return text;
|
|
316
|
+
}
|
|
317
|
+
function explodeIp(text) {
|
|
318
|
+
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(text)) {
|
|
319
|
+
return text.split(".").every((o) => Number(o) <= 255 && String(Number(o)) === o) ? text : null;
|
|
320
|
+
}
|
|
321
|
+
if (!text.includes(":")) return null;
|
|
322
|
+
let body = text;
|
|
323
|
+
let zone = "";
|
|
324
|
+
const percent = body.indexOf("%");
|
|
325
|
+
if (percent !== -1) {
|
|
326
|
+
zone = body.slice(percent);
|
|
327
|
+
body = body.slice(0, percent);
|
|
328
|
+
}
|
|
329
|
+
const halves = body.split("::");
|
|
330
|
+
if (halves.length > 2) return null;
|
|
331
|
+
const expand = (part) => {
|
|
332
|
+
if (!part) return [];
|
|
333
|
+
const groups2 = part.split(":");
|
|
334
|
+
const out = [];
|
|
335
|
+
for (const [index2, group] of groups2.entries()) {
|
|
336
|
+
if (index2 === groups2.length - 1 && group.includes(".")) {
|
|
337
|
+
const quad = explodeIp(group);
|
|
338
|
+
if (!quad) return null;
|
|
339
|
+
const bytes = quad.split(".").map(Number);
|
|
340
|
+
out.push(
|
|
341
|
+
(bytes[0] << 8 | bytes[1]).toString(16),
|
|
342
|
+
(bytes[2] << 8 | bytes[3]).toString(16)
|
|
343
|
+
);
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return null;
|
|
347
|
+
out.push(group.toLowerCase());
|
|
348
|
+
}
|
|
349
|
+
return out;
|
|
350
|
+
};
|
|
351
|
+
const head = expand(halves[0]);
|
|
352
|
+
const tail = halves.length === 2 ? expand(halves[1]) : [];
|
|
353
|
+
if (!head || !tail) return null;
|
|
354
|
+
const missing = 8 - head.length - tail.length;
|
|
355
|
+
if (halves.length === 2 ? missing < 1 : missing !== 0) return null;
|
|
356
|
+
const groups = [
|
|
357
|
+
...head,
|
|
358
|
+
...Array(halves.length === 2 ? missing : 0).fill("0"),
|
|
359
|
+
...tail
|
|
360
|
+
];
|
|
361
|
+
return groups.map((g) => g.padStart(4, "0")).join(":") + zone;
|
|
362
|
+
}
|
|
363
|
+
function index(runKey, kind, value, salt = "") {
|
|
364
|
+
const digest = (0, import_node_crypto.createHmac)("sha256", Buffer.from(runKey, "hex")).update(`${kind}:${value}:${salt}`, "utf8").digest();
|
|
365
|
+
return digest.readBigUInt64BE(0);
|
|
366
|
+
}
|
|
367
|
+
var pick = (pool, n) => pool[Number(n % BigInt(pool.length))];
|
|
368
|
+
var words = (text) => text.split(" ").filter(Boolean);
|
|
369
|
+
function nameParts(name) {
|
|
370
|
+
const text = name.trim().replace(/\s+/g, " ");
|
|
371
|
+
if (text.includes(",")) {
|
|
372
|
+
const comma = text.indexOf(",");
|
|
373
|
+
const surname = text.slice(0, comma);
|
|
374
|
+
const bits2 = words(text.slice(comma + 1));
|
|
375
|
+
return [bits2[0] ?? "", bits2.slice(1).join(" "), surname.trim()];
|
|
376
|
+
}
|
|
377
|
+
const bits = words(text);
|
|
378
|
+
if (bits.length === 1) return [bits[0], "", ""];
|
|
379
|
+
return [
|
|
380
|
+
bits[0] ?? "",
|
|
381
|
+
bits.slice(1, -1).join(" "),
|
|
382
|
+
bits[bits.length - 1] ?? ""
|
|
383
|
+
];
|
|
384
|
+
}
|
|
385
|
+
function format(template, parts2) {
|
|
386
|
+
return template.replace(/\{(\w+)\}/g, (_, key2) => parts2[key2] ?? "").trim();
|
|
387
|
+
}
|
|
388
|
+
var pair = (real, fake, template) => [
|
|
389
|
+
format(template, real),
|
|
390
|
+
format(template, fake)
|
|
391
|
+
];
|
|
392
|
+
function parts(name) {
|
|
393
|
+
const [given, middle, surname] = nameParts(name);
|
|
394
|
+
return {
|
|
395
|
+
given,
|
|
396
|
+
middle,
|
|
397
|
+
surname,
|
|
398
|
+
gi: given ? given[0] : "",
|
|
399
|
+
mi: middle ? middle[0] : "",
|
|
400
|
+
si: surname ? surname[0] : "",
|
|
401
|
+
g: given.toLowerCase(),
|
|
402
|
+
s: surname.toLowerCase(),
|
|
403
|
+
G: given.toUpperCase(),
|
|
404
|
+
S: surname.toUpperCase()
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
var NAME_FORMS = [
|
|
408
|
+
"{given} {middle} {surname}",
|
|
409
|
+
"{given} {mi}. {surname}",
|
|
410
|
+
"{given} {surname}",
|
|
411
|
+
"{surname}, {given}",
|
|
412
|
+
"{surname} {given}",
|
|
413
|
+
"{gi}. {surname}",
|
|
414
|
+
"{gi}.{surname}",
|
|
415
|
+
"{gi} {surname}",
|
|
416
|
+
"{surname}'s",
|
|
417
|
+
"{given}'s",
|
|
418
|
+
"{surname}",
|
|
419
|
+
"{given}",
|
|
420
|
+
"{g}{s}",
|
|
421
|
+
"{g}.{s}",
|
|
422
|
+
"{g}_{s}",
|
|
423
|
+
"{g}-{s}",
|
|
424
|
+
"{s}{g}",
|
|
425
|
+
// Capitalised joined forms: a wiki path (`/wiki/Do_Kwon`), a hyphenated slug in a
|
|
426
|
+
// headline URL, a dotted handle. Without them a short given name that is rightly
|
|
427
|
+
// never replaced bare (`Do`) leaves `Do_Gresham` beside `David Gresham`.
|
|
428
|
+
"{given}_{surname}",
|
|
429
|
+
"{given}-{surname}",
|
|
430
|
+
"{given}.{surname}",
|
|
431
|
+
"{given}{surname}",
|
|
432
|
+
// Bare lower- and upper-case spellings: a profile slug (`/in/nowell`), a handle
|
|
433
|
+
// fragment (`@nowell`) or a shouted heading (`NOWELL LTD`) is the commonest leak
|
|
434
|
+
// after the bare surname itself.
|
|
435
|
+
"{g} {s}",
|
|
436
|
+
"{G} {S}",
|
|
437
|
+
"{s}",
|
|
438
|
+
"{g}",
|
|
439
|
+
"{S}",
|
|
440
|
+
"{G}"
|
|
441
|
+
];
|
|
442
|
+
function namePairs(real, fake) {
|
|
443
|
+
const realParts = parts(real);
|
|
444
|
+
const fakeParts = parts(fake);
|
|
445
|
+
const out = [[real, fake]];
|
|
446
|
+
if (realParts.given && realParts.surname) {
|
|
447
|
+
for (const template of NAME_FORMS) {
|
|
448
|
+
const p = pair(realParts, fakeParts, template);
|
|
449
|
+
if (p[0].length > 2 && !p[0].includes("{")) out.push(p);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return dedupe(out);
|
|
453
|
+
}
|
|
454
|
+
var EMAIL_FORMS = [
|
|
455
|
+
"{local}@{domain}",
|
|
456
|
+
"{LOCAL}@{DOMAIN}",
|
|
457
|
+
"{local} (at) {domain}",
|
|
458
|
+
"{local}(at){domain}",
|
|
459
|
+
"{local} [at] {domain}",
|
|
460
|
+
"{local}[at]{domain}",
|
|
461
|
+
"{local} at {domain}",
|
|
462
|
+
"{local}%40{domain}",
|
|
463
|
+
"{local}"
|
|
464
|
+
];
|
|
465
|
+
function splitEmail(email) {
|
|
466
|
+
const at = email.indexOf("@");
|
|
467
|
+
return at === -1 ? [email, ""] : [email.slice(0, at), email.slice(at + 1)];
|
|
468
|
+
}
|
|
469
|
+
function emailPairs(real, fake) {
|
|
470
|
+
const [realLocal, realDomain] = splitEmail(real);
|
|
471
|
+
const [fakeLocal, fakeDomain] = splitEmail(fake);
|
|
472
|
+
const realParts = {
|
|
473
|
+
local: realLocal,
|
|
474
|
+
domain: realDomain,
|
|
475
|
+
LOCAL: realLocal.toUpperCase(),
|
|
476
|
+
DOMAIN: realDomain.toUpperCase()
|
|
477
|
+
};
|
|
478
|
+
const fakeParts = {
|
|
479
|
+
local: fakeLocal,
|
|
480
|
+
domain: fakeDomain,
|
|
481
|
+
LOCAL: fakeLocal.toUpperCase(),
|
|
482
|
+
DOMAIN: fakeDomain.toUpperCase()
|
|
483
|
+
};
|
|
484
|
+
const out = [[real, fake]];
|
|
485
|
+
for (const template of EMAIL_FORMS) {
|
|
486
|
+
const p = pair(realParts, fakeParts, template);
|
|
487
|
+
if (p[0].length > 2) out.push(p);
|
|
488
|
+
}
|
|
489
|
+
return dedupe(out);
|
|
490
|
+
}
|
|
491
|
+
function phoneForms(number) {
|
|
492
|
+
const digits = number.replace(/\D/g, "");
|
|
493
|
+
const forms = [
|
|
494
|
+
["raw", number],
|
|
495
|
+
["digits", digits],
|
|
496
|
+
["plus", `+${digits}`]
|
|
497
|
+
];
|
|
498
|
+
if (digits.length >= 10) {
|
|
499
|
+
const a = digits.slice(-10, -7);
|
|
500
|
+
const b = digits.slice(-7, -4);
|
|
501
|
+
const c = digits.slice(-4);
|
|
502
|
+
const country = digits.slice(0, -10);
|
|
503
|
+
const prefix = country ? `+${country} ` : "";
|
|
504
|
+
forms.push(
|
|
505
|
+
["spaced", `${prefix}${a} ${b} ${c}`],
|
|
506
|
+
["dashed", `${prefix}${a}-${b}-${c}`],
|
|
507
|
+
["paren", `${prefix}(${a}) ${b}-${c}`],
|
|
508
|
+
["dotted", `${prefix}${a}.${b}.${c}`],
|
|
509
|
+
["local_spaced", `${a} ${b} ${c}`],
|
|
510
|
+
["local_dashed", `${a}-${b}-${c}`],
|
|
511
|
+
["local_paren", `(${a}) ${b}-${c}`]
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
return forms;
|
|
515
|
+
}
|
|
516
|
+
function phonePairs(real, fake) {
|
|
517
|
+
const fakeForms = new Map(phoneForms(fake));
|
|
518
|
+
const out = [];
|
|
519
|
+
for (const [key2, value] of phoneForms(real)) {
|
|
520
|
+
const other = fakeForms.get(key2);
|
|
521
|
+
if (other !== void 0 && value.length >= 7) out.push([value, other]);
|
|
522
|
+
}
|
|
523
|
+
return dedupe(out);
|
|
524
|
+
}
|
|
525
|
+
function pyQuote(value) {
|
|
526
|
+
return encodeURIComponent(value).replace(
|
|
527
|
+
/[!'()*]/g,
|
|
528
|
+
(c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
var GENERIC_FORMS = [
|
|
532
|
+
(v) => v,
|
|
533
|
+
(v) => v.toLowerCase(),
|
|
534
|
+
(v) => v.toUpperCase(),
|
|
535
|
+
(v) => pyQuote(v),
|
|
536
|
+
(v) => v.split("_").join("-"),
|
|
537
|
+
(v) => v.split("-").join("_"),
|
|
538
|
+
(v) => v.split("_").join(""),
|
|
539
|
+
(v) => v.split("-").join("")
|
|
540
|
+
];
|
|
541
|
+
function genericPairs(real, fake) {
|
|
542
|
+
const out = [];
|
|
543
|
+
for (const form of GENERIC_FORMS) {
|
|
544
|
+
const left = form(real);
|
|
545
|
+
if (left.length > 2) out.push([left, form(fake)]);
|
|
546
|
+
}
|
|
547
|
+
return dedupe(out);
|
|
548
|
+
}
|
|
549
|
+
function dedupe(pairs) {
|
|
550
|
+
const seen = /* @__PURE__ */ new Set();
|
|
551
|
+
const out = [];
|
|
552
|
+
for (const [left, right] of pairs) {
|
|
553
|
+
if (left && right && !seen.has(left)) {
|
|
554
|
+
seen.add(left);
|
|
555
|
+
out.push([left, right]);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
return out.sort((a, b) => b[0].length - a[0].length);
|
|
559
|
+
}
|
|
560
|
+
var fullName = (identity) => `${identity.given} ${identity.surname}`;
|
|
561
|
+
var AliasMap = class _AliasMap {
|
|
562
|
+
constructor(runKey, slugs = [], options = {}) {
|
|
563
|
+
this.runKey = runKey;
|
|
564
|
+
this.slugs = slugs;
|
|
565
|
+
if (!/^[0-9a-f]{64}$/i.test(runKey))
|
|
566
|
+
throw new Error("run key must be 32 bytes as hex (newRunKey())");
|
|
567
|
+
this.publicLayerWins = options.publicLayerWins ?? true;
|
|
568
|
+
this.publicMailboxDomains = options.publicMailboxDomains ?? null;
|
|
569
|
+
this.mintInbound = options.mintInbound ?? [];
|
|
570
|
+
}
|
|
571
|
+
aliases = /* @__PURE__ */ new Map();
|
|
572
|
+
identities = /* @__PURE__ */ new Map();
|
|
573
|
+
taken = /* @__PURE__ */ new Set();
|
|
574
|
+
/** Digests that are ALREADY an alias's stand-in: never re-mint over one. */
|
|
575
|
+
aliasDigests = /* @__PURE__ */ new Set();
|
|
576
|
+
leaksIn = [];
|
|
577
|
+
leaksOut = [];
|
|
578
|
+
unresolvedOut = [];
|
|
579
|
+
/** Every value minted on sight: `{where, kind, alias}`. */
|
|
580
|
+
found = [];
|
|
581
|
+
/** Every value a `redact` handler removed: `{where, kind}`. */
|
|
582
|
+
redactions = [];
|
|
583
|
+
// Every persona's own spelling, so a pattern that finds a stand-in in text it
|
|
584
|
+
// already rewrote never mints (or redacts) over it.
|
|
585
|
+
displays = /* @__PURE__ */ new Set();
|
|
586
|
+
pairsCache = null;
|
|
587
|
+
/** A value seeded `role: "public"` is never rewritten, even where a private
|
|
588
|
+
* entity's derived variants reach it (the domain of a private email that is a
|
|
589
|
+
* state company's). Off, the private entity's variants apply as derived. */
|
|
590
|
+
publicLayerWins;
|
|
591
|
+
/** Mail domains kept real inside an email persona ("a gmail address" stays a
|
|
592
|
+
* fact without naming anyone). `null` is the built-in free-mail list; `[]`
|
|
593
|
+
* keeps none real; any other list replaces the built-in one. */
|
|
594
|
+
publicMailboxDomains;
|
|
595
|
+
/** Kinds (of `INBOUND_KINDS`) minted ON SIGHT: a value of one of them that arrives
|
|
596
|
+
* in a tool result or a page and was never seeded gets a persona there and then, so
|
|
597
|
+
* a third party found on the web is aliased in and resolved out like a seeded
|
|
598
|
+
* subject. Off (the default) such a value reaches the agent as it is — the seed
|
|
599
|
+
* list is the whole map. */
|
|
600
|
+
mintInbound;
|
|
601
|
+
mailboxDomains() {
|
|
602
|
+
if (this.publicMailboxDomains === null) return PUBLIC_MAILBOX_DOMAINS;
|
|
603
|
+
return new Set(this.publicMailboxDomains.map((d) => d.toLowerCase()));
|
|
604
|
+
}
|
|
605
|
+
isPublic(kind, value) {
|
|
606
|
+
const alias = this.aliases.get(_AliasMap.key(kind, canonical(kind, value)));
|
|
607
|
+
return alias !== void 0 && alias.role === "public";
|
|
608
|
+
}
|
|
609
|
+
static key(kind, canonicalValue) {
|
|
610
|
+
return `${kind}\0${canonicalValue}`;
|
|
611
|
+
}
|
|
612
|
+
// ------------------------------------------------------------ identities
|
|
613
|
+
identityFor(key2) {
|
|
614
|
+
const existing = this.identities.get(key2);
|
|
615
|
+
if (existing) return existing;
|
|
616
|
+
let n = 0n;
|
|
617
|
+
let given = GIVEN[0];
|
|
618
|
+
let surname = SURNAME[0];
|
|
619
|
+
let found = false;
|
|
620
|
+
for (let attempt = 0; attempt < 64 && !found; attempt++) {
|
|
621
|
+
n = index(this.runKey, "identity", key2, String(attempt));
|
|
622
|
+
given = pick(GIVEN, n);
|
|
623
|
+
surname = pick(SURNAME, n / BigInt(GIVEN.length));
|
|
624
|
+
found = !this.taken.has(`${given} ${surname}`);
|
|
625
|
+
}
|
|
626
|
+
if (!found) [given, surname] = [GIVEN[0], SURNAME[0]];
|
|
627
|
+
this.taken.add(`${given} ${surname}`);
|
|
628
|
+
const head = pick(COMPANY_HEAD, n);
|
|
629
|
+
const tail = pick(COMPANY_TAIL, n / BigInt(COMPANY_HEAD.length));
|
|
630
|
+
const identity = {
|
|
631
|
+
key: key2,
|
|
632
|
+
given,
|
|
633
|
+
surname,
|
|
634
|
+
company: `${head} ${tail}`,
|
|
635
|
+
domain: `${head.toLowerCase()}-${surname.toLowerCase()}.alias`
|
|
636
|
+
};
|
|
637
|
+
this.identities.set(key2, identity);
|
|
638
|
+
this.pairsCache = null;
|
|
639
|
+
return identity;
|
|
640
|
+
}
|
|
641
|
+
// ------------------------------------------------------------ minting
|
|
642
|
+
/** The alias for one value. `identityKey` ties an attribute to its person, so
|
|
643
|
+
* every attribute of one identity stays consistent (the relationship rule). */
|
|
644
|
+
mint(kind, value, opts = {}) {
|
|
645
|
+
const canon = canonical(kind, value);
|
|
646
|
+
const key2 = _AliasMap.key(kind, canon);
|
|
647
|
+
const existing = this.aliases.get(key2);
|
|
648
|
+
if (existing) return existing;
|
|
649
|
+
const real = String(value);
|
|
650
|
+
const role = opts.role ?? "private";
|
|
651
|
+
const provenance = opts.provenance ?? "seed";
|
|
652
|
+
if (role === "public") {
|
|
653
|
+
const alias2 = {
|
|
654
|
+
kind,
|
|
655
|
+
canonical: canon,
|
|
656
|
+
real,
|
|
657
|
+
display: real,
|
|
658
|
+
identity: null,
|
|
659
|
+
role,
|
|
660
|
+
variants: [],
|
|
661
|
+
provenance,
|
|
662
|
+
hitsIn: 0,
|
|
663
|
+
hitsOut: 0
|
|
664
|
+
};
|
|
665
|
+
this.aliases.set(key2, alias2);
|
|
666
|
+
this.displays.add(key2);
|
|
667
|
+
return alias2;
|
|
668
|
+
}
|
|
669
|
+
const identityKey = opts.identityKey ?? `${kind}:${canon}`;
|
|
670
|
+
const identity = this.identityFor(identityKey);
|
|
671
|
+
const [display, variants] = this.derive(kind, real, identity);
|
|
672
|
+
const alias = {
|
|
673
|
+
kind,
|
|
674
|
+
canonical: canon,
|
|
675
|
+
real,
|
|
676
|
+
display,
|
|
677
|
+
identity: identityKey,
|
|
678
|
+
role: "private",
|
|
679
|
+
variants,
|
|
680
|
+
provenance,
|
|
681
|
+
hitsIn: 0,
|
|
682
|
+
hitsOut: 0
|
|
683
|
+
};
|
|
684
|
+
this.aliases.set(key2, alias);
|
|
685
|
+
this.displays.add(_AliasMap.key(kind, canonical(kind, display)));
|
|
686
|
+
this.pairsCache = null;
|
|
687
|
+
return alias;
|
|
688
|
+
}
|
|
689
|
+
/** A value of an inbound kind met in a result and never seeded: minted there and
|
|
690
|
+
* then (`provenance: "found"`), its variants spliced into the live pair lists so
|
|
691
|
+
* the rest of this walk and every later call see it, and recorded in `found`. The
|
|
692
|
+
* spelling the text carried is a variant too — a mixed-case address that canonical
|
|
693
|
+
* form alone would miss. */
|
|
694
|
+
mintFound(kind, value, where) {
|
|
695
|
+
const alias = this.mint(kind, value, { provenance: "found" });
|
|
696
|
+
if (!alias.variants.some(([real]) => real === value))
|
|
697
|
+
alias.variants = dedupe([[value, alias.display], ...alias.variants]);
|
|
698
|
+
this.found.push({ where, kind, alias: alias.display });
|
|
699
|
+
const pub = this.publicFolded();
|
|
700
|
+
alias.variants = alias.variants.filter(([real]) => !pub.has(folded(real)));
|
|
701
|
+
if (this.pairsCache !== null) {
|
|
702
|
+
for (const [real, fake] of alias.variants) {
|
|
703
|
+
insertByLength(this.pairsCache[0], [real, fake, alias]);
|
|
704
|
+
insertByLength(this.pairsCache[1], [fake, real, alias]);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
return alias;
|
|
708
|
+
}
|
|
709
|
+
known(kind, value) {
|
|
710
|
+
const key2 = _AliasMap.key(kind, canonical(kind, value));
|
|
711
|
+
return this.aliases.has(key2) || this.displays.has(key2);
|
|
712
|
+
}
|
|
713
|
+
/** `mint_inbound` over a whole tree BEFORE it is rewritten: every unseeded value of
|
|
714
|
+
* a listed kind, in any string of it, gets its persona now. `walk` does this first so
|
|
715
|
+
* a spelling that sits in an earlier field than the one that reveals the value (a
|
|
716
|
+
* profile URL carrying the address percent-encoded, above the snippet that spells it
|
|
717
|
+
* out) is rewritten too — string order in a page is not the order the door learns
|
|
718
|
+
* things in. Returns how many were minted. */
|
|
719
|
+
discover(node, where = "tool_result") {
|
|
720
|
+
if (!this.mintInbound.length) return 0;
|
|
721
|
+
const before = this.found.length;
|
|
722
|
+
const go = (value) => {
|
|
723
|
+
if (typeof value === "string") {
|
|
724
|
+
for (const kind of this.mintInbound)
|
|
725
|
+
for (const found of findKind(kind, value))
|
|
726
|
+
if (!this.known(kind, found)) this.mintFound(kind, found, where);
|
|
727
|
+
} else if (Array.isArray(value)) value.forEach(go);
|
|
728
|
+
else if (value && typeof value === "object")
|
|
729
|
+
Object.values(value).forEach(go);
|
|
730
|
+
};
|
|
731
|
+
go(node);
|
|
732
|
+
return this.found.length - before;
|
|
733
|
+
}
|
|
734
|
+
/** `mint_inbound` on one string: every unseeded value of a listed kind in `text`
|
|
735
|
+
* gets a persona and is rewritten here, before the leak meter looks. */
|
|
736
|
+
mintFoundIn(text, where) {
|
|
737
|
+
let out = text;
|
|
738
|
+
for (const kind of this.mintInbound) {
|
|
739
|
+
for (const value of findKind(kind, out)) {
|
|
740
|
+
if (this.known(kind, value)) continue;
|
|
741
|
+
const alias = this.mintFound(kind, value, where);
|
|
742
|
+
for (const [real, fake] of alias.variants) {
|
|
743
|
+
if (real && out.includes(real)) {
|
|
744
|
+
out = out.split(real).join(fake);
|
|
745
|
+
alias.hitsIn += 1;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
return out;
|
|
751
|
+
}
|
|
752
|
+
/** A `redact` handler: every value of the listed kinds, and every match of the
|
|
753
|
+
* listed patterns, becomes `token` — removed, not aliased. A persona's own spelling
|
|
754
|
+
* is left alone, so redaction after the door keeps the door's work. */
|
|
755
|
+
redactText(text, opts = {}) {
|
|
756
|
+
if (typeof text !== "string" || !text) return text;
|
|
757
|
+
const token = opts.token ?? "[redacted {kind}]";
|
|
758
|
+
const where = opts.where ?? "tool_result";
|
|
759
|
+
let out = text;
|
|
760
|
+
for (const value of opts.values ?? []) {
|
|
761
|
+
if (!value.trim()) continue;
|
|
762
|
+
const pattern = new RegExp(
|
|
763
|
+
value.split(/\s+/).map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\s+"),
|
|
764
|
+
"gi"
|
|
765
|
+
);
|
|
766
|
+
const count = [...out.matchAll(pattern)].length;
|
|
767
|
+
out = out.replace(pattern, token.split("{kind}").join("value"));
|
|
768
|
+
for (let i = 0; i < count; i += 1)
|
|
769
|
+
this.redactions.push({
|
|
770
|
+
where,
|
|
771
|
+
kind: "value",
|
|
772
|
+
value: value.length > 3 ? value.slice(0, 3) + "\u2026" : value
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
for (const kind of opts.kinds ?? []) {
|
|
776
|
+
for (const value of findKind(kind, out)) {
|
|
777
|
+
if (this.known(kind, value)) continue;
|
|
778
|
+
out = out.split(value).join(token.split("{kind}").join(kind));
|
|
779
|
+
this.redactions.push({ where, kind });
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
for (const pattern of opts.patterns ?? []) {
|
|
783
|
+
const global = new RegExp(
|
|
784
|
+
pattern.source,
|
|
785
|
+
pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g"
|
|
786
|
+
);
|
|
787
|
+
const count = [...out.matchAll(global)].length;
|
|
788
|
+
out = out.replace(global, token.split("{kind}").join("pattern"));
|
|
789
|
+
for (let i = 0; i < count; i += 1)
|
|
790
|
+
this.redactions.push({ where, kind: `pattern:${pattern.source}` });
|
|
791
|
+
}
|
|
792
|
+
return out;
|
|
793
|
+
}
|
|
794
|
+
derive(kind, real, identity) {
|
|
795
|
+
if (kind === "person_name") {
|
|
796
|
+
const display2 = fullName(identity);
|
|
797
|
+
return [display2, namePairs(real, display2)];
|
|
798
|
+
}
|
|
799
|
+
if (kind === "email") {
|
|
800
|
+
const [local, domain] = splitEmail(canonical("email", real));
|
|
801
|
+
const publicDomain = this.mailboxDomains().has(domain) || this.publicLayerWins && this.isPublic("domain", domain);
|
|
802
|
+
const newDomain = publicDomain ? domain : identity.domain;
|
|
803
|
+
const display2 = `${mirrorHandle(local, identity)}@${newDomain}`;
|
|
804
|
+
let variants = emailPairs(canonical("email", real), display2);
|
|
805
|
+
if (!publicDomain)
|
|
806
|
+
variants = variants.concat(genericPairs(domain, newDomain));
|
|
807
|
+
return [display2, dedupe(variants)];
|
|
808
|
+
}
|
|
809
|
+
if (kind === "username") {
|
|
810
|
+
const display2 = mirrorHandle(canonical("username", real), identity);
|
|
811
|
+
return [display2, genericPairs(canonical("username", real), display2)];
|
|
812
|
+
}
|
|
813
|
+
if (kind === "phone") {
|
|
814
|
+
const digits = canonical("phone", real);
|
|
815
|
+
const tail = Number(index(this.runKey, "phone", digits) % 100n);
|
|
816
|
+
const display2 = `+1 999 555 01${String(tail).padStart(2, "0")}`;
|
|
817
|
+
return [display2, phonePairs(real, display2)];
|
|
818
|
+
}
|
|
819
|
+
if (kind === "company")
|
|
820
|
+
return [identity.company, genericPairs(real, identity.company)];
|
|
821
|
+
if (kind === "domain")
|
|
822
|
+
return [
|
|
823
|
+
identity.domain,
|
|
824
|
+
genericPairs(canonical("domain", real), identity.domain)
|
|
825
|
+
];
|
|
826
|
+
if (kind === "ip") {
|
|
827
|
+
const octet = Number(index(this.runKey, "ip", canonical("ip", real)) % 254n) + 1;
|
|
828
|
+
const display2 = `203.0.113.${octet}`;
|
|
829
|
+
return [display2, [[real, display2]]];
|
|
830
|
+
}
|
|
831
|
+
if (kind === "account" || kind === "machine" || kind === "log") {
|
|
832
|
+
const prefix = { account: "AC", machine: "MC", log: "LG" }[kind];
|
|
833
|
+
const display2 = `${prefix}-${Number(index(this.runKey, kind, real) % 9000n) + 1e3}`;
|
|
834
|
+
return [display2, [[real, display2]]];
|
|
835
|
+
}
|
|
836
|
+
const display = `REF-${Number(index(this.runKey, kind, real) % 9000n) + 1e3}`;
|
|
837
|
+
return [display, [[real, display]]];
|
|
838
|
+
}
|
|
839
|
+
/** A world serves hashed personal fields as `sha256:<hex>`. If the plaintext is
|
|
840
|
+
* one we know, the digest is that alias's; otherwise it is an identity we have no
|
|
841
|
+
* plaintext for, and it gets its own stable stand-in digest so records still join. */
|
|
842
|
+
mintDigest(digest, provenance = "world") {
|
|
843
|
+
const key2 = _AliasMap.key("digest", digest.toLowerCase());
|
|
844
|
+
const existing = this.aliases.get(key2);
|
|
845
|
+
if (existing) return existing.display;
|
|
846
|
+
if (this.aliasDigests.has(digest.toLowerCase())) return digest;
|
|
847
|
+
const standIn = "sha256:" + (0, import_node_crypto.createHmac)("sha256", Buffer.from(this.runKey, "hex")).update(digest, "utf8").digest("hex");
|
|
848
|
+
this.aliasDigests.add(standIn.toLowerCase());
|
|
849
|
+
const alias = {
|
|
850
|
+
kind: "digest",
|
|
851
|
+
canonical: digest.toLowerCase(),
|
|
852
|
+
real: digest,
|
|
853
|
+
display: standIn,
|
|
854
|
+
identity: null,
|
|
855
|
+
role: "private",
|
|
856
|
+
provenance,
|
|
857
|
+
variants: [[digest, standIn]],
|
|
858
|
+
hitsIn: 0,
|
|
859
|
+
hitsOut: 0
|
|
860
|
+
};
|
|
861
|
+
this.aliases.set(key2, alias);
|
|
862
|
+
if (this.pairsCache !== null) {
|
|
863
|
+
insertByLength(this.pairsCache[0], [digest, standIn, alias]);
|
|
864
|
+
insertByLength(this.pairsCache[1], [standIn, digest, alias]);
|
|
865
|
+
}
|
|
866
|
+
return standIn;
|
|
867
|
+
}
|
|
868
|
+
// ------------------------------------------------------------ seeding
|
|
869
|
+
/** Mint aliases for a task's known entities before the run starts, so the
|
|
870
|
+
* instruction the agent reads is already in alias space. `identity` groups the
|
|
871
|
+
* attributes of one person; `role: "public"` marks the public layer, never replaced. */
|
|
872
|
+
seed(entities) {
|
|
873
|
+
for (const entity of entities) {
|
|
874
|
+
if ((entity.role ?? "private") === "public")
|
|
875
|
+
this.mint(entity.type, entity.value, { role: "public" });
|
|
876
|
+
}
|
|
877
|
+
const minted = [];
|
|
878
|
+
for (const entity of entities) {
|
|
879
|
+
const alias = this.mint(entity.type, entity.value, {
|
|
880
|
+
identityKey: entity.identity,
|
|
881
|
+
role: entity.role ?? "private"
|
|
882
|
+
});
|
|
883
|
+
if (alias.role === "private") {
|
|
884
|
+
for (const slug of this.slugs) {
|
|
885
|
+
const standIn = "sha256:" + (0, import_node_crypto.createHash)("sha256").update(`${slug}:${canonical(alias.kind, alias.display)}`, "utf8").digest("hex");
|
|
886
|
+
alias.variants.push([
|
|
887
|
+
"sha256:" + (0, import_node_crypto.createHash)("sha256").update(`${slug}:${alias.canonical}`, "utf8").digest("hex"),
|
|
888
|
+
standIn
|
|
889
|
+
]);
|
|
890
|
+
this.aliasDigests.add(standIn.toLowerCase());
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
minted.push({
|
|
894
|
+
type: alias.kind,
|
|
895
|
+
real: alias.real,
|
|
896
|
+
alias: alias.display,
|
|
897
|
+
role: alias.role,
|
|
898
|
+
identity: alias.identity
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
this.pairsCache = null;
|
|
902
|
+
return minted;
|
|
903
|
+
}
|
|
904
|
+
// ------------------------------------------------------------ the door
|
|
905
|
+
/** (needle, replacement, alias) for every variant, longest first, so a full name
|
|
906
|
+
* is replaced before its bare surname. */
|
|
907
|
+
/** The public layer, folded: what is never replaced — and never counted as a
|
|
908
|
+
* leak either. A found email whose local part IS a public handle (the subject's
|
|
909
|
+
* own `oni-sensei`, seeded public) derives that handle as a bare variant; with
|
|
910
|
+
* `publicLayerWins` the handle stays real in both directions and the meters agree,
|
|
911
|
+
* or every mention of the subject would read as a leak. */
|
|
912
|
+
publicFolded() {
|
|
913
|
+
if (!this.publicLayerWins) return /* @__PURE__ */ new Set();
|
|
914
|
+
return new Set(
|
|
915
|
+
[...this.aliases.values()].filter((a) => a.role === "public").map((a) => folded(a.real))
|
|
916
|
+
);
|
|
917
|
+
}
|
|
918
|
+
pairs() {
|
|
919
|
+
if (this.pairsCache === null) {
|
|
920
|
+
const inbound = [];
|
|
921
|
+
const outbound = [];
|
|
922
|
+
const publicValues = /* @__PURE__ */ new Set();
|
|
923
|
+
if (this.publicLayerWins)
|
|
924
|
+
for (const alias of this.aliases.values()) {
|
|
925
|
+
if (alias.role === "public") publicValues.add(folded(alias.real));
|
|
926
|
+
}
|
|
927
|
+
for (const alias of this.aliases.values()) {
|
|
928
|
+
if (alias.role === "public") continue;
|
|
929
|
+
for (const [real, fake] of alias.variants) {
|
|
930
|
+
if (publicValues.has(folded(real))) continue;
|
|
931
|
+
inbound.push([real, fake, alias]);
|
|
932
|
+
outbound.push([fake, real, alias]);
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
inbound.sort((a, b) => b[0].length - a[0].length);
|
|
936
|
+
outbound.sort((a, b) => b[0].length - a[0].length);
|
|
937
|
+
this.pairsCache = [inbound, outbound];
|
|
938
|
+
}
|
|
939
|
+
return this.pairsCache;
|
|
940
|
+
}
|
|
941
|
+
/** Inbound. Every real value and variant becomes its alias, then what slipped
|
|
942
|
+
* through is counted. `meter: false` rewrites text that is being RECORDED, not
|
|
943
|
+
* shown to the agent, so it is not counted as leak-through. */
|
|
944
|
+
toAgent(text, where = "tool_result", meter = true) {
|
|
945
|
+
if (typeof text !== "string" || !text) return text;
|
|
946
|
+
const [inbound] = this.pairs();
|
|
947
|
+
let out = text;
|
|
948
|
+
for (const [needle, replacement, alias] of inbound) {
|
|
949
|
+
if (needle && out.includes(needle)) {
|
|
950
|
+
out = out.split(needle).join(replacement);
|
|
951
|
+
alias.hitsIn += 1;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
out = out.replace(SHA256_ANY_GLOBAL, (match) => this.mintDigest(match));
|
|
955
|
+
if (this.mintInbound.length) out = this.mintFoundIn(out, where);
|
|
956
|
+
if (meter) this.meter(out, where);
|
|
957
|
+
return out;
|
|
958
|
+
}
|
|
959
|
+
/** Outbound. Every alias variant becomes the real value, for a live API or for a
|
|
960
|
+
* fidelity world. An alias that leaves unresolved would make the agent fold a
|
|
961
|
+
* stranger into the case, so anything left over is recorded as a run-failing bug;
|
|
962
|
+
* a `sha256:` digest is a stored form, never a selector. */
|
|
963
|
+
toWorld(text, where = "tool_args") {
|
|
964
|
+
if (typeof text !== "string" || !text) return [text, []];
|
|
965
|
+
const [, outbound] = this.pairs();
|
|
966
|
+
let out = text;
|
|
967
|
+
for (const [needle, replacement, alias] of outbound) {
|
|
968
|
+
if (needle && out.includes(needle)) {
|
|
969
|
+
out = out.split(needle).join(replacement);
|
|
970
|
+
alias.hitsOut += 1;
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
const problems = [];
|
|
974
|
+
for (const [needle] of outbound) {
|
|
975
|
+
if (needle && out.includes(needle))
|
|
976
|
+
problems.push({ check: "unresolved_alias", detail: needle, where });
|
|
977
|
+
}
|
|
978
|
+
const digest = SHA256_ANY.exec(out);
|
|
979
|
+
if (digest)
|
|
980
|
+
problems.push({ check: "digest_as_selector", detail: digest[0], where });
|
|
981
|
+
this.unresolvedOut.push(...problems);
|
|
982
|
+
return [out, problems];
|
|
983
|
+
}
|
|
984
|
+
walk(node, direction, where = "", meter = true) {
|
|
985
|
+
if (direction === "in") this.discover(node, where);
|
|
986
|
+
const problems = [];
|
|
987
|
+
const go = (value) => {
|
|
988
|
+
if (typeof value === "string") {
|
|
989
|
+
if (direction === "in") return this.toAgent(value, where, meter);
|
|
990
|
+
const [rewritten, found] = this.toWorld(value, where);
|
|
991
|
+
problems.push(...found);
|
|
992
|
+
return rewritten;
|
|
993
|
+
}
|
|
994
|
+
if (Array.isArray(value)) return value.map(go);
|
|
995
|
+
if (value && typeof value === "object") {
|
|
996
|
+
const out = {};
|
|
997
|
+
for (const [k, v] of Object.entries(value))
|
|
998
|
+
out[k] = go(v);
|
|
999
|
+
return out;
|
|
1000
|
+
}
|
|
1001
|
+
return value;
|
|
1002
|
+
};
|
|
1003
|
+
const result = go(node);
|
|
1004
|
+
return direction === "out" ? [result, problems] : result;
|
|
1005
|
+
}
|
|
1006
|
+
// ------------------------------------------------------------ metering
|
|
1007
|
+
/** Requirement 3: count what slipped, do not assume nothing did. */
|
|
1008
|
+
/** Requirement 3: count what slipped, do not assume nothing did. The scan is
|
|
1009
|
+
* case-folded with whitespace collapsed and walks EVERY variant of every alias,
|
|
1010
|
+
* not only the pairs the rewriter used. */
|
|
1011
|
+
meter(text, where) {
|
|
1012
|
+
const haystack = folded(text);
|
|
1013
|
+
const pub = this.publicFolded();
|
|
1014
|
+
for (const alias of this.aliases.values()) {
|
|
1015
|
+
if (alias.role === "public") continue;
|
|
1016
|
+
for (const [real] of alias.variants) {
|
|
1017
|
+
if (real.length >= 4 && !pub.has(folded(real)) && haystack.includes(folded(real))) {
|
|
1018
|
+
this.leaksIn.push({
|
|
1019
|
+
where,
|
|
1020
|
+
kind: alias.kind,
|
|
1021
|
+
variant: shorten(real),
|
|
1022
|
+
alias: alias.display
|
|
1023
|
+
});
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
/** Requirement 4: the report and the artifacts must contain no real value. */
|
|
1030
|
+
scanOutgoing(text, where) {
|
|
1031
|
+
const hits = [];
|
|
1032
|
+
const haystack = typeof text === "string" ? folded(text) : "";
|
|
1033
|
+
const pub = this.publicFolded();
|
|
1034
|
+
for (const alias of this.aliases.values()) {
|
|
1035
|
+
if (alias.role === "public") continue;
|
|
1036
|
+
for (const [real] of alias.variants) {
|
|
1037
|
+
if (real.length >= 4 && !pub.has(folded(real)) && haystack.includes(folded(real))) {
|
|
1038
|
+
hits.push({
|
|
1039
|
+
check: "leak_outbound",
|
|
1040
|
+
where,
|
|
1041
|
+
kind: alias.kind,
|
|
1042
|
+
alias: alias.display,
|
|
1043
|
+
variant: shorten(real)
|
|
1044
|
+
});
|
|
1045
|
+
break;
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
this.leaksOut.push(...hits);
|
|
1050
|
+
return hits;
|
|
1051
|
+
}
|
|
1052
|
+
// ------------------------------------------------------------ reporting
|
|
1053
|
+
/** The task the agent is given, in alias space. */
|
|
1054
|
+
rewriteInstruction(text) {
|
|
1055
|
+
return this.toAgent(text, "instruction");
|
|
1056
|
+
}
|
|
1057
|
+
/** The run key's map. Kept WITH THE RUN KEY, never with the world data. */
|
|
1058
|
+
/** Outbound without the meters: every persona spelling back to the real value.
|
|
1059
|
+
* What `gateway hooks reveal` does to a run's files for an owner holding the
|
|
1060
|
+
* legend. A `[redacted …]` token has nothing behind it: redaction removed the
|
|
1061
|
+
* value; the raw copy is a `record` sink placed before the `redact` rule. */
|
|
1062
|
+
revealText(text) {
|
|
1063
|
+
if (typeof text !== "string" || !text) return text;
|
|
1064
|
+
const [, outbound] = this.pairs();
|
|
1065
|
+
let out = text;
|
|
1066
|
+
for (const [needle, replacement] of outbound)
|
|
1067
|
+
if (needle && out.includes(needle))
|
|
1068
|
+
out = out.split(needle).join(replacement);
|
|
1069
|
+
return out;
|
|
1070
|
+
}
|
|
1071
|
+
/** `revealText` over a whole JSON structure. */
|
|
1072
|
+
reveal(node) {
|
|
1073
|
+
if (typeof node === "string") return this.revealText(node);
|
|
1074
|
+
if (Array.isArray(node)) return node.map((v) => this.reveal(v));
|
|
1075
|
+
if (node && typeof node === "object")
|
|
1076
|
+
return Object.fromEntries(
|
|
1077
|
+
Object.entries(node).map(([k, v]) => [
|
|
1078
|
+
k,
|
|
1079
|
+
this.reveal(v)
|
|
1080
|
+
])
|
|
1081
|
+
);
|
|
1082
|
+
return node;
|
|
1083
|
+
}
|
|
1084
|
+
/** The map a legend describes, rebuilt: every persona derives from the run key and
|
|
1085
|
+
* its real value alone, so minting the rows again — the public layer first, then the
|
|
1086
|
+
* rest in the legend's order — reproduces the same stand-ins, found ones included.
|
|
1087
|
+
* This is how an owner's `gateway hooks legend` / `reveal` read a run that ended in
|
|
1088
|
+
* another process. */
|
|
1089
|
+
static fromLegend(legend, options = {}) {
|
|
1090
|
+
const aliases = new _AliasMap(legend.run_key, options.slugs ?? [], {
|
|
1091
|
+
...options.publicLayerWins !== void 0 ? { publicLayerWins: options.publicLayerWins } : {},
|
|
1092
|
+
...options.publicMailboxDomains !== void 0 ? { publicMailboxDomains: options.publicMailboxDomains } : {}
|
|
1093
|
+
});
|
|
1094
|
+
const rows = [...legend.aliases];
|
|
1095
|
+
const ordered = [
|
|
1096
|
+
...rows.filter((r) => r.role === "public"),
|
|
1097
|
+
...rows.filter((r) => r.role !== "public")
|
|
1098
|
+
];
|
|
1099
|
+
for (const row of ordered) {
|
|
1100
|
+
const real = String(row.real ?? "");
|
|
1101
|
+
if (row.kind === "digest") {
|
|
1102
|
+
aliases.mintDigest(
|
|
1103
|
+
real,
|
|
1104
|
+
row.provenance ?? "world"
|
|
1105
|
+
);
|
|
1106
|
+
continue;
|
|
1107
|
+
}
|
|
1108
|
+
const provenance = row.provenance ?? "seed";
|
|
1109
|
+
if (provenance === "found")
|
|
1110
|
+
aliases.mintFound(String(row.kind), real, "legend");
|
|
1111
|
+
else
|
|
1112
|
+
aliases.mint(String(row.kind), real, {
|
|
1113
|
+
...row.identity ? { identityKey: row.identity } : {},
|
|
1114
|
+
role: row.role ?? "private",
|
|
1115
|
+
provenance
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
return aliases;
|
|
1119
|
+
}
|
|
1120
|
+
legend() {
|
|
1121
|
+
return [...this.aliases.values()].map((a) => ({
|
|
1122
|
+
kind: a.kind,
|
|
1123
|
+
role: a.role,
|
|
1124
|
+
real: a.real,
|
|
1125
|
+
alias: a.display,
|
|
1126
|
+
identity: a.identity,
|
|
1127
|
+
provenance: a.provenance,
|
|
1128
|
+
hits_in: a.hitsIn,
|
|
1129
|
+
hits_out: a.hitsOut
|
|
1130
|
+
}));
|
|
1131
|
+
}
|
|
1132
|
+
summary() {
|
|
1133
|
+
const all = [...this.aliases.values()];
|
|
1134
|
+
const priv = all.filter((a) => a.role === "private");
|
|
1135
|
+
return {
|
|
1136
|
+
aliases: priv.length,
|
|
1137
|
+
public_layer_entities: all.length - priv.length,
|
|
1138
|
+
identities: this.identities.size,
|
|
1139
|
+
variants_tracked: priv.reduce((n, a) => n + a.variants.length, 0),
|
|
1140
|
+
substitutions_inbound: priv.reduce((n, a) => n + a.hitsIn, 0),
|
|
1141
|
+
substitutions_outbound: priv.reduce((n, a) => n + a.hitsOut, 0),
|
|
1142
|
+
leak_through_inbound: this.leaksIn.length,
|
|
1143
|
+
leak_through_inbound_detail: this.leaksIn.slice(0, 50),
|
|
1144
|
+
leaks_outbound: this.leaksOut.length,
|
|
1145
|
+
leaks_outbound_detail: this.leaksOut.slice(0, 50),
|
|
1146
|
+
unresolved_aliases_outbound: this.unresolvedOut.length,
|
|
1147
|
+
unresolved_detail: this.unresolvedOut.slice(0, 50),
|
|
1148
|
+
found_inbound: this.found.length,
|
|
1149
|
+
found_inbound_detail: this.found.slice(0, 50),
|
|
1150
|
+
redactions: this.redactions.length,
|
|
1151
|
+
redactions_detail: this.redactions.slice(0, 50)
|
|
1152
|
+
};
|
|
1153
|
+
}
|
|
1154
|
+
/** The alias minted for a kind and value, if any. */
|
|
1155
|
+
get(kind, value) {
|
|
1156
|
+
return this.aliases.get(_AliasMap.key(kind, canonical(kind, value)));
|
|
1157
|
+
}
|
|
1158
|
+
};
|
|
1159
|
+
var shorten = (real) => real.length > 6 ? real.slice(0, 6) + "\u2026" : real;
|
|
1160
|
+
var folded = (text) => text.replace(/\s+/g, " ").toLowerCase();
|
|
1161
|
+
function insertByLength(pairs, entry) {
|
|
1162
|
+
const length = entry[0].length;
|
|
1163
|
+
const index2 = pairs.findIndex(([needle]) => needle.length < length);
|
|
1164
|
+
if (index2 === -1) pairs.push(entry);
|
|
1165
|
+
else pairs.splice(index2, 0, entry);
|
|
1166
|
+
}
|
|
1167
|
+
function mirrorHandle(handle, identity) {
|
|
1168
|
+
const given = identity.given.toLowerCase();
|
|
1169
|
+
const surname = identity.surname.toLowerCase();
|
|
1170
|
+
const text = handle.toLowerCase();
|
|
1171
|
+
const digits = /\d+$/.exec(text);
|
|
1172
|
+
const suffix = digits ? digits[0] : "";
|
|
1173
|
+
const body = text.slice(0, text.length - suffix.length);
|
|
1174
|
+
for (const separator of [".", "_", "-"]) {
|
|
1175
|
+
if (body.includes(separator))
|
|
1176
|
+
return `${given}${separator}${surname}${suffix}`;
|
|
1177
|
+
}
|
|
1178
|
+
if (body.length <= surname.length + 2)
|
|
1179
|
+
return `${given[0]}${surname}${suffix}`;
|
|
1180
|
+
return `${given}${surname}${suffix}`;
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
// src/hooks/config.ts
|
|
1184
|
+
var fs = __toESM(require("fs"));
|
|
1185
|
+
|
|
1186
|
+
// src/cli/platform/worldData/toml.ts
|
|
1187
|
+
var TomlError = class extends Error {
|
|
1188
|
+
};
|
|
1189
|
+
function parseToml(text) {
|
|
1190
|
+
const root = {};
|
|
1191
|
+
let current = root;
|
|
1192
|
+
const lines = joinContinuations(text);
|
|
1193
|
+
for (const [number, rawLine] of lines.entries()) {
|
|
1194
|
+
const line = stripComment(rawLine).trim();
|
|
1195
|
+
if (!line) continue;
|
|
1196
|
+
const arrayTable = /^\[\[\s*([^\]]+?)\s*\]\]$/.exec(line);
|
|
1197
|
+
if (arrayTable) {
|
|
1198
|
+
const parent = tableAt(root, keyPath(arrayTable[1]).slice(0, -1));
|
|
1199
|
+
const name = keyPath(arrayTable[1]).at(-1);
|
|
1200
|
+
const list = parent[name] ??= [];
|
|
1201
|
+
if (!Array.isArray(list)) throw new TomlError(`line ${number + 1}: ${name} is not an array of tables`);
|
|
1202
|
+
current = {};
|
|
1203
|
+
list.push(current);
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
1206
|
+
const table = /^\[\s*([^\]]+?)\s*\]$/.exec(line);
|
|
1207
|
+
if (table) {
|
|
1208
|
+
current = tableAt(root, keyPath(table[1]));
|
|
1209
|
+
continue;
|
|
1210
|
+
}
|
|
1211
|
+
const eq = line.indexOf("=");
|
|
1212
|
+
if (eq === -1) throw new TomlError(`line ${number + 1}: expected key = value`);
|
|
1213
|
+
const key2 = unquoteKey(line.slice(0, eq).trim());
|
|
1214
|
+
const [value, rest] = readValue(line.slice(eq + 1).trim(), number + 1);
|
|
1215
|
+
if (rest.trim()) throw new TomlError(`line ${number + 1}: unexpected text after value`);
|
|
1216
|
+
current[key2] = value;
|
|
1217
|
+
}
|
|
1218
|
+
return root;
|
|
1219
|
+
}
|
|
1220
|
+
function keyPath(header) {
|
|
1221
|
+
return header.split(".").map((part) => unquoteKey(part.trim()));
|
|
1222
|
+
}
|
|
1223
|
+
function unquoteKey(key2) {
|
|
1224
|
+
if (key2.startsWith('"') && key2.endsWith('"') || key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
|
|
1225
|
+
return key2;
|
|
1226
|
+
}
|
|
1227
|
+
function tableAt(root, parts2) {
|
|
1228
|
+
let node = root;
|
|
1229
|
+
for (const part of parts2) {
|
|
1230
|
+
const next = node[part] ??= {};
|
|
1231
|
+
if (Array.isArray(next)) {
|
|
1232
|
+
const last = next[next.length - 1];
|
|
1233
|
+
if (!last || typeof last !== "object" || Array.isArray(last)) throw new TomlError(`${part} is not a table`);
|
|
1234
|
+
node = last;
|
|
1235
|
+
} else if (typeof next !== "object") throw new TomlError(`${part} is not a table`);
|
|
1236
|
+
else node = next;
|
|
1237
|
+
}
|
|
1238
|
+
return node;
|
|
1239
|
+
}
|
|
1240
|
+
function joinContinuations(text) {
|
|
1241
|
+
const out = [];
|
|
1242
|
+
let pending = "";
|
|
1243
|
+
let depth = 0;
|
|
1244
|
+
for (const physical of text.split(/\r?\n/)) {
|
|
1245
|
+
const raw = stripComment(physical);
|
|
1246
|
+
const line = pending ? pending + "\n" + raw : raw;
|
|
1247
|
+
depth = bracketDepth(line);
|
|
1248
|
+
if (depth > 0) {
|
|
1249
|
+
pending = line;
|
|
1250
|
+
continue;
|
|
1251
|
+
}
|
|
1252
|
+
pending = "";
|
|
1253
|
+
out.push(line);
|
|
1254
|
+
}
|
|
1255
|
+
if (pending) out.push(pending);
|
|
1256
|
+
return out;
|
|
1257
|
+
}
|
|
1258
|
+
function bracketDepth(line) {
|
|
1259
|
+
let depth = 0;
|
|
1260
|
+
let quote = null;
|
|
1261
|
+
for (let i = 0; i < line.length; i++) {
|
|
1262
|
+
const c = line[i];
|
|
1263
|
+
if (quote) {
|
|
1264
|
+
if (c === "\\" && quote === '"') i++;
|
|
1265
|
+
else if (c === quote) quote = null;
|
|
1266
|
+
continue;
|
|
1267
|
+
}
|
|
1268
|
+
if (c === '"' || c === "'") quote = c;
|
|
1269
|
+
else if (c === "[" || c === "{") depth++;
|
|
1270
|
+
else if (c === "]" || c === "}") depth--;
|
|
1271
|
+
}
|
|
1272
|
+
return depth;
|
|
1273
|
+
}
|
|
1274
|
+
function stripComment(line) {
|
|
1275
|
+
let quote = null;
|
|
1276
|
+
for (let i = 0; i < line.length; i++) {
|
|
1277
|
+
const c = line[i];
|
|
1278
|
+
if (quote) {
|
|
1279
|
+
if (c === "\\" && quote === '"') i++;
|
|
1280
|
+
else if (c === quote) quote = null;
|
|
1281
|
+
continue;
|
|
1282
|
+
}
|
|
1283
|
+
if (c === '"' || c === "'") quote = c;
|
|
1284
|
+
else if (c === "#") return line.slice(0, i);
|
|
1285
|
+
}
|
|
1286
|
+
return line;
|
|
1287
|
+
}
|
|
1288
|
+
function readValue(text, line) {
|
|
1289
|
+
const s = text.trimStart();
|
|
1290
|
+
if (s.startsWith('"')) {
|
|
1291
|
+
let out = "";
|
|
1292
|
+
for (let i = 1; i < s.length; i++) {
|
|
1293
|
+
const c = s[i];
|
|
1294
|
+
if (c === "\\") {
|
|
1295
|
+
const e = s[++i];
|
|
1296
|
+
const map = { n: "\n", t: " ", r: "\r", '"': '"', "\\": "\\", b: "\b", f: "\f" };
|
|
1297
|
+
if (e === "u" || e === "U") {
|
|
1298
|
+
const width = e === "u" ? 4 : 8;
|
|
1299
|
+
out += String.fromCodePoint(parseInt(s.slice(i + 1, i + 1 + width), 16));
|
|
1300
|
+
i += width;
|
|
1301
|
+
} else if (e !== void 0 && e in map) out += map[e];
|
|
1302
|
+
else throw new TomlError(`line ${line}: unsupported escape \\${e ?? ""}`);
|
|
1303
|
+
continue;
|
|
1304
|
+
}
|
|
1305
|
+
if (c === '"') return [out, s.slice(i + 1)];
|
|
1306
|
+
out += c;
|
|
1307
|
+
}
|
|
1308
|
+
throw new TomlError(`line ${line}: unterminated string`);
|
|
1309
|
+
}
|
|
1310
|
+
if (s.startsWith("'")) {
|
|
1311
|
+
const end = s.indexOf("'", 1);
|
|
1312
|
+
if (end === -1) throw new TomlError(`line ${line}: unterminated string`);
|
|
1313
|
+
return [s.slice(1, end), s.slice(end + 1)];
|
|
1314
|
+
}
|
|
1315
|
+
if (s.startsWith("[")) {
|
|
1316
|
+
const items = [];
|
|
1317
|
+
let rest2 = s.slice(1);
|
|
1318
|
+
for (; ; ) {
|
|
1319
|
+
rest2 = rest2.replace(/^[\s\n]+/, "");
|
|
1320
|
+
if (rest2.startsWith("]")) return [items, rest2.slice(1)];
|
|
1321
|
+
const [item, after] = readValue(rest2, line);
|
|
1322
|
+
items.push(item);
|
|
1323
|
+
rest2 = after.replace(/^[\s\n]+/, "");
|
|
1324
|
+
if (rest2.startsWith(",")) rest2 = rest2.slice(1);
|
|
1325
|
+
else if (!rest2.startsWith("]")) throw new TomlError(`line ${line}: expected , or ] in array`);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
if (s.startsWith("{")) {
|
|
1329
|
+
const table = {};
|
|
1330
|
+
let rest2 = s.slice(1);
|
|
1331
|
+
for (; ; ) {
|
|
1332
|
+
rest2 = rest2.replace(/^[\s\n]+/, "");
|
|
1333
|
+
if (rest2.startsWith("}")) return [table, rest2.slice(1)];
|
|
1334
|
+
const eq = rest2.indexOf("=");
|
|
1335
|
+
if (eq === -1) throw new TomlError(`line ${line}: expected key = value in inline table`);
|
|
1336
|
+
const key2 = unquoteKey(rest2.slice(0, eq).trim());
|
|
1337
|
+
const [value, after] = readValue(rest2.slice(eq + 1), line);
|
|
1338
|
+
table[key2] = value;
|
|
1339
|
+
rest2 = after.replace(/^[\s\n]+/, "");
|
|
1340
|
+
if (rest2.startsWith(",")) rest2 = rest2.slice(1);
|
|
1341
|
+
else if (!rest2.startsWith("}")) throw new TomlError(`line ${line}: expected , or } in inline table`);
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
const scalar = /^([^,\]}\s]+)/.exec(s);
|
|
1345
|
+
if (!scalar) throw new TomlError(`line ${line}: expected a value`);
|
|
1346
|
+
const token = scalar[1];
|
|
1347
|
+
const rest = s.slice(token.length);
|
|
1348
|
+
if (token === "true") return [true, rest];
|
|
1349
|
+
if (token === "false") return [false, rest];
|
|
1350
|
+
if (/^[+-]?\d[\d_]*$/.test(token)) return [Number(token.replace(/_/g, "")), rest];
|
|
1351
|
+
if (/^[+-]?(\d[\d_]*)?\.?\d[\d_]*([eE][+-]?\d+)?$/.test(token)) return [Number(token.replace(/_/g, "")), rest];
|
|
1352
|
+
throw new TomlError(`line ${line}: unsupported value ${token}`);
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
// src/hooks/events.ts
|
|
1356
|
+
var EVENTS = [
|
|
1357
|
+
"pre_tool_call",
|
|
1358
|
+
"post_tool_call",
|
|
1359
|
+
"pre_request",
|
|
1360
|
+
"post_response",
|
|
1361
|
+
"run_end"
|
|
1362
|
+
];
|
|
1363
|
+
var EVENT_ALIASES = {
|
|
1364
|
+
PreToolUse: "pre_tool_call",
|
|
1365
|
+
PostToolUse: "post_tool_call",
|
|
1366
|
+
Stop: "run_end",
|
|
1367
|
+
SessionEnd: "run_end"
|
|
1368
|
+
};
|
|
1369
|
+
var DECISIONS = ["allow", "deny", "rewrite"];
|
|
1370
|
+
var UPDATE_FIELDS = [
|
|
1371
|
+
"updated_input",
|
|
1372
|
+
"updated_result",
|
|
1373
|
+
"updated_error",
|
|
1374
|
+
"updated_request",
|
|
1375
|
+
"updated_response"
|
|
1376
|
+
];
|
|
1377
|
+
function normalizeEvent(name) {
|
|
1378
|
+
if (EVENTS.includes(name))
|
|
1379
|
+
return name;
|
|
1380
|
+
return EVENT_ALIASES[name] ?? null;
|
|
1381
|
+
}
|
|
1382
|
+
function eventToJson(event) {
|
|
1383
|
+
const out = {
|
|
1384
|
+
hook_event_name: event.event,
|
|
1385
|
+
run_id: event.runId,
|
|
1386
|
+
tool_name: event.toolName,
|
|
1387
|
+
tool_input: event.toolInput ?? null,
|
|
1388
|
+
matcher: event.matcher,
|
|
1389
|
+
cwd: event.cwd
|
|
1390
|
+
};
|
|
1391
|
+
if (event.vendor !== void 0) out.vendor = event.vendor;
|
|
1392
|
+
if (event.event === "post_tool_call") {
|
|
1393
|
+
out.tool_result = event.toolResult ?? null;
|
|
1394
|
+
if (event.error !== void 0) out.error = event.error;
|
|
1395
|
+
}
|
|
1396
|
+
if (event.event === "pre_request" || event.event === "post_response")
|
|
1397
|
+
out.request = event.request ?? null;
|
|
1398
|
+
if (event.event === "post_response") out.response = event.response ?? null;
|
|
1399
|
+
if (event.event === "run_end") {
|
|
1400
|
+
out.report = event.report ?? null;
|
|
1401
|
+
out.artifacts = { ...event.artifacts ?? {} };
|
|
1402
|
+
}
|
|
1403
|
+
return out;
|
|
1404
|
+
}
|
|
1405
|
+
var allow = (extra = {}) => ({
|
|
1406
|
+
decision: "allow",
|
|
1407
|
+
findings: [],
|
|
1408
|
+
...extra
|
|
1409
|
+
});
|
|
1410
|
+
var rewrites = (result) => UPDATE_FIELDS.some((key2) => key2 in result);
|
|
1411
|
+
var HookDenied = class extends Error {
|
|
1412
|
+
constructor(event, toolName, reason, findings = [], handler = "") {
|
|
1413
|
+
super(`${event} ${toolName}: denied \u2014 ${reason}`);
|
|
1414
|
+
this.event = event;
|
|
1415
|
+
this.toolName = toolName;
|
|
1416
|
+
this.reason = reason;
|
|
1417
|
+
this.findings = findings;
|
|
1418
|
+
this.handler = handler;
|
|
1419
|
+
this.name = "HookDenied";
|
|
1420
|
+
}
|
|
1421
|
+
};
|
|
1422
|
+
var HookError = class extends Error {
|
|
1423
|
+
constructor(event, toolName, handler, detail) {
|
|
1424
|
+
super(`${event} ${toolName}: hook ${handler} \u2014 ${detail}`);
|
|
1425
|
+
this.event = event;
|
|
1426
|
+
this.toolName = toolName;
|
|
1427
|
+
this.handler = handler;
|
|
1428
|
+
this.detail = detail;
|
|
1429
|
+
this.name = "HookError";
|
|
1430
|
+
}
|
|
1431
|
+
};
|
|
1432
|
+
var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1433
|
+
function resultFromJson(raw, handler = "handler") {
|
|
1434
|
+
if (!isObject(raw))
|
|
1435
|
+
throw new Error(
|
|
1436
|
+
`${handler} answered ${raw === null ? "null" : typeof raw}, not a JSON object`
|
|
1437
|
+
);
|
|
1438
|
+
let source = raw;
|
|
1439
|
+
if (isObject(raw.hookSpecificOutput))
|
|
1440
|
+
source = fromClaudeCode(raw.hookSpecificOutput);
|
|
1441
|
+
let decision = source.decision ?? "allow";
|
|
1442
|
+
if (decision === "block") decision = "deny";
|
|
1443
|
+
if (!DECISIONS.includes(decision))
|
|
1444
|
+
throw new Error(
|
|
1445
|
+
`${handler} answered decision=${JSON.stringify(decision)}; expected one of ${DECISIONS.join(", ")}`
|
|
1446
|
+
);
|
|
1447
|
+
const findings = source.findings ?? [];
|
|
1448
|
+
if (!Array.isArray(findings))
|
|
1449
|
+
throw new Error(`${handler} answered findings that are not a list`);
|
|
1450
|
+
const context = source.additional_context;
|
|
1451
|
+
if (context !== void 0 && context !== null && typeof context !== "string")
|
|
1452
|
+
throw new Error(
|
|
1453
|
+
`${handler} answered additional_context that is not a string`
|
|
1454
|
+
);
|
|
1455
|
+
const result = {
|
|
1456
|
+
decision,
|
|
1457
|
+
findings
|
|
1458
|
+
};
|
|
1459
|
+
if (typeof source.reason === "string") result.reason = source.reason;
|
|
1460
|
+
if (typeof context === "string") result.additional_context = context;
|
|
1461
|
+
for (const key2 of UPDATE_FIELDS)
|
|
1462
|
+
if (key2 in source) result[key2] = source[key2];
|
|
1463
|
+
if (result.decision === "allow" && rewrites(result))
|
|
1464
|
+
result.decision = "rewrite";
|
|
1465
|
+
if (result.decision === "rewrite" && !rewrites(result))
|
|
1466
|
+
throw new Error(
|
|
1467
|
+
`${handler} answered decision=rewrite with no updated_* field`
|
|
1468
|
+
);
|
|
1469
|
+
return result;
|
|
1470
|
+
}
|
|
1471
|
+
function fromClaudeCode(specific) {
|
|
1472
|
+
const out = {};
|
|
1473
|
+
const decision = specific.permissionDecision ?? specific.decision;
|
|
1474
|
+
out.decision = decision === "deny" || decision === "block" ? "deny" : decision === void 0 || decision === null ? "allow" : decision;
|
|
1475
|
+
const reason = specific.permissionDecisionReason ?? specific.reason;
|
|
1476
|
+
if (reason !== void 0) out.reason = reason;
|
|
1477
|
+
if ("updatedInput" in specific) out.updated_input = specific.updatedInput;
|
|
1478
|
+
if ("additionalContext" in specific)
|
|
1479
|
+
out.additional_context = specific.additionalContext;
|
|
1480
|
+
return out;
|
|
1481
|
+
}
|
|
1482
|
+
function applyResult(event, result) {
|
|
1483
|
+
if ("updated_input" in result) event.toolInput = result.updated_input;
|
|
1484
|
+
if ("updated_result" in result) event.toolResult = result.updated_result;
|
|
1485
|
+
if ("updated_error" in result) event.error = result.updated_error;
|
|
1486
|
+
if ("updated_request" in result) event.request = result.updated_request;
|
|
1487
|
+
if ("updated_response" in result) event.response = result.updated_response;
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
// src/hooks/matchers.ts
|
|
1491
|
+
function splitTopLevel(text) {
|
|
1492
|
+
const parts2 = [];
|
|
1493
|
+
let depth = 0;
|
|
1494
|
+
let current = "";
|
|
1495
|
+
let escaped = false;
|
|
1496
|
+
let inClass = false;
|
|
1497
|
+
for (const char of text) {
|
|
1498
|
+
if (escaped) {
|
|
1499
|
+
current += char;
|
|
1500
|
+
escaped = false;
|
|
1501
|
+
continue;
|
|
1502
|
+
}
|
|
1503
|
+
if (char === "\\") {
|
|
1504
|
+
current += char;
|
|
1505
|
+
escaped = true;
|
|
1506
|
+
continue;
|
|
1507
|
+
}
|
|
1508
|
+
if (inClass) {
|
|
1509
|
+
current += char;
|
|
1510
|
+
if (char === "]") inClass = false;
|
|
1511
|
+
continue;
|
|
1512
|
+
}
|
|
1513
|
+
if (char === "[") inClass = true;
|
|
1514
|
+
else if (char === "(") depth += 1;
|
|
1515
|
+
else if (char === ")") depth = Math.max(0, depth - 1);
|
|
1516
|
+
else if (char === "|" && depth === 0) {
|
|
1517
|
+
parts2.push(current);
|
|
1518
|
+
current = "";
|
|
1519
|
+
continue;
|
|
1520
|
+
}
|
|
1521
|
+
current += char;
|
|
1522
|
+
}
|
|
1523
|
+
parts2.push(current);
|
|
1524
|
+
return parts2;
|
|
1525
|
+
}
|
|
1526
|
+
function alternatives(raw) {
|
|
1527
|
+
if (raw === void 0 || raw === null) return [];
|
|
1528
|
+
const parts2 = (typeof raw === "string" ? splitTopLevel(raw) : raw).map((p) => String(p).trim()).filter(Boolean);
|
|
1529
|
+
if (!parts2.length || parts2.includes("*")) return [];
|
|
1530
|
+
return parts2;
|
|
1531
|
+
}
|
|
1532
|
+
function hasPath(node, path4) {
|
|
1533
|
+
let current = node;
|
|
1534
|
+
for (const part of path4.split(".")) {
|
|
1535
|
+
if (current && typeof current === "object" && !Array.isArray(current) && part in current) {
|
|
1536
|
+
current = current[part];
|
|
1537
|
+
continue;
|
|
1538
|
+
}
|
|
1539
|
+
if (Array.isArray(current) && /^\d+$/.test(part) && Number(part) < current.length) {
|
|
1540
|
+
current = current[Number(part)];
|
|
1541
|
+
continue;
|
|
1542
|
+
}
|
|
1543
|
+
return false;
|
|
1544
|
+
}
|
|
1545
|
+
return current !== null && current !== void 0;
|
|
1546
|
+
}
|
|
1547
|
+
function parseMatcher(matcher, opts = {}) {
|
|
1548
|
+
const patterns = alternatives(matcher);
|
|
1549
|
+
for (const pattern of patterns) {
|
|
1550
|
+
try {
|
|
1551
|
+
new RegExp(pattern);
|
|
1552
|
+
} catch (error) {
|
|
1553
|
+
throw new Error(
|
|
1554
|
+
`matcher ${JSON.stringify(pattern)} is not a regular expression: ${error.message}`
|
|
1555
|
+
);
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
const args = opts.arg === void 0 || opts.arg === null ? [] : typeof opts.arg === "string" ? [opts.arg] : opts.arg.map(String);
|
|
1559
|
+
return { patterns, ...opts.vendor ? { vendor: opts.vendor } : {}, args };
|
|
1560
|
+
}
|
|
1561
|
+
function describeMatcher(m) {
|
|
1562
|
+
let text = m.patterns.length ? m.patterns.join(" | ") : "*";
|
|
1563
|
+
if (m.vendor) text += ` vendor=${m.vendor}`;
|
|
1564
|
+
if (m.args.length) text += " arg=" + m.args.join(",");
|
|
1565
|
+
return text;
|
|
1566
|
+
}
|
|
1567
|
+
function matches(m, event) {
|
|
1568
|
+
const name = event.toolName ?? "";
|
|
1569
|
+
if (m.patterns.length && !m.patterns.some((pattern) => new RegExp(pattern).test(name)))
|
|
1570
|
+
return false;
|
|
1571
|
+
if (m.vendor && event.vendor !== m.vendor) return false;
|
|
1572
|
+
if (m.args.length) {
|
|
1573
|
+
const haystacks = event.event === "pre_request" || event.event === "post_response" ? [event.request?.query, event.request?.body] : [event.toolInput];
|
|
1574
|
+
const present = haystacks.filter((h) => h !== void 0 && h !== null);
|
|
1575
|
+
if (!m.args.every((path4) => present.some((h) => hasPath(h, path4))))
|
|
1576
|
+
return false;
|
|
1577
|
+
}
|
|
1578
|
+
return true;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
// src/hooks/config.ts
|
|
1582
|
+
var HANDLER_TYPES = [
|
|
1583
|
+
"alias",
|
|
1584
|
+
"command",
|
|
1585
|
+
"callable",
|
|
1586
|
+
"http",
|
|
1587
|
+
"deny",
|
|
1588
|
+
"record",
|
|
1589
|
+
"redact"
|
|
1590
|
+
];
|
|
1591
|
+
var DEFAULT_TIMEOUTS = {
|
|
1592
|
+
command: 60,
|
|
1593
|
+
http: 30
|
|
1594
|
+
};
|
|
1595
|
+
var RUN_END_TIMEOUT = 120;
|
|
1596
|
+
var COMMON_HANDLER_KEYS = /* @__PURE__ */ new Set(["type", "name", "timeout", "async"]);
|
|
1597
|
+
var HookConfigError = class extends Error {
|
|
1598
|
+
constructor(message) {
|
|
1599
|
+
super(message);
|
|
1600
|
+
this.name = "HookConfigError";
|
|
1601
|
+
}
|
|
1602
|
+
};
|
|
1603
|
+
var TOOL_KINDS = ["http", "callable", "connector"];
|
|
1604
|
+
var PARSE_MODES = ["json", "regex", "text"];
|
|
1605
|
+
var INPUT_TYPES = [
|
|
1606
|
+
"string",
|
|
1607
|
+
"integer",
|
|
1608
|
+
"number",
|
|
1609
|
+
"boolean",
|
|
1610
|
+
"object",
|
|
1611
|
+
"array"
|
|
1612
|
+
];
|
|
1613
|
+
var HTTP_TOOL_KEYS = /* @__PURE__ */ new Set([
|
|
1614
|
+
"method",
|
|
1615
|
+
"url",
|
|
1616
|
+
"headers",
|
|
1617
|
+
"body",
|
|
1618
|
+
"parse",
|
|
1619
|
+
"results",
|
|
1620
|
+
"fields",
|
|
1621
|
+
"pattern",
|
|
1622
|
+
"limit",
|
|
1623
|
+
"max_bytes",
|
|
1624
|
+
"strip_html",
|
|
1625
|
+
"ok_status",
|
|
1626
|
+
"fail_if",
|
|
1627
|
+
"min_interval_ms"
|
|
1628
|
+
]);
|
|
1629
|
+
var STATUS_RANGE = /^(\d{3})(?:-(\d{3}))?$/;
|
|
1630
|
+
function parseOkStatus(raw, position) {
|
|
1631
|
+
if (raw === void 0 || raw === null) return [[200, 200]];
|
|
1632
|
+
const items = Array.isArray(raw) ? raw : [raw];
|
|
1633
|
+
const ranges = [];
|
|
1634
|
+
for (const item of items) {
|
|
1635
|
+
if (typeof item !== "number" && typeof item !== "string")
|
|
1636
|
+
throw new HookConfigError(
|
|
1637
|
+
`${position}.ok_status: expected a status, a "lo-hi" range, or a list of them`
|
|
1638
|
+
);
|
|
1639
|
+
const match = STATUS_RANGE.exec(String(item).trim());
|
|
1640
|
+
if (!match)
|
|
1641
|
+
throw new HookConfigError(
|
|
1642
|
+
`${position}.ok_status: ${JSON.stringify(item)} is not a status or a "lo-hi" range`
|
|
1643
|
+
);
|
|
1644
|
+
const low = Number(match[1]);
|
|
1645
|
+
const high = Number(match[2] ?? match[1]);
|
|
1646
|
+
if (low > high)
|
|
1647
|
+
throw new HookConfigError(
|
|
1648
|
+
`${position}.ok_status: ${JSON.stringify(item)} is inverted`
|
|
1649
|
+
);
|
|
1650
|
+
ranges.push([low, high]);
|
|
1651
|
+
}
|
|
1652
|
+
if (!ranges.length)
|
|
1653
|
+
throw new HookConfigError(
|
|
1654
|
+
`${position}.ok_status: expected at least one status`
|
|
1655
|
+
);
|
|
1656
|
+
return ranges;
|
|
1657
|
+
}
|
|
1658
|
+
var COMMON_TOOL_KEYS = /* @__PURE__ */ new Set([
|
|
1659
|
+
"description",
|
|
1660
|
+
"input",
|
|
1661
|
+
"defaults",
|
|
1662
|
+
"vendor"
|
|
1663
|
+
]);
|
|
1664
|
+
var PLACEHOLDER = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
|
|
1665
|
+
var ENV_REF = /\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g;
|
|
1666
|
+
var jsPattern = (pattern) => pattern.replace(/\(\?P</g, "(?<");
|
|
1667
|
+
var emptyLive = () => ({
|
|
1668
|
+
allowedEnv: [],
|
|
1669
|
+
timeout: 45,
|
|
1670
|
+
tools: {}
|
|
1671
|
+
});
|
|
1672
|
+
function describeTool(spec) {
|
|
1673
|
+
if (spec.kind === "http")
|
|
1674
|
+
return `http ${spec.options.method} ${spec.options.url} parse=${spec.options.parse}`;
|
|
1675
|
+
if (spec.kind === "callable") return `callable ${spec.options.callable}`;
|
|
1676
|
+
return `connector ${spec.options.connector} operation=${spec.options.operation}`;
|
|
1677
|
+
}
|
|
1678
|
+
function inputSchema(shorthand, position) {
|
|
1679
|
+
if (shorthand === void 0 || shorthand === null)
|
|
1680
|
+
return { type: "object", properties: {}, required: [] };
|
|
1681
|
+
if (!isObject2(shorthand))
|
|
1682
|
+
throw new HookConfigError(
|
|
1683
|
+
`${position}.input: expected a table of field = "type"`
|
|
1684
|
+
);
|
|
1685
|
+
const properties = {};
|
|
1686
|
+
const required = [];
|
|
1687
|
+
for (const [name, raw] of Object.entries(shorthand)) {
|
|
1688
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
|
|
1689
|
+
throw new HookConfigError(
|
|
1690
|
+
`${position}.input.${name}: a field name is an identifier`
|
|
1691
|
+
);
|
|
1692
|
+
let schema;
|
|
1693
|
+
let optional;
|
|
1694
|
+
if (typeof raw === "string") {
|
|
1695
|
+
const colon = raw.indexOf(":");
|
|
1696
|
+
const head = (colon === -1 ? raw : raw.slice(0, colon)).trim();
|
|
1697
|
+
const description = colon === -1 ? "" : raw.slice(colon + 1).trim();
|
|
1698
|
+
optional = head.endsWith("?");
|
|
1699
|
+
const kind = head.replace(/\?+$/, "").trim();
|
|
1700
|
+
if (!INPUT_TYPES.includes(kind))
|
|
1701
|
+
throw new HookConfigError(
|
|
1702
|
+
`${position}.input.${name}: ${JSON.stringify(kind)} is not one of ${INPUT_TYPES.join(", ")} (add ? for optional)`
|
|
1703
|
+
);
|
|
1704
|
+
schema = { type: kind };
|
|
1705
|
+
if (description) schema.description = description;
|
|
1706
|
+
} else if (isObject2(raw)) {
|
|
1707
|
+
schema = Object.fromEntries(
|
|
1708
|
+
Object.entries(raw).filter(([k]) => k !== "optional")
|
|
1709
|
+
);
|
|
1710
|
+
optional = raw.optional === true;
|
|
1711
|
+
if (!("type" in schema))
|
|
1712
|
+
throw new HookConfigError(
|
|
1713
|
+
`${position}.input.${name}: a schema table needs \`type\``
|
|
1714
|
+
);
|
|
1715
|
+
} else
|
|
1716
|
+
throw new HookConfigError(
|
|
1717
|
+
`${position}.input.${name}: expected "type" or a schema table`
|
|
1718
|
+
);
|
|
1719
|
+
properties[name] = schema;
|
|
1720
|
+
if (!optional) required.push(name);
|
|
1721
|
+
}
|
|
1722
|
+
return { type: "object", properties, required };
|
|
1723
|
+
}
|
|
1724
|
+
function placeholders(value) {
|
|
1725
|
+
if (typeof value === "string")
|
|
1726
|
+
return [...value.matchAll(PLACEHOLDER)].map((m) => m[1]);
|
|
1727
|
+
if (Array.isArray(value)) return value.flatMap(placeholders);
|
|
1728
|
+
if (isObject2(value)) return Object.values(value).flatMap(placeholders);
|
|
1729
|
+
return [];
|
|
1730
|
+
}
|
|
1731
|
+
function parseLive(raw, toolsRaw) {
|
|
1732
|
+
if (!isObject2(raw)) throw new HookConfigError("`live` must be a table");
|
|
1733
|
+
const unknown = Object.keys(raw).filter(
|
|
1734
|
+
(k) => !["record", "replay", "allowed_env", "timeout"].includes(k)
|
|
1735
|
+
);
|
|
1736
|
+
if (unknown.length)
|
|
1737
|
+
throw new HookConfigError(
|
|
1738
|
+
`live: unknown key(s) ${unknown.sort().join(", ")}`
|
|
1739
|
+
);
|
|
1740
|
+
const allowed = typeof raw.allowed_env === "string" ? [raw.allowed_env] : raw.allowed_env ?? [];
|
|
1741
|
+
if (!Array.isArray(allowed) || !allowed.every((a) => typeof a === "string"))
|
|
1742
|
+
throw new HookConfigError(
|
|
1743
|
+
"live.allowed_env: expected a list of variable names"
|
|
1744
|
+
);
|
|
1745
|
+
for (const key2 of ["record", "replay"]) {
|
|
1746
|
+
if (raw[key2] !== void 0 && raw[key2] !== null && typeof raw[key2] !== "string")
|
|
1747
|
+
throw new HookConfigError(`live.${key2}: expected a file path`);
|
|
1748
|
+
}
|
|
1749
|
+
const timeout = raw.timeout ?? 45;
|
|
1750
|
+
if (typeof timeout !== "number" || !(timeout > 0))
|
|
1751
|
+
throw new HookConfigError(
|
|
1752
|
+
"live.timeout: expected a positive number of seconds"
|
|
1753
|
+
);
|
|
1754
|
+
if (!isObject2(toolsRaw))
|
|
1755
|
+
throw new HookConfigError("`tools` must be a table of [tools.<name>]");
|
|
1756
|
+
const tools = {};
|
|
1757
|
+
for (const [name, spec] of Object.entries(toolsRaw))
|
|
1758
|
+
tools[name] = parseTool(name, spec, allowed);
|
|
1759
|
+
return {
|
|
1760
|
+
...typeof raw.record === "string" && raw.record ? { record: raw.record } : {},
|
|
1761
|
+
...typeof raw.replay === "string" && raw.replay ? { replay: raw.replay } : {},
|
|
1762
|
+
allowedEnv: allowed,
|
|
1763
|
+
timeout,
|
|
1764
|
+
tools
|
|
1765
|
+
};
|
|
1766
|
+
}
|
|
1767
|
+
function parseTool(name, raw, allowedEnv) {
|
|
1768
|
+
const position = `tools.${name}`;
|
|
1769
|
+
if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(name))
|
|
1770
|
+
throw new HookConfigError(`${position}: a tool name is an identifier`);
|
|
1771
|
+
if (!isObject2(raw))
|
|
1772
|
+
throw new HookConfigError(`${position}: a tool is a table`);
|
|
1773
|
+
const kinds = [
|
|
1774
|
+
...["callable", "connector"].filter((k) => k in raw),
|
|
1775
|
+
..."url" in raw ? ["http"] : []
|
|
1776
|
+
];
|
|
1777
|
+
if (kinds.length !== 1)
|
|
1778
|
+
throw new HookConfigError(
|
|
1779
|
+
`${position}: declare exactly one of \`url\` (http), \`callable\`, or \`connector\` + \`operation\``
|
|
1780
|
+
);
|
|
1781
|
+
const kind = kinds[0];
|
|
1782
|
+
const description = raw.description ?? "";
|
|
1783
|
+
if (typeof description !== "string")
|
|
1784
|
+
throw new HookConfigError(`${position}.description: expected a string`);
|
|
1785
|
+
const schema = inputSchema(raw.input, position);
|
|
1786
|
+
const defaults = raw.defaults ?? {};
|
|
1787
|
+
if (!isObject2(defaults))
|
|
1788
|
+
throw new HookConfigError(
|
|
1789
|
+
`${position}.defaults: expected a table of field = value`
|
|
1790
|
+
);
|
|
1791
|
+
for (const key2 of Object.keys(defaults))
|
|
1792
|
+
if (!(key2 in schema.properties))
|
|
1793
|
+
throw new HookConfigError(
|
|
1794
|
+
`${position}.defaults.${key2}: not an input field`
|
|
1795
|
+
);
|
|
1796
|
+
const vendor = raw.vendor;
|
|
1797
|
+
if (vendor !== void 0 && (typeof vendor !== "string" || !vendor))
|
|
1798
|
+
throw new HookConfigError(`${position}.vendor: expected a vendor name`);
|
|
1799
|
+
const options = {};
|
|
1800
|
+
for (const [k, v] of Object.entries(raw))
|
|
1801
|
+
if (!COMMON_TOOL_KEYS.has(k)) options[k] = v;
|
|
1802
|
+
const fields = new Set(Object.keys(schema.properties));
|
|
1803
|
+
if (kind === "http") checkHttpTool(position, options, fields, allowedEnv);
|
|
1804
|
+
else if (kind === "callable") {
|
|
1805
|
+
const unknown = Object.keys(options).filter((k) => k !== "callable");
|
|
1806
|
+
if (unknown.length)
|
|
1807
|
+
throw new HookConfigError(
|
|
1808
|
+
`${position}: unknown key(s) ${unknown.sort().join(", ")}`
|
|
1809
|
+
);
|
|
1810
|
+
if (typeof options.callable !== "string" || !options.callable.includes("#"))
|
|
1811
|
+
throw new HookConfigError(
|
|
1812
|
+
`${position}.callable: expected "./module.js#exportName"`
|
|
1813
|
+
);
|
|
1814
|
+
} else {
|
|
1815
|
+
const unknown = Object.keys(options).filter(
|
|
1816
|
+
(k) => !["connector", "operation"].includes(k)
|
|
1817
|
+
);
|
|
1818
|
+
if (unknown.length)
|
|
1819
|
+
throw new HookConfigError(
|
|
1820
|
+
`${position}: unknown key(s) ${unknown.sort().join(", ")}`
|
|
1821
|
+
);
|
|
1822
|
+
if (typeof options.connector !== "string" || typeof options.operation !== "string")
|
|
1823
|
+
throw new HookConfigError(
|
|
1824
|
+
`${position}: a connector tool needs \`connector\` (a connector.toml or its directory) and \`operation\``
|
|
1825
|
+
);
|
|
1826
|
+
}
|
|
1827
|
+
return {
|
|
1828
|
+
name,
|
|
1829
|
+
kind,
|
|
1830
|
+
description,
|
|
1831
|
+
input: schema,
|
|
1832
|
+
options,
|
|
1833
|
+
defaults: { ...defaults },
|
|
1834
|
+
...typeof vendor === "string" ? { vendor } : {}
|
|
1835
|
+
};
|
|
1836
|
+
}
|
|
1837
|
+
function checkHttpTool(position, options, fields, allowedEnv) {
|
|
1838
|
+
const unknown = Object.keys(options).filter((k) => !HTTP_TOOL_KEYS.has(k));
|
|
1839
|
+
if (unknown.length)
|
|
1840
|
+
throw new HookConfigError(
|
|
1841
|
+
`${position}: unknown key(s) ${unknown.sort().join(", ")}`
|
|
1842
|
+
);
|
|
1843
|
+
const method = options.method ?? "GET";
|
|
1844
|
+
if (method !== "GET" && method !== "POST")
|
|
1845
|
+
throw new HookConfigError(`${position}.method: expected GET or POST`);
|
|
1846
|
+
options.method = method;
|
|
1847
|
+
const url = options.url;
|
|
1848
|
+
if (typeof url !== "string" || !(/^https?:\/\//.test(url) || /^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(url)))
|
|
1849
|
+
throw new HookConfigError(
|
|
1850
|
+
`${position}.url: expected an http(s) URL template, or a single {field} holding one`
|
|
1851
|
+
);
|
|
1852
|
+
if (options.body !== void 0 && options.body !== null && method !== "POST")
|
|
1853
|
+
throw new HookConfigError(`${position}: \`body\` needs method = "POST"`);
|
|
1854
|
+
const headers = options.headers ?? {};
|
|
1855
|
+
if (!isObject2(headers) || !Object.values(headers).every((v) => typeof v === "string"))
|
|
1856
|
+
throw new HookConfigError(
|
|
1857
|
+
`${position}.headers: expected a table of string values`
|
|
1858
|
+
);
|
|
1859
|
+
for (const [header, value] of Object.entries(headers)) {
|
|
1860
|
+
for (const match of value.matchAll(ENV_REF)) {
|
|
1861
|
+
if (!allowedEnv.includes(match[1]))
|
|
1862
|
+
throw new HookConfigError(
|
|
1863
|
+
`${position}.headers.${header}: $${match[1]} is not in live.allowed_env`
|
|
1864
|
+
);
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
const parse = options.parse ?? "json";
|
|
1868
|
+
if (!PARSE_MODES.includes(parse))
|
|
1869
|
+
throw new HookConfigError(
|
|
1870
|
+
`${position}.parse: expected one of ${PARSE_MODES.join(", ")}`
|
|
1871
|
+
);
|
|
1872
|
+
options.parse = parse;
|
|
1873
|
+
if (parse === "regex") {
|
|
1874
|
+
const pattern = options.pattern;
|
|
1875
|
+
if (typeof pattern !== "string" || !pattern)
|
|
1876
|
+
throw new HookConfigError(
|
|
1877
|
+
`${position}: parse = "regex" needs \`pattern\` with named groups`
|
|
1878
|
+
);
|
|
1879
|
+
let compiled;
|
|
1880
|
+
try {
|
|
1881
|
+
compiled = new RegExp(jsPattern(pattern), "gis");
|
|
1882
|
+
} catch (error) {
|
|
1883
|
+
throw new HookConfigError(
|
|
1884
|
+
`${position}.pattern: not a regular expression \u2014 ${error.message}`
|
|
1885
|
+
);
|
|
1886
|
+
}
|
|
1887
|
+
if (!/\(\?<[A-Za-z_]/.test(compiled.source))
|
|
1888
|
+
throw new HookConfigError(
|
|
1889
|
+
`${position}.pattern: needs at least one named group ((?<name>...))`
|
|
1890
|
+
);
|
|
1891
|
+
} else if ("pattern" in options)
|
|
1892
|
+
throw new HookConfigError(
|
|
1893
|
+
`${position}: \`pattern\` applies to parse = "regex" only`
|
|
1894
|
+
);
|
|
1895
|
+
if (parse === "text") {
|
|
1896
|
+
for (const key2 of ["results", "fields", "limit"])
|
|
1897
|
+
if (key2 in options)
|
|
1898
|
+
throw new HookConfigError(
|
|
1899
|
+
`${position}: \`${key2}\` does not apply to parse = "text"`
|
|
1900
|
+
);
|
|
1901
|
+
const maxBytes = options.max_bytes ?? 2e5;
|
|
1902
|
+
if (typeof maxBytes !== "number" || !Number.isInteger(maxBytes) || maxBytes < 1)
|
|
1903
|
+
throw new HookConfigError(
|
|
1904
|
+
`${position}.max_bytes: expected a positive integer`
|
|
1905
|
+
);
|
|
1906
|
+
options.max_bytes = maxBytes;
|
|
1907
|
+
} else if ("max_bytes" in options)
|
|
1908
|
+
throw new HookConfigError(
|
|
1909
|
+
`${position}: \`max_bytes\` applies to parse = "text" only`
|
|
1910
|
+
);
|
|
1911
|
+
if ("results" in options && (parse !== "json" || typeof options.results !== "string"))
|
|
1912
|
+
throw new HookConfigError(
|
|
1913
|
+
`${position}.results: a JSON path such as $.items[*], for parse = "json" only`
|
|
1914
|
+
);
|
|
1915
|
+
const fieldMap = options.fields ?? {};
|
|
1916
|
+
if (!isObject2(fieldMap))
|
|
1917
|
+
throw new HookConfigError(
|
|
1918
|
+
`${position}.fields: expected a table of result field = item path (or { from, query_param })`
|
|
1919
|
+
);
|
|
1920
|
+
for (const [outName, source] of Object.entries(fieldMap)) {
|
|
1921
|
+
if (isObject2(source)) {
|
|
1922
|
+
if (Object.keys(source).some((k) => !["from", "query_param"].includes(k)) || typeof source.from !== "string")
|
|
1923
|
+
throw new HookConfigError(
|
|
1924
|
+
`${position}.fields.${outName}: a table needs \`from\` and may add \`query_param\``
|
|
1925
|
+
);
|
|
1926
|
+
} else if (typeof source !== "string")
|
|
1927
|
+
throw new HookConfigError(
|
|
1928
|
+
`${position}.fields.${outName}: expected an item path`
|
|
1929
|
+
);
|
|
1930
|
+
}
|
|
1931
|
+
const limit = options.limit;
|
|
1932
|
+
if (limit !== void 0 && limit !== null && !(typeof limit === "number" && Number.isInteger(limit) && limit > 0) && !(typeof limit === "string" && /^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(limit)))
|
|
1933
|
+
throw new HookConfigError(
|
|
1934
|
+
`${position}.limit: expected a positive integer or one {field}`
|
|
1935
|
+
);
|
|
1936
|
+
if (options.strip_html !== void 0 && typeof options.strip_html !== "boolean")
|
|
1937
|
+
throw new HookConfigError(`${position}.strip_html: expected true or false`);
|
|
1938
|
+
options.ok_status = parseOkStatus(options.ok_status, position);
|
|
1939
|
+
const failIf = options.fail_if;
|
|
1940
|
+
if (failIf !== void 0 && failIf !== null) {
|
|
1941
|
+
if (typeof failIf !== "string" || !failIf)
|
|
1942
|
+
throw new HookConfigError(
|
|
1943
|
+
`${position}.fail_if: expected a regular expression`
|
|
1944
|
+
);
|
|
1945
|
+
try {
|
|
1946
|
+
new RegExp(jsPattern(failIf), "si");
|
|
1947
|
+
} catch (error) {
|
|
1948
|
+
throw new HookConfigError(
|
|
1949
|
+
`${position}.fail_if: not a regular expression \u2014 ${error.message}`
|
|
1950
|
+
);
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
const interval = options.min_interval_ms;
|
|
1954
|
+
if (interval !== void 0 && interval !== null && (typeof interval !== "number" || !(interval >= 0)))
|
|
1955
|
+
throw new HookConfigError(
|
|
1956
|
+
`${position}.min_interval_ms: expected milliseconds (0 or more)`
|
|
1957
|
+
);
|
|
1958
|
+
const used = /* @__PURE__ */ new Set([
|
|
1959
|
+
...placeholders(url),
|
|
1960
|
+
...placeholders(options.body),
|
|
1961
|
+
...placeholders(limit)
|
|
1962
|
+
]);
|
|
1963
|
+
const unknownFields = [...used].filter((f) => !fields.has(f));
|
|
1964
|
+
if (unknownFields.length)
|
|
1965
|
+
throw new HookConfigError(
|
|
1966
|
+
`${position}: template field(s) ${unknownFields.sort().join(", ")} are not declared in \`input\``
|
|
1967
|
+
);
|
|
1968
|
+
}
|
|
1969
|
+
var emptyConfig = () => ({
|
|
1970
|
+
rules: [],
|
|
1971
|
+
aliasSlugs: [],
|
|
1972
|
+
aliasPublicLayerWins: true,
|
|
1973
|
+
aliasPublicMailboxDomains: null,
|
|
1974
|
+
aliasMintInbound: [],
|
|
1975
|
+
aliasLegend: null,
|
|
1976
|
+
vendors: {},
|
|
1977
|
+
live: emptyLive()
|
|
1978
|
+
});
|
|
1979
|
+
function describeHandler(spec) {
|
|
1980
|
+
switch (spec.type) {
|
|
1981
|
+
case "command": {
|
|
1982
|
+
const args = spec.options.args;
|
|
1983
|
+
return `command ${spec.options.command}${args?.length ? " " + args.join(" ") : ""}`;
|
|
1984
|
+
}
|
|
1985
|
+
case "http":
|
|
1986
|
+
return `http ${spec.options.url}`;
|
|
1987
|
+
case "callable":
|
|
1988
|
+
return `callable ${spec.options.target}`;
|
|
1989
|
+
case "alias": {
|
|
1990
|
+
const bits = ["direction", "check"].filter((k) => k in spec.options).map((k) => `${k}=${spec.options[k]}`);
|
|
1991
|
+
return "alias" + (bits.length ? " " + bits.join(" ") : "");
|
|
1992
|
+
}
|
|
1993
|
+
case "record":
|
|
1994
|
+
return `record -> ${spec.options.sink}`;
|
|
1995
|
+
case "deny":
|
|
1996
|
+
return `deny: ${spec.options.reason ?? "denied by rule"}`;
|
|
1997
|
+
case "redact": {
|
|
1998
|
+
const bits = [];
|
|
1999
|
+
const kinds = spec.options.kinds;
|
|
2000
|
+
const patterns = spec.options.patterns;
|
|
2001
|
+
const values = spec.options.values;
|
|
2002
|
+
if (kinds?.length) bits.push(`kinds=${kinds.join(",")}`);
|
|
2003
|
+
if (values?.length) bits.push(`values=${values.length}`);
|
|
2004
|
+
if (patterns?.length) bits.push(`patterns=${patterns.length}`);
|
|
2005
|
+
return "redact " + bits.join(" ");
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
var isRewriter = (spec) => spec.type === "alias" || spec.type === "redact";
|
|
2010
|
+
function vendorOf(config, toolName) {
|
|
2011
|
+
for (const [vendor, patterns] of Object.entries(config.vendors)) {
|
|
2012
|
+
if (patterns.some((pattern) => new RegExp(pattern).test(toolName)))
|
|
2013
|
+
return vendor;
|
|
2014
|
+
}
|
|
2015
|
+
return void 0;
|
|
2016
|
+
}
|
|
2017
|
+
function loadHookConfig(file) {
|
|
2018
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile())
|
|
2019
|
+
throw new HookConfigError(`${file}: no such file`);
|
|
2020
|
+
const text = fs.readFileSync(file, "utf8");
|
|
2021
|
+
if (file.toLowerCase().endsWith(".json")) {
|
|
2022
|
+
let data2;
|
|
2023
|
+
try {
|
|
2024
|
+
data2 = JSON.parse(text);
|
|
2025
|
+
} catch (error) {
|
|
2026
|
+
throw new HookConfigError(
|
|
2027
|
+
`${file}: not JSON \u2014 ${error.message}`
|
|
2028
|
+
);
|
|
2029
|
+
}
|
|
2030
|
+
return parseHookConfig(data2, file);
|
|
2031
|
+
}
|
|
2032
|
+
let data;
|
|
2033
|
+
try {
|
|
2034
|
+
data = parseToml(text);
|
|
2035
|
+
} catch (tomlError) {
|
|
2036
|
+
try {
|
|
2037
|
+
data = JSON.parse(text);
|
|
2038
|
+
} catch {
|
|
2039
|
+
const detail = tomlError instanceof TomlError ? tomlError.message : String(tomlError);
|
|
2040
|
+
throw new HookConfigError(`${file}: not TOML \u2014 ${detail}`);
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
return parseHookConfig(data, file);
|
|
2044
|
+
}
|
|
2045
|
+
var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2046
|
+
function parseHookConfig(data, source) {
|
|
2047
|
+
const where = source ?? "config";
|
|
2048
|
+
if (!isObject2(data))
|
|
2049
|
+
throw new HookConfigError(`${where}: expected a table at the top level`);
|
|
2050
|
+
const unknown = Object.keys(data).filter(
|
|
2051
|
+
(k) => !["hooks", "alias", "vendors", "live", "tools"].includes(k)
|
|
2052
|
+
);
|
|
2053
|
+
if (unknown.length)
|
|
2054
|
+
throw new HookConfigError(
|
|
2055
|
+
`${where}: unknown top-level key(s) ${unknown.sort().join(", ")}`
|
|
2056
|
+
);
|
|
2057
|
+
const hooks = data.hooks ?? {};
|
|
2058
|
+
if (!isObject2(hooks))
|
|
2059
|
+
throw new HookConfigError(`${where}: \`hooks\` must be a table of events`);
|
|
2060
|
+
const rules = [];
|
|
2061
|
+
for (const [rawEvent, rawRules] of Object.entries(hooks)) {
|
|
2062
|
+
const event = normalizeEvent(rawEvent);
|
|
2063
|
+
if (!event)
|
|
2064
|
+
throw new HookConfigError(
|
|
2065
|
+
`hooks.${rawEvent}: unknown event; expected one of ${EVENTS.join(", ")} (or PreToolUse, PostToolUse, Stop)`
|
|
2066
|
+
);
|
|
2067
|
+
const list = isObject2(rawRules) ? [rawRules] : rawRules;
|
|
2068
|
+
if (!Array.isArray(list))
|
|
2069
|
+
throw new HookConfigError(
|
|
2070
|
+
`hooks.${rawEvent}: expected an array of rules ([[hooks.${rawEvent}]])`
|
|
2071
|
+
);
|
|
2072
|
+
list.forEach(
|
|
2073
|
+
(raw, index2) => rules.push(parseRule(event, raw, `hooks.${rawEvent}[${index2}]`))
|
|
2074
|
+
);
|
|
2075
|
+
}
|
|
2076
|
+
const alias = data.alias ?? {};
|
|
2077
|
+
if (!isObject2(alias)) throw new HookConfigError("`alias` must be a table");
|
|
2078
|
+
const slugsRaw = typeof alias.slugs === "string" ? [alias.slugs] : alias.slugs ?? [];
|
|
2079
|
+
if (!Array.isArray(slugsRaw) || !slugsRaw.every((s) => typeof s === "string"))
|
|
2080
|
+
throw new HookConfigError("alias.slugs must be a list of connector slugs");
|
|
2081
|
+
const unknownAlias = Object.keys(alias).filter(
|
|
2082
|
+
(k) => ![
|
|
2083
|
+
"slugs",
|
|
2084
|
+
"public_layer_wins",
|
|
2085
|
+
"public_mailbox_domains",
|
|
2086
|
+
"mint_inbound",
|
|
2087
|
+
"legend"
|
|
2088
|
+
].includes(k)
|
|
2089
|
+
);
|
|
2090
|
+
if (unknownAlias.length)
|
|
2091
|
+
throw new HookConfigError(
|
|
2092
|
+
`alias: unknown keys ${JSON.stringify(unknownAlias.sort())}`
|
|
2093
|
+
);
|
|
2094
|
+
const publicLayerWins = alias.public_layer_wins ?? true;
|
|
2095
|
+
if (typeof publicLayerWins !== "boolean")
|
|
2096
|
+
throw new HookConfigError("alias.public_layer_wins must be true or false");
|
|
2097
|
+
const mailbox = alias.public_mailbox_domains ?? null;
|
|
2098
|
+
if (mailbox !== null && (!Array.isArray(mailbox) || !mailbox.every((d) => typeof d === "string")))
|
|
2099
|
+
throw new HookConfigError(
|
|
2100
|
+
"alias.public_mailbox_domains must be a list of domains ([] keeps none real; omit it for the built-in free-mail list)"
|
|
2101
|
+
);
|
|
2102
|
+
const mintInboundRaw = typeof alias.mint_inbound === "string" ? [alias.mint_inbound] : alias.mint_inbound ?? [];
|
|
2103
|
+
if (!Array.isArray(mintInboundRaw) || !mintInboundRaw.every((k) => typeof k === "string"))
|
|
2104
|
+
throw new HookConfigError(
|
|
2105
|
+
`alias.mint_inbound must be a list of kinds from ${INBOUND_KINDS.join(", ")}`
|
|
2106
|
+
);
|
|
2107
|
+
const badKinds = mintInboundRaw.filter(
|
|
2108
|
+
(k) => !INBOUND_KINDS.includes(k)
|
|
2109
|
+
);
|
|
2110
|
+
if (badKinds.length)
|
|
2111
|
+
throw new HookConfigError(
|
|
2112
|
+
`alias.mint_inbound: ${badKinds.join(", ")} cannot be found by a pattern; only ${INBOUND_KINDS.join(", ")} can (a name or a handle is seeded, never guessed)`
|
|
2113
|
+
);
|
|
2114
|
+
const legendPath = alias.legend ?? null;
|
|
2115
|
+
if (legendPath !== null && (typeof legendPath !== "string" || !legendPath.trim()))
|
|
2116
|
+
throw new HookConfigError(
|
|
2117
|
+
"alias.legend must be a file path (may carry {run_dir} and {run_id})"
|
|
2118
|
+
);
|
|
2119
|
+
const vendorsRaw = data.vendors ?? {};
|
|
2120
|
+
if (!isObject2(vendorsRaw))
|
|
2121
|
+
throw new HookConfigError(
|
|
2122
|
+
'`vendors` must be a table of vendor = "pattern | pattern"'
|
|
2123
|
+
);
|
|
2124
|
+
const vendors = {};
|
|
2125
|
+
for (const [vendor, patterns] of Object.entries(vendorsRaw)) {
|
|
2126
|
+
if (typeof patterns !== "string" && !(Array.isArray(patterns) && patterns.every((p) => typeof p === "string")))
|
|
2127
|
+
throw new HookConfigError(
|
|
2128
|
+
`vendors.${vendor}: expected a pattern string or a list of patterns`
|
|
2129
|
+
);
|
|
2130
|
+
try {
|
|
2131
|
+
vendors[vendor] = [
|
|
2132
|
+
...parseMatcher(patterns).patterns
|
|
2133
|
+
];
|
|
2134
|
+
} catch (error) {
|
|
2135
|
+
throw new HookConfigError(
|
|
2136
|
+
`vendors.${vendor}: ${error.message}`
|
|
2137
|
+
);
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
return {
|
|
2141
|
+
rules,
|
|
2142
|
+
aliasSlugs: slugsRaw,
|
|
2143
|
+
aliasPublicLayerWins: publicLayerWins,
|
|
2144
|
+
aliasPublicMailboxDomains: mailbox,
|
|
2145
|
+
aliasMintInbound: mintInboundRaw,
|
|
2146
|
+
aliasLegend: legendPath,
|
|
2147
|
+
vendors,
|
|
2148
|
+
live: parseLive(data.live ?? {}, data.tools ?? {}),
|
|
2149
|
+
...source ? { source } : {}
|
|
2150
|
+
};
|
|
2151
|
+
}
|
|
2152
|
+
function parseRule(event, raw, position) {
|
|
2153
|
+
if (!isObject2(raw))
|
|
2154
|
+
throw new HookConfigError(`${position}: a rule is a table`);
|
|
2155
|
+
const unknown = Object.keys(raw).filter(
|
|
2156
|
+
(k) => !["matcher", "vendor", "arg", "handlers", "hooks"].includes(k)
|
|
2157
|
+
);
|
|
2158
|
+
if (unknown.length)
|
|
2159
|
+
throw new HookConfigError(
|
|
2160
|
+
`${position}: unknown key(s) ${unknown.sort().join(", ")}`
|
|
2161
|
+
);
|
|
2162
|
+
const matcherRaw = raw.matcher;
|
|
2163
|
+
if (matcherRaw !== void 0 && typeof matcherRaw !== "string" && !Array.isArray(matcherRaw))
|
|
2164
|
+
throw new HookConfigError(
|
|
2165
|
+
`${position}.matcher: expected a string (\`A | B\`) or a list of patterns`
|
|
2166
|
+
);
|
|
2167
|
+
if (raw.vendor !== void 0 && typeof raw.vendor !== "string")
|
|
2168
|
+
throw new HookConfigError(`${position}.vendor: expected a string`);
|
|
2169
|
+
if (raw.arg !== void 0 && typeof raw.arg !== "string" && !Array.isArray(raw.arg))
|
|
2170
|
+
throw new HookConfigError(`${position}.arg: expected a string or a list`);
|
|
2171
|
+
let matcher;
|
|
2172
|
+
try {
|
|
2173
|
+
matcher = parseMatcher(matcherRaw, {
|
|
2174
|
+
vendor: raw.vendor,
|
|
2175
|
+
arg: raw.arg
|
|
2176
|
+
});
|
|
2177
|
+
} catch (error) {
|
|
2178
|
+
throw new HookConfigError(
|
|
2179
|
+
`${position}.matcher: ${error.message}`
|
|
2180
|
+
);
|
|
2181
|
+
}
|
|
2182
|
+
const handlersRaw = raw.handlers ?? raw.hooks;
|
|
2183
|
+
const list = isObject2(handlersRaw) ? [handlersRaw] : handlersRaw;
|
|
2184
|
+
if (!Array.isArray(list) || !list.length)
|
|
2185
|
+
throw new HookConfigError(
|
|
2186
|
+
`${position}.handlers: expected a non-empty array of handler tables`
|
|
2187
|
+
);
|
|
2188
|
+
const handlers = list.map(
|
|
2189
|
+
(h, i) => parseHandler(event, h, `${position}.handlers[${i}]`)
|
|
2190
|
+
);
|
|
2191
|
+
const rewriters = handlers.filter(isRewriter);
|
|
2192
|
+
if (rewriters.length > 1)
|
|
2193
|
+
throw new HookConfigError(
|
|
2194
|
+
`${position}: ${rewriters.length} handlers rewrite the same event (${rewriters.map(describeHandler).join(", ")}); at most one handler per matcher may rewrite \u2014 put the second under its own [[hooks.${event}]]`
|
|
2195
|
+
);
|
|
2196
|
+
return { event, matcher, handlers, position };
|
|
2197
|
+
}
|
|
2198
|
+
function parseHandler(event, raw, position) {
|
|
2199
|
+
if (!isObject2(raw))
|
|
2200
|
+
throw new HookConfigError(
|
|
2201
|
+
`${position}: a handler is a table with a \`type\``
|
|
2202
|
+
);
|
|
2203
|
+
const kind = raw.type;
|
|
2204
|
+
if (!HANDLER_TYPES.includes(kind))
|
|
2205
|
+
throw new HookConfigError(
|
|
2206
|
+
`${position}.type: ${JSON.stringify(kind)} is not one of ${HANDLER_TYPES.join(", ")}`
|
|
2207
|
+
);
|
|
2208
|
+
const type = kind;
|
|
2209
|
+
const options = {};
|
|
2210
|
+
for (const [k, v] of Object.entries(raw))
|
|
2211
|
+
if (!COMMON_HANDLER_KEYS.has(k)) options[k] = v;
|
|
2212
|
+
if (raw.name !== void 0 && typeof raw.name !== "string")
|
|
2213
|
+
throw new HookConfigError(`${position}.name: expected a string`);
|
|
2214
|
+
const background = raw.async ?? false;
|
|
2215
|
+
if (typeof background !== "boolean")
|
|
2216
|
+
throw new HookConfigError(`${position}.async: expected true or false`);
|
|
2217
|
+
let timeout = raw.timeout;
|
|
2218
|
+
if (timeout !== void 0 && (typeof timeout !== "number" || !(timeout > 0)))
|
|
2219
|
+
throw new HookConfigError(
|
|
2220
|
+
`${position}.timeout: expected a positive number of seconds`
|
|
2221
|
+
);
|
|
2222
|
+
if (timeout === void 0)
|
|
2223
|
+
timeout = event === "run_end" && type in DEFAULT_TIMEOUTS ? RUN_END_TIMEOUT : DEFAULT_TIMEOUTS[type];
|
|
2224
|
+
let defaultName;
|
|
2225
|
+
switch (type) {
|
|
2226
|
+
case "command": {
|
|
2227
|
+
const command = options.command;
|
|
2228
|
+
if (typeof command !== "string" || !command.trim())
|
|
2229
|
+
throw new HookConfigError(
|
|
2230
|
+
`${position}: a command handler needs \`command\` (a string; add \`args\` for the exec form)`
|
|
2231
|
+
);
|
|
2232
|
+
const args = options.args;
|
|
2233
|
+
if (args !== void 0 && !(Array.isArray(args) && args.every((a) => typeof a === "string")))
|
|
2234
|
+
throw new HookConfigError(
|
|
2235
|
+
`${position}.args: expected a list of strings`
|
|
2236
|
+
);
|
|
2237
|
+
if (options.cwd !== void 0 && typeof options.cwd !== "string")
|
|
2238
|
+
throw new HookConfigError(`${position}.cwd: expected a string`);
|
|
2239
|
+
defaultName = `command:${command.trim().split(/\s+/)[0].split("/").pop()}`;
|
|
2240
|
+
break;
|
|
2241
|
+
}
|
|
2242
|
+
case "http": {
|
|
2243
|
+
const url = options.url;
|
|
2244
|
+
if (typeof url !== "string" || !/^https?:\/\//.test(url))
|
|
2245
|
+
throw new HookConfigError(
|
|
2246
|
+
`${position}: an http handler needs \`url\` (http:// or https://)`
|
|
2247
|
+
);
|
|
2248
|
+
const headers = options.headers ?? {};
|
|
2249
|
+
if (!isObject2(headers) || !Object.values(headers).every((v) => typeof v === "string"))
|
|
2250
|
+
throw new HookConfigError(
|
|
2251
|
+
`${position}.headers: expected a table of string values`
|
|
2252
|
+
);
|
|
2253
|
+
const allowed = options.allowed_env ?? [];
|
|
2254
|
+
if (!Array.isArray(allowed) || !allowed.every((a) => typeof a === "string"))
|
|
2255
|
+
throw new HookConfigError(
|
|
2256
|
+
`${position}.allowed_env: expected a list of variable names`
|
|
2257
|
+
);
|
|
2258
|
+
defaultName = `http:${url}`;
|
|
2259
|
+
break;
|
|
2260
|
+
}
|
|
2261
|
+
case "callable": {
|
|
2262
|
+
const target = options.target;
|
|
2263
|
+
if (typeof target !== "string" || !target.includes("#"))
|
|
2264
|
+
throw new HookConfigError(
|
|
2265
|
+
`${position}: a callable handler needs \`target = "./module.js#exportName"\``
|
|
2266
|
+
);
|
|
2267
|
+
defaultName = `callable:${target}`;
|
|
2268
|
+
break;
|
|
2269
|
+
}
|
|
2270
|
+
case "record": {
|
|
2271
|
+
if (event !== "post_tool_call" && event !== "post_response")
|
|
2272
|
+
throw new HookConfigError(
|
|
2273
|
+
`${position}: \`record\` writes a call and its result, so it belongs on post_tool_call or post_response, not ${event}`
|
|
2274
|
+
);
|
|
2275
|
+
if (typeof options.sink !== "string" || !options.sink.trim())
|
|
2276
|
+
throw new HookConfigError(
|
|
2277
|
+
`${position}: a record handler needs \`sink\` (a JSONL file path)`
|
|
2278
|
+
);
|
|
2279
|
+
defaultName = "record";
|
|
2280
|
+
break;
|
|
2281
|
+
}
|
|
2282
|
+
case "alias": {
|
|
2283
|
+
const direction = options.direction;
|
|
2284
|
+
if (direction !== void 0 && direction !== "in" && direction !== "out")
|
|
2285
|
+
throw new HookConfigError(`${position}.direction: expected in or out`);
|
|
2286
|
+
const check = options.check;
|
|
2287
|
+
if (check !== void 0 && check !== "outgoing")
|
|
2288
|
+
throw new HookConfigError(`${position}.check: expected outgoing`);
|
|
2289
|
+
if (event === "run_end" && direction !== void 0)
|
|
2290
|
+
throw new HookConfigError(
|
|
2291
|
+
`${position}: on run_end the alias handler scans outgoing text; \`direction\` does not apply`
|
|
2292
|
+
);
|
|
2293
|
+
if (event !== "run_end" && check !== void 0)
|
|
2294
|
+
throw new HookConfigError(
|
|
2295
|
+
`${position}: \`check = "outgoing"\` applies to run_end only`
|
|
2296
|
+
);
|
|
2297
|
+
const expected = event === "pre_tool_call" || event === "pre_request" ? "out" : "in";
|
|
2298
|
+
if (event !== "run_end" && direction !== void 0 && direction !== expected)
|
|
2299
|
+
throw new HookConfigError(
|
|
2300
|
+
`${position}: direction=${direction} on ${event} would send ${direction === "in" ? "real values to the agent" : "aliases to the world"}; ${event} rewrites ${expected}`
|
|
2301
|
+
);
|
|
2302
|
+
if (background)
|
|
2303
|
+
throw new HookConfigError(
|
|
2304
|
+
`${position}: the alias handler rewrites the call; it cannot be async`
|
|
2305
|
+
);
|
|
2306
|
+
const args = options.args;
|
|
2307
|
+
if (args !== void 0 && args !== "alias" && args !== "keep")
|
|
2308
|
+
throw new HookConfigError(
|
|
2309
|
+
`${position}.args: expected alias (rewrite the recorded arguments) or keep`
|
|
2310
|
+
);
|
|
2311
|
+
if (args !== void 0 && event !== "post_tool_call")
|
|
2312
|
+
throw new HookConfigError(
|
|
2313
|
+
`${position}: \`args\` applies to post_tool_call only`
|
|
2314
|
+
);
|
|
2315
|
+
defaultName = "alias";
|
|
2316
|
+
break;
|
|
2317
|
+
}
|
|
2318
|
+
case "redact": {
|
|
2319
|
+
if (event !== "post_tool_call" && event !== "post_response")
|
|
2320
|
+
throw new HookConfigError(
|
|
2321
|
+
`${position}: \`redact\` removes values from what comes back, so it belongs on post_tool_call or post_response, not ${event}`
|
|
2322
|
+
);
|
|
2323
|
+
const kinds = typeof options.kinds === "string" ? [options.kinds] : options.kinds ?? [];
|
|
2324
|
+
if (!Array.isArray(kinds) || !kinds.every((k) => typeof k === "string"))
|
|
2325
|
+
throw new HookConfigError(
|
|
2326
|
+
`${position}.kinds: expected a list of kinds from ${INBOUND_KINDS.join(", ")}`
|
|
2327
|
+
);
|
|
2328
|
+
const bad = kinds.filter(
|
|
2329
|
+
(k) => !INBOUND_KINDS.includes(k)
|
|
2330
|
+
);
|
|
2331
|
+
if (bad.length)
|
|
2332
|
+
throw new HookConfigError(
|
|
2333
|
+
`${position}.kinds: ${bad.join(", ")} cannot be found by a pattern; only ${INBOUND_KINDS.join(", ")} can`
|
|
2334
|
+
);
|
|
2335
|
+
const patterns = typeof options.patterns === "string" ? [options.patterns] : options.patterns ?? [];
|
|
2336
|
+
if (!Array.isArray(patterns) || !patterns.every((x) => typeof x === "string"))
|
|
2337
|
+
throw new HookConfigError(
|
|
2338
|
+
`${position}.patterns: expected a list of regular expressions`
|
|
2339
|
+
);
|
|
2340
|
+
for (const pattern of patterns) {
|
|
2341
|
+
try {
|
|
2342
|
+
new RegExp(pattern);
|
|
2343
|
+
} catch (error) {
|
|
2344
|
+
throw new HookConfigError(
|
|
2345
|
+
`${position}.patterns: ${JSON.stringify(pattern)} is not a regular expression (${error.message})`
|
|
2346
|
+
);
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
const values = typeof options.values === "string" ? [options.values] : options.values ?? [];
|
|
2350
|
+
if (!Array.isArray(values) || !values.every((v) => typeof v === "string" && v.trim()))
|
|
2351
|
+
throw new HookConfigError(
|
|
2352
|
+
`${position}.values: expected a list of non-empty strings (removed wherever they appear, any case)`
|
|
2353
|
+
);
|
|
2354
|
+
if (!kinds.length && !patterns.length && !values.length)
|
|
2355
|
+
throw new HookConfigError(
|
|
2356
|
+
`${position}: a redact handler needs \`kinds\`, \`values\` and/or \`patterns\``
|
|
2357
|
+
);
|
|
2358
|
+
const token = options.token ?? "[redacted {kind}]";
|
|
2359
|
+
if (typeof token !== "string")
|
|
2360
|
+
throw new HookConfigError(
|
|
2361
|
+
`${position}.token: expected a string (may carry {kind})`
|
|
2362
|
+
);
|
|
2363
|
+
if (background)
|
|
2364
|
+
throw new HookConfigError(
|
|
2365
|
+
`${position}: a redact handler rewrites the result; it cannot be async`
|
|
2366
|
+
);
|
|
2367
|
+
options.kinds = kinds;
|
|
2368
|
+
options.values = values;
|
|
2369
|
+
options.patterns = patterns;
|
|
2370
|
+
options.token = token;
|
|
2371
|
+
defaultName = "redact";
|
|
2372
|
+
break;
|
|
2373
|
+
}
|
|
2374
|
+
case "deny": {
|
|
2375
|
+
if (options.reason !== void 0 && typeof options.reason !== "string")
|
|
2376
|
+
throw new HookConfigError(`${position}.reason: expected a string`);
|
|
2377
|
+
if (event === "post_tool_call" || event === "post_response")
|
|
2378
|
+
throw new HookConfigError(
|
|
2379
|
+
`${position}: \`deny\` refuses a call before it runs (or fails the run on run_end); it belongs on pre_tool_call, pre_request or run_end`
|
|
2380
|
+
);
|
|
2381
|
+
if (background)
|
|
2382
|
+
throw new HookConfigError(
|
|
2383
|
+
`${position}: a deny handler decides the call; it cannot be async`
|
|
2384
|
+
);
|
|
2385
|
+
defaultName = "deny";
|
|
2386
|
+
break;
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
return {
|
|
2390
|
+
type,
|
|
2391
|
+
name: raw.name ?? defaultName,
|
|
2392
|
+
options,
|
|
2393
|
+
...timeout !== void 0 ? { timeout } : {},
|
|
2394
|
+
background
|
|
2395
|
+
};
|
|
2396
|
+
}
|
|
2397
|
+
|
|
2398
|
+
// src/hooks/handlers.ts
|
|
2399
|
+
var import_node_child_process = require("child_process");
|
|
2400
|
+
var fs2 = __toESM(require("fs"));
|
|
2401
|
+
var path = __toESM(require("path"));
|
|
2402
|
+
var import_node_url = require("url");
|
|
2403
|
+
function parseStdout(text, handler) {
|
|
2404
|
+
const stripped = text.trim();
|
|
2405
|
+
if (!stripped) return allow();
|
|
2406
|
+
if (stripped.startsWith("{")) {
|
|
2407
|
+
let raw;
|
|
2408
|
+
try {
|
|
2409
|
+
raw = JSON.parse(stripped);
|
|
2410
|
+
} catch (error) {
|
|
2411
|
+
throw new Error(
|
|
2412
|
+
`stdout starts like JSON but is not (${error.message}): ${stripped.slice(0, 200)}`
|
|
2413
|
+
);
|
|
2414
|
+
}
|
|
2415
|
+
return resultFromJson(raw, handler);
|
|
2416
|
+
}
|
|
2417
|
+
return allow({ additional_context: stripped });
|
|
2418
|
+
}
|
|
2419
|
+
var CommandHandler = class {
|
|
2420
|
+
constructor(command, opts = {}) {
|
|
2421
|
+
this.command = command;
|
|
2422
|
+
this.opts = opts;
|
|
2423
|
+
}
|
|
2424
|
+
describe() {
|
|
2425
|
+
return `command ${this.command}${this.opts.args?.length ? " " + this.opts.args.join(" ") : ""}`;
|
|
2426
|
+
}
|
|
2427
|
+
run(event) {
|
|
2428
|
+
const input = JSON.stringify(eventToJson(event));
|
|
2429
|
+
const exec = this.opts.args !== void 0;
|
|
2430
|
+
return new Promise((resolve4, reject) => {
|
|
2431
|
+
let child;
|
|
2432
|
+
try {
|
|
2433
|
+
child = exec ? (0, import_node_child_process.spawn)(this.command, this.opts.args, {
|
|
2434
|
+
cwd: this.opts.cwd,
|
|
2435
|
+
env: this.opts.env ?? process.env,
|
|
2436
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2437
|
+
}) : (0, import_node_child_process.spawn)(this.command, {
|
|
2438
|
+
shell: true,
|
|
2439
|
+
cwd: this.opts.cwd,
|
|
2440
|
+
env: this.opts.env ?? process.env,
|
|
2441
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2442
|
+
});
|
|
2443
|
+
} catch (error) {
|
|
2444
|
+
reject(new Error(`could not start: ${error.message}`));
|
|
2445
|
+
return;
|
|
2446
|
+
}
|
|
2447
|
+
const out = [];
|
|
2448
|
+
const err = [];
|
|
2449
|
+
let settled = false;
|
|
2450
|
+
let timer;
|
|
2451
|
+
const finish = (fn) => {
|
|
2452
|
+
if (settled) return;
|
|
2453
|
+
settled = true;
|
|
2454
|
+
if (timer) clearTimeout(timer);
|
|
2455
|
+
fn();
|
|
2456
|
+
};
|
|
2457
|
+
if (this.opts.timeout !== void 0) {
|
|
2458
|
+
timer = setTimeout(() => {
|
|
2459
|
+
child.kill("SIGKILL");
|
|
2460
|
+
finish(
|
|
2461
|
+
() => reject(new Error(`timed out after ${this.opts.timeout}s`))
|
|
2462
|
+
);
|
|
2463
|
+
}, this.opts.timeout * 1e3);
|
|
2464
|
+
}
|
|
2465
|
+
child.stdout.on("data", (chunk) => out.push(chunk));
|
|
2466
|
+
child.stderr.on("data", (chunk) => err.push(chunk));
|
|
2467
|
+
child.on(
|
|
2468
|
+
"error",
|
|
2469
|
+
(error) => finish(() => reject(new Error(`could not start: ${error.message}`)))
|
|
2470
|
+
);
|
|
2471
|
+
child.on("close", (code) => {
|
|
2472
|
+
finish(() => {
|
|
2473
|
+
const stderr = Buffer.concat(err).toString("utf8").trim();
|
|
2474
|
+
if (code === 2) {
|
|
2475
|
+
reject(
|
|
2476
|
+
new HookDenied(
|
|
2477
|
+
event.event,
|
|
2478
|
+
event.toolName,
|
|
2479
|
+
stderr || "denied by hook (exit 2, no reason on stderr)",
|
|
2480
|
+
[],
|
|
2481
|
+
this.describe()
|
|
2482
|
+
)
|
|
2483
|
+
);
|
|
2484
|
+
return;
|
|
2485
|
+
}
|
|
2486
|
+
if (code !== 0) {
|
|
2487
|
+
reject(new Error(`exit ${code}${stderr ? ": " + stderr : ""}`));
|
|
2488
|
+
return;
|
|
2489
|
+
}
|
|
2490
|
+
try {
|
|
2491
|
+
resolve4(
|
|
2492
|
+
parseStdout(Buffer.concat(out).toString("utf8"), this.describe())
|
|
2493
|
+
);
|
|
2494
|
+
} catch (error) {
|
|
2495
|
+
reject(error);
|
|
2496
|
+
}
|
|
2497
|
+
});
|
|
2498
|
+
});
|
|
2499
|
+
child.stdin.on("error", () => void 0);
|
|
2500
|
+
child.stdin.end(input);
|
|
2501
|
+
});
|
|
2502
|
+
}
|
|
2503
|
+
};
|
|
2504
|
+
var VAR = /\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g;
|
|
2505
|
+
function interpolateHeaders(headers, allowedEnv) {
|
|
2506
|
+
const out = {};
|
|
2507
|
+
for (const [key2, value] of Object.entries(headers)) {
|
|
2508
|
+
out[key2] = value.replace(VAR, (_, name) => {
|
|
2509
|
+
if (!allowedEnv.includes(name))
|
|
2510
|
+
throw new Error(
|
|
2511
|
+
`header ${key2} uses $${name}, which is not in allowed_env`
|
|
2512
|
+
);
|
|
2513
|
+
const found = process.env[name];
|
|
2514
|
+
if (found === void 0)
|
|
2515
|
+
throw new Error(`header ${key2} uses $${name}, which is not set`);
|
|
2516
|
+
return found;
|
|
2517
|
+
});
|
|
2518
|
+
}
|
|
2519
|
+
return out;
|
|
2520
|
+
}
|
|
2521
|
+
var HttpHandler = class {
|
|
2522
|
+
constructor(url, opts = {}) {
|
|
2523
|
+
this.url = url;
|
|
2524
|
+
this.opts = opts;
|
|
2525
|
+
}
|
|
2526
|
+
describe() {
|
|
2527
|
+
return `http ${this.url}`;
|
|
2528
|
+
}
|
|
2529
|
+
async run(event) {
|
|
2530
|
+
const headers = {
|
|
2531
|
+
"content-type": "application/json",
|
|
2532
|
+
accept: "application/json",
|
|
2533
|
+
...interpolateHeaders(
|
|
2534
|
+
this.opts.headers ?? {},
|
|
2535
|
+
this.opts.allowedEnv ?? []
|
|
2536
|
+
)
|
|
2537
|
+
};
|
|
2538
|
+
let response;
|
|
2539
|
+
try {
|
|
2540
|
+
response = await fetch(this.url, {
|
|
2541
|
+
method: "POST",
|
|
2542
|
+
headers,
|
|
2543
|
+
body: JSON.stringify(eventToJson(event)),
|
|
2544
|
+
...this.opts.timeout !== void 0 ? { signal: AbortSignal.timeout(this.opts.timeout * 1e3) } : {}
|
|
2545
|
+
});
|
|
2546
|
+
} catch (error) {
|
|
2547
|
+
const reason = error.name === "TimeoutError" ? `timed out after ${this.opts.timeout}s` : `unreachable: ${error.message}`;
|
|
2548
|
+
throw new Error(reason);
|
|
2549
|
+
}
|
|
2550
|
+
const body = await response.text();
|
|
2551
|
+
if (!response.ok)
|
|
2552
|
+
throw new Error(
|
|
2553
|
+
`${response.status}${body ? ": " + body.slice(0, 200) : ""}`
|
|
2554
|
+
);
|
|
2555
|
+
return parseStdout(body, this.describe());
|
|
2556
|
+
}
|
|
2557
|
+
};
|
|
2558
|
+
var DenyHandler = class {
|
|
2559
|
+
constructor(reason = "denied by rule") {
|
|
2560
|
+
this.reason = reason;
|
|
2561
|
+
}
|
|
2562
|
+
describe() {
|
|
2563
|
+
return `deny: ${this.reason}`;
|
|
2564
|
+
}
|
|
2565
|
+
async run() {
|
|
2566
|
+
return { decision: "deny", reason: this.reason, findings: [] };
|
|
2567
|
+
}
|
|
2568
|
+
};
|
|
2569
|
+
var RecordHandler = class {
|
|
2570
|
+
constructor(sink, opts = {}) {
|
|
2571
|
+
this.sink = sink;
|
|
2572
|
+
this.opts = opts;
|
|
2573
|
+
}
|
|
2574
|
+
describe() {
|
|
2575
|
+
return `record -> ${typeof this.sink === "string" ? this.sink : typeof this.sink === "function" ? "callback" : "array"}`;
|
|
2576
|
+
}
|
|
2577
|
+
async run(event) {
|
|
2578
|
+
let record;
|
|
2579
|
+
if (event.event === "post_response")
|
|
2580
|
+
record = {
|
|
2581
|
+
tool: event.toolName,
|
|
2582
|
+
args: event.request ?? null,
|
|
2583
|
+
result: event.response ?? null
|
|
2584
|
+
};
|
|
2585
|
+
else if (event.event === "post_tool_call") {
|
|
2586
|
+
record = { tool: event.toolName, args: event.toolInput ?? null };
|
|
2587
|
+
if (event.error !== void 0) record.error = event.error;
|
|
2588
|
+
else record.result = event.toolResult ?? null;
|
|
2589
|
+
} else return allow();
|
|
2590
|
+
record.at = (/* @__PURE__ */ new Date()).toISOString();
|
|
2591
|
+
record.session = this.opts.session ?? null;
|
|
2592
|
+
record.source = this.opts.source ?? null;
|
|
2593
|
+
if (Array.isArray(this.sink)) this.sink.push(record);
|
|
2594
|
+
else if (typeof this.sink === "string") {
|
|
2595
|
+
fs2.mkdirSync(path.dirname(this.sink), { recursive: true });
|
|
2596
|
+
fs2.appendFileSync(this.sink, JSON.stringify(record) + "\n");
|
|
2597
|
+
} else await this.sink(record);
|
|
2598
|
+
return allow();
|
|
2599
|
+
}
|
|
2600
|
+
};
|
|
2601
|
+
var interpolatePath = (file, runId, runDir) => file.split("{run_id}").join(runId).split("{run_dir}").join(runDir);
|
|
2602
|
+
var RedactHandler = class {
|
|
2603
|
+
constructor(aliases, opts = {}) {
|
|
2604
|
+
this.aliases = aliases;
|
|
2605
|
+
this.kinds = opts.kinds ?? [];
|
|
2606
|
+
this.values = opts.values ?? [];
|
|
2607
|
+
this.patterns = (opts.patterns ?? []).map((p) => new RegExp(p, "g"));
|
|
2608
|
+
this.token = opts.token ?? "[redacted {kind}]";
|
|
2609
|
+
}
|
|
2610
|
+
kinds;
|
|
2611
|
+
/** Literal strings (a name, a company, a phrase) removed wherever they appear, any
|
|
2612
|
+
* case — the arbitrary half of redaction; `patterns` is the shaped half. */
|
|
2613
|
+
values;
|
|
2614
|
+
patterns;
|
|
2615
|
+
token;
|
|
2616
|
+
describe() {
|
|
2617
|
+
const bits = [];
|
|
2618
|
+
if (this.kinds.length) bits.push(`kinds=${this.kinds.join(",")}`);
|
|
2619
|
+
if (this.values.length) bits.push(`values=${this.values.length}`);
|
|
2620
|
+
if (this.patterns.length) bits.push(`patterns=${this.patterns.length}`);
|
|
2621
|
+
return "redact " + bits.join(" ");
|
|
2622
|
+
}
|
|
2623
|
+
walk(node, where) {
|
|
2624
|
+
if (typeof node === "string")
|
|
2625
|
+
return this.aliases.redactText(node, {
|
|
2626
|
+
kinds: this.kinds,
|
|
2627
|
+
values: this.values,
|
|
2628
|
+
patterns: this.patterns,
|
|
2629
|
+
token: this.token,
|
|
2630
|
+
where
|
|
2631
|
+
});
|
|
2632
|
+
if (Array.isArray(node)) return node.map((v) => this.walk(v, where));
|
|
2633
|
+
if (node && typeof node === "object")
|
|
2634
|
+
return Object.fromEntries(
|
|
2635
|
+
Object.entries(node).map(([k, v]) => [
|
|
2636
|
+
k,
|
|
2637
|
+
this.walk(v, where)
|
|
2638
|
+
])
|
|
2639
|
+
);
|
|
2640
|
+
return node;
|
|
2641
|
+
}
|
|
2642
|
+
async run(event) {
|
|
2643
|
+
if (event.event === "post_response") {
|
|
2644
|
+
const response = {
|
|
2645
|
+
...event.response ?? { status: 0, body: null }
|
|
2646
|
+
};
|
|
2647
|
+
if ("body" in response)
|
|
2648
|
+
response.body = this.walk(response.body, `${event.toolName}.response`);
|
|
2649
|
+
return { decision: "rewrite", updated_response: response, findings: [] };
|
|
2650
|
+
}
|
|
2651
|
+
const result = { decision: "rewrite", findings: [] };
|
|
2652
|
+
if (event.error !== void 0)
|
|
2653
|
+
result.updated_error = this.walk(
|
|
2654
|
+
event.error,
|
|
2655
|
+
`${event.toolName}.error`
|
|
2656
|
+
);
|
|
2657
|
+
else
|
|
2658
|
+
result.updated_result = this.walk(
|
|
2659
|
+
event.toolResult,
|
|
2660
|
+
`${event.toolName}.result`
|
|
2661
|
+
);
|
|
2662
|
+
return result;
|
|
2663
|
+
}
|
|
2664
|
+
};
|
|
2665
|
+
var AliasHandler = class {
|
|
2666
|
+
constructor(aliases, opts = {}) {
|
|
2667
|
+
this.aliases = aliases;
|
|
2668
|
+
this.opts = opts;
|
|
2669
|
+
}
|
|
2670
|
+
describe() {
|
|
2671
|
+
if (this.opts.check) return `alias check=${this.opts.check}`;
|
|
2672
|
+
return this.opts.direction ? `alias direction=${this.opts.direction}` : "alias";
|
|
2673
|
+
}
|
|
2674
|
+
async run(event) {
|
|
2675
|
+
if (event.event === "run_end") return this.outgoing(event);
|
|
2676
|
+
const direction = this.opts.direction ?? (event.event === "pre_tool_call" || event.event === "pre_request" ? "out" : "in");
|
|
2677
|
+
return direction === "out" ? this.out(event) : this.in(event);
|
|
2678
|
+
}
|
|
2679
|
+
out(event) {
|
|
2680
|
+
const problems = [];
|
|
2681
|
+
let result;
|
|
2682
|
+
if (event.event === "pre_request") {
|
|
2683
|
+
const request = {
|
|
2684
|
+
...event.request ?? { method: "GET", path: event.toolName }
|
|
2685
|
+
};
|
|
2686
|
+
for (const key2 of ["path", "query", "body"]) {
|
|
2687
|
+
if (key2 in request) {
|
|
2688
|
+
const [value, found] = this.aliases.walk(
|
|
2689
|
+
request[key2],
|
|
2690
|
+
"out",
|
|
2691
|
+
`${event.toolName}.${key2}`
|
|
2692
|
+
);
|
|
2693
|
+
request[key2] = value;
|
|
2694
|
+
problems.push(...found);
|
|
2695
|
+
}
|
|
2696
|
+
}
|
|
2697
|
+
result = {
|
|
2698
|
+
decision: "rewrite",
|
|
2699
|
+
updated_request: request,
|
|
2700
|
+
findings: problems
|
|
2701
|
+
};
|
|
2702
|
+
} else {
|
|
2703
|
+
const [updated, found] = this.aliases.walk(
|
|
2704
|
+
event.toolInput,
|
|
2705
|
+
"out",
|
|
2706
|
+
`${event.toolName}.args`
|
|
2707
|
+
);
|
|
2708
|
+
problems.push(...found);
|
|
2709
|
+
result = {
|
|
2710
|
+
decision: "rewrite",
|
|
2711
|
+
updated_input: updated,
|
|
2712
|
+
findings: problems
|
|
2713
|
+
};
|
|
2714
|
+
}
|
|
2715
|
+
const blocking = problems.filter(
|
|
2716
|
+
(p) => p.check === "digest_as_selector" || p.check === "unresolved_alias"
|
|
2717
|
+
);
|
|
2718
|
+
if (blocking.length) {
|
|
2719
|
+
const first = blocking[0];
|
|
2720
|
+
return {
|
|
2721
|
+
decision: "deny",
|
|
2722
|
+
reason: `${first.check}: ${first.detail} in ${first.where}. A sha256 digest is a stored form, never a selector; send the value itself.`,
|
|
2723
|
+
findings: problems
|
|
2724
|
+
};
|
|
2725
|
+
}
|
|
2726
|
+
return result;
|
|
2727
|
+
}
|
|
2728
|
+
in(event) {
|
|
2729
|
+
if (event.event === "post_response") {
|
|
2730
|
+
const response = {
|
|
2731
|
+
...event.response ?? { status: 0, body: null }
|
|
2732
|
+
};
|
|
2733
|
+
if ("body" in response)
|
|
2734
|
+
response.body = this.aliases.walk(
|
|
2735
|
+
response.body,
|
|
2736
|
+
"in",
|
|
2737
|
+
`${event.toolName}.response`
|
|
2738
|
+
);
|
|
2739
|
+
return { decision: "rewrite", updated_response: response, findings: [] };
|
|
2740
|
+
}
|
|
2741
|
+
const result = { decision: "rewrite", findings: [] };
|
|
2742
|
+
if (event.error !== void 0)
|
|
2743
|
+
result.updated_error = this.aliases.toAgent(
|
|
2744
|
+
event.error,
|
|
2745
|
+
`${event.toolName}.error`
|
|
2746
|
+
);
|
|
2747
|
+
else
|
|
2748
|
+
result.updated_result = this.aliases.walk(
|
|
2749
|
+
event.toolResult,
|
|
2750
|
+
"in",
|
|
2751
|
+
`${event.toolName}.result`
|
|
2752
|
+
);
|
|
2753
|
+
if ((this.opts.args ?? "alias") === "alias")
|
|
2754
|
+
result.updated_input = this.aliases.walk(
|
|
2755
|
+
event.toolInput,
|
|
2756
|
+
"in",
|
|
2757
|
+
`${event.toolName}.args`,
|
|
2758
|
+
false
|
|
2759
|
+
);
|
|
2760
|
+
return result;
|
|
2761
|
+
}
|
|
2762
|
+
outgoing(event) {
|
|
2763
|
+
const hits = this.aliases.scanOutgoing(event.report ?? "", "report");
|
|
2764
|
+
for (const [name, text] of Object.entries(event.artifacts ?? {}))
|
|
2765
|
+
hits.push(...this.aliases.scanOutgoing(text, `artifact:${name}`));
|
|
2766
|
+
if (hits.length) {
|
|
2767
|
+
return {
|
|
2768
|
+
decision: "deny",
|
|
2769
|
+
reason: `${hits.length} real value(s) in the outgoing report/artifacts: ` + hits.slice(0, 5).map((h) => `${h.kind} in ${h.where}`).join(", "),
|
|
2770
|
+
findings: hits
|
|
2771
|
+
};
|
|
2772
|
+
}
|
|
2773
|
+
return allow();
|
|
2774
|
+
}
|
|
2775
|
+
};
|
|
2776
|
+
async function resultOf(fn, event, name) {
|
|
2777
|
+
const answer = await fn(event);
|
|
2778
|
+
if (answer === void 0 || answer === null) return allow();
|
|
2779
|
+
if (typeof answer !== "object")
|
|
2780
|
+
throw new Error(
|
|
2781
|
+
`${name} returned ${typeof answer}; expected a HookResult, an object or nothing`
|
|
2782
|
+
);
|
|
2783
|
+
return resultFromJson(answer, name);
|
|
2784
|
+
}
|
|
2785
|
+
var FunctionHandler = class {
|
|
2786
|
+
constructor(fn, name) {
|
|
2787
|
+
this.fn = fn;
|
|
2788
|
+
this.name = name;
|
|
2789
|
+
}
|
|
2790
|
+
describe() {
|
|
2791
|
+
return `callable ${this.name}`;
|
|
2792
|
+
}
|
|
2793
|
+
run(event) {
|
|
2794
|
+
return resultOf(this.fn, event, this.describe());
|
|
2795
|
+
}
|
|
2796
|
+
};
|
|
2797
|
+
async function importCallable(target, cwd) {
|
|
2798
|
+
const hash = target.lastIndexOf("#");
|
|
2799
|
+
const modulePath = target.slice(0, hash);
|
|
2800
|
+
const exportName = target.slice(hash + 1) || "default";
|
|
2801
|
+
const resolved = modulePath.startsWith(".") || path.isAbsolute(modulePath) ? (0, import_node_url.pathToFileURL)(path.resolve(cwd, modulePath)).href : modulePath;
|
|
2802
|
+
let module2;
|
|
2803
|
+
try {
|
|
2804
|
+
module2 = await import(resolved);
|
|
2805
|
+
} catch (error) {
|
|
2806
|
+
throw new Error(`callable ${target}: ${error.message}`);
|
|
2807
|
+
}
|
|
2808
|
+
const fn = module2[exportName];
|
|
2809
|
+
if (typeof fn !== "function")
|
|
2810
|
+
throw new Error(
|
|
2811
|
+
`callable ${target}: ${modulePath} has no function export ${JSON.stringify(exportName)}`
|
|
2812
|
+
);
|
|
2813
|
+
return fn;
|
|
2814
|
+
}
|
|
2815
|
+
async function buildHandler(spec, aliases, opts) {
|
|
2816
|
+
const o = spec.options;
|
|
2817
|
+
switch (spec.type) {
|
|
2818
|
+
case "command":
|
|
2819
|
+
return new CommandHandler(o.command, {
|
|
2820
|
+
...o.args !== void 0 ? { args: o.args } : {},
|
|
2821
|
+
...spec.timeout !== void 0 ? { timeout: spec.timeout } : {},
|
|
2822
|
+
...o.cwd !== void 0 ? { cwd: o.cwd } : {}
|
|
2823
|
+
});
|
|
2824
|
+
case "http":
|
|
2825
|
+
return new HttpHandler(o.url, {
|
|
2826
|
+
headers: o.headers ?? {},
|
|
2827
|
+
allowedEnv: o.allowed_env ?? [],
|
|
2828
|
+
...spec.timeout !== void 0 ? { timeout: spec.timeout } : {}
|
|
2829
|
+
});
|
|
2830
|
+
case "callable":
|
|
2831
|
+
return new FunctionHandler(
|
|
2832
|
+
await importCallable(o.target, opts.cwd),
|
|
2833
|
+
o.target
|
|
2834
|
+
);
|
|
2835
|
+
case "deny":
|
|
2836
|
+
return new DenyHandler(
|
|
2837
|
+
o.reason ?? "denied by rule"
|
|
2838
|
+
);
|
|
2839
|
+
case "record":
|
|
2840
|
+
return new RecordHandler(
|
|
2841
|
+
interpolatePath(o.sink, opts.runId ?? "", opts.runDir ?? ""),
|
|
2842
|
+
{
|
|
2843
|
+
session: o.session ?? opts.session,
|
|
2844
|
+
source: o.source ?? opts.source
|
|
2845
|
+
}
|
|
2846
|
+
);
|
|
2847
|
+
case "alias":
|
|
2848
|
+
return new AliasHandler(aliases, {
|
|
2849
|
+
...o.direction !== void 0 ? { direction: o.direction } : {},
|
|
2850
|
+
...o.check !== void 0 ? { check: o.check } : {},
|
|
2851
|
+
...o.args !== void 0 ? { args: o.args } : {}
|
|
2852
|
+
});
|
|
2853
|
+
case "redact":
|
|
2854
|
+
return new RedactHandler(aliases, {
|
|
2855
|
+
kinds: o.kinds ?? [],
|
|
2856
|
+
values: o.values ?? [],
|
|
2857
|
+
patterns: o.patterns ?? [],
|
|
2858
|
+
token: o.token ?? "[redacted {kind}]"
|
|
2859
|
+
});
|
|
2860
|
+
}
|
|
2861
|
+
}
|
|
2862
|
+
|
|
2863
|
+
// src/hooks/live.ts
|
|
2864
|
+
var fs3 = __toESM(require("fs"));
|
|
2865
|
+
var path2 = __toESM(require("path"));
|
|
2866
|
+
var USER_AGENT = "gateway-hooks/1 (+https://withgateway.ai)";
|
|
2867
|
+
var TAGS = /<(script|style)[^>]*>.*?<\/\1>/gis;
|
|
2868
|
+
var STRIP = /<[^>]+>/g;
|
|
2869
|
+
var TITLE = /<title[^>]*>(.*?)<\/title>/is;
|
|
2870
|
+
var LiveToolError = class extends Error {
|
|
2871
|
+
status;
|
|
2872
|
+
body;
|
|
2873
|
+
constructor(message, opts = {}) {
|
|
2874
|
+
super(message);
|
|
2875
|
+
this.name = "LiveToolError";
|
|
2876
|
+
if (opts.status !== void 0) this.status = opts.status;
|
|
2877
|
+
if (opts.body !== void 0) this.body = opts.body.slice(0, 500);
|
|
2878
|
+
}
|
|
2879
|
+
};
|
|
2880
|
+
var Pacer = class {
|
|
2881
|
+
last = /* @__PURE__ */ new Map();
|
|
2882
|
+
/** Waits until the interval since the tool's last call has passed; resolves to the
|
|
2883
|
+
* seconds waited. `sleep`/`clock` are injectable for tests. */
|
|
2884
|
+
async wait(name, intervalMs, opts = {}) {
|
|
2885
|
+
const sleep = opts.sleep ?? ((seconds) => new Promise((resolve4) => setTimeout(resolve4, seconds * 1e3)));
|
|
2886
|
+
const clock = opts.clock ?? (() => Date.now() / 1e3);
|
|
2887
|
+
const now = clock();
|
|
2888
|
+
const due = (this.last.get(name) ?? -Infinity) + intervalMs / 1e3;
|
|
2889
|
+
const waited = Math.max(0, due - now);
|
|
2890
|
+
this.last.set(name, Math.max(now, due));
|
|
2891
|
+
if (waited) await sleep(waited);
|
|
2892
|
+
return Math.round(waited * 1e3) / 1e3;
|
|
2893
|
+
}
|
|
2894
|
+
};
|
|
2895
|
+
var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2896
|
+
function render(template, values, encode = false) {
|
|
2897
|
+
if (typeof template === "string") {
|
|
2898
|
+
const whole = /^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(template);
|
|
2899
|
+
if (whole) return values[whole[1]] ?? void 0;
|
|
2900
|
+
return template.replace(PLACEHOLDER, (_, name) => {
|
|
2901
|
+
const value = values[name];
|
|
2902
|
+
const text = value === void 0 || value === null ? "" : String(value);
|
|
2903
|
+
return encode ? pyQuote2(text) : text;
|
|
2904
|
+
});
|
|
2905
|
+
}
|
|
2906
|
+
if (Array.isArray(template))
|
|
2907
|
+
return template.map((item) => render(item, values, encode));
|
|
2908
|
+
if (isObject3(template)) {
|
|
2909
|
+
const out = {};
|
|
2910
|
+
for (const [key2, item] of Object.entries(template)) {
|
|
2911
|
+
const rendered = render(item, values, encode);
|
|
2912
|
+
if (rendered !== void 0 && rendered !== null) out[key2] = rendered;
|
|
2913
|
+
}
|
|
2914
|
+
return out;
|
|
2915
|
+
}
|
|
2916
|
+
return template;
|
|
2917
|
+
}
|
|
2918
|
+
var pyQuote2 = (value) => encodeURIComponent(value).replace(
|
|
2919
|
+
/[!'()*]/g,
|
|
2920
|
+
(c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
|
|
2921
|
+
);
|
|
2922
|
+
function jsonPath(node, pathText) {
|
|
2923
|
+
const steps = pathText.trim().split(/\.|(?=\[)/).filter((s) => s && s !== "$");
|
|
2924
|
+
let current = node;
|
|
2925
|
+
for (const step of steps) {
|
|
2926
|
+
const index2 = /^\[(\*|\d+)\]$/.exec(step);
|
|
2927
|
+
if (index2) {
|
|
2928
|
+
if (!Array.isArray(current)) return index2[1] === "*" ? [] : void 0;
|
|
2929
|
+
if (index2[1] === "*") continue;
|
|
2930
|
+
current = current[Number(index2[1])];
|
|
2931
|
+
continue;
|
|
2932
|
+
}
|
|
2933
|
+
if (Array.isArray(current))
|
|
2934
|
+
current = current.map(
|
|
2935
|
+
(item) => isObject3(item) ? item[step] : void 0
|
|
2936
|
+
);
|
|
2937
|
+
else if (isObject3(current)) current = current[step];
|
|
2938
|
+
else return void 0;
|
|
2939
|
+
}
|
|
2940
|
+
return current;
|
|
2941
|
+
}
|
|
2942
|
+
var NAMED_ENTITIES = {
|
|
2943
|
+
amp: "&",
|
|
2944
|
+
lt: "<",
|
|
2945
|
+
gt: ">",
|
|
2946
|
+
quot: '"',
|
|
2947
|
+
apos: "'",
|
|
2948
|
+
nbsp: "\xA0",
|
|
2949
|
+
copy: "\xA9",
|
|
2950
|
+
reg: "\xAE",
|
|
2951
|
+
mdash: "\u2014",
|
|
2952
|
+
ndash: "\u2013",
|
|
2953
|
+
hellip: "\u2026",
|
|
2954
|
+
middot: "\xB7",
|
|
2955
|
+
laquo: "\xAB",
|
|
2956
|
+
raquo: "\xBB",
|
|
2957
|
+
lsquo: "\u2018",
|
|
2958
|
+
rsquo: "\u2019",
|
|
2959
|
+
ldquo: "\u201C",
|
|
2960
|
+
rdquo: "\u201D",
|
|
2961
|
+
euro: "\u20AC",
|
|
2962
|
+
pound: "\xA3",
|
|
2963
|
+
yen: "\xA5",
|
|
2964
|
+
trade: "\u2122",
|
|
2965
|
+
deg: "\xB0",
|
|
2966
|
+
times: "\xD7",
|
|
2967
|
+
bull: "\u2022"
|
|
2968
|
+
};
|
|
2969
|
+
function unescapeHtml(text) {
|
|
2970
|
+
return text.replace(
|
|
2971
|
+
/&(#x[0-9a-fA-F]+|#\d+|[A-Za-z][A-Za-z0-9]*);/g,
|
|
2972
|
+
(match, body) => {
|
|
2973
|
+
if (body.startsWith("#x") || body.startsWith("#X"))
|
|
2974
|
+
return String.fromCodePoint(parseInt(body.slice(2), 16));
|
|
2975
|
+
if (body.startsWith("#"))
|
|
2976
|
+
return String.fromCodePoint(parseInt(body.slice(1), 10));
|
|
2977
|
+
return NAMED_ENTITIES[body] ?? match;
|
|
2978
|
+
}
|
|
2979
|
+
);
|
|
2980
|
+
}
|
|
2981
|
+
var stripTags = (text) => unescapeHtml(text.replace(STRIP, "")).trim();
|
|
2982
|
+
function readable(body) {
|
|
2983
|
+
return unescapeHtml(body.replace(TAGS, " ").replace(STRIP, " ")).replace(/\s+/g, " ").trim();
|
|
2984
|
+
}
|
|
2985
|
+
function pageTitle(body) {
|
|
2986
|
+
const match = TITLE.exec(body);
|
|
2987
|
+
return match ? stripTags(match[1]) : "";
|
|
2988
|
+
}
|
|
2989
|
+
function pick2(item, source, stripHtml) {
|
|
2990
|
+
let queryParam;
|
|
2991
|
+
if (isObject3(source)) {
|
|
2992
|
+
queryParam = source.query_param;
|
|
2993
|
+
source = source.from;
|
|
2994
|
+
}
|
|
2995
|
+
let value = isObject3(item) ? jsonPath(item, source) : void 0;
|
|
2996
|
+
if (typeof value === "string") {
|
|
2997
|
+
if (stripHtml) value = stripTags(value);
|
|
2998
|
+
if (queryParam) {
|
|
2999
|
+
const query = value.split("?")[1];
|
|
3000
|
+
if (query) {
|
|
3001
|
+
const params = new URLSearchParams(query.split("#")[0]);
|
|
3002
|
+
const found = params.get(queryParam);
|
|
3003
|
+
if (found) value = found;
|
|
3004
|
+
}
|
|
3005
|
+
}
|
|
3006
|
+
}
|
|
3007
|
+
return value ?? null;
|
|
3008
|
+
}
|
|
3009
|
+
function mapFields(items, fields, stripHtml) {
|
|
3010
|
+
return items.map((item) => {
|
|
3011
|
+
if (!Object.keys(fields).length) {
|
|
3012
|
+
if (isObject3(item))
|
|
3013
|
+
return Object.fromEntries(
|
|
3014
|
+
Object.entries(item).map(([k, v]) => [
|
|
3015
|
+
k,
|
|
3016
|
+
stripHtml && typeof v === "string" ? stripTags(v) : v
|
|
3017
|
+
])
|
|
3018
|
+
);
|
|
3019
|
+
return { value: item };
|
|
3020
|
+
}
|
|
3021
|
+
return Object.fromEntries(
|
|
3022
|
+
Object.entries(fields).map(([name, source]) => [
|
|
3023
|
+
name,
|
|
3024
|
+
pick2(item, source, stripHtml)
|
|
3025
|
+
])
|
|
3026
|
+
);
|
|
3027
|
+
});
|
|
3028
|
+
}
|
|
3029
|
+
function parseJson(body, options) {
|
|
3030
|
+
let data;
|
|
3031
|
+
try {
|
|
3032
|
+
data = JSON.parse(body);
|
|
3033
|
+
} catch (error) {
|
|
3034
|
+
throw new LiveToolError(
|
|
3035
|
+
`the response is not JSON (${error.message}): ${JSON.stringify(body.slice(0, 200))}`
|
|
3036
|
+
);
|
|
3037
|
+
}
|
|
3038
|
+
const results = options.results;
|
|
3039
|
+
if (results === void 0) return data;
|
|
3040
|
+
const items = jsonPath(data, results);
|
|
3041
|
+
if (!Array.isArray(items))
|
|
3042
|
+
throw new LiveToolError(
|
|
3043
|
+
`results path ${results} did not select a list (got ${items === null ? "null" : typeof items})`
|
|
3044
|
+
);
|
|
3045
|
+
return mapFields(
|
|
3046
|
+
items,
|
|
3047
|
+
options.fields ?? {},
|
|
3048
|
+
options.strip_html !== false
|
|
3049
|
+
);
|
|
3050
|
+
}
|
|
3051
|
+
function parseRegex(body, options) {
|
|
3052
|
+
const pattern = new RegExp(jsPattern(options.pattern), "gis");
|
|
3053
|
+
const strip = options.strip_html !== false;
|
|
3054
|
+
const items = [];
|
|
3055
|
+
for (const match of body.matchAll(pattern)) {
|
|
3056
|
+
const groups = match.groups ?? {};
|
|
3057
|
+
items.push(
|
|
3058
|
+
Object.fromEntries(Object.entries(groups).map(([k, v]) => [k, v ?? ""]))
|
|
3059
|
+
);
|
|
3060
|
+
}
|
|
3061
|
+
const fields = options.fields ?? {};
|
|
3062
|
+
const rows = mapFields(items, fields, strip);
|
|
3063
|
+
if (Object.keys(fields).length) {
|
|
3064
|
+
rows.forEach((row, index2) => {
|
|
3065
|
+
for (const [group, value] of Object.entries(items[index2]))
|
|
3066
|
+
if (!(group in row)) row[group] = strip ? stripTags(value) : value;
|
|
3067
|
+
});
|
|
3068
|
+
}
|
|
3069
|
+
return rows;
|
|
3070
|
+
}
|
|
3071
|
+
function parseText(body, status, url, options) {
|
|
3072
|
+
const text = readable(body);
|
|
3073
|
+
const cap = Number(options.max_bytes ?? 2e5);
|
|
3074
|
+
return {
|
|
3075
|
+
url,
|
|
3076
|
+
status,
|
|
3077
|
+
title: pageTitle(body),
|
|
3078
|
+
text: text.slice(0, cap),
|
|
3079
|
+
truncated: text.length > cap
|
|
3080
|
+
};
|
|
3081
|
+
}
|
|
3082
|
+
function applyLimit(rows, limit, values) {
|
|
3083
|
+
if (limit === void 0 || limit === null || !Array.isArray(rows))
|
|
3084
|
+
return rows;
|
|
3085
|
+
const resolved = typeof limit === "string" ? render(limit, values) : limit;
|
|
3086
|
+
if (resolved === void 0 || resolved === null) return rows;
|
|
3087
|
+
const count = Number(resolved);
|
|
3088
|
+
if (!Number.isInteger(count))
|
|
3089
|
+
throw new LiveToolError(
|
|
3090
|
+
`limit ${JSON.stringify(resolved)} is not an integer`
|
|
3091
|
+
);
|
|
3092
|
+
return rows.slice(0, Math.max(count, 0));
|
|
3093
|
+
}
|
|
3094
|
+
function withDefaults(spec, given) {
|
|
3095
|
+
const values = { ...spec.defaults };
|
|
3096
|
+
for (const [k, v] of Object.entries(given))
|
|
3097
|
+
if (v !== void 0 && v !== null) values[k] = v;
|
|
3098
|
+
const missing = spec.input.required.filter((name) => !(name in values));
|
|
3099
|
+
if (missing.length)
|
|
3100
|
+
throw new TypeError(
|
|
3101
|
+
`${spec.name}: missing required input ${missing.join(", ")}`
|
|
3102
|
+
);
|
|
3103
|
+
const fields = Object.keys(spec.input.properties);
|
|
3104
|
+
const unknown = Object.keys(values).filter((k) => !fields.includes(k));
|
|
3105
|
+
if (unknown.length && fields.length)
|
|
3106
|
+
throw new TypeError(
|
|
3107
|
+
`${spec.name}: unknown input ${unknown.sort().join(", ")}`
|
|
3108
|
+
);
|
|
3109
|
+
return values;
|
|
3110
|
+
}
|
|
3111
|
+
var HttpTool = class _HttpTool {
|
|
3112
|
+
constructor(spec, live) {
|
|
3113
|
+
this.spec = spec;
|
|
3114
|
+
this.live = live;
|
|
3115
|
+
}
|
|
3116
|
+
/** Shared across tools: the pace is per tool name, not per HttpTool instance. */
|
|
3117
|
+
static pacer = new Pacer();
|
|
3118
|
+
/** The status of the most recent answer, for the recording line. */
|
|
3119
|
+
lastStatus;
|
|
3120
|
+
inputSchema() {
|
|
3121
|
+
return this.spec.input;
|
|
3122
|
+
}
|
|
3123
|
+
request(values) {
|
|
3124
|
+
const o = this.spec.options;
|
|
3125
|
+
const url = render(o.url, values, true);
|
|
3126
|
+
if (typeof url !== "string" || !/^https?:\/\//.test(url))
|
|
3127
|
+
throw new LiveToolError(
|
|
3128
|
+
`${this.spec.name}: the url rendered to ${JSON.stringify(url)}, not an http(s) URL`
|
|
3129
|
+
);
|
|
3130
|
+
const headers = {
|
|
3131
|
+
"user-agent": USER_AGENT,
|
|
3132
|
+
accept: "*/*",
|
|
3133
|
+
...interpolateHeaders(
|
|
3134
|
+
o.headers ?? {},
|
|
3135
|
+
this.live.allowedEnv
|
|
3136
|
+
)
|
|
3137
|
+
};
|
|
3138
|
+
const init = {
|
|
3139
|
+
method: o.method,
|
|
3140
|
+
headers,
|
|
3141
|
+
signal: AbortSignal.timeout(this.live.timeout * 1e3)
|
|
3142
|
+
};
|
|
3143
|
+
if (o.body !== void 0 && o.body !== null) {
|
|
3144
|
+
const body = render(o.body, values);
|
|
3145
|
+
const named = Object.keys(headers).some(
|
|
3146
|
+
(h) => h.toLowerCase() === "content-type"
|
|
3147
|
+
);
|
|
3148
|
+
if (typeof body === "string") {
|
|
3149
|
+
init.body = body;
|
|
3150
|
+
if (!named)
|
|
3151
|
+
headers["content-type"] = "application/x-www-form-urlencoded";
|
|
3152
|
+
} else {
|
|
3153
|
+
init.body = JSON.stringify(body);
|
|
3154
|
+
if (!named) headers["content-type"] = "application/json";
|
|
3155
|
+
}
|
|
3156
|
+
}
|
|
3157
|
+
return { url, init };
|
|
3158
|
+
}
|
|
3159
|
+
async call(given) {
|
|
3160
|
+
const values = withDefaults(this.spec, given);
|
|
3161
|
+
const { url, init } = this.request(values);
|
|
3162
|
+
const o = this.spec.options;
|
|
3163
|
+
const interval = o.min_interval_ms;
|
|
3164
|
+
if (interval) await _HttpTool.pacer.wait(this.spec.name, interval);
|
|
3165
|
+
this.lastStatus = void 0;
|
|
3166
|
+
let response;
|
|
3167
|
+
let body;
|
|
3168
|
+
try {
|
|
3169
|
+
response = await fetch(url, init);
|
|
3170
|
+
body = await response.text();
|
|
3171
|
+
} catch (error) {
|
|
3172
|
+
throw new LiveToolError(
|
|
3173
|
+
`${this.spec.name}: ${url} unreachable \u2014 ${error.message}`
|
|
3174
|
+
);
|
|
3175
|
+
}
|
|
3176
|
+
this.lastStatus = response.status;
|
|
3177
|
+
if (o.parse === "text") {
|
|
3178
|
+
this.checkFailIf(response.status, body, url);
|
|
3179
|
+
return parseText(body, response.status, url, o);
|
|
3180
|
+
}
|
|
3181
|
+
const okStatus = o.ok_status ?? [
|
|
3182
|
+
[200, 200]
|
|
3183
|
+
];
|
|
3184
|
+
if (!okStatus.some(([low, high]) => response.status >= low && response.status <= high)) {
|
|
3185
|
+
const expected = okStatus.map(([low, high]) => low === high ? String(low) : `${low}-${high}`).join(", ");
|
|
3186
|
+
throw new LiveToolError(
|
|
3187
|
+
`${this.spec.name}: ${url} answered HTTP ${response.status} (ok_status ${expected}): ${JSON.stringify(body.slice(0, 200))}`,
|
|
3188
|
+
{ status: response.status, body }
|
|
3189
|
+
);
|
|
3190
|
+
}
|
|
3191
|
+
this.checkFailIf(response.status, body, url);
|
|
3192
|
+
if (o.parse === "json")
|
|
3193
|
+
return applyLimit(parseJson(body, o), o.limit, values);
|
|
3194
|
+
return applyLimit(parseRegex(body, o), o.limit, values);
|
|
3195
|
+
}
|
|
3196
|
+
/** `fail_if`: a body that matches is a refusal from the provider (a bot challenge,
|
|
3197
|
+
* a block page), never an empty answer. */
|
|
3198
|
+
checkFailIf(status, body, url) {
|
|
3199
|
+
const pattern = this.spec.options.fail_if;
|
|
3200
|
+
if (pattern && new RegExp(jsPattern(pattern), "si").test(body))
|
|
3201
|
+
throw new LiveToolError(
|
|
3202
|
+
`${this.spec.name}: ${url} answered HTTP ${status} with a body matching fail_if ${JSON.stringify(pattern)}: ${JSON.stringify(body.slice(0, 200))}`,
|
|
3203
|
+
{ status, body }
|
|
3204
|
+
);
|
|
3205
|
+
}
|
|
3206
|
+
};
|
|
3207
|
+
var CallableTool = class _CallableTool {
|
|
3208
|
+
constructor(spec, fn) {
|
|
3209
|
+
this.spec = spec;
|
|
3210
|
+
this.fn = fn;
|
|
3211
|
+
}
|
|
3212
|
+
static async create(spec, cwd) {
|
|
3213
|
+
const fn = await importCallable(spec.options.callable, cwd);
|
|
3214
|
+
return new _CallableTool(
|
|
3215
|
+
spec,
|
|
3216
|
+
fn
|
|
3217
|
+
);
|
|
3218
|
+
}
|
|
3219
|
+
inputSchema() {
|
|
3220
|
+
return this.spec.input;
|
|
3221
|
+
}
|
|
3222
|
+
async call(given) {
|
|
3223
|
+
return this.fn(
|
|
3224
|
+
Object.keys(this.spec.input.properties).length ? withDefaults(this.spec, given) : given
|
|
3225
|
+
);
|
|
3226
|
+
}
|
|
3227
|
+
};
|
|
3228
|
+
function readConnection(root) {
|
|
3229
|
+
const file = path2.join(root, "connector.toml");
|
|
3230
|
+
if (!fs3.existsSync(file)) throw new Error(`no connector.toml at ${root}`);
|
|
3231
|
+
const raw = parseToml(fs3.readFileSync(file, "utf8"));
|
|
3232
|
+
const connector = raw.connector ?? {};
|
|
3233
|
+
const auth = raw.auth ?? {};
|
|
3234
|
+
const operations = {};
|
|
3235
|
+
for (const op of raw.operations ?? []) {
|
|
3236
|
+
operations[op.name] = {
|
|
3237
|
+
name: op.name,
|
|
3238
|
+
method: op.method ?? "GET",
|
|
3239
|
+
path: op.path,
|
|
3240
|
+
params: op.params ?? [],
|
|
3241
|
+
...typeof op.results === "string" ? { results: op.results } : {}
|
|
3242
|
+
};
|
|
3243
|
+
}
|
|
3244
|
+
return {
|
|
3245
|
+
slug: connector.slug ?? path2.basename(root),
|
|
3246
|
+
baseUrl: (connector.base_url ?? "").replace(/\/+$/, ""),
|
|
3247
|
+
scheme: auth.scheme ?? "none",
|
|
3248
|
+
...typeof auth.name === "string" ? { authName: auth.name } : {},
|
|
3249
|
+
...typeof auth.secret_env === "string" ? { secretEnv: auth.secret_env } : {},
|
|
3250
|
+
...typeof auth.client_id_env === "string" ? { clientIdEnv: auth.client_id_env } : {},
|
|
3251
|
+
...typeof auth.token_url === "string" ? { tokenUrl: auth.token_url } : {},
|
|
3252
|
+
...typeof auth.scope === "string" ? { scope: auth.scope } : {},
|
|
3253
|
+
extraHeaders: auth.headers ?? {},
|
|
3254
|
+
operations
|
|
3255
|
+
};
|
|
3256
|
+
}
|
|
3257
|
+
var ConnectorTool = class {
|
|
3258
|
+
constructor(spec, live, baseDir) {
|
|
3259
|
+
this.spec = spec;
|
|
3260
|
+
this.live = live;
|
|
3261
|
+
let location = spec.options.connector;
|
|
3262
|
+
if (!path2.isAbsolute(location)) location = path2.resolve(baseDir, location);
|
|
3263
|
+
const root = fs3.existsSync(location) && fs3.statSync(location).isFile() ? path2.dirname(location) : location;
|
|
3264
|
+
try {
|
|
3265
|
+
this.connection = readConnection(root);
|
|
3266
|
+
} catch (error) {
|
|
3267
|
+
throw new Error(`tools.${spec.name}: ${error.message}`);
|
|
3268
|
+
}
|
|
3269
|
+
const operation = this.connection.operations[spec.options.operation];
|
|
3270
|
+
if (!operation)
|
|
3271
|
+
throw new Error(
|
|
3272
|
+
`tools.${spec.name}: unknown operation; choose one of ${Object.keys(this.connection.operations).sort().join(", ")}`
|
|
3273
|
+
);
|
|
3274
|
+
this.operation = operation;
|
|
3275
|
+
for (const variable of [
|
|
3276
|
+
this.connection.secretEnv,
|
|
3277
|
+
this.connection.clientIdEnv,
|
|
3278
|
+
...Object.values(this.connection.extraHeaders)
|
|
3279
|
+
]) {
|
|
3280
|
+
if (variable && !live.allowedEnv.includes(variable))
|
|
3281
|
+
throw new Error(
|
|
3282
|
+
`tools.${spec.name}: the connection reads $${variable}, which is not in live.allowed_env`
|
|
3283
|
+
);
|
|
3284
|
+
}
|
|
3285
|
+
}
|
|
3286
|
+
connection;
|
|
3287
|
+
operation;
|
|
3288
|
+
get placeholders() {
|
|
3289
|
+
return [
|
|
3290
|
+
...this.operation.path.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g)
|
|
3291
|
+
].map((m) => m[1]);
|
|
3292
|
+
}
|
|
3293
|
+
inputSchema() {
|
|
3294
|
+
if (Object.keys(this.spec.input.properties).length) return this.spec.input;
|
|
3295
|
+
const properties = {};
|
|
3296
|
+
for (const name of [...this.placeholders, ...this.operation.params])
|
|
3297
|
+
properties[name] = { type: "string" };
|
|
3298
|
+
return { type: "object", properties, required: this.placeholders };
|
|
3299
|
+
}
|
|
3300
|
+
env(name, what) {
|
|
3301
|
+
const value = name ? process.env[name] : void 0;
|
|
3302
|
+
if (!value)
|
|
3303
|
+
throw new LiveToolError(
|
|
3304
|
+
`${this.spec.name}: set ${name ?? "the credential variable"} for ${what}`
|
|
3305
|
+
);
|
|
3306
|
+
return value;
|
|
3307
|
+
}
|
|
3308
|
+
async credential() {
|
|
3309
|
+
const c = this.connection;
|
|
3310
|
+
if (c.scheme === "none") return void 0;
|
|
3311
|
+
if (c.scheme !== "oauth2")
|
|
3312
|
+
return this.env(c.secretEnv, "the connection's credential");
|
|
3313
|
+
const tokenUrl = c.tokenUrl ? /^https?:\/\//.test(c.tokenUrl) ? c.tokenUrl : c.baseUrl + c.tokenUrl : c.baseUrl + "/oauth/token";
|
|
3314
|
+
const form = new URLSearchParams({
|
|
3315
|
+
grant_type: "client_credentials",
|
|
3316
|
+
client_id: this.env(c.clientIdEnv, "the client id"),
|
|
3317
|
+
client_secret: this.env(c.secretEnv, "the client secret")
|
|
3318
|
+
});
|
|
3319
|
+
if (c.scope) form.set("scope", c.scope);
|
|
3320
|
+
const response = await fetch(tokenUrl, {
|
|
3321
|
+
method: "POST",
|
|
3322
|
+
body: form.toString(),
|
|
3323
|
+
headers: {
|
|
3324
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
3325
|
+
accept: "application/json"
|
|
3326
|
+
}
|
|
3327
|
+
});
|
|
3328
|
+
const body = await response.json().catch(() => ({}));
|
|
3329
|
+
if (!response.ok || typeof body.access_token !== "string")
|
|
3330
|
+
throw new LiveToolError(
|
|
3331
|
+
`${this.spec.name}: token endpoint answered ${response.status} without an access_token`
|
|
3332
|
+
);
|
|
3333
|
+
return body.access_token;
|
|
3334
|
+
}
|
|
3335
|
+
async call(given) {
|
|
3336
|
+
const c = this.connection;
|
|
3337
|
+
const values = Object.fromEntries(
|
|
3338
|
+
Object.entries(given).filter(([, v]) => v !== void 0 && v !== null)
|
|
3339
|
+
);
|
|
3340
|
+
const missing = this.placeholders.filter((name) => !(name in values));
|
|
3341
|
+
if (missing.length)
|
|
3342
|
+
throw new TypeError(
|
|
3343
|
+
`${this.spec.name}: missing path argument(s) ${missing.join(", ")}`
|
|
3344
|
+
);
|
|
3345
|
+
const pathText = this.operation.path.replace(
|
|
3346
|
+
/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,
|
|
3347
|
+
(_, name) => pyQuote2(String(values[name]))
|
|
3348
|
+
);
|
|
3349
|
+
const query = new URLSearchParams();
|
|
3350
|
+
for (const [k, v] of Object.entries(values))
|
|
3351
|
+
if (!this.placeholders.includes(k)) query.append(k, String(v));
|
|
3352
|
+
const headers = {
|
|
3353
|
+
accept: "application/json",
|
|
3354
|
+
"user-agent": `gateway-connector/${c.slug}`
|
|
3355
|
+
};
|
|
3356
|
+
for (const [header, variable] of Object.entries(c.extraHeaders))
|
|
3357
|
+
headers[header] = this.env(variable, `the ${header} header`);
|
|
3358
|
+
const secret = await this.credential();
|
|
3359
|
+
if (c.scheme === "header") headers[c.authName ?? ""] = secret ?? "";
|
|
3360
|
+
else if (c.scheme === "bearer" || c.scheme === "oauth2")
|
|
3361
|
+
headers.authorization = `Bearer ${secret}`;
|
|
3362
|
+
else if (c.scheme === "basic")
|
|
3363
|
+
headers.authorization = "Basic " + Buffer.from(secret ?? "").toString("base64");
|
|
3364
|
+
else if (c.scheme === "query") query.append(c.authName ?? "", secret ?? "");
|
|
3365
|
+
const url = c.baseUrl + pathText + (query.toString() ? `?${query.toString()}` : "");
|
|
3366
|
+
const response = await fetch(url, {
|
|
3367
|
+
method: this.operation.method,
|
|
3368
|
+
headers,
|
|
3369
|
+
signal: AbortSignal.timeout(this.live.timeout * 1e3)
|
|
3370
|
+
});
|
|
3371
|
+
const text = await response.text();
|
|
3372
|
+
let body = text;
|
|
3373
|
+
try {
|
|
3374
|
+
body = text ? JSON.parse(text) : null;
|
|
3375
|
+
} catch {
|
|
3376
|
+
body = text;
|
|
3377
|
+
}
|
|
3378
|
+
if (response.status >= 400)
|
|
3379
|
+
throw new LiveToolError(
|
|
3380
|
+
`${this.spec.name}: ${c.baseUrl}${pathText} answered HTTP ${response.status}: ${text.slice(0, 200)}`
|
|
3381
|
+
);
|
|
3382
|
+
if (this.operation.results && isObject3(body)) {
|
|
3383
|
+
const selected = jsonPath(body, this.operation.results);
|
|
3384
|
+
if (selected !== void 0 && selected !== null) return selected;
|
|
3385
|
+
}
|
|
3386
|
+
return body;
|
|
3387
|
+
}
|
|
3388
|
+
};
|
|
3389
|
+
async function buildTool(spec, live, baseDir) {
|
|
3390
|
+
if (spec.kind === "http") return new HttpTool(spec, live);
|
|
3391
|
+
if (spec.kind === "callable") return CallableTool.create(spec, baseDir);
|
|
3392
|
+
return new ConnectorTool(spec, live, baseDir);
|
|
3393
|
+
}
|
|
3394
|
+
function definition(tool) {
|
|
3395
|
+
return {
|
|
3396
|
+
type: "function",
|
|
3397
|
+
function: {
|
|
3398
|
+
name: tool.spec.name,
|
|
3399
|
+
description: tool.spec.description || tool.spec.name,
|
|
3400
|
+
parameters: tool.inputSchema()
|
|
3401
|
+
}
|
|
3402
|
+
};
|
|
3403
|
+
}
|
|
3404
|
+
function canonical2(value) {
|
|
3405
|
+
if (Array.isArray(value)) return "[" + value.map(canonical2).join(", ") + "]";
|
|
3406
|
+
if (isObject3(value))
|
|
3407
|
+
return "{" + Object.keys(value).sort().map((k) => JSON.stringify(k) + ": " + canonical2(value[k])).join(", ") + "}";
|
|
3408
|
+
if (value === void 0) return "null";
|
|
3409
|
+
return JSON.stringify(value);
|
|
3410
|
+
}
|
|
3411
|
+
var key = (tool, values) => tool + " " + canonical2(values);
|
|
3412
|
+
var Recorder = class {
|
|
3413
|
+
constructor(file) {
|
|
3414
|
+
this.file = file;
|
|
3415
|
+
}
|
|
3416
|
+
write(line) {
|
|
3417
|
+
fs3.mkdirSync(path2.dirname(this.file), { recursive: true });
|
|
3418
|
+
fs3.appendFileSync(this.file, canonical2(line) + "\n");
|
|
3419
|
+
}
|
|
3420
|
+
};
|
|
3421
|
+
var Replay = class {
|
|
3422
|
+
constructor(file) {
|
|
3423
|
+
this.file = file;
|
|
3424
|
+
if (!fs3.existsSync(file))
|
|
3425
|
+
throw new LiveToolError(`replay: no recording at ${file}`);
|
|
3426
|
+
fs3.readFileSync(file, "utf8").split(/\r?\n/).forEach((raw, index2) => {
|
|
3427
|
+
if (!raw.trim()) return;
|
|
3428
|
+
let line;
|
|
3429
|
+
try {
|
|
3430
|
+
line = JSON.parse(raw);
|
|
3431
|
+
} catch (error) {
|
|
3432
|
+
throw new LiveToolError(
|
|
3433
|
+
`replay: ${file}:${index2 + 1} is not JSON \u2014 ${error.message}`
|
|
3434
|
+
);
|
|
3435
|
+
}
|
|
3436
|
+
if ("result_raw" in line)
|
|
3437
|
+
this.answers.set(
|
|
3438
|
+
key(
|
|
3439
|
+
line.tool,
|
|
3440
|
+
line.input_sent ?? {}
|
|
3441
|
+
),
|
|
3442
|
+
line.result_raw
|
|
3443
|
+
);
|
|
3444
|
+
});
|
|
3445
|
+
}
|
|
3446
|
+
answers = /* @__PURE__ */ new Map();
|
|
3447
|
+
tool(spec) {
|
|
3448
|
+
const answers = this.answers;
|
|
3449
|
+
const file = this.file;
|
|
3450
|
+
return {
|
|
3451
|
+
spec,
|
|
3452
|
+
inputSchema: () => spec.input,
|
|
3453
|
+
async call(given) {
|
|
3454
|
+
let values = Object.fromEntries(
|
|
3455
|
+
Object.entries(given).filter(
|
|
3456
|
+
([, v]) => v !== void 0 && v !== null
|
|
3457
|
+
)
|
|
3458
|
+
);
|
|
3459
|
+
if (spec.kind !== "connector") values = withDefaults(spec, values);
|
|
3460
|
+
const k = key(spec.name, values);
|
|
3461
|
+
if (!answers.has(k))
|
|
3462
|
+
throw new LiveToolError(
|
|
3463
|
+
`replay: no recorded answer for ${spec.name} with input ${canonical2(values)} in ${file}`
|
|
3464
|
+
);
|
|
3465
|
+
return answers.get(k);
|
|
3466
|
+
}
|
|
3467
|
+
};
|
|
3468
|
+
}
|
|
3469
|
+
};
|
|
3470
|
+
function refusalReason(error) {
|
|
3471
|
+
if (error instanceof HookDenied) return error.reason;
|
|
3472
|
+
if (!(error instanceof Error)) return null;
|
|
3473
|
+
const reason = error.reason;
|
|
3474
|
+
if (typeof reason === "string" && reason) return reason;
|
|
3475
|
+
if (/(Denied|Refusal|Refused)$/.test(error.name))
|
|
3476
|
+
return error.message || error.name;
|
|
3477
|
+
return null;
|
|
3478
|
+
}
|
|
3479
|
+
var LiveTools = class _LiveTools {
|
|
3480
|
+
constructor(run, live) {
|
|
3481
|
+
this.run = run;
|
|
3482
|
+
this.live = live;
|
|
3483
|
+
if (live.replay) this.replay = new Replay(live.replay);
|
|
3484
|
+
if (live.record) this.recorder = new Recorder(live.record);
|
|
3485
|
+
}
|
|
3486
|
+
replay;
|
|
3487
|
+
recorder;
|
|
3488
|
+
built = {};
|
|
3489
|
+
raw = {};
|
|
3490
|
+
inside;
|
|
3491
|
+
static async create(run, live, baseDir) {
|
|
3492
|
+
const tools = new _LiveTools(run, live);
|
|
3493
|
+
for (const [name, spec] of Object.entries(live.tools)) {
|
|
3494
|
+
tools.built[name] = await buildTool(spec, live, baseDir);
|
|
3495
|
+
tools.raw[name] = tools.replay ? tools.replay.tool(spec) : tools.built[name];
|
|
3496
|
+
}
|
|
3497
|
+
return tools;
|
|
3498
|
+
}
|
|
3499
|
+
/** The tools of a hooks file for an existing run: the file read, `{run_id}` /
|
|
3500
|
+
* `{run_dir}` in its `[live]` paths filled from the run (`runDir` overrides the
|
|
3501
|
+
* run's), the `connector` paths resolved from the file's directory. */
|
|
3502
|
+
static async fromConfig(file, run, opts = {}) {
|
|
3503
|
+
const config = loadHookConfig(file);
|
|
3504
|
+
const directory = opts.runDir ?? run.runDir;
|
|
3505
|
+
const live = {
|
|
3506
|
+
...config.live,
|
|
3507
|
+
...config.live.record ? { record: interpolatePath(config.live.record, run.runId, directory) } : {},
|
|
3508
|
+
...config.live.replay ? { replay: interpolatePath(config.live.replay, run.runId, directory) } : {}
|
|
3509
|
+
};
|
|
3510
|
+
return _LiveTools.create(run, live, path2.dirname(path2.resolve(file)));
|
|
3511
|
+
}
|
|
3512
|
+
/** The declared tools for a model. `openai`: `{type: "function", function: {name,
|
|
3513
|
+
* description, parameters}}`; `anthropic`: `{name, description, input_schema}`. */
|
|
3514
|
+
definitions(shape = "openai") {
|
|
3515
|
+
if (shape !== "openai" && shape !== "anthropic")
|
|
3516
|
+
throw new Error(
|
|
3517
|
+
`shape must be openai or anthropic, not ${JSON.stringify(shape)}`
|
|
3518
|
+
);
|
|
3519
|
+
return Object.values(this.built).map((tool) => {
|
|
3520
|
+
const openai = definition(tool);
|
|
3521
|
+
if (shape === "openai") return openai;
|
|
3522
|
+
const fn = openai.function;
|
|
3523
|
+
return {
|
|
3524
|
+
name: fn.name,
|
|
3525
|
+
description: fn.description,
|
|
3526
|
+
input_schema: fn.parameters
|
|
3527
|
+
};
|
|
3528
|
+
});
|
|
3529
|
+
}
|
|
3530
|
+
/** Every tool wrapped by the run's rules and recorded. A tool's own `vendor`
|
|
3531
|
+
* (`vendor = "..."` in its entry) wins over the one given here. */
|
|
3532
|
+
materialize(vendor = "live") {
|
|
3533
|
+
const byVendor = {};
|
|
3534
|
+
for (const [name, tool] of Object.entries(this.raw))
|
|
3535
|
+
(byVendor[tool.spec.vendor ?? vendor] ??= {})[name] = this.capturing(tool);
|
|
3536
|
+
const wrapped = {};
|
|
3537
|
+
for (const [toolVendor, group] of Object.entries(byVendor))
|
|
3538
|
+
Object.assign(wrapped, this.run.wrapTools(group, { vendor: toolVendor }));
|
|
3539
|
+
const out = {};
|
|
3540
|
+
for (const name of Object.keys(this.raw))
|
|
3541
|
+
out[name] = this.recording(name, wrapped[name]);
|
|
3542
|
+
return out;
|
|
3543
|
+
}
|
|
3544
|
+
/** Inside the door: sees the input as SENT (defaults filled) and the result as
|
|
3545
|
+
* ANSWERED — and, for an HTTP tool, the `status` it answered with (plus `body` on
|
|
3546
|
+
* a `LiveToolError` that carries one). */
|
|
3547
|
+
capturing(tool) {
|
|
3548
|
+
return async (sent) => {
|
|
3549
|
+
const complete = tool.spec.kind === "connector" ? sent : withDefaults(tool.spec, sent);
|
|
3550
|
+
this.inside = { input_sent: { ...complete } };
|
|
3551
|
+
let result;
|
|
3552
|
+
try {
|
|
3553
|
+
result = await tool.call(complete);
|
|
3554
|
+
} catch (error) {
|
|
3555
|
+
if (error instanceof LiveToolError && error.status !== void 0) {
|
|
3556
|
+
this.inside.status = error.status;
|
|
3557
|
+
this.inside.body = error.body;
|
|
3558
|
+
}
|
|
3559
|
+
throw error;
|
|
3560
|
+
}
|
|
3561
|
+
const status = tool.lastStatus;
|
|
3562
|
+
if (status !== void 0) this.inside.status = status;
|
|
3563
|
+
this.inside.result_raw = result;
|
|
3564
|
+
return result;
|
|
3565
|
+
};
|
|
3566
|
+
}
|
|
3567
|
+
/** Outside the door: sees the input as ASKED and the result as SHOWN. */
|
|
3568
|
+
recording(name, fn) {
|
|
3569
|
+
return async (asked = {}) => {
|
|
3570
|
+
const started = Date.now();
|
|
3571
|
+
this.inside = void 0;
|
|
3572
|
+
const line = {
|
|
3573
|
+
at: (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z"),
|
|
3574
|
+
tool: name,
|
|
3575
|
+
input_asked: { ...asked },
|
|
3576
|
+
replayed: this.replay !== void 0
|
|
3577
|
+
};
|
|
3578
|
+
const elapsed = () => Math.round((Date.now() - started) / 1e3 * 1e3) / 1e3;
|
|
3579
|
+
let shown;
|
|
3580
|
+
try {
|
|
3581
|
+
shown = await fn(asked);
|
|
3582
|
+
} catch (error) {
|
|
3583
|
+
Object.assign(line, this.inside ?? {});
|
|
3584
|
+
const refusal = refusalReason(error);
|
|
3585
|
+
if (refusal !== null)
|
|
3586
|
+
Object.assign(line, { denied: true, error: `denied: ${refusal}` });
|
|
3587
|
+
else
|
|
3588
|
+
line.error = `${error.name}: ${error.message}`;
|
|
3589
|
+
line.elapsed = elapsed();
|
|
3590
|
+
this.write(line);
|
|
3591
|
+
throw error;
|
|
3592
|
+
}
|
|
3593
|
+
Object.assign(line, this.inside ?? {}, {
|
|
3594
|
+
result_shown: shown,
|
|
3595
|
+
elapsed: elapsed()
|
|
3596
|
+
});
|
|
3597
|
+
this.write(line);
|
|
3598
|
+
return shown;
|
|
3599
|
+
};
|
|
3600
|
+
}
|
|
3601
|
+
write(line) {
|
|
3602
|
+
this.run.liveLog.push(line);
|
|
3603
|
+
this.recorder?.write(line);
|
|
3604
|
+
}
|
|
3605
|
+
};
|
|
3606
|
+
|
|
3607
|
+
// src/hooks/run.ts
|
|
3608
|
+
var import_node_crypto2 = require("crypto");
|
|
3609
|
+
var fs4 = __toESM(require("fs"));
|
|
3610
|
+
var path3 = __toESM(require("path"));
|
|
3611
|
+
var BLOCKING_EVENTS = [
|
|
3612
|
+
"pre_tool_call",
|
|
3613
|
+
"pre_request",
|
|
3614
|
+
"run_end"
|
|
3615
|
+
];
|
|
3616
|
+
var CONTEXT_KEY = "hook_context";
|
|
3617
|
+
var HookRun = class _HookRun {
|
|
3618
|
+
config;
|
|
3619
|
+
runId;
|
|
3620
|
+
runKey;
|
|
3621
|
+
alias;
|
|
3622
|
+
cwd;
|
|
3623
|
+
/** What `{run_dir}` means in a `record` sink or a `[live]` path. */
|
|
3624
|
+
runDir;
|
|
3625
|
+
/** Where `writeLegend()` writes at run_end — `[alias] legend` or the option; null
|
|
3626
|
+
* writes nothing. Keep it with the run key, never with world data. */
|
|
3627
|
+
legendPath;
|
|
3628
|
+
denials = [];
|
|
3629
|
+
errors = [];
|
|
3630
|
+
findings = [];
|
|
3631
|
+
context = [];
|
|
3632
|
+
/** Answers of `async` handlers, as they complete: `{event, tool, handler, result | error}`. */
|
|
3633
|
+
background = [];
|
|
3634
|
+
calls = 0;
|
|
3635
|
+
/** Every declared-tool call this run made: the recording lines, in memory. */
|
|
3636
|
+
liveLog = [];
|
|
3637
|
+
/** Where a relative `connector` path in `[tools.*]` resolves from: the config file's directory. */
|
|
3638
|
+
configDir;
|
|
3639
|
+
live;
|
|
3640
|
+
bound = {
|
|
3641
|
+
pre_tool_call: [],
|
|
3642
|
+
post_tool_call: [],
|
|
3643
|
+
pre_request: [],
|
|
3644
|
+
post_response: [],
|
|
3645
|
+
run_end: []
|
|
3646
|
+
};
|
|
3647
|
+
pending = [];
|
|
3648
|
+
sessionId;
|
|
3649
|
+
source;
|
|
3650
|
+
constructor(config, options) {
|
|
3651
|
+
this.config = config;
|
|
3652
|
+
this.runId = options.runId ?? `run-${(0, import_node_crypto2.randomBytes)(6).toString("hex")}`;
|
|
3653
|
+
this.runKey = options.runKey ?? newRunKey();
|
|
3654
|
+
this.alias = new AliasMap(this.runKey, options.slugs ?? config.aliasSlugs, {
|
|
3655
|
+
publicLayerWins: config.aliasPublicLayerWins,
|
|
3656
|
+
publicMailboxDomains: config.aliasPublicMailboxDomains,
|
|
3657
|
+
mintInbound: options.mintInbound ?? config.aliasMintInbound
|
|
3658
|
+
});
|
|
3659
|
+
this.cwd = options.cwd ?? process.cwd();
|
|
3660
|
+
this.runDir = options.runDir ?? path3.join(this.cwd, "runs", this.runId);
|
|
3661
|
+
const chosen = options.legend !== void 0 ? options.legend : config.aliasLegend;
|
|
3662
|
+
this.legendPath = chosen ? path3.resolve(this.cwd, interpolatePath(chosen, this.runId, this.runDir)) : null;
|
|
3663
|
+
this.sessionId = options.session;
|
|
3664
|
+
this.source = options.source;
|
|
3665
|
+
this.configDir = config.source ? path3.dirname(path3.resolve(config.source)) : this.cwd;
|
|
3666
|
+
}
|
|
3667
|
+
/** Build from a parsed config (an object in the file's shape, or a `HookConfig`);
|
|
3668
|
+
* handlers are constructed now, so a callable that does not import fails here. */
|
|
3669
|
+
static async create(config, options = {}) {
|
|
3670
|
+
const parsed = config == null ? emptyConfig() : "rules" in config && Array.isArray(config.rules) ? config : parseHookConfig(config);
|
|
3671
|
+
const run = new _HookRun(parsed, options);
|
|
3672
|
+
for (const rule of parsed.rules) {
|
|
3673
|
+
const handlers = [];
|
|
3674
|
+
for (const spec of rule.handlers) {
|
|
3675
|
+
const handler = await buildHandler(spec, run.alias, {
|
|
3676
|
+
cwd: run.cwd,
|
|
3677
|
+
session: run.sessionId,
|
|
3678
|
+
source: run.source,
|
|
3679
|
+
runId: run.runId,
|
|
3680
|
+
runDir: run.runDir
|
|
3681
|
+
});
|
|
3682
|
+
handlers.push({
|
|
3683
|
+
name: spec.name,
|
|
3684
|
+
handler,
|
|
3685
|
+
background: spec.background
|
|
3686
|
+
});
|
|
3687
|
+
}
|
|
3688
|
+
run.bound[rule.event].push({ rule, handlers });
|
|
3689
|
+
}
|
|
3690
|
+
if (Object.keys(parsed.live.tools).length || parsed.live.replay)
|
|
3691
|
+
run.live = await run.liveTools();
|
|
3692
|
+
return run;
|
|
3693
|
+
}
|
|
3694
|
+
liveTools() {
|
|
3695
|
+
const live = this.config.live;
|
|
3696
|
+
return LiveTools.create(
|
|
3697
|
+
this,
|
|
3698
|
+
{
|
|
3699
|
+
...live,
|
|
3700
|
+
...live.record ? { record: interpolatePath(live.record, this.runId, this.runDir) } : {},
|
|
3701
|
+
...live.replay ? { replay: interpolatePath(live.replay, this.runId, this.runDir) } : {}
|
|
3702
|
+
},
|
|
3703
|
+
this.configDir
|
|
3704
|
+
);
|
|
3705
|
+
}
|
|
3706
|
+
/** Read the file once; the run keeps that snapshot. Edit the file, start a new run. */
|
|
3707
|
+
static fromConfig(file, options = {}) {
|
|
3708
|
+
return _HookRun.create(loadHookConfig(file), options);
|
|
3709
|
+
}
|
|
3710
|
+
// ------------------------------------------------------------ rules from code
|
|
3711
|
+
/** Add handlers from code as one rule: `run.on("pre_tool_call", guard, { matcher: "spycloud_.*" })`.
|
|
3712
|
+
* A handler is a function taking a `HookEvent` and returning a `HookResult`, an
|
|
3713
|
+
* object of the same shape, or nothing (allow) — or a built-in instance
|
|
3714
|
+
* (`AliasHandler`, `RecordHandler`, `DenyHandler`, `CommandHandler`, ...), used as
|
|
3715
|
+
* it is. Several handlers in one call are the handlers of one matcher: they see the
|
|
3716
|
+
* same event and their answers merge. `before: true` puts the rule ahead of the
|
|
3717
|
+
* file's rules (and of earlier code rules) instead of after them. */
|
|
3718
|
+
on(event, handlers, opts = {}) {
|
|
3719
|
+
const normalized = normalizeEvent(event);
|
|
3720
|
+
if (!normalized)
|
|
3721
|
+
throw new Error(
|
|
3722
|
+
`unknown event ${JSON.stringify(event)}; expected one of ${EVENTS.join(", ")}`
|
|
3723
|
+
);
|
|
3724
|
+
const fns = Array.isArray(handlers) ? handlers : [handlers];
|
|
3725
|
+
if (!fns.length) throw new Error("on() needs at least one handler");
|
|
3726
|
+
if (opts.name !== void 0 && fns.length > 1)
|
|
3727
|
+
throw new Error(
|
|
3728
|
+
"name applies to a single handler; several handlers are named by their functions"
|
|
3729
|
+
);
|
|
3730
|
+
const matcher = parseMatcher(opts.matcher, {
|
|
3731
|
+
vendor: opts.vendor,
|
|
3732
|
+
arg: opts.arg
|
|
3733
|
+
});
|
|
3734
|
+
const rule = {
|
|
3735
|
+
event: normalized,
|
|
3736
|
+
matcher,
|
|
3737
|
+
handlers: [],
|
|
3738
|
+
position: `code:${normalized}`
|
|
3739
|
+
};
|
|
3740
|
+
const bound = {
|
|
3741
|
+
rule,
|
|
3742
|
+
handlers: fns.map((fn) => {
|
|
3743
|
+
if (typeof fn !== "function") {
|
|
3744
|
+
const name2 = opts.name ?? fn.describe();
|
|
3745
|
+
return { name: name2, handler: fn, background: opts.background ?? false };
|
|
3746
|
+
}
|
|
3747
|
+
const name = opts.name ?? (fn.name || "callable");
|
|
3748
|
+
return {
|
|
3749
|
+
name,
|
|
3750
|
+
handler: new FunctionHandler(fn, name),
|
|
3751
|
+
background: opts.background ?? false
|
|
3752
|
+
};
|
|
3753
|
+
})
|
|
3754
|
+
};
|
|
3755
|
+
if (opts.before) this.bound[normalized].unshift(bound);
|
|
3756
|
+
else this.bound[normalized].push(bound);
|
|
3757
|
+
return this;
|
|
3758
|
+
}
|
|
3759
|
+
/** Mint aliases for the task's known entities (see `AliasMap.seed`). */
|
|
3760
|
+
seed(entities) {
|
|
3761
|
+
return this.alias.seed(entities);
|
|
3762
|
+
}
|
|
3763
|
+
/** The rules bound for one event, in the order `dispatch` applies them. */
|
|
3764
|
+
bindings(event) {
|
|
3765
|
+
return this.bound[event];
|
|
3766
|
+
}
|
|
3767
|
+
// ------------------------------------------------------------ dispatch
|
|
3768
|
+
/** Apply every matching rule, in order, merging each rule's answers. Throws
|
|
3769
|
+
* `HookDenied` on a deny and `HookError` when a rule cannot be applied; both are
|
|
3770
|
+
* recorded on the run before they propagate. */
|
|
3771
|
+
async dispatch(event) {
|
|
3772
|
+
for (const bound of this.bound[event.event]) {
|
|
3773
|
+
if (!matches(bound.rule.matcher, event)) continue;
|
|
3774
|
+
event.matcher = describeMatcher(bound.rule.matcher);
|
|
3775
|
+
const answers = [];
|
|
3776
|
+
for (const entry of bound.handlers) {
|
|
3777
|
+
if (entry.background) {
|
|
3778
|
+
this.startBackground(entry.name, entry.handler, event);
|
|
3779
|
+
continue;
|
|
3780
|
+
}
|
|
3781
|
+
try {
|
|
3782
|
+
answers.push([entry.name, await entry.handler.run(event)]);
|
|
3783
|
+
} catch (error) {
|
|
3784
|
+
if (error instanceof HookDenied) {
|
|
3785
|
+
error.handler = error.handler || entry.name;
|
|
3786
|
+
this.recordDenial(event, error.reason, entry.name, error.findings);
|
|
3787
|
+
throw error;
|
|
3788
|
+
}
|
|
3789
|
+
const detail = this.recordError(event, entry.name, error);
|
|
3790
|
+
if (BLOCKING_EVENTS.includes(event.event)) {
|
|
3791
|
+
this.recordDenial(
|
|
3792
|
+
event,
|
|
3793
|
+
`hook ${entry.name} failed: ${detail}`,
|
|
3794
|
+
entry.name,
|
|
3795
|
+
[]
|
|
3796
|
+
);
|
|
3797
|
+
throw new HookError(
|
|
3798
|
+
event.event,
|
|
3799
|
+
event.toolName,
|
|
3800
|
+
entry.name,
|
|
3801
|
+
detail
|
|
3802
|
+
);
|
|
3803
|
+
}
|
|
3804
|
+
}
|
|
3805
|
+
}
|
|
3806
|
+
this.merge(event, answers);
|
|
3807
|
+
}
|
|
3808
|
+
return event;
|
|
3809
|
+
}
|
|
3810
|
+
merge(event, answers) {
|
|
3811
|
+
for (const [name, result] of answers) {
|
|
3812
|
+
this.findings.push(...result.findings);
|
|
3813
|
+
if (result.additional_context) {
|
|
3814
|
+
event.context.push(`[hook ${name}] ${result.additional_context}`);
|
|
3815
|
+
this.context.push({
|
|
3816
|
+
event: event.event,
|
|
3817
|
+
tool: event.toolName,
|
|
3818
|
+
handler: name,
|
|
3819
|
+
context: result.additional_context
|
|
3820
|
+
});
|
|
3821
|
+
}
|
|
3822
|
+
}
|
|
3823
|
+
const denials = answers.filter(([, r]) => r.decision === "deny");
|
|
3824
|
+
if (denials.length) {
|
|
3825
|
+
const [name, result] = denials[0];
|
|
3826
|
+
const reason = result.reason ?? "denied by hook";
|
|
3827
|
+
const findings = denials.flatMap(([, r]) => r.findings);
|
|
3828
|
+
this.recordDenial(event, reason, name, findings);
|
|
3829
|
+
throw new HookDenied(event.event, event.toolName, reason, findings, name);
|
|
3830
|
+
}
|
|
3831
|
+
const rewriters = answers.filter(([, r]) => rewrites(r));
|
|
3832
|
+
if (rewriters.length > 1) {
|
|
3833
|
+
const names = rewriters.map(([n]) => n).join(", ");
|
|
3834
|
+
const detail = `${rewriters.length} handlers of matcher \`${event.matcher}\` rewrote the event (${names}); at most one may`;
|
|
3835
|
+
this.errors.push({
|
|
3836
|
+
event: event.event,
|
|
3837
|
+
tool: event.toolName,
|
|
3838
|
+
handler: names,
|
|
3839
|
+
error: detail
|
|
3840
|
+
});
|
|
3841
|
+
throw new HookError(event.event, event.toolName, names, detail);
|
|
3842
|
+
}
|
|
3843
|
+
if (rewriters.length) applyResult(event, rewriters[0][1]);
|
|
3844
|
+
}
|
|
3845
|
+
startBackground(name, handler, event) {
|
|
3846
|
+
const record = {
|
|
3847
|
+
event: event.event,
|
|
3848
|
+
tool: event.toolName,
|
|
3849
|
+
handler: name
|
|
3850
|
+
};
|
|
3851
|
+
const task = handler.run(event).then((result) => {
|
|
3852
|
+
record.result = result;
|
|
3853
|
+
}).catch((error) => {
|
|
3854
|
+
record.error = this.recordError(event, name, error);
|
|
3855
|
+
}).then(() => {
|
|
3856
|
+
this.background.push(record);
|
|
3857
|
+
});
|
|
3858
|
+
this.pending.push(task);
|
|
3859
|
+
}
|
|
3860
|
+
/** Wait for every `async` handler started so far. */
|
|
3861
|
+
async drain() {
|
|
3862
|
+
const pending = this.pending;
|
|
3863
|
+
this.pending = [];
|
|
3864
|
+
await Promise.all(pending);
|
|
3865
|
+
}
|
|
3866
|
+
recordError(event, handler, error) {
|
|
3867
|
+
const detail = error instanceof Error ? error.message || error.name : String(error);
|
|
3868
|
+
this.errors.push({
|
|
3869
|
+
event: event.event,
|
|
3870
|
+
tool: event.toolName,
|
|
3871
|
+
handler,
|
|
3872
|
+
error: detail
|
|
3873
|
+
});
|
|
3874
|
+
return detail;
|
|
3875
|
+
}
|
|
3876
|
+
recordDenial(event, reason, handler, findings) {
|
|
3877
|
+
this.denials.push({
|
|
3878
|
+
event: event.event,
|
|
3879
|
+
tool: event.toolName,
|
|
3880
|
+
handler,
|
|
3881
|
+
reason,
|
|
3882
|
+
findings: [...findings]
|
|
3883
|
+
});
|
|
3884
|
+
}
|
|
3885
|
+
event(event, toolName, fields = {}, vendor) {
|
|
3886
|
+
const resolvedVendor = vendor ?? vendorOf(this.config, toolName);
|
|
3887
|
+
return {
|
|
3888
|
+
event,
|
|
3889
|
+
runId: this.runId,
|
|
3890
|
+
toolName,
|
|
3891
|
+
matcher: "",
|
|
3892
|
+
cwd: this.cwd,
|
|
3893
|
+
context: [],
|
|
3894
|
+
...resolvedVendor !== void 0 ? { vendor: resolvedVendor } : {},
|
|
3895
|
+
...fields
|
|
3896
|
+
};
|
|
3897
|
+
}
|
|
3898
|
+
// ------------------------------------------------------------ tool calls
|
|
3899
|
+
/** `pre_tool_call` for one call: the (possibly rewritten) arguments and the context lines. */
|
|
3900
|
+
async beforeCall(toolName, args, opts = {}) {
|
|
3901
|
+
this.calls += 1;
|
|
3902
|
+
const event = await this.dispatch(
|
|
3903
|
+
this.event("pre_tool_call", toolName, { toolInput: args }, opts.vendor)
|
|
3904
|
+
);
|
|
3905
|
+
return [event.toolInput, event.context];
|
|
3906
|
+
}
|
|
3907
|
+
/** `post_tool_call` for one call: the (possibly rewritten) result, carrying every
|
|
3908
|
+
* context line (from `pre_tool_call` too) for the agent. */
|
|
3909
|
+
async afterCall(toolName, args, result, opts = {}) {
|
|
3910
|
+
const event = await this.dispatch(
|
|
3911
|
+
this.event(
|
|
3912
|
+
"post_tool_call",
|
|
3913
|
+
toolName,
|
|
3914
|
+
{
|
|
3915
|
+
toolInput: args,
|
|
3916
|
+
toolResult: result,
|
|
3917
|
+
context: [...opts.context ?? []]
|
|
3918
|
+
},
|
|
3919
|
+
opts.vendor
|
|
3920
|
+
)
|
|
3921
|
+
);
|
|
3922
|
+
return withContext(event.toolResult, event.context);
|
|
3923
|
+
}
|
|
3924
|
+
/** `post_tool_call` for a call that threw or was denied; returns the error text the
|
|
3925
|
+
* agent should see (an alias handler rewrites it, a record handler records it). */
|
|
3926
|
+
async afterError(toolName, args, error, opts = {}) {
|
|
3927
|
+
const event = await this.dispatch(
|
|
3928
|
+
this.event(
|
|
3929
|
+
"post_tool_call",
|
|
3930
|
+
toolName,
|
|
3931
|
+
{ toolInput: args, error },
|
|
3932
|
+
opts.vendor
|
|
3933
|
+
)
|
|
3934
|
+
);
|
|
3935
|
+
return event.error ?? error;
|
|
3936
|
+
}
|
|
3937
|
+
/** The error the agent should see after `post_tool_call` saw its text: the same
|
|
3938
|
+
* class with the rewritten message, or the original when nothing changed. */
|
|
3939
|
+
async rewrittenError(toolName, args, error, vendor) {
|
|
3940
|
+
const text = error instanceof Error ? error.message || error.name : String(error);
|
|
3941
|
+
const shown = await this.afterError(toolName, args, text, { vendor });
|
|
3942
|
+
if (shown === text || !(error instanceof Error)) return error;
|
|
3943
|
+
const replacement = new error.constructor(shown);
|
|
3944
|
+
replacement.cause = error;
|
|
3945
|
+
return replacement;
|
|
3946
|
+
}
|
|
3947
|
+
/**
|
|
3948
|
+
* Wrap a name -> async function map — the shape the Vercel AI SDK's tools, a
|
|
3949
|
+
* `WorldToolkit`'s `impls` and `captureToolCalls` share — so `pre_tool_call` runs
|
|
3950
|
+
* before each call with its argument object as `tool_input` and `post_tool_call`
|
|
3951
|
+
* after it with the result.
|
|
3952
|
+
*
|
|
3953
|
+
* A deny throws `HookDenied` to the caller (after `post_tool_call` saw the denial as
|
|
3954
|
+
* `error`, so a record handler logs it); a rule that cannot be applied throws
|
|
3955
|
+
* `HookError`; a tool's own exception goes through `post_tool_call` as `error` text
|
|
3956
|
+
* and is re-thrown (same class with the rewritten message). `additional_context`
|
|
3957
|
+
* from the handlers is delivered with the result (see `withContext`).
|
|
3958
|
+
*/
|
|
3959
|
+
wrapTools(tools, opts = {}) {
|
|
3960
|
+
const wrapped = /* @__PURE__ */ Object.create(null);
|
|
3961
|
+
for (const [name, fn] of Object.entries(tools)) {
|
|
3962
|
+
wrapped[name] = async (args = {}) => {
|
|
3963
|
+
let real;
|
|
3964
|
+
let context;
|
|
3965
|
+
try {
|
|
3966
|
+
[real, context] = await this.beforeCall(name, args, opts);
|
|
3967
|
+
} catch (error) {
|
|
3968
|
+
if (error instanceof HookDenied)
|
|
3969
|
+
await this.afterError(name, args, `denied: ${error.reason}`, opts);
|
|
3970
|
+
throw error;
|
|
3971
|
+
}
|
|
3972
|
+
let result;
|
|
3973
|
+
try {
|
|
3974
|
+
result = await fn(real);
|
|
3975
|
+
} catch (error) {
|
|
3976
|
+
throw await this.rewrittenError(name, real, error, opts.vendor);
|
|
3977
|
+
}
|
|
3978
|
+
return this.afterCall(name, real, result, { ...opts, context });
|
|
3979
|
+
};
|
|
3980
|
+
}
|
|
3981
|
+
return wrapped;
|
|
3982
|
+
}
|
|
3983
|
+
// ------------------------------------------------------------ declared tools
|
|
3984
|
+
/** Every `[tools.<name>]` entry as a name -> async function map, already wrapped by
|
|
3985
|
+
* this run's rules and, with `[live].record` set, recorded (`input_asked`,
|
|
3986
|
+
* `input_sent`, `result_raw`, `result_shown`, `elapsed` per call; also in `liveLog`).
|
|
3987
|
+
* With `[live].replay` set every tool answers from that recording and an unrecorded
|
|
3988
|
+
* call is refused by name. Built once per run. */
|
|
3989
|
+
async tools(opts = {}) {
|
|
3990
|
+
this.live ??= await this.liveTools();
|
|
3991
|
+
return this.live.materialize(opts.vendor ?? "live");
|
|
3992
|
+
}
|
|
3993
|
+
/** The declared tools for a model: `{type: "function", function: {name, description, parameters}}`. */
|
|
3994
|
+
async toolDefinitions(shape = "openai") {
|
|
3995
|
+
this.live ??= await this.liveTools();
|
|
3996
|
+
return this.live.definitions(shape);
|
|
3997
|
+
}
|
|
3998
|
+
// ------------------------------------------------------------ sessions
|
|
3999
|
+
/** A world-session client (`WorldSession`, or anything with `call(tool, args)`)
|
|
4000
|
+
* with the hooks on its boundary: `call` and `toolkit()` fire the tool-call events,
|
|
4001
|
+
* `request` fires `pre_request` / `post_response` around one HTTP request to the
|
|
4002
|
+
* session's api surface. */
|
|
4003
|
+
session(session, opts = {}) {
|
|
4004
|
+
return new HookedSession(this, session, opts.vendor, opts.requestFn);
|
|
4005
|
+
}
|
|
4006
|
+
async beforeRequest(request, opts = {}) {
|
|
4007
|
+
const event = await this.dispatch(
|
|
4008
|
+
this.event("pre_request", request.path, { request }, opts.vendor)
|
|
4009
|
+
);
|
|
4010
|
+
return event.request ?? request;
|
|
4011
|
+
}
|
|
4012
|
+
async afterResponse(request, response, opts = {}) {
|
|
4013
|
+
const event = await this.dispatch(
|
|
4014
|
+
this.event(
|
|
4015
|
+
"post_response",
|
|
4016
|
+
request.path,
|
|
4017
|
+
{ request, response },
|
|
4018
|
+
opts.vendor
|
|
4019
|
+
)
|
|
4020
|
+
);
|
|
4021
|
+
return event.response ?? response;
|
|
4022
|
+
}
|
|
4023
|
+
// ------------------------------------------------------------ the end
|
|
4024
|
+
/** `run_end`: every handler sees the report and the artifacts; a deny (the alias
|
|
4025
|
+
* outgoing scan found a real value) or a failed handler fails the run. Waits for the
|
|
4026
|
+
* `async` handlers first. Findings are returned either way. */
|
|
4027
|
+
async end(report, artifacts = {}) {
|
|
4028
|
+
await this.drain();
|
|
4029
|
+
const event = this.event("run_end", "run_end", {
|
|
4030
|
+
report,
|
|
4031
|
+
artifacts: { ...artifacts }
|
|
4032
|
+
});
|
|
4033
|
+
const before = this.findings.length;
|
|
4034
|
+
try {
|
|
4035
|
+
await this.dispatch(event);
|
|
4036
|
+
} catch (error) {
|
|
4037
|
+
await this.drain();
|
|
4038
|
+
this.writeLegendIfConfigured();
|
|
4039
|
+
const fresh = this.findings.slice(before);
|
|
4040
|
+
if (error instanceof HookDenied)
|
|
4041
|
+
return {
|
|
4042
|
+
passed: false,
|
|
4043
|
+
reason: error.reason,
|
|
4044
|
+
findings: [
|
|
4045
|
+
...fresh,
|
|
4046
|
+
...error.findings.filter((f) => !fresh.includes(f))
|
|
4047
|
+
],
|
|
4048
|
+
context: event.context
|
|
4049
|
+
};
|
|
4050
|
+
if (error instanceof HookError)
|
|
4051
|
+
return {
|
|
4052
|
+
passed: false,
|
|
4053
|
+
reason: error.message,
|
|
4054
|
+
findings: fresh,
|
|
4055
|
+
context: event.context
|
|
4056
|
+
};
|
|
4057
|
+
throw error;
|
|
4058
|
+
}
|
|
4059
|
+
await this.drain();
|
|
4060
|
+
this.writeLegendIfConfigured();
|
|
4061
|
+
return {
|
|
4062
|
+
passed: true,
|
|
4063
|
+
findings: this.findings.slice(before),
|
|
4064
|
+
context: event.context
|
|
4065
|
+
};
|
|
4066
|
+
}
|
|
4067
|
+
/** Write `legend()` as JSON to `file` (default: the configured legend path) and
|
|
4068
|
+
* return where. Found personas are in it: the map is complete. */
|
|
4069
|
+
writeLegend(file) {
|
|
4070
|
+
const target = file ?? this.legendPath;
|
|
4071
|
+
if (!target)
|
|
4072
|
+
throw new Error(
|
|
4073
|
+
"no legend path: set [alias] legend, pass legend to the run, or give a path"
|
|
4074
|
+
);
|
|
4075
|
+
fs4.mkdirSync(path3.dirname(target), { recursive: true });
|
|
4076
|
+
fs4.writeFileSync(target, JSON.stringify(this.legend(), null, 2) + "\n");
|
|
4077
|
+
return target;
|
|
4078
|
+
}
|
|
4079
|
+
writeLegendIfConfigured() {
|
|
4080
|
+
if (!this.legendPath) return;
|
|
4081
|
+
try {
|
|
4082
|
+
this.writeLegend();
|
|
4083
|
+
} catch (error) {
|
|
4084
|
+
this.errors.push({
|
|
4085
|
+
event: "run_end",
|
|
4086
|
+
tool: "run_end",
|
|
4087
|
+
handler: "legend",
|
|
4088
|
+
error: `could not write the legend to ${this.legendPath}: ${error.message}`
|
|
4089
|
+
});
|
|
4090
|
+
}
|
|
4091
|
+
}
|
|
4092
|
+
/** The run key and the alias map, for the grader. Never stored with world data. */
|
|
4093
|
+
legend() {
|
|
4094
|
+
return {
|
|
4095
|
+
run_id: this.runId,
|
|
4096
|
+
run_key: this.runKey,
|
|
4097
|
+
aliases: this.alias.legend()
|
|
4098
|
+
};
|
|
4099
|
+
}
|
|
4100
|
+
summary() {
|
|
4101
|
+
return {
|
|
4102
|
+
...this.alias.summary(),
|
|
4103
|
+
run_id: this.runId,
|
|
4104
|
+
calls: this.calls,
|
|
4105
|
+
denials: this.denials.length,
|
|
4106
|
+
denials_detail: this.denials.slice(0, 50),
|
|
4107
|
+
hook_errors: this.errors.length,
|
|
4108
|
+
hook_errors_detail: this.errors.slice(0, 50),
|
|
4109
|
+
findings: this.findings.length,
|
|
4110
|
+
context_lines: this.context.length,
|
|
4111
|
+
background_answers: this.background.length
|
|
4112
|
+
};
|
|
4113
|
+
}
|
|
4114
|
+
};
|
|
4115
|
+
function withContext(result, context) {
|
|
4116
|
+
if (!context.length) return result;
|
|
4117
|
+
const lines = [...context];
|
|
4118
|
+
if (result && typeof result === "object" && !Array.isArray(result)) {
|
|
4119
|
+
const existing = result[CONTEXT_KEY];
|
|
4120
|
+
return {
|
|
4121
|
+
...result,
|
|
4122
|
+
[CONTEXT_KEY]: [...Array.isArray(existing) ? existing : [], ...lines]
|
|
4123
|
+
};
|
|
4124
|
+
}
|
|
4125
|
+
if (typeof result === "string") return result + "\n\n" + lines.join("\n");
|
|
4126
|
+
return { result, [CONTEXT_KEY]: lines };
|
|
4127
|
+
}
|
|
4128
|
+
var HookedSession = class {
|
|
4129
|
+
constructor(run, inner, vendor, requestFn) {
|
|
4130
|
+
this.run = run;
|
|
4131
|
+
this.inner = inner;
|
|
4132
|
+
this.vendor = vendor;
|
|
4133
|
+
this.requestFn = requestFn;
|
|
4134
|
+
}
|
|
4135
|
+
async call(tool, args = {}, ...rest) {
|
|
4136
|
+
const [real, context] = await this.run.beforeCall(
|
|
4137
|
+
tool,
|
|
4138
|
+
{ ...args },
|
|
4139
|
+
{ vendor: this.vendor }
|
|
4140
|
+
);
|
|
4141
|
+
let result;
|
|
4142
|
+
try {
|
|
4143
|
+
result = await this.inner.call(
|
|
4144
|
+
tool,
|
|
4145
|
+
real,
|
|
4146
|
+
...rest
|
|
4147
|
+
);
|
|
4148
|
+
} catch (error) {
|
|
4149
|
+
throw await this.run.rewrittenError(tool, real, error, this.vendor);
|
|
4150
|
+
}
|
|
4151
|
+
return this.run.afterCall(tool, real, result, {
|
|
4152
|
+
vendor: this.vendor,
|
|
4153
|
+
context
|
|
4154
|
+
});
|
|
4155
|
+
}
|
|
4156
|
+
async toolkit() {
|
|
4157
|
+
if (!this.inner.toolkit) throw new Error("this session has no toolkit()");
|
|
4158
|
+
const toolkit = await this.inner.toolkit();
|
|
4159
|
+
return {
|
|
4160
|
+
...toolkit,
|
|
4161
|
+
impls: this.run.wrapTools(toolkit.impls, { vendor: this.vendor })
|
|
4162
|
+
};
|
|
4163
|
+
}
|
|
4164
|
+
/** One HTTP request to the session's api surface (`api()` + `path`, with
|
|
4165
|
+
* `apiHeaders()`), `pre_request` before it and `post_response` after. Returns
|
|
4166
|
+
* `{status, body, headers}`; a 4xx/5xx is returned, not thrown, so the agent sees
|
|
4167
|
+
* the vendor's own error shape (rewritten like any result). */
|
|
4168
|
+
async request(method, path4, opts = {}) {
|
|
4169
|
+
if (!this.inner.api && !this.requestFn)
|
|
4170
|
+
throw new Error(
|
|
4171
|
+
"this session has no api surface (pass requestFn for a transport of your own)"
|
|
4172
|
+
);
|
|
4173
|
+
let request = {
|
|
4174
|
+
method: method.toUpperCase(),
|
|
4175
|
+
path: path4,
|
|
4176
|
+
query: { ...opts.query ?? {} },
|
|
4177
|
+
body: opts.body ?? null
|
|
4178
|
+
};
|
|
4179
|
+
request = await this.run.beforeRequest(request, { vendor: this.vendor });
|
|
4180
|
+
const started = Date.now();
|
|
4181
|
+
const elapsed = () => Math.round(Date.now() - started) / 1e3;
|
|
4182
|
+
if (this.requestFn) {
|
|
4183
|
+
let answered;
|
|
4184
|
+
try {
|
|
4185
|
+
answered = await this.requestFn({ ...request });
|
|
4186
|
+
} catch (error) {
|
|
4187
|
+
answered = {
|
|
4188
|
+
status: null,
|
|
4189
|
+
body: null,
|
|
4190
|
+
error: `${error.name}: ${error.message}`
|
|
4191
|
+
};
|
|
4192
|
+
}
|
|
4193
|
+
const response = {
|
|
4194
|
+
status: answered.status,
|
|
4195
|
+
body: answered.body,
|
|
4196
|
+
headers: { ...answered.headers ?? {} },
|
|
4197
|
+
elapsed: elapsed(),
|
|
4198
|
+
...answered.error !== void 0 ? { error: answered.error } : {}
|
|
4199
|
+
};
|
|
4200
|
+
return this.run.afterResponse(request, response, { vendor: this.vendor });
|
|
4201
|
+
}
|
|
4202
|
+
const base = (await this.inner.api()).replace(/\/+$/, "");
|
|
4203
|
+
let url = base + request.path;
|
|
4204
|
+
const query = Object.entries(request.query ?? {});
|
|
4205
|
+
if (query.length) {
|
|
4206
|
+
const params = new URLSearchParams();
|
|
4207
|
+
for (const [key2, value] of query) {
|
|
4208
|
+
if (Array.isArray(value))
|
|
4209
|
+
value.forEach((v) => params.append(key2, String(v)));
|
|
4210
|
+
else params.append(key2, String(value));
|
|
4211
|
+
}
|
|
4212
|
+
url += (url.includes("?") ? "&" : "?") + params.toString();
|
|
4213
|
+
}
|
|
4214
|
+
const headers = {
|
|
4215
|
+
accept: "application/json",
|
|
4216
|
+
...await this.inner.apiHeaders?.() ?? {},
|
|
4217
|
+
...opts.headers ?? {}
|
|
4218
|
+
};
|
|
4219
|
+
let body;
|
|
4220
|
+
if (request.body !== null && request.body !== void 0) {
|
|
4221
|
+
body = JSON.stringify(request.body);
|
|
4222
|
+
if (!Object.keys(headers).some((h) => h.toLowerCase() === "content-type"))
|
|
4223
|
+
headers["content-type"] = "application/json";
|
|
4224
|
+
}
|
|
4225
|
+
let res;
|
|
4226
|
+
try {
|
|
4227
|
+
res = await fetch(url, {
|
|
4228
|
+
method: request.method,
|
|
4229
|
+
headers,
|
|
4230
|
+
...body !== void 0 ? { body } : {},
|
|
4231
|
+
...opts.timeoutMs !== void 0 ? { signal: AbortSignal.timeout(opts.timeoutMs) } : {}
|
|
4232
|
+
});
|
|
4233
|
+
} catch (error) {
|
|
4234
|
+
const cause = error.cause;
|
|
4235
|
+
const detail = cause?.code ? `${error.message} (${cause.code})` : error.message;
|
|
4236
|
+
return this.run.afterResponse(
|
|
4237
|
+
request,
|
|
4238
|
+
{
|
|
4239
|
+
status: null,
|
|
4240
|
+
body: null,
|
|
4241
|
+
headers: {},
|
|
4242
|
+
error: `${error.name}: ${detail}`,
|
|
4243
|
+
elapsed: elapsed()
|
|
4244
|
+
},
|
|
4245
|
+
{ vendor: this.vendor }
|
|
4246
|
+
);
|
|
4247
|
+
}
|
|
4248
|
+
const text = await res.text();
|
|
4249
|
+
const responseHeaders = {};
|
|
4250
|
+
res.headers.forEach((value, key2) => {
|
|
4251
|
+
responseHeaders[key2] = value;
|
|
4252
|
+
});
|
|
4253
|
+
let parsed = text;
|
|
4254
|
+
if ((responseHeaders["content-type"] ?? "").includes("json")) {
|
|
4255
|
+
try {
|
|
4256
|
+
parsed = text ? JSON.parse(text) : null;
|
|
4257
|
+
} catch {
|
|
4258
|
+
parsed = text;
|
|
4259
|
+
}
|
|
4260
|
+
}
|
|
4261
|
+
return this.run.afterResponse(
|
|
4262
|
+
request,
|
|
4263
|
+
{
|
|
4264
|
+
status: res.status,
|
|
4265
|
+
body: parsed,
|
|
4266
|
+
headers: responseHeaders,
|
|
4267
|
+
elapsed: elapsed()
|
|
4268
|
+
},
|
|
4269
|
+
{ vendor: this.vendor }
|
|
4270
|
+
);
|
|
4271
|
+
}
|
|
4272
|
+
};
|
|
4273
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
4274
|
+
0 && (module.exports = {
|
|
4275
|
+
AliasHandler,
|
|
4276
|
+
AliasMap,
|
|
4277
|
+
CONTEXT_KEY,
|
|
4278
|
+
CallableTool,
|
|
4279
|
+
CommandHandler,
|
|
4280
|
+
ConnectorTool,
|
|
4281
|
+
DenyHandler,
|
|
4282
|
+
EVENTS,
|
|
4283
|
+
EVENT_ALIASES,
|
|
4284
|
+
FunctionHandler,
|
|
4285
|
+
HANDLER_TYPES,
|
|
4286
|
+
HookConfigError,
|
|
4287
|
+
HookDenied,
|
|
4288
|
+
HookError,
|
|
4289
|
+
HookRun,
|
|
4290
|
+
HookedSession,
|
|
4291
|
+
HttpHandler,
|
|
4292
|
+
HttpTool,
|
|
4293
|
+
INBOUND_KINDS,
|
|
4294
|
+
INPUT_TYPES,
|
|
4295
|
+
KINDS,
|
|
4296
|
+
LiveToolError,
|
|
4297
|
+
LiveTools,
|
|
4298
|
+
PARSE_MODES,
|
|
4299
|
+
RecordHandler,
|
|
4300
|
+
Recorder,
|
|
4301
|
+
RedactHandler,
|
|
4302
|
+
Replay,
|
|
4303
|
+
TOOL_KINDS,
|
|
4304
|
+
applyLimit,
|
|
4305
|
+
applyResult,
|
|
4306
|
+
buildTool,
|
|
4307
|
+
canonical,
|
|
4308
|
+
definition,
|
|
4309
|
+
describeHandler,
|
|
4310
|
+
describeMatcher,
|
|
4311
|
+
describeTool,
|
|
4312
|
+
emailPairs,
|
|
4313
|
+
emptyConfig,
|
|
4314
|
+
emptyLive,
|
|
4315
|
+
eventToJson,
|
|
4316
|
+
explodeIp,
|
|
4317
|
+
findKind,
|
|
4318
|
+
folded,
|
|
4319
|
+
genericPairs,
|
|
4320
|
+
importCallable,
|
|
4321
|
+
inputSchema,
|
|
4322
|
+
interpolateHeaders,
|
|
4323
|
+
interpolatePath,
|
|
4324
|
+
isGlobalIpv4,
|
|
4325
|
+
jsPattern,
|
|
4326
|
+
jsonPath,
|
|
4327
|
+
loadHookConfig,
|
|
4328
|
+
mapFields,
|
|
4329
|
+
matches,
|
|
4330
|
+
mirrorHandle,
|
|
4331
|
+
namePairs,
|
|
4332
|
+
newRunKey,
|
|
4333
|
+
normalizeEvent,
|
|
4334
|
+
pageTitle,
|
|
4335
|
+
parseHookConfig,
|
|
4336
|
+
parseJson,
|
|
4337
|
+
parseMatcher,
|
|
4338
|
+
parseRegex,
|
|
4339
|
+
parseStdout,
|
|
4340
|
+
parseText,
|
|
4341
|
+
phonePairs,
|
|
4342
|
+
pyQuote,
|
|
4343
|
+
readConnection,
|
|
4344
|
+
readable,
|
|
4345
|
+
refusalReason,
|
|
4346
|
+
render,
|
|
4347
|
+
resultFromJson,
|
|
4348
|
+
splitTopLevel,
|
|
4349
|
+
stripTags,
|
|
4350
|
+
unescapeHtml,
|
|
4351
|
+
vendorOf,
|
|
4352
|
+
withContext,
|
|
4353
|
+
withDefaults
|
|
4354
|
+
});
|
|
4355
|
+
//# sourceMappingURL=index.js.map
|