@osfactory/otel-hook 0.10.0 → 0.12.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/README.md +108 -4
- package/dist/{adapter-B9RwW6TO.d.ts → adapter-DQiPu8xF.d.ts} +2 -2
- package/dist/cli.js +1495 -135
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +11 -4
- package/dist/config.js +116 -21
- package/dist/config.js.map +1 -1
- package/dist/{destinations-DWOkVxV1.d.ts → destinations-DvqsPulb.d.ts} +12 -2
- package/dist/diagnostics.d.ts +1 -1
- package/dist/diagnostics.js.map +1 -1
- package/dist/{events-CSD_YiJ2.d.ts → events-fcomX6d5.d.ts} +22 -0
- package/dist/{export-destinations-lORbe25J.d.ts → export-destinations-CI7z4n3i.d.ts} +136 -6
- package/dist/{filesystem-store-DX3dGIgu.d.ts → filesystem-store-CmnUlj1O.d.ts} +1 -1
- package/dist/{hook-BAxXoKsp.d.ts → hook-vM_cgqS2.d.ts} +11 -5
- package/dist/index.d.ts +16 -16
- package/dist/index.js +1496 -183
- package/dist/index.js.map +1 -1
- package/dist/install.d.ts +4 -4
- package/dist/install.js +9 -1
- package/dist/install.js.map +1 -1
- package/dist/integration.d.ts +36 -12
- package/dist/integration.js +1464 -231
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.d.ts +55 -4
- package/dist/lifecycle.js +279 -5
- package/dist/lifecycle.js.map +1 -1
- package/dist/{memory-aJilVG4R.d.ts → memory-DdU1U91y.d.ts} +2 -2
- package/dist/{semconv-Dw7gcQcg.d.ts → metric-model-C9lLqqpI.d.ts} +157 -2
- package/dist/model.d.ts +1 -1
- package/dist/model.js +9 -1
- package/dist/model.js.map +1 -1
- package/dist/{payload-D7gc0-WQ.d.ts → payload-BT19hiVZ.d.ts} +1 -1
- package/dist/{ports-plO5MKrY.d.ts → ports-C3k_5eOQ.d.ts} +57 -2
- package/dist/providers.d.ts +10 -10
- package/dist/providers.js +10 -1
- package/dist/providers.js.map +1 -1
- package/dist/{registry-C7XO4DzD.d.ts → registry-gyJqaWmp.d.ts} +2 -2
- package/dist/runtime.d.ts +97 -9
- package/dist/runtime.js +312 -33
- package/dist/runtime.js.map +1 -1
- package/dist/{schema-CHb3GU1r.d.ts → schema-SpFM6YQY.d.ts} +87 -1
- package/dist/state.d.ts +4 -4
- package/dist/state.js +32 -1
- package/dist/state.js.map +1 -1
- package/dist/telemetry.d.ts +6 -6
- package/dist/telemetry.js +929 -31
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.d.ts +11 -9
- package/dist/testing.js +164 -33
- package/dist/testing.js.map +1 -1
- package/package.json +3 -1
package/dist/runtime.js
CHANGED
|
@@ -808,7 +808,15 @@ var baseEventFields = {
|
|
|
808
808
|
* factory, never by hand.
|
|
809
809
|
*/
|
|
810
810
|
subagentId: subagentIdSchema.optional(),
|
|
811
|
-
extensions: extensionsSchema.default(emptyExtensions)
|
|
811
|
+
extensions: extensionsSchema.default(emptyExtensions),
|
|
812
|
+
/**
|
|
813
|
+
* Attributes of the session context segment in force when the event
|
|
814
|
+
* occurred (`docs/session-context.md`), stamped by the core from a file a
|
|
815
|
+
* harness wrote. Exported on every record of the event, over the same keys
|
|
816
|
+
* from the Resource. Absent when no context applies. Set by the core only,
|
|
817
|
+
* never by an adapter.
|
|
818
|
+
*/
|
|
819
|
+
contextAttributes: z9.record(z9.string().min(1).max(255), z9.union([z9.string(), z9.number(), z9.boolean()])).optional()
|
|
812
820
|
};
|
|
813
821
|
var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
|
|
814
822
|
var sessionStartEventSchema = event({
|
|
@@ -985,6 +993,29 @@ var stateValueSchema = z10.discriminatedUnion("kind", [
|
|
|
985
993
|
* (Claude Code's transcript), so the next read starts where the last ended.
|
|
986
994
|
* `source` is an opaque digest of what was read, never a path.
|
|
987
995
|
*/
|
|
996
|
+
/**
|
|
997
|
+
* Running state of one metric series (issue #69), so a cumulative data point
|
|
998
|
+
* exported by a later hook process continues the same total. Holds numbers and
|
|
999
|
+
* a series digest only; the series' attributes are re-supplied by the caller
|
|
1000
|
+
* and never read back from disk.
|
|
1001
|
+
*/
|
|
1002
|
+
z10.strictObject({
|
|
1003
|
+
kind: z10.literal("metric-series"),
|
|
1004
|
+
/** Start of the cumulative interval. */
|
|
1005
|
+
startTimeMillis: epochMillisSchema,
|
|
1006
|
+
/** Counters: the running total. */
|
|
1007
|
+
value: z10.number().finite().min(0).optional(),
|
|
1008
|
+
/** Histograms: the running aggregation. */
|
|
1009
|
+
histogram: z10.strictObject({
|
|
1010
|
+
count: z10.number().int().min(0),
|
|
1011
|
+
sum: z10.number().finite().min(0),
|
|
1012
|
+
min: z10.number().finite(),
|
|
1013
|
+
max: z10.number().finite(),
|
|
1014
|
+
bucketCounts: z10.array(z10.number().int().min(0)).max(64)
|
|
1015
|
+
}).optional(),
|
|
1016
|
+
/** Opaque digest of the last delivery folded in; makes a replay a no-op. */
|
|
1017
|
+
appliedDelivery: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
|
|
1018
|
+
}),
|
|
988
1019
|
z10.strictObject({
|
|
989
1020
|
kind: z10.literal("read-cursor"),
|
|
990
1021
|
source: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
|
|
@@ -1330,9 +1361,10 @@ var resolveDeliveryIdentity = (input) => {
|
|
|
1330
1361
|
};
|
|
1331
1362
|
|
|
1332
1363
|
// src/runtime/hook.ts
|
|
1333
|
-
import { z as
|
|
1364
|
+
import { z as z18 } from "zod";
|
|
1334
1365
|
|
|
1335
1366
|
// src/config/schema.ts
|
|
1367
|
+
import { isAbsolute } from "path";
|
|
1336
1368
|
import { z as z15 } from "zod";
|
|
1337
1369
|
|
|
1338
1370
|
// src/privacy/policy.ts
|
|
@@ -1448,7 +1480,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
|
|
|
1448
1480
|
var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
|
|
1449
1481
|
var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
1450
1482
|
var MAX_HEADER_VALUE_LENGTH = 8192;
|
|
1451
|
-
var exportSignalSchema = z13.enum(["traces", "logs"]);
|
|
1483
|
+
var exportSignalSchema = z13.enum(["traces", "logs", "metrics"]);
|
|
1452
1484
|
var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
|
|
1453
1485
|
(value) => !isUnsafeHeaderValue(value),
|
|
1454
1486
|
"header values may not contain line breaks, control characters, or characters beyond Latin-1"
|
|
@@ -1471,6 +1503,8 @@ var exportDestinationSchema = z13.strictObject({
|
|
|
1471
1503
|
tracesEndpoint: endpointSchema.optional(),
|
|
1472
1504
|
/** Per-signal override of the derived logs URL. */
|
|
1473
1505
|
logsEndpoint: endpointSchema.optional(),
|
|
1506
|
+
/** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
|
|
1507
|
+
metricsEndpoint: endpointSchema.optional(),
|
|
1474
1508
|
/** Defaults to `exporter.protocol`. */
|
|
1475
1509
|
protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
|
|
1476
1510
|
/**
|
|
@@ -1483,15 +1517,17 @@ var exportDestinationSchema = z13.strictObject({
|
|
|
1483
1517
|
`at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
|
|
1484
1518
|
).optional(),
|
|
1485
1519
|
/**
|
|
1486
|
-
* Which signals this destination receives. Default:
|
|
1487
|
-
* still governed by `exporter.logs.enabled`, which stays the one
|
|
1488
|
-
*
|
|
1520
|
+
* Which signals this destination receives. Default: traces and logs. The logs
|
|
1521
|
+
* signal is still governed by `exporter.logs.enabled`, which stays the one
|
|
1522
|
+
* opt-in for content-bearing records leaving the host. `metrics` is never on by
|
|
1523
|
+
* default: a destination receives hook-derived metrics only when it lists them.
|
|
1489
1524
|
*/
|
|
1490
|
-
signals: z13.array(exportSignalSchema).min(1).max(
|
|
1525
|
+
signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
|
|
1491
1526
|
}).refine(
|
|
1492
|
-
(destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
|
|
1493
|
-
"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
|
|
1527
|
+
(destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
|
|
1528
|
+
"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
|
|
1494
1529
|
);
|
|
1530
|
+
var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
|
|
1495
1531
|
var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
|
|
1496
1532
|
const seen = /* @__PURE__ */ new Set();
|
|
1497
1533
|
destinations.forEach((destination, index) => {
|
|
@@ -1616,6 +1652,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
|
|
|
1616
1652
|
includeContent: false,
|
|
1617
1653
|
maxBatchSize: 128
|
|
1618
1654
|
});
|
|
1655
|
+
var metricsPolicySchema = z15.strictObject({
|
|
1656
|
+
enabled: z15.boolean(),
|
|
1657
|
+
/** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
|
|
1658
|
+
endpoint: z15.string().url().max(2048).optional(),
|
|
1659
|
+
temporality: z15.enum(["cumulative", "delta"]),
|
|
1660
|
+
includeSessionId: z15.boolean()
|
|
1661
|
+
});
|
|
1662
|
+
var DEFAULT_METRICS_POLICY = Object.freeze({
|
|
1663
|
+
enabled: false,
|
|
1664
|
+
temporality: "cumulative",
|
|
1665
|
+
includeSessionId: true
|
|
1666
|
+
});
|
|
1619
1667
|
var exporterPolicySchema = z15.strictObject({
|
|
1620
1668
|
enabled: z15.boolean(),
|
|
1621
1669
|
protocol: z15.enum(["http/protobuf", "http/json", "none"]),
|
|
@@ -1646,6 +1694,11 @@ var exporterPolicySchema = z15.strictObject({
|
|
|
1646
1694
|
* a second top-level section would invite two of each to drift apart.
|
|
1647
1695
|
*/
|
|
1648
1696
|
logs: logsPolicySchema,
|
|
1697
|
+
/**
|
|
1698
|
+
* Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
|
|
1699
|
+
* metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
|
|
1700
|
+
*/
|
|
1701
|
+
metrics: metricsPolicySchema.optional(),
|
|
1649
1702
|
/**
|
|
1650
1703
|
* Additional OTLP destinations, each sent every batch in parallel.
|
|
1651
1704
|
*
|
|
@@ -1682,20 +1735,27 @@ var providersPolicySchema = z15.strictObject({
|
|
|
1682
1735
|
readTranscriptUsage: z15.boolean()
|
|
1683
1736
|
}).optional()
|
|
1684
1737
|
});
|
|
1738
|
+
var sessionContextPolicySchema = z15.strictObject({
|
|
1739
|
+
/** Absolute path of the context directory. */
|
|
1740
|
+
dir: z15.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
|
|
1741
|
+
});
|
|
1685
1742
|
var otelHookConfigSchema = z15.strictObject({
|
|
1686
1743
|
exporter: exporterPolicySchema,
|
|
1687
1744
|
privacy: privacyPolicySchema,
|
|
1688
1745
|
detection: detectionPolicySchema,
|
|
1689
1746
|
diagnostics: diagnosticsPolicySchema,
|
|
1690
1747
|
/** Optional so a hand-built configuration from before it existed stays valid. */
|
|
1691
|
-
providers: providersPolicySchema.optional()
|
|
1748
|
+
providers: providersPolicySchema.optional(),
|
|
1749
|
+
/** Optional: absent means no session context is read. */
|
|
1750
|
+
sessionContext: sessionContextPolicySchema.optional()
|
|
1692
1751
|
});
|
|
1693
1752
|
var otelHookConfigPatchSchema = z15.strictObject({
|
|
1694
1753
|
// `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
|
|
1695
1754
|
// merging happens per leaf, so a layer must be able to set `logs.enabled` alone
|
|
1696
1755
|
// without also restating the endpoint and the batch size.
|
|
1697
|
-
exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
|
|
1756
|
+
exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
|
|
1698
1757
|
logs: logsPolicySchema.partial().optional(),
|
|
1758
|
+
metrics: metricsPolicySchema.partial().optional(),
|
|
1699
1759
|
spool: spoolPolicySchema.partial().optional()
|
|
1700
1760
|
}).optional(),
|
|
1701
1761
|
privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
|
|
@@ -1703,7 +1763,8 @@ var otelHookConfigPatchSchema = z15.strictObject({
|
|
|
1703
1763
|
diagnostics: diagnosticsPolicySchema.partial().optional(),
|
|
1704
1764
|
providers: z15.strictObject({
|
|
1705
1765
|
claudeCode: z15.strictObject({ readTranscriptUsage: z15.boolean() }).partial().optional()
|
|
1706
|
-
}).partial().optional()
|
|
1766
|
+
}).partial().optional(),
|
|
1767
|
+
sessionContext: sessionContextPolicySchema.partial().optional()
|
|
1707
1768
|
});
|
|
1708
1769
|
var DEFAULT_EXPORTER_POLICY = Object.freeze({
|
|
1709
1770
|
enabled: true,
|
|
@@ -1715,7 +1776,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
|
|
|
1715
1776
|
maxRetryAttempts: 2,
|
|
1716
1777
|
serviceName: "coding-agent",
|
|
1717
1778
|
resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
|
|
1718
|
-
logs: DEFAULT_LOGS_POLICY
|
|
1779
|
+
logs: DEFAULT_LOGS_POLICY,
|
|
1780
|
+
metrics: DEFAULT_METRICS_POLICY
|
|
1719
1781
|
});
|
|
1720
1782
|
var DEFAULT_DETECTION_POLICY = Object.freeze({
|
|
1721
1783
|
minimumConfidence: "strong",
|
|
@@ -1956,11 +2018,11 @@ var createPrivacyService = (policyInput) => {
|
|
|
1956
2018
|
};
|
|
1957
2019
|
const flattenToAttributes = (value, prefix) => {
|
|
1958
2020
|
const attributes = {};
|
|
1959
|
-
const walk = (current,
|
|
2021
|
+
const walk = (current, path4) => {
|
|
1960
2022
|
if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
|
|
1961
2023
|
const primitive = toAttributePrimitive(current);
|
|
1962
2024
|
if (primitive !== void 0) {
|
|
1963
|
-
attributes[
|
|
2025
|
+
attributes[path4] = primitive;
|
|
1964
2026
|
}
|
|
1965
2027
|
return;
|
|
1966
2028
|
}
|
|
@@ -1979,16 +2041,16 @@ var createPrivacyService = (policyInput) => {
|
|
|
1979
2041
|
primitives.push(entryPrimitive);
|
|
1980
2042
|
}
|
|
1981
2043
|
if (uniform) {
|
|
1982
|
-
attributes[
|
|
2044
|
+
attributes[path4] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
|
|
1983
2045
|
return;
|
|
1984
2046
|
}
|
|
1985
2047
|
for (const [index, entry] of current.entries()) {
|
|
1986
|
-
walk(entry, `${
|
|
2048
|
+
walk(entry, `${path4}.${index}`);
|
|
1987
2049
|
}
|
|
1988
2050
|
return;
|
|
1989
2051
|
}
|
|
1990
2052
|
for (const [key, entry] of Object.entries(current)) {
|
|
1991
|
-
walk(entry,
|
|
2053
|
+
walk(entry, path4 === "" ? key : `${path4}.${key}`);
|
|
1992
2054
|
}
|
|
1993
2055
|
};
|
|
1994
2056
|
walk(value, prefix);
|
|
@@ -2507,8 +2569,200 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
|
|
|
2507
2569
|
return fn();
|
|
2508
2570
|
};
|
|
2509
2571
|
|
|
2572
|
+
// src/runtime/session-context.ts
|
|
2573
|
+
import { open } from "fs/promises";
|
|
2574
|
+
import * as path2 from "path";
|
|
2575
|
+
import { z as z17 } from "zod";
|
|
2576
|
+
var SESSION_CONTEXT_FILE_VERSION = 1;
|
|
2577
|
+
var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
|
|
2578
|
+
var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
|
|
2579
|
+
var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
|
|
2580
|
+
var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
|
|
2581
|
+
"claude-code": "claude_code",
|
|
2582
|
+
codex: "codex",
|
|
2583
|
+
cursor: "cursor",
|
|
2584
|
+
"gemini-cli": "gemini_cli",
|
|
2585
|
+
antigravity: "antigravity"
|
|
2586
|
+
});
|
|
2587
|
+
var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
|
|
2588
|
+
var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
|
|
2589
|
+
var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
|
|
2590
|
+
var sessionContextFilePath = (dir, providerId, sessionId) => {
|
|
2591
|
+
const tool = sessionContextAgentTool(providerId);
|
|
2592
|
+
if (tool === void 0 || !isSessionContextFileName(sessionId) || !path2.isAbsolute(dir)) {
|
|
2593
|
+
return void 0;
|
|
2594
|
+
}
|
|
2595
|
+
return path2.join(dir, tool, `${sessionId}.json`);
|
|
2596
|
+
};
|
|
2597
|
+
var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
|
|
2598
|
+
"session.id",
|
|
2599
|
+
"trace_id",
|
|
2600
|
+
"span_id",
|
|
2601
|
+
"parent_span_id",
|
|
2602
|
+
"gen_ai.conversation.id",
|
|
2603
|
+
"factory.local"
|
|
2604
|
+
]);
|
|
2605
|
+
var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
|
|
2606
|
+
var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
|
|
2607
|
+
var sanitizeSessionContextAttributes = (attributes) => {
|
|
2608
|
+
const kept = {};
|
|
2609
|
+
let count = 0;
|
|
2610
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
2611
|
+
if (count >= MAX_RESOURCE_ATTRIBUTES) {
|
|
2612
|
+
break;
|
|
2613
|
+
}
|
|
2614
|
+
if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
|
|
2615
|
+
continue;
|
|
2616
|
+
}
|
|
2617
|
+
if (typeof value === "string") {
|
|
2618
|
+
if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
|
|
2619
|
+
continue;
|
|
2620
|
+
}
|
|
2621
|
+
} else if (typeof value === "number") {
|
|
2622
|
+
if (!Number.isFinite(value)) {
|
|
2623
|
+
continue;
|
|
2624
|
+
}
|
|
2625
|
+
} else if (typeof value !== "boolean") {
|
|
2626
|
+
continue;
|
|
2627
|
+
}
|
|
2628
|
+
kept[key] = value;
|
|
2629
|
+
count += 1;
|
|
2630
|
+
}
|
|
2631
|
+
return kept;
|
|
2632
|
+
};
|
|
2633
|
+
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})$/;
|
|
2634
|
+
var isoInstantSchema = z17.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
|
|
2635
|
+
const millis = Date.parse(value);
|
|
2636
|
+
if (!Number.isFinite(millis)) {
|
|
2637
|
+
ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
|
|
2638
|
+
return z17.NEVER;
|
|
2639
|
+
}
|
|
2640
|
+
return millis;
|
|
2641
|
+
});
|
|
2642
|
+
var segmentSchema = z17.object({
|
|
2643
|
+
from: isoInstantSchema,
|
|
2644
|
+
to: isoInstantSchema.nullable(),
|
|
2645
|
+
reason: z17.string().max(256).optional(),
|
|
2646
|
+
attributes: z17.record(z17.string(), z17.unknown())
|
|
2647
|
+
});
|
|
2648
|
+
var sessionContextFileSchema = z17.object({
|
|
2649
|
+
version: z17.literal(SESSION_CONTEXT_FILE_VERSION),
|
|
2650
|
+
agentTool: z17.string().max(64).optional(),
|
|
2651
|
+
sessionId: z17.string().max(256).optional(),
|
|
2652
|
+
segments: z17.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
|
|
2653
|
+
});
|
|
2654
|
+
var parseSessionContextFile = (value, expected) => {
|
|
2655
|
+
const parsed = sessionContextFileSchema.safeParse(value);
|
|
2656
|
+
if (!parsed.success) {
|
|
2657
|
+
return void 0;
|
|
2658
|
+
}
|
|
2659
|
+
const file = parsed.data;
|
|
2660
|
+
if (expected?.agentTool !== void 0 && file.agentTool !== void 0 && file.agentTool !== expected.agentTool || expected?.sessionId !== void 0 && file.sessionId !== void 0 && file.sessionId !== expected.sessionId) {
|
|
2661
|
+
return void 0;
|
|
2662
|
+
}
|
|
2663
|
+
return file.segments.map((segment) => ({
|
|
2664
|
+
from: segment.from,
|
|
2665
|
+
to: segment.to,
|
|
2666
|
+
attributes: sanitizeSessionContextAttributes(segment.attributes)
|
|
2667
|
+
}));
|
|
2668
|
+
};
|
|
2669
|
+
var segmentInForce = (segments, at) => {
|
|
2670
|
+
let best;
|
|
2671
|
+
for (const segment of segments) {
|
|
2672
|
+
if (segment.from <= at && (segment.to === null || at < segment.to)) {
|
|
2673
|
+
if (best === void 0 || segment.from >= best.from) {
|
|
2674
|
+
best = segment;
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
return best;
|
|
2679
|
+
};
|
|
2680
|
+
var stampSessionContext = (events, segments) => events.map((event2) => {
|
|
2681
|
+
const { contextAttributes: _discarded, ...rest } = event2;
|
|
2682
|
+
const segment = segments === void 0 ? void 0 : segmentInForce(segments, event2.occurredAt);
|
|
2683
|
+
if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
|
|
2684
|
+
return _discarded === void 0 ? event2 : rest;
|
|
2685
|
+
}
|
|
2686
|
+
return { ...rest, contextAttributes: { ...segment.attributes } };
|
|
2687
|
+
});
|
|
2688
|
+
var readBounded = async (file, maxBytes) => {
|
|
2689
|
+
let handle;
|
|
2690
|
+
try {
|
|
2691
|
+
handle = await open(file, "r");
|
|
2692
|
+
} catch {
|
|
2693
|
+
return void 0;
|
|
2694
|
+
}
|
|
2695
|
+
try {
|
|
2696
|
+
const stats = await handle.stat();
|
|
2697
|
+
if (!stats.isFile() || stats.size > maxBytes) {
|
|
2698
|
+
return void 0;
|
|
2699
|
+
}
|
|
2700
|
+
const buffer = Buffer.alloc(maxBytes + 1);
|
|
2701
|
+
let length = 0;
|
|
2702
|
+
while (length < buffer.length) {
|
|
2703
|
+
const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
|
|
2704
|
+
if (bytesRead === 0) {
|
|
2705
|
+
break;
|
|
2706
|
+
}
|
|
2707
|
+
length += bytesRead;
|
|
2708
|
+
}
|
|
2709
|
+
if (length > maxBytes) {
|
|
2710
|
+
return void 0;
|
|
2711
|
+
}
|
|
2712
|
+
return buffer.subarray(0, length).toString("utf8");
|
|
2713
|
+
} catch {
|
|
2714
|
+
return void 0;
|
|
2715
|
+
} finally {
|
|
2716
|
+
await handle.close().catch(() => void 0);
|
|
2717
|
+
}
|
|
2718
|
+
};
|
|
2719
|
+
var createDirectorySessionContextReader = (options) => {
|
|
2720
|
+
const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
|
|
2721
|
+
const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
|
|
2722
|
+
const readOnce = async (providerId, sessionId) => {
|
|
2723
|
+
const file = sessionContextFilePath(options.dir, providerId, sessionId);
|
|
2724
|
+
if (file === void 0) {
|
|
2725
|
+
return void 0;
|
|
2726
|
+
}
|
|
2727
|
+
const text = await readBounded(file, maxBytes);
|
|
2728
|
+
if (text === void 0) {
|
|
2729
|
+
return void 0;
|
|
2730
|
+
}
|
|
2731
|
+
let decoded;
|
|
2732
|
+
try {
|
|
2733
|
+
decoded = JSON.parse(text);
|
|
2734
|
+
} catch {
|
|
2735
|
+
return void 0;
|
|
2736
|
+
}
|
|
2737
|
+
const agentTool = sessionContextAgentTool(providerId);
|
|
2738
|
+
return parseSessionContextFile(decoded, {
|
|
2739
|
+
...agentTool === void 0 ? {} : { agentTool },
|
|
2740
|
+
sessionId
|
|
2741
|
+
});
|
|
2742
|
+
};
|
|
2743
|
+
return {
|
|
2744
|
+
read: async (request) => {
|
|
2745
|
+
let timer;
|
|
2746
|
+
const timeout = new Promise((resolve3) => {
|
|
2747
|
+
timer = setTimeout(() => resolve3(void 0), budgetMillis);
|
|
2748
|
+
timer.unref?.();
|
|
2749
|
+
});
|
|
2750
|
+
try {
|
|
2751
|
+
return await Promise.race([
|
|
2752
|
+
readOnce(request.providerId, request.sessionId).catch(() => void 0),
|
|
2753
|
+
timeout
|
|
2754
|
+
]);
|
|
2755
|
+
} finally {
|
|
2756
|
+
if (timer !== void 0) {
|
|
2757
|
+
clearTimeout(timer);
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
2760
|
+
}
|
|
2761
|
+
};
|
|
2762
|
+
};
|
|
2763
|
+
|
|
2510
2764
|
// src/runtime/hook.ts
|
|
2511
|
-
var usageScopeSchema =
|
|
2765
|
+
var usageScopeSchema = z18.enum(["session", "generation", "subagent"]);
|
|
2512
2766
|
var classifyDurability = (input) => {
|
|
2513
2767
|
if (!input.attempted) {
|
|
2514
2768
|
return "nothing-to-deliver";
|
|
@@ -3217,6 +3471,10 @@ var createOtelHook = (deps) => {
|
|
|
3217
3471
|
});
|
|
3218
3472
|
}
|
|
3219
3473
|
}
|
|
3474
|
+
batch = stampSessionContext(
|
|
3475
|
+
batch,
|
|
3476
|
+
!suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
|
|
3477
|
+
);
|
|
3220
3478
|
let emitted = 0;
|
|
3221
3479
|
let exportRejected = 0;
|
|
3222
3480
|
if (!suppress && batch.length > 0) {
|
|
@@ -3332,6 +3590,13 @@ var createOtelHook = (deps) => {
|
|
|
3332
3590
|
};
|
|
3333
3591
|
return { resolveDelivery, ingest, flush, shutdown, config };
|
|
3334
3592
|
};
|
|
3593
|
+
var readSessionContext = async (reader, providerId, sessionId) => {
|
|
3594
|
+
try {
|
|
3595
|
+
return await reader.read({ providerId, sessionId });
|
|
3596
|
+
} catch {
|
|
3597
|
+
return void 0;
|
|
3598
|
+
}
|
|
3599
|
+
};
|
|
3335
3600
|
var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
|
|
3336
3601
|
const events = [];
|
|
3337
3602
|
for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
|
|
@@ -3366,8 +3631,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
|
|
|
3366
3631
|
};
|
|
3367
3632
|
|
|
3368
3633
|
// src/runtime/git-worktree.ts
|
|
3369
|
-
import { lstat, open, stat } from "fs/promises";
|
|
3370
|
-
import * as
|
|
3634
|
+
import { lstat, open as open2, stat } from "fs/promises";
|
|
3635
|
+
import * as path3 from "path";
|
|
3371
3636
|
var MAX_WORKTREE_WALK_DEPTH = 128;
|
|
3372
3637
|
var MAX_GIT_FILE_BYTES = 4096;
|
|
3373
3638
|
var MAX_CACHE_ENTRIES = 1024;
|
|
@@ -3375,10 +3640,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
|
|
|
3375
3640
|
var MAX_BRANCH_NAME_LENGTH = 255;
|
|
3376
3641
|
var ABSENT = Object.freeze({ kind: "absent" });
|
|
3377
3642
|
var INVALID = Object.freeze({ kind: "invalid" });
|
|
3378
|
-
var
|
|
3643
|
+
var readBounded2 = async (filePath) => {
|
|
3379
3644
|
let handle;
|
|
3380
3645
|
try {
|
|
3381
|
-
handle = await
|
|
3646
|
+
handle = await open2(filePath, "r");
|
|
3382
3647
|
const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
|
|
3383
3648
|
const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
|
|
3384
3649
|
return buffer.subarray(0, bytesRead).toString("utf8");
|
|
@@ -3399,7 +3664,7 @@ var parseHeadBranch = (head) => {
|
|
|
3399
3664
|
return branch;
|
|
3400
3665
|
};
|
|
3401
3666
|
var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
|
|
3402
|
-
var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 :
|
|
3667
|
+
var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
|
|
3403
3668
|
var parseGitDirFile = (content, worktreeRoot) => {
|
|
3404
3669
|
const line = firstLine(content);
|
|
3405
3670
|
return resolveGitPath(
|
|
@@ -3425,17 +3690,17 @@ var isDirectory = async (directory) => {
|
|
|
3425
3690
|
}
|
|
3426
3691
|
};
|
|
3427
3692
|
var repositoryOf = async (worktreeRoot, gitDir) => {
|
|
3428
|
-
const commonDirFile =
|
|
3429
|
-
const content = await
|
|
3693
|
+
const commonDirFile = path3.join(gitDir, "commondir");
|
|
3694
|
+
const content = await readBounded2(commonDirFile);
|
|
3430
3695
|
if (content === void 0) {
|
|
3431
3696
|
return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
|
|
3432
3697
|
}
|
|
3433
3698
|
const commonDir = parseCommonDirFile(content, gitDir);
|
|
3434
|
-
const mainRoot = commonDir !== void 0 &&
|
|
3699
|
+
const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
|
|
3435
3700
|
return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
|
|
3436
3701
|
};
|
|
3437
3702
|
var probeDirectory = async (directory) => {
|
|
3438
|
-
const dotGit =
|
|
3703
|
+
const dotGit = path3.join(directory, ".git");
|
|
3439
3704
|
let info;
|
|
3440
3705
|
try {
|
|
3441
3706
|
info = await stat(dotGit);
|
|
@@ -3446,13 +3711,13 @@ var probeDirectory = async (directory) => {
|
|
|
3446
3711
|
if (info.isDirectory()) {
|
|
3447
3712
|
gitDir = dotGit;
|
|
3448
3713
|
} else if (info.isFile()) {
|
|
3449
|
-
const content = await
|
|
3714
|
+
const content = await readBounded2(dotGit);
|
|
3450
3715
|
gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
|
|
3451
3716
|
}
|
|
3452
3717
|
if (gitDir === void 0) {
|
|
3453
3718
|
return INVALID;
|
|
3454
3719
|
}
|
|
3455
|
-
const head = await
|
|
3720
|
+
const head = await readBounded2(path3.join(gitDir, "HEAD"));
|
|
3456
3721
|
if (head === void 0) {
|
|
3457
3722
|
return INVALID;
|
|
3458
3723
|
}
|
|
@@ -3482,10 +3747,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
|
|
|
3482
3747
|
};
|
|
3483
3748
|
const locate = async (absolutePath) => {
|
|
3484
3749
|
try {
|
|
3485
|
-
if (!
|
|
3750
|
+
if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
|
|
3486
3751
|
return void 0;
|
|
3487
3752
|
}
|
|
3488
|
-
let directory =
|
|
3753
|
+
let directory = path3.resolve(absolutePath);
|
|
3489
3754
|
for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
|
|
3490
3755
|
const probe = await cachedProbe(directory);
|
|
3491
3756
|
if (probe.kind === "worktree") {
|
|
@@ -3494,7 +3759,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
|
|
|
3494
3759
|
if (probe.kind === "invalid") {
|
|
3495
3760
|
return void 0;
|
|
3496
3761
|
}
|
|
3497
|
-
const parent =
|
|
3762
|
+
const parent = path3.dirname(directory);
|
|
3498
3763
|
if (parent === directory) {
|
|
3499
3764
|
return void 0;
|
|
3500
3765
|
}
|
|
@@ -3508,13 +3773,19 @@ var createFilesystemWorktreeLocator = (options = {}) => {
|
|
|
3508
3773
|
return { locate };
|
|
3509
3774
|
};
|
|
3510
3775
|
export {
|
|
3776
|
+
DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS,
|
|
3777
|
+
DEFAULT_SESSION_CONTEXT_MAX_BYTES,
|
|
3511
3778
|
DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,
|
|
3512
3779
|
DEFAULT_WORKTREE_CACHE_TTL_MILLIS,
|
|
3513
3780
|
LOG_LEVEL_RANK,
|
|
3781
|
+
MAX_SESSION_CONTEXT_SEGMENTS,
|
|
3514
3782
|
MAX_WORKTREE_WALK_DEPTH,
|
|
3783
|
+
SESSION_CONTEXT_AGENT_TOOLS,
|
|
3784
|
+
SESSION_CONTEXT_FILE_VERSION,
|
|
3515
3785
|
appliedDeliverySchema,
|
|
3516
3786
|
classifyDurability,
|
|
3517
3787
|
createDeterministicIdGenerator,
|
|
3788
|
+
createDirectorySessionContextReader,
|
|
3518
3789
|
createFilesystemWorktreeLocator,
|
|
3519
3790
|
createFixedClock,
|
|
3520
3791
|
createInMemoryStateStore,
|
|
@@ -3528,12 +3799,20 @@ export {
|
|
|
3528
3799
|
createSystemClock,
|
|
3529
3800
|
hostDeliveryIdentity,
|
|
3530
3801
|
isCommittable,
|
|
3802
|
+
isReservedSessionContextKey,
|
|
3803
|
+
isSessionContextFileName,
|
|
3531
3804
|
logLevelSchema,
|
|
3532
3805
|
parseCommonDirFile,
|
|
3533
3806
|
parseGitDirFile,
|
|
3534
3807
|
parseHeadBranch,
|
|
3808
|
+
parseSessionContextFile,
|
|
3535
3809
|
resolveDeliveryIdentity,
|
|
3536
3810
|
resolveEventTargets,
|
|
3811
|
+
sanitizeSessionContextAttributes,
|
|
3812
|
+
segmentInForce,
|
|
3813
|
+
sessionContextAgentTool,
|
|
3814
|
+
sessionContextFilePath,
|
|
3815
|
+
stampSessionContext,
|
|
3537
3816
|
stateRecordSchema,
|
|
3538
3817
|
stateValueSchema,
|
|
3539
3818
|
usageScopeSchema
|