|
| 1 | +import { createHash } from "node:crypto"; |
| 2 | +import { inflateSync } from "node:zlib"; |
| 3 | + |
| 4 | +import { authorityUnicodeCompare } from "../coordination/authority_store_codec.ts"; |
| 5 | +import { contextSourceIdentity } from "./diagnostic_projection.ts"; |
| 6 | +import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; |
| 7 | +import { pythonString, requireJsonObject, type JsonObject } from "../runtime_decode.ts"; |
| 8 | + |
| 9 | +export const COMPLETE_TURN_DECISION_VERSION = "loopx_turn_envelope_v1"; |
| 10 | +// Sparse producer metadata is a different identity from the earlier |
| 11 | +// experimental all-float binding; its saved contracts need their pinned reader. |
| 12 | +export const COMPLETE_TURN_HASH_CODEC = "context_source_numbers_v2"; |
| 13 | + |
| 14 | +const EXECUTABLE_CLI_ARGS_MAX_ITEMS = 64; |
| 15 | +const EXECUTABLE_CLI_ARGS_MAX_ITEM_CHARS = 512; |
| 16 | +const EXECUTABLE_CLI_ARGS_MAX_TOTAL_CHARS = 2_048; |
| 17 | + |
| 18 | +export function object(value: unknown): JsonObject { |
| 19 | + return typeof value === "object" && value !== null && !Array.isArray(value) |
| 20 | + ? { ...(value as JsonObject) } |
| 21 | + : {}; |
| 22 | +} |
| 23 | + |
| 24 | +export function pickNonNull(source: JsonObject, fields: readonly string[]): JsonObject { |
| 25 | + const picked: JsonObject = {}; |
| 26 | + for (const field of fields) { |
| 27 | + if (source[field] !== null && source[field] !== undefined) picked[field] = source[field]; |
| 28 | + } |
| 29 | + return picked; |
| 30 | +} |
| 31 | + |
| 32 | +export function pickOwn(source: JsonObject, fields: readonly string[]): JsonObject { |
| 33 | + const picked: JsonObject = {}; |
| 34 | + for (const field of fields) { |
| 35 | + if (Object.hasOwn(source, field)) picked[field] = source[field]; |
| 36 | + } |
| 37 | + return picked; |
| 38 | +} |
| 39 | + |
| 40 | +export function isNonEmptyFilePath(value: unknown): value is string { |
| 41 | + return typeof value === "string" && value.trim().length > 0 && !value.includes("\0"); |
| 42 | +} |
| 43 | + |
| 44 | +export function scalarString(value: unknown, label: string, fallback = ""): string { |
| 45 | + if (value === null || value === undefined || value === "") return fallback; |
| 46 | + if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") { |
| 47 | + throw new EffectRuntimeRequestError(`${label} must be scalar-compatible`); |
| 48 | + } |
| 49 | + return pythonString(value); |
| 50 | +} |
| 51 | + |
| 52 | +export function integer(value: unknown, label: string): number { |
| 53 | + if (value === null || value === undefined || value === "") return 0; |
| 54 | + if (typeof value === "boolean") return Number(value); |
| 55 | + if (typeof value === "number" && Number.isFinite(value)) return Math.trunc(value); |
| 56 | + if (typeof value === "string" && /^[+-]?\d+$/u.test(value.trim())) return Number.parseInt(value, 10); |
| 57 | + throw new EffectRuntimeRequestError(`${label} must be integer-compatible`); |
| 58 | +} |
| 59 | + |
| 60 | +export function text(value: unknown, limit: number): string | null { |
| 61 | + if (value === null || value === undefined) return null; |
| 62 | + const compact = scalarString(value, "text value").trim().split(/\s+/u).join(" "); |
| 63 | + if (!compact) return null; |
| 64 | + return compact.length <= limit ? compact : `${compact.slice(0, Math.max(0, limit - 3)).trimEnd()}...`; |
| 65 | +} |
| 66 | + |
| 67 | +export function textList(value: unknown, limit: number, itemLimit = 240): string[] { |
| 68 | + if (!Array.isArray(value)) return []; |
| 69 | + const result: string[] = []; |
| 70 | + for (const item of value) { |
| 71 | + const rendered = text(item, itemLimit); |
| 72 | + if (!rendered || result.includes(rendered)) continue; |
| 73 | + result.push(rendered); |
| 74 | + if (result.length >= limit) break; |
| 75 | + } |
| 76 | + return result; |
| 77 | +} |
| 78 | + |
| 79 | +export function compactFields( |
| 80 | + value: unknown, fields: readonly string[], limits: Readonly<Record<string, number>> = {}, |
| 81 | +): JsonObject { |
| 82 | + const source = object(value); |
| 83 | + const compact: JsonObject = {}; |
| 84 | + for (const field of fields) { |
| 85 | + const raw = source[field]; |
| 86 | + if (raw === null || raw === undefined) continue; |
| 87 | + if (limits[field] !== undefined) { |
| 88 | + const rendered = text(raw, limits[field]); |
| 89 | + if (rendered) compact[field] = rendered; |
| 90 | + } else if (Array.isArray(raw)) { |
| 91 | + const values = textList(raw, 6, 140); |
| 92 | + if (values.length > 0) compact[field] = values; |
| 93 | + } else compact[field] = raw; |
| 94 | + } |
| 95 | + return compact; |
| 96 | +} |
| 97 | + |
| 98 | +export function executableCliArgs(value: unknown): string[] { |
| 99 | + if (!Array.isArray(value) || value.length === 0 || value.length > EXECUTABLE_CLI_ARGS_MAX_ITEMS) return []; |
| 100 | + const result: string[] = []; |
| 101 | + let totalChars = 0; |
| 102 | + for (const item of value) { |
| 103 | + if (typeof item !== "string" || !item || item.length > EXECUTABLE_CLI_ARGS_MAX_ITEM_CHARS) return []; |
| 104 | + totalChars += item.length + 1; |
| 105 | + if (totalChars > EXECUTABLE_CLI_ARGS_MAX_TOTAL_CHARS) return []; |
| 106 | + result.push(item); |
| 107 | + } |
| 108 | + return result; |
| 109 | +} |
| 110 | + |
| 111 | +export function canonicalValue(value: unknown): unknown { |
| 112 | + if (Array.isArray(value)) return value.map(canonicalValue); |
| 113 | + if (typeof value !== "object" || value === null) return value; |
| 114 | + const source = value as JsonObject; |
| 115 | + return Object.fromEntries( |
| 116 | + Object.keys(source).sort(authorityUnicodeCompare).map((key) => [key, canonicalValue(source[key])]), |
| 117 | + ); |
| 118 | +} |
| 119 | + |
| 120 | +export function canonicalHash(value: unknown): string { |
| 121 | + return `sha256:${createHash("sha256").update(JSON.stringify(canonicalValue(value)), "utf8").digest("hex")}`; |
| 122 | +} |
| 123 | + |
| 124 | +export function completeSourceHash(value: JsonObject, identity = contextSourceIdentity(value, [])): string { |
| 125 | + return `sha256:${createHash("sha256").update(identity(value, []), "utf8").digest("hex")}`; |
| 126 | +} |
| 127 | + |
| 128 | +/** Complete references reuse the checked content binding. Historical captures |
| 129 | + * retain their old JSON hash; never rewrite a stored action or Turn key. */ |
| 130 | +export function decisionSourceHash(payload: JsonObject): string { |
| 131 | + if (payload.schema_version !== COMPLETE_TURN_DECISION_VERSION) return canonicalHash(payload); |
| 132 | + const digest = object(payload.contract_binding).content_hash; |
| 133 | + if (typeof digest !== "string") throw new EffectRuntimeRequestError("complete Turn decision content binding is missing"); |
| 134 | + return digest; |
| 135 | +} |
| 136 | + |
| 137 | +export function shellQuote(value: string): string { |
| 138 | + return /^[A-Za-z0-9_@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`; |
| 139 | +} |
| 140 | + |
| 141 | +export function commandPrefix(runtimeRoot: unknown, registry?: unknown): string { |
| 142 | + const runtimeRootText = scalarString(runtimeRoot, "quota payload runtime_root").trim(); |
| 143 | + const registryText = scalarString(registry, "quota payload registry").trim(); |
| 144 | + return "loopx" + (registryText ? ` --registry ${shellQuote(registryText)}` : "") + |
| 145 | + (runtimeRootText ? ` --runtime-root ${shellQuote(runtimeRootText)}` : ""); |
| 146 | +} |
| 147 | + |
| 148 | +export function coldPath( |
| 149 | + payload: JsonObject, agentId: string | null, schedulerExecutionArgs: string, capturedDecisionPath?: string, |
| 150 | +): JsonObject { |
| 151 | + const goalId = scalarString(payload.goal_id, "quota payload goal_id", "<goal-id>"); |
| 152 | + const agentArg = agentId ? ` --agent-id ${agentId}` : ""; |
| 153 | + const prefix = commandPrefix(payload.runtime_root, payload.registry); |
| 154 | + return { |
| 155 | + full_decision: capturedDecisionPath ? `cat -- ${shellQuote(capturedDecisionPath)}` : schedulerExecutionArgs |
| 156 | + ? `${prefix} --format json quota should-run --goal-id ${goalId}${agentArg}${schedulerExecutionArgs}` |
| 157 | + : "rerun the typed quota_guard from the current host packet", |
| 158 | + ...(capturedDecisionPath ? { |
| 159 | + captured_decision: { |
| 160 | + path: capturedDecisionPath, |
| 161 | + goal_id: payload.goal_id ?? null, |
| 162 | + agent_id: agentId, |
| 163 | + turn_instance_id: object(payload.heartbeat_receipt).turn_instance_id ?? null, |
| 164 | + source_hash_ref: "$.action_signature.source_decision_hash", |
| 165 | + instruction: "Read this saved observation for omitted context. Check ok, Goal/Agent/Turn and source hash before use. " + |
| 166 | + "It grants no fresh authority: selection, lease/workspace changes, cancellation or quota revalidation require " + |
| 167 | + "the current host guard and a new capture directory. Missing or invalid capture requires recovery, not blind guard replay.", |
| 168 | + }, |
| 169 | + } : {}), |
| 170 | + todo_detail: `${prefix} --format json todo list --goal-id ${goalId}`, |
| 171 | + status_detail: `${prefix} --format json status --goal-id ${goalId}`, |
| 172 | + }; |
| 173 | +} |
| 174 | + |
| 175 | +export function decodeTurnSource(request: JsonObject, inlineField: "payload" | "source"): JsonObject { |
| 176 | + const transport = requireJsonObject(request.source_transport, "Turn composition source transport"); |
| 177 | + const { encoding, data } = transport; |
| 178 | + const maxSourceBytes = 1024 * 1024; |
| 179 | + if (Object.hasOwn(request, inlineField) || encoding !== "deflate-base64-json-v0" || |
| 180 | + typeof data !== "string" || data.length > maxSourceBytes || |
| 181 | + data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) { |
| 182 | + throw new EffectRuntimeRequestError("invalid Turn composition source transport"); |
| 183 | + } |
| 184 | + let source: unknown; |
| 185 | + try { |
| 186 | + const compressed = Buffer.from(data, "base64"); |
| 187 | + // Inflate may stop at the first stream and silently leave input unread. |
| 188 | + // The synchronous info result reports consumed bytes on supported Node versions. |
| 189 | + const { buffer, engine } = inflateSync(compressed, |
| 190 | + { info: true, maxOutputLength: maxSourceBytes }) as unknown as { buffer: Buffer; engine: { bytesWritten: number } }; |
| 191 | + if (engine.bytesWritten !== compressed.length) throw new Error("trailing compressed source data"); |
| 192 | + source = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer)); |
| 193 | + } catch { |
| 194 | + throw new EffectRuntimeRequestError("Turn composition source must be valid compressed JSON within 1 MiB"); |
| 195 | + } |
| 196 | + return requireJsonObject(source, "complete Turn decision source"); |
| 197 | +} |
0 commit comments