@tangle-network/agent-app 0.60.240 → 0.60.242
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/assistant/index.js +4 -4
- package/dist/chat-react/index.js +3 -3
- package/dist/chat-routes/index.js +2 -2
- package/dist/{chunk-YNM44SQC.js → chunk-5OXWETUE.js} +16 -2
- package/dist/chunk-5OXWETUE.js.map +1 -0
- package/dist/{chunk-DLVMKDFX.js → chunk-FT2Z3AOX.js} +3 -3
- package/dist/{chunk-P2E5TZUZ.js → chunk-PBSFLSQ2.js} +2 -2
- package/dist/{chunk-P2E5TZUZ.js.map → chunk-PBSFLSQ2.js.map} +1 -1
- package/dist/{chunk-VBRUG4N5.js → chunk-PYZYB5V2.js} +1 -1
- package/dist/chunk-PYZYB5V2.js.map +1 -0
- package/dist/{chunk-CI53V6DD.js → chunk-XKRJ275O.js} +2 -2
- package/dist/{chunk-A77IBQ7S.js → chunk-YVMOYCNL.js} +2 -2
- package/dist/harness/index.js +1 -1
- package/dist/rollout/cli.d.ts +3 -0
- package/dist/rollout/cli.js +9 -3
- package/dist/rollout/cli.js.map +1 -1
- package/dist/rollout/d1.js +2 -1
- package/dist/rollout/d1.js.map +1 -1
- package/dist/rollout/index.d.ts +3 -1
- package/dist/rollout/index.js +1 -1
- package/dist/sandbox/index.js +2 -2
- package/dist/sandbox/payload-limits.d.ts +2 -1
- package/dist/skills-placement/index.js +1 -1
- package/dist/web-react/agent-profile-editor.js +3 -3
- package/dist/web-react/index.js +4 -4
- package/package.json +8 -8
- package/dist/chunk-VBRUG4N5.js.map +0 -1
- package/dist/chunk-YNM44SQC.js.map +0 -1
- /package/dist/{chunk-DLVMKDFX.js.map → chunk-FT2Z3AOX.js.map} +0 -0
- /package/dist/{chunk-CI53V6DD.js.map → chunk-XKRJ275O.js.map} +0 -0
- /package/dist/{chunk-A77IBQ7S.js.map → chunk-YVMOYCNL.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/harness/index.ts","../src/harness/session-selection.ts"],"sourcesContent":["/**\n * Coding-agent harness selection, model compatibility, and the session lock.\n *\n * Known identities are not a deployment's available runners. Products supply\n * server-owned availability to resolveSessionHarness. Historical session IDs\n * remain intact when their runner is unavailable; a harness change requires an\n * explicit transfer, not a fallback or a rewritten session lock.\n *\n * Model compatibility is owned by @tangle-network/agent-interface. The shell\n * owns session selection; the consumer owns storage and deployment policy.\n */\n\nimport {\n harnessProviders,\n harnessSupportsModel,\n harnessTypeSchema,\n modelProvider,\n preferredHarnessForModel,\n snapHarnessToModel as aiSnapHarnessToModel,\n snapModelToHarness as aiSnapModelToHarness,\n type HarnessType,\n} from '@tangle-network/agent-interface'\nimport {\n selectSessionHarness,\n type HarnessAvailability as SelectionAvailability,\n type SessionHarnessSelection,\n type SessionHarnessSelectionInput,\n} from './session-selection'\n\nexport { HarnessSelectionError } from './session-selection'\n\n/** Canonical identities that have no direct Sandbox backend. */\nconst NON_BACKEND_HARNESSES = ['gemini'] as const satisfies readonly HarnessType[]\nconst nonBackendHarnesses = new Set<string>(NON_BACKEND_HARNESSES)\n\n/** A recognized coding-agent backend, not a promise that it is installed. */\nexport type Harness = Exclude<HarnessType, (typeof NON_BACKEND_HARNESSES)[number]>\n\n/**\n * Recognized backend identities, including IDs needed by historical sessions.\n * Use deployment availability, not membership here, to offer or admit new runs.\n */\nexport const KNOWN_HARNESSES: readonly Harness[] = [\n ...harnessTypeSchema.options.filter(\n (harness): harness is Exclude<HarnessType, (typeof NON_BACKEND_HARNESSES)[number]> =>\n !nonBackendHarnesses.has(harness),\n ),\n]\n\n/** Default for an absent choice; never a replacement for an invalid explicit ID. */\nexport const DEFAULT_HARNESS: Harness = 'opencode'\nconst HARNESS_SET: ReadonlySet<string> = new Set(KNOWN_HARNESSES)\n\n/** Determine whether a value is a recognized identity, independently of availability. */\nexport function isHarness(value: unknown): value is Harness {\n return typeof value === 'string' && HARNESS_SET.has(value)\n}\n\n/** Display/config convenience only. Never use coercion to admit an execution or restore a lock. */\nexport function coerceHarness(value: unknown, fallback: Harness = DEFAULT_HARNESS): Harness {\n return isHarness(value) ? value : fallback\n}\n\n/** Server-owned start and resume sets. Existing-only entries are draining. */\nexport type HarnessAvailability = SelectionAvailability<Harness>\n\n/** A saved lock, explicit choice, workspace default, and optional deployment availability. */\nexport type ResolveSessionHarnessInput = SessionHarnessSelectionInput<Harness>\n\n/** The selected identity and the existing session-lock/swap-attempt result. */\nexport type ResolvedSessionHarness = SessionHarnessSelection<Harness>\n\n/**\n * Resolve requested → workspaceDefault → fallback only for a genuinely new session.\n * A non-null saved identity always takes the lock path. Unknown/retired identities\n * and invalid explicit requests throw HarnessSelectionError instead of falling back.\n * A known different request still reports swapAttempted while preserving the lock.\n * The caller must reject that attempt before execution, as in the existing contract.\n */\nexport function resolveSessionHarness(input: ResolveSessionHarnessInput = {}): ResolvedSessionHarness {\n return selectSessionHarness(input, KNOWN_HARNESSES, DEFAULT_HARNESS)\n}\n\n/**\n * An app's harness configuration, read from its deploy configuration (for example the env vars\n * `AGENT_HARNESS` and `AGENT_HARNESS_WORKSPACES`), so no product hard-codes `backend.type`.\n */\nexport interface HarnessConfig {\n /** The app default for new sessions. Unset or blank means {@link DEFAULT_HARNESS}. */\n default?: string\n /** Per-workspace choices: a JSON object mapping a workspace id to a harness. */\n workspaces?: string\n}\n\nfunction configHarness(value: unknown, where: string): Harness {\n if (!isHarness(value)) throw new Error(`${where} names an unknown harness: ${String(value)}`)\n return value\n}\n\n/**\n * The harness a workspace's new sessions start on: its own choice, else the app default, else\n * {@link DEFAULT_HARNESS}. Pass the result to {@link resolveSessionHarness} as `workspaceDefault`\n * so a session that already ran keeps its harness. A value naming an unknown harness throws:\n * a configuration typo must fail loudly, never run a different harness than the one configured.\n */\nexport function configuredHarness(config: HarnessConfig, workspaceId?: string): Harness {\n const appDefault = config.default?.trim()\n ? configHarness(config.default.trim(), 'The harness default') : DEFAULT_HARNESS\n const raw = config.workspaces?.trim()\n if (!raw) return appDefault\n let choices: unknown\n try {\n choices = JSON.parse(raw)\n } catch {\n throw new Error('The per-workspace harness configuration is not JSON')\n }\n if (!choices || typeof choices !== 'object' || Array.isArray(choices)) {\n throw new Error('The per-workspace harness configuration must map workspace ids to harnesses')\n }\n // Every entry is checked, not only the caller's, so one bad entry fails every workspace's\n // first turn after the deploy instead of hiding until that workspace sends a message.\n const parsed = new Map(Object.entries(choices).map(([id, value]) =>\n [id, configHarness(value, `The harness for workspace ${id}`)]))\n return (workspaceId === undefined ? undefined : parsed.get(workspaceId)) ?? appDefault\n}\n\n/** Harness-model compatibility is delegated to the Interface owner. */\nexport { modelProvider }\n\n/** A resolved model and the transport provider that will execute it. */\nexport interface HarnessModelSelection {\n model: string\n provider?: string\n}\n\n/** Provider-less ids (sentinels like \"default\", or a session's own config) are\n * compatible everywhere — every harness honors its own configuration. */\nexport function isModelCompatibleWithHarness(harness: Harness, modelId: string): boolean {\n return harnessSupportsModel(harness, modelId)\n}\n\n/** Keep `modelId` when the harness can run it; else the harness's best compatible\n * catalog id (preferred patterns in order, highest version). When nothing in the\n * catalog fits, return the original so the caller sees the incompatibility. */\nexport function snapModelToHarness(harness: Harness, modelId: string, canonicalIds: readonly string[]): string {\n return aiSnapModelToHarness(harness, modelId, canonicalIds)\n}\n\n/** Keep the harness when it can run `modelId`; else the model's native harness\n * (anthropic → claude-code, openai → codex, moonshot → kimi-code), falling back to opencode. */\nexport function snapHarnessToModel(harness: Harness, modelId: string): Harness {\n const snapped = aiSnapHarnessToModel(harness, modelId)\n if (!isHarness(snapped)) {\n throw new Error(\n `Harness \"${harness}\" snapped to \"${snapped}\" for model \"${modelId}\", which this platform has no backend for.`,\n )\n }\n return snapped\n}\n\n/** Fail-loud server guard: throw when a harness is asked to run a model it can't.\n * A resolved model tuple supplies provider evidence when its id is unqualified.\n * Call before dispatching a sandbox turn so a bypassed UI cannot reach the\n * sidecar with an incompatible or unproven pair. */\nexport function assertHarnessModelCompatible(\n harness: Harness,\n selection: string | HarnessModelSelection,\n): void {\n const modelId = typeof selection === 'string' ? selection : selection.model\n const transportProvider = typeof selection === 'string' ? undefined : selection.provider\n const providers = harnessProviders(harness)\n const provider = modelProvider(modelId) ?? transportProvider ?? null\n // An omitted/default model is deliberately left to the harness. Once a\n // caller names a model, however, a vendor-locked harness must have provider\n // evidence. Interface owns which harnesses are locked: since 5.7 Claude Code\n // and Codex run any Router-served model, and kimi-code stays Moonshot-only.\n const isDefaultSentinel = modelId.trim() === '' || modelId.trim() === 'default'\n const compatible = isDefaultSentinel\n || providers === null\n || (provider !== null && providers.includes(provider))\n if (!compatible) {\n const native = preferredHarnessForModel(modelId)\n const providerDescription = provider ?? 'unqualified'\n throw new Error(\n `Harness \"${harness}\" cannot run model \"${modelId}\" (provider \"${providerDescription}\"). ` +\n `Use ${native ?? 'a router-backed harness (opencode)'} or an allowed model.`,\n )\n }\n}\n\n// Profile-support facts remain here until the materializer supplies its owned descriptor.\n// Do not confuse these facts with deployment availability.\n\n/** What a harness can express, for profile assembly. */\nexport interface HarnessCapabilities {\n /** Lower profile.subagents into native cwd files; false means materialization refuses them. */\n subagents: boolean\n /** How profile.mcp reaches the harness. */\n mcp: 'native' | 'config-file' | 'extension' | 'none'\n /** Whether tool controls are checked before MCP tools register. */\n toolControls: 'startup' | 'runtime'\n /** cwd-relative skill directory, or null when skills must be inlined. */\n skillsDir: string | null\n}\n\nconst HARNESS_CAPABILITIES: Record<Harness, HarnessCapabilities> = {\n 'claude-code': { subagents: true, mcp: 'native', toolControls: 'runtime', skillsDir: '.claude/skills' },\n nanoclaw: { subagents: true, mcp: 'native', toolControls: 'runtime', skillsDir: '.claude/skills' },\n opencode: { subagents: true, mcp: 'config-file', toolControls: 'runtime', skillsDir: '.opencode/skills' },\n codex: { subagents: true, mcp: 'config-file', toolControls: 'runtime', skillsDir: '.codex/skills' },\n 'kimi-code': { subagents: false, mcp: 'config-file', toolControls: 'runtime', skillsDir: '.kimi/skills' },\n pi: { subagents: false, mcp: 'extension', toolControls: 'startup', skillsDir: '.pi/skills' },\n prime: { subagents: true, mcp: 'native', toolControls: 'runtime', skillsDir: '.prime/agent/skills' },\n hermes: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n openclaw: { subagents: false, mcp: 'config-file', toolControls: 'runtime', skillsDir: 'skills' },\n acp: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n amp: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n 'factory-droids': { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n forge: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n cursor: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n 'cli-base': { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n}\n\n/** Profile-support facts, independent of whether this deployment enables the harness. */\nexport function harnessCapabilities(harness: Harness): HarnessCapabilities {\n const caps = HARNESS_CAPABILITIES[harness]\n if (!caps) throw new Error(`harnessCapabilities: no capability facts for \"${harness}\"`)\n return caps\n}\n","/** Pure session admission. Harness identity is not deployment availability. */\nexport interface HarnessAvailability<H extends string> {\n /** Server-owned selection for new sessions. An empty list disables all starts. */\n readonly newSessions: readonly H[]\n /** Includes draining harnesses. Omission uses newSessions, never all known IDs. */\n readonly existingSessions?: readonly H[]\n}\n\nexport interface SessionHarnessSelectionInput<H extends string> {\n sessionHarness?: unknown\n requested?: unknown\n workspaceDefault?: unknown\n fallback?: H\n /** Omit only when the caller deliberately admits every known harness. */\n availability?: HarnessAvailability<H>\n}\n\nexport interface SessionHarnessSelection<H extends string> {\n harness: H\n locked: boolean\n swapAttempted: boolean\n}\n\ntype SelectionSource = 'session' | 'requested' | 'workspace' | 'fallback'\n\n/** An admission failure, never permission to retry on another harness. */\nexport class HarnessSelectionError extends Error {\n readonly code: 'harness_unknown' | 'harness_unavailable'\n readonly harness: string | null\n readonly source: SelectionSource\n\n constructor(\n code: 'harness_unknown' | 'harness_unavailable',\n value: unknown,\n source: SelectionSource,\n ) {\n const harness = typeof value === 'string' ? value : null\n super(`${code}: ${source} harness ${harness === null ? '<invalid>' : JSON.stringify(harness)}`)\n this.name = 'HarnessSelectionError'\n this.code = code\n this.harness = harness\n this.source = source\n }\n}\n\n/**\n * Null/undefined mean no choice. Every other value is an explicit choice and must\n * validate. A retired or unrecognized saved identity must never become a new session.\n * Availability is supplied by the authenticated server, not by a request body.\n */\nexport function selectSessionHarness<H extends string>(\n input: SessionHarnessSelectionInput<H>,\n knownHarnesses: readonly H[],\n defaultHarness: H,\n): SessionHarnessSelection<H> {\n const known = new Set<string>(knownHarnesses)\n const resolve = (value: unknown, source: SelectionSource): H => {\n if (typeof value !== 'string' || !known.has(value)) {\n throw new HarnessSelectionError('harness_unknown', value, source)\n }\n return value as H\n }\n const admit = (harness: H, source: SelectionSource, existing: boolean): void => {\n if (input.availability === undefined) return\n const allowed = existing\n ? input.availability.existingSessions ?? input.availability.newSessions\n : input.availability.newSessions\n if (!allowed.includes(harness)) {\n throw new HarnessSelectionError('harness_unavailable', harness, source)\n }\n }\n\n if (input.sessionHarness !== undefined && input.sessionHarness !== null) {\n const harness = resolve(input.sessionHarness, 'session')\n admit(harness, 'session', true)\n // A known different request remains a swap attempt; it is not executed. An\n // invalid request is refused rather than being misreported as no swap.\n const requested = input.requested === undefined || input.requested === null\n ? undefined : resolve(input.requested, 'requested')\n return { harness, locked: true, swapAttempted: requested !== undefined && requested !== harness }\n }\n\n const source: SelectionSource = input.requested !== undefined && input.requested !== null\n ? 'requested'\n : input.workspaceDefault !== undefined && input.workspaceDefault !== null\n ? 'workspace' : 'fallback'\n const value = source === 'requested' ? input.requested\n : source === 'workspace' ? input.workspaceDefault : input.fallback ?? defaultHarness\n const harness = resolve(value, source)\n admit(harness, source, false)\n return { harness, locked: false, swapAttempted: false }\n}\n"],"mappings":";AAYA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,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AqB,OAAO;AACzC,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,iDAAiD,OAAO,GAAG;AACtF,SAAO;AACT;","names":["value","source","harness"]}
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
import {
|
|
16
16
|
snapHarnessToModel,
|
|
17
17
|
snapModelToHarness
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-PYZYB5V2.js";
|
|
19
19
|
|
|
20
20
|
// src/web-react/composer-file-accept.ts
|
|
21
21
|
function isAcceptedFileType(file, accept) {
|
|
@@ -576,4 +576,4 @@ export {
|
|
|
576
576
|
HarnessPicker,
|
|
577
577
|
AgentSessionControls
|
|
578
578
|
};
|
|
579
|
-
//# sourceMappingURL=chunk-
|
|
579
|
+
//# sourceMappingURL=chunk-XKRJ275O.js.map
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
filterAcceptedFiles,
|
|
14
14
|
isAcceptedFileType,
|
|
15
15
|
renamePastedImages
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-XKRJ275O.js";
|
|
17
17
|
import {
|
|
18
18
|
OVERLAY_SHADOW,
|
|
19
19
|
POPOVER_OPTION_FOCUS,
|
|
@@ -1603,4 +1603,4 @@ export {
|
|
|
1603
1603
|
ComposerModeControls,
|
|
1604
1604
|
EntryComposer
|
|
1605
1605
|
};
|
|
1606
|
-
//# sourceMappingURL=chunk-
|
|
1606
|
+
//# sourceMappingURL=chunk-YVMOYCNL.js.map
|
package/dist/harness/index.js
CHANGED
package/dist/rollout/cli.d.ts
CHANGED
|
@@ -5,7 +5,10 @@ export interface RolloutConfig {
|
|
|
5
5
|
measure(input: {
|
|
6
6
|
plan: RolloutPlan;
|
|
7
7
|
stage: RolloutStage;
|
|
8
|
+
signal?: AbortSignal;
|
|
8
9
|
}): Promise<StageMeasurement | null>;
|
|
10
|
+
/** Shared observation deadline; see decideRollout. */
|
|
11
|
+
measurementTimeoutMs?: number;
|
|
9
12
|
record?(decision: RolloutDecision): Promise<void> | void;
|
|
10
13
|
/** Default `wrangler.toml`. */
|
|
11
14
|
wrangler?: string;
|
package/dist/rollout/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
decideRollout
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-5OXWETUE.js";
|
|
5
5
|
import {
|
|
6
6
|
invokedAsScript
|
|
7
7
|
} from "../chunk-C3CAYGGQ.js";
|
|
@@ -88,7 +88,13 @@ async function runRolloutCheck(args) {
|
|
|
88
88
|
for (const plan of plans) {
|
|
89
89
|
const fromValue = args.from ?? readWranglerVar(base, plan.variable) ?? "";
|
|
90
90
|
const toValue = args.to ?? readWranglerVar(head, plan.variable) ?? "";
|
|
91
|
-
const decision = await decideRollout({
|
|
91
|
+
const decision = await decideRollout({
|
|
92
|
+
plan,
|
|
93
|
+
fromValue,
|
|
94
|
+
toValue,
|
|
95
|
+
measure: (stage, signal) => config.measure({ plan, stage, signal }),
|
|
96
|
+
measurementTimeoutMs: config.measurementTimeoutMs
|
|
97
|
+
});
|
|
92
98
|
decisions.push(decision);
|
|
93
99
|
const ledger = resolve(args.appDir, args.record);
|
|
94
100
|
mkdirSync(dirname(ledger), { recursive: true });
|
|
@@ -125,7 +131,7 @@ async function main() {
|
|
|
125
131
|
}
|
|
126
132
|
if (invokedAsScript(import.meta.url, process.argv[1])) {
|
|
127
133
|
main().then((code) => {
|
|
128
|
-
process.
|
|
134
|
+
process.stdout.write("", () => process.stderr.write("", () => process.exit(code)));
|
|
129
135
|
});
|
|
130
136
|
}
|
|
131
137
|
export {
|
package/dist/rollout/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/rollout/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `agent-app-rollout-check` — refuse a deploy that widens a staged rollout\n * before the stage it leaves met its kill lines.\n *\n * Runs in the app's repo, in the step that ships (ship.sh verify, or the PR\n * check). Add `rollout.config.mjs` at the root:\n *\n * export default {\n * plans: [{\n * name: 'hospitality-routed-chat',\n * variable: 'HOSPITALITY_ROUTED_BUSINESS_IDS',\n * stages: [\n * { name: 'qa', value: 'ws-a,ws-b', minSamples: 30,\n * kill: { first_words_p50_ms: { max: 2500 }, failure_rate: { max: 0 } } },\n * { name: 'all', value: '*', minSamples: 200,\n * kill: { first_words_p50_ms: { max: 1500 }, failure_rate: { max: 0.01 } } },\n * ],\n * }],\n * // The product's own instrument: production numbers for the stage being left.\n * async measure({ plan, stage }) { return { stage: stage.name, samples, metrics: { … }, source } },\n * // Optional: keep the decision somewhere durable as well as the JSONL ledger.\n * async record(decision) {},\n * }\n *\n * The new value is read from the `[vars]` of wrangler.toml; the current one\n * from the same file at `--base` (default `origin/main`), or given with\n * `--from`. `--to` overrides the new value.\n *\n * Usage: agent-app-rollout-check [appDir] [--config <file>] [--base <git ref>]\n * [--from <value>] [--to <value>] [--plan <name>] [--record <jsonl>]\n * Exits 0 when allowed, 1 for a measured refusal, 3 for insufficient widening evidence, 2 on a usage error. Undecided holds exit 0.\n */\nimport { execFileSync } from 'node:child_process'\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { invokedAsScript } from '../signoff/invoked-as-script.js'\nimport { decideRollout, type RolloutDecision, type RolloutPlan, type RolloutStage, type StageMeasurement } from './index.js'\n\nexport interface RolloutConfig {\n plans: RolloutPlan[]\n measure(input: { plan: RolloutPlan; stage: RolloutStage }): Promise<StageMeasurement | null>\n record?(decision: RolloutDecision): Promise<void> | void\n /** Default `wrangler.toml`. */\n wrangler?: string\n}\n\ninterface CliArgs {\n appDir: string\n config?: string\n base: string\n from?: string\n to?: string\n plan?: string\n record: string\n}\n\nconst CONFIG_NAMES = ['rollout.config.mjs', 'rollout.config.js']\n\nfunction parseArgs(argv: readonly string[]): CliArgs {\n const args: CliArgs = { appDir: process.cwd(), base: 'origin/main', record: '.rollout/decisions.jsonl' }\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index]!\n const value = () => {\n const next = argv[++index]\n if (next === undefined) throw new Error(`${arg} needs a value`)\n return next\n }\n if (arg === '--config') args.config = value()\n else if (arg === '--base') args.base = value()\n else if (arg === '--from') args.from = value()\n else if (arg === '--to') args.to = value()\n else if (arg === '--plan') args.plan = value()\n else if (arg === '--record') args.record = value()\n else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`)\n else args.appDir = resolve(arg)\n }\n return args\n}\n\n/** A top-level `[vars]` string value from wrangler.toml source; environments are not read. */\nexport function readWranglerVar(source: string, name: string): string | null {\n let inVars = false\n for (const line of source.split('\\n')) {\n const header = line.match(/^\\s*\\[([^\\]]+)\\]\\s*(?:#.*)?$/)\n if (header) {\n inVars = header[1]!.trim() === 'vars'\n continue\n }\n if (!inVars) continue\n const entry = line.match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/)\n if (entry && entry[1] === name) return JSON.parse(`\"${entry[2]}\"`) as string\n }\n return null\n}\n\nasync function loadConfig(appDir: string, explicit?: string): Promise<RolloutConfig> {\n const file = explicit ? resolve(appDir, explicit) : CONFIG_NAMES.map(name => join(appDir, name)).find(path => existsSync(path))\n if (!file || !existsSync(file)) throw new Error(`no ${CONFIG_NAMES[0]} in ${appDir}`)\n const config = ((await import(pathToFileURL(file).href)) as { default: RolloutConfig }).default\n if (!Array.isArray(config?.plans) || typeof config.measure !== 'function') {\n throw new Error(`${file} must export { plans, measure }`)\n }\n return config\n}\n\nfunction gitShow(cwd: string, spec: string): string | null {\n try {\n return execFileSync('git', ['show', spec], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })\n } catch {\n return null\n }\n}\n\n/**\n * The file at `ref`. Under agent-app-signoff the app runs in a clean copy with\n * no `.git`; signoff names the source checkout and the copy's root, so the\n * base is read from the source at the same repo-relative path.\n */\nfunction wranglerAt(appDir: string, file: string, ref: string, env: NodeJS.ProcessEnv = process.env): string {\n const local = gitShow(appDir, `${ref}:./${file}`)\n if (local !== null) return local\n const source = env.SIGNOFF_SOURCE_REPO\n const tree = env.SIGNOFF_TREE\n if (source && tree) {\n const path = relative(resolve(tree), resolve(appDir, file))\n if (!path.startsWith('..') && !isAbsolute(path)) {\n const fromSource = gitShow(source, `${ref}:${path.split(sep).join('/')}`)\n if (fromSource !== null) return fromSource\n }\n }\n throw new Error(`cannot read ${file} at ${ref}; fetch it or pass --from`)\n}\n\nexport async function runRolloutCheck(args: CliArgs): Promise<RolloutDecision[]> {\n const config = await loadConfig(args.appDir, args.config)\n const file = config.wrangler ?? 'wrangler.toml'\n const plans = args.plan ? config.plans.filter(plan => plan.name === args.plan) : config.plans\n if (!plans.length) throw new Error(args.plan ? `no plan named ${args.plan}` : 'the config declares no plans')\n if (plans.length > 1 && (args.from !== undefined || args.to !== undefined)) throw new Error('--from and --to need --plan')\n const head = readFileSync(join(args.appDir, file), 'utf8')\n const base = args.from === undefined ? wranglerAt(args.appDir, file, args.base) : null\n const decisions: RolloutDecision[] = []\n for (const plan of plans) {\n const fromValue = args.from ?? readWranglerVar(base!, plan.variable) ?? ''\n const toValue = args.to ?? readWranglerVar(head, plan.variable) ?? ''\n const decision = await decideRollout({ plan, fromValue, toValue, measure: stage => config.measure({ plan, stage }) })\n decisions.push(decision)\n const ledger = resolve(args.appDir, args.record)\n mkdirSync(dirname(ledger), { recursive: true })\n appendFileSync(ledger, `${JSON.stringify(decision)}\\n`)\n await config.record?.(decision)\n }\n return decisions\n}\n\nfunction describe(decision: RolloutDecision): string {\n const move = `${decision.from.stage ?? decision.from.value ?? '(empty)'} -> ${decision.to.stage ?? decision.to.value}`\n if (decision.decision === 'allowed') {\n return `rollout ${decision.rollout}: allowed ${move}${decision.widens ? '' : ' (not a widening)'}`\n }\n return `rollout ${decision.rollout}: ${decision.decision.toUpperCase()} ${move} (${decision.recommendation})\\n${decision.reasons.map(reason => ` - ${reason}`).join('\\n')}`\n}\n\nasync function main(): Promise<number> {\n let args: CliArgs\n try {\n args = parseArgs(process.argv.slice(2))\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error))\n return 2\n }\n try {\n const decisions = await runRolloutCheck(args)\n for (const decision of decisions) console.log(describe(decision))\n return decisions.some(decision => decision.decision === 'refused') ? 1 : decisions.some(decision => decision.decision === 'undecided' && decision.widens) ? 3 : 0\n } catch (error) {\n console.error(`agent-app-rollout-check: ${error instanceof Error ? error.message : String(error)}`)\n return 2\n }\n}\n\nif (invokedAsScript(import.meta.url, process.argv[1])) {\n main().then(code => { process.exitCode = code })\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,YAAY,WAAW,oBAAoB;AACpE,SAAS,SAAS,YAAY,MAAM,UAAU,SAAS,WAAW;AAClE,SAAS,qBAAqB;AAsB9B,IAAM,eAAe,CAAC,sBAAsB,mBAAmB;AAE/D,SAAS,UAAU,MAAkC;AACnD,QAAM,OAAgB,EAAE,QAAQ,QAAQ,IAAI,GAAG,MAAM,eAAe,QAAQ,2BAA2B;AACvG,WAAS,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GAAG;AACnD,UAAM,MAAM,KAAK,KAAK;AACtB,UAAM,QAAQ,MAAM;AAClB,YAAM,OAAO,KAAK,EAAE,KAAK;AACzB,UAAI,SAAS,OAAW,OAAM,IAAI,MAAM,GAAG,GAAG,gBAAgB;AAC9D,aAAO;AAAA,IACT;AACA,QAAI,QAAQ,WAAY,MAAK,SAAS,MAAM;AAAA,aACnC,QAAQ,SAAU,MAAK,OAAO,MAAM;AAAA,aACpC,QAAQ,SAAU,MAAK,OAAO,MAAM;AAAA,aACpC,QAAQ,OAAQ,MAAK,KAAK,MAAM;AAAA,aAChC,QAAQ,SAAU,MAAK,OAAO,MAAM;AAAA,aACpC,QAAQ,WAAY,MAAK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UAAU,KAAK,cAAY,SAAS,aAAa,eAAe,SAAS,MAAM,IAAI,IAAI;AAAA,EAClK,SAAS,OAAO;AACd,YAAQ,MAAM,4BAA4B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAClG,WAAO;AAAA,EACT;AACF;AAEA,IAAI,gBAAgB,YAAY,KAAK,QAAQ,KAAK,CAAC,CAAC,GAAG;AACrD,OAAK,EAAE,KAAK,UAAQ;AAAE,YAAQ,WAAW;AAAA,EAAK,CAAC;AACjD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/rollout/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `agent-app-rollout-check` — refuse a deploy that widens a staged rollout\n * before the stage it leaves met its kill lines.\n *\n * Runs in the app's repo, in the step that ships (ship.sh verify, or the PR\n * check). Add `rollout.config.mjs` at the root:\n *\n * export default {\n * plans: [{\n * name: 'hospitality-routed-chat',\n * variable: 'HOSPITALITY_ROUTED_BUSINESS_IDS',\n * stages: [\n * { name: 'qa', value: 'ws-a,ws-b', minSamples: 30,\n * kill: { first_words_p50_ms: { max: 2500 }, failure_rate: { max: 0 } } },\n * { name: 'all', value: '*', minSamples: 200,\n * kill: { first_words_p50_ms: { max: 1500 }, failure_rate: { max: 0.01 } } },\n * ],\n * }],\n * // The product's own instrument: production numbers for the stage being left.\n * async measure({ plan, stage }) { return { stage: stage.name, samples, metrics: { … }, source } },\n * // Optional: keep the decision somewhere durable as well as the JSONL ledger.\n * async record(decision) {},\n * }\n *\n * The new value is read from the `[vars]` of wrangler.toml; the current one\n * from the same file at `--base` (default `origin/main`), or given with\n * `--from`. `--to` overrides the new value.\n *\n * Usage: agent-app-rollout-check [appDir] [--config <file>] [--base <git ref>]\n * [--from <value>] [--to <value>] [--plan <name>] [--record <jsonl>]\n * Exits 0 when allowed, 1 for a measured refusal, 3 for insufficient widening evidence, 2 on a usage error. Undecided holds exit 0.\n */\nimport { execFileSync } from 'node:child_process'\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { invokedAsScript } from '../signoff/invoked-as-script.js'\nimport { decideRollout, type RolloutDecision, type RolloutPlan, type RolloutStage, type StageMeasurement } from './index.js'\n\nexport interface RolloutConfig {\n plans: RolloutPlan[]\n measure(input: { plan: RolloutPlan; stage: RolloutStage; signal?: AbortSignal }): Promise<StageMeasurement | null>\n /** Shared observation deadline; see decideRollout. */\n measurementTimeoutMs?: number\n record?(decision: RolloutDecision): Promise<void> | void\n /** Default `wrangler.toml`. */\n wrangler?: string\n}\n\ninterface CliArgs {\n appDir: string\n config?: string\n base: string\n from?: string\n to?: string\n plan?: string\n record: string\n}\n\nconst CONFIG_NAMES = ['rollout.config.mjs', 'rollout.config.js']\n\nfunction parseArgs(argv: readonly string[]): CliArgs {\n const args: CliArgs = { appDir: process.cwd(), base: 'origin/main', record: '.rollout/decisions.jsonl' }\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index]!\n const value = () => {\n const next = argv[++index]\n if (next === undefined) throw new Error(`${arg} needs a value`)\n return next\n }\n if (arg === '--config') args.config = value()\n else if (arg === '--base') args.base = value()\n else if (arg === '--from') args.from = value()\n else if (arg === '--to') args.to = value()\n else if (arg === '--plan') args.plan = value()\n else if (arg === '--record') args.record = value()\n else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`)\n else args.appDir = resolve(arg)\n }\n return args\n}\n\n/** A top-level `[vars]` string value from wrangler.toml source; environments are not read. */\nexport function readWranglerVar(source: string, name: string): string | null {\n let inVars = false\n for (const line of source.split('\\n')) {\n const header = line.match(/^\\s*\\[([^\\]]+)\\]\\s*(?:#.*)?$/)\n if (header) {\n inVars = header[1]!.trim() === 'vars'\n continue\n }\n if (!inVars) continue\n const entry = line.match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/)\n if (entry && entry[1] === name) return JSON.parse(`\"${entry[2]}\"`) as string\n }\n return null\n}\n\nasync function loadConfig(appDir: string, explicit?: string): Promise<RolloutConfig> {\n const file = explicit ? resolve(appDir, explicit) : CONFIG_NAMES.map(name => join(appDir, name)).find(path => existsSync(path))\n if (!file || !existsSync(file)) throw new Error(`no ${CONFIG_NAMES[0]} in ${appDir}`)\n const config = ((await import(pathToFileURL(file).href)) as { default: RolloutConfig }).default\n if (!Array.isArray(config?.plans) || typeof config.measure !== 'function') {\n throw new Error(`${file} must export { plans, measure }`)\n }\n return config\n}\n\nfunction gitShow(cwd: string, spec: string): string | null {\n try {\n return execFileSync('git', ['show', spec], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })\n } catch {\n return null\n }\n}\n\n/**\n * The file at `ref`. Under agent-app-signoff the app runs in a clean copy with\n * no `.git`; signoff names the source checkout and the copy's root, so the\n * base is read from the source at the same repo-relative path.\n */\nfunction wranglerAt(appDir: string, file: string, ref: string, env: NodeJS.ProcessEnv = process.env): string {\n const local = gitShow(appDir, `${ref}:./${file}`)\n if (local !== null) return local\n const source = env.SIGNOFF_SOURCE_REPO\n const tree = env.SIGNOFF_TREE\n if (source && tree) {\n const path = relative(resolve(tree), resolve(appDir, file))\n if (!path.startsWith('..') && !isAbsolute(path)) {\n const fromSource = gitShow(source, `${ref}:${path.split(sep).join('/')}`)\n if (fromSource !== null) return fromSource\n }\n }\n throw new Error(`cannot read ${file} at ${ref}; fetch it or pass --from`)\n}\n\nexport async function runRolloutCheck(args: CliArgs): Promise<RolloutDecision[]> {\n const config = await loadConfig(args.appDir, args.config)\n const file = config.wrangler ?? 'wrangler.toml'\n const plans = args.plan ? config.plans.filter(plan => plan.name === args.plan) : config.plans\n if (!plans.length) throw new Error(args.plan ? `no plan named ${args.plan}` : 'the config declares no plans')\n if (plans.length > 1 && (args.from !== undefined || args.to !== undefined)) throw new Error('--from and --to need --plan')\n const head = readFileSync(join(args.appDir, file), 'utf8')\n const base = args.from === undefined ? wranglerAt(args.appDir, file, args.base) : null\n const decisions: RolloutDecision[] = []\n for (const plan of plans) {\n const fromValue = args.from ?? readWranglerVar(base!, plan.variable) ?? ''\n const toValue = args.to ?? readWranglerVar(head, plan.variable) ?? ''\n const decision = await decideRollout({\n plan, fromValue, toValue,\n measure: (stage, signal) => config.measure({ plan, stage, signal }),\n measurementTimeoutMs: config.measurementTimeoutMs,\n })\n decisions.push(decision)\n const ledger = resolve(args.appDir, args.record)\n mkdirSync(dirname(ledger), { recursive: true })\n appendFileSync(ledger, `${JSON.stringify(decision)}\\n`)\n await config.record?.(decision)\n }\n return decisions\n}\n\nfunction describe(decision: RolloutDecision): string {\n const move = `${decision.from.stage ?? decision.from.value ?? '(empty)'} -> ${decision.to.stage ?? decision.to.value}`\n if (decision.decision === 'allowed') {\n return `rollout ${decision.rollout}: allowed ${move}${decision.widens ? '' : ' (not a widening)'}`\n }\n return `rollout ${decision.rollout}: ${decision.decision.toUpperCase()} ${move} (${decision.recommendation})\\n${decision.reasons.map(reason => ` - ${reason}`).join('\\n')}`\n}\n\nasync function main(): Promise<number> {\n let args: CliArgs\n try {\n args = parseArgs(process.argv.slice(2))\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error))\n return 2\n }\n try {\n const decisions = await runRolloutCheck(args)\n for (const decision of decisions) console.log(describe(decision))\n return decisions.some(decision => decision.decision === 'refused') ? 1 : decisions.some(decision => decision.decision === 'undecided' && decision.widens) ? 3 : 0\n } catch (error) {\n console.error(`agent-app-rollout-check: ${error instanceof Error ? error.message : String(error)}`)\n return 2\n }\n}\n\nif (invokedAsScript(import.meta.url, process.argv[1])) {\n // A timed-out product instrument can leave an uncooperative socket open.\n // All durable records are awaited by main; flush the receipt before ending the CLI.\n main().then(code => {\n process.stdout.write('', () => process.stderr.write('', () => process.exit(code)))\n })\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,YAAY,WAAW,oBAAoB;AACpE,S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
|
|
|
1
1
|
import {
|
|
2
2
|
rolloutAdmits
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-5OXWETUE.js";
|
|
4
4
|
|
|
5
5
|
// src/rollout/d1.ts
|
|
6
6
|
var ROLLOUT_TURN_TIMING_SCHEMA_SQL = `
|
|
@@ -93,6 +93,7 @@ function createD1TurnTimingStore(options) {
|
|
|
93
93
|
const rows = results.filter((row) => rolloutAdmits(input.stage.value, { id: row.workspace_id })).map((row) => ({ firstVisibleMs: row.first_visible_ms ?? void 0, firstTextMs: row.first_text_ms ?? void 0, settledMs: row.settled_ms, failed: row.failed === 1 }));
|
|
94
94
|
return {
|
|
95
95
|
stage: input.stage.name,
|
|
96
|
+
lane: input.lane,
|
|
96
97
|
samples: rows.length,
|
|
97
98
|
metrics: stageMetrics(rows),
|
|
98
99
|
source: `rollout_turn_timing lane=${input.lane}`,
|
package/dist/rollout/d1.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/rollout/d1.ts"],"sourcesContent":["/**\n * The measurement a rollout guard reads: one row per turn with its lane, its\n * first visible word and whether it failed, and the stage numbers computed\n * from those rows.\n *\n * Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`\n * carry `firstVisibleMs`, `firstTextMs` and `durationMs`), then serve `measureStage` behind an\n * operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is\n * measured on the turns of the workspaces it admits, in the lane being rolled\n * out, since the time it went live.\n */\nimport { rolloutAdmits, type RolloutStage, type StageMeasurement } from './index'\n\n/** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForRollout {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results?: T[] }>\n }\n }\n}\n\nexport const ROLLOUT_TURN_TIMING_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n admission_ms INTEGER,\n model TEXT,\n revision TEXT,\n arm TEXT,\n first_visible_ms INTEGER,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n`\n\n/** Apply once through the product migration runner to existing tables; historical rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;`\n\n/** Apply once through the product migration runner; old rows remain unknown. */\nexport const ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL = `\nALTER TABLE rollout_turn_timing ADD COLUMN admission_ms INTEGER;\nALTER TABLE rollout_turn_timing ADD COLUMN model TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN revision TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN arm TEXT;\n`\n\nexport interface TurnTimingRow {\n /** Request receipt to lifecycle start, before the existing relative durations. */\n admissionMs?: number\n model?: string\n revision?: string\n arm?: string\n turnId: string\n /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */\n rollout: string\n workspaceId: string\n /** The lane that served the turn, e.g. `routed` or `sandbox`. Only the rolled-out lane is measured. */\n lane: string\n /** From the lifecycle's `firstTextMs`; absent when no word streamed. */\n firstTextMs?: number\n /** From the lifecycle firstVisibleMs; absent when no reasoning, tool or answer streamed. */\n firstVisibleMs?: number\n settledMs: number\n failed: boolean\n failureCode?: string\n /** Epoch ms; defaults to now. */\n at?: number\n}\n\n/** Rows read for one measurement; a stage needing more than this would be measured on its newest rows. */\nconst MEASURE_ROW_LIMIT = 20_000\n\nfunction percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n return sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)]!\n}\n\n/** Stage metrics from turn rows: first-words and settled percentiles in ms, and the failure rate. */\nexport function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'firstVisibleMs' | 'firstTextMs' | 'settledMs' | 'failed'>>) {\n const firstVisible = rows.flatMap(row => row.firstVisibleMs == null ? [] : [row.firstVisibleMs]).sort((a, b) => a - b)\n const firstWords = rows.flatMap(row => row.firstTextMs === undefined || row.firstTextMs === null ? [] : [row.firstTextMs]).sort((a, b) => a - b)\n const settled = rows.filter(row => !row.failed).map(row => row.settledMs).sort((a, b) => a - b)\n return {\n first_visible_p50_ms: percentile(firstVisible, 50),\n first_visible_p90_ms: percentile(firstVisible, 90),\n first_words_p50_ms: percentile(firstWords, 50),\n first_words_p90_ms: percentile(firstWords, 90),\n settled_p50_ms: percentile(settled, 50),\n settled_p90_ms: percentile(settled, 90),\n // A turn that streamed no word failed the user whatever its envelope said.\n failure_rate: rows.length ? rows.filter(row => row.failed || row.firstTextMs === undefined || row.firstTextMs === null).length / rows.length : null,\n }\n}\n\nexport function createD1TurnTimingStore(options: { db: D1LikeForRollout; now?: () => number }) {\n const now = options.now ?? Date.now\n return {\n /** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */\n async record(row: TurnTimingRow): Promise<void> {\n try {\n await options.db.prepare(\n `INSERT OR IGNORE INTO rollout_turn_timing\n (turn_id, rollout, workspace_id, lane, first_visible_ms, first_text_ms, settled_ms, failed, failure_code, at, admission_ms, model, revision, arm)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).bind(row.turnId, row.rollout, row.workspaceId, row.lane,\n row.firstVisibleMs === undefined ? null : Math.round(row.firstVisibleMs),\n row.firstTextMs === undefined ? null : Math.round(row.firstTextMs), Math.round(row.settledMs),\n row.failed ? 1 : 0, row.failureCode ?? null, row.at ?? now(),\n row.admissionMs === undefined ? null : Math.round(row.admissionMs),\n row.model ?? null, row.revision ?? null, row.arm ?? null).run()\n } catch (error) {\n console.error(JSON.stringify({ event: 'rollout_turn_timing_record_failed', turnId: row.turnId,\n error: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200) }))\n }\n },\n\n /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no\n * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */\n async measureStage(input: { rollout: string; stage: RolloutStage; lane: string; since: number }): Promise<StageMeasurement> {\n const { results = [] } = await options.db.prepare(\n `SELECT workspace_id, first_visible_ms, first_text_ms, settled_ms, failed FROM rollout_turn_timing\n WHERE rollout = ? AND lane = ? AND at >= ? ORDER BY at DESC LIMIT ?`,\n ).bind(input.rollout, input.lane, input.since, MEASURE_ROW_LIMIT).all<{\n workspace_id: string; first_visible_ms: number | null; first_text_ms: number | null; settled_ms: number; failed: number\n }>()\n const rows = results\n .filter(row => rolloutAdmits(input.stage.value, { id: row.workspace_id }))\n .map(row => ({ firstVisibleMs: row.first_visible_ms ?? undefined, firstTextMs: row.first_text_ms ?? undefined, settledMs: row.settled_ms, failed: row.failed === 1 }))\n return {\n stage: input.stage.name,\n samples: rows.length,\n metrics: stageMetrics(rows),\n source: `rollout_turn_timing lane=${input.lane}`,\n window: { from: new Date(input.since).toISOString(), to: new Date(now()).toISOString() },\n }\n },\n }\n}\n"],"mappings":";;;;;AAuBO,IAAM,iCAAiC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBvC,IAAM,kDACX;AAGK,IAAM,0CAA0C;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BvD,IAAM,oBAAoB;AAE1B,SAAS,WAAW,QAA2B,GAA0B;AACvE,MAAI,CAAC,OAAO,OAAQ,QAAO;AAC3B,SAAO,OAAO,KAAK,IAAI,OAAO,SAAS,GAAG,KAAK,KAAM,IAAI,MAAO,OAAO,MAAM,IAAI,C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Y,EAAE;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/rollout/d1.ts"],"sourcesContent":["/**\n * The measurement a rollout guard reads: one row per turn with its lane, its\n * first visible word and whether it failed, and the stage numbers computed\n * from those rows.\n *\n * Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`\n * carry `firstVisibleMs`, `firstTextMs` and `durationMs`), then serve `measureStage` behind an\n * operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is\n * measured on the turns of the workspaces it admits, in the lane being rolled\n * out, since the time it went live.\n */\nimport { rolloutAdmits, type RolloutStage, type StageMeasurement } from './index'\n\n/** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForRollout {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results?: T[] }>\n }\n }\n}\n\nexport const ROLLOUT_TURN_TIMING_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n admission_ms INTEGER,\n model TEXT,\n revision TEXT,\n arm TEXT,\n first_visible_ms INTEGER,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n`\n\n/** Apply once through the product migration runner to existing tables; historical rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;`\n\n/** Apply once through the product migration runner; old rows remain unknown. */\nexport const ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL = `\nALTER TABLE rollout_turn_timing ADD COLUMN admission_ms INTEGER;\nALTER TABLE rollout_turn_timing ADD COLUMN model TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN revision TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN arm TEXT;\n`\n\nexport interface TurnTimingRow {\n /** Request receipt to lifecycle start, before the existing relative durations. */\n admissionMs?: number\n model?: string\n revision?: string\n arm?: string\n turnId: string\n /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */\n rollout: string\n workspaceId: string\n /** The lane that served the turn, e.g. `routed` or `sandbox`. Only the rolled-out lane is measured. */\n lane: string\n /** From the lifecycle's `firstTextMs`; absent when no word streamed. */\n firstTextMs?: number\n /** From the lifecycle firstVisibleMs; absent when no reasoning, tool or answer streamed. */\n firstVisibleMs?: number\n settledMs: number\n failed: boolean\n failureCode?: string\n /** Epoch ms; defaults to now. */\n at?: number\n}\n\n/** Rows read for one measurement; a stage needing more than this would be measured on its newest rows. */\nconst MEASURE_ROW_LIMIT = 20_000\n\nfunction percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n return sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)]!\n}\n\n/** Stage metrics from turn rows: first-words and settled percentiles in ms, and the failure rate. */\nexport function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'firstVisibleMs' | 'firstTextMs' | 'settledMs' | 'failed'>>) {\n const firstVisible = rows.flatMap(row => row.firstVisibleMs == null ? [] : [row.firstVisibleMs]).sort((a, b) => a - b)\n const firstWords = rows.flatMap(row => row.firstTextMs === undefined || row.firstTextMs === null ? [] : [row.firstTextMs]).sort((a, b) => a - b)\n const settled = rows.filter(row => !row.failed).map(row => row.settledMs).sort((a, b) => a - b)\n return {\n first_visible_p50_ms: percentile(firstVisible, 50),\n first_visible_p90_ms: percentile(firstVisible, 90),\n first_words_p50_ms: percentile(firstWords, 50),\n first_words_p90_ms: percentile(firstWords, 90),\n settled_p50_ms: percentile(settled, 50),\n settled_p90_ms: percentile(settled, 90),\n // A turn that streamed no word failed the user whatever its envelope said.\n failure_rate: rows.length ? rows.filter(row => row.failed || row.firstTextMs === undefined || row.firstTextMs === null).length / rows.length : null,\n }\n}\n\nexport function createD1TurnTimingStore(options: { db: D1LikeForRollout; now?: () => number }) {\n const now = options.now ?? Date.now\n return {\n /** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */\n async record(row: TurnTimingRow): Promise<void> {\n try {\n await options.db.prepare(\n `INSERT OR IGNORE INTO rollout_turn_timing\n (turn_id, rollout, workspace_id, lane, first_visible_ms, first_text_ms, settled_ms, failed, failure_code, at, admission_ms, model, revision, arm)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).bind(row.turnId, row.rollout, row.workspaceId, row.lane,\n row.firstVisibleMs === undefined ? null : Math.round(row.firstVisibleMs),\n row.firstTextMs === undefined ? null : Math.round(row.firstTextMs), Math.round(row.settledMs),\n row.failed ? 1 : 0, row.failureCode ?? null, row.at ?? now(),\n row.admissionMs === undefined ? null : Math.round(row.admissionMs),\n row.model ?? null, row.revision ?? null, row.arm ?? null).run()\n } catch (error) {\n console.error(JSON.stringify({ event: 'rollout_turn_timing_record_failed', turnId: row.turnId,\n error: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200) }))\n }\n },\n\n /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no\n * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */\n async measureStage(input: { rollout: string; stage: RolloutStage; lane: string; since: number }): Promise<StageMeasurement> {\n const { results = [] } = await options.db.prepare(\n `SELECT workspace_id, first_visible_ms, first_text_ms, settled_ms, failed FROM rollout_turn_timing\n WHERE rollout = ? AND lane = ? AND at >= ? ORDER BY at DESC LIMIT ?`,\n ).bind(input.rollout, input.lane, input.since, MEASURE_ROW_LIMIT).all<{\n workspace_id: string; first_visible_ms: number | null; first_text_ms: number | null; settled_ms: number; failed: number\n }>()\n const rows = results\n .filter(row => rolloutAdmits(input.stage.value, { id: row.workspace_id }))\n .map(row => ({ firstVisibleMs: row.first_visible_ms ?? undefined, firstTextMs: row.first_text_ms ?? undefined, settledMs: row.settled_ms, failed: row.failed === 1 }))\n return {\n stage: input.stage.name,\n lane: input.lane,\n samples: rows.length,\n metrics: stageMetrics(rows),\n source: `rollout_turn_timing lane=${input.lane}`,\n window: { from: new Date(input.since).toISOString(), to: new Date(now()).toISOString() },\n }\n },\n }\n}\n"],"mappings":";;;;;AAuBO,IAAM,iCAAiC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBvC,IAAM,kDACX;AAGK,IAAM,0CAA0C;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BvD,IAAM,oBAAoB;AAE1B,SAAS,WAAW,QAA2B,GAA0B;AACvE,MAAI,CAAC,OAAO,OAAQ,QAAO;AAC3B,SAAO,OAAO,KAAK,IAAI,OAAO,SAAS,GAAG,KAAK,KAAM,IAAI,MAAO,OAAO,MAAM,IAAI,CAAC,CAAC;AACrF;AAGO,SAAS,aAAa,MAAqG;AAChI,QAAM,eAAe,KAAK,QAAQ,SAAO,IAAI,kBAAkB,OAAO,CAAC,IAAI,CAAC,IAAI,cAAc,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AACrH,QAAM,aAAa,KAAK,QAAQ,SAAO,IAAI,gBAAgB,UAAa,IAAI,gBAAgB,OAAO,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAC/I,QAAM,UAAU,KAAK,OAAO,SAAO,CAAC,IAAI,MAAM,EAAE,IAAI,SAAO,IAAI,SAAS,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAC9F,SAAO;AAAA,IACL,sBAAsB,WAAW,cAAc,EAAE;AAAA,IACjD,sBAAsB,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AA,MAChG;AAAA,IACF;AAAA;AAAA;AAAA,IAIA,MAAM,aAAa,OAAyG;AAC1H,YAAM,EAAE,UAAU,CAAC,EAAE,IAAI,MAAM,QAAQ,GAAG;AAAA,QACxC;AAAA;AAAA,MAEF,EAAE,KAAK,MAAM,SAAS,MAAM,MAAM,MAAM,OAAO,iBAAiB,EAAE,IAE/D;AACH,YAAM,OAAO,QACV,OAAO,SAAO,cAAc,MAAM,MAAM,OAAO,EAAE,IAAI,IAAI,aAAa,CAAC,CAAC,EACxE,IAAI,UAAQ,EAAE,gBAAgB,IAAI,oBAAoB,QAAW,aAAa,IAAI,iBAAiB,QAAW,WAAW,IAAI,YAAY,QAAQ,IAAI,WAAW,EAAE,EAAE;AACvK,aAAO;AAAA,QACL,OAAO,MAAM,MAAM;AAAA,QACnB,MAAM,MAAM;AAAA,QACZ,SAAS,KAAK;AAAA,QACd,SAAS,aAAa,IAAI;AAAA,QAC1B,QAAQ,4BAA4B,MAAM,IAAI;AAAA,QAC9C,QAAQ,EAAE,MAAM,IAAI,KAAK,MAAM,KAAK,EAAE,YAAY,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC,EAAE,YAAY,EAAE;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/rollout/index.d.ts
CHANGED
|
@@ -117,6 +117,8 @@ export declare function decideRollout(input: {
|
|
|
117
117
|
plan: RolloutPlan;
|
|
118
118
|
fromValue: string;
|
|
119
119
|
toValue: string;
|
|
120
|
-
measure(stage: RolloutStage): Promise<StageMeasurement | null>;
|
|
120
|
+
measure(stage: RolloutStage, signal?: AbortSignal): Promise<StageMeasurement | null>;
|
|
121
|
+
/** Bound observation even when the product instrument ignores cancellation. */
|
|
122
|
+
measurementTimeoutMs?: number;
|
|
121
123
|
now?: () => Date;
|
|
122
124
|
}): Promise<RolloutDecision>;
|
package/dist/rollout/index.js
CHANGED
package/dist/sandbox/index.js
CHANGED
|
@@ -100,7 +100,7 @@ import {
|
|
|
100
100
|
warmBinOf,
|
|
101
101
|
warmWeekdayOf,
|
|
102
102
|
writeProfileFilesToBox
|
|
103
|
-
} from "../chunk-
|
|
103
|
+
} from "../chunk-PBSFLSQ2.js";
|
|
104
104
|
import {
|
|
105
105
|
EGRESS_PROXY_RECOVERY_PHASE,
|
|
106
106
|
EGRESS_PROXY_RECOVERY_REQUIRED,
|
|
@@ -139,7 +139,7 @@ import {
|
|
|
139
139
|
workspaceSandboxRecoveryMessage,
|
|
140
140
|
workspaceSandboxRecoveryRecommendedActions
|
|
141
141
|
} from "../chunk-4LBCTFBP.js";
|
|
142
|
-
import "../chunk-
|
|
142
|
+
import "../chunk-PYZYB5V2.js";
|
|
143
143
|
import "../chunk-LWSJK546.js";
|
|
144
144
|
import "../chunk-6CKOEPXS.js";
|
|
145
145
|
import "../chunk-6A7MYOUI.js";
|
|
@@ -32,7 +32,8 @@ export interface ProvisionProfileSection {
|
|
|
32
32
|
* the gate is testable without the SDK's (unexported) create-payload type. */
|
|
33
33
|
export interface ProvisionPayloadSections {
|
|
34
34
|
env?: Record<string, string>;
|
|
35
|
-
|
|
35
|
+
/** Secret names, or Sandbox 0.63 host-scoped `SecretBinding` objects; the gate only measures bytes. */
|
|
36
|
+
secrets?: readonly unknown[] | 'all';
|
|
36
37
|
/** `profile` may also be a named-profile string ref (the SDK's
|
|
37
38
|
* `BackendConfig` union) — a string ref is tiny and has no files channel. */
|
|
38
39
|
backend?: {
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AGENT_PROFILE_EDITOR_SECTIONS,
|
|
3
3
|
AgentProfileEditor
|
|
4
|
-
} from "../chunk-
|
|
5
|
-
import "../chunk-
|
|
4
|
+
} from "../chunk-FT2Z3AOX.js";
|
|
5
|
+
import "../chunk-XKRJ275O.js";
|
|
6
6
|
import "../chunk-FUZETA6Z.js";
|
|
7
7
|
import "../chunk-R4X5474U.js";
|
|
8
8
|
import "../chunk-RASGKEAL.js";
|
|
9
|
-
import "../chunk-
|
|
9
|
+
import "../chunk-PYZYB5V2.js";
|
|
10
10
|
import "../chunk-B7CL7ENS.js";
|
|
11
11
|
import "../chunk-PV33JZKV.js";
|
|
12
12
|
import "../chunk-AMUXRAUO.js";
|
package/dist/web-react/index.js
CHANGED
|
@@ -181,7 +181,7 @@ import {
|
|
|
181
181
|
preloadWhenIdle,
|
|
182
182
|
useComposerAttachments,
|
|
183
183
|
useDictation
|
|
184
|
-
} from "../chunk-
|
|
184
|
+
} from "../chunk-YVMOYCNL.js";
|
|
185
185
|
import "../chunk-L7MB2LLM.js";
|
|
186
186
|
import {
|
|
187
187
|
WorkspaceInitial,
|
|
@@ -202,7 +202,7 @@ import {
|
|
|
202
202
|
AGENT_PROFILE_EDITOR_SECTIONS,
|
|
203
203
|
AgentProfileEditor,
|
|
204
204
|
AgentProfileRegistryError
|
|
205
|
-
} from "../chunk-
|
|
205
|
+
} from "../chunk-FT2Z3AOX.js";
|
|
206
206
|
import {
|
|
207
207
|
AgentSessionControls,
|
|
208
208
|
AgentSettingsPopover,
|
|
@@ -212,7 +212,7 @@ import {
|
|
|
212
212
|
filterAcceptedFiles,
|
|
213
213
|
isAcceptedFileType,
|
|
214
214
|
renamePastedImages
|
|
215
|
-
} from "../chunk-
|
|
215
|
+
} from "../chunk-XKRJ275O.js";
|
|
216
216
|
import "../chunk-FUZETA6Z.js";
|
|
217
217
|
import {
|
|
218
218
|
DEFAULT_EFFORT_LEVELS,
|
|
@@ -246,7 +246,7 @@ import {
|
|
|
246
246
|
ATTACHMENT_ACCEPT,
|
|
247
247
|
OOXML_SNIFFED_MIMES
|
|
248
248
|
} from "../chunk-2ZRXJ3NO.js";
|
|
249
|
-
import "../chunk-
|
|
249
|
+
import "../chunk-PYZYB5V2.js";
|
|
250
250
|
import "../chunk-B7CL7ENS.js";
|
|
251
251
|
import "../chunk-PV33JZKV.js";
|
|
252
252
|
import "../chunk-AMUXRAUO.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "0.60.
|
|
3
|
+
"version": "0.60.242",
|
|
4
4
|
"packageManager": "pnpm@11.24.0",
|
|
5
5
|
"description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
|
|
6
6
|
"keywords": [
|
|
@@ -705,16 +705,16 @@
|
|
|
705
705
|
"@storybook/react-vite": "^10.5.10",
|
|
706
706
|
"@tailwindcss/postcss": "^4.3.3",
|
|
707
707
|
"@tangle-network/agent-docs": "0.2.1",
|
|
708
|
-
"@tangle-network/agent-eval": "0.
|
|
708
|
+
"@tangle-network/agent-eval": "0.215.1",
|
|
709
709
|
"@tangle-network/agent-gateway": "0.11.4",
|
|
710
710
|
"@tangle-network/agent-integrations": "0.75.0",
|
|
711
|
-
"@tangle-network/agent-interface": "5.
|
|
711
|
+
"@tangle-network/agent-interface": "5.7.0",
|
|
712
712
|
"@tangle-network/agent-knowledge": "22.0.3",
|
|
713
713
|
"@tangle-network/agent-profile-materialize": "0.25.2",
|
|
714
|
-
"@tangle-network/agent-runtime": "0.
|
|
714
|
+
"@tangle-network/agent-runtime": "0.337.2",
|
|
715
715
|
"@tangle-network/brand": "1.26.0",
|
|
716
716
|
"@tangle-network/hub-sdk": "0.30.2",
|
|
717
|
-
"@tangle-network/sandbox": "0.
|
|
717
|
+
"@tangle-network/sandbox": "0.63.10",
|
|
718
718
|
"@tangle-network/sandbox-ui": "0.134.10",
|
|
719
719
|
"@tangle-network/ui": "11.40.0",
|
|
720
720
|
"@testing-library/dom": "^10.4.1",
|
|
@@ -779,15 +779,15 @@
|
|
|
779
779
|
"@better-auth/oauth-provider": ">=1.7.2",
|
|
780
780
|
"@firecrawl/pdf-inspector-wasm": ">=0.1.3",
|
|
781
781
|
"@huggingface/transformers": ">=3",
|
|
782
|
-
"@tangle-network/agent-eval": ">=0.199.0 <0.205.0 || >=0.205.1 <0.206.0 || >=0.209.1 <0.210.0 || >=0.211.2 <0.212.0 || >=0.213.0 <0.
|
|
782
|
+
"@tangle-network/agent-eval": ">=0.199.0 <0.205.0 || >=0.205.1 <0.206.0 || >=0.209.1 <0.210.0 || >=0.211.2 <0.212.0 || >=0.213.0 <0.216.0",
|
|
783
783
|
"@tangle-network/agent-integrations": ">=0.54.2 <0.58.0 || >=0.59.0 <0.61.0 || >=0.66.0 <0.67.0 || >=0.67.0 <0.68.0 || >=0.68.0 <0.69.0 || >=0.69.0 <0.70.0 || >=0.70.0 <0.71.0 || >=0.75.0 <0.76.0",
|
|
784
784
|
"@tangle-network/agent-interface": "^2.13.0 || ^3.0.0 || ^5.2.0",
|
|
785
785
|
"@tangle-network/agent-knowledge": "^17.1.2 || ^18.0.0 || ^19.0.1 || ^20.0.0 || ^22.0.1",
|
|
786
786
|
"@tangle-network/agent-profile-materialize": ">=0.20.1 <0.21.0 || >=0.21.0 <0.22.0 || >=0.22.0 <0.23.0 || >=0.25.2 <0.26.0",
|
|
787
|
-
"@tangle-network/agent-runtime": ">=0.
|
|
787
|
+
"@tangle-network/agent-runtime": ">=0.319.3 <0.340.0",
|
|
788
788
|
"@tangle-network/brand": ">=1.21.1",
|
|
789
789
|
"@tangle-network/hub-sdk": ">=0.19.3 <0.21.0 || >=0.21.0 <0.22.0 || >=0.22.1 <0.25.0 || >=0.27.0 <0.28.0 || >=0.28.0 <0.29.0 || >=0.29.5 <0.30.0 || >=0.30.2 <0.31.0",
|
|
790
|
-
"@tangle-network/sandbox": ">=0.45.0 <0.48.0 || ^0.49.0 || ^0.50.0 || ^0.51.0 || ^0.52.0 || ^0.53.0 || ^0.54.0 || ^0.55.0 || >=0.58.1 <0.60.0 || >=0.60.3 <0.61.0",
|
|
790
|
+
"@tangle-network/sandbox": ">=0.45.0 <0.48.0 || ^0.49.0 || ^0.50.0 || ^0.51.0 || ^0.52.0 || ^0.53.0 || ^0.54.0 || ^0.55.0 || >=0.58.1 <0.60.0 || >=0.60.3 <0.61.0 || >=0.61.1 <0.64.0",
|
|
791
791
|
"@tangle-network/sandbox-ui": ">=0.134.10 <0.137.0",
|
|
792
792
|
"@tangle-network/ui": ">=11.40.0 <12.0.0",
|
|
793
793
|
"@tiptap/core": ">=3.28.0 <4.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/harness/index.ts","../src/harness/session-selection.ts"],"sourcesContent":["/**\n * Coding-agent harness selection, model compatibility, and the session lock.\n *\n * Known identities are not a deployment's available runners. Products supply\n * server-owned availability to resolveSessionHarness. Historical session IDs\n * remain intact when their runner is unavailable; a harness change requires an\n * explicit transfer, not a fallback or a rewritten session lock.\n *\n * Model compatibility is owned by @tangle-network/agent-interface. The shell\n * owns session selection; the consumer owns storage and deployment policy.\n */\n\nimport {\n harnessProviders,\n harnessSupportsModel,\n harnessTypeSchema,\n modelProvider,\n preferredHarnessForModel,\n snapHarnessToModel as aiSnapHarnessToModel,\n snapModelToHarness as aiSnapModelToHarness,\n type HarnessType,\n} from '@tangle-network/agent-interface'\nimport {\n selectSessionHarness,\n type HarnessAvailability as SelectionAvailability,\n type SessionHarnessSelection,\n type SessionHarnessSelectionInput,\n} from './session-selection'\n\nexport { HarnessSelectionError } from './session-selection'\n\n/** Canonical identities that have no direct Sandbox backend. */\nconst NON_BACKEND_HARNESSES = ['gemini'] as const satisfies readonly HarnessType[]\nconst nonBackendHarnesses = new Set<string>(NON_BACKEND_HARNESSES)\n\n/** A recognized coding-agent backend, not a promise that it is installed. */\nexport type Harness = Exclude<HarnessType, (typeof NON_BACKEND_HARNESSES)[number]>\n\n/**\n * Recognized backend identities, including IDs needed by historical sessions.\n * Use deployment availability, not membership here, to offer or admit new runs.\n */\nexport const KNOWN_HARNESSES: readonly Harness[] = [\n ...harnessTypeSchema.options.filter(\n (harness): harness is Exclude<HarnessType, (typeof NON_BACKEND_HARNESSES)[number]> =>\n !nonBackendHarnesses.has(harness),\n ),\n]\n\n/** Default for an absent choice; never a replacement for an invalid explicit ID. */\nexport const DEFAULT_HARNESS: Harness = 'opencode'\nconst HARNESS_SET: ReadonlySet<string> = new Set(KNOWN_HARNESSES)\n\n/** Determine whether a value is a recognized identity, independently of availability. */\nexport function isHarness(value: unknown): value is Harness {\n return typeof value === 'string' && HARNESS_SET.has(value)\n}\n\n/** Display/config convenience only. Never use coercion to admit an execution or restore a lock. */\nexport function coerceHarness(value: unknown, fallback: Harness = DEFAULT_HARNESS): Harness {\n return isHarness(value) ? value : fallback\n}\n\n/** Server-owned start and resume sets. Existing-only entries are draining. */\nexport type HarnessAvailability = SelectionAvailability<Harness>\n\n/** A saved lock, explicit choice, workspace default, and optional deployment availability. */\nexport type ResolveSessionHarnessInput = SessionHarnessSelectionInput<Harness>\n\n/** The selected identity and the existing session-lock/swap-attempt result. */\nexport type ResolvedSessionHarness = SessionHarnessSelection<Harness>\n\n/**\n * Resolve requested → workspaceDefault → fallback only for a genuinely new session.\n * A non-null saved identity always takes the lock path. Unknown/retired identities\n * and invalid explicit requests throw HarnessSelectionError instead of falling back.\n * A known different request still reports swapAttempted while preserving the lock.\n * The caller must reject that attempt before execution, as in the existing contract.\n */\nexport function resolveSessionHarness(input: ResolveSessionHarnessInput = {}): ResolvedSessionHarness {\n return selectSessionHarness(input, KNOWN_HARNESSES, DEFAULT_HARNESS)\n}\n\n/**\n * An app's harness configuration, read from its deploy configuration (for example the env vars\n * `AGENT_HARNESS` and `AGENT_HARNESS_WORKSPACES`), so no product hard-codes `backend.type`.\n */\nexport interface HarnessConfig {\n /** The app default for new sessions. Unset or blank means {@link DEFAULT_HARNESS}. */\n default?: string\n /** Per-workspace choices: a JSON object mapping a workspace id to a harness. */\n workspaces?: string\n}\n\nfunction configHarness(value: unknown, where: string): Harness {\n if (!isHarness(value)) throw new Error(`${where} names an unknown harness: ${String(value)}`)\n return value\n}\n\n/**\n * The harness a workspace's new sessions start on: its own choice, else the app default, else\n * {@link DEFAULT_HARNESS}. Pass the result to {@link resolveSessionHarness} as `workspaceDefault`\n * so a session that already ran keeps its harness. A value naming an unknown harness throws:\n * a configuration typo must fail loudly, never run a different harness than the one configured.\n */\nexport function configuredHarness(config: HarnessConfig, workspaceId?: string): Harness {\n const appDefault = config.default?.trim()\n ? configHarness(config.default.trim(), 'The harness default') : DEFAULT_HARNESS\n const raw = config.workspaces?.trim()\n if (!raw) return appDefault\n let choices: unknown\n try {\n choices = JSON.parse(raw)\n } catch {\n throw new Error('The per-workspace harness configuration is not JSON')\n }\n if (!choices || typeof choices !== 'object' || Array.isArray(choices)) {\n throw new Error('The per-workspace harness configuration must map workspace ids to harnesses')\n }\n // Every entry is checked, not only the caller's, so one bad entry fails every workspace's\n // first turn after the deploy instead of hiding until that workspace sends a message.\n const parsed = new Map(Object.entries(choices).map(([id, value]) =>\n [id, configHarness(value, `The harness for workspace ${id}`)]))\n return (workspaceId === undefined ? undefined : parsed.get(workspaceId)) ?? appDefault\n}\n\n/** Harness-model compatibility is delegated to the Interface owner. */\nexport { modelProvider }\n\n/** A resolved model and the transport provider that will execute it. */\nexport interface HarnessModelSelection {\n model: string\n provider?: string\n}\n\n/** Provider-less ids (sentinels like \"default\", or a session's own config) are\n * compatible everywhere — every harness honors its own configuration. */\nexport function isModelCompatibleWithHarness(harness: Harness, modelId: string): boolean {\n return harnessSupportsModel(harness, modelId)\n}\n\n/** Keep `modelId` when the harness can run it; else the harness's best compatible\n * catalog id (preferred patterns in order, highest version). When nothing in the\n * catalog fits, return the original so the caller sees the incompatibility. */\nexport function snapModelToHarness(harness: Harness, modelId: string, canonicalIds: readonly string[]): string {\n return aiSnapModelToHarness(harness, modelId, canonicalIds)\n}\n\n/** Keep the harness when it can run `modelId`; else the model's native harness\n * (anthropic → claude-code, openai → codex, moonshot → kimi-code), falling back to opencode. */\nexport function snapHarnessToModel(harness: Harness, modelId: string): Harness {\n const snapped = aiSnapHarnessToModel(harness, modelId)\n if (!isHarness(snapped)) {\n throw new Error(\n `Harness \"${harness}\" snapped to \"${snapped}\" for model \"${modelId}\", which this platform has no backend for.`,\n )\n }\n return snapped\n}\n\n/** Fail-loud server guard: throw when a harness is asked to run a model it can't.\n * A resolved model tuple supplies provider evidence when its id is unqualified.\n * Call before dispatching a sandbox turn so a bypassed UI cannot reach the\n * sidecar with an incompatible or unproven pair. */\nexport function assertHarnessModelCompatible(\n harness: Harness,\n selection: string | HarnessModelSelection,\n): void {\n const modelId = typeof selection === 'string' ? selection : selection.model\n const transportProvider = typeof selection === 'string' ? undefined : selection.provider\n const providers = harnessProviders(harness)\n const provider = modelProvider(modelId) ?? transportProvider ?? null\n // An omitted/default model is deliberately left to the harness. Once a\n // caller names a model, however, a vendor-locked harness must have provider\n // evidence. Treating a router provider as compatible with every native CLI\n // is how a bare Gemini model reached Claude Code and produced \"Not logged in\".\n const isDefaultSentinel = modelId.trim() === '' || modelId.trim() === 'default'\n const compatible = isDefaultSentinel\n || providers === null\n || (provider !== null && providers.includes(provider))\n if (!compatible) {\n const native = preferredHarnessForModel(modelId)\n const providerDescription = provider ?? 'unqualified'\n throw new Error(\n `Harness \"${harness}\" cannot run model \"${modelId}\" (provider \"${providerDescription}\"). ` +\n `Use ${native ?? 'a router-backed harness (opencode)'} or an allowed model.`,\n )\n }\n}\n\n// Profile-support facts remain here until the materializer supplies its owned descriptor.\n// Do not confuse these facts with deployment availability.\n\n/** What a harness can express, for profile assembly. */\nexport interface HarnessCapabilities {\n /** Lower profile.subagents into native cwd files; false means materialization refuses them. */\n subagents: boolean\n /** How profile.mcp reaches the harness. */\n mcp: 'native' | 'config-file' | 'extension' | 'none'\n /** Whether tool controls are checked before MCP tools register. */\n toolControls: 'startup' | 'runtime'\n /** cwd-relative skill directory, or null when skills must be inlined. */\n skillsDir: string | null\n}\n\nconst HARNESS_CAPABILITIES: Record<Harness, HarnessCapabilities> = {\n 'claude-code': { subagents: true, mcp: 'native', toolControls: 'runtime', skillsDir: '.claude/skills' },\n nanoclaw: { subagents: true, mcp: 'native', toolControls: 'runtime', skillsDir: '.claude/skills' },\n opencode: { subagents: true, mcp: 'config-file', toolControls: 'runtime', skillsDir: '.opencode/skills' },\n codex: { subagents: true, mcp: 'config-file', toolControls: 'runtime', skillsDir: '.codex/skills' },\n 'kimi-code': { subagents: false, mcp: 'config-file', toolControls: 'runtime', skillsDir: '.kimi/skills' },\n pi: { subagents: false, mcp: 'extension', toolControls: 'startup', skillsDir: '.pi/skills' },\n prime: { subagents: true, mcp: 'native', toolControls: 'runtime', skillsDir: '.prime/agent/skills' },\n hermes: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n openclaw: { subagents: false, mcp: 'config-file', toolControls: 'runtime', skillsDir: 'skills' },\n acp: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n amp: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n 'factory-droids': { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n forge: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n cursor: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n 'cli-base': { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n}\n\n/** Profile-support facts, independent of whether this deployment enables the harness. */\nexport function harnessCapabilities(harness: Harness): HarnessCapabilities {\n const caps = HARNESS_CAPABILITIES[harness]\n if (!caps) throw new Error(`harnessCapabilities: no capability facts for \"${harness}\"`)\n return caps\n}\n","/** Pure session admission. Harness identity is not deployment availability. */\nexport interface HarnessAvailability<H extends string> {\n /** Server-owned selection for new sessions. An empty list disables all starts. */\n readonly newSessions: readonly H[]\n /** Includes draining harnesses. Omission uses newSessions, never all known IDs. */\n readonly existingSessions?: readonly H[]\n}\n\nexport interface SessionHarnessSelectionInput<H extends string> {\n sessionHarness?: unknown\n requested?: unknown\n workspaceDefault?: unknown\n fallback?: H\n /** Omit only when the caller deliberately admits every known harness. */\n availability?: HarnessAvailability<H>\n}\n\nexport interface SessionHarnessSelection<H extends string> {\n harness: H\n locked: boolean\n swapAttempted: boolean\n}\n\ntype SelectionSource = 'session' | 'requested' | 'workspace' | 'fallback'\n\n/** An admission failure, never permission to retry on another harness. */\nexport class HarnessSelectionError extends Error {\n readonly code: 'harness_unknown' | 'harness_unavailable'\n readonly harness: string | null\n readonly source: SelectionSource\n\n constructor(\n code: 'harness_unknown' | 'harness_unavailable',\n value: unknown,\n source: SelectionSource,\n ) {\n const harness = typeof value === 'string' ? value : null\n super(`${code}: ${source} harness ${harness === null ? '<invalid>' : JSON.stringify(harness)}`)\n this.name = 'HarnessSelectionError'\n this.code = code\n this.harness = harness\n this.source = source\n }\n}\n\n/**\n * Null/undefined mean no choice. Every other value is an explicit choice and must\n * validate. A retired or unrecognized saved identity must never become a new session.\n * Availability is supplied by the authenticated server, not by a request body.\n */\nexport function selectSessionHarness<H extends string>(\n input: SessionHarnessSelectionInput<H>,\n knownHarnesses: readonly H[],\n defaultHarness: H,\n): SessionHarnessSelection<H> {\n const known = new Set<string>(knownHarnesses)\n const resolve = (value: unknown, source: SelectionSource): H => {\n if (typeof value !== 'string' || !known.has(value)) {\n throw new HarnessSelectionError('harness_unknown', value, source)\n }\n return value as H\n }\n const admit = (harness: H, source: SelectionSource, existing: boolean): void => {\n if (input.availability === undefined) return\n const allowed = existing\n ? input.availability.existingSessions ?? input.availability.newSessions\n : input.availability.newSessions\n if (!allowed.includes(harness)) {\n throw new HarnessSelectionError('harness_unavailable', harness, source)\n }\n }\n\n if (input.sessionHarness !== undefined && input.sessionHarness !== null) {\n const harness = resolve(input.sessionHarness, 'session')\n admit(harness, 'session', true)\n // A known different request remains a swap attempt; it is not executed. An\n // invalid request is refused rather than being misreported as no swap.\n const requested = input.requested === undefined || input.requested === null\n ? undefined : resolve(input.requested, 'requested')\n return { harness, locked: true, swapAttempted: requested !== undefined && requested !== harness }\n }\n\n const source: SelectionSource = input.requested !== undefined && input.requested !== null\n ? 'requested'\n : input.workspaceDefault !== undefined && input.workspaceDefault !== null\n ? 'workspace' : 'fallback'\n const value = source === 'requested' ? input.requested\n : source === 'workspace' ? input.workspaceDefault : input.fallback ?? defaultHarness\n const harness = resolve(value, source)\n admit(harness, source, false)\n return { harness, locked: false, swapAttempted: false }\n}\n"],"mappings":";AAYA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,sBAAsB;AAAA,EACtB,sBAAsB;AAAA,OAEjB;;;ACKA,IAAM,wBAAN,cAAoC,MAAM;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,MACA,OACA,QACA;AACA,UAAM,UAAU,OAAO,UAAU,WAAW,QAAQ;AACpD,UAAM,GAAG,IAAI,KAAK,MAAM,YAAY,YAAY,OAAO,cAAc,KAAK,UAAU,OAAO,CAAC,EAAE;AAC9F,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU;AACf,SAAK,SAAS;AAAA,EAChB;AACF;AAOO,SAAS,qBACd,OACA,gBACA,gBAC4B;AAC5B,QAAM,QAAQ,IAAI,IAAY,cAAc;AAC5C,QAAM,UAAU,CAACA,QAAgBC,YAA+B;AAC9D,QAAI,OAAOD,WAAU,YAAY,CAAC,MAAM,IAAIA,MAAK,GAAG;AAClD,YAAM,IAAI,sBAAsB,mBAAmBA,QAAOC,OAAM;AAAA,IAClE;AACA,WAAOD;AAAA,EACT;AACA,QAAM,QAAQ,CAACE,UAAYD,SAAyB,aAA4B;AAC9E,QAAI,MAAM,iBAAiB,OAAW;AACtC,UAAM,UAAU,WACZ,MAAM,aAAa,oBAAoB,MAAM,aAAa,cAC1D,MAAM,aAAa;AACvB,QAAI,CAAC,QAAQ,SAASC,QAAO,GAAG;AAC9B,YAAM,IAAI,sBAAsB,uBAAuBA,UAASD,OAAM;AAAA,IACxE;AAAA,EACF;AAEA,MAAI,MAAM,mBAAmB,UAAa,MAAM,mBAAmB,MAAM;AACvE,UAAMC,WAAU,QAAQ,MAAM,gBAAgB,SAAS;AACvD,UAAMA,UAAS,WAAW,IAAI;AAG9B,UAAM,YAAY,MAAM,cAAc,UAAa,MAAM,cAAc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U,cAAc,WAAW,WAAW,KAAK;AAAA,EACpF,YAAY,EAAE,WAAW,OAAO,KAAK,UAAU,cAAc,WAAW,WAAW,KAAK;AAC1F;AAGO,SAAS,oBAAoB,SAAuC;AACzE,QAAM,OAAO,qBAAqB,OAAO;AACzC,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,iDAAiD,OAAO,GAAG;AACtF,SAAO;AACT;","names":["value","source","harness"]}
|
|
@@ -1 +0,0 @@
|
|
|
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\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): Promise<StageMeasurement | null>\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 let measured: StageMeasurement | null\n try { measured = await input.measure(fromStage) }\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 }\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,MA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