@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/state.js
ADDED
|
@@ -0,0 +1,710 @@
|
|
|
1
|
+
// src/state/async-lock.ts
|
|
2
|
+
var LockWaitTimeoutError = class extends Error {
|
|
3
|
+
lockKey;
|
|
4
|
+
constructor(key, timeoutMillis) {
|
|
5
|
+
super(`lock wait exceeded ${timeoutMillis}ms`);
|
|
6
|
+
this.name = "LockWaitTimeoutError";
|
|
7
|
+
this.lockKey = key;
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var createAsyncLock = () => {
|
|
11
|
+
const tail = /* @__PURE__ */ new Map();
|
|
12
|
+
const run = async (key, fn, timeoutMillis) => {
|
|
13
|
+
const previous = tail.get(key) ?? Promise.resolve();
|
|
14
|
+
const queued = previous.then(
|
|
15
|
+
() => void 0,
|
|
16
|
+
() => void 0
|
|
17
|
+
);
|
|
18
|
+
let cancelled = false;
|
|
19
|
+
let entered = false;
|
|
20
|
+
const current = queued.then(() => {
|
|
21
|
+
if (cancelled) {
|
|
22
|
+
throw new LockWaitTimeoutError(key, timeoutMillis ?? 0);
|
|
23
|
+
}
|
|
24
|
+
entered = true;
|
|
25
|
+
return fn();
|
|
26
|
+
});
|
|
27
|
+
const swallowed = current.then(
|
|
28
|
+
() => void 0,
|
|
29
|
+
() => void 0
|
|
30
|
+
);
|
|
31
|
+
tail.set(key, swallowed);
|
|
32
|
+
void swallowed.then(() => {
|
|
33
|
+
if (tail.get(key) === swallowed) {
|
|
34
|
+
tail.delete(key);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
if (timeoutMillis === void 0) {
|
|
38
|
+
return current;
|
|
39
|
+
}
|
|
40
|
+
let timer;
|
|
41
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
42
|
+
timer = setTimeout(() => {
|
|
43
|
+
if (!entered) {
|
|
44
|
+
cancelled = true;
|
|
45
|
+
}
|
|
46
|
+
reject(new LockWaitTimeoutError(key, timeoutMillis));
|
|
47
|
+
}, timeoutMillis);
|
|
48
|
+
timer.unref?.();
|
|
49
|
+
});
|
|
50
|
+
try {
|
|
51
|
+
await Promise.race([queued, timeout]);
|
|
52
|
+
} finally {
|
|
53
|
+
if (timer !== void 0) {
|
|
54
|
+
clearTimeout(timer);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return current;
|
|
58
|
+
};
|
|
59
|
+
return { run };
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// src/state/store.ts
|
|
63
|
+
var StateLockTimeoutError = class extends Error {
|
|
64
|
+
lockKey;
|
|
65
|
+
constructor(key, timeoutMillis) {
|
|
66
|
+
super(`state store lock wait for "${key}" exceeded ${String(timeoutMillis)}ms`);
|
|
67
|
+
this.name = "StateLockTimeoutError";
|
|
68
|
+
this.lockKey = key;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
var isLockingStateStore = (store) => typeof store.withSessionLock === "function";
|
|
72
|
+
var withOptionalSessionLock = async (store, sessionId, fn, options) => {
|
|
73
|
+
if (isLockingStateStore(store)) {
|
|
74
|
+
return store.withSessionLock(sessionId, fn, options);
|
|
75
|
+
}
|
|
76
|
+
return fn();
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// src/runtime/ports.ts
|
|
80
|
+
import { z as z3 } from "zod";
|
|
81
|
+
|
|
82
|
+
// src/model/primitives.ts
|
|
83
|
+
import { z } from "zod";
|
|
84
|
+
var MAX_IDENTIFIER_LENGTH = 256;
|
|
85
|
+
var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
|
|
86
|
+
var MAX_ATTRIBUTE_ARRAY_LENGTH = 128;
|
|
87
|
+
var nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
|
|
88
|
+
var epochMillisSchema = z.number().int().min(0).max(864e13);
|
|
89
|
+
var durationMillisSchema = z.number().min(0).finite();
|
|
90
|
+
var tokenCountSchema = z.number().int().min(0);
|
|
91
|
+
var sequenceNumberSchema = z.number().int().min(0);
|
|
92
|
+
var brandedIdSchema = () => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
|
|
93
|
+
var invocationIdSchema = brandedIdSchema().brand();
|
|
94
|
+
var sessionIdSchema = brandedIdSchema().brand();
|
|
95
|
+
var eventIdSchema = brandedIdSchema().brand();
|
|
96
|
+
var WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;
|
|
97
|
+
var workspaceIdSchema = z.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
|
|
98
|
+
var PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
99
|
+
var providerIdSchema = z.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
|
|
100
|
+
var UNKNOWN_PROVIDER_ID = "unknown";
|
|
101
|
+
var resolvedProviderIdSchema = z.union([
|
|
102
|
+
providerIdSchema,
|
|
103
|
+
z.literal(UNKNOWN_PROVIDER_ID)
|
|
104
|
+
]);
|
|
105
|
+
var attributePrimitiveSchema = z.union([
|
|
106
|
+
z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
|
|
107
|
+
z.number().finite(),
|
|
108
|
+
z.boolean()
|
|
109
|
+
]);
|
|
110
|
+
var attributeValueSchema = z.union([
|
|
111
|
+
attributePrimitiveSchema,
|
|
112
|
+
z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
|
|
113
|
+
]);
|
|
114
|
+
var attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
|
|
115
|
+
var detectionConfidenceSchema = z.enum(["none", "weak", "strong", "exact"]);
|
|
116
|
+
var DETECTION_CONFIDENCE_RANK = Object.freeze({
|
|
117
|
+
none: 0,
|
|
118
|
+
weak: 1,
|
|
119
|
+
strong: 2,
|
|
120
|
+
exact: 3
|
|
121
|
+
});
|
|
122
|
+
var sourceTransportSchema = z.enum([
|
|
123
|
+
"hook-stdin",
|
|
124
|
+
"cli-argument",
|
|
125
|
+
"library-call",
|
|
126
|
+
"test-fixture"
|
|
127
|
+
]);
|
|
128
|
+
|
|
129
|
+
// src/model/usage.ts
|
|
130
|
+
import { z as z2 } from "zod";
|
|
131
|
+
var usageTemporalitySchema = z2.enum(["delta", "cumulative"]);
|
|
132
|
+
var cacheCreationAccountingSchema = z2.enum([
|
|
133
|
+
"included-in-input",
|
|
134
|
+
"disjoint-from-input",
|
|
135
|
+
"not-reported"
|
|
136
|
+
]);
|
|
137
|
+
var providerTotalAgreementSchema = z2.enum(["unreported", "agrees", "disagrees"]);
|
|
138
|
+
var usageReportSchema = z2.strictObject({
|
|
139
|
+
temporality: usageTemporalitySchema,
|
|
140
|
+
/** Inclusive input tokens. */
|
|
141
|
+
inputTokens: tokenCountSchema.optional(),
|
|
142
|
+
/** Subset of `inputTokens` served from a prompt cache. */
|
|
143
|
+
cachedInputTokens: tokenCountSchema.optional(),
|
|
144
|
+
/** Tokens written to a prompt cache. */
|
|
145
|
+
cacheCreationInputTokens: tokenCountSchema.optional(),
|
|
146
|
+
/** Required when `cacheCreationInputTokens` is present and non-zero. */
|
|
147
|
+
cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
|
|
148
|
+
/** Inclusive output tokens. */
|
|
149
|
+
outputTokens: tokenCountSchema.optional(),
|
|
150
|
+
/** Subset of `outputTokens` spent on reasoning. */
|
|
151
|
+
reasoningOutputTokens: tokenCountSchema.optional(),
|
|
152
|
+
/** Total exactly as the provider reported it, if it reported one. */
|
|
153
|
+
providerTotalTokens: tokenCountSchema.optional()
|
|
154
|
+
});
|
|
155
|
+
var canonicalUsageSchema = z2.strictObject({
|
|
156
|
+
temporality: usageTemporalitySchema,
|
|
157
|
+
inputTokens: tokenCountSchema,
|
|
158
|
+
cachedInputTokens: tokenCountSchema,
|
|
159
|
+
cacheCreationInputTokens: tokenCountSchema,
|
|
160
|
+
cacheCreationAccounting: cacheCreationAccountingSchema,
|
|
161
|
+
outputTokens: tokenCountSchema,
|
|
162
|
+
reasoningOutputTokens: tokenCountSchema,
|
|
163
|
+
/** Derived: input tokens that were neither cache reads nor cache writes. */
|
|
164
|
+
uncachedInputTokens: tokenCountSchema,
|
|
165
|
+
/** Derived: canonical billable total. */
|
|
166
|
+
totalTokens: tokenCountSchema,
|
|
167
|
+
providerTotalTokens: tokenCountSchema.optional(),
|
|
168
|
+
providerTotalAgreement: providerTotalAgreementSchema
|
|
169
|
+
}).check((ctx) => {
|
|
170
|
+
const usage = ctx.value;
|
|
171
|
+
const push = (message) => {
|
|
172
|
+
ctx.issues.push({ code: "custom", input: usage, message });
|
|
173
|
+
};
|
|
174
|
+
if (usage.cachedInputTokens > usage.inputTokens) {
|
|
175
|
+
push("cachedInputTokens must not exceed inputTokens (it is a subset)");
|
|
176
|
+
}
|
|
177
|
+
if (usage.reasoningOutputTokens > usage.outputTokens) {
|
|
178
|
+
push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
|
|
179
|
+
}
|
|
180
|
+
if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
|
|
181
|
+
push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
|
|
182
|
+
}
|
|
183
|
+
const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
|
|
184
|
+
if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
|
|
185
|
+
push(
|
|
186
|
+
"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
|
|
190
|
+
if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
|
|
191
|
+
push(`uncachedInputTokens must equal ${expectedUncached}`);
|
|
192
|
+
}
|
|
193
|
+
const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
|
|
194
|
+
const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
|
|
195
|
+
if (usage.totalTokens !== expectedTotal) {
|
|
196
|
+
push(`totalTokens must equal ${expectedTotal}`);
|
|
197
|
+
}
|
|
198
|
+
const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
|
|
199
|
+
if (usage.providerTotalAgreement !== expectedAgreement) {
|
|
200
|
+
push(`providerTotalAgreement must be ${expectedAgreement}`);
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
var normalizeUsage = (report) => {
|
|
204
|
+
const parsed = usageReportSchema.safeParse(report);
|
|
205
|
+
if (!parsed.success) {
|
|
206
|
+
return {
|
|
207
|
+
status: "invalid",
|
|
208
|
+
issues: parsed.error.issues.map((issue) => ({
|
|
209
|
+
code: "invalid-report",
|
|
210
|
+
message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
|
|
211
|
+
}))
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
const input = parsed.data;
|
|
215
|
+
const issues = [];
|
|
216
|
+
const notes = [];
|
|
217
|
+
const inputTokens = input.inputTokens ?? 0;
|
|
218
|
+
const cachedInputTokens = input.cachedInputTokens ?? 0;
|
|
219
|
+
const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
|
|
220
|
+
const outputTokens = input.outputTokens ?? 0;
|
|
221
|
+
const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
|
|
222
|
+
let accounting;
|
|
223
|
+
if (cacheCreationInputTokens === 0) {
|
|
224
|
+
accounting = input.cacheCreationAccounting ?? "not-reported";
|
|
225
|
+
if (accounting !== "not-reported") {
|
|
226
|
+
notes.push(
|
|
227
|
+
`cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
} else if (input.cacheCreationAccounting === void 0) {
|
|
231
|
+
issues.push({
|
|
232
|
+
code: "cache-creation-accounting-missing",
|
|
233
|
+
message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
|
|
234
|
+
});
|
|
235
|
+
accounting = "not-reported";
|
|
236
|
+
} else if (input.cacheCreationAccounting === "not-reported") {
|
|
237
|
+
issues.push({
|
|
238
|
+
code: "cache-creation-accounting-missing",
|
|
239
|
+
message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
|
|
240
|
+
});
|
|
241
|
+
accounting = "not-reported";
|
|
242
|
+
} else {
|
|
243
|
+
accounting = input.cacheCreationAccounting;
|
|
244
|
+
}
|
|
245
|
+
if (cachedInputTokens > inputTokens) {
|
|
246
|
+
issues.push({
|
|
247
|
+
code: "cached-exceeds-input",
|
|
248
|
+
message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
if (reasoningOutputTokens > outputTokens) {
|
|
252
|
+
issues.push({
|
|
253
|
+
code: "reasoning-exceeds-output",
|
|
254
|
+
message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
|
|
258
|
+
if (cachedInputTokens + creationInsideInput > inputTokens) {
|
|
259
|
+
issues.push({
|
|
260
|
+
code: "cache-creation-exceeds-input",
|
|
261
|
+
message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
if (issues.length > 0) {
|
|
265
|
+
return { status: "invalid", issues };
|
|
266
|
+
}
|
|
267
|
+
const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
|
|
268
|
+
const totalTokens = inputTokens + creationOutsideInput + outputTokens;
|
|
269
|
+
const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
|
|
270
|
+
if (providerTotalAgreement === "disagrees") {
|
|
271
|
+
notes.push(
|
|
272
|
+
`providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
const usage = {
|
|
276
|
+
temporality: input.temporality,
|
|
277
|
+
inputTokens,
|
|
278
|
+
cachedInputTokens,
|
|
279
|
+
cacheCreationInputTokens,
|
|
280
|
+
cacheCreationAccounting: accounting,
|
|
281
|
+
outputTokens,
|
|
282
|
+
reasoningOutputTokens,
|
|
283
|
+
uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
|
|
284
|
+
totalTokens,
|
|
285
|
+
...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
|
|
286
|
+
providerTotalAgreement
|
|
287
|
+
};
|
|
288
|
+
return { status: "ok", usage, notes };
|
|
289
|
+
};
|
|
290
|
+
var UsageNormalizationError = class extends Error {
|
|
291
|
+
issues;
|
|
292
|
+
constructor(issues) {
|
|
293
|
+
super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
|
|
294
|
+
this.name = "UsageNormalizationError";
|
|
295
|
+
this.issues = issues;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
var normalizeUsageOrThrow = (report) => {
|
|
299
|
+
const result = normalizeUsage(report);
|
|
300
|
+
if (result.status === "invalid") {
|
|
301
|
+
throw new UsageNormalizationError(result.issues);
|
|
302
|
+
}
|
|
303
|
+
return result.usage;
|
|
304
|
+
};
|
|
305
|
+
var EMPTY_DELTA_USAGE = Object.freeze(
|
|
306
|
+
normalizeUsageOrThrow({ temporality: "delta" })
|
|
307
|
+
);
|
|
308
|
+
|
|
309
|
+
// src/runtime/ports.ts
|
|
310
|
+
var appliedDeliverySchema = z3.strictObject({
|
|
311
|
+
callbackId: z3.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
|
|
312
|
+
/** How many of that delivery's observations are folded in, counted from one. */
|
|
313
|
+
applications: z3.number().int().min(1).max(4096)
|
|
314
|
+
});
|
|
315
|
+
var stateValueSchema = z3.discriminatedUnion("kind", [
|
|
316
|
+
z3.strictObject({
|
|
317
|
+
kind: z3.literal("usage-cumulative"),
|
|
318
|
+
usage: canonicalUsageSchema,
|
|
319
|
+
/**
|
|
320
|
+
* Optional: absent on every record written before this field existed, which
|
|
321
|
+
* reads as "unknown provenance" and simply forgoes the idempotency check
|
|
322
|
+
* rather than resetting a baseline to gain it.
|
|
323
|
+
*/
|
|
324
|
+
appliedDelivery: appliedDeliverySchema.optional()
|
|
325
|
+
}),
|
|
326
|
+
z3.strictObject({
|
|
327
|
+
kind: z3.literal("sequence"),
|
|
328
|
+
next: sequenceNumberSchema
|
|
329
|
+
}),
|
|
330
|
+
z3.strictObject({
|
|
331
|
+
kind: z3.literal("attributes"),
|
|
332
|
+
attributes: attributesSchema
|
|
333
|
+
})
|
|
334
|
+
]);
|
|
335
|
+
var stateRecordSchema = z3.strictObject({
|
|
336
|
+
/** Incremented on each write; lets callers detect lost updates. */
|
|
337
|
+
revision: z3.number().int().min(0),
|
|
338
|
+
updatedAt: epochMillisSchema,
|
|
339
|
+
value: stateValueSchema
|
|
340
|
+
});
|
|
341
|
+
var logLevelSchema = z3.enum(["silent", "error", "warn", "info", "debug"]);
|
|
342
|
+
var LOG_LEVEL_RANK = Object.freeze({
|
|
343
|
+
silent: 0,
|
|
344
|
+
error: 1,
|
|
345
|
+
warn: 2,
|
|
346
|
+
info: 3,
|
|
347
|
+
debug: 4
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
// src/state/memory-store.ts
|
|
351
|
+
var createBoundedMemoryStateStore = (options) => {
|
|
352
|
+
const records = /* @__PURE__ */ new Map();
|
|
353
|
+
const keyLock = createAsyncLock();
|
|
354
|
+
const sessionLock = createAsyncLock();
|
|
355
|
+
const maxEntries = options.maxEntries ?? 1e4;
|
|
356
|
+
const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
|
|
357
|
+
const isExpired = (record, now) => options.ttlMillis !== void 0 && now - record.updatedAt > options.ttlMillis;
|
|
358
|
+
const evictOldestIfOverCapacity = () => {
|
|
359
|
+
while (records.size > maxEntries) {
|
|
360
|
+
let oldestKey;
|
|
361
|
+
let oldestAt = Number.POSITIVE_INFINITY;
|
|
362
|
+
for (const [key, record] of records) {
|
|
363
|
+
if (record.updatedAt < oldestAt) {
|
|
364
|
+
oldestAt = record.updatedAt;
|
|
365
|
+
oldestKey = key;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
if (oldestKey === void 0) {
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
records.delete(oldestKey);
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
return {
|
|
375
|
+
read: (key) => keyLock.run(key, () => {
|
|
376
|
+
const record = records.get(key);
|
|
377
|
+
if (record === void 0) {
|
|
378
|
+
return Promise.resolve(void 0);
|
|
379
|
+
}
|
|
380
|
+
if (isExpired(record, options.clock.now())) {
|
|
381
|
+
records.delete(key);
|
|
382
|
+
return Promise.resolve(void 0);
|
|
383
|
+
}
|
|
384
|
+
return Promise.resolve(record);
|
|
385
|
+
}),
|
|
386
|
+
write: (key, value) => keyLock.run(key, () => {
|
|
387
|
+
const previous = records.get(key);
|
|
388
|
+
const record = stateRecordSchema.parse({
|
|
389
|
+
revision: (previous?.revision ?? 0) + 1,
|
|
390
|
+
updatedAt: options.clock.now(),
|
|
391
|
+
value
|
|
392
|
+
});
|
|
393
|
+
records.set(key, record);
|
|
394
|
+
evictOldestIfOverCapacity();
|
|
395
|
+
return Promise.resolve(record);
|
|
396
|
+
}),
|
|
397
|
+
delete: (key) => keyLock.run(key, () => {
|
|
398
|
+
records.delete(key);
|
|
399
|
+
return Promise.resolve();
|
|
400
|
+
}),
|
|
401
|
+
keys: (prefix) => Promise.resolve([...records.keys()].filter((key) => key.startsWith(prefix)).sort()),
|
|
402
|
+
withSessionLock: (sessionId, fn, lockOptions) => sessionLock.run(sessionId, fn, lockOptions?.timeoutMillis ?? lockTimeoutMillis),
|
|
403
|
+
size: () => records.size,
|
|
404
|
+
pruneExpired: (now) => {
|
|
405
|
+
const cutoff = now ?? options.clock.now();
|
|
406
|
+
let removed = 0;
|
|
407
|
+
for (const [key, record] of records) {
|
|
408
|
+
if (isExpired(record, cutoff)) {
|
|
409
|
+
records.delete(key);
|
|
410
|
+
removed += 1;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return removed;
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
// src/state/filesystem-store.ts
|
|
419
|
+
import { randomBytes } from "crypto";
|
|
420
|
+
import { mkdir, open, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
|
|
421
|
+
import * as path from "path";
|
|
422
|
+
|
|
423
|
+
// src/state/keys.ts
|
|
424
|
+
import { createHash } from "crypto";
|
|
425
|
+
var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
426
|
+
var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
|
|
427
|
+
var sanitizeSegment = (segment) => {
|
|
428
|
+
if (isSafeSegment(segment)) {
|
|
429
|
+
return segment;
|
|
430
|
+
}
|
|
431
|
+
return `h_${createHash("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
|
|
432
|
+
};
|
|
433
|
+
var namespaceSegments = (namespace) => [
|
|
434
|
+
sanitizeSegment(namespace.providerId),
|
|
435
|
+
sanitizeSegment(namespace.installationId)
|
|
436
|
+
];
|
|
437
|
+
var keyDigest = (key) => createHash("sha256").update(key, "utf8").digest("hex");
|
|
438
|
+
|
|
439
|
+
// src/state/filesystem-store.ts
|
|
440
|
+
var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
|
|
441
|
+
var sleep = (millis) => new Promise((resolve) => {
|
|
442
|
+
const timer = setTimeout(resolve, millis);
|
|
443
|
+
timer.unref?.();
|
|
444
|
+
});
|
|
445
|
+
var wrapFsError = (thrown, operation) => {
|
|
446
|
+
if (thrown instanceof Error) {
|
|
447
|
+
return new Error(`filesystem state store ${operation} failed: ${thrown.name}`, { cause: thrown });
|
|
448
|
+
}
|
|
449
|
+
return new Error(`filesystem state store ${operation} failed`);
|
|
450
|
+
};
|
|
451
|
+
var createFilesystemStateStore = (options) => {
|
|
452
|
+
const [providerSegment, installationSegment] = namespaceSegments(options);
|
|
453
|
+
const baseDir = path.join(options.rootDir, providerSegment, installationSegment);
|
|
454
|
+
const recordsDir = path.join(baseDir, "records");
|
|
455
|
+
const quarantineDir = path.join(baseDir, "quarantine");
|
|
456
|
+
const locksDir = path.join(baseDir, "locks");
|
|
457
|
+
const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
|
|
458
|
+
const lockStaleMillis = options.lockStaleMillis ?? 3e4;
|
|
459
|
+
const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
|
|
460
|
+
const keyLock = createAsyncLock();
|
|
461
|
+
const sessionLock = createAsyncLock();
|
|
462
|
+
let dirsReady;
|
|
463
|
+
const ensureDirs = async () => {
|
|
464
|
+
if (dirsReady !== void 0) {
|
|
465
|
+
return dirsReady;
|
|
466
|
+
}
|
|
467
|
+
const promise = (async () => {
|
|
468
|
+
await mkdir(recordsDir, { recursive: true });
|
|
469
|
+
await mkdir(quarantineDir, { recursive: true });
|
|
470
|
+
await mkdir(locksDir, { recursive: true });
|
|
471
|
+
})();
|
|
472
|
+
dirsReady = promise;
|
|
473
|
+
try {
|
|
474
|
+
await promise;
|
|
475
|
+
} catch (thrown) {
|
|
476
|
+
dirsReady = void 0;
|
|
477
|
+
throw wrapFsError(thrown, "ensure-dirs");
|
|
478
|
+
}
|
|
479
|
+
};
|
|
480
|
+
const recordPath = (key) => path.join(recordsDir, `${keyDigest(key)}.json`);
|
|
481
|
+
const tempPath = (key) => path.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes(6).toString("hex")}.json`);
|
|
482
|
+
const lockPath = (sessionId) => path.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
|
|
483
|
+
const quarantine = async (filePath, key, reason) => {
|
|
484
|
+
const dest = path.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
|
|
485
|
+
try {
|
|
486
|
+
await rename(filePath, dest);
|
|
487
|
+
} catch {
|
|
488
|
+
await unlink(filePath).catch(() => void 0);
|
|
489
|
+
}
|
|
490
|
+
options.logger?.warn("filesystem state record quarantined", { "state.reason": reason });
|
|
491
|
+
};
|
|
492
|
+
const readUnlocked = async (key) => {
|
|
493
|
+
await ensureDirs();
|
|
494
|
+
const filePath = recordPath(key);
|
|
495
|
+
let raw;
|
|
496
|
+
try {
|
|
497
|
+
raw = await readFile(filePath, "utf8");
|
|
498
|
+
} catch (thrown) {
|
|
499
|
+
if (isErrnoException(thrown, "ENOENT")) {
|
|
500
|
+
return void 0;
|
|
501
|
+
}
|
|
502
|
+
throw wrapFsError(thrown, "read");
|
|
503
|
+
}
|
|
504
|
+
let parsedJson;
|
|
505
|
+
try {
|
|
506
|
+
parsedJson = JSON.parse(raw);
|
|
507
|
+
} catch {
|
|
508
|
+
await quarantine(filePath, key, "invalid-json");
|
|
509
|
+
return void 0;
|
|
510
|
+
}
|
|
511
|
+
const envelope = parsedJson;
|
|
512
|
+
if (envelope.key !== key) {
|
|
513
|
+
await quarantine(filePath, key, "key-mismatch");
|
|
514
|
+
return void 0;
|
|
515
|
+
}
|
|
516
|
+
const parsed = stateRecordSchema.safeParse(envelope.record);
|
|
517
|
+
if (!parsed.success) {
|
|
518
|
+
await quarantine(filePath, key, "schema-invalid");
|
|
519
|
+
return void 0;
|
|
520
|
+
}
|
|
521
|
+
return parsed.data;
|
|
522
|
+
};
|
|
523
|
+
const writeUnlocked = async (key, value) => {
|
|
524
|
+
await ensureDirs();
|
|
525
|
+
const previous = await readUnlocked(key);
|
|
526
|
+
const record = stateRecordSchema.parse({
|
|
527
|
+
revision: (previous?.revision ?? 0) + 1,
|
|
528
|
+
updatedAt: options.clock.now(),
|
|
529
|
+
value
|
|
530
|
+
});
|
|
531
|
+
const envelope = { key, record };
|
|
532
|
+
const tmp = tempPath(key);
|
|
533
|
+
try {
|
|
534
|
+
await writeFile(tmp, JSON.stringify(envelope), "utf8");
|
|
535
|
+
await rename(tmp, recordPath(key));
|
|
536
|
+
} catch (thrown) {
|
|
537
|
+
await unlink(tmp).catch(() => void 0);
|
|
538
|
+
throw wrapFsError(thrown, "write");
|
|
539
|
+
}
|
|
540
|
+
return record;
|
|
541
|
+
};
|
|
542
|
+
const acquireFileLock = async (sessionId, timeoutMillis) => {
|
|
543
|
+
await ensureDirs();
|
|
544
|
+
const filePath = lockPath(sessionId);
|
|
545
|
+
const startedAt = options.clock.monotonicMillis();
|
|
546
|
+
for (; ; ) {
|
|
547
|
+
try {
|
|
548
|
+
const handle = await open(filePath, "wx");
|
|
549
|
+
try {
|
|
550
|
+
await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
|
|
551
|
+
} finally {
|
|
552
|
+
await handle.close();
|
|
553
|
+
}
|
|
554
|
+
return async () => {
|
|
555
|
+
await unlink(filePath).catch(() => void 0);
|
|
556
|
+
};
|
|
557
|
+
} catch (thrown) {
|
|
558
|
+
if (!isErrnoException(thrown, "EEXIST")) {
|
|
559
|
+
throw wrapFsError(thrown, "lock");
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
const stale = await (async () => {
|
|
563
|
+
try {
|
|
564
|
+
const raw = await readFile(filePath, "utf8");
|
|
565
|
+
const parsed = JSON.parse(raw);
|
|
566
|
+
return typeof parsed.acquiredAt !== "number" || options.clock.now() - parsed.acquiredAt > lockStaleMillis;
|
|
567
|
+
} catch {
|
|
568
|
+
return true;
|
|
569
|
+
}
|
|
570
|
+
})();
|
|
571
|
+
if (stale) {
|
|
572
|
+
await unlink(filePath).catch(() => void 0);
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {
|
|
576
|
+
throw new StateLockTimeoutError(sessionId, timeoutMillis);
|
|
577
|
+
}
|
|
578
|
+
await sleep(lockPollIntervalMillis);
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
return {
|
|
582
|
+
recordsDir,
|
|
583
|
+
quarantineDir,
|
|
584
|
+
read: (key) => keyLock.run(key, () => readUnlocked(key), lockTimeoutMillis),
|
|
585
|
+
write: (key, value) => keyLock.run(key, () => writeUnlocked(key, value), lockTimeoutMillis),
|
|
586
|
+
delete: (key) => keyLock.run(
|
|
587
|
+
key,
|
|
588
|
+
async () => {
|
|
589
|
+
await ensureDirs();
|
|
590
|
+
await unlink(recordPath(key)).catch((thrown) => {
|
|
591
|
+
if (!isErrnoException(thrown, "ENOENT")) {
|
|
592
|
+
throw wrapFsError(thrown, "delete");
|
|
593
|
+
}
|
|
594
|
+
});
|
|
595
|
+
},
|
|
596
|
+
lockTimeoutMillis
|
|
597
|
+
),
|
|
598
|
+
keys: async (prefix) => {
|
|
599
|
+
await ensureDirs();
|
|
600
|
+
let entries;
|
|
601
|
+
try {
|
|
602
|
+
entries = await readdir(recordsDir);
|
|
603
|
+
} catch (thrown) {
|
|
604
|
+
if (isErrnoException(thrown, "ENOENT")) {
|
|
605
|
+
return [];
|
|
606
|
+
}
|
|
607
|
+
throw wrapFsError(thrown, "keys");
|
|
608
|
+
}
|
|
609
|
+
const found = [];
|
|
610
|
+
for (const entry of entries) {
|
|
611
|
+
if (!entry.endsWith(".json") || entry.startsWith(".tmp-")) {
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
let raw;
|
|
615
|
+
try {
|
|
616
|
+
raw = await readFile(path.join(recordsDir, entry), "utf8");
|
|
617
|
+
} catch {
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
try {
|
|
621
|
+
const envelope = JSON.parse(raw);
|
|
622
|
+
if (typeof envelope.key === "string" && envelope.key.startsWith(prefix)) {
|
|
623
|
+
found.push(envelope.key);
|
|
624
|
+
}
|
|
625
|
+
} catch {
|
|
626
|
+
continue;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
return found.sort();
|
|
630
|
+
},
|
|
631
|
+
withSessionLock: async (sessionId, fn, lockOptions) => {
|
|
632
|
+
const timeoutMillis = lockOptions?.timeoutMillis ?? lockTimeoutMillis;
|
|
633
|
+
return sessionLock.run(
|
|
634
|
+
sessionId,
|
|
635
|
+
async () => {
|
|
636
|
+
const release = await acquireFileLock(sessionId, timeoutMillis);
|
|
637
|
+
try {
|
|
638
|
+
return await fn();
|
|
639
|
+
} finally {
|
|
640
|
+
await release();
|
|
641
|
+
}
|
|
642
|
+
},
|
|
643
|
+
timeoutMillis
|
|
644
|
+
);
|
|
645
|
+
},
|
|
646
|
+
pruneStale: async (maxAgeMillis, pruneOptions) => {
|
|
647
|
+
await ensureDirs();
|
|
648
|
+
const cap = pruneOptions?.maxEntries ?? 5e3;
|
|
649
|
+
const now = options.clock.now();
|
|
650
|
+
let removed = 0;
|
|
651
|
+
let scanned = 0;
|
|
652
|
+
let entries;
|
|
653
|
+
try {
|
|
654
|
+
entries = await readdir(recordsDir);
|
|
655
|
+
} catch (thrown) {
|
|
656
|
+
if (!isErrnoException(thrown, "ENOENT")) {
|
|
657
|
+
throw wrapFsError(thrown, "prune");
|
|
658
|
+
}
|
|
659
|
+
entries = [];
|
|
660
|
+
}
|
|
661
|
+
for (const entry of entries) {
|
|
662
|
+
if (scanned >= cap) {
|
|
663
|
+
break;
|
|
664
|
+
}
|
|
665
|
+
if (!entry.endsWith(".json") || entry.startsWith(".tmp-")) {
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
scanned += 1;
|
|
669
|
+
const filePath = path.join(recordsDir, entry);
|
|
670
|
+
try {
|
|
671
|
+
const raw = await readFile(filePath, "utf8");
|
|
672
|
+
const envelope = JSON.parse(raw);
|
|
673
|
+
const updatedAt = envelope.record?.updatedAt;
|
|
674
|
+
if (typeof updatedAt === "number" && now - updatedAt > maxAgeMillis) {
|
|
675
|
+
await unlink(filePath).catch(() => void 0);
|
|
676
|
+
removed += 1;
|
|
677
|
+
}
|
|
678
|
+
} catch {
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
let lockEntries;
|
|
683
|
+
try {
|
|
684
|
+
lockEntries = await readdir(locksDir);
|
|
685
|
+
} catch {
|
|
686
|
+
lockEntries = [];
|
|
687
|
+
}
|
|
688
|
+
for (const entry of lockEntries) {
|
|
689
|
+
const filePath = path.join(locksDir, entry);
|
|
690
|
+
try {
|
|
691
|
+
const raw = await readFile(filePath, "utf8");
|
|
692
|
+
const parsed = JSON.parse(raw);
|
|
693
|
+
if (typeof parsed.acquiredAt === "number" && now - parsed.acquiredAt > lockStaleMillis) {
|
|
694
|
+
await unlink(filePath).catch(() => void 0);
|
|
695
|
+
}
|
|
696
|
+
} catch {
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
return { removed, scanned };
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
};
|
|
704
|
+
export {
|
|
705
|
+
createBoundedMemoryStateStore,
|
|
706
|
+
createFilesystemStateStore,
|
|
707
|
+
isLockingStateStore,
|
|
708
|
+
withOptionalSessionLock
|
|
709
|
+
};
|
|
710
|
+
//# sourceMappingURL=state.js.map
|