@osfactory/otel-hook 0.13.0 → 0.13.2
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/README.md +51 -3
- package/dist/cli.js +907 -164
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +5 -3
- package/dist/config.js +39 -5
- package/dist/config.js.map +1 -1
- package/dist/{destinations-DvqsPulb.d.ts → destinations-C4sSKjDO.d.ts} +1 -1
- package/dist/{export-destinations-Bey2djRk.d.ts → export-destinations-BjRXDots.d.ts} +37 -5
- package/dist/{hook-D5imE0Qc.d.ts → hook-CKLpgrYP.d.ts} +2 -2
- package/dist/index.d.ts +9 -9
- package/dist/index.js +921 -182
- package/dist/index.js.map +1 -1
- package/dist/install.d.ts +1 -1
- package/dist/install.js +5 -1
- package/dist/install.js.map +1 -1
- package/dist/integration.d.ts +15 -8
- package/dist/integration.js +998 -160
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.d.ts +8 -1
- package/dist/lifecycle.js +10 -3
- package/dist/lifecycle.js.map +1 -1
- package/dist/{metric-model-CFIeUwqd.d.ts → metric-model-B4lIuk6i.d.ts} +8 -0
- package/dist/{payload-CdDKeRpH.d.ts → payload-DLK7QaBB.d.ts} +17 -1
- package/dist/providers.d.ts +91 -6
- package/dist/providers.js +311 -4
- package/dist/providers.js.map +1 -1
- package/dist/{registry-BKQhhIO3.d.ts → registry-DM-4YvIA.d.ts} +1 -1
- package/dist/runtime.d.ts +3 -3
- package/dist/runtime.js +23 -3
- package/dist/runtime.js.map +1 -1
- package/dist/{schema-SpFM6YQY.d.ts → schema-CD61uW99.d.ts} +32 -3
- package/dist/state.js +20 -6
- package/dist/state.js.map +1 -1
- package/dist/telemetry.d.ts +4 -4
- package/dist/telemetry.js +865 -472
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +61 -21
- package/dist/testing.js.map +1 -1
- package/package.json +2 -1
package/dist/integration.js
CHANGED
|
@@ -476,8 +476,26 @@ var exporterPolicySchema = z5.strictObject({
|
|
|
476
476
|
* Per-destination retry spool bounds, each optional and merged per leaf; any
|
|
477
477
|
* bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
|
|
478
478
|
*/
|
|
479
|
-
spool: spoolPolicySchema.partial().optional()
|
|
479
|
+
spool: spoolPolicySchema.partial().optional(),
|
|
480
|
+
/**
|
|
481
|
+
* The most time one hook invocation spends trying to reach one endpoint, in
|
|
482
|
+
* milliseconds: caps `timeoutMillis` for every OTLP request (connection setup
|
|
483
|
+
* included) and the exporter's own retries inside it. A batch that does not
|
|
484
|
+
* get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:
|
|
485
|
+
* the host agent waits for its hooks, so a down collector must not stall it.
|
|
486
|
+
*/
|
|
487
|
+
exportBudgetMillis: z5.number().int().min(50).max(6e5).optional(),
|
|
488
|
+
/**
|
|
489
|
+
* After an endpoint was unreachable (refused, timed out, or answered a
|
|
490
|
+
* retryable status), every hook spools for it without trying for this long,
|
|
491
|
+
* in milliseconds; then one hook probes it again. 0 disables the window.
|
|
492
|
+
* Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.
|
|
493
|
+
*/
|
|
494
|
+
endpointDownMillis: z5.number().int().min(0).max(36e5).optional()
|
|
480
495
|
});
|
|
496
|
+
var DEFAULT_EXPORT_BUDGET_MILLIS = 1500;
|
|
497
|
+
var DEFAULT_ENDPOINT_DOWN_MILLIS = 3e4;
|
|
498
|
+
var effectiveExportTimeoutMillis = (exporter) => Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);
|
|
481
499
|
var detectionPolicySchema = z5.strictObject({
|
|
482
500
|
/** Detections below this confidence resolve to the unknown provider. */
|
|
483
501
|
minimumConfidence: detectionConfidenceSchema,
|
|
@@ -494,6 +512,9 @@ var diagnosticsPolicySchema = z5.strictObject({
|
|
|
494
512
|
var providersPolicySchema = z5.strictObject({
|
|
495
513
|
claudeCode: z5.strictObject({
|
|
496
514
|
readTranscriptUsage: z5.boolean()
|
|
515
|
+
}).optional(),
|
|
516
|
+
codex: z5.strictObject({
|
|
517
|
+
readRolloutUsage: z5.boolean()
|
|
497
518
|
}).optional()
|
|
498
519
|
});
|
|
499
520
|
var sessionContextPolicySchema = z5.strictObject({
|
|
@@ -523,7 +544,8 @@ var otelHookConfigPatchSchema = z5.strictObject({
|
|
|
523
544
|
detection: detectionPolicySchema.partial().optional(),
|
|
524
545
|
diagnostics: diagnosticsPolicySchema.partial().optional(),
|
|
525
546
|
providers: z5.strictObject({
|
|
526
|
-
claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional()
|
|
547
|
+
claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional(),
|
|
548
|
+
codex: z5.strictObject({ readRolloutUsage: z5.boolean() }).partial().optional()
|
|
527
549
|
}).partial().optional(),
|
|
528
550
|
sessionContext: sessionContextPolicySchema.partial().optional()
|
|
529
551
|
});
|
|
@@ -550,7 +572,8 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
|
|
|
550
572
|
emitErrorEvents: true
|
|
551
573
|
});
|
|
552
574
|
var DEFAULT_PROVIDERS_POLICY = Object.freeze({
|
|
553
|
-
claudeCode: Object.freeze({ readTranscriptUsage: false })
|
|
575
|
+
claudeCode: Object.freeze({ readTranscriptUsage: false }),
|
|
576
|
+
codex: Object.freeze({ readRolloutUsage: false })
|
|
554
577
|
});
|
|
555
578
|
var DEFAULT_CONFIG = Object.freeze({
|
|
556
579
|
exporter: DEFAULT_EXPORTER_POLICY,
|
|
@@ -560,6 +583,7 @@ var DEFAULT_CONFIG = Object.freeze({
|
|
|
560
583
|
providers: DEFAULT_PROVIDERS_POLICY
|
|
561
584
|
});
|
|
562
585
|
var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
|
|
586
|
+
var readsCodexRolloutUsage = (config) => config.providers?.codex?.readRolloutUsage === true;
|
|
563
587
|
var sessionContextDir = (config) => config.sessionContext?.dir;
|
|
564
588
|
var effectiveMetricsPolicy = (exporter) => ({
|
|
565
589
|
...DEFAULT_METRICS_POLICY,
|
|
@@ -2419,7 +2443,7 @@ import {
|
|
|
2419
2443
|
} from "@opentelemetry/semantic-conventions/incubating";
|
|
2420
2444
|
|
|
2421
2445
|
// src/version.ts
|
|
2422
|
-
var VERSION = "0.13.
|
|
2446
|
+
var VERSION = "0.13.2";
|
|
2423
2447
|
|
|
2424
2448
|
// src/telemetry/semconv.ts
|
|
2425
2449
|
var SCOPE_NAME = "@osfactory/otel-hook";
|
|
@@ -2655,7 +2679,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
|
|
|
2655
2679
|
const resolved = resolvePairing(group, anchor, correlation);
|
|
2656
2680
|
const traceId = plan.traceId;
|
|
2657
2681
|
const spanId = plan.spanId;
|
|
2658
|
-
const
|
|
2682
|
+
const parentRef = resolved.parent ?? resumedSessionParent(group.ref, correlation);
|
|
2683
|
+
const parentSpanId = parentRef === void 0 ? void 0 : deriveSpanId(providerId, sessionId, parentRef);
|
|
2659
2684
|
let name = group.ref.family;
|
|
2660
2685
|
let kind = SpanKind.INTERNAL;
|
|
2661
2686
|
let status = { code: SpanStatusCode.UNSET };
|
|
@@ -2879,7 +2904,7 @@ var planGroup = (group, correlation, correlationAvailable) => {
|
|
|
2879
2904
|
// persist something that should have been persisted.
|
|
2880
2905
|
correlation === void 0 && correlationAvailable === void 0);
|
|
2881
2906
|
const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
|
|
2882
|
-
const discriminator = durablyRecorded ?
|
|
2907
|
+
const discriminator = durablyRecorded ? runDiscriminatorOf(correlation) : effective?.spanIdDiscriminator ?? runDiscriminatorOf(effective);
|
|
2883
2908
|
return {
|
|
2884
2909
|
group,
|
|
2885
2910
|
anchor,
|
|
@@ -2899,6 +2924,8 @@ var planGroup = (group, correlation, correlationAvailable) => {
|
|
|
2899
2924
|
)
|
|
2900
2925
|
};
|
|
2901
2926
|
};
|
|
2927
|
+
var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
|
|
2928
|
+
var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
|
|
2902
2929
|
var canonicalEventTraceIdentities = (events, options = {}) => {
|
|
2903
2930
|
const layout = layoutBatch(events);
|
|
2904
2931
|
const correlations = indexCorrelations(options.correlations);
|
|
@@ -2923,7 +2950,7 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
|
|
|
2923
2950
|
});
|
|
2924
2951
|
continue;
|
|
2925
2952
|
}
|
|
2926
|
-
const parent = plan.correlation?.parent ?? parentScopeRefOf(event2);
|
|
2953
|
+
const parent = plan.correlation?.parent ?? parentScopeRefOf(event2) ?? resumedSessionParent(plan.group.ref, plan.correlation);
|
|
2927
2954
|
identities.set(event2.eventId, {
|
|
2928
2955
|
traceId: plan.traceId,
|
|
2929
2956
|
spanId: plan.spanId,
|
|
@@ -3006,6 +3033,7 @@ var encodeRecord = (record) => ({
|
|
|
3006
3033
|
...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
|
|
3007
3034
|
...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
|
|
3008
3035
|
...record.exported === true ? { exported: true } : {},
|
|
3036
|
+
...record.runKey === void 0 ? {} : { runKey: record.runKey },
|
|
3009
3037
|
...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
|
|
3010
3038
|
...encodeAttributes(record.attributes)
|
|
3011
3039
|
}
|
|
@@ -3029,6 +3057,7 @@ var decodeRecord = (attributes) => {
|
|
|
3029
3057
|
return { kind: "corrupt" };
|
|
3030
3058
|
}
|
|
3031
3059
|
const exported = attributes["exported"] === true;
|
|
3060
|
+
const runKey = optionalString(attributes["runKey"]);
|
|
3032
3061
|
const parentFamily = attributes["parentFamily"];
|
|
3033
3062
|
const parentScopeKey = optionalString(attributes["parentScopeKey"]);
|
|
3034
3063
|
const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
|
|
@@ -3043,6 +3072,7 @@ var decodeRecord = (attributes) => {
|
|
|
3043
3072
|
...endedAt === void 0 ? {} : { endedAt },
|
|
3044
3073
|
...parent === void 0 ? {} : { parent },
|
|
3045
3074
|
...exported ? { exported: true } : {},
|
|
3075
|
+
...runKey === void 0 ? {} : { runKey },
|
|
3046
3076
|
...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
|
|
3047
3077
|
}
|
|
3048
3078
|
};
|
|
@@ -3051,13 +3081,15 @@ var factsOf = (record) => ({
|
|
|
3051
3081
|
...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
|
|
3052
3082
|
...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
|
|
3053
3083
|
...record.parent === void 0 ? {} : { parent: record.parent },
|
|
3054
|
-
...record.attributes === void 0 ? {} : { attributes: record.attributes }
|
|
3084
|
+
...record.attributes === void 0 ? {} : { attributes: record.attributes },
|
|
3085
|
+
...record.runKey === void 0 ? {} : { runKey: record.runKey }
|
|
3055
3086
|
});
|
|
3056
3087
|
var correlationTimesOf = (facts, options = { withStart: true }) => ({
|
|
3057
3088
|
...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
|
|
3058
3089
|
...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
|
|
3059
3090
|
...facts.parent === void 0 ? {} : { parent: facts.parent },
|
|
3060
|
-
...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
|
|
3091
|
+
...facts.attributes === void 0 ? {} : { attributes: facts.attributes },
|
|
3092
|
+
...facts.runKey === void 0 ? {} : { runSpanIdDiscriminator: facts.runKey }
|
|
3061
3093
|
});
|
|
3062
3094
|
var orphanClassificationOf = (reason) => {
|
|
3063
3095
|
switch (reason) {
|
|
@@ -3117,10 +3149,12 @@ var createSpanCorrelator = (deps) => {
|
|
|
3117
3149
|
return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
|
|
3118
3150
|
}
|
|
3119
3151
|
}
|
|
3152
|
+
const previouslyExported = decoded.kind === "present" && decoded.record.exported === true;
|
|
3120
3153
|
const fresh = {
|
|
3121
3154
|
providerId: input.providerId,
|
|
3122
3155
|
startEventId: input.eventId,
|
|
3123
3156
|
startedAt: input.occurredAt,
|
|
3157
|
+
...previouslyExported ? { runKey: input.eventId } : {},
|
|
3124
3158
|
...input.parent === void 0 ? {} : { parent: input.parent },
|
|
3125
3159
|
...input.attributes === void 0 ? {} : { attributes: input.attributes }
|
|
3126
3160
|
};
|
|
@@ -3676,11 +3710,11 @@ var createPrivacyService = (policyInput) => {
|
|
|
3676
3710
|
};
|
|
3677
3711
|
const flattenToAttributes = (value, prefix) => {
|
|
3678
3712
|
const attributes = {};
|
|
3679
|
-
const walk = (current,
|
|
3713
|
+
const walk = (current, path9) => {
|
|
3680
3714
|
if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
|
|
3681
3715
|
const primitive = toAttributePrimitive(current);
|
|
3682
3716
|
if (primitive !== void 0) {
|
|
3683
|
-
attributes[
|
|
3717
|
+
attributes[path9] = primitive;
|
|
3684
3718
|
}
|
|
3685
3719
|
return;
|
|
3686
3720
|
}
|
|
@@ -3699,16 +3733,16 @@ var createPrivacyService = (policyInput) => {
|
|
|
3699
3733
|
primitives.push(entryPrimitive);
|
|
3700
3734
|
}
|
|
3701
3735
|
if (uniform) {
|
|
3702
|
-
attributes[
|
|
3736
|
+
attributes[path9] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
|
|
3703
3737
|
return;
|
|
3704
3738
|
}
|
|
3705
3739
|
for (const [index, entry] of current.entries()) {
|
|
3706
|
-
walk(entry, `${
|
|
3740
|
+
walk(entry, `${path9}.${index}`);
|
|
3707
3741
|
}
|
|
3708
3742
|
return;
|
|
3709
3743
|
}
|
|
3710
3744
|
for (const [key, entry] of Object.entries(current)) {
|
|
3711
|
-
walk(entry,
|
|
3745
|
+
walk(entry, path9 === "" ? key : `${path9}.${key}`);
|
|
3712
3746
|
}
|
|
3713
3747
|
};
|
|
3714
3748
|
walk(value, prefix);
|
|
@@ -4027,7 +4061,10 @@ var postToolUseFailurePayloadSchema = z16.object({
|
|
|
4027
4061
|
hook_event_name: z16.literal("PostToolUseFailure"),
|
|
4028
4062
|
tool_name: z16.string().min(1),
|
|
4029
4063
|
tool_input: z16.unknown().optional(),
|
|
4030
|
-
|
|
4064
|
+
// Optional: a failure that names no message still ends its tool call. The
|
|
4065
|
+
// `error` spelling Claude Code 2.1.x sends is folded onto it by
|
|
4066
|
+
// `normalizeClaudeHookPayload`.
|
|
4067
|
+
tool_error: z16.unknown().optional(),
|
|
4031
4068
|
tool_use_id: z16.string().min(1)
|
|
4032
4069
|
});
|
|
4033
4070
|
var permissionRequestPayloadSchema = z16.object({
|
|
@@ -4603,6 +4640,419 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
|
|
|
4603
4640
|
});
|
|
4604
4641
|
};
|
|
4605
4642
|
|
|
4643
|
+
// src/providers/codex/rollout-usage.ts
|
|
4644
|
+
import { createHash as createHash5 } from "crypto";
|
|
4645
|
+
import { open as open2, readdir, stat as stat2 } from "fs/promises";
|
|
4646
|
+
import path2 from "path";
|
|
4647
|
+
|
|
4648
|
+
// src/providers/codex/version.ts
|
|
4649
|
+
var CODEX_PROVIDER_ID = providerIdSchema.parse("codex");
|
|
4650
|
+
|
|
4651
|
+
// src/providers/codex/payload.ts
|
|
4652
|
+
import { z as z17 } from "zod";
|
|
4653
|
+
var permissionModeSchema = z17.enum([
|
|
4654
|
+
"default",
|
|
4655
|
+
"acceptEdits",
|
|
4656
|
+
"plan",
|
|
4657
|
+
"dontAsk",
|
|
4658
|
+
"bypassPermissions"
|
|
4659
|
+
]);
|
|
4660
|
+
var codexUsageSchema = z17.object({
|
|
4661
|
+
input_tokens: z17.number().int().min(0).optional(),
|
|
4662
|
+
cached_input_tokens: z17.number().int().min(0).optional(),
|
|
4663
|
+
cache_write_input_tokens: z17.number().int().min(0).optional(),
|
|
4664
|
+
output_tokens: z17.number().int().min(0).optional(),
|
|
4665
|
+
reasoning_output_tokens: z17.number().int().min(0).optional(),
|
|
4666
|
+
total_tokens: z17.number().int().min(0).optional()
|
|
4667
|
+
});
|
|
4668
|
+
var baseFields = {
|
|
4669
|
+
session_id: z17.string().min(1).max(256),
|
|
4670
|
+
cwd: z17.string().min(1).max(4096).optional(),
|
|
4671
|
+
model: z17.string().min(1).max(256).optional(),
|
|
4672
|
+
permission_mode: permissionModeSchema.optional(),
|
|
4673
|
+
transcript_path: z17.string().min(1).max(4096).optional(),
|
|
4674
|
+
codex_version: z17.string().min(1).max(64).optional(),
|
|
4675
|
+
/** Not part of the documented protocol; lets tests and replay stay deterministic. */
|
|
4676
|
+
occurred_at: z17.number().int().min(0).optional()
|
|
4677
|
+
};
|
|
4678
|
+
var codexSessionStartPayloadSchema = z17.object({
|
|
4679
|
+
...baseFields,
|
|
4680
|
+
hook_event_name: z17.literal("SessionStart"),
|
|
4681
|
+
source: z17.enum(["startup", "resume", "clear", "compact"]).optional()
|
|
4682
|
+
});
|
|
4683
|
+
var codexUserPromptSubmitPayloadSchema = z17.object({
|
|
4684
|
+
...baseFields,
|
|
4685
|
+
hook_event_name: z17.literal("UserPromptSubmit"),
|
|
4686
|
+
turn_id: z17.string().min(1).max(256).optional(),
|
|
4687
|
+
prompt: z17.string().max(1e6).optional()
|
|
4688
|
+
});
|
|
4689
|
+
var codexPreToolUsePayloadSchema = z17.object({
|
|
4690
|
+
...baseFields,
|
|
4691
|
+
hook_event_name: z17.literal("PreToolUse"),
|
|
4692
|
+
turn_id: z17.string().min(1).max(256).optional(),
|
|
4693
|
+
tool_name: z17.string().min(1).max(256),
|
|
4694
|
+
tool_call_id: z17.string().min(1).max(256).optional(),
|
|
4695
|
+
tool_input: z17.unknown().optional()
|
|
4696
|
+
});
|
|
4697
|
+
var codexPermissionRequestPayloadSchema = z17.object({
|
|
4698
|
+
...baseFields,
|
|
4699
|
+
hook_event_name: z17.literal("PermissionRequest"),
|
|
4700
|
+
turn_id: z17.string().min(1).max(256).optional(),
|
|
4701
|
+
tool_name: z17.string().min(1).max(256).optional(),
|
|
4702
|
+
tool_call_id: z17.string().min(1).max(256).optional(),
|
|
4703
|
+
tool_input: z17.unknown().optional()
|
|
4704
|
+
});
|
|
4705
|
+
var codexPostToolUsePayloadSchema = z17.object({
|
|
4706
|
+
...baseFields,
|
|
4707
|
+
hook_event_name: z17.literal("PostToolUse"),
|
|
4708
|
+
turn_id: z17.string().min(1).max(256).optional(),
|
|
4709
|
+
tool_name: z17.string().min(1).max(256),
|
|
4710
|
+
tool_call_id: z17.string().min(1).max(256).optional(),
|
|
4711
|
+
tool_input: z17.unknown().optional(),
|
|
4712
|
+
tool_response: z17.unknown().optional(),
|
|
4713
|
+
permission_decision: z17.enum(["allowed", "denied", "deferred"]).optional(),
|
|
4714
|
+
duration_ms: z17.number().min(0).optional()
|
|
4715
|
+
});
|
|
4716
|
+
var codexPreCompactPayloadSchema = z17.object({
|
|
4717
|
+
...baseFields,
|
|
4718
|
+
hook_event_name: z17.literal("PreCompact"),
|
|
4719
|
+
trigger: z17.enum(["auto", "manual"]).optional(),
|
|
4720
|
+
context_tokens_before: z17.number().int().min(0).optional()
|
|
4721
|
+
});
|
|
4722
|
+
var codexPostCompactPayloadSchema = z17.object({
|
|
4723
|
+
...baseFields,
|
|
4724
|
+
hook_event_name: z17.literal("PostCompact"),
|
|
4725
|
+
trigger: z17.enum(["auto", "manual"]).optional(),
|
|
4726
|
+
context_tokens_after: z17.number().int().min(0).optional(),
|
|
4727
|
+
dropped_message_count: z17.number().int().min(0).optional(),
|
|
4728
|
+
usage: codexUsageSchema.optional()
|
|
4729
|
+
});
|
|
4730
|
+
var codexSubagentStartPayloadSchema = z17.object({
|
|
4731
|
+
...baseFields,
|
|
4732
|
+
hook_event_name: z17.literal("SubagentStart"),
|
|
4733
|
+
turn_id: z17.string().min(1).max(256).optional(),
|
|
4734
|
+
subagent_id: z17.string().min(1).max(256),
|
|
4735
|
+
subagent_type: z17.string().min(1).max(256).optional()
|
|
4736
|
+
});
|
|
4737
|
+
var codexSubagentStopPayloadSchema = z17.object({
|
|
4738
|
+
...baseFields,
|
|
4739
|
+
hook_event_name: z17.literal("SubagentStop"),
|
|
4740
|
+
turn_id: z17.string().min(1).max(256).optional(),
|
|
4741
|
+
subagent_id: z17.string().min(1).max(256),
|
|
4742
|
+
status: z17.enum(["completed", "failed", "cancelled"]).optional(),
|
|
4743
|
+
usage: codexUsageSchema.optional()
|
|
4744
|
+
});
|
|
4745
|
+
var codexStopPayloadSchema = z17.object({
|
|
4746
|
+
...baseFields,
|
|
4747
|
+
hook_event_name: z17.literal("Stop"),
|
|
4748
|
+
turn_id: z17.string().min(1).max(256).optional(),
|
|
4749
|
+
stop_reason: z17.string().min(1).max(256).optional(),
|
|
4750
|
+
usage: codexUsageSchema.optional(),
|
|
4751
|
+
duration_ms: z17.number().min(0).optional()
|
|
4752
|
+
});
|
|
4753
|
+
var CODEX_HOOK_EVENT_NAMES = [
|
|
4754
|
+
"SessionStart",
|
|
4755
|
+
"UserPromptSubmit",
|
|
4756
|
+
"PreToolUse",
|
|
4757
|
+
"PermissionRequest",
|
|
4758
|
+
"PostToolUse",
|
|
4759
|
+
"PreCompact",
|
|
4760
|
+
"PostCompact",
|
|
4761
|
+
"SubagentStart",
|
|
4762
|
+
"SubagentStop",
|
|
4763
|
+
"Stop"
|
|
4764
|
+
];
|
|
4765
|
+
var codexHookPayloadSchema = z17.discriminatedUnion("hook_event_name", [
|
|
4766
|
+
codexSessionStartPayloadSchema,
|
|
4767
|
+
codexUserPromptSubmitPayloadSchema,
|
|
4768
|
+
codexPreToolUsePayloadSchema,
|
|
4769
|
+
codexPermissionRequestPayloadSchema,
|
|
4770
|
+
codexPostToolUsePayloadSchema,
|
|
4771
|
+
codexPreCompactPayloadSchema,
|
|
4772
|
+
codexPostCompactPayloadSchema,
|
|
4773
|
+
codexSubagentStartPayloadSchema,
|
|
4774
|
+
codexSubagentStopPayloadSchema,
|
|
4775
|
+
codexStopPayloadSchema
|
|
4776
|
+
]);
|
|
4777
|
+
var codexHookEnvelopeSchema = z17.object({
|
|
4778
|
+
session_id: z17.string().min(1),
|
|
4779
|
+
hook_event_name: z17.enum(CODEX_HOOK_EVENT_NAMES)
|
|
4780
|
+
});
|
|
4781
|
+
|
|
4782
|
+
// src/providers/codex/rollout-usage.ts
|
|
4783
|
+
var CODEX_ROLLOUT_USAGE_ENRICHER_ID = "codex-rollout-usage";
|
|
4784
|
+
var DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8388608;
|
|
4785
|
+
var DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1048576;
|
|
4786
|
+
var DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;
|
|
4787
|
+
var DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;
|
|
4788
|
+
var ROLLOUT_LOOKUP_DAYS = 7;
|
|
4789
|
+
var MIN_BYTES = 65536;
|
|
4790
|
+
var MAX_RANGE_BYTES2 = 67108864;
|
|
4791
|
+
var MAX_TAIL_BYTES2 = 16777216;
|
|
4792
|
+
var MIN_TIMEOUT_MILLIS2 = 10;
|
|
4793
|
+
var MAX_TIMEOUT_MILLIS2 = 5e3;
|
|
4794
|
+
var MAX_SETTLE_MILLIS = 1e3;
|
|
4795
|
+
var MAX_MODEL_ID_LENGTH2 = 256;
|
|
4796
|
+
var MAX_LOOKUP_DIR_ENTRIES = 2e4;
|
|
4797
|
+
var SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
|
|
4798
|
+
var clamp2 = (value, fallback, min, max) => {
|
|
4799
|
+
if (value === void 0 || !Number.isFinite(value)) {
|
|
4800
|
+
return fallback;
|
|
4801
|
+
}
|
|
4802
|
+
return Math.min(max, Math.max(min, Math.floor(value)));
|
|
4803
|
+
};
|
|
4804
|
+
var asRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
4805
|
+
var isRolloutPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !value.includes("\0") && path2.isAbsolute(value) && path2.extname(value) === ".jsonl";
|
|
4806
|
+
var sourceDigest2 = (rolloutPath) => createHash5("sha256").update(rolloutPath, "utf8").digest("hex").slice(0, 32);
|
|
4807
|
+
var parseUsage = (value) => {
|
|
4808
|
+
const parsed = codexUsageSchema.safeParse(value);
|
|
4809
|
+
if (!parsed.success) {
|
|
4810
|
+
return void 0;
|
|
4811
|
+
}
|
|
4812
|
+
const usage = parsed.data;
|
|
4813
|
+
return usage.input_tokens === void 0 || usage.output_tokens === void 0 ? void 0 : usage;
|
|
4814
|
+
};
|
|
4815
|
+
var modelOf = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_MODEL_ID_LENGTH2 ? value : void 0;
|
|
4816
|
+
var factsOf2 = (line) => {
|
|
4817
|
+
const usageLine = line.includes('"token_count"') || line.includes('"token_usage_record"');
|
|
4818
|
+
const contextLine = line.includes('"turn_context"');
|
|
4819
|
+
if (!usageLine && !contextLine) {
|
|
4820
|
+
return void 0;
|
|
4821
|
+
}
|
|
4822
|
+
let parsed;
|
|
4823
|
+
try {
|
|
4824
|
+
parsed = JSON.parse(line);
|
|
4825
|
+
} catch {
|
|
4826
|
+
return void 0;
|
|
4827
|
+
}
|
|
4828
|
+
const record = asRecord3(parsed);
|
|
4829
|
+
const payload = asRecord3(record?.payload);
|
|
4830
|
+
if (record === void 0 || payload === void 0) {
|
|
4831
|
+
return void 0;
|
|
4832
|
+
}
|
|
4833
|
+
if (record.type === "turn_context") {
|
|
4834
|
+
const model = modelOf(payload.model);
|
|
4835
|
+
return model === void 0 ? void 0 : { model };
|
|
4836
|
+
}
|
|
4837
|
+
if (record.type === "event_msg" && payload.type === "token_count") {
|
|
4838
|
+
const info = asRecord3(payload.info) ?? payload;
|
|
4839
|
+
const usage = parseUsage(info.total_token_usage);
|
|
4840
|
+
return usage === void 0 ? void 0 : { usage };
|
|
4841
|
+
}
|
|
4842
|
+
if (record.type === "token_usage_record") {
|
|
4843
|
+
const usage = parseUsage(payload.thread_token_usage);
|
|
4844
|
+
return usage === void 0 ? void 0 : { usage };
|
|
4845
|
+
}
|
|
4846
|
+
return void 0;
|
|
4847
|
+
};
|
|
4848
|
+
var lastSnapshotIn = (lines) => {
|
|
4849
|
+
let usage;
|
|
4850
|
+
let model;
|
|
4851
|
+
for (const line of lines) {
|
|
4852
|
+
const facts = factsOf2(line.trim());
|
|
4853
|
+
if (facts === void 0) {
|
|
4854
|
+
continue;
|
|
4855
|
+
}
|
|
4856
|
+
if (facts.model !== void 0) {
|
|
4857
|
+
model = facts.model;
|
|
4858
|
+
}
|
|
4859
|
+
if (facts.usage !== void 0) {
|
|
4860
|
+
usage = facts.usage;
|
|
4861
|
+
}
|
|
4862
|
+
}
|
|
4863
|
+
return usage === void 0 ? void 0 : { usage, ...model === void 0 ? {} : { model } };
|
|
4864
|
+
};
|
|
4865
|
+
var readBytes2 = async (handle, start, length) => {
|
|
4866
|
+
const buffer = Buffer.alloc(length);
|
|
4867
|
+
let filled = 0;
|
|
4868
|
+
while (filled < length) {
|
|
4869
|
+
const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
|
|
4870
|
+
if (bytesRead === 0) {
|
|
4871
|
+
break;
|
|
4872
|
+
}
|
|
4873
|
+
filled += bytesRead;
|
|
4874
|
+
}
|
|
4875
|
+
return buffer.subarray(0, filled);
|
|
4876
|
+
};
|
|
4877
|
+
var readRollout = async (rolloutPath, fromOffset, maxRangeBytes, tailBytes) => {
|
|
4878
|
+
let handle;
|
|
4879
|
+
try {
|
|
4880
|
+
const info = await stat2(rolloutPath);
|
|
4881
|
+
if (!info.isFile()) {
|
|
4882
|
+
return { status: "unavailable", reason: "not-a-file" };
|
|
4883
|
+
}
|
|
4884
|
+
handle = await open2(rolloutPath, "r");
|
|
4885
|
+
} catch {
|
|
4886
|
+
return { status: "unavailable", reason: "unreadable" };
|
|
4887
|
+
}
|
|
4888
|
+
try {
|
|
4889
|
+
const { size } = await handle.stat();
|
|
4890
|
+
let start;
|
|
4891
|
+
if (fromOffset === void 0) {
|
|
4892
|
+
start = Math.max(0, size - tailBytes);
|
|
4893
|
+
} else if (size < fromOffset) {
|
|
4894
|
+
return { status: "unavailable", reason: "truncated" };
|
|
4895
|
+
} else if (size - fromOffset > maxRangeBytes) {
|
|
4896
|
+
return { status: "unavailable", reason: "over-cap" };
|
|
4897
|
+
} else {
|
|
4898
|
+
start = fromOffset;
|
|
4899
|
+
}
|
|
4900
|
+
const bytes = await readBytes2(handle, start, size - start);
|
|
4901
|
+
const lastNewline = bytes.lastIndexOf(10);
|
|
4902
|
+
const endOffset = lastNewline < 0 ? start : start + lastNewline + 1;
|
|
4903
|
+
const lines = bytes.subarray(0, endOffset - start).toString("utf8").split("\n");
|
|
4904
|
+
if (fromOffset === void 0 && start > 0) {
|
|
4905
|
+
lines.shift();
|
|
4906
|
+
}
|
|
4907
|
+
const snapshot = lastSnapshotIn(lines);
|
|
4908
|
+
return { status: "found", ...snapshot === void 0 ? {} : { snapshot }, endOffset };
|
|
4909
|
+
} catch {
|
|
4910
|
+
return { status: "unavailable", reason: "unreadable" };
|
|
4911
|
+
} finally {
|
|
4912
|
+
await handle.close().catch(() => void 0);
|
|
4913
|
+
}
|
|
4914
|
+
};
|
|
4915
|
+
var pad = (value) => String(value).padStart(2, "0");
|
|
4916
|
+
var findRolloutBySessionId = async (sessionsRoot, sessionId, now) => {
|
|
4917
|
+
if (!SESSION_ID_PATTERN.test(sessionId) || !path2.isAbsolute(sessionsRoot)) {
|
|
4918
|
+
return void 0;
|
|
4919
|
+
}
|
|
4920
|
+
const suffix = `-${sessionId}.jsonl`;
|
|
4921
|
+
for (let back = 0; back < ROLLOUT_LOOKUP_DAYS; back += 1) {
|
|
4922
|
+
const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);
|
|
4923
|
+
const dir = path2.join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));
|
|
4924
|
+
let names;
|
|
4925
|
+
try {
|
|
4926
|
+
names = await readdir(dir);
|
|
4927
|
+
} catch {
|
|
4928
|
+
continue;
|
|
4929
|
+
}
|
|
4930
|
+
if (names.length > MAX_LOOKUP_DIR_ENTRIES) {
|
|
4931
|
+
continue;
|
|
4932
|
+
}
|
|
4933
|
+
const match = names.find((name) => name.startsWith("rollout-") && name.endsWith(suffix));
|
|
4934
|
+
if (match !== void 0) {
|
|
4935
|
+
return path2.join(dir, match);
|
|
4936
|
+
}
|
|
4937
|
+
}
|
|
4938
|
+
return void 0;
|
|
4939
|
+
};
|
|
4940
|
+
var TIMED_OUT2 = /* @__PURE__ */ Symbol("timed-out");
|
|
4941
|
+
var withTimeout2 = async (work, timeoutMillis) => {
|
|
4942
|
+
let timer;
|
|
4943
|
+
const timeout = new Promise((resolve3) => {
|
|
4944
|
+
timer = setTimeout(() => {
|
|
4945
|
+
resolve3(TIMED_OUT2);
|
|
4946
|
+
}, timeoutMillis);
|
|
4947
|
+
timer.unref();
|
|
4948
|
+
});
|
|
4949
|
+
try {
|
|
4950
|
+
return await Promise.race([work, timeout]);
|
|
4951
|
+
} finally {
|
|
4952
|
+
clearTimeout(timer);
|
|
4953
|
+
}
|
|
4954
|
+
};
|
|
4955
|
+
var sleep = (millis) => new Promise((resolve3) => {
|
|
4956
|
+
setTimeout(resolve3, millis).unref();
|
|
4957
|
+
});
|
|
4958
|
+
var hasUsage2 = (record) => record.usage !== void 0;
|
|
4959
|
+
var createCodexRolloutUsageEnricher = (options = {}) => {
|
|
4960
|
+
const maxRangeBytes = clamp2(options.maxRangeBytes, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, MIN_BYTES, MAX_RANGE_BYTES2);
|
|
4961
|
+
const maxTailBytes = clamp2(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES2);
|
|
4962
|
+
const timeoutMillis = clamp2(
|
|
4963
|
+
options.timeoutMillis,
|
|
4964
|
+
DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,
|
|
4965
|
+
MIN_TIMEOUT_MILLIS2,
|
|
4966
|
+
MAX_TIMEOUT_MILLIS2
|
|
4967
|
+
);
|
|
4968
|
+
const settleMillis = clamp2(options.settleMillis, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, 0, MAX_SETTLE_MILLIS);
|
|
4969
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
4970
|
+
const fileSize = async (rolloutPath) => {
|
|
4971
|
+
try {
|
|
4972
|
+
const info = await stat2(rolloutPath);
|
|
4973
|
+
return info.isFile() ? info.size : void 0;
|
|
4974
|
+
} catch (thrown) {
|
|
4975
|
+
return thrown?.code === "ENOENT" ? "absent" : void 0;
|
|
4976
|
+
}
|
|
4977
|
+
};
|
|
4978
|
+
const resolveRollout = async (record) => {
|
|
4979
|
+
const named = record.transcript_path;
|
|
4980
|
+
if (named !== void 0 && named !== null) {
|
|
4981
|
+
return isRolloutPath(named) ? named : void 0;
|
|
4982
|
+
}
|
|
4983
|
+
const sessionId = record.session_id;
|
|
4984
|
+
if (options.sessionsRoot === void 0 || typeof sessionId !== "string") {
|
|
4985
|
+
return void 0;
|
|
4986
|
+
}
|
|
4987
|
+
return findRolloutBySessionId(options.sessionsRoot, sessionId, now());
|
|
4988
|
+
};
|
|
4989
|
+
const enrichWithin = async (input) => {
|
|
4990
|
+
const unchanged = { payload: input.payload };
|
|
4991
|
+
const record = asRecord3(input.payload);
|
|
4992
|
+
const eventName = record?.hook_event_name;
|
|
4993
|
+
if (record === void 0 || eventName !== "SessionStart" && eventName !== "Stop") {
|
|
4994
|
+
return unchanged;
|
|
4995
|
+
}
|
|
4996
|
+
const rolloutPath = await resolveRollout(record);
|
|
4997
|
+
if (rolloutPath === void 0) {
|
|
4998
|
+
return { ...unchanged, notes: ["no rollout named or found for this session"] };
|
|
4999
|
+
}
|
|
5000
|
+
const source = sourceDigest2(rolloutPath);
|
|
5001
|
+
const cursor = input.cursor?.source === source ? input.cursor : void 0;
|
|
5002
|
+
if (eventName === "SessionStart") {
|
|
5003
|
+
if (cursor !== void 0) {
|
|
5004
|
+
return unchanged;
|
|
5005
|
+
}
|
|
5006
|
+
const size = await fileSize(rolloutPath);
|
|
5007
|
+
if (size === void 0) {
|
|
5008
|
+
return { ...unchanged, notes: ["rollout is not a readable regular file; no cursor recorded"] };
|
|
5009
|
+
}
|
|
5010
|
+
return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
|
|
5011
|
+
}
|
|
5012
|
+
if (hasUsage2(record)) {
|
|
5013
|
+
const size = await fileSize(rolloutPath);
|
|
5014
|
+
return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
|
|
5015
|
+
}
|
|
5016
|
+
const attach = (snapshot) => ({
|
|
5017
|
+
...record,
|
|
5018
|
+
...record.model === void 0 && snapshot.model !== void 0 ? { model: snapshot.model } : {},
|
|
5019
|
+
usage: snapshot.usage
|
|
5020
|
+
});
|
|
5021
|
+
let read = await readRollout(rolloutPath, cursor?.offset, maxRangeBytes, maxTailBytes);
|
|
5022
|
+
if (read.status === "found" && read.snapshot === void 0 && cursor !== void 0 && settleMillis > 0) {
|
|
5023
|
+
await sleep(settleMillis);
|
|
5024
|
+
read = await readRollout(rolloutPath, cursor.offset, maxRangeBytes, maxTailBytes);
|
|
5025
|
+
}
|
|
5026
|
+
if (read.status === "unavailable") {
|
|
5027
|
+
if (read.reason !== "truncated" && read.reason !== "over-cap") {
|
|
5028
|
+
return { ...unchanged, notes: [`rollout not read (${read.reason}); cursor kept`] };
|
|
5029
|
+
}
|
|
5030
|
+
read = await readRollout(rolloutPath, void 0, maxRangeBytes, maxTailBytes);
|
|
5031
|
+
if (read.status === "unavailable") {
|
|
5032
|
+
return { ...unchanged, notes: [`rollout tail not read (${read.reason})`] };
|
|
5033
|
+
}
|
|
5034
|
+
}
|
|
5035
|
+
const next = { source, offset: read.endOffset };
|
|
5036
|
+
if (read.snapshot === void 0) {
|
|
5037
|
+
return { payload: input.payload, cursor: next, notes: ["no token_count since the last stop"] };
|
|
5038
|
+
}
|
|
5039
|
+
return {
|
|
5040
|
+
payload: attach(read.snapshot),
|
|
5041
|
+
cursor: next,
|
|
5042
|
+
notes: [cursor === void 0 ? "no cursor; attached the last running total in the tail" : "attached the running total"]
|
|
5043
|
+
};
|
|
5044
|
+
};
|
|
5045
|
+
const enrich = async (input) => {
|
|
5046
|
+
try {
|
|
5047
|
+
const result = await withTimeout2(enrichWithin(input), timeoutMillis);
|
|
5048
|
+
return result === TIMED_OUT2 ? { payload: input.payload, notes: ["rollout read timed out; cursor kept"] } : result;
|
|
5049
|
+
} catch {
|
|
5050
|
+
return { payload: input.payload, notes: ["rollout read failed; cursor kept"] };
|
|
5051
|
+
}
|
|
5052
|
+
};
|
|
5053
|
+
return Object.freeze({ id: CODEX_ROLLOUT_USAGE_ENRICHER_ID, providerId: CODEX_PROVIDER_ID, enrich });
|
|
5054
|
+
};
|
|
5055
|
+
|
|
4606
5056
|
// src/runtime/clock.ts
|
|
4607
5057
|
var createSystemClock = () => ({
|
|
4608
5058
|
now: () => epochMillisSchema.parse(Date.now()),
|
|
@@ -4610,7 +5060,7 @@ var createSystemClock = () => ({
|
|
|
4610
5060
|
});
|
|
4611
5061
|
|
|
4612
5062
|
// src/runtime/hook.ts
|
|
4613
|
-
import { z as
|
|
5063
|
+
import { z as z20 } from "zod";
|
|
4614
5064
|
|
|
4615
5065
|
// src/providers/registry.ts
|
|
4616
5066
|
var createProviderRegistry = (adapters) => {
|
|
@@ -4765,9 +5215,9 @@ var resolveDeliveryIdentity = (input) => {
|
|
|
4765
5215
|
};
|
|
4766
5216
|
|
|
4767
5217
|
// src/runtime/ids.ts
|
|
4768
|
-
import { createHash as
|
|
5218
|
+
import { createHash as createHash6, randomUUID } from "crypto";
|
|
4769
5219
|
var digest2 = (namespace, parts) => {
|
|
4770
|
-
const hash =
|
|
5220
|
+
const hash = createHash6("sha256");
|
|
4771
5221
|
hash.update(namespace);
|
|
4772
5222
|
for (const part of parts) {
|
|
4773
5223
|
hash.update("\0");
|
|
@@ -4806,15 +5256,15 @@ var createDeterministicIdGenerator = (options = {}) => {
|
|
|
4806
5256
|
};
|
|
4807
5257
|
|
|
4808
5258
|
// src/runtime/ports.ts
|
|
4809
|
-
import { z as
|
|
4810
|
-
var appliedDeliverySchema =
|
|
4811
|
-
callbackId:
|
|
5259
|
+
import { z as z18 } from "zod";
|
|
5260
|
+
var appliedDeliverySchema = z18.strictObject({
|
|
5261
|
+
callbackId: z18.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
|
|
4812
5262
|
/** How many of that delivery's observations are folded in, counted from one. */
|
|
4813
|
-
applications:
|
|
5263
|
+
applications: z18.number().int().min(1).max(4096)
|
|
4814
5264
|
});
|
|
4815
|
-
var stateValueSchema =
|
|
4816
|
-
|
|
4817
|
-
kind:
|
|
5265
|
+
var stateValueSchema = z18.discriminatedUnion("kind", [
|
|
5266
|
+
z18.strictObject({
|
|
5267
|
+
kind: z18.literal("usage-cumulative"),
|
|
4818
5268
|
usage: canonicalUsageSchema,
|
|
4819
5269
|
/**
|
|
4820
5270
|
* Optional: absent on every record written before this field existed, which
|
|
@@ -4823,12 +5273,12 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
|
|
|
4823
5273
|
*/
|
|
4824
5274
|
appliedDelivery: appliedDeliverySchema.optional()
|
|
4825
5275
|
}),
|
|
4826
|
-
|
|
4827
|
-
kind:
|
|
5276
|
+
z18.strictObject({
|
|
5277
|
+
kind: z18.literal("sequence"),
|
|
4828
5278
|
next: sequenceNumberSchema
|
|
4829
5279
|
}),
|
|
4830
|
-
|
|
4831
|
-
kind:
|
|
5280
|
+
z18.strictObject({
|
|
5281
|
+
kind: z18.literal("attributes"),
|
|
4832
5282
|
attributes: attributesSchema
|
|
4833
5283
|
}),
|
|
4834
5284
|
/**
|
|
@@ -4837,8 +5287,8 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
|
|
|
4837
5287
|
* not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
|
|
4838
5288
|
* bounded canonical shape, never a payload fragment.
|
|
4839
5289
|
*/
|
|
4840
|
-
|
|
4841
|
-
kind:
|
|
5290
|
+
z18.strictObject({
|
|
5291
|
+
kind: z18.literal("session-model"),
|
|
4842
5292
|
model: modelDescriptorSchema
|
|
4843
5293
|
}),
|
|
4844
5294
|
/**
|
|
@@ -4852,36 +5302,36 @@ var stateValueSchema = z17.discriminatedUnion("kind", [
|
|
|
4852
5302
|
* a series digest only; the series' attributes are re-supplied by the caller
|
|
4853
5303
|
* and never read back from disk.
|
|
4854
5304
|
*/
|
|
4855
|
-
|
|
4856
|
-
kind:
|
|
5305
|
+
z18.strictObject({
|
|
5306
|
+
kind: z18.literal("metric-series"),
|
|
4857
5307
|
/** Start of the cumulative interval. */
|
|
4858
5308
|
startTimeMillis: epochMillisSchema,
|
|
4859
5309
|
/** Counters: the running total. */
|
|
4860
|
-
value:
|
|
5310
|
+
value: z18.number().finite().min(0).optional(),
|
|
4861
5311
|
/** Histograms: the running aggregation. */
|
|
4862
|
-
histogram:
|
|
4863
|
-
count:
|
|
4864
|
-
sum:
|
|
4865
|
-
min:
|
|
4866
|
-
max:
|
|
4867
|
-
bucketCounts:
|
|
5312
|
+
histogram: z18.strictObject({
|
|
5313
|
+
count: z18.number().int().min(0),
|
|
5314
|
+
sum: z18.number().finite().min(0),
|
|
5315
|
+
min: z18.number().finite(),
|
|
5316
|
+
max: z18.number().finite(),
|
|
5317
|
+
bucketCounts: z18.array(z18.number().int().min(0)).max(64)
|
|
4868
5318
|
}).optional(),
|
|
4869
5319
|
/** Opaque digest of the last delivery folded in; makes a replay a no-op. */
|
|
4870
|
-
appliedDelivery:
|
|
5320
|
+
appliedDelivery: z18.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
|
|
4871
5321
|
}),
|
|
4872
|
-
|
|
4873
|
-
kind:
|
|
4874
|
-
source:
|
|
4875
|
-
offset:
|
|
5322
|
+
z18.strictObject({
|
|
5323
|
+
kind: z18.literal("read-cursor"),
|
|
5324
|
+
source: z18.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
|
|
5325
|
+
offset: z18.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
|
|
4876
5326
|
})
|
|
4877
5327
|
]);
|
|
4878
|
-
var stateRecordSchema =
|
|
5328
|
+
var stateRecordSchema = z18.strictObject({
|
|
4879
5329
|
/** Incremented on each write; lets callers detect lost updates. */
|
|
4880
|
-
revision:
|
|
5330
|
+
revision: z18.number().int().min(0),
|
|
4881
5331
|
updatedAt: epochMillisSchema,
|
|
4882
5332
|
value: stateValueSchema
|
|
4883
5333
|
});
|
|
4884
|
-
var logLevelSchema =
|
|
5334
|
+
var logLevelSchema = z18.enum(["silent", "error", "warn", "info", "debug"]);
|
|
4885
5335
|
var LOG_LEVEL_RANK = Object.freeze({
|
|
4886
5336
|
silent: 0,
|
|
4887
5337
|
error: 1,
|
|
@@ -4899,7 +5349,7 @@ var createNullLogger = () => ({
|
|
|
4899
5349
|
});
|
|
4900
5350
|
|
|
4901
5351
|
// src/runtime/target-resolution.ts
|
|
4902
|
-
import * as
|
|
5352
|
+
import * as path3 from "path";
|
|
4903
5353
|
|
|
4904
5354
|
// src/privacy/workspace.ts
|
|
4905
5355
|
var canonicalizeGitRemote = (remoteUrl) => {
|
|
@@ -4951,13 +5401,13 @@ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
|
|
|
4951
5401
|
// src/runtime/target-resolution.ts
|
|
4952
5402
|
var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
|
|
4953
5403
|
var absolutePathsOf = (hint) => {
|
|
4954
|
-
const base = hint.baseDirectory !== void 0 &&
|
|
5404
|
+
const base = hint.baseDirectory !== void 0 && path3.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
|
|
4955
5405
|
const resolved = [];
|
|
4956
5406
|
for (const candidate of hint.paths) {
|
|
4957
|
-
if (
|
|
4958
|
-
resolved.push(
|
|
5407
|
+
if (path3.isAbsolute(candidate)) {
|
|
5408
|
+
resolved.push(path3.resolve(candidate));
|
|
4959
5409
|
} else if (base !== void 0) {
|
|
4960
|
-
resolved.push(
|
|
5410
|
+
resolved.push(path3.resolve(base, candidate));
|
|
4961
5411
|
} else {
|
|
4962
5412
|
return void 0;
|
|
4963
5413
|
}
|
|
@@ -5036,9 +5486,9 @@ var resolveEventTargets = async (input) => {
|
|
|
5036
5486
|
};
|
|
5037
5487
|
|
|
5038
5488
|
// src/runtime/session-context.ts
|
|
5039
|
-
import { open as
|
|
5040
|
-
import * as
|
|
5041
|
-
import { z as
|
|
5489
|
+
import { open as open3 } from "fs/promises";
|
|
5490
|
+
import * as path4 from "path";
|
|
5491
|
+
import { z as z19 } from "zod";
|
|
5042
5492
|
var SESSION_CONTEXT_FILE_VERSION = 1;
|
|
5043
5493
|
var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
|
|
5044
5494
|
var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
|
|
@@ -5055,10 +5505,10 @@ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
|
|
|
5055
5505
|
var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
|
|
5056
5506
|
var sessionContextFilePath = (dir, providerId, sessionId) => {
|
|
5057
5507
|
const tool = sessionContextAgentTool(providerId);
|
|
5058
|
-
if (tool === void 0 || !isSessionContextFileName(sessionId) || !
|
|
5508
|
+
if (tool === void 0 || !isSessionContextFileName(sessionId) || !path4.isAbsolute(dir)) {
|
|
5059
5509
|
return void 0;
|
|
5060
5510
|
}
|
|
5061
|
-
return
|
|
5511
|
+
return path4.join(dir, tool, `${sessionId}.json`);
|
|
5062
5512
|
};
|
|
5063
5513
|
var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
|
|
5064
5514
|
"session.id",
|
|
@@ -5097,25 +5547,25 @@ var sanitizeSessionContextAttributes = (attributes) => {
|
|
|
5097
5547
|
return kept;
|
|
5098
5548
|
};
|
|
5099
5549
|
var ISO_INSTANT_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
5100
|
-
var isoInstantSchema =
|
|
5550
|
+
var isoInstantSchema = z19.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
|
|
5101
5551
|
const millis = Date.parse(value);
|
|
5102
5552
|
if (!Number.isFinite(millis)) {
|
|
5103
5553
|
ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
|
|
5104
|
-
return
|
|
5554
|
+
return z19.NEVER;
|
|
5105
5555
|
}
|
|
5106
5556
|
return millis;
|
|
5107
5557
|
});
|
|
5108
|
-
var segmentSchema =
|
|
5558
|
+
var segmentSchema = z19.object({
|
|
5109
5559
|
from: isoInstantSchema,
|
|
5110
5560
|
to: isoInstantSchema.nullable(),
|
|
5111
|
-
reason:
|
|
5112
|
-
attributes:
|
|
5561
|
+
reason: z19.string().max(256).optional(),
|
|
5562
|
+
attributes: z19.record(z19.string(), z19.unknown())
|
|
5113
5563
|
});
|
|
5114
|
-
var sessionContextFileSchema =
|
|
5115
|
-
version:
|
|
5116
|
-
agentTool:
|
|
5117
|
-
sessionId:
|
|
5118
|
-
segments:
|
|
5564
|
+
var sessionContextFileSchema = z19.object({
|
|
5565
|
+
version: z19.literal(SESSION_CONTEXT_FILE_VERSION),
|
|
5566
|
+
agentTool: z19.string().max(64).optional(),
|
|
5567
|
+
sessionId: z19.string().max(256).optional(),
|
|
5568
|
+
segments: z19.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
|
|
5119
5569
|
});
|
|
5120
5570
|
var parseSessionContextFile = (value, expected) => {
|
|
5121
5571
|
const parsed = sessionContextFileSchema.safeParse(value);
|
|
@@ -5154,7 +5604,7 @@ var stampSessionContext = (events, segments) => events.map((event2) => {
|
|
|
5154
5604
|
var readBounded = async (file, maxBytes) => {
|
|
5155
5605
|
let handle;
|
|
5156
5606
|
try {
|
|
5157
|
-
handle = await
|
|
5607
|
+
handle = await open3(file, "r");
|
|
5158
5608
|
} catch {
|
|
5159
5609
|
return void 0;
|
|
5160
5610
|
}
|
|
@@ -5228,7 +5678,7 @@ var createDirectorySessionContextReader = (options) => {
|
|
|
5228
5678
|
};
|
|
5229
5679
|
|
|
5230
5680
|
// src/runtime/hook.ts
|
|
5231
|
-
var usageScopeSchema =
|
|
5681
|
+
var usageScopeSchema = z20.enum(["session", "generation", "subagent"]);
|
|
5232
5682
|
var classifyDurability = (input) => {
|
|
5233
5683
|
if (!input.attempted) {
|
|
5234
5684
|
return "nothing-to-deliver";
|
|
@@ -6107,8 +6557,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
|
|
|
6107
6557
|
};
|
|
6108
6558
|
|
|
6109
6559
|
// src/runtime/git-worktree.ts
|
|
6110
|
-
import { lstat, open as
|
|
6111
|
-
import * as
|
|
6560
|
+
import { lstat, open as open4, stat as stat3 } from "fs/promises";
|
|
6561
|
+
import * as path5 from "path";
|
|
6112
6562
|
var MAX_WORKTREE_WALK_DEPTH = 128;
|
|
6113
6563
|
var MAX_GIT_FILE_BYTES = 4096;
|
|
6114
6564
|
var MAX_CACHE_ENTRIES = 1024;
|
|
@@ -6119,7 +6569,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
|
|
|
6119
6569
|
var readBounded2 = async (filePath) => {
|
|
6120
6570
|
let handle;
|
|
6121
6571
|
try {
|
|
6122
|
-
handle = await
|
|
6572
|
+
handle = await open4(filePath, "r");
|
|
6123
6573
|
const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
|
|
6124
6574
|
const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
|
|
6125
6575
|
return buffer.subarray(0, bytesRead).toString("utf8");
|
|
@@ -6140,7 +6590,7 @@ var parseHeadBranch = (head) => {
|
|
|
6140
6590
|
return branch;
|
|
6141
6591
|
};
|
|
6142
6592
|
var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
|
|
6143
|
-
var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 :
|
|
6593
|
+
var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path5.resolve(base, target);
|
|
6144
6594
|
var parseGitDirFile = (content, worktreeRoot) => {
|
|
6145
6595
|
const line = firstLine(content);
|
|
6146
6596
|
return resolveGitPath(
|
|
@@ -6160,26 +6610,26 @@ var isMissing = async (filePath) => {
|
|
|
6160
6610
|
};
|
|
6161
6611
|
var isDirectory = async (directory) => {
|
|
6162
6612
|
try {
|
|
6163
|
-
return (await
|
|
6613
|
+
return (await stat3(directory)).isDirectory();
|
|
6164
6614
|
} catch {
|
|
6165
6615
|
return false;
|
|
6166
6616
|
}
|
|
6167
6617
|
};
|
|
6168
6618
|
var repositoryOf = async (worktreeRoot, gitDir) => {
|
|
6169
|
-
const commonDirFile =
|
|
6619
|
+
const commonDirFile = path5.join(gitDir, "commondir");
|
|
6170
6620
|
const content = await readBounded2(commonDirFile);
|
|
6171
6621
|
if (content === void 0) {
|
|
6172
6622
|
return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
|
|
6173
6623
|
}
|
|
6174
6624
|
const commonDir = parseCommonDirFile(content, gitDir);
|
|
6175
|
-
const mainRoot = commonDir !== void 0 &&
|
|
6625
|
+
const mainRoot = commonDir !== void 0 && path5.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path5.dirname(commonDir) : void 0;
|
|
6176
6626
|
return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
|
|
6177
6627
|
};
|
|
6178
6628
|
var probeDirectory = async (directory) => {
|
|
6179
|
-
const dotGit =
|
|
6629
|
+
const dotGit = path5.join(directory, ".git");
|
|
6180
6630
|
let info;
|
|
6181
6631
|
try {
|
|
6182
|
-
info = await
|
|
6632
|
+
info = await stat3(dotGit);
|
|
6183
6633
|
} catch {
|
|
6184
6634
|
return ABSENT;
|
|
6185
6635
|
}
|
|
@@ -6193,7 +6643,7 @@ var probeDirectory = async (directory) => {
|
|
|
6193
6643
|
if (gitDir === void 0) {
|
|
6194
6644
|
return INVALID;
|
|
6195
6645
|
}
|
|
6196
|
-
const head = await readBounded2(
|
|
6646
|
+
const head = await readBounded2(path5.join(gitDir, "HEAD"));
|
|
6197
6647
|
if (head === void 0) {
|
|
6198
6648
|
return INVALID;
|
|
6199
6649
|
}
|
|
@@ -6223,10 +6673,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
|
|
|
6223
6673
|
};
|
|
6224
6674
|
const locate = async (absolutePath) => {
|
|
6225
6675
|
try {
|
|
6226
|
-
if (!
|
|
6676
|
+
if (!path5.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
|
|
6227
6677
|
return void 0;
|
|
6228
6678
|
}
|
|
6229
|
-
let directory =
|
|
6679
|
+
let directory = path5.resolve(absolutePath);
|
|
6230
6680
|
for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
|
|
6231
6681
|
const probe = await cachedProbe(directory);
|
|
6232
6682
|
if (probe.kind === "worktree") {
|
|
@@ -6235,7 +6685,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
|
|
|
6235
6685
|
if (probe.kind === "invalid") {
|
|
6236
6686
|
return void 0;
|
|
6237
6687
|
}
|
|
6238
|
-
const parent =
|
|
6688
|
+
const parent = path5.dirname(directory);
|
|
6239
6689
|
if (parent === directory) {
|
|
6240
6690
|
return void 0;
|
|
6241
6691
|
}
|
|
@@ -6251,30 +6701,29 @@ var createFilesystemWorktreeLocator = (options = {}) => {
|
|
|
6251
6701
|
|
|
6252
6702
|
// src/state/filesystem-store.ts
|
|
6253
6703
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
6254
|
-
import { mkdir, open as
|
|
6255
|
-
import * as
|
|
6704
|
+
import { mkdir, open as open5, readFile, readdir as readdir2, rename, stat as stat4, unlink, writeFile } from "fs/promises";
|
|
6705
|
+
import * as path6 from "path";
|
|
6256
6706
|
|
|
6257
6707
|
// src/state/keys.ts
|
|
6258
|
-
import { createHash as
|
|
6708
|
+
import { createHash as createHash7 } from "crypto";
|
|
6259
6709
|
var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
6260
6710
|
var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
|
|
6261
6711
|
var sanitizeSegment = (segment) => {
|
|
6262
6712
|
if (isSafeSegment(segment)) {
|
|
6263
6713
|
return segment;
|
|
6264
6714
|
}
|
|
6265
|
-
return `h_${
|
|
6715
|
+
return `h_${createHash7("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
|
|
6266
6716
|
};
|
|
6267
6717
|
var namespaceSegments = (namespace) => [
|
|
6268
6718
|
sanitizeSegment(namespace.providerId),
|
|
6269
6719
|
sanitizeSegment(namespace.installationId)
|
|
6270
6720
|
];
|
|
6271
|
-
var keyDigest = (key) =>
|
|
6721
|
+
var keyDigest = (key) => createHash7("sha256").update(key, "utf8").digest("hex");
|
|
6272
6722
|
|
|
6273
6723
|
// src/state/filesystem-store.ts
|
|
6274
6724
|
var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
|
|
6275
|
-
var
|
|
6276
|
-
|
|
6277
|
-
timer.unref?.();
|
|
6725
|
+
var sleep2 = (millis) => new Promise((resolve3) => {
|
|
6726
|
+
setTimeout(resolve3, millis);
|
|
6278
6727
|
});
|
|
6279
6728
|
var wrapFsError = (thrown, operation) => {
|
|
6280
6729
|
if (thrown instanceof Error) {
|
|
@@ -6284,10 +6733,10 @@ var wrapFsError = (thrown, operation) => {
|
|
|
6284
6733
|
};
|
|
6285
6734
|
var createFilesystemStateStore = (options) => {
|
|
6286
6735
|
const [providerSegment, installationSegment] = namespaceSegments(options);
|
|
6287
|
-
const baseDir =
|
|
6288
|
-
const recordsDir =
|
|
6289
|
-
const quarantineDir =
|
|
6290
|
-
const locksDir =
|
|
6736
|
+
const baseDir = path6.join(options.rootDir, providerSegment, installationSegment);
|
|
6737
|
+
const recordsDir = path6.join(baseDir, "records");
|
|
6738
|
+
const quarantineDir = path6.join(baseDir, "quarantine");
|
|
6739
|
+
const locksDir = path6.join(baseDir, "locks");
|
|
6291
6740
|
const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
|
|
6292
6741
|
const lockStaleMillis = options.lockStaleMillis ?? 3e4;
|
|
6293
6742
|
const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
|
|
@@ -6311,11 +6760,11 @@ var createFilesystemStateStore = (options) => {
|
|
|
6311
6760
|
throw wrapFsError(thrown, "ensure-dirs");
|
|
6312
6761
|
}
|
|
6313
6762
|
};
|
|
6314
|
-
const recordPath = (key) =>
|
|
6315
|
-
const tempPath = (key) =>
|
|
6316
|
-
const lockPath = (sessionId) =>
|
|
6763
|
+
const recordPath = (key) => path6.join(recordsDir, `${keyDigest(key)}.json`);
|
|
6764
|
+
const tempPath = (key) => path6.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
|
|
6765
|
+
const lockPath = (sessionId) => path6.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
|
|
6317
6766
|
const quarantine = async (filePath, key, reason) => {
|
|
6318
|
-
const dest =
|
|
6767
|
+
const dest = path6.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
|
|
6319
6768
|
try {
|
|
6320
6769
|
await rename(filePath, dest);
|
|
6321
6770
|
} catch {
|
|
@@ -6379,7 +6828,7 @@ var createFilesystemStateStore = (options) => {
|
|
|
6379
6828
|
const startedAt = options.clock.monotonicMillis();
|
|
6380
6829
|
for (; ; ) {
|
|
6381
6830
|
try {
|
|
6382
|
-
const handle = await
|
|
6831
|
+
const handle = await open5(filePath, "wx");
|
|
6383
6832
|
try {
|
|
6384
6833
|
await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
|
|
6385
6834
|
} finally {
|
|
@@ -6394,14 +6843,29 @@ var createFilesystemStateStore = (options) => {
|
|
|
6394
6843
|
}
|
|
6395
6844
|
}
|
|
6396
6845
|
const stale = await (async () => {
|
|
6846
|
+
let raw;
|
|
6847
|
+
try {
|
|
6848
|
+
raw = await readFile(filePath, "utf8");
|
|
6849
|
+
} catch (thrown) {
|
|
6850
|
+
return isErrnoException(thrown, "ENOENT") ? "gone" : true;
|
|
6851
|
+
}
|
|
6397
6852
|
try {
|
|
6398
|
-
const raw = await readFile(filePath, "utf8");
|
|
6399
6853
|
const parsed = JSON.parse(raw);
|
|
6400
|
-
|
|
6854
|
+
if (typeof parsed.acquiredAt === "number") {
|
|
6855
|
+
return options.clock.now() - parsed.acquiredAt > lockStaleMillis;
|
|
6856
|
+
}
|
|
6401
6857
|
} catch {
|
|
6402
|
-
|
|
6858
|
+
}
|
|
6859
|
+
try {
|
|
6860
|
+
const stats = await stat4(filePath);
|
|
6861
|
+
return Date.now() - stats.mtimeMs > lockStaleMillis;
|
|
6862
|
+
} catch {
|
|
6863
|
+
return "gone";
|
|
6403
6864
|
}
|
|
6404
6865
|
})();
|
|
6866
|
+
if (stale === "gone") {
|
|
6867
|
+
continue;
|
|
6868
|
+
}
|
|
6405
6869
|
if (stale) {
|
|
6406
6870
|
await unlink(filePath).catch(() => void 0);
|
|
6407
6871
|
continue;
|
|
@@ -6409,7 +6873,7 @@ var createFilesystemStateStore = (options) => {
|
|
|
6409
6873
|
if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {
|
|
6410
6874
|
throw new StateLockTimeoutError(sessionId, timeoutMillis);
|
|
6411
6875
|
}
|
|
6412
|
-
await
|
|
6876
|
+
await sleep2(lockPollIntervalMillis);
|
|
6413
6877
|
}
|
|
6414
6878
|
};
|
|
6415
6879
|
return {
|
|
@@ -6433,7 +6897,7 @@ var createFilesystemStateStore = (options) => {
|
|
|
6433
6897
|
await ensureDirs();
|
|
6434
6898
|
let entries;
|
|
6435
6899
|
try {
|
|
6436
|
-
entries = await
|
|
6900
|
+
entries = await readdir2(recordsDir);
|
|
6437
6901
|
} catch (thrown) {
|
|
6438
6902
|
if (isErrnoException(thrown, "ENOENT")) {
|
|
6439
6903
|
return [];
|
|
@@ -6447,7 +6911,7 @@ var createFilesystemStateStore = (options) => {
|
|
|
6447
6911
|
}
|
|
6448
6912
|
let raw;
|
|
6449
6913
|
try {
|
|
6450
|
-
raw = await readFile(
|
|
6914
|
+
raw = await readFile(path6.join(recordsDir, entry), "utf8");
|
|
6451
6915
|
} catch {
|
|
6452
6916
|
continue;
|
|
6453
6917
|
}
|
|
@@ -6485,7 +6949,7 @@ var createFilesystemStateStore = (options) => {
|
|
|
6485
6949
|
let scanned = 0;
|
|
6486
6950
|
let entries;
|
|
6487
6951
|
try {
|
|
6488
|
-
entries = await
|
|
6952
|
+
entries = await readdir2(recordsDir);
|
|
6489
6953
|
} catch (thrown) {
|
|
6490
6954
|
if (!isErrnoException(thrown, "ENOENT")) {
|
|
6491
6955
|
throw wrapFsError(thrown, "prune");
|
|
@@ -6500,7 +6964,7 @@ var createFilesystemStateStore = (options) => {
|
|
|
6500
6964
|
continue;
|
|
6501
6965
|
}
|
|
6502
6966
|
scanned += 1;
|
|
6503
|
-
const filePath =
|
|
6967
|
+
const filePath = path6.join(recordsDir, entry);
|
|
6504
6968
|
try {
|
|
6505
6969
|
const raw = await readFile(filePath, "utf8");
|
|
6506
6970
|
const envelope = JSON.parse(raw);
|
|
@@ -6515,12 +6979,12 @@ var createFilesystemStateStore = (options) => {
|
|
|
6515
6979
|
}
|
|
6516
6980
|
let lockEntries;
|
|
6517
6981
|
try {
|
|
6518
|
-
lockEntries = await
|
|
6982
|
+
lockEntries = await readdir2(locksDir);
|
|
6519
6983
|
} catch {
|
|
6520
6984
|
lockEntries = [];
|
|
6521
6985
|
}
|
|
6522
6986
|
for (const entry of lockEntries) {
|
|
6523
|
-
const filePath =
|
|
6987
|
+
const filePath = path6.join(locksDir, entry);
|
|
6524
6988
|
try {
|
|
6525
6989
|
const raw = await readFile(filePath, "utf8");
|
|
6526
6990
|
const parsed = JSON.parse(raw);
|
|
@@ -6572,8 +7036,8 @@ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
|
|
|
6572
7036
|
|
|
6573
7037
|
// src/telemetry/spool-queue.ts
|
|
6574
7038
|
import { randomBytes as randomBytes3 } from "crypto";
|
|
6575
|
-
import { mkdir as mkdir2, readFile as readFile2, readdir as
|
|
6576
|
-
import * as
|
|
7039
|
+
import { mkdir as mkdir2, open as open6, readFile as readFile2, readdir as readdir3, rename as rename2, stat as stat5, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
|
|
7040
|
+
import * as path7 from "path";
|
|
6577
7041
|
var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
|
|
6578
7042
|
total: 0,
|
|
6579
7043
|
age: 0,
|
|
@@ -6589,7 +7053,7 @@ var enqueuedAtOf = (fileName) => {
|
|
|
6589
7053
|
var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
6590
7054
|
var readSpoolDropCounts = async (queueDir) => {
|
|
6591
7055
|
try {
|
|
6592
|
-
const parsed = JSON.parse(await readFile2(
|
|
7056
|
+
const parsed = JSON.parse(await readFile2(path7.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
|
|
6593
7057
|
if (typeof parsed !== "object" || parsed === null) {
|
|
6594
7058
|
return EMPTY_SPOOL_DROP_COUNTS;
|
|
6595
7059
|
}
|
|
@@ -6610,7 +7074,7 @@ var readSpoolDropCounts = async (queueDir) => {
|
|
|
6610
7074
|
var readSpoolQueueStats = async (queueDir) => {
|
|
6611
7075
|
let entries;
|
|
6612
7076
|
try {
|
|
6613
|
-
entries = await
|
|
7077
|
+
entries = await readdir3(queueDir);
|
|
6614
7078
|
} catch {
|
|
6615
7079
|
return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
|
|
6616
7080
|
}
|
|
@@ -6618,7 +7082,7 @@ var readSpoolQueueStats = async (queueDir) => {
|
|
|
6618
7082
|
let bytes = 0;
|
|
6619
7083
|
for (const file of files) {
|
|
6620
7084
|
try {
|
|
6621
|
-
bytes += (await
|
|
7085
|
+
bytes += (await stat5(path7.join(queueDir, file))).size;
|
|
6622
7086
|
} catch {
|
|
6623
7087
|
}
|
|
6624
7088
|
}
|
|
@@ -6631,11 +7095,56 @@ var readSpoolQueueStats = async (queueDir) => {
|
|
|
6631
7095
|
};
|
|
6632
7096
|
};
|
|
6633
7097
|
var DEFAULT_DRAIN_MAX_BATCHES = 20;
|
|
7098
|
+
var SPOOL_CLAIM_STALE_MILLIS = 5 * 60 * 1e3;
|
|
7099
|
+
var CLAIM_SUFFIX = ".claim";
|
|
7100
|
+
var RELEASING_SUFFIX = ".releasing";
|
|
7101
|
+
var isClaimOwnerAlive = (pid) => {
|
|
7102
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) {
|
|
7103
|
+
return true;
|
|
7104
|
+
}
|
|
7105
|
+
if (pid === process.pid) {
|
|
7106
|
+
return true;
|
|
7107
|
+
}
|
|
7108
|
+
try {
|
|
7109
|
+
process.kill(pid, 0);
|
|
7110
|
+
return true;
|
|
7111
|
+
} catch (thrown) {
|
|
7112
|
+
return thrown?.code !== "ESRCH";
|
|
7113
|
+
}
|
|
7114
|
+
};
|
|
6634
7115
|
var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
|
|
7116
|
+
var readClaim = async (claimPath) => {
|
|
7117
|
+
try {
|
|
7118
|
+
const parsed = JSON.parse(await readFile2(claimPath, "utf8"));
|
|
7119
|
+
return typeof parsed.token === "string" && typeof parsed.pid === "number" && typeof parsed.claimedAt === "number" ? { token: parsed.token, pid: parsed.pid, claimedAt: parsed.claimedAt } : void 0;
|
|
7120
|
+
} catch {
|
|
7121
|
+
return void 0;
|
|
7122
|
+
}
|
|
7123
|
+
};
|
|
7124
|
+
var releaseClaim = async (claimPath, token) => {
|
|
7125
|
+
const tombstone = `${claimPath}.${token ?? "untokened"}-${randomBytes3(4).toString("hex")}${RELEASING_SUFFIX}`;
|
|
7126
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
7127
|
+
try {
|
|
7128
|
+
await rename2(claimPath, tombstone);
|
|
7129
|
+
break;
|
|
7130
|
+
} catch (thrown) {
|
|
7131
|
+
if (isErrnoException2(thrown, "ENOENT") || attempt >= 3) {
|
|
7132
|
+
return;
|
|
7133
|
+
}
|
|
7134
|
+
await new Promise((resolve3) => setTimeout(resolve3, 10 * attempt));
|
|
7135
|
+
}
|
|
7136
|
+
}
|
|
7137
|
+
const captured = await readClaim(tombstone);
|
|
7138
|
+
if (captured !== void 0 && captured.token !== token) {
|
|
7139
|
+
await rename2(tombstone, claimPath).catch(() => void 0);
|
|
7140
|
+
return;
|
|
7141
|
+
}
|
|
7142
|
+
await unlink2(tombstone).catch(() => void 0);
|
|
7143
|
+
};
|
|
6635
7144
|
var createSpoolQueue = (options) => {
|
|
6636
7145
|
const [providerSegment, installationSegment] = namespaceSegments(options);
|
|
6637
|
-
const queueDir =
|
|
6638
|
-
const corruptDir =
|
|
7146
|
+
const queueDir = path7.join(options.rootDir, providerSegment, installationSegment, options.queueName);
|
|
7147
|
+
const corruptDir = path7.join(
|
|
6639
7148
|
options.rootDir,
|
|
6640
7149
|
providerSegment,
|
|
6641
7150
|
installationSegment,
|
|
@@ -6661,7 +7170,7 @@ var createSpoolQueue = (options) => {
|
|
|
6661
7170
|
const listSorted = async () => {
|
|
6662
7171
|
let entries;
|
|
6663
7172
|
try {
|
|
6664
|
-
entries = await
|
|
7173
|
+
entries = await readdir3(queueDir);
|
|
6665
7174
|
} catch (thrown) {
|
|
6666
7175
|
if (isErrnoException2(thrown, "ENOENT")) {
|
|
6667
7176
|
return [];
|
|
@@ -6682,9 +7191,9 @@ var createSpoolQueue = (options) => {
|
|
|
6682
7191
|
[reason]: current[reason] + dropped,
|
|
6683
7192
|
lastDroppedAt: options.clock.now()
|
|
6684
7193
|
};
|
|
6685
|
-
const tmp =
|
|
7194
|
+
const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
|
|
6686
7195
|
await writeFile2(tmp, JSON.stringify(next), "utf8");
|
|
6687
|
-
await rename2(tmp,
|
|
7196
|
+
await rename2(tmp, path7.join(queueDir, SPOOL_DROPS_FILE));
|
|
6688
7197
|
} catch {
|
|
6689
7198
|
}
|
|
6690
7199
|
options.logger?.warn("durable spool dropped batches", {
|
|
@@ -6700,7 +7209,7 @@ var createSpoolQueue = (options) => {
|
|
|
6700
7209
|
let bytes = 0;
|
|
6701
7210
|
if (options.maxBytes !== void 0) {
|
|
6702
7211
|
try {
|
|
6703
|
-
bytes = (await
|
|
7212
|
+
bytes = (await stat5(path7.join(queueDir, name))).size;
|
|
6704
7213
|
} catch {
|
|
6705
7214
|
continue;
|
|
6706
7215
|
}
|
|
@@ -6714,7 +7223,7 @@ var createSpoolQueue = (options) => {
|
|
|
6714
7223
|
let removed = 0;
|
|
6715
7224
|
for (const file of files) {
|
|
6716
7225
|
try {
|
|
6717
|
-
await unlink2(
|
|
7226
|
+
await unlink2(path7.join(queueDir, file.name));
|
|
6718
7227
|
removed += 1;
|
|
6719
7228
|
} catch {
|
|
6720
7229
|
}
|
|
@@ -6774,15 +7283,69 @@ var createSpoolQueue = (options) => {
|
|
|
6774
7283
|
}
|
|
6775
7284
|
}
|
|
6776
7285
|
const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
|
|
6777
|
-
const target =
|
|
6778
|
-
const tmp =
|
|
7286
|
+
const target = path7.join(queueDir, fileName);
|
|
7287
|
+
const tmp = path7.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
|
|
6779
7288
|
await writeFile2(tmp, serialized, "utf8");
|
|
6780
7289
|
await rename2(tmp, target);
|
|
6781
7290
|
return { spooled: true };
|
|
6782
7291
|
};
|
|
7292
|
+
const claimStaleMillis = options.claimStaleMillis ?? SPOOL_CLAIM_STALE_MILLIS;
|
|
7293
|
+
const staleClaim = async (claimPath) => {
|
|
7294
|
+
const claim = await readClaim(claimPath);
|
|
7295
|
+
const now = Date.now();
|
|
7296
|
+
if (claim !== void 0) {
|
|
7297
|
+
return !isClaimOwnerAlive(claim.pid) || now - claim.claimedAt > claimStaleMillis ? { stale: true, token: claim.token } : { stale: false };
|
|
7298
|
+
}
|
|
7299
|
+
try {
|
|
7300
|
+
return now - (await stat5(claimPath)).mtimeMs > claimStaleMillis ? { stale: true, token: void 0 } : { stale: false };
|
|
7301
|
+
} catch {
|
|
7302
|
+
return { stale: false };
|
|
7303
|
+
}
|
|
7304
|
+
};
|
|
7305
|
+
const releaseStaleClaims = async () => {
|
|
7306
|
+
let entries;
|
|
7307
|
+
try {
|
|
7308
|
+
entries = await readdir3(queueDir);
|
|
7309
|
+
} catch {
|
|
7310
|
+
return;
|
|
7311
|
+
}
|
|
7312
|
+
const now = Date.now();
|
|
7313
|
+
for (const entry of entries) {
|
|
7314
|
+
const entryPath = path7.join(queueDir, entry);
|
|
7315
|
+
if (entry.endsWith(CLAIM_SUFFIX)) {
|
|
7316
|
+
const staleness = await staleClaim(entryPath);
|
|
7317
|
+
if (staleness.stale) {
|
|
7318
|
+
await releaseClaim(entryPath, staleness.token);
|
|
7319
|
+
}
|
|
7320
|
+
} else if (entry.endsWith(RELEASING_SUFFIX)) {
|
|
7321
|
+
try {
|
|
7322
|
+
if (now - (await stat5(entryPath)).mtimeMs > claimStaleMillis) {
|
|
7323
|
+
await unlink2(entryPath);
|
|
7324
|
+
}
|
|
7325
|
+
} catch {
|
|
7326
|
+
}
|
|
7327
|
+
}
|
|
7328
|
+
}
|
|
7329
|
+
};
|
|
7330
|
+
const claimBatch = async (claimPath) => {
|
|
7331
|
+
const token = randomBytes3(16).toString("hex");
|
|
7332
|
+
try {
|
|
7333
|
+
const handle = await open6(claimPath, "wx");
|
|
7334
|
+
try {
|
|
7335
|
+
const contents = { token, pid: process.pid, claimedAt: Date.now() };
|
|
7336
|
+
await handle.writeFile(JSON.stringify(contents), "utf8");
|
|
7337
|
+
} finally {
|
|
7338
|
+
await handle.close();
|
|
7339
|
+
}
|
|
7340
|
+
return token;
|
|
7341
|
+
} catch {
|
|
7342
|
+
return void 0;
|
|
7343
|
+
}
|
|
7344
|
+
};
|
|
6783
7345
|
const drain = async (send, drainOptions) => {
|
|
6784
7346
|
await ensureDirs();
|
|
6785
7347
|
const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
|
|
7348
|
+
await releaseStaleClaims();
|
|
6786
7349
|
let files = await listSorted();
|
|
6787
7350
|
if (options.maxAgeMillis !== void 0) {
|
|
6788
7351
|
const now = options.clock.now();
|
|
@@ -6800,12 +7363,7 @@ var createSpoolQueue = (options) => {
|
|
|
6800
7363
|
let failed = 0;
|
|
6801
7364
|
let quarantined = 0;
|
|
6802
7365
|
let index = 0;
|
|
6803
|
-
|
|
6804
|
-
const fileName = files[index];
|
|
6805
|
-
if (fileName === void 0) {
|
|
6806
|
-
break;
|
|
6807
|
-
}
|
|
6808
|
-
const filePath = path6.join(queueDir, fileName);
|
|
7366
|
+
const sendClaimed = async (fileName, filePath, claimPath, token) => {
|
|
6809
7367
|
const quarantine = async (rejection) => {
|
|
6810
7368
|
quarantined += 1;
|
|
6811
7369
|
options.logger?.error("durable spool quarantined an unusable batch", {
|
|
@@ -6814,17 +7372,27 @@ var createSpoolQueue = (options) => {
|
|
|
6814
7372
|
"spool.queue": options.queueName
|
|
6815
7373
|
});
|
|
6816
7374
|
try {
|
|
6817
|
-
await rename2(filePath,
|
|
7375
|
+
await rename2(filePath, path7.join(corruptDir, fileName));
|
|
6818
7376
|
} catch {
|
|
6819
7377
|
await unlink2(filePath).catch(() => void 0);
|
|
6820
7378
|
}
|
|
6821
7379
|
};
|
|
7380
|
+
let text;
|
|
7381
|
+
try {
|
|
7382
|
+
text = await readFile2(filePath, "utf8");
|
|
7383
|
+
} catch (thrown) {
|
|
7384
|
+
if (thrown?.code === "ENOENT") {
|
|
7385
|
+
return "next";
|
|
7386
|
+
}
|
|
7387
|
+
await quarantine("unreadable");
|
|
7388
|
+
return "next";
|
|
7389
|
+
}
|
|
6822
7390
|
let parsed;
|
|
6823
7391
|
try {
|
|
6824
|
-
parsed = JSON.parse(
|
|
7392
|
+
parsed = JSON.parse(text);
|
|
6825
7393
|
} catch {
|
|
6826
7394
|
await quarantine("unparseable-json");
|
|
6827
|
-
|
|
7395
|
+
return "next";
|
|
6828
7396
|
}
|
|
6829
7397
|
const validation = options.validate(parsed, {
|
|
6830
7398
|
providerId: options.providerId,
|
|
@@ -6832,7 +7400,10 @@ var createSpoolQueue = (options) => {
|
|
|
6832
7400
|
});
|
|
6833
7401
|
if ("rejection" in validation) {
|
|
6834
7402
|
await quarantine(validation.rejection);
|
|
6835
|
-
|
|
7403
|
+
return "next";
|
|
7404
|
+
}
|
|
7405
|
+
if ((await readClaim(claimPath))?.token !== token) {
|
|
7406
|
+
return "next";
|
|
6836
7407
|
}
|
|
6837
7408
|
let delivered;
|
|
6838
7409
|
try {
|
|
@@ -6844,13 +7415,34 @@ var createSpoolQueue = (options) => {
|
|
|
6844
7415
|
if (await unlink2(filePath).then(() => true, () => false)) {
|
|
6845
7416
|
await recordDrops("rejected", 1);
|
|
6846
7417
|
}
|
|
6847
|
-
|
|
7418
|
+
return "next";
|
|
6848
7419
|
}
|
|
6849
7420
|
if (delivered) {
|
|
6850
7421
|
await unlink2(filePath).catch(() => void 0);
|
|
6851
7422
|
drained += 1;
|
|
6852
|
-
|
|
6853
|
-
|
|
7423
|
+
return "next";
|
|
7424
|
+
}
|
|
7425
|
+
failed += 1;
|
|
7426
|
+
return "stop";
|
|
7427
|
+
};
|
|
7428
|
+
for (; index < files.length && index < cap; index += 1) {
|
|
7429
|
+
const fileName = files[index];
|
|
7430
|
+
if (fileName === void 0) {
|
|
7431
|
+
break;
|
|
7432
|
+
}
|
|
7433
|
+
const filePath = path7.join(queueDir, fileName);
|
|
7434
|
+
const claimPath = `${filePath}${CLAIM_SUFFIX}`;
|
|
7435
|
+
const token = await claimBatch(claimPath);
|
|
7436
|
+
if (token === void 0) {
|
|
7437
|
+
continue;
|
|
7438
|
+
}
|
|
7439
|
+
let outcome;
|
|
7440
|
+
try {
|
|
7441
|
+
outcome = await sendClaimed(fileName, filePath, claimPath, token);
|
|
7442
|
+
} finally {
|
|
7443
|
+
await releaseClaim(claimPath, token);
|
|
7444
|
+
}
|
|
7445
|
+
if (outcome === "stop") {
|
|
6854
7446
|
break;
|
|
6855
7447
|
}
|
|
6856
7448
|
}
|
|
@@ -7144,9 +7736,220 @@ var createFileDurableSpool = (options) => createSpoolQueue({
|
|
|
7144
7736
|
validate: validateSpoolBatch
|
|
7145
7737
|
});
|
|
7146
7738
|
|
|
7739
|
+
// src/telemetry/endpoint-health.ts
|
|
7740
|
+
import { createHash as createHash8, randomBytes as randomBytes4 } from "crypto";
|
|
7741
|
+
import { mkdir as mkdir3, readFile as readFile3, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "fs/promises";
|
|
7742
|
+
import * as http from "http";
|
|
7743
|
+
import * as https from "https";
|
|
7744
|
+
import path8 from "path";
|
|
7745
|
+
import { ExportResultCode } from "@opentelemetry/core";
|
|
7746
|
+
var ENDPOINT_DOWN_ERROR_CODE = "OTEL_HOOK_ENDPOINT_DOWN";
|
|
7747
|
+
var UNREACHABLE_NETWORK_CODES = /* @__PURE__ */ new Set([
|
|
7748
|
+
"ECONNREFUSED",
|
|
7749
|
+
"ECONNRESET",
|
|
7750
|
+
"ETIMEDOUT",
|
|
7751
|
+
"EPIPE",
|
|
7752
|
+
"EHOSTUNREACH",
|
|
7753
|
+
"ENETUNREACH",
|
|
7754
|
+
"EHOSTDOWN",
|
|
7755
|
+
"ENETDOWN",
|
|
7756
|
+
"EAI_AGAIN",
|
|
7757
|
+
"ENOTFOUND",
|
|
7758
|
+
ENDPOINT_DOWN_ERROR_CODE
|
|
7759
|
+
]);
|
|
7760
|
+
var isUnreachableExportFailure = (result) => {
|
|
7761
|
+
if (result.code === ExportResultCode.SUCCESS) {
|
|
7762
|
+
return false;
|
|
7763
|
+
}
|
|
7764
|
+
const error = result.error;
|
|
7765
|
+
const code = error?.code;
|
|
7766
|
+
if (typeof code === "string") {
|
|
7767
|
+
return UNREACHABLE_NETWORK_CODES.has(code);
|
|
7768
|
+
}
|
|
7769
|
+
if (code !== void 0) {
|
|
7770
|
+
return false;
|
|
7771
|
+
}
|
|
7772
|
+
return typeof error?.message === "string" && /timed out/i.test(error.message);
|
|
7773
|
+
};
|
|
7774
|
+
var withConnectTimeout = (agent, connectTimeoutMillis) => {
|
|
7775
|
+
const target = agent;
|
|
7776
|
+
const original = target.createConnection.bind(agent);
|
|
7777
|
+
target.createConnection = (options, callback) => {
|
|
7778
|
+
const socket = original(options, callback);
|
|
7779
|
+
if (socket !== void 0 && socket.connecting) {
|
|
7780
|
+
const timer = setTimeout(() => {
|
|
7781
|
+
const error = Object.assign(new Error("connect timed out"), { code: "ETIMEDOUT" });
|
|
7782
|
+
socket.destroy(error);
|
|
7783
|
+
}, connectTimeoutMillis);
|
|
7784
|
+
timer.unref();
|
|
7785
|
+
const clear = () => {
|
|
7786
|
+
clearTimeout(timer);
|
|
7787
|
+
};
|
|
7788
|
+
socket.once("connect", clear);
|
|
7789
|
+
socket.once("close", clear);
|
|
7790
|
+
}
|
|
7791
|
+
return socket;
|
|
7792
|
+
};
|
|
7793
|
+
return agent;
|
|
7794
|
+
};
|
|
7795
|
+
var boundedExporterOptions = (exporter) => {
|
|
7796
|
+
const timeoutMillis = effectiveExportTimeoutMillis(exporter);
|
|
7797
|
+
let agents = {};
|
|
7798
|
+
return {
|
|
7799
|
+
timeoutMillis,
|
|
7800
|
+
httpAgentOptions: (protocol) => {
|
|
7801
|
+
if (protocol === "https:") {
|
|
7802
|
+
agents = { ...agents, https: agents.https ?? withConnectTimeout(new https.Agent({ keepAlive: true }), timeoutMillis) };
|
|
7803
|
+
return agents.https;
|
|
7804
|
+
}
|
|
7805
|
+
agents = { ...agents, http: agents.http ?? withConnectTimeout(new http.Agent({ keepAlive: true }), timeoutMillis) };
|
|
7806
|
+
return agents.http;
|
|
7807
|
+
}
|
|
7808
|
+
};
|
|
7809
|
+
};
|
|
7810
|
+
var parseMark = (raw) => {
|
|
7811
|
+
try {
|
|
7812
|
+
const parsed = JSON.parse(raw);
|
|
7813
|
+
return typeof parsed.downUntil === "number" && Number.isFinite(parsed.downUntil) ? {
|
|
7814
|
+
downUntil: parsed.downUntil,
|
|
7815
|
+
failures: typeof parsed.failures === "number" && Number.isInteger(parsed.failures) ? parsed.failures : 1
|
|
7816
|
+
} : void 0;
|
|
7817
|
+
} catch {
|
|
7818
|
+
return void 0;
|
|
7819
|
+
}
|
|
7820
|
+
};
|
|
7821
|
+
var originOf = (url) => {
|
|
7822
|
+
if (url === void 0) {
|
|
7823
|
+
return void 0;
|
|
7824
|
+
}
|
|
7825
|
+
try {
|
|
7826
|
+
return new URL(url).origin;
|
|
7827
|
+
} catch {
|
|
7828
|
+
return void 0;
|
|
7829
|
+
}
|
|
7830
|
+
};
|
|
7831
|
+
var createEndpointHealth = (options) => {
|
|
7832
|
+
const downMillis = options.downMillis ?? DEFAULT_ENDPOINT_DOWN_MILLIS;
|
|
7833
|
+
const gates = /* @__PURE__ */ new Map();
|
|
7834
|
+
const createGate = (origin) => {
|
|
7835
|
+
const digest3 = createHash8("sha256").update(origin, "utf8").digest("hex").slice(0, 32);
|
|
7836
|
+
const dir = options.rootDir === void 0 ? void 0 : path8.join(options.rootDir, "endpoint-health");
|
|
7837
|
+
const file = dir === void 0 ? void 0 : path8.join(dir, `${digest3}.json`);
|
|
7838
|
+
let downUntil = 0;
|
|
7839
|
+
let failures = 0;
|
|
7840
|
+
let marked = false;
|
|
7841
|
+
let loaded;
|
|
7842
|
+
let warned = false;
|
|
7843
|
+
const write = async (mark) => {
|
|
7844
|
+
if (file === void 0 || dir === void 0) {
|
|
7845
|
+
return;
|
|
7846
|
+
}
|
|
7847
|
+
try {
|
|
7848
|
+
await mkdir3(dir, { recursive: true });
|
|
7849
|
+
const tmp = path8.join(dir, `.tmp-${randomBytes4(6).toString("hex")}.json`);
|
|
7850
|
+
await writeFile3(tmp, `${JSON.stringify(mark)}
|
|
7851
|
+
`);
|
|
7852
|
+
await rename3(tmp, file);
|
|
7853
|
+
marked = true;
|
|
7854
|
+
} catch {
|
|
7855
|
+
}
|
|
7856
|
+
};
|
|
7857
|
+
const load = () => {
|
|
7858
|
+
loaded ??= (async () => {
|
|
7859
|
+
if (file === void 0) {
|
|
7860
|
+
return;
|
|
7861
|
+
}
|
|
7862
|
+
let raw;
|
|
7863
|
+
try {
|
|
7864
|
+
raw = await readFile3(file, "utf8");
|
|
7865
|
+
} catch {
|
|
7866
|
+
return;
|
|
7867
|
+
}
|
|
7868
|
+
marked = true;
|
|
7869
|
+
const mark = parseMark(raw);
|
|
7870
|
+
if (mark === void 0) {
|
|
7871
|
+
return;
|
|
7872
|
+
}
|
|
7873
|
+
failures = mark.failures;
|
|
7874
|
+
const now = options.clock.now();
|
|
7875
|
+
if (mark.downUntil > now) {
|
|
7876
|
+
downUntil = mark.downUntil;
|
|
7877
|
+
return;
|
|
7878
|
+
}
|
|
7879
|
+
await write({ downUntil: now + options.probeMillis, failures });
|
|
7880
|
+
})();
|
|
7881
|
+
return loaded;
|
|
7882
|
+
};
|
|
7883
|
+
return {
|
|
7884
|
+
available: async () => {
|
|
7885
|
+
if (downMillis === 0) {
|
|
7886
|
+
return true;
|
|
7887
|
+
}
|
|
7888
|
+
await load();
|
|
7889
|
+
return options.clock.now() >= downUntil;
|
|
7890
|
+
},
|
|
7891
|
+
record: async (result) => {
|
|
7892
|
+
if (downMillis === 0) {
|
|
7893
|
+
return;
|
|
7894
|
+
}
|
|
7895
|
+
if (!isUnreachableExportFailure(result)) {
|
|
7896
|
+
if (!marked && downUntil === 0) {
|
|
7897
|
+
return;
|
|
7898
|
+
}
|
|
7899
|
+
downUntil = 0;
|
|
7900
|
+
failures = 0;
|
|
7901
|
+
marked = false;
|
|
7902
|
+
if (file !== void 0) {
|
|
7903
|
+
await unlink3(file).catch(() => void 0);
|
|
7904
|
+
}
|
|
7905
|
+
return;
|
|
7906
|
+
}
|
|
7907
|
+
failures += 1;
|
|
7908
|
+
downUntil = options.clock.now() + downMillis;
|
|
7909
|
+
if (!warned) {
|
|
7910
|
+
warned = true;
|
|
7911
|
+
options.logger?.warn("export endpoint unreachable; hooks spool for it without trying until it is probed again", {
|
|
7912
|
+
"export.endpoint_down_millis": downMillis,
|
|
7913
|
+
"export.endpoint_failures": failures
|
|
7914
|
+
});
|
|
7915
|
+
}
|
|
7916
|
+
await write({ downUntil, failures });
|
|
7917
|
+
}
|
|
7918
|
+
};
|
|
7919
|
+
};
|
|
7920
|
+
return {
|
|
7921
|
+
gateFor: (url) => {
|
|
7922
|
+
const origin = originOf(url);
|
|
7923
|
+
if (origin === void 0) {
|
|
7924
|
+
return void 0;
|
|
7925
|
+
}
|
|
7926
|
+
let gate = gates.get(origin);
|
|
7927
|
+
if (gate === void 0) {
|
|
7928
|
+
gate = createGate(origin);
|
|
7929
|
+
gates.set(origin, gate);
|
|
7930
|
+
}
|
|
7931
|
+
return gate;
|
|
7932
|
+
}
|
|
7933
|
+
};
|
|
7934
|
+
};
|
|
7935
|
+
var guardExport = async (gate, send) => {
|
|
7936
|
+
if (gate === void 0) {
|
|
7937
|
+
return send();
|
|
7938
|
+
}
|
|
7939
|
+
if (!await gate.available()) {
|
|
7940
|
+
return {
|
|
7941
|
+
code: ExportResultCode.FAILED,
|
|
7942
|
+
error: Object.assign(new Error("endpoint marked down; batch not sent"), { code: ENDPOINT_DOWN_ERROR_CODE })
|
|
7943
|
+
};
|
|
7944
|
+
}
|
|
7945
|
+
const result = await send();
|
|
7946
|
+
await gate.record(result).catch(() => void 0);
|
|
7947
|
+
return result;
|
|
7948
|
+
};
|
|
7949
|
+
|
|
7147
7950
|
// src/telemetry/otlp-log-sink.ts
|
|
7148
7951
|
import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
|
|
7149
|
-
import { ExportResultCode } from "@opentelemetry/core";
|
|
7952
|
+
import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
|
|
7150
7953
|
import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
|
|
7151
7954
|
import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
|
|
7152
7955
|
|
|
@@ -7727,12 +8530,16 @@ var createOtlpLogSink = (options) => {
|
|
|
7727
8530
|
const exporter = new OTLPLogExporter({
|
|
7728
8531
|
url: deliverability.endpoint,
|
|
7729
8532
|
headers: { ...options.headers },
|
|
7730
|
-
|
|
8533
|
+
...boundedExporterOptions(options.exporter)
|
|
7731
8534
|
});
|
|
8535
|
+
const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
|
|
7732
8536
|
let shutdownCompleted = false;
|
|
7733
|
-
const exportRecords = (records) =>
|
|
7734
|
-
|
|
7735
|
-
|
|
8537
|
+
const exportRecords = (records) => guardExport(
|
|
8538
|
+
gate,
|
|
8539
|
+
() => new Promise((resolve3) => {
|
|
8540
|
+
exporter.export([...records], (result) => resolve3(result));
|
|
8541
|
+
})
|
|
8542
|
+
);
|
|
7736
8543
|
const toSpoolBatch = (records, batchResource) => ({
|
|
7737
8544
|
providerId: options.providerId,
|
|
7738
8545
|
installationId: options.installationId,
|
|
@@ -7750,7 +8557,7 @@ var createOtlpLogSink = (options) => {
|
|
|
7750
8557
|
(record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
|
|
7751
8558
|
);
|
|
7752
8559
|
const result = await exportRecords(records);
|
|
7753
|
-
if (result.code ===
|
|
8560
|
+
if (result.code === ExportResultCode2.SUCCESS) {
|
|
7754
8561
|
return true;
|
|
7755
8562
|
}
|
|
7756
8563
|
return isPermanentExportFailure(result) ? "discard" : false;
|
|
@@ -7796,11 +8603,11 @@ var createOtlpLogSink = (options) => {
|
|
|
7796
8603
|
result = await exportRecords(batch);
|
|
7797
8604
|
} catch (thrown) {
|
|
7798
8605
|
result = {
|
|
7799
|
-
code:
|
|
8606
|
+
code: ExportResultCode2.FAILED,
|
|
7800
8607
|
error: thrown instanceof Error ? thrown : new Error("export threw")
|
|
7801
8608
|
};
|
|
7802
8609
|
}
|
|
7803
|
-
if (result.code ===
|
|
8610
|
+
if (result.code === ExportResultCode2.SUCCESS) {
|
|
7804
8611
|
accepted += batch.length;
|
|
7805
8612
|
health.recordSuccess(batch.length, options.clock.now());
|
|
7806
8613
|
continue;
|
|
@@ -7841,6 +8648,9 @@ var createOtlpLogSink = (options) => {
|
|
|
7841
8648
|
if (options.spool === void 0) {
|
|
7842
8649
|
return { drained: 0, remaining: 0, failed: 0 };
|
|
7843
8650
|
}
|
|
8651
|
+
if (gate !== void 0 && !await gate.available()) {
|
|
8652
|
+
return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
|
|
8653
|
+
}
|
|
7844
8654
|
const result = await options.spool.drain(sendSerializedBatch, {
|
|
7845
8655
|
...maxBatches === void 0 ? {} : { maxBatches }
|
|
7846
8656
|
});
|
|
@@ -7878,7 +8688,7 @@ var createOtlpLogSink = (options) => {
|
|
|
7878
8688
|
|
|
7879
8689
|
// src/telemetry/otlp-metric-sink.ts
|
|
7880
8690
|
import { ValueType } from "@opentelemetry/api";
|
|
7881
|
-
import { ExportResultCode as
|
|
8691
|
+
import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
|
|
7882
8692
|
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
|
|
7883
8693
|
import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
|
|
7884
8694
|
import {
|
|
@@ -8022,10 +8832,12 @@ var createOtlpMetricSink = (options) => {
|
|
|
8022
8832
|
const exporter = new OTLPMetricExporter({
|
|
8023
8833
|
url: deliverability.endpoint,
|
|
8024
8834
|
headers: { ...options.headers },
|
|
8025
|
-
|
|
8835
|
+
...boundedExporterOptions(options.exporter)
|
|
8026
8836
|
});
|
|
8837
|
+
const gate = options.endpointHealth?.gateFor(deliverability.endpoint);
|
|
8027
8838
|
let shutdownCompleted = false;
|
|
8028
|
-
const exportResourceMetrics = (points, batchResource, batchScope) =>
|
|
8839
|
+
const exportResourceMetrics = (points, batchResource, batchScope) => guardExport(gate, () => sendResourceMetrics(points, batchResource, batchScope));
|
|
8840
|
+
const sendResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve3) => {
|
|
8029
8841
|
const payload = {
|
|
8030
8842
|
resource: batchResource,
|
|
8031
8843
|
scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
|
|
@@ -8034,7 +8846,7 @@ var createOtlpMetricSink = (options) => {
|
|
|
8034
8846
|
exporter.export(payload, (result) => resolve3(result));
|
|
8035
8847
|
} catch (thrown) {
|
|
8036
8848
|
resolve3({
|
|
8037
|
-
code:
|
|
8849
|
+
code: ExportResultCode3.FAILED,
|
|
8038
8850
|
error: thrown instanceof Error ? thrown : new Error("export threw")
|
|
8039
8851
|
});
|
|
8040
8852
|
}
|
|
@@ -8055,7 +8867,7 @@ var createOtlpMetricSink = (options) => {
|
|
|
8055
8867
|
withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
|
|
8056
8868
|
);
|
|
8057
8869
|
const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
|
|
8058
|
-
if (result.code ===
|
|
8870
|
+
if (result.code === ExportResultCode3.SUCCESS) {
|
|
8059
8871
|
return true;
|
|
8060
8872
|
}
|
|
8061
8873
|
return isPermanentExportFailure(result) ? "discard" : false;
|
|
@@ -8066,7 +8878,7 @@ var createOtlpMetricSink = (options) => {
|
|
|
8066
8878
|
}
|
|
8067
8879
|
const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
|
|
8068
8880
|
const result = await exportResourceMetrics(points, batchResource, scope);
|
|
8069
|
-
if (result.code ===
|
|
8881
|
+
if (result.code === ExportResultCode3.SUCCESS) {
|
|
8070
8882
|
health.recordSuccess(points.length, options.clock.now());
|
|
8071
8883
|
return { accepted: points.length, rejected: 0, errors: [] };
|
|
8072
8884
|
}
|
|
@@ -8106,6 +8918,9 @@ var createOtlpMetricSink = (options) => {
|
|
|
8106
8918
|
if (options.spool === void 0) {
|
|
8107
8919
|
return { drained: 0, remaining: 0, failed: 0 };
|
|
8108
8920
|
}
|
|
8921
|
+
if (gate !== void 0 && !await gate.available()) {
|
|
8922
|
+
return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
|
|
8923
|
+
}
|
|
8109
8924
|
const result = await options.spool.drain(sendSerializedBatch, {
|
|
8110
8925
|
...maxBatches === void 0 ? {} : { maxBatches }
|
|
8111
8926
|
});
|
|
@@ -8143,7 +8958,7 @@ var createOtlpMetricSink = (options) => {
|
|
|
8143
8958
|
};
|
|
8144
8959
|
|
|
8145
8960
|
// src/telemetry/otlp-sink.ts
|
|
8146
|
-
import { ExportResultCode as
|
|
8961
|
+
import { ExportResultCode as ExportResultCode4 } from "@opentelemetry/core";
|
|
8147
8962
|
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
|
|
8148
8963
|
var chunk2 = (items, size) => {
|
|
8149
8964
|
if (size <= 0 || items.length <= size) {
|
|
@@ -8221,12 +9036,16 @@ var createOtlpTraceSink = (options) => {
|
|
|
8221
9036
|
const exporter = new OTLPTraceExporter({
|
|
8222
9037
|
url: options.exporter.endpoint,
|
|
8223
9038
|
headers: { ...options.headers },
|
|
8224
|
-
|
|
9039
|
+
...boundedExporterOptions(options.exporter)
|
|
8225
9040
|
});
|
|
9041
|
+
const gate = options.endpointHealth?.gateFor(options.exporter.endpoint);
|
|
8226
9042
|
let shutdownCompleted = false;
|
|
8227
|
-
const exportSpans = (spans) =>
|
|
8228
|
-
|
|
8229
|
-
|
|
9043
|
+
const exportSpans = (spans) => guardExport(
|
|
9044
|
+
gate,
|
|
9045
|
+
() => new Promise((resolve3) => {
|
|
9046
|
+
exporter.export([...spans], (result) => resolve3(result));
|
|
9047
|
+
})
|
|
9048
|
+
);
|
|
8230
9049
|
const toSpoolBatch = (spans, batchResource) => ({
|
|
8231
9050
|
providerId: options.providerId,
|
|
8232
9051
|
installationId: options.installationId,
|
|
@@ -8239,7 +9058,7 @@ var createOtlpTraceSink = (options) => {
|
|
|
8239
9058
|
const batchResource = replayResource(batch.resourceAttributes, options.exporter);
|
|
8240
9059
|
const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
|
|
8241
9060
|
const result = await exportSpans(spans);
|
|
8242
|
-
if (result.code ===
|
|
9061
|
+
if (result.code === ExportResultCode4.SUCCESS) {
|
|
8243
9062
|
return true;
|
|
8244
9063
|
}
|
|
8245
9064
|
return isPermanentExportFailure(result) ? "discard" : false;
|
|
@@ -8278,9 +9097,9 @@ var createOtlpTraceSink = (options) => {
|
|
|
8278
9097
|
try {
|
|
8279
9098
|
result = await exportSpans(batch);
|
|
8280
9099
|
} catch (thrown) {
|
|
8281
|
-
result = { code:
|
|
9100
|
+
result = { code: ExportResultCode4.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
|
|
8282
9101
|
}
|
|
8283
|
-
if (result.code ===
|
|
9102
|
+
if (result.code === ExportResultCode4.SUCCESS) {
|
|
8284
9103
|
accepted += batch.length;
|
|
8285
9104
|
health.recordSuccess(batch.length, options.clock.now());
|
|
8286
9105
|
continue;
|
|
@@ -8317,6 +9136,9 @@ var createOtlpTraceSink = (options) => {
|
|
|
8317
9136
|
if (options.spool === void 0) {
|
|
8318
9137
|
return { drained: 0, remaining: 0, failed: 0 };
|
|
8319
9138
|
}
|
|
9139
|
+
if (gate !== void 0 && !await gate.available()) {
|
|
9140
|
+
return { drained: 0, remaining: await options.spool.size().catch(() => 0), failed: 0 };
|
|
9141
|
+
}
|
|
8320
9142
|
const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
|
|
8321
9143
|
if (result.drained > 0) {
|
|
8322
9144
|
health.recordSuccess(result.drained, options.clock.now());
|
|
@@ -8451,6 +9273,13 @@ var createExportDestinationSinks = (options) => {
|
|
|
8451
9273
|
const spoolPolicy = effectiveSpoolPolicy(options.exporter);
|
|
8452
9274
|
const destinations = [];
|
|
8453
9275
|
const skipped = [];
|
|
9276
|
+
const endpointHealth = options.endpointHealth ?? createEndpointHealth({
|
|
9277
|
+
...options.spoolRootDir === void 0 ? {} : { rootDir: options.spoolRootDir },
|
|
9278
|
+
clock: options.clock,
|
|
9279
|
+
...options.logger === void 0 ? {} : { logger: options.logger },
|
|
9280
|
+
...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
|
|
9281
|
+
probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
|
|
9282
|
+
});
|
|
8454
9283
|
for (const destination of resolveExportDestinations(options.exporter)) {
|
|
8455
9284
|
let headers;
|
|
8456
9285
|
let logHeaders;
|
|
@@ -8510,6 +9339,7 @@ var createExportDestinationSinks = (options) => {
|
|
|
8510
9339
|
const sinkShared = {
|
|
8511
9340
|
exporter: policy,
|
|
8512
9341
|
...shared,
|
|
9342
|
+
endpointHealth,
|
|
8513
9343
|
...options.correlate === void 0 ? {} : { correlate: options.correlate },
|
|
8514
9344
|
...label === void 0 ? {} : { destination: label }
|
|
8515
9345
|
};
|
|
@@ -8527,6 +9357,7 @@ var createExportDestinationSinks = (options) => {
|
|
|
8527
9357
|
const metrics = destination.signals.metrics ? createOtlpMetricSink({
|
|
8528
9358
|
exporter: policy,
|
|
8529
9359
|
...shared,
|
|
9360
|
+
endpointHealth,
|
|
8530
9361
|
...label === void 0 ? {} : { destination: label },
|
|
8531
9362
|
...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
|
|
8532
9363
|
...metricSpool === void 0 ? {} : { spool: metricSpool }
|
|
@@ -8696,7 +9527,14 @@ var createHookRuntime = (options) => {
|
|
|
8696
9527
|
privacy,
|
|
8697
9528
|
logger,
|
|
8698
9529
|
installationId: options.installationId,
|
|
8699
|
-
payloadEnrichers: options.payloadEnrichers ??
|
|
9530
|
+
payloadEnrichers: options.payloadEnrichers ?? [
|
|
9531
|
+
...readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : [],
|
|
9532
|
+
...readsCodexRolloutUsage(options.config) ? [
|
|
9533
|
+
createCodexRolloutUsageEnricher(
|
|
9534
|
+
options.codexSessionsRoot === void 0 ? {} : { sessionsRoot: options.codexSessionsRoot }
|
|
9535
|
+
)
|
|
9536
|
+
] : []
|
|
9537
|
+
],
|
|
8700
9538
|
...(() => {
|
|
8701
9539
|
if (options.sessionContextReader === null) {
|
|
8702
9540
|
return {};
|