@osfactory/otel-hook 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1020 -0
- package/dist/adapter-DIgRACtL.d.ts +303 -0
- package/dist/cli.js +12607 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +233 -0
- package/dist/config.js +996 -0
- package/dist/config.js.map +1 -0
- package/dist/content-CoB7aNP1.d.ts +118 -0
- package/dist/diagnostics.d.ts +58 -0
- package/dist/diagnostics.js +46 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/errors.d.ts +91 -0
- package/dist/errors.js +322 -0
- package/dist/errors.js.map +1 -0
- package/dist/events-VxBnDFaO.d.ts +2044 -0
- package/dist/filesystem-store-J8jjDMTh.d.ts +65 -0
- package/dist/hook-CGpo-vks.d.ts +292 -0
- package/dist/identity-BrVBs901.d.ts +227 -0
- package/dist/index.d.ts +44 -0
- package/dist/index.js +11798 -0
- package/dist/index.js.map +1 -0
- package/dist/install.d.ts +1021 -0
- package/dist/install.js +3271 -0
- package/dist/install.js.map +1 -0
- package/dist/integration.d.ts +303 -0
- package/dist/integration.js +5942 -0
- package/dist/integration.js.map +1 -0
- package/dist/keys-Dej5bN3L.d.ts +7 -0
- package/dist/lifecycle.d.ts +428 -0
- package/dist/lifecycle.js +1077 -0
- package/dist/lifecycle.js.map +1 -0
- package/dist/memory-DXVBc8V9.d.ts +94 -0
- package/dist/model.d.ts +45 -0
- package/dist/model.js +1023 -0
- package/dist/model.js.map +1 -0
- package/dist/otlp-log-sink-CeIFDDpn.d.ts +457 -0
- package/dist/payload-CHr53E_v.d.ts +201 -0
- package/dist/policy-D1CrlYn3.d.ts +73 -0
- package/dist/ports-Q8x0ODhs.d.ts +200 -0
- package/dist/primitives-CJ8-rn-f.d.ts +75 -0
- package/dist/privacy.d.ts +51 -0
- package/dist/privacy.js +633 -0
- package/dist/privacy.js.map +1 -0
- package/dist/providers.d.ts +257 -0
- package/dist/providers.js +4398 -0
- package/dist/providers.js.map +1 -0
- package/dist/registry-BzYmC9OC.d.ts +49 -0
- package/dist/runtime.d.ts +32 -0
- package/dist/runtime.js +2907 -0
- package/dist/runtime.js.map +1 -0
- package/dist/schema-Cn0-xz8L.d.ts +224 -0
- package/dist/semconv-Baoz-0OI.d.ts +188 -0
- package/dist/service-j4jEO6cZ.d.ts +68 -0
- package/dist/state.d.ts +36 -0
- package/dist/state.js +710 -0
- package/dist/state.js.map +1 -0
- package/dist/taxonomy-DwhTtuWd.d.ts +87 -0
- package/dist/telemetry.d.ts +77 -0
- package/dist/telemetry.js +2294 -0
- package/dist/telemetry.js.map +1 -0
- package/dist/testing.d.ts +155 -0
- package/dist/testing.js +6513 -0
- package/dist/testing.js.map +1 -0
- package/package.json +124 -0
package/dist/install.js
ADDED
|
@@ -0,0 +1,3271 @@
|
|
|
1
|
+
// src/providers/antigravity/payload.ts
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
var ANTIGRAVITY_HOOK_EVENT_NAMES = [
|
|
4
|
+
"PreInvocation",
|
|
5
|
+
"PostInvocation",
|
|
6
|
+
"PreToolUse",
|
|
7
|
+
"PostToolUse",
|
|
8
|
+
"Stop"
|
|
9
|
+
];
|
|
10
|
+
var hookEventNameSchema = z.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);
|
|
11
|
+
var antigravityWeakShapeSchema = z.object({ hookEventName: hookEventNameSchema }).passthrough();
|
|
12
|
+
var commonFields = {
|
|
13
|
+
conversationId: z.string().min(1),
|
|
14
|
+
workspacePaths: z.array(z.string().min(1)).max(64),
|
|
15
|
+
invocationNum: z.number().int().min(0),
|
|
16
|
+
/** Never disclosed: a real filesystem path. Accepted, never propagated. */
|
|
17
|
+
transcriptPath: z.string().min(1).optional(),
|
|
18
|
+
/** Never disclosed: a real filesystem path. Accepted, never propagated. */
|
|
19
|
+
artifactDirectoryPath: z.string().min(1).optional()
|
|
20
|
+
};
|
|
21
|
+
var preInvocationPayloadSchema = z.object({
|
|
22
|
+
hookEventName: z.literal("PreInvocation"),
|
|
23
|
+
...commonFields,
|
|
24
|
+
agentVersion: z.string().min(1).optional()
|
|
25
|
+
});
|
|
26
|
+
var postInvocationPayloadSchema = z.object({
|
|
27
|
+
hookEventName: z.literal("PostInvocation"),
|
|
28
|
+
...commonFields,
|
|
29
|
+
agentVersion: z.string().min(1).optional()
|
|
30
|
+
});
|
|
31
|
+
var preToolUsePayloadSchema = z.object({
|
|
32
|
+
hookEventName: z.literal("PreToolUse"),
|
|
33
|
+
...commonFields,
|
|
34
|
+
stepIdx: z.number().int().min(0),
|
|
35
|
+
toolName: z.string().min(1),
|
|
36
|
+
toolInput: z.unknown().optional()
|
|
37
|
+
});
|
|
38
|
+
var postToolUsePayloadSchema = z.object({
|
|
39
|
+
hookEventName: z.literal("PostToolUse"),
|
|
40
|
+
...commonFields,
|
|
41
|
+
stepIdx: z.number().int().min(0),
|
|
42
|
+
toolName: z.string().min(1),
|
|
43
|
+
toolResponse: z.unknown().optional(),
|
|
44
|
+
isError: z.boolean().optional()
|
|
45
|
+
});
|
|
46
|
+
var stopPayloadSchema = z.object({
|
|
47
|
+
hookEventName: z.literal("Stop"),
|
|
48
|
+
...commonFields,
|
|
49
|
+
fullyIdle: z.boolean()
|
|
50
|
+
});
|
|
51
|
+
var antigravityHookPayloadSchema = z.discriminatedUnion("hookEventName", [
|
|
52
|
+
preInvocationPayloadSchema,
|
|
53
|
+
postInvocationPayloadSchema,
|
|
54
|
+
preToolUsePayloadSchema,
|
|
55
|
+
postToolUsePayloadSchema,
|
|
56
|
+
stopPayloadSchema
|
|
57
|
+
]);
|
|
58
|
+
|
|
59
|
+
// src/providers/antigravity/registration.ts
|
|
60
|
+
var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
61
|
+
var mergeAntigravityHookRegistration = (input) => {
|
|
62
|
+
const events = input.events ?? ANTIGRAVITY_HOOK_EVENT_NAMES;
|
|
63
|
+
const base = isPlainObject(input.existing) ? input.existing : {};
|
|
64
|
+
const existingHooks = isPlainObject(base.hooks) ? base.hooks : {};
|
|
65
|
+
let changed = !isPlainObject(input.existing) || !isPlainObject(base.hooks);
|
|
66
|
+
const nextHooks = { ...existingHooks };
|
|
67
|
+
const identifies = input.identifies ?? ((entry) => entry.command === input.command);
|
|
68
|
+
const desired = {
|
|
69
|
+
command: input.command,
|
|
70
|
+
...input.matcher === void 0 ? {} : { matcher: input.matcher }
|
|
71
|
+
};
|
|
72
|
+
for (const event3 of events) {
|
|
73
|
+
const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
|
|
74
|
+
const managedIndex = currentList.findIndex((entry) => isPlainObject(entry) && identifies(entry));
|
|
75
|
+
if (managedIndex === -1) {
|
|
76
|
+
changed = true;
|
|
77
|
+
nextHooks[event3] = [...currentList, desired];
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const managed = currentList[managedIndex];
|
|
81
|
+
const updated = { ...managed, ...desired };
|
|
82
|
+
const next = currentList.filter(
|
|
83
|
+
(entry, index) => index === managedIndex || !(isPlainObject(entry) && identifies(entry))
|
|
84
|
+
);
|
|
85
|
+
next[next.indexOf(managed)] = updated;
|
|
86
|
+
const rewritten = Object.entries(desired).some(([key, value]) => managed[key] !== value);
|
|
87
|
+
if (next.length !== currentList.length || rewritten) {
|
|
88
|
+
changed = true;
|
|
89
|
+
}
|
|
90
|
+
nextHooks[event3] = next;
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
config: { ...base, hooks: nextHooks },
|
|
94
|
+
changed
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
var removeAntigravityHookRegistration = (input) => {
|
|
98
|
+
const base = isPlainObject(input.existing) ? { ...input.existing } : {};
|
|
99
|
+
if (!isPlainObject(base.hooks)) {
|
|
100
|
+
return { config: base, changed: false };
|
|
101
|
+
}
|
|
102
|
+
const nextHooks = { ...base.hooks };
|
|
103
|
+
const events = input.events ?? Object.keys(nextHooks);
|
|
104
|
+
let changed = false;
|
|
105
|
+
for (const event3 of events) {
|
|
106
|
+
const currentList = nextHooks[event3];
|
|
107
|
+
if (!Array.isArray(currentList)) {
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const kept = currentList.filter(
|
|
111
|
+
(entry) => !(isPlainObject(entry) && input.identifies(entry))
|
|
112
|
+
);
|
|
113
|
+
if (kept.length === currentList.length) {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
changed = true;
|
|
117
|
+
if (kept.length === 0) {
|
|
118
|
+
delete nextHooks[event3];
|
|
119
|
+
} else {
|
|
120
|
+
nextHooks[event3] = kept;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (!changed) {
|
|
124
|
+
return { config: base, changed: false };
|
|
125
|
+
}
|
|
126
|
+
const config = { ...base };
|
|
127
|
+
if (Object.keys(nextHooks).length === 0) {
|
|
128
|
+
delete config.hooks;
|
|
129
|
+
} else {
|
|
130
|
+
config.hooks = nextHooks;
|
|
131
|
+
}
|
|
132
|
+
return { config, changed };
|
|
133
|
+
};
|
|
134
|
+
var readAntigravityHookRegistrations = (existing, identifies) => {
|
|
135
|
+
const found = /* @__PURE__ */ new Map();
|
|
136
|
+
if (!isPlainObject(existing) || !isPlainObject(existing.hooks)) {
|
|
137
|
+
return found;
|
|
138
|
+
}
|
|
139
|
+
for (const [event3, list] of Object.entries(existing.hooks)) {
|
|
140
|
+
if (!Array.isArray(list)) {
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const commands = list.filter(
|
|
144
|
+
(entry) => isPlainObject(entry) && typeof entry.command === "string" && identifies(entry)
|
|
145
|
+
).map((entry) => entry.command);
|
|
146
|
+
if (commands.length > 0) {
|
|
147
|
+
found.set(event3, commands);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return found;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
// src/providers/hook-document.ts
|
|
154
|
+
var isPlainObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
155
|
+
var normalizeMatcher = (value) => typeof value === "string" && value !== "" && value !== "*" ? value : void 0;
|
|
156
|
+
var isManaged = (value, identifies) => isPlainObject2(value) && identifies(value);
|
|
157
|
+
var cloneGroup = (value) => isPlainObject2(value) && Array.isArray(value.hooks) ? { ...value, hooks: [...value.hooks] } : void 0;
|
|
158
|
+
var matchesDesired = (existing, desired) => {
|
|
159
|
+
for (const [key, value] of Object.entries(desired)) {
|
|
160
|
+
if (existing[key] !== value) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return true;
|
|
165
|
+
};
|
|
166
|
+
var readEventList = (hooks, event3, conflicts) => {
|
|
167
|
+
const raw = hooks[event3];
|
|
168
|
+
if (raw === void 0) {
|
|
169
|
+
return [];
|
|
170
|
+
}
|
|
171
|
+
if (!Array.isArray(raw)) {
|
|
172
|
+
conflicts.push({
|
|
173
|
+
location: `hooks.${event3}`,
|
|
174
|
+
detail: `expected an array of hook groups, found ${raw === null ? "null" : typeof raw}`
|
|
175
|
+
});
|
|
176
|
+
return void 0;
|
|
177
|
+
}
|
|
178
|
+
return [...raw];
|
|
179
|
+
};
|
|
180
|
+
var readHooksObject = (base, conflicts) => {
|
|
181
|
+
const raw = base.hooks;
|
|
182
|
+
if (raw === void 0) {
|
|
183
|
+
return {};
|
|
184
|
+
}
|
|
185
|
+
if (!isPlainObject2(raw)) {
|
|
186
|
+
conflicts.push({
|
|
187
|
+
location: "hooks",
|
|
188
|
+
detail: `expected an object keyed by hook event name, found ${Array.isArray(raw) ? "an array" : raw === null ? "null" : typeof raw}`
|
|
189
|
+
});
|
|
190
|
+
return void 0;
|
|
191
|
+
}
|
|
192
|
+
return { ...raw };
|
|
193
|
+
};
|
|
194
|
+
var pruneEventList = (list) => list.filter((group) => !(isPlainObject2(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
|
|
195
|
+
var finalize = (base, hooks) => {
|
|
196
|
+
const next = { ...base };
|
|
197
|
+
if (Object.keys(hooks).length === 0) {
|
|
198
|
+
delete next.hooks;
|
|
199
|
+
return next;
|
|
200
|
+
}
|
|
201
|
+
next.hooks = hooks;
|
|
202
|
+
return next;
|
|
203
|
+
};
|
|
204
|
+
var mergeNestedHookRegistration = (input) => {
|
|
205
|
+
const base = isPlainObject2(input.existing) ? { ...input.existing } : {};
|
|
206
|
+
const conflicts = [];
|
|
207
|
+
const hooks = readHooksObject(base, conflicts);
|
|
208
|
+
if (hooks === void 0) {
|
|
209
|
+
return { document: base, changed: false, changes: [], conflicts };
|
|
210
|
+
}
|
|
211
|
+
const changes = [];
|
|
212
|
+
let changed = false;
|
|
213
|
+
const desiredMatcher = normalizeMatcher(input.matcher);
|
|
214
|
+
for (const event3 of input.events) {
|
|
215
|
+
const list = readEventList(hooks, event3, conflicts);
|
|
216
|
+
if (list === void 0) {
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const groups = list.map((group) => cloneGroup(group) ?? group);
|
|
220
|
+
const usableGroups = groups.filter(
|
|
221
|
+
(group) => isPlainObject2(group) && Array.isArray(group.hooks)
|
|
222
|
+
);
|
|
223
|
+
let ownHandler;
|
|
224
|
+
let ownGroup;
|
|
225
|
+
let ownIndex = -1;
|
|
226
|
+
let duplicates = 0;
|
|
227
|
+
for (const group of usableGroups) {
|
|
228
|
+
const handlers = group.hooks;
|
|
229
|
+
for (let index = 0; index < handlers.length; index += 1) {
|
|
230
|
+
if (!isManaged(handlers[index], input.identifies)) {
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (ownHandler === void 0) {
|
|
234
|
+
ownHandler = handlers[index];
|
|
235
|
+
ownGroup = group;
|
|
236
|
+
ownIndex = index;
|
|
237
|
+
} else {
|
|
238
|
+
duplicates += 1;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (duplicates > 0) {
|
|
243
|
+
for (const group of usableGroups) {
|
|
244
|
+
group.hooks = group.hooks.filter(
|
|
245
|
+
(handler) => handler === ownHandler || !isManaged(handler, input.identifies)
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
let target = usableGroups.find(
|
|
250
|
+
(group) => normalizeMatcher(group.matcher) === desiredMatcher
|
|
251
|
+
);
|
|
252
|
+
if (target === void 0) {
|
|
253
|
+
target = {
|
|
254
|
+
...input.matcher === void 0 ? {} : { matcher: input.matcher },
|
|
255
|
+
hooks: []
|
|
256
|
+
};
|
|
257
|
+
groups.push(target);
|
|
258
|
+
}
|
|
259
|
+
let action;
|
|
260
|
+
if (ownHandler === void 0) {
|
|
261
|
+
target.hooks = [...target.hooks, { ...input.entry }];
|
|
262
|
+
action = "added";
|
|
263
|
+
} else if (ownGroup === target) {
|
|
264
|
+
const handlers = [...target.hooks];
|
|
265
|
+
const alreadyDesired = matchesDesired(ownHandler, input.entry);
|
|
266
|
+
handlers[ownIndex] = alreadyDesired ? ownHandler : { ...ownHandler, ...input.entry };
|
|
267
|
+
target.hooks = handlers;
|
|
268
|
+
action = alreadyDesired && duplicates === 0 ? "unchanged" : "updated";
|
|
269
|
+
} else {
|
|
270
|
+
if (ownGroup !== void 0) {
|
|
271
|
+
ownGroup.hooks = ownGroup.hooks.filter((handler) => handler !== ownHandler);
|
|
272
|
+
}
|
|
273
|
+
target.hooks = [...target.hooks, { ...ownHandler, ...input.entry }];
|
|
274
|
+
action = "updated";
|
|
275
|
+
}
|
|
276
|
+
changes.push({ event: event3, action });
|
|
277
|
+
changed = changed || action !== "unchanged";
|
|
278
|
+
hooks[event3] = pruneEventList(groups);
|
|
279
|
+
}
|
|
280
|
+
if (conflicts.length > 0) {
|
|
281
|
+
return { document: base, changed: false, changes: [], conflicts };
|
|
282
|
+
}
|
|
283
|
+
return { document: finalize(base, hooks), changed, changes, conflicts };
|
|
284
|
+
};
|
|
285
|
+
var removeNestedHookRegistrations = (input) => {
|
|
286
|
+
const base = isPlainObject2(input.existing) ? { ...input.existing } : {};
|
|
287
|
+
const conflicts = [];
|
|
288
|
+
const hooks = readHooksObject(base, conflicts);
|
|
289
|
+
if (hooks === void 0) {
|
|
290
|
+
return { document: base, changed: false, changes: [], conflicts };
|
|
291
|
+
}
|
|
292
|
+
const changes = [];
|
|
293
|
+
let changed = false;
|
|
294
|
+
const events = input.events ?? Object.keys(hooks);
|
|
295
|
+
for (const event3 of events) {
|
|
296
|
+
if (!(event3 in hooks)) {
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
const list = readEventList(hooks, event3, conflicts);
|
|
300
|
+
if (list === void 0) {
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
let removedHere = false;
|
|
304
|
+
const groups = [];
|
|
305
|
+
for (const group of list) {
|
|
306
|
+
const cloned = cloneGroup(group);
|
|
307
|
+
if (cloned === void 0) {
|
|
308
|
+
groups.push(group);
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
const handlers = cloned.hooks.filter(
|
|
312
|
+
(handler) => !isManaged(handler, input.identifies)
|
|
313
|
+
);
|
|
314
|
+
if (handlers.length !== cloned.hooks.length) {
|
|
315
|
+
removedHere = true;
|
|
316
|
+
}
|
|
317
|
+
cloned.hooks = handlers;
|
|
318
|
+
groups.push(cloned);
|
|
319
|
+
}
|
|
320
|
+
if (!removedHere) {
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
changed = true;
|
|
324
|
+
changes.push({ event: event3, action: "removed" });
|
|
325
|
+
const pruned = pruneEventList(groups);
|
|
326
|
+
if (pruned.length === 0) {
|
|
327
|
+
delete hooks[event3];
|
|
328
|
+
} else {
|
|
329
|
+
hooks[event3] = pruned;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (conflicts.length > 0) {
|
|
333
|
+
return { document: base, changed: false, changes: [], conflicts };
|
|
334
|
+
}
|
|
335
|
+
return { document: finalize(base, hooks), changed, changes, conflicts };
|
|
336
|
+
};
|
|
337
|
+
var readNestedHookRegistrations = (existing, identifies) => {
|
|
338
|
+
const found = /* @__PURE__ */ new Map();
|
|
339
|
+
if (!isPlainObject2(existing) || !isPlainObject2(existing.hooks)) {
|
|
340
|
+
return found;
|
|
341
|
+
}
|
|
342
|
+
for (const [event3, list] of Object.entries(existing.hooks)) {
|
|
343
|
+
if (!Array.isArray(list)) {
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
const commands = [];
|
|
347
|
+
for (const group of list) {
|
|
348
|
+
if (!isPlainObject2(group) || !Array.isArray(group.hooks)) {
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
for (const handler of group.hooks) {
|
|
352
|
+
if (isManaged(handler, identifies)) {
|
|
353
|
+
const command = handler.command;
|
|
354
|
+
commands.push(typeof command === "string" ? command : "");
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
if (commands.length > 0) {
|
|
359
|
+
found.set(event3, commands);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return found;
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
// src/providers/claude/schema.ts
|
|
366
|
+
import { z as z2 } from "zod";
|
|
367
|
+
var commonFields2 = {
|
|
368
|
+
session_id: z2.string().min(1),
|
|
369
|
+
transcript_path: z2.string().min(1).optional(),
|
|
370
|
+
cwd: z2.string().min(1).optional(),
|
|
371
|
+
permission_mode: z2.string().min(1).optional(),
|
|
372
|
+
/** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */
|
|
373
|
+
prompt_id: z2.string().min(1).optional(),
|
|
374
|
+
/** Present when the hook fired while running inside a subagent. */
|
|
375
|
+
agent_id: z2.string().min(1).optional(),
|
|
376
|
+
agent_type: z2.string().min(1).optional()
|
|
377
|
+
};
|
|
378
|
+
var claudeCacheCreationSchema = z2.object({
|
|
379
|
+
ephemeral_5m_input_tokens: z2.number().int().min(0).optional(),
|
|
380
|
+
ephemeral_1h_input_tokens: z2.number().int().min(0).optional()
|
|
381
|
+
});
|
|
382
|
+
var claudeUsageIterationSchema = z2.object({
|
|
383
|
+
input_tokens: z2.number().int().min(0).optional(),
|
|
384
|
+
output_tokens: z2.number().int().min(0).optional(),
|
|
385
|
+
cache_creation_input_tokens: z2.number().int().min(0).optional(),
|
|
386
|
+
cache_read_input_tokens: z2.number().int().min(0).optional()
|
|
387
|
+
});
|
|
388
|
+
var claudeUsageSchema = z2.object({
|
|
389
|
+
input_tokens: z2.number().int().min(0),
|
|
390
|
+
output_tokens: z2.number().int().min(0),
|
|
391
|
+
cache_creation_input_tokens: z2.number().int().min(0).optional(),
|
|
392
|
+
cache_read_input_tokens: z2.number().int().min(0).optional(),
|
|
393
|
+
cache_creation: claudeCacheCreationSchema.optional(),
|
|
394
|
+
iterations: z2.array(claudeUsageIterationSchema).optional(),
|
|
395
|
+
/**
|
|
396
|
+
* Counters the canonical model has a home for but Claude Code never reports:
|
|
397
|
+
* 0 of 4,999 real usage objects carried either (finding 5).
|
|
398
|
+
*
|
|
399
|
+
* Named here rather than left to the object's forward-compatible looseness so
|
|
400
|
+
* that a harness attaching one gets told it was excluded, instead of watching
|
|
401
|
+
* it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.
|
|
402
|
+
*/
|
|
403
|
+
total_tokens: z2.number().int().min(0).optional(),
|
|
404
|
+
reasoning_output_tokens: z2.number().int().min(0).optional()
|
|
405
|
+
});
|
|
406
|
+
var sessionStartPayloadSchema = z2.object({
|
|
407
|
+
...commonFields2,
|
|
408
|
+
hook_event_name: z2.literal("SessionStart"),
|
|
409
|
+
/** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */
|
|
410
|
+
source: z2.string().min(1).optional(),
|
|
411
|
+
model: z2.string().min(1).optional(),
|
|
412
|
+
session_title: z2.string().min(1).optional()
|
|
413
|
+
});
|
|
414
|
+
var sessionEndPayloadSchema = z2.object({
|
|
415
|
+
...commonFields2,
|
|
416
|
+
hook_event_name: z2.literal("SessionEnd"),
|
|
417
|
+
/** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */
|
|
418
|
+
reason: z2.string().min(1).optional(),
|
|
419
|
+
/** Compatibility alias emitted by older wrappers and hook integrations. */
|
|
420
|
+
end_reason: z2.string().min(1).optional()
|
|
421
|
+
});
|
|
422
|
+
var userPromptSubmitPayloadSchema = z2.object({
|
|
423
|
+
...commonFields2,
|
|
424
|
+
hook_event_name: z2.literal("UserPromptSubmit"),
|
|
425
|
+
prompt: z2.string()
|
|
426
|
+
});
|
|
427
|
+
var preToolUsePayloadSchema2 = z2.object({
|
|
428
|
+
...commonFields2,
|
|
429
|
+
hook_event_name: z2.literal("PreToolUse"),
|
|
430
|
+
tool_name: z2.string().min(1),
|
|
431
|
+
tool_input: z2.unknown(),
|
|
432
|
+
tool_use_id: z2.string().min(1)
|
|
433
|
+
});
|
|
434
|
+
var postToolUsePayloadSchema2 = z2.object({
|
|
435
|
+
...commonFields2,
|
|
436
|
+
hook_event_name: z2.literal("PostToolUse"),
|
|
437
|
+
tool_name: z2.string().min(1),
|
|
438
|
+
tool_input: z2.unknown().optional(),
|
|
439
|
+
tool_response: z2.unknown(),
|
|
440
|
+
tool_use_id: z2.string().min(1)
|
|
441
|
+
});
|
|
442
|
+
var postToolUseFailurePayloadSchema = z2.object({
|
|
443
|
+
...commonFields2,
|
|
444
|
+
hook_event_name: z2.literal("PostToolUseFailure"),
|
|
445
|
+
tool_name: z2.string().min(1),
|
|
446
|
+
tool_input: z2.unknown().optional(),
|
|
447
|
+
tool_error: z2.unknown(),
|
|
448
|
+
tool_use_id: z2.string().min(1)
|
|
449
|
+
});
|
|
450
|
+
var permissionRequestPayloadSchema = z2.object({
|
|
451
|
+
...commonFields2,
|
|
452
|
+
hook_event_name: z2.literal("PermissionRequest"),
|
|
453
|
+
tool_name: z2.string().min(1),
|
|
454
|
+
tool_input: z2.unknown().optional(),
|
|
455
|
+
tool_use_id: z2.string().min(1)
|
|
456
|
+
});
|
|
457
|
+
var subagentStartPayloadSchema = z2.object({
|
|
458
|
+
...commonFields2,
|
|
459
|
+
hook_event_name: z2.literal("SubagentStart"),
|
|
460
|
+
agent_type: z2.string().min(1),
|
|
461
|
+
agent_id: z2.string().min(1)
|
|
462
|
+
});
|
|
463
|
+
var subagentStopPayloadSchema = z2.object({
|
|
464
|
+
...commonFields2,
|
|
465
|
+
hook_event_name: z2.literal("SubagentStop"),
|
|
466
|
+
agent_type: z2.string().min(1),
|
|
467
|
+
agent_id: z2.string().min(1),
|
|
468
|
+
last_assistant_message: z2.string().optional(),
|
|
469
|
+
/** True when this stop fired because a hook continued the subagent's turn. */
|
|
470
|
+
stop_hook_active: z2.boolean().optional(),
|
|
471
|
+
usage: claudeUsageSchema.optional()
|
|
472
|
+
});
|
|
473
|
+
var preCompactPayloadSchema = z2.object({
|
|
474
|
+
...commonFields2,
|
|
475
|
+
hook_event_name: z2.literal("PreCompact"),
|
|
476
|
+
/** Upstream values: manual | auto. Forward-compatible: any string. */
|
|
477
|
+
trigger: z2.string().min(1).optional(),
|
|
478
|
+
/** Compatibility alias emitted by older wrappers and hook integrations. */
|
|
479
|
+
compact_trigger: z2.string().min(1).optional(),
|
|
480
|
+
/**
|
|
481
|
+
* Harness-supplied, never upstream. Reported as an explicit exclusion rather
|
|
482
|
+
* than carried across the process boundary: see `events.ts`.
|
|
483
|
+
*/
|
|
484
|
+
context_tokens_before: z2.number().int().min(0).optional(),
|
|
485
|
+
estimated_tokens_removed: z2.number().int().min(0).optional()
|
|
486
|
+
});
|
|
487
|
+
var postCompactPayloadSchema = z2.object({
|
|
488
|
+
...commonFields2,
|
|
489
|
+
hook_event_name: z2.literal("PostCompact"),
|
|
490
|
+
trigger: z2.string().min(1).optional(),
|
|
491
|
+
compact_trigger: z2.string().min(1).optional(),
|
|
492
|
+
/** Harness-supplied, never upstream; accepted here because one callback carries both. */
|
|
493
|
+
context_tokens_before: z2.number().int().min(0).optional(),
|
|
494
|
+
context_tokens_after: z2.number().int().min(0).optional(),
|
|
495
|
+
dropped_message_count: z2.number().int().min(0).optional(),
|
|
496
|
+
usage: claudeUsageSchema.optional()
|
|
497
|
+
});
|
|
498
|
+
var stopPayloadSchema2 = z2.object({
|
|
499
|
+
...commonFields2,
|
|
500
|
+
hook_event_name: z2.literal("Stop"),
|
|
501
|
+
last_assistant_message: z2.string().optional(),
|
|
502
|
+
/**
|
|
503
|
+
* True when this stop fired because a hook continued the turn.
|
|
504
|
+
*
|
|
505
|
+
* Required upstream, optional here. It is what separates the once-per-prompt
|
|
506
|
+
* stop from a continuation stop, which is what lets `delivery.ts` deduplicate
|
|
507
|
+
* the former without suppressing the latter.
|
|
508
|
+
*/
|
|
509
|
+
stop_hook_active: z2.boolean().optional(),
|
|
510
|
+
usage: claudeUsageSchema.optional()
|
|
511
|
+
});
|
|
512
|
+
var stopFailurePayloadSchema = z2.object({
|
|
513
|
+
...commonFields2,
|
|
514
|
+
hook_event_name: z2.literal("StopFailure"),
|
|
515
|
+
/**
|
|
516
|
+
* Matcher values: rate_limit | overloaded | authentication_failed |
|
|
517
|
+
* oauth_org_not_allowed | billing_error | invalid_request | model_not_found
|
|
518
|
+
* | server_error | max_output_tokens | unknown.
|
|
519
|
+
*/
|
|
520
|
+
error_type: z2.string().min(1),
|
|
521
|
+
error_message: z2.string().optional(),
|
|
522
|
+
usage: claudeUsageSchema.optional()
|
|
523
|
+
});
|
|
524
|
+
var claudeHookPayloadSchema = z2.discriminatedUnion("hook_event_name", [
|
|
525
|
+
sessionStartPayloadSchema,
|
|
526
|
+
sessionEndPayloadSchema,
|
|
527
|
+
userPromptSubmitPayloadSchema,
|
|
528
|
+
preToolUsePayloadSchema2,
|
|
529
|
+
postToolUsePayloadSchema2,
|
|
530
|
+
postToolUseFailurePayloadSchema,
|
|
531
|
+
permissionRequestPayloadSchema,
|
|
532
|
+
subagentStartPayloadSchema,
|
|
533
|
+
subagentStopPayloadSchema,
|
|
534
|
+
preCompactPayloadSchema,
|
|
535
|
+
postCompactPayloadSchema,
|
|
536
|
+
stopPayloadSchema2,
|
|
537
|
+
stopFailurePayloadSchema
|
|
538
|
+
]);
|
|
539
|
+
var CLAUDE_HOOK_EVENT_NAMES = [
|
|
540
|
+
"SessionStart",
|
|
541
|
+
"SessionEnd",
|
|
542
|
+
"UserPromptSubmit",
|
|
543
|
+
"PreToolUse",
|
|
544
|
+
"PostToolUse",
|
|
545
|
+
"PostToolUseFailure",
|
|
546
|
+
"PermissionRequest",
|
|
547
|
+
"SubagentStart",
|
|
548
|
+
"SubagentStop",
|
|
549
|
+
"PreCompact",
|
|
550
|
+
"PostCompact",
|
|
551
|
+
"Stop",
|
|
552
|
+
"StopFailure"
|
|
553
|
+
];
|
|
554
|
+
var claudeIdentityFieldsSchema = z2.object({
|
|
555
|
+
session_id: z2.string().min(1),
|
|
556
|
+
hook_event_name: z2.string().min(1),
|
|
557
|
+
cwd: z2.string().min(1).optional(),
|
|
558
|
+
prompt_id: z2.string().min(1).optional(),
|
|
559
|
+
agent_id: z2.string().min(1).optional(),
|
|
560
|
+
tool_use_id: z2.string().min(1).optional(),
|
|
561
|
+
/** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */
|
|
562
|
+
stop_hook_active: z2.boolean().optional()
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
// src/providers/claude/registration.ts
|
|
566
|
+
var CLAUDE_HOOK_EVENTS_MODELLED = CLAUDE_HOOK_EVENT_NAMES;
|
|
567
|
+
var CLAUDE_REGISTRABLE_HOOK_EVENTS = Object.freeze([
|
|
568
|
+
"SessionStart",
|
|
569
|
+
"UserPromptSubmit",
|
|
570
|
+
"PreToolUse",
|
|
571
|
+
"PostToolUse",
|
|
572
|
+
"PostToolUseFailure",
|
|
573
|
+
"SubagentStart",
|
|
574
|
+
"SubagentStop",
|
|
575
|
+
"PostCompact",
|
|
576
|
+
"Stop",
|
|
577
|
+
"StopFailure",
|
|
578
|
+
"SessionEnd"
|
|
579
|
+
]);
|
|
580
|
+
var CLAUDE_UNREGISTERED_HOOK_EVENTS = Object.freeze({
|
|
581
|
+
PermissionRequest: "the adapter reports permission decisions on the paired tool.end event, so a hook here would emit nothing",
|
|
582
|
+
PreCompact: "the adapter reports compaction once it completes, at PostCompact, so a hook here would emit nothing"
|
|
583
|
+
});
|
|
584
|
+
var buildEntry = (options) => ({
|
|
585
|
+
type: "command",
|
|
586
|
+
command: options.command,
|
|
587
|
+
...options.timeoutSeconds === void 0 ? {} : { timeout: options.timeoutSeconds }
|
|
588
|
+
});
|
|
589
|
+
var mergeClaudeHookRegistration = (options) => mergeNestedHookRegistration({
|
|
590
|
+
...options.existing === void 0 ? {} : { existing: options.existing },
|
|
591
|
+
events: options.events ?? CLAUDE_REGISTRABLE_HOOK_EVENTS,
|
|
592
|
+
entry: buildEntry(options),
|
|
593
|
+
...options.matcher === void 0 ? {} : { matcher: options.matcher },
|
|
594
|
+
identifies: options.identifies
|
|
595
|
+
});
|
|
596
|
+
var removeClaudeHookRegistration = (options) => removeNestedHookRegistrations({
|
|
597
|
+
...options.existing === void 0 ? {} : { existing: options.existing },
|
|
598
|
+
...options.events === void 0 ? {} : { events: options.events },
|
|
599
|
+
identifies: options.identifies
|
|
600
|
+
});
|
|
601
|
+
var readClaudeHookRegistrations = readNestedHookRegistrations;
|
|
602
|
+
|
|
603
|
+
// src/providers/codex/payload.ts
|
|
604
|
+
import { z as z3 } from "zod";
|
|
605
|
+
var permissionModeSchema = z3.enum([
|
|
606
|
+
"default",
|
|
607
|
+
"acceptEdits",
|
|
608
|
+
"plan",
|
|
609
|
+
"dontAsk",
|
|
610
|
+
"bypassPermissions"
|
|
611
|
+
]);
|
|
612
|
+
var codexUsageSchema = z3.object({
|
|
613
|
+
input_tokens: z3.number().int().min(0).optional(),
|
|
614
|
+
cached_input_tokens: z3.number().int().min(0).optional(),
|
|
615
|
+
output_tokens: z3.number().int().min(0).optional(),
|
|
616
|
+
reasoning_output_tokens: z3.number().int().min(0).optional(),
|
|
617
|
+
total_tokens: z3.number().int().min(0).optional()
|
|
618
|
+
});
|
|
619
|
+
var baseFields = {
|
|
620
|
+
session_id: z3.string().min(1).max(256),
|
|
621
|
+
cwd: z3.string().min(1).max(4096).optional(),
|
|
622
|
+
model: z3.string().min(1).max(256).optional(),
|
|
623
|
+
permission_mode: permissionModeSchema.optional(),
|
|
624
|
+
transcript_path: z3.string().min(1).max(4096).optional(),
|
|
625
|
+
codex_version: z3.string().min(1).max(64).optional(),
|
|
626
|
+
/** Not part of the documented protocol; lets tests and replay stay deterministic. */
|
|
627
|
+
occurred_at: z3.number().int().min(0).optional()
|
|
628
|
+
};
|
|
629
|
+
var codexSessionStartPayloadSchema = z3.object({
|
|
630
|
+
...baseFields,
|
|
631
|
+
hook_event_name: z3.literal("SessionStart"),
|
|
632
|
+
source: z3.enum(["startup", "resume", "clear", "compact"]).optional()
|
|
633
|
+
});
|
|
634
|
+
var codexUserPromptSubmitPayloadSchema = z3.object({
|
|
635
|
+
...baseFields,
|
|
636
|
+
hook_event_name: z3.literal("UserPromptSubmit"),
|
|
637
|
+
turn_id: z3.string().min(1).max(256).optional(),
|
|
638
|
+
prompt: z3.string().max(1e6).optional()
|
|
639
|
+
});
|
|
640
|
+
var codexPreToolUsePayloadSchema = z3.object({
|
|
641
|
+
...baseFields,
|
|
642
|
+
hook_event_name: z3.literal("PreToolUse"),
|
|
643
|
+
turn_id: z3.string().min(1).max(256).optional(),
|
|
644
|
+
tool_name: z3.string().min(1).max(256),
|
|
645
|
+
tool_call_id: z3.string().min(1).max(256).optional(),
|
|
646
|
+
tool_input: z3.unknown().optional()
|
|
647
|
+
});
|
|
648
|
+
var codexPermissionRequestPayloadSchema = z3.object({
|
|
649
|
+
...baseFields,
|
|
650
|
+
hook_event_name: z3.literal("PermissionRequest"),
|
|
651
|
+
turn_id: z3.string().min(1).max(256).optional(),
|
|
652
|
+
tool_name: z3.string().min(1).max(256).optional(),
|
|
653
|
+
tool_call_id: z3.string().min(1).max(256).optional(),
|
|
654
|
+
tool_input: z3.unknown().optional()
|
|
655
|
+
});
|
|
656
|
+
var codexPostToolUsePayloadSchema = z3.object({
|
|
657
|
+
...baseFields,
|
|
658
|
+
hook_event_name: z3.literal("PostToolUse"),
|
|
659
|
+
turn_id: z3.string().min(1).max(256).optional(),
|
|
660
|
+
tool_name: z3.string().min(1).max(256),
|
|
661
|
+
tool_call_id: z3.string().min(1).max(256).optional(),
|
|
662
|
+
tool_input: z3.unknown().optional(),
|
|
663
|
+
tool_response: z3.unknown().optional(),
|
|
664
|
+
permission_decision: z3.enum(["allowed", "denied", "deferred"]).optional(),
|
|
665
|
+
duration_ms: z3.number().min(0).optional()
|
|
666
|
+
});
|
|
667
|
+
var codexPreCompactPayloadSchema = z3.object({
|
|
668
|
+
...baseFields,
|
|
669
|
+
hook_event_name: z3.literal("PreCompact"),
|
|
670
|
+
trigger: z3.enum(["auto", "manual"]).optional(),
|
|
671
|
+
context_tokens_before: z3.number().int().min(0).optional()
|
|
672
|
+
});
|
|
673
|
+
var codexPostCompactPayloadSchema = z3.object({
|
|
674
|
+
...baseFields,
|
|
675
|
+
hook_event_name: z3.literal("PostCompact"),
|
|
676
|
+
trigger: z3.enum(["auto", "manual"]).optional(),
|
|
677
|
+
context_tokens_after: z3.number().int().min(0).optional(),
|
|
678
|
+
dropped_message_count: z3.number().int().min(0).optional(),
|
|
679
|
+
usage: codexUsageSchema.optional()
|
|
680
|
+
});
|
|
681
|
+
var codexSubagentStartPayloadSchema = z3.object({
|
|
682
|
+
...baseFields,
|
|
683
|
+
hook_event_name: z3.literal("SubagentStart"),
|
|
684
|
+
turn_id: z3.string().min(1).max(256).optional(),
|
|
685
|
+
subagent_id: z3.string().min(1).max(256),
|
|
686
|
+
subagent_type: z3.string().min(1).max(256).optional()
|
|
687
|
+
});
|
|
688
|
+
var codexSubagentStopPayloadSchema = z3.object({
|
|
689
|
+
...baseFields,
|
|
690
|
+
hook_event_name: z3.literal("SubagentStop"),
|
|
691
|
+
turn_id: z3.string().min(1).max(256).optional(),
|
|
692
|
+
subagent_id: z3.string().min(1).max(256),
|
|
693
|
+
status: z3.enum(["completed", "failed", "cancelled"]).optional(),
|
|
694
|
+
usage: codexUsageSchema.optional()
|
|
695
|
+
});
|
|
696
|
+
var codexStopPayloadSchema = z3.object({
|
|
697
|
+
...baseFields,
|
|
698
|
+
hook_event_name: z3.literal("Stop"),
|
|
699
|
+
turn_id: z3.string().min(1).max(256).optional(),
|
|
700
|
+
stop_reason: z3.string().min(1).max(256).optional(),
|
|
701
|
+
usage: codexUsageSchema.optional(),
|
|
702
|
+
duration_ms: z3.number().min(0).optional()
|
|
703
|
+
});
|
|
704
|
+
var CODEX_HOOK_EVENT_NAMES = [
|
|
705
|
+
"SessionStart",
|
|
706
|
+
"UserPromptSubmit",
|
|
707
|
+
"PreToolUse",
|
|
708
|
+
"PermissionRequest",
|
|
709
|
+
"PostToolUse",
|
|
710
|
+
"PreCompact",
|
|
711
|
+
"PostCompact",
|
|
712
|
+
"SubagentStart",
|
|
713
|
+
"SubagentStop",
|
|
714
|
+
"Stop"
|
|
715
|
+
];
|
|
716
|
+
var codexHookPayloadSchema = z3.discriminatedUnion("hook_event_name", [
|
|
717
|
+
codexSessionStartPayloadSchema,
|
|
718
|
+
codexUserPromptSubmitPayloadSchema,
|
|
719
|
+
codexPreToolUsePayloadSchema,
|
|
720
|
+
codexPermissionRequestPayloadSchema,
|
|
721
|
+
codexPostToolUsePayloadSchema,
|
|
722
|
+
codexPreCompactPayloadSchema,
|
|
723
|
+
codexPostCompactPayloadSchema,
|
|
724
|
+
codexSubagentStartPayloadSchema,
|
|
725
|
+
codexSubagentStopPayloadSchema,
|
|
726
|
+
codexStopPayloadSchema
|
|
727
|
+
]);
|
|
728
|
+
var codexHookEnvelopeSchema = z3.object({
|
|
729
|
+
session_id: z3.string().min(1),
|
|
730
|
+
hook_event_name: z3.enum(CODEX_HOOK_EVENT_NAMES)
|
|
731
|
+
});
|
|
732
|
+
|
|
733
|
+
// src/providers/codex/registration.ts
|
|
734
|
+
var CODEX_HOOK_EVENTS_MODELLED = CODEX_HOOK_EVENT_NAMES;
|
|
735
|
+
var CODEX_REGISTRABLE_HOOK_EVENTS = Object.freeze([
|
|
736
|
+
"SessionStart",
|
|
737
|
+
"UserPromptSubmit",
|
|
738
|
+
"PreToolUse",
|
|
739
|
+
"PostToolUse",
|
|
740
|
+
"SubagentStart",
|
|
741
|
+
"SubagentStop",
|
|
742
|
+
"PreCompact",
|
|
743
|
+
"PostCompact",
|
|
744
|
+
"Stop"
|
|
745
|
+
]);
|
|
746
|
+
var CODEX_UNREGISTERED_HOOK_EVENTS = Object.freeze({
|
|
747
|
+
PermissionRequest: "the adapter reports the decision on the paired tool.end event, so a hook here would emit nothing",
|
|
748
|
+
SessionEnd: "documented by Codex but not modelled by this adapter; the payload would be rejected (see payload.ts)"
|
|
749
|
+
});
|
|
750
|
+
var buildEntry2 = (options) => ({
|
|
751
|
+
type: "command",
|
|
752
|
+
command: options.command,
|
|
753
|
+
...options.timeoutSeconds === void 0 ? {} : { timeout: options.timeoutSeconds }
|
|
754
|
+
});
|
|
755
|
+
var mergeCodexHookRegistration = (options) => mergeNestedHookRegistration({
|
|
756
|
+
...options.existing === void 0 ? {} : { existing: options.existing },
|
|
757
|
+
events: options.events ?? CODEX_REGISTRABLE_HOOK_EVENTS,
|
|
758
|
+
entry: buildEntry2(options),
|
|
759
|
+
...options.matcher === void 0 ? {} : { matcher: options.matcher },
|
|
760
|
+
identifies: options.identifies
|
|
761
|
+
});
|
|
762
|
+
var removeCodexHookRegistration = (options) => removeNestedHookRegistrations({
|
|
763
|
+
...options.existing === void 0 ? {} : { existing: options.existing },
|
|
764
|
+
...options.events === void 0 ? {} : { events: options.events },
|
|
765
|
+
identifies: options.identifies
|
|
766
|
+
});
|
|
767
|
+
var readCodexHookRegistrations = readNestedHookRegistrations;
|
|
768
|
+
var readCodexHooksFeatureFlag = (configToml) => {
|
|
769
|
+
let inFeatures = false;
|
|
770
|
+
for (const line of configToml.split(/\r?\n/)) {
|
|
771
|
+
const trimmed = line.trim();
|
|
772
|
+
if (trimmed.startsWith("#") || trimmed.length === 0) {
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
if (trimmed.startsWith("[")) {
|
|
776
|
+
inFeatures = trimmed === "[features]";
|
|
777
|
+
continue;
|
|
778
|
+
}
|
|
779
|
+
if (!inFeatures) {
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
782
|
+
const match = /^hooks\s*=\s*(true|false)\s*(?:#.*)?$/.exec(trimmed);
|
|
783
|
+
if (match !== null) {
|
|
784
|
+
return match[1] === "false" ? "disabled" : "enabled";
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
return "unset";
|
|
788
|
+
};
|
|
789
|
+
|
|
790
|
+
// src/providers/cursor/payload.ts
|
|
791
|
+
import { z as z4 } from "zod";
|
|
792
|
+
var CURSOR_PROVIDER_ID = "cursor";
|
|
793
|
+
var CURSOR_HOOK_EVENT_NAMES = [
|
|
794
|
+
"sessionStart",
|
|
795
|
+
"sessionEnd",
|
|
796
|
+
"beforeSubmitPrompt",
|
|
797
|
+
"afterAgentResponse",
|
|
798
|
+
"afterAgentThought",
|
|
799
|
+
"preToolUse",
|
|
800
|
+
"postToolUse",
|
|
801
|
+
"postToolUseFailure",
|
|
802
|
+
"beforeShellExecution",
|
|
803
|
+
"afterShellExecution",
|
|
804
|
+
"beforeMCPExecution",
|
|
805
|
+
"afterMCPExecution",
|
|
806
|
+
"beforeReadFile",
|
|
807
|
+
"afterFileEdit",
|
|
808
|
+
"subagentStart",
|
|
809
|
+
"subagentStop",
|
|
810
|
+
"preCompact",
|
|
811
|
+
"stop"
|
|
812
|
+
];
|
|
813
|
+
var CURSOR_UNMODELLED_HOOK_EVENT_NAMES = Object.freeze({
|
|
814
|
+
beforeTabFileRead: "a Tab (inline-completion) hook, not an agent-session hook; it belongs to no generation or tool lifecycle this model expresses",
|
|
815
|
+
afterTabFileEdit: "a Tab (inline-completion) hook, as above",
|
|
816
|
+
workspaceOpen: "an app-lifecycle hook that the reference states omits conversation_id, generation_id, model, session_id, and transcript_path, so it carries no session to attribute telemetry to"
|
|
817
|
+
});
|
|
818
|
+
var CURSOR_DECISION_EVENTS = Object.freeze({
|
|
819
|
+
preToolUse: "permission",
|
|
820
|
+
beforeShellExecution: "permission",
|
|
821
|
+
beforeMCPExecution: "permission",
|
|
822
|
+
beforeReadFile: "permission",
|
|
823
|
+
subagentStart: "permission",
|
|
824
|
+
beforeSubmitPrompt: "continue"
|
|
825
|
+
});
|
|
826
|
+
var modelParamSchema = z4.object({
|
|
827
|
+
id: z4.string(),
|
|
828
|
+
value: z4.string()
|
|
829
|
+
});
|
|
830
|
+
var attachmentSchema = z4.object({
|
|
831
|
+
type: z4.string().optional(),
|
|
832
|
+
file_path: z4.string().optional()
|
|
833
|
+
});
|
|
834
|
+
var fileEditSchema = z4.object({
|
|
835
|
+
old_string: z4.string().optional(),
|
|
836
|
+
new_string: z4.string().optional()
|
|
837
|
+
});
|
|
838
|
+
var usageFields = {
|
|
839
|
+
input_tokens: z4.number().int().min(0).optional(),
|
|
840
|
+
output_tokens: z4.number().int().min(0).optional(),
|
|
841
|
+
cache_read_tokens: z4.number().int().min(0).optional(),
|
|
842
|
+
cache_write_tokens: z4.number().int().min(0).optional()
|
|
843
|
+
};
|
|
844
|
+
var envelopeShape = {
|
|
845
|
+
conversation_id: z4.string().min(1),
|
|
846
|
+
generation_id: z4.string().optional(),
|
|
847
|
+
session_id: z4.string().optional(),
|
|
848
|
+
model: z4.string().optional(),
|
|
849
|
+
model_id: z4.string().optional(),
|
|
850
|
+
model_params: z4.array(modelParamSchema).max(64).optional(),
|
|
851
|
+
cursor_version: z4.string().optional(),
|
|
852
|
+
workspace_roots: z4.array(z4.string()).max(64).optional(),
|
|
853
|
+
cwd: z4.string().optional(),
|
|
854
|
+
/** Never propagated. */
|
|
855
|
+
user_email: z4.string().nullish(),
|
|
856
|
+
/** Never propagated. */
|
|
857
|
+
transcript_path: z4.string().nullish()
|
|
858
|
+
};
|
|
859
|
+
var event = (name, shape) => z4.object({ ...envelopeShape, hook_event_name: z4.literal(name), ...shape });
|
|
860
|
+
var sessionStartPayloadSchema2 = event("sessionStart", {
|
|
861
|
+
is_background_agent: z4.boolean().optional(),
|
|
862
|
+
composer_mode: z4.string().optional()
|
|
863
|
+
});
|
|
864
|
+
var sessionEndPayloadSchema2 = event("sessionEnd", {
|
|
865
|
+
reason: z4.string().optional(),
|
|
866
|
+
duration_ms: z4.number().min(0).optional(),
|
|
867
|
+
is_background_agent: z4.boolean().optional(),
|
|
868
|
+
final_status: z4.string().optional(),
|
|
869
|
+
error_message: z4.string().optional()
|
|
870
|
+
});
|
|
871
|
+
var beforeSubmitPromptPayloadSchema = event("beforeSubmitPrompt", {
|
|
872
|
+
prompt: z4.string().optional(),
|
|
873
|
+
attachments: z4.array(attachmentSchema).max(256).optional(),
|
|
874
|
+
composer_mode: z4.string().optional()
|
|
875
|
+
});
|
|
876
|
+
var afterAgentResponsePayloadSchema = event("afterAgentResponse", {
|
|
877
|
+
text: z4.string().optional(),
|
|
878
|
+
...usageFields
|
|
879
|
+
});
|
|
880
|
+
var afterAgentThoughtPayloadSchema = event("afterAgentThought", {
|
|
881
|
+
text: z4.string().optional(),
|
|
882
|
+
duration_ms: z4.number().min(0).optional()
|
|
883
|
+
});
|
|
884
|
+
var preToolUsePayloadSchema3 = event("preToolUse", {
|
|
885
|
+
tool_name: z4.string().min(1),
|
|
886
|
+
tool_input: z4.unknown().optional(),
|
|
887
|
+
tool_use_id: z4.string().optional(),
|
|
888
|
+
agent_message: z4.string().optional()
|
|
889
|
+
});
|
|
890
|
+
var postToolUsePayloadSchema3 = event("postToolUse", {
|
|
891
|
+
tool_name: z4.string().min(1),
|
|
892
|
+
tool_input: z4.unknown().optional(),
|
|
893
|
+
tool_output: z4.unknown().optional(),
|
|
894
|
+
tool_use_id: z4.string().optional(),
|
|
895
|
+
duration: z4.number().min(0).optional()
|
|
896
|
+
});
|
|
897
|
+
var postToolUseFailurePayloadSchema2 = event("postToolUseFailure", {
|
|
898
|
+
tool_name: z4.string().min(1),
|
|
899
|
+
tool_input: z4.unknown().optional(),
|
|
900
|
+
tool_use_id: z4.string().optional(),
|
|
901
|
+
error_message: z4.string().optional(),
|
|
902
|
+
failure_type: z4.string().optional(),
|
|
903
|
+
duration: z4.number().min(0).optional(),
|
|
904
|
+
is_interrupt: z4.boolean().optional()
|
|
905
|
+
});
|
|
906
|
+
var beforeShellExecutionPayloadSchema = event("beforeShellExecution", {
|
|
907
|
+
command: z4.string(),
|
|
908
|
+
sandbox: z4.boolean().optional()
|
|
909
|
+
});
|
|
910
|
+
var afterShellExecutionPayloadSchema = event("afterShellExecution", {
|
|
911
|
+
command: z4.string(),
|
|
912
|
+
output: z4.string().optional(),
|
|
913
|
+
duration: z4.number().min(0).optional(),
|
|
914
|
+
sandbox: z4.boolean().optional()
|
|
915
|
+
});
|
|
916
|
+
var beforeMcpExecutionPayloadSchema = event("beforeMCPExecution", {
|
|
917
|
+
tool_name: z4.string().min(1),
|
|
918
|
+
tool_input: z4.unknown().optional(),
|
|
919
|
+
url: z4.string().optional(),
|
|
920
|
+
command: z4.string().optional()
|
|
921
|
+
});
|
|
922
|
+
var afterMcpExecutionPayloadSchema = event("afterMCPExecution", {
|
|
923
|
+
tool_name: z4.string().min(1),
|
|
924
|
+
tool_input: z4.unknown().optional(),
|
|
925
|
+
result_json: z4.string().optional(),
|
|
926
|
+
duration: z4.number().min(0).optional()
|
|
927
|
+
});
|
|
928
|
+
var beforeReadFilePayloadSchema = event("beforeReadFile", {
|
|
929
|
+
file_path: z4.string(),
|
|
930
|
+
content: z4.string().optional(),
|
|
931
|
+
attachments: z4.array(attachmentSchema).max(256).optional()
|
|
932
|
+
});
|
|
933
|
+
var afterFileEditPayloadSchema = event("afterFileEdit", {
|
|
934
|
+
file_path: z4.string(),
|
|
935
|
+
edits: z4.array(fileEditSchema).max(1024).optional()
|
|
936
|
+
});
|
|
937
|
+
var subagentStartPayloadSchema2 = event("subagentStart", {
|
|
938
|
+
subagent_id: z4.string().optional(),
|
|
939
|
+
subagent_type: z4.string().optional(),
|
|
940
|
+
task: z4.string().optional(),
|
|
941
|
+
parent_conversation_id: z4.string().optional(),
|
|
942
|
+
tool_call_id: z4.string().optional(),
|
|
943
|
+
subagent_model: z4.string().optional(),
|
|
944
|
+
is_parallel_worker: z4.boolean().optional(),
|
|
945
|
+
git_branch: z4.string().optional()
|
|
946
|
+
});
|
|
947
|
+
var subagentStopPayloadSchema2 = event("subagentStop", {
|
|
948
|
+
subagent_type: z4.string().optional(),
|
|
949
|
+
status: z4.string().optional(),
|
|
950
|
+
task: z4.string().optional(),
|
|
951
|
+
description: z4.string().optional(),
|
|
952
|
+
summary: z4.string().optional(),
|
|
953
|
+
duration_ms: z4.number().min(0).optional(),
|
|
954
|
+
message_count: z4.number().int().min(0).optional(),
|
|
955
|
+
tool_call_count: z4.number().int().min(0).optional(),
|
|
956
|
+
loop_count: z4.number().int().min(0).optional(),
|
|
957
|
+
modified_files: z4.array(z4.string()).max(1024).optional(),
|
|
958
|
+
agent_transcript_path: z4.string().nullish()
|
|
959
|
+
});
|
|
960
|
+
var preCompactPayloadSchema2 = event("preCompact", {
|
|
961
|
+
trigger: z4.string().optional(),
|
|
962
|
+
context_usage_percent: z4.number().optional(),
|
|
963
|
+
context_tokens: z4.number().int().min(0).optional(),
|
|
964
|
+
context_window_size: z4.number().int().min(0).optional(),
|
|
965
|
+
message_count: z4.number().int().min(0).optional(),
|
|
966
|
+
messages_to_compact: z4.number().int().min(0).optional(),
|
|
967
|
+
is_first_compaction: z4.boolean().optional()
|
|
968
|
+
});
|
|
969
|
+
var stopPayloadSchema3 = event("stop", {
|
|
970
|
+
status: z4.string().optional(),
|
|
971
|
+
loop_count: z4.number().int().min(0).optional(),
|
|
972
|
+
...usageFields
|
|
973
|
+
});
|
|
974
|
+
var cursorPayloadSchema = z4.discriminatedUnion("hook_event_name", [
|
|
975
|
+
sessionStartPayloadSchema2,
|
|
976
|
+
sessionEndPayloadSchema2,
|
|
977
|
+
beforeSubmitPromptPayloadSchema,
|
|
978
|
+
afterAgentResponsePayloadSchema,
|
|
979
|
+
afterAgentThoughtPayloadSchema,
|
|
980
|
+
preToolUsePayloadSchema3,
|
|
981
|
+
postToolUsePayloadSchema3,
|
|
982
|
+
postToolUseFailurePayloadSchema2,
|
|
983
|
+
beforeShellExecutionPayloadSchema,
|
|
984
|
+
afterShellExecutionPayloadSchema,
|
|
985
|
+
beforeMcpExecutionPayloadSchema,
|
|
986
|
+
afterMcpExecutionPayloadSchema,
|
|
987
|
+
beforeReadFilePayloadSchema,
|
|
988
|
+
afterFileEditPayloadSchema,
|
|
989
|
+
subagentStartPayloadSchema2,
|
|
990
|
+
subagentStopPayloadSchema2,
|
|
991
|
+
preCompactPayloadSchema2,
|
|
992
|
+
stopPayloadSchema3
|
|
993
|
+
]);
|
|
994
|
+
|
|
995
|
+
// src/providers/cursor/registration.ts
|
|
996
|
+
var CURSOR_HOOK_EVENTS_MODELLED = CURSOR_HOOK_EVENT_NAMES;
|
|
997
|
+
var CURSOR_REGISTRABLE_HOOK_EVENTS = Object.freeze([
|
|
998
|
+
"sessionStart",
|
|
999
|
+
"beforeSubmitPrompt",
|
|
1000
|
+
"preToolUse",
|
|
1001
|
+
"postToolUse",
|
|
1002
|
+
"postToolUseFailure",
|
|
1003
|
+
"afterFileEdit",
|
|
1004
|
+
"preCompact",
|
|
1005
|
+
"stop",
|
|
1006
|
+
"sessionEnd"
|
|
1007
|
+
]);
|
|
1008
|
+
var CURSOR_UNREGISTERED_HOOK_EVENTS = Object.freeze({
|
|
1009
|
+
afterAgentResponse: "the generation's outcome and the same token snapshot arrive on stop; registering both would double-count usage",
|
|
1010
|
+
afterAgentThought: "a reasoning notification with no canonical event type, and its text is never exported",
|
|
1011
|
+
beforeShellExecution: "one shell call also fires preToolUse/postToolUse \u2014 the capture's fired.log shows all four for a single command \u2014 and only the generic pair carries tool_use_id, so registering this one duplicates the tool call",
|
|
1012
|
+
afterShellExecution: "the same shell call also fires postToolUse, which duplicates this tool end and \u2014 unlike this callback \u2014 carries both a tool_use_id and a success/failure signal",
|
|
1013
|
+
beforeMCPExecution: "an MCP call also fires preToolUse/postToolUse, which additionally carry tool_use_id; registering this one duplicates the tool call",
|
|
1014
|
+
afterMCPExecution: "the same MCP call also fires postToolUse, which duplicates this tool end and, unlike this callback, reports a success/failure signal",
|
|
1015
|
+
beforeReadFile: "no completion callback exists for it, so a tool.start emitted here would never close",
|
|
1016
|
+
subagentStart: "subagentStop carries no subagent id to pair with, so no closable delegation lifecycle can be produced",
|
|
1017
|
+
subagentStop: "it carries no subagent id, so it cannot be paired with the subagentStart it ends",
|
|
1018
|
+
beforeTabFileRead: "a Tab (inline-completion) hook, not an agent-session hook; not modelled by this adapter",
|
|
1019
|
+
afterTabFileEdit: "a Tab (inline-completion) hook, not an agent-session hook; not modelled by this adapter",
|
|
1020
|
+
workspaceOpen: "an app-lifecycle hook that carries no conversation_id, so it has no session to attribute telemetry to"
|
|
1021
|
+
});
|
|
1022
|
+
var CURSOR_HOOKS_DOCUMENT_VERSION = 1;
|
|
1023
|
+
var isPlainObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1024
|
+
var buildEntry3 = (input) => ({
|
|
1025
|
+
type: "command",
|
|
1026
|
+
command: input.command,
|
|
1027
|
+
...input.timeoutSeconds === void 0 ? {} : { timeout: input.timeoutSeconds },
|
|
1028
|
+
...input.matcher === void 0 ? {} : { matcher: input.matcher }
|
|
1029
|
+
});
|
|
1030
|
+
var mergeCursorHookRegistration = (input) => {
|
|
1031
|
+
const events = input.events ?? CURSOR_REGISTRABLE_HOOK_EVENTS;
|
|
1032
|
+
const base = isPlainObject3(input.existing) ? { ...input.existing } : {};
|
|
1033
|
+
const existingHooks = isPlainObject3(base.hooks) ? base.hooks : {};
|
|
1034
|
+
const nextHooks = { ...existingHooks };
|
|
1035
|
+
const desired = buildEntry3(input);
|
|
1036
|
+
let changed = false;
|
|
1037
|
+
if (base.version === void 0) {
|
|
1038
|
+
base.version = CURSOR_HOOKS_DOCUMENT_VERSION;
|
|
1039
|
+
changed = true;
|
|
1040
|
+
}
|
|
1041
|
+
for (const event3 of events) {
|
|
1042
|
+
const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
|
|
1043
|
+
const managed = currentList.filter(
|
|
1044
|
+
(entry) => isPlainObject3(entry) && input.identifies(entry)
|
|
1045
|
+
);
|
|
1046
|
+
const [ours] = managed;
|
|
1047
|
+
if (ours === void 0) {
|
|
1048
|
+
nextHooks[event3] = [...currentList, desired];
|
|
1049
|
+
changed = true;
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
const rewritten = { ...ours, ...desired };
|
|
1053
|
+
const next = currentList.filter((entry) => entry === ours || !(isPlainObject3(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
|
|
1054
|
+
const entryChanged = Object.entries(desired).some(([key, value]) => ours[key] !== value);
|
|
1055
|
+
if (entryChanged || managed.length > 1) {
|
|
1056
|
+
changed = true;
|
|
1057
|
+
}
|
|
1058
|
+
nextHooks[event3] = next;
|
|
1059
|
+
}
|
|
1060
|
+
return { config: { ...base, hooks: nextHooks }, changed };
|
|
1061
|
+
};
|
|
1062
|
+
var removeCursorHookRegistration = (input) => {
|
|
1063
|
+
const base = isPlainObject3(input.existing) ? { ...input.existing } : {};
|
|
1064
|
+
if (!isPlainObject3(base.hooks)) {
|
|
1065
|
+
return { config: base, changed: false };
|
|
1066
|
+
}
|
|
1067
|
+
const nextHooks = { ...base.hooks };
|
|
1068
|
+
const events = input.events ?? Object.keys(nextHooks);
|
|
1069
|
+
let changed = false;
|
|
1070
|
+
for (const event3 of events) {
|
|
1071
|
+
const currentList = nextHooks[event3];
|
|
1072
|
+
if (!Array.isArray(currentList)) {
|
|
1073
|
+
continue;
|
|
1074
|
+
}
|
|
1075
|
+
const kept = currentList.filter(
|
|
1076
|
+
(entry) => !(isPlainObject3(entry) && input.identifies(entry))
|
|
1077
|
+
);
|
|
1078
|
+
if (kept.length === currentList.length) {
|
|
1079
|
+
continue;
|
|
1080
|
+
}
|
|
1081
|
+
changed = true;
|
|
1082
|
+
if (kept.length === 0) {
|
|
1083
|
+
delete nextHooks[event3];
|
|
1084
|
+
} else {
|
|
1085
|
+
nextHooks[event3] = kept;
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
if (!changed) {
|
|
1089
|
+
return { config: base, changed: false };
|
|
1090
|
+
}
|
|
1091
|
+
const config = { ...base };
|
|
1092
|
+
if (Object.keys(nextHooks).length === 0) {
|
|
1093
|
+
delete config.hooks;
|
|
1094
|
+
if (Object.keys(config).length === 1 && config.version === CURSOR_HOOKS_DOCUMENT_VERSION) {
|
|
1095
|
+
delete config.version;
|
|
1096
|
+
}
|
|
1097
|
+
} else {
|
|
1098
|
+
config.hooks = nextHooks;
|
|
1099
|
+
}
|
|
1100
|
+
return { config, changed };
|
|
1101
|
+
};
|
|
1102
|
+
var readCursorHookRegistrations = (existing, identifies) => {
|
|
1103
|
+
const found = /* @__PURE__ */ new Map();
|
|
1104
|
+
if (!isPlainObject3(existing) || !isPlainObject3(existing.hooks)) {
|
|
1105
|
+
return found;
|
|
1106
|
+
}
|
|
1107
|
+
for (const [event3, list] of Object.entries(existing.hooks)) {
|
|
1108
|
+
if (!Array.isArray(list)) {
|
|
1109
|
+
continue;
|
|
1110
|
+
}
|
|
1111
|
+
const commands = list.filter(
|
|
1112
|
+
(entry) => isPlainObject3(entry) && typeof entry.command === "string" && identifies(entry)
|
|
1113
|
+
).map((entry) => entry.command);
|
|
1114
|
+
if (commands.length > 0) {
|
|
1115
|
+
found.set(event3, commands);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
return found;
|
|
1119
|
+
};
|
|
1120
|
+
|
|
1121
|
+
// src/providers/gemini/schema.ts
|
|
1122
|
+
import { z as z5 } from "zod";
|
|
1123
|
+
var GEMINI_HOOK_EVENT_NAMES = [
|
|
1124
|
+
"SessionStart",
|
|
1125
|
+
"SessionEnd",
|
|
1126
|
+
"BeforeAgent",
|
|
1127
|
+
"AfterAgent",
|
|
1128
|
+
"BeforeModel",
|
|
1129
|
+
"AfterModel",
|
|
1130
|
+
"BeforeToolSelection",
|
|
1131
|
+
"BeforeTool",
|
|
1132
|
+
"AfterTool",
|
|
1133
|
+
"PreCompress",
|
|
1134
|
+
"Notification"
|
|
1135
|
+
];
|
|
1136
|
+
var baseHookInputSchema = z5.object({
|
|
1137
|
+
session_id: z5.string().min(1),
|
|
1138
|
+
transcript_path: z5.string().optional(),
|
|
1139
|
+
cwd: z5.string().optional(),
|
|
1140
|
+
timestamp: z5.string().min(1).optional()
|
|
1141
|
+
});
|
|
1142
|
+
var llmMessageSchema = z5.object({
|
|
1143
|
+
role: z5.enum(["user", "model", "system"]).optional(),
|
|
1144
|
+
content: z5.union([z5.string(), z5.array(z5.unknown())]).optional()
|
|
1145
|
+
}).loose();
|
|
1146
|
+
var llmRequestConfigSchema = z5.object({
|
|
1147
|
+
temperature: z5.number().optional(),
|
|
1148
|
+
maxOutputTokens: z5.number().int().min(0).optional()
|
|
1149
|
+
}).loose();
|
|
1150
|
+
var geminiLlmRequestSchema = z5.object({
|
|
1151
|
+
model: z5.string().min(1).optional(),
|
|
1152
|
+
messages: z5.array(llmMessageSchema).optional(),
|
|
1153
|
+
config: llmRequestConfigSchema.optional(),
|
|
1154
|
+
toolConfig: z5.unknown().optional()
|
|
1155
|
+
}).loose();
|
|
1156
|
+
var geminiUsageMetadataSchema = z5.object({
|
|
1157
|
+
promptTokenCount: z5.number().int().min(0).optional(),
|
|
1158
|
+
cachedContentTokenCount: z5.number().int().min(0).optional(),
|
|
1159
|
+
candidatesTokenCount: z5.number().int().min(0).optional(),
|
|
1160
|
+
thoughtsTokenCount: z5.number().int().min(0).optional(),
|
|
1161
|
+
totalTokenCount: z5.number().int().min(0).optional()
|
|
1162
|
+
}).loose();
|
|
1163
|
+
var geminiCandidateSchema = z5.object({
|
|
1164
|
+
content: z5.object({
|
|
1165
|
+
role: z5.string().optional(),
|
|
1166
|
+
parts: z5.array(z5.unknown()).optional()
|
|
1167
|
+
}).loose().optional(),
|
|
1168
|
+
finishReason: z5.string().optional(),
|
|
1169
|
+
index: z5.number().int().min(0).optional()
|
|
1170
|
+
}).loose();
|
|
1171
|
+
var geminiLlmResponseSchema = z5.object({
|
|
1172
|
+
/** Whole-response text, set by the translator from `getResponseText`. */
|
|
1173
|
+
text: z5.string().optional(),
|
|
1174
|
+
candidates: z5.array(geminiCandidateSchema).optional(),
|
|
1175
|
+
usageMetadata: geminiUsageMetadataSchema.optional()
|
|
1176
|
+
}).loose();
|
|
1177
|
+
var geminiMcpContextSchema = z5.object({
|
|
1178
|
+
server_name: z5.string().optional(),
|
|
1179
|
+
tool_name: z5.string().optional()
|
|
1180
|
+
}).loose();
|
|
1181
|
+
var geminiToolResponseSchema = z5.object({
|
|
1182
|
+
llmContent: z5.unknown().optional(),
|
|
1183
|
+
returnDisplay: z5.unknown().optional(),
|
|
1184
|
+
error: z5.unknown().optional()
|
|
1185
|
+
}).loose();
|
|
1186
|
+
var sessionStartInputSchema = baseHookInputSchema.extend({
|
|
1187
|
+
hook_event_name: z5.literal("SessionStart"),
|
|
1188
|
+
source: z5.enum(["startup", "resume", "clear"]).optional()
|
|
1189
|
+
});
|
|
1190
|
+
var sessionEndInputSchema = baseHookInputSchema.extend({
|
|
1191
|
+
hook_event_name: z5.literal("SessionEnd"),
|
|
1192
|
+
reason: z5.enum(["exit", "clear", "logout", "prompt_input_exit", "other"]).optional()
|
|
1193
|
+
});
|
|
1194
|
+
var beforeAgentInputSchema = baseHookInputSchema.extend({
|
|
1195
|
+
hook_event_name: z5.literal("BeforeAgent"),
|
|
1196
|
+
prompt: z5.string().optional()
|
|
1197
|
+
});
|
|
1198
|
+
var afterAgentInputSchema = baseHookInputSchema.extend({
|
|
1199
|
+
hook_event_name: z5.literal("AfterAgent"),
|
|
1200
|
+
prompt: z5.string().optional(),
|
|
1201
|
+
prompt_response: z5.string().optional(),
|
|
1202
|
+
stop_hook_active: z5.boolean().optional()
|
|
1203
|
+
});
|
|
1204
|
+
var beforeModelInputSchema = baseHookInputSchema.extend({
|
|
1205
|
+
hook_event_name: z5.literal("BeforeModel"),
|
|
1206
|
+
llm_request: geminiLlmRequestSchema
|
|
1207
|
+
});
|
|
1208
|
+
var afterModelInputSchema = baseHookInputSchema.extend({
|
|
1209
|
+
hook_event_name: z5.literal("AfterModel"),
|
|
1210
|
+
llm_request: geminiLlmRequestSchema,
|
|
1211
|
+
llm_response: geminiLlmResponseSchema
|
|
1212
|
+
});
|
|
1213
|
+
var beforeToolSelectionInputSchema = baseHookInputSchema.extend({
|
|
1214
|
+
hook_event_name: z5.literal("BeforeToolSelection"),
|
|
1215
|
+
llm_request: geminiLlmRequestSchema
|
|
1216
|
+
});
|
|
1217
|
+
var beforeToolInputSchema = baseHookInputSchema.extend({
|
|
1218
|
+
hook_event_name: z5.literal("BeforeTool"),
|
|
1219
|
+
tool_name: z5.string().min(1),
|
|
1220
|
+
tool_input: z5.unknown().optional(),
|
|
1221
|
+
mcp_context: geminiMcpContextSchema.optional(),
|
|
1222
|
+
original_request_name: z5.string().min(1).optional()
|
|
1223
|
+
});
|
|
1224
|
+
var afterToolInputSchema = baseHookInputSchema.extend({
|
|
1225
|
+
hook_event_name: z5.literal("AfterTool"),
|
|
1226
|
+
tool_name: z5.string().min(1),
|
|
1227
|
+
tool_input: z5.unknown().optional(),
|
|
1228
|
+
tool_response: geminiToolResponseSchema.optional(),
|
|
1229
|
+
mcp_context: geminiMcpContextSchema.optional(),
|
|
1230
|
+
original_request_name: z5.string().min(1).optional()
|
|
1231
|
+
});
|
|
1232
|
+
var preCompressInputSchema = baseHookInputSchema.extend({
|
|
1233
|
+
hook_event_name: z5.literal("PreCompress"),
|
|
1234
|
+
trigger: z5.enum(["auto", "manual"]).optional()
|
|
1235
|
+
});
|
|
1236
|
+
var notificationInputSchema = baseHookInputSchema.extend({
|
|
1237
|
+
hook_event_name: z5.literal("Notification"),
|
|
1238
|
+
notification_type: z5.string().optional(),
|
|
1239
|
+
message: z5.string().optional(),
|
|
1240
|
+
details: z5.unknown().optional()
|
|
1241
|
+
});
|
|
1242
|
+
var geminiHookInputSchema = z5.discriminatedUnion("hook_event_name", [
|
|
1243
|
+
sessionStartInputSchema,
|
|
1244
|
+
sessionEndInputSchema,
|
|
1245
|
+
beforeAgentInputSchema,
|
|
1246
|
+
afterAgentInputSchema,
|
|
1247
|
+
beforeModelInputSchema,
|
|
1248
|
+
afterModelInputSchema,
|
|
1249
|
+
beforeToolSelectionInputSchema,
|
|
1250
|
+
beforeToolInputSchema,
|
|
1251
|
+
afterToolInputSchema,
|
|
1252
|
+
preCompressInputSchema,
|
|
1253
|
+
notificationInputSchema
|
|
1254
|
+
]);
|
|
1255
|
+
|
|
1256
|
+
// src/providers/gemini/setup.ts
|
|
1257
|
+
var GEMINI_REGISTRABLE_HOOK_EVENTS = Object.freeze([
|
|
1258
|
+
"SessionStart",
|
|
1259
|
+
"BeforeAgent",
|
|
1260
|
+
"BeforeModel",
|
|
1261
|
+
"AfterModel",
|
|
1262
|
+
"BeforeTool",
|
|
1263
|
+
"AfterTool",
|
|
1264
|
+
"PreCompress",
|
|
1265
|
+
"SessionEnd"
|
|
1266
|
+
]);
|
|
1267
|
+
var GEMINI_UNREGISTERED_HOOK_EVENTS = Object.freeze({
|
|
1268
|
+
AfterAgent: "marks turn completion, which the canonical model has no event for distinct from generation.end",
|
|
1269
|
+
BeforeToolSelection: "carries tool-choice configuration only, so the adapter emits nothing",
|
|
1270
|
+
Notification: "observability-only in this protocol; no canonical event type corresponds"
|
|
1271
|
+
});
|
|
1272
|
+
var GEMINI_HOOKS_CONFIG_FIELDS = Object.freeze([
|
|
1273
|
+
"enabled",
|
|
1274
|
+
"disabled",
|
|
1275
|
+
"notifications"
|
|
1276
|
+
]);
|
|
1277
|
+
var MILLIS_PER_SECOND = 1e3;
|
|
1278
|
+
var buildCommandEntry = (options) => ({
|
|
1279
|
+
name: options.name,
|
|
1280
|
+
type: "command",
|
|
1281
|
+
command: options.command,
|
|
1282
|
+
...options.timeoutSeconds === void 0 ? {} : { timeout: options.timeoutSeconds * MILLIS_PER_SECOND }
|
|
1283
|
+
});
|
|
1284
|
+
var identifiesByName = (name) => (handler) => handler.name === name;
|
|
1285
|
+
var mergeGeminiHookRegistration = (existing, options) => {
|
|
1286
|
+
const events = options.events ?? GEMINI_REGISTRABLE_HOOK_EVENTS;
|
|
1287
|
+
const merged = mergeNestedHookRegistration({
|
|
1288
|
+
existing,
|
|
1289
|
+
events,
|
|
1290
|
+
entry: buildCommandEntry(options),
|
|
1291
|
+
matcher: options.matcher ?? "*",
|
|
1292
|
+
identifies: options.identifies ?? identifiesByName(options.name)
|
|
1293
|
+
});
|
|
1294
|
+
return {
|
|
1295
|
+
settings: merged.document,
|
|
1296
|
+
changed: merged.changed,
|
|
1297
|
+
registeredEvents: merged.conflicts.length > 0 ? [] : events,
|
|
1298
|
+
changes: merged.changes,
|
|
1299
|
+
conflicts: merged.conflicts
|
|
1300
|
+
};
|
|
1301
|
+
};
|
|
1302
|
+
var removeGeminiHookRegistration = (existing, options) => removeNestedHookRegistrations({
|
|
1303
|
+
existing,
|
|
1304
|
+
events: options.events ?? GEMINI_HOOK_EVENT_NAMES,
|
|
1305
|
+
identifies: options.identifies
|
|
1306
|
+
});
|
|
1307
|
+
var readGeminiHookRegistrations = readNestedHookRegistrations;
|
|
1308
|
+
|
|
1309
|
+
// src/errors/index.ts
|
|
1310
|
+
import { z as z8 } from "zod";
|
|
1311
|
+
|
|
1312
|
+
// src/model/primitives.ts
|
|
1313
|
+
import { z as z6 } from "zod";
|
|
1314
|
+
var MAX_IDENTIFIER_LENGTH = 256;
|
|
1315
|
+
var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
|
|
1316
|
+
var MAX_ATTRIBUTE_ARRAY_LENGTH = 128;
|
|
1317
|
+
var nonEmptyStringSchema = z6.string().min(1).max(MAX_IDENTIFIER_LENGTH);
|
|
1318
|
+
var epochMillisSchema = z6.number().int().min(0).max(864e13);
|
|
1319
|
+
var durationMillisSchema = z6.number().min(0).finite();
|
|
1320
|
+
var tokenCountSchema = z6.number().int().min(0);
|
|
1321
|
+
var sequenceNumberSchema = z6.number().int().min(0);
|
|
1322
|
+
var brandedIdSchema = () => z6.string().min(1).max(MAX_IDENTIFIER_LENGTH);
|
|
1323
|
+
var invocationIdSchema = brandedIdSchema().brand();
|
|
1324
|
+
var sessionIdSchema = brandedIdSchema().brand();
|
|
1325
|
+
var eventIdSchema = brandedIdSchema().brand();
|
|
1326
|
+
var WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;
|
|
1327
|
+
var workspaceIdSchema = z6.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
|
|
1328
|
+
var PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
1329
|
+
var providerIdSchema = z6.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
|
|
1330
|
+
var UNKNOWN_PROVIDER_ID = "unknown";
|
|
1331
|
+
var resolvedProviderIdSchema = z6.union([
|
|
1332
|
+
providerIdSchema,
|
|
1333
|
+
z6.literal(UNKNOWN_PROVIDER_ID)
|
|
1334
|
+
]);
|
|
1335
|
+
var attributePrimitiveSchema = z6.union([
|
|
1336
|
+
z6.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
|
|
1337
|
+
z6.number().finite(),
|
|
1338
|
+
z6.boolean()
|
|
1339
|
+
]);
|
|
1340
|
+
var attributeValueSchema = z6.union([
|
|
1341
|
+
attributePrimitiveSchema,
|
|
1342
|
+
z6.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
|
|
1343
|
+
]);
|
|
1344
|
+
var attributesSchema = z6.record(z6.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
|
|
1345
|
+
var detectionConfidenceSchema = z6.enum(["none", "weak", "strong", "exact"]);
|
|
1346
|
+
var DETECTION_CONFIDENCE_RANK = Object.freeze({
|
|
1347
|
+
none: 0,
|
|
1348
|
+
weak: 1,
|
|
1349
|
+
strong: 2,
|
|
1350
|
+
exact: 3
|
|
1351
|
+
});
|
|
1352
|
+
var sourceTransportSchema = z6.enum([
|
|
1353
|
+
"hook-stdin",
|
|
1354
|
+
"cli-argument",
|
|
1355
|
+
"library-call",
|
|
1356
|
+
"test-fixture"
|
|
1357
|
+
]);
|
|
1358
|
+
|
|
1359
|
+
// src/errors/taxonomy.ts
|
|
1360
|
+
import { z as z7 } from "zod";
|
|
1361
|
+
var otelHookErrorCodeSchema = z7.enum([
|
|
1362
|
+
/** Input was not usable at all (empty stdin, unparsable JSON). */
|
|
1363
|
+
"invalid-input",
|
|
1364
|
+
/** Input parsed but failed canonical schema validation. */
|
|
1365
|
+
"schema-validation-failed",
|
|
1366
|
+
/** No adapter claimed the input with sufficient confidence. */
|
|
1367
|
+
"provider-unknown",
|
|
1368
|
+
/** Several adapters claimed the input at the same confidence. */
|
|
1369
|
+
"provider-detection-ambiguous",
|
|
1370
|
+
/** An adapter threw or returned a malformed result. */
|
|
1371
|
+
"provider-adapter-failure",
|
|
1372
|
+
/** Two identity claims disagreed at equal confidence. */
|
|
1373
|
+
"identity-conflict",
|
|
1374
|
+
/** Required identity fields were absent. */
|
|
1375
|
+
"identity-incomplete",
|
|
1376
|
+
/** A usage report violated the canonical usage invariants. */
|
|
1377
|
+
"usage-invalid",
|
|
1378
|
+
/** The state store could not be read or written. */
|
|
1379
|
+
"state-store-failure",
|
|
1380
|
+
/** The telemetry sink rejected or could not deliver a batch. */
|
|
1381
|
+
"telemetry-export-failure",
|
|
1382
|
+
/** Content reached the sink boundary in a state the policy forbids. */
|
|
1383
|
+
"privacy-policy-violation",
|
|
1384
|
+
/** Configuration could not be resolved. */
|
|
1385
|
+
"configuration-invalid",
|
|
1386
|
+
/** A configured bound (events, batch size) dropped data. */
|
|
1387
|
+
"limit-exceeded",
|
|
1388
|
+
/**
|
|
1389
|
+
* No replay-stable delivery identifier was available for a callback while
|
|
1390
|
+
* deduplication was required.
|
|
1391
|
+
*/
|
|
1392
|
+
"delivery-identifier-unavailable",
|
|
1393
|
+
"delivery-claim-superseded",
|
|
1394
|
+
/** Anything unanticipated. Always reported, never fatal to the host. */
|
|
1395
|
+
"internal-error"
|
|
1396
|
+
]);
|
|
1397
|
+
var errorSeveritySchema = z7.enum(["warning", "error"]);
|
|
1398
|
+
var errorPhaseSchema = z7.enum([
|
|
1399
|
+
"configuration",
|
|
1400
|
+
"detection",
|
|
1401
|
+
"identity",
|
|
1402
|
+
"parsing",
|
|
1403
|
+
"normalization",
|
|
1404
|
+
"privacy",
|
|
1405
|
+
"state",
|
|
1406
|
+
"export",
|
|
1407
|
+
"shutdown"
|
|
1408
|
+
]);
|
|
1409
|
+
var failurePostureSchema = z7.enum(["fail-open", "fail-closed-attribution"]);
|
|
1410
|
+
var ERROR_TAXONOMY = Object.freeze({
|
|
1411
|
+
"invalid-input": {
|
|
1412
|
+
code: "invalid-input",
|
|
1413
|
+
severity: "warning",
|
|
1414
|
+
posture: "fail-open",
|
|
1415
|
+
retryable: false,
|
|
1416
|
+
summary: "Input could not be read or decoded."
|
|
1417
|
+
},
|
|
1418
|
+
"schema-validation-failed": {
|
|
1419
|
+
code: "schema-validation-failed",
|
|
1420
|
+
severity: "error",
|
|
1421
|
+
posture: "fail-closed-attribution",
|
|
1422
|
+
retryable: false,
|
|
1423
|
+
summary: "A canonical event failed schema validation and was dropped."
|
|
1424
|
+
},
|
|
1425
|
+
"provider-unknown": {
|
|
1426
|
+
code: "provider-unknown",
|
|
1427
|
+
severity: "warning",
|
|
1428
|
+
posture: "fail-closed-attribution",
|
|
1429
|
+
retryable: false,
|
|
1430
|
+
summary: "No adapter recognized the source provider; the input stays unattributed."
|
|
1431
|
+
},
|
|
1432
|
+
"provider-detection-ambiguous": {
|
|
1433
|
+
code: "provider-detection-ambiguous",
|
|
1434
|
+
severity: "warning",
|
|
1435
|
+
posture: "fail-closed-attribution",
|
|
1436
|
+
retryable: false,
|
|
1437
|
+
summary: "Multiple adapters claimed the input at equal confidence."
|
|
1438
|
+
},
|
|
1439
|
+
"provider-adapter-failure": {
|
|
1440
|
+
code: "provider-adapter-failure",
|
|
1441
|
+
severity: "error",
|
|
1442
|
+
posture: "fail-open",
|
|
1443
|
+
retryable: false,
|
|
1444
|
+
summary: "A provider adapter failed while parsing."
|
|
1445
|
+
},
|
|
1446
|
+
"identity-conflict": {
|
|
1447
|
+
code: "identity-conflict",
|
|
1448
|
+
severity: "error",
|
|
1449
|
+
posture: "fail-closed-attribution",
|
|
1450
|
+
retryable: false,
|
|
1451
|
+
summary: "Identity claims disagreed; attribution was declined."
|
|
1452
|
+
},
|
|
1453
|
+
"identity-incomplete": {
|
|
1454
|
+
code: "identity-incomplete",
|
|
1455
|
+
severity: "warning",
|
|
1456
|
+
posture: "fail-closed-attribution",
|
|
1457
|
+
retryable: false,
|
|
1458
|
+
summary: "Required identity fields were missing; attribution was declined."
|
|
1459
|
+
},
|
|
1460
|
+
"usage-invalid": {
|
|
1461
|
+
code: "usage-invalid",
|
|
1462
|
+
severity: "error",
|
|
1463
|
+
posture: "fail-open",
|
|
1464
|
+
retryable: false,
|
|
1465
|
+
summary: "A usage report violated the canonical usage invariants."
|
|
1466
|
+
},
|
|
1467
|
+
"state-store-failure": {
|
|
1468
|
+
code: "state-store-failure",
|
|
1469
|
+
severity: "warning",
|
|
1470
|
+
posture: "fail-open",
|
|
1471
|
+
retryable: true,
|
|
1472
|
+
summary: "State could not be read or written; derived values may be incomplete."
|
|
1473
|
+
},
|
|
1474
|
+
"telemetry-export-failure": {
|
|
1475
|
+
code: "telemetry-export-failure",
|
|
1476
|
+
severity: "warning",
|
|
1477
|
+
posture: "fail-open",
|
|
1478
|
+
retryable: true,
|
|
1479
|
+
summary: "The telemetry sink could not accept a batch."
|
|
1480
|
+
},
|
|
1481
|
+
"privacy-policy-violation": {
|
|
1482
|
+
code: "privacy-policy-violation",
|
|
1483
|
+
severity: "error",
|
|
1484
|
+
posture: "fail-closed-attribution",
|
|
1485
|
+
retryable: false,
|
|
1486
|
+
summary: "Content violated the resolved privacy policy and was dropped."
|
|
1487
|
+
},
|
|
1488
|
+
"configuration-invalid": {
|
|
1489
|
+
code: "configuration-invalid",
|
|
1490
|
+
severity: "error",
|
|
1491
|
+
posture: "fail-open",
|
|
1492
|
+
retryable: false,
|
|
1493
|
+
summary: "Configuration could not be resolved; defaults apply."
|
|
1494
|
+
},
|
|
1495
|
+
"limit-exceeded": {
|
|
1496
|
+
code: "limit-exceeded",
|
|
1497
|
+
severity: "warning",
|
|
1498
|
+
posture: "fail-open",
|
|
1499
|
+
retryable: false,
|
|
1500
|
+
summary: "A configured bound was reached and data was dropped."
|
|
1501
|
+
},
|
|
1502
|
+
"delivery-identifier-unavailable": {
|
|
1503
|
+
code: "delivery-identifier-unavailable",
|
|
1504
|
+
severity: "warning",
|
|
1505
|
+
// Fail-open: the observation is still attributed and exported. Only the
|
|
1506
|
+
// at-most-once guarantee is missing, and refusing the telemetry to protect
|
|
1507
|
+
// a duplicate count would trade a certain loss for a possible one.
|
|
1508
|
+
posture: "fail-open",
|
|
1509
|
+
retryable: false,
|
|
1510
|
+
summary: "No replay-stable delivery identifier was available; this callback was exported without deduplication."
|
|
1511
|
+
},
|
|
1512
|
+
"delivery-claim-superseded": {
|
|
1513
|
+
code: "delivery-claim-superseded",
|
|
1514
|
+
severity: "warning",
|
|
1515
|
+
// Fail-open, and specifically *not* silent. A peer reclaimed this callback's
|
|
1516
|
+
// claim while this process was still working on it, which means the
|
|
1517
|
+
// configured stale window is shorter than this installation's real worst
|
|
1518
|
+
// case. Both processes may now have exported the callback, so the
|
|
1519
|
+
// at-most-once guarantee did not hold for it — the only honest response is
|
|
1520
|
+
// to say so and let the operator raise the window.
|
|
1521
|
+
posture: "fail-open",
|
|
1522
|
+
retryable: false,
|
|
1523
|
+
summary: "A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice."
|
|
1524
|
+
},
|
|
1525
|
+
"internal-error": {
|
|
1526
|
+
code: "internal-error",
|
|
1527
|
+
severity: "error",
|
|
1528
|
+
posture: "fail-open",
|
|
1529
|
+
retryable: false,
|
|
1530
|
+
summary: "An unexpected failure was contained."
|
|
1531
|
+
}
|
|
1532
|
+
});
|
|
1533
|
+
var attributionOutcomeSchema = z7.enum([
|
|
1534
|
+
/** Identity resolved; events carry provider and session identity. */
|
|
1535
|
+
"attributed",
|
|
1536
|
+
/** Identity could not be established safely; nothing was attributed. */
|
|
1537
|
+
"declined",
|
|
1538
|
+
/** Attribution was attempted and failed unexpectedly. */
|
|
1539
|
+
"failed",
|
|
1540
|
+
/** Input was recognized but intentionally carried no telemetry. */
|
|
1541
|
+
"not-applicable"
|
|
1542
|
+
]);
|
|
1543
|
+
var attributionReasonSchema = z7.enum([
|
|
1544
|
+
"provider-unknown",
|
|
1545
|
+
"provider-detection-ambiguous",
|
|
1546
|
+
"identity-conflict",
|
|
1547
|
+
"identity-incomplete",
|
|
1548
|
+
"adapter-ignored-input",
|
|
1549
|
+
"adapter-failure",
|
|
1550
|
+
"invalid-input",
|
|
1551
|
+
"internal-error"
|
|
1552
|
+
]);
|
|
1553
|
+
|
|
1554
|
+
// src/errors/index.ts
|
|
1555
|
+
var otelHookErrorInfoSchema = z8.strictObject({
|
|
1556
|
+
code: otelHookErrorCodeSchema,
|
|
1557
|
+
severity: errorSeveritySchema,
|
|
1558
|
+
phase: errorPhaseSchema,
|
|
1559
|
+
posture: failurePostureSchema,
|
|
1560
|
+
retryable: z8.boolean(),
|
|
1561
|
+
message: z8.string().min(1).max(512),
|
|
1562
|
+
details: attributesSchema.optional(),
|
|
1563
|
+
occurredAt: epochMillisSchema.optional()
|
|
1564
|
+
});
|
|
1565
|
+
|
|
1566
|
+
// src/model/identity.ts
|
|
1567
|
+
import { z as z9 } from "zod";
|
|
1568
|
+
var workspaceKeySourceSchema = z9.enum([
|
|
1569
|
+
"git-remote",
|
|
1570
|
+
"git-root",
|
|
1571
|
+
"working-directory",
|
|
1572
|
+
"explicit",
|
|
1573
|
+
"unknown"
|
|
1574
|
+
]);
|
|
1575
|
+
var workspaceIdentitySchema = z9.strictObject({
|
|
1576
|
+
workspaceId: workspaceIdSchema,
|
|
1577
|
+
keySource: workspaceKeySourceSchema,
|
|
1578
|
+
/** Repository name only; never an owner path or URL with credentials. */
|
|
1579
|
+
repositoryName: nonEmptyStringSchema.optional(),
|
|
1580
|
+
vcsBranchName: nonEmptyStringSchema.optional(),
|
|
1581
|
+
/** Opaque handle for the checked-out revision. */
|
|
1582
|
+
vcsRevisionId: nonEmptyStringSchema.optional()
|
|
1583
|
+
}).readonly();
|
|
1584
|
+
var sourceProvenanceSchema = z9.strictObject({
|
|
1585
|
+
providerId: resolvedProviderIdSchema,
|
|
1586
|
+
providerVersion: nonEmptyStringSchema.optional(),
|
|
1587
|
+
adapterId: nonEmptyStringSchema,
|
|
1588
|
+
adapterVersion: nonEmptyStringSchema,
|
|
1589
|
+
detectionConfidence: detectionConfidenceSchema,
|
|
1590
|
+
/** The provider's own name for the source event, e.g. a hook event name. */
|
|
1591
|
+
sourceEventName: nonEmptyStringSchema.optional(),
|
|
1592
|
+
transport: sourceTransportSchema
|
|
1593
|
+
}).readonly();
|
|
1594
|
+
var consumerAttributesSchema = attributesSchema.readonly();
|
|
1595
|
+
var invocationIdentitySchema = z9.strictObject({
|
|
1596
|
+
invocationId: invocationIdSchema,
|
|
1597
|
+
sessionId: sessionIdSchema,
|
|
1598
|
+
/** Set when this invocation runs beneath another agent invocation. */
|
|
1599
|
+
parentInvocationId: invocationIdSchema.optional(),
|
|
1600
|
+
/** Root of the session tree when the provider exposes one. */
|
|
1601
|
+
rootSessionId: sessionIdSchema.optional(),
|
|
1602
|
+
/** Stable handle for the agent process/instance, when available. */
|
|
1603
|
+
agentInstanceId: nonEmptyStringSchema.optional(),
|
|
1604
|
+
provenance: sourceProvenanceSchema,
|
|
1605
|
+
workspace: workspaceIdentitySchema,
|
|
1606
|
+
startedAt: epochMillisSchema,
|
|
1607
|
+
consumerAttributes: consumerAttributesSchema
|
|
1608
|
+
}).readonly();
|
|
1609
|
+
var identityClaimFieldsSchema = z9.strictObject({
|
|
1610
|
+
invocationId: invocationIdSchema.optional(),
|
|
1611
|
+
sessionId: sessionIdSchema.optional(),
|
|
1612
|
+
parentInvocationId: invocationIdSchema.optional(),
|
|
1613
|
+
rootSessionId: sessionIdSchema.optional(),
|
|
1614
|
+
agentInstanceId: nonEmptyStringSchema.optional(),
|
|
1615
|
+
workspace: workspaceIdentitySchema.optional(),
|
|
1616
|
+
startedAt: epochMillisSchema.optional()
|
|
1617
|
+
});
|
|
1618
|
+
var identityClaimSchema = z9.strictObject({
|
|
1619
|
+
/** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
|
|
1620
|
+
source: nonEmptyStringSchema,
|
|
1621
|
+
confidence: detectionConfidenceSchema,
|
|
1622
|
+
fields: identityClaimFieldsSchema
|
|
1623
|
+
});
|
|
1624
|
+
|
|
1625
|
+
// src/providers/adapter.ts
|
|
1626
|
+
import { z as z15 } from "zod";
|
|
1627
|
+
|
|
1628
|
+
// src/model/events.ts
|
|
1629
|
+
import { z as z14 } from "zod";
|
|
1630
|
+
|
|
1631
|
+
// src/model/content.ts
|
|
1632
|
+
import { z as z10 } from "zod";
|
|
1633
|
+
var contentKindSchema = z10.enum([
|
|
1634
|
+
"prompt",
|
|
1635
|
+
"response",
|
|
1636
|
+
"reasoning",
|
|
1637
|
+
"tool-input",
|
|
1638
|
+
"tool-output",
|
|
1639
|
+
"error-message",
|
|
1640
|
+
"system-instruction",
|
|
1641
|
+
"attachment"
|
|
1642
|
+
]);
|
|
1643
|
+
var contentRoleSchema = z10.enum(["user", "assistant", "system", "tool", "unknown"]);
|
|
1644
|
+
var contentDisclosureSchema = z10.enum(["omitted", "masked", "redacted", "raw"]);
|
|
1645
|
+
var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
|
|
1646
|
+
var contentFactSchema = z10.strictObject({
|
|
1647
|
+
kind: contentKindSchema,
|
|
1648
|
+
role: contentRoleSchema.optional(),
|
|
1649
|
+
/** Unicode code point count of the original content. */
|
|
1650
|
+
characterLength: z10.number().int().min(0),
|
|
1651
|
+
/** UTF-8 byte length of the original content. */
|
|
1652
|
+
byteLength: z10.number().int().min(0),
|
|
1653
|
+
/** Stable salted digest of the original content. */
|
|
1654
|
+
contentHash: z10.string().regex(CONTENT_HASH_PATTERN),
|
|
1655
|
+
disclosure: contentDisclosureSchema,
|
|
1656
|
+
/** Disclosed text, bounded by the privacy policy. Absent when omitted. */
|
|
1657
|
+
text: z10.string().optional(),
|
|
1658
|
+
/** True when `text` was cut short by the configured string bound. */
|
|
1659
|
+
truncated: z10.boolean(),
|
|
1660
|
+
/** Number of secret-looking spans replaced while producing `text`. */
|
|
1661
|
+
secretsRedacted: z10.number().int().min(0),
|
|
1662
|
+
/** Optional non-sensitive label, e.g. a MIME type or tool name. */
|
|
1663
|
+
label: nonEmptyStringSchema.optional()
|
|
1664
|
+
});
|
|
1665
|
+
var contentFactsSchema = z10.array(contentFactSchema).max(64);
|
|
1666
|
+
|
|
1667
|
+
// src/model/extensions.ts
|
|
1668
|
+
import { z as z11 } from "zod";
|
|
1669
|
+
var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
|
|
1670
|
+
var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
|
|
1671
|
+
"otelhook",
|
|
1672
|
+
"otel",
|
|
1673
|
+
"telemetry"
|
|
1674
|
+
]);
|
|
1675
|
+
var MAX_EXTENSION_ENTRIES = 64;
|
|
1676
|
+
var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
|
|
1677
|
+
var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
|
|
1678
|
+
var extensionsSchema = z11.record(z11.string(), attributeValueSchema).check((ctx) => {
|
|
1679
|
+
const keys = Object.keys(ctx.value);
|
|
1680
|
+
if (keys.length > MAX_EXTENSION_ENTRIES) {
|
|
1681
|
+
ctx.issues.push({
|
|
1682
|
+
code: "custom",
|
|
1683
|
+
input: ctx.value,
|
|
1684
|
+
message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
for (const key of keys) {
|
|
1688
|
+
if (!EXTENSION_KEY_PATTERN.test(key)) {
|
|
1689
|
+
ctx.issues.push({
|
|
1690
|
+
code: "custom",
|
|
1691
|
+
input: ctx.value,
|
|
1692
|
+
path: [key],
|
|
1693
|
+
message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
|
|
1694
|
+
});
|
|
1695
|
+
continue;
|
|
1696
|
+
}
|
|
1697
|
+
if (isReservedExtensionNamespace(key)) {
|
|
1698
|
+
ctx.issues.push({
|
|
1699
|
+
code: "custom",
|
|
1700
|
+
input: ctx.value,
|
|
1701
|
+
path: [key],
|
|
1702
|
+
message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
|
|
1703
|
+
});
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
});
|
|
1707
|
+
var EMPTY_EXTENSIONS = Object.freeze({});
|
|
1708
|
+
var emptyExtensions = () => ({});
|
|
1709
|
+
|
|
1710
|
+
// src/model/usage.ts
|
|
1711
|
+
import { z as z12 } from "zod";
|
|
1712
|
+
var usageTemporalitySchema = z12.enum(["delta", "cumulative"]);
|
|
1713
|
+
var cacheCreationAccountingSchema = z12.enum([
|
|
1714
|
+
"included-in-input",
|
|
1715
|
+
"disjoint-from-input",
|
|
1716
|
+
"not-reported"
|
|
1717
|
+
]);
|
|
1718
|
+
var providerTotalAgreementSchema = z12.enum(["unreported", "agrees", "disagrees"]);
|
|
1719
|
+
var usageReportSchema = z12.strictObject({
|
|
1720
|
+
temporality: usageTemporalitySchema,
|
|
1721
|
+
/** Inclusive input tokens. */
|
|
1722
|
+
inputTokens: tokenCountSchema.optional(),
|
|
1723
|
+
/** Subset of `inputTokens` served from a prompt cache. */
|
|
1724
|
+
cachedInputTokens: tokenCountSchema.optional(),
|
|
1725
|
+
/** Tokens written to a prompt cache. */
|
|
1726
|
+
cacheCreationInputTokens: tokenCountSchema.optional(),
|
|
1727
|
+
/** Required when `cacheCreationInputTokens` is present and non-zero. */
|
|
1728
|
+
cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
|
|
1729
|
+
/** Inclusive output tokens. */
|
|
1730
|
+
outputTokens: tokenCountSchema.optional(),
|
|
1731
|
+
/** Subset of `outputTokens` spent on reasoning. */
|
|
1732
|
+
reasoningOutputTokens: tokenCountSchema.optional(),
|
|
1733
|
+
/** Total exactly as the provider reported it, if it reported one. */
|
|
1734
|
+
providerTotalTokens: tokenCountSchema.optional()
|
|
1735
|
+
});
|
|
1736
|
+
var canonicalUsageSchema = z12.strictObject({
|
|
1737
|
+
temporality: usageTemporalitySchema,
|
|
1738
|
+
inputTokens: tokenCountSchema,
|
|
1739
|
+
cachedInputTokens: tokenCountSchema,
|
|
1740
|
+
cacheCreationInputTokens: tokenCountSchema,
|
|
1741
|
+
cacheCreationAccounting: cacheCreationAccountingSchema,
|
|
1742
|
+
outputTokens: tokenCountSchema,
|
|
1743
|
+
reasoningOutputTokens: tokenCountSchema,
|
|
1744
|
+
/** Derived: input tokens that were neither cache reads nor cache writes. */
|
|
1745
|
+
uncachedInputTokens: tokenCountSchema,
|
|
1746
|
+
/** Derived: canonical billable total. */
|
|
1747
|
+
totalTokens: tokenCountSchema,
|
|
1748
|
+
providerTotalTokens: tokenCountSchema.optional(),
|
|
1749
|
+
providerTotalAgreement: providerTotalAgreementSchema
|
|
1750
|
+
}).check((ctx) => {
|
|
1751
|
+
const usage = ctx.value;
|
|
1752
|
+
const push = (message) => {
|
|
1753
|
+
ctx.issues.push({ code: "custom", input: usage, message });
|
|
1754
|
+
};
|
|
1755
|
+
if (usage.cachedInputTokens > usage.inputTokens) {
|
|
1756
|
+
push("cachedInputTokens must not exceed inputTokens (it is a subset)");
|
|
1757
|
+
}
|
|
1758
|
+
if (usage.reasoningOutputTokens > usage.outputTokens) {
|
|
1759
|
+
push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
|
|
1760
|
+
}
|
|
1761
|
+
if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
|
|
1762
|
+
push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
|
|
1763
|
+
}
|
|
1764
|
+
const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
|
|
1765
|
+
if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
|
|
1766
|
+
push(
|
|
1767
|
+
"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
|
|
1768
|
+
);
|
|
1769
|
+
}
|
|
1770
|
+
const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
|
|
1771
|
+
if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
|
|
1772
|
+
push(`uncachedInputTokens must equal ${expectedUncached}`);
|
|
1773
|
+
}
|
|
1774
|
+
const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
|
|
1775
|
+
const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
|
|
1776
|
+
if (usage.totalTokens !== expectedTotal) {
|
|
1777
|
+
push(`totalTokens must equal ${expectedTotal}`);
|
|
1778
|
+
}
|
|
1779
|
+
const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
|
|
1780
|
+
if (usage.providerTotalAgreement !== expectedAgreement) {
|
|
1781
|
+
push(`providerTotalAgreement must be ${expectedAgreement}`);
|
|
1782
|
+
}
|
|
1783
|
+
});
|
|
1784
|
+
var normalizeUsage = (report) => {
|
|
1785
|
+
const parsed = usageReportSchema.safeParse(report);
|
|
1786
|
+
if (!parsed.success) {
|
|
1787
|
+
return {
|
|
1788
|
+
status: "invalid",
|
|
1789
|
+
issues: parsed.error.issues.map((issue) => ({
|
|
1790
|
+
code: "invalid-report",
|
|
1791
|
+
message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
|
|
1792
|
+
}))
|
|
1793
|
+
};
|
|
1794
|
+
}
|
|
1795
|
+
const input = parsed.data;
|
|
1796
|
+
const issues = [];
|
|
1797
|
+
const notes = [];
|
|
1798
|
+
const inputTokens = input.inputTokens ?? 0;
|
|
1799
|
+
const cachedInputTokens = input.cachedInputTokens ?? 0;
|
|
1800
|
+
const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
|
|
1801
|
+
const outputTokens = input.outputTokens ?? 0;
|
|
1802
|
+
const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
|
|
1803
|
+
let accounting;
|
|
1804
|
+
if (cacheCreationInputTokens === 0) {
|
|
1805
|
+
accounting = input.cacheCreationAccounting ?? "not-reported";
|
|
1806
|
+
if (accounting !== "not-reported") {
|
|
1807
|
+
notes.push(
|
|
1808
|
+
`cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
|
|
1809
|
+
);
|
|
1810
|
+
}
|
|
1811
|
+
} else if (input.cacheCreationAccounting === void 0) {
|
|
1812
|
+
issues.push({
|
|
1813
|
+
code: "cache-creation-accounting-missing",
|
|
1814
|
+
message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
|
|
1815
|
+
});
|
|
1816
|
+
accounting = "not-reported";
|
|
1817
|
+
} else if (input.cacheCreationAccounting === "not-reported") {
|
|
1818
|
+
issues.push({
|
|
1819
|
+
code: "cache-creation-accounting-missing",
|
|
1820
|
+
message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
|
|
1821
|
+
});
|
|
1822
|
+
accounting = "not-reported";
|
|
1823
|
+
} else {
|
|
1824
|
+
accounting = input.cacheCreationAccounting;
|
|
1825
|
+
}
|
|
1826
|
+
if (cachedInputTokens > inputTokens) {
|
|
1827
|
+
issues.push({
|
|
1828
|
+
code: "cached-exceeds-input",
|
|
1829
|
+
message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
|
|
1830
|
+
});
|
|
1831
|
+
}
|
|
1832
|
+
if (reasoningOutputTokens > outputTokens) {
|
|
1833
|
+
issues.push({
|
|
1834
|
+
code: "reasoning-exceeds-output",
|
|
1835
|
+
message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
|
|
1836
|
+
});
|
|
1837
|
+
}
|
|
1838
|
+
const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
|
|
1839
|
+
if (cachedInputTokens + creationInsideInput > inputTokens) {
|
|
1840
|
+
issues.push({
|
|
1841
|
+
code: "cache-creation-exceeds-input",
|
|
1842
|
+
message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
|
|
1843
|
+
});
|
|
1844
|
+
}
|
|
1845
|
+
if (issues.length > 0) {
|
|
1846
|
+
return { status: "invalid", issues };
|
|
1847
|
+
}
|
|
1848
|
+
const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
|
|
1849
|
+
const totalTokens = inputTokens + creationOutsideInput + outputTokens;
|
|
1850
|
+
const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
|
|
1851
|
+
if (providerTotalAgreement === "disagrees") {
|
|
1852
|
+
notes.push(
|
|
1853
|
+
`providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
|
|
1854
|
+
);
|
|
1855
|
+
}
|
|
1856
|
+
const usage = {
|
|
1857
|
+
temporality: input.temporality,
|
|
1858
|
+
inputTokens,
|
|
1859
|
+
cachedInputTokens,
|
|
1860
|
+
cacheCreationInputTokens,
|
|
1861
|
+
cacheCreationAccounting: accounting,
|
|
1862
|
+
outputTokens,
|
|
1863
|
+
reasoningOutputTokens,
|
|
1864
|
+
uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
|
|
1865
|
+
totalTokens,
|
|
1866
|
+
...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
|
|
1867
|
+
providerTotalAgreement
|
|
1868
|
+
};
|
|
1869
|
+
return { status: "ok", usage, notes };
|
|
1870
|
+
};
|
|
1871
|
+
var UsageNormalizationError = class extends Error {
|
|
1872
|
+
issues;
|
|
1873
|
+
constructor(issues) {
|
|
1874
|
+
super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
|
|
1875
|
+
this.name = "UsageNormalizationError";
|
|
1876
|
+
this.issues = issues;
|
|
1877
|
+
}
|
|
1878
|
+
};
|
|
1879
|
+
var normalizeUsageOrThrow = (report) => {
|
|
1880
|
+
const result = normalizeUsage(report);
|
|
1881
|
+
if (result.status === "invalid") {
|
|
1882
|
+
throw new UsageNormalizationError(result.issues);
|
|
1883
|
+
}
|
|
1884
|
+
return result.usage;
|
|
1885
|
+
};
|
|
1886
|
+
var EMPTY_DELTA_USAGE = Object.freeze(
|
|
1887
|
+
normalizeUsageOrThrow({ temporality: "delta" })
|
|
1888
|
+
);
|
|
1889
|
+
|
|
1890
|
+
// src/model/version.ts
|
|
1891
|
+
import { z as z13 } from "zod";
|
|
1892
|
+
var CANONICAL_SCHEMA_VERSION = 1;
|
|
1893
|
+
var canonicalSchemaVersionSchema = z13.literal(CANONICAL_SCHEMA_VERSION);
|
|
1894
|
+
|
|
1895
|
+
// src/model/events.ts
|
|
1896
|
+
var modelDescriptorSchema = z14.strictObject({
|
|
1897
|
+
modelId: nonEmptyStringSchema,
|
|
1898
|
+
/** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
|
|
1899
|
+
vendor: nonEmptyStringSchema.optional(),
|
|
1900
|
+
family: nonEmptyStringSchema.optional()
|
|
1901
|
+
});
|
|
1902
|
+
var costFactsSchema = z14.strictObject({
|
|
1903
|
+
/** ISO 4217 code. */
|
|
1904
|
+
currency: z14.string().length(3),
|
|
1905
|
+
amount: z14.number().min(0).finite(),
|
|
1906
|
+
source: z14.enum(["provider-reported", "computed"])
|
|
1907
|
+
});
|
|
1908
|
+
var canonicalEventTypeSchema = z14.enum([
|
|
1909
|
+
"session.start",
|
|
1910
|
+
"session.end",
|
|
1911
|
+
"prompt.submitted",
|
|
1912
|
+
"generation.start",
|
|
1913
|
+
"generation.end",
|
|
1914
|
+
"tool.start",
|
|
1915
|
+
"tool.end",
|
|
1916
|
+
"subagent.start",
|
|
1917
|
+
"subagent.end",
|
|
1918
|
+
"compaction.performed",
|
|
1919
|
+
"error.raised"
|
|
1920
|
+
]);
|
|
1921
|
+
var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
|
|
1922
|
+
var outcomeSchema = z14.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
|
|
1923
|
+
var baseEventFields = {
|
|
1924
|
+
schemaVersion: canonicalSchemaVersionSchema,
|
|
1925
|
+
eventId: eventIdSchema,
|
|
1926
|
+
invocationId: invocationIdSchema,
|
|
1927
|
+
sessionId: sessionIdSchema,
|
|
1928
|
+
/** Per-invocation ordering key. Stable across replays of the same input. */
|
|
1929
|
+
sequence: sequenceNumberSchema,
|
|
1930
|
+
occurredAt: epochMillisSchema,
|
|
1931
|
+
provenance: sourceProvenanceSchema,
|
|
1932
|
+
workspace: workspaceIdentitySchema,
|
|
1933
|
+
extensions: extensionsSchema.default(emptyExtensions)
|
|
1934
|
+
};
|
|
1935
|
+
var event2 = (shape) => z14.strictObject({ ...baseEventFields, ...shape });
|
|
1936
|
+
var sessionStartEventSchema = event2({
|
|
1937
|
+
type: z14.literal("session.start"),
|
|
1938
|
+
sessionKind: z14.enum(["interactive", "non-interactive", "unknown"]),
|
|
1939
|
+
agentName: nonEmptyStringSchema.optional(),
|
|
1940
|
+
agentVersion: nonEmptyStringSchema.optional(),
|
|
1941
|
+
model: modelDescriptorSchema.optional()
|
|
1942
|
+
});
|
|
1943
|
+
var sessionEndEventSchema = event2({
|
|
1944
|
+
type: z14.literal("session.end"),
|
|
1945
|
+
reason: z14.enum(["completed", "aborted", "error", "timeout", "unknown"]),
|
|
1946
|
+
durationMillis: durationMillisSchema.optional(),
|
|
1947
|
+
/** Session totals, typically cumulative. */
|
|
1948
|
+
usage: canonicalUsageSchema.optional(),
|
|
1949
|
+
cost: costFactsSchema.optional()
|
|
1950
|
+
});
|
|
1951
|
+
var promptSubmittedEventSchema = event2({
|
|
1952
|
+
type: z14.literal("prompt.submitted"),
|
|
1953
|
+
promptSource: z14.enum(["user", "automation", "resumed", "unknown"]),
|
|
1954
|
+
content: contentFactSchema.optional(),
|
|
1955
|
+
turnIndex: z14.number().int().min(0).optional()
|
|
1956
|
+
});
|
|
1957
|
+
var generationStartEventSchema = event2({
|
|
1958
|
+
type: z14.literal("generation.start"),
|
|
1959
|
+
generationId: nonEmptyStringSchema,
|
|
1960
|
+
model: modelDescriptorSchema,
|
|
1961
|
+
requestedMaxOutputTokens: tokenCountSchema.optional(),
|
|
1962
|
+
inputContent: contentFactsSchema.optional()
|
|
1963
|
+
});
|
|
1964
|
+
var generationEndEventSchema = event2({
|
|
1965
|
+
type: z14.literal("generation.end"),
|
|
1966
|
+
generationId: nonEmptyStringSchema,
|
|
1967
|
+
model: modelDescriptorSchema,
|
|
1968
|
+
outcome: outcomeSchema,
|
|
1969
|
+
stopReason: nonEmptyStringSchema.optional(),
|
|
1970
|
+
durationMillis: durationMillisSchema.optional(),
|
|
1971
|
+
usage: canonicalUsageSchema.optional(),
|
|
1972
|
+
cost: costFactsSchema.optional(),
|
|
1973
|
+
outputContent: contentFactsSchema.optional()
|
|
1974
|
+
});
|
|
1975
|
+
var toolKindSchema = z14.enum([
|
|
1976
|
+
"read",
|
|
1977
|
+
"write",
|
|
1978
|
+
"execute",
|
|
1979
|
+
"search",
|
|
1980
|
+
"network",
|
|
1981
|
+
"delegate",
|
|
1982
|
+
"other",
|
|
1983
|
+
"unknown"
|
|
1984
|
+
]);
|
|
1985
|
+
var toolStartEventSchema = event2({
|
|
1986
|
+
type: z14.literal("tool.start"),
|
|
1987
|
+
toolCallId: nonEmptyStringSchema,
|
|
1988
|
+
toolName: nonEmptyStringSchema,
|
|
1989
|
+
toolKind: toolKindSchema,
|
|
1990
|
+
generationId: nonEmptyStringSchema.optional(),
|
|
1991
|
+
input: contentFactSchema.optional()
|
|
1992
|
+
});
|
|
1993
|
+
var toolEndEventSchema = event2({
|
|
1994
|
+
type: z14.literal("tool.end"),
|
|
1995
|
+
toolCallId: nonEmptyStringSchema,
|
|
1996
|
+
toolName: nonEmptyStringSchema,
|
|
1997
|
+
outcome: outcomeSchema,
|
|
1998
|
+
durationMillis: durationMillisSchema.optional(),
|
|
1999
|
+
/** Present when the host asked for or recorded a permission decision. */
|
|
2000
|
+
permissionDecision: z14.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
|
|
2001
|
+
output: contentFactSchema.optional()
|
|
2002
|
+
});
|
|
2003
|
+
var subagentStartEventSchema = event2({
|
|
2004
|
+
type: z14.literal("subagent.start"),
|
|
2005
|
+
subagentInvocationId: invocationIdSchema,
|
|
2006
|
+
subagentType: nonEmptyStringSchema.optional(),
|
|
2007
|
+
/** 0 for the top-level agent; 1 for its direct children. */
|
|
2008
|
+
delegationDepth: z14.number().int().min(0).max(64),
|
|
2009
|
+
model: modelDescriptorSchema.optional()
|
|
2010
|
+
});
|
|
2011
|
+
var subagentEndEventSchema = event2({
|
|
2012
|
+
type: z14.literal("subagent.end"),
|
|
2013
|
+
subagentInvocationId: invocationIdSchema,
|
|
2014
|
+
outcome: outcomeSchema,
|
|
2015
|
+
durationMillis: durationMillisSchema.optional(),
|
|
2016
|
+
usage: canonicalUsageSchema.optional()
|
|
2017
|
+
});
|
|
2018
|
+
var compactionPerformedEventSchema = event2({
|
|
2019
|
+
type: z14.literal("compaction.performed"),
|
|
2020
|
+
trigger: z14.enum(["automatic", "manual", "unknown"]),
|
|
2021
|
+
/** Provider-reported context size before and after compaction, if known. */
|
|
2022
|
+
contextTokensBefore: tokenCountSchema.optional(),
|
|
2023
|
+
contextTokensAfter: tokenCountSchema.optional(),
|
|
2024
|
+
droppedMessageCount: z14.number().int().min(0).optional(),
|
|
2025
|
+
usage: canonicalUsageSchema.optional()
|
|
2026
|
+
});
|
|
2027
|
+
var errorRaisedEventSchema = event2({
|
|
2028
|
+
type: z14.literal("error.raised"),
|
|
2029
|
+
errorCode: otelHookErrorCodeSchema,
|
|
2030
|
+
severity: errorSeveritySchema,
|
|
2031
|
+
phase: errorPhaseSchema,
|
|
2032
|
+
retryable: z14.boolean(),
|
|
2033
|
+
/** Error text is content: it is described, never embedded verbatim by default. */
|
|
2034
|
+
message: contentFactSchema.optional(),
|
|
2035
|
+
/** Non-sensitive, provider-agnostic short label. */
|
|
2036
|
+
detail: nonEmptyStringSchema.optional()
|
|
2037
|
+
});
|
|
2038
|
+
var canonicalEventSchema = z14.discriminatedUnion("type", [
|
|
2039
|
+
sessionStartEventSchema,
|
|
2040
|
+
sessionEndEventSchema,
|
|
2041
|
+
promptSubmittedEventSchema,
|
|
2042
|
+
generationStartEventSchema,
|
|
2043
|
+
generationEndEventSchema,
|
|
2044
|
+
toolStartEventSchema,
|
|
2045
|
+
toolEndEventSchema,
|
|
2046
|
+
subagentStartEventSchema,
|
|
2047
|
+
subagentEndEventSchema,
|
|
2048
|
+
compactionPerformedEventSchema,
|
|
2049
|
+
errorRaisedEventSchema
|
|
2050
|
+
]);
|
|
2051
|
+
|
|
2052
|
+
// src/providers/adapter.ts
|
|
2053
|
+
var providerDetectionSchema = z15.strictObject({
|
|
2054
|
+
providerId: resolvedProviderIdSchema,
|
|
2055
|
+
confidence: detectionConfidenceSchema,
|
|
2056
|
+
/**
|
|
2057
|
+
* Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
|
|
2058
|
+
* Reasons are exported in diagnostics, so they must not quote payload values.
|
|
2059
|
+
*/
|
|
2060
|
+
reasons: z15.array(z15.string().min(1).max(160)).max(8),
|
|
2061
|
+
providerVersion: nonEmptyStringSchema.optional(),
|
|
2062
|
+
/** The provider's own name for this event, when the payload states one. */
|
|
2063
|
+
sourceEventName: nonEmptyStringSchema.optional()
|
|
2064
|
+
});
|
|
2065
|
+
var deliveryIdentifierSupportSchema = z15.enum(["none", "partial", "all"]);
|
|
2066
|
+
var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
|
|
2067
|
+
var deliveryComponentSchema = z15.string().regex(
|
|
2068
|
+
DELIVERY_COMPONENT_PATTERN,
|
|
2069
|
+
"delivery component must be identifier-shaped: no whitespace, no path separators"
|
|
2070
|
+
);
|
|
2071
|
+
var MAX_DELIVERY_COMPONENTS = 8;
|
|
2072
|
+
var providerDeliveryClaimSchema = z15.strictObject({
|
|
2073
|
+
/**
|
|
2074
|
+
* The provider's own session/conversation id. Scopes the callback identity, so
|
|
2075
|
+
* two sessions reusing one tool-call id never collide.
|
|
2076
|
+
*/
|
|
2077
|
+
sessionId: nonEmptyStringSchema,
|
|
2078
|
+
/** The provider's own name for this callback, e.g. `PostToolUse`. */
|
|
2079
|
+
sourceEventName: deliveryComponentSchema,
|
|
2080
|
+
/**
|
|
2081
|
+
* Identifier-shaped payload fields that, together with `sourceEventName`,
|
|
2082
|
+
* name this callback within the session exactly once.
|
|
2083
|
+
*/
|
|
2084
|
+
components: z15.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
|
|
2085
|
+
/**
|
|
2086
|
+
* Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
|
|
2087
|
+
* tool call"`. Evidence reaches diagnostics, so it must name fields, never
|
|
2088
|
+
* quote their values.
|
|
2089
|
+
*/
|
|
2090
|
+
evidence: z15.array(z15.string().min(1).max(160)).min(1).max(4).readonly()
|
|
2091
|
+
});
|
|
2092
|
+
var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
|
|
2093
|
+
var deliveryGapReasonSchema = z15.string().regex(
|
|
2094
|
+
DELIVERY_GAP_REASON_PATTERN,
|
|
2095
|
+
"delivery gap reason must be one line of prose: no path separators, no control characters"
|
|
2096
|
+
);
|
|
2097
|
+
var MAX_DELIVERY_GAPS = 48;
|
|
2098
|
+
var providerDeliveryGapsSchema = z15.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
|
|
2099
|
+
message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
|
|
2100
|
+
});
|
|
2101
|
+
var providerCapabilitiesSchema = z15.strictObject({
|
|
2102
|
+
/** Event types the adapter can produce. */
|
|
2103
|
+
lifecycleEvents: z15.array(canonicalEventTypeSchema).max(32).readonly(),
|
|
2104
|
+
usageTemporality: usageTemporalitySchema,
|
|
2105
|
+
/**
|
|
2106
|
+
* Which accumulator series a `cumulative` report continues — that is, which
|
|
2107
|
+
* previous snapshot the next one should be diffed against.
|
|
2108
|
+
*
|
|
2109
|
+
* Only meaningful when `usageTemporality` is `cumulative`; omit otherwise.
|
|
2110
|
+
*
|
|
2111
|
+
* - `event-scope` (the default when omitted) — each event scope keeps its own
|
|
2112
|
+
* running total, so a `generation.end` snapshot is diffed against the
|
|
2113
|
+
* previous snapshot *for that same generation*.
|
|
2114
|
+
* - `session-lifetime` — the provider maintains **one** running total for the
|
|
2115
|
+
* whole session and stamps it onto whichever callback happens to report it.
|
|
2116
|
+
* Diffing such a snapshot per event scope would restart the baseline on
|
|
2117
|
+
* every new generation id and re-count the entire session total each turn,
|
|
2118
|
+
* so session-level and generation-level snapshots share one baseline.
|
|
2119
|
+
* Subagent snapshots keep their own series regardless: a delegated agent's
|
|
2120
|
+
* counter is not a point on the parent session's curve.
|
|
2121
|
+
*/
|
|
2122
|
+
cumulativeUsageSeries: z15.enum(["event-scope", "session-lifetime"]).optional(),
|
|
2123
|
+
reportsCachedInput: z15.boolean(),
|
|
2124
|
+
reportsCacheCreation: z15.boolean(),
|
|
2125
|
+
cacheCreationAccounting: cacheCreationAccountingSchema,
|
|
2126
|
+
reportsReasoningOutput: z15.boolean(),
|
|
2127
|
+
reportsProviderTotal: z15.boolean(),
|
|
2128
|
+
reportsCost: z15.boolean(),
|
|
2129
|
+
emitsSubagentEvents: z15.boolean(),
|
|
2130
|
+
emitsCompactionEvents: z15.boolean(),
|
|
2131
|
+
/** True when the provider reads a structured response from stdout. */
|
|
2132
|
+
requiresHookResponse: z15.boolean(),
|
|
2133
|
+
/** How much of this provider's hook traffic is replay-identifiable. */
|
|
2134
|
+
deliveryIdentifier: deliveryIdentifierSupportSchema
|
|
2135
|
+
});
|
|
2136
|
+
var providerHookResponseSchema = z15.strictObject({
|
|
2137
|
+
/**
|
|
2138
|
+
* Always 0. A telemetry hook that can fail the host agent is a liability, so
|
|
2139
|
+
* the type forbids expressing anything else (ADR 0004).
|
|
2140
|
+
*/
|
|
2141
|
+
exitCode: z15.literal(0),
|
|
2142
|
+
/** Protocol response text. Omit to write nothing at all. */
|
|
2143
|
+
stdout: z15.string().max(8192).optional(),
|
|
2144
|
+
/** Non-sensitive diagnostic text for stderr. */
|
|
2145
|
+
stderr: z15.string().max(8192).optional(),
|
|
2146
|
+
/** Declares which of the two stdout contracts this response follows. */
|
|
2147
|
+
contract: z15.enum(["silent", "provider-protocol"])
|
|
2148
|
+
});
|
|
2149
|
+
var SILENT_HOOK_RESPONSE = Object.freeze({
|
|
2150
|
+
exitCode: 0,
|
|
2151
|
+
contract: "silent"
|
|
2152
|
+
});
|
|
2153
|
+
var asProviderId = (value) => providerIdSchema.parse(value);
|
|
2154
|
+
|
|
2155
|
+
// src/providers/antigravity/delivery.ts
|
|
2156
|
+
var ANTIGRAVITY_DELIVERY_GAPS = Object.freeze({
|
|
2157
|
+
Stop: "Stop can fire twice per invocation (idle, then fully idle) and payload `fullyIdle` \u2014 the only field separating them \u2014 is an unconfirmed reconstruction, so invocationNum alone would suppress the second real firing"
|
|
2158
|
+
});
|
|
2159
|
+
|
|
2160
|
+
// src/providers/antigravity/adapter.ts
|
|
2161
|
+
var ANTIGRAVITY_PROVIDER_ID = "antigravity";
|
|
2162
|
+
var ANTIGRAVITY_CAPABILITIES = Object.freeze({
|
|
2163
|
+
lifecycleEvents: Object.freeze(["tool.start", "tool.end"]),
|
|
2164
|
+
usageTemporality: "delta",
|
|
2165
|
+
reportsCachedInput: false,
|
|
2166
|
+
reportsCacheCreation: false,
|
|
2167
|
+
cacheCreationAccounting: "not-reported",
|
|
2168
|
+
reportsReasoningOutput: false,
|
|
2169
|
+
reportsProviderTotal: false,
|
|
2170
|
+
reportsCost: false,
|
|
2171
|
+
emitsSubagentEvents: false,
|
|
2172
|
+
emitsCompactionEvents: false,
|
|
2173
|
+
requiresHookResponse: false,
|
|
2174
|
+
// Only the tool pair carries a replay-stable id, and only from the two
|
|
2175
|
+
// verified counters. See `./delivery.ts` for which and why.
|
|
2176
|
+
deliveryIdentifier: "partial"
|
|
2177
|
+
});
|
|
2178
|
+
|
|
2179
|
+
// src/providers/claude/detect.ts
|
|
2180
|
+
var CLAUDE_CODE_PROVIDER_ID = asProviderId("claude-code");
|
|
2181
|
+
var KNOWN_EVENT_NAMES = new Set(CLAUDE_HOOK_EVENT_NAMES);
|
|
2182
|
+
|
|
2183
|
+
// src/providers/codex/version.ts
|
|
2184
|
+
var CODEX_PROVIDER_ID = providerIdSchema.parse("codex");
|
|
2185
|
+
|
|
2186
|
+
// src/providers/gemini/delivery.ts
|
|
2187
|
+
var GEMINI_UNIDENTIFIABLE_CALLBACKS = Object.freeze({
|
|
2188
|
+
SessionStart: "fires again within the same session_id on resume and clear (payload `source`), so session_id names a class of firings rather than one",
|
|
2189
|
+
SessionEnd: "the closing side of the same problem: a cleared session ends under the same session_id",
|
|
2190
|
+
BeforeTool: "ToolCallRequestInfo.callId exists but is not projected into the hook input; two calls to one tool can share a millisecond, so (timestamp, tool_name) would suppress a genuine second call",
|
|
2191
|
+
AfterTool: "ToolCallRequestInfo.callId exists but is not projected into the hook input; two calls to one tool can share a millisecond, so (timestamp, tool_name) would suppress a genuine second call",
|
|
2192
|
+
BeforeAgent: "no turn id; fires once per turn with only a millisecond separating turns",
|
|
2193
|
+
AfterAgent: "no turn id; fires once per turn with only a millisecond separating turns",
|
|
2194
|
+
PreCompress: "no compaction id; can fire repeatedly within one session",
|
|
2195
|
+
BeforeModel: "no request id",
|
|
2196
|
+
AfterModel: "fires per streaming chunk with the same llm_request each time, so several genuine firings share one request and often one millisecond",
|
|
2197
|
+
BeforeToolSelection: "no request id",
|
|
2198
|
+
Notification: "produces no canonical event"
|
|
2199
|
+
});
|
|
2200
|
+
|
|
2201
|
+
// src/providers/gemini/tool-kind.ts
|
|
2202
|
+
var BUILT_IN_TOOL_KIND = Object.freeze({
|
|
2203
|
+
read_file: "read",
|
|
2204
|
+
read_many_files: "read",
|
|
2205
|
+
list_directory: "read",
|
|
2206
|
+
get_internal_docs: "read",
|
|
2207
|
+
read_mcp_resource: "read",
|
|
2208
|
+
list_mcp_resources: "read",
|
|
2209
|
+
write_file: "write",
|
|
2210
|
+
replace: "write",
|
|
2211
|
+
run_shell_command: "execute",
|
|
2212
|
+
glob: "search",
|
|
2213
|
+
grep_search: "search",
|
|
2214
|
+
web_fetch: "network",
|
|
2215
|
+
google_web_search: "network",
|
|
2216
|
+
// Gemini's subagent entry point. The CLI has no subagent hook events, so a
|
|
2217
|
+
// delegated run is observable only as this tool's BeforeTool/AfterTool pair.
|
|
2218
|
+
invoke_agent: "delegate",
|
|
2219
|
+
activate_skill: "other",
|
|
2220
|
+
ask_user: "other",
|
|
2221
|
+
write_todos: "other",
|
|
2222
|
+
enter_plan_mode: "other",
|
|
2223
|
+
exit_plan_mode: "other",
|
|
2224
|
+
update_topic: "other",
|
|
2225
|
+
complete_task: "other",
|
|
2226
|
+
tracker_create_task: "other",
|
|
2227
|
+
tracker_update_task: "other",
|
|
2228
|
+
tracker_get_task: "other",
|
|
2229
|
+
tracker_list_tasks: "other",
|
|
2230
|
+
tracker_add_dependency: "other",
|
|
2231
|
+
tracker_visualize: "other"
|
|
2232
|
+
});
|
|
2233
|
+
|
|
2234
|
+
// src/providers/gemini/adapter.ts
|
|
2235
|
+
var GEMINI_PROVIDER_ID = "gemini-cli";
|
|
2236
|
+
var DEFAULT_GEMINI_CAPABILITIES = Object.freeze({
|
|
2237
|
+
lifecycleEvents: Object.freeze([
|
|
2238
|
+
"session.start",
|
|
2239
|
+
"session.end",
|
|
2240
|
+
"prompt.submitted",
|
|
2241
|
+
"generation.start",
|
|
2242
|
+
"generation.end",
|
|
2243
|
+
"tool.start",
|
|
2244
|
+
"tool.end",
|
|
2245
|
+
"compaction.performed"
|
|
2246
|
+
]),
|
|
2247
|
+
// `AfterModel` fires per streaming chunk and a chunk's `usageMetadata` is a
|
|
2248
|
+
// snapshot of the response so far, not that chunk's increment. See
|
|
2249
|
+
// `./usage.ts` for the evidence; `delta` here would bill a multi-snapshot
|
|
2250
|
+
// stream several times over.
|
|
2251
|
+
usageTemporality: "cumulative",
|
|
2252
|
+
// Both false because the CLI's hook translator strips the counters before any
|
|
2253
|
+
// hook runs: `toHookLLMResponse` rebuilds `usageMetadata` as exactly
|
|
2254
|
+
// `{ promptTokenCount, candidatesTokenCount, totalTokenCount }`. The SDK
|
|
2255
|
+
// response it reads does carry `cachedContentTokenCount` and
|
|
2256
|
+
// `thoughtsTokenCount`, so this is a gap in the hook projection rather than in
|
|
2257
|
+
// the model — but a consumer must be able to tell "this provider reports no
|
|
2258
|
+
// cache reads" from "this session had none", and today it is the former.
|
|
2259
|
+
reportsCachedInput: false,
|
|
2260
|
+
reportsCacheCreation: false,
|
|
2261
|
+
cacheCreationAccounting: "not-reported",
|
|
2262
|
+
reportsReasoningOutput: false,
|
|
2263
|
+
reportsProviderTotal: true,
|
|
2264
|
+
reportsCost: false,
|
|
2265
|
+
// The Gemini CLI has no subagent hook events. Delegation happens through the
|
|
2266
|
+
// `invoke_agent` tool, so a subagent run is observable only as that tool's
|
|
2267
|
+
// BeforeTool/AfterTool pair — never as a distinct subagent lifecycle.
|
|
2268
|
+
emitsSubagentEvents: false,
|
|
2269
|
+
emitsCompactionEvents: true,
|
|
2270
|
+
requiresHookResponse: false,
|
|
2271
|
+
// Nothing in this protocol identifies a callback across a redelivery: there is
|
|
2272
|
+
// no request, turn, or tool-call id, and `session_id` repeats across resume and
|
|
2273
|
+
// clear. See `./delivery.ts` for the field-by-field reasoning.
|
|
2274
|
+
deliveryIdentifier: "none"
|
|
2275
|
+
});
|
|
2276
|
+
var SESSION_END_REASON_OUTCOME = Object.freeze({
|
|
2277
|
+
exit: "completed",
|
|
2278
|
+
clear: "completed",
|
|
2279
|
+
logout: "completed",
|
|
2280
|
+
prompt_input_exit: "completed",
|
|
2281
|
+
other: "unknown"
|
|
2282
|
+
});
|
|
2283
|
+
var FINISH_REASON_OUTCOME = Object.freeze({
|
|
2284
|
+
STOP: "ok",
|
|
2285
|
+
MAX_TOKENS: "ok",
|
|
2286
|
+
SAFETY: "denied",
|
|
2287
|
+
RECITATION: "denied",
|
|
2288
|
+
BLOCKLIST: "denied",
|
|
2289
|
+
PROHIBITED_CONTENT: "denied",
|
|
2290
|
+
SPII: "denied",
|
|
2291
|
+
LANGUAGE: "denied",
|
|
2292
|
+
MALFORMED_FUNCTION_CALL: "error",
|
|
2293
|
+
OTHER: "unknown"
|
|
2294
|
+
});
|
|
2295
|
+
|
|
2296
|
+
// src/install/planners.ts
|
|
2297
|
+
var MANAGED_HOOK_NAME = "otel-hook";
|
|
2298
|
+
var DEFAULT_MANAGED_COMMAND_MARKER = "otel-hook";
|
|
2299
|
+
var MANAGED_MARKER_TOKEN = "otel-hook";
|
|
2300
|
+
var MAX_MANAGED_COMMAND_MARKER_LENGTH = 200;
|
|
2301
|
+
var MIN_ABSOLUTE_PATH_MARKER_LENGTH = 8;
|
|
2302
|
+
var MANAGED_MARKER_REJECTION_DETAIL = Object.freeze({
|
|
2303
|
+
empty: "the managed marker is empty, which would match every hook already configured",
|
|
2304
|
+
"too-long": `the managed marker is longer than ${String(MAX_MANAGED_COMMAND_MARKER_LENGTH)} characters`,
|
|
2305
|
+
untrimmed: "the managed marker has leading or trailing whitespace, which is almost always a quoting mistake and would not match the command as written",
|
|
2306
|
+
"not-ownership-bearing": `the managed marker must identify this tool: either contain "${MANAGED_MARKER_TOKEN}", or be an absolute path to the installed command. A generic marker matches hooks this tool does not own, and uninstall would delete them`
|
|
2307
|
+
});
|
|
2308
|
+
var isAbsolutePathMarker = (marker) => /^\//.test(marker) || /^[A-Za-z]:[\\/]/.test(marker) || /^\\\\[^\\]/.test(marker);
|
|
2309
|
+
var checkManagedMarker = (marker) => {
|
|
2310
|
+
if (marker.length === 0) {
|
|
2311
|
+
return "empty";
|
|
2312
|
+
}
|
|
2313
|
+
if (marker !== marker.trim()) {
|
|
2314
|
+
return "untrimmed";
|
|
2315
|
+
}
|
|
2316
|
+
if (marker.length > MAX_MANAGED_COMMAND_MARKER_LENGTH) {
|
|
2317
|
+
return "too-long";
|
|
2318
|
+
}
|
|
2319
|
+
if (marker.toLowerCase().includes(MANAGED_MARKER_TOKEN)) {
|
|
2320
|
+
return void 0;
|
|
2321
|
+
}
|
|
2322
|
+
if (isAbsolutePathMarker(marker) && marker.length >= MIN_ABSOLUTE_PATH_MARKER_LENGTH) {
|
|
2323
|
+
return void 0;
|
|
2324
|
+
}
|
|
2325
|
+
return "not-ownership-bearing";
|
|
2326
|
+
};
|
|
2327
|
+
var managedHookPredicate = (marker) => {
|
|
2328
|
+
const rejection = checkManagedMarker(marker);
|
|
2329
|
+
if (rejection !== void 0) {
|
|
2330
|
+
throw new Error(MANAGED_MARKER_REJECTION_DETAIL[rejection]);
|
|
2331
|
+
}
|
|
2332
|
+
return (handler) => handler.name === MANAGED_HOOK_NAME || typeof handler.command === "string" && handler.command.includes(marker);
|
|
2333
|
+
};
|
|
2334
|
+
var isPlainObject4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2335
|
+
var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
|
|
2336
|
+
const before = read(existing, identifies);
|
|
2337
|
+
const after = read(result.config, identifies);
|
|
2338
|
+
const changes = [];
|
|
2339
|
+
for (const event3 of events) {
|
|
2340
|
+
const had = before.has(event3);
|
|
2341
|
+
const has = after.has(event3);
|
|
2342
|
+
if (removal) {
|
|
2343
|
+
if (had && !has) {
|
|
2344
|
+
changes.push({ event: event3, action: "removed" });
|
|
2345
|
+
}
|
|
2346
|
+
continue;
|
|
2347
|
+
}
|
|
2348
|
+
if (!had) {
|
|
2349
|
+
changes.push({ event: event3, action: "added" });
|
|
2350
|
+
} else {
|
|
2351
|
+
const same = JSON.stringify(before.get(event3) ?? []) === JSON.stringify(after.get(event3) ?? []);
|
|
2352
|
+
changes.push({ event: event3, action: same ? "unchanged" : "updated" });
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
return { document: result.config, changed: result.changed, changes, conflicts: [] };
|
|
2356
|
+
};
|
|
2357
|
+
var flatHookConflicts = (existing) => {
|
|
2358
|
+
if (!isPlainObject4(existing) || existing.hooks === void 0) {
|
|
2359
|
+
return [];
|
|
2360
|
+
}
|
|
2361
|
+
if (!isPlainObject4(existing.hooks)) {
|
|
2362
|
+
return [
|
|
2363
|
+
{
|
|
2364
|
+
location: "hooks",
|
|
2365
|
+
detail: `expected an object keyed by hook event name, found ${Array.isArray(existing.hooks) ? "an array" : typeof existing.hooks}`
|
|
2366
|
+
}
|
|
2367
|
+
];
|
|
2368
|
+
}
|
|
2369
|
+
const conflicts = [];
|
|
2370
|
+
for (const [event3, list] of Object.entries(existing.hooks)) {
|
|
2371
|
+
if (!Array.isArray(list)) {
|
|
2372
|
+
conflicts.push({
|
|
2373
|
+
location: `hooks.${event3}`,
|
|
2374
|
+
detail: `expected an array of hook entries, found ${list === null ? "null" : typeof list}`
|
|
2375
|
+
});
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
return conflicts;
|
|
2379
|
+
};
|
|
2380
|
+
var asAntigravityEvents = (events) => events;
|
|
2381
|
+
var documentEventNames = (existing) => isPlainObject4(existing) && isPlainObject4(existing.hooks) ? Object.keys(existing.hooks) : [];
|
|
2382
|
+
var PLANNERS = Object.freeze([
|
|
2383
|
+
Object.freeze({
|
|
2384
|
+
providerId: ANTIGRAVITY_PROVIDER_ID,
|
|
2385
|
+
defaultEvents: ANTIGRAVITY_HOOK_EVENT_NAMES,
|
|
2386
|
+
merge: (input) => {
|
|
2387
|
+
const conflicts = flatHookConflicts(input.existing);
|
|
2388
|
+
if (conflicts.length > 0) {
|
|
2389
|
+
return {
|
|
2390
|
+
document: isPlainObject4(input.existing) ? input.existing : {},
|
|
2391
|
+
changed: false,
|
|
2392
|
+
changes: [],
|
|
2393
|
+
conflicts
|
|
2394
|
+
};
|
|
2395
|
+
}
|
|
2396
|
+
const events = input.events ?? ANTIGRAVITY_HOOK_EVENT_NAMES;
|
|
2397
|
+
return adaptFlatResult(
|
|
2398
|
+
readAntigravityHookRegistrations,
|
|
2399
|
+
input.existing,
|
|
2400
|
+
events,
|
|
2401
|
+
input.identifies,
|
|
2402
|
+
mergeAntigravityHookRegistration({
|
|
2403
|
+
...input.existing === void 0 ? {} : { existing: input.existing },
|
|
2404
|
+
command: input.command,
|
|
2405
|
+
events: asAntigravityEvents(events),
|
|
2406
|
+
...input.matcher === void 0 ? {} : { matcher: input.matcher },
|
|
2407
|
+
identifies: input.identifies
|
|
2408
|
+
}),
|
|
2409
|
+
false
|
|
2410
|
+
);
|
|
2411
|
+
},
|
|
2412
|
+
remove: (input) => {
|
|
2413
|
+
const conflicts = flatHookConflicts(input.existing);
|
|
2414
|
+
if (conflicts.length > 0) {
|
|
2415
|
+
return {
|
|
2416
|
+
document: isPlainObject4(input.existing) ? input.existing : {},
|
|
2417
|
+
changed: false,
|
|
2418
|
+
changes: [],
|
|
2419
|
+
conflicts
|
|
2420
|
+
};
|
|
2421
|
+
}
|
|
2422
|
+
const events = input.events ?? documentEventNames(input.existing);
|
|
2423
|
+
return adaptFlatResult(
|
|
2424
|
+
readAntigravityHookRegistrations,
|
|
2425
|
+
input.existing,
|
|
2426
|
+
events,
|
|
2427
|
+
input.identifies,
|
|
2428
|
+
removeAntigravityHookRegistration({
|
|
2429
|
+
...input.existing === void 0 ? {} : { existing: input.existing },
|
|
2430
|
+
...input.events === void 0 ? {} : { events: asAntigravityEvents(input.events) },
|
|
2431
|
+
identifies: input.identifies
|
|
2432
|
+
}),
|
|
2433
|
+
true
|
|
2434
|
+
);
|
|
2435
|
+
},
|
|
2436
|
+
read: readAntigravityHookRegistrations
|
|
2437
|
+
}),
|
|
2438
|
+
Object.freeze({
|
|
2439
|
+
providerId: CLAUDE_CODE_PROVIDER_ID,
|
|
2440
|
+
defaultEvents: CLAUDE_REGISTRABLE_HOOK_EVENTS,
|
|
2441
|
+
merge: (input) => mergeClaudeHookRegistration(input),
|
|
2442
|
+
remove: (input) => removeClaudeHookRegistration(input),
|
|
2443
|
+
read: readClaudeHookRegistrations
|
|
2444
|
+
}),
|
|
2445
|
+
Object.freeze({
|
|
2446
|
+
providerId: CODEX_PROVIDER_ID,
|
|
2447
|
+
defaultEvents: CODEX_REGISTRABLE_HOOK_EVENTS,
|
|
2448
|
+
merge: (input) => mergeCodexHookRegistration(input),
|
|
2449
|
+
remove: (input) => removeCodexHookRegistration(input),
|
|
2450
|
+
read: readCodexHookRegistrations
|
|
2451
|
+
}),
|
|
2452
|
+
Object.freeze({
|
|
2453
|
+
providerId: CURSOR_PROVIDER_ID,
|
|
2454
|
+
defaultEvents: CURSOR_REGISTRABLE_HOOK_EVENTS,
|
|
2455
|
+
merge: (input) => {
|
|
2456
|
+
const conflicts = flatHookConflicts(input.existing);
|
|
2457
|
+
if (conflicts.length > 0) {
|
|
2458
|
+
return {
|
|
2459
|
+
document: isPlainObject4(input.existing) ? input.existing : {},
|
|
2460
|
+
changed: false,
|
|
2461
|
+
changes: [],
|
|
2462
|
+
conflicts
|
|
2463
|
+
};
|
|
2464
|
+
}
|
|
2465
|
+
const events = input.events ?? CURSOR_REGISTRABLE_HOOK_EVENTS;
|
|
2466
|
+
return adaptFlatResult(
|
|
2467
|
+
readCursorHookRegistrations,
|
|
2468
|
+
input.existing,
|
|
2469
|
+
events,
|
|
2470
|
+
input.identifies,
|
|
2471
|
+
mergeCursorHookRegistration({
|
|
2472
|
+
...input.existing === void 0 ? {} : { existing: input.existing },
|
|
2473
|
+
command: input.command,
|
|
2474
|
+
events,
|
|
2475
|
+
...input.matcher === void 0 ? {} : { matcher: input.matcher },
|
|
2476
|
+
...input.timeoutSeconds === void 0 ? {} : { timeoutSeconds: input.timeoutSeconds },
|
|
2477
|
+
identifies: input.identifies
|
|
2478
|
+
}),
|
|
2479
|
+
false
|
|
2480
|
+
);
|
|
2481
|
+
},
|
|
2482
|
+
remove: (input) => {
|
|
2483
|
+
const conflicts = flatHookConflicts(input.existing);
|
|
2484
|
+
if (conflicts.length > 0) {
|
|
2485
|
+
return {
|
|
2486
|
+
document: isPlainObject4(input.existing) ? input.existing : {},
|
|
2487
|
+
changed: false,
|
|
2488
|
+
changes: [],
|
|
2489
|
+
conflicts
|
|
2490
|
+
};
|
|
2491
|
+
}
|
|
2492
|
+
return adaptFlatResult(
|
|
2493
|
+
readCursorHookRegistrations,
|
|
2494
|
+
input.existing,
|
|
2495
|
+
input.events ?? documentEventNames(input.existing),
|
|
2496
|
+
input.identifies,
|
|
2497
|
+
removeCursorHookRegistration({
|
|
2498
|
+
...input.existing === void 0 ? {} : { existing: input.existing },
|
|
2499
|
+
...input.events === void 0 ? {} : { events: input.events },
|
|
2500
|
+
identifies: input.identifies
|
|
2501
|
+
}),
|
|
2502
|
+
true
|
|
2503
|
+
);
|
|
2504
|
+
},
|
|
2505
|
+
read: readCursorHookRegistrations
|
|
2506
|
+
}),
|
|
2507
|
+
Object.freeze({
|
|
2508
|
+
providerId: GEMINI_PROVIDER_ID,
|
|
2509
|
+
defaultEvents: GEMINI_REGISTRABLE_HOOK_EVENTS,
|
|
2510
|
+
merge: (input) => {
|
|
2511
|
+
const merged = mergeGeminiHookRegistration(input.existing, {
|
|
2512
|
+
name: MANAGED_HOOK_NAME,
|
|
2513
|
+
command: input.command,
|
|
2514
|
+
events: input.events ?? GEMINI_REGISTRABLE_HOOK_EVENTS,
|
|
2515
|
+
...input.matcher === void 0 ? {} : { matcher: input.matcher },
|
|
2516
|
+
// Seconds in; the Gemini planner converts to the milliseconds that
|
|
2517
|
+
// vocabulary uses.
|
|
2518
|
+
...input.timeoutSeconds === void 0 ? {} : { timeoutSeconds: input.timeoutSeconds },
|
|
2519
|
+
identifies: input.identifies
|
|
2520
|
+
});
|
|
2521
|
+
return {
|
|
2522
|
+
document: merged.settings,
|
|
2523
|
+
changed: merged.changed,
|
|
2524
|
+
changes: merged.changes,
|
|
2525
|
+
conflicts: merged.conflicts
|
|
2526
|
+
};
|
|
2527
|
+
},
|
|
2528
|
+
remove: (input) => removeGeminiHookRegistration(input.existing, {
|
|
2529
|
+
...input.events === void 0 ? {} : { events: input.events },
|
|
2530
|
+
identifies: input.identifies
|
|
2531
|
+
}),
|
|
2532
|
+
read: readGeminiHookRegistrations
|
|
2533
|
+
})
|
|
2534
|
+
]);
|
|
2535
|
+
var findRegistrationPlanner = (providerId) => PLANNERS.find((planner) => planner.providerId === providerId);
|
|
2536
|
+
var REGISTRATION_PLANNERS = PLANNERS;
|
|
2537
|
+
|
|
2538
|
+
// src/install/support.ts
|
|
2539
|
+
var PROVIDER_REGISTRATION_SUPPORT = Object.freeze([
|
|
2540
|
+
Object.freeze({
|
|
2541
|
+
providerId: ANTIGRAVITY_PROVIDER_ID,
|
|
2542
|
+
supported: true,
|
|
2543
|
+
reason: "the five documented camelCase command hooks and the hook-file shape are recorded by the antigravity adapter",
|
|
2544
|
+
helper: "mergeAntigravityHookRegistration"
|
|
2545
|
+
}),
|
|
2546
|
+
Object.freeze({
|
|
2547
|
+
providerId: CLAUDE_CODE_PROVIDER_ID,
|
|
2548
|
+
supported: true,
|
|
2549
|
+
reason: "the settings.json hook document, its global and project scopes, and every event this adapter models are documented at code.claude.com/docs/en/hooks and cross-checked against o11y-dev/opentelemetry-hooks v0.14.0",
|
|
2550
|
+
helper: "mergeClaudeHookRegistration"
|
|
2551
|
+
}),
|
|
2552
|
+
Object.freeze({
|
|
2553
|
+
providerId: CODEX_PROVIDER_ID,
|
|
2554
|
+
supported: true,
|
|
2555
|
+
reason: "the .codex/hooks.json document, its global and project scopes, and the event vocabulary are documented at learn.chatgpt.com/docs/hooks \u2014 the same reference this adapter's payload contract is drawn from",
|
|
2556
|
+
helper: "mergeCodexHookRegistration"
|
|
2557
|
+
}),
|
|
2558
|
+
Object.freeze({
|
|
2559
|
+
providerId: CURSOR_PROVIDER_ID,
|
|
2560
|
+
supported: true,
|
|
2561
|
+
reason: "the ~/.cursor/hooks.json and .cursor/hooks.json documents, their shape, and the event vocabulary are documented at cursor.com/docs/agent/hooks, and the payload contract this adapter parses is derived from that reference plus four real redacted capture runs (Cursor IDE 3.12.17 and CLI 2026.07.17, recorded in providers/cursor/payload.ts and replayed from fixtures/parity/cursor)",
|
|
2562
|
+
helper: "mergeCursorHookRegistration"
|
|
2563
|
+
}),
|
|
2564
|
+
Object.freeze({
|
|
2565
|
+
providerId: GEMINI_PROVIDER_ID,
|
|
2566
|
+
supported: true,
|
|
2567
|
+
reason: "the Gemini CLI settings.json hooks schema and event vocabulary are recorded by the gemini adapter",
|
|
2568
|
+
helper: "mergeGeminiHookRegistration"
|
|
2569
|
+
})
|
|
2570
|
+
]);
|
|
2571
|
+
var findRegistrationSupport = (providerId) => PROVIDER_REGISTRATION_SUPPORT.find((entry) => entry.providerId === providerId);
|
|
2572
|
+
var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
|
|
2573
|
+
PROVIDER_REGISTRATION_SUPPORT.filter((entry) => entry.supported).map((entry) => entry.providerId)
|
|
2574
|
+
);
|
|
2575
|
+
|
|
2576
|
+
// src/install/scopes.ts
|
|
2577
|
+
import * as path from "path";
|
|
2578
|
+
var REGISTRATION_SCOPES = Object.freeze([
|
|
2579
|
+
"global",
|
|
2580
|
+
"project"
|
|
2581
|
+
]);
|
|
2582
|
+
var CLAUDE_EVIDENCE = "code.claude.com/docs/en/hooks settings-file table, cross-checked against o11y-dev/opentelemetry-hooks v0.14.0 setup.sh";
|
|
2583
|
+
var CODEX_EVIDENCE = "learn.chatgpt.com/docs/hooks discovery-locations list, cross-checked against o11y-dev/opentelemetry-hooks v0.14.0 setup.sh";
|
|
2584
|
+
var GEMINI_EVIDENCE = "o11y-dev/opentelemetry-hooks v0.14.0 setup.sh (setup_gemini) and its supported-agents table";
|
|
2585
|
+
var CURSOR_EVIDENCE = "cursor.com/docs/agent/hooks configuration-levels list (user and project), cross-checked against o11y-dev/opentelemetry-hooks v0.14.0 setup.sh";
|
|
2586
|
+
var PROVIDER_INSTALL_LOCATIONS = Object.freeze([
|
|
2587
|
+
Object.freeze({
|
|
2588
|
+
providerId: CLAUDE_CODE_PROVIDER_ID,
|
|
2589
|
+
scope: "global",
|
|
2590
|
+
segments: Object.freeze([".claude", "settings.json"]),
|
|
2591
|
+
evidence: CLAUDE_EVIDENCE
|
|
2592
|
+
}),
|
|
2593
|
+
Object.freeze({
|
|
2594
|
+
providerId: CLAUDE_CODE_PROVIDER_ID,
|
|
2595
|
+
scope: "project",
|
|
2596
|
+
segments: Object.freeze([".claude", "settings.json"]),
|
|
2597
|
+
evidence: CLAUDE_EVIDENCE
|
|
2598
|
+
}),
|
|
2599
|
+
Object.freeze({
|
|
2600
|
+
providerId: CODEX_PROVIDER_ID,
|
|
2601
|
+
scope: "global",
|
|
2602
|
+
segments: Object.freeze([".codex", "hooks.json"]),
|
|
2603
|
+
evidence: CODEX_EVIDENCE
|
|
2604
|
+
}),
|
|
2605
|
+
Object.freeze({
|
|
2606
|
+
providerId: CODEX_PROVIDER_ID,
|
|
2607
|
+
scope: "project",
|
|
2608
|
+
segments: Object.freeze([".codex", "hooks.json"]),
|
|
2609
|
+
evidence: CODEX_EVIDENCE
|
|
2610
|
+
}),
|
|
2611
|
+
Object.freeze({
|
|
2612
|
+
providerId: CURSOR_PROVIDER_ID,
|
|
2613
|
+
scope: "global",
|
|
2614
|
+
segments: Object.freeze([".cursor", "hooks.json"]),
|
|
2615
|
+
evidence: CURSOR_EVIDENCE
|
|
2616
|
+
}),
|
|
2617
|
+
Object.freeze({
|
|
2618
|
+
providerId: CURSOR_PROVIDER_ID,
|
|
2619
|
+
scope: "project",
|
|
2620
|
+
segments: Object.freeze([".cursor", "hooks.json"]),
|
|
2621
|
+
evidence: CURSOR_EVIDENCE
|
|
2622
|
+
}),
|
|
2623
|
+
Object.freeze({
|
|
2624
|
+
providerId: GEMINI_PROVIDER_ID,
|
|
2625
|
+
scope: "global",
|
|
2626
|
+
segments: Object.freeze([".gemini", "settings.json"]),
|
|
2627
|
+
evidence: GEMINI_EVIDENCE
|
|
2628
|
+
}),
|
|
2629
|
+
Object.freeze({
|
|
2630
|
+
providerId: GEMINI_PROVIDER_ID,
|
|
2631
|
+
scope: "project",
|
|
2632
|
+
segments: Object.freeze([".gemini", "settings.json"]),
|
|
2633
|
+
evidence: GEMINI_EVIDENCE
|
|
2634
|
+
})
|
|
2635
|
+
]);
|
|
2636
|
+
var PROVIDERS_WITHOUT_VERIFIED_LOCATION = Object.freeze({
|
|
2637
|
+
[ANTIGRAVITY_PROVIDER_ID]: 'no Antigravity hook-file path has been verified; o11y-dev/opentelemetry-hooks v0.14.0 lists Antigravity as a "manual hook command, runner-defined" integration and writes no file for it'
|
|
2638
|
+
});
|
|
2639
|
+
var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
|
|
2640
|
+
...new Set(PROVIDER_INSTALL_LOCATIONS.map((entry) => entry.providerId))
|
|
2641
|
+
]);
|
|
2642
|
+
var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
|
|
2643
|
+
(entry) => entry.providerId === providerId && entry.scope === scope
|
|
2644
|
+
);
|
|
2645
|
+
var resolveInstallPath = (location, roots) => path.resolve(
|
|
2646
|
+
location.scope === "global" ? roots.homeDir : roots.projectDir,
|
|
2647
|
+
...location.segments
|
|
2648
|
+
);
|
|
2649
|
+
|
|
2650
|
+
// src/install/document.ts
|
|
2651
|
+
import { randomBytes } from "crypto";
|
|
2652
|
+
import { chmod, mkdir, open, readFile, rename, stat, unlink } from "fs/promises";
|
|
2653
|
+
import * as path2 from "path";
|
|
2654
|
+
var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
|
|
2655
|
+
indent: " ",
|
|
2656
|
+
eol: "\n",
|
|
2657
|
+
trailingNewline: true
|
|
2658
|
+
});
|
|
2659
|
+
var isErrnoException = (thrown, ...codes) => thrown instanceof Error && codes.includes(thrown.code ?? "");
|
|
2660
|
+
var detectDocumentFormat = (raw) => {
|
|
2661
|
+
const eol = /\r\n/.test(raw) ? "\r\n" : "\n";
|
|
2662
|
+
const indentMatch = /(?:\r?\n)([ \t]+)\S/.exec(raw);
|
|
2663
|
+
return {
|
|
2664
|
+
indent: indentMatch?.[1] ?? DEFAULT_DOCUMENT_FORMAT.indent,
|
|
2665
|
+
eol,
|
|
2666
|
+
trailingNewline: raw.length === 0 || /\r?\n$/.test(raw)
|
|
2667
|
+
};
|
|
2668
|
+
};
|
|
2669
|
+
var renderJsonDocument = (value, format) => {
|
|
2670
|
+
const body = JSON.stringify(value, null, format.indent);
|
|
2671
|
+
const withEol = format.eol === "\n" ? body : body.split("\n").join(format.eol);
|
|
2672
|
+
return format.trailingNewline ? `${withEol}${format.eol}` : withEol;
|
|
2673
|
+
};
|
|
2674
|
+
var readJsonDocument = async (filePath) => {
|
|
2675
|
+
let raw;
|
|
2676
|
+
try {
|
|
2677
|
+
raw = await readFile(filePath, "utf8");
|
|
2678
|
+
} catch (thrown) {
|
|
2679
|
+
if (isErrnoException(thrown, "ENOENT")) {
|
|
2680
|
+
return { status: "absent", format: DEFAULT_DOCUMENT_FORMAT };
|
|
2681
|
+
}
|
|
2682
|
+
return {
|
|
2683
|
+
status: "unreadable",
|
|
2684
|
+
detail: thrown instanceof Error ? thrown.name : typeof thrown
|
|
2685
|
+
};
|
|
2686
|
+
}
|
|
2687
|
+
const format = detectDocumentFormat(raw);
|
|
2688
|
+
if (raw.trim().length === 0) {
|
|
2689
|
+
return { status: "absent", format };
|
|
2690
|
+
}
|
|
2691
|
+
try {
|
|
2692
|
+
return { status: "ok", value: JSON.parse(raw), raw, format };
|
|
2693
|
+
} catch (thrown) {
|
|
2694
|
+
return {
|
|
2695
|
+
status: "unparseable",
|
|
2696
|
+
raw,
|
|
2697
|
+
detail: thrown instanceof Error ? thrown.message.slice(0, 200) : "not well-formed JSON",
|
|
2698
|
+
format
|
|
2699
|
+
};
|
|
2700
|
+
}
|
|
2701
|
+
};
|
|
2702
|
+
var RENAME_RETRY_DELAYS_MILLIS = [10, 25, 50, 100];
|
|
2703
|
+
var delay = (millis) => new Promise((resolve3) => {
|
|
2704
|
+
setTimeout(resolve3, millis);
|
|
2705
|
+
});
|
|
2706
|
+
var renameWithRetry = async (from, to) => {
|
|
2707
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
2708
|
+
try {
|
|
2709
|
+
await rename(from, to);
|
|
2710
|
+
return;
|
|
2711
|
+
} catch (thrown) {
|
|
2712
|
+
const retryable = isErrnoException(thrown, "EPERM", "EACCES", "EBUSY");
|
|
2713
|
+
const remaining = RENAME_RETRY_DELAYS_MILLIS[attempt];
|
|
2714
|
+
if (!retryable || remaining === void 0) {
|
|
2715
|
+
throw thrown;
|
|
2716
|
+
}
|
|
2717
|
+
await delay(remaining);
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
};
|
|
2721
|
+
var NEW_DOCUMENT_MODE = 384;
|
|
2722
|
+
var TEMPORARY_DOCUMENT_MODE = 384;
|
|
2723
|
+
var writeDocumentAtomically = async (filePath, contents) => {
|
|
2724
|
+
const directory = path2.dirname(filePath);
|
|
2725
|
+
await mkdir(directory, { recursive: true });
|
|
2726
|
+
const temporary = path2.join(
|
|
2727
|
+
directory,
|
|
2728
|
+
`.${path2.basename(filePath)}.${randomBytes(6).toString("hex")}.tmp`
|
|
2729
|
+
);
|
|
2730
|
+
let existingMode;
|
|
2731
|
+
try {
|
|
2732
|
+
existingMode = (await stat(filePath)).mode & 4095;
|
|
2733
|
+
} catch (thrown) {
|
|
2734
|
+
if (!isErrnoException(thrown, "ENOENT")) {
|
|
2735
|
+
throw thrown;
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
|
|
2739
|
+
try {
|
|
2740
|
+
const handle = await open(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
|
|
2741
|
+
try {
|
|
2742
|
+
await handle.writeFile(contents, "utf8");
|
|
2743
|
+
await handle.sync();
|
|
2744
|
+
await handle.chmod(targetMode);
|
|
2745
|
+
} finally {
|
|
2746
|
+
await handle.close();
|
|
2747
|
+
}
|
|
2748
|
+
await renameWithRetry(temporary, filePath);
|
|
2749
|
+
} catch (thrown) {
|
|
2750
|
+
await unlink(temporary).catch(() => void 0);
|
|
2751
|
+
throw thrown;
|
|
2752
|
+
}
|
|
2753
|
+
};
|
|
2754
|
+
|
|
2755
|
+
// src/install/file-lock.ts
|
|
2756
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
2757
|
+
import { mkdir as mkdir2, open as open2, readFile as readFile2, rename as rename2, stat as stat2, unlink as unlink2 } from "fs/promises";
|
|
2758
|
+
import * as path3 from "path";
|
|
2759
|
+
var FileLockTimeoutError = class extends Error {
|
|
2760
|
+
constructor(lockPath, timeoutMillis) {
|
|
2761
|
+
super(
|
|
2762
|
+
`timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path3.basename(lockPath)}`
|
|
2763
|
+
);
|
|
2764
|
+
this.name = "FileLockTimeoutError";
|
|
2765
|
+
}
|
|
2766
|
+
};
|
|
2767
|
+
var lockPathFor = (filePath) => `${filePath}.otel-hook.lock`;
|
|
2768
|
+
var RECLAIM_UNTOKENED = "reclaim-untokened";
|
|
2769
|
+
var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
|
|
2770
|
+
var readLockContents = async (lockPath) => {
|
|
2771
|
+
let raw;
|
|
2772
|
+
try {
|
|
2773
|
+
raw = await readFile2(lockPath, "utf8");
|
|
2774
|
+
} catch {
|
|
2775
|
+
return void 0;
|
|
2776
|
+
}
|
|
2777
|
+
try {
|
|
2778
|
+
const parsed = JSON.parse(raw);
|
|
2779
|
+
return typeof parsed.token === "string" && typeof parsed.acquiredAt === "number" && typeof parsed.pid === "number" ? { token: parsed.token, pid: parsed.pid, acquiredAt: parsed.acquiredAt } : void 0;
|
|
2780
|
+
} catch {
|
|
2781
|
+
return void 0;
|
|
2782
|
+
}
|
|
2783
|
+
};
|
|
2784
|
+
var releaseIfOwned = async (lockPath, token) => {
|
|
2785
|
+
const tombstone = `${lockPath}.${token}.releasing`;
|
|
2786
|
+
try {
|
|
2787
|
+
await rename2(lockPath, tombstone);
|
|
2788
|
+
} catch {
|
|
2789
|
+
return false;
|
|
2790
|
+
}
|
|
2791
|
+
const captured = await readLockContents(tombstone);
|
|
2792
|
+
if (captured !== void 0 && captured.token !== token) {
|
|
2793
|
+
await rename2(tombstone, lockPath).catch(async () => {
|
|
2794
|
+
await Promise.resolve();
|
|
2795
|
+
});
|
|
2796
|
+
return false;
|
|
2797
|
+
}
|
|
2798
|
+
await unlink2(tombstone).catch(() => void 0);
|
|
2799
|
+
return true;
|
|
2800
|
+
};
|
|
2801
|
+
var delay2 = (millis) => new Promise((resolve3) => {
|
|
2802
|
+
setTimeout(resolve3, millis);
|
|
2803
|
+
});
|
|
2804
|
+
var isStale = async (lockPath, clock, staleMillis) => {
|
|
2805
|
+
let raw;
|
|
2806
|
+
try {
|
|
2807
|
+
raw = await readFile2(lockPath, "utf8");
|
|
2808
|
+
} catch (thrown) {
|
|
2809
|
+
return { stale: !isErrnoException2(thrown, "ENOENT") };
|
|
2810
|
+
}
|
|
2811
|
+
try {
|
|
2812
|
+
const parsed = JSON.parse(raw);
|
|
2813
|
+
if (typeof parsed.acquiredAt === "number") {
|
|
2814
|
+
return {
|
|
2815
|
+
stale: clock.now() - parsed.acquiredAt > staleMillis,
|
|
2816
|
+
...typeof parsed.token === "string" ? { token: parsed.token } : {}
|
|
2817
|
+
};
|
|
2818
|
+
}
|
|
2819
|
+
} catch {
|
|
2820
|
+
}
|
|
2821
|
+
try {
|
|
2822
|
+
const stats = await stat2(lockPath);
|
|
2823
|
+
return { stale: clock.now() - stats.mtimeMs > staleMillis };
|
|
2824
|
+
} catch (thrown) {
|
|
2825
|
+
return { stale: !isErrnoException2(thrown, "ENOENT") };
|
|
2826
|
+
}
|
|
2827
|
+
};
|
|
2828
|
+
var withFileLock = async (filePath, options, fn) => {
|
|
2829
|
+
const timeoutMillis = options.timeoutMillis ?? 5e3;
|
|
2830
|
+
const staleMillis = options.staleMillis ?? 3e4;
|
|
2831
|
+
const pollIntervalMillis = options.pollIntervalMillis ?? 25;
|
|
2832
|
+
const lockPath = lockPathFor(filePath);
|
|
2833
|
+
const startedAt = options.clock.monotonicMillis();
|
|
2834
|
+
await mkdir2(path3.dirname(filePath), { recursive: true });
|
|
2835
|
+
for (; ; ) {
|
|
2836
|
+
const token = randomBytes2(16).toString("hex");
|
|
2837
|
+
let acquired = false;
|
|
2838
|
+
try {
|
|
2839
|
+
const handle = await open2(lockPath, "wx", 384);
|
|
2840
|
+
try {
|
|
2841
|
+
const contents = {
|
|
2842
|
+
token,
|
|
2843
|
+
pid: process.pid,
|
|
2844
|
+
acquiredAt: options.clock.now()
|
|
2845
|
+
};
|
|
2846
|
+
await handle.writeFile(JSON.stringify(contents));
|
|
2847
|
+
await handle.sync();
|
|
2848
|
+
} finally {
|
|
2849
|
+
await handle.close();
|
|
2850
|
+
}
|
|
2851
|
+
acquired = true;
|
|
2852
|
+
} catch (thrown) {
|
|
2853
|
+
if (!isErrnoException2(thrown, "EEXIST")) {
|
|
2854
|
+
throw thrown;
|
|
2855
|
+
}
|
|
2856
|
+
}
|
|
2857
|
+
if (acquired) {
|
|
2858
|
+
try {
|
|
2859
|
+
return await fn();
|
|
2860
|
+
} finally {
|
|
2861
|
+
await releaseIfOwned(lockPath, token);
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
const staleness = await isStale(lockPath, options.clock, staleMillis);
|
|
2865
|
+
if (staleness.stale) {
|
|
2866
|
+
if (staleness.token === void 0) {
|
|
2867
|
+
await releaseIfOwned(lockPath, RECLAIM_UNTOKENED);
|
|
2868
|
+
} else {
|
|
2869
|
+
await releaseIfOwned(lockPath, staleness.token);
|
|
2870
|
+
}
|
|
2871
|
+
continue;
|
|
2872
|
+
}
|
|
2873
|
+
if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {
|
|
2874
|
+
throw new FileLockTimeoutError(lockPath, timeoutMillis);
|
|
2875
|
+
}
|
|
2876
|
+
await delay2(pollIntervalMillis);
|
|
2877
|
+
}
|
|
2878
|
+
};
|
|
2879
|
+
|
|
2880
|
+
// src/install/lifecycle.ts
|
|
2881
|
+
import { readFile as readFile3 } from "fs/promises";
|
|
2882
|
+
import * as path4 from "path";
|
|
2883
|
+
var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
|
|
2884
|
+
var unsupportedOutcome = (providerId, scope, reason) => ({
|
|
2885
|
+
providerId,
|
|
2886
|
+
scope,
|
|
2887
|
+
status: "unsupported",
|
|
2888
|
+
changed: false,
|
|
2889
|
+
changes: [],
|
|
2890
|
+
conflicts: [],
|
|
2891
|
+
registeredEvents: [],
|
|
2892
|
+
missingEvents: [],
|
|
2893
|
+
notes: [],
|
|
2894
|
+
problems: [reason]
|
|
2895
|
+
});
|
|
2896
|
+
var resolveTarget = (providerId, scope, request) => {
|
|
2897
|
+
if (request.configFile !== void 0) {
|
|
2898
|
+
return {
|
|
2899
|
+
configPath: path4.resolve(request.configFile),
|
|
2900
|
+
evidence: "path supplied by the caller with --settings-file"
|
|
2901
|
+
};
|
|
2902
|
+
}
|
|
2903
|
+
const location = findInstallLocation(providerId, scope);
|
|
2904
|
+
if (location !== void 0) {
|
|
2905
|
+
return {
|
|
2906
|
+
configPath: resolveInstallPath(location, request.roots),
|
|
2907
|
+
evidence: location.evidence
|
|
2908
|
+
};
|
|
2909
|
+
}
|
|
2910
|
+
const blocker = PROVIDERS_WITHOUT_VERIFIED_LOCATION[providerId];
|
|
2911
|
+
return {
|
|
2912
|
+
reason: blocker === void 0 ? `no ${scope} configuration path is known for provider "${providerId}"` : `${blocker}; pass --settings-file to register into a path you have verified yourself`
|
|
2913
|
+
};
|
|
2914
|
+
};
|
|
2915
|
+
var codexFeatureNote = async (configPath) => {
|
|
2916
|
+
const tomlPath = path4.join(path4.dirname(configPath), "config.toml");
|
|
2917
|
+
let raw;
|
|
2918
|
+
try {
|
|
2919
|
+
raw = await readFile3(tomlPath, "utf8");
|
|
2920
|
+
} catch {
|
|
2921
|
+
return void 0;
|
|
2922
|
+
}
|
|
2923
|
+
return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path4.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
|
|
2924
|
+
};
|
|
2925
|
+
var readState = async (configPath) => {
|
|
2926
|
+
const read = await readJsonDocument(configPath);
|
|
2927
|
+
switch (read.status) {
|
|
2928
|
+
case "absent":
|
|
2929
|
+
return { existing: void 0, format: read.format, existed: false };
|
|
2930
|
+
case "ok":
|
|
2931
|
+
return { existing: read.value, format: read.format, existed: true };
|
|
2932
|
+
case "unparseable":
|
|
2933
|
+
return {
|
|
2934
|
+
status: "blocked",
|
|
2935
|
+
problem: `${path4.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
|
|
2936
|
+
};
|
|
2937
|
+
case "unreadable":
|
|
2938
|
+
return {
|
|
2939
|
+
status: "failed",
|
|
2940
|
+
problem: `${path4.basename(configPath)} could not be read (${read.detail})`
|
|
2941
|
+
};
|
|
2942
|
+
}
|
|
2943
|
+
};
|
|
2944
|
+
var duplicateProblems = (registrations) => {
|
|
2945
|
+
const duplicated = [...registrations.entries()].filter(([, commands]) => commands.length > 1).map(([event3]) => event3);
|
|
2946
|
+
return duplicated.length === 0 ? [] : [
|
|
2947
|
+
`${String(duplicated.length)} event(s) carry more than one registration of this hook (${duplicated.join(", ")}), which would duplicate every span; re-run setup to collapse them`
|
|
2948
|
+
];
|
|
2949
|
+
};
|
|
2950
|
+
var staleCommandNotes = (registrations, command) => {
|
|
2951
|
+
const stale = /* @__PURE__ */ new Set();
|
|
2952
|
+
for (const commands of registrations.values()) {
|
|
2953
|
+
for (const found of commands) {
|
|
2954
|
+
if (found !== command) {
|
|
2955
|
+
stale.add(found);
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
}
|
|
2959
|
+
return [...stale].sort().map(
|
|
2960
|
+
(found) => `registered command "${found}" differs from "${command}"; re-run setup to rewrite it in place`
|
|
2961
|
+
);
|
|
2962
|
+
};
|
|
2963
|
+
var runOneTarget = async (providerId, scope, request, command) => {
|
|
2964
|
+
const support = findRegistrationSupport(providerId);
|
|
2965
|
+
const planner = findRegistrationPlanner(providerId);
|
|
2966
|
+
if (planner === void 0 || support?.supported !== true) {
|
|
2967
|
+
return unsupportedOutcome(
|
|
2968
|
+
providerId,
|
|
2969
|
+
scope,
|
|
2970
|
+
support?.reason ?? `no registration planner is available for provider "${providerId}"`
|
|
2971
|
+
);
|
|
2972
|
+
}
|
|
2973
|
+
const target = resolveTarget(providerId, scope, request);
|
|
2974
|
+
if ("reason" in target) {
|
|
2975
|
+
return unsupportedOutcome(providerId, scope, target.reason);
|
|
2976
|
+
}
|
|
2977
|
+
const { configPath, evidence } = target;
|
|
2978
|
+
const identifies = managedHookPredicate(
|
|
2979
|
+
request.managedMarker ?? DEFAULT_MANAGED_COMMAND_MARKER
|
|
2980
|
+
);
|
|
2981
|
+
const events = request.events ?? planner.defaultEvents;
|
|
2982
|
+
const notes = [];
|
|
2983
|
+
if (providerId === CODEX_PROVIDER_ID) {
|
|
2984
|
+
const note = await codexFeatureNote(configPath);
|
|
2985
|
+
if (note !== void 0) {
|
|
2986
|
+
notes.push(note);
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
const base = {
|
|
2990
|
+
providerId,
|
|
2991
|
+
scope,
|
|
2992
|
+
configPath,
|
|
2993
|
+
evidence,
|
|
2994
|
+
changes: [],
|
|
2995
|
+
conflicts: []
|
|
2996
|
+
};
|
|
2997
|
+
const work = async () => {
|
|
2998
|
+
const state = await readState(configPath);
|
|
2999
|
+
if ("problem" in state) {
|
|
3000
|
+
return {
|
|
3001
|
+
...base,
|
|
3002
|
+
status: state.status,
|
|
3003
|
+
changed: false,
|
|
3004
|
+
registeredEvents: [],
|
|
3005
|
+
missingEvents: [],
|
|
3006
|
+
notes,
|
|
3007
|
+
problems: [state.problem]
|
|
3008
|
+
};
|
|
3009
|
+
}
|
|
3010
|
+
const registrations = planner.read(state.existing, identifies);
|
|
3011
|
+
const registeredEvents = [...registrations.keys()].sort();
|
|
3012
|
+
if (request.action === "diagnose") {
|
|
3013
|
+
const missingEvents = events.filter((event3) => !registrations.has(event3));
|
|
3014
|
+
const problems = [...duplicateProblems(registrations)];
|
|
3015
|
+
if (registeredEvents.length > 0 && missingEvents.length > 0) {
|
|
3016
|
+
problems.push(
|
|
3017
|
+
`registered for ${String(registeredEvents.length)} event(s) but missing ${String(missingEvents.length)} (${missingEvents.join(", ")}); re-run setup`
|
|
3018
|
+
);
|
|
3019
|
+
}
|
|
3020
|
+
return {
|
|
3021
|
+
...base,
|
|
3022
|
+
status: registeredEvents.length === 0 ? "absent" : "unchanged",
|
|
3023
|
+
changed: false,
|
|
3024
|
+
registeredEvents,
|
|
3025
|
+
missingEvents,
|
|
3026
|
+
notes: [...notes, ...staleCommandNotes(registrations, command)],
|
|
3027
|
+
problems
|
|
3028
|
+
};
|
|
3029
|
+
}
|
|
3030
|
+
const planned = request.action === "setup" ? planner.merge({
|
|
3031
|
+
...state.existing === void 0 ? {} : { existing: state.existing },
|
|
3032
|
+
command,
|
|
3033
|
+
events,
|
|
3034
|
+
...request.matcher === void 0 ? {} : { matcher: request.matcher },
|
|
3035
|
+
...request.timeoutSeconds === void 0 ? {} : { timeoutSeconds: request.timeoutSeconds },
|
|
3036
|
+
identifies
|
|
3037
|
+
}) : planner.remove({
|
|
3038
|
+
...state.existing === void 0 ? {} : { existing: state.existing },
|
|
3039
|
+
...request.events === void 0 ? {} : { events: request.events },
|
|
3040
|
+
identifies
|
|
3041
|
+
});
|
|
3042
|
+
if (planned.conflicts.length > 0) {
|
|
3043
|
+
return {
|
|
3044
|
+
...base,
|
|
3045
|
+
status: "blocked",
|
|
3046
|
+
changed: false,
|
|
3047
|
+
conflicts: planned.conflicts,
|
|
3048
|
+
registeredEvents,
|
|
3049
|
+
missingEvents: [],
|
|
3050
|
+
notes,
|
|
3051
|
+
problems: planned.conflicts.map(
|
|
3052
|
+
(conflict) => `${path4.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
|
|
3053
|
+
)
|
|
3054
|
+
};
|
|
3055
|
+
}
|
|
3056
|
+
if (request.action === "uninstall" && !state.existed) {
|
|
3057
|
+
return {
|
|
3058
|
+
...base,
|
|
3059
|
+
status: "absent",
|
|
3060
|
+
changed: false,
|
|
3061
|
+
registeredEvents: [],
|
|
3062
|
+
missingEvents: [],
|
|
3063
|
+
notes: [...notes, `${path4.basename(configPath)} does not exist; nothing to remove`],
|
|
3064
|
+
problems: []
|
|
3065
|
+
};
|
|
3066
|
+
}
|
|
3067
|
+
if (!planned.changed) {
|
|
3068
|
+
return {
|
|
3069
|
+
...base,
|
|
3070
|
+
status: request.action === "uninstall" && registeredEvents.length === 0 ? "absent" : "unchanged",
|
|
3071
|
+
changed: false,
|
|
3072
|
+
changes: planned.changes,
|
|
3073
|
+
registeredEvents,
|
|
3074
|
+
missingEvents: [],
|
|
3075
|
+
notes,
|
|
3076
|
+
problems: []
|
|
3077
|
+
};
|
|
3078
|
+
}
|
|
3079
|
+
const format = state.existed ? state.format : DEFAULT_DOCUMENT_FORMAT;
|
|
3080
|
+
const contents = renderJsonDocument(planned.document, format);
|
|
3081
|
+
if (request.dryRun) {
|
|
3082
|
+
return {
|
|
3083
|
+
...base,
|
|
3084
|
+
status: "planned",
|
|
3085
|
+
changed: true,
|
|
3086
|
+
changes: planned.changes,
|
|
3087
|
+
registeredEvents,
|
|
3088
|
+
missingEvents: [],
|
|
3089
|
+
notes,
|
|
3090
|
+
problems: [],
|
|
3091
|
+
plannedContents: contents
|
|
3092
|
+
};
|
|
3093
|
+
}
|
|
3094
|
+
try {
|
|
3095
|
+
await writeDocumentAtomically(configPath, contents);
|
|
3096
|
+
} catch (thrown) {
|
|
3097
|
+
return {
|
|
3098
|
+
...base,
|
|
3099
|
+
status: "failed",
|
|
3100
|
+
changed: false,
|
|
3101
|
+
changes: planned.changes,
|
|
3102
|
+
registeredEvents,
|
|
3103
|
+
missingEvents: [],
|
|
3104
|
+
notes,
|
|
3105
|
+
problems: [
|
|
3106
|
+
`could not write ${path4.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
|
|
3107
|
+
]
|
|
3108
|
+
};
|
|
3109
|
+
}
|
|
3110
|
+
return {
|
|
3111
|
+
...base,
|
|
3112
|
+
status: "applied",
|
|
3113
|
+
changed: true,
|
|
3114
|
+
changes: planned.changes,
|
|
3115
|
+
registeredEvents,
|
|
3116
|
+
missingEvents: [],
|
|
3117
|
+
notes,
|
|
3118
|
+
problems: []
|
|
3119
|
+
};
|
|
3120
|
+
};
|
|
3121
|
+
const mutating = request.action !== "diagnose" && !request.dryRun;
|
|
3122
|
+
try {
|
|
3123
|
+
return mutating ? await withFileLock(configPath, { ...request.lock, clock: request.clock }, work) : await work();
|
|
3124
|
+
} catch (thrown) {
|
|
3125
|
+
return {
|
|
3126
|
+
...base,
|
|
3127
|
+
status: "failed",
|
|
3128
|
+
changed: false,
|
|
3129
|
+
registeredEvents: [],
|
|
3130
|
+
missingEvents: [],
|
|
3131
|
+
notes,
|
|
3132
|
+
problems: [
|
|
3133
|
+
thrown instanceof Error ? `${path4.basename(configPath)}: ${thrown.message}` : `${path4.basename(configPath)}: the configuration file could not be locked`
|
|
3134
|
+
]
|
|
3135
|
+
};
|
|
3136
|
+
}
|
|
3137
|
+
};
|
|
3138
|
+
var runRegistrationLifecycle = async (request) => {
|
|
3139
|
+
const markerRejection = checkManagedMarker(
|
|
3140
|
+
request.managedMarker ?? DEFAULT_MANAGED_COMMAND_MARKER
|
|
3141
|
+
);
|
|
3142
|
+
if (markerRejection !== void 0) {
|
|
3143
|
+
const reason = `refusing to run ${request.action}: ${MANAGED_MARKER_REJECTION_DETAIL[markerRejection]}`;
|
|
3144
|
+
return {
|
|
3145
|
+
action: request.action,
|
|
3146
|
+
dryRun: request.dryRun,
|
|
3147
|
+
ok: false,
|
|
3148
|
+
hookCommand: request.command ?? defaultHookCommand("<provider>"),
|
|
3149
|
+
outcomes: request.providerIds.flatMap(
|
|
3150
|
+
(providerId) => request.scopes.map((scope) => ({
|
|
3151
|
+
...unsupportedOutcome(providerId, scope, reason),
|
|
3152
|
+
status: "blocked"
|
|
3153
|
+
}))
|
|
3154
|
+
)
|
|
3155
|
+
};
|
|
3156
|
+
}
|
|
3157
|
+
const outcomes = [];
|
|
3158
|
+
for (const providerId of request.providerIds) {
|
|
3159
|
+
const command = request.command ?? defaultHookCommand(providerId);
|
|
3160
|
+
for (const scope of request.scopes) {
|
|
3161
|
+
outcomes.push(await runOneTarget(providerId, scope, request, command));
|
|
3162
|
+
}
|
|
3163
|
+
}
|
|
3164
|
+
return {
|
|
3165
|
+
action: request.action,
|
|
3166
|
+
dryRun: request.dryRun,
|
|
3167
|
+
ok: outcomes.every((outcome) => outcome.problems.length === 0),
|
|
3168
|
+
hookCommand: request.command ?? defaultHookCommand("<provider>"),
|
|
3169
|
+
outcomes
|
|
3170
|
+
};
|
|
3171
|
+
};
|
|
3172
|
+
|
|
3173
|
+
// src/install/index.ts
|
|
3174
|
+
var planProviderRegistration = (input) => {
|
|
3175
|
+
const support = findRegistrationSupport(input.providerId);
|
|
3176
|
+
const planner = findRegistrationPlanner(input.providerId);
|
|
3177
|
+
if (planner === void 0 || support?.supported !== true) {
|
|
3178
|
+
return {
|
|
3179
|
+
status: "unsupported",
|
|
3180
|
+
providerId: input.providerId,
|
|
3181
|
+
reason: support?.reason ?? `no registration planner is available for provider "${input.providerId}"`
|
|
3182
|
+
};
|
|
3183
|
+
}
|
|
3184
|
+
const options = input.options ?? {};
|
|
3185
|
+
if (typeof options.command !== "string" || options.command.length === 0) {
|
|
3186
|
+
return {
|
|
3187
|
+
status: "invalid",
|
|
3188
|
+
providerId: input.providerId,
|
|
3189
|
+
reason: `planning a "${input.providerId}" registration requires a non-empty options.command`
|
|
3190
|
+
};
|
|
3191
|
+
}
|
|
3192
|
+
const timeoutSeconds = options.timeoutSeconds ?? options.timeout;
|
|
3193
|
+
const result = planner.merge({
|
|
3194
|
+
...input.existing === void 0 ? {} : { existing: input.existing },
|
|
3195
|
+
command: options.command,
|
|
3196
|
+
...options.events === void 0 ? {} : { events: options.events },
|
|
3197
|
+
...options.matcher === void 0 ? {} : { matcher: options.matcher },
|
|
3198
|
+
...timeoutSeconds === void 0 ? {} : { timeoutSeconds },
|
|
3199
|
+
identifies: options.identifies ?? managedHookPredicate(options.command)
|
|
3200
|
+
});
|
|
3201
|
+
if (result.conflicts.length > 0) {
|
|
3202
|
+
return { status: "conflict", providerId: input.providerId, conflicts: result.conflicts };
|
|
3203
|
+
}
|
|
3204
|
+
return {
|
|
3205
|
+
status: "planned",
|
|
3206
|
+
providerId: input.providerId,
|
|
3207
|
+
document: result.document,
|
|
3208
|
+
changed: result.changed,
|
|
3209
|
+
changes: result.changes
|
|
3210
|
+
};
|
|
3211
|
+
};
|
|
3212
|
+
export {
|
|
3213
|
+
CLAUDE_HOOK_EVENTS_MODELLED,
|
|
3214
|
+
CLAUDE_REGISTRABLE_HOOK_EVENTS,
|
|
3215
|
+
CLAUDE_UNREGISTERED_HOOK_EVENTS,
|
|
3216
|
+
CODEX_HOOK_EVENTS_MODELLED,
|
|
3217
|
+
CODEX_REGISTRABLE_HOOK_EVENTS,
|
|
3218
|
+
CODEX_UNREGISTERED_HOOK_EVENTS,
|
|
3219
|
+
CURSOR_HOOKS_DOCUMENT_VERSION,
|
|
3220
|
+
CURSOR_HOOK_EVENTS_MODELLED,
|
|
3221
|
+
CURSOR_REGISTRABLE_HOOK_EVENTS,
|
|
3222
|
+
CURSOR_UNREGISTERED_HOOK_EVENTS,
|
|
3223
|
+
DEFAULT_DOCUMENT_FORMAT,
|
|
3224
|
+
DEFAULT_MANAGED_COMMAND_MARKER,
|
|
3225
|
+
FileLockTimeoutError,
|
|
3226
|
+
MANAGED_HOOK_NAME,
|
|
3227
|
+
MANAGED_MARKER_REJECTION_DETAIL,
|
|
3228
|
+
MANAGED_MARKER_TOKEN,
|
|
3229
|
+
PROVIDERS_WITHOUT_VERIFIED_LOCATION,
|
|
3230
|
+
PROVIDERS_WITH_VERIFIED_LOCATION,
|
|
3231
|
+
PROVIDER_INSTALL_LOCATIONS,
|
|
3232
|
+
PROVIDER_REGISTRATION_SUPPORT,
|
|
3233
|
+
REGISTRATION_PLANNERS,
|
|
3234
|
+
REGISTRATION_SCOPES,
|
|
3235
|
+
SUPPORTED_REGISTRATION_PROVIDER_IDS,
|
|
3236
|
+
checkManagedMarker,
|
|
3237
|
+
defaultHookCommand,
|
|
3238
|
+
detectDocumentFormat,
|
|
3239
|
+
findInstallLocation,
|
|
3240
|
+
findRegistrationPlanner,
|
|
3241
|
+
findRegistrationSupport,
|
|
3242
|
+
lockPathFor,
|
|
3243
|
+
managedHookPredicate,
|
|
3244
|
+
mergeAntigravityHookRegistration,
|
|
3245
|
+
mergeClaudeHookRegistration,
|
|
3246
|
+
mergeCodexHookRegistration,
|
|
3247
|
+
mergeCursorHookRegistration,
|
|
3248
|
+
mergeGeminiHookRegistration,
|
|
3249
|
+
mergeNestedHookRegistration,
|
|
3250
|
+
planProviderRegistration,
|
|
3251
|
+
readAntigravityHookRegistrations,
|
|
3252
|
+
readClaudeHookRegistrations,
|
|
3253
|
+
readCodexHookRegistrations,
|
|
3254
|
+
readCodexHooksFeatureFlag,
|
|
3255
|
+
readCursorHookRegistrations,
|
|
3256
|
+
readGeminiHookRegistrations,
|
|
3257
|
+
readJsonDocument,
|
|
3258
|
+
readNestedHookRegistrations,
|
|
3259
|
+
removeAntigravityHookRegistration,
|
|
3260
|
+
removeClaudeHookRegistration,
|
|
3261
|
+
removeCodexHookRegistration,
|
|
3262
|
+
removeCursorHookRegistration,
|
|
3263
|
+
removeGeminiHookRegistration,
|
|
3264
|
+
removeNestedHookRegistrations,
|
|
3265
|
+
renderJsonDocument,
|
|
3266
|
+
resolveInstallPath,
|
|
3267
|
+
runRegistrationLifecycle,
|
|
3268
|
+
withFileLock,
|
|
3269
|
+
writeDocumentAtomically
|
|
3270
|
+
};
|
|
3271
|
+
//# sourceMappingURL=install.js.map
|