@copilotkit/runtime
Version:
<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />
321 lines (319 loc) • 9.11 kB
JavaScript
import "reflect-metadata";
import { EventType } from "@ag-ui/client";
//#region src/agent/state-delta.ts
function parseJsonPointer(pointer) {
if (pointer === "") return [];
if (!pointer.startsWith("/")) return void 0;
const segments = pointer.slice(1).split("/");
if (segments.some((segment) => /~(?![01])/.test(segment))) return;
return segments.map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
}
function encodeJsonPointer(segments) {
if (segments.length === 0) return "";
return `/${segments.map((segment) => segment.replace(/~/g, "~0").replace(/\//g, "~1")).join("/")}`;
}
function getArrayIndex(segment, length) {
if (segment !== "0" && !/^[1-9]\d*$/.test(segment)) return void 0;
const index = Number(segment);
return Number.isSafeInteger(index) && index < length ? index : void 0;
}
function getJsonPointerValue(root, pointer) {
const segments = parseJsonPointer(pointer);
if (segments === void 0) return { exists: false };
let current = root;
for (const segment of segments) {
if (current === null || typeof current !== "object") return { exists: false };
if (Array.isArray(current)) {
const index = getArrayIndex(segment, current.length);
if (index === void 0) return { exists: false };
current = current[index];
} else {
if (!Object.prototype.hasOwnProperty.call(current, segment)) return { exists: false };
current = current[segment];
}
}
return {
exists: true,
value: current
};
}
function getParent(root, segments) {
return getJsonPointerValue(root, encodeJsonPointer(segments.slice(0, -1)));
}
function cloneStateFallback(state, seen = /* @__PURE__ */ new WeakMap()) {
if (state === null || typeof state !== "object") return state;
const existing = seen.get(state);
if (existing !== void 0) return existing;
let clone;
try {
clone = Array.isArray(state) ? [] : Object.create(Object.getPrototypeOf(state));
} catch {
clone = Array.isArray(state) ? [] : {};
}
seen.set(state, clone);
let keys = [];
try {
keys = Reflect.ownKeys(state);
} catch {
return clone;
}
for (const key of keys) try {
const descriptor = Object.getOwnPropertyDescriptor(state, key);
if (!descriptor) continue;
if ("value" in descriptor) descriptor.value = cloneStateFallback(descriptor.value, seen);
Object.defineProperty(clone, key, descriptor);
} catch {}
return clone;
}
function cloneState(state) {
try {
return structuredClone(state);
} catch {
return cloneStateFallback(state);
}
}
function addValue(root, segments, value) {
if (segments.length === 0) return {
root: cloneState(value),
applied: true
};
const parent = getParent(root, segments);
if (!parent.exists || parent.value === null || typeof parent.value !== "object") return {
root,
applied: false
};
const segment = segments[segments.length - 1];
if (Array.isArray(parent.value)) {
if (segment === "-") {
parent.value.push(cloneState(value));
return {
root,
applied: true
};
}
const index = segment === "0" ? 0 : /^[1-9]\d*$/.test(segment) ? Number(segment) : void 0;
if (index === void 0 || !Number.isSafeInteger(index) || index > parent.value.length) return {
root,
applied: false
};
parent.value.splice(index, 0, cloneState(value));
return {
root,
applied: true
};
}
parent.value[segment] = cloneState(value);
return {
root,
applied: true
};
}
function removeValue(root, segments) {
if (segments.length === 0) return {
root: void 0,
applied: true
};
const parent = getParent(root, segments);
if (!parent.exists || parent.value === null || typeof parent.value !== "object") return {
root,
applied: false
};
const segment = segments[segments.length - 1];
if (Array.isArray(parent.value)) {
const index = getArrayIndex(segment, parent.value.length);
if (index === void 0) return {
root,
applied: false
};
parent.value.splice(index, 1);
return {
root,
applied: true
};
}
if (!Object.prototype.hasOwnProperty.call(parent.value, segment)) return {
root,
applied: false
};
delete parent.value[segment];
return {
root,
applied: true
};
}
function replaceValue(root, segments, value) {
if (segments.length === 0) return {
root: cloneState(value),
applied: true
};
const parent = getParent(root, segments);
if (!parent.exists || parent.value === null || typeof parent.value !== "object") return {
root,
applied: false
};
const segment = segments[segments.length - 1];
if (Array.isArray(parent.value)) {
const index = getArrayIndex(segment, parent.value.length);
if (index === void 0) return {
root,
applied: false
};
parent.value[index] = cloneState(value);
return {
root,
applied: true
};
}
if (!Object.prototype.hasOwnProperty.call(parent.value, segment)) return {
root,
applied: false
};
parent.value[segment] = cloneState(value);
return {
root,
applied: true
};
}
function jsonValueEqual(left, right) {
if (Object.is(left, right)) return true;
if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false;
if (Array.isArray(left) !== Array.isArray(right)) return false;
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
if (leftKeys.length !== rightKeys.length) return false;
return leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && jsonValueEqual(left[key], right[key]));
}
function applyStateDeltaOperation(root, operation) {
if (typeof operation.path !== "string") return {
root,
applied: false
};
const path = parseJsonPointer(operation.path);
if (path === void 0) return {
root,
applied: false
};
switch (operation.op) {
case "add": return addValue(root, path, operation.value);
case "remove": return removeValue(root, path);
case "replace": return replaceValue(root, path, operation.value);
case "test": {
const actual = getJsonPointerValue(root, operation.path);
return {
root,
applied: actual.exists && jsonValueEqual(actual.value, operation.value)
};
}
case "copy": {
if (typeof operation.from !== "string") return {
root,
applied: false
};
const source = getJsonPointerValue(root, operation.from);
if (!source.exists) return {
root,
applied: false
};
return addValue(root, path, source.value);
}
case "move": {
if (typeof operation.from !== "string") return {
root,
applied: false
};
const from = parseJsonPointer(operation.from);
if (from === void 0) return {
root,
applied: false
};
const source = getJsonPointerValue(root, operation.from);
if (!source.exists) return {
root,
applied: false
};
if (operation.from === operation.path) return {
root,
applied: true
};
const removed = removeValue(cloneState(root), from);
if (!removed.applied) return {
root,
applied: false
};
const added = addValue(removed.root, path, source.value);
return added.applied ? added : {
root,
applied: false
};
}
default: return {
root,
applied: false
};
}
}
function normalizeStateDelta(delta, initialState) {
let state = cloneState(initialState);
const normalized = [];
for (const operation of delta) {
const candidate = operation !== null && typeof operation === "object" ? operation : void 0;
if (candidate?.op === "add" && typeof candidate.path === "string" && candidate.path.endsWith("/-")) {
const arrayPath = candidate.path.slice(0, -2);
if (!getJsonPointerValue(state, arrayPath).exists) {
const lastSlash = arrayPath.lastIndexOf("/");
const parentPath = lastSlash > 0 ? arrayPath.slice(0, lastSlash) : "";
if (getJsonPointerValue(state, parentPath).exists) {
const initializer = {
op: "add",
path: arrayPath,
value: []
};
const applied = applyStateDeltaOperation(state, initializer);
if (applied.applied) {
normalized.push(initializer);
state = applied.root;
}
}
}
}
normalized.push(operation);
if (candidate) {
const applied = applyStateDeltaOperation(state, candidate);
if (applied.applied) state = applied.root;
}
}
return {
delta: normalized,
state
};
}
function createStateEventNormalizer(initialState) {
let state = cloneState(initialState);
let hasEmittedState = false;
return (event) => {
if (event.type === EventType.STATE_SNAPSHOT) {
state = cloneState(event.snapshot);
hasEmittedState = true;
return [event];
}
if (event.type !== EventType.STATE_DELTA) return [event];
const stateDeltaEvent = event;
const initialSnapshot = !hasEmittedState && initialState !== void 0 ? [{
type: EventType.STATE_SNAPSHOT,
snapshot: cloneState(state)
}] : [];
const normalized = Array.isArray(stateDeltaEvent.delta) ? normalizeStateDelta(stateDeltaEvent.delta, state) : {
delta: stateDeltaEvent.delta,
state
};
state = normalized.state;
hasEmittedState = true;
return [...initialSnapshot, {
...stateDeltaEvent,
delta: normalized.delta
}];
};
}
//#endregion
export { createStateEventNormalizer };
//# sourceMappingURL=state-delta.mjs.map