@tangle-network/agent-app 0.60.239 → 0.60.241
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat-routes/index.js +2 -2
- package/dist/chat-routes/turn-route-contracts.d.ts +5 -0
- package/dist/chunk-5OXWETUE.js +174 -0
- package/dist/chunk-5OXWETUE.js.map +1 -0
- package/dist/{chunk-QW6PFYJS.js → chunk-LSXJJL4I.js} +8 -3
- package/dist/chunk-LSXJJL4I.js.map +1 -0
- package/dist/{chunk-GNWGP3PA.js → chunk-P2E5TZUZ.js} +12 -3
- package/dist/chunk-P2E5TZUZ.js.map +1 -0
- package/dist/public-consultation/index.js +1 -1
- package/dist/rollout/cli.d.ts +3 -0
- package/dist/rollout/cli.js +11 -5
- package/dist/rollout/cli.js.map +1 -1
- package/dist/rollout/d1.d.ts +8 -1
- package/dist/rollout/d1.js +20 -4
- package/dist/rollout/d1.js.map +1 -1
- package/dist/rollout/index.d.ts +22 -14
- package/dist/rollout/index.js +3 -1
- package/dist/sandbox/index.js +1 -1
- package/dist/sandbox/sandbox-run-tool.d.ts +2 -0
- package/package.json +1 -1
- package/dist/chunk-4JUEOVQS.js +0 -134
- package/dist/chunk-4JUEOVQS.js.map +0 -1
- package/dist/chunk-GNWGP3PA.js.map +0 -1
- package/dist/chunk-QW6PFYJS.js.map +0 -1
|
@@ -43,7 +43,7 @@ import {
|
|
|
43
43
|
flattenHistory,
|
|
44
44
|
readSandboxBinaryBytes,
|
|
45
45
|
statSandboxFileSize
|
|
46
|
-
} from "../chunk-
|
|
46
|
+
} from "../chunk-P2E5TZUZ.js";
|
|
47
47
|
import "../chunk-4LBCTFBP.js";
|
|
48
48
|
import {
|
|
49
49
|
ModelFailoverExhaustedError,
|
|
@@ -83,7 +83,7 @@ import {
|
|
|
83
83
|
rowIdOf,
|
|
84
84
|
storeSupportsDraftPersistence,
|
|
85
85
|
streamChatRouteAsSandboxEvents
|
|
86
|
-
} from "../chunk-
|
|
86
|
+
} from "../chunk-LSXJJL4I.js";
|
|
87
87
|
import "../chunk-TCGZFSN5.js";
|
|
88
88
|
import "../chunk-FENBDSIW.js";
|
|
89
89
|
import "../chunk-RN4WPTBH.js";
|
|
@@ -351,6 +351,8 @@ interface ChatTurnLifecycleBase<TContext> {
|
|
|
351
351
|
}
|
|
352
352
|
/** When the turn's first visible word streamed, measured from `onTurnStart`. Absent when no word streamed. */
|
|
353
353
|
interface ChatTurnLifecycleTiming {
|
|
354
|
+
/** Request receipt to onTurnStart; add to firstVisibleMs for request-origin latency. */
|
|
355
|
+
admissionMs?: number;
|
|
354
356
|
/** First reasoning, tool activity or answer output, measured from onTurnStart. */
|
|
355
357
|
firstVisibleMs?: number;
|
|
356
358
|
firstTextMs?: number;
|
|
@@ -360,6 +362,9 @@ interface ChatTurnLifecycleTiming {
|
|
|
360
362
|
/** Define lifecycle start event with context and timestamp for a chat turn */
|
|
361
363
|
export interface ChatTurnLifecycleStart<TContext> extends ChatTurnLifecycleBase<TContext> {
|
|
362
364
|
startedAt: number;
|
|
365
|
+
/** Request receipt on the server clock. */
|
|
366
|
+
requestReceivedAt: number;
|
|
367
|
+
admissionMs: number;
|
|
363
368
|
}
|
|
364
369
|
/** Define the structure representing the completion state of a chat turn lifecycle with usage data */
|
|
365
370
|
export interface ChatTurnLifecycleComplete<TContext> extends ChatTurnLifecycleBase<TContext>, ChatTurnLifecycleTiming {
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// src/rollout/index.ts
|
|
2
|
+
function parseRolloutList(value) {
|
|
3
|
+
const ids = /* @__PURE__ */ new Set();
|
|
4
|
+
const excluded = /* @__PURE__ */ new Set();
|
|
5
|
+
const newSince = [];
|
|
6
|
+
let all = false;
|
|
7
|
+
for (const raw of (value ?? "").split(",")) {
|
|
8
|
+
const entry = raw.trim();
|
|
9
|
+
if (!entry) continue;
|
|
10
|
+
if (entry === "*") all = true;
|
|
11
|
+
else if (entry.startsWith("!")) excluded.add(entry.slice(1).trim());
|
|
12
|
+
else if (entry.startsWith("new-since:")) {
|
|
13
|
+
const at = Date.parse(entry.slice("new-since:".length));
|
|
14
|
+
if (!Number.isFinite(at)) throw new Error(`rollout list entry ${entry} is not a valid time`);
|
|
15
|
+
newSince.push(at);
|
|
16
|
+
} else ids.add(entry);
|
|
17
|
+
}
|
|
18
|
+
return { all, ids, excluded, newSince };
|
|
19
|
+
}
|
|
20
|
+
function rolloutAdmits(value, workspace) {
|
|
21
|
+
const list = typeof value === "string" ? parseRolloutList(value) : value;
|
|
22
|
+
if (list.excluded.has(workspace.id)) return false;
|
|
23
|
+
if (list.all || list.ids.has(workspace.id)) return true;
|
|
24
|
+
return workspace.createdAt !== void 0 && list.newSince.some((at) => workspace.createdAt >= at);
|
|
25
|
+
}
|
|
26
|
+
function rolloutWidens(fromValue, toValue) {
|
|
27
|
+
const from = parseRolloutList(fromValue);
|
|
28
|
+
const to = parseRolloutList(toValue);
|
|
29
|
+
if (to.all) {
|
|
30
|
+
if (!from.all) return true;
|
|
31
|
+
return [...from.excluded].some((id) => !to.excluded.has(id));
|
|
32
|
+
}
|
|
33
|
+
if ([...to.ids].some((id) => !rolloutAdmits(from, { id }))) return true;
|
|
34
|
+
const earliest = (list) => list.newSince.length ? Math.min(...list.newSince) : Infinity;
|
|
35
|
+
if (to.newSince.length && !from.all && earliest(to) < earliest(from)) return true;
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
function normalizeRolloutValue(value) {
|
|
39
|
+
return value.split(",").map((entry) => entry.trim()).filter(Boolean).sort().join(",");
|
|
40
|
+
}
|
|
41
|
+
function stageOf(plan, value) {
|
|
42
|
+
const key = normalizeRolloutValue(value);
|
|
43
|
+
return plan.stages.find((stage) => normalizeRolloutValue(stage.value) === key) ?? null;
|
|
44
|
+
}
|
|
45
|
+
function killLineBreaches(stage, measured) {
|
|
46
|
+
if (!measured || measured.stage !== stage.name) return [];
|
|
47
|
+
return Object.entries(stage.kill).flatMap(([metric, line]) => {
|
|
48
|
+
const value = measured.metrics[metric];
|
|
49
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return [];
|
|
50
|
+
return [
|
|
51
|
+
...line.max !== void 0 && value > line.max ? [`${metric} ${value} over kill line ${line.max}`] : [],
|
|
52
|
+
...line.min !== void 0 && value < line.min && !metric.endsWith("samples") ? [`${metric} ${value} under kill line ${line.min}`] : []
|
|
53
|
+
];
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function validateRolloutPlan(plan) {
|
|
57
|
+
if (!plan.name || !plan.variable) throw new Error("a rollout plan needs a name and a variable");
|
|
58
|
+
if (!plan.stages.length) throw new Error(`rollout ${plan.name} declares no stages`);
|
|
59
|
+
const names = /* @__PURE__ */ new Set();
|
|
60
|
+
const values = /* @__PURE__ */ new Set();
|
|
61
|
+
for (const stage of plan.stages) {
|
|
62
|
+
if (names.has(stage.name)) throw new Error(`rollout ${plan.name} repeats stage ${stage.name}`);
|
|
63
|
+
names.add(stage.name);
|
|
64
|
+
const value = normalizeRolloutValue(stage.value);
|
|
65
|
+
if (values.has(value)) throw new Error(`rollout ${plan.name} gives two stages the value ${stage.value}`);
|
|
66
|
+
values.add(value);
|
|
67
|
+
parseRolloutList(stage.value);
|
|
68
|
+
if (!Number.isInteger(stage.minSamples) || stage.minSamples < 1) {
|
|
69
|
+
throw new Error(`stage ${stage.name} needs minSamples of at least 1`);
|
|
70
|
+
}
|
|
71
|
+
if (!Object.keys(stage.kill).length) throw new Error(`stage ${stage.name} declares no kill lines`);
|
|
72
|
+
}
|
|
73
|
+
for (let index = 1; index < plan.stages.length; index++) {
|
|
74
|
+
const previous = plan.stages[index - 1];
|
|
75
|
+
const stage = plan.stages[index];
|
|
76
|
+
if (!rolloutWidens(previous.value, stage.value)) {
|
|
77
|
+
throw new Error(`stage ${stage.name} does not widen stage ${previous.name}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function assignRolloutArm(turnId, treatmentPct) {
|
|
82
|
+
if (!Number.isFinite(treatmentPct) || treatmentPct < 0 || treatmentPct > 100) {
|
|
83
|
+
throw new RangeError("treatmentPct must be between 0 and 100");
|
|
84
|
+
}
|
|
85
|
+
let hash = 2166136261;
|
|
86
|
+
for (let i = 0; i < turnId.length; i++) hash = Math.imul(hash ^ turnId.charCodeAt(i), 16777619);
|
|
87
|
+
return (hash >>> 0) / 2 ** 32 < treatmentPct / 100 ? "treatment" : "control";
|
|
88
|
+
}
|
|
89
|
+
var DEFAULT_MEASUREMENT_TIMEOUT_MS = 5e3;
|
|
90
|
+
async function decideRollout(input) {
|
|
91
|
+
const { plan, fromValue, toValue } = input;
|
|
92
|
+
validateRolloutPlan(plan);
|
|
93
|
+
const fromStage = stageOf(plan, fromValue);
|
|
94
|
+
const toStage = stageOf(plan, toValue);
|
|
95
|
+
const widens = rolloutWidens(fromValue, toValue);
|
|
96
|
+
const narrowing = !widens && normalizeRolloutValue(fromValue) !== normalizeRolloutValue(toValue);
|
|
97
|
+
const record = (decision, reasons2, measured2, turnsNeeded2 = {}, breach = false) => ({
|
|
98
|
+
rollout: plan.name,
|
|
99
|
+
variable: plan.variable,
|
|
100
|
+
from: { value: fromValue, stage: fromStage?.name ?? null },
|
|
101
|
+
to: { value: toValue, stage: toStage?.name ?? null },
|
|
102
|
+
widens,
|
|
103
|
+
decision,
|
|
104
|
+
recommendation: narrowing || breach ? "narrow" : decision === "refused" ? "refuse" : decision === "undecided" ? "hold" : widens ? "widen" : "hold",
|
|
105
|
+
turnsNeeded: turnsNeeded2,
|
|
106
|
+
reasons: reasons2,
|
|
107
|
+
measured: measured2,
|
|
108
|
+
at: (input.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
|
|
109
|
+
});
|
|
110
|
+
if (widens) {
|
|
111
|
+
if (!toStage) return record("refused", [`${toValue} is not a declared stage of ${plan.name}`], null);
|
|
112
|
+
const target = plan.stages.indexOf(toStage);
|
|
113
|
+
if (!fromStage) {
|
|
114
|
+
const empty = !normalizeRolloutValue(fromValue);
|
|
115
|
+
return empty && target === 0 ? record("allowed", [], null) : record("refused", [`the current value ${fromValue || "(empty)"} is not a declared stage of ${plan.name}`], null);
|
|
116
|
+
}
|
|
117
|
+
const current = plan.stages.indexOf(fromStage);
|
|
118
|
+
if (target > current + 1) return record("refused", [`${toStage.name} skips ${plan.stages.slice(current + 1, target).map((stage) => stage.name).join(", ")}`], null);
|
|
119
|
+
}
|
|
120
|
+
if (!fromStage) return record("allowed", [], null);
|
|
121
|
+
const timeoutMs = input.measurementTimeoutMs ?? DEFAULT_MEASUREMENT_TIMEOUT_MS;
|
|
122
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new RangeError("measurementTimeoutMs must be positive");
|
|
123
|
+
const abort = new AbortController();
|
|
124
|
+
let timer;
|
|
125
|
+
let measured;
|
|
126
|
+
try {
|
|
127
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
128
|
+
timer = setTimeout(() => {
|
|
129
|
+
const error = new Error("measurement timed out");
|
|
130
|
+
abort.abort(error);
|
|
131
|
+
reject(error);
|
|
132
|
+
}, timeoutMs);
|
|
133
|
+
});
|
|
134
|
+
measured = await Promise.race([input.measure(fromStage, abort.signal), deadline]);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
return record(
|
|
137
|
+
narrowing ? "allowed" : "undecided",
|
|
138
|
+
[`measuring stage ${fromStage.name} failed: ${error instanceof Error ? error.message : String(error)}`],
|
|
139
|
+
null,
|
|
140
|
+
{ [fromStage.name]: fromStage.minSamples }
|
|
141
|
+
);
|
|
142
|
+
} finally {
|
|
143
|
+
clearTimeout(timer);
|
|
144
|
+
}
|
|
145
|
+
const lane = measured?.lane ?? fromStage.name;
|
|
146
|
+
const requirements = { ...measured?.sampleRequirements };
|
|
147
|
+
requirements[lane] = {
|
|
148
|
+
samples: Math.min(measured?.samples ?? 0, requirements[lane]?.samples ?? Infinity),
|
|
149
|
+
minSamples: Math.max(fromStage.minSamples, requirements[lane]?.minSamples ?? 0)
|
|
150
|
+
};
|
|
151
|
+
for (const [metric, line] of Object.entries(fromStage.kill)) {
|
|
152
|
+
if (metric.endsWith("samples") && line.min !== void 0) {
|
|
153
|
+
requirements[metric] = { samples: measured?.metrics[metric] ?? 0, minSamples: line.min };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const turnsNeeded = Object.fromEntries(Object.entries(requirements).map(([lane2, floor]) => [lane2, Math.max(0, Math.ceil(floor.minSamples - (Number.isFinite(floor.samples) ? floor.samples : 0)))]).filter(([, needed]) => needed > 0));
|
|
157
|
+
const measuredStage = measured?.stage === fromStage.name;
|
|
158
|
+
const breaches = killLineBreaches(fromStage, measured);
|
|
159
|
+
const missing = !measuredStage ? [`stage ${fromStage.name} has no matching measurement`] : Object.keys(fromStage.kill).filter((metric) => !Number.isFinite(measured.metrics[metric])).map((metric) => `${metric} was not measured`);
|
|
160
|
+
const reasons = [...breaches, ...missing, ...Object.entries(turnsNeeded).map(([lane2, needed]) => `${lane2} needs ${needed} more turns`)];
|
|
161
|
+
return record(narrowing ? "allowed" : breaches.length ? "refused" : reasons.length ? "undecided" : "allowed", reasons, measured, turnsNeeded, breaches.length > 0);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export {
|
|
165
|
+
parseRolloutList,
|
|
166
|
+
rolloutAdmits,
|
|
167
|
+
rolloutWidens,
|
|
168
|
+
normalizeRolloutValue,
|
|
169
|
+
killLineBreaches,
|
|
170
|
+
validateRolloutPlan,
|
|
171
|
+
assignRolloutArm,
|
|
172
|
+
decideRollout
|
|
173
|
+
};
|
|
174
|
+
//# sourceMappingURL=chunk-5OXWETUE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/rollout/index.ts"],"sourcesContent":["/**\n * Rollout guard: a staged rollout widens only when the stage it leaves met\n * that stage's kill lines on measured production numbers.\n *\n * WHY. Hospitality's routed lane widened from two QA workspaces to `*` at a\n * first-words p50 of 3.54 s, past kill lines of 2.5 s and 3.0 s\n * (hospitality-agent #382, 2026-10-11). The numbers existed; nothing read them\n * before the list changed. This module is the one place that reads them.\n *\n * THE LIST. A rollout is one comma-separated value, usually a deploy variable\n * such as `HOSPITALITY_ROUTED_BUSINESS_IDS`: workspace ids, `*` for every\n * workspace, `!<id>` to keep one out whatever else matches, and\n * `new-since:<ISO time>` for workspaces created at or after that time.\n * {@link rolloutAdmits} is the reference reading of that grammar.\n *\n * THE RULE ({@link decideRollout}).\n * - Narrowing is always allowed. Holds and widenings measure the current stage.\n * - A widening must land on a declared stage, the next one after the current\n * value's stage, never past it.\n * - The stage being left must have at least `minSamples` measured turns and\n * every kill line met. A missing metric leaves the decision undecided.\n * - Missing samples are undecided; a measured breach names each reason (`first_words_p50_ms 3540 over kill line 2500`).\n *\n * Every decision, allowed, refused or undecided, is returned as one record the caller\n * persists (the CLI appends it to a JSONL ledger and hands it to the\n * config's `record`).\n */\n\n/** A kill line: the measured value must stay at or under `max` and at or over `min`. */\nexport interface RolloutKillLine {\n max?: number\n min?: number\n}\n\nexport interface RolloutStage {\n /** Short name used in refusals and records, e.g. `qa`, `all-but-recenter`. */\n name: string\n /** The exact list value that defines this stage. */\n value: string\n /** Turns the stage must have served, measured, before the rollout may leave it. */\n minSamples: number\n /** Metric name → line. Metric names are the product's, e.g. `first_words_p50_ms`, `failure_rate`. */\n kill: Record<string, RolloutKillLine>\n}\n\nexport interface RolloutPlan {\n /** e.g. `hospitality-routed-chat`. */\n name: string\n /** The deploy variable that carries the list, e.g. `HOSPITALITY_ROUTED_BUSINESS_IDS`. */\n variable: string\n /** In widening order. */\n stages: RolloutStage[]\n}\n\n/** Production numbers for one stage, from the product's own instrument. */\nexport interface StageMeasurement {\n stage: string\n samples: number\n /** Lane name for the stage sample floor; defaults to the stage name. */\n lane?: string\n /** Additional lane sample floors, evaluated as missing evidence rather than breaches. */\n sampleRequirements?: Record<string, { samples: number; minSamples: number }>\n metrics: Record<string, number | null | undefined>\n /** Where the numbers came from (ledger, query, soak), for the record. */\n source?: string\n window?: { from: string; to: string }\n}\n\nexport interface RolloutDecision {\n rollout: string\n variable: string\n from: { value: string; stage: string | null }\n to: { value: string; stage: string | null }\n widens: boolean\n decision: 'allowed' | 'refused' | 'undecided'\n recommendation: 'widen' | 'hold' | 'narrow' | 'refuse'\n turnsNeeded: Record<string, number>\n /** Breaches or evidence deficits, including observations made while narrowing. */\n reasons: string[]\n measured: StageMeasurement | null\n at: string\n}\n\nexport interface ParsedRolloutList {\n all: boolean\n ids: ReadonlySet<string>\n excluded: ReadonlySet<string>\n /** Epoch ms of each `new-since:` entry. */\n newSince: readonly number[]\n}\n\nexport function parseRolloutList(value: string | null | undefined): ParsedRolloutList {\n const ids = new Set<string>()\n const excluded = new Set<string>()\n const newSince: number[] = []\n let all = false\n for (const raw of (value ?? '').split(',')) {\n const entry = raw.trim()\n if (!entry) continue\n if (entry === '*') all = true\n else if (entry.startsWith('!')) excluded.add(entry.slice(1).trim())\n else if (entry.startsWith('new-since:')) {\n const at = Date.parse(entry.slice('new-since:'.length))\n if (!Number.isFinite(at)) throw new Error(`rollout list entry ${entry} is not a valid time`)\n newSince.push(at)\n } else ids.add(entry)\n }\n return { all, ids, excluded, newSince }\n}\n\n/** Whether a list admits one workspace. `createdAt` (epoch ms) is needed only for `new-since:` entries. */\nexport function rolloutAdmits(value: string | ParsedRolloutList, workspace: { id: string; createdAt?: number }): boolean {\n const list = typeof value === 'string' ? parseRolloutList(value) : value\n if (list.excluded.has(workspace.id)) return false\n if (list.all || list.ids.has(workspace.id)) return true\n return workspace.createdAt !== undefined && list.newSince.some(at => workspace.createdAt! >= at)\n}\n\n/**\n * Whether `to` may admit a workspace `from` does not. Conservative: a change it\n * cannot prove narrower counts as a widening.\n */\nexport function rolloutWidens(fromValue: string, toValue: string): boolean {\n const from = parseRolloutList(fromValue)\n const to = parseRolloutList(toValue)\n if (to.all) {\n if (!from.all) return true\n // Under `*` on both sides, only a dropped exclusion widens.\n return [...from.excluded].some(id => !to.excluded.has(id))\n }\n if ([...to.ids].some(id => !rolloutAdmits(from, { id }))) return true\n // An id `from` admitted only because it was listed, which `to` now excludes, narrows; nothing else here widens.\n const earliest = (list: ParsedRolloutList) => list.newSince.length ? Math.min(...list.newSince) : Infinity\n if (to.newSince.length && !from.all && earliest(to) < earliest(from)) return true\n return false\n}\n\n/** Canonical form for matching a value to a stage: entries trimmed and sorted. */\nexport function normalizeRolloutValue(value: string): string {\n return value.split(',').map(entry => entry.trim()).filter(Boolean).sort().join(',')\n}\n\nfunction stageOf(plan: RolloutPlan, value: string): RolloutStage | null {\n const key = normalizeRolloutValue(value)\n return plan.stages.find(stage => normalizeRolloutValue(stage.value) === key) ?? null\n}\n\n/** Finite measured breaches only. Missing observations and sample floors are evidence deficits. */\nexport function killLineBreaches(stage: RolloutStage, measured: StageMeasurement | null): string[] {\n if (!measured || measured.stage !== stage.name) return []\n return Object.entries(stage.kill).flatMap(([metric, line]) => {\n const value = measured.metrics[metric]\n if (typeof value !== 'number' || !Number.isFinite(value)) return []\n return [\n ...(line.max !== undefined && value > line.max ? [`${metric} ${value} over kill line ${line.max}`] : []),\n ...(line.min !== undefined && value < line.min && !metric.endsWith('samples') ? [`${metric} ${value} under kill line ${line.min}`] : []),\n ]\n })\n}\n\nexport function validateRolloutPlan(plan: RolloutPlan): void {\n if (!plan.name || !plan.variable) throw new Error('a rollout plan needs a name and a variable')\n if (!plan.stages.length) throw new Error(`rollout ${plan.name} declares no stages`)\n const names = new Set<string>()\n const values = new Set<string>()\n for (const stage of plan.stages) {\n if (names.has(stage.name)) throw new Error(`rollout ${plan.name} repeats stage ${stage.name}`)\n names.add(stage.name)\n const value = normalizeRolloutValue(stage.value)\n if (values.has(value)) throw new Error(`rollout ${plan.name} gives two stages the value ${stage.value}`)\n values.add(value)\n parseRolloutList(stage.value)\n if (!Number.isInteger(stage.minSamples) || stage.minSamples < 1) {\n throw new Error(`stage ${stage.name} needs minSamples of at least 1`)\n }\n if (!Object.keys(stage.kill).length) throw new Error(`stage ${stage.name} declares no kill lines`)\n }\n for (let index = 1; index < plan.stages.length; index++) {\n const previous = plan.stages[index - 1]!\n const stage = plan.stages[index]!\n if (!rolloutWidens(previous.value, stage.value)) {\n throw new Error(`stage ${stage.name} does not widen stage ${previous.name}`)\n }\n }\n}\n\n/** Stable per-turn percentage assignment; the product records the returned arm on its row and trace. */\nexport function assignRolloutArm(turnId: string, treatmentPct: number): 'control' | 'treatment' {\n if (!Number.isFinite(treatmentPct) || treatmentPct < 0 || treatmentPct > 100) {\n throw new RangeError('treatmentPct must be between 0 and 100')\n }\n let hash = 2166136261\n for (let i = 0; i < turnId.length; i++) hash = Math.imul(hash ^ turnId.charCodeAt(i), 16777619)\n return (hash >>> 0) / 2 ** 32 < treatmentPct / 100 ? 'treatment' : 'control'\n}\n\nconst DEFAULT_MEASUREMENT_TIMEOUT_MS = 5_000\n\n/** Measure the current stage for widening, holding and narrowing. Narrowing always remains available. */\nexport async function decideRollout(input: {\n plan: RolloutPlan\n fromValue: string\n toValue: string\n measure(stage: RolloutStage, signal?: AbortSignal): Promise<StageMeasurement | null>\n /** Bound observation even when the product instrument ignores cancellation. */\n measurementTimeoutMs?: number\n now?: () => Date\n}): Promise<RolloutDecision> {\n const { plan, fromValue, toValue } = input\n validateRolloutPlan(plan)\n const fromStage = stageOf(plan, fromValue)\n const toStage = stageOf(plan, toValue)\n const widens = rolloutWidens(fromValue, toValue)\n const narrowing = !widens && normalizeRolloutValue(fromValue) !== normalizeRolloutValue(toValue)\n const record = (decision: RolloutDecision['decision'], reasons: string[], measured: StageMeasurement | null,\n turnsNeeded: Record<string, number> = {}, breach = false): RolloutDecision => ({\n rollout: plan.name, variable: plan.variable,\n from: { value: fromValue, stage: fromStage?.name ?? null },\n to: { value: toValue, stage: toStage?.name ?? null }, widens, decision,\n recommendation: narrowing || breach ? 'narrow' : decision === 'refused' ? 'refuse' : decision === 'undecided' ? 'hold' : widens ? 'widen' : 'hold',\n turnsNeeded, reasons, measured, at: (input.now?.() ?? new Date()).toISOString(),\n })\n if (widens) {\n if (!toStage) return record('refused', [`${toValue} is not a declared stage of ${plan.name}`], null)\n const target = plan.stages.indexOf(toStage)\n if (!fromStage) {\n const empty = !normalizeRolloutValue(fromValue)\n return empty && target === 0 ? record('allowed', [], null)\n : record('refused', [`the current value ${fromValue || '(empty)'} is not a declared stage of ${plan.name}`], null)\n }\n const current = plan.stages.indexOf(fromStage)\n if (target > current + 1) return record('refused', [`${toStage.name} skips ${plan.stages.slice(current + 1, target).map(stage => stage.name).join(', ')}`], null)\n }\n if (!fromStage) return record('allowed', [], null)\n const timeoutMs = input.measurementTimeoutMs ?? DEFAULT_MEASUREMENT_TIMEOUT_MS\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new RangeError('measurementTimeoutMs must be positive')\n const abort = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n let measured: StageMeasurement | null\n try {\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n const error = new Error('measurement timed out')\n abort.abort(error)\n reject(error)\n }, timeoutMs)\n })\n measured = await Promise.race([input.measure(fromStage, abort.signal), deadline])\n }\n catch (error) {\n return record(narrowing ? 'allowed' : 'undecided', [`measuring stage ${fromStage.name} failed: ${error instanceof Error ? error.message : String(error)}`], null,\n { [fromStage.name]: fromStage.minSamples })\n } finally {\n clearTimeout(timer)\n }\n const lane = measured?.lane ?? fromStage.name\n const requirements = { ...measured?.sampleRequirements }\n requirements[lane] = {\n samples: Math.min(measured?.samples ?? 0, requirements[lane]?.samples ?? Infinity),\n minSamples: Math.max(fromStage.minSamples, requirements[lane]?.minSamples ?? 0),\n }\n // Older product configs expressed control floors as *_samples minimum kill lines.\n for (const [metric, line] of Object.entries(fromStage.kill)) {\n if (metric.endsWith('samples') && line.min !== undefined) {\n requirements[metric] = { samples: measured?.metrics[metric] ?? 0, minSamples: line.min }\n }\n }\n const turnsNeeded = Object.fromEntries(Object.entries(requirements)\n .map(([lane, floor]) => [lane, Math.max(0, Math.ceil(floor.minSamples - (Number.isFinite(floor.samples) ? floor.samples : 0)))] as const)\n .filter(([, needed]) => needed > 0))\n const measuredStage = measured?.stage === fromStage.name\n const breaches = killLineBreaches(fromStage, measured)\n const missing = !measuredStage ? [`stage ${fromStage.name} has no matching measurement`]\n : Object.keys(fromStage.kill).filter(metric => !Number.isFinite(measured!.metrics[metric])).map(metric => `${metric} was not measured`)\n const reasons = [...breaches, ...missing, ...Object.entries(turnsNeeded).map(([lane, needed]) => `${lane} needs ${needed} more turns`)]\n return record(narrowing ? 'allowed' : breaches.length ? 'refused' : reasons.length ? 'undecided' : 'allowed', reasons, measured, turnsNeeded, breaches.length > 0)\n}\n"],"mappings":";AA2FO,SAAS,iBAAiB,OAAqD;AACpF,QAAM,MAAM,oBAAI,IAAY;AAC5B,QAAM,WAAW,oBAAI,IAAY;AACjC,QAAM,WAAqB,CAAC;AAC5B,MAAI,MAAM;AACV,aAAW,QAAQ,SAAS,IAAI,MAAM,GAAG,GAAG;AAC1C,UAAM,QAAQ,IAAI,KAAK;AACvB,QAAI,CAAC,MAAO;AACZ,QAAI,UAAU,IAAK,OAAM;AAAA,aAChB,MAAM,WAAW,GAAG,EAAG,UAAS,IAAI,MAAM,MAAM,CAAC,EAAE,KAAK,CAAC;AAAA,aACzD,MAAM,WAAW,YAAY,GAAG;AACvC,YAAM,KAAK,KAAK,MAAM,MAAM,MAAM,aAAa,MAAM,CAAC;AACtD,UAAI,CAAC,OAAO,SAAS,EAAE,EAAG,OAAM,IAAI,MAAM,sBAAsB,KAAK,sBAAsB;AAC3F,eAAS,KAAK,EAAE;AAAA,IAClB,MAAO,KAAI,IAAI,KAAK;AAAA,EACtB;AACA,SAAO,EAAE,KAAK,KAAK,UAAU,SAAS;AACxC;AAGO,SAAS,cAAc,OAAmC,WAAwD;AACvH,QAAM,OAAO,OAAO,UAAU,WAAW,iBAAiB,KAAK,IAAI;AACnE,MAAI,KAAK,SAAS,IAAI,UAAU,EAAE,EAAG,QAAO;AAC5C,MAAI,KAA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AAM,UAAU,CAAC,gBAAgB,CAAC,SAAS,UAAU,IAAI,8BAA8B,IACnF,OAAO,KAAK,UAAU,IAAI,EAAE,OAAO,YAAU,CAAC,OAAO,SAAS,SAAU,QAAQ,MAAM,CAAC,CAAC,EAAE,IAAI,YAAU,GAAG,MAAM,mBAAmB;AACxI,QAAM,UAAU,CAAC,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,QAAQ,WAAW,EAAE,IAAI,CAAC,CAACA,OAAM,MAAM,MAAM,GAAGA,KAAI,UAAU,MAAM,aAAa,CAAC;AACtI,SAAO,OAAO,YAAY,YAAY,SAAS,SAAS,YAAY,QAAQ,SAAS,cAAc,WAAW,SAAS,UAAU,aAAa,SAAS,SAAS,CAAC;AACnK;","names":["reasons","measured","turnsNeeded","lane"]}
|
|
@@ -662,6 +662,7 @@ function createAdmittedTurnRunner({
|
|
|
662
662
|
const lifecycle = options.lifecycle;
|
|
663
663
|
const durationMs = Date.now() - turnStartedAtMs;
|
|
664
664
|
const timing = {
|
|
665
|
+
admissionMs: turnStartedAtMs - trace.startedAt,
|
|
665
666
|
...firstVisibleAtMs === void 0 ? {} : { firstVisibleMs: firstVisibleAtMs - turnStartedAtMs },
|
|
666
667
|
...firstTextAtMs === void 0 ? {} : { firstTextMs: firstTextAtMs - turnStartedAtMs },
|
|
667
668
|
trace: snapshot.summary
|
|
@@ -788,7 +789,9 @@ function createAdmittedTurnRunner({
|
|
|
788
789
|
executionId,
|
|
789
790
|
turnStreamId,
|
|
790
791
|
context,
|
|
791
|
-
startedAt: turnStartedAtMs
|
|
792
|
+
startedAt: turnStartedAtMs,
|
|
793
|
+
requestReceivedAt: trace.startedAt,
|
|
794
|
+
admissionMs: turnStartedAtMs - trace.startedAt
|
|
792
795
|
});
|
|
793
796
|
} catch (err) {
|
|
794
797
|
log("[chat-routes] lifecycle.onTurnStart failed", {
|
|
@@ -846,7 +849,9 @@ function createAdmittedTurnRunner({
|
|
|
846
849
|
executionId,
|
|
847
850
|
turnStreamId,
|
|
848
851
|
context,
|
|
849
|
-
startedAt: turnStartedAtMs
|
|
852
|
+
startedAt: turnStartedAtMs,
|
|
853
|
+
requestReceivedAt: trace.startedAt,
|
|
854
|
+
admissionMs: turnStartedAtMs - trace.startedAt
|
|
850
855
|
});
|
|
851
856
|
} catch (err) {
|
|
852
857
|
log("[chat-routes] lifecycle.onTurnStart failed", {
|
|
@@ -1508,4 +1513,4 @@ export {
|
|
|
1508
1513
|
createChatTurnRoutes,
|
|
1509
1514
|
streamChatRouteAsSandboxEvents
|
|
1510
1515
|
};
|
|
1511
|
-
//# sourceMappingURL=chunk-
|
|
1516
|
+
//# sourceMappingURL=chunk-LSXJJL4I.js.map
|